make more strings translatable + try to load a default translation that suits the...
[LameXP.git] / src / Thread_Process.cpp
blobfa0944a0f0d5409c540d8b1c4115853c1af30af1
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 "Registry_Decoder.h"
32 #include "Model_Settings.h"
34 #include <QUuid>
35 #include <QFileInfo>
36 #include <QDir>
37 #include <QMutex>
38 #include <QMutexLocker>
40 #include <limits.h>
41 #include <time.h>
43 QMutex *ProcessThread::m_mutex_genFileName = NULL;
45 ////////////////////////////////////////////////////////////
46 // Constructor
47 ////////////////////////////////////////////////////////////
49 ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
51 m_audioFile(audioFile),
52 m_outputDirectory(outputDirectory),
53 m_encoder(encoder),
54 m_jobId(QUuid::createUuid()),
55 m_prependRelativeSourcePath(prependRelativeSourcePath),
56 m_aborted(false)
58 if(m_mutex_genFileName)
60 m_mutex_genFileName = new QMutex;
63 connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
64 connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
66 m_currentStep = UnknownStep;
69 ProcessThread::~ProcessThread(void)
71 while(!m_tempFiles.isEmpty())
73 lamexp_remove_file(m_tempFiles.takeFirst());
76 LAMEXP_DELETE(m_encoder);
79 void ProcessThread::run()
81 try
83 processFile();
85 catch(...)
87 fflush(stdout);
88 fflush(stderr);
89 fprintf(stderr, "\nGURU MEDITATION !!!\n");
90 FatalAppExit(0, L"Unhandeled exception error, application will exit!");
91 TerminateProcess(GetCurrentProcess(), -1);
95 void ProcessThread::processFile()
97 m_aborted = false;
98 bool bSuccess = true;
100 qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
101 emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
103 //Generate output file name
104 QString outFileName = generateOutFileName();
105 if(outFileName.isEmpty())
107 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
108 emit processStateFinished(m_jobId, outFileName, false);
109 return;
112 QList<AbstractFilter*> filters;
114 //Do we need Stereo downmix?
115 if(m_audioFile.formatAudioChannels() > 2 && m_encoder->requiresDownmix())
117 filters.prepend(new DownmixFilter());
120 QString sourceFile = m_audioFile.filePath();
122 //Decode source file
123 if(!filters.isEmpty() || !m_encoder->isFormatSupported(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion()))
125 m_currentStep = DecodingStep;
126 AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
128 if(decoder)
130 QString tempFile = generateTempFileName();
132 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
133 connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
135 bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
137 if(bSuccess)
139 sourceFile = tempFile;
140 handleMessage("\n-------------------------------\n");
143 else
145 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()));
146 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
147 emit processStateFinished(m_jobId, outFileName, false);
148 return;
152 //Apply all filters
153 while(!filters.isEmpty())
155 QString tempFile = generateTempFileName();
156 AbstractFilter *poFilter = filters.takeFirst();
158 if(bSuccess)
160 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
161 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
163 m_currentStep = FilteringStep;
164 bSuccess = poFilter->apply(sourceFile, tempFile, &m_aborted);
166 if(bSuccess)
168 sourceFile = tempFile;
169 handleMessage("\n-------------------------------\n");
173 delete poFilter;
176 //Encode audio file
177 if(bSuccess)
179 m_currentStep = EncodingStep;
180 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
183 //Make sure output file exists
184 if(bSuccess)
186 QFileInfo fileInfo(outFileName);
187 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
190 //Report result
191 emit processStateChanged(m_jobId, (bSuccess ? tr("Done.") : (m_aborted ? tr("Aborted!") : tr("Failed!"))), (bSuccess ? ProgressModel::JobComplete : ProgressModel::JobFailed));
192 emit processStateFinished(m_jobId, outFileName, bSuccess);
194 qDebug("Process thread is done.");
197 ////////////////////////////////////////////////////////////
198 // SLOTS
199 ////////////////////////////////////////////////////////////
201 void ProcessThread::handleUpdate(int progress)
203 switch(m_currentStep)
205 case EncodingStep:
206 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
207 break;
208 case FilteringStep:
209 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
210 break;
211 case DecodingStep:
212 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
213 break;
217 void ProcessThread::handleMessage(const QString &line)
219 emit processMessageLogged(m_jobId, line);
222 ////////////////////////////////////////////////////////////
223 // PRIVAE FUNCTIONS
224 ////////////////////////////////////////////////////////////
226 QString ProcessThread::generateOutFileName(void)
228 QMutexLocker lock(m_mutex_genFileName);
230 int n = 1;
232 QFileInfo sourceFile(m_audioFile.filePath());
233 if(!sourceFile.exists() || !sourceFile.isFile())
235 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
236 return QString();
239 QFile readTest(sourceFile.canonicalFilePath());
240 if(!readTest.open(QIODevice::ReadOnly))
242 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
243 return QString();
245 else
247 readTest.close();
250 QString baseName = sourceFile.completeBaseName();
251 QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
253 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
255 QDir rootDir = sourceFile.dir();
256 while(!rootDir.isRoot())
258 if(!rootDir.cdUp()) break;
260 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
263 if(!targetDir.exists())
265 targetDir.mkpath(".");
266 if(!targetDir.exists())
268 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
269 return QString();
273 QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
274 if(!writeTest.open(QIODevice::ReadWrite))
276 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
277 return QString();
279 else
281 writeTest.close();
282 writeTest.remove();
285 QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), baseName, m_encoder->extension());
286 while(QFileInfo(outFileName).exists())
288 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), baseName, QString::number(++n), m_encoder->extension());
291 QFile placeholder(outFileName);
292 if(placeholder.open(QIODevice::WriteOnly))
294 placeholder.close();
297 return outFileName;
300 QString ProcessThread::generateTempFileName(void)
302 QMutexLocker lock(m_mutex_genFileName);
303 QString tempFileName = QString("%1/%2.wav").arg(lamexp_temp_folder(), lamexp_rand_str());
305 while(QFileInfo(tempFileName).exists())
307 tempFileName = QString("%1/%2.wav").arg(lamexp_temp_folder(), lamexp_rand_str());
310 QFile file(tempFileName);
311 if(file.open(QFile::ReadWrite))
313 file.close();
316 m_tempFiles << tempFileName;
317 return tempFileName;
320 ////////////////////////////////////////////////////////////
321 // EVENTS
322 ////////////////////////////////////////////////////////////
324 /*NONE*/