OSDN Git Service

Much improved VapourSynth detection + added option "--no-deadlock-detection" to disab...
[x264-launcher/x264-launcher.git] / src / thread_encode.cpp
index 2163764..0ca637c 100644 (file)
@@ -1,6 +1,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 // Simple x264 Launcher
-// Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2013 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
@@ -23,6 +23,7 @@
 
 #include "global.h"
 #include "model_options.h"
+#include "model_preferences.h"
 #include "version.h"
 
 #include <QDate>
 #include <QDir>
 #include <QProcess>
 #include <QMutex>
-#include <QLibrary>
-
-/*
- * Win32 API definitions
- */
-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);
+#include <QTextCodec>
+#include <QLocale>
 
 /*
  * Static vars
@@ -49,41 +44,87 @@ QMutex EncodeThread::m_mutex_startProcess;
 /*
  * 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(indexFile).exists()) QFile::remove(indexFile); \
+               if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
                return; \
        } \
        else if(!(OK_FLAG)) \
        { \
                setStatus(JobStatus_Failed); \
+               if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
+               if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
                return; \
        } \
-}
+} \
+while(0)
+
+#define APPEND_AND_CLEAR(LIST, STR) do \
+{ \
+       if(!((STR).isEmpty())) \
+       { \
+               (LIST) << (STR); \
+               (STR).clear(); \
+       } \
+} \
+while(0)
+
+#define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
+{ \
+       if(ITER != LIST.end()) \
+       { \
+               if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
+               { \
+                       log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
+                       ITER = LIST.erase(ITER); \
+                       if(ITER != LIST.end()) \
+                       { \
+                               if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
+                       } \
+                       FLAG = true; \
+               } \
+       } \
+} \
+while(0)
+
+#define AVS2_BINARY(BIN_DIR, IS_X64) (QString("%1/%2/avs2yuv_%2.exe").arg((BIN_DIR), ((IS_X64) ? "x64" : "x86")))
+#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")))
+#define VPSP_BINARY(VPS_DIR) (QString("%1/vspipe.exe").arg((VPS_DIR)))
 
 /*
  * Static vars
  */
 static const unsigned int REV_MULT = 10000;
+static const char *VPS_TEST_FILE = "import vapoursynth as vs\ncore = vs.get_core()\nv = core.std.BlankClip()\nv.set_output()\n";
 
 ///////////////////////////////////////////////////////////////////////////////
 // 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 QString &binDir, const QString &vpsDir, const bool &x264_x64, const bool &x264_10bit, const bool &avs2yuv_x64, const bool &skipVersionTest, const int &processPriroity, const bool &abortOnTimeout)
 :
        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_vpsDir(vpsDir),
+       m_x264_x64(x264_x64),
+       m_x264_10bit(x264_10bit),
+       m_avs2yuv_x64(avs2yuv_x64),
+       m_skipVersionTest(skipVersionTest),
+       m_processPriority(processPriroity),
+       m_abortOnTimeout(abortOnTimeout),
+       m_handle_jobObject(NULL),
+       m_semaphorePaused(0)
 {
        m_abort = false;
+       m_pause = false;
 }
 
 EncodeThread::~EncodeThread(void)
@@ -103,27 +144,63 @@ EncodeThread::~EncodeThread(void)
 
 void EncodeThread::run(void)
 {
+#if !defined(_DEBUG)
+       __try
+       {
+               checkedRun();
+       }
+       __except(1)
+       {
+               qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
+       }
+#else
+       checkedRun();
+#endif
+
+       if(m_handle_jobObject)
+       {
+               TerminateJobObject(m_handle_jobObject, 42);
+               m_handle_jobObject = NULL;
+       }
+}
+
+void EncodeThread::checkedRun(void)
+{
        m_progress = 0;
        m_status = JobStatus_Starting;
 
        try
        {
-               encode();
-       }
-       catch(char *msg)
-       {
-               log(tr("EXCEPTION ERROR: ").append(QString::fromLatin1(msg)));
+               try
+               {
+                       encode();
+               }
+               catch(char *msg)
+               {
+                       log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
+                       setStatus(JobStatus_Failed);
+               }
+               catch(...)
+               {
+                       log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
+                       setStatus(JobStatus_Failed);
+               }
        }
        catch(...)
        {
-               log(tr("EXCEPTION ERROR !!!"));
+               RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
        }
+}
 
-       if(m_handle_jobObject)
-       {
-               CloseHandle(m_handle_jobObject);
-               m_handle_jobObject = NULL;
-       }
+void EncodeThread::start(Priority priority)
+{
+       qDebug("Thread starting...");
+
+       m_abort = false;
+       m_pause = false;
+
+       while(m_semaphorePaused.tryAcquire(1, 0));
+       QThread::start(priority);
 }
 
 ///////////////////////////////////////////////////////////////////////////////
@@ -133,11 +210,12 @@ void EncodeThread::run(void)
 void EncodeThread::encode(void)
 {
        QDateTime startTime = QDateTime::currentDateTime();
-       
+
        //Print some basic info
+       log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_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(m_sourceFileName));
-       log(tr("Output file: %1").arg(m_outputFileName));
+       log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
+       log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
        
        //Print encoder settings
        log(tr("\n--- SETTINGS ---\n"));
@@ -145,57 +223,77 @@ void EncodeThread::encode(void)
        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()));
+       log(tr("Custom:  %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
        
+       log(m_binDir);
+
        bool ok = false;
        unsigned int frames = 0;
 
-       //Use Avisynth?
-       const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
+       //Seletct type of input
+       const int inputType = getInputType(QFileInfo(m_sourceFileName).suffix());
+       const QString indexFile = QString("%1/%2.ffindex").arg(QDir::tempPath(), m_jobId.toString());
 
        //Checking x264 version
        log(tr("\n--- CHECK VERSION ---\n"));
        unsigned int revision_x264 = UINT_MAX;
-       ok = ((revision_x264 = checkVersionX264(m_x64)) != UINT_MAX);
+       bool x264_modified = false;
+       ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
        CHECK_STATUS(m_abort, ok);
        
        //Checking avs2yuv version
        unsigned int revision_avs2yuv = UINT_MAX;
-       if(usePipe)
+       switch(inputType)
        {
-               ok = ((revision_avs2yuv = checkVersionAvs2yuv()) != UINT_MAX);
+       case INPUT_AVISYN:
+               ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
                CHECK_STATUS(m_abort, ok);
+               break;
+       case INPUT_VAPOUR:
+               ok = checkVersionVapoursynth();
+               CHECK_STATUS(m_abort, ok);
+               break;
        }
 
        //Print versions
-       log(tr("\nx264 revision: %1 (core #%2)").arg(QString::number(revision_x264 % REV_MULT), QString::number(revision_x264 / REV_MULT)));
+       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()));
        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)));
 
        //Is x264 revision supported?
-       if((revision_x264 % REV_MULT) < VER_X264_MINIMUM_REV)
+       if((revision_x264 % 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_x264 / REV_MULT) != VER_X264_CURRENT_API)
+       if((revision_x264 / 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)));
        }
-       if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != 242))
+       if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
        {
-               log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version is v0.24bm2)"));
+               log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
+               log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
                setStatus(JobStatus_Failed);
                return;
        }
 
        //Detect source info
-       if(usePipe)
+       if(inputType != INPUT_NATIVE)
        {
-               log(tr("\n--- AVS INFO ---\n"));
-               ok = checkProperties(frames);
-               CHECK_STATUS(m_abort, ok);
+               log(tr("\n--- SOURCE INFO ---\n"));
+               switch(inputType)
+               {
+               case INPUT_AVISYN:
+                       ok = checkPropertiesAvisynth(m_avs2yuv_x64, frames);
+                       CHECK_STATUS(m_abort, ok);
+                       break;
+               case INPUT_VAPOUR:
+                       ok = checkPropertiesVapoursynth(frames);
+                       CHECK_STATUS(m_abort, ok);
+                       break;
+               }
        }
 
        //Run encoding passes
@@ -214,109 +312,198 @@ void EncodeThread::encode(void)
                }
                
                log(tr("\n--- PASS 1 ---\n"));
-               ok = runEncodingPass(m_x64, usePipe, frames, 1, passLogFile);
+               ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 1, passLogFile);
                CHECK_STATUS(m_abort, ok);
 
                log(tr("\n--- PASS 2 ---\n"));
-               ok = runEncodingPass(m_x64, usePipe, frames, 2, passLogFile);
+               ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 2, passLogFile);
                CHECK_STATUS(m_abort, ok);
        }
        else
        {
                log(tr("\n--- ENCODING ---\n"));
-               ok = runEncodingPass(m_x64, usePipe, frames);
+               ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile);
                CHECK_STATUS(m_abort, ok);
        }
 
        log(tr("\n--- DONE ---\n"));
+       if(QFileInfo(indexFile).exists()) QFile::remove(indexFile);
        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);
 }
 
-bool EncodeThread::runEncodingPass(bool x64, bool usePipe, unsigned int frames, int pass, const QString &passLogFile)
+bool EncodeThread::runEncodingPass(bool x264_x64, bool x264_10bit, bool avs2yuv_x64, int inputType, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
 {
-       QProcess processEncode, processAvisynth;
+       QProcess processEncode, processInput;
        
-       if(usePipe)
+       if(inputType != INPUT_NATIVE)
        {
-               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))
+               QStringList cmdLine_Input;
+               processInput.setStandardOutputProcess(&processEncode);
+               switch(inputType)
                {
-                       return false;
+               case INPUT_AVISYN:
+                       if(!m_options->customAvs2YUV().isEmpty())
+                       {
+                               cmdLine_Input.append(splitParams(m_options->customAvs2YUV()));
+                       }
+                       cmdLine_Input << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
+                       cmdLine_Input << "-";
+                       log("Creating Avisynth process:");
+                       if(!startProcess(processInput, AVS2_BINARY(m_binDir, avs2yuv_x64), cmdLine_Input, false))
+                       {
+                               return false;
+                       }
+                       break;
+               case INPUT_VAPOUR:
+                       cmdLine_Input << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
+                       cmdLine_Input << "-" << "-y4m";
+                       log("Creating Vapoursynth process:");
+                       if(!startProcess(processInput, VPSP_BINARY(m_vpsDir), cmdLine_Input, false))
+                       {
+                               return false;
+                       }
+                       break;
+               default:
+                       throw "Bad input type encontered!";
                }
        }
 
-       QStringList cmdLine_Encode = buildCommandLine(usePipe, frames, pass, passLogFile);
+       QStringList cmdLine_Encode = buildCommandLine((inputType != INPUT_NATIVE), x264_10bit, frames, indexFile, pass, passLogFile);
 
        log("Creating x264 process:");
-       if(!startProcess(processEncode, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine_Encode))
+       if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
        {
                return false;
        }
 
-       QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
-       QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
+       QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
+       QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
        QRegExp regExpFrameCnt("^(\\d+) frames:");
        
+       QTextCodec *localCodec = QTextCodec::codecForName("System");
+
        bool bTimeout = false;
        bool bAborted = false;
 
+       unsigned int last_progress = UINT_MAX;
+       unsigned int last_indexing = UINT_MAX;
+       qint64 size_estimate = 0I64;
+
+       //Main processing loop
        while(processEncode.state() != QProcess::NotRunning)
        {
-               if(m_abort)
-               {
-                       processEncode.kill();
-                       processAvisynth.kill();
-                       bAborted = true;
-                       break;
-               }
-               if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
+               unsigned int waitCounter = 0;
+
+               //Wait until new output is available
+               forever
                {
-                       if(processEncode.state() == QProcess::Running)
+                       if(m_abort)
                        {
                                processEncode.kill();
-                               qWarning("x264 process timed out <-- killing!");
-                               log("\nPROCESS TIMEOUT !!!");
-                               bTimeout = true;
+                               processInput.kill();
+                               bAborted = true;
                                break;
                        }
+                       if(m_pause && (processEncode.state() == QProcess::Running))
+                       {
+                               JobStatus previousStatus = m_status;
+                               setStatus(JobStatus_Paused);
+                               log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
+                               bool ok[2] = {false, false};
+                               Q_PID pid[2] = {processEncode.pid(), processInput.pid()};
+                               if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
+                               if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
+                               while(m_pause) m_semaphorePaused.tryAcquire(1, 5000);
+                               while(m_semaphorePaused.tryAcquire(1, 0));
+                               if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
+                               if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
+                               if(!m_abort) setStatus(previousStatus);
+                               log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
+                               waitCounter = 0;
+                               continue;
+                       }
+                       if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
+                       {
+                               if(processEncode.state() == QProcess::Running)
+                               {
+                                       if(++waitCounter > m_processTimeoutMaxCounter)
+                                       {
+                                               if(m_abortOnTimeout)
+                                               {
+                                                       processEncode.kill();
+                                                       qWarning("x264 process timed out <-- killing!");
+                                                       log("\nPROCESS TIMEOUT !!!");
+                                                       bTimeout = true;
+                                                       break;
+                                               }
+                                       }
+                                       else if(waitCounter == m_processTimeoutWarning)
+                                       {
+                                               unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
+                                               log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
+                                       }
+                                       continue;
+                               }
+                       }
+                       if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
+                       {
+                               continue;
+                       }
+                       break;
+               }
+               
+               //Exit main processing loop now?
+               if(bAborted || bTimeout)
+               {
+                       break;
                }
+
+               //Process all output
                while(processEncode.bytesAvailable() > 0)
                {
                        QList<QByteArray> lines = processEncode.readLine().split('\r');
                        while(!lines.isEmpty())
                        {
-                               QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
+                               QString text = localCodec->toUnicode(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);
+                                       if(ok && ((progress > last_progress) || (last_progress == UINT_MAX)))
+                                       {
+                                               setProgress(progress);
+                                               size_estimate = estimateSize(progress);
+                                               last_progress = progress;
+                                       }
+                                       setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate)));
+                                       last_indexing = UINT_MAX;
                                }
                                else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
                                {
                                        bool ok = false;
                                        unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
                                        setStatus(JobStatus_Indexing);
+                                       if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
+                                       {
+                                               setProgress(progress);
+                                               last_indexing = progress;
+                                       }
                                        setDetails(text.mid(offset).trimmed());
-                                       if(ok) setProgress(progress);
+                                       last_progress = UINT_MAX;
                                }
                                else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
                                {
+                                       last_progress = last_indexing = UINT_MAX;
                                        setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
                                        setDetails(text.mid(offset).trimmed());
                                }
                                else if(!text.isEmpty())
                                {
+                                       last_progress = last_indexing = UINT_MAX;
                                        log(text);
                                }
                        }
@@ -331,24 +518,35 @@ bool EncodeThread::runEncodingPass(bool x64, bool usePipe, unsigned int frames,
                processEncode.waitForFinished(-1);
        }
        
-       processAvisynth.waitForFinished(5000);
-       if(processAvisynth.state() != QProcess::NotRunning)
+       processInput.waitForFinished(5000);
+       if(processInput.state() != QProcess::NotRunning)
        {
-               qWarning("Avisynth process still running, going to kill it!");
-               processAvisynth.kill();
-               processAvisynth.waitForFinished(-1);
+               qWarning("Input process still running, going to kill it!");
+               processInput.kill();
+               processInput.waitForFinished(-1);
        }
 
-       while(processAvisynth.bytesAvailable() > 0)
+       if(!(bTimeout || bAborted))
        {
-               log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
+               while(processInput.bytesAvailable() > 0)
+               {
+                       switch(inputType)
+                       {
+                       case INPUT_AVISYN:
+                               log(tr("av2y [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
+                               break;
+                       case INPUT_VAPOUR:
+                               log(tr("vpyp [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
+                               break;
+                       }
+               }
        }
 
-       if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
+       if((inputType != INPUT_NATIVE) && (processInput.exitCode() != EXIT_SUCCESS))
        {
                if(!(bTimeout || bAborted))
                {
-                       log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
+                       log(tr("\nWARNING: Input process exited with error code: %1").arg(QString::number(processInput.exitCode())));
                }
        }
 
@@ -359,10 +557,16 @@ bool EncodeThread::runEncodingPass(bool x64, bool usePipe, unsigned int frames,
                        log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
                }
                processEncode.close();
-               processAvisynth.close();
+               processInput.close();
                return false;
        }
 
+       QThread::yieldCurrentThread();
+
+       const qint64 finalSize = QFileInfo(m_outputFileName).size();
+       QLocale locale(QLocale::English);
+       log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
+
        switch(pass)
        {
        case 1:
@@ -371,31 +575,33 @@ bool EncodeThread::runEncodingPass(bool x64, bool usePipe, unsigned int frames,
                break;
        case 2:
                setStatus(JobStatus_Running_Pass2);
-               setDetails(tr("Second pass completed successfully."));
+               setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
                break;
        default:
                setStatus(JobStatus_Running);
-               setDetails(tr("Encode completed successfully."));
+               setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
                break;
        }
 
        setProgress(100);
        processEncode.close();
-       processAvisynth.close();
+       processInput.close();
        return true;
 }
 
-QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, int pass, const QString &passLogFile)
+QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
 {
        QStringList cmdLine;
+       double crf_int = 0.0, crf_frc = 0.0;
 
        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());
+               cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
+               break;
+       case OptionsModel::RCMode_CRF:
+               crf_frc = modf(m_options->quantizer(), &crf_int);
+               cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
                break;
        case OptionsModel::RCMode_2Pass:
        case OptionsModel::RCMode_ABR:
@@ -409,23 +615,53 @@ QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, in
        if((pass == 1) || (pass == 2))
        {
                cmdLine << "--pass" << QString::number(pass);
-               cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
+               cmdLine << "--stats" << pathToLocal(QDir::toNativeSeparators(passLogFile), true);
        }
 
+       cmdLine << "--preset" << m_options->preset().toLower();
+
        if(m_options->tune().compare("none", Qt::CaseInsensitive))
        {
                cmdLine << "--tune" << m_options->tune().toLower();
        }
-       
-       cmdLine << "--preset" << m_options->preset().toLower();
 
-       if(!m_options->custom().isEmpty())
+       if(m_options->profile().compare("auto", Qt::CaseInsensitive))
        {
-               //FIXME: Handle custom parameters that contain spaces!
-               cmdLine.append(m_options->custom().split(" "));
+               if(use10Bit)
+               {
+                       if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
+                       {
+                               log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
+                       }
+                       else
+                       {
+                               cmdLine << "--profile" << m_options->profile().toLower();
+                       }
+               }
+               else
+               {
+                       cmdLine << "--profile" << m_options->profile().toLower();
+               }
        }
 
-       cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
+       if(!m_options->customX264().isEmpty())
+       {
+               QStringList customArgs = splitParams(m_options->customX264());
+               if(usePipe)
+               {
+                       QStringList::iterator i = customArgs.begin();
+                       while(i != customArgs.end())
+                       {
+                               bool bModified = false;
+                               REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
+                               REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
+                               if(!bModified) i++;
+                       }
+               }
+               cmdLine.append(customArgs);
+       }
+
+       cmdLine << "--output" << pathToLocal(QDir::toNativeSeparators(m_outputFileName), true);
        
        if(usePipe)
        {
@@ -436,30 +672,39 @@ QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, in
        }
        else
        {
-               cmdLine << QDir::toNativeSeparators(m_sourceFileName);
+               cmdLine << "--index" << pathToLocal(QDir::toNativeSeparators(indexFile), true, false);
+               cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
        }
 
        return cmdLine;
 }
 
-unsigned int EncodeThread::checkVersionX264(bool x64)
+unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
 {
+       if(m_skipVersionTest)
+       {
+               log("Warning: Skipping x264 version check this time!");
+               return (999 * REV_MULT) + (9999 % REV_MULT);
+       }
+
        QProcess process;
        QStringList cmdLine = QStringList() << "--version";
 
        log("Creating process:");
-       if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
+       if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
        {
                return false;;
        }
 
-       QRegExp regExpVersion("x264 (\\d)\\.(\\d+)\\.(\\d+) ([0-9A-Fa-f]{7})");
+       QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
+       QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
        
        bool bTimeout = false;
        bool bAborted = false;
 
        unsigned int revision = UINT_MAX;
        unsigned int coreVers = UINT_MAX;
+       modified = false;
 
        while(process.state() != QProcess::NotRunning)
        {
@@ -469,7 +714,7 @@ unsigned int EncodeThread::checkVersionX264(bool x64)
                        bAborted = true;
                        break;
                }
-               if(!process.waitForReadyRead(m_processTimeoutInterval))
+               if(!process.waitForReadyRead())
                {
                        if(process.state() == QProcess::Running)
                        {
@@ -495,6 +740,15 @@ unsigned int EncodeThread::checkVersionX264(bool x64)
                                        if(ok1) coreVers = temp1;
                                        if(ok2) revision = temp2;
                                }
+                               else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
+                               {
+                                       bool ok1 = false, ok2 = false;
+                                       unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
+                                       unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
+                                       if(ok1) coreVers = temp1;
+                                       if(ok2) revision = temp2;
+                                       modified = true;
+                               }
                                if(!text.isEmpty())
                                {
                                        log(text);
@@ -528,24 +782,25 @@ unsigned int EncodeThread::checkVersionX264(bool x64)
        return (coreVers * REV_MULT) + (revision % REV_MULT);
 }
 
-unsigned int EncodeThread::checkVersionAvs2yuv(void)
+unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
 {
        QProcess process;
 
        log("\nCreating process:");
-       if(!startProcess(process, QString("%1/avs2yuv.exe").arg(m_binDir), QStringList()))
+       if(!startProcess(process, AVS2_BINARY(m_binDir, x64), QStringList()))
        {
                return false;;
        }
 
-       QRegExp regExpVersion("Avs2YUV (\\d+).(\\d+)bm(\\d)");
+       QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
+       QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
        
        bool bTimeout = false;
        bool bAborted = false;
 
        unsigned int ver_maj = UINT_MAX;
        unsigned int ver_min = UINT_MAX;
-       unsigned int ver_bld = UINT_MAX;
+       unsigned int ver_mod = 0;
 
        while(process.state() != QProcess::NotRunning)
        {
@@ -555,7 +810,7 @@ unsigned int EncodeThread::checkVersionAvs2yuv(void)
                        bAborted = true;
                        break;
                }
-               if(!process.waitForReadyRead(m_processTimeoutInterval))
+               if(!process.waitForReadyRead())
                {
                        if(process.state() == QProcess::Running)
                        {
@@ -573,22 +828,30 @@ unsigned int EncodeThread::checkVersionAvs2yuv(void)
                        {
                                QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
                                int offset = -1;
-                               if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_bld == UINT_MAX))
+                               if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
                                {
                                        if(!text.isEmpty())
                                        {
                                                log(text);
                                        }
                                }
-                               if((offset = regExpVersion.lastIndexIn(text)) >= 0)
+                               if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
                                {
                                        bool ok1 = false, ok2 = false, ok3 = false;
-                                       unsigned int temp1 = regExpVersion.cap(1).toUInt(&ok1);
-                                       unsigned int temp2 = regExpVersion.cap(2).toUInt(&ok2);
-                                       unsigned int temp3 = regExpVersion.cap(3).toUInt(&ok3);
+                                       unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
+                                       unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
+                                       unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
+                                       if(ok1) ver_maj = temp1;
+                                       if(ok2) ver_min = temp2;
+                                       if(ok3) ver_mod = temp3;
+                               }
+                               else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
+                               {
+                                       bool ok1 = false, ok2 = false;
+                                       unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
+                                       unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
                                        if(ok1) ver_maj = temp1;
                                        if(ok2) ver_min = temp2;
-                                       if(ok3) ver_bld = temp3;
                                }
                        }
                }
@@ -610,24 +873,116 @@ unsigned int EncodeThread::checkVersionAvs2yuv(void)
                return UINT_MAX;
        }
 
-       if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_bld == UINT_MAX))
+       if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
        {
                log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
                return UINT_MAX;
        }
        
-       return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_bld % 10);
+       return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
 }
 
-bool EncodeThread::checkProperties(unsigned int &frames)
+bool EncodeThread::checkVersionVapoursynth(/*const QString &vspipePath*/)
 {
+       //Is VapourSynth available at all?
+       if(m_vpsDir.isEmpty() || (!QFileInfo(VPSP_BINARY(m_vpsDir)).isFile()))
+       {
+               log(tr("\nVPY INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
+               return false;
+       }
+
        QProcess process;
+
+       log("\nCreating process:");
+       if(!startProcess(process, VPSP_BINARY(m_vpsDir), QStringList()))
+       {
+               return false;;
+       }
+
+       QRegExp regExpSignature("\\bVSPipe\\s+usage\\b", Qt::CaseInsensitive);
        
-       QStringList cmdLine = QStringList() << "-frames" << "1";
-       cmdLine << QDir::toNativeSeparators(m_sourceFileName) << "NUL";
+       bool bTimeout = false;
+       bool bAborted = false;
+
+       bool vspipeSignature = false;
+
+       while(process.state() != QProcess::NotRunning)
+       {
+               if(m_abort)
+               {
+                       process.kill();
+                       bAborted = true;
+                       break;
+               }
+               if(!process.waitForReadyRead())
+               {
+                       if(process.state() == QProcess::Running)
+                       {
+                               process.kill();
+                               qWarning("VSPipe 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();
+                               if(regExpSignature.lastIndexIn(text) >= 0)
+                               {
+                                       vspipeSignature = true;
+                               }
+                               if(!text.isEmpty())
+                               {
+                                       log(text);
+                               }
+                       }
+               }
+       }
+
+       process.waitForFinished();
+       if(process.state() != QProcess::NotRunning)
+       {
+               process.kill();
+               process.waitForFinished(-1);
+       }
+
+       if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 1)))
+       {
+               if(!(bTimeout || bAborted))
+               {
+                       log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
+               }
+               return false;
+       }
+
+       if(!vspipeSignature)
+       {
+               log(tr("\nFAILED TO DETECT VSPIPE SIGNATURE !!!"));
+               return false;
+       }
+       
+       return vspipeSignature;
+}
+
+bool EncodeThread::checkPropertiesAvisynth(bool x64, unsigned int &frames)
+{
+       QProcess process;
+       QStringList cmdLine;
+
+       if(!m_options->customAvs2YUV().isEmpty())
+       {
+               cmdLine.append(splitParams(m_options->customAvs2YUV()));
+       }
+
+       cmdLine << "-frames" << "1";
+       cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
 
        log("Creating process:");
-       if(!startProcess(process, QString("%1/avs2yuv.exe").arg(m_binDir), cmdLine))
+       if(!startProcess(process, AVS2_BINARY(m_binDir, x64), cmdLine))
        {
                return false;;
        }
@@ -635,6 +990,8 @@ bool EncodeThread::checkProperties(unsigned int &frames)
        QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
        QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
        
+       QTextCodec *localCodec = QTextCodec::codecForName("System");
+
        bool bTimeout = false;
        bool bAborted = false;
 
@@ -645,6 +1002,8 @@ bool EncodeThread::checkProperties(unsigned int &frames)
        unsigned int fSizeW = 0;
        unsigned int fSizeH = 0;
        
+       unsigned int waitCounter = 0;
+
        while(process.state() != QProcess::NotRunning)
        {
                if(m_abort)
@@ -657,19 +1016,35 @@ bool EncodeThread::checkProperties(unsigned int &frames)
                {
                        if(process.state() == QProcess::Running)
                        {
-                               process.kill();
-                               qWarning("x264 process timed out <-- killing!");
-                               log("\nPROCESS TIMEOUT !!!");
-                               bTimeout = true;
-                               break;
+                               if(++waitCounter > m_processTimeoutMaxCounter)
+                               {
+                                       if(m_abortOnTimeout)
+                                       {
+                                               process.kill();
+                                               qWarning("Avs2YUV process timed out <-- killing!");
+                                               log("\nPROCESS TIMEOUT !!!");
+                                               log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
+                                               bTimeout = true;
+                                               break;
+                                       }
+                               }
+                               else if(waitCounter == m_processTimeoutWarning)
+                               {
+                                       unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
+                                       log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
+                               }
                        }
+                       continue;
                }
+               
+               waitCounter = 0;
+               
                while(process.bytesAvailable() > 0)
                {
                        QList<QByteArray> lines = process.readLine().split('\r');
                        while(!lines.isEmpty())
                        {
-                               QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
+                               QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
                                int offset = -1;
                                if((offset = regExpInt.lastIndexIn(text)) >= 0)
                                {
@@ -703,6 +1078,14 @@ bool EncodeThread::checkProperties(unsigned int &frames)
                                {
                                        log(text);
                                }
+                               if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
+                               {
+                                       log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
+                               }
+                               if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
+                               {
+                                       log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
+                               }
                        }
                }
        }
@@ -751,6 +1134,140 @@ bool EncodeThread::checkProperties(unsigned int &frames)
        return true;
 }
 
+bool EncodeThread::checkPropertiesVapoursynth(/*const QString &vspipePath,*/ unsigned int &frames)
+{
+       QProcess process;
+       QStringList cmdLine;
+
+       cmdLine << pathToLocal(QDir::toNativeSeparators(m_sourceFileName));
+       cmdLine << "-" << "-info";
+
+       log("Creating process:");
+       if(!startProcess(process, VPSP_BINARY(m_vpsDir), cmdLine))
+       {
+               return false;;
+       }
+
+       QRegExp regExpFrm("\\bFrames:\\s+(\\d+)\\b");
+       QRegExp regExpSzW("\\bWidth:\\s+(\\d+)\\b");
+       QRegExp regExpSzH("\\bHeight:\\s+(\\d+)\\b");
+       
+       QTextCodec *localCodec = QTextCodec::codecForName("System");
+
+       bool bTimeout = false;
+       bool bAborted = false;
+
+       frames = 0;
+       
+       unsigned int fSizeW = 0;
+       unsigned int fSizeH = 0;
+       
+       unsigned int waitCounter = 0;
+
+       while(process.state() != QProcess::NotRunning)
+       {
+               if(m_abort)
+               {
+                       process.kill();
+                       bAborted = true;
+                       break;
+               }
+               if(!process.waitForReadyRead(m_processTimeoutInterval))
+               {
+                       if(process.state() == QProcess::Running)
+                       {
+                               if(++waitCounter > m_processTimeoutMaxCounter)
+                               {
+                                       if(m_abortOnTimeout)
+                                       {
+                                               process.kill();
+                                               qWarning("VSPipe process timed out <-- killing!");
+                                               log("\nPROCESS TIMEOUT !!!");
+                                               log("\nVapoursynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
+                                               bTimeout = true;
+                                               break;
+                                       }
+                               }
+                               else if(waitCounter == m_processTimeoutWarning)
+                               {
+                                       unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
+                                       log(tr("Warning: nVapoursynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
+                               }
+                       }
+                       continue;
+               }
+               
+               waitCounter = 0;
+               
+               while(process.bytesAvailable() > 0)
+               {
+                       QList<QByteArray> lines = process.readLine().split('\r');
+                       while(!lines.isEmpty())
+                       {
+                               QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
+                               int offset = -1;
+                               if((offset = regExpFrm.lastIndexIn(text)) >= 0)
+                               {
+                                       bool ok = false;
+                                       unsigned int temp = regExpFrm.cap(1).toUInt(&ok);
+                                       if(ok) frames = temp;
+                               }
+                               if((offset = regExpSzW.lastIndexIn(text)) >= 0)
+                               {
+                                       bool ok = false;
+                                       unsigned int temp = regExpSzW.cap(1).toUInt(&ok);
+                                       if(ok) fSizeW = temp;
+                               }
+                               if((offset = regExpSzH.lastIndexIn(text)) >= 0)
+                               {
+                                       bool ok = false;
+                                       unsigned int temp = regExpSzH.cap(1).toUInt(&ok);
+                                       if(ok) fSizeH = temp;
+                               }
+                               if(!text.isEmpty())
+                               {
+                                       log(text);
+                               }
+                       }
+               }
+       }
+
+       process.waitForFinished();
+       if(process.state() != QProcess::NotRunning)
+       {
+               process.kill();
+               process.waitForFinished(-1);
+       }
+
+       if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
+       {
+               if(!(bTimeout || bAborted))
+               {
+                       log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
+               }
+               return false;
+       }
+
+       if(frames == 0)
+       {
+               log(tr("\nFAILED TO DETERMINE VPY PROPERTIES !!!"));
+               return false;
+       }
+       
+       log("");
+
+       if((fSizeW > 0) && (fSizeH > 0))
+       {
+               log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
+       }
+       if(frames > 0)
+       {
+               log(tr("No. Frames: %1").arg(QString::number(frames)));
+       }
+
+       return true;
+}
+
 ///////////////////////////////////////////////////////////////////////////////
 // Misc functions
 ///////////////////////////////////////////////////////////////////////////////
@@ -759,10 +1276,9 @@ void EncodeThread::setStatus(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)
                {
@@ -772,6 +1288,7 @@ void EncodeThread::setStatus(JobStatus newStatus)
                {
                        setDetails("The job was aborted by the user!");
                }
+               m_status = newStatus;
                emit statusChanged(m_jobId, newStatus);
        }
 }
@@ -790,48 +1307,78 @@ void EncodeThread::setDetails(const QString &text)
        emit detailsChanged(m_jobId, text);
 }
 
-bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
+QString EncodeThread::pathToLocal(const QString &longPath, bool create, bool keep)
 {
-       static AssignProcessToJobObjectFun AssignProcessToJobObjectPtr = NULL;
-       static CreateJobObjectFun CreateJobObjectPtr = NULL;
-       static SetInformationJobObjectFun SetInformationJobObjectPtr = NULL;
+       QTextCodec *localCodec = QTextCodec::codecForName("System");
        
+       //Do NOT convert to short, if path can be represented in local Codepage
+       if(localCodec->toUnicode(localCodec->fromUnicode(longPath)).compare(longPath, Qt::CaseInsensitive) == 0)
+       {
+               return longPath;
+       }
+       
+       //Create dummy file, if required (only existing files can have a short path!)
+       QFile tempFile;
+       if((!QFileInfo(longPath).exists()) && create)
+       {
+               tempFile.setFileName(longPath);
+               tempFile.open(QIODevice::WriteOnly);
+       }
+       
+       QString shortPath;
+       DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
+       
+       if(buffSize > 0)
+       {
+               wchar_t *buffer = new wchar_t[buffSize];
+               DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
+
+               if(result > 0 && result < buffSize)
+               {
+                       shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
+               }
+
+               delete[] buffer;
+               buffer = NULL;
+       }
+
+       //Remove the dummy file now (FFMS2 fails, if index file does exist but is empty!)
+       if(tempFile.isOpen())
+       {
+               if(!keep) tempFile.remove();
+               tempFile.close();
+       }
+
+       if(shortPath.isEmpty())
+       {
+               log(tr("Warning: Failed to convert path \"%1\" to short!\n").arg(longPath));
+       }
+
+       return (shortPath.isEmpty() ? longPath : shortPath);
+}
+
+bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
+{
        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)
+               m_handle_jobObject = CreateJobObject(NULL, NULL);
+               if(m_handle_jobObject == INVALID_HANDLE_VALUE)
                {
-                       QLibrary Kernel32Lib("kernel32.dll");
-                       CreateJobObjectPtr = (CreateJobObjectFun) Kernel32Lib.resolve("CreateJobObjectA");
-                       SetInformationJobObjectPtr = (SetInformationJobObjectFun) Kernel32Lib.resolve("SetInformationJobObject");
+                       m_handle_jobObject = NULL;
                }
-               if(CreateJobObjectPtr && SetInformationJobObjectPtr)
+               if(m_handle_jobObject)
                {
-                       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));
-                       }
+                       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;
+                       SetInformationJobObject(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);
@@ -847,13 +1394,11 @@ bool EncodeThread::startProcess(QProcess &process, const QString &program, const
        
        if(process.waitForStarted())
        {
-               if(AssignProcessToJobObjectPtr)
+               Q_PID pid = process.pid();
+               if(pid != NULL)
                {
-                       AssignProcessToJobObjectPtr(m_handle_jobObject, process.pid()->hProcess);
-               }
-               if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
-               {
-                       SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
+                       AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
+                       setPorcessPriority(process.pid()->hProcess, m_processPriority);
                }
                
                lock.unlock();
@@ -880,3 +1425,106 @@ QString EncodeThread::commandline2string(const QString &program, const QStringLi
 
        return commandline;
 }
+
+QStringList EncodeThread::splitParams(const QString &params)
+{
+       QStringList list; 
+       bool ignoreWhitespaces = false;
+       QString temp;
+
+       for(int i = 0; i < params.length(); i++)
+       {
+               const QChar c = params.at(i);
+
+               if(c == QChar::fromLatin1('"'))
+               {
+                       ignoreWhitespaces = (!ignoreWhitespaces);
+                       continue;
+               }
+               else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
+               {
+                       APPEND_AND_CLEAR(list, temp);
+                       continue;
+               }
+               
+               temp.append(c);
+       }
+       
+       APPEND_AND_CLEAR(list, temp);
+
+       list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
+       list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
+
+       return list;
+}
+
+qint64 EncodeThread::estimateSize(int progress)
+{
+       if(progress >= 3)
+       {
+               qint64 currentSize = QFileInfo(m_outputFileName).size();
+               qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
+               return estimatedSize;
+       }
+
+       return 0I64;
+}
+
+QString EncodeThread::sizeToString(qint64 size)
+{
+       static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
+
+       if(size > 1024I64)
+       {
+               qint64 estimatedSize = size;
+               qint64 remainderSize = 0I64;
+
+               int prefixIdx = 0;
+               while((estimatedSize > 1024I64) && (prefixIdx < 4))
+               {
+                       remainderSize = estimatedSize % 1024I64;
+                       estimatedSize = estimatedSize / 1024I64;
+                       prefixIdx++;
+               }
+                       
+               double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
+               return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);
+       }
+
+       return tr("N/A");
+}
+
+int EncodeThread::getInputType(const QString &fileExt)
+{
+       int type = INPUT_NATIVE;
+       if(fileExt.compare("avs", Qt::CaseInsensitive) == 0)       type = INPUT_AVISYN;
+       else if(fileExt.compare("avsi", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
+       else if(fileExt.compare("vpy", Qt::CaseInsensitive) == 0)  type = INPUT_VAPOUR;
+       else if(fileExt.compare("py", Qt::CaseInsensitive) == 0)   type = INPUT_VAPOUR;
+       return type;
+}
+
+void EncodeThread::setPorcessPriority(void *processId, int priroity)
+{
+       switch(priroity)
+       {
+       case PreferencesModel::X264_PRIORITY_ABOVENORMAL:
+               if(!SetPriorityClass(processId, ABOVE_NORMAL_PRIORITY_CLASS))
+               {
+                       SetPriorityClass(processId, NORMAL_PRIORITY_CLASS);
+               }
+               break;
+       case PreferencesModel::X264_PRIORITY_NORMAL:
+               SetPriorityClass(processId, NORMAL_PRIORITY_CLASS);
+               break;
+       case PreferencesModel::X264_PRIORITY_BELOWNORMAL:
+               if(!SetPriorityClass(processId, BELOW_NORMAL_PRIORITY_CLASS))
+               {
+                       SetPriorityClass(processId, IDLE_PRIORITY_CLASS);
+               }
+               break;
+       case PreferencesModel::X264_PRIORITY_IDLE:
+               SetPriorityClass(processId, IDLE_PRIORITY_CLASS);
+               break;
+       }
+}