OSDN Git Service

More code refactoring and clean-up.
[lamexp/LameXP.git] / src / Encoder_Opus.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "Encoder_Opus.h"
24
25 #include "Global.h"
26 #include "Model_Settings.h"
27
28 #include <QProcess>
29 #include <QDir>
30 #include <QUUid>
31
32 ///////////////////////////////////////////////////////////////////////////////
33 // Encoder Info
34 ///////////////////////////////////////////////////////////////////////////////
35
36 class OpusEncoderInfo : public AbstractEncoderInfo
37 {
38         virtual bool isModeSupported(int mode) const
39         {
40                 switch(mode)
41                 {
42                 case SettingsModel::VBRMode:
43                 case SettingsModel::ABRMode:
44                 case SettingsModel::CBRMode:
45                         return true;
46                         break;
47                 default:
48                         MUTILS_THROW("Bad RC mode specified!");
49                 }
50         }
51
52         virtual int valueCount(int mode) const
53         {
54                 switch(mode)
55                 {
56                 case SettingsModel::VBRMode:
57                 case SettingsModel::ABRMode:
58                 case SettingsModel::CBRMode:
59                         return 32;
60                         break;
61                 default:
62                         MUTILS_THROW("Bad RC mode specified!");
63                 }
64         }
65
66         virtual int valueAt(int mode, int index) const
67         {
68                 switch(mode)
69                 {
70                 case SettingsModel::VBRMode:
71                 case SettingsModel::ABRMode:
72                 case SettingsModel::CBRMode:
73                         return qBound(8, (index + 1) * 8, 256);
74                         break;
75                 default:
76                         MUTILS_THROW("Bad RC mode specified!");
77                 }
78         }
79
80         virtual int valueType(int mode) const
81         {
82                 switch(mode)
83                 {
84                 case SettingsModel::VBRMode:
85                 case SettingsModel::ABRMode:
86                         return TYPE_APPROX_BITRATE;
87                         break;
88                 case SettingsModel::CBRMode:
89                         return TYPE_BITRATE;
90                         break;
91                 default:
92                         MUTILS_THROW("Bad RC mode specified!");
93                 }
94         }
95
96         virtual const char *description(void) const
97         {
98                 static const char* s_description = "Opus-Tools OpusEnc (libopus)";
99                 return s_description;
100         }
101 }
102 static const g_opusEncoderInfo;
103
104 ///////////////////////////////////////////////////////////////////////////////
105 // Encoder implementation
106 ///////////////////////////////////////////////////////////////////////////////
107
108 OpusEncoder::OpusEncoder(void)
109 :
110         m_binary(lamexp_tool_lookup("opusenc.exe"))
111 {
112         if(m_binary.isEmpty())
113         {
114                 MUTILS_THROW("Error initializing Opus encoder. Tool 'opusenc.exe' is not registred!");
115         }
116
117         m_configOptimizeFor = 0;
118         m_configEncodeComplexity = 10;
119         m_configFrameSize = 3;
120 }
121
122 OpusEncoder::~OpusEncoder(void)
123 {
124 }
125
126 bool OpusEncoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const QString &outputFile, volatile bool *abortFlag)
127 {
128         QProcess process;
129         QStringList args;
130
131         switch(m_configRCMode)
132         {
133         case SettingsModel::VBRMode:
134                 args << "--vbr";
135                 break;
136         case SettingsModel::ABRMode:
137                 args << "--cvbr";
138                 break;
139         case SettingsModel::CBRMode:
140                 args << "--hard-cbr";
141                 break;
142         default:
143                 MUTILS_THROW("Bad rate-control mode!");
144                 break;
145         }
146
147         args << "--comp" << QString::number(m_configEncodeComplexity);
148
149         switch(m_configFrameSize)
150         {
151         case 0:
152                 args << "--framesize" << "2.5";
153                 break;
154         case 1:
155                 args << "--framesize" << "5";
156                 break;
157         case 2:
158                 args << "--framesize" << "10";
159                 break;
160         case 3:
161                 args << "--framesize" << "20";
162                 break;
163         case 4:
164                 args << "--framesize" << "40";
165                 break;
166         case 5:
167                 args << "--framesize" << "60";
168                 break;
169         }
170
171         args << QString("--bitrate") << QString::number(qBound(8, (m_configBitrate + 1) * 8, 256));
172
173         if(!metaInfo.title().isEmpty()) args << "--title" << cleanTag(metaInfo.title());
174         if(!metaInfo.artist().isEmpty()) args << "--artist" << cleanTag(metaInfo.artist());
175         if(!metaInfo.album().isEmpty()) args << "--album" << cleanTag(metaInfo.album());
176         if(!metaInfo.genre().isEmpty()) args << "--genre" << cleanTag(metaInfo.genre());
177         if(metaInfo.year()) args << "--date" << QString::number(metaInfo.year());
178         if(metaInfo.position()) args << "--comment" << QString("tracknumber=%1").arg(QString::number(metaInfo.position()));
179         if(!metaInfo.comment().isEmpty()) args << "--comment" << QString("comment=%1").arg(cleanTag(metaInfo.comment()));
180         
181         if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);
182
183         args << QDir::toNativeSeparators(sourceFile);
184         args << QDir::toNativeSeparators(outputFile);
185
186         if(!startProcess(process, m_binary, args))
187         {
188                 return false;
189         }
190
191         bool bTimeout = false;
192         bool bAborted = false;
193         int prevProgress = -1;
194
195         QRegExp regExp("\\((\\d+)%\\)");
196
197         while(process.state() != QProcess::NotRunning)
198         {
199                 if(*abortFlag)
200                 {
201                         process.kill();
202                         bAborted = true;
203                         emit messageLogged("\nABORTED BY USER !!!");
204                         break;
205                 }
206                 process.waitForReadyRead(m_processTimeoutInterval);
207                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
208                 {
209                         process.kill();
210                         qWarning("Opus process timed out <-- killing!");
211                         emit messageLogged("\nPROCESS TIMEOUT !!!");
212                         bTimeout = true;
213                         break;
214                 }
215                 while(process.bytesAvailable() > 0)
216                 {
217                         QByteArray line = process.readLine();
218                         QString text = QString::fromUtf8(line.constData()).simplified();
219                         if(regExp.lastIndexIn(text) >= 0)
220                         {
221                                 bool ok = false;
222                                 int progress = regExp.cap(1).toInt(&ok);
223                                 if(ok && (progress > prevProgress))
224                                 {
225                                         emit statusUpdated(progress);
226                                         prevProgress = qMin(progress + 2, 99);
227                                 }
228                         }
229                         else if(!text.isEmpty())
230                         {
231                                 emit messageLogged(text);
232                         }
233                 }
234         }
235
236         process.waitForFinished();
237         if(process.state() != QProcess::NotRunning)
238         {
239                 process.kill();
240                 process.waitForFinished(-1);
241         }
242         
243         emit statusUpdated(100);
244         emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));
245
246         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
247         {
248                 return false;
249         }
250         
251         return true;
252 }
253
254 void OpusEncoder::setOptimizeFor(int optimizeFor)
255 {
256         m_configOptimizeFor = qBound(0, optimizeFor, 2);
257 }
258
259 void OpusEncoder::setEncodeComplexity(int complexity)
260 {
261         m_configEncodeComplexity = qBound(0, complexity, 10);
262 }
263
264 void OpusEncoder::setFrameSize(int frameSize)
265 {
266         m_configFrameSize = qBound(0, frameSize, 5);
267 }
268
269 QString OpusEncoder::extension(void)
270 {
271         return "opus";
272 }
273
274 bool OpusEncoder::isFormatSupported(const QString &containerType, const QString &containerProfile, const QString &formatType, const QString &formatProfile, const QString &formatVersion)
275 {
276         if(containerType.compare("Wave", Qt::CaseInsensitive) == 0)
277         {
278                 if(formatType.compare("PCM", Qt::CaseInsensitive) == 0)
279                 {
280                         return true;
281                 }
282         }
283
284         return false;
285 }
286
287 const unsigned int *OpusEncoder::supportedChannelCount(void)
288 {
289         return NULL;
290 }
291
292 const unsigned int *OpusEncoder::supportedBitdepths(void)
293 {
294         static const unsigned int supportedBPS[] = {8, 16, 24, AudioFileModel::BITDEPTH_IEEE_FLOAT32, NULL};
295         return supportedBPS;
296 }
297
298 const bool OpusEncoder::needsTimingInfo(void)
299 {
300         return true;
301 }
302
303 const AbstractEncoderInfo *OpusEncoder::getEncoderInfo(void)
304 {
305         return &g_opusEncoderInfo;
306 }