1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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.
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.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Thread_CueSplitter.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"
42 ////////////////////////////////////////////////////////////
44 ////////////////////////////////////////////////////////////
46 CueSplitter::CueSplitter(const QString
&outputDir
, const QString
&baseName
, CueSheetModel
*model
, const QList
<AudioFileModel
> &inputFilesInfo
)
49 m_outputDir(outputDir
),
51 m_soxBin(lamexp_lookup_tool("sox.exe"))
53 if(m_soxBin
.isEmpty())
55 qFatal("Invalid path to SoX binary. Tool not initialized properly.");
58 m_decompressedFiles
.clear();
61 qDebug("\n[CueSplitter]");
63 int nInputFiles
= inputFilesInfo
.count();
64 for(int i
= 0; i
< nInputFiles
; i
++)
66 m_inputFilesInfo
.insert(inputFilesInfo
[i
].filePath(), inputFilesInfo
[i
]);
67 qDebug("File %02d: <%s>", i
, inputFilesInfo
[i
].filePath().toUtf8().constData());
70 qDebug("All input files added.");
74 CueSplitter::~CueSplitter(void)
76 while(!m_tempFiles
.isEmpty())
78 lamexp_remove_file(m_tempFiles
.takeFirst());
82 ////////////////////////////////////////////////////////////
84 ////////////////////////////////////////////////////////////
86 void CueSplitter::run()
93 m_decompressedFiles
.clear();
96 if(!QDir(m_outputDir
).exists())
98 qWarning("Output directory \"%s\" does not exist!", m_outputDir
.toUtf8().constData());
102 QStringList inputFileList
= m_inputFilesInfo
.keys();
103 int nInputFiles
= inputFileList
.count();
105 //Decompress all input files
106 for(int i
= 0; i
< nInputFiles
; i
++)
108 AudioFileModel
&inputFileInfo
= m_inputFilesInfo
[inputFileList
.at(i
)];
109 if(inputFileInfo
.formatContainerType().compare("Wave", Qt::CaseInsensitive
) || inputFileInfo
.formatAudioType().compare("PCM", Qt::CaseInsensitive
))
111 AbstractDecoder
*decoder
= DecoderRegistry::lookup(inputFileInfo
.formatContainerType(), inputFileInfo
.formatContainerProfile(), inputFileInfo
.formatAudioType(), inputFileInfo
.formatAudioProfile(), inputFileInfo
.formatAudioVersion());
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
))
120 m_decompressedFiles
.insert(inputFileList
.at(i
), tempFile
);
121 m_tempFiles
.append(tempFile
);
125 qWarning("Failed to decompress file: <%s>", inputFileList
.at(i
).toLatin1().constData());
126 lamexp_remove_file(tempFile
);
128 m_activeFile
.clear();
129 LAMEXP_DELETE(decoder
);
133 qWarning("Unsupported input file: <%s>", inputFileList
.at(i
).toLatin1().constData());
138 m_decompressedFiles
.insert(inputFileList
.at(i
), inputFileList
.at(i
));
143 qWarning("The user has requested to abort the process!");
148 int nFiles
= m_model
->getFileCount();
149 QString albumPerformer
= m_model
->getAlbumPerformer();
150 QString albumTitle
= m_model
->getAlbumTitle();
152 //Now split all files
153 for(int i
= 0; i
< nFiles
; i
++)
155 int nTracks
= m_model
->getTrackCount(i
);
156 QString trackFile
= m_model
->getFileName(i
);
160 for(int j
= 0; j
< nTracks
; j
++)
162 int trackNo
= m_model
->getTrackNo(i
, j
);
163 double trackOffset
= std::numeric_limits
<double>::quiet_NaN();
164 double trackLength
= std::numeric_limits
<double>::quiet_NaN();
165 m_model
->getTrackIndex(i
, j
, &trackOffset
, &trackLength
);
167 if((trackNo
< 0) || _isnan(trackOffset
) || _isnan(trackLength
))
169 qWarning("Failed to fetch information for track #%d of file #%d!", j
, i
);
174 AudioFileModel
trackMetaInfo(QString().sprintf("cue://File%02d/Track%02d", i
, j
));
175 trackMetaInfo
.setFileName(m_model
->getTrackTitle(i
, j
));
176 trackMetaInfo
.setFileArtist(m_model
->getTrackPerformer(i
, j
));
177 trackMetaInfo
.setFilePosition(trackNo
);
179 if(!albumTitle
.isEmpty())
181 trackMetaInfo
.setFileAlbum(albumTitle
);
183 if(!albumPerformer
.isEmpty() && trackMetaInfo
.fileArtist().isEmpty())
185 trackMetaInfo
.setFileArtist(albumPerformer
);
187 if(_finite(trackLength
))
189 trackMetaInfo
.setFileDuration(static_cast<unsigned int>(abs(trackLength
)));
192 //Generate output file name
193 QString trackTitle
= trackMetaInfo
.fileName().isEmpty() ? QString().sprintf("Track %02d", trackNo
) : trackMetaInfo
.fileName();
194 QString outputFile
= QString("%1/[%2] %3 - %4.wav").arg(m_outputDir
, QString().sprintf("%02d", trackNo
), m_baseName
, trackTitle
);
195 for(int n
= 2; QFileInfo(outputFile
).exists(); n
++)
197 outputFile
= QString("%1/[%2] %3 - %4 (%5).wav").arg(m_outputDir
, QString().sprintf("%02d", trackNo
), m_baseName
, trackTitle
, QString::number(n
));
200 //Call split function
201 emit
fileSelected(shortName(QFileInfo(outputFile
).fileName()));
202 splitFile(outputFile
, trackNo
, trackFile
, trackOffset
, trackLength
, trackMetaInfo
, maxProgress
);
207 qWarning("The user has requested to abort the process!");
213 qDebug("All files were split.\n");
217 ////////////////////////////////////////////////////////////
219 ////////////////////////////////////////////////////////////
221 void CueSplitter::handleUpdate(int progress
)
223 emit
fileSelected(QString("%1 [%2%]").arg(m_activeFile
, QString::number(progress
)));
226 ////////////////////////////////////////////////////////////
228 ////////////////////////////////////////////////////////////
230 void CueSplitter::splitFile(const QString
&output
, const int trackNo
, const QString
&file
, const double offset
, const double length
, const AudioFileModel
&metaInfo
, int &maxProgress
)
232 qDebug("[Track %02d]", trackNo
);
233 qDebug("File: <%s>", file
.toUtf8().constData());
234 qDebug("Offset: <%f> <%s>", offset
, indexToString(offset
).toLatin1().constData());
235 qDebug("Length: <%f> <%s>", length
, indexToString(length
).toLatin1().constData());
236 qDebug("Artist: <%s>", metaInfo
.fileArtist().toUtf8().constData());
237 qDebug("Title: <%s>", metaInfo
.fileName().toUtf8().constData());
239 if(!m_decompressedFiles
.contains(file
))
241 qWarning("Unknown or unsupported input file, skipping!");
246 QString baseName
= shortName(QFileInfo(output
).fileName());
247 QString decompressedInput
= m_decompressedFiles
[file
];
248 qDebug("Input: <%s>", decompressedInput
.toUtf8().constData());
250 emit
fileSelected(QString("%1 [%2%]").arg(baseName
, QString::number(maxProgress
)));
252 AudioFileModel
outFileInfo(metaInfo
);
253 outFileInfo
.setFilePath(output
);
254 outFileInfo
.setFormatContainerType("Wave");
255 outFileInfo
.setFormatAudioType("PCM");
258 args
<< "-S" << "-V3";
259 args
<< "--guard" << "--temp" << ".";
260 args
<< QDir::toNativeSeparators(decompressedInput
);
261 args
<< QDir::toNativeSeparators(output
);
263 //Add trim parameters, if needed
267 args
<< indexToString(offset
);
271 args
<< indexToString(length
);
275 QRegExp
rxProgress("In:(\\d+)(\\.\\d+)*%", Qt::CaseInsensitive
);
276 QRegExp
rxChannels("Channels\\s*:\\s*(\\d+)", Qt::CaseInsensitive
);
277 QRegExp
rxSamplerate("Sample Rate\\s*:\\s*(\\d+)", Qt::CaseInsensitive
);
278 QRegExp
rxPrecision("Precision\\s*:\\s*(\\d+)-bit", Qt::CaseInsensitive
);
279 QRegExp
rxDuration("Duration\\s*:\\s*(\\d\\d):(\\d\\d):(\\d\\d).(\\d\\d)", Qt::CaseInsensitive
);
282 process
.setProcessChannelMode(QProcess::MergedChannels
);
283 process
.setReadChannel(QProcess::StandardOutput
);
284 process
.setWorkingDirectory(m_outputDir
);
285 process
.start(m_soxBin
, args
);
287 if(!process
.waitForStarted())
289 qWarning("SoX process failed to create!");
290 qWarning("Error message: \"%s\"\n", process
.errorString().toLatin1().constData());
292 process
.waitForFinished(-1);
297 while(process
.state() != QProcess::NotRunning
)
302 qWarning("Process was aborted on user request!");
305 process
.waitForReadyRead(m_processTimeoutInterval
);
306 if(!process
.bytesAvailable() && process
.state() == QProcess::Running
)
309 qWarning("SoX process timed out <-- killing!");
312 while(process
.bytesAvailable() > 0)
314 QByteArray line
= process
.readLine();
315 QString text
= QString::fromUtf8(line
.constData()).simplified();
316 if(rxProgress
.lastIndexIn(text
) >= 0)
319 int progress
= rxProgress
.cap(1).toInt(&ok
);
322 maxProgress
= max(maxProgress
, progress
);
323 emit
fileSelected(QString("%1 [%2%]").arg(baseName
, QString::number(maxProgress
)));
326 else if(rxChannels
.lastIndexIn(text
) >= 0)
329 unsigned int channels
= rxChannels
.cap(1).toUInt(&ok
);
330 if(ok
) outFileInfo
.setFormatAudioChannels(channels
);
332 else if(rxSamplerate
.lastIndexIn(text
) >= 0)
335 unsigned int samplerate
= rxSamplerate
.cap(1).toUInt(&ok
);
336 if(ok
) outFileInfo
.setFormatAudioSamplerate(samplerate
);
338 else if(rxPrecision
.lastIndexIn(text
) >= 0)
341 unsigned int precision
= rxPrecision
.cap(1).toUInt(&ok
);
342 if(ok
) outFileInfo
.setFormatAudioBitdepth(precision
);
344 else if(rxDuration
.lastIndexIn(text
) >= 0)
346 bool ok1
= false, ok2
= false, ok3
= false;
347 unsigned int hh
= rxDuration
.cap(1).toUInt(&ok1
);
348 unsigned int mm
= rxDuration
.cap(2).toUInt(&ok2
);
349 unsigned int ss
= rxDuration
.cap(3).toUInt(&ok3
);
350 if(ok1
&& ok2
&& ok3
)
352 unsigned intputLen
= (hh
* 3600) + (mm
* 60) + ss
;
353 if(length
== std::numeric_limits
<double>::infinity())
355 qDebug("Duration updated from SoX info!");
356 int duration
= intputLen
- static_cast<int>(floor(offset
+ 0.5));
357 if(duration
< 0) qWarning("Track is out of bounds: Track offset exceeds input file duration!");
358 outFileInfo
.setFileDuration(max(0, duration
));
362 unsigned int trackEnd
= static_cast<unsigned int>(floor(offset
+ 0.5)) + static_cast<unsigned int>(floor(length
+ 0.5));
363 if(trackEnd
> intputLen
) qWarning("Track is out of bounds: End of track exceeds input file duration!");
370 process
.waitForFinished();
371 if(process
.state() != QProcess::NotRunning
)
374 process
.waitForFinished(-1);
377 if(process
.exitStatus() != QProcess::NormalExit
|| QFileInfo(output
).size() == 0)
379 qWarning("Splitting has failed !!!");
384 emit
fileSplit(outFileInfo
);
388 QString
CueSplitter::indexToString(const double index
) const
390 if(!_finite(index
) || (index
< 0.0) || (index
> 86400.0))
395 QTime time
= QTime().addMSecs(static_cast<int>(floor(0.5 + (index
* 1000.0))));
396 return time
.toString(time
.hour() ? "H:mm:ss.zzz" : "m:ss.zzz");
399 QString
CueSplitter::shortName(const QString
&longName
) const
401 static const int maxLen
= 54;
403 if(longName
.length() > maxLen
)
405 return QString("%1...%2").arg(longName
.left(maxLen
/2).trimmed(), longName
.right(maxLen
/2).trimmed());
411 ////////////////////////////////////////////////////////////
413 ////////////////////////////////////////////////////////////