OSDN Git Service

Refactored source types (Avisynth, VapourSynth, etc) into separate classes + loads...
[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 //Internal
25 #include "global.h"
26 #include "model_options.h"
27 #include "model_preferences.h"
28 #include "model_sysinfo.h"
29 #include "job_object.h"
30 #include "binaries.h"
31
32 //Encoders
33 #include "encoder_x264.h"
34 #include "encoder_x265.h"
35
36 //Source
37 #include "source_avisynth.h"
38 #include "source_vapoursynth.h"
39
40 //Qt Framework
41 #include <QDate>
42 #include <QTime>
43 #include <QDateTime>
44 #include <QFileInfo>
45 #include <QDir>
46 #include <QProcess>
47 #include <QMutex>
48 #include <QTextCodec>
49 #include <QLocale>
50 #include <QCryptographicHash>
51
52 /*
53  * RAII execution state handler
54  */
55 class ExecutionStateHandler
56 {
57 public:
58         ExecutionStateHandler(void)
59         {
60                 x264_set_thread_execution_state(true);
61         }
62         ~ExecutionStateHandler(void)
63         {
64                 x264_set_thread_execution_state(false);
65         }
66 private:
67         //Disable copy constructor and assignment
68         ExecutionStateHandler(const ExecutionStateHandler &other) {}
69         ExecutionStateHandler &operator=(const ExecutionStateHandler &) {}
70
71         //Prevent object allocation on the heap
72         void *operator new(size_t);   void *operator new[](size_t);
73         void operator delete(void *); void operator delete[](void*);
74 };
75
76 /*
77  * Macros
78  */
79 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
80 { \
81         if(ABORT_FLAG) \
82         { \
83                 log("\nPROCESS ABORTED BY USER !!!"); \
84                 setStatus(JobStatus_Aborted); \
85                 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
86                 return; \
87         } \
88         else if(!(OK_FLAG)) \
89         { \
90                 setStatus(JobStatus_Failed); \
91                 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
92                 return; \
93         } \
94 } \
95 while(0)
96
97 /*
98  * Input types
99  */
100 typedef enum
101 {
102         INPUT_NATIVE = 0,
103         INPUT_AVISYN = 1,
104         INPUT_VAPOUR = 2
105 };
106
107 /*
108  * Static vars
109  */
110 //static const char *VPS_TEST_FILE = "import vapoursynth as vs\ncore = vs.get_core()\nv = core.std.BlankClip()\nv.set_output()\n";
111
112 ///////////////////////////////////////////////////////////////////////////////
113 // Constructor & Destructor
114 ///////////////////////////////////////////////////////////////////////////////
115
116 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
117 :
118         m_jobId(QUuid::createUuid()),
119         m_sourceFileName(sourceFileName),
120         m_outputFileName(outputFileName),
121         m_options(new OptionsModel(*options)),
122         m_sysinfo(sysinfo),
123         m_preferences(preferences),
124         m_jobObject(new JobObject),
125         m_semaphorePaused(0),
126         m_encoder(NULL),
127         m_pipedSource(NULL)
128 {
129         m_abort = false;
130         m_pause = false;
131
132         //Create encoder object
133         switch(options->encType())
134         {
135         case OptionsModel::EncType_X264:
136                 m_encoder = new X264Encoder(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName, m_outputFileName);
137                 break;
138         case OptionsModel::EncType_X265:
139                 m_encoder = new X265Encoder(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName, m_outputFileName);
140                 break;
141         default:
142                 throw "Unknown encoder type encountered!";
143         }
144
145         //Create input handler object
146         switch(getInputType(QFileInfo(m_sourceFileName).suffix()))
147         {
148         case INPUT_AVISYN:
149                 m_pipedSource = new AvisynthSource   (m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
150                 break;
151         case INPUT_VAPOUR:
152                 m_pipedSource = new VapoursynthSource(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
153                 break;
154         }
155
156         //Establish connections
157         connect(m_encoder, SIGNAL(statusChanged(JobStatus)), this, SIGNAL(setStatus(QString)), Qt::DirectConnection);
158         connect(m_encoder, SIGNAL(progressChanged(unsigned int)), this, SIGNAL(setProgress(QString)), Qt::DirectConnection);
159         connect(m_encoder, SIGNAL(messageLogged(QString)), this, SIGNAL(log(QString)), Qt::DirectConnection);
160         connect(m_encoder, SIGNAL(detailsChanged(QString)), this, SIGNAL(setDetails(QString)), Qt::DirectConnection);
161         if(m_pipedSource)
162         {
163                 connect(m_pipedSource, SIGNAL(statusChanged(JobStatus)), this, SIGNAL(setStatus(QString)), Qt::DirectConnection);
164                 connect(m_pipedSource, SIGNAL(progressChanged(unsigned int)), this, SIGNAL(setProgress(QString)), Qt::DirectConnection);
165                 connect(m_pipedSource, SIGNAL(messageLogged(QString)), this, SIGNAL(log(QString)), Qt::DirectConnection);
166                 connect(m_pipedSource, SIGNAL(detailsChanged(QString)), this, SIGNAL(setDetails(QString)), Qt::DirectConnection);
167         }
168 }
169
170 EncodeThread::~EncodeThread(void)
171 {
172         X264_DELETE(m_encoder);
173         X264_DELETE(m_jobObject);
174         X264_DELETE(m_options);
175 }
176
177 ///////////////////////////////////////////////////////////////////////////////
178 // Thread entry point
179 ///////////////////////////////////////////////////////////////////////////////
180
181 void EncodeThread::run(void)
182 {
183 #if !defined(_DEBUG)
184         __try
185         {
186                 checkedRun();
187         }
188         __except(1)
189         {
190                 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
191         }
192 #else
193         checkedRun();
194 #endif
195
196         if(m_jobObject)
197         {
198                 m_jobObject->terminateJob(42);
199                 X264_DELETE(m_jobObject);
200         }
201 }
202
203 void EncodeThread::checkedRun(void)
204 {
205         m_progress = 0;
206         m_status = JobStatus_Starting;
207
208         try
209         {
210                 try
211                 {
212                         ExecutionStateHandler executionStateHandler;
213                         encode();
214                 }
215                 catch(char *msg)
216                 {
217                         log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
218                         setStatus(JobStatus_Failed);
219                 }
220                 catch(...)
221                 {
222                         log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
223                         setStatus(JobStatus_Failed);
224                 }
225         }
226         catch(...)
227         {
228                 x264_fatal_exit(L"Unhandeled exception error in encode thread!");
229         }
230 }
231
232 void EncodeThread::start(Priority priority)
233 {
234         qDebug("Thread starting...");
235
236         m_abort = false;
237         m_pause = false;
238
239         while(m_semaphorePaused.tryAcquire(1, 0));
240         QThread::start(priority);
241 }
242
243 ///////////////////////////////////////////////////////////////////////////////
244 // Encode functions
245 ///////////////////////////////////////////////////////////////////////////////
246
247 void EncodeThread::encode(void)
248 {
249         QDateTime startTime = QDateTime::currentDateTime();
250
251         // -----------------------------------------------------------------------------------
252         // Print Information
253         // -----------------------------------------------------------------------------------
254
255         //Print some basic info
256         log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
257         log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
258         log(tr("Source file: %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
259         log(tr("Output file: %1").arg(QDir::toNativeSeparators(m_outputFileName)));
260         
261         //Print system info
262         log(tr("\n--- SYSTEMINFO ---\n"));
263         log(tr("Binary Path: %1").arg(QDir::toNativeSeparators(m_sysinfo->getAppPath())));
264         log(tr("Avisynth OK: %1").arg(m_sysinfo->hasAVSSupport() ? tr("Yes") : tr("No")));
265         log(tr("VapourSynth: %1").arg(m_sysinfo->hasVPSSupport() ? QDir::toNativeSeparators(m_sysinfo->getVPSPath()) : tr("N/A")));
266
267         //Print encoder settings
268         log(tr("\n--- SETTINGS ---\n"));
269         log(tr("RC Mode: %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
270         log(tr("Preset:  %1").arg(m_options->preset()));
271         log(tr("Tuning:  %1").arg(m_options->tune()));
272         log(tr("Profile: %1").arg(m_options->profile()));
273         log(tr("Custom:  %1").arg(m_options->customEncParams().isEmpty() ? tr("(None)") : m_options->customEncParams()));
274         
275         bool ok = false;
276         unsigned int frames = 0;
277         
278         // -----------------------------------------------------------------------------------
279         // Check Versions
280         // -----------------------------------------------------------------------------------
281         
282         log(tr("\n--- CHECK VERSION ---\n"));
283
284         //Check encoder version
285         bool encoderModified = false;
286         const unsigned int encoderRevision = m_encoder->checkVersion(encoderModified);
287         CHECK_STATUS(m_abort, (ok = (encoderRevision != UINT_MAX)));
288         
289         //Print source versions
290         m_encoder->printVersion(encoderRevision, encoderModified);
291
292         //Is encoder version suppoprted?
293         if(!m_encoder->isVersionSupported(encoderRevision, encoderModified))
294         {
295                 setStatus(JobStatus_Failed);
296                 return;
297         }
298
299         if(m_pipedSource)
300         {
301                 //Checking source version
302                 bool sourceModified = false;
303                 const unsigned int sourceRevision = m_pipedSource->checkVersion(sourceModified);
304                 CHECK_STATUS(m_abort, (ok = (sourceRevision != UINT_MAX)));
305
306                 //Print source versions
307                 m_pipedSource->printVersion(sourceModified, sourceModified);
308
309                 //Is source version supported?
310                 if(!m_pipedSource->isVersionSupported(sourceRevision, sourceModified))
311                 {
312                         setStatus(JobStatus_Failed);
313                         return;
314                 }
315         }
316
317         // -----------------------------------------------------------------------------------
318         // Detect Source Info
319         // -----------------------------------------------------------------------------------
320
321         //Detect source info
322         if(m_pipedSource)
323         {
324                 log(tr("\n--- GET SOURCE INFO ---\n"));
325                 ok = m_pipedSource->checkSourceProperties(frames);
326                 CHECK_STATUS(m_abort, ok);
327         }
328
329         // -----------------------------------------------------------------------------------
330         // Encoding Passes
331         // -----------------------------------------------------------------------------------
332
333         //Run encoding passes
334         if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
335         {
336                 const QString passLogFile = getPasslogFile(m_outputFileName);
337                 
338                 log(tr("\n--- ENCODING PASS #1 ---\n"));
339                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames, 1, passLogFile);
340                 CHECK_STATUS(m_abort, ok);
341
342                 log(tr("\n--- ENCODING PASS #2 ---\n"));
343                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames, 2, passLogFile);
344                 CHECK_STATUS(m_abort, ok);
345         }
346         else
347         {
348                 log(tr("\n--- ENCODING VIDEO ---\n"));
349                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames);
350                 CHECK_STATUS(m_abort, ok);
351         }
352
353         // -----------------------------------------------------------------------------------
354         // Encoding complete
355         // -----------------------------------------------------------------------------------
356
357         log(tr("\n--- COMPLETED ---\n"));
358
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 ///////////////////////////////////////////////////////////////////////////////
365 // Misc functions
366 ///////////////////////////////////////////////////////////////////////////////
367
368 void EncodeThread::log(const QString &text)
369 {
370         emit messageLogged(m_jobId, text);
371 }
372
373 void EncodeThread::setStatus(const JobStatus &newStatus)
374 {
375         if(m_status != newStatus)
376         {
377                 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
378                 {
379                         if(m_status != JobStatus_Paused) setProgress(0);
380                 }
381                 if(newStatus == JobStatus_Failed)
382                 {
383                         setDetails("The job has failed. See log for details!");
384                 }
385                 if(newStatus == JobStatus_Aborted)
386                 {
387                         setDetails("The job was aborted by the user!");
388                 }
389                 m_status = newStatus;
390                 emit statusChanged(m_jobId, newStatus);
391         }
392 }
393
394 void EncodeThread::setProgress(const unsigned int &newProgress)
395 {
396         if(m_progress != newProgress)
397         {
398                 m_progress = newProgress;
399                 emit progressChanged(m_jobId, m_progress);
400         }
401 }
402
403 void EncodeThread::setDetails(const QString &text)
404 {
405         emit detailsChanged(m_jobId, text);
406 }
407
408 int EncodeThread::getInputType(const QString &fileExt)
409 {
410         int type = INPUT_NATIVE;
411
412         if(fileExt.compare("avs",  Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
413         if(fileExt.compare("avsi", Qt::CaseInsensitive) == 0) type = INPUT_AVISYN;
414         if(fileExt.compare("vpy",  Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
415         if(fileExt.compare("py",   Qt::CaseInsensitive) == 0) type = INPUT_VAPOUR;
416
417         return type;
418 }
419
420 QString EncodeThread::getPasslogFile(const QString &outputFile)
421 {
422         QFileInfo info(outputFile);
423         QString passLogFile = QString("%1/%2.stats").arg(info.absolutePath(), info.completeBaseName());
424         int counter = 1;
425
426         while(QFileInfo(passLogFile).exists())
427         {
428                 passLogFile = QString("%1/%2_%3.stats").arg(info.absolutePath(), info.completeBaseName(), QString::number(++counter));
429         }
430
431         return passLogFile;
432 }
433
434
435
436
437 // ==========================================
438 // DISABLED
439 // ==========================================
440
441 /*
442 unsigned int EncodeThread::checkVersionAvs2yuv(void)
443 {
444         if(!m_sysinfo->hasAVSSupport())
445         {
446                 log(tr("\nAVS INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
447                 return false;
448         }
449
450         QProcess process;
451
452         log("\nCreating process:");
453         if(!startProcess(process, AVS_BINARY(m_sysinfo, m_preferences), QStringList()))
454         {
455                 return false;;
456         }
457
458         QRegExp regExpVersionMod("\\bAvs2YUV (\\d+).(\\d+)bm(\\d)\\b", Qt::CaseInsensitive);
459         QRegExp regExpVersionOld("\\bAvs2YUV (\\d+).(\\d+)\\b", Qt::CaseInsensitive);
460         
461         bool bTimeout = false;
462         bool bAborted = false;
463
464         unsigned int ver_maj = UINT_MAX;
465         unsigned int ver_min = UINT_MAX;
466         unsigned int ver_mod = 0;
467
468         while(process.state() != QProcess::NotRunning)
469         {
470                 if(m_abort)
471                 {
472                         process.kill();
473                         bAborted = true;
474                         break;
475                 }
476                 if(!process.waitForReadyRead())
477                 {
478                         if(process.state() == QProcess::Running)
479                         {
480                                 process.kill();
481                                 qWarning("Avs2YUV process timed out <-- killing!");
482                                 log("\nPROCESS TIMEOUT !!!");
483                                 bTimeout = true;
484                                 break;
485                         }
486                 }
487                 while(process.bytesAvailable() > 0)
488                 {
489                         QList<QByteArray> lines = process.readLine().split('\r');
490                         while(!lines.isEmpty())
491                         {
492                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
493                                 int offset = -1;
494                                 if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX) || (ver_mod == UINT_MAX))
495                                 {
496                                         if(!text.isEmpty())
497                                         {
498                                                 log(text);
499                                         }
500                                 }
501                                 if((offset = regExpVersionMod.lastIndexIn(text)) >= 0)
502                                 {
503                                         bool ok1 = false, ok2 = false, ok3 = false;
504                                         unsigned int temp1 = regExpVersionMod.cap(1).toUInt(&ok1);
505                                         unsigned int temp2 = regExpVersionMod.cap(2).toUInt(&ok2);
506                                         unsigned int temp3 = regExpVersionMod.cap(3).toUInt(&ok3);
507                                         if(ok1) ver_maj = temp1;
508                                         if(ok2) ver_min = temp2;
509                                         if(ok3) ver_mod = temp3;
510                                 }
511                                 else if((offset = regExpVersionOld.lastIndexIn(text)) >= 0)
512                                 {
513                                         bool ok1 = false, ok2 = false;
514                                         unsigned int temp1 = regExpVersionOld.cap(1).toUInt(&ok1);
515                                         unsigned int temp2 = regExpVersionOld.cap(2).toUInt(&ok2);
516                                         if(ok1) ver_maj = temp1;
517                                         if(ok2) ver_min = temp2;
518                                 }
519                         }
520                 }
521         }
522
523         process.waitForFinished();
524         if(process.state() != QProcess::NotRunning)
525         {
526                 process.kill();
527                 process.waitForFinished(-1);
528         }
529
530         if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 2)))
531         {
532                 if(!(bTimeout || bAborted))
533                 {
534                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
535                 }
536                 return UINT_MAX;
537         }
538
539         if((ver_maj == UINT_MAX) || (ver_min == UINT_MAX))
540         {
541                 log(tr("\nFAILED TO DETERMINE AVS2YUV VERSION !!!"));
542                 return UINT_MAX;
543         }
544         
545         return (ver_maj * REV_MULT) + ((ver_min % REV_MULT) * 10) + (ver_mod % 10);
546 }
547
548 bool EncodeThread::checkVersionVapoursynth(void)
549 {
550         //Is VapourSynth available at all?
551         if((!m_sysinfo->hasVPSSupport()) || (!QFileInfo(VPS_BINARY(m_sysinfo, m_preferences)).isFile()))
552         {
553                 log(tr("\nVPY INPUT REQUIRES VAPOURSYNTH, BUT IT IS *NOT* AVAILABLE !!!"));
554                 return false;
555         }
556
557         QProcess process;
558
559         log("\nCreating process:");
560         if(!startProcess(process, VPS_BINARY(m_sysinfo, m_preferences), QStringList()))
561         {
562                 return false;;
563         }
564
565         QRegExp regExpSignature("\\bVSPipe\\s+usage\\b", Qt::CaseInsensitive);
566         
567         bool bTimeout = false;
568         bool bAborted = false;
569
570         bool vspipeSignature = false;
571
572         while(process.state() != QProcess::NotRunning)
573         {
574                 if(m_abort)
575                 {
576                         process.kill();
577                         bAborted = true;
578                         break;
579                 }
580                 if(!process.waitForReadyRead())
581                 {
582                         if(process.state() == QProcess::Running)
583                         {
584                                 process.kill();
585                                 qWarning("VSPipe process timed out <-- killing!");
586                                 log("\nPROCESS TIMEOUT !!!");
587                                 bTimeout = true;
588                                 break;
589                         }
590                 }
591                 while(process.bytesAvailable() > 0)
592                 {
593                         QList<QByteArray> lines = process.readLine().split('\r');
594                         while(!lines.isEmpty())
595                         {
596                                 QString text = QString::fromUtf8(lines.takeFirst().constData()).simplified();
597                                 if(regExpSignature.lastIndexIn(text) >= 0)
598                                 {
599                                         vspipeSignature = true;
600                                 }
601                                 if(!text.isEmpty())
602                                 {
603                                         log(text);
604                                 }
605                         }
606                 }
607         }
608
609         process.waitForFinished();
610         if(process.state() != QProcess::NotRunning)
611         {
612                 process.kill();
613                 process.waitForFinished(-1);
614         }
615
616         if(bTimeout || bAborted || ((process.exitCode() != EXIT_SUCCESS) && (process.exitCode() != 1)))
617         {
618                 if(!(bTimeout || bAborted))
619                 {
620                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(process.exitCode())));
621                 }
622                 return false;
623         }
624
625         if(!vspipeSignature)
626         {
627                 log(tr("\nFAILED TO DETECT VSPIPE SIGNATURE !!!"));
628                 return false;
629         }
630         
631         return vspipeSignature;
632 }
633
634 bool EncodeThread::checkPropertiesAVS(unsigned int &frames)
635 {
636         QProcess process;
637         QStringList cmdLine;
638
639         if(!m_options->customAvs2YUV().isEmpty())
640         {
641                 cmdLine.append(splitParams(m_options->customAvs2YUV()));
642         }
643
644         cmdLine << "-frames" << "1";
645         cmdLine << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true)) << "NUL";
646
647         log("Creating process:");
648         if(!startProcess(process, AVS_BINARY(m_sysinfo, m_preferences), cmdLine))
649         {
650                 return false;;
651         }
652
653         QRegExp regExpInt(": (\\d+)x(\\d+), (\\d+) fps, (\\d+) frames");
654         QRegExp regExpFrc(": (\\d+)x(\\d+), (\\d+)/(\\d+) fps, (\\d+) frames");
655         
656         QTextCodec *localCodec = QTextCodec::codecForName("System");
657
658         bool bTimeout = false;
659         bool bAborted = false;
660
661         frames = 0;
662         
663         unsigned int fpsNom = 0;
664         unsigned int fpsDen = 0;
665         unsigned int fSizeW = 0;
666         unsigned int fSizeH = 0;
667         
668         unsigned int waitCounter = 0;
669
670         while(process.state() != QProcess::NotRunning)
671         {
672                 if(m_abort)
673                 {
674                         process.kill();
675                         bAborted = true;
676                         break;
677                 }
678                 if(!process.waitForReadyRead(m_processTimeoutInterval))
679                 {
680                         if(process.state() == QProcess::Running)
681                         {
682                                 if(++waitCounter > m_processTimeoutMaxCounter)
683                                 {
684                                         if(m_preferences->getAbortOnTimeout())
685                                         {
686                                                 process.kill();
687                                                 qWarning("Avs2YUV process timed out <-- killing!");
688                                                 log("\nPROCESS TIMEOUT !!!");
689                                                 log("\nAvisynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
690                                                 bTimeout = true;
691                                                 break;
692                                         }
693                                 }
694                                 else if(waitCounter == m_processTimeoutWarning)
695                                 {
696                                         unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
697                                         log(tr("Warning: Avisynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
698                                 }
699                         }
700                         continue;
701                 }
702                 
703                 waitCounter = 0;
704                 
705                 while(process.bytesAvailable() > 0)
706                 {
707                         QList<QByteArray> lines = process.readLine().split('\r');
708                         while(!lines.isEmpty())
709                         {
710                                 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
711                                 int offset = -1;
712                                 if((offset = regExpInt.lastIndexIn(text)) >= 0)
713                                 {
714                                         bool ok1 = false, ok2 = false;
715                                         bool ok3 = false, ok4 = false;
716                                         unsigned int temp1 = regExpInt.cap(1).toUInt(&ok1);
717                                         unsigned int temp2 = regExpInt.cap(2).toUInt(&ok2);
718                                         unsigned int temp3 = regExpInt.cap(3).toUInt(&ok3);
719                                         unsigned int temp4 = regExpInt.cap(4).toUInt(&ok4);
720                                         if(ok1) fSizeW = temp1;
721                                         if(ok2) fSizeH = temp2;
722                                         if(ok3) fpsNom = temp3;
723                                         if(ok4) frames = temp4;
724                                 }
725                                 else if((offset = regExpFrc.lastIndexIn(text)) >= 0)
726                                 {
727                                         bool ok1 = false, ok2 = false;
728                                         bool ok3 = false, ok4 = false, ok5 = false;
729                                         unsigned int temp1 = regExpFrc.cap(1).toUInt(&ok1);
730                                         unsigned int temp2 = regExpFrc.cap(2).toUInt(&ok2);
731                                         unsigned int temp3 = regExpFrc.cap(3).toUInt(&ok3);
732                                         unsigned int temp4 = regExpFrc.cap(4).toUInt(&ok4);
733                                         unsigned int temp5 = regExpFrc.cap(5).toUInt(&ok5);
734                                         if(ok1) fSizeW = temp1;
735                                         if(ok2) fSizeH = temp2;
736                                         if(ok3) fpsNom = temp3;
737                                         if(ok4) fpsDen = temp4;
738                                         if(ok5) frames = temp5;
739                                 }
740                                 if(!text.isEmpty())
741                                 {
742                                         log(text);
743                                 }
744                                 if(text.contains("failed to load avisynth.dll", Qt::CaseInsensitive))
745                                 {
746                                         log(tr("\nWarning: It seems that %1-Bit Avisynth is not currently installed !!!").arg(m_preferences->getUseAvisyth64Bit() ? "64" : "32"));
747                                 }
748                                 if(text.contains(QRegExp("couldn't convert input clip to (YV16|YV24)", Qt::CaseInsensitive)))
749                                 {
750                                         log(tr("\nWarning: YV16 (4:2:2) and YV24 (4:4:4) color-spaces only supported in Avisynth 2.6 !!!"));
751                                 }
752                         }
753                 }
754         }
755
756         process.waitForFinished();
757         if(process.state() != QProcess::NotRunning)
758         {
759                 process.kill();
760                 process.waitForFinished(-1);
761         }
762
763         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
764         {
765                 if(!(bTimeout || bAborted))
766                 {
767                         const int exitCode = process.exitCode();
768                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(exitCode)));
769                         if((exitCode < 0) || (exitCode >= 32))
770                         {
771                                 log(tr("\nIMPORTANT: The Avs2YUV process terminated abnormally. This means Avisynth or one of your Avisynth-Plugin's just crashed."));
772                                 log(tr("IMPORTANT: Please fix your Avisynth script and try again! If you use Avisynth-MT, try using a *stable* Avisynth instead!"));
773                         }
774                 }
775                 return false;
776         }
777
778         if(frames == 0)
779         {
780                 log(tr("\nFAILED TO DETERMINE AVS PROPERTIES !!!"));
781                 return false;
782         }
783         
784         log("");
785
786         if((fSizeW > 0) && (fSizeH > 0))
787         {
788                 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
789         }
790         if((fpsNom > 0) && (fpsDen > 0))
791         {
792                 log(tr("Frame Rate: %1/%2").arg(QString::number(fpsNom), QString::number(fpsDen)));
793         }
794         if((fpsNom > 0) && (fpsDen == 0))
795         {
796                 log(tr("Frame Rate: %1").arg(QString::number(fpsNom)));
797         }
798         if(frames > 0)
799         {
800                 log(tr("No. Frames: %1").arg(QString::number(frames)));
801         }
802
803         return true;
804 }
805
806 bool EncodeThread::checkPropertiesVPS(unsigned int &frames)
807 {
808         QProcess process;
809         QStringList cmdLine;
810
811         cmdLine << QDir::toNativeSeparators(x264_path2ansi(m_sourceFileName, true));
812         cmdLine << "-" << "-info";
813
814         log("Creating process:");
815         if(!startProcess(process, VPS_BINARY(m_sysinfo, m_preferences), cmdLine))
816         {
817                 return false;;
818         }
819
820         QRegExp regExpFrm("\\bFrames:\\s+(\\d+)\\b");
821         QRegExp regExpSzW("\\bWidth:\\s+(\\d+)\\b");
822         QRegExp regExpSzH("\\bHeight:\\s+(\\d+)\\b");
823         
824         QTextCodec *localCodec = QTextCodec::codecForName("System");
825
826         bool bTimeout = false;
827         bool bAborted = false;
828
829         frames = 0;
830         
831         unsigned int fSizeW = 0;
832         unsigned int fSizeH = 0;
833         
834         unsigned int waitCounter = 0;
835
836         while(process.state() != QProcess::NotRunning)
837         {
838                 if(m_abort)
839                 {
840                         process.kill();
841                         bAborted = true;
842                         break;
843                 }
844                 if(!process.waitForReadyRead(m_processTimeoutInterval))
845                 {
846                         if(process.state() == QProcess::Running)
847                         {
848                                 if(++waitCounter > m_processTimeoutMaxCounter)
849                                 {
850                                         if(m_preferences->getAbortOnTimeout())
851                                         {
852                                                 process.kill();
853                                                 qWarning("VSPipe process timed out <-- killing!");
854                                                 log("\nPROCESS TIMEOUT !!!");
855                                                 log("\nVapoursynth has encountered a deadlock or your script takes EXTREMELY long to initialize!");
856                                                 bTimeout = true;
857                                                 break;
858                                         }
859                                 }
860                                 else if(waitCounter == m_processTimeoutWarning)
861                                 {
862                                         unsigned int timeOut = (waitCounter * m_processTimeoutInterval) / 1000U;
863                                         log(tr("Warning: nVapoursynth did not respond for %1 seconds, potential deadlock...").arg(QString::number(timeOut)));
864                                 }
865                         }
866                         continue;
867                 }
868                 
869                 waitCounter = 0;
870                 
871                 while(process.bytesAvailable() > 0)
872                 {
873                         QList<QByteArray> lines = process.readLine().split('\r');
874                         while(!lines.isEmpty())
875                         {
876                                 QString text = localCodec->toUnicode(lines.takeFirst().constData()).simplified();
877                                 int offset = -1;
878                                 if((offset = regExpFrm.lastIndexIn(text)) >= 0)
879                                 {
880                                         bool ok = false;
881                                         unsigned int temp = regExpFrm.cap(1).toUInt(&ok);
882                                         if(ok) frames = temp;
883                                 }
884                                 if((offset = regExpSzW.lastIndexIn(text)) >= 0)
885                                 {
886                                         bool ok = false;
887                                         unsigned int temp = regExpSzW.cap(1).toUInt(&ok);
888                                         if(ok) fSizeW = temp;
889                                 }
890                                 if((offset = regExpSzH.lastIndexIn(text)) >= 0)
891                                 {
892                                         bool ok = false;
893                                         unsigned int temp = regExpSzH.cap(1).toUInt(&ok);
894                                         if(ok) fSizeH = temp;
895                                 }
896                                 if(!text.isEmpty())
897                                 {
898                                         log(text);
899                                 }
900                         }
901                 }
902         }
903
904         process.waitForFinished();
905         if(process.state() != QProcess::NotRunning)
906         {
907                 process.kill();
908                 process.waitForFinished(-1);
909         }
910
911         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
912         {
913                 if(!(bTimeout || bAborted))
914                 {
915                         const int exitCode = process.exitCode();
916                         log(tr("\nPROCESS EXITED WITH ERROR CODE: %1").arg(QString::number(exitCode)));
917                         if((exitCode < 0) || (exitCode >= 32))
918                         {
919                                 log(tr("\nIMPORTANT: The Vapoursynth process terminated abnormally. This means Vapoursynth or one of your Vapoursynth-Plugin's just crashed."));
920                         }
921                 }
922                 return false;
923         }
924
925         if(frames == 0)
926         {
927                 log(tr("\nFAILED TO DETERMINE VPY PROPERTIES !!!"));
928                 return false;
929         }
930         
931         log("");
932
933         if((fSizeW > 0) && (fSizeH > 0))
934         {
935                 log(tr("Resolution: %1x%2").arg(QString::number(fSizeW), QString::number(fSizeH)));
936         }
937         if(frames > 0)
938         {
939                 log(tr("No. Frames: %1").arg(QString::number(frames)));
940         }
941
942         return true;
943 }
944 */