Version v4.05 is released!
[LameXP.git] / src / Thread_Process.cpp
blob5d5a31f79972d6843511ff1d5f6656ace905fec3
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 m_audioFile.setFormatContainerType(QString::fromLatin1("Wave"));
162 m_audioFile.setFormatAudioType(QString::fromLatin1("PCM"));
164 if(QFileInfo(sourceFile).size() >= 4294967296i64)
166 handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
169 handleMessage("\n-------------------------------\n");
172 else
174 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()));
175 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
176 emit processStateFinished(m_jobId, outFileName, false);
177 return;
181 //------------------------------------
182 //Update audio properties after decode
183 //------------------------------------
184 if(bSuccess && !m_aborted && IS_WAVE(m_audioFile))
186 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
188 m_currentStep = AnalyzeStep;
189 bSuccess = m_propDetect->detect(sourceFile, &m_audioFile, &m_aborted);
191 if(bSuccess)
193 handleMessage("\n-------------------------------\n");
195 //Do we need to take care if Stereo downmix?
196 if(m_encoder->supportedChannelCount())
198 insertDownmixFilter();
201 //Do we need to take care of downsampling the input?
202 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths())
204 insertDownsampleFilter();
210 //-----------------------
211 //Apply all audio filters
212 //-----------------------
213 if(bSuccess)
215 while(!m_filters.isEmpty() && !m_aborted)
217 QString tempFile = generateTempFileName();
218 AbstractFilter *poFilter = m_filters.takeFirst();
219 m_currentStep = FilteringStep;
221 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
222 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
224 if(poFilter->apply(sourceFile, tempFile, &m_audioFile, &m_aborted))
226 sourceFile = tempFile;
229 handleMessage("\n-------------------------------\n");
230 delete poFilter;
234 //-----------------
235 //Encode audio file
236 //-----------------
237 if(bSuccess && !m_aborted)
239 m_currentStep = EncodingStep;
240 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
243 //Make sure output file exists
244 if(bSuccess && !m_aborted)
246 QFileInfo fileInfo(outFileName);
247 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
250 QThread::msleep(500);
252 //Report result
253 emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
254 emit processStateFinished(m_jobId, outFileName, bSuccess);
256 qDebug("Process thread is done.");
259 ////////////////////////////////////////////////////////////
260 // SLOTS
261 ////////////////////////////////////////////////////////////
263 void ProcessThread::handleUpdate(int progress)
265 //printf("Progress: %d\n", progress);
267 switch(m_currentStep)
269 case EncodingStep:
270 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
271 break;
272 case AnalyzeStep:
273 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
274 break;
275 case FilteringStep:
276 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
277 break;
278 case DecodingStep:
279 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
280 break;
284 void ProcessThread::handleMessage(const QString &line)
286 emit processMessageLogged(m_jobId, line);
289 ////////////////////////////////////////////////////////////
290 // PRIVAE FUNCTIONS
291 ////////////////////////////////////////////////////////////
293 QString ProcessThread::generateOutFileName(void)
295 QMutexLocker lock(m_mutex_genFileName);
297 int n = 1;
299 QFileInfo sourceFile(m_audioFile.filePath());
300 if(!sourceFile.exists() || !sourceFile.isFile())
302 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
303 return QString();
306 QFile readTest(sourceFile.canonicalFilePath());
307 if(!readTest.open(QIODevice::ReadOnly))
309 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
310 return QString();
312 else
314 readTest.close();
317 QString baseName = sourceFile.completeBaseName();
318 QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
320 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
322 QDir rootDir = sourceFile.dir();
323 while(!rootDir.isRoot())
325 if(!rootDir.cdUp()) break;
327 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
330 if(!targetDir.exists())
332 targetDir.mkpath(".");
333 if(!targetDir.exists())
335 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
336 return QString();
340 QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
341 if(!writeTest.open(QIODevice::ReadWrite))
343 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
344 return QString();
346 else
348 writeTest.close();
349 writeTest.remove();
352 QString fileName = m_renamePattern;
353 fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
354 fileName.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile.filePosition()), Qt::CaseInsensitive);
355 fileName.replace("<Title>", STRDEF(m_audioFile.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive);
356 fileName.replace("<Artist>", STRDEF(m_audioFile.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive);
357 fileName.replace("<Album>", STRDEF(m_audioFile.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive);
358 fileName.replace("<Year>", QString().sprintf("%04d", m_audioFile.fileYear()), Qt::CaseInsensitive);
359 fileName.replace("<Comment>", STRDEF(m_audioFile.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive);
360 fileName = lamexp_clean_filename(fileName).simplified();
362 QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
363 while(QFileInfo(outFileName).exists())
365 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
368 QFile placeholder(outFileName);
369 if(placeholder.open(QIODevice::WriteOnly))
371 placeholder.close();
374 return outFileName;
377 QString ProcessThread::generateTempFileName(void)
379 QMutexLocker lock(m_mutex_genFileName);
380 QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
382 while(QFileInfo(tempFileName).exists())
384 tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
387 QFile file(tempFileName);
388 if(file.open(QFile::ReadWrite))
390 file.close();
393 m_tempFiles << tempFileName;
394 return tempFileName;
397 void ProcessThread::insertDownsampleFilter(void)
399 int targetSampleRate = 0;
400 int targetBitDepth = 0;
402 /* Adjust sample rate */
403 if(m_encoder->supportedSamplerates() && m_audioFile.formatAudioSamplerate())
405 bool applyDownsampling = true;
407 //Check if downsampling filter is already in the chain
408 for(int i = 0; i < m_filters.count(); i++)
410 if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
412 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
413 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
414 applyDownsampling = false;
418 //Now determine the target sample rate, if required
419 if(applyDownsampling)
421 const unsigned int *supportedRates = m_encoder->supportedSamplerates();
422 const unsigned int inputRate = m_audioFile.formatAudioSamplerate();
423 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
425 //Find the most suitable supported sampling rate
426 for(int i = 0; supportedRates[i]; i++)
428 currentDiff = DIFF(inputRate, supportedRates[i]);
429 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestRate < supportedRates[i])))
431 bestRate = supportedRates[i];
432 minimumDiff = currentDiff;
433 if(!(minimumDiff > 0)) break;
437 if(bestRate != inputRate)
439 targetSampleRate = (bestRate != UINT_MAX) ? bestRate : supportedRates[0];
444 /* Adjust bit depth (word size) */
445 if(m_encoder->supportedBitdepths() && m_audioFile.formatAudioBitdepth())
447 const unsigned int inputBPS = m_audioFile.formatAudioBitdepth();
448 const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
450 bool bAdjustBitdepth = true;
452 //Is the input bit depth supported exactly? (inclduing IEEE Float)
453 for(int i = 0; supportedBPS[i]; i++)
455 if(supportedBPS[i] == inputBPS) bAdjustBitdepth = false;
458 if(bAdjustBitdepth)
460 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
461 const unsigned int originalBPS = (inputBPS == AudioFileModel::BITDEPTH_IEEE_FLOAT32) ? 32 : inputBPS;
463 //Find the most suitable supported bit depth
464 for(int i = 0; supportedBPS[i]; i++)
466 if(supportedBPS[i] == AudioFileModel::BITDEPTH_IEEE_FLOAT32) continue;
468 currentDiff = DIFF(originalBPS, supportedBPS[i]);
469 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBPS[i])))
471 bestBPS = supportedBPS[i];
472 minimumDiff = currentDiff;
473 if(!(minimumDiff > 0)) break;
477 if(bestBPS != originalBPS)
479 targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBPS[0];
484 /* Insert the filter */
485 if(targetSampleRate || targetBitDepth)
487 m_filters.append(new ResampleFilter(targetSampleRate, targetBitDepth));
491 void ProcessThread::insertDownmixFilter(void)
493 bool applyDownmixing = true;
495 //Check if downmixing filter is already in the chain
496 for(int i = 0; i < m_filters.count(); i++)
498 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
500 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
501 handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
502 applyDownmixing = false;
506 //Now add the downmixing filter, if needed
507 if(applyDownmixing)
509 bool requiresDownmix = true;
510 const unsigned int *supportedChannels = m_encoder->supportedChannelCount();
511 unsigned int channels = m_audioFile.formatAudioChannels();
513 for(int i = 0; supportedChannels[i]; i++)
515 if(supportedChannels[i] == channels)
517 requiresDownmix = false;
518 break;
522 if(requiresDownmix)
524 m_filters.append(new DownmixFilter());
529 ////////////////////////////////////////////////////////////
530 // PUBLIC FUNCTIONS
531 ////////////////////////////////////////////////////////////
533 void ProcessThread::addFilter(AbstractFilter *filter)
535 m_filters.append(filter);
538 void ProcessThread::setRenamePattern(const QString &pattern)
540 QString newPattern = pattern.simplified();
541 if(!newPattern.isEmpty()) m_renamePattern = newPattern;
544 ////////////////////////////////////////////////////////////
545 // EVENTS
546 ////////////////////////////////////////////////////////////
548 /*NONE*/