Krita Source Code Documentation
Loading...
Searching...
No Matches
RecorderWriterManager Class Reference

#include <recorder_writer.h>

+ Inheritance diagram for RecorderWriterManager:

Classes

class  Private
 

Signals

void frameWriteFailed ()
 
void lowPerformanceWarning ()
 
void recorderStopWarning ()
 
void started ()
 
void stopped ()
 

Public Member Functions

bool canStartCapture () const
 
RecorderWriterManager & operator= (const RecorderWriterManager &)=delete
 
RecorderWriterManager & operator= (RecorderWriterManager &&)=delete
 
 RecorderWriterManager ()=delete
 
 RecorderWriterManager (const RecorderExportSettings &es)
 
 RecorderWriterManager (const RecorderWriterManager &)=delete
 
 RecorderWriterManager (RecorderWriterManager &&)=delete
 
void restoreState ()
 Remove the tail and restore region from a file.
 
void saveRegion ()
 
void saveState ()
 Generate a tail and save the recording region.
 
void setCanvas (QPointer< KisCanvas2 > canvas)
 
void setEnabled (bool enabled)
 
void setup (const RecorderWriterSettings &settings)
 
void start (bool toggleEnabled, bool restoreState)
 
bool stop (bool toggleEnabled, bool saveState)
 
void tryRestoreRegion ()
 
 ~RecorderWriterManager ()
 

Public Attributes

ThreadCounter recorderThreads {}
 

Private Slots

void onCapturingDone (int workerId, bool success)
 
void onImageModified ()
 
void onTimer ()
 
void onToolChanged (const QString &toolId)
 
void onToolPrimaryActionActivated (bool activated)
 

Private Attributes

Private *const d
 
const RecorderExportSettings & exporterSettings
 

Detailed Description

Definition at line 105 of file recorder_writer.h.

Constructor & Destructor Documentation

◆ RecorderWriterManager() [1/4]

RecorderWriterManager::RecorderWriterManager ( const RecorderExportSettings & es)
explicit

Definition at line 509 of file recorder_writer.cpp.

510 : d(new Private(this, recorderThreads))
511 , exporterSettings(es)
512{
513 d->timer.setTimerType(Qt::PreciseTimer);
514}
ThreadCounter recorderThreads
const RecorderExportSettings & exporterSettings

References d, and RecorderWriterManager::Private::timer.

◆ ~RecorderWriterManager()

RecorderWriterManager::~RecorderWriterManager ( )

Definition at line 516 of file recorder_writer.cpp.

517{
518 delete d;
519}

References d.

◆ RecorderWriterManager() [2/4]

RecorderWriterManager::RecorderWriterManager ( )
delete

◆ RecorderWriterManager() [3/4]

RecorderWriterManager::RecorderWriterManager ( const RecorderWriterManager & )
delete

◆ RecorderWriterManager() [4/4]

RecorderWriterManager::RecorderWriterManager ( RecorderWriterManager && )
delete

Member Function Documentation

◆ canStartCapture()

bool RecorderWriterManager::canStartCapture ( ) const

◆ frameWriteFailed

void RecorderWriterManager::frameWriteFailed ( )
signal

◆ lowPerformanceWarning

void RecorderWriterManager::lowPerformanceWarning ( )
signal

◆ onCapturingDone

void RecorderWriterManager::onCapturingDone ( int workerId,
bool success )
privateslot

Definition at line 814 of file recorder_writer.cpp.

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}
bool stop(bool toggleEnabled, bool saveState)

References d, ThreadCounter::decUsedAndNotify(), RecorderWriterManager::Private::destroyingWriters, frameWriteFailed(), recorderThreads, stop(), and RecorderWriterManager::Private::writerPool.

◆ onImageModified

void RecorderWriterManager::onImageModified ( )
privateslot

◆ onTimer

void RecorderWriterManager::onTimer ( )
privateslot

Definition at line 651 of file recorder_writer.cpp.

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}
KisMagneticGraph::vertex_descriptor target(typename KisMagneticGraph::edge_descriptor e, KisMagneticGraph g)
KisMagneticGraph::vertex_descriptor source(typename KisMagneticGraph::edge_descriptor e, KisMagneticGraph g)
QPointF lerp(const QPointF &p1, const QPointF &p2, qreal t)
#define KIS_SAFE_ASSERT_RECOVER(cond)
Definition kis_assert.h:126
Point abs(const Point &pt)

References RecorderWriterManager::Private::canStartCapture(), RecorderWriterManager::Private::canvas, RecorderWriterManager::Private::captureTail, d, RecorderWriterManager::Private::destroyingWriters, RecorderWriterManager::Private::enabled, RecorderWriterSettings::focusedRecord, RecorderWriterManager::Private::freeWriterId, RecorderWriterManager::Private::imageModified, ThreadCounter::incUsedAndNotify(), KIS_SAFE_ASSERT_RECOVER, lerp(), lowPerformanceWarning(), RecorderWriterManager::Private::oldRegion, RecorderWriterManager::Private::partIndex, recorderThreads, RecorderWriterSettings::recordIsolateLayerMode, RecorderWriterManager::Private::searchForFreeWriter(), RecorderWriterManager::Private::settings, source(), target(), and RecorderWriterManager::Private::writerPool.

◆ onToolChanged

void RecorderWriterManager::onToolChanged ( const QString & toolId)
privateslot

Definition at line 839 of file recorder_writer.cpp.

840{
841 d->isForceBlackTool = forceBlacklistedTools.contains(toolId);
842 d->isActivateBlackTool = activateBlacklistedTools.contains(toolId);
843}
volatile std::atomic_bool isActivateBlackTool
volatile std::atomic_bool isForceBlackTool

References d, RecorderWriterManager::Private::isActivateBlackTool, and RecorderWriterManager::Private::isForceBlackTool.

◆ onToolPrimaryActionActivated

void RecorderWriterManager::onToolPrimaryActionActivated ( bool activated)
privateslot

Definition at line 845 of file recorder_writer.cpp.

846{
847 d->toolActivated = activated;
848}
volatile std::atomic_bool toolActivated

References d, and RecorderWriterManager::Private::toolActivated.

◆ operator=() [1/2]

RecorderWriterManager & RecorderWriterManager::operator= ( const RecorderWriterManager & )
delete

◆ operator=() [2/2]

RecorderWriterManager & RecorderWriterManager::operator= ( RecorderWriterManager && )
delete

◆ recorderStopWarning

void RecorderWriterManager::recorderStopWarning ( )
signal

◆ restoreState()

void RecorderWriterManager::restoreState ( )

Remove the tail and restore region from a file.

Definition at line 910 of file recorder_writer.cpp.

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}
QList< QString > QStringList
const QString recorderMetaDataName
QRegularExpression snapshotFilePatternFor(const QString &extension)
QLatin1String fileExtension(RecorderFormat format)

References d, RecorderFormatInfo::fileExtension(), RecorderWriterSettings::format, RecorderWriterManager::Private::outputDir, RecorderWriterManager::Private::partIndex, RecorderConst::recorderMetaDataName, RecorderWriterManager::Private::settings, RecorderConst::snapshotFilePatternFor(), and tryRestoreRegion().

◆ saveRegion()

void RecorderWriterManager::saveRegion ( )

Definition at line 851 of file recorder_writer.cpp.

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}

References d, RecorderWriterManager::Private::oldRegion, RecorderWriterManager::Private::outputDir, and RecorderConst::recorderMetaDataName.

◆ saveState()

void RecorderWriterManager::saveState ( )

Generate a tail and save the recording region.

Definition at line 876 of file recorder_writer.cpp.

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}

References RecorderWriterManager::Private::canvas, RecorderWriterManager::Private::captureTail, d, RecorderWriterSettings::format, RecorderWriterManager::Private::oldRegion, onTimer(), RecorderWriterManager::Private::outputDir, RecorderWriterManager::Private::partIndex, RecorderConst::recorderMetaDataName, saveRegion(), and RecorderWriterManager::Private::settings.

◆ setCanvas()

void RecorderWriterManager::setCanvas ( QPointer< KisCanvas2 > canvas)

Definition at line 521 of file recorder_writer.cpp.

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}
void start(bool toggleEnabled, bool restoreState)
void onToolPrimaryActionActivated(bool activated)
void onToolChanged(const QString &toolId)

References RecorderWriterManager::Private::canvas, d, onImageModified(), onToolChanged(), onToolPrimaryActionActivated(), saveRegion(), start(), stop(), and RecorderWriterManager::Private::timer.

◆ setEnabled()

void RecorderWriterManager::setEnabled ( bool enabled = false)

Definition at line 646 of file recorder_writer.cpp.

647{
648 d->enabled = enabled;
649}

References d, and RecorderWriterManager::Private::enabled.

◆ setup()

void RecorderWriterManager::setup ( const RecorderWriterSettings & settings)

Definition at line 562 of file recorder_writer.cpp.

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}
int findLastIndex(const QString &directory)

References d, RecorderWriterManager::Private::findLastIndex(), RecorderWriterManager::Private::outputDir, RecorderWriterSettings::outputDirectory, RecorderWriterManager::Private::partIndex, RecorderWriterManager::Private::settings, start(), stop(), RecorderWriterManager::Private::timer, and tryRestoreRegion().

◆ start()

void RecorderWriterManager::start ( bool toggleEnabled,
bool restoreState )

Definition at line 583 of file recorder_writer.cpp.

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}
void restoreState()
Remove the tail and restore region from a file.

References RecorderWriterManager::Private::canvas, RecorderWriterSettings::captureInterval, RecorderWriterManager::Private::createWriters(), d, RecorderWriterManager::Private::enabled, exporterSettings, RecorderExportSettings::fps, RecorderWriterManager::Private::imageModified, RecorderWriterManager::Private::interval, onTimer(), RecorderWriterSettings::realTimeCaptureMode, restoreState(), RecorderWriterManager::Private::settings, started(), and RecorderWriterManager::Private::timer.

◆ started

void RecorderWriterManager::started ( )
signal

◆ stop()

bool RecorderWriterManager::stop ( bool toggleEnabled,
bool saveState )

Definition at line 613 of file recorder_writer.cpp.

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}
void saveState()
Generate a tail and save the recording region.
bool setUsed(int value)

References RecorderWriterManager::Private::clearWriterPool(), d, recorderThreads, saveState(), ThreadCounter::setUsed(), stopped(), and RecorderWriterManager::Private::timer.

◆ stopped

void RecorderWriterManager::stopped ( )
signal

◆ tryRestoreRegion()

void RecorderWriterManager::tryRestoreRegion ( )

Definition at line 864 of file recorder_writer.cpp.

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}

References d, RecorderWriterManager::Private::oldRegion, RecorderWriterManager::Private::outputDir, and RecorderConst::recorderMetaDataName.

Member Data Documentation

◆ d

Private* const RecorderWriterManager::d
private

Definition at line 174 of file recorder_writer.h.

◆ exporterSettings

const RecorderExportSettings& RecorderWriterManager::exporterSettings
private

Definition at line 175 of file recorder_writer.h.

◆ recorderThreads

ThreadCounter RecorderWriterManager::recorderThreads {}

Definition at line 170 of file recorder_writer.h.

170{};

The documentation for this class was generated from the following files: