1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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"
25 #include "model_options.h"
37 * Win32 API definitions
39 typedef HANDLE (WINAPI *CreateJobObjectFun)(__in_opt LPSECURITY_ATTRIBUTES lpJobAttributes, __in_opt LPCSTR lpName);
40 typedef BOOL (WINAPI *SetInformationJobObjectFun)(__in HANDLE hJob, __in JOBOBJECTINFOCLASS JobObjectInformationClass, __in_bcount(cbJobObjectInformationLength) LPVOID lpJobObjectInformation, __in DWORD cbJobObjectInformationLength);
41 typedef BOOL (WINAPI *AssignProcessToJobObjectFun)(__in HANDLE hJob, __in HANDLE hProcess);
46 QMutex EncodeThread::m_mutex_startProcess;
47 HANDLE EncodeThread::m_handle_jobObject = NULL;
52 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) \
56 log("\nPROCESS ABORTED BY USER !!!"); \
57 setStatus(JobStatus_Aborted); \
62 setStatus(JobStatus_Failed); \
70 static const unsigned int REV_MULT = 10000;
72 ///////////////////////////////////////////////////////////////////////////////
73 // Constructor & Destructor
74 ///////////////////////////////////////////////////////////////////////////////
76 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x64)
78 m_jobId(QUuid::createUuid()),
79 m_sourceFileName(sourceFileName),
80 m_outputFileName(outputFileName),
81 m_options(new OptionsModel(*options)),
88 EncodeThread::~EncodeThread(void)
90 X264_DELETE(m_options);
93 ///////////////////////////////////////////////////////////////////////////////
95 ///////////////////////////////////////////////////////////////////////////////
97 void EncodeThread::run(void)
102 m_status = JobStatus_Starting;
107 log(tr("EXCEPTION ERROR: ").append(QString::fromLatin1(msg)));
111 log(tr("EXCEPTION ERROR !!!"));
115 ///////////////////////////////////////////////////////////////////////////////
117 ///////////////////////////////////////////////////////////////////////////////
119 void EncodeThread::encode(void)
123 //Print some basic info
124 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
125 log(tr("Source file: %1").arg(m_sourceFileName));
126 log(tr("Output file: %1").arg(m_outputFileName));
127 log(tr("\n[Encoder Options]"));
128 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
129 log(tr("Preset: %1").arg(m_options->preset()));
130 log(tr("Tuning: %1").arg(m_options->tune()));
131 log(tr("Profile: %1").arg(m_options->profile()));
132 log(tr("Custom: %1").arg(m_options->custom().isEmpty() ? tr("(None)") : m_options->custom()));
135 log(tr("\n[Input Properties]"));
136 log(tr("Not implemented yet, sorry ;-)\n"));
141 log(tr("--- VERSION ---\n"));
142 unsigned int revision;
143 ok = ((revision = checkVersion(m_x64)) != UINT_MAX);
144 CHECK_STATUS(m_abort, ok);
146 //Is revision supported?
147 log(tr("\nx264 revision: %1 (core #%2)").arg(QString::number(revision % REV_MULT), QString::number(revision / REV_MULT)));
148 if((revision % REV_MULT) < VER_X264_MINIMUM_REV)
150 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
151 setStatus(JobStatus_Failed);
154 if((revision / REV_MULT) != VER_X264_CURRENT_API)
156 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
157 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
160 //Run encoding passes
161 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
163 QFileInfo info(m_outputFileName);
164 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
166 if(QFileInfo(passLogFile).exists())
169 while(QFileInfo(passLogFile).exists())
171 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
175 log(tr("\n--- PASS 1 ---\n"));
176 ok = runEncodingPass(m_x64, 1, passLogFile);
177 CHECK_STATUS(m_abort, ok);
179 log(tr("\n--- PASS 2 ---\n"));
180 ok = runEncodingPass(m_x64,2, passLogFile);
181 CHECK_STATUS(m_abort, ok);
185 log(tr("\n--- ENCODING ---\n"));
186 ok = runEncodingPass(m_x64);
187 CHECK_STATUS(m_abort, ok);
190 log(tr("\n--- DONE ---\n"));
191 log(tr("Job finished at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
192 setStatus(JobStatus_Completed);
195 bool EncodeThread::runEncodingPass(bool x64, int pass, const QString &passLogFile)
198 QStringList cmdLine = buildCommandLine(pass, passLogFile);
200 log("Creating process:");
201 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
206 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
207 QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
209 bool bTimeout = false;
210 bool bAborted = false;
212 while(process.state() != QProcess::NotRunning)
220 if(!process.waitForReadyRead(m_processTimeoutInterval))
222 if(process.state() == QProcess::Running)
225 qWarning("x264 process timed out <-- killing!");
226 log("\nPROCESS TIMEOUT !!!");
231 while(process.bytesAvailable() > 0)
233 QList<QByteArray> lines = process.readLine().split('\r');
234 while(!lines.isEmpty())
236 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
238 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
241 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
242 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
243 setDetails(text.mid(offset).trimmed());
244 if(ok) setProgress(progress);
246 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
249 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
250 setStatus(JobStatus_Indexing);
251 setDetails(text.mid(offset).trimmed());
252 if(ok) setProgress(progress);
254 else if(!text.isEmpty())
262 process.waitForFinished();
263 if(process.state() != QProcess::NotRunning)
266 process.waitForFinished(-1);
269 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
274 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
279 QStringList EncodeThread::buildCommandLine(int pass, const QString &passLogFile)
283 switch(m_options->rcMode())
285 case OptionsModel::RCMode_CRF:
286 cmdLine << "--crf" << QString::number(m_options->quantizer());
288 case OptionsModel::RCMode_CQ:
289 cmdLine << "--qp" << QString::number(m_options->quantizer());
291 case OptionsModel::RCMode_2Pass:
292 case OptionsModel::RCMode_ABR:
293 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
296 throw "Bad rate-control mode !!!";
300 if((pass == 1) || (pass == 2))
302 cmdLine << "--pass" << QString::number(pass);
303 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
306 if(m_options->tune().compare("none", Qt::CaseInsensitive))
308 cmdLine << "--tune" << m_options->tune().toLower();
311 cmdLine << "--preset" << m_options->preset().toLower();
313 if(!m_options->custom().isEmpty())
315 //FIXME: Handle custom parameters that contain spaces!
316 cmdLine.append(m_options->custom().split(" "));
319 cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
320 cmdLine << m_sourceFileName;
325 unsigned int EncodeThread::checkVersion(bool x64)
328 QStringList cmdLine = QStringList() << "--version";
330 log("Creating process:");
331 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
336 QRegExp regExpVersion("x264 (\\d)\\.(\\d+)\\.(\\d+) ([0-9A-Fa-f]{7})");
338 bool bTimeout = false;
339 bool bAborted = false;
341 unsigned int revision = UINT_MAX;
342 unsigned int coreVers = UINT_MAX;
344 while(process.state() != QProcess::NotRunning)
352 if(!process.waitForReadyRead(m_processTimeoutInterval))
354 if(process.state() == QProcess::Running)
357 qWarning("x264 process timed out <-- killing!");
358 log("\nPROCESS TIMEOUT !!!");
363 while(process.bytesAvailable() > 0)
365 QList<QByteArray> lines = process.readLine().split('\r');
366 while(!lines.isEmpty())
368 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
370 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
372 bool ok1 = false, ok2 = false;
373 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
374 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
375 if(ok1) coreVers = temp1;
376 if(ok2) revision = temp2;
386 process.waitForFinished();
387 if(process.state() != QProcess::NotRunning)
390 process.waitForFinished(-1);
393 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
398 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
400 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
404 return (coreVers * REV_MULT) + revision;
407 ///////////////////////////////////////////////////////////////////////////////
409 ///////////////////////////////////////////////////////////////////////////////
411 void EncodeThread::setStatus(JobStatus newStatus)
413 if(m_status != newStatus)
415 m_status = newStatus;
416 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted))
420 if(newStatus == JobStatus_Failed)
422 setDetails("The job has failed. See log for details!");
424 if(newStatus == JobStatus_Aborted)
426 setDetails("The job was aborted by the user!");
428 emit statusChanged(m_jobId, newStatus);
432 void EncodeThread::setProgress(unsigned int newProgress)
434 if(m_progress != newProgress)
436 m_progress = newProgress;
437 emit progressChanged(m_jobId, m_progress);
441 void EncodeThread::setDetails(const QString &text)
443 emit detailsChanged(m_jobId, text);
446 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args)
448 static AssignProcessToJobObjectFun AssignProcessToJobObjectPtr = NULL;
450 QMutexLocker lock(&m_mutex_startProcess);
451 log(commandline2string(program, args) + "\n");
453 if(!AssignProcessToJobObjectPtr)
455 QLibrary Kernel32Lib("kernel32.dll");
456 AssignProcessToJobObjectPtr = (AssignProcessToJobObjectFun) Kernel32Lib.resolve("AssignProcessToJobObject");
459 process.setProcessChannelMode(QProcess::MergedChannels);
460 process.setReadChannel(QProcess::StandardOutput);
461 process.start(program, args);
463 if(process.waitForStarted())
466 if(AssignProcessToJobObjectPtr)
468 AssignProcessToJobObjectPtr(m_handle_jobObject, process.pid()->hProcess);
470 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
472 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
479 log("Process creation has failed :-(");
480 QString errorMsg= process.errorString().trimmed();
481 if(!errorMsg.isEmpty()) log(errorMsg);
484 process.waitForFinished(-1);
488 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
490 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
492 for(int i = 0; i < arguments.count(); i++)
494 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));