///////////////////////////////////////////////////////////////////////////////
// Simple x264 Launcher
-// Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2018 LoRd_MuldeR <MuldeR2@GMX.de>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
#include "thread_encode.h"
+//Internal
#include "global.h"
#include "model_options.h"
-#include "version.h"
+#include "model_preferences.h"
+#include "model_sysinfo.h"
+#include "model_clipInfo.h"
+#include "job_object.h"
+#include "mediainfo.h"
+//Encoders
+#include "encoder_factory.h"
+
+//Source
+#include "source_factory.h"
+
+//MUtils
+#include <MUtils/OSSupport.h>
+#include <MUtils/Version.h>
+
+//Qt Framework
#include <QDate>
#include <QTime>
#include <QDateTime>
#include <QDir>
#include <QProcess>
#include <QMutex>
-#include <QLibrary>
+#include <QTextCodec>
+#include <QLocale>
+#include <QCryptographicHash>
/*
- * Win32 API definitions
+ * RAII execution state handler
*/
-typedef HANDLE (WINAPI *CreateJobObjectFun)(__in_opt LPSECURITY_ATTRIBUTES lpJobAttributes, __in_opt LPCSTR lpName);
-typedef BOOL (WINAPI *SetInformationJobObjectFun)(__in HANDLE hJob, __in JOBOBJECTINFOCLASS JobObjectInformationClass, __in_bcount(cbJobObjectInformationLength) LPVOID lpJobObjectInformation, __in DWORD cbJobObjectInformationLength);
-typedef BOOL (WINAPI *AssignProcessToJobObjectFun)(__in HANDLE hJob, __in HANDLE hProcess);
+class ExecutionStateHandler
+{
+public:
+ ExecutionStateHandler(void)
+ {
+ x264_set_thread_execution_state(true);
+ }
+ ~ExecutionStateHandler(void)
+ {
+ x264_set_thread_execution_state(false);
+ }
+private:
+ //Disable copy constructor and assignment
+ ExecutionStateHandler(const ExecutionStateHandler &other) {}
+ ExecutionStateHandler &operator=(const ExecutionStateHandler &) {}
-/*
- * Static vars
- */
-QMutex EncodeThread::m_mutex_startProcess;
+ //Prevent object allocation on the heap
+ void *operator new(size_t); void *operator new[](size_t);
+ void operator delete(void *); void operator delete[](void*);
+};
/*
* Macros
*/
-#define CHECK_STATUS(ABORT_FLAG, OK_FLAG) \
+#define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
{ \
if(ABORT_FLAG) \
{ \
log("\nPROCESS ABORTED BY USER !!!"); \
setStatus(JobStatus_Aborted); \
+ if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
return; \
} \
else if(!(OK_FLAG)) \
{ \
setStatus(JobStatus_Failed); \
+ if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
return; \
} \
-}
+} \
+while(0)
-/*
- * Static vars
- */
-static const unsigned int REV_MULT = 10000;
+#define CONNECT(OBJ) do \
+{ \
+ if((OBJ)) \
+ { \
+ connect((OBJ), SIGNAL(statusChanged(JobStatus)), this, SLOT(setStatus(JobStatus)), Qt::DirectConnection); \
+ connect((OBJ), SIGNAL(progressChanged(unsigned int)), this, SLOT(setProgress(unsigned int)), Qt::DirectConnection); \
+ connect((OBJ), SIGNAL(detailsChanged(QString)), this, SLOT(setDetails(QString)), Qt::DirectConnection); \
+ connect((OBJ), SIGNAL(messageLogged(QString)), this, SLOT(log(QString)), Qt::DirectConnection); \
+ } \
+} \
+while(0)
///////////////////////////////////////////////////////////////////////////////
// Constructor & Destructor
///////////////////////////////////////////////////////////////////////////////
-EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x64)
+EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
:
m_jobId(QUuid::createUuid()),
m_sourceFileName(sourceFileName),
m_outputFileName(outputFileName),
m_options(new OptionsModel(*options)),
- m_binDir(binDir),
- m_x64(x64),
- m_handle_jobObject(NULL)
+ m_sysinfo(sysinfo),
+ m_preferences(preferences),
+ m_jobObject(new JobObject),
+ m_semaphorePaused(0),
+ m_encoder(NULL),
+ m_pipedSource(NULL)
{
m_abort = false;
+ m_pause = false;
+
+ //Create encoder object
+ m_encoder = EncoderFactory::createEncoder(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName, m_outputFileName);
+
+ //Create input handler object
+ switch(MediaInfo::analyze(m_sourceFileName))
+ {
+ case MediaInfo::FILETYPE_AVISYNTH:
+ if(m_sysinfo->hasAvisynth())
+ {
+ m_pipedSource = SourceFactory::createSource(SourceFactory::SourceType_AVS, m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
+ }
+ break;
+ case MediaInfo::FILETYPE_VAPOURSYNTH:
+ if(m_sysinfo->hasVapourSynth())
+ {
+ m_pipedSource = SourceFactory::createSource(SourceFactory::SourceType_VPS, m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
+ }
+ break;
+ }
+
+ //Establish connections
+ CONNECT(m_encoder);
+ CONNECT(m_pipedSource);
}
EncodeThread::~EncodeThread(void)
{
- X264_DELETE(m_options);
-
- if(m_handle_jobObject)
- {
- CloseHandle(m_handle_jobObject);
- m_handle_jobObject = NULL;
- }
+ MUTILS_DELETE(m_encoder);
+ MUTILS_DELETE(m_jobObject);
+ MUTILS_DELETE(m_options);
+ MUTILS_DELETE(m_pipedSource);
}
///////////////////////////////////////////////////////////////////////////////
void EncodeThread::run(void)
{
- m_progress = 0;
- m_status = JobStatus_Starting;
-
- try
- {
- encode();
- }
- catch(char *msg)
+#if !defined(_DEBUG)
+ __try
{
- log(tr("EXCEPTION ERROR: ").append(QString::fromLatin1(msg)));
+ checkedRun();
}
- catch(...)
+ __except(1)
{
- log(tr("EXCEPTION ERROR !!!"));
+ qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
}
+#else
+ checkedRun();
+#endif
- if(m_handle_jobObject)
+ if(m_jobObject)
{
- CloseHandle(m_handle_jobObject);
- m_handle_jobObject = NULL;
+ m_jobObject->terminateJob(42);
+ MUTILS_DELETE(m_jobObject);
}
}
-///////////////////////////////////////////////////////////////////////////////
-// Encode functions
-///////////////////////////////////////////////////////////////////////////////
-
-void EncodeThread::encode(void)
+void EncodeThread::checkedRun(void)
{
- QDateTime startTime = QDateTime::currentDateTime();
-
- //Print some basic info
- log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
- log(tr("Source file: %1").arg(m_sourceFileName));
- log(tr("Output file: %1").arg(m_outputFileName));
-
- //Print encoder settings
- log(tr("\n--- SETTINGS ---\n"));
- log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
- log(tr("Preset: %1").arg(m_options->preset()));
- log(tr("Tuning: %1").arg(m_options->tune()));
- log(tr("Profile: %1").arg(m_options->profile()));
- log(tr("Custom: %1").arg(m_options->custom().isEmpty() ? tr("(None)") : m_options->custom()));
-
- bool ok = false;
- unsigned int frames = 0;
-
- //Detect source info
- bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
- if(usePipe)
- {
- log(tr("\n--- AVS INFO ---\n"));
- ok = checkProperties(frames);
- CHECK_STATUS(m_abort, ok);
- }
-
- //Checking version
- log(tr("\n--- X264 VERSION ---\n"));
- unsigned int revision;
- ok = ((revision = checkVersion(m_x64)) != UINT_MAX);
- CHECK_STATUS(m_abort, ok);
-
- //Is revision supported?
- log(tr("\nx264 revision: %1 (core #%2)").arg(QString::number(revision % REV_MULT), QString::number(revision / REV_MULT)));
- if((revision % REV_MULT) < VER_X264_MINIMUM_REV)
- {
- log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
- setStatus(JobStatus_Failed);
- return;
- }
- if((revision / REV_MULT) != VER_X264_CURRENT_API)
- {
- log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
- log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
- }
-
- //Run encoding passes
- if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
- {
- QFileInfo info(m_outputFileName);
- QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
-
- if(QFileInfo(passLogFile).exists())
- {
- int n = 2;
- while(QFileInfo(passLogFile).exists())
- {
- passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
- }
- }
-
- log(tr("\n--- PASS 1 ---\n"));
- ok = runEncodingPass(m_x64, usePipe, frames, 1, passLogFile);
- CHECK_STATUS(m_abort, ok);
-
- log(tr("\n--- PASS 2 ---\n"));
- ok = runEncodingPass(m_x64, usePipe, frames, 2, passLogFile);
- CHECK_STATUS(m_abort, ok);
- }
- else
- {
- log(tr("\n--- ENCODING ---\n"));
- ok = runEncodingPass(m_x64, usePipe, frames);
- CHECK_STATUS(m_abort, ok);
- }
-
- log(tr("\n--- DONE ---\n"));
- int timePassed = startTime.secsTo(QDateTime::currentDateTime());
- 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)));
- setStatus(JobStatus_Completed);
-}
+ m_progress = 0;
+ m_status = JobStatus_Starting;
-bool EncodeThread::runEncodingPass(bool x64, bool usePipe, unsigned int frames, int pass, const QString &passLogFile)
-{
- QProcess processEncode, processAvisynth;
-
- if(usePipe)
+ try
{
- QStringList cmdLine_Avisynth;
- cmdLine_Avisynth << QDir::toNativeSeparators(m_sourceFileName);
- cmdLine_Avisynth << "-";
- processAvisynth.setStandardOutputProcess(&processEncode);
-
- log("Creating Avisynth process:");
- if(!startProcess(processAvisynth, QString("%1/avs2yuv.exe").arg(m_binDir), cmdLine_Avisynth, false))
+ try
{
- return false;
+ ExecutionStateHandler executionStateHandler;
+ encode();
}
- }
-
- QStringList cmdLine_Encode = buildCommandLine(usePipe, frames, pass, passLogFile);
-
- log("Creating x264 process:");
- if(!startProcess(processEncode, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine_Encode))
- {
- return false;
- }
-
- QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
- QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
- QRegExp regExpFrameCnt("^(\\d+) frames:");
-
- bool bTimeout = false;
- bool bAborted = false;
-
- while(processEncode.state() != QProcess::NotRunning)
- {
- if(m_abort)
+ catch(const std::exception &e)
{
- processEncode.kill();
- processAvisynth.kill();
- bAborted = true;
- break;
+ log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(e.what())));
+ setStatus(JobStatus_Failed);
}
- if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
+ catch(char *msg)
{
- if(processEncode.state() == QProcess::Running)
- {
- processEncode.kill();
- qWarning("x264 process timed out <-- killing!");
- log("\nPROCESS TIMEOUT !!!");
- bTimeout = true;
- break;
- }
+ log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
+ setStatus(JobStatus_Failed);
}
- while(processEncode.bytesAvailable() > 0)
+ catch(...)
{
- QList<QByteArray> lines = processEncode.readLine().split('\r');
- while(!lines.isEmpty())
- {
- QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
- int offset = -1;
- if((offset = regExpProgress.lastIndexIn(text)) >= 0)
- {
- bool ok = false;
- unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
- setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
- setDetails(text.mid(offset).trimmed());
- if(ok) setProgress(progress);
- }
- else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
- {
- bool ok = false;
- unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
- setStatus(JobStatus_Indexing);
- setDetails(text.mid(offset).trimmed());
- if(ok) setProgress(progress);
- }
- else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
- {
- setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
- setDetails(text.mid(offset).trimmed());
- }
- else if(!text.isEmpty())
- {
- log(text);
- }
- }
+ log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
+ setStatus(JobStatus_Failed);
}
}
-
- processEncode.waitForFinished(5000);
- if(processEncode.state() != QProcess::NotRunning)
- {
- qWarning("x264 process still running, going to kill it!");
- processEncode.kill();
- processEncode.waitForFinished(-1);
- }
-
- processAvisynth.waitForFinished(5000);
- if(processAvisynth.state() != QProcess::NotRunning)
- {
- qWarning("Avisynth process still running, going to kill it!");
- processAvisynth.kill();
- processAvisynth.waitForFinished(-1);
- }
-
- while(processAvisynth.bytesAvailable() > 0)
- {
- log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
- }
-
- if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
+ catch(...)
{
- if(!(bTimeout || bAborted))
- {
- log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
- }
+ MUtils::OS::fatal_exit(L"Unhandeled exception error in encode thread!");
}
+}
- if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
- {
- if(!(bTimeout || bAborted))
- {
- log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
- }
- processEncode.close();
- processAvisynth.close();
- return false;
- }
+void EncodeThread::start(Priority priority)
+{
+ qDebug("Thread starting...");
- switch(pass)
- {
- case 1:
- setStatus(JobStatus_Running_Pass1);
- setDetails(tr("First pass completed. Preparing for second pass..."));
- break;
- case 2:
- setStatus(JobStatus_Running_Pass2);
- setDetails(tr("Second pass completed successfully."));
- break;
- default:
- setStatus(JobStatus_Running);
- setDetails(tr("Encode completed successfully."));
- break;
- }
+ m_abort = false;
+ m_pause = false;
- setProgress(100);
- processEncode.close();
- processAvisynth.close();
- return true;
+ while(m_semaphorePaused.tryAcquire(1, 0));
+ QThread::start(priority);
}
-QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, int pass, const QString &passLogFile)
+///////////////////////////////////////////////////////////////////////////////
+// Encode functions
+///////////////////////////////////////////////////////////////////////////////
+
+void EncodeThread::encode(void)
{
- QStringList cmdLine;
+ QDateTime startTime = QDateTime::currentDateTime();
- switch(m_options->rcMode())
- {
- case OptionsModel::RCMode_CRF:
- cmdLine << "--crf" << QString::number(m_options->quantizer());
- break;
- case OptionsModel::RCMode_CQ:
- cmdLine << "--qp" << QString::number(m_options->quantizer());
- break;
- case OptionsModel::RCMode_2Pass:
- case OptionsModel::RCMode_ABR:
- cmdLine << "--bitrate" << QString::number(m_options->bitrate());
- break;
- default:
- throw "Bad rate-control mode !!!";
- break;
- }
-
- if((pass == 1) || (pass == 2))
- {
- cmdLine << "--pass" << QString::number(pass);
- cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
- }
+ // -----------------------------------------------------------------------------------
+ // Print Information
+ // -----------------------------------------------------------------------------------
- if(m_options->tune().compare("none", Qt::CaseInsensitive))
- {
- cmdLine << "--tune" << m_options->tune().toLower();
- }
+ //Print some basic info
+ log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), MUtils::Version::app_build_date().toString(Qt::ISODate)));
+ log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
+ log(tr("Source file : %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
+ log(tr("Output file : %1").arg(QDir::toNativeSeparators(m_outputFileName)));
- cmdLine << "--preset" << m_options->preset().toLower();
+ //Print system info
+ log(tr("\n--- SYSTEMINFO ---\n"));
+ log(tr("Binary Path : %1").arg(QDir::toNativeSeparators(m_sysinfo->getAppPath())));
+ log(tr("Avisynth : %1").arg(m_sysinfo->hasAvisynth() ? tr("Yes") : tr("No")));
+ log(tr("VapourSynth : %1").arg(m_sysinfo->hasVapourSynth() ? tr("Yes") : tr("No")));
- if(!m_options->custom().isEmpty())
- {
- //FIXME: Handle custom parameters that contain spaces!
- cmdLine.append(m_options->custom().split(" "));
- }
-
- cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
+ //Print encoder settings
+ log(tr("\n--- SETTINGS ---\n"));
+ log(tr("Encoder : %1").arg(m_encoder->getName()));
+ log(tr("Source : %1").arg(m_pipedSource ? m_pipedSource->getName() : tr("Native")));
+ log(tr("RC Mode : %1").arg(m_encoder->getEncoderInfo().rcModeToString(m_options->rcMode())));
+ log(tr("Preset : %1").arg(m_options->preset()));
+ log(tr("Tuning : %1").arg(m_options->tune()));
+ log(tr("Profile : %1").arg(m_options->profile()));
+ log(tr("Custom : %1").arg(m_options->customEncParams().isEmpty() ? tr("<None>") : m_options->customEncParams()));
- if(usePipe)
- {
- if(frames < 1) throw "Frames not set!";
- cmdLine << "--frames" << QString::number(frames);
- cmdLine << "--demuxer" << "y4m";
- cmdLine << "--stdin" << "y4m" << "-";
- }
- else
- {
- cmdLine << QDir::toNativeSeparators(m_sourceFileName);
- }
-
- return cmdLine;
-}
+ bool ok = false;
+ ClipInfo clipInfo;
+
+ // -----------------------------------------------------------------------------------
+ // Check Versions
+ // -----------------------------------------------------------------------------------
+
+ log(tr("\n--- CHECK VERSION ---\n"));
-unsigned int EncodeThread::checkVersion(bool x64)
-{
- QProcess process;
- QStringList cmdLine = QStringList() << "--version";
+ unsigned int encoderRevision = UINT_MAX, sourceRevision = UINT_MAX;
+ bool encoderModified = false, sourceModified = false;
- log("Creating process:");
- if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
- {
- return false;;
- }
+ log("Detect video encoder version:\n");
- QRegExp regExpVersion("x264 (\\d)\\.(\\d+)\\.(\\d+) ([0-9A-Fa-f]{7})");
-
- bool bTimeout = false;
- bool bAborted = false;
+ //Check encoder version
+ encoderRevision = m_encoder->checkVersion(encoderModified);
+ CHECK_STATUS(m_abort, (ok = (encoderRevision != UINT_MAX)));
- unsigned int revision = UINT_MAX;
- unsigned int coreVers = UINT_MAX;
+ //Is encoder version suppoprted?
+ CHECK_STATUS(m_abort, (ok = m_encoder->isVersionSupported(encoderRevision, encoderModified)));
- while(process.state() != QProcess::NotRunning)
+ if(m_pipedSource)
{
- if(m_abort)
- {
- process.kill();
- bAborted = true;
- break;
- }
- if(!process.waitForReadyRead(m_processTimeoutInterval))
- {
- if(process.state() == QProcess::Running)
- {
- process.kill();
- qWarning("x264 process timed out <-- killing!");
- log("\nPROCESS TIMEOUT !!!");
- bTimeout = true;
- break;
- }
- }
- while(process.bytesAvailable() > 0)
- {
- QList<QByteArray> lines = process.readLine().split('\r');
- while(!lines.isEmpty())
- {
- QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
- int offset = -1;
- if((offset = regExpVersion.lastIndexIn(text)) >= 0)
- {
- bool ok1 = false, ok2 = false;
- unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
- unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
- if(ok1) coreVers = temp1;
- if(ok2) revision = temp2;
- }
- if(!text.isEmpty())
- {
- log(text);
- }
- }
- }
- }
+ log("\nDetect video source version:\n");
- process.waitForFinished();
- if(process.state() != QProcess::NotRunning)
- {
- process.kill();
- process.waitForFinished(-1);
- }
+ //Is source type available?
+ CHECK_STATUS(m_abort, (ok = m_pipedSource->isSourceAvailable()));
- if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
- {
- if(!(bTimeout || bAborted))
- {
- log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
- }
- return UINT_MAX;
+ //Checking source version
+ sourceRevision = m_pipedSource->checkVersion(sourceModified);
+ CHECK_STATUS(m_abort, (ok = (sourceRevision != UINT_MAX)));
+
+ //Is source version supported?
+ CHECK_STATUS(m_abort, (ok = m_pipedSource->isVersionSupported(sourceRevision, sourceModified)));
}
- if((revision == UINT_MAX) || (coreVers == UINT_MAX))
+ //Print tool versions
+ log(QString("\n> %1").arg(m_encoder->printVersion(encoderRevision, encoderModified)));
+ if(m_pipedSource)
{
- log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
- return UINT_MAX;
+ log(QString("> %1").arg(m_pipedSource->printVersion(sourceRevision, sourceModified)));
}
-
- return (coreVers * REV_MULT) + revision;
-}
-bool EncodeThread::checkProperties(unsigned int &frames)
-{
- QProcess process;
-
- QStringList cmdLine = QStringList() << "-frames" << "1";
- cmdLine << QDir::toNativeSeparators(m_sourceFileName) << "NUL";
+ // -----------------------------------------------------------------------------------
+ // Detect Source Info
+ // -----------------------------------------------------------------------------------
- log("Creating process:");
- if(!startProcess(process, QString("%1/avs2yuv.exe").arg(m_binDir), cmdLine))
+ //Detect source info
+ if(m_pipedSource)
{
- return false;;
+ log(tr("\n--- GET SOURCE INFO ---\n"));
+ ok = m_pipedSource->checkSourceProperties(clipInfo);
+ CHECK_STATUS(m_abort, ok);
}
- QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
- QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
-
- bool bTimeout = false;
- bool bAborted = false;
+ // -----------------------------------------------------------------------------------
+ // Encoding Passes
+ // -----------------------------------------------------------------------------------
- frames = 0;
-
- unsigned int fpsNom = 0;
- unsigned int fpsDen = 0;
- unsigned int fSizeW = 0;
- unsigned int fSizeH = 0;
-
- while(process.state() != QProcess::NotRunning)
+ //Run encoding passes
+ if(m_encoder->getEncoderInfo().rcModeToType(m_options->rcMode()) == AbstractEncoderInfo::RC_TYPE_MULTIPASS)
{
- if(m_abort)
- {
- process.kill();
- bAborted = true;
- break;
- }
- if(!process.waitForReadyRead(m_processTimeoutInterval))
- {
- if(process.state() == QProcess::Running)
- {
- process.kill();
- qWarning("x264 process timed out <-- killing!");
- log("\nPROCESS TIMEOUT !!!");
- bTimeout = true;
- break;
- }
- }
- while(process.bytesAvailable() > 0)
- {
- QList<QByteArray> lines = process.readLine().split('\r');
- while(!lines.isEmpty())
- {
- QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
- int offset = -1;
- if((offset = regExpInt.lastIndexIn(text)) >= 0)
- {
- bool ok1 = false, ok2 = false;
- bool ok3 = false, ok4 = false;
- unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
- unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
- unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
- unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
- if(ok1) fSizeW = temp1;
- if(ok2) fSizeH = temp2;
- if(ok3) fpsNom = temp3;
- if(ok4) frames = temp4;
- }
- else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
- {
- bool ok1 = false, ok2 = false;
- bool ok3 = false, ok4 = false, ok5 = false;
- unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
- unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
- unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
- unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
- unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
- if(ok1) fSizeW = temp1;
- if(ok2) fSizeH = temp2;
- if(ok3) fpsNom = temp3;
- if(ok4) fpsDen = temp4;
- if(ok5) frames = temp5;
- }
- if(!text.isEmpty())
- {
- log(text);
- }
- }
- }
- }
+ const QString passLogFile = getPasslogFile(m_outputFileName);
+
+ log(tr("\n--- ENCODING PASS #1 ---\n"));
+ ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo, 1, passLogFile);
+ CHECK_STATUS(m_abort, ok);
- process.waitForFinished();
- if(process.state() != QProcess::NotRunning)
- {
- process.kill();
- process.waitForFinished(-1);
+ log(tr("\n--- ENCODING PASS #2 ---\n"));
+ ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo, 2, passLogFile);
+ CHECK_STATUS(m_abort, ok);
}
-
- if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
+ else
{
- if(!(bTimeout || bAborted))
- {
- log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
- }
- return false;
+ log(tr("\n--- ENCODING VIDEO ---\n"));
+ ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo);
+ CHECK_STATUS(m_abort, ok);
}
- if(frames == 0)
- {
- log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
- return false;
- }
-
- log("");
+ // -----------------------------------------------------------------------------------
+ // Encoding complete
+ // -----------------------------------------------------------------------------------
- if((fSizeW > 0) && (fSizeH > 0))
- {
- log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
- }
- if((fpsNom > 0) && (fpsDen > 0))
- {
- log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
- }
- if((fpsNom > 0) && (fpsDen == 0))
- {
- log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
- }
- if(frames > 0)
- {
- log(tr("No. Frames: %1").arg(QString::number(frames)));
- }
+ log(tr("\n--- COMPLETED ---\n"));
- return true;
+ int timePassed = startTime.secsTo(QDateTime::currentDateTime());
+ 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)));
+ setStatus(JobStatus_Completed);
}
///////////////////////////////////////////////////////////////////////////////
// Misc functions
///////////////////////////////////////////////////////////////////////////////
-void EncodeThread::setStatus(JobStatus newStatus)
+void EncodeThread::log(const QString &text)
+{
+ emit messageLogged(m_jobId, QDateTime::currentMSecsSinceEpoch(), text);
+}
+
+void EncodeThread::setStatus(const JobStatus &newStatus)
{
if(m_status != newStatus)
{
- m_status = newStatus;
- if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted))
+ if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
{
- setProgress(0);
+ if(m_status != JobStatus_Paused) setProgress(0);
}
if(newStatus == JobStatus_Failed)
{
{
setDetails("The job was aborted by the user!");
}
+ m_status = newStatus;
emit statusChanged(m_jobId, newStatus);
}
}
-void EncodeThread::setProgress(unsigned int newProgress)
+void EncodeThread::setProgress(const unsigned int &newProgress)
{
if(m_progress != newProgress)
{
void EncodeThread::setDetails(const QString &text)
{
- emit detailsChanged(m_jobId, text);
-}
-
-bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
-{
- static AssignProcessToJobObjectFun AssignProcessToJobObjectPtr = NULL;
- static CreateJobObjectFun CreateJobObjectPtr = NULL;
- static SetInformationJobObjectFun SetInformationJobObjectPtr = NULL;
-
- QMutexLocker lock(&m_mutex_startProcess);
- log(commandline2string(program, args) + "\n");
-
- //Create a new job object, if not done yet
- if(!m_handle_jobObject)
- {
- if(!CreateJobObjectPtr || !SetInformationJobObjectPtr)
- {
- QLibrary Kernel32Lib("kernel32.dll");
- CreateJobObjectPtr = (CreateJobObjectFun) Kernel32Lib.resolve("CreateJobObjectA");
- SetInformationJobObjectPtr = (SetInformationJobObjectFun) Kernel32Lib.resolve("SetInformationJobObject");
- }
- if(CreateJobObjectPtr && SetInformationJobObjectPtr)
- {
- m_handle_jobObject = CreateJobObjectPtr(NULL, NULL);
- if(m_handle_jobObject == INVALID_HANDLE_VALUE)
- {
- m_handle_jobObject = NULL;
- }
- if(m_handle_jobObject)
- {
- JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
- memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
- jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
- SetInformationJobObjectPtr(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
- }
- }
- }
-
- //Initialize AssignProcessToJobObject function
- if(!AssignProcessToJobObjectPtr)
- {
- QLibrary Kernel32Lib("kernel32.dll");
- AssignProcessToJobObjectPtr = (AssignProcessToJobObjectFun) Kernel32Lib.resolve("AssignProcessToJobObject");
- }
-
- if(mergeChannels)
- {
- process.setProcessChannelMode(QProcess::MergedChannels);
- process.setReadChannel(QProcess::StandardOutput);
- }
- else
+ if((!text.isEmpty()) && (m_details.compare(text) != 0))
{
- process.setProcessChannelMode(QProcess::SeparateChannels);
- process.setReadChannel(QProcess::StandardError);
+ emit detailsChanged(m_jobId, text);
+ m_details = text;
}
-
- process.start(program, args);
-
- if(process.waitForStarted())
- {
- if(AssignProcessToJobObjectPtr)
- {
- AssignProcessToJobObjectPtr(m_handle_jobObject, process.pid()->hProcess);
- }
- if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
- {
- SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
- }
-
- lock.unlock();
- return true;
- }
-
- log("Process creation has failed :-(");
- QString errorMsg= process.errorString().trimmed();
- if(!errorMsg.isEmpty()) log(errorMsg);
-
- process.kill();
- process.waitForFinished(-1);
- return false;
}
-QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
+QString EncodeThread::getPasslogFile(const QString &outputFile)
{
- QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
-
- for(int i = 0; i < arguments.count(); i++)
+ QFileInfo info(outputFile);
+ QString passLogFile = QString("%1/%2.stats").arg(info.absolutePath(), info.completeBaseName());
+ int counter = 1;
+
+ while(QFileInfo(passLogFile).exists())
{
- commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
+ passLogFile = QString("%1/%2_%3.stats").arg(info.absolutePath(), info.completeBaseName(), QString::number(++counter));
}
- return commandline;
+ return passLogFile;
}