OSDN Git Service

Added preliminary NVEncC encoding support.
[x264-launcher/x264-launcher.git] / src / encoder_nvenc.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_nvenc.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
31 //MUtils
32 #include <MUtils/Exception.h>
33
34 //Qt
35 #include <QStringList>
36 #include <QDir>
37 #include <QRegExp>
38
39 //x265 version info
40 static const unsigned int VERSION_NVENCC_MINIMUM_VER = 206;
41 static const unsigned int VERSION_NVENCC_MINIMUM_API =  60;
42
43 // ------------------------------------------------------------
44 // Helper Macros
45 // ------------------------------------------------------------
46
47 #define NVENCC_UPDATE_PROGRESS(X) do \
48 { \
49         bool ok = false; \
50         unsigned int progressFrames = (X)->cap(1).toUInt(&ok); \
51         setStatus(JobStatus_Running); \
52         if(ok && (totalFrames > 0) && (totalFrames != UINT_MAX)) \
53         { \
54                 const double progress = (double(progressFrames) / double(totalFrames)); \
55                 if(!qFuzzyCompare(progress, last_progress)) \
56                 { \
57                         setProgress(floor(progress * 100.0)); \
58                         size_estimate = qFuzzyIsNull(size_estimate) ? estimateSize(m_outputFile, progress) : ((0.667 * size_estimate) + (0.333 * estimateSize(m_outputFile, progress))); \
59                         last_progress = progress; \
60                 } \
61         } \
62         setDetails(tr("%1, est. file size %2").arg(line.mid(offset).trimmed(), sizeToString(qRound64(size_estimate)))); \
63 } \
64 while(0)
65
66 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
67 { \
68         if(ITER != LIST.end()) \
69         { \
70                 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
71                 { \
72                         log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
73                         ITER = LIST.erase(ITER); \
74                         if(ITER != LIST.end()) \
75                         { \
76                                 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
77                         } \
78                         FLAG = true; \
79                 } \
80         } \
81 } \
82 while(0)
83
84 // ------------------------------------------------------------
85 // Encoder Info
86 // ------------------------------------------------------------
87
88 class NVEncEncoderInfo : public AbstractEncoderInfo
89 {
90 public:
91         virtual QFlags<OptionsModel::EncVariant> getVariants(void) const
92         {
93                 QFlags<OptionsModel::EncVariant> variants;
94                 variants |= OptionsModel::EncVariant_8Bit;
95                 return variants;
96         }
97
98         virtual QStringList getTunings(void) const
99         {
100                 return QStringList();
101         }
102
103         virtual QStringList getPresets(void) const
104         {
105                 return QStringList();
106         }
107
108         virtual QStringList getProfiles(const OptionsModel::EncVariant &variant) const
109         {
110                 QStringList profiles;
111                 switch(variant)
112                 {
113                 case OptionsModel::EncVariant_8Bit:
114                         profiles << "baseline" << "main" << "high";
115                         break;
116                 }
117                 return profiles;
118         }
119
120         virtual QStringList supportedOutputFormats(void) const
121         {
122                 QStringList extLst;
123                 extLst << "mp4";
124                 return extLst;
125         }
126
127         virtual bool isRCModeSupported(const OptionsModel::RCMode &rcMode) const
128         {
129                 switch(rcMode)
130                 {
131                 case OptionsModel::RCMode_CQ:
132                 case OptionsModel::RCMode_ABR:
133                         return true;
134                 default:
135                         return false;
136                 }
137         }
138
139         virtual bool isInputTypeSupported(const int format) const
140         {
141                 switch(format)
142                 {
143                 case MediaInfo::FILETYPE_YUV4MPEG2:
144                         return true;
145                 default:
146                         return false;
147                 }
148         }
149
150         virtual QString getBinaryPath(const SysinfoModel *sysinfo, const OptionsModel::EncArch &encArch, const OptionsModel::EncVariant &encVariant) const
151         {
152                 QString arch, variant;
153                 switch(encArch)
154                 {
155                         case OptionsModel::EncArch_x86_32: arch = "x86"; break;
156                         case OptionsModel::EncArch_x86_64: arch = "x64"; break;
157                         default: MUTILS_THROW("Unknown encoder arch!");
158                 }
159                 switch(encVariant)
160                 {
161                         case OptionsModel::EncVariant_8Bit:  variant = "8bit";  break;
162                         default: MUTILS_THROW("Unknown encoder arch!");
163                 }
164                 return QString("%1/toolset/%2/nvencc_%2.exe").arg(sysinfo->getAppPath(), arch);
165         }
166
167         virtual QStringList getDependencies(const SysinfoModel *sysinfo, const OptionsModel::EncArch &encArch, const OptionsModel::EncVariant &encVariant) const
168         {
169                 QString arch, variant;
170                 switch (encArch)
171                 {
172                         case OptionsModel::EncArch_x86_32: arch = "x86"; break;
173                         case OptionsModel::EncArch_x86_64: arch = "x64"; break;
174                         default: MUTILS_THROW("Unknown encoder arch!");
175                 }
176                 switch (encVariant)
177                 {
178                         case OptionsModel::EncVariant_8Bit:  variant = "8bit";  break;
179                         default: MUTILS_THROW("Unknown encoder arch!");
180                 }
181                 QStringList dependencies;
182                 dependencies << QString("%1/toolset/%2/avcodec-57.dll"  ).arg(sysinfo->getAppPath(), arch);
183                 dependencies << QString("%1/toolset/%2/avfilter-6.dll"  ).arg(sysinfo->getAppPath(), arch);
184                 dependencies << QString("%1/toolset/%2/avformat-57.dll" ).arg(sysinfo->getAppPath(), arch);
185                 dependencies << QString("%1/toolset/%2/avutil-55.dll"   ).arg(sysinfo->getAppPath(), arch);
186                 dependencies << QString("%1/toolset/%2/swresample-2.dll").arg(sysinfo->getAppPath(), arch);
187                 return dependencies;
188         }
189 };
190
191 static const NVEncEncoderInfo s_x265EncoderInfo;
192
193 const AbstractEncoderInfo &NVEncEncoder::getEncoderInfo(void)
194 {
195         return s_x265EncoderInfo;
196 }
197
198 // ------------------------------------------------------------
199 // Constructor & Destructor
200 // ------------------------------------------------------------
201
202 NVEncEncoder::NVEncEncoder(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_NVEnc)
207         {
208                 MUTILS_THROW("Invalid encoder type!");
209         }
210 }
211
212 NVEncEncoder::~NVEncEncoder(void)
213 {
214         /*Nothing to do here*/
215 }
216
217 QString NVEncEncoder::getName(void) const
218 {
219         QString arch, variant;
220         switch(m_options->encArch())
221         {
222                 case OptionsModel::EncArch_x86_32: arch = "x86"; break;
223                 case OptionsModel::EncArch_x86_64: arch = "x64"; break;
224                 default: MUTILS_THROW("Unknown encoder arch!");
225         }
226         switch(m_options->encVariant())
227         {
228                 case OptionsModel::EncVariant_8Bit:  variant = "8-Bit";  break;
229                 default: MUTILS_THROW("Unknown encoder arch!");
230         }
231         return QString("NVEncC, %1, %2").arg(arch, variant);
232 }
233
234 // ------------------------------------------------------------
235 // Check Version
236 // ------------------------------------------------------------
237
238 void NVEncEncoder::checkVersion_init(QList<QRegExp*> &patterns, QStringList &cmdLine)
239 {
240         cmdLine << "--version";
241         patterns << new QRegExp("\\bNVEncC\\s+\\(\\w+\\)\\s+(\\d)\\.(\\d+)\\s+by\\s+rigaya\\s+\\[NVENC\\s+API\\s+v(\\d+)\\.(\\d+)\\]", Qt::CaseInsensitive);
242 }
243
244 void NVEncEncoder::checkVersion_parseLine(const QString &line, QList<QRegExp*> &patterns, unsigned int &core, unsigned int &build, bool &modified)
245 {
246         int offset = -1;
247
248         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
249         {
250                 bool ok[4] = { false, false, false, false };
251                 unsigned int temp[4];
252                 temp[0] = patterns[0]->cap(1).toUInt(&ok[0]);
253                 temp[1] = patterns[0]->cap(2).toUInt(&ok[1]);
254                 temp[2] = patterns[0]->cap(2).toUInt(&ok[2]);
255                 temp[3] = patterns[0]->cap(2).toUInt(&ok[3]);
256                 if(ok[0] && ok[1])
257                 {
258                         core = (100 * temp[0]) + temp[1];
259                 }
260                 if (ok[2] && ok[3])
261                 {
262                         build = (10 * temp[2]) + temp[3];
263                 }
264         }
265
266         if(!line.isEmpty())
267         {
268                 log(line);
269         }
270 }
271
272 bool NVEncEncoder::checkVersion_succeeded(const int &exitCode)
273 {
274         return (exitCode == 0) || (exitCode == 1);
275 }
276
277 QString NVEncEncoder::printVersion(const unsigned int &revision, const bool &modified)
278 {
279         unsigned int core, build;
280         splitRevision(revision, core, build);
281
282         return tr("NVEncC version: %1.%2").arg(QString::number(core / 100), QString::number(core % 100).leftJustified(2, QLatin1Char('0')));
283 }
284
285 bool NVEncEncoder::isVersionSupported(const unsigned int &revision, const bool &modified)
286 {
287         unsigned int core, build;
288         splitRevision(revision, core, build);
289
290         if(core < VERSION_NVENCC_MINIMUM_VER)
291         {
292                 log(tr("\nERROR: Your version of NVEncC is too old! (Minimum required version is %1.%2)").arg(QString::number(VERSION_NVENCC_MINIMUM_VER / 100), QString::number(VERSION_NVENCC_MINIMUM_VER % 100)));
293                 return false;
294         }
295         else if(core > VERSION_NVENCC_MINIMUM_VER)
296         {
297                 log(tr("\nWARNING: Your version of NVEncC is newer than the latest tested version, take care!"));
298                 log(tr("This application works best with NVEncC version %1.%2. Newer versions may work or not.").arg(QString::number(VERSION_NVENCC_MINIMUM_VER / 100), QString::number(VERSION_NVENCC_MINIMUM_VER % 100)));
299         }
300
301         if (build < VERSION_NVENCC_MINIMUM_API)
302         {
303                 log(tr("\nERROR: Your version of NVENC API is too old! (Minimum required version is %1.%2)").arg(QString::number(VERSION_NVENCC_MINIMUM_API / 10), QString::number(VERSION_NVENCC_MINIMUM_API % 10)));
304                 return false;
305         }
306
307         return true;
308 }
309
310 // ------------------------------------------------------------
311 // Encoding Functions
312 // ------------------------------------------------------------
313
314 void NVEncEncoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, const unsigned int &frames, const QString &indexFile, const int &pass, const QString &passLogFile)
315 {
316         double crf_int = 0.0, crf_frc = 0.0;
317
318         switch(m_options->rcMode())
319         {
320         case OptionsModel::RCMode_ABR:
321                 cmdLine << "--vbr" << QString::number(m_options->bitrate());
322                 break;
323         case OptionsModel::RCMode_CQ:
324                 cmdLine << "--cqp" << QString::number(qRound(m_options->quantizer()));
325                 break;
326         default:
327                 MUTILS_THROW("Bad rate-control mode !!!");
328                 break;
329         }
330         
331         const QString profile = m_options->profile().simplified().toLower();
332         if(!profile.isEmpty())
333         {
334                 if(profile.compare(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED), Qt::CaseInsensitive) != 0)
335                 {
336                         cmdLine << "--profile" << profile;
337                 }
338         }
339
340         if(!m_options->customEncParams().isEmpty())
341         {
342                 QStringList customArgs = splitParams(m_options->customEncParams(), m_sourceFile, m_outputFile);
343                 if(usePipe)
344                 {
345                         QStringList::iterator i = customArgs.begin();
346                         while(i != customArgs.end())
347                         {
348                                 bool bModified = false;
349                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
350                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
351                                 if(!bModified) i++;
352                         }
353                 }
354                 cmdLine.append(customArgs);
355         }
356
357         cmdLine << "--output" << QDir::toNativeSeparators(m_outputFile);
358         
359         if(usePipe)
360         {
361                 cmdLine << "--y4m" << "--input" << "-";
362         }
363         else
364         {
365                 cmdLine << "--input" << QDir::toNativeSeparators(m_sourceFile);
366         }
367 }
368
369 void NVEncEncoder::runEncodingPass_init(QList<QRegExp*> &patterns)
370 {
371         patterns << new QRegExp("^(\\d+) frames:"); //regExpFrameCnt
372 }
373
374 void NVEncEncoder::runEncodingPass_parseLine(const QString &line, QList<QRegExp*> &patterns, const unsigned int &totalFrames, const int &pass, double &last_progress, double &size_estimate)
375 {
376         int offset = -1;
377         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
378         {
379                 NVENCC_UPDATE_PROGRESS(patterns[0]);
380         }
381         else if(!line.isEmpty())
382         {
383                 log(line);
384         }
385 }