OSDN Git Service

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