OSDN Git Service

716f79afe657c7ae6b788df05605fb42fc5ffb56
[lamexp/LameXP.git] / src / Thread_Process.cpp
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.
14 //
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.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Thread_Process.h"
23
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"
34
35 #include <QUuid>
36 #include <QFileInfo>
37 #include <QDir>
38 #include <QMutex>
39 #include <QMutexLocker>
40 #include <QDate>
41
42 #include <limits.h>
43 #include <time.h>
44 #include <stdlib.h>
45
46 #define DIFF(X,Y) ((X > Y) ? (X-Y) : (Y-X))
47 #define STRDEF(STR,DEF) ((!STR.isEmpty()) ? STR : DEF)
48
49 QMutex *ProcessThread::m_mutex_genFileName = NULL;
50
51 ////////////////////////////////////////////////////////////
52 // Constructor
53 ////////////////////////////////////////////////////////////
54
55 ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, const QString &tempDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
56 :
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)
65 {
66         if(m_mutex_genFileName)
67         {
68                 m_mutex_genFileName = new QMutex;
69         }
70
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);
73
74         m_currentStep = UnknownStep;
75 }
76
77 ProcessThread::~ProcessThread(void)
78 {
79         while(!m_tempFiles.isEmpty())
80         {
81                 lamexp_remove_file(m_tempFiles.takeFirst());
82         }
83
84         while(!m_filters.isEmpty())
85         {
86                 delete m_filters.takeFirst();
87         }
88
89         LAMEXP_DELETE(m_encoder);
90 }
91
92 ////////////////////////////////////////////////////////////
93 // Thread Entry Point
94 ////////////////////////////////////////////////////////////
95
96 void ProcessThread::run()
97 {
98         try
99         {
100                 processFile();
101         }
102         catch(...)
103         {
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);
109         }
110 }
111
112 void ProcessThread::processFile()
113 {
114         m_aborted = false;
115         bool bSuccess = true;
116                 
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");
121
122         //Generate output file name
123         QString outFileName = generateOutFileName();
124         if(outFileName.isEmpty())
125         {
126                 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
127                 emit processStateFinished(m_jobId, outFileName, false);
128                 return;
129         }
130
131         //Do we need to take care of downsampling the input?
132         if(m_encoder->requiresDownsample())
133         {
134                 insertDownsampleFilter();
135         }
136
137         //Do we need Stereo downmix?
138         if(m_encoder->requiresDownmix())
139         {
140                 insertDownmixFilter();
141         }
142
143         QString sourceFile = m_audioFile.filePath();
144
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()))
147         {
148                 m_currentStep = DecodingStep;
149                 AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
150                 
151                 if(decoder)
152                 {
153                         QString tempFile = generateTempFileName();
154
155                         connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
156                         connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
157
158                         bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
159                         LAMEXP_DELETE(decoder);
160
161                         if(bSuccess)
162                         {
163                                 sourceFile = tempFile;
164                                 handleMessage("\n-------------------------------\n");
165                         }
166                 }
167                 else
168                 {
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;
173                 }
174         }
175
176         //Apply all audio filters
177         if(bSuccess)
178         {
179                 while(!m_filters.isEmpty())
180                 {
181                         QString tempFile = generateTempFileName();
182                         AbstractFilter *poFilter = m_filters.takeFirst();
183                         m_currentStep = FilteringStep;
184
185                         connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
186                         connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
187
188                         if(poFilter->apply(sourceFile, tempFile, &m_aborted))
189                         {
190                                 sourceFile = tempFile;
191                         }
192
193                         handleMessage("\n-------------------------------\n");
194                         delete poFilter;
195                 }
196         }
197
198         //Encode audio file
199         if(bSuccess)
200         {
201                 m_currentStep = EncodingStep;
202                 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
203         }
204
205         //Make sure output file exists
206         if(bSuccess)
207         {
208                 QFileInfo fileInfo(outFileName);
209                 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
210         }
211
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);
215
216         qDebug("Process thread is done.");
217 }
218
219 ////////////////////////////////////////////////////////////
220 // SLOTS
221 ////////////////////////////////////////////////////////////
222
223 void ProcessThread::handleUpdate(int progress)
224 {
225         switch(m_currentStep)
226         {
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;
236         }
237 }
238
239 void ProcessThread::handleMessage(const QString &line)
240 {
241         emit processMessageLogged(m_jobId, line);
242 }
243
244 ////////////////////////////////////////////////////////////
245 // PRIVAE FUNCTIONS
246 ////////////////////////////////////////////////////////////
247
248 QString ProcessThread::generateOutFileName(void)
249 {
250         QMutexLocker lock(m_mutex_genFileName);
251         
252         int n = 1;
253
254         QFileInfo sourceFile(m_audioFile.filePath());
255         if(!sourceFile.exists() || !sourceFile.isFile())
256         {
257                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
258                 return QString();
259         }
260
261         QFile readTest(sourceFile.canonicalFilePath());
262         if(!readTest.open(QIODevice::ReadOnly))
263         {
264                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
265                 return QString();
266         }
267         else
268         {
269                 readTest.close();
270         }
271
272         QString baseName = sourceFile.completeBaseName();
273         QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
274
275         if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
276         {
277                 QDir rootDir = sourceFile.dir();
278                 while(!rootDir.isRoot())
279                 {
280                         if(!rootDir.cdUp()) break;
281                 }
282                 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
283         }
284         
285         if(!targetDir.exists())
286         {
287                 targetDir.mkpath(".");
288                 if(!targetDir.exists())
289                 {
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();
292                 }
293         }
294         
295         QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
296         if(!writeTest.open(QIODevice::ReadWrite))
297         {
298                 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
299                 return QString();
300         }
301         else
302         {
303                 writeTest.close();
304                 writeTest.remove();
305         }
306
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();
316
317         QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
318         while(QFileInfo(outFileName).exists())
319         {
320                 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
321         }
322
323         QFile placeholder(outFileName);
324         if(placeholder.open(QIODevice::WriteOnly))
325         {
326                 placeholder.close();
327         }
328
329         return outFileName;
330 }
331
332 QString ProcessThread::generateTempFileName(void)
333 {
334         QMutexLocker lock(m_mutex_genFileName);
335         QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
336
337         while(QFileInfo(tempFileName).exists())
338         {
339                 tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
340         }
341
342         QFile file(tempFileName);
343         if(file.open(QFile::ReadWrite))
344         {
345                 file.close();
346         }
347
348         m_tempFiles << tempFileName;
349         return tempFileName;
350 }
351
352 void ProcessThread::insertDownsampleFilter(void)
353 {
354         bool applyDownsampling = true;
355                 
356         //Check if downsampling filter is already in the chain
357         for(int i = 0; i < m_filters.count(); i++)
358         {
359                 if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
360                 {
361                         qWarning("Encoder requires downsampling, but user has already set resamling filter!");
362                         applyDownsampling = false;
363                 }
364         }
365                 
366         //Now add the downsampling filter, if needed
367         if(applyDownsampling)
368         {
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;
372
373                 //Find the most suitable supported sampling rate
374                 for(int i = 0; supportedRates[i]; i++)
375                 {
376                         currentDiff = DIFF(inputRate, supportedRates[i]);
377                         if(currentDiff < minimumDiff)
378                         {
379                                 bestRate = supportedRates[i];
380                                 minimumDiff = currentDiff;
381                                 if(!(minimumDiff > 0)) break;
382                         }
383                 }
384                 
385                 if(bestRate != inputRate)
386                 {
387                         m_filters.prepend(new ResampleFilter((bestRate != UINT_MAX) ? bestRate : supportedRates[0]));
388                 }
389         }
390 }
391
392 void ProcessThread::insertDownmixFilter(void)
393 {
394         bool applyDownmixing = true;
395                 
396         //Check if downmixing filter is already in the chain
397         for(int i = 0; i < m_filters.count(); i++)
398         {
399                 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
400                 {
401                         qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
402                         applyDownmixing = false;
403                 }
404         }
405
406         //Now add the downmixing filter, if needed
407         if(applyDownmixing)
408         {
409                 unsigned int channels = m_audioFile.formatAudioChannels();
410                 if((channels == 0) || (channels > 2))
411                 {
412                         m_filters.prepend(new DownmixFilter());
413                 }
414         }
415 }
416
417 ////////////////////////////////////////////////////////////
418 // PUBLIC FUNCTIONS
419 ////////////////////////////////////////////////////////////
420
421 void ProcessThread::addFilter(AbstractFilter *filter)
422 {
423         m_filters.append(filter);
424 }
425
426 void ProcessThread::setRenamePattern(const QString &pattern)
427 {
428         QString newPattern = pattern.simplified();
429         if(!newPattern.isEmpty()) m_renamePattern = newPattern;
430 }
431
432 ////////////////////////////////////////////////////////////
433 // EVENTS
434 ////////////////////////////////////////////////////////////
435
436 /*NONE*/