Updated OggEnc2 binaries to v2.88 using libvorbis v1.3.5 and aoTuV v6.03_2015 (2015...
[LameXP.git] / src / Thread_Process.cpp
blob7bba4ce80be1fba3a3169e69cd66cb2d5cba051d
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2015 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_initialized(-1),
76 m_aborted(false),
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 < 0)
114 m_initialized = 0;
116 //Initialize job status
117 qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
118 emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
120 //Initialize log
121 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))));
122 handleMessage("\n-------------------------------\n");
124 return true;
127 qWarning("[ProcessThread::init] Job %s already initialialized, skipping!", m_jobId.toString().toLatin1().constData());
128 return false;
131 bool ProcessThread::start(QThreadPool *const pool)
133 //Make sure object was initialized correctly
134 if(m_initialized < 0)
136 MUTILS_THROW("Object not initialized yet!");
139 if(m_initialized < 1)
141 m_initialized = 1;
143 m_outFileName.clear();
144 bool bSuccess = false;
146 //Generate output file name
147 switch(generateOutFileName(m_outFileName))
149 case 1:
150 //File name generated successfully :-)
151 bSuccess = true;
152 pool->start(this);
153 break;
154 case -1:
155 //File name already exists -> skipping!
156 emit processStateChanged(m_jobId, tr("Skipped."), ProgressModel::JobSkipped);
157 emit processStateFinished(m_jobId, m_outFileName, -1);
158 break;
159 default:
160 //File name could not be generated
161 emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
162 emit processStateFinished(m_jobId, m_outFileName, 0);
163 break;
166 if(!bSuccess)
168 emit processFinished();
171 return bSuccess;
174 qWarning("[ProcessThread::start] Job %s already started, skipping!", m_jobId.toString().toLatin1().constData());
175 return false;
178 ////////////////////////////////////////////////////////////
179 // Thread Entry Point
180 ////////////////////////////////////////////////////////////
182 void ProcessThread::run()
186 processFile();
188 catch(const std::exception &error)
190 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
191 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
193 catch(...)
195 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
196 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
200 void ProcessThread::processFile()
202 m_aborted = false;
203 bool bSuccess = true;
205 //Make sure object was initialized correctly
206 if(m_initialized < 1)
208 MUTILS_THROW("Object not initialized yet!");
211 QString sourceFile = m_audioFile.filePath();
213 //-----------------------------------------------------
214 // Decode source file
215 //-----------------------------------------------------
217 const AudioFileModel_TechInfo &formatInfo = m_audioFile.techInfo();
218 if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion()))
220 m_currentStep = DecodingStep;
221 AbstractDecoder *decoder = DecoderRegistry::lookup(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion());
223 if(decoder)
225 QString tempFile = generateTempFileName();
227 connect(decoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
228 connect(decoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
230 bSuccess = decoder->decode(sourceFile, tempFile, &m_aborted);
231 MUTILS_DELETE(decoder);
233 if(bSuccess)
235 sourceFile = tempFile;
236 m_audioFile.techInfo().setContainerType(QString::fromLatin1("Wave"));
237 m_audioFile.techInfo().setAudioType(QString::fromLatin1("PCM"));
239 if(QFileInfo(sourceFile).size() >= 4294967296i64)
241 handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
244 handleMessage("\n-------------------------------\n");
247 else
249 if(QFileInfo(m_outFileName).exists() && (QFileInfo(m_outFileName).size() < 512)) QFile::remove(m_outFileName);
250 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()));
251 emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
252 emit processStateFinished(m_jobId, m_outFileName, 0);
253 return;
257 //-----------------------------------------------------
258 // Update audio properties after decode
259 //-----------------------------------------------------
261 if(bSuccess && !m_aborted && IS_WAVE(m_audioFile.techInfo()))
263 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
265 m_currentStep = AnalyzeStep;
266 bSuccess = m_propDetect->detect(sourceFile, &m_audioFile.techInfo(), &m_aborted);
268 if(bSuccess)
270 handleMessage("\n-------------------------------\n");
272 //Do we need to take care if Stereo downmix?
273 if(m_encoder->supportedChannelCount())
275 insertDownmixFilter();
278 //Do we need to take care of downsampling the input?
279 if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths())
281 insertDownsampleFilter();
287 //-----------------------------------------------------
288 // Apply all audio filters
289 //-----------------------------------------------------
291 if(bSuccess)
293 while(!m_filters.isEmpty() && !m_aborted)
295 QString tempFile = generateTempFileName();
296 AbstractFilter *poFilter = m_filters.takeFirst();
297 m_currentStep = FilteringStep;
299 connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
300 connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
302 if(poFilter->apply(sourceFile, tempFile, &m_audioFile.techInfo(), &m_aborted))
304 sourceFile = tempFile;
307 handleMessage("\n-------------------------------\n");
308 delete poFilter;
312 //-----------------------------------------------------
313 // Encode audio file
314 //-----------------------------------------------------
316 if(bSuccess && !m_aborted)
318 m_currentStep = EncodingStep;
319 bSuccess = m_encoder->encode(sourceFile, m_audioFile.metaInfo(), m_audioFile.techInfo().duration(), m_outFileName, &m_aborted);
322 //Clean-up
323 if((!bSuccess) || m_aborted)
325 QFileInfo fileInfo(m_outFileName);
326 if(fileInfo.exists() && (fileInfo.size() < 1024))
328 QFile::remove(m_outFileName);
332 //Make sure output file exists
333 if(bSuccess && (!m_aborted))
335 const QFileInfo fileInfo(m_outFileName);
336 bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() >= 1024);
339 //-----------------------------------------------------
340 // Finalize
341 //-----------------------------------------------------
343 if (bSuccess && (!m_aborted))
345 updateFileTime(m_audioFile.filePath(), m_outFileName);
348 MUtils::OS::sleep_ms(12);
350 //Report result
351 emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
352 emit processStateFinished(m_jobId, m_outFileName, (bSuccess ? 1 : 0));
354 qDebug("Process thread is done.");
357 ////////////////////////////////////////////////////////////
358 // SLOTS
359 ////////////////////////////////////////////////////////////
361 void ProcessThread::handleUpdate(int progress)
363 //qDebug("Progress: %d\n", progress);
365 switch(m_currentStep)
367 case EncodingStep:
368 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Encoding"), QString::number(progress)), ProgressModel::JobRunning);
369 break;
370 case AnalyzeStep:
371 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Analyzing"), QString::number(progress)), ProgressModel::JobRunning);
372 break;
373 case FilteringStep:
374 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Filtering"), QString::number(progress)), ProgressModel::JobRunning);
375 break;
376 case DecodingStep:
377 emit processStateChanged(m_jobId, QString("%1 (%2%)").arg(tr("Decoding"), QString::number(progress)), ProgressModel::JobRunning);
378 break;
382 void ProcessThread::handleMessage(const QString &line)
384 emit processMessageLogged(m_jobId, line);
387 ////////////////////////////////////////////////////////////
388 // PRIVAE FUNCTIONS
389 ////////////////////////////////////////////////////////////
391 int ProcessThread::generateOutFileName(QString &outFileName)
393 outFileName.clear();
395 //Make sure the source file exists
396 const QFileInfo sourceFile(m_audioFile.filePath());
397 if(!(sourceFile.exists() && sourceFile.isFile()))
399 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
400 return 0;
403 //Make sure the source file readable
404 QFile readTest(sourceFile.canonicalFilePath());
405 if(!readTest.open(QIODevice::ReadOnly))
407 handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), QDir::toNativeSeparators(readTest.fileName())));
408 return 0;
410 else
412 readTest.close();
415 const QString baseName = sourceFile.completeBaseName();
416 QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
418 //Prepend relative source file path?
419 if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
421 QDir rootDir = sourceFile.dir();
422 while(!rootDir.isRoot())
424 if(!rootDir.cdUp()) break;
426 targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
429 //Make sure output directory does exist
430 if(!targetDir.exists())
432 targetDir.mkpath(".");
433 if(!targetDir.exists())
435 handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), QDir::toNativeSeparators(targetDir.absolutePath())));
436 return 0;
440 //Make sure that the output dir is writable
441 QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), MUtils::rand_str()));
442 if(!writeTest.open(QIODevice::ReadWrite))
444 handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), QDir::toNativeSeparators(targetDir.absolutePath())));
445 return 0;
447 else
449 writeTest.remove();
452 //Apply rename pattern
453 const QString fileName = MUtils::clean_file_name(applyRegularExpression(applyRenamePattern(baseName, m_audioFile.metaInfo())));
455 //Generate full output path
457 const QString fileExt = m_renameFileExt.isEmpty() ? QString::fromUtf8(m_encoder->toEncoderInfo()->extension()) : m_renameFileExt;
458 outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, fileExt);
460 //Skip file, if target file exists (optional!)
461 if((m_overwriteMode == OverwriteMode_SkipExisting) && QFileInfo(outFileName).exists())
463 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to skip this file:"), QDir::toNativeSeparators(outFileName)));
464 handleMessage(tr("If you don't want existing files to be skipped, please change the overwrite mode!"));
465 return -1;
468 //Delete file, if target file exists (optional!)
469 if((m_overwriteMode == OverwriteMode_Overwrite) && QFileInfo(outFileName).exists() && QFileInfo(outFileName).isFile())
471 handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to delete existing file:"), QDir::toNativeSeparators(outFileName)));
472 if(sourceFile.canonicalFilePath().compare(QFileInfo(outFileName).absoluteFilePath(), Qt::CaseInsensitive) != 0)
474 for(int i = 0; i < 16; i++)
476 if(QFile::remove(outFileName))
478 break;
480 MUtils::OS::sleep_ms(1);
483 if(QFileInfo(outFileName).exists())
485 handleMessage(QString("%1\n").arg(tr("Failed to delete existing target file, will save to another file name!")));
489 int n = 1;
491 //Generate final name
492 while(QFileInfo(outFileName).exists() && (n < (INT_MAX/2)))
494 outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), fileExt);
497 //Create placeholder
498 QFile placeholder(outFileName);
499 if(placeholder.open(QIODevice::WriteOnly))
501 placeholder.close();
504 return 1;
507 QString ProcessThread::applyRenamePattern(const QString &baseName, const AudioFileModel_MetaInfo &metaInfo)
509 QString fileName = m_renamePattern;
511 fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
512 fileName.replace("<TrackNo>", QString().sprintf("%02d", metaInfo.position()), Qt::CaseInsensitive);
513 fileName.replace("<Title>", STRDEF(metaInfo.title(), tr("Unknown Title")) , Qt::CaseInsensitive);
514 fileName.replace("<Artist>", STRDEF(metaInfo.artist(), tr("Unknown Artist")), Qt::CaseInsensitive);
515 fileName.replace("<Album>", STRDEF(metaInfo.album(), tr("Unknown Album")), Qt::CaseInsensitive);
516 fileName.replace("<Year>", QString().sprintf("%04d", metaInfo.year()), Qt::CaseInsensitive);
517 fileName.replace("<Comment>", STRDEF(metaInfo.comment(), tr("Unknown Comment")), Qt::CaseInsensitive);
519 return fileName;
522 QString ProcessThread::applyRegularExpression(const QString &fileName)
524 if(m_renameRegExp_Search.isEmpty() || m_renameRegExp_Replace.isEmpty())
526 return fileName;
529 QRegExp regExp(m_renameRegExp_Search);
530 if(!regExp.isValid())
532 qWarning("Invalid regular expression detected -> cannot rename!");
533 return fileName;
536 return (QString(fileName).replace(regExp, m_renameRegExp_Replace));
539 QString ProcessThread::generateTempFileName(void)
541 const QString tempFileName = MUtils::make_temp_file(m_tempDirectory, "wav", true);
542 if(tempFileName.isEmpty())
544 return QString("%1/~whoops%2.wav").arg(m_tempDirectory, QString::number(MUtils::next_rand32()));
547 m_tempFiles << tempFileName;
548 return tempFileName;
551 void ProcessThread::insertDownsampleFilter(void)
553 int targetSampleRate = 0;
554 int targetBitDepth = 0;
556 /* Adjust sample rate */
557 if(m_encoder->supportedSamplerates() && m_audioFile.techInfo().audioSamplerate())
559 bool applyDownsampling = true;
561 //Check if downsampling filter is already in the chain
562 for(int i = 0; i < m_filters.count(); i++)
564 if(dynamic_cast<ResampleFilter*>(m_filters.at(i)))
566 qWarning("Encoder requires downsampling, but user has already set resamling filter!");
567 handleMessage("WARNING: Encoder may need resampling, but already using resample filter. Encoding *may* fail!\n");
568 applyDownsampling = false;
572 //Now determine the target sample rate, if required
573 if(applyDownsampling)
575 const unsigned int *supportedRates = m_encoder->supportedSamplerates();
576 const unsigned int inputRate = m_audioFile.techInfo().audioSamplerate();
577 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
579 //Find the most suitable supported sampling rate
580 for(int i = 0; supportedRates[i]; i++)
582 currentDiff = DIFF(inputRate, supportedRates[i]);
583 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestRate < supportedRates[i])))
585 bestRate = supportedRates[i];
586 minimumDiff = currentDiff;
587 if(!(minimumDiff > 0)) break;
591 if(bestRate != inputRate)
593 targetSampleRate = (bestRate != UINT_MAX) ? bestRate : supportedRates[0];
598 /* Adjust bit depth (word size) */
599 if(m_encoder->supportedBitdepths() && m_audioFile.techInfo().audioBitdepth())
601 const unsigned int inputBPS = m_audioFile.techInfo().audioBitdepth();
602 const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
604 bool bAdjustBitdepth = true;
606 //Is the input bit depth supported exactly? (including IEEE Float)
607 for(int i = 0; supportedBPS[i]; i++)
609 if(supportedBPS[i] == inputBPS) bAdjustBitdepth = false;
612 if(bAdjustBitdepth)
614 unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
615 const unsigned int originalBPS = (inputBPS == AudioFileModel::BITDEPTH_IEEE_FLOAT32) ? 32 : inputBPS;
617 //Find the most suitable supported bit depth
618 for(int i = 0; supportedBPS[i]; i++)
620 if(supportedBPS[i] == AudioFileModel::BITDEPTH_IEEE_FLOAT32) continue;
622 currentDiff = DIFF(originalBPS, supportedBPS[i]);
623 if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBPS[i])))
625 bestBPS = supportedBPS[i];
626 minimumDiff = currentDiff;
627 if(!(minimumDiff > 0)) break;
631 if(bestBPS != originalBPS)
633 targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBPS[0];
638 /* Insert the filter */
639 if(targetSampleRate || targetBitDepth)
641 m_filters.append(new ResampleFilter(targetSampleRate, targetBitDepth));
645 void ProcessThread::insertDownmixFilter(void)
647 bool applyDownmixing = true;
649 //Check if downmixing filter is already in the chain
650 for(int i = 0; i < m_filters.count(); i++)
652 if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
654 qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
655 handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
656 applyDownmixing = false;
660 //Now add the downmixing filter, if needed
661 if(applyDownmixing)
663 bool requiresDownmix = true;
664 const unsigned int *supportedChannels = m_encoder->supportedChannelCount();
665 unsigned int channels = m_audioFile.techInfo().audioChannels();
667 for(int i = 0; supportedChannels[i]; i++)
669 if(supportedChannels[i] == channels)
671 requiresDownmix = false;
672 break;
676 if(requiresDownmix)
678 m_filters.append(new DownmixFilter());
683 bool ProcessThread::updateFileTime(const QString &originalFile, const QString &modifiedFile)
685 bool success = false;
687 QFileInfo originalFileInfo(originalFile);
688 const QDateTime timeCreated = originalFileInfo.created(), timeLastMod = originalFileInfo.lastModified();
689 if (timeCreated.isValid() && timeLastMod.isValid())
691 if (!MUtils::OS::set_file_time(modifiedFile, timeCreated, timeLastMod))
693 qWarning("Failed to update creation/modified time of output file: \"%s\"", MUTILS_UTF8(modifiedFile));
696 else
698 qWarning("Failed to read creation/modified time of source file: \"%s\"", MUTILS_UTF8(originalFile));
701 return success;
704 ////////////////////////////////////////////////////////////
705 // PUBLIC FUNCTIONS
706 ////////////////////////////////////////////////////////////
708 void ProcessThread::addFilter(AbstractFilter *filter)
710 m_filters.append(filter);
713 void ProcessThread::setRenamePattern(const QString &pattern)
715 const QString newPattern = pattern.simplified();
716 if(!newPattern.isEmpty()) m_renamePattern = newPattern;
719 void ProcessThread::setRenameRegExp(const QString &search, const QString &replace)
721 const QString newSearch = search.trimmed(), newReplace = replace.simplified();
722 if((!newSearch.isEmpty()) && (!newReplace.isEmpty()))
724 m_renameRegExp_Search = newSearch;
725 m_renameRegExp_Replace = newReplace;
729 void ProcessThread::setRenameFileExt(const QString &fileExtension)
731 m_renameFileExt = MUtils::clean_file_name(fileExtension).simplified();
732 while(m_renameFileExt.startsWith('.'))
734 m_renameFileExt = m_renameFileExt.mid(1).trimmed();
738 void ProcessThread::setOverwriteMode(const bool &bSkipExistingFile, const bool &bReplacesExisting)
740 if(bSkipExistingFile && bReplacesExisting)
742 qWarning("Inconsistent overwrite flags -> reverting to default!");
743 m_overwriteMode = OverwriteMode_KeepBoth;
745 else
747 m_overwriteMode = OverwriteMode_KeepBoth;
748 if(bSkipExistingFile) m_overwriteMode = OverwriteMode_SkipExisting;
749 if(bReplacesExisting) m_overwriteMode = OverwriteMode_Overwrite;
753 ////////////////////////////////////////////////////////////
754 // EVENTS
755 ////////////////////////////////////////////////////////////
757 /*NONE*/