OSDN Git Service

Adapted for the latest MUtils library changes.
[x264-launcher/x264-launcher.git] / src / encoder_nvenc.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_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 #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_NVENCC_MINIMUM_VER = 302;
44 static const unsigned int VERSION_NVENCC_MINIMUM_API =  70;
45
46 // ------------------------------------------------------------
47 // Helper Macros
48 // ------------------------------------------------------------
49
50 #define NVENCC_UPDATE_PROGRESS(X) do \
51 { \
52         bool ok = false; \
53         unsigned int progressFrames = (X)->cap(1).toUInt(&ok); \
54         double progress = 0.0; \
55         setStatus(JobStatus_Running); \
56         if(ok && (clipInfo.getFrameCount() > 0)) \
57         { \
58                 progress = (double(progressFrames) / double(clipInfo.getFrameCount())); \
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] %2, est. file size %3").arg(QString().sprintf("%.1f%%", 100.0 * progress), 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 NVEncEncoderInfo : public AbstractEncoderInfo
93 {
94 public:
95         virtual QString getName(void) const
96         {
97                 return "NVEncC";
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() << "AVC" << "HEVC";
110         }
111
112         virtual QList<RCMode> getRCModes(void) const
113         {
114                 return QList<RCMode>()
115                 << qMakePair(QString("CQP"),  RC_TYPE_QUANTIZER)
116                 << qMakePair(QString("VBR"),  RC_TYPE_RATE_KBPS)
117                 << qMakePair(QString("VBR2"), RC_TYPE_RATE_KBPS)
118                 << qMakePair(QString("CBR"),  RC_TYPE_RATE_KBPS);
119         }
120
121         virtual QStringList getTunings(void) const
122         {
123                 return QStringList();
124         }
125
126         virtual QStringList getPresets(void) const
127         {
128                 return QStringList();
129         }
130
131         virtual QStringList getProfiles(const quint32 &variant) const
132         {
133                 QStringList profiles;
134                 switch(variant)
135                 {
136                         case 0: profiles << "baseline" << "main" << "high"; break;
137                         case 1: profiles << "main";                         break;
138                         default: MUTILS_THROW("Unknown encoder variant!");
139                 }
140                 return profiles;
141         }
142
143         virtual QStringList supportedOutputFormats(void) const
144         {
145                 QStringList extLst;
146                 extLst << "mp4" << "264" << "hevc";
147                 return extLst;
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;
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: break;
173                         case 1: break;
174                         default: MUTILS_THROW("Unknown encoder variant!");
175                 }
176                 return QString("%1/toolset/%2/nvencc_%2.exe").arg(sysinfo->getAppPath(), arch);
177         }
178
179         virtual QStringList getDependencies(const SysinfoModel *sysinfo, const quint32 &encArch, const quint32 &encVariant) const
180         {
181                 QString arch;
182                 switch (encArch)
183                 {
184                         case 0: arch = "x86"; break;
185                         case 1: arch = "x64"; break;
186                         default: MUTILS_THROW("Unknown encoder arch!");
187                 }
188                 switch (encVariant)
189                 {
190                         case 0: break;
191                         case 1: break;
192                         default: MUTILS_THROW("Unknown encoder variant!");
193
194                 }
195                 return QStringList()
196                 << QString("%1/toolset/%2/avcodec-57.dll"  ).arg(sysinfo->getAppPath(), arch)
197                 << QString("%1/toolset/%2/avfilter-6.dll"  ).arg(sysinfo->getAppPath(), arch)
198                 << QString("%1/toolset/%2/avformat-57.dll" ).arg(sysinfo->getAppPath(), arch)
199                 << QString("%1/toolset/%2/avutil-55.dll"   ).arg(sysinfo->getAppPath(), arch)
200                 << QString("%1/toolset/%2/swresample-2.dll").arg(sysinfo->getAppPath(), arch);
201         }
202
203         virtual QString getHelpCommand(void) const
204         {
205                 return "--help";
206         }
207 };
208
209 static const NVEncEncoderInfo s_nvencEncoderInfo;
210
211 const AbstractEncoderInfo& NVEncEncoder::encoderInfo(void)
212 {
213         return s_nvencEncoderInfo;
214 }
215
216 const AbstractEncoderInfo &NVEncEncoder::getEncoderInfo(void) const
217 {
218         return encoderInfo();
219 }
220
221 // ------------------------------------------------------------
222 // Constructor & Destructor
223 // ------------------------------------------------------------
224
225 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)
226 :
227         AbstractEncoder(jobObject, options, sysinfo, preferences, jobStatus, abort, pause, semaphorePause, sourceFile, outputFile)
228 {
229         if(options->encType() != OptionsModel::EncType_NVEnc)
230         {
231                 MUTILS_THROW("Invalid encoder type!");
232         }
233 }
234
235 NVEncEncoder::~NVEncEncoder(void)
236 {
237         /*Nothing to do here*/
238 }
239
240 QString NVEncEncoder::getName(void) const
241 {
242         return s_nvencEncoderInfo.getFullName(m_options->encArch(), m_options->encVariant());
243 }
244
245 // ------------------------------------------------------------
246 // Check Version
247 // ------------------------------------------------------------
248
249 void NVEncEncoder::checkVersion_init(QList<QRegExp*> &patterns, QStringList &cmdLine)
250 {
251         cmdLine << "--version";
252         patterns << new QRegExp("\\bNVEncC\\s+\\(x\\d+\\)\\s+(\\d)\\.(\\d+).*\\[NVENC\\s+API\\s+v(\\d+)\\.(\\d+)\\]", Qt::CaseInsensitive);
253 }
254
255 void NVEncEncoder::checkVersion_parseLine(const QString &line, const QList<QRegExp*> &patterns, unsigned int &core, unsigned int &build, bool &modified)
256 {
257         if(patterns[0]->lastIndexIn(line) >= 0)
258         {
259                 unsigned int temp[4];
260                 if(MUtils::regexp_parse_uint32(*patterns[0], temp, 4))
261                 {
262                         core = (100 * temp[0]) + temp[1];
263                         build = (10 * temp[2]) + temp[3];
264                 }
265         }
266
267         if(!line.isEmpty())
268         {
269                 log(line);
270         }
271 }
272
273 bool NVEncEncoder::checkVersion_succeeded(const int &exitCode)
274 {
275         return (exitCode == 0) || (exitCode == 1);
276 }
277
278 QString NVEncEncoder::printVersion(const unsigned int &revision, const bool &modified)
279 {
280         unsigned int core, build;
281         splitRevision(revision, core, build);
282
283         return tr("NVEncC version: %1.%2 [API: %3.%4]").arg(QString::number(core / 100), QString::number(core % 100).leftJustified(2, QLatin1Char('0')), QString::number(build / 10), QString::number(build % 10));
284 }
285
286 bool NVEncEncoder::isVersionSupported(const unsigned int &revision, const bool &modified)
287 {
288         unsigned int core, build;
289         splitRevision(revision, core, build);
290
291         if(core < VERSION_NVENCC_MINIMUM_VER)
292         {
293                 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)));
294                 return false;
295         }
296         else if(core > VERSION_NVENCC_MINIMUM_VER)
297         {
298                 log(tr("\nWARNING: Your version of NVEncC is newer than the latest tested version, take care!"));
299                 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)));
300         }
301
302         if (build < VERSION_NVENCC_MINIMUM_API)
303         {
304                 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)));
305                 return false;
306         }
307
308         return true;
309 }
310
311 // ------------------------------------------------------------
312 // Encoding Functions
313 // ------------------------------------------------------------
314
315 void NVEncEncoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, const ClipInfo &clipInfo, const QString &indexFile, const int &pass, const QString &passLogFile)
316 {
317         switch (m_options->encVariant())
318         {
319         case 0:
320                 cmdLine << "--codec" << "avc";
321                 break;
322         case 1:
323                 cmdLine << "--codec" << "hevc";
324                 break;
325         default:
326                 MUTILS_THROW("Bad encoder variant !!!");
327         }
328
329         switch(m_options->rcMode())
330         {
331         case 0:
332                 cmdLine << "--cqp" << QString::number(qRound(m_options->quantizer()));
333                 break;
334         case 1:
335                 cmdLine << "--vbr" << QString::number(m_options->bitrate());
336                 break;
337         case 2:
338                 cmdLine << "--vbr2" << QString::number(m_options->bitrate());
339                 break;
340         case 3:
341                 cmdLine << "--cbr" << QString::number(m_options->bitrate());
342                 break;
343         default:
344                 MUTILS_THROW("Bad rate-control mode !!!");
345         }
346         
347         const QString profile = m_options->profile().simplified().toLower();
348         if(!profile.isEmpty())
349         {
350                 if(profile.compare(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED), Qt::CaseInsensitive) != 0)
351                 {
352                         cmdLine << "--profile" << profile;
353                 }
354         }
355
356         if(!m_options->customEncParams().isEmpty())
357         {
358                 QStringList customArgs = splitParams(m_options->customEncParams(), m_sourceFile, m_outputFile);
359                 if(usePipe)
360                 {
361                         QStringList::iterator i = customArgs.begin();
362                         while(i != customArgs.end())
363                         {
364                                 bool bModified = false;
365                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
366                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
367                                 if(!bModified) i++;
368                         }
369                 }
370                 cmdLine.append(customArgs);
371         }
372
373         cmdLine << "--output" << QDir::toNativeSeparators(m_outputFile);
374         
375         if(usePipe)
376         {
377                 cmdLine << "--y4m" << "--input" << "-";
378         }
379         else
380         {
381                 cmdLine << "--input" << QDir::toNativeSeparators(m_sourceFile);
382         }
383 }
384
385 void NVEncEncoder::runEncodingPass_init(QList<QRegExp*> &patterns)
386 {
387         patterns << new QRegExp("^(\\d+) frames:");
388         patterns << new QRegExp("Selected\\s+codec\\s+is\\s+not\\s+supported", Qt::CaseInsensitive);
389         patterns << new QRegExp("nvEncodeAPI.dll\\s+does\\s+not\\s+exists\\s+in\\s+your\\s+system", Qt::CaseInsensitive);
390 }
391
392 void NVEncEncoder::runEncodingPass_parseLine(const QString &line, const QList<QRegExp*> &patterns, const ClipInfo &clipInfo, const int &pass, double &last_progress, double &size_estimate)
393 {
394         int offset = -1;
395         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
396         {
397                 NVENCC_UPDATE_PROGRESS(patterns[0]);
398         }
399         else if ((offset = patterns[1]->lastIndexIn(line)) >= 0)
400         {
401                 log(QString("ERROR: YOUR HARDWARE DOES *NOT* SUPPORT THE '%1' CODEC !!!\n").arg(s_nvencEncoderInfo.variantToString(m_options->encVariant())));
402         }
403         else if ((offset = patterns[2]->lastIndexIn(line)) >= 0)
404         {
405                 log("ERROR: NVIDIA ENCODER API (NVENCODEAPI.DLL) IS *NOT* AVAILABLE !!!\n");
406         }
407         else if(!line.isEmpty())
408         {
409                 log(line);
410         }
411 }