OSDN Git Service

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