1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "thread_encode.h"
25 #include "model_options.h"
26 #include "win_preferences.h"
42 QMutex EncodeThread::m_mutex_startProcess;
47 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
51 log("\nPROCESS ABORTED BY USER !!!"); \
52 setStatus(JobStatus_Aborted); \
53 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
54 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
59 setStatus(JobStatus_Failed); \
60 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
61 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
67 #define APPEND_AND_CLEAR(LIST, STR) do \
69 if(!((STR).isEmpty())) \
77 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
79 if(ITER != LIST.end()) \
81 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
83 log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
84 ITER = LIST.erase(ITER); \
85 if(ITER != LIST.end()) \
87 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
95 #define AVS2_BINARY(BIN_DIR, IS_X64) QString("%1/%2/avs2yuv_%2.exe").arg((BIN_DIR), ((IS_X64) ? "x64" : "x86"))
96 #define X264_BINARY(BIN_DIR, IS_10BIT, IS_X64) QString("%1/%2/x264_%3_%2.exe").arg((BIN_DIR), ((IS_X64) ? "x64" : "x86"), ((IS_10BIT) ? "10bit" : "8bit"))
101 static const unsigned int REV_MULT = 10000;
103 ///////////////////////////////////////////////////////////////////////////////
104 // Constructor & Destructor
105 ///////////////////////////////////////////////////////////////////////////////
107 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x264_x64, bool x264_10bit, bool avs2yuv_x64, unsigned int processPriroity)
109 m_jobId(QUuid::createUuid()),
110 m_sourceFileName(sourceFileName),
111 m_outputFileName(outputFileName),
112 m_options(new OptionsModel(*options)),
114 m_x264_x64(x264_x64),
115 m_x264_10bit(x264_10bit),
116 m_avs2yuv_x64(avs2yuv_x64),
117 m_processPriority(processPriroity),
118 m_handle_jobObject(NULL),
125 EncodeThread::~EncodeThread(void)
127 X264_DELETE(m_options);
129 if(m_handle_jobObject)
131 CloseHandle(m_handle_jobObject);
132 m_handle_jobObject = NULL;
136 ///////////////////////////////////////////////////////////////////////////////
137 // Thread entry point
138 ///////////////////////////////////////////////////////////////////////////////
140 void EncodeThread::run(void)
148 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
151 if(m_handle_jobObject)
153 TerminateJobObject(m_handle_jobObject, 42);
154 m_handle_jobObject = NULL;
158 void EncodeThread::checkedRun(void)
161 m_status = JobStatus_Starting;
171 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
172 setStatus(JobStatus_Failed);
176 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
177 setStatus(JobStatus_Failed);
182 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
186 void EncodeThread::start(Priority priority)
188 qDebug("Thread starting...");
193 while(m_semaphorePaused.tryAcquire(1, 0));
194 QThread::start(priority);
197 ///////////////////////////////////////////////////////////////////////////////
199 ///////////////////////////////////////////////////////////////////////////////
201 void EncodeThread::encode(void)
203 QDateTime startTime = QDateTime::currentDateTime();
205 //Print some basic info
206 log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
207 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
208 log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
209 log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
211 //Print encoder settings
212 log(tr("\n--- SETTINGS ---\n"));
213 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
214 log(tr("Preset: %1").arg(m_options->preset()));
215 log(tr("Tuning: %1").arg(m_options->tune()));
216 log(tr("Profile: %1").arg(m_options->profile()));
217 log(tr("Custom: %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
220 unsigned int frames = 0;
223 const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
224 const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
226 //Checking x264 version
227 log(tr("\n--- CHECK VERSION ---\n"));
228 unsigned int revision_x264 = UINT_MAX;
229 bool x264_modified = false;
230 ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
231 CHECK_STATUS(m_abort, ok);
233 //Checking avs2yuv version
234 unsigned int revision_avs2yuv = UINT_MAX;
237 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
238 CHECK_STATUS(m_abort, ok);
242 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()));
243 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)));
245 //Is x264 revision supported?
246 if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
248 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
249 setStatus(JobStatus_Failed);
252 if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
254 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
255 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
257 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
259 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
260 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
261 setStatus(JobStatus_Failed);
268 log(tr("\n--- AVS INFO ---\n"));
269 ok = checkProperties(m_avs2yuv_x64, frames);
270 CHECK_STATUS(m_abort, ok);
273 //Run encoding passes
274 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
276 QFileInfo info(m_outputFileName);
277 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
279 if(QFileInfo(passLogFile).exists())
282 while(QFileInfo(passLogFile).exists())
284 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
288 log(tr("\n--- PASS 1 ---\n"));
289 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile, 1, passLogFile);
290 CHECK_STATUS(m_abort, ok);
292 log(tr("\n--- PASS 2 ---\n"));
293 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile, 2, passLogFile);
294 CHECK_STATUS(m_abort, ok);
298 log(tr("\n--- ENCODING ---\n"));
299 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, usePipe, frames, indexFile);
300 CHECK_STATUS(m_abort, ok);
303 log(tr("\n--- DONE ---\n"));
304 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
305 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
306 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)));
307 setStatus(JobStatus_Completed);
310 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)
312 QProcess processEncode, processAvisynth;
316 QStringList cmdLine_Avisynth;
317 if(!m_options->customAvs2YUV().isEmpty())
319 cmdLine_Avisynth.append(splitParams(m_options->customAvs2YUV()));
321 cmdLine_Avisynth << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
322 cmdLine_Avisynth << "-";
323 processAvisynth.setStandardOutputProcess(&processEncode);
325 log("Creating Avisynth process:");
326 if(!startProcess(processAvisynth, AVS2_BINARY(m_binDir, avs2yuv_x64), cmdLine_Avisynth, false))
332 QStringList cmdLine_Encode = buildCommandLine(usePipe, x264_10bit, frames, indexFile, pass, passLogFile);
334 log("Creating x264 process:");
335 if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
340 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
341 QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
342 QRegExp regExpFrameCnt("^(\\d+) frames:");
344 QTextCodec *localCodec = QTextCodec::codecForName("System");
346 bool bTimeout = false;
347 bool bAborted = false;
349 unsigned int last_progress = UINT_MAX;
350 unsigned int last_indexing = UINT_MAX;
351 qint64 size_estimate = 0I64;
353 //Main processing loop
354 while(processEncode.state() != QProcess::NotRunning)
356 unsigned int waitCounter = 0;
358 //Wait until new output is available
363 processEncode.kill();
364 processAvisynth.kill();
368 if(m_pause && (processEncode.state() == QProcess::Running))
370 JobStatus previousStatus = m_status;
371 setStatus(JobStatus_Paused);
372 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
373 bool ok[2] = {false, false};
374 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
375 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
376 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
377 while(m_pause) m_semaphorePaused.tryAcquire(1, 5000);
378 while(m_semaphorePaused.tryAcquire(1, 0));
379 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
380 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
381 if(!m_abort) setStatus(previousStatus);
382 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
386 if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
388 if(processEncode.state() == QProcess::Running)
390 if(waitCounter++ > m_processTimeoutMaxCounter)
392 processEncode.kill();
393 qWarning("x264 process timed out <-- killing!");
394 log("\nPROCESS TIMEOUT !!!");
398 else if(waitCounter == m_processTimeoutWarning)
400 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
401 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
406 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
413 //Exit main processing loop now?
414 if(bAborted || bTimeout)
420 while(processEncode.bytesAvailable() > 0)
422 QList<QByteArray> lines = processEncode.readLine().split('\r');
423 while(!lines.isEmpty())
425 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
427 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
430 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
431 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
432 if(ok && ((progress > last_progress) || (last_progress == UINT_MAX)))
434 setProgress(progress);
435 size_estimate = estimateSize(progress);
436 last_progress = progress;
438 setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate)));
439 last_indexing = UINT_MAX;
441 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
444 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
445 setStatus(JobStatus_Indexing);
446 if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
448 setProgress(progress);
449 last_indexing = progress;
451 setDetails(text.mid(offset).trimmed());
452 last_progress = UINT_MAX;
454 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
456 last_progress = last_indexing = UINT_MAX;
457 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
458 setDetails(text.mid(offset).trimmed());
460 else if(!text.isEmpty())
462 last_progress = last_indexing = UINT_MAX;
469 processEncode.waitForFinished(5000);
470 if(processEncode.state() != QProcess::NotRunning)
472 qWarning("x264 process still running, going to kill it!");
473 processEncode.kill();
474 processEncode.waitForFinished(-1);
477 processAvisynth.waitForFinished(5000);
478 if(processAvisynth.state() != QProcess::NotRunning)
480 qWarning("Avisynth process still running, going to kill it!");
481 processAvisynth.kill();
482 processAvisynth.waitForFinished(-1);
485 if(!(bTimeout || bAborted))
487 while(processAvisynth.bytesAvailable() > 0)
489 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
493 if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
495 if(!(bTimeout || bAborted))
497 log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
501 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
503 if(!(bTimeout || bAborted))
505 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
507 processEncode.close();
508 processAvisynth.close();
512 QThread::yieldCurrentThread();
514 const qint64 finalSize = QFileInfo(m_outputFileName).size();
515 QLocale locale(QLocale::English);
516 log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
521 setStatus(JobStatus_Running_Pass1);
522 setDetails(tr("First pass completed. Preparing for second pass..."));
525 setStatus(JobStatus_Running_Pass2);
526 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
529 setStatus(JobStatus_Running);
530 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
535 processEncode.close();
536 processAvisynth.close();
540 QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
543 double crf_int = 0.0, crf_frc = 0.0;
545 switch(m_options->rcMode())
547 case OptionsModel::RCMode_CQ:
548 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
550 case OptionsModel::RCMode_CRF:
551 crf_frc = modf(m_options->quantizer(), &crf_int);
552 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
554 case OptionsModel::RCMode_2Pass:
555 case OptionsModel::RCMode_ABR:
556 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
559 throw "Bad rate-control mode !!!";
563 if((pass == 1) || (pass == 2))
565 cmdLine << "--pass" << QString::number(pass);
566 cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
569 cmdLine << "--preset" << m_options->preset().toLower();
571 if(m_options->tune().compare("none", Qt::CaseInsensitive))
573 cmdLine << "--tune" << m_options->tune().toLower();
576 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
580 if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
582 log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
586 cmdLine << "--profile" << m_options->profile().toLower();
591 cmdLine << "--profile" << m_options->profile().toLower();
595 if(!m_options->customX264().isEmpty())
597 QStringList customArgs = splitParams(m_options->customX264());
600 QStringList::iterator i = customArgs.begin();
601 while(i != customArgs.end())
603 bool bModified = false;
604 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
605 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
609 cmdLine.append(customArgs);
612 cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
616 if(frames < 1) throw "Frames not set!";
617 cmdLine << "--frames" << QString::number(frames);
618 cmdLine << "--demuxer" << "y4m";
619 cmdLine << "--stdin" << "y4m" << "-";
623 cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
624 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
630 unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
633 QStringList cmdLine = QStringList() << "--version";
635 log("Creating process:");
636 if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
641 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
642 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
644 bool bTimeout = false;
645 bool bAborted = false;
647 unsigned int revision = UINT_MAX;
648 unsigned int coreVers = UINT_MAX;
651 while(process.state() != QProcess::NotRunning)
659 if(!process.waitForReadyRead())
661 if(process.state() == QProcess::Running)
664 qWarning("x264 process timed out <-- killing!");
665 log("\nPROCESS TIMEOUT !!!");
670 while(process.bytesAvailable() > 0)
672 QList<QByteArray> lines = process.readLine().split('\r');
673 while(!lines.isEmpty())
675 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
677 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
679 bool ok1 = false, ok2 = false;
680 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
681 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
682 if(ok1) coreVers = temp1;
683 if(ok2) revision = temp2;
685 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
687 bool ok1 = false, ok2 = false;
688 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
689 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
690 if(ok1) coreVers = temp1;
691 if(ok2) revision = temp2;
702 process.waitForFinished();
703 if(process.state() != QProcess::NotRunning)
706 process.waitForFinished(-1);
709 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
711 if(!(bTimeout || bAborted))
713 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
718 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
720 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
724 return (coreVers * REV_MULT) + (revision % REV_MULT);
727 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
731 log("\nCreating process:");
732 if(!startProcess(process, AVS2_BINARY(m_binDir, x64), QStringList()))
737 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
738 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
740 bool bTimeout = false;
741 bool bAborted = false;
743 unsigned int ver_maj = UINT_MAX;
744 unsigned int ver_min = UINT_MAX;
745 unsigned int ver_mod = 0;
747 while(process.state() != QProcess::NotRunning)
755 if(!process.waitForReadyRead())
757 if(process.state() == QProcess::Running)
760 qWarning("Avs2YUV process timed out <-- killing!");
761 log("\nPROCESS TIMEOUT !!!");
766 while(process.bytesAvailable() > 0)
768 QList<QByteArray> lines = process.readLine().split('\r');
769 while(!lines.isEmpty())
771 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
773 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
780 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
782 bool ok1 = false, ok2 = false, ok3 = false;
783 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
784 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
785 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
786 if(ok1) ver_maj = temp1;
787 if(ok2) ver_min = temp2;
788 if(ok3) ver_mod = temp3;
790 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
792 bool ok1 = false, ok2 = false;
793 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
794 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
795 if(ok1) ver_maj = temp1;
796 if(ok2) ver_min = temp2;
802 process.waitForFinished();
803 if(process.state() != QProcess::NotRunning)
806 process.waitForFinished(-1);
809 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
811 if(!(bTimeout || bAborted))
813 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
818 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
820 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
824 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
827 bool EncodeThread::checkProperties(bool x64, unsigned int &frames)
832 if(!m_options->customAvs2YUV().isEmpty())
834 cmdLine.append(splitParams(m_options->customAvs2YUV()));
837 cmdLine << "-frames" << "1";
838 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
840 log("Creating process:");
841 if(!startProcess(process, AVS2_BINARY(m_binDir, x64), cmdLine))
846 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
847 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
849 QTextCodec *localCodec = QTextCodec::codecForName("System");
851 bool bTimeout = false;
852 bool bAborted = false;
856 unsigned int fpsNom = 0;
857 unsigned int fpsDen = 0;
858 unsigned int fSizeW = 0;
859 unsigned int fSizeH = 0;
861 unsigned int waitCounter = 0;
863 while(process.state() != QProcess::NotRunning)
871 if(!process.waitForReadyRead(m_processTimeoutInterval))
873 if(process.state() == QProcess::Running)
875 if(waitCounter++ > m_processTimeoutMaxCounter)
878 qWarning("Avs2YUV process timed out <-- killing!");
879 log("\nPROCESS TIMEOUT !!!");
880 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
884 else if(waitCounter == m_processTimeoutWarning)
886 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
887 log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
895 while(process.bytesAvailable() > 0)
897 QList<QByteArray> lines = process.readLine().split('\r');
898 while(!lines.isEmpty())
900 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
902 if((offset = regExpInt.lastIndexIn(text)) >= 0)
904 bool ok1 = false, ok2 = false;
905 bool ok3 = false, ok4 = false;
906 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
907 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
908 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
909 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
910 if(ok1) fSizeW = temp1;
911 if(ok2) fSizeH = temp2;
912 if(ok3) fpsNom = temp3;
913 if(ok4) frames = temp4;
915 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
917 bool ok1 = false, ok2 = false;
918 bool ok3 = false, ok4 = false, ok5 = false;
919 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
920 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
921 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
922 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
923 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
924 if(ok1) fSizeW = temp1;
925 if(ok2) fSizeH = temp2;
926 if(ok3) fpsNom = temp3;
927 if(ok4) fpsDen = temp4;
928 if(ok5) frames = temp5;
934 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
936 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
938 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
940 log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
946 process.waitForFinished();
947 if(process.state() != QProcess::NotRunning)
950 process.waitForFinished(-1);
953 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
955 if(!(bTimeout || bAborted))
957 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
964 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
970 if((fSizeW > 0) && (fSizeH > 0))
972 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
974 if((fpsNom > 0) && (fpsDen > 0))
976 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
978 if((fpsNom > 0) && (fpsDen == 0))
980 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
984 log(tr("No. Frames: %1").arg(QString::number(frames)));
990 ///////////////////////////////////////////////////////////////////////////////
992 ///////////////////////////////////////////////////////////////////////////////
994 void EncodeThread::setStatus(JobStatus newStatus)
996 if(m_status != newStatus)
998 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
1000 if(m_status != JobStatus_Paused) setProgress(0);
1002 if(newStatus == JobStatus_Failed)
1004 setDetails("The job has failed. See log for details!");
1006 if(newStatus == JobStatus_Aborted)
1008 setDetails("The job was aborted by the user!");
1010 m_status = newStatus;
1011 emit statusChanged(m_jobId, newStatus);
1015 void EncodeThread::setProgress(unsigned int newProgress)
1017 if(m_progress != newProgress)
1019 m_progress = newProgress;
1020 emit progressChanged(m_jobId, m_progress);
1024 void EncodeThread::setDetails(const QString &text)
1026 emit detailsChanged(m_jobId, text);
1029 QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
1031 QTextCodec *localCodec = QTextCodec::codecForName("System");
1033 //Do NOT convert to short, if path can be represented in local Codepage
1034 if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
1039 //Create dummy file, if required (only existing files can have a short path!)
1041 if((!QFileInfo(longPath).exists()) && create)
1043 tempFile.setFileName(longPath);
1044 tempFile.open(QIODevice::WriteOnly);
1048 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1052 wchar_t *buffer = new wchar_t[buffSize];
1053 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1055 if(result > 0 && result < buffSize)
1057 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1064 //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
1065 if(tempFile.isOpen())
1067 if(!keep) tempFile.remove();
1071 if(shortPath.isEmpty())
1073 log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
1076 return (shortPath.isEmpty() ? longPath : shortPath);
1079 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1081 QMutexLocker lock(&m_mutex_startProcess);
1082 log(commandline2string(program, args) + "\n");
1084 //Create a new job object, if not done yet
1085 if(!m_handle_jobObject)
1087 m_handle_jobObject = CreateJobObject(NULL, NULL);
1088 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
1090 m_handle_jobObject = NULL;
1092 if(m_handle_jobObject)
1094 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
1095 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1096 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
1097 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1103 process.setProcessChannelMode(QProcess::MergedChannels);
1104 process.setReadChannel(QProcess::StandardOutput);
1108 process.setProcessChannelMode(QProcess::SeparateChannels);
1109 process.setReadChannel(QProcess::StandardError);
1112 process.start(program, args);
1114 if(process.waitForStarted())
1116 Q_PID pid = process.pid();
1117 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1120 switch(m_processPriority)
1122 case PreferencesDialog::X264_PRIORITY_NORMAL:
1123 SetPriorityClass(process.pid()->hProcess, NORMAL_PRIORITY_CLASS);
1125 case PreferencesDialog::X264_PRIORITY_BELOWNORMAL:
1126 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
1128 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
1131 case PreferencesDialog::X264_PRIORITY_IDLE:
1132 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
1141 log("Process creation has failed :-(");
1142 QString errorMsg= process.errorString().trimmed();
1143 if(!errorMsg.isEmpty()) log(errorMsg);
1146 process.waitForFinished(-1);
1150 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1152 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1154 for(int i = 0; i < arguments.count(); i++)
1156 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1162 QStringList EncodeThread::splitParams(const QString ¶ms)
1165 bool ignoreWhitespaces = false;
1168 for(int i = 0; i < params.length(); i++)
1170 const QChar c = params.at(i);
1172 if(c == QChar::fromLatin1('"'))
1174 ignoreWhitespaces = (!ignoreWhitespaces);
1177 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1179 APPEND_AND_CLEAR(list, temp);
1186 APPEND_AND_CLEAR(list, temp);
1188 list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1189 list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1194 qint64 EncodeThread::estimateSize(int progress)
1198 qint64 currentSize = QFileInfo(m_outputFileName).size();
1199 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1200 return estimatedSize;
1206 QString EncodeThread::sizeToString(qint64 size)
1208 static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1212 qint64 estimatedSize = size;
1213 qint64 remainderSize = 0I64;
1216 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1218 remainderSize = estimatedSize % 1024I64;
1219 estimatedSize = estimatedSize / 1024I64;
1223 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1224 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);