OSDN Git Service

Do not close the application in shutdownComputer(), if hibernation was requested.
[x264-launcher/x264-launcher.git] / src / thread_encode.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2020 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 "model_clipInfo.h"
30 #include "job_object.h"
31 #include "mediainfo.h"
32
33 //Encoders
34 #include "encoder_factory.h"
35
36 //Source
37 #include "source_factory.h"
38
39 //MUtils
40 #include <MUtils/OSSupport.h>
41 #include <MUtils/Version.h>
42
43 //Qt Framework
44 #include <QDate>
45 #include <QTime>
46 #include <QDateTime>
47 #include <QFileInfo>
48 #include <QDir>
49 #include <QProcess>
50 #include <QMutex>
51 #include <QTextCodec>
52 #include <QLocale>
53 #include <QCryptographicHash>
54
55 /*
56  * RAII execution state handler
57  */
58 class ExecutionStateHandler
59 {
60 public:
61         ExecutionStateHandler(void)
62         {
63                 x264_set_thread_execution_state(true);
64         }
65         ~ExecutionStateHandler(void)
66         {
67                 x264_set_thread_execution_state(false);
68         }
69 private:
70         //Disable copy constructor and assignment
71         ExecutionStateHandler(const ExecutionStateHandler &other) {}
72         ExecutionStateHandler &operator=(const ExecutionStateHandler &) {}
73
74         //Prevent object allocation on the heap
75         void *operator new(size_t);   void *operator new[](size_t);
76         void operator delete(void *); void operator delete[](void*);
77 };
78
79 /*
80  * Macros
81  */
82 #define CHECK_STATUS(ABORT_FLAG, OK_FLAG) do \
83 { \
84         if(ABORT_FLAG) \
85         { \
86                 log("\nPROCESS ABORTED BY USER !!!"); \
87                 setStatus(JobStatus_Aborted); \
88                 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
89                 return 0; \
90         } \
91         else if(!(OK_FLAG)) \
92         { \
93                 setStatus(JobStatus_Failed); \
94                 if(QFileInfo(m_outputFileName).exists() && (QFileInfo(m_outputFileName).size() == 0)) QFile::remove(m_outputFileName); \
95                 return 0; \
96         } \
97 } \
98 while(0)
99
100 #define CONNECT(OBJ) do \
101 { \
102         if((OBJ)) \
103         { \
104                 connect((OBJ), SIGNAL(statusChanged(JobStatus)),      this, SLOT(setStatus(JobStatus)),      Qt::DirectConnection); \
105                 connect((OBJ), SIGNAL(progressChanged(unsigned int)), this, SLOT(setProgress(unsigned int)), Qt::DirectConnection); \
106                 connect((OBJ), SIGNAL(detailsChanged(QString)),       this, SLOT(setDetails(QString)),       Qt::DirectConnection); \
107                 connect((OBJ), SIGNAL(messageLogged(QString)),        this, SLOT(log(QString)),              Qt::DirectConnection); \
108         } \
109 } \
110 while(0)
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         m_encoder = EncoderFactory::createEncoder(m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName, m_outputFileName);
134
135         //Create input handler object
136         switch(MediaInfo::analyze(m_sourceFileName))
137         {
138         case MediaInfo::FILETYPE_AVISYNTH:
139                 if(m_sysinfo->hasAvisynth())
140                 {
141                         m_pipedSource = SourceFactory::createSource(SourceFactory::SourceType_AVS, m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
142                 }
143                 break;
144         case MediaInfo::FILETYPE_VAPOURSYNTH:
145                 if(m_sysinfo->hasVapourSynth())
146                 {
147                         m_pipedSource = SourceFactory::createSource(SourceFactory::SourceType_VPS, m_jobObject, m_options, m_sysinfo, m_preferences, m_status, &m_abort, &m_pause, &m_semaphorePaused, m_sourceFileName);
148                 }
149                 break;
150         }
151
152         //Establish connections
153         CONNECT(m_encoder);
154         CONNECT(m_pipedSource);
155 }
156
157 EncodeThread::~EncodeThread(void)
158 {
159         MUTILS_DELETE(m_encoder);
160         MUTILS_DELETE(m_jobObject);
161         MUTILS_DELETE(m_options);
162         MUTILS_DELETE(m_pipedSource);
163 }
164
165 ///////////////////////////////////////////////////////////////////////////////
166 // Thread entry point
167 ///////////////////////////////////////////////////////////////////////////////
168
169 void EncodeThread::run(void)
170 {
171         m_progress = 0;
172         m_status = JobStatus_Starting;
173
174         AbstractThread::run();
175
176         if (m_exception)
177         {
178                 log(tr("UNHANDLED EXCEPTION ERROR IN THREAD !!!"));
179                 setStatus(JobStatus_Failed);
180         }
181
182         if(m_jobObject)
183         {
184                 m_jobObject->terminateJob(42);
185                 MUTILS_DELETE(m_jobObject);
186         }
187 }
188
189 void EncodeThread::start(Priority priority)
190 {
191         qDebug("Thread starting...");
192
193         m_abort = false;
194         m_pause = false;
195
196         while(m_semaphorePaused.tryAcquire(1, 0));
197         AbstractThread::start(priority);
198 }
199
200 ///////////////////////////////////////////////////////////////////////////////
201 // Encode functions
202 ///////////////////////////////////////////////////////////////////////////////
203
204 int EncodeThread::threadMain(void)
205 {
206         QDateTime startTime = QDateTime::currentDateTime();
207
208         // -----------------------------------------------------------------------------------
209         // Print Information
210         // -----------------------------------------------------------------------------------
211
212         //Print some basic info
213         log(tr("Simple x264 Launcher (Build #%1), built %2\n").arg(QString::number(x264_version_build()), MUtils::Version::app_build_date().toString(Qt::ISODate)));
214         log(tr("Job started at %1, %2.\n").arg(QDate::currentDate().toString(Qt::ISODate), QTime::currentTime().toString( Qt::ISODate)));
215         log(tr("Source file : %1").arg(QDir::toNativeSeparators(m_sourceFileName)));
216         log(tr("Output file : %1").arg(QDir::toNativeSeparators(m_outputFileName)));
217         
218         //Print system info
219         log(tr("\n--- SYSTEMINFO ---\n"));
220         log(tr("Binary Path : %1").arg(QDir::toNativeSeparators(m_sysinfo->getAppPath())));
221         log(tr("Avisynth    : %1").arg(m_sysinfo->hasAvisynth() ? tr("Yes") : tr("No")));
222         log(tr("VapourSynth : %1").arg(m_sysinfo->hasVapourSynth() ? tr("Yes") : tr("No")));
223
224         //Print encoder settings
225         log(tr("\n--- SETTINGS ---\n"));
226         log(tr("Encoder : %1").arg(m_encoder->getName()));
227         log(tr("Source  : %1").arg(m_pipedSource ? m_pipedSource->getName() : tr("Native")));
228         log(tr("RC Mode : %1").arg(m_encoder->getEncoderInfo().rcModeToString(m_options->rcMode())));
229         log(tr("Preset  : %1").arg(m_options->preset()));
230         log(tr("Tuning  : %1").arg(m_options->tune()));
231         log(tr("Profile : %1").arg(m_options->profile()));
232         log(tr("Custom  : %1").arg(m_options->customEncParams().isEmpty() ? tr("<None>") : m_options->customEncParams()));
233         
234         bool ok = false;
235         ClipInfo clipInfo;
236         
237         // -----------------------------------------------------------------------------------
238         // Check Versions
239         // -----------------------------------------------------------------------------------
240         
241         log(tr("\n--- CHECK VERSION ---\n"));
242
243         unsigned int encoderRevision = UINT_MAX, sourceRevision = UINT_MAX;
244         bool encoderModified = false, sourceModified = false;
245
246         log("Detect video encoder version:\n");
247
248         //Check encoder version
249         encoderRevision = m_encoder->checkVersion(encoderModified);
250         CHECK_STATUS(m_abort, (ok = (encoderRevision != UINT_MAX)));
251
252         //Is encoder version suppoprted?
253         CHECK_STATUS(m_abort, (ok = m_encoder->isVersionSupported(encoderRevision, encoderModified)));
254
255         if(m_pipedSource)
256         {
257                 log("\nDetect video source version:\n");
258
259                 //Is source type available?
260                 CHECK_STATUS(m_abort, (ok = m_pipedSource->isSourceAvailable()));
261
262                 //Checking source version
263                 sourceRevision = m_pipedSource->checkVersion(sourceModified);
264                 CHECK_STATUS(m_abort, (ok = (sourceRevision != UINT_MAX)));
265
266                 //Is source version supported?
267                 CHECK_STATUS(m_abort, (ok = m_pipedSource->isVersionSupported(sourceRevision, sourceModified)));
268         }
269
270         //Print tool versions
271         log(QString("\n> %1").arg(m_encoder->printVersion(encoderRevision, encoderModified)));
272         if(m_pipedSource)
273         {
274                 log(QString("> %1").arg(m_pipedSource->printVersion(sourceRevision, sourceModified)));
275         }
276
277         // -----------------------------------------------------------------------------------
278         // Detect Source Info
279         // -----------------------------------------------------------------------------------
280
281         //Detect source info
282         if(m_pipedSource)
283         {
284                 log(tr("\n--- GET SOURCE INFO ---\n"));
285                 ok = m_pipedSource->checkSourceProperties(clipInfo);
286                 CHECK_STATUS(m_abort, ok);
287         }
288
289         // -----------------------------------------------------------------------------------
290         // Encoding Passes
291         // -----------------------------------------------------------------------------------
292
293         //Run encoding passes
294         if(m_encoder->getEncoderInfo().rcModeToType(m_options->rcMode()) == AbstractEncoderInfo::RC_TYPE_MULTIPASS)
295         {
296                 const QString passLogFile = getPasslogFile(m_outputFileName);
297                 
298                 log(tr("\n--- ENCODING PASS #1 ---\n"));
299                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo, 1, passLogFile);
300                 CHECK_STATUS(m_abort, ok);
301
302                 log(tr("\n--- ENCODING PASS #2 ---\n"));
303                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo, 2, passLogFile);
304                 CHECK_STATUS(m_abort, ok);
305         }
306         else
307         {
308                 log(tr("\n--- ENCODING VIDEO ---\n"));
309                 ok = m_encoder->runEncodingPass(m_pipedSource, m_outputFileName, clipInfo);
310                 CHECK_STATUS(m_abort, ok);
311         }
312
313         // -----------------------------------------------------------------------------------
314         // Encoding complete
315         // -----------------------------------------------------------------------------------
316
317         log(tr("\n--- COMPLETED ---\n"));
318
319         int timePassed = startTime.secsTo(QDateTime::currentDateTime());
320         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)));
321         setStatus(JobStatus_Completed);
322
323         return 1; /*completed*/
324 }
325
326 ///////////////////////////////////////////////////////////////////////////////
327 // Misc functions
328 ///////////////////////////////////////////////////////////////////////////////
329
330 void EncodeThread::log(const QString &text)
331 {
332         emit messageLogged(m_jobId, QDateTime::currentMSecsSinceEpoch(), text);
333 }
334
335 void EncodeThread::setStatus(const JobStatus &newStatus)
336 {
337         if(m_status != newStatus)
338         {
339                 if((newStatus != JobStatus_Completed) && (newStatus != JobStatus_Failed) && (newStatus != JobStatus_Aborted) && (newStatus != JobStatus_Paused))
340                 {
341                         if(m_status != JobStatus_Paused) setProgress(0);
342                 }
343                 if(newStatus == JobStatus_Failed)
344                 {
345                         setDetails("The job has failed. See log for details!");
346                 }
347                 if(newStatus == JobStatus_Aborted)
348                 {
349                         setDetails("The job was aborted by the user!");
350                 }
351                 m_status = newStatus;
352                 emit statusChanged(m_jobId, newStatus);
353         }
354 }
355
356 void EncodeThread::setProgress(const unsigned int &newProgress)
357 {
358         if(m_progress != newProgress)
359         {
360                 m_progress = newProgress;
361                 emit progressChanged(m_jobId, m_progress);
362         }
363 }
364
365 void EncodeThread::setDetails(const QString &text)
366 {
367         if((!text.isEmpty()) && (m_details.compare(text) != 0))
368         {
369                 emit detailsChanged(m_jobId, text);
370                 m_details = text;
371         }
372 }
373
374 QString EncodeThread::getPasslogFile(const QString &outputFile)
375 {
376         QFileInfo info(outputFile);
377         QString passLogFile = QString("%1/%2.stats").arg(info.absolutePath(), info.completeBaseName());
378         int counter = 1;
379
380         while(QFileInfo(passLogFile).exists())
381         {
382                 passLogFile = QString("%1/%2_%3.stats").arg(info.absolutePath(), info.completeBaseName(), QString::number(++counter));
383         }
384
385         return passLogFile;
386 }