OSDN Git Service

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