OSDN Git Service

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