OSDN Git Service

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