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"
40 QMutex EncodeThread::m_mutex_startProcess;
45 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) \
49 log("\nPROCESS ABORTED BY USER !!!"); \
50 setStatus(JobStatus_Aborted); \
51 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
56 setStatus(JobStatus_Failed); \
57 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
65 static const unsigned int REV_MULT = 10000;
67 ///////////////////////////////////////////////////////////////////////////////
68 // Constructor & Destructor
69 ///////////////////////////////////////////////////////////////////////////////
71 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x264_x64, bool avs2yuv_x64)
73 m_jobId(QUuid::createUuid()),
74 m_sourceFileName(sourceFileName),
75 m_outputFileName(outputFileName),
76 m_options(new OptionsModel(*options)),
79 m_avs2yuv_x64(avs2yuv_x64),
80 m_handle_jobObject(NULL),
87 EncodeThread::~EncodeThread(void)
89 X264_DELETE(m_options);
91 if(m_handle_jobObject)
93 CloseHandle(m_handle_jobObject);
94 m_handle_jobObject = NULL;
98 ///////////////////////////////////////////////////////////////////////////////
100 ///////////////////////////////////////////////////////////////////////////////
102 void EncodeThread::run(void)
110 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
113 if(m_handle_jobObject)
115 TerminateJobObject(m_handle_jobObject, 42);
116 m_handle_jobObject = NULL;
120 void EncodeThread::checkedRun(void)
123 m_status = JobStatus_Starting;
133 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
134 setStatus(JobStatus_Failed);
138 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
139 setStatus(JobStatus_Failed);
144 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
148 void EncodeThread::start(Priority priority)
150 qDebug("Thread starting...");
155 while(m_semaphorePaused.tryAcquire(1, 0));
156 QThread::start(priority);
159 ///////////////////////////////////////////////////////////////////////////////
161 ///////////////////////////////////////////////////////////////////////////////
163 void EncodeThread::encode(void)
165 QDateTime startTime = QDateTime::currentDateTime();
167 //Print some basic info
168 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
169 log(tr("Source file: %1").arg(m_sourceFileName));
170 log(tr("Output file: %1").arg(m_outputFileName));
172 //Print encoder settings
173 log(tr("\n--- SETTINGS ---\n"));
174 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
175 log(tr("Preset: %1").arg(m_options->preset()));
176 log(tr("Tuning: %1").arg(m_options->tune()));
177 log(tr("Profile: %1").arg(m_options->profile()));
178 log(tr("Custom: %1").arg(m_options->custom().isEmpty() ? tr("(None)") : m_options->custom()));
181 unsigned int frames = 0;
184 const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
185 const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
187 //Checking x264 version
188 log(tr("\n--- CHECK VERSION ---\n"));
189 unsigned int revision_x264 = UINT_MAX;
190 bool x264_modified = false;
191 ok = ((revision_x264 = checkVersionX264(m_x264_x64, x264_modified)) != UINT_MAX);
192 CHECK_STATUS(m_abort, ok);
194 //Checking avs2yuv version
195 unsigned int revision_avs2yuv = UINT_MAX;
198 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
199 CHECK_STATUS(m_abort, ok);
203 log(tr("\nx264 revision: %1 (core #%2)").arg(QString::number(revision_x264 % REV_MULT), QString::number(revision_x264 / REV_MULT)).append(x264_modified ? tr(" - with custom patches!") : QString()));
204 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)));
206 //Is x264 revision supported?
207 if((revision_x264 % REV_MULT) < VER_X264_MINIMUM_REV)
209 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
210 setStatus(JobStatus_Failed);
213 if((revision_x264 / REV_MULT) != VER_X264_CURRENT_API)
215 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
216 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
218 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != VER_X264_AVS2YUV_VER))
220 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
221 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
222 setStatus(JobStatus_Failed);
229 log(tr("\n--- AVS INFO ---\n"));
230 ok = checkProperties(m_avs2yuv_x64, frames);
231 CHECK_STATUS(m_abort, ok);
234 //Run encoding passes
235 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
237 QFileInfo info(m_outputFileName);
238 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
240 if(QFileInfo(passLogFile).exists())
243 while(QFileInfo(passLogFile).exists())
245 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
249 log(tr("\n--- PASS 1 ---\n"));
250 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile, 1, passLogFile);
251 CHECK_STATUS(m_abort, ok);
253 log(tr("\n--- PASS 2 ---\n"));
254 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile, 2, passLogFile);
255 CHECK_STATUS(m_abort, ok);
259 log(tr("\n--- ENCODING ---\n"));
260 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile);
261 CHECK_STATUS(m_abort, ok);
264 log(tr("\n--- DONE ---\n"));
265 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
266 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
267 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)));
268 setStatus(JobStatus_Completed);
271 bool EncodeThread::runEncodingPass(bool x264_x64, bool avs2yuv_x64, bool usePipe, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
273 QProcess processEncode, processAvisynth;
277 QStringList cmdLine_Avisynth;
278 cmdLine_Avisynth << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
279 cmdLine_Avisynth << "-";
280 processAvisynth.setStandardOutputProcess(&processEncode);
282 log("Creating Avisynth process:");
283 if(!startProcess(processAvisynth, QString("%1/%2.exe").arg(m_binDir, avs2yuv_x64 ? "avs2yuv_x64" : "avs2yuv"), cmdLine_Avisynth, false))
289 QStringList cmdLine_Encode = buildCommandLine(usePipe, frames, indexFile, pass, passLogFile);
291 log("Creating x264 process:");
292 if(!startProcess(processEncode, QString("%1/%2.exe").arg(m_binDir, x264_x64 ? "x264_x64" : "x264"), cmdLine_Encode))
297 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
298 QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
299 QRegExp regExpFrameCnt("^(\\d+) frames:");
301 QTextCodec *localCodec = QTextCodec::codecForName("System");
303 bool bTimeout = false;
304 bool bAborted = false;
306 //Main processing loop
307 while(processEncode.state() != QProcess::NotRunning)
309 unsigned int waitCounter = 0;
311 //Wait until new output is available
316 processEncode.kill();
317 processAvisynth.kill();
321 if(m_pause && (processEncode.state() == QProcess::Running))
323 JobStatus previousStatus = m_status;
324 setStatus(JobStatus_Paused);
325 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
326 bool ok[2] = {false, false};
327 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
328 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
329 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
330 while(m_pause) m_semaphorePaused.acquire();
331 while(m_semaphorePaused.tryAcquire(1, 0));
332 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
333 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
334 if(!m_abort) setStatus(previousStatus);
335 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
339 if(!processEncode.waitForReadyRead(2500))
341 if(processEncode.state() == QProcess::Running)
343 if(waitCounter++ > m_processTimeoutCounter)
345 processEncode.kill();
346 qWarning("x264 process timed out <-- killing!");
347 log("\nPROCESS TIMEOUT !!!");
354 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
361 //Exit main processing loop now?
362 if(bAborted || bTimeout)
368 while(processEncode.bytesAvailable() > 0)
370 QList<QByteArray> lines = processEncode.readLine().split('\r');
371 while(!lines.isEmpty())
373 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
375 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
378 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
379 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
380 setDetails(text.mid(offset).trimmed());
381 if(ok) setProgress(progress);
383 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
386 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
387 setStatus(JobStatus_Indexing);
388 setDetails(text.mid(offset).trimmed());
389 if(ok) setProgress(progress);
391 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
393 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
394 setDetails(text.mid(offset).trimmed());
396 else if(!text.isEmpty())
404 processEncode.waitForFinished(5000);
405 if(processEncode.state() != QProcess::NotRunning)
407 qWarning("x264 process still running, going to kill it!");
408 processEncode.kill();
409 processEncode.waitForFinished(-1);
412 processAvisynth.waitForFinished(5000);
413 if(processAvisynth.state() != QProcess::NotRunning)
415 qWarning("Avisynth process still running, going to kill it!");
416 processAvisynth.kill();
417 processAvisynth.waitForFinished(-1);
420 if(!(bTimeout || bAborted))
422 while(processAvisynth.bytesAvailable() > 0)
424 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
428 if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
430 if(!(bTimeout || bAborted))
432 log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
436 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
438 if(!(bTimeout || bAborted))
440 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
442 processEncode.close();
443 processAvisynth.close();
450 setStatus(JobStatus_Running_Pass1);
451 setDetails(tr("First pass completed. Preparing for second pass..."));
454 setStatus(JobStatus_Running_Pass2);
455 setDetails(tr("Second pass completed successfully."));
458 setStatus(JobStatus_Running);
459 setDetails(tr("Encode completed successfully."));
464 processEncode.close();
465 processAvisynth.close();
469 QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
472 double crf_int = 0.0, crf_frc = 0.0;
474 switch(m_options->rcMode())
476 case OptionsModel::RCMode_CQ:
477 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
479 case OptionsModel::RCMode_CRF:
480 crf_frc = modf(m_options->quantizer(), &crf_int);
481 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
483 case OptionsModel::RCMode_2Pass:
484 case OptionsModel::RCMode_ABR:
485 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
488 throw "Bad rate-control mode !!!";
492 if((pass == 1) || (pass == 2))
494 cmdLine << "--pass" << QString::number(pass);
495 cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
498 cmdLine << "--preset" << m_options->preset().toLower();
500 if(m_options->tune().compare("none", Qt::CaseInsensitive))
502 cmdLine << "--tune" << m_options->tune().toLower();
505 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
507 cmdLine << "--profile" << m_options->profile().toLower();
510 if(!m_options->custom().isEmpty())
512 //FIXME: Handle custom parameters that contain withspaces within quotes!
513 cmdLine.append(m_options->custom().split(" "));
516 cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
520 if(frames < 1) throw "Frames not set!";
521 cmdLine << "--frames" << QString::number(frames);
522 cmdLine << "--demuxer" << "y4m";
523 cmdLine << "--stdin" << "y4m" << "-";
527 cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
528 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
534 unsigned int EncodeThread::checkVersionX264(bool x64, bool &modified)
537 QStringList cmdLine = QStringList() << "--version";
539 log("Creating process:");
540 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
545 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
546 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
548 bool bTimeout = false;
549 bool bAborted = false;
551 unsigned int revision = UINT_MAX;
552 unsigned int coreVers = UINT_MAX;
555 while(process.state() != QProcess::NotRunning)
563 if(!process.waitForReadyRead())
565 if(process.state() == QProcess::Running)
568 qWarning("x264 process timed out <-- killing!");
569 log("\nPROCESS TIMEOUT !!!");
574 while(process.bytesAvailable() > 0)
576 QList<QByteArray> lines = process.readLine().split('\r');
577 while(!lines.isEmpty())
579 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
581 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
583 bool ok1 = false, ok2 = false;
584 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
585 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
586 if(ok1) coreVers = temp1;
587 if(ok2) revision = temp2;
589 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
591 bool ok1 = false, ok2 = false;
592 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
593 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
594 if(ok1) coreVers = temp1;
595 if(ok2) revision = temp2;
606 process.waitForFinished();
607 if(process.state() != QProcess::NotRunning)
610 process.waitForFinished(-1);
613 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
615 if(!(bTimeout || bAborted))
617 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
622 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
624 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
628 return (coreVers * REV_MULT) + (revision % REV_MULT);
631 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
635 log("\nCreating process:");
636 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv"), QStringList()))
641 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
642 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
644 bool bTimeout = false;
645 bool bAborted = false;
647 unsigned int ver_maj = UINT_MAX;
648 unsigned int ver_min = UINT_MAX;
649 unsigned int ver_mod = 0;
651 while(process.state() != QProcess::NotRunning)
659 if(!process.waitForReadyRead())
661 if(process.state() == QProcess::Running)
664 qWarning("Avs2YUV process timed out <-- killing!");
665 log("\nPROCESS TIMEOUT !!!");
670 while(process.bytesAvailable() > 0)
672 QList<QByteArray> lines = process.readLine().split('\r');
673 while(!lines.isEmpty())
675 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
677 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
684 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
686 bool ok1 = false, ok2 = false, ok3 = false;
687 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
688 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
689 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
690 if(ok1) ver_maj = temp1;
691 if(ok2) ver_min = temp2;
692 if(ok3) ver_mod = temp3;
694 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
696 bool ok1 = false, ok2 = false;
697 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
698 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
699 if(ok1) ver_maj = temp1;
700 if(ok2) ver_min = temp2;
706 process.waitForFinished();
707 if(process.state() != QProcess::NotRunning)
710 process.waitForFinished(-1);
713 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
715 if(!(bTimeout || bAborted))
717 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
722 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
724 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
728 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
731 bool EncodeThread::checkProperties(bool x64, unsigned int &frames)
735 QStringList cmdLine = QStringList() << "-frames" << "1";
736 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
738 log("Creating process:");
739 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv"), cmdLine))
744 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
745 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
747 QTextCodec *localCodec = QTextCodec::codecForName("System");
749 bool bTimeout = false;
750 bool bAborted = false;
754 unsigned int fpsNom = 0;
755 unsigned int fpsDen = 0;
756 unsigned int fSizeW = 0;
757 unsigned int fSizeH = 0;
759 while(process.state() != QProcess::NotRunning)
767 if(!process.waitForReadyRead())
769 if(process.state() == QProcess::Running)
772 qWarning("Avs2YUV process timed out <-- killing!");
773 log("\nPROCESS TIMEOUT !!!");
778 while(process.bytesAvailable() > 0)
780 QList<QByteArray> lines = process.readLine().split('\r');
781 while(!lines.isEmpty())
783 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
785 if((offset = regExpInt.lastIndexIn(text)) >= 0)
787 bool ok1 = false, ok2 = false;
788 bool ok3 = false, ok4 = false;
789 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
790 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
791 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
792 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
793 if(ok1) fSizeW = temp1;
794 if(ok2) fSizeH = temp2;
795 if(ok3) fpsNom = temp3;
796 if(ok4) frames = temp4;
798 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
800 bool ok1 = false, ok2 = false;
801 bool ok3 = false, ok4 = false, ok5 = false;
802 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
803 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
804 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
805 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
806 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
807 if(ok1) fSizeW = temp1;
808 if(ok2) fSizeH = temp2;
809 if(ok3) fpsNom = temp3;
810 if(ok4) fpsDen = temp4;
811 if(ok5) frames = temp5;
817 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
819 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
825 process.waitForFinished();
826 if(process.state() != QProcess::NotRunning)
829 process.waitForFinished(-1);
832 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
834 if(!(bTimeout || bAborted))
836 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
843 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
849 if((fSizeW > 0) && (fSizeH > 0))
851 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
853 if((fpsNom > 0) && (fpsDen > 0))
855 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
857 if((fpsNom > 0) && (fpsDen == 0))
859 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
863 log(tr("No. Frames: %1").arg(QString::number(frames)));
869 ///////////////////////////////////////////////////////////////////////////////
871 ///////////////////////////////////////////////////////////////////////////////
873 void EncodeThread::setStatus(JobStatus newStatus)
875 if(m_status != newStatus)
877 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
879 if(m_status != JobStatus_Paused) setProgress(0);
881 if(newStatus == JobStatus_Failed)
883 setDetails("The job has failed. See log for details!");
885 if(newStatus == JobStatus_Aborted)
887 setDetails("The job was aborted by the user!");
889 m_status = newStatus;
890 emit statusChanged(m_jobId, newStatus);
894 void EncodeThread::setProgress(unsigned int newProgress)
896 if(m_progress != newProgress)
898 m_progress = newProgress;
899 emit progressChanged(m_jobId, m_progress);
903 void EncodeThread::setDetails(const QString &text)
905 emit detailsChanged(m_jobId, text);
908 QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
910 QTextCodec *localCodec = QTextCodec::codecForName("System");
912 //Do NOT convert to short, if path can be represented in local Codepage
913 if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
918 //Create dummy file, if required (only existing files can have a short path!)
920 if((!QFileInfo(longPath).exists()) && create)
922 tempFile.setFileName(longPath);
923 tempFile.open(QIODevice::WriteOnly);
927 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
931 wchar_t *buffer = new wchar_t[buffSize];
932 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
934 if(result > 0 && result < buffSize)
936 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
943 //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
944 if(tempFile.isOpen())
946 if(!keep) tempFile.remove();
950 if(shortPath.isEmpty())
952 log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
955 return (shortPath.isEmpty() ? longPath : shortPath);
958 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
960 QMutexLocker lock(&m_mutex_startProcess);
961 log(commandline2string(program, args) + "\n");
963 //Create a new job object, if not done yet
964 if(!m_handle_jobObject)
966 m_handle_jobObject = CreateJobObject(NULL, NULL);
967 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
969 m_handle_jobObject = NULL;
971 if(m_handle_jobObject)
973 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
974 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
975 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
976 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
982 process.setProcessChannelMode(QProcess::MergedChannels);
983 process.setReadChannel(QProcess::StandardOutput);
987 process.setProcessChannelMode(QProcess::SeparateChannels);
988 process.setReadChannel(QProcess::StandardError);
991 process.start(program, args);
993 if(process.waitForStarted())
995 Q_PID pid = process.pid();
996 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
999 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
1001 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
1009 log("Process creation has failed :-(");
1010 QString errorMsg= process.errorString().trimmed();
1011 if(!errorMsg.isEmpty()) log(errorMsg);
1014 process.waitForFinished(-1);
1018 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1020 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1022 for(int i = 0; i < arguments.count(); i++)
1024 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));