OSDN Git Service

Replaced the Opus encoder/decoder binary wit custom binaries that support UTF-8 file...
[lamexp/LameXP.git] / src / Thread_Process.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 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 "Tool_WaveProperties.h"
33 #include "Registry_Decoder.h"
34 #include "Model_Settings.h"
35
36 #include <QUuid>
37 #include <QFileInfo>
38 #include <QDir>
39 #include <QMutex>
40 #include <QMutexLocker>
41 #include <QDate>
42
43 #include <limits.h>
44 #include <time.h>
45 #include <stdlib.h>
46
47 #define DIFF(X,Y) ((X > Y) ? (X-Y) : (Y-X))
48 #define IS_WAVE(X) ((X.formatContainerType().compare("Wave", Qt::CaseInsensitive) == 0) && (X.formatAudioType().compare("PCM", Qt::CaseInsensitive) == 0))
49 #define STRDEF(STR,DEF) ((!STR.isEmpty()) ? STR : DEF)
50
51 QMutex *ProcessThread::m_mutex_genFileName = NULL;
52
53 ////////////////////////////////////////////////////////////
54 // Constructor
55 ////////////////////////////////////////////////////////////
56
57 ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, const QString &tempDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
58 :
59         m_audioFile(audioFile),
60         m_outputDirectory(outputDirectory),
61         m_tempDirectory(tempDirectory),
62         m_encoder(encoder),
63         m_jobId(QUuid::createUuid()),
64         m_prependRelativeSourcePath(prependRelativeSourcePath),
65         m_renamePattern("<BaseName>"),
66         m_aborted(false),
67         m_propDetect(new WaveProperties())
68 {
69         if(m_mutex_genFileName)
70         {
71                 m_mutex_genFileName = new QMutex;
72         }
73
74         connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
75         connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
76
77         connect(m_propDetect, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
78         connect(m_propDetect, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
79
80         m_currentStep = UnknownStep;
81 }
82
83 ProcessThread::~ProcessThread(void)
84 {
85         while(!m_tempFiles.isEmpty())
86         {
87                 lamexp_remove_file(m_tempFiles.takeFirst());
88         }
89
90         while(!m_filters.isEmpty())
91         {
92                 delete m_filters.takeFirst();
93         }
94
95         LAMEXP_DELETE(m_encoder);
96         LAMEXP_DELETE(m_propDetect);
97 }
98
99 ////////////////////////////////////////////////////////////
100 // Thread Entry Point
101 ////////////////////////////////////////////////////////////
102
103 void ProcessThread::run()
104 {
105         try
106         {
107                 processFile();
108         }
109         catch(...)
110         {
111                 fflush(stdout);
112                 fflush(stderr);
113                 fprintf(stderr, "\nGURU MEDITATION !!!\n");
114                 FatalAppExit(0, L"Unhandeled exception error, application will exit!");
115                 TerminateProcess(GetCurrentProcess(), -1);
116         }
117 }
118
119 void ProcessThread::processFile()
120 {
121         m_aborted = false;
122         bool bSuccess = true;
123                 
124         qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
125         emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
126         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()));
127         handleMessage("\n-------------------------------\n");
128
129         //Generate output file name
130         QString outFileName = generateOutFileName();
131         if(outFileName.isEmpty())
132         {
133                 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
134                 emit processStateFinished(m_jobId, outFileName, false);
135                 return;
136         }
137
138         QString sourceFile = m_audioFile.filePath();
139
140         //------------------
141         //Decode source file
142         //------------------
143         if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion()))
144         {
145                 m_currentStep = DecodingStep;
146                 AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
147                 
148                 if(decoder)
149                 {
150                         QString tempFile = generateTempFileName();
151
152                         connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
153                         connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
154
155                         bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
156                         LAMEXP_DELETE(decoder);
157
158                         if(bSuccess)
159                         {
160                                 sourceFile = tempFile;
161                                 m_audioFile.setFormatContainerType(QString::fromLatin1("Wave"));
162                                 m_audioFile.setFormatAudioType(QString::fromLatin1("PCM"));
163
164                                 if(QFileInfo(sourceFile).size() >= 4294967296i64)
165                                 {
166                                         handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
167                                 }
168
169                                 handleMessage("\n-------------------------------\n");
170                         }
171                 }
172                 else
173                 {
174                         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()));
175                         emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
176                         emit processStateFinished(m_jobId, outFileName, false);
177                         return;
178                 }
179         }
180
181         //------------------------------------
182         //Update audio properties after decode
183         //------------------------------------
184         if(bSuccess && !m_aborted && IS_WAVE(m_audioFile))
185         {
186                 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
187                 {
188                         m_currentStep = AnalyzeStep;
189                         bSuccess = m_propDetect->detect(sourceFile, &m_audioFile, &m_aborted);
190
191                         if(bSuccess)
192                         {
193                                 handleMessage("\n-------------------------------\n");
194
195                                 //Do we need to take care if Stereo downmix?
196                                 if(m_encoder->supportedChannelCount())
197                                 {
198                                         insertDownmixFilter();
199                                 }
200
201                                 //Do we need to take care of downsampling the input?
202                                 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths())
203                                 {
204                                         insertDownsampleFilter();
205                                 }
206                         }
207                 }
208         }
209
210         //-----------------------
211         //Apply all audio filters
212         //-----------------------
213         if(bSuccess)
214         {
215                 while(!m_filters.isEmpty() && !m_aborted)
216                 {
217                         QString tempFile = generateTempFileName();
218                         AbstractFilter *poFilter = m_filters.takeFirst();
219                         m_currentStep = FilteringStep;
220
221                         connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
222                         connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
223
224                         if(poFilter->apply(sourceFile, tempFile, &m_audioFile, &m_aborted))
225                         {
226                                 sourceFile = tempFile;
227                         }
228
229                         handleMessage("\n-------------------------------\n");
230                         delete poFilter;
231                 }
232         }
233
234         //-----------------
235         //Encode audio file
236         //-----------------
237         if(bSuccess && !m_aborted)
238         {
239                 m_currentStep = EncodingStep;
240                 bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
241         }
242
243         //Make sure output file exists
244         if(bSuccess && !m_aborted)
245         {
246                 QFileInfo fileInfo(outFileName);
247                 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
248         }
249
250         QThread::msleep(500);
251
252         //Report result
253         emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
254         emit processStateFinished(m_jobId, outFileName, bSuccess);
255
256         qDebug("Process thread is done.");
257 }
258
259 ////////////////////////////////////////////////////////////
260 // SLOTS
261 ////////////////////////////////////////////////////////////
262
263 void ProcessThread::handleUpdate(int progress)
264 {
265         //printf("Progress: %d\n", progress);
266         
267         switch(m_currentStep)
268         {
269         case EncodingStep:
270                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
271                 break;
272         case AnalyzeStep:
273                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
274                 break;
275         case FilteringStep:
276                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
277                 break;
278         case DecodingStep:
279                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
280                 break;
281         }
282 }
283
284 void ProcessThread::handleMessage(const QString &line)
285 {
286         emit processMessageLogged(m_jobId, line);
287 }
288
289 ////////////////////////////////////////////////////////////
290 // PRIVAE FUNCTIONS
291 ////////////////////////////////////////////////////////////
292
293 QString ProcessThread::generateOutFileName(void)
294 {
295         QMutexLocker lock(m_mutex_genFileName);
296         
297         int n = 1;
298
299         QFileInfo sourceFile(m_audioFile.filePath());
300         if(!sourceFile.exists() || !sourceFile.isFile())
301         {
302                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
303                 return QString();
304         }
305
306         QFile readTest(sourceFile.canonicalFilePath());
307         if(!readTest.open(QIODevice::ReadOnly))
308         {
309                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
310                 return QString();
311         }
312         else
313         {
314                 readTest.close();
315         }
316
317         QString baseName = sourceFile.completeBaseName();
318         QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
319
320         if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
321         {
322                 QDir rootDir = sourceFile.dir();
323                 while(!rootDir.isRoot())
324                 {
325                         if(!rootDir.cdUp()) break;
326                 }
327                 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
328         }
329         
330         if(!targetDir.exists())
331         {
332                 targetDir.mkpath(".");
333                 if(!targetDir.exists())
334                 {
335                         handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
336                         return QString();
337                 }
338         }
339         
340         QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
341         if(!writeTest.open(QIODevice::ReadWrite))
342         {
343                 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
344                 return QString();
345         }
346         else
347         {
348                 writeTest.close();
349                 writeTest.remove();
350         }
351
352         QString fileName = m_renamePattern;
353         fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
354         fileName.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile.filePosition()), Qt::CaseInsensitive);
355         fileName.replace("<Title>", STRDEF(m_audioFile.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive);
356         fileName.replace("<Artist>", STRDEF(m_audioFile.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive);
357         fileName.replace("<Album>", STRDEF(m_audioFile.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive);
358         fileName.replace("<Year>", QString().sprintf("%04d", m_audioFile.fileYear()), Qt::CaseInsensitive);
359         fileName.replace("<Comment>", STRDEF(m_audioFile.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive);
360         fileName = lamexp_clean_filename(fileName).simplified();
361
362         QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
363         while(QFileInfo(outFileName).exists())
364         {
365                 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
366         }
367
368         QFile placeholder(outFileName);
369         if(placeholder.open(QIODevice::WriteOnly))
370         {
371                 placeholder.close();
372         }
373
374         return outFileName;
375 }
376
377 QString ProcessThread::generateTempFileName(void)
378 {
379         QMutexLocker lock(m_mutex_genFileName);
380         QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
381
382         while(QFileInfo(tempFileName).exists())
383         {
384                 tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
385         }
386
387         QFile file(tempFileName);
388         if(file.open(QFile::ReadWrite))
389         {
390                 file.close();
391         }
392
393         m_tempFiles << tempFileName;
394         return tempFileName;
395 }
396
397 void ProcessThread::insertDownsampleFilter(void)
398 {
399         int targetSampleRate = 0;
400         int targetBitDepth = 0;
401         
402         /* Adjust sample rate */
403         if(m_encoder->supportedSamplerates() && m_audioFile.formatAudioSamplerate())
404         {
405                 bool applyDownsampling = true;
406         
407                 //Check if downsampling filter is already in the chain
408                 for(int i = 0; i < m_filters.count(); i++)
409                 {
410                         if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
411                         {
412                                 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
413                                 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
414                                 applyDownsampling = false;
415                         }
416                 }
417                 
418                 //Now determine the target sample rate, if required
419                 if(applyDownsampling)
420                 {
421                         const unsigned int *supportedRates = m_encoder->supportedSamplerates();
422                         const unsigned int inputRate = m_audioFile.formatAudioSamplerate();
423                         unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
424
425                         //Find the most suitable supported sampling rate
426                         for(int i = 0; supportedRates[i]; i++)
427                         {
428                                 currentDiff = DIFF(inputRate, supportedRates[i]);
429                                 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestRate < supportedRates[i])))
430                                 {
431                                         bestRate = supportedRates[i];
432                                         minimumDiff = currentDiff;
433                                         if(!(minimumDiff > 0)) break;
434                                 }
435                         }
436                 
437                         if(bestRate != inputRate)
438                         {
439                                 targetSampleRate = (bestRate != UINT_MAX) ? bestRate : supportedRates[0];
440                         }
441                 }
442         }
443
444         /* Adjust bit depth (word size) */
445         if(m_encoder->supportedBitdepths() && m_audioFile.formatAudioBitdepth())
446         {
447                 const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
448                 const unsigned int inputBPS = m_audioFile.formatAudioBitdepth();
449                 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
450
451                 //Find the most suitable supported bit depth
452                 for(int i = 0; supportedBPS[i]; i++)
453                 {
454                         currentDiff = DIFF(inputBPS, supportedBPS[i]);
455                         if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBPS[i])))
456                         {
457                                 bestBPS = supportedBPS[i];
458                                 minimumDiff = currentDiff;
459                                 if(!(minimumDiff > 0)) break;
460                         }
461                 }
462
463                 if(bestBPS != inputBPS)
464                 {
465                         targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBPS[0];
466                 }
467         }
468
469         /* Insert the filter */
470         if(targetSampleRate || targetBitDepth)
471         {
472                 m_filters.append(new ResampleFilter(targetSampleRate, targetBitDepth));
473         }
474 }
475
476 void ProcessThread::insertDownmixFilter(void)
477 {
478         bool applyDownmixing = true;
479                 
480         //Check if downmixing filter is already in the chain
481         for(int i = 0; i < m_filters.count(); i++)
482         {
483                 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
484                 {
485                         qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
486                         handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
487                         applyDownmixing = false;
488                 }
489         }
490
491         //Now add the downmixing filter, if needed
492         if(applyDownmixing)
493         {
494                 bool requiresDownmix = true;
495                 const unsigned int *supportedChannels = m_encoder->supportedChannelCount();
496                 unsigned int channels = m_audioFile.formatAudioChannels();
497
498                 for(int i = 0; supportedChannels[i]; i++)
499                 {
500                         if(supportedChannels[i] == channels)
501                         {
502                                 requiresDownmix = false;
503                                 break;
504                         }
505                 }
506
507                 if(requiresDownmix)
508                 {
509                         m_filters.append(new DownmixFilter());
510                 }
511         }
512 }
513
514 ////////////////////////////////////////////////////////////
515 // PUBLIC FUNCTIONS
516 ////////////////////////////////////////////////////////////
517
518 void ProcessThread::addFilter(AbstractFilter *filter)
519 {
520         m_filters.append(filter);
521 }
522
523 void ProcessThread::setRenamePattern(const QString &pattern)
524 {
525         QString newPattern = pattern.simplified();
526         if(!newPattern.isEmpty()) m_renamePattern = newPattern;
527 }
528
529 ////////////////////////////////////////////////////////////
530 // EVENTS
531 ////////////////////////////////////////////////////////////
532
533 /*NONE*/