OSDN Git Service

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