OSDN Git Service

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