OSDN Git Service

Fixed number of tools (only relevant for DEBUG builds) + fixed an out-of-bounds array...
[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_overwriteSkipExistingFile(false),
67         m_overwriteReplacesExisting(false),
68         m_initialized(-1),
69         m_aborted(false),
70         m_propDetect(new WaveProperties())
71 {
72         connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
73         connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
74
75         connect(m_propDetect, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
76         connect(m_propDetect, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
77
78         m_currentStep = UnknownStep;
79 }
80
81 ProcessThread::~ProcessThread(void)
82 {
83         while(!m_tempFiles.isEmpty())
84         {
85                 lamexp_remove_file(m_tempFiles.takeFirst());
86         }
87
88         while(!m_filters.isEmpty())
89         {
90                 delete m_filters.takeFirst();
91         }
92
93         LAMEXP_DELETE(m_encoder);
94         LAMEXP_DELETE(m_propDetect);
95
96         emit processFinished();
97 }
98
99 ////////////////////////////////////////////////////////////
100 // Init Function
101 ////////////////////////////////////////////////////////////
102
103 bool ProcessThread::init(void)
104 {
105         if(m_initialized < 0)
106         {
107                 m_initialized = 0;
108
109                 //Initialize job status
110                 qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
111                 emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
112
113                 //Initialize log
114                 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()));
115                 handleMessage("\n-------------------------------\n");
116
117                 return true;
118         }
119
120         qWarning("[ProcessThread::init] Job %s already initialialized, skipping!", m_jobId.toString().toLatin1().constData());
121         return false;
122 }
123
124 bool ProcessThread::start(QThreadPool *pool)
125 {
126         //Make sure object was initialized correctly
127         if(m_initialized < 0)
128         {
129                 THROW("Object not initialized yet!");
130         }
131
132         if(m_initialized < 1)
133         {
134                 m_initialized = 1;
135
136                 m_outFileName.clear();
137                 bool bSuccess = false;
138
139                 //Generate output file name
140                 switch(generateOutFileName(m_outFileName))
141                 {
142                 case 1:
143                         //File name generated successfully :-)
144                         bSuccess = true;
145                         pool->start(this);
146                         break;
147                 case -1:
148                         //File name already exists -> skipping!
149                         emit processStateChanged(m_jobId, tr("Skipped."), ProgressModel::JobSkipped);
150                         emit processStateFinished(m_jobId, m_outFileName, -1);
151                         break;
152                 default:
153                         //File name could not be generated
154                         emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
155                         emit processStateFinished(m_jobId, m_outFileName, 0);
156                         break;
157                 }
158
159                 if(!bSuccess)
160                 {
161                         emit processFinished();
162                 }
163
164                 return bSuccess;
165         }
166
167         qWarning("[ProcessThread::start] Job %s already started, skipping!", m_jobId.toString().toLatin1().constData());
168         return false;
169 }
170
171 ////////////////////////////////////////////////////////////
172 // Thread Entry Point
173 ////////////////////////////////////////////////////////////
174
175 void ProcessThread::run()
176 {
177         try
178         {
179                 processFile();
180         }
181         catch(const std::exception &error)
182         {
183                 fflush(stdout); fflush(stderr);
184                 fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
185                 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
186         }
187         catch(...)
188         {
189                 fflush(stdout); fflush(stderr);
190                 fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
191                 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
192         }
193 }
194
195 void ProcessThread::processFile()
196 {
197         m_aborted = false;
198         bool bSuccess = true;
199
200         //Make sure object was initialized correctly
201         if(m_initialized < 1)
202         {
203                 THROW("Object not initialized yet!");
204         }
205
206         QString sourceFile = m_audioFile.filePath();
207
208         //------------------
209         //Decode source file
210         //------------------
211         const AudioFileModel_TechInfo &formatInfo = m_audioFile.techInfo();
212         if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion()))
213         {
214                 m_currentStep = DecodingStep;
215                 AbstractDecoder *decoder = DecoderRegistry::lookup(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion());
216                 
217                 if(decoder)
218                 {
219                         QString tempFile = generateTempFileName();
220
221                         connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
222                         connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
223
224                         bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
225                         LAMEXP_DELETE(decoder);
226
227                         if(bSuccess)
228                         {
229                                 sourceFile = tempFile;
230                                 m_audioFile.techInfo().setContainerType(QString::fromLatin1("Wave"));
231                                 m_audioFile.techInfo().setAudioType(QString::fromLatin1("PCM"));
232
233                                 if(QFileInfo(sourceFile).size() >= 4294967296i64)
234                                 {
235                                         handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
236                                 }
237
238                                 handleMessage("\n-------------------------------\n");
239                         }
240                 }
241                 else
242                 {
243                         if(QFileInfo(m_outFileName).exists() && (QFileInfo(m_outFileName).size() < 512)) QFile::remove(m_outFileName);
244                         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()));
245                         emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
246                         emit processStateFinished(m_jobId, m_outFileName, 0);
247                         return;
248                 }
249         }
250
251         //------------------------------------
252         //Update audio properties after decode
253         //------------------------------------
254         if(bSuccess && !m_aborted && IS_WAVE(m_audioFile.techInfo()))
255         {
256                 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
257                 {
258                         m_currentStep = AnalyzeStep;
259                         bSuccess = m_propDetect->detect(sourceFile, &m_audioFile.techInfo(), &m_aborted);
260
261                         if(bSuccess)
262                         {
263                                 handleMessage("\n-------------------------------\n");
264
265                                 //Do we need to take care if Stereo downmix?
266                                 if(m_encoder->supportedChannelCount())
267                                 {
268                                         insertDownmixFilter();
269                                 }
270
271                                 //Do we need to take care of downsampling the input?
272                                 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths())
273                                 {
274                                         insertDownsampleFilter();
275                                 }
276                         }
277                 }
278         }
279
280         //-----------------------
281         //Apply all audio filters
282         //-----------------------
283         if(bSuccess)
284         {
285                 while(!m_filters.isEmpty() && !m_aborted)
286                 {
287                         QString tempFile = generateTempFileName();
288                         AbstractFilter *poFilter = m_filters.takeFirst();
289                         m_currentStep = FilteringStep;
290
291                         connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
292                         connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
293
294                         if(poFilter->apply(sourceFile, tempFile, &m_audioFile.techInfo(), &m_aborted))
295                         {
296                                 sourceFile = tempFile;
297                         }
298
299                         handleMessage("\n-------------------------------\n");
300                         delete poFilter;
301                 }
302         }
303
304         //-----------------
305         //Encode audio file
306         //-----------------
307         if(bSuccess && !m_aborted)
308         {
309                 m_currentStep = EncodingStep;
310                 bSuccess = m_encoder->encode(sourceFile, m_audioFile.metaInfo(), m_audioFile.techInfo().duration(), m_outFileName, &m_aborted);
311         }
312
313         //Clean-up
314         if((!bSuccess) || m_aborted)
315         {
316                 QFileInfo fileInfo(m_outFileName);
317                 if(fileInfo.exists() && (fileInfo.size() < 512))
318                 {
319                         QFile::remove(m_outFileName);
320                 }
321         }
322
323         //Make sure output file exists
324         if(bSuccess && (!m_aborted))
325         {
326                 QFileInfo fileInfo(m_outFileName);
327                 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
328         }
329
330         lamexp_sleep(125);
331
332         //Report result
333         emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
334         emit processStateFinished(m_jobId, m_outFileName, (bSuccess ? 1 : 0));
335
336         qDebug("Process thread is done.");
337 }
338
339 ////////////////////////////////////////////////////////////
340 // SLOTS
341 ////////////////////////////////////////////////////////////
342
343 void ProcessThread::handleUpdate(int progress)
344 {
345         //qDebug("Progress: %d\n", progress);
346         
347         switch(m_currentStep)
348         {
349         case EncodingStep:
350                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
351                 break;
352         case AnalyzeStep:
353                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
354                 break;
355         case FilteringStep:
356                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
357                 break;
358         case DecodingStep:
359                 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
360                 break;
361         }
362 }
363
364 void ProcessThread::handleMessage(const QString &line)
365 {
366         emit processMessageLogged(m_jobId, line);
367 }
368
369 ////////////////////////////////////////////////////////////
370 // PRIVAE FUNCTIONS
371 ////////////////////////////////////////////////////////////
372
373 int ProcessThread::generateOutFileName(QString &outFileName)
374 {
375         outFileName.clear();
376
377         //Make sure the source file exists
378         QFileInfo sourceFile(m_audioFile.filePath());
379         if(!sourceFile.exists() || !sourceFile.isFile())
380         {
381                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
382                 return 0;
383         }
384
385         //Make sure the source file readable
386         QFile readTest(sourceFile.canonicalFilePath());
387         if(!readTest.open(QIODevice::ReadOnly))
388         {
389                 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), QDir::toNativeSeparators(readTest.fileName())));
390                 return 0;
391         }
392         else
393         {
394                 readTest.close();
395         }
396
397         QString baseName = sourceFile.completeBaseName();
398         QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
399
400         //Prepend relative source file path?
401         if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
402         {
403                 QDir rootDir = sourceFile.dir();
404                 while(!rootDir.isRoot())
405                 {
406                         if(!rootDir.cdUp()) break;
407                 }
408                 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
409         }
410         
411         //Make sure output directory does exist
412         if(!targetDir.exists())
413         {
414                 targetDir.mkpath(".");
415                 if(!targetDir.exists())
416                 {
417                         handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), QDir::toNativeSeparators(targetDir.absolutePath())));
418                         return 0;
419                 }
420         }
421         
422         //Make sure that the output dir is writable
423         QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
424         if(!writeTest.open(QIODevice::ReadWrite))
425         {
426                 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), QDir::toNativeSeparators(targetDir.absolutePath())));
427                 return 0;
428         }
429         else
430         {
431                 writeTest.close();
432                 writeTest.remove();
433         }
434
435         //Apply rename pattern
436         QString fileName = applyRenamePattern(baseName, m_audioFile.metaInfo());
437
438         //Generate full output path
439         outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
440
441         //Skip file, if target file exists (optional!)
442         if(m_overwriteSkipExistingFile && QFileInfo(outFileName).exists())
443         {
444                 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to skip this file:"), QDir::toNativeSeparators(outFileName)));
445                 handleMessage(tr("If you don't want existing files to be skipped, please change the overwrite mode!"));
446                 return -1;
447         }
448
449         //Delete file, if target file exists (optional!)
450         if(m_overwriteReplacesExisting && QFileInfo(outFileName).exists())
451         {
452                 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to delete existing file:"), QDir::toNativeSeparators(outFileName)));
453                 bool bOkay = false;
454                 for(int i = 0; i < 16; i++)
455                 {
456                         bOkay = QFile::remove(outFileName);
457                         if(bOkay) break;
458                         lamexp_sleep(125);
459                 }
460                 if(QFileInfo(outFileName).exists() || (!bOkay))
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())
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_overwriteSkipExistingFile = false;
685                 m_overwriteReplacesExisting = false;
686         }
687
688         m_overwriteSkipExistingFile = bSkipExistingFile;
689         m_overwriteReplacesExisting = bReplacesExisting;
690 }
691
692 ////////////////////////////////////////////////////////////
693 // EVENTS
694 ////////////////////////////////////////////////////////////
695
696 /*NONE*/