OSDN Git Service

Implemented ClipInfo class + various fixes.
[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 =  19;
43 static const unsigned int VERSION_X265_MINIMUM_REV = 140;
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
180 static const X265EncoderInfo s_x265EncoderInfo;
181
182 const AbstractEncoderInfo& X265Encoder::encoderInfo(void)
183 {
184         return s_x265EncoderInfo;
185 }
186
187 const AbstractEncoderInfo &X265Encoder::getEncoderInfo(void) const
188 {
189         return encoderInfo();
190 }
191
192 // ------------------------------------------------------------
193 // Constructor & Destructor
194 // ------------------------------------------------------------
195
196 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)
197 :
198         AbstractEncoder(jobObject, options, sysinfo, preferences, jobStatus, abort, pause, semaphorePause, sourceFile, outputFile)
199 {
200         if(options->encType() != OptionsModel::EncType_X265)
201         {
202                 MUTILS_THROW("Invalid encoder type!");
203         }
204 }
205
206 X265Encoder::~X265Encoder(void)
207 {
208         /*Nothing to do here*/
209 }
210
211 QString X265Encoder::getName(void) const
212 {
213         return s_x265EncoderInfo.getFullName(m_options->encArch(), m_options->encVariant());
214 }
215
216 // ------------------------------------------------------------
217 // Check Version
218 // ------------------------------------------------------------
219
220 void X265Encoder::checkVersion_init(QList<QRegExp*> &patterns, QStringList &cmdLine)
221 {
222         cmdLine << "--version";
223         patterns << new QRegExp("\\bHEVC\\s+encoder\\s+version\\s+(\\d)\\.(\\d+)\\+(\\d+)\\b", Qt::CaseInsensitive);
224         patterns << new QRegExp("\\bHEVC\\s+encoder\\s+version\\s+(\\d)\\.(\\d+)\\b", Qt::CaseInsensitive);
225 }
226
227 void X265Encoder::checkVersion_parseLine(const QString &line, QList<QRegExp*> &patterns, unsigned int &core, unsigned int &build, bool &modified)
228 {
229         int offset = -1;
230
231         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
232         {
233                 bool ok[3] = { false, false, false };
234                 unsigned int temp[3];
235                 temp[0] = patterns[0]->cap(1).toUInt(&ok[0]);
236                 temp[1] = patterns[0]->cap(2).toUInt(&ok[1]);
237                 temp[2] = patterns[0]->cap(3).toUInt(&ok[2]);
238                 if(ok[0] && ok[1])
239                 {
240                         core = (10 * temp[0]) + temp[1];
241                 }
242                 if(ok[2]) build = temp[2];
243         }
244         else if((offset = patterns[1]->lastIndexIn(line)) >= 0)
245         {
246                 bool ok[2] = { false, false };
247                 unsigned int temp[2];
248                 temp[0] = patterns[1]->cap(1).toUInt(&ok[0]);
249                 temp[1] = patterns[1]->cap(2).toUInt(&ok[1]);
250                 if(ok[0] && ok[1])
251                 {
252                         core = (10 * temp[0]) + temp[1];
253                 }
254                 build = 0;
255         }
256
257         if(!line.isEmpty())
258         {
259                 log(line);
260         }
261 }
262
263 QString X265Encoder::printVersion(const unsigned int &revision, const bool &modified)
264 {
265         unsigned int core, build;
266         splitRevision(revision, core, build);
267
268         return tr("x265 version: %1.%2+%3").arg(QString::number(core / 10), QString::number(core % 10), QString::number(build));
269 }
270
271 bool X265Encoder::isVersionSupported(const unsigned int &revision, const bool &modified)
272 {
273         unsigned int core, build;
274         splitRevision(revision, core, build);
275
276         if((core < VERSION_X265_MINIMUM_VER) || ((core == VERSION_X265_MINIMUM_VER) && (build < VERSION_X265_MINIMUM_REV)))
277         {
278                 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)));
279                 return false;
280         }
281         else if(core > VERSION_X265_MINIMUM_VER)
282         {
283                 log(tr("\nWARNING: Your version of x265 is newer than the latest tested version, take care!"));
284                 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)));
285         }
286         
287         return true;
288 }
289
290 // ------------------------------------------------------------
291 // Encoding Functions
292 // ------------------------------------------------------------
293
294 void X265Encoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, const ClipInfo &clipInfo, const QString &indexFile, const int &pass, const QString &passLogFile)
295 {
296         double crf_int = 0.0, crf_frc = 0.0;
297
298         switch(m_options->rcMode())
299         {
300         case 0:
301                 cmdLine << "--qp" << QString::number(qRound(m_options->quantizer()));
302                 break;
303         case 1:
304                 crf_frc = modf(m_options->quantizer(), &crf_int);
305                 cmdLine << "--crf" << QString("%1.%2").arg(QString::number(qRound(crf_int)), QString::number(qRound(crf_frc * 10.0)));
306                 break;
307         case 2:
308         case 3:
309                 cmdLine << "--bitrate" << QString::number(m_options->bitrate());
310                 break;
311         default:
312                 MUTILS_THROW("Bad rate-control mode !!!");
313                 break;
314         }
315         
316         if((pass == 1) || (pass == 2))
317         {
318                 cmdLine << "--pass" << QString::number(pass);
319                 cmdLine << "--stats" << QDir::toNativeSeparators(passLogFile);
320         }
321
322         const QString preset = m_options->preset().simplified().toLower();
323         if(!preset.isEmpty())
324         {
325                 if(preset.compare(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED), Qt::CaseInsensitive) != 0)
326                 {
327                         cmdLine << "--preset" << preset;
328                 }
329         }
330
331         const QString tune = m_options->tune().simplified().toLower();
332         if(!tune.isEmpty())
333         {
334                 if(tune.compare(QString::fromLatin1(OptionsModel::SETTING_UNSPECIFIED), Qt::CaseInsensitive) != 0)
335                 {
336                         cmdLine << "--tune" << tune;
337                 }
338         }
339
340         const QString profile = m_options->profile().simplified().toLower();
341         if(!profile.isEmpty())
342         {
343                 if(profile.compare(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED), Qt::CaseInsensitive) != 0)
344                 {
345                         cmdLine << "--profile" << profile;
346                 }
347         }
348
349         if(!m_options->customEncParams().isEmpty())
350         {
351                 QStringList customArgs = splitParams(m_options->customEncParams(), m_sourceFile, m_outputFile);
352                 if(usePipe)
353                 {
354                         QStringList::iterator i = customArgs.begin();
355                         while(i != customArgs.end())
356                         {
357                                 bool bModified = false;
358                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
359                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
360                                 if(!bModified) i++;
361                         }
362                 }
363                 cmdLine.append(customArgs);
364         }
365
366         cmdLine << "--output" << QDir::toNativeSeparators(m_outputFile);
367         
368         if(usePipe)
369         {
370                 if (clipInfo.getFrameCount() < 1)
371                 {
372                         MUTILS_THROW("Frames not set!");
373                 }
374                 cmdLine << "--frames" << QString::number(clipInfo.getFrameCount());
375                 cmdLine << "--y4m" << "-";
376         }
377         else
378         {
379                 cmdLine << QDir::toNativeSeparators(m_sourceFile);
380         }
381 }
382
383 void X265Encoder::runEncodingPass_init(QList<QRegExp*> &patterns)
384 {
385         patterns << new QRegExp("\\[(\\d+)\\.(\\d+)%\\].+frames");   //regExpProgress
386         patterns << new QRegExp("indexing.+\\[(\\d+)\\.(\\d+)%\\]"); //regExpIndexing
387         patterns << new QRegExp("^(\\d+) frames:"); //regExpFrameCnt
388         patterns << new QRegExp("\\[\\s*(\\d+)\\.(\\d+)%\\]\\s+(\\d+)/(\\d+)\\s(\\d+).(\\d+)\\s(\\d+).(\\d+)\\s+(\\d+):(\\d+):(\\d+)\\s+(\\d+):(\\d+):(\\d+)"); //regExpModified
389 }
390
391 void X265Encoder::runEncodingPass_parseLine(const QString &line, QList<QRegExp*> &patterns, const ClipInfo &clipInfo, const int &pass, double &last_progress, double &size_estimate)
392 {
393         int offset = -1;
394         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
395         {
396                 X265_UPDATE_PROGRESS(patterns[0]);
397         }
398         else if((offset = patterns[1]->lastIndexIn(line)) >= 0)
399         {
400                 bool ok = false;
401                 unsigned int progress = patterns[1]->cap(1).toUInt(&ok);
402                 setStatus(JobStatus_Indexing);
403                 if(ok)
404                 {
405                         setProgress(progress);
406                 }
407                 setDetails(line.mid(offset).trimmed());
408         }
409         else if((offset = patterns[2]->lastIndexIn(line)) >= 0)
410         {
411                 setStatus((pass == 2) ? JobStatus_Running_Pass2 : ((pass == 1) ? JobStatus_Running_Pass1 : JobStatus_Running));
412                 setDetails(line.mid(offset).trimmed());
413         }
414         else if((offset = patterns[3]->lastIndexIn(line)) >= 0)
415         {
416                 X265_UPDATE_PROGRESS(patterns[3]);
417         }
418         else if(!line.isEmpty())
419         {
420                 log(line);
421         }
422 }