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) \
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); \
65 #define APPEND_AND_CLEAR(LIST, STR) \
67 if(!((STR).isEmpty())) \
74 #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"))
79 static const unsigned int REV_MULT = 10000;
81 ///////////////////////////////////////////////////////////////////////////////
82 // Constructor & Destructor
83 ///////////////////////////////////////////////////////////////////////////////
85 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x264_x64, bool x264_10bit, bool avs2yuv_x64)
87 m_jobId(QUuid::createUuid()),
88 m_sourceFileName(sourceFileName),
89 m_outputFileName(outputFileName),
90 m_options(new OptionsModel(*options)),
93 m_x264_10bit(x264_10bit),
94 m_avs2yuv_x64(avs2yuv_x64),
95 m_handle_jobObject(NULL),
102 EncodeThread::~EncodeThread(void)
104 X264_DELETE(m_options);
106 if(m_handle_jobObject)
108 CloseHandle(m_handle_jobObject);
109 m_handle_jobObject = NULL;
113 ///////////////////////////////////////////////////////////////////////////////
114 // Thread entry point
115 ///////////////////////////////////////////////////////////////////////////////
117 void EncodeThread::run(void)
125 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
128 if(m_handle_jobObject)
130 TerminateJobObject(m_handle_jobObject, 42);
131 m_handle_jobObject = NULL;
135 void EncodeThread::checkedRun(void)
138 m_status = JobStatus_Starting;
148 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
149 setStatus(JobStatus_Failed);
153 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
154 setStatus(JobStatus_Failed);
159 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
163 void EncodeThread::start(Priority priority)
165 qDebug("Thread starting...");
170 while(m_semaphorePaused.tryAcquire(1, 0));
171 QThread::start(priority);
174 ///////////////////////////////////////////////////////////////////////////////
176 ///////////////////////////////////////////////////////////////////////////////
178 void EncodeThread::encode(void)
180 QDateTime startTime = QDateTime::currentDateTime();
182 //Print some basic info
183 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
184 log(tr("Source file: %1").arg(m_sourceFileName));
185 log(tr("Output file: %1").arg(m_outputFileName));
187 //Print encoder settings
188 log(tr("\n--- SETTINGS ---\n"));
189 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
190 log(tr("Preset: %1").arg(m_options->preset()));
191 log(tr("Tuning: %1").arg(m_options->tune()));
192 log(tr("Profile: %1").arg(m_options->profile()));
193 log(tr("Custom: %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
196 unsigned int frames = 0;
199 const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
200 const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
202 //Checking x264 version
203 log(tr("\n--- CHECK VERSION ---\n"));
204 unsigned int revision_x264 = UINT_MAX;
205 bool x264_modified = false;
206 ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
207 CHECK_STATUS(m_abort, ok);
209 //Checking avs2yuv version
210 unsigned int revision_avs2yuv = UINT_MAX;
213 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
214 CHECK_STATUS(m_abort, ok);
218 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()));
219 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)));
221 //Is x264 revision supported?
222 if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
224 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
225 setStatus(JobStatus_Failed);
228 if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
230 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
231 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
233 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
235 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
236 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
237 setStatus(JobStatus_Failed);
244 log(tr("\n--- AVS INFO ---\n"));
245 ok = checkProperties(m_avs2yuv_x64, frames);
246 CHECK_STATUS(m_abort, ok);
249 //Run encoding passes
250 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
252 QFileInfo info(m_outputFileName);
253 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
255 if(QFileInfo(passLogFile).exists())
258 while(QFileInfo(passLogFile).exists())
260 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
264 log(tr("\n--- PASS 1 ---\n"));
265 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile, 1, passLogFile);
266 CHECK_STATUS(m_abort, ok);
268 log(tr("\n--- PASS 2 ---\n"));
269 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile, 2, passLogFile);
270 CHECK_STATUS(m_abort, ok);
274 log(tr("\n--- ENCODING ---\n"));
275 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile);
276 CHECK_STATUS(m_abort, ok);
279 log(tr("\n--- DONE ---\n"));
280 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
281 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
282 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)));
283 setStatus(JobStatus_Completed);
286 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)
288 QProcess processEncode, processAvisynth;
292 QStringList cmdLine_Avisynth;
293 if(!m_options->customAvs2YUV().isEmpty())
295 cmdLine_Avisynth.append(splitParams(m_options->customAvs2YUV()));
297 cmdLine_Avisynth << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
298 cmdLine_Avisynth << "-";
299 processAvisynth.setStandardOutputProcess(&processEncode);
301 log("Creating Avisynth process:");
302 if(!startProcess(processAvisynth, QString("%1/%2.exe").arg(m_binDir, avs2yuv_x64 ? "avs2yuv_x64" : "avs2yuv"), cmdLine_Avisynth, false))
308 QStringList cmdLine_Encode = buildCommandLine(usePipe, x264_10bit, frames, indexFile, pass, passLogFile);
310 log("Creating x264 process:");
311 if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
316 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
317 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
318 QRegExp regExpFrameCnt("^(\\d+) frames:");
320 QTextCodec *localCodec = QTextCodec::codecForName("System");
322 bool bTimeout = false;
323 bool bAborted = false;
325 unsigned int last_progress = UINT_MAX;
326 unsigned int last_indexing = UINT_MAX;
327 qint64 size_estimate = 0I64;
329 //Main processing loop
330 while(processEncode.state() != QProcess::NotRunning)
332 unsigned int waitCounter = 0;
334 //Wait until new output is available
339 processEncode.kill();
340 processAvisynth.kill();
344 if(m_pause && (processEncode.state() == QProcess::Running))
346 JobStatus previousStatus = m_status;
347 setStatus(JobStatus_Paused);
348 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
349 bool ok[2] = {false, false};
350 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
351 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
352 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
353 while(m_pause) m_semaphorePaused.acquire();
354 while(m_semaphorePaused.tryAcquire(1, 0));
355 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
356 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
357 if(!m_abort) setStatus(previousStatus);
358 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
362 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
364 if(processEncode.state() == QProcess::Running)
366 if(waitCounter++ > m_processTimeoutMaxCounter)
368 processEncode.kill();
369 qWarning("x264 process timed out <-- killing!");
370 log("\nPROCESS TIMEOUT !!!");
374 else if(waitCounter == m_processTimeoutWarning)
376 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
377 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
382 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
389 //Exit main processing loop now?
390 if(bAborted || bTimeout)
396 while(processEncode.bytesAvailable() > 0)
398 QList<QByteArray> lines = processEncode.readLine().split('\r');
399 while(!lines.isEmpty())
401 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
403 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
406 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
407 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
408 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX)))
410 setProgress(progress);
411 size_estimate = estimateSize(progress);
412 last_progress = progress;
414 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate)));
415 last_indexing = UINT_MAX;
417 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
420 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
421 setStatus(JobStatus_Indexing);
422 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
424 setProgress(progress);
425 last_indexing = progress;
427 setDetails(text.mid(offset).trimmed());
428 last_progress = UINT_MAX;
430 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
432 last_progress = last_indexing = UINT_MAX;
433 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
434 setDetails(text.mid(offset).trimmed());
436 else if(!text.isEmpty())
438 last_progress = last_indexing = UINT_MAX;
445 processEncode.waitForFinished(5000);
446 if(processEncode.state() != QProcess::NotRunning)
448 qWarning("x264 process still running, going to kill it!");
449 processEncode.kill();
450 processEncode.waitForFinished(-1);
453 processAvisynth.waitForFinished(5000);
454 if(processAvisynth.state() != QProcess::NotRunning)
456 qWarning("Avisynth process still running, going to kill it!");
457 processAvisynth.kill();
458 processAvisynth.waitForFinished(-1);
461 if(!(bTimeout || bAborted))
463 while(processAvisynth.bytesAvailable() > 0)
465 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
469 if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
471 if(!(bTimeout || bAborted))
473 log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
477 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
479 if(!(bTimeout || bAborted))
481 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
483 processEncode.close();
484 processAvisynth.close();
488 QThread::yieldCurrentThread();
490 const qint64 finalSize = QFileInfo(m_outputFileName).size();
491 QLocale locale(QLocale::English);
492 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
497 setStatus(JobStatus_Running_Pass1);
498 setDetails(tr("First pass completed. Preparing for second pass..."));
501 setStatus(JobStatus_Running_Pass2);
502 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
505 setStatus(JobStatus_Running);
506 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
511 processEncode.close();
512 processAvisynth.close();
516 QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
519 double crf_int = 0.0, crf_frc = 0.0;
521 switch(m_options->rcMode())
523 case OptionsModel::RCMode_CQ:
524 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
526 case OptionsModel::RCMode_CRF:
527 crf_frc = modf(m_options->quantizer(), &crf_int);
528 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
530 case OptionsModel::RCMode_2Pass:
531 case OptionsModel::RCMode_ABR:
532 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
535 throw "Bad rate-control mode !!!";
539 if((pass == 1) || (pass == 2))
541 cmdLine << "--pass" << QString::number(pass);
542 cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
545 cmdLine << "--preset" << m_options->preset().toLower();
547 if(m_options->tune().compare("none", Qt::CaseInsensitive))
549 cmdLine << "--tune" << m_options->tune().toLower();
552 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
556 if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
558 log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
562 cmdLine << "--profile" << m_options->profile().toLower();
567 cmdLine << "--profile" << m_options->profile().toLower();
571 if(!m_options->customX264().isEmpty())
573 cmdLine.append(splitParams(m_options->customX264()));
576 cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
580 if(frames < 1) throw "Frames not set!";
581 cmdLine << "--frames" << QString::number(frames);
582 cmdLine << "--demuxer" << "y4m";
583 cmdLine << "--stdin" << "y4m" << "-";
587 cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
588 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
594 unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
597 QStringList cmdLine = QStringList() << "--version";
599 log("Creating process:");
600 if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
605 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
606 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
608 bool bTimeout = false;
609 bool bAborted = false;
611 unsigned int revision = UINT_MAX;
612 unsigned int coreVers = UINT_MAX;
615 while(process.state() != QProcess::NotRunning)
623 if(!process.waitForReadyRead())
625 if(process.state() == QProcess::Running)
628 qWarning("x264 process timed out <-- killing!");
629 log("\nPROCESS TIMEOUT !!!");
634 while(process.bytesAvailable() > 0)
636 QList<QByteArray> lines = process.readLine().split('\r');
637 while(!lines.isEmpty())
639 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
641 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
643 bool ok1 = false, ok2 = false;
644 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
645 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
646 if(ok1) coreVers = temp1;
647 if(ok2) revision = temp2;
649 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
651 bool ok1 = false, ok2 = false;
652 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
653 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
654 if(ok1) coreVers = temp1;
655 if(ok2) revision = temp2;
666 process.waitForFinished();
667 if(process.state() != QProcess::NotRunning)
670 process.waitForFinished(-1);
673 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
675 if(!(bTimeout || bAborted))
677 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
682 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
684 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
688 return (coreVers * REV_MULT) + (revision % REV_MULT);
691 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
695 log("\nCreating process:");
696 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv"), QStringList()))
701 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
702 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
704 bool bTimeout = false;
705 bool bAborted = false;
707 unsigned int ver_maj = UINT_MAX;
708 unsigned int ver_min = UINT_MAX;
709 unsigned int ver_mod = 0;
711 while(process.state() != QProcess::NotRunning)
719 if(!process.waitForReadyRead())
721 if(process.state() == QProcess::Running)
724 qWarning("Avs2YUV process timed out <-- killing!");
725 log("\nPROCESS TIMEOUT !!!");
730 while(process.bytesAvailable() > 0)
732 QList<QByteArray> lines = process.readLine().split('\r');
733 while(!lines.isEmpty())
735 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
737 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
744 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
746 bool ok1 = false, ok2 = false, ok3 = false;
747 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
748 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
749 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
750 if(ok1) ver_maj = temp1;
751 if(ok2) ver_min = temp2;
752 if(ok3) ver_mod = temp3;
754 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
756 bool ok1 = false, ok2 = false;
757 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
758 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
759 if(ok1) ver_maj = temp1;
760 if(ok2) ver_min = temp2;
766 process.waitForFinished();
767 if(process.state() != QProcess::NotRunning)
770 process.waitForFinished(-1);
773 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
775 if(!(bTimeout || bAborted))
777 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
782 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
784 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
788 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
791 bool EncodeThread::checkProperties(bool x64, unsigned int &frames)
796 if(!m_options->customAvs2YUV().isEmpty())
798 cmdLine.append(splitParams(m_options->customAvs2YUV()));
801 cmdLine << "-frames" << "1";
802 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
804 log("Creating process:");
805 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv"), cmdLine))
810 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
811 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
813 QTextCodec *localCodec = QTextCodec::codecForName("System");
815 bool bTimeout = false;
816 bool bAborted = false;
820 unsigned int fpsNom = 0;
821 unsigned int fpsDen = 0;
822 unsigned int fSizeW = 0;
823 unsigned int fSizeH = 0;
825 unsigned int waitCounter = 0;
827 while(process.state() != QProcess::NotRunning)
835 if(!process.waitForReadyRead(m_processTimeoutInterval))
837 if(process.state() == QProcess::Running)
839 if(waitCounter++ > m_processTimeoutMaxCounter)
842 qWarning("Avs2YUV process timed out <-- killing!");
843 log("\nPROCESS TIMEOUT !!!");
844 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
848 else if(waitCounter == m_processTimeoutWarning)
850 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
851 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
859 while(process.bytesAvailable() > 0)
861 QList<QByteArray> lines = process.readLine().split('\r');
862 while(!lines.isEmpty())
864 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
866 if((offset = regExpInt.lastIndexIn(text)) >= 0)
868 bool ok1 = false, ok2 = false;
869 bool ok3 = false, ok4 = false;
870 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
871 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
872 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
873 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
874 if(ok1) fSizeW = temp1;
875 if(ok2) fSizeH = temp2;
876 if(ok3) fpsNom = temp3;
877 if(ok4) frames = temp4;
879 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
881 bool ok1 = false, ok2 = false;
882 bool ok3 = false, ok4 = false, ok5 = false;
883 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
884 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
885 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
886 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
887 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
888 if(ok1) fSizeW = temp1;
889 if(ok2) fSizeH = temp2;
890 if(ok3) fpsNom = temp3;
891 if(ok4) fpsDen = temp4;
892 if(ok5) frames = temp5;
898 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
900 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
902 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
904 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
910 process.waitForFinished();
911 if(process.state() != QProcess::NotRunning)
914 process.waitForFinished(-1);
917 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
919 if(!(bTimeout || bAborted))
921 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
928 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
934 if((fSizeW > 0) && (fSizeH > 0))
936 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
938 if((fpsNom > 0) && (fpsDen > 0))
940 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
942 if((fpsNom > 0) && (fpsDen == 0))
944 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
948 log(tr("No. Frames: %1").arg(QString::number(frames)));
954 ///////////////////////////////////////////////////////////////////////////////
956 ///////////////////////////////////////////////////////////////////////////////
958 void EncodeThread::setStatus(JobStatus newStatus)
960 if(m_status != newStatus)
962 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
964 if(m_status != JobStatus_Paused) setProgress(0);
966 if(newStatus == JobStatus_Failed)
968 setDetails("The job has failed. See log for details!");
970 if(newStatus == JobStatus_Aborted)
972 setDetails("The job was aborted by the user!");
974 m_status = newStatus;
975 emit statusChanged(m_jobId, newStatus);
979 void EncodeThread::setProgress(unsigned int newProgress)
981 if(m_progress != newProgress)
983 m_progress = newProgress;
984 emit progressChanged(m_jobId, m_progress);
988 void EncodeThread::setDetails(const QString &text)
990 emit detailsChanged(m_jobId, text);
993 QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
995 QTextCodec *localCodec = QTextCodec::codecForName("System");
997 //Do NOT convert to short, if path can be represented in local Codepage
998 if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
1003 //Create dummy file, if required (only existing files can have a short path!)
1005 if((!QFileInfo(longPath).exists()) && create)
1007 tempFile.setFileName(longPath);
1008 tempFile.open(QIODevice::WriteOnly);
1012 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1016 wchar_t *buffer = new wchar_t[buffSize];
1017 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1019 if(result > 0 && result < buffSize)
1021 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1028 //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
1029 if(tempFile.isOpen())
1031 if(!keep) tempFile.remove();
1035 if(shortPath.isEmpty())
1037 log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
1040 return (shortPath.isEmpty() ? longPath : shortPath);
1043 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1045 QMutexLocker lock(&m_mutex_startProcess);
1046 log(commandline2string(program, args) + "\n");
1048 //Create a new job object, if not done yet
1049 if(!m_handle_jobObject)
1051 m_handle_jobObject = CreateJobObject(NULL, NULL);
1052 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
1054 m_handle_jobObject = NULL;
1056 if(m_handle_jobObject)
1058 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
1059 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1060 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
1061 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1067 process.setProcessChannelMode(QProcess::MergedChannels);
1068 process.setReadChannel(QProcess::StandardOutput);
1072 process.setProcessChannelMode(QProcess::SeparateChannels);
1073 process.setReadChannel(QProcess::StandardError);
1076 process.start(program, args);
1078 if(process.waitForStarted())
1080 Q_PID pid = process.pid();
1081 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1084 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
1086 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
1094 log("Process creation has failed :-(");
1095 QString errorMsg= process.errorString().trimmed();
1096 if(!errorMsg.isEmpty()) log(errorMsg);
1099 process.waitForFinished(-1);
1103 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1105 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1107 for(int i = 0; i < arguments.count(); i++)
1109 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1115 QStringList EncodeThread::splitParams(const QString ¶ms)
1118 bool ignoreWhitespaces = false;
1121 for(int i = 0; i < params.length(); i++)
1123 const QChar c = params.at(i);
1125 if(c == QChar::fromLatin1('"'))
1127 ignoreWhitespaces = (!ignoreWhitespaces);
1130 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1132 APPEND_AND_CLEAR(list, temp);
1139 APPEND_AND_CLEAR(list, temp);
1141 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1142 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1147 qint64 EncodeThread::estimateSize(int progress)
1151 qint64 currentSize = QFileInfo(m_outputFileName).size();
1152 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1153 return estimatedSize;
1159 QString EncodeThread::sizeToString(qint64 size)
1161 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1165 qint64 estimatedSize = size;
1166 qint64 remainderSize = 0I64;
1169 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1171 remainderSize = estimatedSize % 1024I64;
1172 estimatedSize = estimatedSize / 1024I64;
1176 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1177 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);