forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OutputSchedulerThread.cpp
4024 lines (3396 loc) · 139 KB
/
OutputSchedulerThread.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ***** BEGIN LICENSE BLOCK *****
* This file is part of Natron <https://natrongithub.github.io/>,
* (C) 2018-2021 The Natron developers
* (C) 2013-2018 INRIA and Alexandre Gauthier-Foichat
*
* Natron is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Natron is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Natron. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
* ***** END LICENSE BLOCK ***** */
// ***** BEGIN PYTHON BLOCK *****
// from <https://docs.python.org/3/c-api/intro.html#include-files>:
// "Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included."
#include <Python.h>
// ***** END PYTHON BLOCK *****
#include "OutputSchedulerThread.h"
#include <iostream>
#include <set>
#include <list>
#include <algorithm> // min, max
#include <cassert>
#include <stdexcept>
#include <sstream> // stringstream
#include <boost/scoped_ptr.hpp>
#include <boost/algorithm/clamp.hpp>
#include <QtCore/QMetaType>
#include <QtCore/QMutex>
#include <QtCore/QWaitCondition>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>
#include <QtCore/QThreadPool>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
#include <QtCore/QRunnable>
#ifdef DEBUG
#include "Global/FloatingPointExceptions.h"
#endif
#include "Engine/AbortableRenderInfo.h"
#include "Engine/AppManager.h"
#include "Engine/AppInstance.h"
#include "Engine/EffectInstance.h"
#include "Engine/Image.h"
#include "Engine/KnobFile.h"
#include "Engine/Node.h"
#include "Engine/OpenGLViewerI.h"
#include "Engine/GenericSchedulerThreadWatcher.h"
#include "Engine/Project.h"
#include "Engine/RenderStats.h"
#include "Engine/RotoContext.h"
#include "Engine/Settings.h"
#include "Engine/Timer.h"
#include "Engine/TimeLine.h"
#include "Engine/TLSHolder.h"
#include "Engine/UpdateViewerParams.h"
#include "Engine/ViewIdx.h"
#include "Engine/ViewerInstance.h"
#include "Engine/WriteNode.h"
#ifdef DEBUG
//#define TRACE_SCHEDULER
//#define TRACE_CURRENT_FRAME_SCHEDULER
#endif
#define NATRON_FPS_REFRESH_RATE_SECONDS 1.5
/*
When defined, parallel frame renders are spawned from a timer so that the frames
appear to be rendered all at the same speed.
When undefined each time a frame is computed a new thread will be spawned
until we reach the maximum allowed parallel frame renders.
*/
//#define NATRON_SCHEDULER_SPAWN_THREADS_WITH_TIMER
#ifdef NATRON_SCHEDULER_SPAWN_THREADS_WITH_TIMER
#define NATRON_SCHEDULER_THREADS_SPAWN_DEFAULT_TIMEOUT_MS 500
#endif
#define NATRON_SCHEDULER_ABORT_AFTER_X_UNSUCCESSFUL_ITERATIONS 5000
NATRON_NAMESPACE_ENTER
///Sort the frames by time and then by view
struct BufferedFrameKey
{
int time;
};
struct BufferedFrameCompare_less
{
bool operator()(const BufferedFrameKey& lhs,
const BufferedFrameKey& rhs) const
{
return lhs.time < rhs.time;
}
};
typedef std::multimap<BufferedFrameKey, BufferedFrame, BufferedFrameCompare_less> FrameBuffer;
NATRON_NAMESPACE_ANONYMOUS_ENTER
class MetaTypesRegistration
{
public:
inline MetaTypesRegistration()
{
qRegisterMetaType<BufferedFrames>("BufferedFrames");
qRegisterMetaType<BufferableObjectPtrList>("BufferableObjectPtrList");
}
};
NATRON_NAMESPACE_ANONYMOUS_EXIT
static MetaTypesRegistration registration;
struct RenderThread
{
RenderThreadTask* thread;
bool active;
};
typedef std::list<RenderThread> RenderThreads;
struct ProducedFrame
{
BufferableObjectPtrList frames;
U64 age;
RenderStatsPtr stats;
};
struct ProducedFrameCompareAgeLess
{
bool operator() (const ProducedFrame& lhs,
const ProducedFrame& rhs) const
{
return lhs.age < rhs.age;
}
};
typedef std::set<ProducedFrame, ProducedFrameCompareAgeLess> ProducedFrameSet;
class OutputSchedulerThreadExecMTArgs
: public GenericThreadExecOnMainThreadArgs
{
public:
BufferedFrames frames;
OutputSchedulerThreadExecMTArgs()
: GenericThreadExecOnMainThreadArgs()
{}
virtual ~OutputSchedulerThreadExecMTArgs() {}
};
typedef boost::shared_ptr<OutputSchedulerThreadExecMTArgs> OutputSchedulerThreadExecMTArgsPtr;
#ifndef NATRON_PLAYBACK_USES_THREAD_POOL
static bool
isBufferFull(int nbBufferedElement,
int hardwardIdealThreadCount)
{
return nbBufferedElement >= hardwardIdealThreadCount * 3;
}
#endif
struct OutputSchedulerThreadPrivate
{
FrameBuffer buf; //the frames rendered by the worker threads that needs to be rendered in order by the output device
QWaitCondition bufEmptyCondition;
mutable QMutex bufMutex;
//doesn't need any protection since it never changes and is set in the constructor
OutputSchedulerThread::ProcessFrameModeEnum mode; //is the frame to be processed on the main-thread (i.e OpenGL rendering) or on the scheduler thread
Timer timer; // Timer regulating the engine execution. It is controlled by the GUI and MT-safe.
boost::scoped_ptr<TimeLapse> renderTimer; // Timer used to report stats when rendering
///When the render threads are not using the appendToBuffer API, the scheduler has no way to know the rendering is finished
///but to count the number of frames rendered via notifyFrameRended which is called by the render thread.
mutable QMutex renderFinishedMutex;
U64 nFramesRendered;
bool renderFinished; //< set to true when nFramesRendered = runArgs->lastFrame - runArgs->firstFrame + 1
// Pointer to the args used in threadLoopOnce(), only usable from the scheduler thread
OutputSchedulerThreadStartArgsWPtr runArgs;
mutable QMutex lastRunArgsMutex;
std::vector<ViewIdx> lastPlaybackViewsToRender;
RenderDirectionEnum lastPlaybackRenderDirection;
///Worker threads
mutable QMutex renderThreadsMutex;
RenderThreads renderThreads;
QWaitCondition allRenderThreadsInactiveCond; // wait condition to make sure all render threads are asleep
#ifdef NATRON_PLAYBACK_USES_THREAD_POOL
QThreadPool* threadPool;
#else
QWaitCondition allRenderThreadsQuitCond; //to make sure all render threads have quit
std::list<int> framesToRender;
///Render threads wait in this condition and the scheduler wake them when it needs to render some frames
QWaitCondition framesToRenderNotEmptyCond;
#endif
///Work queue filled by the scheduler thread when in playback/render on disk
QMutex framesToRenderMutex; // protects framesToRender & currentFrameRequests
///index of the last frame pushed (framesToRender.back())
///we store this because when we call pushFramesToRender we need to know what was the last frame that was queued
///Protected by framesToRenderMutex
int lastFramePushedIndex;
int expectFrameToRender;
OutputEffectInstanceWPtr outputEffect; //< The effect used as output device
RenderEngine* engine;
#ifdef NATRON_SCHEDULER_SPAWN_THREADS_WITH_TIMER
QTimer threadSpawnsTimer;
QMutex lastRecordedFPSMutex;
double lastRecordedFPS;
#endif
QMutex bufferedOutputMutex;
int lastBufferedOutputSize;
OutputSchedulerThreadPrivate(RenderEngine* engine,
const OutputEffectInstancePtr& effect,
OutputSchedulerThread::ProcessFrameModeEnum mode)
: buf()
, bufEmptyCondition()
, bufMutex()
, mode(mode)
, timer()
, renderTimer()
, renderFinishedMutex()
, nFramesRendered(0)
, renderFinished(false)
, runArgs()
, lastRunArgsMutex()
, lastPlaybackViewsToRender()
, lastPlaybackRenderDirection(eRenderDirectionForward)
, renderThreadsMutex()
, renderThreads()
, allRenderThreadsInactiveCond()
#ifdef NATRON_PLAYBACK_USES_THREAD_POOL
, threadPool( QThreadPool::globalInstance() )
#else
, allRenderThreadsQuitCond()
, framesToRender()
, framesToRenderNotEmptyCond()
#endif
, framesToRenderMutex()
, lastFramePushedIndex(0)
, expectFrameToRender(0)
, outputEffect(effect)
, engine(engine)
#ifdef NATRON_SCHEDULER_SPAWN_THREADS_WITH_TIMER
, threadSpawnsTimer()
, lastRecordedFPSMutex()
, lastRecordedFPS(0.)
#endif
, bufferedOutputMutex()
, lastBufferedOutputSize(0)
{
}
void appendBufferedFrame(double time,
ViewIdx view,
const RenderStatsPtr& stats,
const BufferableObjectPtr& image)
{
///Private, shouldn't lock
assert( !bufMutex.tryLock() );
#ifdef TRACE_SCHEDULER
QString idStr;
if (image) {
idStr = QString::fromUtf8("ID: ") + QString::number( image->getUniqueID() );
}
qDebug() << "Parallel Render Thread: Rendered Frame:" << time << " View:" << (int)view << idStr;
#endif
BufferedFrameKey key;
BufferedFrame value;
value.time = key.time = time;
value.view = view;
value.frame = image;
value.stats = stats;
buf.insert( std::make_pair(key, value) );
}
struct ViewUniqueIDPair
{
int view;
int uniqueId;
};
struct ViewUniqueIDPairCompareLess
{
bool operator() (const ViewUniqueIDPair& lhs,
const ViewUniqueIDPair& rhs) const
{
if (lhs.view < rhs.view) {
return true;
} else if (lhs.view > rhs.view) {
return false;
} else {
if (lhs.uniqueId < rhs.uniqueId) {
return true;
} else if (lhs.uniqueId > rhs.uniqueId) {
return false;
} else {
return false;
}
}
}
};
typedef std::set<ViewUniqueIDPair, ViewUniqueIDPairCompareLess> ViewUniqueIDSet;
void getFromBufferAndErase(double time,
BufferedFrames& frames)
{
///Private, shouldn't lock
assert( !bufMutex.tryLock() );
/*
Note that the frame buffer does not hold any particular ordering and just contains all the frames as they
were received by render threads.
In the buffer, for any particular given time there can be:
- Multiple views
- Multiple "unique ID" (corresponds to viewer input A or B)
Also since we are rendering ahead, we can have a buffered frame at time 23,
and also another frame at time 23, each of which could have multiple unique IDs and so on
To retrieve what we need to render, we extract at least one view and unique ID for this particular time
*/
ViewUniqueIDSet uniqueIdsRetrieved;
BufferedFrameKey key;
key.time = time;
std::pair<FrameBuffer::iterator, FrameBuffer::iterator> range = buf.equal_range(key);
std::list<std::pair<BufferedFrameKey, BufferedFrame> > toKeep;
for (FrameBuffer::iterator it = range.first; it != range.second; ++it) {
bool keepInBuf = true;
if (it->second.frame) {
ViewUniqueIDPair p;
p.view = (int)it->second.view;
p.uniqueId = it->second.frame->getUniqueID();
std::pair<ViewUniqueIDSet::iterator, bool> alreadyRetrievedIndex = uniqueIdsRetrieved.insert(p);
if (alreadyRetrievedIndex.second) {
frames.push_back(it->second);
keepInBuf = false;
}
}
if (keepInBuf) {
toKeep.push_back(*it);
}
}
if ( range.first != buf.end() ) {
buf.erase(range.first, range.second);
buf.insert( toKeep.begin(), toKeep.end() );
}
}
void appendRunnable(RenderThreadTask* runnable)
{
assert( !renderThreadsMutex.tryLock() );
RenderThread r;
r.thread = runnable;
r.active = true;
renderThreads.push_back(r);
#ifndef NATRON_PLAYBACK_USES_THREAD_POOL
runnable->start();
#else
threadPool->start(runnable);
#endif
}
RenderThreads::iterator getRunnableIterator(RenderThreadTask* runnable)
{
///Private shouldn't lock
assert( !renderThreadsMutex.tryLock() );
for (RenderThreads::iterator it = renderThreads.begin(); it != renderThreads.end(); ++it) {
if (it->thread == runnable) {
return it;
}
}
return renderThreads.end();
}
int getNBufferedFrames() const
{
QMutexLocker l(&bufMutex);
return buf.size();
}
static bool getNextFrameInSequence(PlaybackModeEnum pMode,
RenderDirectionEnum direction,
int frame,
int firstFrame,
int lastFrame,
unsigned int frameStep,
int* nextFrame,
RenderDirectionEnum* newDirection);
static void getNearestInSequence(RenderDirectionEnum direction,
int frame,
int firstFrame,
int lastFrame,
int* nextFrame);
void waitForRenderThreadsToBeDone()
{
assert( !renderThreadsMutex.tryLock() );
while (renderThreads.size() > 0
#ifndef NATRON_PLAYBACK_USES_THREAD_POOL
/*
When not using the thread pool we use the same threads for computing several frames.
When using the thread-pool tasks are actually just removed from renderThreads when they are finisehd
*/
&& getNActiveRenderThreads() > 0
#endif
) {
allRenderThreadsInactiveCond.wait(&renderThreadsMutex);
}
}
int getNActiveRenderThreads() const
{
///Private shouldn't lock
assert( !renderThreadsMutex.tryLock() );
#ifndef NATRON_PLAYBACK_USES_THREAD_POOL
int ret = 0;
for (RenderThreads::const_iterator it = renderThreads.begin(); it != renderThreads.end(); ++it) {
if (it->active) {
++ret;
}
}
return ret;
#else
/*
When not using the thread pool we use the same threads for computing several frames.
When using the thread-pool tasks are actually just removed from renderThreads when they are finisehd
*/
return (int)renderThreads.size();
#endif
}
#ifndef NATRON_PLAYBACK_USES_THREAD_POOL
void removeQuitRenderThreadsInternal()
{
for (;; ) {
bool hasRemoved = false;
for (RenderThreads::iterator it = renderThreads.begin(); it != renderThreads.end(); ++it) {
if ( it->thread->hasQuit() ) {
it->thread->deleteLater();
renderThreads.erase(it);
hasRemoved = true;
break;
}
}
if (!hasRemoved) {
break;
}
}
}
#endif
#ifndef NATRON_PLAYBACK_USES_THREAD_POOL
void removeAllQuitRenderThreads()
{
///Private shouldn't lock
assert( !renderThreadsMutex.tryLock() );
removeQuitRenderThreadsInternal();
///Wake-up the main-thread if it was waiting for all threads to quit
allRenderThreadsQuitCond.wakeOne();
}
#endif
void waitForRenderThreadsToQuit()
{
#ifndef NATRON_PLAYBACK_USES_THREAD_POOL
RenderThreads threads;
{
QMutexLocker l(&renderThreadsMutex);
threads = renderThreads;
}
for (RenderThreads::iterator it = threads.begin(); it != threads.end(); ++it) {
it->thread->wait();
}
{
QMutexLocker l(&renderThreadsMutex);
removeQuitRenderThreadsInternal();
assert( renderThreads.empty() );
}
#else
/*
We don't need the threads to actually quit, just need the runnables to be done
*/
QMutexLocker l(&renderThreadsMutex);
waitForRenderThreadsToBeDone();
#endif
}
};
OutputSchedulerThread::OutputSchedulerThread(RenderEngine* engine,
const OutputEffectInstancePtr& effect,
ProcessFrameModeEnum mode)
: GenericSchedulerThread()
, _imp( new OutputSchedulerThreadPrivate(engine, effect, mode) )
{
QObject::connect( &_imp->timer, SIGNAL(fpsChanged(double,double)), _imp->engine, SIGNAL(fpsChanged(double,double)) );
#ifdef NATRON_SCHEDULER_SPAWN_THREADS_WITH_TIMER
QObject::connect( &_imp->threadSpawnsTimer, SIGNAL(timeout()), this, SLOT(onThreadSpawnsTimerTriggered()) );
#endif
setThreadName("Scheduler thread");
}
OutputSchedulerThread::~OutputSchedulerThread()
{
///Wake-up all threads and tell them that they must quit
stopRenderThreads(0);
///Make sure they are all gone, there will be a deadlock here if that's not the case.
_imp->waitForRenderThreadsToQuit();
}
bool
OutputSchedulerThreadPrivate::getNextFrameInSequence(PlaybackModeEnum pMode,
RenderDirectionEnum direction,
int frame,
int firstFrame,
int lastFrame,
unsigned int frameStep,
int* nextFrame,
RenderDirectionEnum* newDirection)
{
assert(frameStep >= 1);
*newDirection = direction;
if (firstFrame == lastFrame) {
*nextFrame = firstFrame;
return true;
}
if (frame <= firstFrame) {
switch (pMode) {
case ePlaybackModeLoop:
if (direction == eRenderDirectionForward) {
*nextFrame = firstFrame + frameStep;
} else {
*nextFrame = lastFrame - frameStep;
}
break;
case ePlaybackModeBounce:
if (direction == eRenderDirectionForward) {
*newDirection = eRenderDirectionBackward;
*nextFrame = lastFrame - frameStep;
} else {
*newDirection = eRenderDirectionForward;
*nextFrame = firstFrame + frameStep;
}
break;
case ePlaybackModeOnce:
default:
if (direction == eRenderDirectionForward) {
*nextFrame = firstFrame + frameStep;
break;
} else {
return false;
}
}
} else if (frame >= lastFrame) {
switch (pMode) {
case ePlaybackModeLoop:
if (direction == eRenderDirectionForward) {
*nextFrame = firstFrame;
} else {
*nextFrame = lastFrame - frameStep;
}
break;
case ePlaybackModeBounce:
if (direction == eRenderDirectionForward) {
*newDirection = eRenderDirectionBackward;
*nextFrame = lastFrame - frameStep;
} else {
*newDirection = eRenderDirectionForward;
*nextFrame = firstFrame + frameStep;
}
break;
case ePlaybackModeOnce:
default:
if (direction == eRenderDirectionForward) {
return false;
} else {
*nextFrame = lastFrame - frameStep;
break;
}
}
} else {
if (direction == eRenderDirectionForward) {
*nextFrame = frame + frameStep;
} else {
*nextFrame = frame - frameStep;
}
}
return true;
} // OutputSchedulerThreadPrivate::getNextFrameInSequence
void
OutputSchedulerThreadPrivate::getNearestInSequence(RenderDirectionEnum direction,
int frame,
int firstFrame,
int lastFrame,
int* nextFrame)
{
if ( (frame >= firstFrame) && (frame <= lastFrame) ) {
*nextFrame = frame;
} else if (frame < firstFrame) {
if (direction == eRenderDirectionForward) {
*nextFrame = firstFrame;
} else {
*nextFrame = lastFrame;
}
} else { // frame > lastFrame
if (direction == eRenderDirectionForward) {
*nextFrame = lastFrame;
} else {
*nextFrame = firstFrame;
}
}
}
#ifndef NATRON_PLAYBACK_USES_THREAD_POOL
void
OutputSchedulerThread::pushFramesToRender(int startingFrame,
int nThreads)
{
QMutexLocker l(&_imp->framesToRenderMutex);
_imp->lastFramePushedIndex = startingFrame;
pushFramesToRenderInternal(startingFrame, nThreads);
}
void
OutputSchedulerThread::pushFramesToRenderInternal(int startingFrame,
int nThreads)
{
// QMutexLocker l(&_imp->framesToRenderMutex); already locked (check below)
assert( !_imp->framesToRenderMutex.tryLock() );
///Make sure at least 1 frame is pushed
if (nThreads <= 0) {
nThreads = 1;
}
RenderDirectionEnum direction;
int firstFrame, lastFrame, frameStep;
OutputSchedulerThreadStartArgsPtr runArgs = _imp->runArgs.lock();
assert(runArgs);
direction = runArgs->pushTimelineDirection;
firstFrame = runArgs->firstFrame;
lastFrame = runArgs->lastFrame;
frameStep = runArgs->frameStep;
PlaybackModeEnum pMode = _imp->engine->getPlaybackMode();
RenderDirectionEnum newDirection = direction;
if (firstFrame == lastFrame) {
_imp->framesToRender.push_back(startingFrame);
#ifdef TRACE_SCHEDULER
qDebug() << "Scheduler Thread: Pushing frame to render: " << startingFrame;
#endif
_imp->lastFramePushedIndex = startingFrame;
} else {
///Push 2x the count of threads to be sure no one will be waiting
while ( (int)_imp->framesToRender.size() < nThreads * 2 ) {
_imp->framesToRender.push_back(startingFrame);
#ifdef TRACE_SCHEDULER
QString pushDirectionStr = newDirection == eRenderDirectionForward ? QLatin1String("Forward") : QLatin1String("Backward");
qDebug() << "Scheduler Thread: Pushing frame to render: " << startingFrame << ", new push direction is " << pushDirectionStr;
#endif
_imp->lastFramePushedIndex = startingFrame;
runArgs->pushTimelineDirection = newDirection;
if ( !OutputSchedulerThreadPrivate::getNextFrameInSequence(pMode, newDirection, startingFrame,
firstFrame, lastFrame, frameStep, &startingFrame, &newDirection) ) {
break;
}
}
}
///Wake up render threads to notify them there's work to do
_imp->framesToRenderNotEmptyCond.wakeAll();
}
void
OutputSchedulerThread::pushAllFrameRange()
{
QMutexLocker l(&_imp->framesToRenderMutex);
RenderDirectionEnum direction;
int firstFrame, lastFrame, frameStep;
OutputSchedulerThreadStartArgsPtr runArgs = _imp->runArgs.lock();
assert(runArgs);
direction = runArgs->pushTimelineDirection;
firstFrame = runArgs->firstFrame;
lastFrame = runArgs->lastFrame;
frameStep = runArgs->frameStep;
if (direction == eRenderDirectionForward) {
for (int i = firstFrame; i <= lastFrame; i += frameStep) {
#ifdef TRACE_SCHEDULER
qDebug() << "Scheduler Thread: Pushing frame to render: " << i;
#endif
_imp->framesToRender.push_back(i);
}
} else {
for (int i = lastFrame; i >= firstFrame; i -= frameStep) {
#ifdef TRACE_SCHEDULER
qDebug() << "Scheduler Thread: Pushing frame to render: " << i;
#endif
_imp->framesToRender.push_back(i);
}
}
///Wake up render threads to notify them there's work to do
_imp->framesToRenderNotEmptyCond.wakeAll();
}
void
OutputSchedulerThread::pushFramesToRender(int nThreads)
{
QMutexLocker l(&_imp->framesToRenderMutex);
RenderDirectionEnum direction;
int firstFrame, lastFrame, frameStep;
OutputSchedulerThreadStartArgsPtr runArgs = _imp->runArgs.lock();
assert(runArgs);
direction = runArgs->pushTimelineDirection;
firstFrame = runArgs->firstFrame;
lastFrame = runArgs->lastFrame;
frameStep = runArgs->frameStep;
PlaybackModeEnum pMode = _imp->engine->getPlaybackMode();
int frame = _imp->lastFramePushedIndex;
if ( (firstFrame == lastFrame) && (frame == firstFrame) ) {
return;
}
RenderDirectionEnum newDirection = direction;
///If startingTime is already taken into account in the framesToRender, push new frames from the last one in the stack instead
bool canContinue = OutputSchedulerThreadPrivate::getNextFrameInSequence(pMode, direction, frame,
firstFrame, lastFrame, frameStep, &frame, &newDirection);
if ( canContinue && (direction != newDirection) ) {
runArgs->pushTimelineDirection = newDirection;
}
if (canContinue) {
pushFramesToRenderInternal(frame, nThreads);
} else {
///Still wake up threads that may still sleep
_imp->framesToRenderNotEmptyCond.wakeAll();
}
}
int
OutputSchedulerThread::pickFrameToRender(RenderThreadTask* thread,
bool* enableRenderStats,
std::vector<ViewIdx>* viewsToRender)
{
///Flag the thread as inactive
{
QMutexLocker l(&_imp->renderThreadsMutex);
RenderThreads::iterator found = _imp->getRunnableIterator(thread);
assert( found != _imp->renderThreads.end() );
found->active = false;
///Wake up the scheduler if it is waiting for all threads do be inactive
_imp->allRenderThreadsInactiveCond.wakeOne();
}
bool gotFrame = false;
int frame = -1;
{
QMutexLocker l(&_imp->framesToRenderMutex);
while ( _imp->framesToRender.empty() && !thread->mustQuit() ) {
///Notify that we're no longer doing work
thread->notifyIsRunning(false);
_imp->framesToRenderNotEmptyCond.wait(&_imp->framesToRenderMutex);
}
if ( !_imp->framesToRender.empty() ) {
///Notify that we're running for good, will do nothing if flagged already running
thread->notifyIsRunning(true);
frame = _imp->framesToRender.front();
_imp->framesToRender.pop_front();
gotFrame = true;
}
}
// thread is quitting, make sure we notified the application it is no longer running
if (!gotFrame) {
thread->notifyIsRunning(false);
*enableRenderStats = false;
return -1;
} else {
///Flag the thread as active
{
QMutexLocker l(&_imp->renderThreadsMutex);
RenderThreads::iterator found = _imp->getRunnableIterator(thread);
assert( found != _imp->renderThreads.end() );
found->active = true;
}
OutputSchedulerThreadStartArgsPtr args = _imp->runArgs.lock();
*enableRenderStats = args->enableRenderStats;
*viewsToRender = args->viewsToRender;
return frame;
}
} // OutputSchedulerThread::pickFrameToRender
#else // NATRON_PLAYBACK_USES_THREAD_POOL
void
OutputSchedulerThread::startTasksFromLastStartedFrame()
{
int frame;
bool canContinue;
{
QMutexLocker l(&_imp->framesToRenderMutex);
RenderDirectionEnum direction;
int firstFrame, lastFrame, frameStep;
{
QMutexLocker l(&_imp->runArgsMutex);
direction = _imp->livingRunArgs.timelineDirection;
firstFrame = _imp->livingRunArgs.firstFrame;
lastFrame = _imp->livingRunArgs.lastFrame;
frameStep = _imp->livingRunArgs.frameStep;
}
PlaybackModeEnum pMode = _imp->engine->getPlaybackMode();
frame = _imp->lastFramePushedIndex;
if ( (firstFrame == lastFrame) && (frame == firstFrame) ) {
return;
}
RenderDirectionEnum newDirection = direction;
///If startingTime is already taken into account in the framesToRender, push new frames from the last one in the stack instead
canContinue = OutputSchedulerThreadPrivate::getNextFrameInSequence(pMode, direction, frame,
firstFrame, lastFrame, frameStep, &frame, &newDirection);
if (newDirection != direction) {
QMutexLocker l(&_imp->runArgsMutex);
_imp->livingRunArgs.timelineDirection = newDirection;
}
}
if (canContinue) {
QMutexLocker l(&_imp->renderThreadsMutex);
startTasks(frame);
}
}
void
OutputSchedulerThread::startTasks(int startingFrame)
{
int maxThreads = _imp->threadPool->maxThreadCount();
int activeThreads = _imp->getNActiveRenderThreads();
//This thread is from the thread pool so do not count it as it is probably done anyway
if (QThread::currentThread() != this) {
activeThreads -= 1;
}
int nFrames;
#ifdef NATRON_SCHEDULER_SPAWN_THREADS_WITH_TIMER
//We check every now and then if we need to start new threads
{
int nbAvailableThreads = maxThreads - activeThreads;
if (nbAvailableThreads <= 0) {
return;
}
nFrames = 1;
}
#else
//Start one more thread until we use all the thread pool.
//We leave some CPU available so that the multi-thread suite can take advantage of it
nFrames = boost::algorithm::clamp(maxThreads - activeThreads, 1, 1);
#endif
RenderDirectionEnum direction;
int firstFrame, lastFrame, frameStep;
bool useStats;
std::vector<int> viewsToRender;
{
QMutexLocker l(&_imp->runArgsMutex);
direction = _imp->livingRunArgs.timelineDirection;
firstFrame = _imp->livingRunArgs.firstFrame;
lastFrame = _imp->livingRunArgs.lastFrame;
frameStep = _imp->livingRunArgs.frameStep;
useStats = _imp->livingRunArgs.enableRenderStats;
viewsToRender = _imp->livingRunArgs.viewsToRender;
}
PlaybackModeEnum pMode = _imp->engine->getPlaybackMode();
if (firstFrame == lastFrame) {
RenderThreadTask* task = createRunnable(startingFrame, useStats, viewsToRender);
_imp->appendRunnable(task);
QMutexLocker k(&_imp->framesToRenderMutex);
_imp->lastFramePushedIndex = startingFrame;
} else {
int frame = startingFrame;
RenderDirectionEnum newDirection = direction;
for (int i = 0; i < nFrames; ++i) {
RenderThreadTask* task = createRunnable(frame, useStats, viewsToRender);
_imp->appendRunnable(task);
{
QMutexLocker k(&_imp->framesToRenderMutex);
_imp->lastFramePushedIndex = frame;
}
if ( !OutputSchedulerThreadPrivate::getNextFrameInSequence(pMode, direction, frame,
firstFrame, lastFrame, frameStep, &frame, &newDirection) ) {
break;
}
}
if (newDirection != direction) {
QMutexLocker l(&_imp->runArgsMutex);
_imp->livingRunArgs.timelineDirection = newDirection;
}
}
} // OutputSchedulerThread::startTasks
#endif //NATRON_PLAYBACK_USES_THREAD_POOL
void
OutputSchedulerThread::onThreadSpawnsTimerTriggered()
{
#ifdef NATRON_SCHEDULER_SPAWN_THREADS_WITH_TIMER
#ifdef NATRON_PLAYBACK_USES_THREAD_POOL
startTasksFromLastStartedFrame();
#else
///////////
/////If we were analysing the CPU activity, now set the appropriate number of threads to render.
int newNThreads, lastNThreads;
adjustNumberOfThreads(&newNThreads, &lastNThreads);