Krita Source Code Documentation
Loading...
Searching...
No Matches
recorder_writer.cpp
Go to the documentation of this file.
1/*
2 * SPDX-FileCopyrightText: 2020 Dmitrii Utkin <loentar@gmail.com>
3 *
4 * SPDX-License-Identifier: LGPL-2.1-only
5 */
6
7#include "recorder_writer.h"
10#include "recorder_const.h"
12
13#include <kis_canvas2.h>
14#include <kis_image.h>
15#include <KisDocument.h>
16#include <KoToolProxy.h>
17#include "kis_tool_proxy.h"
18#include <KisMainWindow.h>
19
20#include <QDir>
21#include <QDirIterator>
22#include <QElapsedTimer>
23#include <QImage>
24#include <QRegularExpression>
25#include <QApplication>
26#include <QMutexLocker>
27#include <QPointer>
28#include <QTimer>
29#include <QVector>
30#include <QSharedPointer>
31#include <atomic>
32#include <QtMath>
33#include <qobjectdefs.h>
34#include <qscopedvaluerollback.h>
35
36namespace
37{
38 const QStringList forceBlacklistedTools = {
39 "KisToolTransform",
40 "KisToolPolyline",
41 "KisToolPolygon",
42 }; // disable recorder when toggled to one of these tools.
43 const QStringList activateBlacklistedTools = {
44 "KritaShape/KisToolLine",
45 "KritaShape/KisToolRectangle",
46 "KritaShape/KisToolEllipse",
47 }; // disable recorder when toggled to one of these tools and activated tool(left button pressed on canvas).
48
49 static QString filePathForIndex(int index, QString directory, RecorderFormat format )
50 {
51 QString fileName = QString("%1").arg(index, 7, 10, QLatin1Char('0'));
52
53 return QString("%1%2.%3").arg(directory,
54 fileName,
56 }
57}
58
60{
61 auto oldValue = threads;
62 threads = static_cast<unsigned int>(
63 qBound(1, value, static_cast<int>(ThreadSystemValue::MaxThreadCount))
64 );
65 return oldValue != threads;
66}
67
69{
70 auto oldValue = get();
71 if (set(value)) {
72 // Emit signal to GUI that the value has been changed
73 Q_EMIT notifyValueChange(oldValue < get());
74 }
75}
76
77unsigned int ThreadCounter::get() const
78{
79 return threads;
80}
81
83{
84 QMutexLocker lock(&inUseMutex);
85 return setUsedImpl(value);
86}
87
89{
90 QMutexLocker lock(&inUseMutex);
91 auto oldValue = getUsed();
92 if (setUsedImpl(value)) {
93 // Emit signal to GUI that the value has been changed
94 Q_EMIT notifyInUseChange(oldValue < getUsed());
95 }
96}
97
99{
100 QMutexLocker lock(&inUseMutex);
101 auto oldValue = getUsed();
102 if (setUsedImpl(inUse + 1)) {
103 // Emit signal to GUI that the value has been changed
104 Q_EMIT notifyInUseChange(oldValue < getUsed());
105 }
106}
108{
109 QMutexLocker lock(&inUseMutex);
110 if (setUsedImpl(inUse - 1)) {
111 // Emit signal to GUI that the value has been changed
112 Q_EMIT notifyInUseChange(false);
113 }
114}
115
116unsigned int ThreadCounter::getUsed() const
117{
118 return inUse;
119}
120
122{
123 auto oldValue = inUse;
124 inUse = static_cast<unsigned int>(
125 qBound(0, value, static_cast<int>(threads))
126 );
127 return oldValue != inUse;
128}
129
131{
132public:
134 : canvas(c)
135 , settings(&s)
136 , outputDir(&d)
137 {}
138 Private() = delete;
139 Private(const Private&) = default;
140 Private(Private&&) = delete;
141 Private& operator=(const Private&) = default;
143
145 QByteArray imageBuffer;
148 QImage frame;
150 int partIndex = 0; // Consecutive file number
152 const QDir* outputDir;
153
158
159 void captureImage(QRect area, KisPaintDevice* device)
160 {
161 const bool needSrgbConversion = [&]() {
163 || device->colorSpace()->colorModelId() != RGBAColorModelID) {
164 return true;
165 }
166 const bool hasPrimaries = device->colorSpace()->profile()->hasColorants();
168 if (hasPrimaries) {
169 const ColorPrimaries primaries = device->colorSpace()->profile()->getColorPrimaries();
170 if (gamma == TRC_IEC_61966_2_1 && primaries == PRIMARIES_ITU_R_BT_709_5) {
171 return false;
172 }
173 }
174 return true;
175 }();
176
177 if (targetCs && needSrgbConversion) {
178 device->convertTo(targetCs);
179 }
180
181 // truncate uneven image width/height making it even for subdivided size too
182 const quint32 bitmask = ~(0xFFFFFFFFu >> (31 - settings->resolution));
183 const quint32 width = area.width() & bitmask;
184 const quint32 height = area.height() & bitmask;
185 const int bufferSize = device->pixelSize() * width * height;
186
187 bool resize = imageBuffer.size() != bufferSize;
188 if (resize)
189 imageBuffer.resize(bufferSize);
190
191 if (resize || frameResolution != settings->resolution) {
192 const int divider = 1 << settings->resolution;
193 const int outWidth = width / divider;
194 const int outHeight = height / divider;
195 uchar *outData = reinterpret_cast<uchar *>(imageBuffer.data());
196
197 frame = QImage(outData, outWidth, outHeight, QImage::Format_ARGB32);
198 }
199
200 device->readBytes(reinterpret_cast<quint8 *>(imageBuffer.data()), area.x(), area.y(), width, height);
201
202 imageBufferWidth = width;
203 imageBufferHeight = height;
204 }
205
206 // Calculate ARGB average value using carry save adder:
207 // https://www.qt.io/blog/2009/01/20/50-scaling-of-argb32-image
208 inline quint32 avg(quint32 c1, quint32 c2)
209 {
210 return (((c1 ^ c2) & 0xfefefefeUL) >> 1) + (c1 & c2);
211 }
212
214 {
215 quint32 *buffer = reinterpret_cast<quint32 *>(imageBuffer.data());
216 quint32 *out = buffer;
217
218 for (int y = 0; y < imageBufferHeight; y += 2) {
219 const quint32 *in1 = buffer + y * imageBufferWidth;
220 const quint32 *in2 = in1 + imageBufferWidth;
221
222 for (int x = 0; x < imageBufferWidth; x += 2) {
223 *out = avg(
224 avg(in1[x], in1[x + 1]),
225 avg(in2[x], in2[x + 1])
226 );
227
228 ++out;
229 }
230 }
231
232 imageBufferWidth /= 2;
234 }
235
236 inline quint32 blendSourceOver(const int alpha, const quint32 source, const quint32 destination)
237 {
238 // co = αs x Cs + αb x Cb x (1 – αs)
239 // αo = 1, αb = 1
240
241 const int inverseAlpha = 255 - alpha;
242 return qRgb(
243 (alpha * qRed(source) + inverseAlpha * qRed(destination)) >> 8,
244 (alpha * qGreen(source) + inverseAlpha * qGreen(destination)) >> 8,
245 (alpha * qBlue(source) + inverseAlpha * qBlue(destination)) >> 8
246 );
247 }
248
250 {
251 const quint32 background = 0xFFFFFFFF;
252 quint32 *buffer = reinterpret_cast<quint32 *>(imageBuffer.data());
253 const quint32 *end = buffer + imageBufferWidth * imageBufferHeight;
254 while (buffer != end) {
255 const int alpha = qAlpha(*buffer);
256 switch (alpha) {
257 case 0xFF: // fully opaque
258 break;
259 case 0x00: // fully transparent - just replace to background
260 *buffer = background;
261 break;
262 default: // partly transparent - do color blending
263 *buffer = blendSourceOver(alpha, *buffer, background);
264 break;
265 }
266 ++buffer;
267 }
268 }
269
271 {
272 if (!outputDir->exists() && !outputDir->mkpath(settings->outputDirectory))
273 return false;
274
275 const QString fileName = QString("%1").arg(partIndex, 7, 10, QLatin1Char('0'));
276 const QString &filePath = QString("%1%2.%3").arg(settings->outputDirectory,
277 fileName,
279
280 int factor = -1; // default value
281 switch (settings->format) {
283 factor = settings->quality; // 0...100
284 break;
286 factor = qBound(0, 100 - (settings->compression * 10), 100); // 0..10 -> 100..0
287 break;
288 }
289
290 bool result = frame.save(filePath, RecorderFormatInfo::fileFormat(settings->format).data(), factor);
291 if (!result) {
292 QFile(filePath).remove(); // remove corrupted frame
293 return false;
294 }
295
296 return true;
297 }
298};
299
301 unsigned int i,
303 const RecorderWriterSettings& s,
304 const QDir& d)
305 : d(new Private(c, s, d))
306 , id(i)
307{}
308
310{
311 delete d;
312}
313
314bool RecorderWriter::onCaptureImageImpl(int index, QRect region, KisPaintDevice *device)
315{
316 d->captureImage(region, device);
317
318 // downscale image buffer
319 for (int res = 0; res < d->settings->resolution; ++res)
321
323
324 d->partIndex = index;
325
326 return d->writeFrame();
327}
328
330{
331 // Sanity check
332 KIS_ASSERT(!regions.isEmpty());
333
334 bool framesWrittens = true;
335
336 Q_FOREACH (QRect region, regions) {
337 framesWrittens &= onCaptureImageImpl(index, region, device.data());
338 index++;
339 }
340
341 Q_EMIT capturingDone(id, framesWrittens);
342}
343
345{
348
350 QObject* threadParent,
351 unsigned int i,
353 const RecorderWriterSettings& s,
354 const QDir& d
355 )
356 : thread(QThreadPtr::create(threadParent))
357 , writer(RecorderWriterPtr::create(i, c, s, d))
358 {}
359
360 bool inUse{false};
363};
364
366
368{
369public:
371 : q(q_ptr)
372 , recorderThreads(rt)
373 {}
374
377 volatile std::atomic_bool enabled = false; // enable recording only for active documents
378 volatile std::atomic_bool imageModified = false;
379 volatile std::atomic_bool isForceBlackTool = false;
380 volatile std::atomic_bool isActivateBlackTool = false;
381 volatile std::atomic_bool toolActivated = false;
382 int partIndex = 0; // Consecutive file number
383 std::atomic_int freeWriterId = -1;
384 int interval = 1;
386 QTimer timer;
390 bool captureTail = false;
391 QRect oldRegion = QRect(-1, -1, -1, -1);
392 bool destroyingWriters = false;
393
394 int findLastIndex(const QString &directory)
395 {
396 QElapsedTimer dbgTimer;
397 dbgTimer.start();
398
399 QDirIterator dirIterator(directory);
400 const QString &extension = RecorderFormatInfo::fileExtension(settings.format);
401 const QRegularExpression &snapshotFilePattern = RecorderConst::snapshotFilePatternFor(extension);
402
403 int recordIndex = -1;
404 while (dirIterator.hasNext()) {
405 dirIterator.next();
406
407 const QString &fileName = dirIterator.fileName();
408 const QRegularExpressionMatch &match = snapshotFilePattern.match(fileName);
409 if (match.hasMatch()) {
410 int index = match.captured(1).toInt();
411 if (recordIndex < index)
412 recordIndex = index;
413 }
414 }
415 dbgTools << "findLastPartNumber for" << directory << ": " << dbgTimer.elapsed() << "ms";
416
417 return recordIndex;
418 }
419
421 {
422 QScopedValueRollback rollback(destroyingWriters, true);
423 bool result = true;
424 bool alreadyWarn = false;
425 bool alreadyErr = false;
426
427 // Wait until all the jobs processes
428 canvas->image()->waitForDone();
429
430 // Make sure the signals are delivered
431 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
432
433 for (auto &el : writerPool) {
434 el.thread->quit();
435 el.thread->wait(RecorderConst::waitThreadTimeoutMs);
436 disconnect(el.writer.get(), SIGNAL(capturingDone(int, bool)), q, SLOT(onCapturingDone(int, bool)));
437 if (el.thread->isRunning())
438 {
439 if (!alreadyWarn) {
440 warnResources << "One of the Recorder WriterPool threads has been blocked and has to be terminated. "
441 << "Thread Name: " << el.thread->objectName();
442 alreadyWarn = true;
443 }
444 el.thread->terminate();
445 if (!el.thread->wait(RecorderConst::waitThreadTimeoutMs))
446 {
447 if (!alreadyErr) {
448 errResources << "Something odd has been happen. Krita was unable to stop one of the Recorder WriterPool Threads. "
449 << "Thread Name: " << el.thread->objectName();
450 alreadyErr = true;
451 }
452 result = false;
453 }
454 }
455
456 QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
457 }
458
459 writerPool.clear();
460 freeWriterId = -1;
461
462 if (!result)
463 Q_EMIT q->recorderStopWarning();
464
465 return result;
466 }
467
469 {
470 writerPool.reserve(recorderThreads.get());
471 while (static_cast<int>(recorderThreads.get()) > writerPool.size()) {
472 auto newWorkerId = writerPool.size();
473 freeWriterId = newWorkerId - 1; // Set the value to the last existing writerEl index ->
474 // The next call of searchForFreeWriter() will than automatically find newWorkerId
475
476 writerPool.append(WriterPoolEl(q, newWorkerId, canvas, settings, outputDir));
477
478 auto writerPtr = writerPool[newWorkerId].writer;
479 auto threadPtr = writerPool[newWorkerId].thread;
480 threadPtr->setObjectName(QString("Krita-Recorder-WriterPool#%1").arg(newWorkerId));
481 connect(writerPtr.get(), SIGNAL(capturingDone(int, bool)), q, SLOT(onCapturingDone(int, bool)));
482 writerPtr->moveToThread(threadPtr.get());
483 threadPtr->start(QThread::IdlePriority);
484 }
485 }
486
488 {
489 auto j = freeWriterId + 1;
490 for(auto i = 0; i < writerPool.size(); i++, j++)
491 {
492 freeWriterId = j % writerPool.size();
493 if (writerPool[freeWriterId].thread->isRunning() && !writerPool[freeWriterId].inUse)
494 return;
495 }
496 freeWriterId = -1;
497 }
498
499 bool canStartCapture() // skip capture when use some tools.
500 {
502 return false;
504 return false;
505 return true;
506 }
507};
508
510 : d(new Private(this, recorderThreads))
511 , exporterSettings(es)
512{
513 d->timer.setTimerType(Qt::PreciseTimer);
514}
515
520
522{
523 //Saving previous region as a precaution, so that we don't have to externally manage its state
524 if (d->canvas) {
525 saveRegion();
526 }
527
528 // Restart writers if canvas changes
529 bool restart = d->timer.isActive();
530 if (restart) {
531 stop(false, false);
532 }
533
534 if (d->canvas) {
535 KoToolProxy *proxy = d->canvas->toolProxy();
536 KisToolProxy *kritaProxy = dynamic_cast<KisToolProxy*>(proxy);
537
538 disconnect(proxy, SIGNAL(toolChanged(QString)), this, SLOT(onToolChanged(QString)));
539 disconnect(kritaProxy, SIGNAL(toolPrimaryActionActivated(bool)), this, SLOT(onToolPrimaryActionActivated(bool)));
540 disconnect(d->canvas->image(), SIGNAL(sigImageUpdated(QRect)), this, SLOT(onImageModified()));
541 }
542
543 d->canvas = canvas;
544
545 if (d->canvas) {
546 KoToolProxy *proxy = d->canvas->toolProxy();
547 KisToolProxy *kritaProxy = dynamic_cast<KisToolProxy*>(proxy);
548
549 connect(proxy, SIGNAL(toolChanged(QString)), this, SLOT(onToolChanged(QString)),
550 Qt::DirectConnection); // need to handle it even if our event loop is not running
551 connect(kritaProxy, SIGNAL(toolPrimaryActionActivated(bool)), this, SLOT(onToolPrimaryActionActivated(bool)),
552 Qt::DirectConnection);
553 connect(d->canvas->image(), SIGNAL(sigImageUpdated(QRect)), this, SLOT(onImageModified()),
554 Qt::DirectConnection); // because it spams
555 }
556
557 if (restart) {
558 start(false, false);
559 }
560}
561
563{
564 // Restart writers if setup changes
565 bool restart = d->timer.isActive();
566 if (restart) {
567 stop(false, false);
568 }
569
570 d->settings = settings;
571 d->outputDir.setPath(settings.outputDirectory);
572
574
575 if (restart) {
576 start(false, false);
577 }
578
579 //Settings change whenever a different document is about to be recorder, so instead of externally tracking old region, we can just read it from a file
581}
582
583void RecorderWriterManager::start(bool toggleEnabled, bool restoreState)
584{
585 // This function is called in a lot of places, so we need to restore state very slectively to avoid huge performance
586 // losses. Even tho restoring state is a lot cheaper than saving it, it's still better to be careful
587 if (restoreState) {
588 this->restoreState();
589 }
590
591 if (d->timer.isActive())
592 return;
593
594 if (!d->canvas)
595 return;
596
597 d->enabled = true;
598 d->imageModified = false;
599
600 connect(&d->timer, SIGNAL (timeout()), this, SLOT (onTimer()));
602 d->interval = static_cast<int>(1000.0/static_cast<double>(exporterSettings.fps));
603 } else {
604 d->interval = static_cast<int>(qMax(d->settings.captureInterval, .1) * 1000.0);
605 }
606 d->createWriters();
607 d->timer.start(d->interval);
608 if (toggleEnabled) {
609 Q_EMIT started();
610 }
611}
612
613bool RecorderWriterManager::stop(bool toggleEnabled, bool saveState)
614{
615 //Check if the timer is active, so that we don't try to clear the writer pool multiple times
616 if (!d->timer.isActive())
617 return true;
618
619 // This function is called in a lot of places, so we need to save state very slectively to avoid huge performance
620 // losses
621 if (saveState) {
622 this->saveState();
623 }
624
625 d->timer.stop();
626
627 bool result = false;
628
629 // Not sure if this is necessary, but, this may prevent the message from popping up when switching tabs
630 if (saveState) {
631 KisAsyncActionFeedback f(i18n("Stopping recording"), nullptr);
632 result = f.runAction([&] {
633 return d->clearWriterPool();
634 });
635 } else {
636 result = d->clearWriterPool();
637 }
638
640 if (toggleEnabled) {
641 Q_EMIT stopped();
642 }
643 return result;
644}
645
646void RecorderWriterManager::setEnabled(bool enabled = false)
647{
648 d->enabled = enabled;
649}
650
652{
653 if ((!d->enabled && !d->captureTail) || !d->canvas || d->destroyingWriters) {
654 return;
655 }
656
657 // take snapshots only if main window is active
658 // else some dialogs like filters may disappear when canvas->image()->lock() is called
659 if (qobject_cast<KisMainWindow *>(QApplication::activeWindow()) == nullptr && !d->captureTail) {
660 return;
661 }
662
664 (d->canvas->image()->isIsolatingLayer() || d->canvas->image()->isIsolatingGroup())) {
665 return;
666 }
667
668 if (!d->imageModified && !d->captureTail)
669 return;
670
671 d->imageModified = false;
672
673 if (!d->canStartCapture())
674 return;
675
677
678 if (d->freeWriterId == -1)
679 {
680 Q_EMIT lowPerformanceWarning();
681 return;
682 }
683
684 d->writerPool[d->freeWriterId].inUse = true;
685 d->writerPool[d->freeWriterId].thread->setPriority(QThread::HighPriority);
687
688 QRect fullSize = d->canvas->image()->bounds();
689
690 QRect region = d->settings.focusedRecord && !d->captureTail ? d->canvas->regionOfInterest() : fullSize;
691
692 // Handle initialisation
693 if (d->oldRegion.width() == -1 || d->oldRegion.height() == 1) {
694 d->oldRegion = region;
695 }
696
697 bool interpolate = region != d->oldRegion;
698
699 int totalFrames = 1;
700 // Change in the region, let's generate some frames
701 if (interpolate) {
702 // Prevent a divide by zero..
703 float diffX = abs(region.x() - d->oldRegion.x()) / std::max(1.0f, (float)d->oldRegion.width());
704 float diffY = abs(region.y() - d->oldRegion.y()) / std::max(1.0f, (float)d->oldRegion.height());
705 float diffW = abs(region.width() - d->oldRegion.width()) / std::max(1.0f, (float)d->oldRegion.width());
706 float diffH = abs(region.height() - d->oldRegion.height()) / std::max(1.0f, (float)d->oldRegion.height());
707
708 // Find the highest diff
709 float maxDiff = std::min(std::max({diffX, diffY, diffW, diffH}), 1.0f);
710
711 // Maximum amount of interpolation frames to generate
712 const int maxFrames = 10;
713
714 // TODO: Potentially change the number of frames function from linear to smth else
715 int framesToGenerate = std::ceil(maxFrames * maxDiff);
716
717 totalFrames += framesToGenerate;
718 }
719
720 auto lerp = [](QRect a, QRect b, qreal t) {
721
723 QRect out;
724
725 out.setX(a.x() + t * (b.x() - a.x()));
726 out.setY(a.y() + t * (b.y() - a.y()));
727 out.setWidth(a.width() + t * (b.width() - a.width()));
728 out.setHeight(a.height() + t * (b.height() - a.height()));
729
730 return out;
731 };
732
733 //Expands source to the aspect ratio of target in the most effiient way
734 auto expandToAspectRatio = [](QRectF source, QRectF target) {
735 float targetAspect = (float)target.width() / (float)target.height();
736
737 float sourceAspect = (float)source.width() / source.height();
738
739 QRectF out = source;
740
741 if (sourceAspect > targetAspect) {
742 // Expanding vertically
743 out.setHeight(source.width() / targetAspect);
744 out.moveTop(out.top() - ((source.height() - out.height()) / 2));
745 } else {
746 // Expanding horizontally
747 out.setWidth(source.height() * targetAspect);
748 out.moveLeft(out.left() + ((source.width() - out.width()) / 2));
749
750 }
751
752 if (out.bottom() > target.bottom()) {
753 out.moveBottom(target.bottom());
754 }
755 if (out.right() > target.right()) {
756 out.moveRight(target.right());
757 }
758 if (out.top() < target.top()) {
759 out.moveTop(target.top());
760 }
761 if (out.left() < target.left()) {
762 out.moveLeft(target.left());
763 }
764
765 return out;
766 };
767
768 //TODO: try other easing functions
769 auto easeOutCubic = [](qreal t) {
770 return 1 - qPow(1 - t, 3);
771 };
772
773 QVector<QRect> rects;
774
775 for (int frame = 0; frame < totalFrames; frame++) {
776 //Linear animations look really bad, so do easing
777 QRect interpolatedRect = lerp(d->oldRegion, region, easeOutCubic((qreal)(frame + 1) / (qreal)totalFrames));
778 QRect expandedRect = expandToAspectRatio(interpolatedRect, fullSize).toRect();
779
780 rects.push_back(expandedRect);
781 };
782
783 QRect copyArea = rects.first();
784
785 if (rects.length() > 1) {
786 QRect united = rects.first();
787
788 Q_FOREACH (QRect r, rects) {
789 united = united.united(r);
790 }
791
792 copyArea = united;
793 }
794
796 new RecorderImageCopyingJob(d->canvas->image()->projection(), copyArea, ++d->partIndex, rects);
797
798 connect(job,
799 SIGNAL(sigImageCopyingDoneWithData(int, QVector<QRect>, KisPaintDeviceSP)),
800 d->writerPool[d->freeWriterId].writer.data(),
801 SLOT(onCaptureImage( int, QVector<QRect>, KisPaintDeviceSP)));
802
803 d->canvas->image()->addSpontaneousJob(job);
804
805 d->partIndex += totalFrames - 1;
806
807 if (!d->captureTail) {
808 d->oldRegion = region;
809 }
810
811 d->captureTail = false;
812}
813
814void RecorderWriterManager::onCapturingDone(int workerId, bool success)
815{
816 if (workerId >= d->writerPool.size() || d->destroyingWriters)
817 return;
818 d->writerPool[workerId].inUse = false;
819 d->writerPool[workerId].thread->setPriority(QThread::IdlePriority);
821 if (!success) {
822 stop(true, true);
823 Q_EMIT frameWriteFailed();
824 }
825}
826
828{
829 if (!d->enabled || !d->canStartCapture())
830 return;
831
833 (d->canvas->image()->isIsolatingLayer() || d->canvas->image()->isIsolatingGroup()))
834 return;
835
836 d->imageModified = true;
837}
838
839void RecorderWriterManager::onToolChanged(const QString &toolId)
840{
841 d->isForceBlackTool = forceBlacklistedTools.contains(toolId);
842 d->isActivateBlackTool = activateBlacklistedTools.contains(toolId);
843}
844
846{
847 d->toolActivated = activated;
848}
849
850//Need to save the region, so that there are no jumps when stopping and resuming the recording
852{
853 if (!d->outputDir.exists()) {
854 return;
855 }
856
857 const QString filename = RecorderConst::recorderMetaDataName;
858 auto config = KSharedConfig ::openConfig(d->outputDir.filePath(RecorderConst::recorderMetaDataName));
859 KConfigGroup cfg = KConfigGroup(config, "");
860
861 cfg.writeEntry("region", d->oldRegion);
862}
863
865{
866 if (!d->outputDir.exists()) {
867 return;
868 }
869
870 auto config = KSharedConfig ::openConfig(d->outputDir.filePath(RecorderConst::recorderMetaDataName));
871 KConfigGroup cfg = KConfigGroup(config, "");
872
873 d->oldRegion = cfg.readEntry("region", QRect(-1, -1, -1, -1));
874}
875
877{
878 if (!d->outputDir.exists()) {
879 return;
880 }
881
882 saveRegion();
883
884 // Capture some tail frames, but only if we're zoomed in, and if some frames were captured
885 const QString filename = "tail";
886
887 if (d->oldRegion == d->canvas->image()->bounds() || d->oldRegion == QRect(-1, -1, -1, -1)) {
888 return;
889 }
890
891 int beginIndex = d->partIndex + 1;
892
893 d->captureTail = true;
894 onTimer();
895
896 int endIndex = d->partIndex;
897
898 QStringList fileNames;
899
900 for (int i = beginIndex; i <= endIndex; i++) {
901 fileNames.push_back(filePathForIndex(i, "", d->settings.format));
902 }
903
904 auto config = KSharedConfig ::openConfig(d->outputDir.filePath(RecorderConst::recorderMetaDataName));
905 KConfigGroup cfg = KConfigGroup(config, "");
906
907 cfg.writeEntry("tails", fileNames);
908}
909
911{
912 if (!d->outputDir.exists()) {
913 return;
914 }
915
917 auto config = KSharedConfig ::openConfig(d->outputDir.filePath(RecorderConst::recorderMetaDataName));
918 KConfigGroup cfg = KConfigGroup(config, "");
919
920 QStringList fileNames = cfg.readEntry("tails", QStringList());
921
922 if (fileNames.isEmpty()) {
923 return;
924 }
925
926 //Clear it out if the tail is not generated next time
927 cfg.writeEntry("tails", QStringList());
928
929 Q_FOREACH (QString name, fileNames) {
930 d->outputDir.remove(name);
931 }
932
933 // Move the frame index back
934 QRegularExpression fileRegex =
936
937 QRegularExpressionMatch match = fileRegex.match(fileNames.first());
938
939 if (match.hasMatch()) {
940 int index = match.captured(1).toInt();
941 d->partIndex = index - 1;
942 }
943}
float value(const T *src, size_t ch)
KisMagneticGraph::vertex_descriptor target(typename KisMagneticGraph::edge_descriptor e, KisMagneticGraph g)
KisMagneticGraph::vertex_descriptor source(typename KisMagneticGraph::edge_descriptor e, KisMagneticGraph g)
QList< QString > QStringList
const KoID Integer8BitsColorDepthID("U8", ki18n("8-bit integer/channel"))
const KoID RGBAColorModelID("RGBA", ki18n("RGB/Alpha"))
ColorPrimaries
The colorPrimaries enum Enum of colorants, follows ITU H.273 for values 0 to 255, and has extra known...
@ PRIMARIES_ITU_R_BT_709_5
TransferCharacteristics
The transferCharacteristics enum Enum of transfer characteristics, follows ITU H.273 for values 0 to ...
@ TRC_IEC_61966_2_1
QPointF lerp(const QPointF &p1, const QPointF &p2, qreal t)
quint32 pixelSize() const
const KoColorSpace * colorSpace() const
void convertTo(const KoColorSpace *dstColorSpace, KoColorConversionTransformation::Intent renderingIntent=KoColorConversionTransformation::internalRenderingIntent(), KoColorConversionTransformation::ConversionFlags conversionFlags=KoColorConversionTransformation::internalConversionFlags(), KUndo2Command *parentCommand=nullptr, KoUpdater *progressUpdater=nullptr)
void readBytes(quint8 *data, qint32 x, qint32 y, qint32 w, qint32 h) const
virtual KoID colorModelId() const =0
virtual KoID colorDepthId() const =0
virtual const KoColorProfile * profile() const =0
QString id() const
Definition KoID.cpp:63
volatile std::atomic_bool toolActivated
int findLastIndex(const QString &directory)
RecorderWriterManager *const q
volatile std::atomic_bool isActivateBlackTool
volatile std::atomic_bool imageModified
Private(RecorderWriterManager *q_ptr, ThreadCounter &rt)
volatile std::atomic_bool isForceBlackTool
RecorderWriterSettings settings
volatile std::atomic_bool enabled
void saveState()
Generate a tail and save the recording region.
RecorderWriterManager()=delete
void start(bool toggleEnabled, bool restoreState)
bool stop(bool toggleEnabled, bool saveState)
void restoreState()
Remove the tail and restore region from a file.
void onCapturingDone(int workerId, bool success)
void onToolPrimaryActionActivated(bool activated)
void setCanvas(QPointer< KisCanvas2 > canvas)
void setEnabled(bool enabled)
void setup(const RecorderWriterSettings &settings)
ThreadCounter recorderThreads
const RecorderExportSettings & exporterSettings
void onToolChanged(const QString &toolId)
Private(Private &&)=delete
QPointer< KisCanvas2 > canvas
quint32 avg(quint32 c1, quint32 c2)
const KoColorSpace * targetCs
Private & operator=(Private &&)=delete
Private & operator=(const Private &)=default
quint32 blendSourceOver(const int alpha, const quint32 source, const quint32 destination)
const RecorderWriterSettings * settings
Private(QPointer< KisCanvas2 > c, const RecorderWriterSettings &s, const QDir &d)
void captureImage(QRect area, KisPaintDevice *device)
Private(const Private &)=default
RecorderWriter()=delete
void onCaptureImage(int index, QVector< QRect > regions, KisPaintDeviceSP device)
bool onCaptureImageImpl(int index, QRect region, KisPaintDevice *device)
Private *const d
void capturingDone(int writerId, bool success)
void setUsedAndNotify(int value)
bool setUsedImpl(int value)
unsigned int getUsed() const
unsigned int get() const
void notifyValueChange(bool valueWasIncreased)
unsigned int threads
void setAndNotify(int value)
bool setUsed(int value)
bool set(int value)
unsigned int inUse
void notifyInUseChange(bool valueWasIncreased)
#define KIS_SAFE_ASSERT_RECOVER(cond)
Definition kis_assert.h:126
#define KIS_ASSERT(cond)
Definition kis_assert.h:33
#define errResources
Definition kis_debug.h:113
#define warnResources
Definition kis_debug.h:92
#define dbgTools
Definition kis_debug.h:52
const QString recorderMetaDataName
QRegularExpression snapshotFilePatternFor(const QString &extension)
constexpr int waitThreadTimeoutMs
QLatin1String fileFormat(RecorderFormat format)
QLatin1String fileExtension(RecorderFormat format)
const unsigned int MaxThreadCount
RecorderFormat
virtual ColorPrimaries getColorPrimaries() const
getColorPrimaries
virtual bool hasColorants() const =0
virtual TransferCharacteristics getTransferCharacteristics() const
getTransferCharacteristics This function should be subclassed at some point so we can get the value f...
const KoColorSpace * colorSpace(const QString &colorModelId, const QString &colorDepthId, const KoColorProfile *profile)
static KoColorSpaceRegistry * instance()
const KoColorProfile * p709SRGBProfile() const
QSharedPointer< RecorderWriter > writer
QSharedPointer< QThread > thread
WriterPoolEl(QObject *threadParent, unsigned int i, QPointer< KisCanvas2 > c, const RecorderWriterSettings &s, const QDir &d)