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"
42 QMutex EncodeThread::m_mutex_startProcess;
47 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
51 log("\nPROCESS ABORTED BY USER !!!"); \
52 setStatus(JobStatus_Aborted); \
53 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
54 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
59 setStatus(JobStatus_Failed); \
60 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
61 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
67 #define APPEND_AND_CLEAR(LIST, STR) do \
69 if(!((STR).isEmpty())) \
77 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
79 if(ITER != LIST.end()) \
81 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
83 log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
84 ITER = LIST.erase(ITER); \
85 if(ITER != LIST.end()) \
87 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
95 #define AVS2_BINARY(BIN_DIR, IS_X64) (QString("%1/%2/avs2yuv_%2.exe").arg((BIN_DIR), ((IS_X64) ? "x64" : "x86")))
96 #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")))
97 #define VPSP_BINARY(VPS_DIR) (QString("%1/vspipe.exe").arg((VPS_DIR)))
102 static const unsigned int REV_MULT = 10000;
103 static const char *VPS_TEST_FILE = "import vapoursynth as vs\ncore = vs.get_core()\nv = core.std.BlankClip()\nv.set_output()\n";
105 ///////////////////////////////////////////////////////////////////////////////
106 // Constructor & Destructor
107 ///////////////////////////////////////////////////////////////////////////////
109 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)
111 m_jobId(QUuid::createUuid()),
112 m_sourceFileName(sourceFileName),
113 m_outputFileName(outputFileName),
114 m_options(new OptionsModel(*options)),
117 m_x264_x64(x264_x64),
118 m_x264_10bit(x264_10bit),
119 m_avs2yuv_x64(avs2yuv_x64),
120 m_skipVersionTest(skipVersionTest),
121 m_processPriority(processPriroity),
122 m_abortOnTimeout(abortOnTimeout),
123 m_handle_jobObject(NULL),
130 EncodeThread::~EncodeThread(void)
132 X264_DELETE(m_options);
134 if(m_handle_jobObject)
136 CloseHandle(m_handle_jobObject);
137 m_handle_jobObject = NULL;
141 ///////////////////////////////////////////////////////////////////////////////
142 // Thread entry point
143 ///////////////////////////////////////////////////////////////////////////////
145 void EncodeThread::run(void)
154 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
160 if(m_handle_jobObject)
162 TerminateJobObject(m_handle_jobObject, 42);
163 m_handle_jobObject = NULL;
167 void EncodeThread::checkedRun(void)
170 m_status = JobStatus_Starting;
180 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
181 setStatus(JobStatus_Failed);
185 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
186 setStatus(JobStatus_Failed);
191 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
195 void EncodeThread::start(Priority priority)
197 qDebug("Thread starting...");
202 while(m_semaphorePaused.tryAcquire(1, 0));
203 QThread::start(priority);
206 ///////////////////////////////////////////////////////////////////////////////
208 ///////////////////////////////////////////////////////////////////////////////
210 void EncodeThread::encode(void)
212 QDateTime startTime = QDateTime::currentDateTime();
214 //Print some basic info
215 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
216 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
217 log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
218 log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
220 //Print encoder settings
221 log(tr("\n--- SETTINGS ---\n"));
222 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
223 log(tr("Preset: %1").arg(m_options->preset()));
224 log(tr("Tuning: %1").arg(m_options->tune()));
225 log(tr("Profile: %1").arg(m_options->profile()));
226 log(tr("Custom: %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
231 unsigned int frames = 0;
233 //Seletct type of input
234 const int inputType = getInputType(QFileInfo(m_sourceFileName).suffix());
235 const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
237 //Checking x264 version
238 log(tr("\n--- CHECK VERSION ---\n"));
239 unsigned int revision_x264 = UINT_MAX;
240 bool x264_modified = false;
241 ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
242 CHECK_STATUS(m_abort, ok);
244 //Checking avs2yuv version
245 unsigned int revision_avs2yuv = UINT_MAX;
249 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
250 CHECK_STATUS(m_abort, ok);
253 ok = checkVersionVapoursynth();
254 CHECK_STATUS(m_abort, ok);
259 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()));
260 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)));
262 //Is x264 revision supported?
263 if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
265 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
266 setStatus(JobStatus_Failed);
269 if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
271 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
272 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
274 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
276 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
277 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
278 setStatus(JobStatus_Failed);
283 if(inputType != INPUT_NATIVE)
285 log(tr("\n--- SOURCE INFO ---\n"));
289 ok = checkPropertiesAvisynth(m_avs2yuv_x64, frames);
290 CHECK_STATUS(m_abort, ok);
293 ok = checkPropertiesVapoursynth(frames);
294 CHECK_STATUS(m_abort, ok);
299 //Run encoding passes
300 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
302 QFileInfo info(m_outputFileName);
303 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
305 if(QFileInfo(passLogFile).exists())
308 while(QFileInfo(passLogFile).exists())
310 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
314 log(tr("\n--- PASS 1 ---\n"));
315 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 1, passLogFile);
316 CHECK_STATUS(m_abort, ok);
318 log(tr("\n--- PASS 2 ---\n"));
319 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 2, passLogFile);
320 CHECK_STATUS(m_abort, ok);
324 log(tr("\n--- ENCODING ---\n"));
325 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile);
326 CHECK_STATUS(m_abort, ok);
329 log(tr("\n--- DONE ---\n"));
330 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
331 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
332 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)));
333 setStatus(JobStatus_Completed);
336 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)
338 QProcess processEncode, processInput;
340 if(inputType != INPUT_NATIVE)
342 QStringList cmdLine_Input;
343 processInput.setStandardOutputProcess(&processEncode);
347 if(!m_options->customAvs2YUV().isEmpty())
349 cmdLine_Input.append(splitParams(m_options->customAvs2YUV()));
351 cmdLine_Input << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
352 cmdLine_Input << "-";
353 log("Creating Avisynth process:");
354 if(!startProcess(processInput, AVS2_BINARY(m_binDir, avs2yuv_x64), cmdLine_Input, false))
360 cmdLine_Input << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
361 cmdLine_Input << "-" << "-y4m";
362 log("Creating Vapoursynth process:");
363 if(!startProcess(processInput, VPSP_BINARY(m_vpsDir), cmdLine_Input, false))
369 throw "Bad input type encontered!";
373 QStringList cmdLine_Encode = buildCommandLine((inputType != INPUT_NATIVE), x264_10bit, frames, indexFile, pass, passLogFile);
375 log("Creating x264 process:");
376 if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
381 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
382 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
383 QRegExp regExpFrameCnt("^(\\d+) frames:");
385 QTextCodec *localCodec = QTextCodec::codecForName("System");
387 bool bTimeout = false;
388 bool bAborted = false;
390 unsigned int last_progress = UINT_MAX;
391 unsigned int last_indexing = UINT_MAX;
392 qint64 size_estimate = 0I64;
394 //Main processing loop
395 while(processEncode.state() != QProcess::NotRunning)
397 unsigned int waitCounter = 0;
399 //Wait until new output is available
404 processEncode.kill();
409 if(m_pause && (processEncode.state() == QProcess::Running))
411 JobStatus previousStatus = m_status;
412 setStatus(JobStatus_Paused);
413 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
414 bool ok[2] = {false, false};
415 Q_PID pid[2] = {processEncode.pid(), processInput.pid()};
416 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
417 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
418 while(m_pause) m_semaphorePaused.tryAcquire(1, 5000);
419 while(m_semaphorePaused.tryAcquire(1, 0));
420 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
421 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
422 if(!m_abort) setStatus(previousStatus);
423 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
427 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
429 if(processEncode.state() == QProcess::Running)
431 if(++waitCounter > m_processTimeoutMaxCounter)
435 processEncode.kill();
436 qWarning("x264 process timed out <-- killing!");
437 log("\nPROCESS TIMEOUT !!!");
442 else if(waitCounter == m_processTimeoutWarning)
444 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
445 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
450 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
457 //Exit main processing loop now?
458 if(bAborted || bTimeout)
464 while(processEncode.bytesAvailable() > 0)
466 QList<QByteArray> lines = processEncode.readLine().split('\r');
467 while(!lines.isEmpty())
469 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
471 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
474 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
475 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
476 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX)))
478 setProgress(progress);
479 size_estimate = estimateSize(progress);
480 last_progress = progress;
482 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate)));
483 last_indexing = UINT_MAX;
485 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
488 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
489 setStatus(JobStatus_Indexing);
490 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
492 setProgress(progress);
493 last_indexing = progress;
495 setDetails(text.mid(offset).trimmed());
496 last_progress = UINT_MAX;
498 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
500 last_progress = last_indexing = UINT_MAX;
501 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
502 setDetails(text.mid(offset).trimmed());
504 else if(!text.isEmpty())
506 last_progress = last_indexing = UINT_MAX;
513 processEncode.waitForFinished(5000);
514 if(processEncode.state() != QProcess::NotRunning)
516 qWarning("x264 process still running, going to kill it!");
517 processEncode.kill();
518 processEncode.waitForFinished(-1);
521 processInput.waitForFinished(5000);
522 if(processInput.state() != QProcess::NotRunning)
524 qWarning("Input process still running, going to kill it!");
526 processInput.waitForFinished(-1);
529 if(!(bTimeout || bAborted))
531 while(processInput.bytesAvailable() > 0)
536 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
539 log(tr("vpyp [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
545 if((inputType != INPUT_NATIVE) && (processInput.exitCode() != EXIT_SUCCESS))
547 if(!(bTimeout || bAborted))
549 log(tr("\nWARNING: Input process exited with error code: %1").arg(QString::number(processInput.exitCode())));
553 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
555 if(!(bTimeout || bAborted))
557 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
559 processEncode.close();
560 processInput.close();
564 QThread::yieldCurrentThread();
566 const qint64 finalSize = QFileInfo(m_outputFileName).size();
567 QLocale locale(QLocale::English);
568 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
573 setStatus(JobStatus_Running_Pass1);
574 setDetails(tr("First pass completed. Preparing for second pass..."));
577 setStatus(JobStatus_Running_Pass2);
578 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
581 setStatus(JobStatus_Running);
582 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
587 processEncode.close();
588 processInput.close();
592 QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
595 double crf_int = 0.0, crf_frc = 0.0;
597 switch(m_options->rcMode())
599 case OptionsModel::RCMode_CQ:
600 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
602 case OptionsModel::RCMode_CRF:
603 crf_frc = modf(m_options->quantizer(), &crf_int);
604 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
606 case OptionsModel::RCMode_2Pass:
607 case OptionsModel::RCMode_ABR:
608 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
611 throw "Bad rate-control mode !!!";
615 if((pass == 1) || (pass == 2))
617 cmdLine << "--pass" << QString::number(pass);
618 cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
621 cmdLine << "--preset" << m_options->preset().toLower();
623 if(m_options->tune().compare("none", Qt::CaseInsensitive))
625 cmdLine << "--tune" << m_options->tune().toLower();
628 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
632 if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
634 log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
638 cmdLine << "--profile" << m_options->profile().toLower();
643 cmdLine << "--profile" << m_options->profile().toLower();
647 if(!m_options->customX264().isEmpty())
649 QStringList customArgs = splitParams(m_options->customX264());
652 QStringList::iterator i = customArgs.begin();
653 while(i != customArgs.end())
655 bool bModified = false;
656 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
657 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
661 cmdLine.append(customArgs);
664 cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
668 if(frames < 1) throw "Frames not set!";
669 cmdLine << "--frames" << QString::number(frames);
670 cmdLine << "--demuxer" << "y4m";
671 cmdLine << "--stdin" << "y4m" << "-";
675 cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
676 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
682 unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
684 if(m_skipVersionTest)
686 log("Warning: Skipping x264 version check this time!");
687 return (999 * REV_MULT) + (9999 % REV_MULT);
691 QStringList cmdLine = QStringList() << "--version";
693 log("Creating process:");
694 if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
699 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
700 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
702 bool bTimeout = false;
703 bool bAborted = false;
705 unsigned int revision = UINT_MAX;
706 unsigned int coreVers = UINT_MAX;
709 while(process.state() != QProcess::NotRunning)
717 if(!process.waitForReadyRead())
719 if(process.state() == QProcess::Running)
722 qWarning("x264 process timed out <-- killing!");
723 log("\nPROCESS TIMEOUT !!!");
728 while(process.bytesAvailable() > 0)
730 QList<QByteArray> lines = process.readLine().split('\r');
731 while(!lines.isEmpty())
733 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
735 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
737 bool ok1 = false, ok2 = false;
738 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
739 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
740 if(ok1) coreVers = temp1;
741 if(ok2) revision = temp2;
743 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
745 bool ok1 = false, ok2 = false;
746 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
747 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
748 if(ok1) coreVers = temp1;
749 if(ok2) revision = temp2;
760 process.waitForFinished();
761 if(process.state() != QProcess::NotRunning)
764 process.waitForFinished(-1);
767 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
769 if(!(bTimeout || bAborted))
771 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
776 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
778 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
782 return (coreVers * REV_MULT) + (revision % REV_MULT);
785 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
789 log("\nCreating process:");
790 if(!startProcess(process, AVS2_BINARY(m_binDir, x64), QStringList()))
795 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
796 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
798 bool bTimeout = false;
799 bool bAborted = false;
801 unsigned int ver_maj = UINT_MAX;
802 unsigned int ver_min = UINT_MAX;
803 unsigned int ver_mod = 0;
805 while(process.state() != QProcess::NotRunning)
813 if(!process.waitForReadyRead())
815 if(process.state() == QProcess::Running)
818 qWarning("Avs2YUV process timed out <-- killing!");
819 log("\nPROCESS TIMEOUT !!!");
824 while(process.bytesAvailable() > 0)
826 QList<QByteArray> lines = process.readLine().split('\r');
827 while(!lines.isEmpty())
829 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
831 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
838 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
840 bool ok1 = false, ok2 = false, ok3 = false;
841 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
842 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
843 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
844 if(ok1) ver_maj = temp1;
845 if(ok2) ver_min = temp2;
846 if(ok3) ver_mod = temp3;
848 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
850 bool ok1 = false, ok2 = false;
851 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
852 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
853 if(ok1) ver_maj = temp1;
854 if(ok2) ver_min = temp2;
860 process.waitForFinished();
861 if(process.state() != QProcess::NotRunning)
864 process.waitForFinished(-1);
867 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
869 if(!(bTimeout || bAborted))
871 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
876 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
878 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
882 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
885 bool EncodeThread::checkVersionVapoursynth(/*const QString &vspipePath*/)
887 //Is VapourSynth available at all?
888 if(m_vpsDir.isEmpty() || (!QFileInfo(VPSP_BINARY(m_vpsDir)).isFile()))
890 log(tr("\nVPY INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
896 log("\nCreating process:");
897 if(!startProcess(process, VPSP_BINARY(m_vpsDir), QStringList()))
902 QRegExp regExpSignature("\\bVSPipe\\s+usage\\b", Qt::CaseInsensitive);
904 bool bTimeout = false;
905 bool bAborted = false;
907 bool vspipeSignature = false;
909 while(process.state() != QProcess::NotRunning)
917 if(!process.waitForReadyRead())
919 if(process.state() == QProcess::Running)
922 qWarning("VSPipe process timed out <-- killing!");
923 log("\nPROCESS TIMEOUT !!!");
928 while(process.bytesAvailable() > 0)
930 QList<QByteArray> lines = process.readLine().split('\r');
931 while(!lines.isEmpty())
933 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
934 if(regExpSignature.lastIndexIn(text) >= 0)
936 vspipeSignature = true;
946 process.waitForFinished();
947 if(process.state() != QProcess::NotRunning)
950 process.waitForFinished(-1);
953 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 1)))
955 if(!(bTimeout || bAborted))
957 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
964 log(tr("\nFAILED TO DETECT VSPIPE SIGNATURE !!!"));
968 return vspipeSignature;
971 bool EncodeThread::checkPropertiesAvisynth(bool x64, unsigned int &frames)
976 if(!m_options->customAvs2YUV().isEmpty())
978 cmdLine.append(splitParams(m_options->customAvs2YUV()));
981 cmdLine << "-frames" << "1";
982 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
984 log("Creating process:");
985 if(!startProcess(process, AVS2_BINARY(m_binDir, x64), cmdLine))
990 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
991 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
993 QTextCodec *localCodec = QTextCodec::codecForName("System");
995 bool bTimeout = false;
996 bool bAborted = false;
1000 unsigned int fpsNom = 0;
1001 unsigned int fpsDen = 0;
1002 unsigned int fSizeW = 0;
1003 unsigned int fSizeH = 0;
1005 unsigned int waitCounter = 0;
1007 while(process.state() != QProcess::NotRunning)
1015 if(!process.waitForReadyRead(m_processTimeoutInterval))
1017 if(process.state() == QProcess::Running)
1019 if(++waitCounter > m_processTimeoutMaxCounter)
1021 if(m_abortOnTimeout)
1024 qWarning("Avs2YUV process timed out <-- killing!");
1025 log("\nPROCESS TIMEOUT !!!");
1026 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1031 else if(waitCounter == m_processTimeoutWarning)
1033 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1034 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1042 while(process.bytesAvailable() > 0)
1044 QList<QByteArray> lines = process.readLine().split('\r');
1045 while(!lines.isEmpty())
1047 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1049 if((offset = regExpInt.lastIndexIn(text)) >= 0)
1051 bool ok1 = false, ok2 = false;
1052 bool ok3 = false, ok4 = false;
1053 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
1054 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
1055 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
1056 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
1057 if(ok1) fSizeW = temp1;
1058 if(ok2) fSizeH = temp2;
1059 if(ok3) fpsNom = temp3;
1060 if(ok4) frames = temp4;
1062 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
1064 bool ok1 = false, ok2 = false;
1065 bool ok3 = false, ok4 = false, ok5 = false;
1066 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
1067 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
1068 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
1069 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
1070 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
1071 if(ok1) fSizeW = temp1;
1072 if(ok2) fSizeH = temp2;
1073 if(ok3) fpsNom = temp3;
1074 if(ok4) fpsDen = temp4;
1075 if(ok5) frames = temp5;
1081 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
1083 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
1085 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
1087 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
1093 process.waitForFinished();
1094 if(process.state() != QProcess::NotRunning)
1097 process.waitForFinished(-1);
1100 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1102 if(!(bTimeout || bAborted))
1104 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
1111 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
1117 if((fSizeW > 0) && (fSizeH > 0))
1119 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1121 if((fpsNom > 0) && (fpsDen > 0))
1123 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
1125 if((fpsNom > 0) && (fpsDen == 0))
1127 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
1131 log(tr("No. Frames: %1").arg(QString::number(frames)));
1137 bool EncodeThread::checkPropertiesVapoursynth(/*const QString &vspipePath,*/ unsigned int &frames)
1140 QStringList cmdLine;
1142 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
1143 cmdLine << "-" << "-info";
1145 log("Creating process:");
1146 if(!startProcess(process, VPSP_BINARY(m_vpsDir), cmdLine))
1151 QRegExp regExpFrm("\\bFrames:\\s+(\\d+)\\b");
1152 QRegExp regExpSzW("\\bWidth:\\s+(\\d+)\\b");
1153 QRegExp regExpSzH("\\bHeight:\\s+(\\d+)\\b");
1155 QTextCodec *localCodec = QTextCodec::codecForName("System");
1157 bool bTimeout = false;
1158 bool bAborted = false;
1162 unsigned int fSizeW = 0;
1163 unsigned int fSizeH = 0;
1165 unsigned int waitCounter = 0;
1167 while(process.state() != QProcess::NotRunning)
1175 if(!process.waitForReadyRead(m_processTimeoutInterval))
1177 if(process.state() == QProcess::Running)
1179 if(++waitCounter > m_processTimeoutMaxCounter)
1181 if(m_abortOnTimeout)
1184 qWarning("VSPipe process timed out <-- killing!");
1185 log("\nPROCESS TIMEOUT !!!");
1186 log("\nVapoursynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1191 else if(waitCounter == m_processTimeoutWarning)
1193 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1194 log(tr("Warning: nVapoursynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1202 while(process.bytesAvailable() > 0)
1204 QList<QByteArray> lines = process.readLine().split('\r');
1205 while(!lines.isEmpty())
1207 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1209 if((offset = regExpFrm.lastIndexIn(text)) >= 0)
1212 unsigned int temp = regExpFrm.cap(1).toUInt(&ok);
1213 if(ok) frames = temp;
1215 if((offset = regExpSzW.lastIndexIn(text)) >= 0)
1218 unsigned int temp = regExpSzW.cap(1).toUInt(&ok);
1219 if(ok) fSizeW = temp;
1221 if((offset = regExpSzH.lastIndexIn(text)) >= 0)
1224 unsigned int temp = regExpSzH.cap(1).toUInt(&ok);
1225 if(ok) fSizeH = temp;
1235 process.waitForFinished();
1236 if(process.state() != QProcess::NotRunning)
1239 process.waitForFinished(-1);
1242 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1244 if(!(bTimeout || bAborted))
1246 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
1253 log(tr("\nFAILED TO DETERMINE VPY PROPERTIES !!!"));
1259 if((fSizeW > 0) && (fSizeH > 0))
1261 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1265 log(tr("No. Frames: %1").arg(QString::number(frames)));
1271 ///////////////////////////////////////////////////////////////////////////////
1273 ///////////////////////////////////////////////////////////////////////////////
1275 void EncodeThread::setStatus(JobStatus newStatus)
1277 if(m_status != newStatus)
1279 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
1281 if(m_status != JobStatus_Paused) setProgress(0);
1283 if(newStatus == JobStatus_Failed)
1285 setDetails("The job has failed. See log for details!");
1287 if(newStatus == JobStatus_Aborted)
1289 setDetails("The job was aborted by the user!");
1291 m_status = newStatus;
1292 emit statusChanged(m_jobId, newStatus);
1296 void EncodeThread::setProgress(unsigned int newProgress)
1298 if(m_progress != newProgress)
1300 m_progress = newProgress;
1301 emit progressChanged(m_jobId, m_progress);
1305 void EncodeThread::setDetails(const QString &text)
1307 emit detailsChanged(m_jobId, text);
1310 QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
1312 QTextCodec *localCodec = QTextCodec::codecForName("System");
1314 //Do NOT convert to short, if path can be represented in local Codepage
1315 if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
1320 //Create dummy file, if required (only existing files can have a short path!)
1322 if((!QFileInfo(longPath).exists()) && create)
1324 tempFile.setFileName(longPath);
1325 tempFile.open(QIODevice::WriteOnly);
1329 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1333 wchar_t *buffer = new wchar_t[buffSize];
1334 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1336 if(result > 0 && result < buffSize)
1338 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1345 //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
1346 if(tempFile.isOpen())
1348 if(!keep) tempFile.remove();
1352 if(shortPath.isEmpty())
1354 log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
1357 return (shortPath.isEmpty() ? longPath : shortPath);
1360 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1362 QMutexLocker lock(&m_mutex_startProcess);
1363 log(commandline2string(program, args) + "\n");
1365 //Create a new job object, if not done yet
1366 if(!m_handle_jobObject)
1368 m_handle_jobObject = CreateJobObject(NULL, NULL);
1369 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
1371 m_handle_jobObject = NULL;
1373 if(m_handle_jobObject)
1375 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
1376 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1377 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
1378 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1384 process.setProcessChannelMode(QProcess::MergedChannels);
1385 process.setReadChannel(QProcess::StandardOutput);
1389 process.setProcessChannelMode(QProcess::SeparateChannels);
1390 process.setReadChannel(QProcess::StandardError);
1393 process.start(program, args);
1395 if(process.waitForStarted())
1397 Q_PID pid = process.pid();
1400 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1401 setPorcessPriority(process.pid()->hProcess, m_processPriority);
1408 log("Process creation has failed :-(");
1409 QString errorMsg= process.errorString().trimmed();
1410 if(!errorMsg.isEmpty()) log(errorMsg);
1413 process.waitForFinished(-1);
1417 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1419 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1421 for(int i = 0; i < arguments.count(); i++)
1423 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1429 QStringList EncodeThread::splitParams(const QString ¶ms)
1432 bool ignoreWhitespaces = false;
1435 for(int i = 0; i < params.length(); i++)
1437 const QChar c = params.at(i);
1439 if(c == QChar::fromLatin1('"'))
1441 ignoreWhitespaces = (!ignoreWhitespaces);
1444 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1446 APPEND_AND_CLEAR(list, temp);
1453 APPEND_AND_CLEAR(list, temp);
1455 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1456 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1461 qint64 EncodeThread::estimateSize(int progress)
1465 qint64 currentSize = QFileInfo(m_outputFileName).size();
1466 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1467 return estimatedSize;
1473 QString EncodeThread::sizeToString(qint64 size)
1475 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1479 qint64 estimatedSize = size;
1480 qint64 remainderSize = 0I64;
1483 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1485 remainderSize = estimatedSize % 1024I64;
1486 estimatedSize = estimatedSize / 1024I64;
1490 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1491 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);
1497 int EncodeThread::getInputType(const QString &fileExt)
1499 int type = INPUT_NATIVE;
1500 if(fileExt.compare("avs", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1501 else if(fileExt.compare("avsi", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1502 else if(fileExt.compare("vpy", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
1503 else if(fileExt.compare("py", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
1507 void EncodeThread::setPorcessPriority(void *processId, int priroity)
1511 case PreferencesModel::X264_PRIORITY_ABOVENORMAL:
1512 if(!SetPriorityClass(processId, ABOVE_NORMAL_PRIORITY_CLASS))
1514 SetPriorityClass(processId, NORMAL_PRIORITY_CLASS);
1517 case PreferencesModel::X264_PRIORITY_NORMAL:
1518 SetPriorityClass(processId, NORMAL_PRIORITY_CLASS);
1520 case PreferencesModel::X264_PRIORITY_BELOWNORMAL:
1521 if(!SetPriorityClass(processId, BELOW_NORMAL_PRIORITY_CLASS))
1523 SetPriorityClass(processId, IDLE_PRIORITY_CLASS);
1526 case PreferencesModel::X264_PRIORITY_IDLE:
1527 SetPriorityClass(processId, IDLE_PRIORITY_CLASS);