Updated Ukrainian translation.
[LameXP.git] / src / Thread_Process.cpp
blobc89643fa561dbc4d7cc80f51c133d77980d8506d
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_overwriteSkipExistingFile(false),
67 m_overwriteReplacesExisting(false),
68 m_aborted(false),
69 m_propDetect(new WaveProperties())
71 if(m_mutex_genFileName)
73 m_mutex_genFileName = new QMutex;
76 connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
77 connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
79 connect(m_propDetect, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
80 connect(m_propDetect, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
82 m_currentStep = UnknownStep;
85 ProcessThread::~ProcessThread(void)
87 while(!m_tempFiles.isEmpty())
89 lamexp_remove_file(m_tempFiles.takeFirst());
92 while(!m_filters.isEmpty())
94 delete m_filters.takeFirst();
97 LAMEXP_DELETE(m_encoder);
98 LAMEXP_DELETE(m_propDetect);
101 ////////////////////////////////////////////////////////////
102 // Thread Entry Point
103 ////////////////////////////////////////////////////////////
105 void ProcessThread::run()
109 processFile();
111 catch(...)
113 fflush(stdout);
114 fflush(stderr);
115 fprintf(stderr, "\nGURU MEDITATION !!!\n");
116 lamexp_fatal_exit(L"Unhandeled exception error, application will exit!");
120 void ProcessThread::processFile()
122 m_aborted = false;
123 bool bSuccess = true;
125 qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
126 emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
127 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()));
128 handleMessage("\n-------------------------------\n");
130 //Generate output file name
131 QString outFileName;
132 switch(generateOutFileName(outFileName))
134 case 1:
135 //File name generated successfully :-)
136 break;
137 case -1:
138 //File name already exists -> skipping!
139 emit processStateChanged(m_jobId, tr("Skipped."), ProgressModel::JobSkipped);
140 emit processStateFinished(m_jobId, outFileName, -1);
141 return;
142 default:
143 //File name could not be generated
144 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
145 emit processStateFinished(m_jobId, outFileName, 0);
146 return;
149 QString sourceFile = m_audioFile.filePath();
151 //------------------
152 //Decode source file
153 //------------------
154 if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion()))
156 m_currentStep = DecodingStep;
157 AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
159 if(decoder)
161 QString tempFile = generateTempFileName();
163 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
164 connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
166 bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
167 LAMEXP_DELETE(decoder);
169 if(bSuccess)
171 sourceFile = tempFile;
172 m_audioFile.setFormatContainerType(QString::fromLatin1("Wave"));
173 m_audioFile.setFormatAudioType(QString::fromLatin1("PCM"));
175 if(QFileInfo(sourceFile).size() >= 4294967296i64)
177 handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
180 handleMessage("\n-------------------------------\n");
183 else
185 if(QFileInfo(outFileName).exists() && (QFileInfo(outFileName).size() < 512)) QFile::remove(outFileName);
186 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()));
187 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
188 emit processStateFinished(m_jobId, outFileName, 0);
189 return;
193 //------------------------------------
194 //Update audio properties after decode
195 //------------------------------------
196 if(bSuccess && !m_aborted && IS_WAVE(m_audioFile))
198 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
200 m_currentStep = AnalyzeStep;
201 bSuccess = m_propDetect->detect(sourceFile, &m_audioFile, &m_aborted);
203 if(bSuccess)
205 handleMessage("\n-------------------------------\n");
207 //Do we need to take care if Stereo downmix?
208 if(m_encoder->supportedChannelCount())
210 insertDownmixFilter();
213 //Do we need to take care of downsampling the input?
214 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths())
216 insertDownsampleFilter();
222 //-----------------------
223 //Apply all audio filters
224 //-----------------------
225 if(bSuccess)
227 while(!m_filters.isEmpty() && !m_aborted)
229 QString tempFile = generateTempFileName();
230 AbstractFilter *poFilter = m_filters.takeFirst();
231 m_currentStep = FilteringStep;
233 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
234 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
236 if(poFilter->apply(sourceFile, tempFile, &m_audioFile, &m_aborted))
238 sourceFile = tempFile;
241 handleMessage("\n-------------------------------\n");
242 delete poFilter;
246 //-----------------
247 //Encode audio file
248 //-----------------
249 if(bSuccess && !m_aborted)
251 m_currentStep = EncodingStep;
252 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
255 //Clean-up
256 if((!bSuccess) || m_aborted)
258 QFileInfo fileInfo(outFileName);
259 if(fileInfo.exists() && (fileInfo.size() < 512))
261 QFile::remove(outFileName);
265 //Make sure output file exists
266 if(bSuccess && (!m_aborted))
268 QFileInfo fileInfo(outFileName);
269 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
272 QThread::msleep(125);
274 //Report result
275 emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
276 emit processStateFinished(m_jobId, outFileName, (bSuccess ? 1 : 0));
278 qDebug("Process thread is done.");
281 ////////////////////////////////////////////////////////////
282 // SLOTS
283 ////////////////////////////////////////////////////////////
285 void ProcessThread::handleUpdate(int progress)
287 //printf("Progress: %d\n", progress);
289 switch(m_currentStep)
291 case EncodingStep:
292 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
293 break;
294 case AnalyzeStep:
295 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
296 break;
297 case FilteringStep:
298 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
299 break;
300 case DecodingStep:
301 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
302 break;
306 void ProcessThread::handleMessage(const QString &line)
308 emit processMessageLogged(m_jobId, line);
311 ////////////////////////////////////////////////////////////
312 // PRIVAE FUNCTIONS
313 ////////////////////////////////////////////////////////////
315 int ProcessThread::generateOutFileName(QString &outFileName)
317 outFileName.clear();
319 QMutexLocker lock(m_mutex_genFileName);
321 //Make sure the source file exists
322 QFileInfo sourceFile(m_audioFile.filePath());
323 if(!sourceFile.exists() || !sourceFile.isFile())
325 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
326 return 0;
329 //Make sure the source file readable
330 QFile readTest(sourceFile.canonicalFilePath());
331 if(!readTest.open(QIODevice::ReadOnly))
333 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), QDir::toNativeSeparators(readTest.fileName())));
334 return 0;
336 else
338 readTest.close();
341 QString baseName = sourceFile.completeBaseName();
342 QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
344 //Prepend relative source file path?
345 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
347 QDir rootDir = sourceFile.dir();
348 while(!rootDir.isRoot())
350 if(!rootDir.cdUp()) break;
352 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
355 //Make sure output directory does exist
356 if(!targetDir.exists())
358 targetDir.mkpath(".");
359 if(!targetDir.exists())
361 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), QDir::toNativeSeparators(targetDir.absolutePath())));
362 return 0;
366 //Make sure that the output dir is writable
367 QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
368 if(!writeTest.open(QIODevice::ReadWrite))
370 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), QDir::toNativeSeparators(targetDir.absolutePath())));
371 return 0;
373 else
375 writeTest.close();
376 writeTest.remove();
379 //Apply rename pattern
380 QString fileName = m_renamePattern;
381 fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
382 fileName.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile.filePosition()), Qt::CaseInsensitive);
383 fileName.replace("<Title>", STRDEF(m_audioFile.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive);
384 fileName.replace("<Artist>", STRDEF(m_audioFile.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive);
385 fileName.replace("<Album>", STRDEF(m_audioFile.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive);
386 fileName.replace("<Year>", QString().sprintf("%04d", m_audioFile.fileYear()), Qt::CaseInsensitive);
387 fileName.replace("<Comment>", STRDEF(m_audioFile.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive);
388 fileName = lamexp_clean_filename(fileName).simplified();
390 //Generate full output path
391 outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
393 //Skip file, if target file exists (optional!)
394 if(m_overwriteSkipExistingFile && QFileInfo(outFileName).exists())
396 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to skip this file:"), QDir::toNativeSeparators(outFileName)));
397 handleMessage(tr("If you don't want existing files to be skipped, please change the overwrite mode!"));
398 return -1;
401 //Delete file, if target file exists (optional!)
402 if(m_overwriteReplacesExisting && QFileInfo(outFileName).exists())
404 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to delete existing file:"), QDir::toNativeSeparators(outFileName)));
405 bool bOkay = false;
406 for(int i = 0; i < 16; i++)
408 bOkay = QFile::remove(outFileName);
409 if(bOkay) break;
410 QThread::msleep(125);
412 if(QFileInfo(outFileName).exists() || (!bOkay))
414 handleMessage(QString("%1\n").arg(tr("Failed to delete existing target file, will save to another file name!")));
418 int n = 1;
420 //Generate final name
421 while(QFileInfo(outFileName).exists())
423 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
426 //Create placeholder
427 QFile placeholder(outFileName);
428 if(placeholder.open(QIODevice::WriteOnly))
430 placeholder.close();
433 return 1;
436 QString ProcessThread::generateTempFileName(void)
438 QMutexLocker lock(m_mutex_genFileName);
439 QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
441 while(QFileInfo(tempFileName).exists())
443 tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
446 QFile file(tempFileName);
447 if(file.open(QFile::ReadWrite))
449 file.close();
452 m_tempFiles << tempFileName;
453 return tempFileName;
456 void ProcessThread::insertDownsampleFilter(void)
458 int targetSampleRate = 0;
459 int targetBitDepth = 0;
461 /* Adjust sample rate */
462 if(m_encoder->supportedSamplerates() && m_audioFile.formatAudioSamplerate())
464 bool applyDownsampling = true;
466 //Check if downsampling filter is already in the chain
467 for(int i = 0; i < m_filters.count(); i++)
469 if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
471 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
472 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
473 applyDownsampling = false;
477 //Now determine the target sample rate, if required
478 if(applyDownsampling)
480 const unsigned int *supportedRates = m_encoder->supportedSamplerates();
481 const unsigned int inputRate = m_audioFile.formatAudioSamplerate();
482 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
484 //Find the most suitable supported sampling rate
485 for(int i = 0; supportedRates[i]; i++)
487 currentDiff = DIFF(inputRate, supportedRates[i]);
488 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestRate < supportedRates[i])))
490 bestRate = supportedRates[i];
491 minimumDiff = currentDiff;
492 if(!(minimumDiff > 0)) break;
496 if(bestRate != inputRate)
498 targetSampleRate = (bestRate != UINT_MAX) ? bestRate : supportedRates[0];
503 /* Adjust bit depth (word size) */
504 if(m_encoder->supportedBitdepths() && m_audioFile.formatAudioBitdepth())
506 const unsigned int inputBPS = m_audioFile.formatAudioBitdepth();
507 const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
509 bool bAdjustBitdepth = true;
511 //Is the input bit depth supported exactly? (inclduing IEEE Float)
512 for(int i = 0; supportedBPS[i]; i++)
514 if(supportedBPS[i] == inputBPS) bAdjustBitdepth = false;
517 if(bAdjustBitdepth)
519 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
520 const unsigned int originalBPS = (inputBPS == AudioFileModel::BITDEPTH_IEEE_FLOAT32) ? 32 : inputBPS;
522 //Find the most suitable supported bit depth
523 for(int i = 0; supportedBPS[i]; i++)
525 if(supportedBPS[i] == AudioFileModel::BITDEPTH_IEEE_FLOAT32) continue;
527 currentDiff = DIFF(originalBPS, supportedBPS[i]);
528 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBPS[i])))
530 bestBPS = supportedBPS[i];
531 minimumDiff = currentDiff;
532 if(!(minimumDiff > 0)) break;
536 if(bestBPS != originalBPS)
538 targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBPS[0];
543 /* Insert the filter */
544 if(targetSampleRate || targetBitDepth)
546 m_filters.append(new ResampleFilter(targetSampleRate, targetBitDepth));
550 void ProcessThread::insertDownmixFilter(void)
552 bool applyDownmixing = true;
554 //Check if downmixing filter is already in the chain
555 for(int i = 0; i < m_filters.count(); i++)
557 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
559 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
560 handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
561 applyDownmixing = false;
565 //Now add the downmixing filter, if needed
566 if(applyDownmixing)
568 bool requiresDownmix = true;
569 const unsigned int *supportedChannels = m_encoder->supportedChannelCount();
570 unsigned int channels = m_audioFile.formatAudioChannels();
572 for(int i = 0; supportedChannels[i]; i++)
574 if(supportedChannels[i] == channels)
576 requiresDownmix = false;
577 break;
581 if(requiresDownmix)
583 m_filters.append(new DownmixFilter());
588 ////////////////////////////////////////////////////////////
589 // PUBLIC FUNCTIONS
590 ////////////////////////////////////////////////////////////
592 void ProcessThread::addFilter(AbstractFilter *filter)
594 m_filters.append(filter);
597 void ProcessThread::setRenamePattern(const QString &pattern)
599 QString newPattern = pattern.simplified();
600 if(!newPattern.isEmpty()) m_renamePattern = newPattern;
603 void ProcessThread::setOverwriteMode(const bool bSkipExistingFile, const bool bReplacesExisting)
605 if(bSkipExistingFile && bReplacesExisting)
607 qWarning("Inconsistent overwrite flags, reverting to default!");
608 m_overwriteSkipExistingFile = false;
609 m_overwriteReplacesExisting = false;
612 m_overwriteSkipExistingFile = bSkipExistingFile;
613 m_overwriteReplacesExisting = bReplacesExisting;
616 ////////////////////////////////////////////////////////////
617 // EVENTS
618 ////////////////////////////////////////////////////////////
620 /*NONE*/