OSDN Git Service

Update MediaInfo binaries to v0.7.53 (2012-01-24), compiled with ICL 12.1.6 and MSVC...
[lamexp/LameXP.git] / src / Thread_CueSplitter.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 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 "Thread_CueSplitter.h"
23
24 #include "Global.h"
25 #include "LockedFile.h"
26 #include "Model_AudioFile.h"
27 #include "Model_CueSheet.h"
28 #include "Registry_Decoder.h"
29 #include "Decoder_Abstract.h"
30
31 #include <QDir>
32 #include <QFileInfo>
33 #include <QProcess>
34 #include <QDate>
35 #include <QTime>
36 #include <QDebug>
37
38 #include <math.h>
39 #include <float.h>
40 #include <limits>
41
42 ////////////////////////////////////////////////////////////
43 // Constructor
44 ////////////////////////////////////////////////////////////
45
46 CueSplitter::CueSplitter(const QString &outputDir, const QString &baseName, CueSheetModel *model, const QList<AudioFileModel> &inputFilesInfo)
47 :
48         m_model(model),
49         m_outputDir(outputDir),
50         m_baseName(baseName),
51         m_soxBin(lamexp_lookup_tool("sox.exe"))
52 {
53         if(m_soxBin.isEmpty())
54         {
55                 qFatal("Invalid path to SoX binary. Tool not initialized properly.");
56         }
57
58         m_decompressedFiles.clear();
59         m_tempFiles.clear();
60
61         qDebug("\n[CueSplitter]");
62
63         int nInputFiles = inputFilesInfo.count();
64         for(int i = 0; i < nInputFiles; i++)
65         {
66                 m_inputFilesInfo.insert(inputFilesInfo[i].filePath(), inputFilesInfo[i]);
67                 qDebug("File %02d: <%s>", i, inputFilesInfo[i].filePath().toUtf8().constData());
68         }
69         
70         qDebug("All input files added.");
71         m_bSuccess = false;
72 }
73
74 CueSplitter::~CueSplitter(void)
75 {
76         while(!m_tempFiles.isEmpty())
77         {
78                 lamexp_remove_file(m_tempFiles.takeFirst());
79         }
80 }
81
82 ////////////////////////////////////////////////////////////
83 // Thread Main
84 ////////////////////////////////////////////////////////////
85
86 void CueSplitter::run()
87 {
88         m_bSuccess = false;
89         m_bAborted = false;
90         m_abortFlag = false;
91         m_nTracksSuccess = 0;
92         m_nTracksSkipped = 0;
93         m_decompressedFiles.clear();
94         m_activeFile.clear();
95         
96         if(!QDir(m_outputDir).exists())
97         {
98                 qWarning("Output directory \"%s\" does not exist!", m_outputDir.toUtf8().constData());
99                 return;
100         }
101         
102         QStringList inputFileList = m_inputFilesInfo.keys();
103         int nInputFiles = inputFileList.count();
104         
105         //Decompress all input files
106         for(int i = 0; i < nInputFiles; i++)
107         {
108                 AudioFileModel &inputFileInfo = m_inputFilesInfo[inputFileList.at(i)];
109                 if(inputFileInfo.formatContainerType().compare("Wave", Qt::CaseInsensitive) || inputFileInfo.formatAudioType().compare("PCM", Qt::CaseInsensitive))
110                 {
111                         AbstractDecoder *decoder = DecoderRegistry::lookup(inputFileInfo.formatContainerType(), inputFileInfo.formatContainerProfile(), inputFileInfo.formatAudioType(), inputFileInfo.formatAudioProfile(), inputFileInfo.formatAudioVersion());
112                         if(decoder)
113                         {
114                                 m_activeFile = shortName(QFileInfo(inputFileList.at(i)).fileName());
115                                 emit fileSelected(m_activeFile);
116                                 QString tempFile = QString("%1/~%2.wav").arg(m_outputDir, lamexp_rand_str());
117                                 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
118                                 if(decoder->decode(inputFileList.at(i), tempFile, &m_abortFlag))
119                                 {
120                                         m_decompressedFiles.insert(inputFileList.at(i), tempFile);
121                                         m_tempFiles.append(tempFile);
122                                 }
123                                 else
124                                 {
125                                         qWarning("Failed to decompress file: <%s>", inputFileList.at(i).toLatin1().constData());
126                                         lamexp_remove_file(tempFile);
127                                 }
128                                 m_activeFile.clear();
129                                 LAMEXP_DELETE(decoder);
130                         }
131                         else
132                         {
133                                 qWarning("Unsupported input file: <%s>", inputFileList.at(i).toLatin1().constData());
134                         }
135                 }
136                 else
137                 {
138                         m_decompressedFiles.insert(inputFileList.at(i), inputFileList.at(i));
139                 }
140                 if(m_abortFlag)
141                 {
142                         m_bAborted = true;
143                         qWarning("The user has requested to abort the process!");
144                         return;
145                 }
146         }
147
148         int nFiles = m_model->getFileCount();
149         QString albumPerformer = m_model->getAlbumPerformer();
150         QString albumTitle = m_model->getAlbumTitle();
151         QString albumGenre = m_model->getAlbumGenre();
152         unsigned int albumYear = m_model->getAlbumYear();
153
154         //Now split all files
155         for(int i = 0; i < nFiles; i++)
156         {
157                 int nTracks = m_model->getTrackCount(i);
158                 QString trackFile = m_model->getFileName(i);
159                 int maxProgress = 0;
160
161                 //Process all tracks
162                 for(int j = 0; j < nTracks; j++)
163                 {
164                         int trackNo = m_model->getTrackNo(i, j);
165                         double trackOffset = std::numeric_limits<double>::quiet_NaN();
166                         double trackLength = std::numeric_limits<double>::quiet_NaN();
167                         m_model->getTrackIndex(i, j, &trackOffset, &trackLength);
168                         
169                         if((trackNo < 0) || _isnan(trackOffset) || _isnan(trackLength))
170                         {
171                                 qWarning("Failed to fetch information for track #%d of file #%d!", j, i);
172                                 continue;
173                         }
174                         
175                         //Setup meta info
176                         AudioFileModel trackMetaInfo(QString().sprintf("cue://File%02d/Track%02d", i, j));
177                         trackMetaInfo.setFileName(m_model->getTrackTitle(i, j));
178                         trackMetaInfo.setFileArtist(m_model->getTrackPerformer(i, j));
179                         trackMetaInfo.setFileGenre(m_model->getTrackGenre(i, j));
180                         trackMetaInfo.setFileYear(m_model->getTrackYear(i, j));
181                         trackMetaInfo.setFilePosition(trackNo);
182                         
183                         //Apply album meta data on files
184                         if(trackMetaInfo.fileName().trimmed().isEmpty())
185                         {
186                                 trackMetaInfo.setFileName(QString().sprintf("Track %02d", trackNo));
187                         }
188                         if(!albumTitle.isEmpty())
189                         {
190                                 trackMetaInfo.setFileAlbum(albumTitle);
191                         }
192                         if(!albumPerformer.isEmpty() && trackMetaInfo.fileArtist().isEmpty())
193                         {
194                                 trackMetaInfo.setFileArtist(albumPerformer);
195                         }
196                         if(!albumGenre.isEmpty() && trackMetaInfo.fileGenre().isEmpty())
197                         {
198                                 trackMetaInfo.setFileGenre(albumGenre);
199                         }
200                         if((albumYear > 0) && (trackMetaInfo.fileYear() == 0))
201                         {
202                                 trackMetaInfo.setFileYear(albumYear);
203                         }
204                         if(_finite(trackLength))
205                         {
206                                 trackMetaInfo.setFileDuration(static_cast<unsigned int>(abs(trackLength)));
207                         }
208
209                         //Generate output file name
210                         QString trackTitle = trackMetaInfo.fileName().isEmpty() ? QString().sprintf("Track %02d", trackNo) : trackMetaInfo.fileName();
211                         QString outputFile = QString("%1/[%2] %3 - %4.wav").arg(m_outputDir, QString().sprintf("%02d", trackNo), lamexp_clean_filename(m_baseName), lamexp_clean_filename(trackTitle));
212                         for(int n = 2; QFileInfo(outputFile).exists(); n++)
213                         {
214                                 outputFile = QString("%1/[%2] %3 - %4 (%5).wav").arg(m_outputDir, QString().sprintf("%02d", trackNo), lamexp_clean_filename(m_baseName), lamexp_clean_filename(trackTitle), QString::number(n));
215                         }
216
217                         //Call split function
218                         emit fileSelected(shortName(QFileInfo(outputFile).fileName()));
219                         splitFile(outputFile,  trackNo, trackFile, trackOffset, trackLength, trackMetaInfo, maxProgress);
220
221                         if(m_abortFlag)
222                         {
223                                 m_bAborted = true;
224                                 qWarning("The user has requested to abort the process!");
225                                 return;
226                         }
227                 }
228         }
229
230         qDebug("All files were split.\n");
231         m_bSuccess = true;
232 }
233
234 ////////////////////////////////////////////////////////////
235 // Slots
236 ////////////////////////////////////////////////////////////
237
238 void CueSplitter::handleUpdate(int progress)
239 {
240         emit fileSelected(QString("%1 [%2%]").arg(m_activeFile, QString::number(progress)));
241 }
242
243 ////////////////////////////////////////////////////////////
244 // Privtae Functions
245 ////////////////////////////////////////////////////////////
246
247 void CueSplitter::splitFile(const QString &output, const int trackNo, const QString &file, const double offset, const double length, const AudioFileModel &metaInfo, int &maxProgress)
248 {
249         qDebug("[Track %02d]", trackNo);
250         qDebug("File: <%s>", file.toUtf8().constData());
251         qDebug("Offset: <%f> <%s>", offset, indexToString(offset).toLatin1().constData());
252         qDebug("Length: <%f> <%s>", length, indexToString(length).toLatin1().constData());
253         qDebug("Artist: <%s>", metaInfo.fileArtist().toUtf8().constData());
254         qDebug("Title: <%s>", metaInfo.fileName().toUtf8().constData());
255         
256         if(!m_decompressedFiles.contains(file))
257         {
258                 qWarning("Unknown or unsupported input file, skipping!");
259                 m_nTracksSkipped++;
260                 return;
261         }
262
263         QString baseName = shortName(QFileInfo(output).fileName());
264         QString decompressedInput = m_decompressedFiles[file];
265         qDebug("Input: <%s>", decompressedInput.toUtf8().constData());
266         
267         emit fileSelected(QString("%1 [%2%]").arg(baseName, QString::number(maxProgress)));
268
269         AudioFileModel outFileInfo(metaInfo);
270         outFileInfo.setFilePath(output);
271         outFileInfo.setFormatContainerType("Wave");
272         outFileInfo.setFormatAudioType("PCM");
273
274         QStringList args;
275         args << "-S" << "-V3";
276         args << "--guard" << "--temp" << ".";
277         args << QDir::toNativeSeparators(decompressedInput);
278         args << QDir::toNativeSeparators(output);
279         
280         //Add trim parameters, if needed
281         if(_finite(offset))
282         {
283                 args << "trim";
284                 args << indexToString(offset);
285                 
286                 if(_finite(length))
287                 {
288                         args << indexToString(length);
289                 }
290         }
291
292         QRegExp rxProgress("In:(\\d+)(\\.\\d+)*%", Qt::CaseInsensitive);
293         QRegExp rxChannels("Channels\\s*:\\s*(\\d+)", Qt::CaseInsensitive);
294         QRegExp rxSamplerate("Sample Rate\\s*:\\s*(\\d+)", Qt::CaseInsensitive);
295         QRegExp rxPrecision("Precision\\s*:\\s*(\\d+)-bit", Qt::CaseInsensitive);
296         QRegExp rxDuration("Duration\\s*:\\s*(\\d\\d):(\\d\\d):(\\d\\d).(\\d\\d)", Qt::CaseInsensitive);
297
298         QProcess process;
299         process.setProcessChannelMode(QProcess::MergedChannels);
300         process.setReadChannel(QProcess::StandardOutput);
301         process.setWorkingDirectory(m_outputDir);
302         process.start(m_soxBin, args);
303                 
304         if(!process.waitForStarted())
305         {
306                 qWarning("SoX process failed to create!");
307                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
308                 process.kill();
309                 process.waitForFinished(-1);
310                 m_nTracksSkipped++;
311                 return;
312         }
313
314         while(process.state() != QProcess::NotRunning)
315         {
316                 if(m_abortFlag)
317                 {
318                         process.kill();
319                         qWarning("Process was aborted on user request!");
320                         break;
321                 }
322                 process.waitForReadyRead(m_processTimeoutInterval);
323                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
324                 {
325                         process.kill();
326                         qWarning("SoX process timed out <-- killing!");
327                         break;
328                 }
329                 while(process.bytesAvailable() > 0)
330                 {
331                         QByteArray line = process.readLine();
332                         QString text = QString::fromUtf8(line.constData()).simplified();
333                         if(rxProgress.lastIndexIn(text) >= 0)
334                         {
335                                 bool ok = false;
336                                 int progress = rxProgress.cap(1).toInt(&ok);
337                                 if(ok)
338                                 {
339                                         maxProgress = qMax(maxProgress, progress);
340                                         emit fileSelected(QString("%1 [%2%]").arg(baseName, QString::number(maxProgress)));
341                                 }
342                         }
343                         else if(rxChannels.lastIndexIn(text) >= 0)
344                         {
345                                 bool ok = false;
346                                 unsigned int channels = rxChannels.cap(1).toUInt(&ok);
347                                 if(ok) outFileInfo.setFormatAudioChannels(channels);
348                         }
349                         else if(rxSamplerate.lastIndexIn(text) >= 0)
350                         {
351                                 bool ok = false;
352                                 unsigned int samplerate = rxSamplerate.cap(1).toUInt(&ok);
353                                 if(ok) outFileInfo.setFormatAudioSamplerate(samplerate);
354                         }
355                         else if(rxPrecision.lastIndexIn(text) >= 0)
356                         {
357                                 bool ok = false;
358                                 unsigned int precision = rxPrecision.cap(1).toUInt(&ok);
359                                 if(ok) outFileInfo.setFormatAudioBitdepth(precision);
360                         }
361                         else if(rxDuration.lastIndexIn(text) >= 0)
362                         {
363                                 bool ok1 = false, ok2 = false, ok3 = false;
364                                 unsigned int hh = rxDuration.cap(1).toUInt(&ok1);
365                                 unsigned int mm = rxDuration.cap(2).toUInt(&ok2);
366                                 unsigned int ss = rxDuration.cap(3).toUInt(&ok3);
367                                 if(ok1 && ok2 && ok3)
368                                 {
369                                         unsigned intputLen = (hh * 3600) + (mm * 60) + ss;
370                                         if(length == std::numeric_limits<double>::infinity())
371                                         {
372                                                 qDebug("Duration updated from SoX info!");
373                                                 int duration = intputLen - static_cast<int>(floor(offset + 0.5));
374                                                 if(duration < 0) qWarning("Track is out of bounds: Track offset exceeds input file duration!");
375                                                 outFileInfo.setFileDuration(qMax(0, duration));
376                                         }
377                                         else
378                                         {
379                                                 unsigned int trackEnd = static_cast<unsigned int>(floor(offset + 0.5)) + static_cast<unsigned int>(floor(length + 0.5));
380                                                 if(trackEnd > intputLen) qWarning("Track is out of bounds: End of track exceeds input file duration!");
381                                         }
382                                 }
383                         }
384                 }
385         }
386
387         process.waitForFinished();
388         if(process.state() != QProcess::NotRunning)
389         {
390                 process.kill();
391                 process.waitForFinished(-1);
392         }
393
394         if(process.exitCode() != EXIT_SUCCESS || QFileInfo(output).size() == 0)
395         {
396                 qWarning("Splitting has failed !!!");
397                 m_nTracksSkipped++;
398                 return;
399         }
400
401         emit fileSplit(outFileInfo);
402         m_nTracksSuccess++;
403 }
404
405 QString CueSplitter::indexToString(const double index) const
406 {
407         if(!_finite(index) || (index < 0.0) || (index > 86400.0))
408         {
409                 return QString();
410         }
411         
412         QTime time = QTime().addMSecs(static_cast<int>(floor(0.5 + (index * 1000.0))));
413         return time.toString(time.hour() ? "H:mm:ss.zzz" : "m:ss.zzz");
414 }
415
416 QString CueSplitter::shortName(const QString &longName) const
417 {
418         static const int maxLen = 54;
419         
420         if(longName.length() > maxLen)
421         {
422                 return QString("%1...%2").arg(longName.left(maxLen/2).trimmed(), longName.right(maxLen/2).trimmed());
423         }
424
425         return longName;
426 }
427
428 ////////////////////////////////////////////////////////////
429 // EVENTS
430 ////////////////////////////////////////////////////////////
431
432 /*NONE*/