OSDN Git Service

Happy new year 2015 !!!
[x264-launcher/x264-launcher.git] / src / encoder_x264.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 "encoder_x264.h"
23
24 #include "global.h"
25 #include "model_options.h"
26 #include "model_status.h"
27 #include "binaries.h"
28 #include "mediainfo.h"
29
30 #include <QStringList>
31 #include <QDir>
32 #include <QRegExp>
33
34 //x264 version info
35 static const unsigned int VERSION_X264_MINIMUM_REV = 2495;
36 static const unsigned int VERSION_X264_CURRENT_API = 144;
37
38 // ------------------------------------------------------------
39 // Helper Macros
40 // ------------------------------------------------------------
41
42 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
43 { \
44         if(ITER != LIST.end()) \
45         { \
46                 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
47                 { \
48                         log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
49                         ITER = LIST.erase(ITER); \
50                         if(ITER != LIST.end()) \
51                         { \
52                                 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
53                         } \
54                         FLAG = true; \
55                 } \
56         } \
57 } \
58 while(0)
59
60 #define X264_UPDATE_PROGRESS(X) do \
61 { \
62         bool ok[2] = { false, false }; \
63         unsigned int progressInt = (X)->cap(1).toUInt(&ok[0]); \
64         unsigned int progressFrc = (X)->cap(2).toUInt(&ok[1]); \
65         setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running)); \
66         if(ok[0] && ok[1]) \
67         { \
68                 const double progress = (double(progressInt) / 100.0) + (double(progressFrc) / 1000.0); \
69                 if(!qFuzzyCompare(progress, last_progress)) \
70                 { \
71                         setProgress(floor(progress * 100.0)); \
72                         size_estimate = qFuzzyIsNull(size_estimate) ? estimateSize(m_outputFile, progress) : ((0.667 * size_estimate) + (0.333 * estimateSize(m_outputFile, progress))); \
73                         last_progress = progress; \
74                 } \
75         } \
76         setDetails(tr("%1, est. file size %2").arg(line.mid(offset).trimmed(), sizeToString(qRound64(size_estimate)))); \
77 } \
78 while(0)
79
80 static QString MAKE_NAME(const char *baseName, const OptionsModel *options)
81 {
82         const QString arch = (options->encArch() == OptionsModel::EncArch_x64) ? "x64" : "x86";
83         const QString vari = (options->encVariant() == OptionsModel::EncVariant_HiBit ) ? "10-Bit" : "8-Bit";
84         return QString("%1, %2, %3").arg(QString::fromLatin1(baseName), arch, vari);
85 }
86
87 // ------------------------------------------------------------
88 // Encoder Info
89 // ------------------------------------------------------------
90
91 class X264EncoderInfo : public AbstractEncoderInfo
92 {
93 public:
94         virtual QString getVariantId(const int &variant) const
95         {
96                 switch(variant)
97                 {
98                 case OptionsModel::EncVariant_LoBit:
99                         return QString::fromLatin1("8-Bit");
100                 case OptionsModel::EncVariant_HiBit:
101                         return QString::fromLatin1("10-Bit");
102                 default:
103                         return QString::fromLatin1("N/A");
104                 }
105         }
106
107         virtual QStringList getTunings(void) const
108         {
109                 QStringList tunings;
110
111                 tunings << "Film"       << "Animation"   << "Grain";
112                 tunings << "StillImage" << "PSNR"        << "SSIM";
113                 tunings << "FastDecode" << "ZeroLatency" << "Touhou";
114                 
115                 return tunings;
116         }
117
118         virtual QStringList getProfiles(const int &variant) const
119         {
120                 QStringList profiles;
121
122                 if(variant == OptionsModel::EncVariant_LoBit)
123                 {
124                         profiles << "Baseline" << "Main" << "High";
125                 }
126                 if((variant == OptionsModel::EncVariant_LoBit) || (variant == OptionsModel::EncVariant_HiBit))
127                 {
128                         profiles << "High10" << "High422" << "High444";
129                 }
130
131                 return profiles;
132         }
133
134         virtual QStringList supportedOutputFormats(void) const
135         {
136                 QStringList extLst;
137                 extLst << "264" << "mkv" << "mp4";
138                 return extLst;
139         }
140
141         virtual bool isRCModeSupported(const int rcMode) const
142         {
143                 switch(rcMode)
144                 {
145                 case OptionsModel::RCMode_CRF:
146                 case OptionsModel::RCMode_CQ:
147                 case OptionsModel::RCMode_2Pass:
148                 case OptionsModel::RCMode_ABR:
149                         return true;
150                 default:
151                         return false;
152                 }
153         }
154
155         virtual bool isInputTypeSupported(const int format) const
156         {
157                 switch(format)
158                 {
159                 case MediaInfo::FILETYPE_AVISYNTH:
160                 case MediaInfo::FILETYPE_YUV4MPEG2:
161                 case MediaInfo::FILETYPE_UNKNOWN:
162                         return true;
163                 default:
164                         return false;
165                 }
166         }
167 };
168
169 static const X264EncoderInfo s_x264EncoderInfo;
170
171 const AbstractEncoderInfo &X264Encoder::getEncoderInfo(void)
172 {
173         return s_x264EncoderInfo;
174 }
175
176 // ------------------------------------------------------------
177 // Constructor & Destructor
178 // ------------------------------------------------------------
179
180 X264Encoder::X264Encoder(JobObject *jobObject, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences, JobStatus &jobStatus, volatile bool *abort, volatile bool *pause, QSemaphore *semaphorePause, const QString &sourceFile, const QString &outputFile)
181 :
182         AbstractEncoder(jobObject, options, sysinfo, preferences, jobStatus, abort, pause, semaphorePause, sourceFile, outputFile),
183         m_encoderName(MAKE_NAME("x264 (H.264/AVC)", m_options)),
184         m_binaryFile(ENC_BINARY(sysinfo, options))
185 {
186         if(options->encType() != OptionsModel::EncType_X264)
187         {
188                 THROW("Invalid encoder type!");
189         }
190 }
191
192 X264Encoder::~X264Encoder(void)
193 {
194         /*Nothing to do here*/
195 }
196
197 const QString &X264Encoder::getName(void)
198 {
199         return m_encoderName;
200 }
201
202 // ------------------------------------------------------------
203 // Check Version
204 // ------------------------------------------------------------
205
206 void X264Encoder::checkVersion_init(QList<QRegExp*> &patterns, QStringList &cmdLine)
207 {
208         cmdLine << "--version";
209         patterns << new QRegExp("\\bx264\\s+(\\d)\\.(\\d+)\\.(\\d+)\\s+([a-f0-9]{7})", Qt::CaseInsensitive);
210         patterns << new QRegExp("\\bx264\\s+(\\d)\\.(\\d+)\\.(\\d+)", Qt::CaseInsensitive);
211 }
212
213 void X264Encoder::checkVersion_parseLine(const QString &line, QList<QRegExp*> &patterns, unsigned int &core, unsigned int &build, bool &modified)
214 {
215         int offset = -1;
216
217         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
218         {
219                 bool ok1 = false, ok2 = false;
220                 unsigned int temp1 = patterns[0]->cap(2).toUInt(&ok1);
221                 unsigned int temp2 = patterns[0]->cap(3).toUInt(&ok2);
222                 if(ok1 && ok2 && (temp1 > 0) && (temp2 > 0))
223                 {
224                         core  = temp1;
225                         build = temp2;
226                 }
227         }
228         else if((offset = patterns[1]->lastIndexIn(line)) >= 0)
229         {
230                 bool ok1 = false, ok2 = false;
231                 unsigned int temp1 = patterns[1]->cap(2).toUInt(&ok1);
232                 unsigned int temp2 = patterns[1]->cap(3).toUInt(&ok2);
233                 if(ok1 && ok2 && (temp1 > 0) && (temp2 > 0))
234                 {
235                         core  = temp1;
236                         build = temp2;
237                 }
238                 modified = true;
239         }
240
241         if(!line.isEmpty())
242         {
243                 log(line);
244         }
245 }
246
247 QString X264Encoder::printVersion(const unsigned int &revision, const bool &modified)
248 {
249         unsigned int core, build;
250         splitRevision(revision, core, build);
251
252         QString versionStr = tr("x264 revision: %1 (core #%2)").arg(QString::number(build), QString::number(core));
253         if(modified)
254         {
255                 versionStr.append(tr(" - with custom patches!"));
256         }
257
258         return versionStr;
259 }
260
261 bool X264Encoder::isVersionSupported(const unsigned int &revision, const bool &modified)
262 {
263         unsigned int core, build;
264         splitRevision(revision, core, build);
265
266         if(build < VERSION_X264_MINIMUM_REV)
267         {
268                 log(tr("\nERROR: Your revision of x264 is too old! Minimum required revision is %1.").arg(QString::number(VERSION_X264_MINIMUM_REV)));
269                 return false;
270         }
271         
272         if(core != VERSION_X264_CURRENT_API)
273         {
274                 log(tr("\nWARNING: Your x264 binary uses an untested core (API) version, take care!"));
275                 log(tr("This application works best with x264 core (API) version %1. Newer versions may work or not.").arg(QString::number(VERSION_X264_CURRENT_API)));
276         }
277
278         return true;
279 }
280
281 // ------------------------------------------------------------
282 // Encoding Functions
283 // ------------------------------------------------------------
284
285 void X264Encoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, const unsigned int &frames, const QString &indexFile, const int &pass, const QString &passLogFile)
286 {
287         double crf_int = 0.0, crf_frc = 0.0;
288
289         switch(m_options->rcMode())
290         {
291         case OptionsModel::RCMode_CQ:
292                 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
293                 break;
294         case OptionsModel::RCMode_CRF:
295                 crf_frc = modf(m_options->quantizer(), &crf_int);
296                 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
297                 break;
298         case OptionsModel::RCMode_2Pass:
299         case OptionsModel::RCMode_ABR:
300                 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
301                 break;
302         default:
303                 THROW("Bad rate-control mode !!!");
304         }
305         
306         if((pass == 1) || (pass == 2))
307         {
308                 cmdLine << "--pass" << QString::number(pass);
309                 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
310         }
311
312         cmdLine << "--preset" << m_options->preset().toLower();
313
314         if(!m_options->tune().simplified().isEmpty())
315         {
316                 if(m_options->tune().simplified().compare(QString::fromLatin1(OptionsModel::TUNING_UNSPECIFIED), Qt::CaseInsensitive) != 0)
317                 {
318                         cmdLine << "--tune" << m_options->tune().simplified().toLower();
319                 }
320         }
321
322         if(!m_options->profile().simplified().isEmpty())
323         {
324                 if(m_options->profile().simplified().compare(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED), Qt::CaseInsensitive) != 0)
325                 {
326                         cmdLine << "--profile" << m_options->profile().simplified().toLower();
327                 }
328         }
329
330         if(!m_options->customEncParams().isEmpty())
331         {
332                 QStringList customArgs = splitParams(m_options->customEncParams(), m_sourceFile, m_outputFile);
333                 if(usePipe)
334                 {
335                         QStringList::iterator i = customArgs.begin();
336                         while(i != customArgs.end())
337                         {
338                                 bool bModified = false;
339                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
340                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
341                                 if(!bModified) i++;
342                         }
343                 }
344                 cmdLine.append(customArgs);
345         }
346
347         cmdLine << "--output" << QDir::toNativeSeparators(m_outputFile);
348         
349         if(usePipe)
350         {
351                 if(frames < 1) THROW("Frames not set!");
352                 cmdLine << "--frames" << QString::number(frames);
353                 cmdLine << "--demuxer" << "y4m";
354                 cmdLine << "--stdin" << "y4m" << "-";
355         }
356         else
357         {
358                 cmdLine << "--index" << QDir::toNativeSeparators(indexFile);
359                 cmdLine << QDir::toNativeSeparators(m_sourceFile);
360         }
361 }
362
363 void X264Encoder::runEncodingPass_init(QList<QRegExp*> &patterns)
364 {
365         patterns << new QRegExp("\\[(\\d+)\\.(\\d+)%\\].+frames");
366         patterns << new QRegExp("indexing.+\\[(\\d+)\\.(\\d+)%\\]");
367         patterns << new QRegExp("^(\\d+) frames:");
368         patterns << new QRegExp("\\[\\s*(\\d+)\\.(\\d+)%\\]\\s+(\\d+)/(\\d+)\\s(\\d+).(\\d+)\\s(\\d+).(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)"); //regExpModified
369 }
370
371 void X264Encoder::runEncodingPass_parseLine(const QString &line, QList<QRegExp*> &patterns, const int &pass, double &last_progress, double &size_estimate)
372 {
373         int offset = -1;
374         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
375         {
376                 X264_UPDATE_PROGRESS(patterns[0]);
377         }
378         else if((offset = patterns[1]->lastIndexIn(line)) >= 0)
379         {
380                 bool ok = false;
381                 unsigned int progress = patterns[1]->cap(1).toUInt(&ok);
382                 setStatus(JobStatus_Indexing);
383                 if(ok)
384                 {
385                         setProgress(progress);
386                 }
387                 setDetails(line.mid(offset).trimmed());
388         }
389         else if((offset = patterns[2]->lastIndexIn(line)) >= 0)
390         {
391                 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
392                 setDetails(line.mid(offset).trimmed());
393         }
394         else if((offset = patterns[3]->lastIndexIn(line)) >= 0)
395         {
396                 X264_UPDATE_PROGRESS(patterns[3]);
397         }
398         else if(!line.isEmpty())
399         {
400                 log(line);
401         }
402 }