Improved detected of source file type + EncoderInfo object can check if the given...
[simple-x264-launcher.git] / src / thread_encode.cpp
blobcee4bd0efd011c9880c4b36739d6b3115de37292
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2014 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 "job_object.h"
30 #include "binaries.h"
31 #include "mediainfo.h"
33 //Encoders
34 #include "encoder_factory.h"
36 //Source
37 #include "source_avisynth.h"
38 #include "source_vapoursynth.h"
40 //Qt Framework
41 #include <QDate>
42 #include <QTime>
43 #include <QDateTime>
44 #include <QFileInfo>
45 #include <QDir>
46 #include <QProcess>
47 #include <QMutex>
48 #include <QTextCodec>
49 #include <QLocale>
50 #include <QCryptographicHash>
53 * RAII execution state handler
55 class ExecutionStateHandler
57 public:
58 ExecutionStateHandler(void)
60 x264_set_thread_execution_state(true);
62 ~ExecutionStateHandler(void)
64 x264_set_thread_execution_state(false);
66 private:
67 //Disable copy constructor and assignment
68 ExecutionStateHandler(const ExecutionStateHandler &other) {}
69 ExecutionStateHandler &operator=(const ExecutionStateHandler &) {}
71 //Prevent object allocation on the heap
72 void *operator new(size_t); void *operator new[](size_t);
73 void operator delete(void *); void operator delete[](void*);
77 * Macros
79 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
80 { \
81 if(ABORT_FLAG) \
82 { \
83 log("\nPROCESS ABORTED BY USER !!!"); \
84 setStatus(JobStatus_Aborted); \
85 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
86 return; \
87 } \
88 else if(!(OK_FLAG)) \
89 { \
90 setStatus(JobStatus_Failed); \
91 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
92 return; \
93 } \
94 } \
95 while(0)
97 #define CONNECT(OBJ) do \
98 { \
99 if((OBJ)) \
101 connect((OBJ), SIGNAL(statusChanged(JobStatus)), this, SLOT(setStatus(JobStatus)), Qt::DirectConnection); \
102 connect((OBJ), SIGNAL(progressChanged(unsigned int)), this, SLOT(setProgress(unsigned int)), Qt::DirectConnection); \
103 connect((OBJ), SIGNAL(detailsChanged(QString)), this, SLOT(setDetails(QString)), Qt::DirectConnection); \
104 connect((OBJ), SIGNAL(messageLogged(QString)), this, SLOT(log(QString)), Qt::DirectConnection); \
107 while(0)
109 ///////////////////////////////////////////////////////////////////////////////
110 // Constructor & Destructor
111 ///////////////////////////////////////////////////////////////////////////////
113 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
115 m_jobId(QUuid::createUuid()),
116 m_sourceFileName(sourceFileName),
117 m_outputFileName(outputFileName),
118 m_options(new OptionsModel(*options)),
119 m_sysinfo(sysinfo),
120 m_preferences(preferences),
121 m_jobObject(new JobObject),
122 m_semaphorePaused(0),
123 m_encoder(NULL),
124 m_pipedSource(NULL)
126 m_abort = false;
127 m_pause = false;
129 //Create encoder object
130 m_encoder = EncoderFactory::createEncoder(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName, m_outputFileName);
132 //Create input handler object
133 switch(MediaInfo::analyze(m_sourceFileName))
135 case MediaInfo::FILETYPE_AVISYNTH:
136 if(m_sysinfo->hasAVSSupport())
138 m_pipedSource = new AvisynthSource (m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
140 break;
141 case MediaInfo::FILETYPE_VAPOURSYNTH:
142 if(m_sysinfo->hasVPSSupport())
144 m_pipedSource = new VapoursynthSource(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
146 break;
149 //Establish connections
150 CONNECT(m_encoder);
151 CONNECT(m_pipedSource);
154 EncodeThread::~EncodeThread(void)
156 X264_DELETE(m_encoder);
157 X264_DELETE(m_jobObject);
158 X264_DELETE(m_options);
161 ///////////////////////////////////////////////////////////////////////////////
162 // Thread entry point
163 ///////////////////////////////////////////////////////////////////////////////
165 void EncodeThread::run(void)
167 #if !defined(_DEBUG)
168 __try
170 checkedRun();
172 __except(1)
174 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
176 #else
177 checkedRun();
178 #endif
180 if(m_jobObject)
182 m_jobObject->terminateJob(42);
183 X264_DELETE(m_jobObject);
187 void EncodeThread::checkedRun(void)
189 m_progress = 0;
190 m_status = JobStatus_Starting;
196 ExecutionStateHandler executionStateHandler;
197 encode();
199 catch(const std::exception &e)
201 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(e.what())));
202 setStatus(JobStatus_Failed);
204 catch(char *msg)
206 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
207 setStatus(JobStatus_Failed);
209 catch(...)
211 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
212 setStatus(JobStatus_Failed);
215 catch(...)
217 x264_fatal_exit(L"Unhandeled exception error in encode thread!");
221 void EncodeThread::start(Priority priority)
223 qDebug("Thread starting...");
225 m_abort = false;
226 m_pause = false;
228 while(m_semaphorePaused.tryAcquire(1, 0));
229 QThread::start(priority);
232 ///////////////////////////////////////////////////////////////////////////////
233 // Encode functions
234 ///////////////////////////////////////////////////////////////////////////////
236 void EncodeThread::encode(void)
238 QDateTime startTime = QDateTime::currentDateTime();
240 // -----------------------------------------------------------------------------------
241 // Print Information
242 // -----------------------------------------------------------------------------------
244 //Print some basic info
245 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
246 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
247 log(tr("Source file : %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
248 log(tr("Output file : %1").arg(QDir::toNativeSeparators(m_outputFileName)));
250 //Print system info
251 log(tr("\n--- SYSTEMINFO ---\n"));
252 log(tr("Binary Path : %1").arg(QDir::toNativeSeparators(m_sysinfo->getAppPath())));
253 log(tr("Avisynth : %1").arg(m_sysinfo->hasAVSSupport() ? tr("Yes") : tr("No")));
254 log(tr("VapourSynth : %1").arg(m_sysinfo->hasVPSSupport() ? QDir::toNativeSeparators(m_sysinfo->getVPSPath()) : tr("N/A")));
256 //Print encoder settings
257 log(tr("\n--- SETTINGS ---\n"));
258 log(tr("Encoder : %1").arg(m_encoder->getName()));
259 log(tr("Source : %1").arg(m_pipedSource ? m_pipedSource->getName() : tr("Native")));
260 log(tr("RC Mode : %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
261 log(tr("Preset : %1").arg(m_options->preset()));
262 log(tr("Tuning : %1").arg(m_options->tune()));
263 log(tr("Profile : %1").arg(m_options->profile()));
264 log(tr("Custom : %1").arg(m_options->customEncParams().isEmpty() ? tr("(None)") : m_options->customEncParams()));
266 bool ok = false;
267 unsigned int frames = 0;
269 // -----------------------------------------------------------------------------------
270 // Check Versions
271 // -----------------------------------------------------------------------------------
273 log(tr("\n--- CHECK VERSION ---\n"));
275 unsigned int encoderRevision = UINT_MAX, sourceRevision = UINT_MAX;
276 bool encoderModified = false, sourceModified = false;
278 log("Detect video encoder version:\n");
280 //Check encoder version
281 encoderRevision = m_encoder->checkVersion(encoderModified);
282 CHECK_STATUS(m_abort, (ok = (encoderRevision != UINT_MAX)));
284 //Is encoder version suppoprted?
285 CHECK_STATUS(m_abort, (ok = m_encoder->isVersionSupported(encoderRevision, encoderModified)));
287 if(m_pipedSource)
289 log("\nDetect video source version:\n");
291 //Is source type available?
292 CHECK_STATUS(m_abort, (ok = m_pipedSource->isSourceAvailable()));
294 //Checking source version
295 sourceRevision = m_pipedSource->checkVersion(sourceModified);
296 CHECK_STATUS(m_abort, (ok = (sourceRevision != UINT_MAX)));
298 //Is source version supported?
299 CHECK_STATUS(m_abort, (ok = m_pipedSource->isVersionSupported(sourceRevision, sourceModified)));
302 //Print tool versions
303 log(QString("\n> %1").arg(m_encoder->printVersion(encoderRevision, encoderModified)));
304 if(m_pipedSource)
306 log(QString("> %1").arg(m_pipedSource->printVersion(sourceRevision, sourceModified)));
309 // -----------------------------------------------------------------------------------
310 // Detect Source Info
311 // -----------------------------------------------------------------------------------
313 //Detect source info
314 if(m_pipedSource)
316 log(tr("\n--- GET SOURCE INFO ---\n"));
317 ok = m_pipedSource->checkSourceProperties(frames);
318 CHECK_STATUS(m_abort, ok);
321 // -----------------------------------------------------------------------------------
322 // Encoding Passes
323 // -----------------------------------------------------------------------------------
325 //Run encoding passes
326 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
328 const QString passLogFile = getPasslogFile(m_outputFileName);
330 log(tr("\n--- ENCODING PASS #1 ---\n"));
331 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames, 1, passLogFile);
332 CHECK_STATUS(m_abort, ok);
334 log(tr("\n--- ENCODING PASS #2 ---\n"));
335 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames, 2, passLogFile);
336 CHECK_STATUS(m_abort, ok);
338 else
340 log(tr("\n--- ENCODING VIDEO ---\n"));
341 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames);
342 CHECK_STATUS(m_abort, ok);
345 // -----------------------------------------------------------------------------------
346 // Encoding complete
347 // -----------------------------------------------------------------------------------
349 log(tr("\n--- COMPLETED ---\n"));
351 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
352 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)));
353 setStatus(JobStatus_Completed);
356 ///////////////////////////////////////////////////////////////////////////////
357 // Misc functions
358 ///////////////////////////////////////////////////////////////////////////////
360 void EncodeThread::log(const QString &text)
362 emit messageLogged(m_jobId, text);
365 void EncodeThread::setStatus(const JobStatus &newStatus)
367 if(m_status != newStatus)
369 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
371 if(m_status != JobStatus_Paused) setProgress(0);
373 if(newStatus == JobStatus_Failed)
375 setDetails("The job has failed. See log for details!");
377 if(newStatus == JobStatus_Aborted)
379 setDetails("The job was aborted by the user!");
381 m_status = newStatus;
382 emit statusChanged(m_jobId, newStatus);
386 void EncodeThread::setProgress(const unsigned int &newProgress)
388 if(m_progress != newProgress)
390 m_progress = newProgress;
391 emit progressChanged(m_jobId, m_progress);
395 void EncodeThread::setDetails(const QString &text)
397 if((!text.isEmpty()) && (m_details.compare(text) != 0))
399 emit detailsChanged(m_jobId, text);
400 m_details = text;
404 QString EncodeThread::getPasslogFile(const QString &outputFile)
406 QFileInfo info(outputFile);
407 QString passLogFile = QString("%1/%2.stats").arg(info.absolutePath(), info.completeBaseName());
408 int counter = 1;
410 while(QFileInfo(passLogFile).exists())
412 passLogFile = QString("%1/%2_%3.stats").arg(info.absolutePath(), info.completeBaseName(), QString::number(++counter));
415 return passLogFile;