1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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"
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"
38 #include <QMutexLocker>
43 QMutex
*ProcessThread::m_mutex_genFileName
= NULL
;
45 ////////////////////////////////////////////////////////////
47 ////////////////////////////////////////////////////////////
49 ProcessThread::ProcessThread(const AudioFileModel
&audioFile
, const QString
&outputDirectory
, AbstractEncoder
*encoder
, const bool prependRelativeSourcePath
)
51 m_audioFile(audioFile
),
52 m_outputDirectory(outputDirectory
),
54 m_jobId(QUuid::createUuid()),
55 m_prependRelativeSourcePath(prependRelativeSourcePath
),
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 while(!m_filters
.isEmpty())
78 delete m_filters
.takeFirst();
81 LAMEXP_DELETE(m_encoder
);
84 void ProcessThread::run()
94 fprintf(stderr
, "\nGURU MEDITATION !!!\n");
95 FatalAppExit(0, L
"Unhandeled exception error, application will exit!");
96 TerminateProcess(GetCurrentProcess(), -1);
100 void ProcessThread::processFile()
103 bool bSuccess
= true;
105 qDebug("Process thread %s has started.", m_jobId
.toString().toLatin1().constData());
106 emit
processStateInitialized(m_jobId
, QFileInfo(m_audioFile
.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning
);
108 //Generate output file name
109 QString outFileName
= generateOutFileName();
110 if(outFileName
.isEmpty())
112 emit
processStateChanged(m_jobId
, tr("Not found!"), ProgressModel::JobFailed
);
113 emit
processStateFinished(m_jobId
, outFileName
, false);
117 //Do we need Stereo downmix?
118 if(m_audioFile
.formatAudioChannels() > 2 && m_encoder
->requiresDownmix())
120 m_filters
.prepend(new DownmixFilter());
123 QString sourceFile
= m_audioFile
.filePath();
126 if(!m_filters
.isEmpty() || !m_encoder
->isFormatSupported(m_audioFile
.formatContainerType(), m_audioFile
.formatContainerProfile(), m_audioFile
.formatAudioType(), m_audioFile
.formatAudioProfile(), m_audioFile
.formatAudioVersion()))
128 m_currentStep
= DecodingStep
;
129 AbstractDecoder
*decoder
= DecoderRegistry::lookup(m_audioFile
.formatContainerType(), m_audioFile
.formatContainerProfile(), m_audioFile
.formatAudioType(), m_audioFile
.formatAudioProfile(), m_audioFile
.formatAudioVersion());
133 QString tempFile
= generateTempFileName();
135 connect(decoder
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
136 connect(decoder
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
138 bSuccess
= decoder
->decode(sourceFile
, tempFile
, &m_aborted
);
142 sourceFile
= tempFile
;
143 handleMessage("\n-------------------------------\n");
148 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()));
149 emit
processStateChanged(m_jobId
, tr("Unsupported!"), ProgressModel::JobFailed
);
150 emit
processStateFinished(m_jobId
, outFileName
, false);
156 while(!m_filters
.isEmpty())
158 QString tempFile
= generateTempFileName();
159 AbstractFilter
*poFilter
= m_filters
.takeFirst();
163 connect(poFilter
, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection
);
164 connect(poFilter
, SIGNAL(messageLogged(QString
)), this, SLOT(handleMessage(QString
)), Qt::DirectConnection
);
166 m_currentStep
= FilteringStep
;
167 bSuccess
= poFilter
->apply(sourceFile
, tempFile
, &m_aborted
);
171 sourceFile
= tempFile
;
172 handleMessage("\n-------------------------------\n");
182 m_currentStep
= EncodingStep
;
183 bSuccess
= m_encoder
->encode(sourceFile
, m_audioFile
, outFileName
, &m_aborted
);
186 //Make sure output file exists
189 QFileInfo
fileInfo(outFileName
);
190 bSuccess
= fileInfo
.exists() && fileInfo
.isFile() && (fileInfo
.size() > 0);
194 emit
processStateChanged(m_jobId
, (bSuccess
? tr("Done.") : (m_aborted
? tr("Aborted!") : tr("Failed!"))), (bSuccess
? ProgressModel::JobComplete
: ProgressModel::JobFailed
));
195 emit
processStateFinished(m_jobId
, outFileName
, bSuccess
);
197 qDebug("Process thread is done.");
200 ////////////////////////////////////////////////////////////
202 ////////////////////////////////////////////////////////////
204 void ProcessThread::handleUpdate(int progress
)
206 switch(m_currentStep
)
209 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress
)), ProgressModel::JobRunning
);
212 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress
)), ProgressModel::JobRunning
);
215 emit
processStateChanged(m_jobId
, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress
)), ProgressModel::JobRunning
);
220 void ProcessThread::handleMessage(const QString
&line
)
222 emit
processMessageLogged(m_jobId
, line
);
225 ////////////////////////////////////////////////////////////
227 ////////////////////////////////////////////////////////////
229 QString
ProcessThread::generateOutFileName(void)
231 QMutexLocker
lock(m_mutex_genFileName
);
235 QFileInfo
sourceFile(m_audioFile
.filePath());
236 if(!sourceFile
.exists() || !sourceFile
.isFile())
238 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile
.absoluteFilePath()));
242 QFile
readTest(sourceFile
.canonicalFilePath());
243 if(!readTest
.open(QIODevice::ReadOnly
))
245 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest
.fileName()));
253 QString baseName
= sourceFile
.completeBaseName();
254 QDir
targetDir(m_outputDirectory
.isEmpty() ? sourceFile
.canonicalPath() : m_outputDirectory
);
256 if(m_prependRelativeSourcePath
&& !m_outputDirectory
.isEmpty())
258 QDir rootDir
= sourceFile
.dir();
259 while(!rootDir
.isRoot())
261 if(!rootDir
.cdUp()) break;
263 targetDir
.setPath(QString("%1/%2").arg(targetDir
.absolutePath(), QFileInfo(rootDir
.relativeFilePath(sourceFile
.canonicalFilePath())).path()));
266 if(!targetDir
.exists())
268 targetDir
.mkpath(".");
269 if(!targetDir
.exists())
271 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir
.absolutePath()));
276 QFile
writeTest(QString("%1/.%2").arg(targetDir
.canonicalPath(), lamexp_rand_str()));
277 if(!writeTest
.open(QIODevice::ReadWrite
))
279 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir
.absolutePath()));
288 QString outFileName
= QString("%1/%2.%3").arg(targetDir
.canonicalPath(), baseName
, m_encoder
->extension());
289 while(QFileInfo(outFileName
).exists())
291 outFileName
= QString("%1/%2 (%3).%4").arg(targetDir
.canonicalPath(), baseName
, QString::number(++n
), m_encoder
->extension());
294 QFile
placeholder(outFileName
);
295 if(placeholder
.open(QIODevice::WriteOnly
))
303 QString
ProcessThread::generateTempFileName(void)
305 QMutexLocker
lock(m_mutex_genFileName
);
306 QString tempFileName
= QString("%1/%2.wav").arg(lamexp_temp_folder(), lamexp_rand_str());
308 while(QFileInfo(tempFileName
).exists())
310 tempFileName
= QString("%1/%2.wav").arg(lamexp_temp_folder(), lamexp_rand_str());
313 QFile
file(tempFileName
);
314 if(file
.open(QFile::ReadWrite
))
319 m_tempFiles
<< tempFileName
;
323 void ProcessThread::addFilter(AbstractFilter
*filter
)
325 m_filters
.append(filter
);
328 ////////////////////////////////////////////////////////////
330 ////////////////////////////////////////////////////////////