forked from NatronGitHub/Natron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOutputEffectInstance.cpp
530 lines (469 loc) · 21 KB
/
OutputEffectInstance.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
/* ***** 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 "OutputEffectInstance.h"
#include <map>
#include <sstream>
#include <algorithm> // min, max
#include <fstream>
#include <cassert>
#include <stdexcept>
#include <QtCore/QReadWriteLock>
#include <QtCore/QCoreApplication>
#include <QtCore/QThread>
#include <QtCore/QRegExp>
#include <QtConcurrentMap> // QtCore on Qt4, QtConcurrent on Qt5
#include <QtConcurrentRun> // QtCore on Qt4, QtConcurrent on Qt5
#include <SequenceParsing.h> // for removePath
#include "Global/QtCompat.h"
#include "Global/FStreamsSupport.h"
#include "Engine/AppInstance.h"
#include "Engine/AppManager.h"
#include "Engine/BlockingBackgroundRender.h"
#include "Engine/DiskCacheNode.h"
#include "Engine/Image.h"
#include "Engine/ImageParams.h"
#include "Engine/KnobFile.h"
#include "Engine/KnobTypes.h"
#include "Engine/Log.h"
#include "Engine/Node.h"
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxEffectInstance.h"
#include "Engine/OfxImageEffectInstance.h"
#include "Engine/OutputSchedulerThread.h"
#include "Engine/PluginMemory.h"
#include "Engine/Project.h"
#include "Engine/RenderStats.h"
#include "Engine/RotoContext.h"
#include "Engine/RotoDrawableItem.h"
#include "Engine/Settings.h"
#include "Engine/Timer.h"
#include "Engine/Transform.h"
#include "Engine/ViewerInstance.h"
#include "Engine/ViewIdx.h"
#include "Engine/EngineFwd.h"
//#define NATRON_ALWAYS_ALLOCATE_FULL_IMAGE_BOUNDS
NATRON_NAMESPACE_ENTER
OutputEffectInstance::OutputEffectInstance(NodePtr node)
: EffectInstance(node)
, _outputEffectDataLock()
, _renderSequenceRequests()
, _engine()
{
}
OutputEffectInstance::OutputEffectInstance(const OutputEffectInstance& other)
: EffectInstance(other)
, _outputEffectDataLock()
, _renderSequenceRequests()
, _engine(other._engine)
{
}
OutputEffectInstance::~OutputEffectInstance()
{
}
void
OutputEffectInstance::renderCurrentFrame(bool canAbort)
{
_engine->renderCurrentFrame(getApp()->isRenderStatsActionChecked(), canAbort);
}
void
OutputEffectInstance::renderCurrentFrameWithRenderStats(bool canAbort)
{
_engine->renderCurrentFrame(true, canAbort);
}
bool
OutputEffectInstance::ifInfiniteclipRectToProjectDefault(RectD* rod) const
{
if ( !getApp()->getProject() ) {
return false;
}
/*If the rod is infinite clip it to the project's default*/
Format projectDefault;
getApp()->getProject()->getProjectDefaultFormat(&projectDefault);
// BE CAREFUL:
// std::numeric_limits<int>::infinity() does not exist (check std::numeric_limits<int>::has_infinity)
// an int can not be equal to (or compared to) std::numeric_limits<double>::infinity()
bool isRodProjectFormat = false;
if (rod->left() <= kOfxFlagInfiniteMin) {
rod->set_left( projectDefault.left() );
isRodProjectFormat = true;
}
if (rod->bottom() <= kOfxFlagInfiniteMin) {
rod->set_bottom( projectDefault.bottom() );
isRodProjectFormat = true;
}
if (rod->right() >= kOfxFlagInfiniteMax) {
rod->set_right( projectDefault.right() );
isRodProjectFormat = true;
}
if (rod->top() >= kOfxFlagInfiniteMax) {
rod->set_top( projectDefault.top() );
isRodProjectFormat = true;
}
return isRodProjectFormat;
}
void
OutputEffectInstance::renderFullSequence(bool isBlocking,
bool enableRenderStats,
BlockingBackgroundRender* renderController,
int first,
int last,
int frameStep)
{
int viewsCount = getApp()->getProject()->getProjectViewsCount();
const ViewIdx mainView(0);
std::vector<ViewIdx> viewsToRender(viewsCount);
for (int i = 0; i < viewsCount; ++i) {
viewsToRender[i] = ViewIdx(i);
}
///The effect is sequential (e.g: WriteFFMPEG), and thus cannot render multiple views, we have to choose one
///We pick the user defined main view in the project settings
SequentialPreferenceEnum sequentiallity = getSequentialPreference();
bool canOnlyHandleOneView = sequentiallity == eSequentialPreferenceOnlySequential || sequentiallity == eSequentialPreferencePreferSequential;
if (canOnlyHandleOneView) {
viewsToRender.clear();
viewsToRender.push_back(mainView);
}
KnobIPtr outputFileNameKnob = getKnobByName(kOfxImageEffectFileParamName);
KnobOutputFile* outputFileName = outputFileNameKnob ? dynamic_cast<KnobOutputFile*>( outputFileNameKnob.get() ) : 0;
std::string pattern = outputFileName ? outputFileName->getValue() : std::string();
if ( isViewAware() ) {
//If the Writer is view aware, check if it wants to render all views at once or not
std::size_t foundViewPattern = pattern.find_first_of("%v");
if (foundViewPattern == std::string::npos) {
foundViewPattern = pattern.find_first_of("%V");
}
if (foundViewPattern == std::string::npos) {
///No view pattern
///all views will be overwritten to the same file
///If this is WriteOIIO, check the parameter "viewsSelector" to determine if the user wants to encode all
///views to a single file or not
KnobIPtr viewsKnob = getKnobByName(kWriteOIIOParamViewsSelector);
bool hasViewChoice = false;
if ( viewsKnob && !viewsKnob->getIsSecret() ) {
KnobChoice* viewsChoice = dynamic_cast<KnobChoice*>( viewsKnob.get() );
if (viewsChoice) {
hasViewChoice = true;
int viewChoice_i = viewsChoice->getValue();
if (viewChoice_i == 0) { // the "All" choice
viewsToRender.clear();
// note: if the plugin renders all views to a single file, then rendering view 0 will do the job.
viewsToRender.push_back( ViewIdx(0) );
} else {
//The user has specified a view
viewsToRender.clear();
assert(viewChoice_i >= 1);
viewsToRender.push_back( ViewIdx(viewChoice_i - 1) );
}
}
}
if (!hasViewChoice) {
if (viewsToRender.size() > 1) {
std::string mainViewName;
const std::vector<std::string>& viewNames = getApp()->getProject()->getProjectViewNames();
if ( mainView < (int)viewNames.size() ) {
mainViewName = viewNames[mainView];
}
QString message = tr("%1 does not support multi-view, only the view %2 will be rendered.")
.arg( QString::fromUtf8( getNode()->getLabel_mt_safe().c_str() ) )
.arg( QString::fromUtf8( mainViewName.c_str() ) );
if (!renderController) {
message.append( QChar::fromLatin1('\n') );
message.append( QString::fromUtf8("You can use the %v or %V indicator in the filename to render to separate files.\n"
"Would you like to continue?") );
StandardButtonEnum rep = Dialogs::questionDialog(tr("Multi-view support").toStdString(), message.toStdString(), false, StandardButtons(eStandardButtonOk | eStandardButtonCancel), eStandardButtonOk);
if (rep != eStandardButtonOk) {
return;
}
} else {
Dialogs::warningDialog( tr("Multi-view support").toStdString(), message.toStdString() );
}
}
//Render the main-view only...
viewsToRender.clear();
viewsToRender.push_back(mainView);
}
} else {
///The user wants to write each view into a separate file
///This will disregard the content of kWriteOIIOParamViewsSelector and the Writer
///should write one view per-file.
}
} else { // !isViewAware
if (viewsToRender.size() > 1) {
std::string mainViewName;
const std::vector<std::string>& viewNames = getApp()->getProject()->getProjectViewNames();
if ( mainView < (int)viewNames.size() ) {
mainViewName = viewNames[mainView];
}
QString message = tr("%1 does not support multi-view, only the view %2 will be rendered.")
.arg( QString::fromUtf8( getNode()->getLabel_mt_safe().c_str() ) )
.arg( QString::fromUtf8( mainViewName.c_str() ) );
if (!renderController) {
message.append( QChar::fromLatin1('\n') );
message.append( QString::fromUtf8("You can use the %v or %V indicator in the filename to render to separate files.\n"
"Would you like to continue?") );
StandardButtonEnum rep = Dialogs::questionDialog(tr("Multi-view support").toStdString(), message.toStdString(), false, StandardButtons(eStandardButtonOk | eStandardButtonCancel), eStandardButtonOk);
if (rep != eStandardButtonOk) {
// Notify progress that we were aborted
getRenderEngine()->s_renderFinished(1);
return;
}
} else {
Dialogs::warningDialog( tr("Multi-view support").toStdString(), message.toStdString() );
}
}
}
if (first != last && !isVideoWriter() && isWriter()) {
// We render a sequence, check that the user wants to render multiple images
// Look first for # character
std::size_t foundHash = pattern.find_first_of("#");
if (foundHash == std::string::npos) {
// Look for printf style numbering
QRegExp exp(QString::fromUtf8("%[0-9]*d"));
QString qp(QString::fromUtf8(pattern.c_str()));
if (!qp.contains(exp)) {
QString message = tr("You are trying to render the frame range [%1 - %2] but you did not specify any hash ('#') character(s) or printf-like format ('%d') for the padding. This will result in the same image being overwritten multiple times.").arg(first).arg(last);
if (!renderController) {
message += tr("Would you like to continue?");
StandardButtonEnum rep = Dialogs::questionDialog(tr("Image Sequence").toStdString(), message.toStdString(), false, StandardButtons(eStandardButtonOk | eStandardButtonCancel), eStandardButtonOk);
if (rep != eStandardButtonOk) {
// Notify progress that we were aborted
getRenderEngine()->s_renderFinished(1);
return;
}
} else {
Dialogs::warningDialog( tr("Image Sequence").toStdString(), message.toStdString() );
}
}
}
}
RenderSequenceArgs args;
{
QMutexLocker k(&_outputEffectDataLock);
args.firstFrame = first;
args.lastFrame = last;
args.frameStep = frameStep;
args.renderController = renderController;
args.useStats = enableRenderStats;
args.blocking = isBlocking;
args.viewsToRender = viewsToRender;
_renderSequenceRequests.push_back(args);
if (_renderSequenceRequests.size() > 1) {
//The node is already rendering a sequence, queue it and dequeue it in notifyRenderFinished()
return;
}
}
launchRenderSequence(args);
} // OutputEffectInstance::renderFullSequence
void
OutputEffectInstance::launchRenderSequence(const RenderSequenceArgs& args)
{
createWriterPath();
///If you want writers to render backward (from last to first), just change the flag in parameter here
_engine->renderFrameRange(args.blocking,
args.useStats,
args.firstFrame,
args.lastFrame,
args.frameStep,
args.viewsToRender,
eRenderDirectionForward);
}
void
OutputEffectInstance::createWriterPath()
{
///Make sure that the file path exists
KnobIPtr fileParam = getKnobByName(kOfxImageEffectFileParamName);
if (fileParam) {
KnobStringBase* isString = dynamic_cast<KnobStringBase*>( fileParam.get() );
if (isString) {
std::string pattern = isString->getValue();
std::string path = SequenceParsing::removePath(pattern);
std::map<std::string, std::string> env;
getApp()->getProject()->getEnvironmentVariables(env);
Project::expandVariable(env, path);
if ( !path.empty() ) {
QDir().mkpath( QString::fromUtf8( path.c_str() ) );
}
}
}
}
void
OutputEffectInstance::notifyRenderFinished()
{
RenderSequenceArgs newArgs;
{
QMutexLocker k(&_outputEffectDataLock);
if ( !_renderSequenceRequests.empty() ) {
const RenderSequenceArgs& args = _renderSequenceRequests.front();
if (args.renderController) {
args.renderController->notifyFinished();
}
_renderSequenceRequests.pop_front();
}
if ( _renderSequenceRequests.empty() ) {
return;
}
newArgs = _renderSequenceRequests.front();
}
launchRenderSequence(newArgs);
}
bool
OutputEffectInstance::isSequentialRenderBeingAborted() const
{
return _engine ? _engine->isSequentialRenderBeingAborted() : false;
}
bool
OutputEffectInstance::isDoingSequentialRender() const
{
return _engine ? _engine->isDoingSequentialRender() : false;
}
void
OutputEffectInstance::initializeData()
{
_engine.reset( createRenderEngine() );
}
RenderEngine*
OutputEffectInstance::createRenderEngine()
{
OutputEffectInstancePtr thisShared = boost::dynamic_pointer_cast<OutputEffectInstance>( shared_from_this() );
assert(thisShared);
return new RenderEngine(thisShared);
}
void
OutputEffectInstance::reportStats(int time,
ViewIdx view,
double wallTime,
const std::map<NodePtr, NodeRenderStats > & stats)
{
std::string filename;
KnobIPtr fileKnob = getKnobByName(kOfxImageEffectFileParamName);
if (fileKnob) {
KnobOutputFile* strKnob = dynamic_cast<KnobOutputFile*>( fileKnob.get() );
if (strKnob) {
QString qfileName = QString::fromUtf8( SequenceParsing::generateFileNameFromPattern(strKnob->getValue( 0, ViewIdx(view) ), getApp()->getProject()->getProjectViewNames(), time, view).c_str() );
QtCompat::removeFileExtension(qfileName);
qfileName.append( QString::fromUtf8("-stats.txt") );
filename = qfileName.toStdString();
}
}
//If there's no filename knob, do not write anything
if ( filename.empty() ) {
std::cout << tr("Cannot write render statistics file: "
"%1 does not seem to have a parameter named \"filename\" "
"to determine the location where to write the stats file.")
.arg( QString::fromUtf8( getScriptName_mt_safe().c_str() ) ).toStdString();
return;
}
FStreamsSupport::ofstream ofile;
FStreamsSupport::open(&ofile, filename);
if (!ofile) {
std::cout << tr("Failure to write render statistics file.").toStdString() << std::endl;
return;
}
ofile << "Time spent to render frame (wall clock time): " << Timer::printAsTime(wallTime, false).toStdString() << std::endl;
for (std::map<NodePtr, NodeRenderStats >::const_iterator it = stats.begin(); it != stats.end(); ++it) {
ofile << "------------------------------- " << it->first->getScriptName_mt_safe() << "------------------------------- " << std::endl;
ofile << "Time spent rendering: " << Timer::printAsTime(it->second.getTotalTimeSpentRendering(), false).toStdString() << std::endl;
const RectD & rod = it->second.getRoD();
ofile << "Region of definition: x1 = " << rod.x1 << " y1 = " << rod.y1 << " x2 = " << rod.x2 << " y2 = " << rod.y2 << std::endl;
ofile << "Is Identity to Effect? ";
NodePtr identity = it->second.getInputImageIdentity();
if (identity) {
ofile << "Yes, to " << identity->getScriptName_mt_safe() << std::endl;
} else {
ofile << "No" << std::endl;
}
ofile << "Has render-scale support? ";
if ( it->second.isRenderScaleSupportEnabled() ) {
ofile << "Yes";
} else {
ofile << "No";
}
ofile << std::endl;
ofile << "Has tiles support? ";
if ( it->second.isTilesSupportEnabled() ) {
ofile << "Yes";
} else {
ofile << "No";
}
ofile << std::endl;
ofile << "Channels processed: ";
std::bitset<4> processChannels = it->second.getChannelsRendered();
if (processChannels[0]) {
ofile << "red ";
}
if (processChannels[1]) {
ofile << "green ";
}
if (processChannels[2]) {
ofile << "blue ";
}
if (processChannels[3]) {
ofile << "alpha";
}
ofile << std::endl;
ofile << "Output alpha premultiplication: ";
switch ( it->second.getOutputPremult() ) {
case eImagePremultiplicationOpaque:
ofile << "opaque";
break;
case eImagePremultiplicationPremultiplied:
ofile << "premultiplied";
break;
case eImagePremultiplicationUnPremultiplied:
ofile << "unpremultiplied";
break;
}
ofile << std::endl;
ofile << "Mipmap level(s) rendered: ";
for (std::set<unsigned int>::const_iterator it2 = it->second.getMipMapLevelsRendered().begin(); it2 != it->second.getMipMapLevelsRendered().end(); ++it2) {
ofile << *it2 << ' ';
}
ofile << std::endl;
int nbCacheMiss, nbCacheHit, nbCacheHitButDownscaled;
it->second.getCacheAccessInfos(&nbCacheMiss, &nbCacheHit, &nbCacheHitButDownscaled);
ofile << "Nb cache hit: " << nbCacheMiss << std::endl;
ofile << "Nb cache miss: " << nbCacheMiss << std::endl;
ofile << "Nb cache hit requiring mipmap downscaling: " << nbCacheHitButDownscaled << std::endl;
const std::set<std::string> & planes = it->second.getPlanesRendered();
ofile << "Plane(s) rendered: ";
for (std::set<std::string>::const_iterator it2 = planes.begin(); it2 != planes.end(); ++it2) {
ofile << *it2 << ' ';
}
ofile << std::endl;
std::list<std::pair<RectI, NodePtr> > identityRectangles = it->second.getIdentityRectangles();
const std::list<RectI> & renderedRectangles = it->second.getRenderedRectangles();
ofile << "Identity rectangles: " << identityRectangles.size() << std::endl;
for (std::list<std::pair<RectI, NodePtr> > ::iterator it2 = identityRectangles.begin(); it2 != identityRectangles.end(); ++it2) {
ofile << "Origin: " << it2->second->getScriptName_mt_safe() << ", rect: x1 = " << it2->first.x1
<< " y1 = " << it2->first.y1 << " x2 = " << it2->first.x2 << " y2 = " << it2->first.y2 << std::endl;
}
ofile << "Rectangles rendered: " << renderedRectangles.size() << std::endl;
for (std::list<RectI>::const_iterator it2 = renderedRectangles.begin(); it2 != renderedRectangles.end(); ++it2) {
ofile << "x1 = " << it2->x1 << " y1 = " << it2->y1 << " x2 = " << it2->x2 << " y2 = " << it2->y2 << std::endl;
}
}
} // OutputEffectInstance::reportStats
NATRON_NAMESPACE_EXIT
NATRON_NAMESPACE_USING
#include "moc_OutputEffectInstance.cpp"