Adapted for recent changes in NVEncC progress output.
[simple-x264-launcher.git] / src / thread_encode.cpp
blob730cd37bbd79b33b91e87f6fabfd49fc4b442762
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2019 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "thread_encode.h"
24 //Internal
25 #include "global.h"
26 #include "model_options.h"
27 #include "model_preferences.h"
28 #include "model_sysinfo.h"
29 #include "model_clipInfo.h"
30 #include "job_object.h"
31 #include "mediainfo.h"
33 //Encoders
34 #include "encoder_factory.h"
36 //Source
37 #include "source_factory.h"
39 //MUtils
40 #include <MUtils/OSSupport.h>
41 #include <MUtils/Version.h>
43 //Qt Framework
44 #include <QDate>
45 #include <QTime>
46 #include <QDateTime>
47 #include <QFileInfo>
48 #include <QDir>
49 #include <QProcess>
50 #include <QMutex>
51 #include <QTextCodec>
52 #include <QLocale>
53 #include <QCryptographicHash>
56 * RAII execution state handler
58 class ExecutionStateHandler
60 public:
61 ExecutionStateHandler(void)
63 x264_set_thread_execution_state(true);
65 ~ExecutionStateHandler(void)
67 x264_set_thread_execution_state(false);
69 private:
70 //Disable copy constructor and assignment
71 ExecutionStateHandler(const ExecutionStateHandler &other) {}
72 ExecutionStateHandler &operator=(const ExecutionStateHandler &) {}
74 //Prevent object allocation on the heap
75 void *operator new(size_t); void *operator new[](size_t);
76 void operator delete(void *); void operator delete[](void*);
80 * Macros
82 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
83 { \
84 if(ABORT_FLAG) \
85 { \
86 log("\nPROCESS ABORTED BY USER !!!"); \
87 setStatus(JobStatus_Aborted); \
88 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
89 return 0; \
90 } \
91 else if(!(OK_FLAG)) \
92 { \
93 setStatus(JobStatus_Failed); \
94 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
95 return 0; \
96 } \
97 } \
98 while(0)
100 #define CONNECT(OBJ) do \
102 if((OBJ)) \
104 connect((OBJ), SIGNAL(statusChanged(JobStatus)), this, SLOT(setStatus(JobStatus)), Qt::DirectConnection); \
105 connect((OBJ), SIGNAL(progressChanged(unsigned int)), this, SLOT(setProgress(unsigned int)), Qt::DirectConnection); \
106 connect((OBJ), SIGNAL(detailsChanged(QString)), this, SLOT(setDetails(QString)), Qt::DirectConnection); \
107 connect((OBJ), SIGNAL(messageLogged(QString)), this, SLOT(log(QString)), Qt::DirectConnection); \
110 while(0)
112 ///////////////////////////////////////////////////////////////////////////////
113 // Constructor & Destructor
114 ///////////////////////////////////////////////////////////////////////////////
116 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
118 m_jobId(QUuid::createUuid()),
119 m_sourceFileName(sourceFileName),
120 m_outputFileName(outputFileName),
121 m_options(new OptionsModel(*options)),
122 m_sysinfo(sysinfo),
123 m_preferences(preferences),
124 m_jobObject(new JobObject),
125 m_semaphorePaused(0),
126 m_encoder(NULL),
127 m_pipedSource(NULL)
129 m_abort = false;
130 m_pause = false;
132 //Create encoder object
133 m_encoder = EncoderFactory::createEncoder(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName, m_outputFileName);
135 //Create input handler object
136 switch(MediaInfo::analyze(m_sourceFileName))
138 case MediaInfo::FILETYPE_AVISYNTH:
139 if(m_sysinfo->hasAvisynth())
141 m_pipedSource = SourceFactory::createSource(SourceFactory::SourceType_AVS, m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
143 break;
144 case MediaInfo::FILETYPE_VAPOURSYNTH:
145 if(m_sysinfo->hasVapourSynth())
147 m_pipedSource = SourceFactory::createSource(SourceFactory::SourceType_VPS, m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
149 break;
152 //Establish connections
153 CONNECT(m_encoder);
154 CONNECT(m_pipedSource);
157 EncodeThread::~EncodeThread(void)
159 MUTILS_DELETE(m_encoder);
160 MUTILS_DELETE(m_jobObject);
161 MUTILS_DELETE(m_options);
162 MUTILS_DELETE(m_pipedSource);
165 ///////////////////////////////////////////////////////////////////////////////
166 // Thread entry point
167 ///////////////////////////////////////////////////////////////////////////////
169 void EncodeThread::run(void)
171 m_progress = 0;
172 m_status = JobStatus_Starting;
174 AbstractThread::run();
176 if (m_exception)
178 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
179 setStatus(JobStatus_Failed);
182 if(m_jobObject)
184 m_jobObject->terminateJob(42);
185 MUTILS_DELETE(m_jobObject);
189 void EncodeThread::start(Priority priority)
191 qDebug("Thread starting...");
193 m_abort = false;
194 m_pause = false;
196 while(m_semaphorePaused.tryAcquire(1, 0));
197 AbstractThread::start(priority);
200 ///////////////////////////////////////////////////////////////////////////////
201 // Encode functions
202 ///////////////////////////////////////////////////////////////////////////////
204 int EncodeThread::threadMain(void)
206 QDateTime startTime = QDateTime::currentDateTime();
208 // -----------------------------------------------------------------------------------
209 // Print Information
210 // -----------------------------------------------------------------------------------
212 //Print some basic info
213 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), MUtils::Version::app_build_date().toString(Qt::ISODate)));
214 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
215 log(tr("Source file : %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
216 log(tr("Output file : %1").arg(QDir::toNativeSeparators(m_outputFileName)));
218 //Print system info
219 log(tr("\n--- SYSTEMINFO ---\n"));
220 log(tr("Binary Path : %1").arg(QDir::toNativeSeparators(m_sysinfo->getAppPath())));
221 log(tr("Avisynth : %1").arg(m_sysinfo->hasAvisynth() ? tr("Yes") : tr("No")));
222 log(tr("VapourSynth : %1").arg(m_sysinfo->hasVapourSynth() ? tr("Yes") : tr("No")));
224 //Print encoder settings
225 log(tr("\n--- SETTINGS ---\n"));
226 log(tr("Encoder : %1").arg(m_encoder->getName()));
227 log(tr("Source : %1").arg(m_pipedSource ? m_pipedSource->getName() : tr("Native")));
228 log(tr("RC Mode : %1").arg(m_encoder->getEncoderInfo().rcModeToString(m_options->rcMode())));
229 log(tr("Preset : %1").arg(m_options->preset()));
230 log(tr("Tuning : %1").arg(m_options->tune()));
231 log(tr("Profile : %1").arg(m_options->profile()));
232 log(tr("Custom : %1").arg(m_options->customEncParams().isEmpty() ? tr("<None>") : m_options->customEncParams()));
234 bool ok = false;
235 ClipInfo clipInfo;
237 // -----------------------------------------------------------------------------------
238 // Check Versions
239 // -----------------------------------------------------------------------------------
241 log(tr("\n--- CHECK VERSION ---\n"));
243 unsigned int encoderRevision = UINT_MAX, sourceRevision = UINT_MAX;
244 bool encoderModified = false, sourceModified = false;
246 log("Detect video encoder version:\n");
248 //Check encoder version
249 encoderRevision = m_encoder->checkVersion(encoderModified);
250 CHECK_STATUS(m_abort, (ok = (encoderRevision != UINT_MAX)));
252 //Is encoder version suppoprted?
253 CHECK_STATUS(m_abort, (ok = m_encoder->isVersionSupported(encoderRevision, encoderModified)));
255 if(m_pipedSource)
257 log("\nDetect video source version:\n");
259 //Is source type available?
260 CHECK_STATUS(m_abort, (ok = m_pipedSource->isSourceAvailable()));
262 //Checking source version
263 sourceRevision = m_pipedSource->checkVersion(sourceModified);
264 CHECK_STATUS(m_abort, (ok = (sourceRevision != UINT_MAX)));
266 //Is source version supported?
267 CHECK_STATUS(m_abort, (ok = m_pipedSource->isVersionSupported(sourceRevision, sourceModified)));
270 //Print tool versions
271 log(QString("\n> %1").arg(m_encoder->printVersion(encoderRevision, encoderModified)));
272 if(m_pipedSource)
274 log(QString("> %1").arg(m_pipedSource->printVersion(sourceRevision, sourceModified)));
277 // -----------------------------------------------------------------------------------
278 // Detect Source Info
279 // -----------------------------------------------------------------------------------
281 //Detect source info
282 if(m_pipedSource)
284 log(tr("\n--- GET SOURCE INFO ---\n"));
285 ok = m_pipedSource->checkSourceProperties(clipInfo);
286 CHECK_STATUS(m_abort, ok);
289 // -----------------------------------------------------------------------------------
290 // Encoding Passes
291 // -----------------------------------------------------------------------------------
293 //Run encoding passes
294 if(m_encoder->getEncoderInfo().rcModeToType(m_options->rcMode()) == AbstractEncoderInfo::RC_TYPE_MULTIPASS)
296 const QString passLogFile = getPasslogFile(m_outputFileName);
298 log(tr("\n--- ENCODING PASS #1 ---\n"));
299 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo, 1, passLogFile);
300 CHECK_STATUS(m_abort, ok);
302 log(tr("\n--- ENCODING PASS #2 ---\n"));
303 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo, 2, passLogFile);
304 CHECK_STATUS(m_abort, ok);
306 else
308 log(tr("\n--- ENCODING VIDEO ---\n"));
309 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo);
310 CHECK_STATUS(m_abort, ok);
313 // -----------------------------------------------------------------------------------
314 // Encoding complete
315 // -----------------------------------------------------------------------------------
317 log(tr("\n--- COMPLETED ---\n"));
319 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
320 log(tr("Job finished at %1, %2. Process took %3 minutes, %4 seconds.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString(Qt::ISODate), QString::number(timePassed / 60), QString::number(timePassed % 60)));
321 setStatus(JobStatus_Completed);
323 return 1; /*completed*/
326 ///////////////////////////////////////////////////////////////////////////////
327 // Misc functions
328 ///////////////////////////////////////////////////////////////////////////////
330 void EncodeThread::log(const QString &text)
332 emit messageLogged(m_jobId, QDateTime::currentMSecsSinceEpoch(), text);
335 void EncodeThread::setStatus(const JobStatus &newStatus)
337 if(m_status != newStatus)
339 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
341 if(m_status != JobStatus_Paused) setProgress(0);
343 if(newStatus == JobStatus_Failed)
345 setDetails("The job has failed. See log for details!");
347 if(newStatus == JobStatus_Aborted)
349 setDetails("The job was aborted by the user!");
351 m_status = newStatus;
352 emit statusChanged(m_jobId, newStatus);
356 void EncodeThread::setProgress(const unsigned int &newProgress)
358 if(m_progress != newProgress)
360 m_progress = newProgress;
361 emit progressChanged(m_jobId, m_progress);
365 void EncodeThread::setDetails(const QString &text)
367 if((!text.isEmpty()) && (m_details.compare(text) != 0))
369 emit detailsChanged(m_jobId, text);
370 m_details = text;
374 QString EncodeThread::getPasslogFile(const QString &outputFile)
376 QFileInfo info(outputFile);
377 QString passLogFile = QString("%1/%2.stats").arg(info.absolutePath(), info.completeBaseName());
378 int counter = 1;
380 while(QFileInfo(passLogFile).exists())
382 passLogFile = QString("%1/%2_%3.stats").arg(info.absolutePath(), info.completeBaseName(), QString::number(++counter));
385 return passLogFile;