1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2013 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"
26 #include "model_preferences.h"
27 #include "job_object.h"
38 #include <QCryptographicHash>
43 QMutex EncodeThread::m_mutex_startProcess;
46 * RAII execution state handler
48 class ExecutionStateHandler
51 ExecutionStateHandler(void)
53 x264_set_thread_execution_state(true);
55 ~ExecutionStateHandler(void)
57 x264_set_thread_execution_state(false);
60 //Disable copy constructor and assignment
61 ExecutionStateHandler(const ExecutionStateHandler &other) {}
62 ExecutionStateHandler &operator=(const ExecutionStateHandler &) {}
64 //Prevent object allocation on the heap
65 void *operator new(size_t); void *operator new[](size_t);
66 void operator delete(void *); void operator delete[](void*);
72 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
76 log("\nPROCESS ABORTED BY USER !!!"); \
77 setStatus(JobStatus_Aborted); \
78 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
79 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
84 setStatus(JobStatus_Failed); \
85 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
86 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
92 #define APPEND_AND_CLEAR(LIST, STR) do \
94 if(!((STR).isEmpty())) \
102 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
104 if(ITER != LIST.end()) \
106 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
108 log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
109 ITER = LIST.erase(ITER); \
110 if(ITER != LIST.end()) \
112 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
120 #define AVS2_BINARY(BIN_DIR, IS_X64) (QString("%1/%2/avs2yuv_%2.exe").arg((BIN_DIR), ((IS_X64) ? "x64" : "x86")))
121 #define X264_BINARY(BIN_DIR, IS_10BIT, IS_X64) (QString("%1/%2/x264_%3_%2.exe").arg((BIN_DIR), ((IS_X64) ? "x64" : "x86"), ((IS_10BIT) ? "10bit" : "8bit")))
122 #define VPSP_BINARY(VPS_DIR) (QString("%1/core/vspipe.exe").arg((VPS_DIR)))
127 static const unsigned int REV_MULT = 10000;
128 static const char *VPS_TEST_FILE = "import vapoursynth as vs\ncore = vs.get_core()\nv = core.std.BlankClip()\nv.set_output()\n";
130 ///////////////////////////////////////////////////////////////////////////////
131 // Constructor & Destructor
132 ///////////////////////////////////////////////////////////////////////////////
134 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, const QString &vpsDir, const bool &x264_x64, const bool &x264_10bit, const bool &avs2yuv_x64, const bool &skipVersionTest, const int &processPriroity, const bool &abortOnTimeout)
136 m_jobId(QUuid::createUuid()),
137 m_sourceFileName(sourceFileName),
138 m_outputFileName(outputFileName),
139 m_options(new OptionsModel(*options)),
142 m_x264_x64(x264_x64),
143 m_x264_10bit(x264_10bit),
144 m_avs2yuv_x64(avs2yuv_x64),
145 m_skipVersionTest(skipVersionTest),
146 m_processPriority(qBound(-2, processPriroity, 1)),
147 m_abortOnTimeout(abortOnTimeout),
148 m_jobObject(new JobObject),
155 EncodeThread::~EncodeThread(void)
157 X264_DELETE(m_options);
158 X264_DELETE(m_jobObject);
161 ///////////////////////////////////////////////////////////////////////////////
162 // Thread entry point
163 ///////////////////////////////////////////////////////////////////////////////
165 void EncodeThread::run(void)
174 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
182 m_jobObject->terminateJob(42);
183 X264_DELETE(m_jobObject);
187 void EncodeThread::checkedRun(void)
190 m_status = JobStatus_Starting;
196 ExecutionStateHandler executionStateHandler;
201 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
202 setStatus(JobStatus_Failed);
206 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
207 setStatus(JobStatus_Failed);
212 x264_fatal_exit(L"Unhandeled exception error in encode thread!");
216 void EncodeThread::start(Priority priority)
218 qDebug("Thread starting...");
223 while(m_semaphorePaused.tryAcquire(1, 0));
224 QThread::start(priority);
227 ///////////////////////////////////////////////////////////////////////////////
229 ///////////////////////////////////////////////////////////////////////////////
231 void EncodeThread::encode(void)
233 QDateTime startTime = QDateTime::currentDateTime();
235 //Print some basic info
236 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
237 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
238 log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
239 log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
241 if(!m_vpsDir.isEmpty())
243 log(tr("\nVapourSynth: %1").arg(m_vpsDir));
246 //Print encoder settings
247 log(tr("\n--- SETTINGS ---\n"));
248 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
249 log(tr("Preset: %1").arg(m_options->preset()));
250 log(tr("Tuning: %1").arg(m_options->tune()));
251 log(tr("Profile: %1").arg(m_options->profile()));
252 log(tr("Custom: %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
257 unsigned int frames = 0;
259 //Seletct type of input
260 const int inputType = getInputType(QFileInfo(m_sourceFileName).suffix());
261 const QString indexFile = QString("%1/x264_%2.ffindex").arg(QDir::tempPath(), stringToHash(m_sourceFileName));
263 //Checking x264 version
264 log(tr("\n--- CHECK VERSION ---\n"));
265 unsigned int revision_x264 = UINT_MAX;
266 bool x264_modified = false;
267 ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
268 CHECK_STATUS(m_abort, ok);
270 //Checking avs2yuv version
271 unsigned int revision_avs2yuv = UINT_MAX;
275 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
276 CHECK_STATUS(m_abort, ok);
279 ok = checkVersionVapoursynth();
280 CHECK_STATUS(m_abort, ok);
285 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()));
286 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)));
288 //Is x264 revision supported?
289 if((revision_x264 % REV_MULT) < x264_version_x264_minimum_rev())
291 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(x264_version_x264_minimum_rev())));
292 setStatus(JobStatus_Failed);
295 if((revision_x264 / REV_MULT) != x264_version_x264_current_api())
297 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
298 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(x264_version_x264_current_api())));
300 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != x264_version_x264_avs2yuv_ver()))
302 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
303 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
304 setStatus(JobStatus_Failed);
309 if(inputType != INPUT_NATIVE)
311 log(tr("\n--- SOURCE INFO ---\n"));
315 ok = checkPropertiesAvisynth(m_avs2yuv_x64, frames);
316 CHECK_STATUS(m_abort, ok);
319 ok = checkPropertiesVapoursynth(frames);
320 CHECK_STATUS(m_abort, ok);
325 //Run encoding passes
326 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
328 QFileInfo info(m_outputFileName);
329 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
331 if(QFileInfo(passLogFile).exists())
334 while(QFileInfo(passLogFile).exists())
336 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
340 log(tr("\n--- PASS 1 ---\n"));
341 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 1, passLogFile);
342 CHECK_STATUS(m_abort, ok);
344 log(tr("\n--- PASS 2 ---\n"));
345 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 2, passLogFile);
346 CHECK_STATUS(m_abort, ok);
350 log(tr("\n--- ENCODING ---\n"));
351 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile);
352 CHECK_STATUS(m_abort, ok);
355 log(tr("\n--- DONE ---\n"));
356 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
357 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)));
358 setStatus(JobStatus_Completed);
361 #define X264_UPDATE_PROGRESS(X) do \
364 unsigned int progress = (X).cap(1).toUInt(&ok); \
365 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running)); \
366 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX))) \
368 setProgress(progress); \
369 size_estimate = estimateSize(progress); \
370 last_progress = progress; \
372 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate))); \
373 last_indexing = UINT_MAX; \
377 bool EncodeThread::runEncodingPass(bool x264_x64, bool x264_10bit, bool avs2yuv_x64, int inputType, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
379 QProcess processEncode, processInput;
381 if(inputType != INPUT_NATIVE)
383 QStringList cmdLine_Input;
384 processInput.setStandardOutputProcess(&processEncode);
388 if(!m_options->customAvs2YUV().isEmpty())
390 cmdLine_Input.append(splitParams(m_options->customAvs2YUV()));
392 cmdLine_Input << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
393 cmdLine_Input << "-";
394 log("Creating Avisynth process:");
395 if(!startProcess(processInput, AVS2_BINARY(m_binDir, avs2yuv_x64), cmdLine_Input, false))
401 cmdLine_Input << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
402 cmdLine_Input << "-" << "-y4m";
403 log("Creating Vapoursynth process:");
404 if(!startProcess(processInput, VPSP_BINARY(m_vpsDir), cmdLine_Input, false))
410 throw "Bad input type encontered!";
414 QStringList cmdLine_Encode = buildCommandLine((inputType != INPUT_NATIVE), x264_10bit, frames, indexFile, pass, passLogFile);
416 log("Creating x264 process:");
417 if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
422 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
423 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
424 QRegExp regExpModified("\\[\\s*(\\d+)\\.(\\d+)%\\]\\s+(\\d+)/(\\d+)\\s(\\d+).(\\d+)\\s(\\d+).(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)");
425 QRegExp regExpFrameCnt("^(\\d+) frames:");
427 QTextCodec *localCodec = QTextCodec::codecForName("System");
429 bool bTimeout = false;
430 bool bAborted = false;
432 unsigned int last_progress = UINT_MAX;
433 unsigned int last_indexing = UINT_MAX;
434 qint64 size_estimate = 0I64;
436 //Main processing loop
437 while(processEncode.state() != QProcess::NotRunning)
439 unsigned int waitCounter = 0;
441 //Wait until new output is available
446 processEncode.kill();
451 if(m_pause && (processEncode.state() == QProcess::Running))
453 JobStatus previousStatus = m_status;
454 setStatus(JobStatus_Paused);
455 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
456 bool ok[2] = {false, false};
457 QProcess *proc[2] = { &processEncode, &processInput };
458 ok[0] = x264_suspendProcess(proc[0], true);
459 ok[1] = x264_suspendProcess(proc[1], true);
460 while(m_pause) m_semaphorePaused.tryAcquire(1, 5000);
461 while(m_semaphorePaused.tryAcquire(1, 0));
462 ok[0] = x264_suspendProcess(proc[0], false);
463 ok[1] = x264_suspendProcess(proc[1], false);
464 if(!m_abort) setStatus(previousStatus);
465 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
469 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
471 if(processEncode.state() == QProcess::Running)
473 if(++waitCounter > m_processTimeoutMaxCounter)
477 processEncode.kill();
478 qWarning("x264 process timed out <-- killing!");
479 log("\nPROCESS TIMEOUT !!!");
484 else if(waitCounter == m_processTimeoutWarning)
486 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
487 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
492 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
499 //Exit main processing loop now?
500 if(bAborted || bTimeout)
506 while(processEncode.bytesAvailable() > 0)
508 QList<QByteArray> lines = processEncode.readLine().split('\r');
509 while(!lines.isEmpty())
511 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
513 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
515 X264_UPDATE_PROGRESS(regExpProgress);
517 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
520 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
521 setStatus(JobStatus_Indexing);
522 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
524 setProgress(progress);
525 last_indexing = progress;
527 setDetails(text.mid(offset).trimmed());
528 last_progress = UINT_MAX;
530 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
532 last_progress = last_indexing = UINT_MAX;
533 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
534 setDetails(text.mid(offset).trimmed());
536 else if((offset = regExpModified.lastIndexIn(text)) >= 0)
538 X264_UPDATE_PROGRESS(regExpModified);
540 else if(!text.isEmpty())
542 last_progress = last_indexing = UINT_MAX;
549 processEncode.waitForFinished(5000);
550 if(processEncode.state() != QProcess::NotRunning)
552 qWarning("x264 process still running, going to kill it!");
553 processEncode.kill();
554 processEncode.waitForFinished(-1);
557 processInput.waitForFinished(5000);
558 if(processInput.state() != QProcess::NotRunning)
560 qWarning("Input process still running, going to kill it!");
562 processInput.waitForFinished(-1);
565 if(!(bTimeout || bAborted))
567 while(processInput.bytesAvailable() > 0)
572 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
575 log(tr("vpyp [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
581 if((inputType != INPUT_NATIVE) && (processInput.exitCode() != EXIT_SUCCESS))
583 if(!(bTimeout || bAborted))
585 const int exitCode = processInput.exitCode();
586 log(tr("\nWARNING: Input process exited with error (code: %1), your encode might be *incomplete* !!!").arg(QString::number(exitCode)));
587 if((inputType == INPUT_AVISYN) && ((exitCode < 0) || (exitCode > 2)))
589 log(tr("\nIMPORTANT: The Avs2YUV process terminated abnormally. This means Avisynth or one of your Avisynth-Plugin's just crashed."));
590 log(tr("IMPORTANT: Please fix your Avisynth script and try again! If you use Avisynth-MT, try using a *stable* Avisynth instead!"));
592 if((inputType == INPUT_VAPOUR) && ((exitCode < 0) || (exitCode > 1)))
594 log(tr("\nIMPORTANT: The Vapoursynth process terminated abnormally. This means Vapoursynth or one of your Vapoursynth-Plugin's just crashed."));
599 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
601 if(!(bTimeout || bAborted))
603 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
605 processEncode.close();
606 processInput.close();
610 QThread::yieldCurrentThread();
612 const qint64 finalSize = QFileInfo(m_outputFileName).size();
613 QLocale locale(QLocale::English);
614 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
619 setStatus(JobStatus_Running_Pass1);
620 setDetails(tr("First pass completed. Preparing for second pass..."));
623 setStatus(JobStatus_Running_Pass2);
624 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
627 setStatus(JobStatus_Running);
628 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
633 processEncode.close();
634 processInput.close();
638 QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
641 double crf_int = 0.0, crf_frc = 0.0;
643 switch(m_options->rcMode())
645 case OptionsModel::RCMode_CQ:
646 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
648 case OptionsModel::RCMode_CRF:
649 crf_frc = modf(m_options->quantizer(), &crf_int);
650 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
652 case OptionsModel::RCMode_2Pass:
653 case OptionsModel::RCMode_ABR:
654 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
657 throw "Bad rate-control mode !!!";
661 if((pass == 1) || (pass == 2))
663 cmdLine << "--pass" << QString::number(pass);
664 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
667 cmdLine << "--preset" << m_options->preset().toLower();
669 if(m_options->tune().compare("none", Qt::CaseInsensitive))
671 cmdLine << "--tune" << m_options->tune().toLower();
674 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
678 if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
680 log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
684 cmdLine << "--profile" << m_options->profile().toLower();
689 cmdLine << "--profile" << m_options->profile().toLower();
693 if(!m_options->customX264().isEmpty())
695 QStringList customArgs = splitParams(m_options->customX264());
698 QStringList::iterator i = customArgs.begin();
699 while(i != customArgs.end())
701 bool bModified = false;
702 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
703 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
707 cmdLine.append(customArgs);
710 cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
714 if(frames < 1) throw "Frames not set!";
715 cmdLine << "--frames" << QString::number(frames);
716 cmdLine << "--demuxer" << "y4m";
717 cmdLine << "--stdin" << "y4m" << "-";
721 cmdLine << "--index" << QDir::toNativeSeparators(indexFile);
722 cmdLine << QDir::toNativeSeparators(m_sourceFileName);
728 unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
730 if(m_skipVersionTest)
732 log("Warning: Skipping x264 version check this time!");
733 return (999 * REV_MULT) + (9999 % REV_MULT);
737 QStringList cmdLine = QStringList() << "--version";
739 log("Creating process:");
740 if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
745 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
746 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
748 bool bTimeout = false;
749 bool bAborted = false;
751 unsigned int revision = UINT_MAX;
752 unsigned int coreVers = UINT_MAX;
755 while(process.state() != QProcess::NotRunning)
763 if(!process.waitForReadyRead())
765 if(process.state() == QProcess::Running)
768 qWarning("x264 process timed out <-- killing!");
769 log("\nPROCESS TIMEOUT !!!");
774 while(process.bytesAvailable() > 0)
776 QList<QByteArray> lines = process.readLine().split('\r');
777 while(!lines.isEmpty())
779 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
781 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
783 bool ok1 = false, ok2 = false;
784 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
785 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
786 if(ok1) coreVers = temp1;
787 if(ok2) revision = temp2;
789 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
791 bool ok1 = false, ok2 = false;
792 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
793 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
794 if(ok1) coreVers = temp1;
795 if(ok2) revision = temp2;
806 process.waitForFinished();
807 if(process.state() != QProcess::NotRunning)
810 process.waitForFinished(-1);
813 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
815 if(!(bTimeout || bAborted))
817 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
822 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
824 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
828 return (coreVers * REV_MULT) + (revision % REV_MULT);
831 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
835 log("\nCreating process:");
836 if(!startProcess(process, AVS2_BINARY(m_binDir, x64), QStringList()))
841 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
842 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
844 bool bTimeout = false;
845 bool bAborted = false;
847 unsigned int ver_maj = UINT_MAX;
848 unsigned int ver_min = UINT_MAX;
849 unsigned int ver_mod = 0;
851 while(process.state() != QProcess::NotRunning)
859 if(!process.waitForReadyRead())
861 if(process.state() == QProcess::Running)
864 qWarning("Avs2YUV process timed out <-- killing!");
865 log("\nPROCESS TIMEOUT !!!");
870 while(process.bytesAvailable() > 0)
872 QList<QByteArray> lines = process.readLine().split('\r');
873 while(!lines.isEmpty())
875 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
877 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
884 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
886 bool ok1 = false, ok2 = false, ok3 = false;
887 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
888 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
889 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
890 if(ok1) ver_maj = temp1;
891 if(ok2) ver_min = temp2;
892 if(ok3) ver_mod = temp3;
894 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
896 bool ok1 = false, ok2 = false;
897 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
898 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
899 if(ok1) ver_maj = temp1;
900 if(ok2) ver_min = temp2;
906 process.waitForFinished();
907 if(process.state() != QProcess::NotRunning)
910 process.waitForFinished(-1);
913 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
915 if(!(bTimeout || bAborted))
917 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
922 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
924 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
928 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
931 bool EncodeThread::checkVersionVapoursynth(/*const QString &vspipePath*/)
933 //Is VapourSynth available at all?
934 if(m_vpsDir.isEmpty() || (!QFileInfo(VPSP_BINARY(m_vpsDir)).isFile()))
936 log(tr("\nVPY INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
942 log("\nCreating process:");
943 if(!startProcess(process, VPSP_BINARY(m_vpsDir), QStringList()))
948 QRegExp regExpSignature("\\bVSPipe\\s+usage\\b", Qt::CaseInsensitive);
950 bool bTimeout = false;
951 bool bAborted = false;
953 bool vspipeSignature = false;
955 while(process.state() != QProcess::NotRunning)
963 if(!process.waitForReadyRead())
965 if(process.state() == QProcess::Running)
968 qWarning("VSPipe process timed out <-- killing!");
969 log("\nPROCESS TIMEOUT !!!");
974 while(process.bytesAvailable() > 0)
976 QList<QByteArray> lines = process.readLine().split('\r');
977 while(!lines.isEmpty())
979 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
980 if(regExpSignature.lastIndexIn(text) >= 0)
982 vspipeSignature = true;
992 process.waitForFinished();
993 if(process.state() != QProcess::NotRunning)
996 process.waitForFinished(-1);
999 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 1)))
1001 if(!(bTimeout || bAborted))
1003 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
1008 if(!vspipeSignature)
1010 log(tr("\nFAILED TO DETECT VSPIPE SIGNATURE !!!"));
1014 return vspipeSignature;
1017 bool EncodeThread::checkPropertiesAvisynth(bool x64, unsigned int &frames)
1020 QStringList cmdLine;
1022 if(!m_options->customAvs2YUV().isEmpty())
1024 cmdLine.append(splitParams(m_options->customAvs2YUV()));
1027 cmdLine << "-frames" << "1";
1028 cmdLine << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true)) << "NUL";
1030 log("Creating process:");
1031 if(!startProcess(process, AVS2_BINARY(m_binDir, x64), cmdLine))
1036 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
1037 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
1039 QTextCodec *localCodec = QTextCodec::codecForName("System");
1041 bool bTimeout = false;
1042 bool bAborted = false;
1046 unsigned int fpsNom = 0;
1047 unsigned int fpsDen = 0;
1048 unsigned int fSizeW = 0;
1049 unsigned int fSizeH = 0;
1051 unsigned int waitCounter = 0;
1053 while(process.state() != QProcess::NotRunning)
1061 if(!process.waitForReadyRead(m_processTimeoutInterval))
1063 if(process.state() == QProcess::Running)
1065 if(++waitCounter > m_processTimeoutMaxCounter)
1067 if(m_abortOnTimeout)
1070 qWarning("Avs2YUV process timed out <-- killing!");
1071 log("\nPROCESS TIMEOUT !!!");
1072 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1077 else if(waitCounter == m_processTimeoutWarning)
1079 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1080 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1088 while(process.bytesAvailable() > 0)
1090 QList<QByteArray> lines = process.readLine().split('\r');
1091 while(!lines.isEmpty())
1093 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1095 if((offset = regExpInt.lastIndexIn(text)) >= 0)
1097 bool ok1 = false, ok2 = false;
1098 bool ok3 = false, ok4 = false;
1099 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
1100 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
1101 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
1102 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
1103 if(ok1) fSizeW = temp1;
1104 if(ok2) fSizeH = temp2;
1105 if(ok3) fpsNom = temp3;
1106 if(ok4) frames = temp4;
1108 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
1110 bool ok1 = false, ok2 = false;
1111 bool ok3 = false, ok4 = false, ok5 = false;
1112 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
1113 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
1114 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
1115 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
1116 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
1117 if(ok1) fSizeW = temp1;
1118 if(ok2) fSizeH = temp2;
1119 if(ok3) fpsNom = temp3;
1120 if(ok4) fpsDen = temp4;
1121 if(ok5) frames = temp5;
1127 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
1129 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
1131 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
1133 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
1139 process.waitForFinished();
1140 if(process.state() != QProcess::NotRunning)
1143 process.waitForFinished(-1);
1146 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1148 if(!(bTimeout || bAborted))
1150 const int exitCode = process.exitCode();
1151 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(exitCode)));
1152 if((exitCode < 0) || (exitCode > 2))
1154 log(tr("\nIMPORTANT: The Avs2YUV process terminated abnormally. This means Avisynth or one of your Avisynth-Plugin's just crashed."));
1155 log(tr("IMPORTANT: Please fix your Avisynth script and try again! If you use Avisynth-MT, try using a *stable* Avisynth instead!"));
1163 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
1169 if((fSizeW > 0) && (fSizeH > 0))
1171 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1173 if((fpsNom > 0) && (fpsDen > 0))
1175 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
1177 if((fpsNom > 0) && (fpsDen == 0))
1179 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
1183 log(tr("No. Frames: %1").arg(QString::number(frames)));
1189 bool EncodeThread::checkPropertiesVapoursynth(/*const QString &vspipePath,*/ unsigned int &frames)
1192 QStringList cmdLine;
1194 cmdLine << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
1195 cmdLine << "-" << "-info";
1197 log("Creating process:");
1198 if(!startProcess(process, VPSP_BINARY(m_vpsDir), cmdLine))
1203 QRegExp regExpFrm("\\bFrames:\\s+(\\d+)\\b");
1204 QRegExp regExpSzW("\\bWidth:\\s+(\\d+)\\b");
1205 QRegExp regExpSzH("\\bHeight:\\s+(\\d+)\\b");
1207 QTextCodec *localCodec = QTextCodec::codecForName("System");
1209 bool bTimeout = false;
1210 bool bAborted = false;
1214 unsigned int fSizeW = 0;
1215 unsigned int fSizeH = 0;
1217 unsigned int waitCounter = 0;
1219 while(process.state() != QProcess::NotRunning)
1227 if(!process.waitForReadyRead(m_processTimeoutInterval))
1229 if(process.state() == QProcess::Running)
1231 if(++waitCounter > m_processTimeoutMaxCounter)
1233 if(m_abortOnTimeout)
1236 qWarning("VSPipe process timed out <-- killing!");
1237 log("\nPROCESS TIMEOUT !!!");
1238 log("\nVapoursynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1243 else if(waitCounter == m_processTimeoutWarning)
1245 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1246 log(tr("Warning: nVapoursynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1254 while(process.bytesAvailable() > 0)
1256 QList<QByteArray> lines = process.readLine().split('\r');
1257 while(!lines.isEmpty())
1259 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1261 if((offset = regExpFrm.lastIndexIn(text)) >= 0)
1264 unsigned int temp = regExpFrm.cap(1).toUInt(&ok);
1265 if(ok) frames = temp;
1267 if((offset = regExpSzW.lastIndexIn(text)) >= 0)
1270 unsigned int temp = regExpSzW.cap(1).toUInt(&ok);
1271 if(ok) fSizeW = temp;
1273 if((offset = regExpSzH.lastIndexIn(text)) >= 0)
1276 unsigned int temp = regExpSzH.cap(1).toUInt(&ok);
1277 if(ok) fSizeH = temp;
1287 process.waitForFinished();
1288 if(process.state() != QProcess::NotRunning)
1291 process.waitForFinished(-1);
1294 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1296 if(!(bTimeout || bAborted))
1298 const int exitCode = process.exitCode();
1299 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(exitCode)));
1300 if((exitCode < 0) || (exitCode > 1))
1302 log(tr("\nIMPORTANT: The Vapoursynth process terminated abnormally. This means Vapoursynth or one of your Vapoursynth-Plugin's just crashed."));
1310 log(tr("\nFAILED TO DETERMINE VPY PROPERTIES !!!"));
1316 if((fSizeW > 0) && (fSizeH > 0))
1318 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1322 log(tr("No. Frames: %1").arg(QString::number(frames)));
1328 ///////////////////////////////////////////////////////////////////////////////
1330 ///////////////////////////////////////////////////////////////////////////////
1332 void EncodeThread::setStatus(JobStatus newStatus)
1334 if(m_status != newStatus)
1336 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
1338 if(m_status != JobStatus_Paused) setProgress(0);
1340 if(newStatus == JobStatus_Failed)
1342 setDetails("The job has failed. See log for details!");
1344 if(newStatus == JobStatus_Aborted)
1346 setDetails("The job was aborted by the user!");
1348 m_status = newStatus;
1349 emit statusChanged(m_jobId, newStatus);
1353 void EncodeThread::setProgress(unsigned int newProgress)
1355 if(m_progress != newProgress)
1357 m_progress = newProgress;
1358 emit progressChanged(m_jobId, m_progress);
1362 void EncodeThread::setDetails(const QString &text)
1364 emit detailsChanged(m_jobId, text);
1367 QString EncodeThread::stringToHash(const QString &string)
1369 QByteArray result(10, char(0));
1370 const QByteArray hash = QCryptographicHash::hash(string.toUtf8(), QCryptographicHash::Sha1);
1372 if((hash.size() == 20) && (result.size() == 10))
1374 unsigned char *out = reinterpret_cast<unsigned char*>(result.data());
1375 const unsigned char *in = reinterpret_cast<const unsigned char*>(hash.constData());
1376 for(int i = 0; i < 10; i++)
1378 out[i] = (in[i] ^ in[10+i]);
1382 return QString::fromLatin1(result.toHex().constData());
1385 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1387 QMutexLocker lock(&m_mutex_startProcess);
1388 log(commandline2string(program, args) + "\n");
1390 process.setWorkingDirectory(QDir::tempPath());
1394 process.setProcessChannelMode(QProcess::MergedChannels);
1395 process.setReadChannel(QProcess::StandardOutput);
1399 process.setProcessChannelMode(QProcess::SeparateChannels);
1400 process.setReadChannel(QProcess::StandardError);
1403 process.start(program, args);
1405 if(process.waitForStarted())
1407 m_jobObject->addProcessToJob(&process);
1408 x264_change_process_priority(&process, m_processPriority);
1413 log("Process creation has failed :-(");
1414 QString errorMsg= process.errorString().trimmed();
1415 if(!errorMsg.isEmpty()) log(errorMsg);
1418 process.waitForFinished(-1);
1422 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1424 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1426 for(int i = 0; i < arguments.count(); i++)
1428 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1434 QStringList EncodeThread::splitParams(const QString ¶ms)
1437 bool ignoreWhitespaces = false;
1440 for(int i = 0; i < params.length(); i++)
1442 const QChar c = params.at(i);
1444 if(c == QChar::fromLatin1('"'))
1446 ignoreWhitespaces = (!ignoreWhitespaces);
1449 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1451 APPEND_AND_CLEAR(list, temp);
1458 APPEND_AND_CLEAR(list, temp);
1460 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1461 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1466 qint64 EncodeThread::estimateSize(int progress)
1470 qint64 currentSize = QFileInfo(m_outputFileName).size();
1471 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1472 return estimatedSize;
1478 QString EncodeThread::sizeToString(qint64 size)
1480 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1484 qint64 estimatedSize = size;
1485 qint64 remainderSize = 0I64;
1488 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1490 remainderSize = estimatedSize % 1024I64;
1491 estimatedSize = estimatedSize / 1024I64;
1495 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1496 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);
1502 int EncodeThread::getInputType(const QString &fileExt)
1504 int type = INPUT_NATIVE;
1505 if(fileExt.compare("avs", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1506 else if(fileExt.compare("avsi", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1507 else if(fileExt.compare("vpy", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
1508 else if(fileExt.compare("py", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;