OSDN Git Service

Renamed Chinese translation.
[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         QThread::msleep(500);
213
214         //Report result
215         emit processStateChanged(m_jobId, (bSuccess ? tr("Done.") : (m_aborted ? tr("Aborted!") : tr("Failed!"))), (bSuccess ? ProgressModel::JobComplete : ProgressModel::JobFailed));
216         emit processStateFinished(m_jobId, outFileName, bSuccess);
217
218         qDebug("Process thread is done.");
219 }
220
221 ////////////////////////////////////////////////////////////
222 // SLOTS
223 ////////////////////////////////////////////////////////////
224
225 void ProcessThread::handleUpdate(int progress)
226 {
227         //printf("Progress: %d\n", progress);
228         
229         switch(m_currentStep)
230         {
231         case EncodingStep:
232                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
233                 break;
234         case FilteringStep:
235                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
236                 break;
237         case DecodingStep:
238                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
239                 break;
240         }
241 }
242
243 void ProcessThread::handleMessage(const QString &line)
244 {
245         emit processMessageLogged(m_jobId, line);
246 }
247
248 ////////////////////////////////////////////////////////////
249 // PRIVAE FUNCTIONS
250 ////////////////////////////////////////////////////////////
251
252 QString ProcessThread::generateOutFileName(void)
253 {
254         QMutexLocker lock(m_mutex_genFileName);
255         
256         int n = 1;
257
258         QFileInfo sourceFile(m_audioFile.filePath());
259         if(!sourceFile.exists() || !sourceFile.isFile())
260         {
261                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
262                 return QString();
263         }
264
265         QFile readTest(sourceFile.canonicalFilePath());
266         if(!readTest.open(QIODevice::ReadOnly))
267         {
268                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
269                 return QString();
270         }
271         else
272         {
273                 readTest.close();
274         }
275
276         QString baseName = sourceFile.completeBaseName();
277         QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
278
279         if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
280         {
281                 QDir rootDir = sourceFile.dir();
282                 while(!rootDir.isRoot())
283                 {
284                         if(!rootDir.cdUp()) break;
285                 }
286                 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
287         }
288         
289         if(!targetDir.exists())
290         {
291                 targetDir.mkpath(".");
292                 if(!targetDir.exists())
293                 {
294                         handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
295                         return QString();
296                 }
297         }
298         
299         QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
300         if(!writeTest.open(QIODevice::ReadWrite))
301         {
302                 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
303                 return QString();
304         }
305         else
306         {
307                 writeTest.close();
308                 writeTest.remove();
309         }
310
311         QString fileName = m_renamePattern;
312         fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
313         fileName.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile.filePosition()), Qt::CaseInsensitive);
314         fileName.replace("<Title>", STRDEF(m_audioFile.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive);
315         fileName.replace("<Artist>", STRDEF(m_audioFile.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive);
316         fileName.replace("<Album>", STRDEF(m_audioFile.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive);
317         fileName.replace("<Year>", QString().sprintf("%04d", m_audioFile.fileYear()), Qt::CaseInsensitive);
318         fileName.replace("<Comment>", STRDEF(m_audioFile.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive);
319         fileName = lamexp_clean_filename(fileName).simplified();
320
321         QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
322         while(QFileInfo(outFileName).exists())
323         {
324                 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
325         }
326
327         QFile placeholder(outFileName);
328         if(placeholder.open(QIODevice::WriteOnly))
329         {
330                 placeholder.close();
331         }
332
333         return outFileName;
334 }
335
336 QString ProcessThread::generateTempFileName(void)
337 {
338         QMutexLocker lock(m_mutex_genFileName);
339         QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
340
341         while(QFileInfo(tempFileName).exists())
342         {
343                 tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
344         }
345
346         QFile file(tempFileName);
347         if(file.open(QFile::ReadWrite))
348         {
349                 file.close();
350         }
351
352         m_tempFiles << tempFileName;
353         return tempFileName;
354 }
355
356 void ProcessThread::insertDownsampleFilter(void)
357 {
358         bool applyDownsampling = true;
359                 
360         //Check if downsampling filter is already in the chain
361         for(int i = 0; i < m_filters.count(); i++)
362         {
363                 if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
364                 {
365                         qWarning("Encoder requires downsampling, but user has already set resamling filter!");
366                         applyDownsampling = false;
367                 }
368         }
369                 
370         //Now add the downsampling filter, if needed
371         if(applyDownsampling)
372         {
373                 const unsigned int *supportedRates = m_encoder->requiresDownsample();
374                 const unsigned int inputRate = m_audioFile.formatAudioSamplerate();
375                 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
376
377                 //Find the most suitable supported sampling rate
378                 for(int i = 0; supportedRates[i]; i++)
379                 {
380                         currentDiff = DIFF(inputRate, supportedRates[i]);
381                         if(currentDiff < minimumDiff)
382                         {
383                                 bestRate = supportedRates[i];
384                                 minimumDiff = currentDiff;
385                                 if(!(minimumDiff > 0)) break;
386                         }
387                 }
388                 
389                 if(bestRate != inputRate)
390                 {
391                         m_filters.prepend(new ResampleFilter((bestRate != UINT_MAX) ? bestRate : supportedRates[0]));
392                 }
393         }
394 }
395
396 void ProcessThread::insertDownmixFilter(void)
397 {
398         bool applyDownmixing = true;
399                 
400         //Check if downmixing filter is already in the chain
401         for(int i = 0; i < m_filters.count(); i++)
402         {
403                 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
404                 {
405                         qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
406                         applyDownmixing = false;
407                 }
408         }
409
410         //Now add the downmixing filter, if needed
411         if(applyDownmixing)
412         {
413                 unsigned int channels = m_audioFile.formatAudioChannels();
414                 if((channels == 0) || (channels > 2))
415                 {
416                         m_filters.prepend(new DownmixFilter());
417                 }
418         }
419 }
420
421 ////////////////////////////////////////////////////////////
422 // PUBLIC FUNCTIONS
423 ////////////////////////////////////////////////////////////
424
425 void ProcessThread::addFilter(AbstractFilter *filter)
426 {
427         m_filters.append(filter);
428 }
429
430 void ProcessThread::setRenamePattern(const QString &pattern)
431 {
432         QString newPattern = pattern.simplified();
433         if(!newPattern.isEmpty()) m_renamePattern = newPattern;
434 }
435
436 ////////////////////////////////////////////////////////////
437 // EVENTS
438 ////////////////////////////////////////////////////////////
439
440 /*NONE*/