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"
40 QMutex EncodeThread::m_mutex_startProcess;
45 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) \
49 log("\nPROCESS ABORTED BY USER !!!"); \
50 setStatus(JobStatus_Aborted); \
51 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
56 setStatus(JobStatus_Failed); \
57 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
62 #define APPEND_AND_CLEAR(LIST, STR) \
64 if(!((STR).isEmpty())) \
74 static const unsigned int REV_MULT = 10000;
76 ///////////////////////////////////////////////////////////////////////////////
77 // Constructor & Destructor
78 ///////////////////////////////////////////////////////////////////////////////
80 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x264_x64, bool avs2yuv_x64)
82 m_jobId(QUuid::createUuid()),
83 m_sourceFileName(sourceFileName),
84 m_outputFileName(outputFileName),
85 m_options(new OptionsModel(*options)),
88 m_avs2yuv_x64(avs2yuv_x64),
89 m_handle_jobObject(NULL),
96 EncodeThread::~EncodeThread(void)
98 X264_DELETE(m_options);
100 if(m_handle_jobObject)
102 CloseHandle(m_handle_jobObject);
103 m_handle_jobObject = NULL;
107 ///////////////////////////////////////////////////////////////////////////////
108 // Thread entry point
109 ///////////////////////////////////////////////////////////////////////////////
111 void EncodeThread::run(void)
119 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
122 if(m_handle_jobObject)
124 TerminateJobObject(m_handle_jobObject, 42);
125 m_handle_jobObject = NULL;
129 void EncodeThread::checkedRun(void)
132 m_status = JobStatus_Starting;
142 log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
143 setStatus(JobStatus_Failed);
147 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
148 setStatus(JobStatus_Failed);
153 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
157 void EncodeThread::start(Priority priority)
159 qDebug("Thread starting...");
164 while(m_semaphorePaused.tryAcquire(1, 0));
165 QThread::start(priority);
168 ///////////////////////////////////////////////////////////////////////////////
170 ///////////////////////////////////////////////////////////////////////////////
172 void EncodeThread::encode(void)
174 QDateTime startTime = QDateTime::currentDateTime();
176 //Print some basic info
177 log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
178 log(tr("Source file: %1").arg(m_sourceFileName));
179 log(tr("Output file: %1").arg(m_outputFileName));
181 //Print encoder settings
182 log(tr("\n--- SETTINGS ---\n"));
183 log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
184 log(tr("Preset: %1").arg(m_options->preset()));
185 log(tr("Tuning: %1").arg(m_options->tune()));
186 log(tr("Profile: %1").arg(m_options->profile()));
187 log(tr("Custom: %1").arg(m_options->custom().isEmpty() ? tr("(None)") : m_options->custom()));
190 unsigned int frames = 0;
193 const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
194 const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
196 //Checking x264 version
197 log(tr("\n--- CHECK VERSION ---\n"));
198 unsigned int revision_x264 = UINT_MAX;
199 bool x264_modified = false;
200 ok = ((revision_x264 = checkVersionX264(m_x264_x64, x264_modified)) != UINT_MAX);
201 CHECK_STATUS(m_abort, ok);
203 //Checking avs2yuv version
204 unsigned int revision_avs2yuv = UINT_MAX;
207 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
208 CHECK_STATUS(m_abort, ok);
212 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()));
213 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)));
215 //Is x264 revision supported?
216 if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
218 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
219 setStatus(JobStatus_Failed);
222 if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
224 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
225 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
227 if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
229 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
230 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
231 setStatus(JobStatus_Failed);
238 log(tr("\n--- AVS INFO ---\n"));
239 ok = checkProperties(m_avs2yuv_x64, frames);
240 CHECK_STATUS(m_abort, ok);
243 //Run encoding passes
244 if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
246 QFileInfo info(m_outputFileName);
247 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
249 if(QFileInfo(passLogFile).exists())
252 while(QFileInfo(passLogFile).exists())
254 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
258 log(tr("\n--- PASS 1 ---\n"));
259 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile, 1, passLogFile);
260 CHECK_STATUS(m_abort, ok);
262 log(tr("\n--- PASS 2 ---\n"));
263 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile, 2, passLogFile);
264 CHECK_STATUS(m_abort, ok);
268 log(tr("\n--- ENCODING ---\n"));
269 ok = runEncodingPass(m_x264_x64, m_avs2yuv_x64, usePipe, frames, indexFile);
270 CHECK_STATUS(m_abort, ok);
273 log(tr("\n--- DONE ---\n"));
274 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
275 int timePassed = startTime.secsTo(QDateTime::currentDateTime());
276 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)));
277 setStatus(JobStatus_Completed);
280 bool EncodeThread::runEncodingPass(bool x264_x64, bool avs2yuv_x64, bool usePipe, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
282 QProcess processEncode, processAvisynth;
286 QStringList cmdLine_Avisynth;
287 cmdLine_Avisynth << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
288 cmdLine_Avisynth << "-";
289 processAvisynth.setStandardOutputProcess(&processEncode);
291 log("Creating Avisynth process:");
292 if(!startProcess(processAvisynth, QString("%1/%2.exe").arg(m_binDir, avs2yuv_x64 ? "avs2yuv_x64" : "avs2yuv"), cmdLine_Avisynth, false))
298 QStringList cmdLine_Encode = buildCommandLine(usePipe, frames, indexFile, pass, passLogFile);
300 log("Creating x264 process:");
301 if(!startProcess(processEncode, QString("%1/%2.exe").arg(m_binDir, x264_x64 ? "x264_x64" : "x264"), cmdLine_Encode))
306 QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
307 QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
308 QRegExp regExpFrameCnt("^(\\d+) frames:");
310 QTextCodec *localCodec = QTextCodec::codecForName("System");
312 bool bTimeout = false;
313 bool bAborted = false;
315 //Main processing loop
316 while(processEncode.state() != QProcess::NotRunning)
318 unsigned int waitCounter = 0;
320 //Wait until new output is available
325 processEncode.kill();
326 processAvisynth.kill();
330 if(m_pause && (processEncode.state() == QProcess::Running))
332 JobStatus previousStatus = m_status;
333 setStatus(JobStatus_Paused);
334 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
335 bool ok[2] = {false, false};
336 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
337 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
338 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
339 while(m_pause) m_semaphorePaused.acquire();
340 while(m_semaphorePaused.tryAcquire(1, 0));
341 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
342 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
343 if(!m_abort) setStatus(previousStatus);
344 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
348 if(!processEncode.waitForReadyRead(2500))
350 if(processEncode.state() == QProcess::Running)
352 if(waitCounter++ > m_processTimeoutCounter)
354 processEncode.kill();
355 qWarning("x264 process timed out <-- killing!");
356 log("\nPROCESS TIMEOUT !!!");
363 if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
370 //Exit main processing loop now?
371 if(bAborted || bTimeout)
377 while(processEncode.bytesAvailable() > 0)
379 QList<QByteArray> lines = processEncode.readLine().split('\r');
380 while(!lines.isEmpty())
382 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
384 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
387 unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
388 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
389 setDetails(text.mid(offset).trimmed());
390 if(ok) setProgress(progress);
392 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
395 unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
396 setStatus(JobStatus_Indexing);
397 setDetails(text.mid(offset).trimmed());
398 if(ok) setProgress(progress);
400 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
402 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
403 setDetails(text.mid(offset).trimmed());
405 else if(!text.isEmpty())
413 processEncode.waitForFinished(5000);
414 if(processEncode.state() != QProcess::NotRunning)
416 qWarning("x264 process still running, going to kill it!");
417 processEncode.kill();
418 processEncode.waitForFinished(-1);
421 processAvisynth.waitForFinished(5000);
422 if(processAvisynth.state() != QProcess::NotRunning)
424 qWarning("Avisynth process still running, going to kill it!");
425 processAvisynth.kill();
426 processAvisynth.waitForFinished(-1);
429 if(!(bTimeout || bAborted))
431 while(processAvisynth.bytesAvailable() > 0)
433 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
437 if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
439 if(!(bTimeout || bAborted))
441 log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
445 if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
447 if(!(bTimeout || bAborted))
449 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
451 processEncode.close();
452 processAvisynth.close();
459 setStatus(JobStatus_Running_Pass1);
460 setDetails(tr("First pass completed. Preparing for second pass..."));
463 setStatus(JobStatus_Running_Pass2);
464 setDetails(tr("Second pass completed successfully."));
467 setStatus(JobStatus_Running);
468 setDetails(tr("Encode completed successfully."));
473 processEncode.close();
474 processAvisynth.close();
478 QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
481 double crf_int = 0.0, crf_frc = 0.0;
483 switch(m_options->rcMode())
485 case OptionsModel::RCMode_CQ:
486 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
488 case OptionsModel::RCMode_CRF:
489 crf_frc = modf(m_options->quantizer(), &crf_int);
490 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
492 case OptionsModel::RCMode_2Pass:
493 case OptionsModel::RCMode_ABR:
494 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
497 throw "Bad rate-control mode !!!";
501 if((pass == 1) || (pass == 2))
503 cmdLine << "--pass" << QString::number(pass);
504 cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
507 cmdLine << "--preset" << m_options->preset().toLower();
509 if(m_options->tune().compare("none", Qt::CaseInsensitive))
511 cmdLine << "--tune" << m_options->tune().toLower();
514 if(m_options->profile().compare("auto", Qt::CaseInsensitive))
516 cmdLine << "--profile" << m_options->profile().toLower();
519 if(!m_options->custom().isEmpty())
521 cmdLine.append(splitParams(m_options->custom()));
524 cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
528 if(frames < 1) throw "Frames not set!";
529 cmdLine << "--frames" << QString::number(frames);
530 cmdLine << "--demuxer" << "y4m";
531 cmdLine << "--stdin" << "y4m" << "-";
535 cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
536 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
542 unsigned int EncodeThread::checkVersionX264(bool x64, bool &modified)
545 QStringList cmdLine = QStringList() << "--version";
547 log("Creating process:");
548 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
553 QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
554 QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
556 bool bTimeout = false;
557 bool bAborted = false;
559 unsigned int revision = UINT_MAX;
560 unsigned int coreVers = UINT_MAX;
563 while(process.state() != QProcess::NotRunning)
571 if(!process.waitForReadyRead())
573 if(process.state() == QProcess::Running)
576 qWarning("x264 process timed out <-- killing!");
577 log("\nPROCESS TIMEOUT !!!");
582 while(process.bytesAvailable() > 0)
584 QList<QByteArray> lines = process.readLine().split('\r');
585 while(!lines.isEmpty())
587 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
589 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
591 bool ok1 = false, ok2 = false;
592 unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
593 unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
594 if(ok1) coreVers = temp1;
595 if(ok2) revision = temp2;
597 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
599 bool ok1 = false, ok2 = false;
600 unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
601 unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
602 if(ok1) coreVers = temp1;
603 if(ok2) revision = temp2;
614 process.waitForFinished();
615 if(process.state() != QProcess::NotRunning)
618 process.waitForFinished(-1);
621 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
623 if(!(bTimeout || bAborted))
625 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
630 if((revision == UINT_MAX) || (coreVers == UINT_MAX))
632 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
636 return (coreVers * REV_MULT) + (revision % REV_MULT);
639 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
643 log("\nCreating process:");
644 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv"), QStringList()))
649 QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
650 QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
652 bool bTimeout = false;
653 bool bAborted = false;
655 unsigned int ver_maj = UINT_MAX;
656 unsigned int ver_min = UINT_MAX;
657 unsigned int ver_mod = 0;
659 while(process.state() != QProcess::NotRunning)
667 if(!process.waitForReadyRead())
669 if(process.state() == QProcess::Running)
672 qWarning("Avs2YUV process timed out <-- killing!");
673 log("\nPROCESS TIMEOUT !!!");
678 while(process.bytesAvailable() > 0)
680 QList<QByteArray> lines = process.readLine().split('\r');
681 while(!lines.isEmpty())
683 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
685 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
692 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
694 bool ok1 = false, ok2 = false, ok3 = false;
695 unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
696 unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
697 unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
698 if(ok1) ver_maj = temp1;
699 if(ok2) ver_min = temp2;
700 if(ok3) ver_mod = temp3;
702 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
704 bool ok1 = false, ok2 = false;
705 unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
706 unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
707 if(ok1) ver_maj = temp1;
708 if(ok2) ver_min = temp2;
714 process.waitForFinished();
715 if(process.state() != QProcess::NotRunning)
718 process.waitForFinished(-1);
721 if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
723 if(!(bTimeout || bAborted))
725 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
730 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
732 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
736 return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
739 bool EncodeThread::checkProperties(bool x64, unsigned int &frames)
743 QStringList cmdLine = QStringList() << "-frames" << "1";
744 cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
746 log("Creating process:");
747 if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "avs2yuv_x64" : "avs2yuv"), cmdLine))
752 QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
753 QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
755 QTextCodec *localCodec = QTextCodec::codecForName("System");
757 bool bTimeout = false;
758 bool bAborted = false;
762 unsigned int fpsNom = 0;
763 unsigned int fpsDen = 0;
764 unsigned int fSizeW = 0;
765 unsigned int fSizeH = 0;
767 while(process.state() != QProcess::NotRunning)
775 if(!process.waitForReadyRead())
777 if(process.state() == QProcess::Running)
780 qWarning("Avs2YUV process timed out <-- killing!");
781 log("\nPROCESS TIMEOUT !!!");
786 while(process.bytesAvailable() > 0)
788 QList<QByteArray> lines = process.readLine().split('\r');
789 while(!lines.isEmpty())
791 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
793 if((offset = regExpInt.lastIndexIn(text)) >= 0)
795 bool ok1 = false, ok2 = false;
796 bool ok3 = false, ok4 = false;
797 unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
798 unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
799 unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
800 unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
801 if(ok1) fSizeW = temp1;
802 if(ok2) fSizeH = temp2;
803 if(ok3) fpsNom = temp3;
804 if(ok4) frames = temp4;
806 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
808 bool ok1 = false, ok2 = false;
809 bool ok3 = false, ok4 = false, ok5 = false;
810 unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
811 unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
812 unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
813 unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
814 unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
815 if(ok1) fSizeW = temp1;
816 if(ok2) fSizeH = temp2;
817 if(ok3) fpsNom = temp3;
818 if(ok4) fpsDen = temp4;
819 if(ok5) frames = temp5;
825 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
827 log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
833 process.waitForFinished();
834 if(process.state() != QProcess::NotRunning)
837 process.waitForFinished(-1);
840 if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
842 if(!(bTimeout || bAborted))
844 log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
851 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
857 if((fSizeW > 0) && (fSizeH > 0))
859 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
861 if((fpsNom > 0) && (fpsDen > 0))
863 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
865 if((fpsNom > 0) && (fpsDen == 0))
867 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
871 log(tr("No. Frames: %1").arg(QString::number(frames)));
877 ///////////////////////////////////////////////////////////////////////////////
879 ///////////////////////////////////////////////////////////////////////////////
881 void EncodeThread::setStatus(JobStatus newStatus)
883 if(m_status != newStatus)
885 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
887 if(m_status != JobStatus_Paused) setProgress(0);
889 if(newStatus == JobStatus_Failed)
891 setDetails("The job has failed. See log for details!");
893 if(newStatus == JobStatus_Aborted)
895 setDetails("The job was aborted by the user!");
897 m_status = newStatus;
898 emit statusChanged(m_jobId, newStatus);
902 void EncodeThread::setProgress(unsigned int newProgress)
904 if(m_progress != newProgress)
906 m_progress = newProgress;
907 emit progressChanged(m_jobId, m_progress);
911 void EncodeThread::setDetails(const QString &text)
913 emit detailsChanged(m_jobId, text);
916 QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
918 QTextCodec *localCodec = QTextCodec::codecForName("System");
920 //Do NOT convert to short, if path can be represented in local Codepage
921 if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
926 //Create dummy file, if required (only existing files can have a short path!)
928 if((!QFileInfo(longPath).exists()) && create)
930 tempFile.setFileName(longPath);
931 tempFile.open(QIODevice::WriteOnly);
935 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
939 wchar_t *buffer = new wchar_t[buffSize];
940 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
942 if(result > 0 && result < buffSize)
944 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
951 //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
952 if(tempFile.isOpen())
954 if(!keep) tempFile.remove();
958 if(shortPath.isEmpty())
960 log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
963 return (shortPath.isEmpty() ? longPath : shortPath);
966 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
968 QMutexLocker lock(&m_mutex_startProcess);
969 log(commandline2string(program, args) + "\n");
971 //Create a new job object, if not done yet
972 if(!m_handle_jobObject)
974 m_handle_jobObject = CreateJobObject(NULL, NULL);
975 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
977 m_handle_jobObject = NULL;
979 if(m_handle_jobObject)
981 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
982 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
983 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
984 SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
990 process.setProcessChannelMode(QProcess::MergedChannels);
991 process.setReadChannel(QProcess::StandardOutput);
995 process.setProcessChannelMode(QProcess::SeparateChannels);
996 process.setReadChannel(QProcess::StandardError);
999 process.start(program, args);
1001 if(process.waitForStarted())
1003 Q_PID pid = process.pid();
1004 AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1007 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
1009 SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
1017 log("Process creation has failed :-(");
1018 QString errorMsg= process.errorString().trimmed();
1019 if(!errorMsg.isEmpty()) log(errorMsg);
1022 process.waitForFinished(-1);
1026 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1028 QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1030 for(int i = 0; i < arguments.count(); i++)
1032 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1038 QStringList EncodeThread::splitParams(const QString ¶ms)
1041 bool ignoreWhitespaces = false;
1044 for(int i = 0; i < params.length(); i++)
1046 const QChar c = params.at(i);
1048 if(c == QChar::fromLatin1('"'))
1050 ignoreWhitespaces = (!ignoreWhitespaces);
1053 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1055 APPEND_AND_CLEAR(list, temp);
1062 APPEND_AND_CLEAR(list, temp);