OSDN Git Service

302482c9d7dad6c9e2a55d861b6824d7973f3c83
[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 = 449;
44
45 // ------------------------------------------------------------
46 // Helper Macros
47 // ------------------------------------------------------------
48
49 #define NVENCC_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(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(line.mid(offset).trimmed()); \
66 } \
67 while(0)
68
69 #define NVENCC_UPDATE_PROGRESS_OLD(X) do \
70 { \
71         bool ok = false; \
72         unsigned int progressFrames = (X)->cap(1).toUInt(&ok); \
73         double progress = 0.0; \
74         setStatus(JobStatus_Running); \
75         if(ok && (clipInfo.getFrameCount() > 0)) \
76         { \
77                 progress = (double(progressFrames) / double(clipInfo.getFrameCount())); \
78                 if(!qFuzzyCompare(progress, last_progress)) \
79                 { \
80                         setProgress(floor(progress * 100.0)); \
81                         size_estimate = qFuzzyIsNull(size_estimate) ? estimateSize(m_outputFile, progress) : ((0.667 * size_estimate) + (0.333 * estimateSize(m_outputFile, progress))); \
82                         last_progress = progress; \
83                 } \
84         } \
85         setDetails(tr("[%1] %2, est. file size %3").arg(QString().sprintf("%.1f%%", 100.0 * progress), line.mid(offset).trimmed(), sizeToString(qRound64(size_estimate)))); \
86 } \
87 while(0)
88
89 #define REMOVE_CUSTOM_ARG(LIST, ITER, FLAG, PARAM) do \
90 { \
91         if(ITER != LIST.end()) \
92         { \
93                 if((*ITER).compare(PARAM, Qt::CaseInsensitive) == 0) \
94                 { \
95                         log(tr("WARNING: Custom parameter \"" PARAM "\" will be ignored in Pipe'd mode!\n")); \
96                         ITER = LIST.erase(ITER); \
97                         if(ITER != LIST.end()) \
98                         { \
99                                 if(!((*ITER).startsWith("--", Qt::CaseInsensitive))) ITER = LIST.erase(ITER); \
100                         } \
101                         FLAG = true; \
102                 } \
103         } \
104 } \
105 while(0)
106
107 // ------------------------------------------------------------
108 // Encoder Info
109 // ------------------------------------------------------------
110
111 class NVEncEncoderInfo : public AbstractEncoderInfo
112 {
113 public:
114         virtual QString getName(void) const
115         {
116                 return "NVEncC";
117         }
118
119         virtual QList<ArchId> getArchitectures(void) const
120         {
121                 return QList<ArchId>()
122                 << qMakePair(QString("32-Bit (x86)"), ARCH_TYPE_X86)
123                 << qMakePair(QString("64-Bit (x64)"), ARCH_TYPE_X64);
124         }
125
126         virtual QStringList getVariants(void) const
127         {
128                 return QStringList() << "AVC" << "HEVC";
129         }
130
131         virtual QList<RCMode> getRCModes(void) const
132         {
133                 return QList<RCMode>()
134                 << qMakePair(QString("CQP"),  RC_TYPE_QUANTIZER)
135                 << qMakePair(QString("VBR"),  RC_TYPE_RATE_KBPS)
136                 << qMakePair(QString("VBR2"), RC_TYPE_RATE_KBPS)
137                 << qMakePair(QString("CBR"),  RC_TYPE_RATE_KBPS);
138         }
139
140         virtual QStringList getTunings(void) const
141         {
142                 return QStringList();
143         }
144
145         virtual QStringList getPresets(void) const
146         {
147                 return QStringList();
148         }
149
150         virtual QStringList getProfiles(const quint32 &variant) const
151         {
152                 QStringList profiles;
153                 switch(variant)
154                 {
155                         case 0: profiles << "baseline" << "main" << "high"; break;
156                         case 1: profiles << "main";                         break;
157                         default: MUTILS_THROW("Unknown encoder variant!");
158                 }
159                 return profiles;
160         }
161
162         virtual QStringList supportedOutputFormats(void) const
163         {
164                 QStringList extLst;
165                 extLst << "mp4" << "264" << "hevc";
166                 return extLst;
167         }
168
169         virtual bool isInputTypeSupported(const int format) const
170         {
171                 switch(format)
172                 {
173                 case MediaInfo::FILETYPE_AVISYNTH:
174                 case MediaInfo::FILETYPE_YUV4MPEG2:
175                 case MediaInfo::FILETYPE_UNKNOWN:
176                         return true;
177                 default:
178                         return false;
179                 }
180         }
181
182         virtual QString getBinaryPath(const SysinfoModel *sysinfo, const quint32 &encArch, const quint32 &encVariant) const
183         {
184                 QString arch, ext;
185                 switch(encArch)
186                 {
187                         case 0: arch = "x86";             break;
188                         case 1: arch = "x64"; ext = "64"; break;
189                         default: MUTILS_THROW("Unknown encoder arch!");
190                 }
191                 switch(encVariant)
192                 {
193                         case 0: break;
194                         case 1: break;
195                         default: MUTILS_THROW("Unknown encoder variant!");
196                 }
197                 return QString("%1/toolset/%2/nvencc/nvencc%3.exe").arg(sysinfo->getAppPath(), arch, ext);
198         }
199
200         virtual QStringList getDependencies(const SysinfoModel *sysinfo, const quint32 &encArch, const quint32 &encVariant) const
201         {
202                 QString arch;
203                 switch (encArch)
204                 {
205                         case 0: arch = "x86"; break;
206                         case 1: arch = "x64"; break;
207                         default: MUTILS_THROW("Unknown encoder arch!");
208                 }
209                 switch (encVariant)
210                 {
211                         case 0: break;
212                         case 1: break;
213                         default: MUTILS_THROW("Unknown encoder variant!");
214
215                 }
216                 return QStringList()
217                 << QString("%1/toolset/%2/nvencc/avcodec-58.dll"  ).arg(sysinfo->getAppPath(), arch)
218                 << QString("%1/toolset/%2/nvencc/avfilter-7.dll"  ).arg(sysinfo->getAppPath(), arch)
219                 << QString("%1/toolset/%2/nvencc/avformat-58.dll" ).arg(sysinfo->getAppPath(), arch)
220                 << QString("%1/toolset/%2/nvencc/avutil-56.dll"   ).arg(sysinfo->getAppPath(), arch)
221                 << QString("%1/toolset/%2/nvencc/swresample-3.dll").arg(sysinfo->getAppPath(), arch);
222         }
223
224         virtual QString getHelpCommand(void) const
225         {
226                 return "--help";
227         }
228 };
229
230 static const NVEncEncoderInfo s_nvencEncoderInfo;
231
232 const AbstractEncoderInfo& NVEncEncoder::encoderInfo(void)
233 {
234         return s_nvencEncoderInfo;
235 }
236
237 const AbstractEncoderInfo &NVEncEncoder::getEncoderInfo(void) const
238 {
239         return encoderInfo();
240 }
241
242 // ------------------------------------------------------------
243 // Constructor & Destructor
244 // ------------------------------------------------------------
245
246 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)
247 :
248         AbstractEncoder(jobObject, options, sysinfo, preferences, jobStatus, abort, pause, semaphorePause, sourceFile, outputFile)
249 {
250         if(options->encType() != OptionsModel::EncType_NVEnc)
251         {
252                 MUTILS_THROW("Invalid encoder type!");
253         }
254 }
255
256 NVEncEncoder::~NVEncEncoder(void)
257 {
258         /*Nothing to do here*/
259 }
260
261 QString NVEncEncoder::getName(void) const
262 {
263         return s_nvencEncoderInfo.getFullName(m_options->encArch(), m_options->encVariant());
264 }
265
266 // ------------------------------------------------------------
267 // Check Version
268 // ------------------------------------------------------------
269
270 void NVEncEncoder::checkVersion_init(QList<QRegExp*> &patterns, QStringList &cmdLine)
271 {
272         cmdLine << "--version";
273         patterns << new QRegExp("\\bNVEncC\\s+\\(x\\d+\\)\\s+(\\d)\\.(\\d+)\\s+\\(r(\\d+)\\)", Qt::CaseInsensitive);
274 }
275
276 void NVEncEncoder::checkVersion_parseLine(const QString &line, const QList<QRegExp*> &patterns, unsigned int &core, unsigned int &build, bool &modified)
277 {
278         if(patterns[0]->lastIndexIn(line) >= 0)
279         {
280                 unsigned int temp[3];
281                 if(MUtils::regexp_parse_uint32(*patterns[0], temp, 3))
282                 {
283                         core = (100 * temp[0]) + temp[1];
284                         build = temp[2];
285                 }
286         }
287
288         if(!line.isEmpty())
289         {
290                 log(line);
291         }
292 }
293
294 bool NVEncEncoder::checkVersion_succeeded(const int &exitCode)
295 {
296         return (exitCode == 0) || (exitCode == 1);
297 }
298
299 QString NVEncEncoder::printVersion(const unsigned int &revision, const bool &modified)
300 {
301         unsigned int core, build;
302         splitRevision(revision, core, build);
303
304         return tr("NVEncC version: %1.%2 [rev #%3]").arg(QString::number(core / 100), QString::number(core % 100).leftJustified(2, QLatin1Char('0')), QString::number(build));
305 }
306
307 bool NVEncEncoder::isVersionSupported(const unsigned int &revision, const bool &modified)
308 {
309         unsigned int core, build;
310         splitRevision(revision, core, build);
311
312         if(core < VERSION_NVENCC_MINIMUM_VER)
313         {
314                 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)));
315                 return false;
316         }
317         else if(core > VERSION_NVENCC_MINIMUM_VER)
318         {
319                 log(tr("\nWARNING: Your version of NVEncC is newer than the latest tested version, take care!"));
320                 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)));
321         }
322
323         return true;
324 }
325
326 // ------------------------------------------------------------
327 // Encoding Functions
328 // ------------------------------------------------------------
329
330 void NVEncEncoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, const ClipInfo &clipInfo, const QString &indexFile, const int &pass, const QString &passLogFile)
331 {
332         switch (m_options->encVariant())
333         {
334         case 0:
335                 cmdLine << "--codec" << "avc";
336                 break;
337         case 1:
338                 cmdLine << "--codec" << "hevc";
339                 break;
340         default:
341                 MUTILS_THROW("Bad encoder variant !!!");
342         }
343
344         switch(m_options->rcMode())
345         {
346         case 0:
347                 cmdLine << "--cqp" << QString::number(qRound(m_options->quantizer()));
348                 break;
349         case 1:
350                 cmdLine << "--vbr" << QString::number(m_options->bitrate());
351                 break;
352         case 2:
353                 cmdLine << "--vbr2" << QString::number(m_options->bitrate());
354                 break;
355         case 3:
356                 cmdLine << "--cbr" << QString::number(m_options->bitrate());
357                 break;
358         default:
359                 MUTILS_THROW("Bad rate-control mode !!!");
360         }
361         
362         const QString profile = m_options->profile().simplified().toLower();
363         if(!profile.isEmpty())
364         {
365                 if(profile.compare(QString::fromLatin1(OptionsModel::PROFILE_UNRESTRICTED), Qt::CaseInsensitive) != 0)
366                 {
367                         cmdLine << "--profile" << profile;
368                 }
369         }
370
371         if(!m_options->customEncParams().isEmpty())
372         {
373                 QStringList customArgs = splitParams(m_options->customEncParams(), m_sourceFile, m_outputFile);
374                 if(usePipe)
375                 {
376                         QStringList::iterator i = customArgs.begin();
377                         while(i != customArgs.end())
378                         {
379                                 bool bModified = false;
380                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--fps");
381                                 REMOVE_CUSTOM_ARG(customArgs, i, bModified, "--frames");
382                                 if(!bModified) i++;
383                         }
384                 }
385                 cmdLine.append(customArgs);
386         }
387
388         cmdLine << "--output" << QDir::toNativeSeparators(m_outputFile);
389         
390         if(usePipe)
391         {
392                 cmdLine << "--y4m" << "--input" << "-";
393         }
394         else
395         {
396                 cmdLine << "--input" << QDir::toNativeSeparators(m_sourceFile);
397         }
398 }
399
400 void NVEncEncoder::runEncodingPass_init(QList<QRegExp*> &patterns)
401 {
402         patterns << new QRegExp("\\[(\\d+)\\.(\\d+)%\\].+frames", Qt::CaseInsensitive);
403         patterns << new QRegExp("^(\\d+) frames:", Qt::CaseInsensitive);
404         patterns << new QRegExp("Selected\\s+codec\\s+is\\s+not\\s+supported", Qt::CaseInsensitive);
405         patterns << new QRegExp("nvEncodeAPI.dll\\s+does\\s+not\\s+exists\\s+in\\s+your\\s+system", Qt::CaseInsensitive);
406 }
407
408 void NVEncEncoder::runEncodingPass_parseLine(const QString &line, const QList<QRegExp*> &patterns, const ClipInfo &clipInfo, const int &pass, double &last_progress, double &size_estimate)
409 {
410         int offset = -1;
411         if((offset = patterns[0]->lastIndexIn(line)) >= 0)
412         {
413                 NVENCC_UPDATE_PROGRESS(patterns[0]);
414         }
415         else if ((offset = patterns[1]->lastIndexIn(line)) >= 0)
416         {
417                 NVENCC_UPDATE_PROGRESS_OLD(patterns[1]);
418         }
419         else if ((offset = patterns[2]->lastIndexIn(line)) >= 0)
420         {
421                 log(QString("ERROR: YOUR HARDWARE DOES *NOT* SUPPORT THE '%1' CODEC !!!\n").arg(s_nvencEncoderInfo.variantToString(m_options->encVariant())));
422         }
423         else if ((offset = patterns[3]->lastIndexIn(line)) >= 0)
424         {
425                 log("ERROR: NVIDIA ENCODER API (NVENCODEAPI.DLL) IS *NOT* AVAILABLE !!!\n");
426         }
427         else if(!line.isEmpty())
428         {
429                 log(line);
430         }
431 }