OSDN Git Service

Merge branch 'master' of github.com:lordmulder/LameXP
[lamexp/LameXP.git] / src / Encoder_AAC.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 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_AAC.h"
24
25 #include "Global.h"
26 #include "Model_Settings.h"
27
28 #include <QProcess>
29 #include <QDir>
30
31 static int index2bitrate(const int index)
32 {
33         return (index < 32) ? ((index + 1) * 8) : ((index - 15) * 16);
34 }
35
36 ///////////////////////////////////////////////////////////////////////////////
37 // Encoder Info
38 ///////////////////////////////////////////////////////////////////////////////
39
40 class AACEncoderInfo : public AbstractEncoderInfo
41 {
42         virtual bool isModeSupported(int mode) const
43         {
44                 switch(mode)
45                 {
46                 case SettingsModel::VBRMode:
47                 case SettingsModel::ABRMode:
48                 case SettingsModel::CBRMode:
49                         return true;
50                         break;
51                 default:
52                         MUTILS_THROW("Bad RC mode specified!");
53                 }
54         }
55
56         virtual int valueCount(int mode) const
57         {
58                 switch(mode)
59                 {
60                 case SettingsModel::VBRMode:
61                         return 21;
62                         break;
63                 case SettingsModel::ABRMode:
64                 case SettingsModel::CBRMode:
65                         return 41;
66                         break;
67                 default:
68                         MUTILS_THROW("Bad RC mode specified!");
69                 }
70         }
71
72         virtual int valueAt(int mode, int index) const
73         {
74                 switch(mode)
75                 {
76                 case SettingsModel::VBRMode:
77                         return qBound(0, index * 5, 100);
78                         break;
79                 case SettingsModel::ABRMode:
80                 case SettingsModel::CBRMode:
81                         return qBound(8, index2bitrate(index), 400);
82                         break;
83                 default:
84                         MUTILS_THROW("Bad RC mode specified!");
85                 }
86         }
87
88         virtual int valueType(int mode) const
89         {
90                 switch(mode)
91                 {
92                 case SettingsModel::VBRMode:
93                         return TYPE_QUALITY_LEVEL_FLT;
94                         break;
95                 case SettingsModel::ABRMode:
96                         return TYPE_APPROX_BITRATE;
97                         break;
98                 case SettingsModel::CBRMode:
99                         return TYPE_BITRATE;
100                         break;
101                 default:
102                         MUTILS_THROW("Bad RC mode specified!");
103                 }
104         }
105
106         virtual const char *description(void) const
107         {
108                 static const char* s_description = "Nero AAC Encoder (\x0C2\x0A9 Nero AG)";
109                 return s_description;
110         }
111 }
112 static const g_aacEncoderInfo;
113
114 ///////////////////////////////////////////////////////////////////////////////
115 // Encoder implementation
116 ///////////////////////////////////////////////////////////////////////////////
117
118 AACEncoder::AACEncoder(void)
119 :
120         m_binary_enc(lamexp_tools_lookup("neroAacEnc.exe")),
121         m_binary_tag(lamexp_tools_lookup("neroAacTag.exe")),
122         m_binary_sox(lamexp_tools_lookup("sox.exe"))
123 {
124         if(m_binary_enc.isEmpty() || m_binary_tag.isEmpty() || m_binary_sox.isEmpty())
125         {
126                 MUTILS_THROW("Error initializing AAC encoder. Tool 'neroAacEnc.exe' is not registred!");
127         }
128
129         m_configProfile = 0;
130         m_configEnable2Pass = true;
131 }
132
133 AACEncoder::~AACEncoder(void)
134 {
135 }
136
137 bool AACEncoder::encode(const QString &sourceFile, const AudioFileModel_MetaInfo &metaInfo, const unsigned int duration, const QString &outputFile, volatile bool *abortFlag)
138 {
139         QProcess process;
140         QStringList args;
141         const QString baseName = QFileInfo(outputFile).fileName();
142
143         switch(m_configRCMode)
144         {
145         case SettingsModel::VBRMode:
146                 args << "-q" << QString().sprintf("%.2f", double(qBound(0, m_configBitrate * 5, 100)) / 100.0);
147                 break;
148         case SettingsModel::ABRMode:
149                 args << "-br" << QString::number(qBound(8, index2bitrate(m_configBitrate), 400) * 1000);
150                 break;
151         case SettingsModel::CBRMode:
152                 args << "-cbr" << QString::number(qBound(8, index2bitrate(m_configBitrate), 400) * 1000);
153                 break;
154         default:
155                 MUTILS_THROW("Bad rate-control mode!");
156                 break;
157         }
158
159         if(m_configEnable2Pass && (m_configRCMode == SettingsModel::ABRMode))
160         {
161                 args << "-2pass";
162         }
163         
164         switch(m_configProfile)
165         {
166         case 1:
167                 args << "-lc"; //Forces use of LC AAC profile
168                 break;
169         case 2:
170                 args << "-he"; //Forces use of HE AAC profile
171                 break;
172         case 3:
173                 args << "-hev2"; //Forces use of HEv2 AAC profile
174                 break;
175         }
176
177         if(!m_configCustomParams.isEmpty()) args << m_configCustomParams.split(" ", QString::SkipEmptyParts);
178
179         args << "-if" << QDir::toNativeSeparators(sourceFile);
180         args << "-of" << QDir::toNativeSeparators(outputFile);
181
182         if(!startProcess(process, m_binary_enc, args))
183         {
184                 return false;
185         }
186
187         bool bTimeout = false;
188         bool bAborted = false;
189         int prevProgress = -1;
190
191
192         QRegExp regExp("Processed\\s+(\\d+)\\s+seconds");
193         QRegExp regExp_pass1("First\\s+pass:\\s+processed\\s+(\\d+)\\s+seconds");
194         QRegExp regExp_pass2("Second\\s+pass:\\s+processed\\s+(\\d+)\\s+seconds");
195
196         while(process.state() != QProcess::NotRunning)
197         {
198                 if(*abortFlag)
199                 {
200                         process.kill();
201                         bAborted = true;
202                         emit messageLogged("\nABORTED BY USER !!!");
203                         break;
204                 }
205                 process.waitForReadyRead(m_processTimeoutInterval);
206                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
207                 {
208                         process.kill();
209                         qWarning("NeroAacEnc process timed out <-- killing!");
210                         emit messageLogged("\nPROCESS TIMEOUT !!!");
211                         bTimeout = true;
212                         break;
213                 }
214                 while(process.bytesAvailable() > 0)
215                 {
216                         QByteArray line = process.readLine();
217                         QString text = QString::fromUtf8(line.constData()).simplified();
218                         if(regExp_pass1.lastIndexIn(text) >= 0)
219                         {
220                                 bool ok = false;
221                                 int progress = regExp_pass1.cap(1).toInt(&ok);
222                                 if(ok && (duration > 0))
223                                 {
224                                         int newProgress = qRound((static_cast<double>(progress) / static_cast<double>(duration)) * 50.0);
225                                         if(newProgress > prevProgress)
226                                         {
227                                                 emit statusUpdated(newProgress);
228                                                 prevProgress = qMin(newProgress + 2, 99);
229                                         }
230                                 }
231                         }
232                         else if(regExp_pass2.lastIndexIn(text) >= 0)
233                         {
234                                 bool ok = false;
235                                 int progress = regExp_pass2.cap(1).toInt(&ok);
236                                 if(ok && (duration > 0))
237                                 {
238                                         int newProgress = qRound((static_cast<double>(progress) / static_cast<double>(duration)) * 50.0) + 50;
239                                         if(newProgress > prevProgress)
240                                         {
241                                                 emit statusUpdated(newProgress);
242                                                 prevProgress = qMin(newProgress + 2, 99);
243                                         }
244                                 }
245                         }
246                         else if(regExp.lastIndexIn(text) >= 0)
247                         {
248                                 bool ok = false;
249                                 int progress = regExp.cap(1).toInt(&ok);
250                                 if(ok && (duration > 0))
251                                 {
252                                         int newProgress = qRound((static_cast<double>(progress) / static_cast<double>(duration)) * 100.0);
253                                         if(newProgress > prevProgress)
254                                         {
255                                                 emit statusUpdated(newProgress);
256                                                 prevProgress = qMin(newProgress + 2, 99);
257                                         }
258                                 }
259                         }
260                         else if(!text.isEmpty())
261                         {
262                                 emit messageLogged(text);
263                         }
264                 }
265         }
266
267         process.waitForFinished();
268         if(process.state() != QProcess::NotRunning)
269         {
270                 process.kill();
271                 process.waitForFinished(-1);
272         }
273         
274         emit statusUpdated(100);
275         emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));
276
277         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
278         {
279                 return false;
280         }
281
282         emit messageLogged("\n-------------------------------\n");
283         
284         args.clear();
285         args << QDir::toNativeSeparators(outputFile);
286
287         if(!metaInfo.title().isEmpty()) args << QString("-meta:title=%1").arg(cleanTag(metaInfo.title()));
288         if(!metaInfo.artist().isEmpty()) args << QString("-meta:artist=%1").arg(cleanTag(metaInfo.artist()));
289         if(!metaInfo.album().isEmpty()) args << QString("-meta:album=%1").arg(cleanTag(metaInfo.album()));
290         if(!metaInfo.genre().isEmpty()) args << QString("-meta:genre=%1").arg(cleanTag(metaInfo.genre()));
291         if(!metaInfo.comment().isEmpty()) args << QString("-meta:comment=%1").arg(cleanTag(metaInfo.comment()));
292         if(metaInfo.year()) args << QString("-meta:year=%1").arg(QString::number(metaInfo.year()));
293         if(metaInfo.position()) args << QString("-meta:track=%1").arg(QString::number(metaInfo.position()));
294         if(!metaInfo.cover().isEmpty()) args << QString("-add-cover:%1:%2").arg("front", metaInfo.cover());
295         
296         if(!startProcess(process, m_binary_tag, args))
297         {
298                 return false;
299         }
300
301         bTimeout = false;
302
303         while(process.state() != QProcess::NotRunning)
304         {
305                 if(*abortFlag)
306                 {
307                         process.kill();
308                         bAborted = true;
309                         emit messageLogged("\nABORTED BY USER !!!");
310                         break;
311                 }
312                 process.waitForReadyRead(m_processTimeoutInterval);
313                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
314                 {
315                         process.kill();
316                         qWarning("NeroAacTag process timed out <-- killing!");
317                         emit messageLogged("\nPROCESS TIMEOUT !!!");
318                         bTimeout = true;
319                         break;
320                 }
321                 while(process.bytesAvailable() > 0)
322                 {
323                         QByteArray line = process.readLine();
324                         QString text = QString::fromUtf8(line.constData()).simplified();
325                         if(!text.isEmpty())
326                         {
327                                 emit messageLogged(text);
328                         }
329                 }
330         }
331
332         process.waitForFinished();
333         if(process.state() != QProcess::NotRunning)
334         {
335                 process.kill();
336                 process.waitForFinished(-1);
337         }
338                 
339         emit messageLogged(QString().sprintf("\nExited with code: 0x%04X", process.exitCode()));
340
341         if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS)
342         {
343                 return false;
344         }
345
346         return true;
347 }
348
349 QString AACEncoder::extension(void)
350 {
351         return "mp4";
352 }
353
354 bool AACEncoder::isFormatSupported(const QString &containerType, const QString &containerProfile, const QString &formatType, const QString &formatProfile, const QString &formatVersion)
355 {
356         if(containerType.compare("Wave", Qt::CaseInsensitive) == 0)
357         {
358                 if(formatType.compare("PCM", Qt::CaseInsensitive) == 0)
359                 {
360                         return true;
361                 }
362         }
363
364         return false;
365 }
366
367 void AACEncoder::setProfile(int profile)
368 {
369         m_configProfile = profile;
370 }
371
372 void AACEncoder::setEnable2Pass(bool enabled)
373 {
374         m_configEnable2Pass = enabled;
375 }
376
377 const bool AACEncoder::needsTimingInfo(void)
378 {
379         return true;
380 }
381
382 const AbstractEncoderInfo *AACEncoder::getEncoderInfo(void)
383 {
384         return &g_aacEncoderInfo;
385 }