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 unsigned int REV_MULT = 10000;
126 static const char *VPS_TEST_FILE = "import vapoursynth as vs\ncore = vs.get_core()\nv = core.std.BlankClip()\nv.set_output()\n";
128 ///////////////////////////////////////////////////////////////////////////////
129 // Constructor & Destructor
130 ///////////////////////////////////////////////////////////////////////////////
132 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
134 m_jobId(QUuid::createUuid()),
135 m_sourceFileName(sourceFileName),
136 m_outputFileName(outputFileName),
137 m_options(new OptionsModel(*options)),
139 m_preferences(preferences),
140 m_jobObject(new JobObject),
147 EncodeThread::~EncodeThread(void)
149 X264_DELETE(m_options);
150 X264_DELETE(m_jobObject);
153 ///////////////////////////////////////////////////////////////////////////////
154 // Thread entry point
155 ///////////////////////////////////////////////////////////////////////////////
157 void EncodeThread::run(void)
166 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
174 m_jobObject->terminateJob(42);
175 X264_DELETE(m_jobObject);
179 void EncodeThread::checkedRun(void)
182 m_status = JobStatus_Starting;
188 ExecutionStateHandler executionStateHandler;
193 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
194 setStatus(JobStatus_Failed);
198 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
199 setStatus(JobStatus_Failed);
204 x264_fatal_exit(L"Unhandeled exception error in encode thread!");
208 void EncodeThread::start(Priority priority)
210 qDebug("Thread starting...");
215 while(m_semaphorePaused.tryAcquire(1, 0));
216 QThread::start(priority);
219 ///////////////////////////////////////////////////////////////////////////////
221 ///////////////////////////////////////////////////////////////////////////////
223 void EncodeThread::encode(void)
225 QDateTime startTime = QDateTime::currentDateTime();
227 //Print some basic info
228 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
229 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
230 log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
231 log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
234 log(tr("\n--- SYSTEMINFO ---\n"));
235 log(tr("Binary Path: %1").arg(QDir::toNativeSeparators(m_sysinfo->getAppPath())));
236 log(tr("Avisynth 2x: %1").arg(m_sysinfo->hasAVSSupport() ? tr("YES") : tr("NO")));
237 log(tr("VapourSynth: %1").arg(m_sysinfo->hasVPSSupport() ? QDir::toNativeSeparators(m_sysinfo->getVPSPath()) : tr("N/A")));
239 //Print encoder settings
240 log(tr("\n--- SETTINGS ---\n"));
241 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
242 log(tr("Preset: %1").arg(m_options->preset()));
243 log(tr("Tuning: %1").arg(m_options->tune()));
244 log(tr("Profile: %1").arg(m_options->profile()));
245 log(tr("Custom: %1").arg(m_options->customEncParams().isEmpty() ? tr("(None)") : m_options->customEncParams()));
248 unsigned int frames = 0;
250 //Seletct type of input
251 const int inputType = getInputType(QFileInfo(m_sourceFileName).suffix());
252 const QString indexFile = QString("%1/x264_%2.ffindex").arg(QDir::tempPath(), stringToHash(m_sourceFileName));
254 //Checking x264 version
255 log(tr("\n--- CHECK VERSION ---\n"));
256 unsigned int revision_x264 = UINT_MAX;
257 bool x264_modified = false;
258 ok = ((revision_x264 = checkVersionX264(x264_modified)) != UINT_MAX);
259 CHECK_STATUS(m_abort, ok);
261 //Checking avs2yuv version
262 unsigned int revision_avs2yuv = UINT_MAX;
266 ok = ((revision_avs2yuv = checkVersionAvs2yuv()) != UINT_MAX);
267 CHECK_STATUS(m_abort, ok);
270 ok = checkVersionVapoursynth();
271 CHECK_STATUS(m_abort, ok);
276 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()));
277 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)));
279 //Is x264 revision supported?
280 if((revision_x264 % REV_MULT) < x264_version_x264_minimum_rev())
282 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(x264_version_x264_minimum_rev())));
283 setStatus(JobStatus_Failed);
286 if((revision_x264 / REV_MULT) != x264_version_x264_current_api())
288 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
289 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(x264_version_x264_current_api())));
291 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != x264_version_x264_avs2yuv_ver()))
293 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
294 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
295 setStatus(JobStatus_Failed);
300 if(inputType != INPUT_NATIVE)
302 log(tr("\n--- SOURCE INFO ---\n"));
306 ok = checkPropertiesAVS(frames);
307 CHECK_STATUS(m_abort, ok);
310 ok = checkPropertiesVPS(frames);
311 CHECK_STATUS(m_abort, ok);
316 //Run encoding passes
317 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
319 QFileInfo info(m_outputFileName);
320 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
322 if(QFileInfo(passLogFile).exists())
325 while(QFileInfo(passLogFile).exists())
327 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
331 log(tr("\n--- PASS 1 ---\n"));
332 ok = runEncodingPass(inputType, frames, indexFile, 1, passLogFile);
333 CHECK_STATUS(m_abort, ok);
335 log(tr("\n--- PASS 2 ---\n"));
336 ok = runEncodingPass(inputType, frames, indexFile, 2, passLogFile);
337 CHECK_STATUS(m_abort, ok);
341 log(tr("\n--- ENCODING ---\n"));
342 ok = runEncodingPass(inputType, frames, indexFile);
343 CHECK_STATUS(m_abort, ok);
346 log(tr("\n--- DONE ---\n"));
347 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
348 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)));
349 setStatus(JobStatus_Completed);
352 #define X264_UPDATE_PROGRESS(X) do \
355 unsigned int progress = (X).cap(1).toUInt(&ok); \
356 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running)); \
357 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX))) \
359 setProgress(progress); \
360 size_estimate = estimateSize(progress); \
361 last_progress = progress; \
363 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate))); \
364 last_indexing = UINT_MAX; \
368 bool EncodeThread::runEncodingPass(const int &inputType, const unsigned int &frames, const QString &indexFile, const int &pass, const QString &passLogFile)
370 QProcess processEncode, processInput;
372 if(inputType != INPUT_NATIVE)
374 QStringList cmdLine_Input;
375 processInput.setStandardOutputProcess(&processEncode);
379 if(!m_options->customAvs2YUV().isEmpty())
381 cmdLine_Input.append(splitParams(m_options->customAvs2YUV()));
383 cmdLine_Input << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
384 cmdLine_Input << "-";
385 log("Creating Avisynth process:");
386 if(!startProcess(processInput, AVS_BINARY(m_sysinfo, m_preferences), cmdLine_Input, false))
392 cmdLine_Input << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
393 cmdLine_Input << "-" << "-y4m";
394 log("Creating Vapoursynth process:");
395 if(!startProcess(processInput, VPS_BINARY(m_sysinfo, m_preferences), cmdLine_Input, false))
401 throw "Bad input type encontered!";
405 QStringList cmdLine_Encode = buildCommandLine((inputType != INPUT_NATIVE), frames, indexFile, pass, passLogFile);
407 log("Creating x264 process:");
408 if(!startProcess(processEncode, ENC_BINARY(m_sysinfo, m_options), cmdLine_Encode))
413 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
414 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
415 QRegExp regExpModified("\\[\\s*(\\d+)\\.(\\d+)%\\]\\s+(\\d+)/(\\d+)\\s(\\d+).(\\d+)\\s(\\d+).(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)");
416 QRegExp regExpFrameCnt("^(\\d+) frames:");
418 QTextCodec *localCodec = QTextCodec::codecForName("System");
420 bool bTimeout = false;
421 bool bAborted = false;
423 unsigned int last_progress = UINT_MAX;
424 unsigned int last_indexing = UINT_MAX;
425 qint64 size_estimate = 0I64;
427 //Main processing loop
428 while(processEncode.state() != QProcess::NotRunning)
430 unsigned int waitCounter = 0;
432 //Wait until new output is available
437 processEncode.kill();
442 if(m_pause && (processEncode.state() == QProcess::Running))
444 JobStatus previousStatus = m_status;
445 setStatus(JobStatus_Paused);
446 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
447 bool ok[2] = {false, false};
448 QProcess *proc[2] = { &processEncode, &processInput };
449 ok[0] = x264_suspendProcess(proc[0], true);
450 ok[1] = x264_suspendProcess(proc[1], true);
451 while(m_pause) m_semaphorePaused.tryAcquire(1, 5000);
452 while(m_semaphorePaused.tryAcquire(1, 0));
453 ok[0] = x264_suspendProcess(proc[0], false);
454 ok[1] = x264_suspendProcess(proc[1], false);
455 if(!m_abort) setStatus(previousStatus);
456 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
460 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
462 if(processEncode.state() == QProcess::Running)
464 if(++waitCounter > m_processTimeoutMaxCounter)
466 if(m_preferences->getAbortOnTimeout())
468 processEncode.kill();
469 qWarning("x264 process timed out <-- killing!");
470 log("\nPROCESS TIMEOUT !!!");
475 else if(waitCounter == m_processTimeoutWarning)
477 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
478 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
483 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
490 //Exit main processing loop now?
491 if(bAborted || bTimeout)
497 while(processEncode.bytesAvailable() > 0)
499 QList<QByteArray> lines = processEncode.readLine().split('\r');
500 while(!lines.isEmpty())
502 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
504 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
506 X264_UPDATE_PROGRESS(regExpProgress);
508 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
511 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
512 setStatus(JobStatus_Indexing);
513 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
515 setProgress(progress);
516 last_indexing = progress;
518 setDetails(text.mid(offset).trimmed());
519 last_progress = UINT_MAX;
521 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
523 last_progress = last_indexing = UINT_MAX;
524 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
525 setDetails(text.mid(offset).trimmed());
527 else if((offset = regExpModified.lastIndexIn(text)) >= 0)
529 X264_UPDATE_PROGRESS(regExpModified);
531 else if(!text.isEmpty())
533 last_progress = last_indexing = UINT_MAX;
540 processEncode.waitForFinished(5000);
541 if(processEncode.state() != QProcess::NotRunning)
543 qWarning("x264 process still running, going to kill it!");
544 processEncode.kill();
545 processEncode.waitForFinished(-1);
548 processInput.waitForFinished(5000);
549 if(processInput.state() != QProcess::NotRunning)
551 qWarning("Input process still running, going to kill it!");
553 processInput.waitForFinished(-1);
556 if(!(bTimeout || bAborted))
558 while(processInput.bytesAvailable() > 0)
563 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
566 log(tr("vpyp [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
572 if((inputType != INPUT_NATIVE) && (processInput.exitCode() != EXIT_SUCCESS))
574 if(!(bTimeout || bAborted))
576 const int exitCode = processInput.exitCode();
577 log(tr("\nWARNING: Input process exited with error (code: %1), your encode might be *incomplete* !!!").arg(QString::number(exitCode)));
578 if((inputType == INPUT_AVISYN) && ((exitCode < 0) || (exitCode >= 32)))
580 log(tr("\nIMPORTANT: The Avs2YUV process terminated abnormally. This means Avisynth or one of your Avisynth-Plugin's just crashed."));
581 log(tr("IMPORTANT: Please fix your Avisynth script and try again! If you use Avisynth-MT, try using a *stable* Avisynth instead!"));
583 if((inputType == INPUT_VAPOUR) && ((exitCode < 0) || (exitCode >= 32)))
585 log(tr("\nIMPORTANT: The Vapoursynth process terminated abnormally. This means Vapoursynth or one of your Vapoursynth-Plugin's just crashed."));
590 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
592 if(!(bTimeout || bAborted))
594 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
596 processEncode.close();
597 processInput.close();
601 QThread::yieldCurrentThread();
603 const qint64 finalSize = QFileInfo(m_outputFileName).size();
604 QLocale locale(QLocale::English);
605 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
610 setStatus(JobStatus_Running_Pass1);
611 setDetails(tr("First pass completed. Preparing for second pass..."));
614 setStatus(JobStatus_Running_Pass2);
615 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
618 setStatus(JobStatus_Running);
619 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
624 processEncode.close();
625 processInput.close();
629 QStringList EncodeThread::buildCommandLine(const bool &usePipe, const unsigned int &frames, const QString &indexFile, const int &pass, const QString &passLogFile)
632 double crf_int = 0.0, crf_frc = 0.0;
634 switch(m_options->rcMode())
636 case OptionsModel::RCMode_CQ:
637 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
639 case OptionsModel::RCMode_CRF:
640 crf_frc = modf(m_options->quantizer(), &crf_int);
641 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
643 case OptionsModel::RCMode_2Pass:
644 case OptionsModel::RCMode_ABR:
645 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
648 throw "Bad rate-control mode !!!";
652 if((pass == 1) || (pass == 2))
654 cmdLine << "--pass" << QString::number(pass);
655 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
658 cmdLine << "--preset" << m_options->preset().toLower();
660 if(m_options->tune().compare("none", Qt::CaseInsensitive))
662 cmdLine << "--tune" << m_options->tune().toLower();
665 if(m_options->profile().compare("auto", Qt::CaseInsensitive) != 0)
667 if((m_options->encType() == OptionsModel::EncType_X264) && (m_options->encVariant() == OptionsModel::EncVariant_LoBit))
669 cmdLine << "--profile" << m_options->profile().toLower();
673 if(!m_options->customEncParams().isEmpty())
675 QStringList customArgs = splitParams(m_options->customEncParams());
678 QStringList::iterator i = customArgs.begin();
679 while(i != customArgs.end())
681 bool bModified = false;
682 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
683 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
687 cmdLine.append(customArgs);
690 cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
694 if(frames < 1) throw "Frames not set!";
695 cmdLine << "--frames" << QString::number(frames);
696 cmdLine << "--demuxer" << "y4m";
697 cmdLine << "--stdin" << "y4m" << "-";
701 cmdLine << "--index" << QDir::toNativeSeparators(indexFile);
702 cmdLine << QDir::toNativeSeparators(m_sourceFileName);
708 unsigned int EncodeThread::checkVersionX264(bool &modified)
710 if(m_preferences->getSkipVersionTest())
712 log("Warning: Skipping x264 version check this time!");
713 return (999 * REV_MULT) + (9999 % REV_MULT);
717 QStringList cmdLine = QStringList() << "--version";
719 log("Creating process:");
720 if(!startProcess(process, ENC_BINARY(m_sysinfo, m_options), cmdLine))
725 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
726 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
728 bool bTimeout = false;
729 bool bAborted = false;
731 unsigned int revision = UINT_MAX;
732 unsigned int coreVers = UINT_MAX;
735 while(process.state() != QProcess::NotRunning)
743 if(!process.waitForReadyRead())
745 if(process.state() == QProcess::Running)
748 qWarning("x264 process timed out <-- killing!");
749 log("\nPROCESS TIMEOUT !!!");
754 while(process.bytesAvailable() > 0)
756 QList<QByteArray> lines = process.readLine().split('\r');
757 while(!lines.isEmpty())
759 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
761 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
763 bool ok1 = false, ok2 = false;
764 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
765 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
766 if(ok1) coreVers = temp1;
767 if(ok2) revision = temp2;
769 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
771 bool ok1 = false, ok2 = false;
772 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
773 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
774 if(ok1) coreVers = temp1;
775 if(ok2) revision = temp2;
786 process.waitForFinished();
787 if(process.state() != QProcess::NotRunning)
790 process.waitForFinished(-1);
793 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
795 if(!(bTimeout || bAborted))
797 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
802 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
804 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
808 return (coreVers * REV_MULT) + (revision % REV_MULT);
811 unsigned int EncodeThread::checkVersionAvs2yuv(void)
813 if(!m_sysinfo->hasAVSSupport())
815 log(tr("\nAVS INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
821 log("\nCreating process:");
822 if(!startProcess(process, AVS_BINARY(m_sysinfo, m_preferences), QStringList()))
827 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
828 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
830 bool bTimeout = false;
831 bool bAborted = false;
833 unsigned int ver_maj = UINT_MAX;
834 unsigned int ver_min = UINT_MAX;
835 unsigned int ver_mod = 0;
837 while(process.state() != QProcess::NotRunning)
845 if(!process.waitForReadyRead())
847 if(process.state() == QProcess::Running)
850 qWarning("Avs2YUV process timed out <-- killing!");
851 log("\nPROCESS TIMEOUT !!!");
856 while(process.bytesAvailable() > 0)
858 QList<QByteArray> lines = process.readLine().split('\r');
859 while(!lines.isEmpty())
861 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
863 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
870 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
872 bool ok1 = false, ok2 = false, ok3 = false;
873 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
874 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
875 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
876 if(ok1) ver_maj = temp1;
877 if(ok2) ver_min = temp2;
878 if(ok3) ver_mod = temp3;
880 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
882 bool ok1 = false, ok2 = false;
883 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
884 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
885 if(ok1) ver_maj = temp1;
886 if(ok2) ver_min = temp2;
892 process.waitForFinished();
893 if(process.state() != QProcess::NotRunning)
896 process.waitForFinished(-1);
899 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
901 if(!(bTimeout || bAborted))
903 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
908 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
910 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
914 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
917 bool EncodeThread::checkVersionVapoursynth(void)
919 //Is VapourSynth available at all?
920 if((!m_sysinfo->hasVPSSupport()) || (!QFileInfo(VPS_BINARY(m_sysinfo, m_preferences)).isFile()))
922 log(tr("\nVPY INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
928 log("\nCreating process:");
929 if(!startProcess(process, VPS_BINARY(m_sysinfo, m_preferences), QStringList()))
934 QRegExp regExpSignature("\\bVSPipe\\s+usage\\b", Qt::CaseInsensitive);
936 bool bTimeout = false;
937 bool bAborted = false;
939 bool vspipeSignature = false;
941 while(process.state() != QProcess::NotRunning)
949 if(!process.waitForReadyRead())
951 if(process.state() == QProcess::Running)
954 qWarning("VSPipe process timed out <-- killing!");
955 log("\nPROCESS TIMEOUT !!!");
960 while(process.bytesAvailable() > 0)
962 QList<QByteArray> lines = process.readLine().split('\r');
963 while(!lines.isEmpty())
965 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
966 if(regExpSignature.lastIndexIn(text) >= 0)
968 vspipeSignature = true;
978 process.waitForFinished();
979 if(process.state() != QProcess::NotRunning)
982 process.waitForFinished(-1);
985 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 1)))
987 if(!(bTimeout || bAborted))
989 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
996 log(tr("\nFAILED TO DETECT VSPIPE SIGNATURE !!!"));
1000 return vspipeSignature;
1003 bool EncodeThread::checkPropertiesAVS(unsigned int &frames)
1006 QStringList cmdLine;
1008 if(!m_options->customAvs2YUV().isEmpty())
1010 cmdLine.append(splitParams(m_options->customAvs2YUV()));
1013 cmdLine << "-frames" << "1";
1014 cmdLine << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true)) << "NUL";
1016 log("Creating process:");
1017 if(!startProcess(process, AVS_BINARY(m_sysinfo, m_preferences), cmdLine))
1022 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
1023 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
1025 QTextCodec *localCodec = QTextCodec::codecForName("System");
1027 bool bTimeout = false;
1028 bool bAborted = false;
1032 unsigned int fpsNom = 0;
1033 unsigned int fpsDen = 0;
1034 unsigned int fSizeW = 0;
1035 unsigned int fSizeH = 0;
1037 unsigned int waitCounter = 0;
1039 while(process.state() != QProcess::NotRunning)
1047 if(!process.waitForReadyRead(m_processTimeoutInterval))
1049 if(process.state() == QProcess::Running)
1051 if(++waitCounter > m_processTimeoutMaxCounter)
1053 if(m_preferences->getAbortOnTimeout())
1056 qWarning("Avs2YUV process timed out <-- killing!");
1057 log("\nPROCESS TIMEOUT !!!");
1058 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1063 else if(waitCounter == m_processTimeoutWarning)
1065 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1066 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1074 while(process.bytesAvailable() > 0)
1076 QList<QByteArray> lines = process.readLine().split('\r');
1077 while(!lines.isEmpty())
1079 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1081 if((offset = regExpInt.lastIndexIn(text)) >= 0)
1083 bool ok1 = false, ok2 = false;
1084 bool ok3 = false, ok4 = false;
1085 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
1086 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
1087 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
1088 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
1089 if(ok1) fSizeW = temp1;
1090 if(ok2) fSizeH = temp2;
1091 if(ok3) fpsNom = temp3;
1092 if(ok4) frames = temp4;
1094 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
1096 bool ok1 = false, ok2 = false;
1097 bool ok3 = false, ok4 = false, ok5 = false;
1098 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
1099 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
1100 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
1101 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
1102 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
1103 if(ok1) fSizeW = temp1;
1104 if(ok2) fSizeH = temp2;
1105 if(ok3) fpsNom = temp3;
1106 if(ok4) fpsDen = temp4;
1107 if(ok5) frames = temp5;
1113 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
1115 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(m_preferences->getUseAvisyth64Bit() ? "64" : "32"));
1117 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
1119 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
1125 process.waitForFinished();
1126 if(process.state() != QProcess::NotRunning)
1129 process.waitForFinished(-1);
1132 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1134 if(!(bTimeout || bAborted))
1136 const int exitCode = process.exitCode();
1137 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(exitCode)));
1138 if((exitCode < 0) || (exitCode >= 32))
1140 log(tr("\nIMPORTANT: The Avs2YUV process terminated abnormally. This means Avisynth or one of your Avisynth-Plugin's just crashed."));
1141 log(tr("IMPORTANT: Please fix your Avisynth script and try again! If you use Avisynth-MT, try using a *stable* Avisynth instead!"));
1149 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
1155 if((fSizeW > 0) && (fSizeH > 0))
1157 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1159 if((fpsNom > 0) && (fpsDen > 0))
1161 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
1163 if((fpsNom > 0) && (fpsDen == 0))
1165 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
1169 log(tr("No. Frames: %1").arg(QString::number(frames)));
1175 bool EncodeThread::checkPropertiesVPS(unsigned int &frames)
1178 QStringList cmdLine;
1180 cmdLine << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
1181 cmdLine << "-" << "-info";
1183 log("Creating process:");
1184 if(!startProcess(process, VPS_BINARY(m_sysinfo, m_preferences), cmdLine))
1189 QRegExp regExpFrm("\\bFrames:\\s+(\\d+)\\b");
1190 QRegExp regExpSzW("\\bWidth:\\s+(\\d+)\\b");
1191 QRegExp regExpSzH("\\bHeight:\\s+(\\d+)\\b");
1193 QTextCodec *localCodec = QTextCodec::codecForName("System");
1195 bool bTimeout = false;
1196 bool bAborted = false;
1200 unsigned int fSizeW = 0;
1201 unsigned int fSizeH = 0;
1203 unsigned int waitCounter = 0;
1205 while(process.state() != QProcess::NotRunning)
1213 if(!process.waitForReadyRead(m_processTimeoutInterval))
1215 if(process.state() == QProcess::Running)
1217 if(++waitCounter > m_processTimeoutMaxCounter)
1219 if(m_preferences->getAbortOnTimeout())
1222 qWarning("VSPipe process timed out <-- killing!");
1223 log("\nPROCESS TIMEOUT !!!");
1224 log("\nVapoursynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1229 else if(waitCounter == m_processTimeoutWarning)
1231 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1232 log(tr("Warning: nVapoursynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1240 while(process.bytesAvailable() > 0)
1242 QList<QByteArray> lines = process.readLine().split('\r');
1243 while(!lines.isEmpty())
1245 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1247 if((offset = regExpFrm.lastIndexIn(text)) >= 0)
1250 unsigned int temp = regExpFrm.cap(1).toUInt(&ok);
1251 if(ok) frames = temp;
1253 if((offset = regExpSzW.lastIndexIn(text)) >= 0)
1256 unsigned int temp = regExpSzW.cap(1).toUInt(&ok);
1257 if(ok) fSizeW = temp;
1259 if((offset = regExpSzH.lastIndexIn(text)) >= 0)
1262 unsigned int temp = regExpSzH.cap(1).toUInt(&ok);
1263 if(ok) fSizeH = temp;
1273 process.waitForFinished();
1274 if(process.state() != QProcess::NotRunning)
1277 process.waitForFinished(-1);
1280 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1282 if(!(bTimeout || bAborted))
1284 const int exitCode = process.exitCode();
1285 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(exitCode)));
1286 if((exitCode < 0) || (exitCode >= 32))
1288 log(tr("\nIMPORTANT: The Vapoursynth process terminated abnormally. This means Vapoursynth or one of your Vapoursynth-Plugin's just crashed."));
1296 log(tr("\nFAILED TO DETERMINE VPY PROPERTIES !!!"));
1302 if((fSizeW > 0) && (fSizeH > 0))
1304 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1308 log(tr("No. Frames: %1").arg(QString::number(frames)));
1314 ///////////////////////////////////////////////////////////////////////////////
1316 ///////////////////////////////////////////////////////////////////////////////
1318 void EncodeThread::setStatus(JobStatus newStatus)
1320 if(m_status != newStatus)
1322 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
1324 if(m_status != JobStatus_Paused) setProgress(0);
1326 if(newStatus == JobStatus_Failed)
1328 setDetails("The job has failed. See log for details!");
1330 if(newStatus == JobStatus_Aborted)
1332 setDetails("The job was aborted by the user!");
1334 m_status = newStatus;
1335 emit statusChanged(m_jobId, newStatus);
1339 void EncodeThread::setProgress(unsigned int newProgress)
1341 if(m_progress != newProgress)
1343 m_progress = newProgress;
1344 emit progressChanged(m_jobId, m_progress);
1348 void EncodeThread::setDetails(const QString &text)
1350 emit detailsChanged(m_jobId, text);
1353 QString EncodeThread::stringToHash(const QString &string)
1355 QByteArray result(10, char(0));
1356 const QByteArray hash = QCryptographicHash::hash(string.toUtf8(), QCryptographicHash::Sha1);
1358 if((hash.size() == 20) && (result.size() == 10))
1360 unsigned char *out = reinterpret_cast<unsigned char*>(result.data());
1361 const unsigned char *in = reinterpret_cast<const unsigned char*>(hash.constData());
1362 for(int i = 0; i < 10; i++)
1364 out[i] = (in[i] ^ in[10+i]);
1368 return QString::fromLatin1(result.toHex().constData());
1371 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1373 QMutexLocker lock(&m_mutex_startProcess);
1374 log(commandline2string(program, args) + "\n");
1376 process.setWorkingDirectory(QDir::tempPath());
1380 process.setProcessChannelMode(QProcess::MergedChannels);
1381 process.setReadChannel(QProcess::StandardOutput);
1385 process.setProcessChannelMode(QProcess::SeparateChannels);
1386 process.setReadChannel(QProcess::StandardError);
1389 process.start(program, args);
1391 if(process.waitForStarted())
1393 m_jobObject->addProcessToJob(&process);
1394 x264_change_process_priority(&process, m_preferences->getProcessPriority());
1399 log("Process creation has failed :-(");
1400 QString errorMsg= process.errorString().trimmed();
1401 if(!errorMsg.isEmpty()) log(errorMsg);
1404 process.waitForFinished(-1);
1408 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1410 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1412 for(int i = 0; i < arguments.count(); i++)
1414 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1420 QStringList EncodeThread::splitParams(const QString ¶ms)
1423 bool ignoreWhitespaces = false;
1426 for(int i = 0; i < params.length(); i++)
1428 const QChar c = params.at(i);
1430 if(c == QChar::fromLatin1('"'))
1432 ignoreWhitespaces = (!ignoreWhitespaces);
1435 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1437 APPEND_AND_CLEAR(list, temp);
1444 APPEND_AND_CLEAR(list, temp);
1446 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1447 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1452 qint64 EncodeThread::estimateSize(int progress)
1456 qint64 currentSize = QFileInfo(m_outputFileName).size();
1457 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1458 return estimatedSize;
1464 QString EncodeThread::sizeToString(qint64 size)
1466 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1470 qint64 estimatedSize = size;
1471 qint64 remainderSize = 0I64;
1474 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1476 remainderSize = estimatedSize % 1024I64;
1477 estimatedSize = estimatedSize / 1024I64;
1481 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1482 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);
1488 int EncodeThread::getInputType(const QString &fileExt)
1490 int type = INPUT_NATIVE;
1491 if(fileExt.compare("avs", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1492 else if(fileExt.compare("avsi", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1493 else if(fileExt.compare("vpy", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
1494 else if(fileExt.compare("py", Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;