1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2014 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 "model_sysinfo.h"
28 #include "job_object.h"
40 #include <QCryptographicHash>
45 QMutex EncodeThread::m_mutex_startProcess;
48 * RAII execution state handler
50 class ExecutionStateHandler
53 ExecutionStateHandler(void)
55 x264_set_thread_execution_state(true);
57 ~ExecutionStateHandler(void)
59 x264_set_thread_execution_state(false);
62 //Disable copy constructor and assignment
63 ExecutionStateHandler(const ExecutionStateHandler &other) {}
64 ExecutionStateHandler &operator=(const ExecutionStateHandler &) {}
66 //Prevent object allocation on the heap
67 void *operator new(size_t); void *operator new[](size_t);
68 void operator delete(void *); void operator delete[](void*);
74 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
78 log("\nPROCESS ABORTED BY USER !!!"); \
79 setStatus(JobStatus_Aborted); \
80 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
81 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
86 setStatus(JobStatus_Failed); \
87 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
88 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
94 #define APPEND_AND_CLEAR(LIST, STR) do \
96 if(!((STR).isEmpty())) \
104 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
106 if(ITER != LIST.end()) \
108 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
110 log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
111 ITER = LIST.erase(ITER); \
112 if(ITER != LIST.end()) \
114 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
125 static const char *VPS_TEST_FILE = "import vapoursynth as vs\ncore = vs.get_core()\nv = core.std.BlankClip()\nv.set_output()\n";
127 ///////////////////////////////////////////////////////////////////////////////
128 // Constructor & Destructor
129 ///////////////////////////////////////////////////////////////////////////////
131 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
133 m_jobId(QUuid::createUuid()),
134 m_sourceFileName(sourceFileName),
135 m_outputFileName(outputFileName),
136 m_options(new OptionsModel(*options)),
138 m_preferences(preferences),
139 m_jobObject(new JobObject),
146 EncodeThread::~EncodeThread(void)
148 X264_DELETE(m_options);
149 X264_DELETE(m_jobObject);
152 ///////////////////////////////////////////////////////////////////////////////
153 // Thread entry point
154 ///////////////////////////////////////////////////////////////////////////////
156 void EncodeThread::run(void)
165 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
173 m_jobObject->terminateJob(42);
174 X264_DELETE(m_jobObject);
178 void EncodeThread::checkedRun(void)
181 m_status = JobStatus_Starting;
187 ExecutionStateHandler executionStateHandler;
192 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
193 setStatus(JobStatus_Failed);
197 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
198 setStatus(JobStatus_Failed);
203 x264_fatal_exit(L"Unhandeled exception error in encode thread!");
207 void EncodeThread::start(Priority priority)
209 qDebug("Thread starting...");
214 while(m_semaphorePaused.tryAcquire(1, 0));
215 QThread::start(priority);
218 ///////////////////////////////////////////////////////////////////////////////
220 ///////////////////////////////////////////////////////////////////////////////
222 void EncodeThread::encode(void)
224 QDateTime startTime = QDateTime::currentDateTime();
226 //Print some basic info
227 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
228 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
229 log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
230 log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
233 log(tr("\n--- SYSTEMINFO ---\n"));
234 log(tr("Binary Path: %1").arg(QDir::toNativeSeparators(m_sysinfo->getAppPath())));
235 log(tr("Avisynth OK: %1").arg(m_sysinfo->hasAVSSupport() ? tr("Yes") : tr("No")));
236 log(tr("VapourSynth: %1").arg(m_sysinfo->hasVPSSupport() ? QDir::toNativeSeparators(m_sysinfo->getVPSPath()) : tr("N/A")));
238 //Print encoder settings
239 log(tr("\n--- SETTINGS ---\n"));
240 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
241 log(tr("Preset: %1").arg(m_options->preset()));
242 log(tr("Tuning: %1").arg(m_options->tune()));
243 log(tr("Profile: %1").arg(m_options->profile()));
244 log(tr("Custom: %1").arg(m_options->customEncParams().isEmpty() ? tr("(None)") : m_options->customEncParams()));
247 unsigned int frames = 0;
249 //Seletct type of input
250 const int inputType = getInputType(QFileInfo(m_sourceFileName).suffix());
251 const QString indexFile = QString("%1/x264_%2.ffindex").arg(QDir::tempPath(), stringToHash(m_sourceFileName));
253 //Checking x264 version
254 log(tr("\n--- CHECK VERSION ---\n"));
255 unsigned int encoderRevision = UINT_MAX;
256 bool encoderModified = false;
257 ok = ((encoderRevision = checkVersionEncoder(encoderModified)) != UINT_MAX);
258 CHECK_STATUS(m_abort, ok);
260 //Checking avs2yuv version
261 unsigned int revision_avs2yuv = UINT_MAX;
264 case INPUT_NATIVE: break;
265 case INPUT_AVISYN: ok = ((revision_avs2yuv = checkVersionAvs2yuv()) != UINT_MAX); break;
266 case INPUT_VAPOUR: ok = checkVersionVapoursynth(); break;
267 default: throw "Invalid input type!";
269 CHECK_STATUS(m_abort, ok);
272 switch(m_options->encType())
274 case OptionsModel::EncType_X264: log(tr("\nx264 revision: %1 (core #%2)").arg(QString::number(encoderRevision % REV_MULT), QString::number(encoderRevision / REV_MULT)).append(encoderModified ? tr(" - with custom patches!") : QString())); break;
275 case OptionsModel::EncType_X265: log(tr("\nx265 version: 0.%1+%2").arg(QString::number(encoderRevision / REV_MULT), QString::number(encoderRevision % REV_MULT))); break;
277 if(revision_avs2yuv != UINT_MAX)
279 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)));
282 //Is encoder version suppoprted?
283 if(m_options->encType() == OptionsModel::EncType_X264)
285 if((encoderRevision % REV_MULT) < x264_version_x264_minimum_rev())
287 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(x264_version_x264_minimum_rev())));
288 setStatus(JobStatus_Failed);
291 if((encoderRevision / REV_MULT) != x264_version_x264_current_api())
293 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
294 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(x264_version_x264_current_api())));
297 else if(m_options->encType() == OptionsModel::EncType_X264)
302 //Is Avs2YUV version supported?
303 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != x264_version_x264_avs2yuv_ver()))
305 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
306 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
307 setStatus(JobStatus_Failed);
312 if(inputType != INPUT_NATIVE)
314 log(tr("\n--- SOURCE INFO ---\n"));
318 ok = checkPropertiesAVS(frames);
319 CHECK_STATUS(m_abort, ok);
322 ok = checkPropertiesVPS(frames);
323 CHECK_STATUS(m_abort, ok);
328 //Run encoding passes
329 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
331 QFileInfo info(m_outputFileName);
332 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
334 if(QFileInfo(passLogFile).exists())
337 while(QFileInfo(passLogFile).exists())
339 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
343 log(tr("\n--- PASS 1 ---\n"));
344 ok = runEncodingPass(inputType, frames, indexFile, 1, passLogFile);
345 CHECK_STATUS(m_abort, ok);
347 log(tr("\n--- PASS 2 ---\n"));
348 ok = runEncodingPass(inputType, frames, indexFile, 2, passLogFile);
349 CHECK_STATUS(m_abort, ok);
353 log(tr("\n--- ENCODING ---\n"));
354 ok = runEncodingPass(inputType, frames, indexFile);
355 CHECK_STATUS(m_abort, ok);
358 log(tr("\n--- DONE ---\n"));
359 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
360 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)));
361 setStatus(JobStatus_Completed);
364 #define X264_UPDATE_PROGRESS(X) do \
367 unsigned int progress = (X).cap(1).toUInt(&ok); \
368 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running)); \
369 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX))) \
371 setProgress(progress); \
372 size_estimate = estimateSize(progress); \
373 last_progress = progress; \
375 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate))); \
376 last_indexing = UINT_MAX; \
380 bool EncodeThread::runEncodingPass(const int &inputType, const unsigned int &frames, const QString &indexFile, const int &pass, const QString &passLogFile)
382 QProcess processEncode, processInput;
384 if(inputType != INPUT_NATIVE)
386 QStringList cmdLine_Input;
387 processInput.setStandardOutputProcess(&processEncode);
391 if(!m_options->customAvs2YUV().isEmpty())
393 cmdLine_Input.append(splitParams(m_options->customAvs2YUV()));
395 cmdLine_Input << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
396 cmdLine_Input << "-";
397 log("Creating Avisynth process:");
398 if(!startProcess(processInput, AVS_BINARY(m_sysinfo, m_preferences), cmdLine_Input, false))
404 cmdLine_Input << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
405 cmdLine_Input << "-" << "-y4m";
406 log("Creating Vapoursynth process:");
407 if(!startProcess(processInput, VPS_BINARY(m_sysinfo, m_preferences), cmdLine_Input, false))
413 throw "Bad input type encontered!";
417 QStringList cmdLine_Encode = buildCommandLine((inputType != INPUT_NATIVE), frames, indexFile, pass, passLogFile);
419 log("Creating x264 process:");
420 if(!startProcess(processEncode, ENC_BINARY(m_sysinfo, m_options), cmdLine_Encode))
425 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
426 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
427 QRegExp regExpModified("\\[\\s*(\\d+)\\.(\\d+)%\\]\\s+(\\d+)/(\\d+)\\s(\\d+).(\\d+)\\s(\\d+).(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)");
428 QRegExp regExpFrameCnt("^(\\d+) frames:");
430 QTextCodec *localCodec = QTextCodec::codecForName("System");
432 bool bTimeout = false;
433 bool bAborted = false;
435 unsigned int last_progress = UINT_MAX;
436 unsigned int last_indexing = UINT_MAX;
437 qint64 size_estimate = 0I64;
439 //Main processing loop
440 while(processEncode.state() != QProcess::NotRunning)
442 unsigned int waitCounter = 0;
444 //Wait until new output is available
449 processEncode.kill();
454 if(m_pause && (processEncode.state() == QProcess::Running))
456 JobStatus previousStatus = m_status;
457 setStatus(JobStatus_Paused);
458 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
459 bool ok[2] = {false, false};
460 QProcess *proc[2] = { &processEncode, &processInput };
461 ok[0] = x264_suspendProcess(proc[0], true);
462 ok[1] = x264_suspendProcess(proc[1], true);
463 while(m_pause) m_semaphorePaused.tryAcquire(1, 5000);
464 while(m_semaphorePaused.tryAcquire(1, 0));
465 ok[0] = x264_suspendProcess(proc[0], false);
466 ok[1] = x264_suspendProcess(proc[1], false);
467 if(!m_abort) setStatus(previousStatus);
468 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
472 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
474 if(processEncode.state() == QProcess::Running)
476 if(++waitCounter > m_processTimeoutMaxCounter)
478 if(m_preferences->getAbortOnTimeout())
480 processEncode.kill();
481 qWarning("x264 process timed out <-- killing!");
482 log("\nPROCESS TIMEOUT !!!");
487 else if(waitCounter == m_processTimeoutWarning)
489 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
490 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
495 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
502 //Exit main processing loop now?
503 if(bAborted || bTimeout)
509 while(processEncode.bytesAvailable() > 0)
511 QList<QByteArray> lines = processEncode.readLine().split('\r');
512 while(!lines.isEmpty())
514 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
516 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
518 X264_UPDATE_PROGRESS(regExpProgress);
520 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
523 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
524 setStatus(JobStatus_Indexing);
525 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
527 setProgress(progress);
528 last_indexing = progress;
530 setDetails(text.mid(offset).trimmed());
531 last_progress = UINT_MAX;
533 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
535 last_progress = last_indexing = UINT_MAX;
536 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
537 setDetails(text.mid(offset).trimmed());
539 else if((offset = regExpModified.lastIndexIn(text)) >= 0)
541 X264_UPDATE_PROGRESS(regExpModified);
543 else if(!text.isEmpty())
545 last_progress = last_indexing = UINT_MAX;
552 processEncode.waitForFinished(5000);
553 if(processEncode.state() != QProcess::NotRunning)
555 qWarning("x264 process still running, going to kill it!");
556 processEncode.kill();
557 processEncode.waitForFinished(-1);
560 processInput.waitForFinished(5000);
561 if(processInput.state() != QProcess::NotRunning)
563 qWarning("Input process still running, going to kill it!");
565 processInput.waitForFinished(-1);
568 if(!(bTimeout || bAborted))
570 while(processInput.bytesAvailable() > 0)
575 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
578 log(tr("vpyp [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
584 if((inputType != INPUT_NATIVE) && (processInput.exitCode() != EXIT_SUCCESS))
586 if(!(bTimeout || bAborted))
588 const int exitCode = processInput.exitCode();
589 log(tr("\nWARNING: Input process exited with error (code: %1), your encode might be *incomplete* !!!").arg(QString::number(exitCode)));
590 if((inputType == INPUT_AVISYN) && ((exitCode < 0) || (exitCode >= 32)))
592 log(tr("\nIMPORTANT: The Avs2YUV process terminated abnormally. This means Avisynth or one of your Avisynth-Plugin's just crashed."));
593 log(tr("IMPORTANT: Please fix your Avisynth script and try again! If you use Avisynth-MT, try using a *stable* Avisynth instead!"));
595 if((inputType == INPUT_VAPOUR) && ((exitCode < 0) || (exitCode >= 32)))
597 log(tr("\nIMPORTANT: The Vapoursynth process terminated abnormally. This means Vapoursynth or one of your Vapoursynth-Plugin's just crashed."));
602 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
604 if(!(bTimeout || bAborted))
606 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
608 processEncode.close();
609 processInput.close();
613 QThread::yieldCurrentThread();
615 const qint64 finalSize = QFileInfo(m_outputFileName).size();
616 QLocale locale(QLocale::English);
617 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
622 setStatus(JobStatus_Running_Pass1);
623 setDetails(tr("First pass completed. Preparing for second pass..."));
626 setStatus(JobStatus_Running_Pass2);
627 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
630 setStatus(JobStatus_Running);
631 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
636 processEncode.close();
637 processInput.close();
641 QStringList EncodeThread::buildCommandLine(const bool &usePipe, const unsigned int &frames, const QString &indexFile, const int &pass, const QString &passLogFile)
644 double crf_int = 0.0, crf_frc = 0.0;
646 switch(m_options->rcMode())
648 case OptionsModel::RCMode_CQ:
649 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
651 case OptionsModel::RCMode_CRF:
652 crf_frc = modf(m_options->quantizer(), &crf_int);
653 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
655 case OptionsModel::RCMode_2Pass:
656 case OptionsModel::RCMode_ABR:
657 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
660 throw "Bad rate-control mode !!!";
664 if((pass == 1) || (pass == 2))
666 cmdLine << "--pass" << QString::number(pass);
667 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
670 cmdLine << "--preset" << m_options->preset().toLower();
672 if(m_options->tune().compare("none", Qt::CaseInsensitive))
674 cmdLine << "--tune" << m_options->tune().toLower();
677 if(m_options->profile().compare("auto", Qt::CaseInsensitive) != 0)
679 if((m_options->encType() == OptionsModel::EncType_X264) && (m_options->encVariant() == OptionsModel::EncVariant_LoBit))
681 cmdLine << "--profile" << m_options->profile().toLower();
685 if(!m_options->customEncParams().isEmpty())
687 QStringList customArgs = splitParams(m_options->customEncParams());
690 QStringList::iterator i = customArgs.begin();
691 while(i != customArgs.end())
693 bool bModified = false;
694 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
695 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
699 cmdLine.append(customArgs);
702 cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
706 if(frames < 1) throw "Frames not set!";
707 cmdLine << "--frames" << QString::number(frames);
708 cmdLine << "--demuxer" << "y4m";
709 cmdLine << "--stdin" << "y4m" << "-";
713 cmdLine << "--index" << QDir::toNativeSeparators(indexFile);
714 cmdLine << QDir::toNativeSeparators(m_sourceFileName);
720 unsigned int EncodeThread::checkVersionEncoder(bool &modified)
725 unsigned int EncodeThread::checkVersionAvs2yuv(void)
727 if(!m_sysinfo->hasAVSSupport())
729 log(tr("\nAVS INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
735 log("\nCreating process:");
736 if(!startProcess(process, AVS_BINARY(m_sysinfo, m_preferences), QStringList()))
741 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
742 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
744 bool bTimeout = false;
745 bool bAborted = false;
747 unsigned int ver_maj = UINT_MAX;
748 unsigned int ver_min = UINT_MAX;
749 unsigned int ver_mod = 0;
751 while(process.state() != QProcess::NotRunning)
759 if(!process.waitForReadyRead())
761 if(process.state() == QProcess::Running)
764 qWarning("Avs2YUV process timed out <-- killing!");
765 log("\nPROCESS TIMEOUT !!!");
770 while(process.bytesAvailable() > 0)
772 QList<QByteArray> lines = process.readLine().split('\r');
773 while(!lines.isEmpty())
775 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
777 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
784 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
786 bool ok1 = false, ok2 = false, ok3 = false;
787 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
788 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
789 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
790 if(ok1) ver_maj = temp1;
791 if(ok2) ver_min = temp2;
792 if(ok3) ver_mod = temp3;
794 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
796 bool ok1 = false, ok2 = false;
797 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
798 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
799 if(ok1) ver_maj = temp1;
800 if(ok2) ver_min = temp2;
806 process.waitForFinished();
807 if(process.state() != QProcess::NotRunning)
810 process.waitForFinished(-1);
813 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
815 if(!(bTimeout || bAborted))
817 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
822 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
824 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
828 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
831 bool EncodeThread::checkVersionVapoursynth(void)
833 //Is VapourSynth available at all?
834 if((!m_sysinfo->hasVPSSupport()) || (!QFileInfo(VPS_BINARY(m_sysinfo, m_preferences)).isFile()))
836 log(tr("\nVPY INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
842 log("\nCreating process:");
843 if(!startProcess(process, VPS_BINARY(m_sysinfo, m_preferences), QStringList()))
848 QRegExp regExpSignature("\\bVSPipe\\s+usage\\b", Qt::CaseInsensitive);
850 bool bTimeout = false;
851 bool bAborted = false;
853 bool vspipeSignature = false;
855 while(process.state() != QProcess::NotRunning)
863 if(!process.waitForReadyRead())
865 if(process.state() == QProcess::Running)
868 qWarning("VSPipe process timed out <-- killing!");
869 log("\nPROCESS TIMEOUT !!!");
874 while(process.bytesAvailable() > 0)
876 QList<QByteArray> lines = process.readLine().split('\r');
877 while(!lines.isEmpty())
879 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
880 if(regExpSignature.lastIndexIn(text) >= 0)
882 vspipeSignature = true;
892 process.waitForFinished();
893 if(process.state() != QProcess::NotRunning)
896 process.waitForFinished(-1);
899 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 1)))
901 if(!(bTimeout || bAborted))
903 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
910 log(tr("\nFAILED TO DETECT VSPIPE SIGNATURE !!!"));
914 return vspipeSignature;
917 bool EncodeThread::checkPropertiesAVS(unsigned int &frames)
922 if(!m_options->customAvs2YUV().isEmpty())
924 cmdLine.append(splitParams(m_options->customAvs2YUV()));
927 cmdLine << "-frames" << "1";
928 cmdLine << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true)) << "NUL";
930 log("Creating process:");
931 if(!startProcess(process, AVS_BINARY(m_sysinfo, m_preferences), cmdLine))
936 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
937 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
939 QTextCodec *localCodec = QTextCodec::codecForName("System");
941 bool bTimeout = false;
942 bool bAborted = false;
946 unsigned int fpsNom = 0;
947 unsigned int fpsDen = 0;
948 unsigned int fSizeW = 0;
949 unsigned int fSizeH = 0;
951 unsigned int waitCounter = 0;
953 while(process.state() != QProcess::NotRunning)
961 if(!process.waitForReadyRead(m_processTimeoutInterval))
963 if(process.state() == QProcess::Running)
965 if(++waitCounter > m_processTimeoutMaxCounter)
967 if(m_preferences->getAbortOnTimeout())
970 qWarning("Avs2YUV process timed out <-- killing!");
971 log("\nPROCESS TIMEOUT !!!");
972 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
977 else if(waitCounter == m_processTimeoutWarning)
979 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
980 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
988 while(process.bytesAvailable() > 0)
990 QList<QByteArray> lines = process.readLine().split('\r');
991 while(!lines.isEmpty())
993 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
995 if((offset = regExpInt.lastIndexIn(text)) >= 0)
997 bool ok1 = false, ok2 = false;
998 bool ok3 = false, ok4 = false;
999 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
1000 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
1001 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
1002 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
1003 if(ok1) fSizeW = temp1;
1004 if(ok2) fSizeH = temp2;
1005 if(ok3) fpsNom = temp3;
1006 if(ok4) frames = temp4;
1008 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
1010 bool ok1 = false, ok2 = false;
1011 bool ok3 = false, ok4 = false, ok5 = false;
1012 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
1013 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
1014 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
1015 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
1016 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
1017 if(ok1) fSizeW = temp1;
1018 if(ok2) fSizeH = temp2;
1019 if(ok3) fpsNom = temp3;
1020 if(ok4) fpsDen = temp4;
1021 if(ok5) frames = temp5;
1027 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
1029 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(m_preferences->getUseAvisyth64Bit() ? "64" : "32"));
1031 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
1033 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
1039 process.waitForFinished();
1040 if(process.state() != QProcess::NotRunning)
1043 process.waitForFinished(-1);
1046 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1048 if(!(bTimeout || bAborted))
1050 const int exitCode = process.exitCode();
1051 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(exitCode)));
1052 if((exitCode < 0) || (exitCode >= 32))
1054 log(tr("\nIMPORTANT: The Avs2YUV process terminated abnormally. This means Avisynth or one of your Avisynth-Plugin's just crashed."));
1055 log(tr("IMPORTANT: Please fix your Avisynth script and try again! If you use Avisynth-MT, try using a *stable* Avisynth instead!"));
1063 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
1069 if((fSizeW > 0) && (fSizeH > 0))
1071 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1073 if((fpsNom > 0) && (fpsDen > 0))
1075 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
1077 if((fpsNom > 0) && (fpsDen == 0))
1079 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
1083 log(tr("No. Frames: %1").arg(QString::number(frames)));
1089 bool EncodeThread::checkPropertiesVPS(unsigned int &frames)
1092 QStringList cmdLine;
1094 cmdLine << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
1095 cmdLine << "-" << "-info";
1097 log("Creating process:");
1098 if(!startProcess(process, VPS_BINARY(m_sysinfo, m_preferences), cmdLine))
1103 QRegExp regExpFrm("\\bFrames:\\s+(\\d+)\\b");
1104 QRegExp regExpSzW("\\bWidth:\\s+(\\d+)\\b");
1105 QRegExp regExpSzH("\\bHeight:\\s+(\\d+)\\b");
1107 QTextCodec *localCodec = QTextCodec::codecForName("System");
1109 bool bTimeout = false;
1110 bool bAborted = false;
1114 unsigned int fSizeW = 0;
1115 unsigned int fSizeH = 0;
1117 unsigned int waitCounter = 0;
1119 while(process.state() != QProcess::NotRunning)
1127 if(!process.waitForReadyRead(m_processTimeoutInterval))
1129 if(process.state() == QProcess::Running)
1131 if(++waitCounter > m_processTimeoutMaxCounter)
1133 if(m_preferences->getAbortOnTimeout())
1136 qWarning("VSPipe process timed out <-- killing!");
1137 log("\nPROCESS TIMEOUT !!!");
1138 log("\nVapoursynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1143 else if(waitCounter == m_processTimeoutWarning)
1145 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1146 log(tr("Warning: nVapoursynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1154 while(process.bytesAvailable() > 0)
1156 QList<QByteArray> lines = process.readLine().split('\r');
1157 while(!lines.isEmpty())
1159 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1161 if((offset = regExpFrm.lastIndexIn(text)) >= 0)
1164 unsigned int temp = regExpFrm.cap(1).toUInt(&ok);
1165 if(ok) frames = temp;
1167 if((offset = regExpSzW.lastIndexIn(text)) >= 0)
1170 unsigned int temp = regExpSzW.cap(1).toUInt(&ok);
1171 if(ok) fSizeW = temp;
1173 if((offset = regExpSzH.lastIndexIn(text)) >= 0)
1176 unsigned int temp = regExpSzH.cap(1).toUInt(&ok);
1177 if(ok) fSizeH = temp;
1187 process.waitForFinished();
1188 if(process.state() != QProcess::NotRunning)
1191 process.waitForFinished(-1);
1194 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1196 if(!(bTimeout || bAborted))
1198 const int exitCode = process.exitCode();
1199 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(exitCode)));
1200 if((exitCode < 0) || (exitCode >= 32))
1202 log(tr("\nIMPORTANT: The Vapoursynth process terminated abnormally. This means Vapoursynth or one of your Vapoursynth-Plugin's just crashed."));
1210 log(tr("\nFAILED TO DETERMINE VPY PROPERTIES !!!"));
1216 if((fSizeW > 0) && (fSizeH > 0))
1218 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1222 log(tr("No. Frames: %1").arg(QString::number(frames)));
1228 ///////////////////////////////////////////////////////////////////////////////
1230 ///////////////////////////////////////////////////////////////////////////////
1232 void EncodeThread::setStatus(JobStatus newStatus)
1234 if(m_status != newStatus)
1236 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
1238 if(m_status != JobStatus_Paused) setProgress(0);
1240 if(newStatus == JobStatus_Failed)
1242 setDetails("The job has failed. See log for details!");
1244 if(newStatus == JobStatus_Aborted)
1246 setDetails("The job was aborted by the user!");
1248 m_status = newStatus;
1249 emit statusChanged(m_jobId, newStatus);
1253 void EncodeThread::setProgress(unsigned int newProgress)
1255 if(m_progress != newProgress)
1257 m_progress = newProgress;
1258 emit progressChanged(m_jobId, m_progress);
1262 void EncodeThread::setDetails(const QString &text)
1264 emit detailsChanged(m_jobId, text);
1267 QString EncodeThread::stringToHash(const QString &string)
1269 QByteArray result(10, char(0));
1270 const QByteArray hash = QCryptographicHash::hash(string.toUtf8(), QCryptographicHash::Sha1);
1272 if((hash.size() == 20) && (result.size() == 10))
1274 unsigned char *out = reinterpret_cast<unsigned char*>(result.data());
1275 const unsigned char *in = reinterpret_cast<const unsigned char*>(hash.constData());
1276 for(int i = 0; i < 10; i++)
1278 out[i] = (in[i] ^ in[10+i]);
1282 return QString::fromLatin1(result.toHex().constData());
1285 QStringList EncodeThread::splitParams(const QString ¶ms)
1288 bool ignoreWhitespaces = false;
1291 for(int i = 0; i < params.length(); i++)
1293 const QChar c = params.at(i);
1295 if(c == QChar::fromLatin1('"'))
1297 ignoreWhitespaces = (!ignoreWhitespaces);
1300 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1302 APPEND_AND_CLEAR(list, temp);
1309 APPEND_AND_CLEAR(list, temp);
1311 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1312 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1317 qint64 EncodeThread::estimateSize(int progress)
1321 qint64 currentSize = QFileInfo(m_outputFileName).size();
1322 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1323 return estimatedSize;
1329 QString EncodeThread::sizeToString(qint64 size)
1331 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1335 qint64 estimatedSize = size;
1336 qint64 remainderSize = 0I64;
1339 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1341 remainderSize = estimatedSize % 1024I64;
1342 estimatedSize = estimatedSize / 1024I64;
1346 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1347 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);
1353 int EncodeThread::getInputType(const QString &fileExt)
1355 int type = INPUT_NATIVE;
1356 if(fileExt.compare("avs", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1357 else if(fileExt.compare("avsi", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1358 else if(fileExt.compare("vpy", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
1359 else if(fileExt.compare("py", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;