1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2012 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"
41 QMutex EncodeThread::m_mutex_startProcess;
46 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
50 log("\nPROCESS ABORTED BY USER !!!"); \
51 setStatus(JobStatus_Aborted); \
52 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
53 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
58 setStatus(JobStatus_Failed); \
59 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
60 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
66 #define APPEND_AND_CLEAR(LIST, STR) do \
68 if(!((STR).isEmpty())) \
76 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
78 if(ITER != LIST.end()) \
80 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
82 log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
83 ITER = LIST.erase(ITER); \
84 if(ITER != LIST.end()) \
86 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
94 #define X264_BINARY(BIN_DIR, IS_10BIT, IS_X64) QString("%1/x264_%2_%3.exe").arg((BIN_DIR), ((IS_10BIT) ? "10bit" : "8bit"), ((IS_X64) ? "x64" : "x86"))
99 static const unsigned int REV_MULT = 10000;
101 ///////////////////////////////////////////////////////////////////////////////
102 // Constructor & Destructor
103 ///////////////////////////////////////////////////////////////////////////////
105 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x264_x64, bool x264_10bit, bool avs2yuv_x64)
107 m_jobId(QUuid::createUuid()),
108 m_sourceFileName(sourceFileName),
109 m_outputFileName(outputFileName),
110 m_options(new OptionsModel(*options)),
112 m_x264_x64(x264_x64),
113 m_x264_10bit(x264_10bit),
114 m_avs2yuv_x64(avs2yuv_x64),
115 m_handle_jobObject(NULL),
122 EncodeThread::~EncodeThread(void)
124 X264_DELETE(m_options);
126 if(m_handle_jobObject)
128 CloseHandle(m_handle_jobObject);
129 m_handle_jobObject = NULL;
133 ///////////////////////////////////////////////////////////////////////////////
134 // Thread entry point
135 ///////////////////////////////////////////////////////////////////////////////
137 void EncodeThread::run(void)
145 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
148 if(m_handle_jobObject)
150 TerminateJobObject(m_handle_jobObject, 42);
151 m_handle_jobObject = NULL;
155 void EncodeThread::checkedRun(void)
158 m_status = JobStatus_Starting;
168 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
169 setStatus(JobStatus_Failed);
173 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
174 setStatus(JobStatus_Failed);
179 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
183 void EncodeThread::start(Priority priority)
185 qDebug("Thread starting...");
190 while(m_semaphorePaused.tryAcquire(1, 0));
191 QThread::start(priority);
194 ///////////////////////////////////////////////////////////////////////////////
196 ///////////////////////////////////////////////////////////////////////////////
198 void EncodeThread::encode(void)
200 QDateTime startTime = QDateTime::currentDateTime();
202 //Print some basic info
203 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
204 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
205 log(tr("Source file: %1").arg(m_sourceFileName));
206 log(tr("Output file: %1").arg(m_outputFileName));
208 //Print encoder settings
209 log(tr("\n--- SETTINGS ---\n"));
210 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
211 log(tr("Preset: %1").arg(m_options->preset()));
212 log(tr("Tuning: %1").arg(m_options->tune()));
213 log(tr("Profile: %1").arg(m_options->profile()));
214 log(tr("Custom: %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
217 unsigned int frames = 0;
220 const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
221 const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
223 //Checking x264 version
224 log(tr("\n--- CHECK VERSION ---\n"));
225 unsigned int revision_x264 = UINT_MAX;
226 bool x264_modified = false;
227 ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
228 CHECK_STATUS(m_abort, ok);
230 //Checking avs2yuv version
231 unsigned int revision_avs2yuv = UINT_MAX;
234 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
235 CHECK_STATUS(m_abort, ok);
239 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()));
240 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)));
242 //Is x264 revision supported?
243 if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
245 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
246 setStatus(JobStatus_Failed);
249 if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
251 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
252 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
254 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
256 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
257 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
258 setStatus(JobStatus_Failed);
265 log(tr("\n--- AVS INFO ---\n"));
266 ok = checkProperties(m_avs2yuv_x64, frames);
267 CHECK_STATUS(m_abort, ok);
270 //Run encoding passes
271 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
273 QFileInfo info(m_outputFileName);
274 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
276 if(QFileInfo(passLogFile).exists())
279 while(QFileInfo(passLogFile).exists())
281 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
285 log(tr("\n--- PASS 1 ---\n"));
286 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile, 1, passLogFile);
287 CHECK_STATUS(m_abort, ok);
289 log(tr("\n--- PASS 2 ---\n"));
290 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile, 2, passLogFile);
291 CHECK_STATUS(m_abort, ok);
295 log(tr("\n--- ENCODING ---\n"));
296 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile);
297 CHECK_STATUS(m_abort, ok);
300 log(tr("\n--- DONE ---\n"));
301 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
302 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
303 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)));
304 setStatus(JobStatus_Completed);
307 bool EncodeThread::runEncodingPass(bool x264_x64, bool x264_10bit, bool avs2yuv_x64, bool usePipe, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
309 QProcess processEncode, processAvisynth;
313 QStringList cmdLine_Avisynth;
314 if(!m_options->customAvs2YUV().isEmpty())
316 cmdLine_Avisynth.append(splitParams(m_options->customAvs2YUV()));
318 cmdLine_Avisynth << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
319 cmdLine_Avisynth << "-";
320 processAvisynth.setStandardOutputProcess(&processEncode);
322 log("Creating Avisynth process:");
323 if(!startProcess(processAvisynth, QString("%1/%2.exe").arg(m_binDir, avs2yuv_x64 ? "avs2yuv_x64" : "avs2yuv_x86"), cmdLine_Avisynth, false))
329 QStringList cmdLine_Encode = buildCommandLine(usePipe, x264_10bit, frames, indexFile, pass, passLogFile);
331 log("Creating x264 process:");
332 if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
337 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
338 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
339 QRegExp regExpFrameCnt("^(\\d+) frames:");
341 QTextCodec *localCodec = QTextCodec::codecForName("System");
343 bool bTimeout = false;
344 bool bAborted = false;
346 unsigned int last_progress = UINT_MAX;
347 unsigned int last_indexing = UINT_MAX;
348 qint64 size_estimate = 0I64;
350 //Main processing loop
351 while(processEncode.state() != QProcess::NotRunning)
353 unsigned int waitCounter = 0;
355 //Wait until new output is available
360 processEncode.kill();
361 processAvisynth.kill();
365 if(m_pause && (processEncode.state() == QProcess::Running))
367 JobStatus previousStatus = m_status;
368 setStatus(JobStatus_Paused);
369 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
370 bool ok[2] = {false, false};
371 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
372 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
373 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
374 while(m_pause) m_semaphorePaused.acquire();
375 while(m_semaphorePaused.tryAcquire(1, 0));
376 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
377 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
378 if(!m_abort) setStatus(previousStatus);
379 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
383 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
385 if(processEncode.state() == QProcess::Running)
387 if(waitCounter++ > m_processTimeoutMaxCounter)
389 processEncode.kill();
390 qWarning("x264 process timed out <-- killing!");
391 log("\nPROCESS TIMEOUT !!!");
395 else if(waitCounter == m_processTimeoutWarning)
397 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
398 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
403 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
410 //Exit main processing loop now?
411 if(bAborted || bTimeout)
417 while(processEncode.bytesAvailable() > 0)
419 QList<QByteArray> lines = processEncode.readLine().split('\r');
420 while(!lines.isEmpty())
422 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
424 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
427 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
428 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
429 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX)))
431 setProgress(progress);
432 size_estimate = estimateSize(progress);
433 last_progress = progress;
435 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate)));
436 last_indexing = UINT_MAX;
438 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
441 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
442 setStatus(JobStatus_Indexing);
443 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
445 setProgress(progress);
446 last_indexing = progress;
448 setDetails(text.mid(offset).trimmed());
449 last_progress = UINT_MAX;
451 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
453 last_progress = last_indexing = UINT_MAX;
454 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
455 setDetails(text.mid(offset).trimmed());
457 else if(!text.isEmpty())
459 last_progress = last_indexing = UINT_MAX;
466 processEncode.waitForFinished(5000);
467 if(processEncode.state() != QProcess::NotRunning)
469 qWarning("x264 process still running, going to kill it!");
470 processEncode.kill();
471 processEncode.waitForFinished(-1);
474 processAvisynth.waitForFinished(5000);
475 if(processAvisynth.state() != QProcess::NotRunning)
477 qWarning("Avisynth process still running, going to kill it!");
478 processAvisynth.kill();
479 processAvisynth.waitForFinished(-1);
482 if(!(bTimeout || bAborted))
484 while(processAvisynth.bytesAvailable() > 0)
486 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
490 if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
492 if(!(bTimeout || bAborted))
494 log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
498 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
500 if(!(bTimeout || bAborted))
502 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
504 processEncode.close();
505 processAvisynth.close();
509 QThread::yieldCurrentThread();
511 const qint64 finalSize = QFileInfo(m_outputFileName).size();
512 QLocale locale(QLocale::English);
513 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
518 setStatus(JobStatus_Running_Pass1);
519 setDetails(tr("First pass completed. Preparing for second pass..."));
522 setStatus(JobStatus_Running_Pass2);
523 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
526 setStatus(JobStatus_Running);
527 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
532 processEncode.close();
533 processAvisynth.close();
537 QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
540 double crf_int = 0.0, crf_frc = 0.0;
542 switch(m_options->rcMode())
544 case OptionsModel::RCMode_CQ:
545 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
547 case OptionsModel::RCMode_CRF:
548 crf_frc = modf(m_options->quantizer(), &crf_int);
549 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
551 case OptionsModel::RCMode_2Pass:
552 case OptionsModel::RCMode_ABR:
553 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
556 throw "Bad rate-control mode !!!";
560 if((pass == 1) || (pass == 2))
562 cmdLine << "--pass" << QString::number(pass);
563 cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
566 cmdLine << "--preset" << m_options->preset().toLower();
568 if(m_options->tune().compare("none", Qt::CaseInsensitive))
570 cmdLine << "--tune" << m_options->tune().toLower();
573 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
577 if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
579 log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
583 cmdLine << "--profile" << m_options->profile().toLower();
588 cmdLine << "--profile" << m_options->profile().toLower();
592 if(!m_options->customX264().isEmpty())
594 QStringList customArgs = splitParams(m_options->customX264());
597 QStringList::iterator i = customArgs.begin();
598 while(i != customArgs.end())
600 bool bModified = false;
601 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
602 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
606 cmdLine.append(customArgs);
609 cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
613 if(frames < 1) throw "Frames not set!";
614 cmdLine << "--frames" << QString::number(frames);
615 cmdLine << "--demuxer" << "y4m";
616 cmdLine << "--stdin" << "y4m" << "-";
620 cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
621 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
627 unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
630 QStringList cmdLine = QStringList() << "--version";
632 log("Creating process:");
633 if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
638 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
639 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
641 bool bTimeout = false;
642 bool bAborted = false;
644 unsigned int revision = UINT_MAX;
645 unsigned int coreVers = UINT_MAX;
648 while(process.state() != QProcess::NotRunning)
656 if(!process.waitForReadyRead())
658 if(process.state() == QProcess::Running)
661 qWarning("x264 process timed out <-- killing!");
662 log("\nPROCESS TIMEOUT !!!");
667 while(process.bytesAvailable() > 0)
669 QList<QByteArray> lines = process.readLine().split('\r');
670 while(!lines.isEmpty())
672 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
674 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
676 bool ok1 = false, ok2 = false;
677 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
678 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
679 if(ok1) coreVers = temp1;
680 if(ok2) revision = temp2;
682 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
684 bool ok1 = false, ok2 = false;
685 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
686 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
687 if(ok1) coreVers = temp1;
688 if(ok2) revision = temp2;
699 process.waitForFinished();
700 if(process.state() != QProcess::NotRunning)
703 process.waitForFinished(-1);
706 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
708 if(!(bTimeout || bAborted))
710 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
715 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
717 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
721 return (coreVers * REV_MULT) + (revision % REV_MULT);
724 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
728 log("\nCreating process:");
729 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv_x86"), QStringList()))
734 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
735 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
737 bool bTimeout = false;
738 bool bAborted = false;
740 unsigned int ver_maj = UINT_MAX;
741 unsigned int ver_min = UINT_MAX;
742 unsigned int ver_mod = 0;
744 while(process.state() != QProcess::NotRunning)
752 if(!process.waitForReadyRead())
754 if(process.state() == QProcess::Running)
757 qWarning("Avs2YUV process timed out <-- killing!");
758 log("\nPROCESS TIMEOUT !!!");
763 while(process.bytesAvailable() > 0)
765 QList<QByteArray> lines = process.readLine().split('\r');
766 while(!lines.isEmpty())
768 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
770 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
777 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
779 bool ok1 = false, ok2 = false, ok3 = false;
780 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
781 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
782 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
783 if(ok1) ver_maj = temp1;
784 if(ok2) ver_min = temp2;
785 if(ok3) ver_mod = temp3;
787 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
789 bool ok1 = false, ok2 = false;
790 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
791 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
792 if(ok1) ver_maj = temp1;
793 if(ok2) ver_min = temp2;
799 process.waitForFinished();
800 if(process.state() != QProcess::NotRunning)
803 process.waitForFinished(-1);
806 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
808 if(!(bTimeout || bAborted))
810 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
815 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
817 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
821 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
824 bool EncodeThread::checkProperties(bool x64, unsigned int &frames)
829 if(!m_options->customAvs2YUV().isEmpty())
831 cmdLine.append(splitParams(m_options->customAvs2YUV()));
834 cmdLine << "-frames" << "1";
835 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
837 log("Creating process:");
838 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv_x86"), cmdLine))
843 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
844 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
846 QTextCodec *localCodec = QTextCodec::codecForName("System");
848 bool bTimeout = false;
849 bool bAborted = false;
853 unsigned int fpsNom = 0;
854 unsigned int fpsDen = 0;
855 unsigned int fSizeW = 0;
856 unsigned int fSizeH = 0;
858 unsigned int waitCounter = 0;
860 while(process.state() != QProcess::NotRunning)
868 if(!process.waitForReadyRead(m_processTimeoutInterval))
870 if(process.state() == QProcess::Running)
872 if(waitCounter++ > m_processTimeoutMaxCounter)
875 qWarning("Avs2YUV process timed out <-- killing!");
876 log("\nPROCESS TIMEOUT !!!");
877 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
881 else if(waitCounter == m_processTimeoutWarning)
883 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
884 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
892 while(process.bytesAvailable() > 0)
894 QList<QByteArray> lines = process.readLine().split('\r');
895 while(!lines.isEmpty())
897 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
899 if((offset = regExpInt.lastIndexIn(text)) >= 0)
901 bool ok1 = false, ok2 = false;
902 bool ok3 = false, ok4 = false;
903 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
904 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
905 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
906 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
907 if(ok1) fSizeW = temp1;
908 if(ok2) fSizeH = temp2;
909 if(ok3) fpsNom = temp3;
910 if(ok4) frames = temp4;
912 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
914 bool ok1 = false, ok2 = false;
915 bool ok3 = false, ok4 = false, ok5 = false;
916 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
917 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
918 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
919 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
920 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
921 if(ok1) fSizeW = temp1;
922 if(ok2) fSizeH = temp2;
923 if(ok3) fpsNom = temp3;
924 if(ok4) fpsDen = temp4;
925 if(ok5) frames = temp5;
931 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
933 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
935 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
937 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
943 process.waitForFinished();
944 if(process.state() != QProcess::NotRunning)
947 process.waitForFinished(-1);
950 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
952 if(!(bTimeout || bAborted))
954 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
961 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
967 if((fSizeW > 0) && (fSizeH > 0))
969 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
971 if((fpsNom > 0) && (fpsDen > 0))
973 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
975 if((fpsNom > 0) && (fpsDen == 0))
977 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
981 log(tr("No. Frames: %1").arg(QString::number(frames)));
987 ///////////////////////////////////////////////////////////////////////////////
989 ///////////////////////////////////////////////////////////////////////////////
991 void EncodeThread::setStatus(JobStatus newStatus)
993 if(m_status != newStatus)
995 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
997 if(m_status != JobStatus_Paused) setProgress(0);
999 if(newStatus == JobStatus_Failed)
1001 setDetails("The job has failed. See log for details!");
1003 if(newStatus == JobStatus_Aborted)
1005 setDetails("The job was aborted by the user!");
1007 m_status = newStatus;
1008 emit statusChanged(m_jobId, newStatus);
1012 void EncodeThread::setProgress(unsigned int newProgress)
1014 if(m_progress != newProgress)
1016 m_progress = newProgress;
1017 emit progressChanged(m_jobId, m_progress);
1021 void EncodeThread::setDetails(const QString &text)
1023 emit detailsChanged(m_jobId, text);
1026 QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
1028 QTextCodec *localCodec = QTextCodec::codecForName("System");
1030 //Do NOT convert to short, if path can be represented in local Codepage
1031 if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
1036 //Create dummy file, if required (only existing files can have a short path!)
1038 if((!QFileInfo(longPath).exists()) && create)
1040 tempFile.setFileName(longPath);
1041 tempFile.open(QIODevice::WriteOnly);
1045 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1049 wchar_t *buffer = new wchar_t[buffSize];
1050 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1052 if(result > 0 && result < buffSize)
1054 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1061 //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
1062 if(tempFile.isOpen())
1064 if(!keep) tempFile.remove();
1068 if(shortPath.isEmpty())
1070 log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
1073 return (shortPath.isEmpty() ? longPath : shortPath);
1076 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1078 QMutexLocker lock(&m_mutex_startProcess);
1079 log(commandline2string(program, args) + "\n");
1081 //Create a new job object, if not done yet
1082 if(!m_handle_jobObject)
1084 m_handle_jobObject = CreateJobObject(NULL, NULL);
1085 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
1087 m_handle_jobObject = NULL;
1089 if(m_handle_jobObject)
1091 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
1092 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1093 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
1094 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1100 process.setProcessChannelMode(QProcess::MergedChannels);
1101 process.setReadChannel(QProcess::StandardOutput);
1105 process.setProcessChannelMode(QProcess::SeparateChannels);
1106 process.setReadChannel(QProcess::StandardError);
1109 process.start(program, args);
1111 if(process.waitForStarted())
1113 Q_PID pid = process.pid();
1114 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1117 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
1119 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
1127 log("Process creation has failed :-(");
1128 QString errorMsg= process.errorString().trimmed();
1129 if(!errorMsg.isEmpty()) log(errorMsg);
1132 process.waitForFinished(-1);
1136 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1138 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1140 for(int i = 0; i < arguments.count(); i++)
1142 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1148 QStringList EncodeThread::splitParams(const QString ¶ms)
1151 bool ignoreWhitespaces = false;
1154 for(int i = 0; i < params.length(); i++)
1156 const QChar c = params.at(i);
1158 if(c == QChar::fromLatin1('"'))
1160 ignoreWhitespaces = (!ignoreWhitespaces);
1163 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1165 APPEND_AND_CLEAR(list, temp);
1172 APPEND_AND_CLEAR(list, temp);
1174 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1175 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1180 qint64 EncodeThread::estimateSize(int progress)
1184 qint64 currentSize = QFileInfo(m_outputFileName).size();
1185 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1186 return estimatedSize;
1192 QString EncodeThread::sizeToString(qint64 size)
1194 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1198 qint64 estimatedSize = size;
1199 qint64 remainderSize = 0I64;
1202 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1204 remainderSize = estimatedSize % 1024I64;
1205 estimatedSize = estimatedSize / 1024I64;
1209 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1210 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);