OSDN Git Service

9e22be6bef6e52b04bcd6c1549fabac807f49984
[x264-launcher/x264-launcher.git] / src / encoder_x265.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2016 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_x265.h"
23
24 //Internal
25 #include "global.h"
26 #include "model_options.h"
27 #include "model_status.h"
28 #include "mediainfo.h"
29 #include "model_sysinfo.h"
30 #include "model_clipInfo.h"
31
32 //MUtils
33 #include <MUtils/Exception.h>
34
35 //Qt
36 #include <QStringList>
37 #include <QDir>
38 #include <QRegExp>
39 #include <QPair>
40
41 //x265 version info
42 static const unsigned int VERSION_X265_MINIMUM_VER = 20;
43 static const unsigned int VERSION_X265_MINIMUM_REV =  0;
44
45 // ------------------------------------------------------------
46 // Helper Macros
47 // ------------------------------------------------------------
48
49 #define X265_UPDATE_PROGRESS(X) do \
50 { \
51         bool ok[2] = { false, false }; \
52         unsigned int progressInt = (X)->cap(1).toUInt(&ok[0]); \
53         unsigned int progressFrc = (X)->cap(2).toUInt(&ok[1]); \
54         setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running)); \
55         if(ok[0] && ok[1]) \
56         { \
57                 const double progress = (double(progressInt) / 100.0) + (double(progressFrc) / 1000.0); \
58                 if(!qFuzzyCompare(progress, last_progress)) \
59                 { \
60                         setProgress(floor(progress * 100.0)); \
61                         size_estimate = qFuzzyIsNull(size_estimate) ? estimateSize(m_outputFile, progress) : ((0.667 * size_estimate) + (0.333 * estimateSize(m_outputFile, progress))); \
62                         last_progress = progress; \
63                 } \
64         } \
65         setDetails(tr("%1, est. file size %2").arg(line.mid(offset).trimmed(), sizeToString(qRound64(size_estimate)))); \
66 } \
67 while(0)
68
69 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
70 { \
71         if(ITER != LIST.end()) \
72         { \
73                 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
74                 { \
75                         log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
76                         ITER = LIST.erase(ITER); \
77                         if(ITER != LIST.end()) \
78                         { \
79                                 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
80                         } \
81                         FLAG = true; \
82                 } \
83         } \
84 } \
85 while(0)
86
87 // ------------------------------------------------------------
88 // Encoder Info
89 // ------------------------------------------------------------
90
91 class X265EncoderInfo : public AbstractEncoderInfo
92 {
93 public:
94         virtual QString getName(void) const
95         {
96                 return "x265 (HEVC/H.265)";
97         }
98
99         virtual QList<ArchId> getArchitectures(void) const
100         {
101                 return QList<ArchId>()
102                 << qMakePair(QString("32-Bit (x86)"), ARCH_TYPE_X86)
103                 << qMakePair(QString("64-Bit (x64)"), ARCH_TYPE_X64);
104         }
105
106         virtual QStringList getVariants(void) const
107         {
108                 return QStringList() << "8-Bit" << "10-Bit" << "12-Bit";
109         }
110         virtual QList<RCMode> getRCModes(void) const
111         {
112                 return QList<RCMode>()
113                 << qMakePair(QString("CRF"),    RC_TYPE_QUANTIZER)
114                 << qMakePair(QString("CQ"),     RC_TYPE_QUANTIZER)
115                 << qMakePair(QString("2-Pass"), RC_TYPE_MULTIPASS)
116                 << qMakePair(QString("ABR"),    RC_TYPE_RATE_KBPS);
117         }
118
119         virtual QStringList getTunings(void) const
120         {
121                 return QStringList() << "Grain" << "PSNR" << "SSIM" << "FastDecode" << "ZeroLatency";
122         }
123
124         virtual QStringList getPresets(void) const
125         {
126                 return QStringList()
127                 << "ultrafast" << "superfast" << "veryfast" << "faster"   << "fast"
128                 << "medium"    << "slow"      << "slower"   << "veryslow" << "placebo";
129         }
130
131         virtual QStringList getProfiles(const quint32 &variant) const
132         {
133                 QStringList profiles;
134                 switch(variant)
135                 {
136                         case 0: profiles << "main"   << "main-intra"   << "mainstillpicture" << "main444-8"        << "main444-intra" << "main444-stillpicture"; break;
137                         case 1: profiles << "main10" << "main10-intra" << "main422-10"       << "main422-10-intra" << "main444-10"    << "main444-10-intra";     break;
138                         case 2: profiles << "main12" << "main12-intra" << "main422-12"       << "main422-12-intra" << "main444-12"    << "main444-12-intra";     break;
139                         default: MUTILS_THROW("Unknown encoder variant!");
140                 }
141                 return profiles;
142         }
143
144         virtual QStringList supportedOutputFormats(void) const
145         {
146                 return QStringList() << "hevc";
147         }
148
149         virtual bool isInputTypeSupported(const int format) const
150         {
151                 switch(format)
152                 {
153                 case MediaInfo::FILETYPE_YUV4MPEG2:
154                         return true;
155                 default:
156                         return false;
157                 }
158         }
159
160         virtual QString getBinaryPath(const SysinfoModel *sysinfo, const quint32 &encArch, const quint32 &encVariant) const
161         {
162                 QString arch, variant;
163                 switch(encArch)
164                 {
165                         case 0: arch = "x86"; break;
166                         case 1: arch = "x64"; break;
167                         default: MUTILS_THROW("Unknown encoder arch!");
168                 }
169                 switch(encVariant)
170                 {
171                         case 0: variant =  "8bit"; break;
172                         case 1: variant = "10bit"; break;
173                         case 2: variant = "12bit"; break;
174                         default: MUTILS_THROW("Unknown encoder arch!");
175                 }
176                 return QString("%1/toolset/%2/x265_%3_%2.exe").arg(sysinfo->getAppPath(), arch, variant);
177         }
178
179         virtual QString getHelpCommand(void) const
180         {
181                 return "--fullhelp";
182         }
183 };
184
185 static const X265EncoderInfo s_x265EncoderInfo;
186
187 const AbstractEncoderInfo& X265Encoder::encoderInfo(void)
188 {
189         return s_x265EncoderInfo;
190 }
191
192 const AbstractEncoderInfo &X265Encoder::getEncoderInfo(void) const
193 {
194         return encoderInfo();
195 }
196
197 // ------------------------------------------------------------
198 // Constructor & Destructor
199 // ------------------------------------------------------------
200
201 X265Encoder::X265Encoder(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)
202 :
203         AbstractEncoder(jobObject, options, sysinfo, preferences, jobStatus, abort, pause, semaphorePause, sourceFile, outputFile)
204 {
205         if(options->encType() != OptionsModel::EncType_X265)
206         {
207                 MUTILS_THROW("Invalid encoder type!");
208         }
209 }
210
211 X265Encoder::~X265Encoder(void)
212 {
213         /*Nothing to do here*/
214 }
215
216 QString X265Encoder::getName(void) const
217 {
218         return s_x265EncoderInfo.getFullName(m_options->encArch(), m_options->encVariant());
219 }
220
221 // ------------------------------------------------------------
222 // Check Version
223 // ------------------------------------------------------------
224
225 void X265Encoder::checkVersion_init(QList<QRegExp*> &patterns, QStringList &cmdLine)
226 {
227         cmdLine << "--version";
228         patterns << new QRegExp("\\bHEVC\\s+encoder\\s+version\\s+(\\d)\\.(\\d+)\\+(\\d+)\\b", Qt::CaseInsensitive);
229         patterns << new QRegExp("\\bHEVC\\s+encoder\\s+version\\s+(\\d)\\.(\\d+)\\b", Qt::CaseInsensitive);
230 }
231
232 void X265Encoder::checkVersion_parseLine(const QString &line, QList<QRegExp*> &patterns, unsigned int &core, unsigned int &build, bool &modified)
233 {
234         int offset = -1;
235
236         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
237         {
238                 bool ok[3] = { false, false, false };
239                 unsigned int temp[3];
240                 temp[0] = patterns[0]->cap(1).toUInt(&ok[0]);
241                 temp[1] = patterns[0]->cap(2).toUInt(&ok[1]);
242                 temp[2] = patterns[0]->cap(3).toUInt(&ok[2]);
243                 if(ok[0] && ok[1])
244                 {
245                         core = (10 * temp[0]) + temp[1];
246                 }
247                 if(ok[2]) build = temp[2];
248         }
249         else if((offset = patterns[1]->lastIndexIn(line)) >= 0)
250         {
251                 bool ok[2] = { false, false };
252                 unsigned int temp[2];
253                 temp[0] = patterns[1]->cap(1).toUInt(&ok[0]);
254                 temp[1] = patterns[1]->cap(2).toUInt(&ok[1]);
255                 if(ok[0] && ok[1])
256                 {
257                         core = (10 * temp[0]) + temp[1];
258                 }
259                 build = 0;
260         }
261
262         if(!line.isEmpty())
263         {
264                 log(line);
265         }
266 }
267
268 QString X265Encoder::printVersion(const unsigned int &revision, const bool &modified)
269 {
270         unsigned int core, build;
271         splitRevision(revision, core, build);
272
273         return tr("x265 version: %1.%2+%3").arg(QString::number(core / 10), QString::number(core % 10), QString::number(build));
274 }
275
276 bool X265Encoder::isVersionSupported(const unsigned int &revision, const bool &modified)
277 {
278         unsigned int core, build;
279         splitRevision(revision, core, build);
280
281         if((core < VERSION_X265_MINIMUM_VER) || ((core == VERSION_X265_MINIMUM_VER) && (build < VERSION_X265_MINIMUM_REV)))
282         {
283                 log(tr("\nERROR: Your version of x265 is too old! (Minimum required revision is 0.%1+%2)").arg(QString::number(VERSION_X265_MINIMUM_VER), QString::number(VERSION_X265_MINIMUM_REV)));
284                 return false;
285         }
286         else if(core > VERSION_X265_MINIMUM_VER)
287         {
288                 log(tr("\nWARNING: Your version of x265 is newer than the latest tested version, take care!"));
289                 log(tr("This application works best with x265 version %1.%2. Newer versions may work or not.").arg(QString::number(VERSION_X265_MINIMUM_VER / 10), QString::number(VERSION_X265_MINIMUM_VER % 10)));
290         }
291         
292         return true;
293 }
294
295 // ------------------------------------------------------------
296 // Encoding Functions
297 // ------------------------------------------------------------
298
299 void X265Encoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, const ClipInfo &clipInfo, const QString &indexFile, const int &pass, const QString &passLogFile)
300 {
301         double crf_int = 0.0, crf_frc = 0.0;
302
303         switch(m_options->rcMode())
304         {
305         case 0:
306                 crf_frc = modf(m_options->quantizer(), &crf_int);
307                 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
308                 break;
309         case 1:
310                 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
311                 break;
312         case 2:
313         case 3:
314                 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
315                 break;
316         default:
317                 MUTILS_THROW("Bad rate-control mode !!!");
318                 break;
319         }
320         
321         if((pass == 1) || (pass == 2))
322         {
323                 cmdLine << "--pass" << QString::number(pass);
324                 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
325         }
326
327         const QString preset = m_options->preset().simplified().toLower();
328         if(!preset.isEmpty())
329         {
330                 if(preset.compare(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED), Qt::CaseInsensitive) != 0)
331                 {
332                         cmdLine << "--preset" << preset;
333                 }
334         }
335
336         const QString tune = m_options->tune().simplified().toLower();
337         if(!tune.isEmpty())
338         {
339                 if(tune.compare(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED), Qt::CaseInsensitive) != 0)
340                 {
341                         cmdLine << "--tune" << tune;
342                 }
343         }
344
345         const QString profile = m_options->profile().simplified().toLower();
346         if(!profile.isEmpty())
347         {
348                 if(profile.compare(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED), Qt::CaseInsensitive) != 0)
349                 {
350                         cmdLine << "--profile" << profile;
351                 }
352         }
353
354         if(!m_options->customEncParams().isEmpty())
355         {
356                 QStringList customArgs = splitParams(m_options->customEncParams(), m_sourceFile, m_outputFile);
357                 if(usePipe)
358                 {
359                         QStringList::iterator i = customArgs.begin();
360                         while(i != customArgs.end())
361                         {
362                                 bool bModified = false;
363                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
364                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
365                                 if(!bModified) i++;
366                         }
367                 }
368                 cmdLine.append(customArgs);
369         }
370
371         cmdLine << "--output" << QDir::toNativeSeparators(m_outputFile);
372         
373         if(usePipe)
374         {
375                 if (clipInfo.getFrameCount() < 1)
376                 {
377                         MUTILS_THROW("Frames not set!");
378                 }
379                 cmdLine << "--frames" << QString::number(clipInfo.getFrameCount());
380                 cmdLine << "--y4m" << "-";
381         }
382         else
383         {
384                 cmdLine << QDir::toNativeSeparators(m_sourceFile);
385         }
386 }
387
388 void X265Encoder::runEncodingPass_init(QList<QRegExp*> &patterns)
389 {
390         patterns << new QRegExp("\\[(\\d+)\\.(\\d+)%\\].+frames");   //regExpProgress
391         patterns << new QRegExp("indexing.+\\[(\\d+)\\.(\\d+)%\\]"); //regExpIndexing
392         patterns << new QRegExp("^(\\d+) frames:"); //regExpFrameCnt
393         patterns << new QRegExp("\\[\\s*(\\d+)\\.(\\d+)%\\]\\s+(\\d+)/(\\d+)\\s(\\d+).(\\d+)\\s(\\d+).(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)"); //regExpModified
394 }
395
396 void X265Encoder::runEncodingPass_parseLine(const QString &line, QList<QRegExp*> &patterns, const ClipInfo &clipInfo, const int &pass, double &last_progress, double &size_estimate)
397 {
398         int offset = -1;
399         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
400         {
401                 X265_UPDATE_PROGRESS(patterns[0]);
402         }
403         else if((offset = patterns[1]->lastIndexIn(line)) >= 0)
404         {
405                 bool ok = false;
406                 unsigned int progress = patterns[1]->cap(1).toUInt(&ok);
407                 setStatus(JobStatus_Indexing);
408                 if(ok)
409                 {
410                         setProgress(progress);
411                 }
412                 setDetails(line.mid(offset).trimmed());
413         }
414         else if((offset = patterns[2]->lastIndexIn(line)) >= 0)
415         {
416                 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
417                 setDetails(line.mid(offset).trimmed());
418         }
419         else if((offset = patterns[3]->lastIndexIn(line)) >= 0)
420         {
421                 X265_UPDATE_PROGRESS(patterns[3]);
422         }
423         else if(!line.isEmpty())
424         {
425                 log(line);
426         }
427 }