OSDN Git Service

Bump x265 minimum required version to 3.2+5.
[x264-launcher/x264-launcher.git] / src / encoder_nvencc.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2019 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_nvencc.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 = 436;
44
45 // ------------------------------------------------------------
46 // Helper Macros
47 // ------------------------------------------------------------
48
49 #define NVENCC_UPDATE_PROGRESS(X) do \
50 { \
51         bool ok = false; \
52         unsigned int progressFrames = (X)->cap(1).toUInt(&ok); \
53         double progress = 0.0; \
54         setStatus(JobStatus_Running); \
55         if(ok && (clipInfo.getFrameCount() > 0)) \
56         { \
57                 progress = (double(progressFrames) / double(clipInfo.getFrameCount())); \
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] %2, est. file size %3").arg(QString().sprintf("%.1f%%", 100.0 * progress), 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 NVEncEncoderInfo : public AbstractEncoderInfo
92 {
93 public:
94         virtual QString getName(void) const
95         {
96                 return "NVEncC";
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() << "AVC" << "HEVC";
109         }
110
111         virtual QList<RCMode> getRCModes(void) const
112         {
113                 return QList<RCMode>()
114                 << qMakePair(QString("CQP"),  RC_TYPE_QUANTIZER)
115                 << qMakePair(QString("VBR"),  RC_TYPE_RATE_KBPS)
116                 << qMakePair(QString("VBR2"), RC_TYPE_RATE_KBPS)
117                 << qMakePair(QString("CBR"),  RC_TYPE_RATE_KBPS);
118         }
119
120         virtual QStringList getTunings(void) const
121         {
122                 return QStringList();
123         }
124
125         virtual QStringList getPresets(void) const
126         {
127                 return QStringList();
128         }
129
130         virtual QStringList getProfiles(const quint32 &variant) const
131         {
132                 QStringList profiles;
133                 switch(variant)
134                 {
135                         case 0: profiles << "baseline" << "main" << "high"; break;
136                         case 1: profiles << "main";                         break;
137                         default: MUTILS_THROW("Unknown encoder variant!");
138                 }
139                 return profiles;
140         }
141
142         virtual QStringList supportedOutputFormats(void) const
143         {
144                 QStringList extLst;
145                 extLst << "mp4" << "264" << "hevc";
146                 return extLst;
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, ext;
163                 switch(encArch)
164                 {
165                         case 0: arch = "x86";             break;
166                         case 1: arch = "x64"; ext = "64"; break;
167                         default: MUTILS_THROW("Unknown encoder arch!");
168                 }
169                 switch(encVariant)
170                 {
171                         case 0: break;
172                         case 1: break;
173                         default: MUTILS_THROW("Unknown encoder variant!");
174                 }
175                 return QString("%1/toolset/%2/nvencc/nvencc%3.exe").arg(sysinfo->getAppPath(), arch, ext);
176         }
177
178         virtual QStringList getDependencies(const SysinfoModel *sysinfo, const quint32 &encArch, const quint32 &encVariant) const
179         {
180                 QString arch;
181                 switch (encArch)
182                 {
183                         case 0: arch = "x86"; break;
184                         case 1: arch = "x64"; break;
185                         default: MUTILS_THROW("Unknown encoder arch!");
186                 }
187                 switch (encVariant)
188                 {
189                         case 0: break;
190                         case 1: break;
191                         default: MUTILS_THROW("Unknown encoder variant!");
192
193                 }
194                 return QStringList()
195                 << QString("%1/toolset/%2/nvencc/avcodec-58.dll"  ).arg(sysinfo->getAppPath(), arch)
196                 << QString("%1/toolset/%2/nvencc/avfilter-7.dll"  ).arg(sysinfo->getAppPath(), arch)
197                 << QString("%1/toolset/%2/nvencc/avformat-58.dll" ).arg(sysinfo->getAppPath(), arch)
198                 << QString("%1/toolset/%2/nvencc/avutil-56.dll"   ).arg(sysinfo->getAppPath(), arch)
199                 << QString("%1/toolset/%2/nvencc/swresample-3.dll").arg(sysinfo->getAppPath(), arch);
200         }
201
202         virtual QString getHelpCommand(void) const
203         {
204                 return "--help";
205         }
206 };
207
208 static const NVEncEncoderInfo s_nvencEncoderInfo;
209
210 const AbstractEncoderInfo& NVEncEncoder::encoderInfo(void)
211 {
212         return s_nvencEncoderInfo;
213 }
214
215 const AbstractEncoderInfo &NVEncEncoder::getEncoderInfo(void) const
216 {
217         return encoderInfo();
218 }
219
220 // ------------------------------------------------------------
221 // Constructor & Destructor
222 // ------------------------------------------------------------
223
224 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)
225 :
226         AbstractEncoder(jobObject, options, sysinfo, preferences, jobStatus, abort, pause, semaphorePause, sourceFile, outputFile)
227 {
228         if(options->encType() != OptionsModel::EncType_NVEnc)
229         {
230                 MUTILS_THROW("Invalid encoder type!");
231         }
232 }
233
234 NVEncEncoder::~NVEncEncoder(void)
235 {
236         /*Nothing to do here*/
237 }
238
239 QString NVEncEncoder::getName(void) const
240 {
241         return s_nvencEncoderInfo.getFullName(m_options->encArch(), m_options->encVariant());
242 }
243
244 // ------------------------------------------------------------
245 // Check Version
246 // ------------------------------------------------------------
247
248 void NVEncEncoder::checkVersion_init(QList<QRegExp*> &patterns, QStringList &cmdLine)
249 {
250         cmdLine << "--version";
251         patterns << new QRegExp("\\bNVEncC\\s+\\(x\\d+\\)\\s+(\\d)\\.(\\d+)\\s+\\(r(\\d+)\\)", Qt::CaseInsensitive);
252 }
253
254 void NVEncEncoder::checkVersion_parseLine(const QString &line, const QList<QRegExp*> &patterns, unsigned int &core, unsigned int &build, bool &modified)
255 {
256         if(patterns[0]->lastIndexIn(line) >= 0)
257         {
258                 unsigned int temp[3];
259                 if(MUtils::regexp_parse_uint32(*patterns[0], temp, 3))
260                 {
261                         core = (100 * temp[0]) + temp[1];
262                         build = temp[2];
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 [rev #%3]").arg(QString::number(core / 100), QString::number(core % 100).leftJustified(2, QLatin1Char('0')), QString::number(build));
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         return true;
302 }
303
304 // ------------------------------------------------------------
305 // Encoding Functions
306 // ------------------------------------------------------------
307
308 void NVEncEncoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, const ClipInfo &clipInfo, const QString &indexFile, const int &pass, const QString &passLogFile)
309 {
310         switch (m_options->encVariant())
311         {
312         case 0:
313                 cmdLine << "--codec" << "avc";
314                 break;
315         case 1:
316                 cmdLine << "--codec" << "hevc";
317                 break;
318         default:
319                 MUTILS_THROW("Bad encoder variant !!!");
320         }
321
322         switch(m_options->rcMode())
323         {
324         case 0:
325                 cmdLine << "--cqp" << QString::number(qRound(m_options->quantizer()));
326                 break;
327         case 1:
328                 cmdLine << "--vbr" << QString::number(m_options->bitrate());
329                 break;
330         case 2:
331                 cmdLine << "--vbr2" << QString::number(m_options->bitrate());
332                 break;
333         case 3:
334                 cmdLine << "--cbr" << QString::number(m_options->bitrate());
335                 break;
336         default:
337                 MUTILS_THROW("Bad rate-control mode !!!");
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                 cmdLine << "--y4m" << "--input" << "-";
371         }
372         else
373         {
374                 cmdLine << "--input" << QDir::toNativeSeparators(m_sourceFile);
375         }
376 }
377
378 void NVEncEncoder::runEncodingPass_init(QList<QRegExp*> &patterns)
379 {
380         patterns << new QRegExp("^(\\d+) frames:");
381         patterns << new QRegExp("Selected\\s+codec\\s+is\\s+not\\s+supported", Qt::CaseInsensitive);
382         patterns << new QRegExp("nvEncodeAPI.dll\\s+does\\s+not\\s+exists\\s+in\\s+your\\s+system", Qt::CaseInsensitive);
383 }
384
385 void NVEncEncoder::runEncodingPass_parseLine(const QString &line, const QList<QRegExp*> &patterns, const ClipInfo &clipInfo, const int &pass, double &last_progress, double &size_estimate)
386 {
387         int offset = -1;
388         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
389         {
390                 NVENCC_UPDATE_PROGRESS(patterns[0]);
391         }
392         else if ((offset = patterns[1]->lastIndexIn(line)) >= 0)
393         {
394                 log(QString("ERROR: YOUR HARDWARE DOES *NOT* SUPPORT THE '%1' CODEC !!!\n").arg(s_nvencEncoderInfo.variantToString(m_options->encVariant())));
395         }
396         else if ((offset = patterns[2]->lastIndexIn(line)) >= 0)
397         {
398                 log("ERROR: NVIDIA ENCODER API (NVENCODEAPI.DLL) IS *NOT* AVAILABLE !!!\n");
399         }
400         else if(!line.isEmpty())
401         {
402                 log(line);
403         }
404 }