Some code refactoring.
[LameXP.git] / src / Thread_Process.cpp
blobe6e33f7ec9d7802837a6595c576597db278a0114
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2017 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.
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.
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.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Thread_Process.h"
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"
38 //MUtils
39 #include <MUtils/Global.h>
40 #include <MUtils/OSSupport.h>
41 #include <MUtils/Version.h>
43 //Qt
44 #include <QUuid>
45 #include <QFileInfo>
46 #include <QDir>
47 #include <QMutex>
48 #include <QMutexLocker>
49 #include <QDate>
50 #include <QThreadPool>
52 //CRT
53 #include <limits.h>
54 #include <time.h>
55 #include <stdlib.h>
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)
61 ////////////////////////////////////////////////////////////
62 // Constructor
63 ////////////////////////////////////////////////////////////
65 ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &outputDirectory, const QString &tempDirectory, AbstractEncoder *encoder, const bool prependRelativeSourcePath)
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())
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);
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);
85 m_currentStep = UnknownStep;
88 ProcessThread::~ProcessThread(void)
90 while(!m_tempFiles.isEmpty())
92 MUtils::remove_file(m_tempFiles.takeFirst());
95 while(!m_filters.isEmpty())
97 delete m_filters.takeFirst();
100 MUTILS_DELETE(m_encoder);
101 MUTILS_DELETE(m_propDetect);
103 emit processFinished();
106 ////////////////////////////////////////////////////////////
107 // Init Function
108 ////////////////////////////////////////////////////////////
110 bool ProcessThread::init(void)
112 if(m_initialized.testAndSetOrdered((-1), 0))
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);
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");
122 return true;
125 qWarning("[ProcessThread::init] Job %s already initialialized, skipping!", m_jobId.toString().toLatin1().constData());
126 return false;
129 bool ProcessThread::start(QThreadPool *const pool)
131 //Make sure object was initialized correctly
132 if (m_initialized < 0)
134 MUTILS_THROW("Object not initialized yet!");
137 if (m_initialized.testAndSetOrdered(0, 1))
139 m_outFileName.clear();
140 m_aborted.fetchAndStoreOrdered(0);
141 bool bSuccess = false;
143 //Generate output file name
144 switch(generateOutFileName(m_outFileName))
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;
163 if(!bSuccess)
165 emit processFinished();
168 return bSuccess;
171 qWarning("[ProcessThread::start] Job %s already started, skipping!", m_jobId.toString().toLatin1().constData());
172 return false;
175 ////////////////////////////////////////////////////////////
176 // Thread Entry Point
177 ////////////////////////////////////////////////////////////
179 void ProcessThread::run()
183 processFile();
185 catch(const std::exception &error)
187 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
188 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
190 catch(...)
192 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
193 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
197 void ProcessThread::processFile()
199 m_aborted = false;
200 bool bSuccess = true;
202 //Make sure object was initialized correctly
203 if(m_initialized < 1)
205 MUTILS_THROW("Object not initialized yet!");
208 QString sourceFile = m_audioFile.filePath();
210 //-----------------------------------------------------
211 // Decode source file
212 //-----------------------------------------------------
214 const AudioFileModel_TechInfo &formatInfo = m_audioFile.techInfo();
215 if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion()))
217 m_currentStep = DecodingStep;
218 AbstractDecoder *decoder = DecoderRegistry::lookup(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion());
220 if(decoder)
222 QString tempFile = generateTempFileName();
224 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
225 connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
227 bSuccess = decoder->decode(sourceFile, tempFile, m_aborted);
228 MUTILS_DELETE(decoder);
230 if(bSuccess)
232 sourceFile = tempFile;
233 m_audioFile.techInfo().setContainerType(QString::fromLatin1("Wave"));
234 m_audioFile.techInfo().setAudioType(QString::fromLatin1("PCM"));
236 if(QFileInfo(sourceFile).size() >= 4294967296i64)
238 handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
241 handleMessage("\n-------------------------------\n");
244 else
246 if(QFileInfo(m_outFileName).exists() && (QFileInfo(m_outFileName).size() < 512)) QFile::remove(m_outFileName);
247 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()));
248 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
249 emit processStateFinished(m_jobId, m_outFileName, 0);
250 return;
254 //-----------------------------------------------------
255 // Update audio properties after decode
256 //-----------------------------------------------------
258 if(bSuccess && (!m_aborted) && IS_WAVE(m_audioFile.techInfo()))
260 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
262 m_currentStep = AnalyzeStep;
263 bSuccess = m_propDetect->detect(sourceFile, &m_audioFile.techInfo(), m_aborted);
265 if(bSuccess)
267 handleMessage("\n-------------------------------\n");
269 //Do we need to take care if Stereo downmix?
270 const unsigned int *const supportedChannelCount = m_encoder->supportedChannelCount();
271 if(supportedChannelCount && supportedChannelCount[0])
273 insertDownmixFilter(supportedChannelCount);
276 //Do we need to take care of downsampling the input?
277 const unsigned int *const supportedSamplerates = m_encoder->supportedSamplerates();
278 const unsigned int *const supportedBitdepths = m_encoder->supportedBitdepths();
279 if((supportedSamplerates && supportedSamplerates[0]) || (supportedBitdepths && supportedBitdepths[0]))
281 insertDownsampleFilter(supportedSamplerates, supportedBitdepths);
287 //-----------------------------------------------------
288 // Apply all audio filters
289 //-----------------------------------------------------
291 while(bSuccess && (!m_filters.isEmpty()) && (!m_aborted))
293 QString tempFile = generateTempFileName();
294 AbstractFilter *poFilter = m_filters.takeFirst();
295 m_currentStep = FilteringStep;
297 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
298 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
300 const AbstractFilter::FilterResult filterResult = poFilter->apply(sourceFile, tempFile, &m_audioFile.techInfo(), m_aborted);
301 switch (filterResult)
303 case AbstractFilter::FILTER_SUCCESS:
304 sourceFile = tempFile;
305 break;
306 case AbstractFilter::FILTER_FAILURE:
307 bSuccess = false;
308 break;
311 handleMessage("\n-------------------------------\n");
312 delete poFilter;
315 //-----------------------------------------------------
316 // Encode audio file
317 //-----------------------------------------------------
319 if(bSuccess && (!m_aborted))
321 m_currentStep = EncodingStep;
322 bSuccess = m_encoder->encode(sourceFile, m_audioFile.metaInfo(), m_audioFile.techInfo().duration(), m_audioFile.techInfo().audioChannels(), m_outFileName, m_aborted);
325 //Clean-up
326 if((!bSuccess) || MUTILS_BOOLIFY(m_aborted))
328 QFileInfo fileInfo(m_outFileName);
329 if(fileInfo.exists() && (fileInfo.size() < 1024))
331 QFile::remove(m_outFileName);
335 //Make sure output file exists
336 if(bSuccess && (!m_aborted))
338 const QFileInfo fileInfo(m_outFileName);
339 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() >= 1024);
342 //-----------------------------------------------------
343 // Finalize
344 //-----------------------------------------------------
346 if (bSuccess && (!m_aborted) && m_keepDateTime)
348 updateFileTime(m_audioFile.filePath(), m_outFileName);
351 MUtils::OS::sleep_ms(12);
353 //Report result
354 emit processStateChanged(m_jobId, (MUTILS_BOOLIFY(m_aborted) ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && (!m_aborted)) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
355 emit processStateFinished(m_jobId, m_outFileName, (bSuccess ? 1 : 0));
357 qDebug("Process thread is done.");
360 ////////////////////////////////////////////////////////////
361 // SLOTS
362 ////////////////////////////////////////////////////////////
364 void ProcessThread::handleUpdate(int progress)
366 //qDebug("Progress: %d\n", progress);
368 switch(m_currentStep)
370 case EncodingStep:
371 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
372 break;
373 case AnalyzeStep:
374 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
375 break;
376 case FilteringStep:
377 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
378 break;
379 case DecodingStep:
380 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
381 break;
385 void ProcessThread::handleMessage(const QString &line)
387 emit processMessageLogged(m_jobId, line);
390 ////////////////////////////////////////////////////////////
391 // PRIVAE FUNCTIONS
392 ////////////////////////////////////////////////////////////
394 int ProcessThread::generateOutFileName(QString &outFileName)
396 outFileName.clear();
398 //Make sure the source file exists
399 const QFileInfo sourceFile(m_audioFile.filePath());
400 if(!(sourceFile.exists() && sourceFile.isFile()))
402 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
403 return 0;
406 //Make sure the source file readable
407 QFile readTest(sourceFile.canonicalFilePath());
408 if(!readTest.open(QIODevice::ReadOnly))
410 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), QDir::toNativeSeparators(readTest.fileName())));
411 return 0;
413 else
415 readTest.close();
418 QDir targetDir(MUtils::clean_file_path(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory, false));
420 //Prepend relative source file path?
421 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
423 QDir sourceDir = sourceFile.dir();
424 if (!sourceDir.isRoot())
426 quint32 depth = 0;
427 while ((!sourceDir.isRoot()) && (++depth <= 0xFF))
429 if (!sourceDir.cdUp()) break;
431 const QString postfix = QFileInfo(sourceDir.relativeFilePath(sourceFile.canonicalFilePath())).path();
432 targetDir.setPath(MUtils::clean_file_path(QString("%1/%2").arg(targetDir.absolutePath(), postfix), false));
436 //Make sure output directory does exist
437 if(!targetDir.exists())
439 targetDir.mkpath(".");
440 if(!targetDir.exists())
442 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), QDir::toNativeSeparators(targetDir.absolutePath())));
443 return 0;
447 //Make sure that the output dir is writable
448 QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), MUtils::next_rand_str()));
449 if(!writeTest.open(QIODevice::ReadWrite))
451 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), QDir::toNativeSeparators(targetDir.absolutePath())));
452 return 0;
454 else
456 writeTest.remove();
459 //File extension
460 const QString fileExt = m_renameFileExt.isEmpty() ? QString::fromUtf8(m_encoder->toEncoderInfo()->extension()) : m_renameFileExt;
462 //Generate file name
463 const QString fileName = MUtils::clean_file_name(QString("%1.%2").arg(applyRegularExpression(applyRenamePattern(sourceFile.completeBaseName(), m_audioFile.metaInfo())), fileExt), true);
465 //Generate full output path
466 outFileName = QString("%1/%2").arg(targetDir.canonicalPath(), fileName);
468 //Skip file, if target file exists (optional!)
469 if((m_overwriteMode == OverwriteMode_SkipExisting) && QFileInfo(outFileName).exists())
471 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to skip this file:"), QDir::toNativeSeparators(outFileName)));
472 handleMessage(tr("If you don't want existing files to be skipped, please change the overwrite mode!"));
473 return -1;
476 //Delete file, if target file exists (optional!)
477 if((m_overwriteMode == OverwriteMode_Overwrite) && QFileInfo(outFileName).exists() && QFileInfo(outFileName).isFile())
479 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to delete existing file:"), QDir::toNativeSeparators(outFileName)));
480 bool removed = false;
481 if(sourceFile.canonicalFilePath().compare(QFileInfo(outFileName).absoluteFilePath(), Qt::CaseInsensitive) != 0)
483 for(int i = 0; i < 16; i++)
485 if(QFile::remove(outFileName))
487 removed = true;
488 break;
490 MUtils::OS::sleep_ms(1);
493 if(!removed)
495 handleMessage(QString("%1\n").arg(tr("Failed to delete existing target file, will save to another file name!")));
499 //Generate final name
500 for (int n = 2; n <= 99999; ++n)
502 //Check file existence
503 QFileInfo outFileInfo(outFileName);
504 if (outFileInfo.exists())
506 outFileName = QString("%1/%2 (%3).%4").arg(outFileInfo.canonicalPath(), outFileInfo.completeBaseName(), QString::number(n), outFileInfo.suffix());
507 continue;
510 //Create placeholder
511 QFile placeholder(outFileName);
512 if (placeholder.open(QIODevice::WriteOnly))
514 placeholder.close();
515 return 1;
519 handleMessage(QString("%1\n").arg(tr("Failed to generate non-existing target file name!")));
520 return 0;
523 QString ProcessThread::applyRenamePattern(const QString &baseName, const AudioFileModel_MetaInfo &metaInfo)
525 QString fileName = m_renamePattern;
527 fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
528 fileName.replace("<TrackNo>", QString().sprintf("%02d", metaInfo.position()), Qt::CaseInsensitive);
529 fileName.replace("<Title>", STRDEF(metaInfo.title(), tr("Unknown Title")) , Qt::CaseInsensitive);
530 fileName.replace("<Artist>", STRDEF(metaInfo.artist(), tr("Unknown Artist")), Qt::CaseInsensitive);
531 fileName.replace("<Album>", STRDEF(metaInfo.album(), tr("Unknown Album")), Qt::CaseInsensitive);
532 fileName.replace("<Year>", QString().sprintf("%04d", metaInfo.year()), Qt::CaseInsensitive);
533 fileName.replace("<Comment>", STRDEF(metaInfo.comment(), tr("Unknown Comment")), Qt::CaseInsensitive);
535 return fileName.trimmed().isEmpty() ? baseName : fileName;
538 QString ProcessThread::applyRegularExpression(const QString &baseName)
540 if(m_renameRegExp_Search.isEmpty() || m_renameRegExp_Replace.isEmpty())
542 return baseName;
545 QRegExp regExp(m_renameRegExp_Search);
546 if(!regExp.isValid())
548 qWarning("Invalid regular expression detected -> cannot rename!");
549 return baseName;
552 const QString fileName = QString(baseName).replace(regExp, m_renameRegExp_Replace);
553 return fileName.trimmed().isEmpty() ? baseName : fileName;
556 QString ProcessThread::generateTempFileName(void)
558 const QString tempFileName = MUtils::make_temp_file(m_tempDirectory, "wav", true);
559 if(tempFileName.isEmpty())
561 return QString("%1/~whoops%2.wav").arg(m_tempDirectory, QString::number(MUtils::next_rand_u32()));
564 m_tempFiles << tempFileName;
565 return tempFileName;
568 bool ProcessThread::insertDownsampleFilter(const unsigned int *const supportedSamplerates, const unsigned int *const supportedBitdepths)
570 int targetSampleRate = 0, targetBitDepth = 0;
572 /* Adjust sample rate */
573 if(supportedSamplerates && m_audioFile.techInfo().audioSamplerate())
575 const unsigned int inputRate = m_audioFile.techInfo().audioSamplerate();
576 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
578 //Find the most suitable supported sampling rate
579 for(int i = 0; supportedSamplerates[i]; i++)
581 currentDiff = DIFF(inputRate, supportedSamplerates[i]);
582 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestRate < supportedSamplerates[i])))
584 bestRate = supportedSamplerates[i];
585 minimumDiff = currentDiff;
586 if(!(minimumDiff > 0)) break;
590 if(bestRate != inputRate)
592 targetSampleRate = (bestRate != UINT_MAX) ? bestRate : supportedSamplerates[0];
596 /* Adjust bit depth (word size) */
597 if(supportedBitdepths && m_audioFile.techInfo().audioBitdepth())
599 const unsigned int inputBPS = m_audioFile.techInfo().audioBitdepth();
600 bool bAdjustBitdepth = true;
602 //Is the input bit depth supported exactly? (including IEEE Float)
603 for(int i = 0; supportedBitdepths[i]; i++)
605 if(supportedBitdepths[i] == inputBPS) bAdjustBitdepth = false;
608 if(bAdjustBitdepth)
610 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
611 const unsigned int originalBPS = (inputBPS == AudioFileModel::BITDEPTH_IEEE_FLOAT32) ? 32 : inputBPS;
613 //Find the most suitable supported bit depth
614 for(int i = 0; supportedBitdepths[i]; i++)
616 if(supportedBitdepths[i] == AudioFileModel::BITDEPTH_IEEE_FLOAT32) continue;
618 currentDiff = DIFF(originalBPS, supportedBitdepths[i]);
619 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBitdepths[i])))
621 bestBPS = supportedBitdepths[i];
622 minimumDiff = currentDiff;
623 if(!(minimumDiff > 0)) break;
627 if(bestBPS != originalBPS)
629 targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBitdepths[0];
634 //Check if downsampling filter is already in the chain
635 if (targetSampleRate || targetBitDepth)
637 for (int i = 0; i < m_filters.count(); i++)
639 if (dynamic_cast<ResampleFilter*>(m_filters.at(i)))
641 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
642 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
643 targetSampleRate = targetBitDepth = 0;
648 /* Insert the filter */
649 if(targetSampleRate || targetBitDepth)
651 m_filters.append(new ResampleFilter(targetSampleRate, targetBitDepth));
652 return true;
655 return false; /*did not insert the resample filter */
658 bool ProcessThread::insertDownmixFilter(const unsigned int *const supportedChannels)
660 //Determine number of channels in source
661 const unsigned int channels = m_audioFile.techInfo().audioChannels();
662 bool requiresDownmix = (channels > 0);
664 //Check whether encoder requires downmixing
665 if(requiresDownmix)
667 for (int i = 0; supportedChannels[i]; i++)
669 if (supportedChannels[i] == channels)
671 requiresDownmix = false;
672 break;
677 //Check if downmixing filter is already in the chain
678 if (requiresDownmix)
680 for (int i = 0; i < m_filters.count(); i++)
682 if (dynamic_cast<DownmixFilter*>(m_filters.at(i)))
684 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
685 handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
686 requiresDownmix = false;
687 break;
692 //Now add the downmixing filter, if needed
693 if(requiresDownmix)
695 m_filters.append(new DownmixFilter());
696 return true;
699 return false; /*did not insert the downmix filter*/
702 bool ProcessThread::updateFileTime(const QString &originalFile, const QString &modifiedFile)
704 bool success = false;
706 QFileInfo originalFileInfo(originalFile);
707 const QDateTime timeCreated = originalFileInfo.created(), timeLastMod = originalFileInfo.lastModified();
708 if (timeCreated.isValid() && timeLastMod.isValid())
710 if (!MUtils::OS::set_file_time(modifiedFile, timeCreated, timeLastMod))
712 qWarning("Failed to update creation/modified time of output file: \"%s\"", MUTILS_UTF8(modifiedFile));
715 else
717 qWarning("Failed to read creation/modified time of source file: \"%s\"", MUTILS_UTF8(originalFile));
720 return success;
723 ////////////////////////////////////////////////////////////
724 // PUBLIC FUNCTIONS
725 ////////////////////////////////////////////////////////////
727 void ProcessThread::addFilter(AbstractFilter *filter)
729 m_filters.append(filter);
732 void ProcessThread::setRenamePattern(const QString &pattern)
734 const QString newPattern = pattern.simplified();
735 if(!newPattern.isEmpty()) m_renamePattern = newPattern;
738 void ProcessThread::setRenameRegExp(const QString &search, const QString &replace)
740 const QString newSearch = search.trimmed(), newReplace = replace.simplified();
741 if((!newSearch.isEmpty()) && (!newReplace.isEmpty()))
743 m_renameRegExp_Search = newSearch;
744 m_renameRegExp_Replace = newReplace;
748 void ProcessThread::setRenameFileExt(const QString &fileExtension)
750 m_renameFileExt = MUtils::clean_file_name(fileExtension, false).simplified();
751 while(m_renameFileExt.startsWith('.'))
753 m_renameFileExt = m_renameFileExt.mid(1).trimmed();
757 void ProcessThread::setOverwriteMode(const bool &bSkipExistingFile, const bool &bReplacesExisting)
759 if(bSkipExistingFile && bReplacesExisting)
761 qWarning("Inconsistent overwrite flags -> reverting to default!");
762 m_overwriteMode = OverwriteMode_KeepBoth;
764 else
766 m_overwriteMode = OverwriteMode_KeepBoth;
767 if(bSkipExistingFile) m_overwriteMode = OverwriteMode_SkipExisting;
768 if(bReplacesExisting) m_overwriteMode = OverwriteMode_Overwrite;
772 void ProcessThread::setKeepDateTime(const bool &keepDateTime)
774 m_keepDateTime = keepDateTime;
777 ////////////////////////////////////////////////////////////
778 // EVENTS
779 ////////////////////////////////////////////////////////////
781 /*NONE*/