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"
38 * Win32 API definitions
40 typedef HANDLE (WINAPI *CreateJobObjectFun)(__in_opt LPSECURITY_ATTRIBUTES lpJobAttributes, __in_opt LPCSTR lpName);
41 typedef BOOL (WINAPI *SetInformationJobObjectFun)(__in HANDLE hJob, __in JOBOBJECTINFOCLASS JobObjectInformationClass, __in_bcount(cbJobObjectInformationLength) LPVOID lpJobObjectInformation, __in DWORD cbJobObjectInformationLength);
42 typedef BOOL (WINAPI *AssignProcessToJobObjectFun)(__in HANDLE hJob, __in HANDLE hProcess);
47 QMutex EncodeThread::m_mutex_startProcess;
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)),
84 m_handle_jobObject(NULL),
91 EncodeThread::~EncodeThread(void)
93 X264_DELETE(m_options);
95 if(m_handle_jobObject)
97 CloseHandle(m_handle_jobObject);
98 m_handle_jobObject = NULL;
102 ///////////////////////////////////////////////////////////////////////////////
103 // Thread entry point
104 ///////////////////////////////////////////////////////////////////////////////
106 void EncodeThread::run(void)
114 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
117 if(m_handle_jobObject)
119 CloseHandle(m_handle_jobObject);
120 m_handle_jobObject = NULL;
124 void EncodeThread::checkedRun(void)
127 m_status = JobStatus_Starting;
137 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
138 setStatus(JobStatus_Failed);
142 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
143 setStatus(JobStatus_Failed);
148 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
152 void EncodeThread::start(Priority priority)
154 qDebug("Thread starting...");
159 while(m_semaphorePaused.tryAcquire(1, 0));
160 QThread::start(priority);
163 ///////////////////////////////////////////////////////////////////////////////
165 ///////////////////////////////////////////////////////////////////////////////
167 void EncodeThread::encode(void)
169 QDateTime startTime = QDateTime::currentDateTime();
171 //Print some basic info
172 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
173 log(tr("Source file: %1").arg(m_sourceFileName));
174 log(tr("Output file: %1").arg(m_outputFileName));
176 //Print encoder settings
177 log(tr("\n--- SETTINGS ---\n"));
178 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
179 log(tr("Preset: %1").arg(m_options->preset()));
180 log(tr("Tuning: %1").arg(m_options->tune()));
181 log(tr("Profile: %1").arg(m_options->profile()));
182 log(tr("Custom: %1").arg(m_options->custom().isEmpty() ? tr("(None)") : m_options->custom()));
185 unsigned int frames = 0;
188 const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
190 //Checking x264 version
191 log(tr("\n--- CHECK VERSION ---\n"));
192 unsigned int revision_x264 = UINT_MAX;
193 ok = ((revision_x264 = checkVersionX264(m_x64)) != UINT_MAX);
194 CHECK_STATUS(m_abort, ok);
196 //Checking avs2yuv version
197 unsigned int revision_avs2yuv = UINT_MAX;
200 ok = ((revision_avs2yuv = checkVersionAvs2yuv()) != UINT_MAX);
201 CHECK_STATUS(m_abort, ok);
205 log(tr("\nx264 revision: %1 (core #%2)").arg(QString::number(revision_x264 % REV_MULT), QString::number(revision_x264 / REV_MULT)));
206 if(revision_avs2yuv != UINT_MAX) log(tr("Avs2YUV version: %1.%2.%3").arg(QString::number(revision_avs2yuv / REV_MULT), QString::number((revision_avs2yuv % REV_MULT) / 10),QString::number((revision_avs2yuv % REV_MULT) % 10)));
208 //Is x264 revision supported?
209 if((revision_x264 % REV_MULT) < VER_X264_MINIMUM_REV)
211 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
212 setStatus(JobStatus_Failed);
215 if((revision_x264 / REV_MULT) != VER_X264_CURRENT_API)
217 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
218 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
220 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != VER_x264_AVS2YUV_VER))
222 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
223 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
224 setStatus(JobStatus_Failed);
231 log(tr("\n--- AVS INFO ---\n"));
232 ok = checkProperties(frames);
233 CHECK_STATUS(m_abort, ok);
236 //Run encoding passes
237 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
239 QFileInfo info(m_outputFileName);
240 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
242 if(QFileInfo(passLogFile).exists())
245 while(QFileInfo(passLogFile).exists())
247 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
251 log(tr("\n--- PASS 1 ---\n"));
252 ok = runEncodingPass(m_x64, usePipe, frames, 1, passLogFile);
253 CHECK_STATUS(m_abort, ok);
255 log(tr("\n--- PASS 2 ---\n"));
256 ok = runEncodingPass(m_x64, usePipe, frames, 2, passLogFile);
257 CHECK_STATUS(m_abort, ok);
261 log(tr("\n--- ENCODING ---\n"));
262 ok = runEncodingPass(m_x64, usePipe, frames);
263 CHECK_STATUS(m_abort, ok);
266 log(tr("\n--- DONE ---\n"));
267 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
268 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)));
269 setStatus(JobStatus_Completed);
272 bool EncodeThread::runEncodingPass(bool x64, bool usePipe, unsigned int frames, int pass, const QString &passLogFile)
274 QProcess processEncode, processAvisynth;
278 QStringList cmdLine_Avisynth;
279 cmdLine_Avisynth << QDir::toNativeSeparators(m_sourceFileName);
280 cmdLine_Avisynth << "-";
281 processAvisynth.setStandardOutputProcess(&processEncode);
283 log("Creating Avisynth process:");
284 if(!startProcess(processAvisynth, QString("%1/avs2yuv.exe").arg(m_binDir), cmdLine_Avisynth, false))
290 QStringList cmdLine_Encode = buildCommandLine(usePipe, frames, pass, passLogFile);
292 log("Creating x264 process:");
293 if(!startProcess(processEncode, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine_Encode))
298 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
299 QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
300 QRegExp regExpFrameCnt("^(\\d+) frames:");
302 bool bTimeout = false;
303 bool bAborted = false;
305 //Main processing loop
306 while(processEncode.state() != QProcess::NotRunning)
308 unsigned int waitCounter = 0;
310 //Wait until new output is available
315 processEncode.kill();
316 processAvisynth.kill();
320 if(m_pause && (processEncode.state() == QProcess::Running))
322 JobStatus previousStatus = m_status;
323 setStatus(JobStatus_Paused);
324 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
325 bool ok[2] = {false, false};
326 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
327 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
328 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
329 while(m_pause) m_semaphorePaused.acquire();
330 while(m_semaphorePaused.tryAcquire(1, 0));
331 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
332 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
333 if(!m_abort) setStatus(previousStatus);
334 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
338 if(!processEncode.waitForReadyRead(2500))
340 if(processEncode.state() == QProcess::Running)
342 if(waitCounter++ > m_processTimeoutCounter)
344 processEncode.kill();
345 qWarning("x264 process timed out <-- killing!");
346 log("\nPROCESS TIMEOUT !!!");
353 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
360 //Exit main processing loop now?
361 if(bAborted || bTimeout)
367 while(processEncode.bytesAvailable() > 0)
369 QList<QByteArray> lines = processEncode.readLine().split('\r');
370 while(!lines.isEmpty())
372 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
374 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
377 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
378 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
379 setDetails(text.mid(offset).trimmed());
380 if(ok) setProgress(progress);
382 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
385 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
386 setStatus(JobStatus_Indexing);
387 setDetails(text.mid(offset).trimmed());
388 if(ok) setProgress(progress);
390 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
392 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
393 setDetails(text.mid(offset).trimmed());
395 else if(!text.isEmpty())
403 processEncode.waitForFinished(5000);
404 if(processEncode.state() != QProcess::NotRunning)
406 qWarning("x264 process still running, going to kill it!");
407 processEncode.kill();
408 processEncode.waitForFinished(-1);
411 processAvisynth.waitForFinished(5000);
412 if(processAvisynth.state() != QProcess::NotRunning)
414 qWarning("Avisynth process still running, going to kill it!");
415 processAvisynth.kill();
416 processAvisynth.waitForFinished(-1);
419 if(!(bTimeout || bAborted))
421 while(processAvisynth.bytesAvailable() > 0)
423 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
427 if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
429 if(!(bTimeout || bAborted))
431 log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
435 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
437 if(!(bTimeout || bAborted))
439 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
441 processEncode.close();
442 processAvisynth.close();
449 setStatus(JobStatus_Running_Pass1);
450 setDetails(tr("First pass completed. Preparing for second pass..."));
453 setStatus(JobStatus_Running_Pass2);
454 setDetails(tr("Second pass completed successfully."));
457 setStatus(JobStatus_Running);
458 setDetails(tr("Encode completed successfully."));
463 processEncode.close();
464 processAvisynth.close();
468 QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, int pass, const QString &passLogFile)
472 switch(m_options->rcMode())
474 case OptionsModel::RCMode_CRF:
475 cmdLine << "--crf" << QString::number(m_options->quantizer());
477 case OptionsModel::RCMode_CQ:
478 cmdLine << "--qp" << QString::number(m_options->quantizer());
480 case OptionsModel::RCMode_2Pass:
481 case OptionsModel::RCMode_ABR:
482 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
485 throw "Bad rate-control mode !!!";
489 if((pass == 1) || (pass == 2))
491 cmdLine << "--pass" << QString::number(pass);
492 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
495 cmdLine << "--preset" << m_options->preset().toLower();
497 if(m_options->tune().compare("none", Qt::CaseInsensitive))
499 cmdLine << "--tune" << m_options->tune().toLower();
502 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
504 cmdLine << "--profile" << m_options->profile().toLower();
507 if(!m_options->custom().isEmpty())
509 //FIXME: Handle custom parameters that contain spaces!
510 cmdLine.append(m_options->custom().split(" "));
513 cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
517 if(frames < 1) throw "Frames not set!";
518 cmdLine << "--frames" << QString::number(frames);
519 cmdLine << "--demuxer" << "y4m";
520 cmdLine << "--stdin" << "y4m" << "-";
524 cmdLine << QDir::toNativeSeparators(m_sourceFileName);
530 unsigned int EncodeThread::checkVersionX264(bool x64)
533 QStringList cmdLine = QStringList() << "--version";
535 log("Creating process:");
536 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
541 QRegExp regExpVersion("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)\\b");
543 bool bTimeout = false;
544 bool bAborted = false;
546 unsigned int revision = UINT_MAX;
547 unsigned int coreVers = UINT_MAX;
549 while(process.state() != QProcess::NotRunning)
557 if(!process.waitForReadyRead())
559 if(process.state() == QProcess::Running)
562 qWarning("x264 process timed out <-- killing!");
563 log("\nPROCESS TIMEOUT !!!");
568 while(process.bytesAvailable() > 0)
570 QList<QByteArray> lines = process.readLine().split('\r');
571 while(!lines.isEmpty())
573 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
575 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
577 bool ok1 = false, ok2 = false;
578 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
579 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
580 if(ok1) coreVers = temp1;
581 if(ok2) revision = temp2;
591 process.waitForFinished();
592 if(process.state() != QProcess::NotRunning)
595 process.waitForFinished(-1);
598 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
600 if(!(bTimeout || bAborted))
602 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
607 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
609 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
613 return (coreVers * REV_MULT) + (revision % REV_MULT);
616 unsigned int EncodeThread::checkVersionAvs2yuv(void)
620 log("\nCreating process:");
621 if(!startProcess(process, QString("%1/avs2yuv.exe").arg(m_binDir), QStringList()))
626 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b");
627 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b");
629 bool bTimeout = false;
630 bool bAborted = false;
632 unsigned int ver_maj = UINT_MAX;
633 unsigned int ver_min = UINT_MAX;
634 unsigned int ver_mod = 0;
636 while(process.state() != QProcess::NotRunning)
644 if(!process.waitForReadyRead())
646 if(process.state() == QProcess::Running)
649 qWarning("Avs2YUV process timed out <-- killing!");
650 log("\nPROCESS TIMEOUT !!!");
655 while(process.bytesAvailable() > 0)
657 QList<QByteArray> lines = process.readLine().split('\r');
658 while(!lines.isEmpty())
660 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
662 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
669 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
671 bool ok1 = false, ok2 = false, ok3 = false;
672 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
673 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
674 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
675 if(ok1) ver_maj = temp1;
676 if(ok2) ver_min = temp2;
677 if(ok3) ver_mod = temp3;
679 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
681 bool ok1 = false, ok2 = false;
682 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
683 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
684 if(ok1) ver_maj = temp1;
685 if(ok2) ver_min = temp2;
691 process.waitForFinished();
692 if(process.state() != QProcess::NotRunning)
695 process.waitForFinished(-1);
698 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
700 if(!(bTimeout || bAborted))
702 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
707 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
709 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
713 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
716 bool EncodeThread::checkProperties(unsigned int &frames)
720 QStringList cmdLine = QStringList() << "-frames" << "1";
721 cmdLine << QDir::toNativeSeparators(m_sourceFileName) << "NUL";
723 log("Creating process:");
724 if(!startProcess(process, QString("%1/avs2yuv.exe").arg(m_binDir), cmdLine))
729 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
730 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
732 bool bTimeout = false;
733 bool bAborted = false;
737 unsigned int fpsNom = 0;
738 unsigned int fpsDen = 0;
739 unsigned int fSizeW = 0;
740 unsigned int fSizeH = 0;
742 while(process.state() != QProcess::NotRunning)
750 if(!process.waitForReadyRead())
752 if(process.state() == QProcess::Running)
755 qWarning("Avs2YUV process timed out <-- killing!");
756 log("\nPROCESS TIMEOUT !!!");
761 while(process.bytesAvailable() > 0)
763 QList<QByteArray> lines = process.readLine().split('\r');
764 while(!lines.isEmpty())
766 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
768 if((offset = regExpInt.lastIndexIn(text)) >= 0)
770 bool ok1 = false, ok2 = false;
771 bool ok3 = false, ok4 = false;
772 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
773 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
774 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
775 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
776 if(ok1) fSizeW = temp1;
777 if(ok2) fSizeH = temp2;
778 if(ok3) fpsNom = temp3;
779 if(ok4) frames = temp4;
781 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
783 bool ok1 = false, ok2 = false;
784 bool ok3 = false, ok4 = false, ok5 = false;
785 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
786 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
787 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
788 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
789 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
790 if(ok1) fSizeW = temp1;
791 if(ok2) fSizeH = temp2;
792 if(ok3) fpsNom = temp3;
793 if(ok4) fpsDen = temp4;
794 if(ok5) frames = temp5;
804 process.waitForFinished();
805 if(process.state() != QProcess::NotRunning)
808 process.waitForFinished(-1);
811 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
813 if(!(bTimeout || bAborted))
815 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
822 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
828 if((fSizeW > 0) && (fSizeH > 0))
830 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
832 if((fpsNom > 0) && (fpsDen > 0))
834 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
836 if((fpsNom > 0) && (fpsDen == 0))
838 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
842 log(tr("No. Frames: %1").arg(QString::number(frames)));
848 ///////////////////////////////////////////////////////////////////////////////
850 ///////////////////////////////////////////////////////////////////////////////
852 void EncodeThread::setStatus(JobStatus newStatus)
854 if(m_status != newStatus)
856 m_status = newStatus;
857 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
861 if(newStatus == JobStatus_Failed)
863 setDetails("The job has failed. See log for details!");
865 if(newStatus == JobStatus_Aborted)
867 setDetails("The job was aborted by the user!");
869 emit statusChanged(m_jobId, newStatus);
873 void EncodeThread::setProgress(unsigned int newProgress)
875 if(m_progress != newProgress)
877 m_progress = newProgress;
878 emit progressChanged(m_jobId, m_progress);
882 void EncodeThread::setDetails(const QString &text)
884 emit detailsChanged(m_jobId, text);
887 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
889 static AssignProcessToJobObjectFun AssignProcessToJobObjectPtr = NULL;
890 static CreateJobObjectFun CreateJobObjectPtr = NULL;
891 static SetInformationJobObjectFun SetInformationJobObjectPtr = NULL;
893 QMutexLocker lock(&m_mutex_startProcess);
894 log(commandline2string(program, args) + "\n");
896 //Create a new job object, if not done yet
897 if(!m_handle_jobObject)
899 if(!CreateJobObjectPtr || !SetInformationJobObjectPtr)
901 QLibrary Kernel32Lib("kernel32.dll");
902 CreateJobObjectPtr = (CreateJobObjectFun) Kernel32Lib.resolve("CreateJobObjectA");
903 SetInformationJobObjectPtr = (SetInformationJobObjectFun) Kernel32Lib.resolve("SetInformationJobObject");
905 if(CreateJobObjectPtr && SetInformationJobObjectPtr)
907 m_handle_jobObject = CreateJobObjectPtr(NULL, NULL);
908 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
910 m_handle_jobObject = NULL;
912 if(m_handle_jobObject)
914 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
915 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
916 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
917 SetInformationJobObjectPtr(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
922 //Initialize AssignProcessToJobObject function
923 if(!AssignProcessToJobObjectPtr)
925 QLibrary Kernel32Lib("kernel32.dll");
926 AssignProcessToJobObjectPtr = (AssignProcessToJobObjectFun) Kernel32Lib.resolve("AssignProcessToJobObject");
931 process.setProcessChannelMode(QProcess::MergedChannels);
932 process.setReadChannel(QProcess::StandardOutput);
936 process.setProcessChannelMode(QProcess::SeparateChannels);
937 process.setReadChannel(QProcess::StandardError);
940 process.start(program, args);
942 if(process.waitForStarted())
944 if(AssignProcessToJobObjectPtr)
946 AssignProcessToJobObjectPtr(m_handle_jobObject, process.pid()->hProcess);
948 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
950 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
957 log("Process creation has failed :-(");
958 QString errorMsg= process.errorString().trimmed();
959 if(!errorMsg.isEmpty()) log(errorMsg);
962 process.waitForFinished(-1);
966 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
968 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
970 for(int i = 0; i < arguments.count(); i++)
972 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));