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("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
184 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
185 log(tr("Source file: %1").arg(m_sourceFileName));
186 log(tr("Output file: %1").arg(m_outputFileName));
188 //Print encoder settings
189 log(tr("\n--- SETTINGS ---\n"));
190 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
191 log(tr("Preset: %1").arg(m_options->preset()));
192 log(tr("Tuning: %1").arg(m_options->tune()));
193 log(tr("Profile: %1").arg(m_options->profile()));
194 log(tr("Custom: %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
197 unsigned int frames = 0;
200 const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
201 const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
203 //Checking x264 version
204 log(tr("\n--- CHECK VERSION ---\n"));
205 unsigned int revision_x264 = UINT_MAX;
206 bool x264_modified = false;
207 ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
208 CHECK_STATUS(m_abort, ok);
210 //Checking avs2yuv version
211 unsigned int revision_avs2yuv = UINT_MAX;
214 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
215 CHECK_STATUS(m_abort, ok);
219 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()));
220 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)));
222 //Is x264 revision supported?
223 if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
225 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
226 setStatus(JobStatus_Failed);
229 if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
231 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
232 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
234 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
236 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
237 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
238 setStatus(JobStatus_Failed);
245 log(tr("\n--- AVS INFO ---\n"));
246 ok = checkProperties(m_avs2yuv_x64, frames);
247 CHECK_STATUS(m_abort, ok);
250 //Run encoding passes
251 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
253 QFileInfo info(m_outputFileName);
254 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
256 if(QFileInfo(passLogFile).exists())
259 while(QFileInfo(passLogFile).exists())
261 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
265 log(tr("\n--- PASS 1 ---\n"));
266 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile, 1, passLogFile);
267 CHECK_STATUS(m_abort, ok);
269 log(tr("\n--- PASS 2 ---\n"));
270 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile, 2, passLogFile);
271 CHECK_STATUS(m_abort, ok);
275 log(tr("\n--- ENCODING ---\n"));
276 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile);
277 CHECK_STATUS(m_abort, ok);
280 log(tr("\n--- DONE ---\n"));
281 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
282 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
283 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)));
284 setStatus(JobStatus_Completed);
287 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)
289 QProcess processEncode, processAvisynth;
293 QStringList cmdLine_Avisynth;
294 if(!m_options->customAvs2YUV().isEmpty())
296 cmdLine_Avisynth.append(splitParams(m_options->customAvs2YUV()));
298 cmdLine_Avisynth << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
299 cmdLine_Avisynth << "-";
300 processAvisynth.setStandardOutputProcess(&processEncode);
302 log("Creating Avisynth process:");
303 if(!startProcess(processAvisynth, QString("%1/%2.exe").arg(m_binDir, avs2yuv_x64 ? "avs2yuv_x64" : "avs2yuv_x86"), cmdLine_Avisynth, false))
309 QStringList cmdLine_Encode = buildCommandLine(usePipe, x264_10bit, frames, indexFile, pass, passLogFile);
311 log("Creating x264 process:");
312 if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
317 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
318 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
319 QRegExp regExpFrameCnt("^(\\d+) frames:");
321 QTextCodec *localCodec = QTextCodec::codecForName("System");
323 bool bTimeout = false;
324 bool bAborted = false;
326 unsigned int last_progress = UINT_MAX;
327 unsigned int last_indexing = UINT_MAX;
328 qint64 size_estimate = 0I64;
330 //Main processing loop
331 while(processEncode.state() != QProcess::NotRunning)
333 unsigned int waitCounter = 0;
335 //Wait until new output is available
340 processEncode.kill();
341 processAvisynth.kill();
345 if(m_pause && (processEncode.state() == QProcess::Running))
347 JobStatus previousStatus = m_status;
348 setStatus(JobStatus_Paused);
349 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
350 bool ok[2] = {false, false};
351 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
352 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
353 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
354 while(m_pause) m_semaphorePaused.acquire();
355 while(m_semaphorePaused.tryAcquire(1, 0));
356 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
357 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
358 if(!m_abort) setStatus(previousStatus);
359 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
363 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
365 if(processEncode.state() == QProcess::Running)
367 if(waitCounter++ > m_processTimeoutMaxCounter)
369 processEncode.kill();
370 qWarning("x264 process timed out <-- killing!");
371 log("\nPROCESS TIMEOUT !!!");
375 else if(waitCounter == m_processTimeoutWarning)
377 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
378 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
383 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
390 //Exit main processing loop now?
391 if(bAborted || bTimeout)
397 while(processEncode.bytesAvailable() > 0)
399 QList<QByteArray> lines = processEncode.readLine().split('\r');
400 while(!lines.isEmpty())
402 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
404 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
407 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
408 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
409 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX)))
411 setProgress(progress);
412 size_estimate = estimateSize(progress);
413 last_progress = progress;
415 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate)));
416 last_indexing = UINT_MAX;
418 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
421 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
422 setStatus(JobStatus_Indexing);
423 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
425 setProgress(progress);
426 last_indexing = progress;
428 setDetails(text.mid(offset).trimmed());
429 last_progress = UINT_MAX;
431 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
433 last_progress = last_indexing = UINT_MAX;
434 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
435 setDetails(text.mid(offset).trimmed());
437 else if(!text.isEmpty())
439 last_progress = last_indexing = UINT_MAX;
446 processEncode.waitForFinished(5000);
447 if(processEncode.state() != QProcess::NotRunning)
449 qWarning("x264 process still running, going to kill it!");
450 processEncode.kill();
451 processEncode.waitForFinished(-1);
454 processAvisynth.waitForFinished(5000);
455 if(processAvisynth.state() != QProcess::NotRunning)
457 qWarning("Avisynth process still running, going to kill it!");
458 processAvisynth.kill();
459 processAvisynth.waitForFinished(-1);
462 if(!(bTimeout || bAborted))
464 while(processAvisynth.bytesAvailable() > 0)
466 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
470 if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
472 if(!(bTimeout || bAborted))
474 log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
478 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
480 if(!(bTimeout || bAborted))
482 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
484 processEncode.close();
485 processAvisynth.close();
489 QThread::yieldCurrentThread();
491 const qint64 finalSize = QFileInfo(m_outputFileName).size();
492 QLocale locale(QLocale::English);
493 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
498 setStatus(JobStatus_Running_Pass1);
499 setDetails(tr("First pass completed. Preparing for second pass..."));
502 setStatus(JobStatus_Running_Pass2);
503 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
506 setStatus(JobStatus_Running);
507 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
512 processEncode.close();
513 processAvisynth.close();
517 QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
520 double crf_int = 0.0, crf_frc = 0.0;
522 switch(m_options->rcMode())
524 case OptionsModel::RCMode_CQ:
525 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
527 case OptionsModel::RCMode_CRF:
528 crf_frc = modf(m_options->quantizer(), &crf_int);
529 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
531 case OptionsModel::RCMode_2Pass:
532 case OptionsModel::RCMode_ABR:
533 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
536 throw "Bad rate-control mode !!!";
540 if((pass == 1) || (pass == 2))
542 cmdLine << "--pass" << QString::number(pass);
543 cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
546 cmdLine << "--preset" << m_options->preset().toLower();
548 if(m_options->tune().compare("none", Qt::CaseInsensitive))
550 cmdLine << "--tune" << m_options->tune().toLower();
553 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
557 if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
559 log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
563 cmdLine << "--profile" << m_options->profile().toLower();
568 cmdLine << "--profile" << m_options->profile().toLower();
572 if(!m_options->customX264().isEmpty())
574 cmdLine.append(splitParams(m_options->customX264()));
577 cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
581 if(frames < 1) throw "Frames not set!";
582 cmdLine << "--frames" << QString::number(frames);
583 cmdLine << "--demuxer" << "y4m";
584 cmdLine << "--stdin" << "y4m" << "-";
588 cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
589 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
595 unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
598 QStringList cmdLine = QStringList() << "--version";
600 log("Creating process:");
601 if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
606 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
607 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
609 bool bTimeout = false;
610 bool bAborted = false;
612 unsigned int revision = UINT_MAX;
613 unsigned int coreVers = UINT_MAX;
616 while(process.state() != QProcess::NotRunning)
624 if(!process.waitForReadyRead())
626 if(process.state() == QProcess::Running)
629 qWarning("x264 process timed out <-- killing!");
630 log("\nPROCESS TIMEOUT !!!");
635 while(process.bytesAvailable() > 0)
637 QList<QByteArray> lines = process.readLine().split('\r');
638 while(!lines.isEmpty())
640 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
642 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
644 bool ok1 = false, ok2 = false;
645 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
646 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
647 if(ok1) coreVers = temp1;
648 if(ok2) revision = temp2;
650 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
652 bool ok1 = false, ok2 = false;
653 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
654 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
655 if(ok1) coreVers = temp1;
656 if(ok2) revision = temp2;
667 process.waitForFinished();
668 if(process.state() != QProcess::NotRunning)
671 process.waitForFinished(-1);
674 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
676 if(!(bTimeout || bAborted))
678 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
683 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
685 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
689 return (coreVers * REV_MULT) + (revision % REV_MULT);
692 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
696 log("\nCreating process:");
697 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv_x86"), QStringList()))
702 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
703 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
705 bool bTimeout = false;
706 bool bAborted = false;
708 unsigned int ver_maj = UINT_MAX;
709 unsigned int ver_min = UINT_MAX;
710 unsigned int ver_mod = 0;
712 while(process.state() != QProcess::NotRunning)
720 if(!process.waitForReadyRead())
722 if(process.state() == QProcess::Running)
725 qWarning("Avs2YUV process timed out <-- killing!");
726 log("\nPROCESS TIMEOUT !!!");
731 while(process.bytesAvailable() > 0)
733 QList<QByteArray> lines = process.readLine().split('\r');
734 while(!lines.isEmpty())
736 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
738 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
745 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
747 bool ok1 = false, ok2 = false, ok3 = false;
748 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
749 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
750 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
751 if(ok1) ver_maj = temp1;
752 if(ok2) ver_min = temp2;
753 if(ok3) ver_mod = temp3;
755 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
757 bool ok1 = false, ok2 = false;
758 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
759 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
760 if(ok1) ver_maj = temp1;
761 if(ok2) ver_min = temp2;
767 process.waitForFinished();
768 if(process.state() != QProcess::NotRunning)
771 process.waitForFinished(-1);
774 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
776 if(!(bTimeout || bAborted))
778 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
783 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
785 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
789 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
792 bool EncodeThread::checkProperties(bool x64, unsigned int &frames)
797 if(!m_options->customAvs2YUV().isEmpty())
799 cmdLine.append(splitParams(m_options->customAvs2YUV()));
802 cmdLine << "-frames" << "1";
803 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
805 log("Creating process:");
806 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv_x86"), cmdLine))
811 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
812 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
814 QTextCodec *localCodec = QTextCodec::codecForName("System");
816 bool bTimeout = false;
817 bool bAborted = false;
821 unsigned int fpsNom = 0;
822 unsigned int fpsDen = 0;
823 unsigned int fSizeW = 0;
824 unsigned int fSizeH = 0;
826 unsigned int waitCounter = 0;
828 while(process.state() != QProcess::NotRunning)
836 if(!process.waitForReadyRead(m_processTimeoutInterval))
838 if(process.state() == QProcess::Running)
840 if(waitCounter++ > m_processTimeoutMaxCounter)
843 qWarning("Avs2YUV process timed out <-- killing!");
844 log("\nPROCESS TIMEOUT !!!");
845 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
849 else if(waitCounter == m_processTimeoutWarning)
851 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
852 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
860 while(process.bytesAvailable() > 0)
862 QList<QByteArray> lines = process.readLine().split('\r');
863 while(!lines.isEmpty())
865 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
867 if((offset = regExpInt.lastIndexIn(text)) >= 0)
869 bool ok1 = false, ok2 = false;
870 bool ok3 = false, ok4 = false;
871 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
872 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
873 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
874 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
875 if(ok1) fSizeW = temp1;
876 if(ok2) fSizeH = temp2;
877 if(ok3) fpsNom = temp3;
878 if(ok4) frames = temp4;
880 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
882 bool ok1 = false, ok2 = false;
883 bool ok3 = false, ok4 = false, ok5 = false;
884 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
885 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
886 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
887 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
888 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
889 if(ok1) fSizeW = temp1;
890 if(ok2) fSizeH = temp2;
891 if(ok3) fpsNom = temp3;
892 if(ok4) fpsDen = temp4;
893 if(ok5) frames = temp5;
899 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
901 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
903 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
905 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
911 process.waitForFinished();
912 if(process.state() != QProcess::NotRunning)
915 process.waitForFinished(-1);
918 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
920 if(!(bTimeout || bAborted))
922 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
929 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
935 if((fSizeW > 0) && (fSizeH > 0))
937 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
939 if((fpsNom > 0) && (fpsDen > 0))
941 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
943 if((fpsNom > 0) && (fpsDen == 0))
945 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
949 log(tr("No. Frames: %1").arg(QString::number(frames)));
955 ///////////////////////////////////////////////////////////////////////////////
957 ///////////////////////////////////////////////////////////////////////////////
959 void EncodeThread::setStatus(JobStatus newStatus)
961 if(m_status != newStatus)
963 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
965 if(m_status != JobStatus_Paused) setProgress(0);
967 if(newStatus == JobStatus_Failed)
969 setDetails("The job has failed. See log for details!");
971 if(newStatus == JobStatus_Aborted)
973 setDetails("The job was aborted by the user!");
975 m_status = newStatus;
976 emit statusChanged(m_jobId, newStatus);
980 void EncodeThread::setProgress(unsigned int newProgress)
982 if(m_progress != newProgress)
984 m_progress = newProgress;
985 emit progressChanged(m_jobId, m_progress);
989 void EncodeThread::setDetails(const QString &text)
991 emit detailsChanged(m_jobId, text);
994 QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
996 QTextCodec *localCodec = QTextCodec::codecForName("System");
998 //Do NOT convert to short, if path can be represented in local Codepage
999 if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
1004 //Create dummy file, if required (only existing files can have a short path!)
1006 if((!QFileInfo(longPath).exists()) && create)
1008 tempFile.setFileName(longPath);
1009 tempFile.open(QIODevice::WriteOnly);
1013 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1017 wchar_t *buffer = new wchar_t[buffSize];
1018 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1020 if(result > 0 && result < buffSize)
1022 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1029 //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
1030 if(tempFile.isOpen())
1032 if(!keep) tempFile.remove();
1036 if(shortPath.isEmpty())
1038 log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
1041 return (shortPath.isEmpty() ? longPath : shortPath);
1044 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1046 QMutexLocker lock(&m_mutex_startProcess);
1047 log(commandline2string(program, args) + "\n");
1049 //Create a new job object, if not done yet
1050 if(!m_handle_jobObject)
1052 m_handle_jobObject = CreateJobObject(NULL, NULL);
1053 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
1055 m_handle_jobObject = NULL;
1057 if(m_handle_jobObject)
1059 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
1060 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1061 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
1062 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1068 process.setProcessChannelMode(QProcess::MergedChannels);
1069 process.setReadChannel(QProcess::StandardOutput);
1073 process.setProcessChannelMode(QProcess::SeparateChannels);
1074 process.setReadChannel(QProcess::StandardError);
1077 process.start(program, args);
1079 if(process.waitForStarted())
1081 Q_PID pid = process.pid();
1082 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1085 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
1087 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
1095 log("Process creation has failed :-(");
1096 QString errorMsg= process.errorString().trimmed();
1097 if(!errorMsg.isEmpty()) log(errorMsg);
1100 process.waitForFinished(-1);
1104 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1106 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1108 for(int i = 0; i < arguments.count(); i++)
1110 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1116 QStringList EncodeThread::splitParams(const QString ¶ms)
1119 bool ignoreWhitespaces = false;
1122 for(int i = 0; i < params.length(); i++)
1124 const QChar c = params.at(i);
1126 if(c == QChar::fromLatin1('"'))
1128 ignoreWhitespaces = (!ignoreWhitespaces);
1131 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1133 APPEND_AND_CLEAR(list, temp);
1140 APPEND_AND_CLEAR(list, temp);
1142 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1143 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1148 qint64 EncodeThread::estimateSize(int progress)
1152 qint64 currentSize = QFileInfo(m_outputFileName).size();
1153 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1154 return estimatedSize;
1160 QString EncodeThread::sizeToString(qint64 size)
1162 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1166 qint64 estimatedSize = size;
1167 qint64 remainderSize = 0I64;
1170 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1172 remainderSize = estimatedSize % 1024I64;
1173 estimatedSize = estimatedSize / 1024I64;
1177 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1178 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);