OSDN Git Service

Added "Pause" support.
[x264-launcher/x264-launcher.git] / src / thread_encode.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2012 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 "version.h"
27
28 #include <QDate>
29 #include <QTime>
30 #include <QDateTime>
31 #include <QFileInfo>
32 #include <QDir>
33 #include <QProcess>
34 #include <QMutex>
35 #include <QLibrary>
36
37 /*
38  * Win32 API definitions
39  */
40 typedef HANDLE (WINAPI *CreateJobObjectFun)(__in_opt LPSECURITY_ATTRIBUTES lpJobAttributes, __in_opt LPCSTR lpName);
41 typedef BOOL (WINAPI *SetInformationJobObjectFun)(__in HANDLE hJob, __in JOBOBJECTINFOCLASS JobObjectInformationClass, __in_bcount(cbJobObjectInformationLength) LPVOID lpJobObjectInformation, __in DWORD cbJobObjectInformationLength);
42 typedef BOOL (WINAPI *AssignProcessToJobObjectFun)(__in HANDLE hJob, __in HANDLE hProcess);
43
44 /*
45  * Static vars
46  */
47 QMutex EncodeThread::m_mutex_startProcess;
48
49 /*
50  * Macros
51  */
52 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) \
53 { \
54         if(ABORT_FLAG) \
55         { \
56                 log("\nPROCESS ABORTED BY USER !!!"); \
57                 setStatus(JobStatus_Aborted); \
58                 return; \
59         } \
60         else if(!(OK_FLAG)) \
61         { \
62                 setStatus(JobStatus_Failed); \
63                 return; \
64         } \
65 }
66
67 /*
68  * Static vars
69  */
70 static const unsigned int REV_MULT = 10000;
71
72 ///////////////////////////////////////////////////////////////////////////////
73 // Constructor & Destructor
74 ///////////////////////////////////////////////////////////////////////////////
75
76 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const QString &binDir, bool x64)
77 :
78         m_jobId(QUuid::createUuid()),
79         m_sourceFileName(sourceFileName),
80         m_outputFileName(outputFileName),
81         m_options(new OptionsModel(*options)),
82         m_binDir(binDir),
83         m_x64(x64),
84         m_handle_jobObject(NULL),
85         m_semaphorePaused(0)
86 {
87         m_abort = false;
88         m_pause = false;
89 }
90
91 EncodeThread::~EncodeThread(void)
92 {
93         X264_DELETE(m_options);
94         
95         if(m_handle_jobObject)
96         {
97                 CloseHandle(m_handle_jobObject);
98                 m_handle_jobObject = NULL;
99         }
100 }
101
102 ///////////////////////////////////////////////////////////////////////////////
103 // Thread entry point
104 ///////////////////////////////////////////////////////////////////////////////
105
106 void EncodeThread::run(void)
107 {
108         __try
109         {
110                 checkedRun();
111         }
112         __except(1)
113         {
114                 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
115         }
116
117         if(m_handle_jobObject)
118         {
119                 CloseHandle(m_handle_jobObject);
120                 m_handle_jobObject = NULL;
121         }
122 }
123
124 void EncodeThread::checkedRun(void)
125 {
126         m_progress = 0;
127         m_status = JobStatus_Starting;
128
129         try
130         {
131                 try
132                 {
133                         encode();
134                 }
135                 catch(char *msg)
136                 {
137                         log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
138                         setStatus(JobStatus_Failed);
139                 }
140                 catch(...)
141                 {
142                         log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
143                         setStatus(JobStatus_Failed);
144                 }
145         }
146         catch(...)
147         {
148                 RaiseException(EXCEPTION_ACCESS_VIOLATION, 0, 0, NULL);
149         }
150 }
151
152 void EncodeThread::start(Priority priority)
153 {
154         qDebug("Thread starting...");
155
156         m_abort = false;
157         m_pause = false;
158
159         while(m_semaphorePaused.tryAcquire(1, 0));
160         QThread::start(priority);
161 }
162
163 ///////////////////////////////////////////////////////////////////////////////
164 // Encode functions
165 ///////////////////////////////////////////////////////////////////////////////
166
167 void EncodeThread::encode(void)
168 {
169         QDateTime startTime = QDateTime::currentDateTime();
170
171         //Print some basic info
172         log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
173         log(tr("Source file: %1").arg(m_sourceFileName));
174         log(tr("Output file: %1").arg(m_outputFileName));
175         
176         //Print encoder settings
177         log(tr("\n--- SETTINGS ---\n"));
178         log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
179         log(tr("Preset:  %1").arg(m_options->preset()));
180         log(tr("Tuning:  %1").arg(m_options->tune()));
181         log(tr("Profile: %1").arg(m_options->profile()));
182         log(tr("Custom:  %1").arg(m_options->custom().isEmpty() ? tr("(None)") : m_options->custom()));
183         
184         bool ok = false;
185         unsigned int frames = 0;
186
187         //Use Avisynth?
188         const bool usePipe = (QFileInfo(m_sourceFileName).suffix().compare("avs", Qt::CaseInsensitive) == 0);
189
190         //Checking x264 version
191         log(tr("\n--- CHECK VERSION ---\n"));
192         unsigned int revision_x264 = UINT_MAX;
193         ok = ((revision_x264 = checkVersionX264(m_x64)) != UINT_MAX);
194         CHECK_STATUS(m_abort, ok);
195         
196         //Checking avs2yuv version
197         unsigned int revision_avs2yuv = UINT_MAX;
198         if(usePipe)
199         {
200                 ok = ((revision_avs2yuv = checkVersionAvs2yuv()) != UINT_MAX);
201                 CHECK_STATUS(m_abort, ok);
202         }
203
204         //Print versions
205         log(tr("\nx264 revision: %1 (core #%2)").arg(QString::number(revision_x264 % REV_MULT), QString::number(revision_x264 / REV_MULT)));
206         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)));
207
208         //Is x264 revision supported?
209         if((revision_x264 % REV_MULT) < VER_X264_MINIMUM_REV)
210         {
211                 log(tr("\nERROR: Your revision of x264 is too old! (Minimum required revision is %2)").arg(QString::number(VER_X264_MINIMUM_REV)));
212                 setStatus(JobStatus_Failed);
213                 return;
214         }
215         if((revision_x264 / REV_MULT) != VER_X264_CURRENT_API)
216         {
217                 log(tr("\nWARNING: Your revision of x264 uses an unsupported core (API) version, take care!"));
218                 log(tr("This application works best with x264 core (API) version %2.").arg(QString::number(VER_X264_CURRENT_API)));
219         }
220         if((revision_avs2yuv != UINT_MAX) && ((revision_avs2yuv % REV_MULT) != VER_x264_AVS2YUV_VER))
221         {
222                 log(tr("\nERROR: Your version of avs2yuv is unsupported (Required version: v0.24 BugMaster's mod 2)"));
223                 log(tr("You can find the required version at: http://komisar.gin.by/tools/avs2yuv/"));
224                 setStatus(JobStatus_Failed);
225                 return;
226         }
227
228         //Detect source info
229         if(usePipe)
230         {
231                 log(tr("\n--- AVS INFO ---\n"));
232                 ok = checkProperties(frames);
233                 CHECK_STATUS(m_abort, ok);
234         }
235
236         //Run encoding passes
237         if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
238         {
239                 QFileInfo info(m_outputFileName);
240                 QString passLogFile = QString("%1/%2.stats").arg(info.path(), info.completeBaseName());
241
242                 if(QFileInfo(passLogFile).exists())
243                 {
244                         int n = 2;
245                         while(QFileInfo(passLogFile).exists())
246                         {
247                                 passLogFile = QString("%1/%2.%3.stats").arg(info.path(), info.completeBaseName(), QString::number(n++));
248                         }
249                 }
250                 
251                 log(tr("\n--- PASS 1 ---\n"));
252                 ok = runEncodingPass(m_x64, usePipe, frames, 1, passLogFile);
253                 CHECK_STATUS(m_abort, ok);
254
255                 log(tr("\n--- PASS 2 ---\n"));
256                 ok = runEncodingPass(m_x64, usePipe, frames, 2, passLogFile);
257                 CHECK_STATUS(m_abort, ok);
258         }
259         else
260         {
261                 log(tr("\n--- ENCODING ---\n"));
262                 ok = runEncodingPass(m_x64, usePipe, frames);
263                 CHECK_STATUS(m_abort, ok);
264         }
265
266         log(tr("\n--- DONE ---\n"));
267         int timePassed = startTime.secsTo(QDateTime::currentDateTime());
268         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)));
269         setStatus(JobStatus_Completed);
270 }
271
272 bool EncodeThread::runEncodingPass(bool x64, bool usePipe, unsigned int frames, int pass, const QString &passLogFile)
273 {
274         QProcess processEncode, processAvisynth;
275         
276         if(usePipe)
277         {
278                 QStringList cmdLine_Avisynth;
279                 cmdLine_Avisynth << QDir::toNativeSeparators(m_sourceFileName);
280                 cmdLine_Avisynth << "-";
281                 processAvisynth.setStandardOutputProcess(&processEncode);
282
283                 log("Creating Avisynth process:");
284                 if(!startProcess(processAvisynth, QString("%1/avs2yuv.exe").arg(m_binDir), cmdLine_Avisynth, false))
285                 {
286                         return false;
287                 }
288         }
289
290         QStringList cmdLine_Encode = buildCommandLine(usePipe, frames, pass, passLogFile);
291
292         log("Creating x264 process:");
293         if(!startProcess(processEncode, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine_Encode))
294         {
295                 return false;
296         }
297
298         QRegExp regExpIndexing("indexing.+\\[(\\d+)\\.\\d+%\\]");
299         QRegExp regExpProgress("\\[(\\d+)\\.\\d+%\\].+frames");
300         QRegExp regExpFrameCnt("^(\\d+) frames:");
301         
302         bool bTimeout = false;
303         bool bAborted = false;
304
305         //Main processing loop
306         while(processEncode.state() != QProcess::NotRunning)
307         {
308                 unsigned int waitCounter = 0;
309
310                 //Wait until new output is available
311                 forever
312                 {
313                         if(m_abort)
314                         {
315                                 processEncode.kill();
316                                 processAvisynth.kill();
317                                 bAborted = true;
318                                 break;
319                         }
320                         if(m_pause && (processEncode.state() == QProcess::Running))
321                         {
322                                 JobStatus previousStatus = m_status;
323                                 setStatus(JobStatus_Paused);
324                                 log(tr("Job paused by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
325                                 bool ok[2] = {false, false};
326                                 Q_PID pid[2] = {processEncode.pid(), processAvisynth.pid()};
327                                 if(pid[0]) { ok[0] = (SuspendThread(pid[0]->hThread) != (DWORD)(-1)); }
328                                 if(pid[1]) { ok[1] = (SuspendThread(pid[1]->hThread) != (DWORD)(-1)); }
329                                 while(m_pause) m_semaphorePaused.acquire();
330                                 while(m_semaphorePaused.tryAcquire(1, 0));
331                                 if(pid[0]) { if(ok[0]) ResumeThread(pid[0]->hThread); }
332                                 if(pid[1]) { if(ok[1]) ResumeThread(pid[1]->hThread); }
333                                 if(!m_abort) setStatus(previousStatus);
334                                 log(tr("Job resumed by user at %1, %2.").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
335                                 waitCounter = 0;
336                                 continue;
337                         }
338                         if(!processEncode.waitForReadyRead(2500))
339                         {
340                                 if(processEncode.state() == QProcess::Running)
341                                 {
342                                         if(waitCounter++ > m_processTimeoutCounter)
343                                         {
344                                                 processEncode.kill();
345                                                 qWarning("x264 process timed out <-- killing!");
346                                                 log("\nPROCESS TIMEOUT !!!");
347                                                 bTimeout = true;
348                                                 break;
349                                         }
350                                         continue;
351                                 }
352                         }
353                         if(m_abort || (m_pause && (processEncode.state() == QProcess::Running)))
354                         {
355                                 continue;
356                         }
357                         break;
358                 }
359                 
360                 //Exit main processing loop now?
361                 if(bAborted || bTimeout)
362                 {
363                         break;
364                 }
365
366                 //Process all output
367                 while(processEncode.bytesAvailable() > 0)
368                 {
369                         QList<QByteArray> lines = processEncode.readLine().split('\r');
370                         while(!lines.isEmpty())
371                         {
372                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
373                                 int offset = -1;
374                                 if((offset = regExpProgress.lastIndexIn(text)) >= 0)
375                                 {
376                                         bool ok = false;
377                                         unsigned int progress = regExpProgress.cap(1).toUInt(&ok);
378                                         setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
379                                         setDetails(text.mid(offset).trimmed());
380                                         if(ok) setProgress(progress);
381                                 }
382                                 else if((offset = regExpIndexing.lastIndexIn(text)) >= 0)
383                                 {
384                                         bool ok = false;
385                                         unsigned int progress = regExpIndexing.cap(1).toUInt(&ok);
386                                         setStatus(JobStatus_Indexing);
387                                         setDetails(text.mid(offset).trimmed());
388                                         if(ok) setProgress(progress);
389                                 }
390                                 else if((offset = regExpFrameCnt.lastIndexIn(text)) >= 0)
391                                 {
392                                         setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
393                                         setDetails(text.mid(offset).trimmed());
394                                 }
395                                 else if(!text.isEmpty())
396                                 {
397                                         log(text);
398                                 }
399                         }
400                 }
401         }
402
403         processEncode.waitForFinished(5000);
404         if(processEncode.state() != QProcess::NotRunning)
405         {
406                 qWarning("x264 process still running, going to kill it!");
407                 processEncode.kill();
408                 processEncode.waitForFinished(-1);
409         }
410         
411         processAvisynth.waitForFinished(5000);
412         if(processAvisynth.state() != QProcess::NotRunning)
413         {
414                 qWarning("Avisynth process still running, going to kill it!");
415                 processAvisynth.kill();
416                 processAvisynth.waitForFinished(-1);
417         }
418
419         if(!(bTimeout || bAborted))
420         {
421                 while(processAvisynth.bytesAvailable() > 0)
422                 {
423                         log(tr("av2y [info]: %1").arg(QString::fromUtf8(processAvisynth.readLine()).simplified()));
424                 }
425         }
426
427         if(usePipe && (processAvisynth.exitCode() != EXIT_SUCCESS))
428         {
429                 if(!(bTimeout || bAborted))
430                 {
431                         log(tr("\nWARNING: Avisynth process exited with error code: %1").arg(QString::number(processAvisynth.exitCode())));
432                 }
433         }
434
435         if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS)
436         {
437                 if(!(bTimeout || bAborted))
438                 {
439                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(processEncode.exitCode())));
440                 }
441                 processEncode.close();
442                 processAvisynth.close();
443                 return false;
444         }
445
446         switch(pass)
447         {
448         case 1:
449                 setStatus(JobStatus_Running_Pass1);
450                 setDetails(tr("First pass completed. Preparing for second pass..."));
451                 break;
452         case 2:
453                 setStatus(JobStatus_Running_Pass2);
454                 setDetails(tr("Second pass completed successfully."));
455                 break;
456         default:
457                 setStatus(JobStatus_Running);
458                 setDetails(tr("Encode completed successfully."));
459                 break;
460         }
461
462         setProgress(100);
463         processEncode.close();
464         processAvisynth.close();
465         return true;
466 }
467
468 QStringList EncodeThread::buildCommandLine(bool usePipe, unsigned int frames, int pass, const QString &passLogFile)
469 {
470         QStringList cmdLine;
471
472         switch(m_options->rcMode())
473         {
474         case OptionsModel::RCMode_CRF:
475                 cmdLine << "--crf" << QString::number(m_options->quantizer());
476                 break;
477         case OptionsModel::RCMode_CQ:
478                 cmdLine << "--qp" << QString::number(m_options->quantizer());
479                 break;
480         case OptionsModel::RCMode_2Pass:
481         case OptionsModel::RCMode_ABR:
482                 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
483                 break;
484         default:
485                 throw "Bad rate-control mode !!!";
486                 break;
487         }
488         
489         if((pass == 1) || (pass == 2))
490         {
491                 cmdLine << "--pass" << QString::number(pass);
492                 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
493         }
494
495         cmdLine << "--preset" << m_options->preset().toLower();
496
497         if(m_options->tune().compare("none", Qt::CaseInsensitive))
498         {
499                 cmdLine << "--tune" << m_options->tune().toLower();
500         }
501
502         if(m_options->profile().compare("auto", Qt::CaseInsensitive))
503         {
504                 cmdLine << "--profile" << m_options->profile().toLower();
505         }
506
507         if(!m_options->custom().isEmpty())
508         {
509                 //FIXME: Handle custom parameters that contain spaces!
510                 cmdLine.append(m_options->custom().split(" "));
511         }
512
513         cmdLine << "--output" << QDir::toNativeSeparators(m_outputFileName);
514         
515         if(usePipe)
516         {
517                 if(frames < 1) throw "Frames not set!";
518                 cmdLine << "--frames" << QString::number(frames);
519                 cmdLine << "--demuxer" << "y4m";
520                 cmdLine << "--stdin" << "y4m" << "-";
521         }
522         else
523         {
524                 cmdLine << QDir::toNativeSeparators(m_sourceFileName);
525         }
526
527         return cmdLine;
528 }
529
530 unsigned int EncodeThread::checkVersionX264(bool x64)
531 {
532         QProcess process;
533         QStringList cmdLine = QStringList() << "--version";
534
535         log("Creating process:");
536         if(!startProcess(process, QString("%1/%2.exe").arg(m_binDir, x64 ? "x264_x64" : "x264"), cmdLine))
537         {
538                 return false;;
539         }
540
541         QRegExp regExpVersion("\\bx264 (\\d)\\.(\\d+)\\.(\\d+)\\b");
542         
543         bool bTimeout = false;
544         bool bAborted = false;
545
546         unsigned int revision = UINT_MAX;
547         unsigned int coreVers = UINT_MAX;
548
549         while(process.state() != QProcess::NotRunning)
550         {
551                 if(m_abort)
552                 {
553                         process.kill();
554                         bAborted = true;
555                         break;
556                 }
557                 if(!process.waitForReadyRead())
558                 {
559                         if(process.state() == QProcess::Running)
560                         {
561                                 process.kill();
562                                 qWarning("x264 process timed out <-- killing!");
563                                 log("\nPROCESS TIMEOUT !!!");
564                                 bTimeout = true;
565                                 break;
566                         }
567                 }
568                 while(process.bytesAvailable() > 0)
569                 {
570                         QList<QByteArray> lines = process.readLine().split('\r');
571                         while(!lines.isEmpty())
572                         {
573                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
574                                 int offset = -1;
575                                 if((offset = regExpVersion.lastIndexIn(text)) >= 0)
576                                 {
577                                         bool ok1 = false, ok2 = false;
578                                         unsigned int temp1 = regExpVersion.cap(2).toUInt(&ok1);
579                                         unsigned int temp2 = regExpVersion.cap(3).toUInt(&ok2);
580                                         if(ok1) coreVers = temp1;
581                                         if(ok2) revision = temp2;
582                                 }
583                                 if(!text.isEmpty())
584                                 {
585                                         log(text);
586                                 }
587                         }
588                 }
589         }
590
591         process.waitForFinished();
592         if(process.state() != QProcess::NotRunning)
593         {
594                 process.kill();
595                 process.waitForFinished(-1);
596         }
597
598         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
599         {
600                 if(!(bTimeout || bAborted))
601                 {
602                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
603                 }
604                 return UINT_MAX;
605         }
606
607         if((revision == UINT_MAX) || (coreVers == UINT_MAX))
608         {
609                 log(tr("\nFAILED TO DETERMINE X264 VERSION !!!"));
610                 return UINT_MAX;
611         }
612         
613         return (coreVers * REV_MULT) + (revision % REV_MULT);
614 }
615
616 unsigned int EncodeThread::checkVersionAvs2yuv(void)
617 {
618         QProcess process;
619
620         log("\nCreating process:");
621         if(!startProcess(process, QString("%1/avs2yuv.exe").arg(m_binDir), QStringList()))
622         {
623                 return false;;
624         }
625
626         QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b");
627         QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b");
628         
629         bool bTimeout = false;
630         bool bAborted = false;
631
632         unsigned int ver_maj = UINT_MAX;
633         unsigned int ver_min = UINT_MAX;
634         unsigned int ver_mod = 0;
635
636         while(process.state() != QProcess::NotRunning)
637         {
638                 if(m_abort)
639                 {
640                         process.kill();
641                         bAborted = true;
642                         break;
643                 }
644                 if(!process.waitForReadyRead())
645                 {
646                         if(process.state() == QProcess::Running)
647                         {
648                                 process.kill();
649                                 qWarning("Avs2YUV process timed out <-- killing!");
650                                 log("\nPROCESS TIMEOUT !!!");
651                                 bTimeout = true;
652                                 break;
653                         }
654                 }
655                 while(process.bytesAvailable() > 0)
656                 {
657                         QList<QByteArray> lines = process.readLine().split('\r');
658                         while(!lines.isEmpty())
659                         {
660                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
661                                 int offset = -1;
662                                 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
663                                 {
664                                         if(!text.isEmpty())
665                                         {
666                                                 log(text);
667                                         }
668                                 }
669                                 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
670                                 {
671                                         bool ok1 = false, ok2 = false, ok3 = false;
672                                         unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
673                                         unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
674                                         unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
675                                         if(ok1) ver_maj = temp1;
676                                         if(ok2) ver_min = temp2;
677                                         if(ok3) ver_mod = temp3;
678                                 }
679                                 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
680                                 {
681                                         bool ok1 = false, ok2 = false;
682                                         unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
683                                         unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
684                                         if(ok1) ver_maj = temp1;
685                                         if(ok2) ver_min = temp2;
686                                 }
687                         }
688                 }
689         }
690
691         process.waitForFinished();
692         if(process.state() != QProcess::NotRunning)
693         {
694                 process.kill();
695                 process.waitForFinished(-1);
696         }
697
698         if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
699         {
700                 if(!(bTimeout || bAborted))
701                 {
702                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
703                 }
704                 return UINT_MAX;
705         }
706
707         if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
708         {
709                 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
710                 return UINT_MAX;
711         }
712         
713         return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
714 }
715
716 bool EncodeThread::checkProperties(unsigned int &frames)
717 {
718         QProcess process;
719         
720         QStringList cmdLine = QStringList() << "-frames" << "1";
721         cmdLine << QDir::toNativeSeparators(m_sourceFileName) << "NUL";
722
723         log("Creating process:");
724         if(!startProcess(process, QString("%1/avs2yuv.exe").arg(m_binDir), cmdLine))
725         {
726                 return false;;
727         }
728
729         QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
730         QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
731         
732         bool bTimeout = false;
733         bool bAborted = false;
734
735         frames = 0;
736         
737         unsigned int fpsNom = 0;
738         unsigned int fpsDen = 0;
739         unsigned int fSizeW = 0;
740         unsigned int fSizeH = 0;
741         
742         while(process.state() != QProcess::NotRunning)
743         {
744                 if(m_abort)
745                 {
746                         process.kill();
747                         bAborted = true;
748                         break;
749                 }
750                 if(!process.waitForReadyRead())
751                 {
752                         if(process.state() == QProcess::Running)
753                         {
754                                 process.kill();
755                                 qWarning("Avs2YUV process timed out <-- killing!");
756                                 log("\nPROCESS TIMEOUT !!!");
757                                 bTimeout = true;
758                                 break;
759                         }
760                 }
761                 while(process.bytesAvailable() > 0)
762                 {
763                         QList<QByteArray> lines = process.readLine().split('\r');
764                         while(!lines.isEmpty())
765                         {
766                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
767                                 int offset = -1;
768                                 if((offset = regExpInt.lastIndexIn(text)) >= 0)
769                                 {
770                                         bool ok1 = false, ok2 = false;
771                                         bool ok3 = false, ok4 = false;
772                                         unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
773                                         unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
774                                         unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
775                                         unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
776                                         if(ok1) fSizeW = temp1;
777                                         if(ok2) fSizeH = temp2;
778                                         if(ok3) fpsNom = temp3;
779                                         if(ok4) frames = temp4;
780                                 }
781                                 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
782                                 {
783                                         bool ok1 = false, ok2 = false;
784                                         bool ok3 = false, ok4 = false, ok5 = false;
785                                         unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
786                                         unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
787                                         unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
788                                         unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
789                                         unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
790                                         if(ok1) fSizeW = temp1;
791                                         if(ok2) fSizeH = temp2;
792                                         if(ok3) fpsNom = temp3;
793                                         if(ok4) fpsDen = temp4;
794                                         if(ok5) frames = temp5;
795                                 }
796                                 if(!text.isEmpty())
797                                 {
798                                         log(text);
799                                 }
800                         }
801                 }
802         }
803
804         process.waitForFinished();
805         if(process.state() != QProcess::NotRunning)
806         {
807                 process.kill();
808                 process.waitForFinished(-1);
809         }
810
811         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
812         {
813                 if(!(bTimeout || bAborted))
814                 {
815                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
816                 }
817                 return false;
818         }
819
820         if(frames == 0)
821         {
822                 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
823                 return false;
824         }
825         
826         log("");
827
828         if((fSizeW > 0) && (fSizeH > 0))
829         {
830                 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
831         }
832         if((fpsNom > 0) && (fpsDen > 0))
833         {
834                 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
835         }
836         if((fpsNom > 0) && (fpsDen == 0))
837         {
838                 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
839         }
840         if(frames > 0)
841         {
842                 log(tr("No. Frames: %1").arg(QString::number(frames)));
843         }
844
845         return true;
846 }
847
848 ///////////////////////////////////////////////////////////////////////////////
849 // Misc functions
850 ///////////////////////////////////////////////////////////////////////////////
851
852 void EncodeThread::setStatus(JobStatus newStatus)
853 {
854         if(m_status != newStatus)
855         {
856                 m_status = newStatus;
857                 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
858                 {
859                         setProgress(0);
860                 }
861                 if(newStatus == JobStatus_Failed)
862                 {
863                         setDetails("The job has failed. See log for details!");
864                 }
865                 if(newStatus == JobStatus_Aborted)
866                 {
867                         setDetails("The job was aborted by the user!");
868                 }
869                 emit statusChanged(m_jobId, newStatus);
870         }
871 }
872
873 void EncodeThread::setProgress(unsigned int newProgress)
874 {
875         if(m_progress != newProgress)
876         {
877                 m_progress = newProgress;
878                 emit progressChanged(m_jobId, m_progress);
879         }
880 }
881
882 void EncodeThread::setDetails(const QString &text)
883 {
884         emit detailsChanged(m_jobId, text);
885 }
886
887 bool EncodeThread::startProcess(QProcess &process, const QString &program, const QStringList &args, bool mergeChannels)
888 {
889         static AssignProcessToJobObjectFun AssignProcessToJobObjectPtr = NULL;
890         static CreateJobObjectFun CreateJobObjectPtr = NULL;
891         static SetInformationJobObjectFun SetInformationJobObjectPtr = NULL;
892         
893         QMutexLocker lock(&m_mutex_startProcess);
894         log(commandline2string(program, args) + "\n");
895
896         //Create a new job object, if not done yet
897         if(!m_handle_jobObject)
898         {
899                 if(!CreateJobObjectPtr || !SetInformationJobObjectPtr)
900                 {
901                         QLibrary Kernel32Lib("kernel32.dll");
902                         CreateJobObjectPtr = (CreateJobObjectFun) Kernel32Lib.resolve("CreateJobObjectA");
903                         SetInformationJobObjectPtr = (SetInformationJobObjectFun) Kernel32Lib.resolve("SetInformationJobObject");
904                 }
905                 if(CreateJobObjectPtr && SetInformationJobObjectPtr)
906                 {
907                         m_handle_jobObject = CreateJobObjectPtr(NULL, NULL);
908                         if(m_handle_jobObject == INVALID_HANDLE_VALUE)
909                         {
910                                 m_handle_jobObject = NULL;
911                         }
912                         if(m_handle_jobObject)
913                         {
914                                 JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobExtendedLimitInfo;
915                                 memset(&jobExtendedLimitInfo, 0, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
916                                 jobExtendedLimitInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION;
917                                 SetInformationJobObjectPtr(m_handle_jobObject, JobObjectExtendedLimitInformation, &jobExtendedLimitInfo, sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
918                         }
919                 }
920         }
921
922         //Initialize AssignProcessToJobObject function
923         if(!AssignProcessToJobObjectPtr)
924         {
925                 QLibrary Kernel32Lib("kernel32.dll");
926                 AssignProcessToJobObjectPtr = (AssignProcessToJobObjectFun) Kernel32Lib.resolve("AssignProcessToJobObject");
927         }
928         
929         if(mergeChannels)
930         {
931                 process.setProcessChannelMode(QProcess::MergedChannels);
932                 process.setReadChannel(QProcess::StandardOutput);
933         }
934         else
935         {
936                 process.setProcessChannelMode(QProcess::SeparateChannels);
937                 process.setReadChannel(QProcess::StandardError);
938         }
939
940         process.start(program, args);
941         
942         if(process.waitForStarted())
943         {
944                 if(AssignProcessToJobObjectPtr)
945                 {
946                         AssignProcessToJobObjectPtr(m_handle_jobObject, process.pid()->hProcess);
947                 }
948                 if(!SetPriorityClass(process.pid()->hProcess, BELOW_NORMAL_PRIORITY_CLASS))
949                 {
950                         SetPriorityClass(process.pid()->hProcess, IDLE_PRIORITY_CLASS);
951                 }
952                 
953                 lock.unlock();
954                 return true;
955         }
956
957         log("Process creation has failed :-(");
958         QString errorMsg= process.errorString().trimmed();
959         if(!errorMsg.isEmpty()) log(errorMsg);
960
961         process.kill();
962         process.waitForFinished(-1);
963         return false;
964 }
965
966 QString EncodeThread::commandline2string(const QString &program, const QStringList &arguments)
967 {
968         QString commandline = (program.contains(' ') ? QString("\"%1\"").arg(program) : program);
969         
970         for(int i = 0; i < arguments.count(); i++)
971         {
972                 commandline += (arguments.at(i).contains(' ') ? QString(" \"%1\"").arg(arguments.at(i)) : QString(" %1").arg(arguments.at(i)));
973         }
974
975         return commandline;
976 }