OSDN Git Service

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