OSDN Git Service

8f6eb02f4dd3212da93cf9340f53e9251d008dcb
[x264-launcher/x264-launcher.git] / src / thread_encode.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2015 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 #include "mediainfo.h"
32
33 //Encoders
34 #include "encoder_factory.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 #define CONNECT(OBJ) do \
98 { \
99         if((OBJ)) \
100         { \
101                 connect((OBJ), SIGNAL(statusChanged(JobStatus)),      this, SLOT(setStatus(JobStatus)),      Qt::DirectConnection); \
102                 connect((OBJ), SIGNAL(progressChanged(unsigned int)), this, SLOT(setProgress(unsigned int)), Qt::DirectConnection); \
103                 connect((OBJ), SIGNAL(detailsChanged(QString)),       this, SLOT(setDetails(QString)),       Qt::DirectConnection); \
104                 connect((OBJ), SIGNAL(messageLogged(QString)),        this, SLOT(log(QString)),              Qt::DirectConnection); \
105         } \
106 } \
107 while(0)
108
109 ///////////////////////////////////////////////////////////////////////////////
110 // Constructor & Destructor
111 ///////////////////////////////////////////////////////////////////////////////
112
113 EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputFileName, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences)
114 :
115         m_jobId(QUuid::createUuid()),
116         m_sourceFileName(sourceFileName),
117         m_outputFileName(outputFileName),
118         m_options(new OptionsModel(*options)),
119         m_sysinfo(sysinfo),
120         m_preferences(preferences),
121         m_jobObject(new JobObject),
122         m_semaphorePaused(0),
123         m_encoder(NULL),
124         m_pipedSource(NULL)
125 {
126         m_abort = false;
127         m_pause = false;
128
129         //Create encoder object
130         m_encoder = EncoderFactory::createEncoder(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName, m_outputFileName);
131
132         //Create input handler object
133         switch(MediaInfo::analyze(m_sourceFileName))
134         {
135         case MediaInfo::FILETYPE_AVISYNTH:
136                 if(m_sysinfo->hasAVSSupport())
137                 {
138                         m_pipedSource = new AvisynthSource   (m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
139                 }
140                 break;
141         case MediaInfo::FILETYPE_VAPOURSYNTH:
142                 if(m_sysinfo->hasVPSSupport())
143                 {
144                         m_pipedSource = new VapoursynthSource(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
145                 }
146                 break;
147         }
148
149         //Establish connections
150         CONNECT(m_encoder);
151         CONNECT(m_pipedSource);
152 }
153
154 EncodeThread::~EncodeThread(void)
155 {
156         X264_DELETE(m_encoder);
157         X264_DELETE(m_jobObject);
158         X264_DELETE(m_options);
159         X264_DELETE(m_pipedSource);
160 }
161
162 ///////////////////////////////////////////////////////////////////////////////
163 // Thread entry point
164 ///////////////////////////////////////////////////////////////////////////////
165
166 void EncodeThread::run(void)
167 {
168 #if !defined(_DEBUG)
169         __try
170         {
171                 checkedRun();
172         }
173         __except(1)
174         {
175                 qWarning("STRUCTURED EXCEPTION ERROR IN ENCODE THREAD !!!");
176         }
177 #else
178         checkedRun();
179 #endif
180
181         if(m_jobObject)
182         {
183                 m_jobObject->terminateJob(42);
184                 X264_DELETE(m_jobObject);
185         }
186 }
187
188 void EncodeThread::checkedRun(void)
189 {
190         m_progress = 0;
191         m_status = JobStatus_Starting;
192
193         try
194         {
195                 try
196                 {
197                         ExecutionStateHandler executionStateHandler;
198                         encode();
199                 }
200                 catch(const std::exception &e)
201                 {
202                         log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(e.what())));
203                         setStatus(JobStatus_Failed);
204                 }
205                 catch(char *msg)
206                 {
207                         log(tr("EXCEPTION ERROR IN THREAD: ").append(QString::fromLatin1(msg)));
208                         setStatus(JobStatus_Failed);
209                 }
210                 catch(...)
211                 {
212                         log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
213                         setStatus(JobStatus_Failed);
214                 }
215         }
216         catch(...)
217         {
218                 x264_fatal_exit(L"Unhandeled exception error in encode thread!");
219         }
220 }
221
222 void EncodeThread::start(Priority priority)
223 {
224         qDebug("Thread starting...");
225
226         m_abort = false;
227         m_pause = false;
228
229         while(m_semaphorePaused.tryAcquire(1, 0));
230         QThread::start(priority);
231 }
232
233 ///////////////////////////////////////////////////////////////////////////////
234 // Encode functions
235 ///////////////////////////////////////////////////////////////////////////////
236
237 void EncodeThread::encode(void)
238 {
239         QDateTime startTime = QDateTime::currentDateTime();
240
241         // -----------------------------------------------------------------------------------
242         // Print Information
243         // -----------------------------------------------------------------------------------
244
245         //Print some basic info
246         log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), x264_version_date().toString(Qt::ISODate)));
247         log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
248         log(tr("Source file : %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
249         log(tr("Output file : %1").arg(QDir::toNativeSeparators(m_outputFileName)));
250         
251         //Print system info
252         log(tr("\n--- SYSTEMINFO ---\n"));
253         log(tr("Binary Path : %1").arg(QDir::toNativeSeparators(m_sysinfo->getAppPath())));
254         log(tr("Avisynth    : %1").arg(m_sysinfo->hasAVSSupport() ? tr("Yes") : tr("No")));
255         log(tr("VapourSynth : %1").arg(m_sysinfo->hasVPSSupport() ? QDir::toNativeSeparators(m_sysinfo->getVPSPath()) : tr("N/A")));
256
257         //Print encoder settings
258         log(tr("\n--- SETTINGS ---\n"));
259         log(tr("Encoder : %1").arg(m_encoder->getName()));
260         log(tr("Source  : %1").arg(m_pipedSource ? m_pipedSource->getName() : tr("Native")));
261         log(tr("RC Mode : %1").arg(OptionsModel::rcMode2String(m_options->rcMode())));
262         log(tr("Preset  : %1").arg(m_options->preset()));
263         log(tr("Tuning  : %1").arg(m_options->tune()));
264         log(tr("Profile : %1").arg(m_options->profile()));
265         log(tr("Custom  : %1").arg(m_options->customEncParams().isEmpty() ? tr("<None>") : m_options->customEncParams()));
266         
267         bool ok = false;
268         unsigned int frames = 0;
269         
270         // -----------------------------------------------------------------------------------
271         // Check Versions
272         // -----------------------------------------------------------------------------------
273         
274         log(tr("\n--- CHECK VERSION ---\n"));
275
276         unsigned int encoderRevision = UINT_MAX, sourceRevision = UINT_MAX;
277         bool encoderModified = false, sourceModified = false;
278
279         log("Detect video encoder version:\n");
280
281         //Check encoder version
282         encoderRevision = m_encoder->checkVersion(encoderModified);
283         CHECK_STATUS(m_abort, (ok = (encoderRevision != UINT_MAX)));
284
285         //Is encoder version suppoprted?
286         CHECK_STATUS(m_abort, (ok = m_encoder->isVersionSupported(encoderRevision, encoderModified)));
287
288         if(m_pipedSource)
289         {
290                 log("\nDetect video source version:\n");
291
292                 //Is source type available?
293                 CHECK_STATUS(m_abort, (ok = m_pipedSource->isSourceAvailable()));
294
295                 //Checking source version
296                 sourceRevision = m_pipedSource->checkVersion(sourceModified);
297                 CHECK_STATUS(m_abort, (ok = (sourceRevision != UINT_MAX)));
298
299                 //Is source version supported?
300                 CHECK_STATUS(m_abort, (ok = m_pipedSource->isVersionSupported(sourceRevision, sourceModified)));
301         }
302
303         //Print tool versions
304         log(QString("\n> %1").arg(m_encoder->printVersion(encoderRevision, encoderModified)));
305         if(m_pipedSource)
306         {
307                 log(QString("> %1").arg(m_pipedSource->printVersion(sourceRevision, sourceModified)));
308         }
309
310         // -----------------------------------------------------------------------------------
311         // Detect Source Info
312         // -----------------------------------------------------------------------------------
313
314         //Detect source info
315         if(m_pipedSource)
316         {
317                 log(tr("\n--- GET SOURCE INFO ---\n"));
318                 ok = m_pipedSource->checkSourceProperties(frames);
319                 CHECK_STATUS(m_abort, ok);
320         }
321
322         // -----------------------------------------------------------------------------------
323         // Encoding Passes
324         // -----------------------------------------------------------------------------------
325
326         //Run encoding passes
327         if(m_options->rcMode() == OptionsModel::RCMode_2Pass)
328         {
329                 const QString passLogFile = getPasslogFile(m_outputFileName);
330                 
331                 log(tr("\n--- ENCODING PASS #1 ---\n"));
332                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames, 1, passLogFile);
333                 CHECK_STATUS(m_abort, ok);
334
335                 log(tr("\n--- ENCODING PASS #2 ---\n"));
336                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames, 2, passLogFile);
337                 CHECK_STATUS(m_abort, ok);
338         }
339         else
340         {
341                 log(tr("\n--- ENCODING VIDEO ---\n"));
342                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, frames);
343                 CHECK_STATUS(m_abort, ok);
344         }
345
346         // -----------------------------------------------------------------------------------
347         // Encoding complete
348         // -----------------------------------------------------------------------------------
349
350         log(tr("\n--- COMPLETED ---\n"));
351
352         int timePassed = startTime.secsTo(QDateTime::currentDateTime());
353         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)));
354         setStatus(JobStatus_Completed);
355 }
356
357 ///////////////////////////////////////////////////////////////////////////////
358 // Misc functions
359 ///////////////////////////////////////////////////////////////////////////////
360
361 void EncodeThread::log(const QString &text)
362 {
363         emit messageLogged(m_jobId, text);
364 }
365
366 void EncodeThread::setStatus(const JobStatus &newStatus)
367 {
368         if(m_status != newStatus)
369         {
370                 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
371                 {
372                         if(m_status != JobStatus_Paused) setProgress(0);
373                 }
374                 if(newStatus == JobStatus_Failed)
375                 {
376                         setDetails("The job has failed. See log for details!");
377                 }
378                 if(newStatus == JobStatus_Aborted)
379                 {
380                         setDetails("The job was aborted by the user!");
381                 }
382                 m_status = newStatus;
383                 emit statusChanged(m_jobId, newStatus);
384         }
385 }
386
387 void EncodeThread::setProgress(const unsigned int &newProgress)
388 {
389         if(m_progress != newProgress)
390         {
391                 m_progress = newProgress;
392                 emit progressChanged(m_jobId, m_progress);
393         }
394 }
395
396 void EncodeThread::setDetails(const QString &text)
397 {
398         if((!text.isEmpty()) && (m_details.compare(text) != 0))
399         {
400                 emit detailsChanged(m_jobId, text);
401                 m_details = text;
402         }
403 }
404
405 QString EncodeThread::getPasslogFile(const QString &outputFile)
406 {
407         QFileInfo info(outputFile);
408         QString passLogFile = QString("%1/%2.stats").arg(info.absolutePath(), info.completeBaseName());
409         int counter = 1;
410
411         while(QFileInfo(passLogFile).exists())
412         {
413                 passLogFile = QString("%1/%2_%3.stats").arg(info.absolutePath(), info.completeBaseName(), QString::number(++counter));
414         }
415
416         return passLogFile;
417 }