Added an option to hibernate the computer ("suspend to disk") instead of shutting...
[LameXP.git] / src / Thread_Process.cpp
blob716f79afe657c7ae6b788df05605fb42fc5ffb56
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 //Do we need to take care of downsampling the input?
132 if(m_encoder->requiresDownsample())
134 insertDownsampleFilter();
137 //Do we need Stereo downmix?
138 if(m_encoder->requiresDownmix())
140 insertDownmixFilter();
143 QString sourceFile = m_audioFile.filePath();
145 //Decode source file
146 if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion()))
148 m_currentStep = DecodingStep;
149 AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
151 if(decoder)
153 QString tempFile = generateTempFileName();
155 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
156 connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
158 bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
159 LAMEXP_DELETE(decoder);
161 if(bSuccess)
163 sourceFile = tempFile;
164 handleMessage("\n-------------------------------\n");
167 else
169 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()));
170 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
171 emit processStateFinished(m_jobId, outFileName, false);
172 return;
176 //Apply all audio filters
177 if(bSuccess)
179 while(!m_filters.isEmpty())
181 QString tempFile = generateTempFileName();
182 AbstractFilter *poFilter = m_filters.takeFirst();
183 m_currentStep = FilteringStep;
185 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
186 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
188 if(poFilter->apply(sourceFile, tempFile, &m_aborted))
190 sourceFile = tempFile;
193 handleMessage("\n-------------------------------\n");
194 delete poFilter;
198 //Encode audio file
199 if(bSuccess)
201 m_currentStep = EncodingStep;
202 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
205 //Make sure output file exists
206 if(bSuccess)
208 QFileInfo fileInfo(outFileName);
209 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
212 //Report result
213 emit processStateChanged(m_jobId, (bSuccess ? tr("Done.") : (m_aborted ? tr("Aborted!") : tr("Failed!"))), (bSuccess ? ProgressModel::JobComplete : ProgressModel::JobFailed));
214 emit processStateFinished(m_jobId, outFileName, bSuccess);
216 qDebug("Process thread is done.");
219 ////////////////////////////////////////////////////////////
220 // SLOTS
221 ////////////////////////////////////////////////////////////
223 void ProcessThread::handleUpdate(int progress)
225 switch(m_currentStep)
227 case EncodingStep:
228 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
229 break;
230 case FilteringStep:
231 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
232 break;
233 case DecodingStep:
234 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
235 break;
239 void ProcessThread::handleMessage(const QString &line)
241 emit processMessageLogged(m_jobId, line);
244 ////////////////////////////////////////////////////////////
245 // PRIVAE FUNCTIONS
246 ////////////////////////////////////////////////////////////
248 QString ProcessThread::generateOutFileName(void)
250 QMutexLocker lock(m_mutex_genFileName);
252 int n = 1;
254 QFileInfo sourceFile(m_audioFile.filePath());
255 if(!sourceFile.exists() || !sourceFile.isFile())
257 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
258 return QString();
261 QFile readTest(sourceFile.canonicalFilePath());
262 if(!readTest.open(QIODevice::ReadOnly))
264 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
265 return QString();
267 else
269 readTest.close();
272 QString baseName = sourceFile.completeBaseName();
273 QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
275 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
277 QDir rootDir = sourceFile.dir();
278 while(!rootDir.isRoot())
280 if(!rootDir.cdUp()) break;
282 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
285 if(!targetDir.exists())
287 targetDir.mkpath(".");
288 if(!targetDir.exists())
290 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
291 return QString();
295 QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
296 if(!writeTest.open(QIODevice::ReadWrite))
298 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
299 return QString();
301 else
303 writeTest.close();
304 writeTest.remove();
307 QString fileName = m_renamePattern;
308 fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
309 fileName.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile.filePosition()), Qt::CaseInsensitive);
310 fileName.replace("<Title>", STRDEF(m_audioFile.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive);
311 fileName.replace("<Artist>", STRDEF(m_audioFile.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive);
312 fileName.replace("<Album>", STRDEF(m_audioFile.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive);
313 fileName.replace("<Year>", QString().sprintf("%04d", m_audioFile.fileYear()), Qt::CaseInsensitive);
314 fileName.replace("<Comment>", STRDEF(m_audioFile.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive);
315 fileName = lamexp_clean_filename(fileName).simplified();
317 QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
318 while(QFileInfo(outFileName).exists())
320 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
323 QFile placeholder(outFileName);
324 if(placeholder.open(QIODevice::WriteOnly))
326 placeholder.close();
329 return outFileName;
332 QString ProcessThread::generateTempFileName(void)
334 QMutexLocker lock(m_mutex_genFileName);
335 QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
337 while(QFileInfo(tempFileName).exists())
339 tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
342 QFile file(tempFileName);
343 if(file.open(QFile::ReadWrite))
345 file.close();
348 m_tempFiles << tempFileName;
349 return tempFileName;
352 void ProcessThread::insertDownsampleFilter(void)
354 bool applyDownsampling = true;
356 //Check if downsampling filter is already in the chain
357 for(int i = 0; i < m_filters.count(); i++)
359 if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
361 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
362 applyDownsampling = false;
366 //Now add the downsampling filter, if needed
367 if(applyDownsampling)
369 const unsigned int *supportedRates = m_encoder->requiresDownsample();
370 const unsigned int inputRate = m_audioFile.formatAudioSamplerate();
371 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
373 //Find the most suitable supported sampling rate
374 for(int i = 0; supportedRates[i]; i++)
376 currentDiff = DIFF(inputRate, supportedRates[i]);
377 if(currentDiff < minimumDiff)
379 bestRate = supportedRates[i];
380 minimumDiff = currentDiff;
381 if(!(minimumDiff > 0)) break;
385 if(bestRate != inputRate)
387 m_filters.prepend(new ResampleFilter((bestRate != UINT_MAX) ? bestRate : supportedRates[0]));
392 void ProcessThread::insertDownmixFilter(void)
394 bool applyDownmixing = true;
396 //Check if downmixing filter is already in the chain
397 for(int i = 0; i < m_filters.count(); i++)
399 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
401 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
402 applyDownmixing = false;
406 //Now add the downmixing filter, if needed
407 if(applyDownmixing)
409 unsigned int channels = m_audioFile.formatAudioChannels();
410 if((channels == 0) || (channels > 2))
412 m_filters.prepend(new DownmixFilter());
417 ////////////////////////////////////////////////////////////
418 // PUBLIC FUNCTIONS
419 ////////////////////////////////////////////////////////////
421 void ProcessThread::addFilter(AbstractFilter *filter)
423 m_filters.append(filter);
426 void ProcessThread::setRenamePattern(const QString &pattern)
428 QString newPattern = pattern.simplified();
429 if(!newPattern.isEmpty()) m_renamePattern = newPattern;
432 ////////////////////////////////////////////////////////////
433 // EVENTS
434 ////////////////////////////////////////////////////////////
436 /*NONE*/