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_Process.h"
25 #include "Model_AudioFile.h"
26 #include "Model_Progress.h"
27 #include "Encoder_Abstract.h"
28 #include "Decoder_Abstract.h"
29 #include "Filter_Abstract.h"
30 #include "Filter_Downmix.h"
31 #include "Filter_Resample.h"
32 #include "Registry_Decoder.h"
33 #include "Model_Settings.h"
39 #include <QMutexLocker>
46 #define DIFF(X,Y) ((X > Y) ? (X-Y) : (Y-X))
47 #define STRDEF(STR,DEF) ((!STR.isEmpty()) ? STR : DEF)
49 QMutex
*ProcessThread::m_mutex_genFileName
= NULL
;
51 ////////////////////////////////////////////////////////////
53 ////////////////////////////////////////////////////////////
55 ProcessThread::ProcessThread(const AudioFileModel
&audioFile
, const QString
&outputDirectory
, const QString
&tempDirectory
, AbstractEncoder
*encoder
, const bool prependRelativeSourcePath
)
57 m_audioFile(audioFile
),
58 m_outputDirectory(outputDirectory
),
59 m_tempDirectory(tempDirectory
),
61 m_jobId(QUuid::createUuid()),
62 m_prependRelativeSourcePath(prependRelativeSourcePath
),
63 m_renamePattern("<BaseName>"),
66 if(m_mutex_genFileName
)
68 m_mutex_genFileName
= new QMutex
;
71 connect(m_encoder
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
72 connect(m_encoder
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
74 m_currentStep
= UnknownStep
;
77 ProcessThread::~ProcessThread(void)
79 while(!m_tempFiles
.isEmpty())
81 lamexp_remove_file(m_tempFiles
.takeFirst());
84 while(!m_filters
.isEmpty())
86 delete m_filters
.takeFirst();
89 LAMEXP_DELETE(m_encoder
);
92 ////////////////////////////////////////////////////////////
94 ////////////////////////////////////////////////////////////
96 void ProcessThread::run()
106 fprintf(stderr
, "\nGURU MEDITATION !!!\n");
107 FatalAppExit(0, L
"Unhandeled exception error, application will exit!");
108 TerminateProcess(GetCurrentProcess(), -1);
112 void ProcessThread::processFile()
115 bool bSuccess
= true;
117 qDebug("Process thread %s has started.", m_jobId
.toString().toLatin1().constData());
118 emit
processStateInitialized(m_jobId
, QFileInfo(m_audioFile
.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning
);
119 handleMessage(QString().sprintf("LameXP v%u.%02u (Build #%u), compiled on %s at %s", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build(), lamexp_version_date().toString(Qt::ISODate
).toLatin1().constData(), lamexp_version_time()));
120 handleMessage("\n-------------------------------\n");
122 //Generate output file name
123 QString outFileName
= generateOutFileName();
124 if(outFileName
.isEmpty())
126 emit
processStateChanged(m_jobId
, tr("Not found!"), ProgressModel::JobFailed
);
127 emit
processStateFinished(m_jobId
, outFileName
, false);
131 QString sourceFile
= m_audioFile
.filePath();
134 if(!m_filters
.isEmpty() || !m_encoder
->isFormatSupported(m_audioFile
.formatContainerType(), m_audioFile
.formatContainerProfile(), m_audioFile
.formatAudioType(), m_audioFile
.formatAudioProfile(), m_audioFile
.formatAudioVersion()))
136 m_currentStep
= DecodingStep
;
137 AbstractDecoder
*decoder
= DecoderRegistry::lookup(m_audioFile
.formatContainerType(), m_audioFile
.formatContainerProfile(), m_audioFile
.formatAudioType(), m_audioFile
.formatAudioProfile(), m_audioFile
.formatAudioVersion());
141 QString tempFile
= generateTempFileName();
143 connect(decoder
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
144 connect(decoder
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
146 bSuccess
= decoder
->decode(sourceFile
, tempFile
, &m_aborted
);
147 LAMEXP_DELETE(decoder
);
151 sourceFile
= tempFile
;
152 handleMessage("\n-------------------------------\n");
157 handleMessage(QString("%1\n%2\n\n%3\t%4\n%5\t%6").arg(tr("The format of this file is NOT supported:"), m_audioFile
.filePath(), tr("Container Format:"), m_audioFile
.formatContainerInfo(), tr("Audio Format:"), m_audioFile
.formatAudioCompressInfo()));
158 emit
processStateChanged(m_jobId
, tr("Unsupported!"), ProgressModel::JobFailed
);
159 emit
processStateFinished(m_jobId
, outFileName
, false);
164 //Check audio properties
167 //Do we need to take care of downsampling the input?
168 if(m_encoder
->supportedSamplerates())
170 insertDownsampleFilter();
173 //Do we need to change the bits per sample of the input?
174 if(m_encoder
->supportedBitdepths())
176 insertBitdepthFilter();
179 //Do we need Stereo downmix?
180 if(m_encoder
->requiresDownmix())
182 insertDownmixFilter();
186 //Apply all audio filters
189 while(!m_filters
.isEmpty())
191 QString tempFile
= generateTempFileName();
192 AbstractFilter
*poFilter
= m_filters
.takeFirst();
193 m_currentStep
= FilteringStep
;
195 connect(poFilter
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
196 connect(poFilter
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
198 if(poFilter
->apply(sourceFile
, tempFile
, &m_aborted
))
200 sourceFile
= tempFile
;
203 handleMessage("\n-------------------------------\n");
211 m_currentStep
= EncodingStep
;
212 bSuccess
= m_encoder
->encode(sourceFile
, m_audioFile
, outFileName
, &m_aborted
);
215 //Make sure output file exists
218 QFileInfo
fileInfo(outFileName
);
219 bSuccess
= fileInfo
.exists() && fileInfo
.isFile() && (fileInfo
.size() > 0);
222 QThread::msleep(500);
225 emit
processStateChanged(m_jobId
, (bSuccess
? tr("Done.") : (m_aborted
? tr("Aborted!") : tr("Failed!"))), (bSuccess
? ProgressModel::JobComplete
: ProgressModel::JobFailed
));
226 emit
processStateFinished(m_jobId
, outFileName
, bSuccess
);
228 qDebug("Process thread is done.");
231 ////////////////////////////////////////////////////////////
233 ////////////////////////////////////////////////////////////
235 void ProcessThread::handleUpdate(int progress
)
237 //printf("Progress: %d\n", progress);
239 switch(m_currentStep
)
242 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress
)), ProgressModel::JobRunning
);
245 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress
)), ProgressModel::JobRunning
);
248 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress
)), ProgressModel::JobRunning
);
253 void ProcessThread::handleMessage(const QString
&line
)
255 emit
processMessageLogged(m_jobId
, line
);
258 ////////////////////////////////////////////////////////////
260 ////////////////////////////////////////////////////////////
262 QString
ProcessThread::generateOutFileName(void)
264 QMutexLocker
lock(m_mutex_genFileName
);
268 QFileInfo
sourceFile(m_audioFile
.filePath());
269 if(!sourceFile
.exists() || !sourceFile
.isFile())
271 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile
.absoluteFilePath()));
275 QFile
readTest(sourceFile
.canonicalFilePath());
276 if(!readTest
.open(QIODevice::ReadOnly
))
278 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest
.fileName()));
286 QString baseName
= sourceFile
.completeBaseName();
287 QDir
targetDir(m_outputDirectory
.isEmpty() ? sourceFile
.canonicalPath() : m_outputDirectory
);
289 if(m_prependRelativeSourcePath
&& !m_outputDirectory
.isEmpty())
291 QDir rootDir
= sourceFile
.dir();
292 while(!rootDir
.isRoot())
294 if(!rootDir
.cdUp()) break;
296 targetDir
.setPath(QString("%1/%2").arg(targetDir
.absolutePath(), QFileInfo(rootDir
.relativeFilePath(sourceFile
.canonicalFilePath())).path()));
299 if(!targetDir
.exists())
301 targetDir
.mkpath(".");
302 if(!targetDir
.exists())
304 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir
.absolutePath()));
309 QFile
writeTest(QString("%1/.%2").arg(targetDir
.canonicalPath(), lamexp_rand_str()));
310 if(!writeTest
.open(QIODevice::ReadWrite
))
312 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir
.absolutePath()));
321 QString fileName
= m_renamePattern
;
322 fileName
.replace("<BaseName>", STRDEF(baseName
, tr("Unknown File Name")), Qt::CaseInsensitive
);
323 fileName
.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile
.filePosition()), Qt::CaseInsensitive
);
324 fileName
.replace("<Title>", STRDEF(m_audioFile
.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive
);
325 fileName
.replace("<Artist>", STRDEF(m_audioFile
.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive
);
326 fileName
.replace("<Album>", STRDEF(m_audioFile
.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive
);
327 fileName
.replace("<Year>", QString().sprintf("%04d", m_audioFile
.fileYear()), Qt::CaseInsensitive
);
328 fileName
.replace("<Comment>", STRDEF(m_audioFile
.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive
);
329 fileName
= lamexp_clean_filename(fileName
).simplified();
331 QString outFileName
= QString("%1/%2.%3").arg(targetDir
.canonicalPath(), fileName
, m_encoder
->extension());
332 while(QFileInfo(outFileName
).exists())
334 outFileName
= QString("%1/%2 (%3).%4").arg(targetDir
.canonicalPath(), fileName
, QString::number(++n
), m_encoder
->extension());
337 QFile
placeholder(outFileName
);
338 if(placeholder
.open(QIODevice::WriteOnly
))
346 QString
ProcessThread::generateTempFileName(void)
348 QMutexLocker
lock(m_mutex_genFileName
);
349 QString tempFileName
= QString("%1/%2.wav").arg(m_tempDirectory
, lamexp_rand_str());
351 while(QFileInfo(tempFileName
).exists())
353 tempFileName
= QString("%1/%2.wav").arg(m_tempDirectory
, lamexp_rand_str());
356 QFile
file(tempFileName
);
357 if(file
.open(QFile::ReadWrite
))
362 m_tempFiles
<< tempFileName
;
366 void ProcessThread::insertDownsampleFilter(void)
368 bool applyDownsampling
= true;
370 //Check if downsampling filter is already in the chain
371 for(int i
= 0; i
< m_filters
.count(); i
++)
373 if(dynamic_cast<ResampleFilter
*>(m_filters
.at(i
)))
375 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
376 applyDownsampling
= false;
380 //Now add the downsampling filter, if needed
381 if(applyDownsampling
)
383 const unsigned int *supportedRates
= m_encoder
->supportedSamplerates();
384 const unsigned int inputRate
= m_audioFile
.formatAudioSamplerate();
385 unsigned int currentDiff
= UINT_MAX
, minimumDiff
= UINT_MAX
, bestRate
= UINT_MAX
;
387 //Find the most suitable supported sampling rate
388 for(int i
= 0; supportedRates
[i
]; i
++)
390 currentDiff
= DIFF(inputRate
, supportedRates
[i
]);
391 if(currentDiff
< minimumDiff
)
393 bestRate
= supportedRates
[i
];
394 minimumDiff
= currentDiff
;
395 if(!(minimumDiff
> 0)) break;
399 if(bestRate
!= inputRate
)
401 m_filters
.prepend(new ResampleFilter((bestRate
!= UINT_MAX
) ? bestRate
: supportedRates
[0]));
406 void ProcessThread::insertBitdepthFilter(void)
408 qFatal("ProcessThread::insertBitdepthFilter not implemented yet!");
411 void ProcessThread::insertDownmixFilter(void)
413 bool applyDownmixing
= true;
415 //Check if downmixing filter is already in the chain
416 for(int i
= 0; i
< m_filters
.count(); i
++)
418 if(dynamic_cast<DownmixFilter
*>(m_filters
.at(i
)))
420 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
421 applyDownmixing
= false;
425 //Now add the downmixing filter, if needed
428 unsigned int channels
= m_audioFile
.formatAudioChannels();
429 if((channels
== 0) || (channels
> 2))
431 m_filters
.prepend(new DownmixFilter());
436 ////////////////////////////////////////////////////////////
438 ////////////////////////////////////////////////////////////
440 void ProcessThread::addFilter(AbstractFilter
*filter
)
442 m_filters
.append(filter
);
445 void ProcessThread::setRenamePattern(const QString
&pattern
)
447 QString newPattern
= pattern
.simplified();
448 if(!newPattern
.isEmpty()) m_renamePattern
= newPattern
;
451 ////////////////////////////////////////////////////////////
453 ////////////////////////////////////////////////////////////