Bump version.
[LameXP.git] / src / Thread_Process.cpp
blobf260ca6f4f6a7b4ab08af4799db4462bec731417
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.
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"
24 #include "Global.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 "Tool_WaveProperties.h"
33 #include "Registry_Decoder.h"
34 #include "Model_Settings.h"
36 #include <QUuid>
37 #include <QFileInfo>
38 #include <QDir>
39 #include <QMutex>
40 #include <QMutexLocker>
41 #include <QDate>
43 #include <limits.h>
44 #include <time.h>
45 #include <stdlib.h>
47 #define DIFF(X,Y) ((X > Y) ? (X-Y) : (Y-X))
48 #define IS_WAVE(X) ((X.formatContainerType().compare("Wave", Qt::CaseInsensitive) == 0) && (X.formatAudioType().compare("PCM", Qt::CaseInsensitive) == 0))
49 #define STRDEF(STR,DEF) ((!STR.isEmpty()) ? STR : DEF)
51 QMutex *ProcessThread::m_mutex_genFileName = NULL;
53 ////////////////////////////////////////////////////////////
54 // Constructor
55 ////////////////////////////////////////////////////////////
57 ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, const QString &tempDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
59 m_audioFile(audioFile),
60 m_outputDirectory(outputDirectory),
61 m_tempDirectory(tempDirectory),
62 m_encoder(encoder),
63 m_jobId(QUuid::createUuid()),
64 m_prependRelativeSourcePath(prependRelativeSourcePath),
65 m_renamePattern("<BaseName>"),
66 m_aborted(false),
67 m_propDetect(new WaveProperties())
69 if(m_mutex_genFileName)
71 m_mutex_genFileName = new QMutex;
74 connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
75 connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
77 connect(m_propDetect, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
78 connect(m_propDetect, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
80 m_currentStep = UnknownStep;
83 ProcessThread::~ProcessThread(void)
85 while(!m_tempFiles.isEmpty())
87 lamexp_remove_file(m_tempFiles.takeFirst());
90 while(!m_filters.isEmpty())
92 delete m_filters.takeFirst();
95 LAMEXP_DELETE(m_encoder);
96 LAMEXP_DELETE(m_propDetect);
99 ////////////////////////////////////////////////////////////
100 // Thread Entry Point
101 ////////////////////////////////////////////////////////////
103 void ProcessThread::run()
107 processFile();
109 catch(...)
111 fflush(stdout);
112 fflush(stderr);
113 fprintf(stderr, "\nGURU MEDITATION !!!\n");
114 FatalAppExit(0, L"Unhandeled exception error, application will exit!");
115 TerminateProcess(GetCurrentProcess(), -1);
119 void ProcessThread::processFile()
121 m_aborted = false;
122 bool bSuccess = true;
124 qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
125 emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
126 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()));
127 handleMessage("\n-------------------------------\n");
129 //Generate output file name
130 QString outFileName = generateOutFileName();
131 if(outFileName.isEmpty())
133 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
134 emit processStateFinished(m_jobId, outFileName, false);
135 return;
138 QString sourceFile = m_audioFile.filePath();
140 //------------------
141 //Decode source file
142 //------------------
143 if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion()))
145 m_currentStep = DecodingStep;
146 AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
148 if(decoder)
150 QString tempFile = generateTempFileName();
152 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
153 connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
155 bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
156 LAMEXP_DELETE(decoder);
158 if(bSuccess)
160 sourceFile = tempFile;
161 handleMessage("\n-------------------------------\n");
162 m_audioFile.setFormatContainerType(QString::fromLatin1("Wave"));
163 m_audioFile.setFormatAudioType(QString::fromLatin1("PCM"));
166 else
168 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()));
169 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
170 emit processStateFinished(m_jobId, outFileName, false);
171 return;
175 //------------------------------------
176 //Update audio properties after decode
177 //------------------------------------
178 if(bSuccess && !m_aborted && IS_WAVE(m_audioFile))
180 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || !m_filters.isEmpty())
182 m_currentStep = AnalyzeStep;
183 bSuccess = m_propDetect->detect(sourceFile, &m_audioFile, &m_aborted);
185 if(bSuccess)
187 handleMessage("\n-------------------------------\n");
189 //Do we need to take care if Stereo downmix?
190 if(m_encoder->supportedChannelCount())
192 insertDownmixFilter();
195 //Do we need to take care of downsampling the input?
196 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths())
198 insertDownsampleFilter();
204 //-----------------------
205 //Apply all audio filters
206 //-----------------------
207 if(bSuccess)
209 while(!m_filters.isEmpty() && !m_aborted)
211 QString tempFile = generateTempFileName();
212 AbstractFilter *poFilter = m_filters.takeFirst();
213 m_currentStep = FilteringStep;
215 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
216 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
218 if(poFilter->apply(sourceFile, tempFile, &m_audioFile, &m_aborted))
220 sourceFile = tempFile;
223 handleMessage("\n-------------------------------\n");
224 delete poFilter;
228 //-----------------
229 //Encode audio file
230 //-----------------
231 if(bSuccess && !m_aborted)
233 m_currentStep = EncodingStep;
234 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
237 //Make sure output file exists
238 if(bSuccess && !m_aborted)
240 QFileInfo fileInfo(outFileName);
241 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
244 QThread::msleep(500);
246 //Report result
247 emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
248 emit processStateFinished(m_jobId, outFileName, bSuccess);
250 qDebug("Process thread is done.");
253 ////////////////////////////////////////////////////////////
254 // SLOTS
255 ////////////////////////////////////////////////////////////
257 void ProcessThread::handleUpdate(int progress)
259 //printf("Progress: %d\n", progress);
261 switch(m_currentStep)
263 case EncodingStep:
264 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
265 break;
266 case AnalyzeStep:
267 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
268 break;
269 case FilteringStep:
270 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
271 break;
272 case DecodingStep:
273 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
274 break;
278 void ProcessThread::handleMessage(const QString &line)
280 emit processMessageLogged(m_jobId, line);
283 ////////////////////////////////////////////////////////////
284 // PRIVAE FUNCTIONS
285 ////////////////////////////////////////////////////////////
287 QString ProcessThread::generateOutFileName(void)
289 QMutexLocker lock(m_mutex_genFileName);
291 int n = 1;
293 QFileInfo sourceFile(m_audioFile.filePath());
294 if(!sourceFile.exists() || !sourceFile.isFile())
296 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
297 return QString();
300 QFile readTest(sourceFile.canonicalFilePath());
301 if(!readTest.open(QIODevice::ReadOnly))
303 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
304 return QString();
306 else
308 readTest.close();
311 QString baseName = sourceFile.completeBaseName();
312 QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
314 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
316 QDir rootDir = sourceFile.dir();
317 while(!rootDir.isRoot())
319 if(!rootDir.cdUp()) break;
321 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
324 if(!targetDir.exists())
326 targetDir.mkpath(".");
327 if(!targetDir.exists())
329 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
330 return QString();
334 QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
335 if(!writeTest.open(QIODevice::ReadWrite))
337 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
338 return QString();
340 else
342 writeTest.close();
343 writeTest.remove();
346 QString fileName = m_renamePattern;
347 fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
348 fileName.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile.filePosition()), Qt::CaseInsensitive);
349 fileName.replace("<Title>", STRDEF(m_audioFile.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive);
350 fileName.replace("<Artist>", STRDEF(m_audioFile.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive);
351 fileName.replace("<Album>", STRDEF(m_audioFile.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive);
352 fileName.replace("<Year>", QString().sprintf("%04d", m_audioFile.fileYear()), Qt::CaseInsensitive);
353 fileName.replace("<Comment>", STRDEF(m_audioFile.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive);
354 fileName = lamexp_clean_filename(fileName).simplified();
356 QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
357 while(QFileInfo(outFileName).exists())
359 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
362 QFile placeholder(outFileName);
363 if(placeholder.open(QIODevice::WriteOnly))
365 placeholder.close();
368 return outFileName;
371 QString ProcessThread::generateTempFileName(void)
373 QMutexLocker lock(m_mutex_genFileName);
374 QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
376 while(QFileInfo(tempFileName).exists())
378 tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
381 QFile file(tempFileName);
382 if(file.open(QFile::ReadWrite))
384 file.close();
387 m_tempFiles << tempFileName;
388 return tempFileName;
391 void ProcessThread::insertDownsampleFilter(void)
393 int targetSampleRate = 0;
394 int targetBitDepth = 0;
396 /* Adjust sample rate */
397 if(m_encoder->supportedSamplerates() && m_audioFile.formatAudioSamplerate())
399 bool applyDownsampling = true;
401 //Check if downsampling filter is already in the chain
402 for(int i = 0; i < m_filters.count(); i++)
404 if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
406 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
407 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
408 applyDownsampling = false;
412 //Now determine the target sample rate, if required
413 if(applyDownsampling)
415 const unsigned int *supportedRates = m_encoder->supportedSamplerates();
416 const unsigned int inputRate = m_audioFile.formatAudioSamplerate();
417 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
419 //Find the most suitable supported sampling rate
420 for(int i = 0; supportedRates[i]; i++)
422 currentDiff = DIFF(inputRate, supportedRates[i]);
423 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestRate < supportedRates[i])))
425 bestRate = supportedRates[i];
426 minimumDiff = currentDiff;
427 if(!(minimumDiff > 0)) break;
431 if(bestRate != inputRate)
433 targetSampleRate = (bestRate != UINT_MAX) ? bestRate : supportedRates[0];
438 /* Adjust bit depth (word size) */
439 if(m_encoder->supportedBitdepths() && m_audioFile.formatAudioBitdepth())
441 const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
442 const unsigned int inputBPS = m_audioFile.formatAudioBitdepth();
443 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
445 //Find the most suitable supported bit depth
446 for(int i = 0; supportedBPS[i]; i++)
448 currentDiff = DIFF(inputBPS, supportedBPS[i]);
449 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBPS[i])))
451 bestBPS = supportedBPS[i];
452 minimumDiff = currentDiff;
453 if(!(minimumDiff > 0)) break;
457 if(bestBPS != inputBPS)
459 targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBPS[0];
463 /* Insert the filter */
464 if(targetSampleRate || targetBitDepth)
466 m_filters.append(new ResampleFilter(targetSampleRate, targetBitDepth));
470 void ProcessThread::insertDownmixFilter(void)
472 bool applyDownmixing = true;
474 //Check if downmixing filter is already in the chain
475 for(int i = 0; i < m_filters.count(); i++)
477 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
479 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
480 handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
481 applyDownmixing = false;
485 //Now add the downmixing filter, if needed
486 if(applyDownmixing)
488 bool requiresDownmix = true;
489 const unsigned int *supportedChannels = m_encoder->supportedChannelCount();
490 unsigned int channels = m_audioFile.formatAudioChannels();
492 for(int i = 0; supportedChannels[i]; i++)
494 if(supportedChannels[i] == channels)
496 requiresDownmix = false;
497 break;
501 if(requiresDownmix)
503 m_filters.append(new DownmixFilter());
508 ////////////////////////////////////////////////////////////
509 // PUBLIC FUNCTIONS
510 ////////////////////////////////////////////////////////////
512 void ProcessThread::addFilter(AbstractFilter *filter)
514 m_filters.append(filter);
517 void ProcessThread::setRenamePattern(const QString &pattern)
519 QString newPattern = pattern.simplified();
520 if(!newPattern.isEmpty()) m_renamePattern = newPattern;
523 ////////////////////////////////////////////////////////////
524 // EVENTS
525 ////////////////////////////////////////////////////////////
527 /*NONE*/