Some fixes to adapt for latest MUtils changes.
[LameXP.git] / src / Thread_Process.cpp
blob081d09af4a92590ec191b94515d0b6a6856f304e
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2016 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_aborted(false),
78 m_propDetect(new WaveProperties())
80 connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
81 connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
83 connect(m_propDetect, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
84 connect(m_propDetect, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
86 m_currentStep = UnknownStep;
89 ProcessThread::~ProcessThread(void)
91 while(!m_tempFiles.isEmpty())
93 MUtils::remove_file(m_tempFiles.takeFirst());
96 while(!m_filters.isEmpty())
98 delete m_filters.takeFirst();
101 MUTILS_DELETE(m_encoder);
102 MUTILS_DELETE(m_propDetect);
104 emit processFinished();
107 ////////////////////////////////////////////////////////////
108 // Init Function
109 ////////////////////////////////////////////////////////////
111 bool ProcessThread::init(void)
113 if(m_initialized < 0)
115 m_initialized = 0;
117 //Initialize job status
118 qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
119 emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
121 //Initialize log
122 handleMessage(QString().sprintf("LameXP v%u.%02u (Build #%u), compiled on %s at %s", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build(), MUTILS_UTF8(MUtils::Version::app_build_date().toString(Qt::ISODate)), MUTILS_UTF8(MUtils::Version::app_build_time().toString(Qt::ISODate))));
123 handleMessage("\n-------------------------------\n");
125 return true;
128 qWarning("[ProcessThread::init] Job %s already initialialized, skipping!", m_jobId.toString().toLatin1().constData());
129 return false;
132 bool ProcessThread::start(QThreadPool *const pool)
134 //Make sure object was initialized correctly
135 if(m_initialized < 0)
137 MUTILS_THROW("Object not initialized yet!");
140 if(m_initialized < 1)
142 m_initialized = 1;
144 m_outFileName.clear();
145 bool bSuccess = false;
147 //Generate output file name
148 switch(generateOutFileName(m_outFileName))
150 case 1:
151 //File name generated successfully :-)
152 bSuccess = true;
153 pool->start(this);
154 break;
155 case -1:
156 //File name already exists -> skipping!
157 emit processStateChanged(m_jobId, tr("Skipped."), ProgressModel::JobSkipped);
158 emit processStateFinished(m_jobId, m_outFileName, -1);
159 break;
160 default:
161 //File name could not be generated
162 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
163 emit processStateFinished(m_jobId, m_outFileName, 0);
164 break;
167 if(!bSuccess)
169 emit processFinished();
172 return bSuccess;
175 qWarning("[ProcessThread::start] Job %s already started, skipping!", m_jobId.toString().toLatin1().constData());
176 return false;
179 ////////////////////////////////////////////////////////////
180 // Thread Entry Point
181 ////////////////////////////////////////////////////////////
183 void ProcessThread::run()
187 processFile();
189 catch(const std::exception &error)
191 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
192 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
194 catch(...)
196 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
197 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
201 void ProcessThread::processFile()
203 m_aborted = false;
204 bool bSuccess = true;
206 //Make sure object was initialized correctly
207 if(m_initialized < 1)
209 MUTILS_THROW("Object not initialized yet!");
212 QString sourceFile = m_audioFile.filePath();
214 //-----------------------------------------------------
215 // Decode source file
216 //-----------------------------------------------------
218 const AudioFileModel_TechInfo &formatInfo = m_audioFile.techInfo();
219 if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion()))
221 m_currentStep = DecodingStep;
222 AbstractDecoder *decoder = DecoderRegistry::lookup(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion());
224 if(decoder)
226 QString tempFile = generateTempFileName();
228 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
229 connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
231 bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
232 MUTILS_DELETE(decoder);
234 if(bSuccess)
236 sourceFile = tempFile;
237 m_audioFile.techInfo().setContainerType(QString::fromLatin1("Wave"));
238 m_audioFile.techInfo().setAudioType(QString::fromLatin1("PCM"));
240 if(QFileInfo(sourceFile).size() >= 4294967296i64)
242 handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
245 handleMessage("\n-------------------------------\n");
248 else
250 if(QFileInfo(m_outFileName).exists() && (QFileInfo(m_outFileName).size() < 512)) QFile::remove(m_outFileName);
251 handleMessage(QString("%1\n%2\n\n%3\t%4\n%5\t%6").arg(tr("The format of this file is NOT supported:"), m_audioFile.filePath(), tr("Container Format:"), m_audioFile.containerInfo(), tr("Audio Format:"), m_audioFile.audioCompressInfo()));
252 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
253 emit processStateFinished(m_jobId, m_outFileName, 0);
254 return;
258 //-----------------------------------------------------
259 // Update audio properties after decode
260 //-----------------------------------------------------
262 if(bSuccess && !m_aborted && IS_WAVE(m_audioFile.techInfo()))
264 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
266 m_currentStep = AnalyzeStep;
267 bSuccess = m_propDetect->detect(sourceFile, &m_audioFile.techInfo(), &m_aborted);
269 if(bSuccess)
271 handleMessage("\n-------------------------------\n");
273 //Do we need to take care if Stereo downmix?
274 const unsigned int *const supportedChannelCount = m_encoder->supportedChannelCount();
275 if(supportedChannelCount && supportedChannelCount[0])
277 insertDownmixFilter(supportedChannelCount);
280 //Do we need to take care of downsampling the input?
281 const unsigned int *const supportedSamplerates = m_encoder->supportedSamplerates();
282 const unsigned int *const supportedBitdepths = m_encoder->supportedBitdepths();
283 if((supportedSamplerates && supportedSamplerates[0]) || (supportedBitdepths && supportedBitdepths[0]))
285 insertDownsampleFilter(supportedSamplerates, supportedBitdepths);
291 //-----------------------------------------------------
292 // Apply all audio filters
293 //-----------------------------------------------------
295 while(bSuccess && (!m_filters.isEmpty()) && (!m_aborted))
297 QString tempFile = generateTempFileName();
298 AbstractFilter *poFilter = m_filters.takeFirst();
299 m_currentStep = FilteringStep;
301 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
302 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
304 const AbstractFilter::FilterResult filterResult = poFilter->apply(sourceFile, tempFile, &m_audioFile.techInfo(), &m_aborted);
305 switch (filterResult)
307 case AbstractFilter::FILTER_SUCCESS:
308 sourceFile = tempFile;
309 break;
310 case AbstractFilter::FILTER_FAILURE:
311 bSuccess = false;
312 break;
315 handleMessage("\n-------------------------------\n");
316 delete poFilter;
319 //-----------------------------------------------------
320 // Encode audio file
321 //-----------------------------------------------------
323 if(bSuccess && !m_aborted)
325 m_currentStep = EncodingStep;
326 bSuccess = m_encoder->encode(sourceFile, m_audioFile.metaInfo(), m_audioFile.techInfo().duration(), m_audioFile.techInfo().audioChannels(), m_outFileName, &m_aborted);
329 //Clean-up
330 if((!bSuccess) || m_aborted)
332 QFileInfo fileInfo(m_outFileName);
333 if(fileInfo.exists() && (fileInfo.size() < 1024))
335 QFile::remove(m_outFileName);
339 //Make sure output file exists
340 if(bSuccess && (!m_aborted))
342 const QFileInfo fileInfo(m_outFileName);
343 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() >= 1024);
346 //-----------------------------------------------------
347 // Finalize
348 //-----------------------------------------------------
350 if (bSuccess && (!m_aborted) && m_keepDateTime)
352 updateFileTime(m_audioFile.filePath(), m_outFileName);
355 MUtils::OS::sleep_ms(12);
357 //Report result
358 emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
359 emit processStateFinished(m_jobId, m_outFileName, (bSuccess ? 1 : 0));
361 qDebug("Process thread is done.");
364 ////////////////////////////////////////////////////////////
365 // SLOTS
366 ////////////////////////////////////////////////////////////
368 void ProcessThread::handleUpdate(int progress)
370 //qDebug("Progress: %d\n", progress);
372 switch(m_currentStep)
374 case EncodingStep:
375 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
376 break;
377 case AnalyzeStep:
378 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
379 break;
380 case FilteringStep:
381 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
382 break;
383 case DecodingStep:
384 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
385 break;
389 void ProcessThread::handleMessage(const QString &line)
391 emit processMessageLogged(m_jobId, line);
394 ////////////////////////////////////////////////////////////
395 // PRIVAE FUNCTIONS
396 ////////////////////////////////////////////////////////////
398 int ProcessThread::generateOutFileName(QString &outFileName)
400 outFileName.clear();
402 //Make sure the source file exists
403 const QFileInfo sourceFile(m_audioFile.filePath());
404 if(!(sourceFile.exists() && sourceFile.isFile()))
406 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
407 return 0;
410 //Make sure the source file readable
411 QFile readTest(sourceFile.canonicalFilePath());
412 if(!readTest.open(QIODevice::ReadOnly))
414 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), QDir::toNativeSeparators(readTest.fileName())));
415 return 0;
417 else
419 readTest.close();
422 const QString baseName = sourceFile.completeBaseName();
423 QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
425 //Prepend relative source file path?
426 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
428 QDir rootDir = sourceFile.dir();
429 while(!rootDir.isRoot())
431 if(!rootDir.cdUp()) break;
433 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
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 //Apply rename pattern
460 const QString fileName = applyRegularExpression(applyRenamePattern(baseName, m_audioFile.metaInfo()));
462 //Generate full output path
463 const QString fileExt = m_renameFileExt.isEmpty() ? QString::fromUtf8(m_encoder->toEncoderInfo()->extension()) : m_renameFileExt;
464 outFileName = MUtils::clean_file_path(QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, fileExt));
466 //Skip file, if target file exists (optional!)
467 if((m_overwriteMode == OverwriteMode_SkipExisting) && QFileInfo(outFileName).exists())
469 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to skip this file:"), QDir::toNativeSeparators(outFileName)));
470 handleMessage(tr("If you don't want existing files to be skipped, please change the overwrite mode!"));
471 return -1;
474 //Delete file, if target file exists (optional!)
475 if((m_overwriteMode == OverwriteMode_Overwrite) && QFileInfo(outFileName).exists() && QFileInfo(outFileName).isFile())
477 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to delete existing file:"), QDir::toNativeSeparators(outFileName)));
478 if(sourceFile.canonicalFilePath().compare(QFileInfo(outFileName).absoluteFilePath(), Qt::CaseInsensitive) != 0)
480 for(int i = 0; i < 16; i++)
482 if(QFile::remove(outFileName))
484 break;
486 MUtils::OS::sleep_ms(1);
489 if(QFileInfo(outFileName).exists())
491 handleMessage(QString("%1\n").arg(tr("Failed to delete existing target file, will save to another file name!")));
495 int n = 1;
497 //Generate final name
498 while(QFileInfo(outFileName).exists() && (n < (INT_MAX/2)))
500 outFileName = MUtils::clean_file_path(QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), fileExt));
503 //Create placeholder
504 QFile placeholder(outFileName);
505 if(placeholder.open(QIODevice::WriteOnly))
507 placeholder.close();
510 return 1;
513 QString ProcessThread::applyRenamePattern(const QString &baseName, const AudioFileModel_MetaInfo &metaInfo)
515 QString fileName = m_renamePattern;
517 fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
518 fileName.replace("<TrackNo>", QString().sprintf("%02d", metaInfo.position()), Qt::CaseInsensitive);
519 fileName.replace("<Title>", STRDEF(metaInfo.title(), tr("Unknown Title")) , Qt::CaseInsensitive);
520 fileName.replace("<Artist>", STRDEF(metaInfo.artist(), tr("Unknown Artist")), Qt::CaseInsensitive);
521 fileName.replace("<Album>", STRDEF(metaInfo.album(), tr("Unknown Album")), Qt::CaseInsensitive);
522 fileName.replace("<Year>", QString().sprintf("%04d", metaInfo.year()), Qt::CaseInsensitive);
523 fileName.replace("<Comment>", STRDEF(metaInfo.comment(), tr("Unknown Comment")), Qt::CaseInsensitive);
525 return fileName;
528 QString ProcessThread::applyRegularExpression(const QString &fileName)
530 if(m_renameRegExp_Search.isEmpty() || m_renameRegExp_Replace.isEmpty())
532 return fileName;
535 QRegExp regExp(m_renameRegExp_Search);
536 if(!regExp.isValid())
538 qWarning("Invalid regular expression detected -> cannot rename!");
539 return fileName;
542 return (QString(fileName).replace(regExp, m_renameRegExp_Replace));
545 QString ProcessThread::generateTempFileName(void)
547 const QString tempFileName = MUtils::make_temp_file(m_tempDirectory, "wav", true);
548 if(tempFileName.isEmpty())
550 return QString("%1/~whoops%2.wav").arg(m_tempDirectory, QString::number(MUtils::next_rand_u32()));
553 m_tempFiles << tempFileName;
554 return tempFileName;
557 bool ProcessThread::insertDownsampleFilter(const unsigned int *const supportedSamplerates, const unsigned int *const supportedBitdepths)
559 int targetSampleRate = 0, targetBitDepth = 0;
561 /* Adjust sample rate */
562 if(supportedSamplerates && m_audioFile.techInfo().audioSamplerate())
564 const unsigned int inputRate = m_audioFile.techInfo().audioSamplerate();
565 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
567 //Find the most suitable supported sampling rate
568 for(int i = 0; supportedSamplerates[i]; i++)
570 currentDiff = DIFF(inputRate, supportedSamplerates[i]);
571 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestRate < supportedSamplerates[i])))
573 bestRate = supportedSamplerates[i];
574 minimumDiff = currentDiff;
575 if(!(minimumDiff > 0)) break;
579 if(bestRate != inputRate)
581 targetSampleRate = (bestRate != UINT_MAX) ? bestRate : supportedSamplerates[0];
585 /* Adjust bit depth (word size) */
586 if(supportedBitdepths && m_audioFile.techInfo().audioBitdepth())
588 const unsigned int inputBPS = m_audioFile.techInfo().audioBitdepth();
589 bool bAdjustBitdepth = true;
591 //Is the input bit depth supported exactly? (including IEEE Float)
592 for(int i = 0; supportedBitdepths[i]; i++)
594 if(supportedBitdepths[i] == inputBPS) bAdjustBitdepth = false;
597 if(bAdjustBitdepth)
599 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
600 const unsigned int originalBPS = (inputBPS == AudioFileModel::BITDEPTH_IEEE_FLOAT32) ? 32 : inputBPS;
602 //Find the most suitable supported bit depth
603 for(int i = 0; supportedBitdepths[i]; i++)
605 if(supportedBitdepths[i] == AudioFileModel::BITDEPTH_IEEE_FLOAT32) continue;
607 currentDiff = DIFF(originalBPS, supportedBitdepths[i]);
608 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBitdepths[i])))
610 bestBPS = supportedBitdepths[i];
611 minimumDiff = currentDiff;
612 if(!(minimumDiff > 0)) break;
616 if(bestBPS != originalBPS)
618 targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBitdepths[0];
623 //Check if downsampling filter is already in the chain
624 if (targetSampleRate || targetBitDepth)
626 for (int i = 0; i < m_filters.count(); i++)
628 if (dynamic_cast<ResampleFilter*>(m_filters.at(i)))
630 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
631 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
632 targetSampleRate = targetBitDepth = 0;
637 /* Insert the filter */
638 if(targetSampleRate || targetBitDepth)
640 m_filters.append(new ResampleFilter(targetSampleRate, targetBitDepth));
641 return true;
644 return false; /*did not insert the resample filter */
647 bool ProcessThread::insertDownmixFilter(const unsigned int *const supportedChannels)
649 //Determine number of channels in source
650 const unsigned int channels = m_audioFile.techInfo().audioChannels();
651 bool requiresDownmix = (channels > 0);
653 //Check whether encoder requires downmixing
654 if(requiresDownmix)
656 for (int i = 0; supportedChannels[i]; i++)
658 if (supportedChannels[i] == channels)
660 requiresDownmix = false;
661 break;
666 //Check if downmixing filter is already in the chain
667 if (requiresDownmix)
669 for (int i = 0; i < m_filters.count(); i++)
671 if (dynamic_cast<DownmixFilter*>(m_filters.at(i)))
673 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
674 handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
675 requiresDownmix = false;
676 break;
681 //Now add the downmixing filter, if needed
682 if(requiresDownmix)
684 m_filters.append(new DownmixFilter());
685 return true;
688 return false; /*did not insert the downmix filter*/
691 bool ProcessThread::updateFileTime(const QString &originalFile, const QString &modifiedFile)
693 bool success = false;
695 QFileInfo originalFileInfo(originalFile);
696 const QDateTime timeCreated = originalFileInfo.created(), timeLastMod = originalFileInfo.lastModified();
697 if (timeCreated.isValid() && timeLastMod.isValid())
699 if (!MUtils::OS::set_file_time(modifiedFile, timeCreated, timeLastMod))
701 qWarning("Failed to update creation/modified time of output file: \"%s\"", MUTILS_UTF8(modifiedFile));
704 else
706 qWarning("Failed to read creation/modified time of source file: \"%s\"", MUTILS_UTF8(originalFile));
709 return success;
712 ////////////////////////////////////////////////////////////
713 // PUBLIC FUNCTIONS
714 ////////////////////////////////////////////////////////////
716 void ProcessThread::addFilter(AbstractFilter *filter)
718 m_filters.append(filter);
721 void ProcessThread::setRenamePattern(const QString &pattern)
723 const QString newPattern = pattern.simplified();
724 if(!newPattern.isEmpty()) m_renamePattern = newPattern;
727 void ProcessThread::setRenameRegExp(const QString &search, const QString &replace)
729 const QString newSearch = search.trimmed(), newReplace = replace.simplified();
730 if((!newSearch.isEmpty()) && (!newReplace.isEmpty()))
732 m_renameRegExp_Search = newSearch;
733 m_renameRegExp_Replace = newReplace;
737 void ProcessThread::setRenameFileExt(const QString &fileExtension)
739 m_renameFileExt = MUtils::clean_file_name(fileExtension).simplified();
740 while(m_renameFileExt.startsWith('.'))
742 m_renameFileExt = m_renameFileExt.mid(1).trimmed();
746 void ProcessThread::setOverwriteMode(const bool &bSkipExistingFile, const bool &bReplacesExisting)
748 if(bSkipExistingFile && bReplacesExisting)
750 qWarning("Inconsistent overwrite flags -> reverting to default!");
751 m_overwriteMode = OverwriteMode_KeepBoth;
753 else
755 m_overwriteMode = OverwriteMode_KeepBoth;
756 if(bSkipExistingFile) m_overwriteMode = OverwriteMode_SkipExisting;
757 if(bReplacesExisting) m_overwriteMode = OverwriteMode_Overwrite;
761 void ProcessThread::setKeepDateTime(const bool &keepDateTime)
763 m_keepDateTime = keepDateTime;
766 ////////////////////////////////////////////////////////////
767 // EVENTS
768 ////////////////////////////////////////////////////////////
770 /*NONE*/