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"
36 * Win32 API definitions
38 typedef HANDLE (WINAPI *CreateJobObjectFun)(__in_opt LPSECURITY_ATTRIBUTES lpJobAttributes, __in_opt LPCSTR lpName);
39 typedef BOOL (WINAPI *SetInformationJobObjectFun)(__in HANDLE hJob, __in JOBOBJECTINFOCLASS JobObjectInformationClass, __in_bcount(cbJobObjectInformationLength) LPVOID lpJobObjectInformation, __in DWORD cbJobObjectInformationLength);
40 typedef BOOL (WINAPI *AssignProcessToJobObjectFun)(__in HANDLE hJob, __in HANDLE hProcess);
45 QMutex EncodeThread::m_mutex_startProcess;
46 HANDLE EncodeThread::m_handle_jobObject = NULL;
48 ///////////////////////////////////////////////////////////////////////////////
49 // Constructor & Destructor
50 ///////////////////////////////////////////////////////////////////////////////
52 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir)
54 m_jobId(QUuid::createUuid()),
55 m_sourceFileName(sourceFileName),
56 m_outputFileName(outputFileName),
57 m_options(new OptionsModel(*options)),
63 EncodeThread::~EncodeThread(void)
65 X264_DELETE(m_options);
68 ///////////////////////////////////////////////////////////////////////////////
70 ///////////////////////////////////////////////////////////////////////////////
72 void EncodeThread::run(void)
77 m_status = JobStatus_Starting;
82 log(tr("EXCEPTION ERROR: ").append(QString::fromLatin1(msg)));
86 log(tr("EXCEPTION ERROR !!!"));
90 ///////////////////////////////////////////////////////////////////////////////
92 ///////////////////////////////////////////////////////////////////////////////
94 void EncodeThread::encode(void)
98 //Print some basic info
99 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
100 log(tr("Source file: %1").arg(m_sourceFileName));
101 log(tr("Output file: %1").arg(m_outputFileName));
102 log(tr("\n[Encoder Options]"));
103 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
104 log(tr("Preset: %1").arg(m_options->preset()));
105 log(tr("Tuning: %1").arg(m_options->tune()));
106 log(tr("Profile: %1").arg(m_options->profile()));
107 log(tr("Custom: %1").arg(m_options->custom().isEmpty() ? tr("(None)") : m_options->custom()));
110 log(tr("\n[Input Properties]"));
111 log(tr("Not implemented yet, sorry ;-)\n"));
115 //Run encoding passes
116 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
118 QFileInfo info(m_outputFileName);
119 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
121 if(QFileInfo(passLogFile).exists())
124 while(QFileInfo(passLogFile).exists())
126 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
130 log("--- PASS 1 ---\n");
131 ok = runEncodingPass(1, passLogFile);
135 log("\nPROCESS ABORTED BY USER !!!");
136 setStatus(JobStatus_Aborted);
141 setStatus(JobStatus_Failed);
145 log("\n--- PASS 2 ---\n");
146 ok = runEncodingPass(2, passLogFile);
150 log("\nPROCESS ABORTED BY USER !!!");
151 setStatus(JobStatus_Aborted);
156 setStatus(JobStatus_Failed);
162 log("--- ENCODING ---\n");
163 ok = runEncodingPass();
167 log("\nPROCESS ABORTED BY USER !!!");
168 setStatus(JobStatus_Aborted);
173 setStatus(JobStatus_Failed);
178 log(tr("\nJob finished at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
179 setStatus(JobStatus_Completed);
182 bool EncodeThread::runEncodingPass(int pass, const QString &passLogFile)
185 QStringList cmdLine = buildCommandLine(pass, passLogFile);
187 log("Creating process:");
188 if(!startProcess(process, QString("%1/x264.exe").arg(m_binDir), cmdLine))
193 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
194 QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
196 bool bTimeout = false;
197 bool bAborted = false;
199 while(process.state() != QProcess::NotRunning)
207 if(!process.waitForReadyRead(m_processTimeoutInterval))
209 if(process.state() == QProcess::Running)
212 qWarning("x264 process timed out <-- killing!");
213 log("\nPROCESS TIMEOUT !!!");
218 while(process.bytesAvailable() > 0)
220 QList<QByteArray> lines = process.readLine().split('\r');
221 while(!lines.isEmpty())
223 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
225 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
228 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
229 if(ok) setProgress(progress);
230 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
231 setDetails(text.mid(offset).trimmed());
233 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
236 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
237 if(ok) setProgress(progress);
238 setStatus(JobStatus_Indexing);
239 setDetails(text.mid(offset).trimmed());
241 else if(!text.isEmpty())
249 process.waitForFinished();
250 if(process.state() != QProcess::NotRunning)
253 process.waitForFinished(-1);
256 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
261 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
266 QStringList EncodeThread::buildCommandLine(int pass, const QString &passLogFile)
270 switch(m_options->rcMode())
272 case OptionsModel::RCMode_CRF:
273 cmdLine << "--crf" << QString::number(m_options->quantizer());
275 case OptionsModel::RCMode_CQ:
276 cmdLine << "--qp" << QString::number(m_options->quantizer());
278 case OptionsModel::RCMode_2Pass:
279 case OptionsModel::RCMode_ABR:
280 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
283 throw "Bad rate-control mode !!!";
287 if((pass == 1) || (pass == 2))
289 cmdLine << "--pass" << QString::number(pass);
290 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
293 if(m_options->tune().compare("none", Qt::CaseInsensitive))
295 cmdLine << "--tune" << m_options->tune().toLower();
298 cmdLine << "--preset" << m_options->preset().toLower();
300 if(!m_options->custom().isEmpty())
302 //FIXME: Handle custom parameters that contain spaces!
303 cmdLine.append(m_options->custom().split(" "));
306 cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
307 cmdLine << m_sourceFileName;
312 ///////////////////////////////////////////////////////////////////////////////
314 ///////////////////////////////////////////////////////////////////////////////
316 void EncodeThread::setStatus(JobStatus newStatus)
318 if(m_status != newStatus)
320 m_status = newStatus;
321 emit statusChanged(m_jobId, newStatus);
326 void EncodeThread::setProgress(unsigned int newProgress)
328 if(m_progress != newProgress)
330 m_progress = newProgress;
331 emit progressChanged(m_jobId, m_progress);
335 void EncodeThread::setDetails(const QString &text)
337 emit detailsChanged(m_jobId, text);
340 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args)
342 static AssignProcessToJobObjectFun AssignProcessToJobObjectPtr = NULL;
344 QMutexLocker lock(&m_mutex_startProcess);
345 log(commandline2string(program, args) + "\n");
347 if(!AssignProcessToJobObjectPtr)
349 QLibrary Kernel32Lib("kernel32.dll");
350 AssignProcessToJobObjectPtr = (AssignProcessToJobObjectFun) Kernel32Lib.resolve("AssignProcessToJobObject");
353 process.setProcessChannelMode(QProcess::MergedChannels);
354 process.setReadChannel(QProcess::StandardOutput);
355 process.start(program, args);
357 if(process.waitForStarted())
360 if(AssignProcessToJobObjectPtr)
362 AssignProcessToJobObjectPtr(m_handle_jobObject, process.pid()->hProcess);
364 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
366 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
373 log("Process creation has failed :-(");
374 QString errorMsg= process.errorString().trimmed();
375 if(!errorMsg.isEmpty()) log(errorMsg);
378 process.waitForFinished(-1);
382 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
384 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
386 for(int i = 0; i < arguments.count(); i++)
388 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));