OSDN Git Service

Added support for modified x264 progress output, as used by some patched build (e...
[x264-launcher/x264-launcher.git] / src / thread_encode.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "thread_encode.h"
23
24 #include "global.h"
25 #include "model_options.h"
26 #include "model_preferences.h"
27 #include "version.h"
28
29 #include <QDate>
30 #include <QTime>
31 #include <QDateTime>
32 #include <QFileInfo>
33 #include <QDir>
34 #include <QProcess>
35 #include <QMutex>
36 #include <QTextCodec>
37 #include <QLocale>
38 #include <QCryptographicHash>
39
40 /*
41  * Static vars
42  */
43 QMutex EncodeThread::m_mutex_startProcess;
44
45 /*
46  * Macros
47  */
48 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
49 { \
50         if(ABORT_FLAG) \
51         { \
52                 log("\nPROCESS ABORTED BY USER !!!"); \
53                 setStatus(JobStatus_Aborted); \
54                 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
55                 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
56                 return; \
57         } \
58         else if(!(OK_FLAG)) \
59         { \
60                 setStatus(JobStatus_Failed); \
61                 if(QFileInfo(indexFile).exists()) QFile::remove(indexFile); \
62                 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
63                 return; \
64         } \
65 } \
66 while(0)
67
68 #define APPEND_AND_CLEAR(LIST, STR) do \
69 { \
70         if(!((STR).isEmpty())) \
71         { \
72                 (LIST) << (STR); \
73                 (STR).clear(); \
74         } \
75 } \
76 while(0)
77
78 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
79 { \
80         if(ITER != LIST.end()) \
81         { \
82                 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
83                 { \
84                         log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
85                         ITER = LIST.erase(ITER); \
86                         if(ITER != LIST.end()) \
87                         { \
88                                 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
89                         } \
90                         FLAG = true; \
91                 } \
92         } \
93 } \
94 while(0)
95
96 #define AVS2_BINARY(BIN_DIR, IS_X64) (QString("%1/%2/avs2yuv_%2.exe").arg((BIN_DIR), ((IS_X64) ? "x64" : "x86")))
97 #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")))
98 #define VPSP_BINARY(VPS_DIR) (QString("%1/core/vspipe.exe").arg((VPS_DIR)))
99
100 /*
101  * Static vars
102  */
103 static const unsigned int REV_MULT = 10000;
104 static const char *VPS_TEST_FILE = "import vapoursynth as vs\ncore = vs.get_core()\nv = core.std.BlankClip()\nv.set_output()\n";
105
106 ///////////////////////////////////////////////////////////////////////////////
107 // Constructor & Destructor
108 ///////////////////////////////////////////////////////////////////////////////
109
110 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)
111 :
112         m_jobId(QUuid::createUuid()),
113         m_sourceFileName(sourceFileName),
114         m_outputFileName(outputFileName),
115         m_options(new OptionsModel(*options)),
116         m_binDir(binDir),
117         m_vpsDir(vpsDir),
118         m_x264_x64(x264_x64),
119         m_x264_10bit(x264_10bit),
120         m_avs2yuv_x64(avs2yuv_x64),
121         m_skipVersionTest(skipVersionTest),
122         m_processPriority(processPriroity),
123         m_abortOnTimeout(abortOnTimeout),
124         m_handle_jobObject(NULL),
125         m_semaphorePaused(0)
126 {
127         m_abort = false;
128         m_pause = false;
129 }
130
131 EncodeThread::~EncodeThread(void)
132 {
133         X264_DELETE(m_options);
134         
135         if(m_handle_jobObject)
136         {
137                 CloseHandle(m_handle_jobObject);
138                 m_handle_jobObject = NULL;
139         }
140 }
141
142 ///////////////////////////////////////////////////////////////////////////////
143 // Thread entry point
144 ///////////////////////////////////////////////////////////////////////////////
145
146 void EncodeThread::run(void)
147 {
148 #if !defined(_DEBUG)
149         __try
150         {
151                 checkedRun();
152         }
153         __except(1)
154         {
155                 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
156         }
157 #else
158         checkedRun();
159 #endif
160
161         if(m_handle_jobObject)
162         {
163                 TerminateJobObject(m_handle_jobObject, 42);
164                 m_handle_jobObject = NULL;
165         }
166 }
167
168 void EncodeThread::checkedRun(void)
169 {
170         m_progress = 0;
171         m_status = JobStatus_Starting;
172
173         try
174         {
175                 try
176                 {
177                         encode();
178                 }
179                 catch(char *msg)
180                 {
181                         log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
182                         setStatus(JobStatus_Failed);
183                 }
184                 catch(...)
185                 {
186                         log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
187                         setStatus(JobStatus_Failed);
188                 }
189         }
190         catch(...)
191         {
192                 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
193         }
194 }
195
196 void EncodeThread::start(Priority priority)
197 {
198         qDebug("Thread starting...");
199
200         m_abort = false;
201         m_pause = false;
202
203         while(m_semaphorePaused.tryAcquire(1, 0));
204         QThread::start(priority);
205 }
206
207 ///////////////////////////////////////////////////////////////////////////////
208 // Encode functions
209 ///////////////////////////////////////////////////////////////////////////////
210
211 void EncodeThread::encode(void)
212 {
213         QDateTime startTime = QDateTime::currentDateTime();
214
215         //Print some basic info
216         log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
217         log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
218         log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
219         log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
220         
221         if(!m_vpsDir.isEmpty())
222         {
223                 log(tr("\nVapourSynth: %1").arg(m_vpsDir));
224         }
225
226         //Print encoder settings
227         log(tr("\n--- SETTINGS ---\n"));
228         log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
229         log(tr("Preset:  %1").arg(m_options->preset()));
230         log(tr("Tuning:  %1").arg(m_options->tune()));
231         log(tr("Profile: %1").arg(m_options->profile()));
232         log(tr("Custom:  %1").arg(m_options->customX264().isEmpty() ? tr("(None)") : m_options->customX264()));
233         
234         log(m_binDir);
235
236         bool ok = false;
237         unsigned int frames = 0;
238
239         //Seletct type of input
240         const int inputType = getInputType(QFileInfo(m_sourceFileName).suffix());
241         const QString indexFile = QString("%1/x264_%2.ffindex").arg(QDir::tempPath(), stringToHash(m_sourceFileName));
242
243         //Checking x264 version
244         log(tr("\n--- CHECK VERSION ---\n"));
245         unsigned int revision_x264 = UINT_MAX;
246         bool x264_modified = false;
247         ok = ((revision_x264 = checkVersionX264(m_x264_x64, m_x264_10bit, x264_modified)) != UINT_MAX);
248         CHECK_STATUS(m_abort, ok);
249         
250         //Checking avs2yuv version
251         unsigned int revision_avs2yuv = UINT_MAX;
252         switch(inputType)
253         {
254         case INPUT_AVISYN:
255                 ok = ((revision_avs2yuv = checkVersionAvs2yuv(m_avs2yuv_x64)) != UINT_MAX);
256                 CHECK_STATUS(m_abort, ok);
257                 break;
258         case INPUT_VAPOUR:
259                 ok = checkVersionVapoursynth();
260                 CHECK_STATUS(m_abort, ok);
261                 break;
262         }
263
264         //Print versions
265         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()));
266         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)));
267
268         //Is x264 revision supported?
269         if((revision_x264 % REV_MULT) < (VER_X264_MINIMUM_REV))
270         {
271                 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
272                 setStatus(JobStatus_Failed);
273                 return;
274         }
275         if((revision_x264 / REV_MULT) != (VER_X264_CURRENT_API))
276         {
277                 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
278                 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
279         }
280         if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != (VER_X264_AVS2YUV_VER)))
281         {
282                 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
283                 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
284                 setStatus(JobStatus_Failed);
285                 return;
286         }
287
288         //Detect source info
289         if(inputType != INPUT_NATIVE)
290         {
291                 log(tr("\n--- SOURCE INFO ---\n"));
292                 switch(inputType)
293                 {
294                 case INPUT_AVISYN:
295                         ok = checkPropertiesAvisynth(m_avs2yuv_x64, frames);
296                         CHECK_STATUS(m_abort, ok);
297                         break;
298                 case INPUT_VAPOUR:
299                         ok = checkPropertiesVapoursynth(frames);
300                         CHECK_STATUS(m_abort, ok);
301                         break;
302                 }
303         }
304
305         //Run encoding passes
306         if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
307         {
308                 QFileInfo info(m_outputFileName);
309                 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
310
311                 if(QFileInfo(passLogFile).exists())
312                 {
313                         int n = 2;
314                         while(QFileInfo(passLogFile).exists())
315                         {
316                                 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
317                         }
318                 }
319                 
320                 log(tr("\n--- PASS 1 ---\n"));
321                 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 1, passLogFile);
322                 CHECK_STATUS(m_abort, ok);
323
324                 log(tr("\n--- PASS 2 ---\n"));
325                 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile, 2, passLogFile);
326                 CHECK_STATUS(m_abort, ok);
327         }
328         else
329         {
330                 log(tr("\n--- ENCODING ---\n"));
331                 ok = runEncodingPass(m_x264_x64, m_x264_10bit, m_avs2yuv_x64, inputType, frames, indexFile);
332                 CHECK_STATUS(m_abort, ok);
333         }
334
335         log(tr("\n--- DONE ---\n"));
336         int timePassed = startTime.secsTo(QDateTime::currentDateTime());
337         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)));
338         setStatus(JobStatus_Completed);
339 }
340
341 #define X264_UPDATE_PROGRESS(X) do \
342 { \
343         bool ok = false; \
344         unsigned int progress = (X).cap(1).toUInt(&ok); \
345         setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running)); \
346         if(ok && ((progress > last_progress) || (last_progress == UINT_MAX))) \
347         { \
348                 setProgress(progress); \
349                 size_estimate = estimateSize(progress); \
350                 last_progress = progress; \
351         } \
352         setDetails(tr("%1, est. file size %2").arg(text.mid(offset).trimmed(), sizeToString(size_estimate))); \
353         last_indexing = UINT_MAX; \
354 } \
355 while(0)
356
357 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)
358 {
359         QProcess processEncode, processInput;
360         
361         if(inputType != INPUT_NATIVE)
362         {
363                 QStringList cmdLine_Input;
364                 processInput.setStandardOutputProcess(&processEncode);
365                 switch(inputType)
366                 {
367                 case INPUT_AVISYN:
368                         if(!m_options->customAvs2YUV().isEmpty())
369                         {
370                                 cmdLine_Input.append(splitParams(m_options->customAvs2YUV()));
371                         }
372                         cmdLine_Input << pathToAnsi(QDir::toNativeSeparators(m_sourceFileName));
373                         cmdLine_Input << "-";
374                         log("Creating Avisynth process:");
375                         if(!startProcess(processInput, AVS2_BINARY(m_binDir, avs2yuv_x64), cmdLine_Input, false))
376                         {
377                                 return false;
378                         }
379                         break;
380                 case INPUT_VAPOUR:
381                         cmdLine_Input << pathToAnsi(QDir::toNativeSeparators(m_sourceFileName));
382                         cmdLine_Input << "-" << "-y4m";
383                         log("Creating Vapoursynth process:");
384                         if(!startProcess(processInput, VPSP_BINARY(m_vpsDir), cmdLine_Input, false))
385                         {
386                                 return false;
387                         }
388                         break;
389                 default:
390                         throw "Bad input type encontered!";
391                 }
392         }
393
394         QStringList cmdLine_Encode = buildCommandLine((inputType != INPUT_NATIVE), x264_10bit, frames, indexFile, pass, passLogFile);
395
396         log("Creating x264 process:");
397         if(!startProcess(processEncode, X264_BINARY(m_binDir, x264_10bit, x264_x64), cmdLine_Encode))
398         {
399                 return false;
400         }
401
402         QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
403         QRegExp regExpProgress("\\[(\\d+)\\.(\\d+)%\\].+frames");
404         QRegExp regExpModified("\\[\\s*(\\d+)\\.(\\d+)%\\]\\s+(\\d+)/(\\d+)\\s(\\d+).(\\d+)\\s(\\d+).(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)");
405         QRegExp regExpFrameCnt("^(\\d+) frames:");
406         
407         QTextCodec *localCodec = QTextCodec::codecForName("System");
408
409         bool bTimeout = false;
410         bool bAborted = false;
411
412         unsigned int last_progress = UINT_MAX;
413         unsigned int last_indexing = UINT_MAX;
414         qint64 size_estimate = 0I64;
415
416         //Main processing loop
417         while(processEncode.state() != QProcess::NotRunning)
418         {
419                 unsigned int waitCounter = 0;
420
421                 //Wait until new output is available
422                 forever
423                 {
424                         if(m_abort)
425                         {
426                                 processEncode.kill();
427                                 processInput.kill();
428                                 bAborted = true;
429                                 break;
430                         }
431                         if(m_pause && (processEncode.state() == QProcess::Running))
432                         {
433                                 JobStatus previousStatus = m_status;
434                                 setStatus(JobStatus_Paused);
435                                 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
436                                 bool ok[2] = {false, false};
437                                 Q_PID pid[2] = {processEncode.pid(), processInput.pid()};
438                                 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
439                                 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
440                                 while(m_pause) m_semaphorePaused.tryAcquire(1, 5000);
441                                 while(m_semaphorePaused.tryAcquire(1, 0));
442                                 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
443                                 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
444                                 if(!m_abort) setStatus(previousStatus);
445                                 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
446                                 waitCounter = 0;
447                                 continue;
448                         }
449                         if(!processEncode.waitForReadyRead(m_processTimeoutInterval))
450                         {
451                                 if(processEncode.state() == QProcess::Running)
452                                 {
453                                         if(++waitCounter > m_processTimeoutMaxCounter)
454                                         {
455                                                 if(m_abortOnTimeout)
456                                                 {
457                                                         processEncode.kill();
458                                                         qWarning("x264 process timed out <-- killing!");
459                                                         log("\nPROCESS TIMEOUT !!!");
460                                                         bTimeout = true;
461                                                         break;
462                                                 }
463                                         }
464                                         else if(waitCounter == m_processTimeoutWarning)
465                                         {
466                                                 unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
467                                                 log(tr("Warning: x264 did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
468                                         }
469                                         continue;
470                                 }
471                         }
472                         if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
473                         {
474                                 continue;
475                         }
476                         break;
477                 }
478                 
479                 //Exit main processing loop now?
480                 if(bAborted || bTimeout)
481                 {
482                         break;
483                 }
484
485                 //Process all output
486                 while(processEncode.bytesAvailable() > 0)
487                 {
488                         QList<QByteArray> lines = processEncode.readLine().split('\r');
489                         while(!lines.isEmpty())
490                         {
491                                 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
492                                 int offset = -1;
493                                 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
494                                 {
495                                         X264_UPDATE_PROGRESS(regExpProgress);
496                                 }
497                                 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
498                                 {
499                                         bool ok = false;
500                                         unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
501                                         setStatus(JobStatus_Indexing);
502                                         if(ok && ((progress > last_indexing) || (last_indexing == UINT_MAX)))
503                                         {
504                                                 setProgress(progress);
505                                                 last_indexing = progress;
506                                         }
507                                         setDetails(text.mid(offset).trimmed());
508                                         last_progress = UINT_MAX;
509                                 }
510                                 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
511                                 {
512                                         last_progress = last_indexing = UINT_MAX;
513                                         setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
514                                         setDetails(text.mid(offset).trimmed());
515                                 }
516                                 else if((offset = regExpModified.lastIndexIn(text)) >= 0)
517                                 {
518                                         X264_UPDATE_PROGRESS(regExpModified);
519                                 }
520                                 else if(!text.isEmpty())
521                                 {
522                                         last_progress = last_indexing = UINT_MAX;
523                                         log(text);
524                                 }
525                         }
526                 }
527         }
528
529         processEncode.waitForFinished(5000);
530         if(processEncode.state() != QProcess::NotRunning)
531         {
532                 qWarning("x264 process still running, going to kill it!");
533                 processEncode.kill();
534                 processEncode.waitForFinished(-1);
535         }
536         
537         processInput.waitForFinished(5000);
538         if(processInput.state() != QProcess::NotRunning)
539         {
540                 qWarning("Input process still running, going to kill it!");
541                 processInput.kill();
542                 processInput.waitForFinished(-1);
543         }
544
545         if(!(bTimeout || bAborted))
546         {
547                 while(processInput.bytesAvailable() > 0)
548                 {
549                         switch(inputType)
550                         {
551                         case INPUT_AVISYN:
552                                 log(tr("av2y [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
553                                 break;
554                         case INPUT_VAPOUR:
555                                 log(tr("vpyp [info]: %1").arg(QString::fromUtf8(processInput.readLine()).simplified()));
556                                 break;
557                         }
558                 }
559         }
560
561         if((inputType != INPUT_NATIVE) && (processInput.exitCode() != EXIT_SUCCESS))
562         {
563                 if(!(bTimeout || bAborted))
564                 {
565                         log(tr("\nWARNING: Input process exited with error code: %1").arg(QString::number(processInput.exitCode())));
566                 }
567         }
568
569         if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
570         {
571                 if(!(bTimeout || bAborted))
572                 {
573                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
574                 }
575                 processEncode.close();
576                 processInput.close();
577                 return false;
578         }
579
580         QThread::yieldCurrentThread();
581
582         const qint64 finalSize = QFileInfo(m_outputFileName).size();
583         QLocale locale(QLocale::English);
584         log(tr("Final file size is %1 bytes.").arg(locale.toString(finalSize)));
585
586         switch(pass)
587         {
588         case 1:
589                 setStatus(JobStatus_Running_Pass1);
590                 setDetails(tr("First pass completed. Preparing for second pass..."));
591                 break;
592         case 2:
593                 setStatus(JobStatus_Running_Pass2);
594                 setDetails(tr("Second pass completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
595                 break;
596         default:
597                 setStatus(JobStatus_Running);
598                 setDetails(tr("Encode completed successfully. Final size is %1.").arg(sizeToString(finalSize)));
599                 break;
600         }
601
602         setProgress(100);
603         processEncode.close();
604         processInput.close();
605         return true;
606 }
607
608 QStringList EncodeThread::buildCommandLine(bool usePipe, bool use10Bit, unsigned int frames, const QString &indexFile, int pass, const QString &passLogFile)
609 {
610         QStringList cmdLine;
611         double crf_int = 0.0, crf_frc = 0.0;
612
613         switch(m_options->rcMode())
614         {
615         case OptionsModel::RCMode_CQ:
616                 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
617                 break;
618         case OptionsModel::RCMode_CRF:
619                 crf_frc = modf(m_options->quantizer(), &crf_int);
620                 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
621                 break;
622         case OptionsModel::RCMode_2Pass:
623         case OptionsModel::RCMode_ABR:
624                 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
625                 break;
626         default:
627                 throw "Bad rate-control mode !!!";
628                 break;
629         }
630         
631         if((pass == 1) || (pass == 2))
632         {
633                 cmdLine << "--pass" << QString::number(pass);
634                 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
635         }
636
637         cmdLine << "--preset" << m_options->preset().toLower();
638
639         if(m_options->tune().compare("none", Qt::CaseInsensitive))
640         {
641                 cmdLine << "--tune" << m_options->tune().toLower();
642         }
643
644         if(m_options->profile().compare("auto", Qt::CaseInsensitive))
645         {
646                 if(use10Bit)
647                 {
648                         if(m_options->profile().compare("baseline", Qt::CaseInsensitive) || m_options->profile().compare("main", Qt::CaseInsensitive) || m_options->profile().compare("high", Qt::CaseInsensitive))
649                         {
650                                 log(tr("WARNING: Selected H.264 Profile not compatible with 10-Bit encoding. Ignoring!\n"));
651                         }
652                         else
653                         {
654                                 cmdLine << "--profile" << m_options->profile().toLower();
655                         }
656                 }
657                 else
658                 {
659                         cmdLine << "--profile" << m_options->profile().toLower();
660                 }
661         }
662
663         if(!m_options->customX264().isEmpty())
664         {
665                 QStringList customArgs = splitParams(m_options->customX264());
666                 if(usePipe)
667                 {
668                         QStringList::iterator i = customArgs.begin();
669                         while(i != customArgs.end())
670                         {
671                                 bool bModified = false;
672                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
673                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
674                                 if(!bModified) i++;
675                         }
676                 }
677                 cmdLine.append(customArgs);
678         }
679
680         cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
681         
682         if(usePipe)
683         {
684                 if(frames < 1) throw "Frames not set!";
685                 cmdLine << "--frames" << QString::number(frames);
686                 cmdLine << "--demuxer" << "y4m";
687                 cmdLine << "--stdin" << "y4m" << "-";
688         }
689         else
690         {
691                 cmdLine << "--index" << QDir::toNativeSeparators(indexFile);
692                 cmdLine << QDir::toNativeSeparators(m_sourceFileName);
693         }
694
695         return cmdLine;
696 }
697
698 unsigned int EncodeThread::checkVersionX264(bool use_x64, bool use_10bit, bool &modified)
699 {
700         if(m_skipVersionTest)
701         {
702                 log("Warning: Skipping x264 version check this time!");
703                 return (999 * REV_MULT) + (9999 % REV_MULT);
704         }
705
706         QProcess process;
707         QStringList cmdLine = QStringList() << "--version";
708
709         log("Creating process:");
710         if(!startProcess(process, X264_BINARY(m_binDir, use_10bit, use_x64), cmdLine))
711         {
712                 return false;;
713         }
714
715         QRegExp regExpVersion("\\bx264\\s(\\d)\\.(\\d+)\\.(\\d+)\\s([a-f0-9]{7})", Qt::CaseInsensitive);
716         QRegExp regExpVersionMod("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
717         
718         bool bTimeout = false;
719         bool bAborted = false;
720
721         unsigned int revision = UINT_MAX;
722         unsigned int coreVers = UINT_MAX;
723         modified = false;
724
725         while(process.state() != QProcess::NotRunning)
726         {
727                 if(m_abort)
728                 {
729                         process.kill();
730                         bAborted = true;
731                         break;
732                 }
733                 if(!process.waitForReadyRead())
734                 {
735                         if(process.state() == QProcess::Running)
736                         {
737                                 process.kill();
738                                 qWarning("x264 process timed out <-- killing!");
739                                 log("\nPROCESS TIMEOUT !!!");
740                                 bTimeout = true;
741                                 break;
742                         }
743                 }
744                 while(process.bytesAvailable() > 0)
745                 {
746                         QList<QByteArray> lines = process.readLine().split('\r');
747                         while(!lines.isEmpty())
748                         {
749                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
750                                 int offset = -1;
751                                 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
752                                 {
753                                         bool ok1 = false, ok2 = false;
754                                         unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
755                                         unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
756                                         if(ok1) coreVers = temp1;
757                                         if(ok2) revision = temp2;
758                                 }
759                                 else if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
760                                 {
761                                         bool ok1 = false, ok2 = false;
762                                         unsigned int temp1 = regExpVersionMod.cap(2).toUInt(&ok1);
763                                         unsigned int temp2 = regExpVersionMod.cap(3).toUInt(&ok2);
764                                         if(ok1) coreVers = temp1;
765                                         if(ok2) revision = temp2;
766                                         modified = true;
767                                 }
768                                 if(!text.isEmpty())
769                                 {
770                                         log(text);
771                                 }
772                         }
773                 }
774         }
775
776         process.waitForFinished();
777         if(process.state() != QProcess::NotRunning)
778         {
779                 process.kill();
780                 process.waitForFinished(-1);
781         }
782
783         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
784         {
785                 if(!(bTimeout || bAborted))
786                 {
787                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
788                 }
789                 return UINT_MAX;
790         }
791
792         if((revision == UINT_MAX) || (coreVers == UINT_MAX))
793         {
794                 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
795                 return UINT_MAX;
796         }
797         
798         return (coreVers * REV_MULT) + (revision % REV_MULT);
799 }
800
801 unsigned int EncodeThread::checkVersionAvs2yuv(bool x64)
802 {
803         QProcess process;
804
805         log("\nCreating process:");
806         if(!startProcess(process, AVS2_BINARY(m_binDir, x64), QStringList()))
807         {
808                 return false;;
809         }
810
811         QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
812         QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
813         
814         bool bTimeout = false;
815         bool bAborted = false;
816
817         unsigned int ver_maj = UINT_MAX;
818         unsigned int ver_min = UINT_MAX;
819         unsigned int ver_mod = 0;
820
821         while(process.state() != QProcess::NotRunning)
822         {
823                 if(m_abort)
824                 {
825                         process.kill();
826                         bAborted = true;
827                         break;
828                 }
829                 if(!process.waitForReadyRead())
830                 {
831                         if(process.state() == QProcess::Running)
832                         {
833                                 process.kill();
834                                 qWarning("Avs2YUV process timed out <-- killing!");
835                                 log("\nPROCESS TIMEOUT !!!");
836                                 bTimeout = true;
837                                 break;
838                         }
839                 }
840                 while(process.bytesAvailable() > 0)
841                 {
842                         QList<QByteArray> lines = process.readLine().split('\r');
843                         while(!lines.isEmpty())
844                         {
845                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
846                                 int offset = -1;
847                                 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
848                                 {
849                                         if(!text.isEmpty())
850                                         {
851                                                 log(text);
852                                         }
853                                 }
854                                 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
855                                 {
856                                         bool ok1 = false, ok2 = false, ok3 = false;
857                                         unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
858                                         unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
859                                         unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
860                                         if(ok1) ver_maj = temp1;
861                                         if(ok2) ver_min = temp2;
862                                         if(ok3) ver_mod = temp3;
863                                 }
864                                 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
865                                 {
866                                         bool ok1 = false, ok2 = false;
867                                         unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
868                                         unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
869                                         if(ok1) ver_maj = temp1;
870                                         if(ok2) ver_min = temp2;
871                                 }
872                         }
873                 }
874         }
875
876         process.waitForFinished();
877         if(process.state() != QProcess::NotRunning)
878         {
879                 process.kill();
880                 process.waitForFinished(-1);
881         }
882
883         if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
884         {
885                 if(!(bTimeout || bAborted))
886                 {
887                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
888                 }
889                 return UINT_MAX;
890         }
891
892         if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
893         {
894                 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
895                 return UINT_MAX;
896         }
897         
898         return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
899 }
900
901 bool EncodeThread::checkVersionVapoursynth(/*const QString &vspipePath*/)
902 {
903         //Is VapourSynth available at all?
904         if(m_vpsDir.isEmpty() || (!QFileInfo(VPSP_BINARY(m_vpsDir)).isFile()))
905         {
906                 log(tr("\nVPY INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
907                 return false;
908         }
909
910         QProcess process;
911
912         log("\nCreating process:");
913         if(!startProcess(process, VPSP_BINARY(m_vpsDir), QStringList()))
914         {
915                 return false;;
916         }
917
918         QRegExp regExpSignature("\\bVSPipe\\s+usage\\b", Qt::CaseInsensitive);
919         
920         bool bTimeout = false;
921         bool bAborted = false;
922
923         bool vspipeSignature = false;
924
925         while(process.state() != QProcess::NotRunning)
926         {
927                 if(m_abort)
928                 {
929                         process.kill();
930                         bAborted = true;
931                         break;
932                 }
933                 if(!process.waitForReadyRead())
934                 {
935                         if(process.state() == QProcess::Running)
936                         {
937                                 process.kill();
938                                 qWarning("VSPipe process timed out <-- killing!");
939                                 log("\nPROCESS TIMEOUT !!!");
940                                 bTimeout = true;
941                                 break;
942                         }
943                 }
944                 while(process.bytesAvailable() > 0)
945                 {
946                         QList<QByteArray> lines = process.readLine().split('\r');
947                         while(!lines.isEmpty())
948                         {
949                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
950                                 if(regExpSignature.lastIndexIn(text) >= 0)
951                                 {
952                                         vspipeSignature = true;
953                                 }
954                                 if(!text.isEmpty())
955                                 {
956                                         log(text);
957                                 }
958                         }
959                 }
960         }
961
962         process.waitForFinished();
963         if(process.state() != QProcess::NotRunning)
964         {
965                 process.kill();
966                 process.waitForFinished(-1);
967         }
968
969         if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 1)))
970         {
971                 if(!(bTimeout || bAborted))
972                 {
973                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
974                 }
975                 return false;
976         }
977
978         if(!vspipeSignature)
979         {
980                 log(tr("\nFAILED TO DETECT VSPIPE SIGNATURE !!!"));
981                 return false;
982         }
983         
984         return vspipeSignature;
985 }
986
987 bool EncodeThread::checkPropertiesAvisynth(bool x64, unsigned int &frames)
988 {
989         QProcess process;
990         QStringList cmdLine;
991
992         if(!m_options->customAvs2YUV().isEmpty())
993         {
994                 cmdLine.append(splitParams(m_options->customAvs2YUV()));
995         }
996
997         cmdLine << "-frames" << "1";
998         cmdLine << pathToAnsi(QDir::toNativeSeparators(m_sourceFileName)) << "NUL";
999
1000         log("Creating process:");
1001         if(!startProcess(process, AVS2_BINARY(m_binDir, x64), cmdLine))
1002         {
1003                 return false;;
1004         }
1005
1006         QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
1007         QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
1008         
1009         QTextCodec *localCodec = QTextCodec::codecForName("System");
1010
1011         bool bTimeout = false;
1012         bool bAborted = false;
1013
1014         frames = 0;
1015         
1016         unsigned int fpsNom = 0;
1017         unsigned int fpsDen = 0;
1018         unsigned int fSizeW = 0;
1019         unsigned int fSizeH = 0;
1020         
1021         unsigned int waitCounter = 0;
1022
1023         while(process.state() != QProcess::NotRunning)
1024         {
1025                 if(m_abort)
1026                 {
1027                         process.kill();
1028                         bAborted = true;
1029                         break;
1030                 }
1031                 if(!process.waitForReadyRead(m_processTimeoutInterval))
1032                 {
1033                         if(process.state() == QProcess::Running)
1034                         {
1035                                 if(++waitCounter > m_processTimeoutMaxCounter)
1036                                 {
1037                                         if(m_abortOnTimeout)
1038                                         {
1039                                                 process.kill();
1040                                                 qWarning("Avs2YUV process timed out <-- killing!");
1041                                                 log("\nPROCESS TIMEOUT !!!");
1042                                                 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1043                                                 bTimeout = true;
1044                                                 break;
1045                                         }
1046                                 }
1047                                 else if(waitCounter == m_processTimeoutWarning)
1048                                 {
1049                                         unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1050                                         log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1051                                 }
1052                         }
1053                         continue;
1054                 }
1055                 
1056                 waitCounter = 0;
1057                 
1058                 while(process.bytesAvailable() > 0)
1059                 {
1060                         QList<QByteArray> lines = process.readLine().split('\r');
1061                         while(!lines.isEmpty())
1062                         {
1063                                 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1064                                 int offset = -1;
1065                                 if((offset = regExpInt.lastIndexIn(text)) >= 0)
1066                                 {
1067                                         bool ok1 = false, ok2 = false;
1068                                         bool ok3 = false, ok4 = false;
1069                                         unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
1070                                         unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
1071                                         unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
1072                                         unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
1073                                         if(ok1) fSizeW = temp1;
1074                                         if(ok2) fSizeH = temp2;
1075                                         if(ok3) fpsNom = temp3;
1076                                         if(ok4) frames = temp4;
1077                                 }
1078                                 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
1079                                 {
1080                                         bool ok1 = false, ok2 = false;
1081                                         bool ok3 = false, ok4 = false, ok5 = false;
1082                                         unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
1083                                         unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
1084                                         unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
1085                                         unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
1086                                         unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
1087                                         if(ok1) fSizeW = temp1;
1088                                         if(ok2) fSizeH = temp2;
1089                                         if(ok3) fpsNom = temp3;
1090                                         if(ok4) fpsDen = temp4;
1091                                         if(ok5) frames = temp5;
1092                                 }
1093                                 if(!text.isEmpty())
1094                                 {
1095                                         log(text);
1096                                 }
1097                                 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
1098                                 {
1099                                         log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(x64 ? "64" : "32"));
1100                                 }
1101                                 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
1102                                 {
1103                                         log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
1104                                 }
1105                         }
1106                 }
1107         }
1108
1109         process.waitForFinished();
1110         if(process.state() != QProcess::NotRunning)
1111         {
1112                 process.kill();
1113                 process.waitForFinished(-1);
1114         }
1115
1116         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1117         {
1118                 if(!(bTimeout || bAborted))
1119                 {
1120                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
1121                 }
1122                 return false;
1123         }
1124
1125         if(frames == 0)
1126         {
1127                 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
1128                 return false;
1129         }
1130         
1131         log("");
1132
1133         if((fSizeW > 0) && (fSizeH > 0))
1134         {
1135                 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1136         }
1137         if((fpsNom > 0) && (fpsDen > 0))
1138         {
1139                 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
1140         }
1141         if((fpsNom > 0) && (fpsDen == 0))
1142         {
1143                 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
1144         }
1145         if(frames > 0)
1146         {
1147                 log(tr("No. Frames: %1").arg(QString::number(frames)));
1148         }
1149
1150         return true;
1151 }
1152
1153 bool EncodeThread::checkPropertiesVapoursynth(/*const QString &vspipePath,*/ unsigned int &frames)
1154 {
1155         QProcess process;
1156         QStringList cmdLine;
1157
1158         cmdLine << pathToAnsi(QDir::toNativeSeparators(m_sourceFileName));
1159         cmdLine << "-" << "-info";
1160
1161         log("Creating process:");
1162         if(!startProcess(process, VPSP_BINARY(m_vpsDir), cmdLine))
1163         {
1164                 return false;;
1165         }
1166
1167         QRegExp regExpFrm("\\bFrames:\\s+(\\d+)\\b");
1168         QRegExp regExpSzW("\\bWidth:\\s+(\\d+)\\b");
1169         QRegExp regExpSzH("\\bHeight:\\s+(\\d+)\\b");
1170         
1171         QTextCodec *localCodec = QTextCodec::codecForName("System");
1172
1173         bool bTimeout = false;
1174         bool bAborted = false;
1175
1176         frames = 0;
1177         
1178         unsigned int fSizeW = 0;
1179         unsigned int fSizeH = 0;
1180         
1181         unsigned int waitCounter = 0;
1182
1183         while(process.state() != QProcess::NotRunning)
1184         {
1185                 if(m_abort)
1186                 {
1187                         process.kill();
1188                         bAborted = true;
1189                         break;
1190                 }
1191                 if(!process.waitForReadyRead(m_processTimeoutInterval))
1192                 {
1193                         if(process.state() == QProcess::Running)
1194                         {
1195                                 if(++waitCounter > m_processTimeoutMaxCounter)
1196                                 {
1197                                         if(m_abortOnTimeout)
1198                                         {
1199                                                 process.kill();
1200                                                 qWarning("VSPipe process timed out <-- killing!");
1201                                                 log("\nPROCESS TIMEOUT !!!");
1202                                                 log("\nVapoursynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
1203                                                 bTimeout = true;
1204                                                 break;
1205                                         }
1206                                 }
1207                                 else if(waitCounter == m_processTimeoutWarning)
1208                                 {
1209                                         unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
1210                                         log(tr("Warning: nVapoursynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
1211                                 }
1212                         }
1213                         continue;
1214                 }
1215                 
1216                 waitCounter = 0;
1217                 
1218                 while(process.bytesAvailable() > 0)
1219                 {
1220                         QList<QByteArray> lines = process.readLine().split('\r');
1221                         while(!lines.isEmpty())
1222                         {
1223                                 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
1224                                 int offset = -1;
1225                                 if((offset = regExpFrm.lastIndexIn(text)) >= 0)
1226                                 {
1227                                         bool ok = false;
1228                                         unsigned int temp = regExpFrm.cap(1).toUInt(&ok);
1229                                         if(ok) frames = temp;
1230                                 }
1231                                 if((offset = regExpSzW.lastIndexIn(text)) >= 0)
1232                                 {
1233                                         bool ok = false;
1234                                         unsigned int temp = regExpSzW.cap(1).toUInt(&ok);
1235                                         if(ok) fSizeW = temp;
1236                                 }
1237                                 if((offset = regExpSzH.lastIndexIn(text)) >= 0)
1238                                 {
1239                                         bool ok = false;
1240                                         unsigned int temp = regExpSzH.cap(1).toUInt(&ok);
1241                                         if(ok) fSizeH = temp;
1242                                 }
1243                                 if(!text.isEmpty())
1244                                 {
1245                                         log(text);
1246                                 }
1247                         }
1248                 }
1249         }
1250
1251         process.waitForFinished();
1252         if(process.state() != QProcess::NotRunning)
1253         {
1254                 process.kill();
1255                 process.waitForFinished(-1);
1256         }
1257
1258         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
1259         {
1260                 if(!(bTimeout || bAborted))
1261                 {
1262                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
1263                 }
1264                 return false;
1265         }
1266
1267         if(frames == 0)
1268         {
1269                 log(tr("\nFAILED TO DETERMINE VPY PROPERTIES !!!"));
1270                 return false;
1271         }
1272         
1273         log("");
1274
1275         if((fSizeW > 0) && (fSizeH > 0))
1276         {
1277                 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
1278         }
1279         if(frames > 0)
1280         {
1281                 log(tr("No. Frames: %1").arg(QString::number(frames)));
1282         }
1283
1284         return true;
1285 }
1286
1287 ///////////////////////////////////////////////////////////////////////////////
1288 // Misc functions
1289 ///////////////////////////////////////////////////////////////////////////////
1290
1291 void EncodeThread::setStatus(JobStatus newStatus)
1292 {
1293         if(m_status != newStatus)
1294         {
1295                 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
1296                 {
1297                         if(m_status != JobStatus_Paused) setProgress(0);
1298                 }
1299                 if(newStatus == JobStatus_Failed)
1300                 {
1301                         setDetails("The job has failed. See log for details!");
1302                 }
1303                 if(newStatus == JobStatus_Aborted)
1304                 {
1305                         setDetails("The job was aborted by the user!");
1306                 }
1307                 m_status = newStatus;
1308                 emit statusChanged(m_jobId, newStatus);
1309         }
1310 }
1311
1312 void EncodeThread::setProgress(unsigned int newProgress)
1313 {
1314         if(m_progress != newProgress)
1315         {
1316                 m_progress = newProgress;
1317                 emit progressChanged(m_jobId, m_progress);
1318         }
1319 }
1320
1321 void EncodeThread::setDetails(const QString &text)
1322 {
1323         emit detailsChanged(m_jobId, text);
1324 }
1325
1326 QString EncodeThread::pathToAnsi(const QString &longPath)
1327 {
1328         QString shortPath = longPath;
1329         
1330         DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1331         
1332         if(buffSize > 0)
1333         {
1334                 wchar_t *buffer = new wchar_t[buffSize];
1335                 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1336
1337                 if((result > 0) && (result < buffSize))
1338                 {
1339                         shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer), result);
1340                 }
1341
1342                 delete[] buffer;
1343                 buffer = NULL;
1344         }
1345
1346         return shortPath;
1347 }
1348
1349 QString EncodeThread::stringToHash(const QString &string)
1350 {
1351         QByteArray result(10, char(0));
1352         const QByteArray hash = QCryptographicHash::hash(string.toUtf8(), QCryptographicHash::Sha1);
1353
1354         if((hash.size() == 20) && (result.size() == 10))
1355         {
1356                 unsigned char *out = reinterpret_cast<unsigned char*>(result.data());
1357                 const unsigned char *in = reinterpret_cast<const unsigned char*>(hash.constData());
1358                 for(int i = 0; i < 10; i++)
1359                 {
1360                         out[i] = (in[i] ^ in[10+i]);
1361                 }
1362         }
1363
1364         return QString::fromLatin1(result.toHex().constData());
1365 }
1366
1367 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
1368 {
1369         QMutexLocker lock(&m_mutex_startProcess);
1370         log(commandline2string(program, args) + "\n");
1371
1372         //Create a new job object, if not done yet
1373         if(!m_handle_jobObject)
1374         {
1375                 m_handle_jobObject = CreateJobObject(NULL, NULL);
1376                 if(m_handle_jobObject == INVALID_HANDLE_VALUE)
1377                 {
1378                         m_handle_jobObject = NULL;
1379                 }
1380                 if(m_handle_jobObject)
1381                 {
1382                         JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
1383                         memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1384                         jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
1385                         SetInformationJobObject(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
1386                 }
1387         }
1388
1389         process.setWorkingDirectory(QDir::tempPath());
1390
1391         if(mergeChannels)
1392         {
1393                 process.setProcessChannelMode(QProcess::MergedChannels);
1394                 process.setReadChannel(QProcess::StandardOutput);
1395         }
1396         else
1397         {
1398                 process.setProcessChannelMode(QProcess::SeparateChannels);
1399                 process.setReadChannel(QProcess::StandardError);
1400         }
1401
1402         process.start(program, args);
1403         
1404         if(process.waitForStarted())
1405         {
1406                 Q_PID pid = process.pid();
1407                 if(pid != NULL)
1408                 {
1409                         AssignProcessToJobObject(m_handle_jobObject, process.pid()->hProcess);
1410                         setPorcessPriority(process.pid()->hProcess, m_processPriority);
1411                 }
1412                 
1413                 lock.unlock();
1414                 return true;
1415         }
1416
1417         log("Process creation has failed :-(");
1418         QString errorMsg= process.errorString().trimmed();
1419         if(!errorMsg.isEmpty()) log(errorMsg);
1420
1421         process.kill();
1422         process.waitForFinished(-1);
1423         return false;
1424 }
1425
1426 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
1427 {
1428         QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
1429         
1430         for(int i = 0; i < arguments.count(); i++)
1431         {
1432                 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
1433         }
1434
1435         return commandline;
1436 }
1437
1438 QStringList EncodeThread::splitParams(const QString &params)
1439 {
1440         QStringList list; 
1441         bool ignoreWhitespaces = false;
1442         QString temp;
1443
1444         for(int i = 0; i < params.length(); i++)
1445         {
1446                 const QChar c = params.at(i);
1447
1448                 if(c == QChar::fromLatin1('"'))
1449                 {
1450                         ignoreWhitespaces = (!ignoreWhitespaces);
1451                         continue;
1452                 }
1453                 else if((!ignoreWhitespaces) && (c == QChar::fromLatin1(' ')))
1454                 {
1455                         APPEND_AND_CLEAR(list, temp);
1456                         continue;
1457                 }
1458                 
1459                 temp.append(c);
1460         }
1461         
1462         APPEND_AND_CLEAR(list, temp);
1463
1464         list.replaceInStrings("$(INPUT)", QDir::toNativeSeparators(m_sourceFileName), Qt::CaseInsensitive);
1465         list.replaceInStrings("$(OUTPUT)", QDir::toNativeSeparators(m_outputFileName), Qt::CaseInsensitive);
1466
1467         return list;
1468 }
1469
1470 qint64 EncodeThread::estimateSize(int progress)
1471 {
1472         if(progress >= 3)
1473         {
1474                 qint64 currentSize = QFileInfo(m_outputFileName).size();
1475                 qint64 estimatedSize = (currentSize * 100I64) / static_cast<qint64>(progress);
1476                 return estimatedSize;
1477         }
1478
1479         return 0I64;
1480 }
1481
1482 QString EncodeThread::sizeToString(qint64 size)
1483 {
1484         static char *prefix[5] = {"Byte", "KB", "MB", "GB", "TB"};
1485
1486         if(size > 1024I64)
1487         {
1488                 qint64 estimatedSize = size;
1489                 qint64 remainderSize = 0I64;
1490
1491                 int prefixIdx = 0;
1492                 while((estimatedSize > 1024I64) && (prefixIdx < 4))
1493                 {
1494                         remainderSize = estimatedSize % 1024I64;
1495                         estimatedSize = estimatedSize / 1024I64;
1496                         prefixIdx++;
1497                 }
1498                         
1499                 double value = static_cast<double>(estimatedSize) + (static_cast<double>(remainderSize) / 1024.0);
1500                 return QString().sprintf((value < 10.0) ? "%.2f %s" : "%.1f %s", value, prefix[prefixIdx]);
1501         }
1502
1503         return tr("N/A");
1504 }
1505
1506 int EncodeThread::getInputType(const QString &fileExt)
1507 {
1508         int type = INPUT_NATIVE;
1509         if(fileExt.compare("avs", Qt::CaseInsensitive) == 0)       type = INPUT_AVISYN;
1510         else if(fileExt.compare("avsi", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
1511         else if(fileExt.compare("vpy", Qt::CaseInsensitive) == 0)  type = INPUT_VAPOUR;
1512         else if(fileExt.compare("py", Qt::CaseInsensitive) == 0)   type = INPUT_VAPOUR;
1513         return type;
1514 }
1515
1516 void EncodeThread::setPorcessPriority(void *processId, int priroity)
1517 {
1518         switch(priroity)
1519         {
1520         case PreferencesModel::X264_PRIORITY_ABOVENORMAL:
1521                 if(!SetPriorityClass(processId, ABOVE_NORMAL_PRIORITY_CLASS))
1522                 {
1523                         SetPriorityClass(processId, NORMAL_PRIORITY_CLASS);
1524                 }
1525                 break;
1526         case PreferencesModel::X264_PRIORITY_NORMAL:
1527                 SetPriorityClass(processId, NORMAL_PRIORITY_CLASS);
1528                 break;
1529         case PreferencesModel::X264_PRIORITY_BELOWNORMAL:
1530                 if(!SetPriorityClass(processId, BELOW_NORMAL_PRIORITY_CLASS))
1531                 {
1532                         SetPriorityClass(processId, IDLE_PRIORITY_CLASS);
1533                 }
1534                 break;
1535         case PreferencesModel::X264_PRIORITY_IDLE:
1536                 SetPriorityClass(processId, IDLE_PRIORITY_CLASS);
1537                 break;
1538         }
1539 }