OSDN Git Service

Bump version.
[lamexp/LameXP.git] / src / Thread_Process.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "Thread_Process.h"
24
25 //Internal
26 #include "Global.h"
27 #include "Model_AudioFile.h"
28 #include "Model_Progress.h"
29 #include "Encoder_Abstract.h"
30 #include "Decoder_Abstract.h"
31 #include "Filter_Abstract.h"
32 #include "Filter_Downmix.h"
33 #include "Filter_Resample.h"
34 #include "Tool_WaveProperties.h"
35 #include "Registry_Decoder.h"
36 #include "Model_Settings.h"
37
38 //MUtils
39 #include <MUtils/Global.h>
40 #include <MUtils/OSSupport.h>
41 #include <MUtils/Version.h>
42
43 //Qt
44 #include <QUuid>
45 #include <QFileInfo>
46 #include <QDir>
47 #include <QMutex>
48 #include <QMutexLocker>
49 #include <QDate>
50 #include <QThreadPool>
51
52 //CRT
53 #include <limits.h>
54 #include <time.h>
55 #include <stdlib.h>
56
57 #define DIFF(X,Y) ((X > Y) ? (X-Y) : (Y-X))
58 #define IS_WAVE(X) ((X.containerType().compare("Wave", Qt::CaseInsensitive) == 0) && (X.audioType().compare("PCM", Qt::CaseInsensitive) == 0))
59 #define STRDEF(STR,DEF) ((!STR.isEmpty()) ? STR : DEF)
60
61 ////////////////////////////////////////////////////////////
62 // Constructor
63 ////////////////////////////////////////////////////////////
64
65 ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, const QString &tempDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
66 :
67         m_audioFile(audioFile),
68         m_outputDirectory(outputDirectory),
69         m_tempDirectory(tempDirectory),
70         m_encoder(encoder),
71         m_jobId(QUuid::createUuid()),
72         m_prependRelativeSourcePath(prependRelativeSourcePath),
73         m_renamePattern("<BaseName>"),
74         m_overwriteMode(OverwriteMode_KeepBoth),
75         m_keepDateTime(false),
76         m_initialized(-1),
77         m_aborted(false),
78         m_propDetect(new WaveProperties())
79 {
80         connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
81         connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
82
83         connect(m_propDetect, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
84         connect(m_propDetect, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
85
86         m_currentStep = UnknownStep;
87 }
88
89 ProcessThread::~ProcessThread(void)
90 {
91         while(!m_tempFiles.isEmpty())
92         {
93                 MUtils::remove_file(m_tempFiles.takeFirst());
94         }
95
96         while(!m_filters.isEmpty())
97         {
98                 delete m_filters.takeFirst();
99         }
100
101         MUTILS_DELETE(m_encoder);
102         MUTILS_DELETE(m_propDetect);
103
104         emit processFinished();
105 }
106
107 ////////////////////////////////////////////////////////////
108 // Init Function
109 ////////////////////////////////////////////////////////////
110
111 bool ProcessThread::init(void)
112 {
113         if(m_initialized < 0)
114         {
115                 m_initialized = 0;
116
117                 //Initialize job status
118                 qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
119                 emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
120
121                 //Initialize log
122                 handleMessage(QString().sprintf("LameXP v%u.%02u (Build #%u), compiled on %s at %s", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build(), MUTILS_UTF8(MUtils::Version::app_build_date().toString(Qt::ISODate)), MUTILS_UTF8(MUtils::Version::app_build_time().toString(Qt::ISODate))));
123                 handleMessage("\n-------------------------------\n");
124
125                 return true;
126         }
127
128         qWarning("[ProcessThread::init] Job %s already initialialized, skipping!", m_jobId.toString().toLatin1().constData());
129         return false;
130 }
131
132 bool ProcessThread::start(QThreadPool *const pool)
133 {
134         //Make sure object was initialized correctly
135         if(m_initialized < 0)
136         {
137                 MUTILS_THROW("Object not initialized yet!");
138         }
139
140         if(m_initialized < 1)
141         {
142                 m_initialized = 1;
143
144                 m_outFileName.clear();
145                 bool bSuccess = false;
146
147                 //Generate output file name
148                 switch(generateOutFileName(m_outFileName))
149                 {
150                 case 1:
151                         //File name generated successfully :-)
152                         bSuccess = true;
153                         pool->start(this);
154                         break;
155                 case -1:
156                         //File name already exists -> skipping!
157                         emit processStateChanged(m_jobId, tr("Skipped."), ProgressModel::JobSkipped);
158                         emit processStateFinished(m_jobId, m_outFileName, -1);
159                         break;
160                 default:
161                         //File name could not be generated
162                         emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
163                         emit processStateFinished(m_jobId, m_outFileName, 0);
164                         break;
165                 }
166
167                 if(!bSuccess)
168                 {
169                         emit processFinished();
170                 }
171
172                 return bSuccess;
173         }
174
175         qWarning("[ProcessThread::start] Job %s already started, skipping!", m_jobId.toString().toLatin1().constData());
176         return false;
177 }
178
179 ////////////////////////////////////////////////////////////
180 // Thread Entry Point
181 ////////////////////////////////////////////////////////////
182
183 void ProcessThread::run()
184 {
185         try
186         {
187                 processFile();
188         }
189         catch(const std::exception &error)
190         {
191                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
192                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
193         }
194         catch(...)
195         {
196                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
197                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
198         }
199 }
200
201 void ProcessThread::processFile()
202 {
203         m_aborted = false;
204         bool bSuccess = true;
205
206         //Make sure object was initialized correctly
207         if(m_initialized < 1)
208         {
209                 MUTILS_THROW("Object not initialized yet!");
210         }
211
212         QString sourceFile = m_audioFile.filePath();
213
214         //-----------------------------------------------------
215         // Decode source file
216         //-----------------------------------------------------
217
218         const AudioFileModel_TechInfo &formatInfo = m_audioFile.techInfo();
219         if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion()))
220         {
221                 m_currentStep = DecodingStep;
222                 AbstractDecoder *decoder = DecoderRegistry::lookup(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion());
223                 
224                 if(decoder)
225                 {
226                         QString tempFile = generateTempFileName();
227
228                         connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
229                         connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
230
231                         bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
232                         MUTILS_DELETE(decoder);
233
234                         if(bSuccess)
235                         {
236                                 sourceFile = tempFile;
237                                 m_audioFile.techInfo().setContainerType(QString::fromLatin1("Wave"));
238                                 m_audioFile.techInfo().setAudioType(QString::fromLatin1("PCM"));
239
240                                 if(QFileInfo(sourceFile).size() >= 4294967296i64)
241                                 {
242                                         handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
243                                 }
244
245                                 handleMessage("\n-------------------------------\n");
246                         }
247                 }
248                 else
249                 {
250                         if(QFileInfo(m_outFileName).exists() && (QFileInfo(m_outFileName).size() < 512)) QFile::remove(m_outFileName);
251                         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.containerInfo(), tr("Audio Format:"), m_audioFile.audioCompressInfo()));
252                         emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
253                         emit processStateFinished(m_jobId, m_outFileName, 0);
254                         return;
255                 }
256         }
257
258         //-----------------------------------------------------
259         // Update audio properties after decode
260         //-----------------------------------------------------
261
262         if(bSuccess && !m_aborted && IS_WAVE(m_audioFile.techInfo()))
263         {
264                 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
265                 {
266                         m_currentStep = AnalyzeStep;
267                         bSuccess = m_propDetect->detect(sourceFile, &m_audioFile.techInfo(), &m_aborted);
268
269                         if(bSuccess)
270                         {
271                                 handleMessage("\n-------------------------------\n");
272
273                                 //Do we need to take care if Stereo downmix?
274                                 if(m_encoder->supportedChannelCount())
275                                 {
276                                         insertDownmixFilter();
277                                 }
278
279                                 //Do we need to take care of downsampling the input?
280                                 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths())
281                                 {
282                                         insertDownsampleFilter();
283                                 }
284                         }
285                 }
286         }
287
288         //-----------------------------------------------------
289         // Apply all audio filters
290         //-----------------------------------------------------
291
292         if(bSuccess)
293         {
294                 while(!m_filters.isEmpty() && !m_aborted)
295                 {
296                         QString tempFile = generateTempFileName();
297                         AbstractFilter *poFilter = m_filters.takeFirst();
298                         m_currentStep = FilteringStep;
299
300                         connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
301                         connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
302
303                         if(poFilter->apply(sourceFile, tempFile, &m_audioFile.techInfo(), &m_aborted))
304                         {
305                                 sourceFile = tempFile;
306                         }
307
308                         handleMessage("\n-------------------------------\n");
309                         delete poFilter;
310                 }
311         }
312
313         //-----------------------------------------------------
314         // Encode audio file
315         //-----------------------------------------------------
316
317         if(bSuccess && !m_aborted)
318         {
319                 m_currentStep = EncodingStep;
320                 bSuccess = m_encoder->encode(sourceFile, m_audioFile.metaInfo(), m_audioFile.techInfo().duration(), m_outFileName, &m_aborted);
321         }
322
323         //Clean-up
324         if((!bSuccess) || m_aborted)
325         {
326                 QFileInfo fileInfo(m_outFileName);
327                 if(fileInfo.exists() && (fileInfo.size() < 1024))
328                 {
329                         QFile::remove(m_outFileName);
330                 }
331         }
332
333         //Make sure output file exists
334         if(bSuccess && (!m_aborted))
335         {
336                 const QFileInfo fileInfo(m_outFileName);
337                 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() >= 1024);
338         }
339
340         //-----------------------------------------------------
341         // Finalize
342         //-----------------------------------------------------
343
344         if (bSuccess && (!m_aborted) && m_keepDateTime)
345         {
346                 updateFileTime(m_audioFile.filePath(), m_outFileName);
347         }
348
349         MUtils::OS::sleep_ms(12);
350
351         //Report result
352         emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
353         emit processStateFinished(m_jobId, m_outFileName, (bSuccess ? 1 : 0));
354
355         qDebug("Process thread is done.");
356 }
357
358 ////////////////////////////////////////////////////////////
359 // SLOTS
360 ////////////////////////////////////////////////////////////
361
362 void ProcessThread::handleUpdate(int progress)
363 {
364         //qDebug("Progress: %d\n", progress);
365         
366         switch(m_currentStep)
367         {
368         case EncodingStep:
369                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
370                 break;
371         case AnalyzeStep:
372                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
373                 break;
374         case FilteringStep:
375                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
376                 break;
377         case DecodingStep:
378                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
379                 break;
380         }
381 }
382
383 void ProcessThread::handleMessage(const QString &line)
384 {
385         emit processMessageLogged(m_jobId, line);
386 }
387
388 ////////////////////////////////////////////////////////////
389 // PRIVAE FUNCTIONS
390 ////////////////////////////////////////////////////////////
391
392 int ProcessThread::generateOutFileName(QString &outFileName)
393 {
394         outFileName.clear();
395
396         //Make sure the source file exists
397         const QFileInfo sourceFile(m_audioFile.filePath());
398         if(!(sourceFile.exists() && sourceFile.isFile()))
399         {
400                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
401                 return 0;
402         }
403
404         //Make sure the source file readable
405         QFile readTest(sourceFile.canonicalFilePath());
406         if(!readTest.open(QIODevice::ReadOnly))
407         {
408                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), QDir::toNativeSeparators(readTest.fileName())));
409                 return 0;
410         }
411         else
412         {
413                 readTest.close();
414         }
415
416         const QString baseName = sourceFile.completeBaseName();
417         QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
418
419         //Prepend relative source file path?
420         if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
421         {
422                 QDir rootDir = sourceFile.dir();
423                 while(!rootDir.isRoot())
424                 {
425                         if(!rootDir.cdUp()) break;
426                 }
427                 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
428         }
429         
430         //Make sure output directory does exist
431         if(!targetDir.exists())
432         {
433                 targetDir.mkpath(".");
434                 if(!targetDir.exists())
435                 {
436                         handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), QDir::toNativeSeparators(targetDir.absolutePath())));
437                         return 0;
438                 }
439         }
440         
441         //Make sure that the output dir is writable
442         QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), MUtils::rand_str()));
443         if(!writeTest.open(QIODevice::ReadWrite))
444         {
445                 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), QDir::toNativeSeparators(targetDir.absolutePath())));
446                 return 0;
447         }
448         else
449         {
450                 writeTest.remove();
451         }
452
453         //Apply rename pattern
454         const QString fileName = MUtils::clean_file_name(applyRegularExpression(applyRenamePattern(baseName, m_audioFile.metaInfo())));
455
456         //Generate full output path
457         
458         const QString fileExt = m_renameFileExt.isEmpty() ?  QString::fromUtf8(m_encoder->toEncoderInfo()->extension()) : m_renameFileExt;
459         outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, fileExt);
460
461         //Skip file, if target file exists (optional!)
462         if((m_overwriteMode == OverwriteMode_SkipExisting) && QFileInfo(outFileName).exists())
463         {
464                 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to skip this file:"), QDir::toNativeSeparators(outFileName)));
465                 handleMessage(tr("If you don't want existing files to be skipped, please change the overwrite mode!"));
466                 return -1;
467         }
468
469         //Delete file, if target file exists (optional!)
470         if((m_overwriteMode == OverwriteMode_Overwrite) && QFileInfo(outFileName).exists() && QFileInfo(outFileName).isFile())
471         {
472                 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to delete existing file:"), QDir::toNativeSeparators(outFileName)));
473                 if(sourceFile.canonicalFilePath().compare(QFileInfo(outFileName).absoluteFilePath(), Qt::CaseInsensitive) != 0)
474                 {
475                         for(int i = 0; i < 16; i++)
476                         {
477                                 if(QFile::remove(outFileName))
478                                 {
479                                         break;
480                                 }
481                                 MUtils::OS::sleep_ms(1);
482                         }
483                 }
484                 if(QFileInfo(outFileName).exists())
485                 {
486                         handleMessage(QString("%1\n").arg(tr("Failed to delete existing target file, will save to another file name!")));
487                 }
488         }
489
490         int n = 1;
491
492         //Generate final name
493         while(QFileInfo(outFileName).exists() && (n < (INT_MAX/2)))
494         {
495                 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), fileExt);
496         }
497
498         //Create placeholder
499         QFile placeholder(outFileName);
500         if(placeholder.open(QIODevice::WriteOnly))
501         {
502                 placeholder.close();
503         }
504
505         return 1;
506 }
507
508 QString ProcessThread::applyRenamePattern(const QString &baseName, const AudioFileModel_MetaInfo &metaInfo)
509 {
510         QString fileName = m_renamePattern;
511         
512         fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")),         Qt::CaseInsensitive);
513         fileName.replace("<TrackNo>",  QString().sprintf("%02d", metaInfo.position()),    Qt::CaseInsensitive);
514         fileName.replace("<Title>",    STRDEF(metaInfo.title(), tr("Unknown Title")) ,    Qt::CaseInsensitive);
515         fileName.replace("<Artist>",   STRDEF(metaInfo.artist(), tr("Unknown Artist")),   Qt::CaseInsensitive);
516         fileName.replace("<Album>",    STRDEF(metaInfo.album(), tr("Unknown Album")),     Qt::CaseInsensitive);
517         fileName.replace("<Year>",     QString().sprintf("%04d", metaInfo.year()),        Qt::CaseInsensitive);
518         fileName.replace("<Comment>",  STRDEF(metaInfo.comment(), tr("Unknown Comment")), Qt::CaseInsensitive);
519
520         return fileName;
521 }
522
523 QString ProcessThread::applyRegularExpression(const QString &fileName)
524 {
525         if(m_renameRegExp_Search.isEmpty() || m_renameRegExp_Replace.isEmpty())
526         {
527                 return fileName;
528         }
529
530         QRegExp regExp(m_renameRegExp_Search);
531         if(!regExp.isValid())
532         {
533                 qWarning("Invalid regular expression detected -> cannot rename!");
534                 return fileName;
535         }
536
537         return (QString(fileName).replace(regExp, m_renameRegExp_Replace));
538 }
539
540 QString ProcessThread::generateTempFileName(void)
541 {
542         const QString tempFileName = MUtils::make_temp_file(m_tempDirectory, "wav", true);
543         if(tempFileName.isEmpty())
544         {
545                 return QString("%1/~whoops%2.wav").arg(m_tempDirectory, QString::number(MUtils::next_rand32()));
546         }
547
548         m_tempFiles << tempFileName;
549         return tempFileName;
550 }
551
552 void ProcessThread::insertDownsampleFilter(void)
553 {
554         int targetSampleRate = 0;
555         int targetBitDepth = 0;
556         
557         /* Adjust sample rate */
558         if(m_encoder->supportedSamplerates() && m_audioFile.techInfo().audioSamplerate())
559         {
560                 bool applyDownsampling = true;
561         
562                 //Check if downsampling filter is already in the chain
563                 for(int i = 0; i < m_filters.count(); i++)
564                 {
565                         if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
566                         {
567                                 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
568                                 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
569                                 applyDownsampling = false;
570                         }
571                 }
572                 
573                 //Now determine the target sample rate, if required
574                 if(applyDownsampling)
575                 {
576                         const unsigned int *supportedRates = m_encoder->supportedSamplerates();
577                         const unsigned int inputRate = m_audioFile.techInfo().audioSamplerate();
578                         unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
579
580                         //Find the most suitable supported sampling rate
581                         for(int i = 0; supportedRates[i]; i++)
582                         {
583                                 currentDiff = DIFF(inputRate, supportedRates[i]);
584                                 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestRate < supportedRates[i])))
585                                 {
586                                         bestRate = supportedRates[i];
587                                         minimumDiff = currentDiff;
588                                         if(!(minimumDiff > 0)) break;
589                                 }
590                         }
591                 
592                         if(bestRate != inputRate)
593                         {
594                                 targetSampleRate = (bestRate != UINT_MAX) ? bestRate : supportedRates[0];
595                         }
596                 }
597         }
598
599         /* Adjust bit depth (word size) */
600         if(m_encoder->supportedBitdepths() && m_audioFile.techInfo().audioBitdepth())
601         {
602                 const unsigned int inputBPS = m_audioFile.techInfo().audioBitdepth();
603                 const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
604
605                 bool bAdjustBitdepth = true;
606
607                 //Is the input bit depth supported exactly? (including IEEE Float)
608                 for(int i = 0; supportedBPS[i]; i++)
609                 {
610                         if(supportedBPS[i] == inputBPS) bAdjustBitdepth = false;
611                 }
612                 
613                 if(bAdjustBitdepth)
614                 {
615                         unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
616                         const unsigned int originalBPS = (inputBPS == AudioFileModel::BITDEPTH_IEEE_FLOAT32) ? 32 : inputBPS;
617
618                         //Find the most suitable supported bit depth
619                         for(int i = 0; supportedBPS[i]; i++)
620                         {
621                                 if(supportedBPS[i] == AudioFileModel::BITDEPTH_IEEE_FLOAT32) continue;
622                                 
623                                 currentDiff = DIFF(originalBPS, supportedBPS[i]);
624                                 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBPS[i])))
625                                 {
626                                         bestBPS = supportedBPS[i];
627                                         minimumDiff = currentDiff;
628                                         if(!(minimumDiff > 0)) break;
629                                 }
630                         }
631
632                         if(bestBPS != originalBPS)
633                         {
634                                 targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBPS[0];
635                         }
636                 }
637         }
638
639         /* Insert the filter */
640         if(targetSampleRate || targetBitDepth)
641         {
642                 m_filters.append(new ResampleFilter(targetSampleRate, targetBitDepth));
643         }
644 }
645
646 void ProcessThread::insertDownmixFilter(void)
647 {
648         bool applyDownmixing = true;
649                 
650         //Check if downmixing filter is already in the chain
651         for(int i = 0; i < m_filters.count(); i++)
652         {
653                 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
654                 {
655                         qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
656                         handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
657                         applyDownmixing = false;
658                 }
659         }
660
661         //Now add the downmixing filter, if needed
662         if(applyDownmixing)
663         {
664                 bool requiresDownmix = true;
665                 const unsigned int *supportedChannels = m_encoder->supportedChannelCount();
666                 unsigned int channels = m_audioFile.techInfo().audioChannels();
667
668                 for(int i = 0; supportedChannels[i]; i++)
669                 {
670                         if(supportedChannels[i] == channels)
671                         {
672                                 requiresDownmix = false;
673                                 break;
674                         }
675                 }
676
677                 if(requiresDownmix)
678                 {
679                         m_filters.append(new DownmixFilter());
680                 }
681         }
682 }
683
684 bool ProcessThread::updateFileTime(const QString &originalFile, const QString &modifiedFile)
685 {
686         bool success = false;
687
688         QFileInfo originalFileInfo(originalFile);
689         const QDateTime timeCreated = originalFileInfo.created(), timeLastMod = originalFileInfo.lastModified();
690         if (timeCreated.isValid() && timeLastMod.isValid())
691         {
692                 if (!MUtils::OS::set_file_time(modifiedFile, timeCreated, timeLastMod))
693                 {
694                         qWarning("Failed to update creation/modified time of output file: \"%s\"", MUTILS_UTF8(modifiedFile));
695                 }
696         }
697         else
698         {
699                 qWarning("Failed to read creation/modified time of source file: \"%s\"", MUTILS_UTF8(originalFile));
700         }
701
702         return success;
703 }
704
705 ////////////////////////////////////////////////////////////
706 // PUBLIC FUNCTIONS
707 ////////////////////////////////////////////////////////////
708
709 void ProcessThread::addFilter(AbstractFilter *filter)
710 {
711         m_filters.append(filter);
712 }
713
714 void ProcessThread::setRenamePattern(const QString &pattern)
715 {
716         const QString newPattern = pattern.simplified();
717         if(!newPattern.isEmpty()) m_renamePattern = newPattern;
718 }
719
720 void ProcessThread::setRenameRegExp(const QString &search, const QString &replace)
721 {
722         const QString newSearch = search.trimmed(), newReplace = replace.simplified();
723         if((!newSearch.isEmpty()) && (!newReplace.isEmpty()))
724         {
725                 m_renameRegExp_Search  = newSearch;
726                 m_renameRegExp_Replace = newReplace;
727         }
728 }
729
730 void ProcessThread::setRenameFileExt(const QString &fileExtension)
731 {
732         m_renameFileExt = MUtils::clean_file_name(fileExtension).simplified();
733         while(m_renameFileExt.startsWith('.'))
734         {
735                 m_renameFileExt = m_renameFileExt.mid(1).trimmed();
736         }
737 }
738
739 void ProcessThread::setOverwriteMode(const bool &bSkipExistingFile, const bool &bReplacesExisting)
740 {
741         if(bSkipExistingFile && bReplacesExisting)
742         {
743                 qWarning("Inconsistent overwrite flags -> reverting to default!");
744                 m_overwriteMode = OverwriteMode_KeepBoth;
745         }
746         else
747         {
748                 m_overwriteMode = OverwriteMode_KeepBoth;
749                 if(bSkipExistingFile) m_overwriteMode = OverwriteMode_SkipExisting;
750                 if(bReplacesExisting) m_overwriteMode = OverwriteMode_Overwrite;
751         }
752 }
753
754 void ProcessThread::setKeepDateTime(const bool &keepDateTime)
755 {
756         m_keepDateTime = keepDateTime;
757 }
758
759 ////////////////////////////////////////////////////////////
760 // EVENTS
761 ////////////////////////////////////////////////////////////
762
763 /*NONE*/