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); \
62 #define APPEND_AND_CLEAR(LIST, STR) \
64 if(!((STR).isEmpty())) \
74 static const unsigned int REV_MULT = 10000;
76 ///////////////////////////////////////////////////////////////////////////////
77 // Constructor & Destructor
78 ///////////////////////////////////////////////////////////////////////////////
80 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x264_x64, bool avs2yuv_x64)
82 m_jobId(QUuid::createUuid()),
83 m_sourceFileName(sourceFileName),
84 m_outputFileName(outputFileName),
85 m_options(new OptionsModel(*options)),
88 m_avs2yuv_x64(avs2yuv_x64),
89 m_handle_jobObject(NULL),
96 EncodeThread::~EncodeThread(void)
98 X264_DELETE(m_options);
100 if(m_handle_jobObject)
102 CloseHandle(m_handle_jobObject);
103 m_handle_jobObject = NULL;
107 ///////////////////////////////////////////////////////////////////////////////
108 // Thread entry point
109 ///////////////////////////////////////////////////////////////////////////////
111 void EncodeThread::run(void)
119 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
122 if(m_handle_jobObject)
124 TerminateJobObject(m_handle_jobObject, 42);
125 m_handle_jobObject = NULL;
129 void EncodeThread::checkedRun(void)
132 m_status = JobStatus_Starting;
142 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
143 setStatus(JobStatus_Failed);
147 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
148 setStatus(JobStatus_Failed);
153 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
157 void EncodeThread::start(Priority priority)
159 qDebug("Thread starting...");
164 while(m_semaphorePaused.tryAcquire(1, 0));
165 QThread::start(priority);
168 ///////////////////////////////////////////////////////////////////////////////
170 ///////////////////////////////////////////////////////////////////////////////
172 void EncodeThread::encode(void)
174 QDateTime startTime = QDateTime::currentDateTime();
176 //Print some basic info
177 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
178 log(tr("Source file: %1").arg(m_sourceFileName));
179 log(tr("Output file: %1").arg(m_outputFileName));
181 //Print encoder settings
182 log(tr("\n--- SETTINGS ---\n"));
183 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
184 log(tr("Preset: %1").arg(m_options->preset()));
185 log(tr("Tuning: %1").arg(m_options->tune()));
186 log(tr("Profile: %1").arg(m_options->profile()));
187 log(tr("Custom: %1").arg(m_options->custom().isEmpty() ? tr("(None)") : m_options->custom()));
190 unsigned int frames = 0;
193 const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
194 const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
196 //Checking x264 version
197 log(tr("\n--- CHECK VERSION ---\n"));
198 unsigned int revision_x264 = UINT_MAX;
199 bool x264_modified = false;
200 ok = ((revision_x264 = checkVersionX264(m_x264_x64, x264_modified)) != UINT_MAX);
201 CHECK_STATUS(m_abort, ok);
203 //Checking avs2yuv version
204 unsigned int revision_avs2yuv = UINT_MAX;
207 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
208 CHECK_STATUS(m_abort, ok);
212 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()));
213 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)));
215 //Is x264 revision supported?
216 if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
218 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
219 setStatus(JobStatus_Failed);
222 if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
224 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
225 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
227 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
229 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
230 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
231 setStatus(JobStatus_Failed);
238 log(tr("\n--- AVS INFO ---\n"));
239 ok = checkProperties(m_avs2yuv_x64, frames);
240 CHECK_STATUS(m_abort, ok);
243 //Run encoding passes
244 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
246 QFileInfo info(m_outputFileName);
247 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
249 if(QFileInfo(passLogFile).exists())
252 while(QFileInfo(passLogFile).exists())
254 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
258 log(tr("\n--- PASS 1 ---\n"));
259 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile, 1, passLogFile);
260 CHECK_STATUS(m_abort, ok);
262 log(tr("\n--- PASS 2 ---\n"));
263 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile, 2, passLogFile);
264 CHECK_STATUS(m_abort, ok);
268 log(tr("\n--- ENCODING ---\n"));
269 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile);
270 CHECK_STATUS(m_abort, ok);
273 log(tr("\n--- DONE ---\n"));
274 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
275 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
276 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)));
277 setStatus(JobStatus_Completed);
280 bool EncodeThread::runEncodingPass(bool x264_x64, bool avs2yuv_x64, bool usePipe, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
282 QProcess processEncode, processAvisynth;
286 QStringList cmdLine_Avisynth;
287 cmdLine_Avisynth << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
288 cmdLine_Avisynth << "-";
289 processAvisynth.setStandardOutputProcess(&processEncode);
291 log("Creating Avisynth process:");
292 if(!startProcess(processAvisynth, QString("%1/%2.exe").arg(m_binDir, avs2yuv_x64 ? "avs2yuv_x64" : "avs2yuv"), cmdLine_Avisynth, false))
298 QStringList cmdLine_Encode = buildCommandLine(usePipe, frames, indexFile, pass, passLogFile);
300 log("Creating x264 process:");
301 if(!startProcess(processEncode, QString("%1/%2.exe").arg(m_binDir, x264_x64 ? "x264_x64" : "x264"), cmdLine_Encode))
306 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
307 QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
308 QRegExp regExpFrameCnt("^(\\d+) frames:");
310 QTextCodec *localCodec = QTextCodec::codecForName("System");
312 bool bTimeout = false;
313 bool bAborted = false;
315 //Main processing loop
316 while(processEncode.state() != QProcess::NotRunning)
318 unsigned int waitCounter = 0;
320 //Wait until new output is available
325 processEncode.kill();
326 processAvisynth.kill();
330 if(m_pause && (processEncode.state() == QProcess::Running))
332 JobStatus previousStatus = m_status;
333 setStatus(JobStatus_Paused);
334 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
335 bool ok[2] = {false, false};
336 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
337 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
338 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
339 while(m_pause) m_semaphorePaused.acquire();
340 while(m_semaphorePaused.tryAcquire(1, 0));
341 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
342 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
343 if(!m_abort) setStatus(previousStatus);
344 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
348 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
350 if(processEncode.state() == QProcess::Running)
352 if(waitCounter++ > m_processTimeoutMaxCounter)
354 processEncode.kill();
355 qWarning("x264 process timed out <-- killing!");
356 log("\nPROCESS TIMEOUT !!!");
360 else if(waitCounter == m_processTimeoutWarning)
362 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
363 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
368 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
375 //Exit main processing loop now?
376 if(bAborted || bTimeout)
382 while(processEncode.bytesAvailable() > 0)
384 QList<QByteArray> lines = processEncode.readLine().split('\r');
385 while(!lines.isEmpty())
387 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
389 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
392 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
393 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
394 setDetails(text.mid(offset).trimmed());
395 if(ok) setProgress(progress);
397 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
400 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
401 setStatus(JobStatus_Indexing);
402 setDetails(text.mid(offset).trimmed());
403 if(ok) setProgress(progress);
405 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
407 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
408 setDetails(text.mid(offset).trimmed());
410 else if(!text.isEmpty())
418 processEncode.waitForFinished(5000);
419 if(processEncode.state() != QProcess::NotRunning)
421 qWarning("x264 process still running, going to kill it!");
422 processEncode.kill();
423 processEncode.waitForFinished(-1);
426 processAvisynth.waitForFinished(5000);
427 if(processAvisynth.state() != QProcess::NotRunning)
429 qWarning("Avisynth process still running, going to kill it!");
430 processAvisynth.kill();
431 processAvisynth.waitForFinished(-1);
434 if(!(bTimeout || bAborted))
436 while(processAvisynth.bytesAvailable() > 0)
438 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
442 if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
444 if(!(bTimeout || bAborted))
446 log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
450 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
452 if(!(bTimeout || bAborted))
454 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
456 processEncode.close();
457 processAvisynth.close();
464 setStatus(JobStatus_Running_Pass1);
465 setDetails(tr("First pass completed. Preparing for second pass..."));
468 setStatus(JobStatus_Running_Pass2);
469 setDetails(tr("Second pass completed successfully."));
472 setStatus(JobStatus_Running);
473 setDetails(tr("Encode completed successfully."));
478 processEncode.close();
479 processAvisynth.close();
483 QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
486 double crf_int = 0.0, crf_frc = 0.0;
488 switch(m_options->rcMode())
490 case OptionsModel::RCMode_CQ:
491 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
493 case OptionsModel::RCMode_CRF:
494 crf_frc = modf(m_options->quantizer(), &crf_int);
495 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
497 case OptionsModel::RCMode_2Pass:
498 case OptionsModel::RCMode_ABR:
499 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
502 throw "Bad rate-control mode !!!";
506 if((pass == 1) || (pass == 2))
508 cmdLine << "--pass" << QString::number(pass);
509 cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
512 cmdLine << "--preset" << m_options->preset().toLower();
514 if(m_options->tune().compare("none", Qt::CaseInsensitive))
516 cmdLine << "--tune" << m_options->tune().toLower();
519 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
521 cmdLine << "--profile" << m_options->profile().toLower();
524 if(!m_options->custom().isEmpty())
526 cmdLine.append(splitParams(m_options->custom()));
529 cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
533 if(frames < 1) throw "Frames not set!";
534 cmdLine << "--frames" << QString::number(frames);
535 cmdLine << "--demuxer" << "y4m";
536 cmdLine << "--stdin" << "y4m" << "-";
540 cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
541 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
547 unsigned int EncodeThread::checkVersionX264(bool x64, bool &modified)
550 QStringList cmdLine = QStringList() << "--version";
552 log("Creating process:");
553 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
558 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
559 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
561 bool bTimeout = false;
562 bool bAborted = false;
564 unsigned int revision = UINT_MAX;
565 unsigned int coreVers = UINT_MAX;
568 while(process.state() != QProcess::NotRunning)
576 if(!process.waitForReadyRead())
578 if(process.state() == QProcess::Running)
581 qWarning("x264 process timed out <-- killing!");
582 log("\nPROCESS TIMEOUT !!!");
587 while(process.bytesAvailable() > 0)
589 QList<QByteArray> lines = process.readLine().split('\r');
590 while(!lines.isEmpty())
592 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
594 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
596 bool ok1 = false, ok2 = false;
597 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
598 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
599 if(ok1) coreVers = temp1;
600 if(ok2) revision = temp2;
602 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
604 bool ok1 = false, ok2 = false;
605 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
606 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
607 if(ok1) coreVers = temp1;
608 if(ok2) revision = temp2;
619 process.waitForFinished();
620 if(process.state() != QProcess::NotRunning)
623 process.waitForFinished(-1);
626 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
628 if(!(bTimeout || bAborted))
630 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
635 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
637 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
641 return (coreVers * REV_MULT) + (revision % REV_MULT);
644 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
648 log("\nCreating process:");
649 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv"), QStringList()))
654 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
655 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
657 bool bTimeout = false;
658 bool bAborted = false;
660 unsigned int ver_maj = UINT_MAX;
661 unsigned int ver_min = UINT_MAX;
662 unsigned int ver_mod = 0;
664 while(process.state() != QProcess::NotRunning)
672 if(!process.waitForReadyRead())
674 if(process.state() == QProcess::Running)
677 qWarning("Avs2YUV process timed out <-- killing!");
678 log("\nPROCESS TIMEOUT !!!");
683 while(process.bytesAvailable() > 0)
685 QList<QByteArray> lines = process.readLine().split('\r');
686 while(!lines.isEmpty())
688 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
690 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
697 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
699 bool ok1 = false, ok2 = false, ok3 = false;
700 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
701 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
702 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
703 if(ok1) ver_maj = temp1;
704 if(ok2) ver_min = temp2;
705 if(ok3) ver_mod = temp3;
707 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
709 bool ok1 = false, ok2 = false;
710 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
711 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
712 if(ok1) ver_maj = temp1;
713 if(ok2) ver_min = temp2;
719 process.waitForFinished();
720 if(process.state() != QProcess::NotRunning)
723 process.waitForFinished(-1);
726 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
728 if(!(bTimeout || bAborted))
730 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
735 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
737 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
741 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
744 bool EncodeThread::checkProperties(bool x64, unsigned int &frames)
748 QStringList cmdLine = QStringList() << "-frames" << "1";
749 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
751 log("Creating process:");
752 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv"), cmdLine))
757 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
758 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
760 QTextCodec *localCodec = QTextCodec::codecForName("System");
762 bool bTimeout = false;
763 bool bAborted = false;
767 unsigned int fpsNom = 0;
768 unsigned int fpsDen = 0;
769 unsigned int fSizeW = 0;
770 unsigned int fSizeH = 0;
772 unsigned int waitCounter = 0;
774 while(process.state() != QProcess::NotRunning)
782 if(!process.waitForReadyRead(m_processTimeoutInterval))
784 if(process.state() == QProcess::Running)
786 if(waitCounter++ > m_processTimeoutMaxCounter)
789 qWarning("Avs2YUV process timed out <-- killing!");
790 log("\nPROCESS TIMEOUT !!!");
791 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
795 else if(waitCounter == m_processTimeoutWarning)
797 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
798 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
806 while(process.bytesAvailable() > 0)
808 QList<QByteArray> lines = process.readLine().split('\r');
809 while(!lines.isEmpty())
811 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
813 if((offset = regExpInt.lastIndexIn(text)) >= 0)
815 bool ok1 = false, ok2 = false;
816 bool ok3 = false, ok4 = false;
817 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
818 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
819 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
820 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
821 if(ok1) fSizeW = temp1;
822 if(ok2) fSizeH = temp2;
823 if(ok3) fpsNom = temp3;
824 if(ok4) frames = temp4;
826 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
828 bool ok1 = false, ok2 = false;
829 bool ok3 = false, ok4 = false, ok5 = false;
830 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
831 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
832 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
833 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
834 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
835 if(ok1) fSizeW = temp1;
836 if(ok2) fSizeH = temp2;
837 if(ok3) fpsNom = temp3;
838 if(ok4) fpsDen = temp4;
839 if(ok5) frames = temp5;
845 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
847 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
853 process.waitForFinished();
854 if(process.state() != QProcess::NotRunning)
857 process.waitForFinished(-1);
860 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
862 if(!(bTimeout || bAborted))
864 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
871 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
877 if((fSizeW > 0) && (fSizeH > 0))
879 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
881 if((fpsNom > 0) && (fpsDen > 0))
883 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
885 if((fpsNom > 0) && (fpsDen == 0))
887 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
891 log(tr("No. Frames: %1").arg(QString::number(frames)));
897 ///////////////////////////////////////////////////////////////////////////////
899 ///////////////////////////////////////////////////////////////////////////////
901 void EncodeThread::setStatus(JobStatus newStatus)
903 if(m_status != newStatus)
905 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
907 if(m_status != JobStatus_Paused) setProgress(0);
909 if(newStatus == JobStatus_Failed)
911 setDetails("The job has failed. See log for details!");
913 if(newStatus == JobStatus_Aborted)
915 setDetails("The job was aborted by the user!");
917 m_status = newStatus;
918 emit statusChanged(m_jobId, newStatus);
922 void EncodeThread::setProgress(unsigned int newProgress)
924 if(m_progress != newProgress)
926 m_progress = newProgress;
927 emit progressChanged(m_jobId, m_progress);
931 void EncodeThread::setDetails(const QString &text)
933 emit detailsChanged(m_jobId, text);
936 QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
938 QTextCodec *localCodec = QTextCodec::codecForName("System");
940 //Do NOT convert to short, if path can be represented in local Codepage
941 if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
946 //Create dummy file, if required (only existing files can have a short path!)
948 if((!QFileInfo(longPath).exists()) && create)
950 tempFile.setFileName(longPath);
951 tempFile.open(QIODevice::WriteOnly);
955 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
959 wchar_t *buffer = new wchar_t[buffSize];
960 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
962 if(result > 0 && result < buffSize)
964 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
971 //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
972 if(tempFile.isOpen())
974 if(!keep) tempFile.remove();
978 if(shortPath.isEmpty())
980 log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
983 return (shortPath.isEmpty() ? longPath : shortPath);
986 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
988 QMutexLocker lock(&m_mutex_startProcess);
989 log(commandline2string(program, args) + "\n");
991 //Create a new job object, if not done yet
992 if(!m_handle_jobObject)
994 m_handle_jobObject = CreateJobObject(NULL, NULL);
995 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
997 m_handle_jobObject = NULL;
999 if(m_handle_jobObject)
1001 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
1002 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1003 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
1004 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1010 process.setProcessChannelMode(QProcess::MergedChannels);
1011 process.setReadChannel(QProcess::StandardOutput);
1015 process.setProcessChannelMode(QProcess::SeparateChannels);
1016 process.setReadChannel(QProcess::StandardError);
1019 process.start(program, args);
1021 if(process.waitForStarted())
1023 Q_PID pid = process.pid();
1024 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1027 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
1029 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
1037 log("Process creation has failed :-(");
1038 QString errorMsg= process.errorString().trimmed();
1039 if(!errorMsg.isEmpty()) log(errorMsg);
1042 process.waitForFinished(-1);
1046 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1048 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1050 for(int i = 0; i < arguments.count(); i++)
1052 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1058 QStringList EncodeThread::splitParams(const QString ¶ms)
1061 bool ignoreWhitespaces = false;
1064 for(int i = 0; i < params.length(); i++)
1066 const QChar c = params.at(i);
1068 if(c == QChar::fromLatin1('"'))
1070 ignoreWhitespaces = (!ignoreWhitespaces);
1073 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1075 APPEND_AND_CLEAR(list, temp);
1082 APPEND_AND_CLEAR(list, temp);