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"
38 #include <QCryptographicHash>
43 QMutex EncodeThread::m_mutex_startProcess;
48 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
52 log("\nPROCESS ABORTED BY USER !!!"); \
53 setStatus(JobStatus_Aborted); \
54 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
55 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
60 setStatus(JobStatus_Failed); \
61 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
62 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
68 #define APPEND_AND_CLEAR(LIST, STR) do \
70 if(!((STR).isEmpty())) \
78 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
80 if(ITER != LIST.end()) \
82 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
84 log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
85 ITER = LIST.erase(ITER); \
86 if(ITER != LIST.end()) \
88 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
96 #define AVS2_BINARY(BIN_DIR, IS_X64) (QString("%1/%2/avs2yuv_%2.exe").arg((BIN_DIR), ((IS_X64) ? "x64" : "x86")))
97 #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")))
98 #define VPSP_BINARY(VPS_DIR) (QString("%1/core/vspipe.exe").arg((VPS_DIR)))
103 static const unsigned int REV_MULT = 10000;
104 static const char *VPS_TEST_FILE = "import vapoursynth as vs\ncore = vs.get_core()\nv = core.std.BlankClip()\nv.set_output()\n";
106 ///////////////////////////////////////////////////////////////////////////////
107 // Constructor & Destructor
108 ///////////////////////////////////////////////////////////////////////////////
110 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)
112 m_jobId(QUuid::createUuid()),
113 m_sourceFileName(sourceFileName),
114 m_outputFileName(outputFileName),
115 m_options(new OptionsModel(*options)),
118 m_x264_x64(x264_x64),
119 m_x264_10bit(x264_10bit),
120 m_avs2yuv_x64(avs2yuv_x64),
121 m_skipVersionTest(skipVersionTest),
122 m_processPriority(processPriroity),
123 m_abortOnTimeout(abortOnTimeout),
124 m_handle_jobObject(NULL),
131 EncodeThread::~EncodeThread(void)
133 X264_DELETE(m_options);
135 if(m_handle_jobObject)
137 CloseHandle(m_handle_jobObject);
138 m_handle_jobObject = NULL;
142 ///////////////////////////////////////////////////////////////////////////////
143 // Thread entry point
144 ///////////////////////////////////////////////////////////////////////////////
146 void EncodeThread::run(void)
155 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
161 if(m_handle_jobObject)
163 TerminateJobObject(m_handle_jobObject, 42);
164 m_handle_jobObject = NULL;
168 void EncodeThread::checkedRun(void)
171 m_status = JobStatus_Starting;
181 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
182 setStatus(JobStatus_Failed);
186 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
187 setStatus(JobStatus_Failed);
192 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
196 void EncodeThread::start(Priority priority)
198 qDebug("Thread starting...");
203 while(m_semaphorePaused.tryAcquire(1, 0));
204 QThread::start(priority);
207 ///////////////////////////////////////////////////////////////////////////////
209 ///////////////////////////////////////////////////////////////////////////////
211 void EncodeThread::encode(void)
213 QDateTime startTime = QDateTime::currentDateTime();
215 //Print some basic info
216 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
217 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
218 log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
219 log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
221 if(!m_vpsDir.isEmpty())
223 log(tr("\nVapourSynth: %1").arg(m_vpsDir));
226 //Print encoder settings
227 log(tr("\n--- SETTINGS ---\n"));
228 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
229 log(tr("Preset: %1").arg(m_options->preset()));
230 log(tr("Tuning: %1").arg(m_options->tune()));
231 log(tr("Profile: %1").arg(m_options->profile()));
232 log(tr("Custom: %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
237 unsigned int frames = 0;
239 //Seletct type of input
240 const int inputType = getInputType(QFileInfo(m_sourceFileName).suffix());
241 const QString indexFile = QString("%1/x264_%2.ffindex").arg(QDir::tempPath(), stringToHash(m_sourceFileName));
243 //Checking x264 version
244 log(tr("\n--- CHECK VERSION ---\n"));
245 unsigned int revision_x264 = UINT_MAX;
246 bool x264_modified = false;
247 ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
248 CHECK_STATUS(m_abort, ok);
250 //Checking avs2yuv version
251 unsigned int revision_avs2yuv = UINT_MAX;
255 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
256 CHECK_STATUS(m_abort, ok);
259 ok = checkVersionVapoursynth();
260 CHECK_STATUS(m_abort, ok);
265 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()));
266 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)));
268 //Is x264 revision supported?
269 if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
271 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
272 setStatus(JobStatus_Failed);
275 if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
277 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
278 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
280 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
282 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
283 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
284 setStatus(JobStatus_Failed);
289 if(inputType != INPUT_NATIVE)
291 log(tr("\n--- SOURCE INFO ---\n"));
295 ok = checkPropertiesAvisynth(m_avs2yuv_x64, frames);
296 CHECK_STATUS(m_abort, ok);
299 ok = checkPropertiesVapoursynth(frames);
300 CHECK_STATUS(m_abort, ok);
305 //Run encoding passes
306 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
308 QFileInfo info(m_outputFileName);
309 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
311 if(QFileInfo(passLogFile).exists())
314 while(QFileInfo(passLogFile).exists())
316 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
320 log(tr("\n--- PASS 1 ---\n"));
321 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 1, passLogFile);
322 CHECK_STATUS(m_abort, ok);
324 log(tr("\n--- PASS 2 ---\n"));
325 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 2, passLogFile);
326 CHECK_STATUS(m_abort, ok);
330 log(tr("\n--- ENCODING ---\n"));
331 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile);
332 CHECK_STATUS(m_abort, ok);
335 log(tr("\n--- DONE ---\n"));
336 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
337 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)));
338 setStatus(JobStatus_Completed);
341 #define X264_UPDATE_PROGRESS(X) do \
344 unsigned int progress = (X).cap(1).toUInt(&ok); \
345 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running)); \
346 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX))) \
348 setProgress(progress); \
349 size_estimate = estimateSize(progress); \
350 last_progress = progress; \
352 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate))); \
353 last_indexing = UINT_MAX; \
357 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)
359 QProcess processEncode, processInput;
361 if(inputType != INPUT_NATIVE)
363 QStringList cmdLine_Input;
364 processInput.setStandardOutputProcess(&processEncode);
368 if(!m_options->customAvs2YUV().isEmpty())
370 cmdLine_Input.append(splitParams(m_options->customAvs2YUV()));
372 cmdLine_Input << pathToAnsi(QDir::toNativeSeparators(m_sourceFileName));
373 cmdLine_Input << "-";
374 log("Creating Avisynth process:");
375 if(!startProcess(processInput, AVS2_BINARY(m_binDir, avs2yuv_x64), cmdLine_Input, false))
381 cmdLine_Input << pathToAnsi(QDir::toNativeSeparators(m_sourceFileName));
382 cmdLine_Input << "-" << "-y4m";
383 log("Creating Vapoursynth process:");
384 if(!startProcess(processInput, VPSP_BINARY(m_vpsDir), cmdLine_Input, false))
390 throw "Bad input type encontered!";
394 QStringList cmdLine_Encode = buildCommandLine((inputType != INPUT_NATIVE), x264_10bit, frames, indexFile, pass, passLogFile);
396 log("Creating x264 process:");
397 if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
402 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
403 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
404 QRegExp regExpModified("\\[\\s*(\\d+)\\.(\\d+)%\\]\\s+(\\d+)/(\\d+)\\s(\\d+).(\\d+)\\s(\\d+).(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)");
405 QRegExp regExpFrameCnt("^(\\d+) frames:");
407 QTextCodec *localCodec = QTextCodec::codecForName("System");
409 bool bTimeout = false;
410 bool bAborted = false;
412 unsigned int last_progress = UINT_MAX;
413 unsigned int last_indexing = UINT_MAX;
414 qint64 size_estimate = 0I64;
416 //Main processing loop
417 while(processEncode.state() != QProcess::NotRunning)
419 unsigned int waitCounter = 0;
421 //Wait until new output is available
426 processEncode.kill();
431 if(m_pause && (processEncode.state() == QProcess::Running))
433 JobStatus previousStatus = m_status;
434 setStatus(JobStatus_Paused);
435 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
436 bool ok[2] = {false, false};
437 Q_PID pid[2] = {processEncode.pid(), processInput.pid()};
438 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
439 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
440 while(m_pause) m_semaphorePaused.tryAcquire(1, 5000);
441 while(m_semaphorePaused.tryAcquire(1, 0));
442 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
443 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
444 if(!m_abort) setStatus(previousStatus);
445 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
449 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
451 if(processEncode.state() == QProcess::Running)
453 if(++waitCounter > m_processTimeoutMaxCounter)
457 processEncode.kill();
458 qWarning("x264 process timed out <-- killing!");
459 log("\nPROCESS TIMEOUT !!!");
464 else if(waitCounter == m_processTimeoutWarning)
466 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
467 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
472 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
479 //Exit main processing loop now?
480 if(bAborted || bTimeout)
486 while(processEncode.bytesAvailable() > 0)
488 QList<QByteArray> lines = processEncode.readLine().split('\r');
489 while(!lines.isEmpty())
491 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
493 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
495 X264_UPDATE_PROGRESS(regExpProgress);
497 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
500 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
501 setStatus(JobStatus_Indexing);
502 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
504 setProgress(progress);
505 last_indexing = progress;
507 setDetails(text.mid(offset).trimmed());
508 last_progress = UINT_MAX;
510 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
512 last_progress = last_indexing = UINT_MAX;
513 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
514 setDetails(text.mid(offset).trimmed());
516 else if((offset = regExpModified.lastIndexIn(text)) >= 0)
518 X264_UPDATE_PROGRESS(regExpModified);
520 else if(!text.isEmpty())
522 last_progress = last_indexing = UINT_MAX;
529 processEncode.waitForFinished(5000);
530 if(processEncode.state() != QProcess::NotRunning)
532 qWarning("x264 process still running, going to kill it!");
533 processEncode.kill();
534 processEncode.waitForFinished(-1);
537 processInput.waitForFinished(5000);
538 if(processInput.state() != QProcess::NotRunning)
540 qWarning("Input process still running, going to kill it!");
542 processInput.waitForFinished(-1);
545 if(!(bTimeout || bAborted))
547 while(processInput.bytesAvailable() > 0)
552 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
555 log(tr("vpyp [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
561 if((inputType != INPUT_NATIVE) && (processInput.exitCode() != EXIT_SUCCESS))
563 if(!(bTimeout || bAborted))
565 log(tr("\nWARNING: Input process exited with error code: %1").arg(QString::number(processInput.exitCode())));
569 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
571 if(!(bTimeout || bAborted))
573 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
575 processEncode.close();
576 processInput.close();
580 QThread::yieldCurrentThread();
582 const qint64 finalSize = QFileInfo(m_outputFileName).size();
583 QLocale locale(QLocale::English);
584 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
589 setStatus(JobStatus_Running_Pass1);
590 setDetails(tr("First pass completed. Preparing for second pass..."));
593 setStatus(JobStatus_Running_Pass2);
594 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
597 setStatus(JobStatus_Running);
598 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
603 processEncode.close();
604 processInput.close();
608 QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
611 double crf_int = 0.0, crf_frc = 0.0;
613 switch(m_options->rcMode())
615 case OptionsModel::RCMode_CQ:
616 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
618 case OptionsModel::RCMode_CRF:
619 crf_frc = modf(m_options->quantizer(), &crf_int);
620 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
622 case OptionsModel::RCMode_2Pass:
623 case OptionsModel::RCMode_ABR:
624 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
627 throw "Bad rate-control mode !!!";
631 if((pass == 1) || (pass == 2))
633 cmdLine << "--pass" << QString::number(pass);
634 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
637 cmdLine << "--preset" << m_options->preset().toLower();
639 if(m_options->tune().compare("none", Qt::CaseInsensitive))
641 cmdLine << "--tune" << m_options->tune().toLower();
644 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
648 if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
650 log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
654 cmdLine << "--profile" << m_options->profile().toLower();
659 cmdLine << "--profile" << m_options->profile().toLower();
663 if(!m_options->customX264().isEmpty())
665 QStringList customArgs = splitParams(m_options->customX264());
668 QStringList::iterator i = customArgs.begin();
669 while(i != customArgs.end())
671 bool bModified = false;
672 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
673 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
677 cmdLine.append(customArgs);
680 cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
684 if(frames < 1) throw "Frames not set!";
685 cmdLine << "--frames" << QString::number(frames);
686 cmdLine << "--demuxer" << "y4m";
687 cmdLine << "--stdin" << "y4m" << "-";
691 cmdLine << "--index" << QDir::toNativeSeparators(indexFile);
692 cmdLine << QDir::toNativeSeparators(m_sourceFileName);
698 unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
700 if(m_skipVersionTest)
702 log("Warning: Skipping x264 version check this time!");
703 return (999 * REV_MULT) + (9999 % REV_MULT);
707 QStringList cmdLine = QStringList() << "--version";
709 log("Creating process:");
710 if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
715 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
716 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
718 bool bTimeout = false;
719 bool bAborted = false;
721 unsigned int revision = UINT_MAX;
722 unsigned int coreVers = UINT_MAX;
725 while(process.state() != QProcess::NotRunning)
733 if(!process.waitForReadyRead())
735 if(process.state() == QProcess::Running)
738 qWarning("x264 process timed out <-- killing!");
739 log("\nPROCESS TIMEOUT !!!");
744 while(process.bytesAvailable() > 0)
746 QList<QByteArray> lines = process.readLine().split('\r');
747 while(!lines.isEmpty())
749 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
751 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
753 bool ok1 = false, ok2 = false;
754 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
755 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
756 if(ok1) coreVers = temp1;
757 if(ok2) revision = temp2;
759 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
761 bool ok1 = false, ok2 = false;
762 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
763 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
764 if(ok1) coreVers = temp1;
765 if(ok2) revision = temp2;
776 process.waitForFinished();
777 if(process.state() != QProcess::NotRunning)
780 process.waitForFinished(-1);
783 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
785 if(!(bTimeout || bAborted))
787 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
792 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
794 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
798 return (coreVers * REV_MULT) + (revision % REV_MULT);
801 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
805 log("\nCreating process:");
806 if(!startProcess(process, AVS2_BINARY(m_binDir, x64), QStringList()))
811 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
812 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
814 bool bTimeout = false;
815 bool bAborted = false;
817 unsigned int ver_maj = UINT_MAX;
818 unsigned int ver_min = UINT_MAX;
819 unsigned int ver_mod = 0;
821 while(process.state() != QProcess::NotRunning)
829 if(!process.waitForReadyRead())
831 if(process.state() == QProcess::Running)
834 qWarning("Avs2YUV process timed out <-- killing!");
835 log("\nPROCESS TIMEOUT !!!");
840 while(process.bytesAvailable() > 0)
842 QList<QByteArray> lines = process.readLine().split('\r');
843 while(!lines.isEmpty())
845 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
847 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
854 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
856 bool ok1 = false, ok2 = false, ok3 = false;
857 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
858 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
859 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
860 if(ok1) ver_maj = temp1;
861 if(ok2) ver_min = temp2;
862 if(ok3) ver_mod = temp3;
864 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
866 bool ok1 = false, ok2 = false;
867 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
868 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
869 if(ok1) ver_maj = temp1;
870 if(ok2) ver_min = temp2;
876 process.waitForFinished();
877 if(process.state() != QProcess::NotRunning)
880 process.waitForFinished(-1);
883 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
885 if(!(bTimeout || bAborted))
887 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
892 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
894 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
898 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
901 bool EncodeThread::checkVersionVapoursynth(/*const QString &vspipePath*/)
903 //Is VapourSynth available at all?
904 if(m_vpsDir.isEmpty() || (!QFileInfo(VPSP_BINARY(m_vpsDir)).isFile()))
906 log(tr("\nVPY INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
912 log("\nCreating process:");
913 if(!startProcess(process, VPSP_BINARY(m_vpsDir), QStringList()))
918 QRegExp regExpSignature("\\bVSPipe\\s+usage\\b", Qt::CaseInsensitive);
920 bool bTimeout = false;
921 bool bAborted = false;
923 bool vspipeSignature = false;
925 while(process.state() != QProcess::NotRunning)
933 if(!process.waitForReadyRead())
935 if(process.state() == QProcess::Running)
938 qWarning("VSPipe process timed out <-- killing!");
939 log("\nPROCESS TIMEOUT !!!");
944 while(process.bytesAvailable() > 0)
946 QList<QByteArray> lines = process.readLine().split('\r');
947 while(!lines.isEmpty())
949 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
950 if(regExpSignature.lastIndexIn(text) >= 0)
952 vspipeSignature = true;
962 process.waitForFinished();
963 if(process.state() != QProcess::NotRunning)
966 process.waitForFinished(-1);
969 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 1)))
971 if(!(bTimeout || bAborted))
973 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
980 log(tr("\nFAILED TO DETECT VSPIPE SIGNATURE !!!"));
984 return vspipeSignature;
987 bool EncodeThread::checkPropertiesAvisynth(bool x64, unsigned int &frames)
992 if(!m_options->customAvs2YUV().isEmpty())
994 cmdLine.append(splitParams(m_options->customAvs2YUV()));
997 cmdLine << "-frames" << "1";
998 cmdLine << pathToAnsi(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
1000 log("Creating process:");
1001 if(!startProcess(process, AVS2_BINARY(m_binDir, x64), cmdLine))
1006 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
1007 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
1009 QTextCodec *localCodec = QTextCodec::codecForName("System");
1011 bool bTimeout = false;
1012 bool bAborted = false;
1016 unsigned int fpsNom = 0;
1017 unsigned int fpsDen = 0;
1018 unsigned int fSizeW = 0;
1019 unsigned int fSizeH = 0;
1021 unsigned int waitCounter = 0;
1023 while(process.state() != QProcess::NotRunning)
1031 if(!process.waitForReadyRead(m_processTimeoutInterval))
1033 if(process.state() == QProcess::Running)
1035 if(++waitCounter > m_processTimeoutMaxCounter)
1037 if(m_abortOnTimeout)
1040 qWarning("Avs2YUV process timed out <-- killing!");
1041 log("\nPROCESS TIMEOUT !!!");
1042 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1047 else if(waitCounter == m_processTimeoutWarning)
1049 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1050 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1058 while(process.bytesAvailable() > 0)
1060 QList<QByteArray> lines = process.readLine().split('\r');
1061 while(!lines.isEmpty())
1063 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1065 if((offset = regExpInt.lastIndexIn(text)) >= 0)
1067 bool ok1 = false, ok2 = false;
1068 bool ok3 = false, ok4 = false;
1069 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
1070 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
1071 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
1072 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
1073 if(ok1) fSizeW = temp1;
1074 if(ok2) fSizeH = temp2;
1075 if(ok3) fpsNom = temp3;
1076 if(ok4) frames = temp4;
1078 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
1080 bool ok1 = false, ok2 = false;
1081 bool ok3 = false, ok4 = false, ok5 = false;
1082 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
1083 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
1084 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
1085 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
1086 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
1087 if(ok1) fSizeW = temp1;
1088 if(ok2) fSizeH = temp2;
1089 if(ok3) fpsNom = temp3;
1090 if(ok4) fpsDen = temp4;
1091 if(ok5) frames = temp5;
1097 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
1099 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
1101 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
1103 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
1109 process.waitForFinished();
1110 if(process.state() != QProcess::NotRunning)
1113 process.waitForFinished(-1);
1116 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1118 if(!(bTimeout || bAborted))
1120 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
1127 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
1133 if((fSizeW > 0) && (fSizeH > 0))
1135 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1137 if((fpsNom > 0) && (fpsDen > 0))
1139 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
1141 if((fpsNom > 0) && (fpsDen == 0))
1143 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
1147 log(tr("No. Frames: %1").arg(QString::number(frames)));
1153 bool EncodeThread::checkPropertiesVapoursynth(/*const QString &vspipePath,*/ unsigned int &frames)
1156 QStringList cmdLine;
1158 cmdLine << pathToAnsi(QDir::toNativeSeparators(m_sourceFileName));
1159 cmdLine << "-" << "-info";
1161 log("Creating process:");
1162 if(!startProcess(process, VPSP_BINARY(m_vpsDir), cmdLine))
1167 QRegExp regExpFrm("\\bFrames:\\s+(\\d+)\\b");
1168 QRegExp regExpSzW("\\bWidth:\\s+(\\d+)\\b");
1169 QRegExp regExpSzH("\\bHeight:\\s+(\\d+)\\b");
1171 QTextCodec *localCodec = QTextCodec::codecForName("System");
1173 bool bTimeout = false;
1174 bool bAborted = false;
1178 unsigned int fSizeW = 0;
1179 unsigned int fSizeH = 0;
1181 unsigned int waitCounter = 0;
1183 while(process.state() != QProcess::NotRunning)
1191 if(!process.waitForReadyRead(m_processTimeoutInterval))
1193 if(process.state() == QProcess::Running)
1195 if(++waitCounter > m_processTimeoutMaxCounter)
1197 if(m_abortOnTimeout)
1200 qWarning("VSPipe process timed out <-- killing!");
1201 log("\nPROCESS TIMEOUT !!!");
1202 log("\nVapoursynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1207 else if(waitCounter == m_processTimeoutWarning)
1209 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1210 log(tr("Warning: nVapoursynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1218 while(process.bytesAvailable() > 0)
1220 QList<QByteArray> lines = process.readLine().split('\r');
1221 while(!lines.isEmpty())
1223 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1225 if((offset = regExpFrm.lastIndexIn(text)) >= 0)
1228 unsigned int temp = regExpFrm.cap(1).toUInt(&ok);
1229 if(ok) frames = temp;
1231 if((offset = regExpSzW.lastIndexIn(text)) >= 0)
1234 unsigned int temp = regExpSzW.cap(1).toUInt(&ok);
1235 if(ok) fSizeW = temp;
1237 if((offset = regExpSzH.lastIndexIn(text)) >= 0)
1240 unsigned int temp = regExpSzH.cap(1).toUInt(&ok);
1241 if(ok) fSizeH = temp;
1251 process.waitForFinished();
1252 if(process.state() != QProcess::NotRunning)
1255 process.waitForFinished(-1);
1258 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1260 if(!(bTimeout || bAborted))
1262 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
1269 log(tr("\nFAILED TO DETERMINE VPY PROPERTIES !!!"));
1275 if((fSizeW > 0) && (fSizeH > 0))
1277 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1281 log(tr("No. Frames: %1").arg(QString::number(frames)));
1287 ///////////////////////////////////////////////////////////////////////////////
1289 ///////////////////////////////////////////////////////////////////////////////
1291 void EncodeThread::setStatus(JobStatus newStatus)
1293 if(m_status != newStatus)
1295 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
1297 if(m_status != JobStatus_Paused) setProgress(0);
1299 if(newStatus == JobStatus_Failed)
1301 setDetails("The job has failed. See log for details!");
1303 if(newStatus == JobStatus_Aborted)
1305 setDetails("The job was aborted by the user!");
1307 m_status = newStatus;
1308 emit statusChanged(m_jobId, newStatus);
1312 void EncodeThread::setProgress(unsigned int newProgress)
1314 if(m_progress != newProgress)
1316 m_progress = newProgress;
1317 emit progressChanged(m_jobId, m_progress);
1321 void EncodeThread::setDetails(const QString &text)
1323 emit detailsChanged(m_jobId, text);
1326 QString EncodeThread::pathToAnsi(const QString &longPath)
1328 QString shortPath = longPath;
1330 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1334 wchar_t *buffer = new wchar_t[buffSize];
1335 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1337 if((result > 0) && (result < buffSize))
1339 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer), result);
1349 QString EncodeThread::stringToHash(const QString &string)
1351 QByteArray result(10, char(0));
1352 const QByteArray hash = QCryptographicHash::hash(string.toUtf8(), QCryptographicHash::Sha1);
1354 if((hash.size() == 20) && (result.size() == 10))
1356 unsigned char *out = reinterpret_cast<unsigned char*>(result.data());
1357 const unsigned char *in = reinterpret_cast<const unsigned char*>(hash.constData());
1358 for(int i = 0; i < 10; i++)
1360 out[i] = (in[i] ^ in[10+i]);
1364 return QString::fromLatin1(result.toHex().constData());
1367 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1369 QMutexLocker lock(&m_mutex_startProcess);
1370 log(commandline2string(program, args) + "\n");
1372 //Create a new job object, if not done yet
1373 if(!m_handle_jobObject)
1375 m_handle_jobObject = CreateJobObject(NULL, NULL);
1376 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
1378 m_handle_jobObject = NULL;
1380 if(m_handle_jobObject)
1382 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
1383 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1384 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
1385 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1389 process.setWorkingDirectory(QDir::tempPath());
1393 process.setProcessChannelMode(QProcess::MergedChannels);
1394 process.setReadChannel(QProcess::StandardOutput);
1398 process.setProcessChannelMode(QProcess::SeparateChannels);
1399 process.setReadChannel(QProcess::StandardError);
1402 process.start(program, args);
1404 if(process.waitForStarted())
1406 Q_PID pid = process.pid();
1409 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1410 setPorcessPriority(process.pid()->hProcess, m_processPriority);
1417 log("Process creation has failed :-(");
1418 QString errorMsg= process.errorString().trimmed();
1419 if(!errorMsg.isEmpty()) log(errorMsg);
1422 process.waitForFinished(-1);
1426 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1428 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1430 for(int i = 0; i < arguments.count(); i++)
1432 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1438 QStringList EncodeThread::splitParams(const QString ¶ms)
1441 bool ignoreWhitespaces = false;
1444 for(int i = 0; i < params.length(); i++)
1446 const QChar c = params.at(i);
1448 if(c == QChar::fromLatin1('"'))
1450 ignoreWhitespaces = (!ignoreWhitespaces);
1453 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1455 APPEND_AND_CLEAR(list, temp);
1462 APPEND_AND_CLEAR(list, temp);
1464 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1465 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1470 qint64 EncodeThread::estimateSize(int progress)
1474 qint64 currentSize = QFileInfo(m_outputFileName).size();
1475 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1476 return estimatedSize;
1482 QString EncodeThread::sizeToString(qint64 size)
1484 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1488 qint64 estimatedSize = size;
1489 qint64 remainderSize = 0I64;
1492 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1494 remainderSize = estimatedSize % 1024I64;
1495 estimatedSize = estimatedSize / 1024I64;
1499 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1500 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);
1506 int EncodeThread::getInputType(const QString &fileExt)
1508 int type = INPUT_NATIVE;
1509 if(fileExt.compare("avs", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1510 else if(fileExt.compare("avsi", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1511 else if(fileExt.compare("vpy", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
1512 else if(fileExt.compare("py", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
1516 void EncodeThread::setPorcessPriority(void *processId, int priroity)
1520 case PreferencesModel::X264_PRIORITY_ABOVENORMAL:
1521 if(!SetPriorityClass(processId, ABOVE_NORMAL_PRIORITY_CLASS))
1523 SetPriorityClass(processId, NORMAL_PRIORITY_CLASS);
1526 case PreferencesModel::X264_PRIORITY_NORMAL:
1527 SetPriorityClass(processId, NORMAL_PRIORITY_CLASS);
1529 case PreferencesModel::X264_PRIORITY_BELOWNORMAL:
1530 if(!SetPriorityClass(processId, BELOW_NORMAL_PRIORITY_CLASS))
1532 SetPriorityClass(processId, IDLE_PRIORITY_CLASS);
1535 case PreferencesModel::X264_PRIORITY_IDLE:
1536 SetPriorityClass(processId, IDLE_PRIORITY_CLASS);