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))
48 QMutex *ProcessThread::m_mutex_genFileName = NULL;
50 ////////////////////////////////////////////////////////////
52 ////////////////////////////////////////////////////////////
54 ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, const QString &tempDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
56 m_audioFile(audioFile),
57 m_outputDirectory(outputDirectory),
58 m_tempDirectory(tempDirectory),
60 m_jobId(QUuid::createUuid()),
61 m_prependRelativeSourcePath(prependRelativeSourcePath),
64 if(m_mutex_genFileName)
66 m_mutex_genFileName = new QMutex;
69 connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
70 connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
72 m_currentStep = UnknownStep;
75 ProcessThread::~ProcessThread(void)
77 while(!m_tempFiles.isEmpty())
79 lamexp_remove_file(m_tempFiles.takeFirst());
82 while(!m_filters.isEmpty())
84 delete m_filters.takeFirst();
87 LAMEXP_DELETE(m_encoder);
90 ////////////////////////////////////////////////////////////
92 ////////////////////////////////////////////////////////////
94 void ProcessThread::run()
104 fprintf(stderr, "\nGURU MEDITATION !!!\n");
105 FatalAppExit(0, L"Unhandeled exception error, application will exit!");
106 TerminateProcess(GetCurrentProcess(), -1);
110 void ProcessThread::processFile()
113 bool bSuccess = true;
115 qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
116 emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
117 handleMessage(QString().sprintf("LameXP v%u.%02u (Build #%u), compiled at %s", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build(), lamexp_version_date().toString(Qt::ISODate).toLatin1().constData()));
118 handleMessage("\n-------------------------------\n");
120 //Generate output file name
121 QString outFileName = generateOutFileName();
122 if(outFileName.isEmpty())
124 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
125 emit processStateFinished(m_jobId, outFileName, false);
129 //Do we need to take of downsampling the input?
130 if(m_encoder->requiresDownsample())
132 insertDownsampleFilter();
135 //Do we need Stereo downmix?
136 if(m_audioFile.formatAudioChannels() > 2 && m_encoder->requiresDownmix())
138 m_filters.prepend(new DownmixFilter());
141 QString sourceFile = m_audioFile.filePath();
144 if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion()))
146 m_currentStep = DecodingStep;
147 AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
151 QString tempFile = generateTempFileName();
153 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
154 connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
156 bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
160 sourceFile = tempFile;
161 handleMessage("\n-------------------------------\n");
166 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()));
167 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
168 emit processStateFinished(m_jobId, outFileName, false);
174 while(!m_filters.isEmpty())
176 QString tempFile = generateTempFileName();
177 AbstractFilter *poFilter = m_filters.takeFirst();
181 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
182 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
184 m_currentStep = FilteringStep;
185 bSuccess = poFilter->apply(sourceFile, tempFile, &m_aborted);
189 sourceFile = tempFile;
190 handleMessage("\n-------------------------------\n");
200 m_currentStep = EncodingStep;
201 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
204 //Make sure output file exists
207 QFileInfo fileInfo(outFileName);
208 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
212 emit processStateChanged(m_jobId, (bSuccess ? tr("Done.") : (m_aborted ? tr("Aborted!") : tr("Failed!"))), (bSuccess ? ProgressModel::JobComplete : ProgressModel::JobFailed));
213 emit processStateFinished(m_jobId, outFileName, bSuccess);
215 qDebug("Process thread is done.");
218 ////////////////////////////////////////////////////////////
220 ////////////////////////////////////////////////////////////
222 void ProcessThread::handleUpdate(int progress)
224 switch(m_currentStep)
227 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
230 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
233 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
238 void ProcessThread::handleMessage(const QString &line)
240 emit processMessageLogged(m_jobId, line);
243 ////////////////////////////////////////////////////////////
245 ////////////////////////////////////////////////////////////
247 QString ProcessThread::generateOutFileName(void)
249 QMutexLocker lock(m_mutex_genFileName);
253 QFileInfo sourceFile(m_audioFile.filePath());
254 if(!sourceFile.exists() || !sourceFile.isFile())
256 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
260 QFile readTest(sourceFile.canonicalFilePath());
261 if(!readTest.open(QIODevice::ReadOnly))
263 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
271 QString baseName = sourceFile.completeBaseName();
272 QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
274 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
276 QDir rootDir = sourceFile.dir();
277 while(!rootDir.isRoot())
279 if(!rootDir.cdUp()) break;
281 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
284 if(!targetDir.exists())
286 targetDir.mkpath(".");
287 if(!targetDir.exists())
289 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
294 QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
295 if(!writeTest.open(QIODevice::ReadWrite))
297 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
306 QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), baseName, m_encoder->extension());
307 while(QFileInfo(outFileName).exists())
309 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), baseName, QString::number(++n), m_encoder->extension());
312 QFile placeholder(outFileName);
313 if(placeholder.open(QIODevice::WriteOnly))
321 QString ProcessThread::generateTempFileName(void)
323 QMutexLocker lock(m_mutex_genFileName);
324 QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
326 while(QFileInfo(tempFileName).exists())
328 tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
331 QFile file(tempFileName);
332 if(file.open(QFile::ReadWrite))
337 m_tempFiles << tempFileName;
341 void ProcessThread::insertDownsampleFilter(void)
343 bool applyDownsampling = true;
345 //Check if downsampling filter is already in the chain
346 for(int i = 0; i < m_filters.count(); i++)
348 if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
350 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
351 applyDownsampling = false;
355 //Now add the downsampling filter, if needed
356 if(applyDownsampling)
358 const unsigned int *supportedRates = m_encoder->requiresDownsample();
359 const unsigned int inputRate = m_audioFile.formatAudioSamplerate();
360 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
362 //Find the most suitable supported sampling rate
363 for(int i = 0; supportedRates[i]; i++)
365 currentDiff = DIFF(inputRate, supportedRates[i]);
366 if(currentDiff < minimumDiff)
368 bestRate = supportedRates[i];
369 minimumDiff = currentDiff;
370 if(!(minimumDiff > 0)) break;
374 if(bestRate != inputRate)
376 m_filters.prepend(new ResampleFilter((bestRate != UINT_MAX) ? bestRate : supportedRates[0]));
381 ////////////////////////////////////////////////////////////
383 ////////////////////////////////////////////////////////////
385 void ProcessThread::addFilter(AbstractFilter *filter)
387 m_filters.append(filter);
390 ////////////////////////////////////////////////////////////
392 ////////////////////////////////////////////////////////////