Updated Ukrainian translation.
[LameXP.git] / src / Thread_Process.cpp
blob864a29867ea411ff4f6c3fa6fd09835b618e3443
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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 "Registry_Decoder.h"
33 #include "Model_Settings.h"
35 #include <QUuid>
36 #include <QFileInfo>
37 #include <QDir>
38 #include <QMutex>
39 #include <QMutexLocker>
40 #include <QDate>
42 #include <limits.h>
43 #include <time.h>
44 #include <stdlib.h>
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 ////////////////////////////////////////////////////////////
52 // Constructor
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),
60 m_encoder(encoder),
61 m_jobId(QUuid::createUuid()),
62 m_prependRelativeSourcePath(prependRelativeSourcePath),
63 m_renamePattern("<BaseName>"),
64 m_aborted(false)
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 ////////////////////////////////////////////////////////////
93 // Thread Entry Point
94 ////////////////////////////////////////////////////////////
96 void ProcessThread::run()
98 try
100 processFile();
102 catch(...)
104 fflush(stdout);
105 fflush(stderr);
106 fprintf(stderr, "\nGURU MEDITATION !!!\n");
107 FatalAppExit(0, L"Unhandeled exception error, application will exit!");
108 TerminateProcess(GetCurrentProcess(), -1);
112 void ProcessThread::processFile()
114 m_aborted = false;
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);
128 return;
131 QString sourceFile = m_audioFile.filePath();
133 //Decode source file
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());
139 if(decoder)
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);
149 if(bSuccess)
151 sourceFile = tempFile;
152 handleMessage("\n-------------------------------\n");
155 else
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);
160 return;
164 //Check audio properties
165 if(bSuccess)
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
187 if(bSuccess)
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");
204 delete poFilter;
208 //Encode audio file
209 if(bSuccess)
211 m_currentStep = EncodingStep;
212 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
215 //Make sure output file exists
216 if(bSuccess)
218 QFileInfo fileInfo(outFileName);
219 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
222 QThread::msleep(500);
224 //Report result
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 ////////////////////////////////////////////////////////////
232 // SLOTS
233 ////////////////////////////////////////////////////////////
235 void ProcessThread::handleUpdate(int progress)
237 //printf("Progress: %d\n", progress);
239 switch(m_currentStep)
241 case EncodingStep:
242 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
243 break;
244 case FilteringStep:
245 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
246 break;
247 case DecodingStep:
248 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
249 break;
253 void ProcessThread::handleMessage(const QString &line)
255 emit processMessageLogged(m_jobId, line);
258 ////////////////////////////////////////////////////////////
259 // PRIVAE FUNCTIONS
260 ////////////////////////////////////////////////////////////
262 QString ProcessThread::generateOutFileName(void)
264 QMutexLocker lock(m_mutex_genFileName);
266 int n = 1;
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()));
272 return QString();
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()));
279 return QString();
281 else
283 readTest.close();
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()));
305 return QString();
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()));
313 return QString();
315 else
317 writeTest.close();
318 writeTest.remove();
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))
340 placeholder.close();
343 return outFileName;
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))
359 file.close();
362 m_tempFiles << tempFileName;
363 return 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
426 if(applyDownmixing)
428 unsigned int channels = m_audioFile.formatAudioChannels();
429 if((channels == 0) || (channels > 2))
431 m_filters.prepend(new DownmixFilter());
436 ////////////////////////////////////////////////////////////
437 // PUBLIC FUNCTIONS
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 ////////////////////////////////////////////////////////////
452 // EVENTS
453 ////////////////////////////////////////////////////////////
455 /*NONE*/