OSDN Git Service

Some improvements and simplifications to error handling functions.
[lamexp/LameXP.git] / src / Thread_Process.cpp
index 159d5bd..78f75be 100644 (file)
@@ -1,11 +1,12 @@
 ///////////////////////////////////////////////////////////////////////////////
 // LameXP - Audio Encoder Front-End
-// Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
 //
 // This program is free software; you can redistribute it and/or modify
 // it under the terms of the GNU General Public License as published by
 // the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
+// (at your option) any later version, but always including the *additional*
+// restrictions defined in the "License.txt" file.
 //
 // This program is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 #include <QMutex>
 #include <QMutexLocker>
 #include <QDate>
+#include <QThreadPool>
 
 #include <limits.h>
 #include <time.h>
 #include <stdlib.h>
 
 #define DIFF(X,Y) ((X > Y) ? (X-Y) : (Y-X))
-#define IS_WAVE(X) ((X.formatContainerType().compare("Wave", Qt::CaseInsensitive) == 0) && (X.formatAudioType().compare("PCM", Qt::CaseInsensitive) == 0))
+#define IS_WAVE(X) ((X.containerType().compare("Wave", Qt::CaseInsensitive) == 0) && (X.audioType().compare("PCM", Qt::CaseInsensitive) == 0))
 #define STRDEF(STR,DEF) ((!STR.isEmpty()) ? STR : DEF)
 
-QMutex *ProcessThread::m_mutex_genFileName = NULL;
-
 ////////////////////////////////////////////////////////////
 // Constructor
 ////////////////////////////////////////////////////////////
@@ -63,16 +63,11 @@ ProcessThread::ProcessThread(const AudioFileModel &audioFile, const QString &out
        m_jobId(QUuid::createUuid()),
        m_prependRelativeSourcePath(prependRelativeSourcePath),
        m_renamePattern("<BaseName>"),
-       m_overwriteSkipExistingFile(false),
-       m_overwriteReplacesExisting(false),
+       m_overwriteMode(OverwriteMode_KeepBoth),
+       m_initialized(-1),
        m_aborted(false),
        m_propDetect(new WaveProperties())
 {
-       if(m_mutex_genFileName)
-       {
-               m_mutex_genFileName = new QMutex;
-       }
-
        connect(m_encoder, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
        connect(m_encoder, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
 
@@ -96,6 +91,80 @@ ProcessThread::~ProcessThread(void)
 
        LAMEXP_DELETE(m_encoder);
        LAMEXP_DELETE(m_propDetect);
+
+       emit processFinished();
+}
+
+////////////////////////////////////////////////////////////
+// Init Function
+////////////////////////////////////////////////////////////
+
+bool ProcessThread::init(void)
+{
+       if(m_initialized < 0)
+       {
+               m_initialized = 0;
+
+               //Initialize job status
+               qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
+               emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
+
+               //Initialize log
+               handleMessage(QString().sprintf("LameXP v%u.%02u (Build #%u), compiled on %s at %s", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build(), lamexp_version_date().toString(Qt::ISODate).toLatin1().constData(), lamexp_version_time()));
+               handleMessage("\n-------------------------------\n");
+
+               return true;
+       }
+
+       qWarning("[ProcessThread::init] Job %s already initialialized, skipping!", m_jobId.toString().toLatin1().constData());
+       return false;
+}
+
+bool ProcessThread::start(QThreadPool *pool)
+{
+       //Make sure object was initialized correctly
+       if(m_initialized < 0)
+       {
+               THROW("Object not initialized yet!");
+       }
+
+       if(m_initialized < 1)
+       {
+               m_initialized = 1;
+
+               m_outFileName.clear();
+               bool bSuccess = false;
+
+               //Generate output file name
+               switch(generateOutFileName(m_outFileName))
+               {
+               case 1:
+                       //File name generated successfully :-)
+                       bSuccess = true;
+                       pool->start(this);
+                       break;
+               case -1:
+                       //File name already exists -> skipping!
+                       emit processStateChanged(m_jobId, tr("Skipped."), ProgressModel::JobSkipped);
+                       emit processStateFinished(m_jobId, m_outFileName, -1);
+                       break;
+               default:
+                       //File name could not be generated
+                       emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
+                       emit processStateFinished(m_jobId, m_outFileName, 0);
+                       break;
+               }
+
+               if(!bSuccess)
+               {
+                       emit processFinished();
+               }
+
+               return bSuccess;
+       }
+
+       qWarning("[ProcessThread::start] Job %s already started, skipping!", m_jobId.toString().toLatin1().constData());
+       return false;
 }
 
 ////////////////////////////////////////////////////////////
@@ -108,13 +177,15 @@ void ProcessThread::run()
        {
                processFile();
        }
+       catch(const std::exception &error)
+       {
+               PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
+               lamexp_fatal_exit("Unhandeled C++ exception error, application will exit!");
+       }
        catch(...)
        {
-               fflush(stdout);
-               fflush(stderr);
-               fprintf(stderr, "\nGURU MEDITATION !!!\n");
-               FatalAppExit(0, L"Unhandeled exception error, application will exit!");
-               TerminateProcess(GetCurrentProcess(), -1);
+               PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
+               lamexp_fatal_exit("Unhandeled C++ exception error, application will exit!");
        }
 }
 
@@ -122,29 +193,11 @@ void ProcessThread::processFile()
 {
        m_aborted = false;
        bool bSuccess = true;
-               
-       qDebug("Process thread %s has started.", m_jobId.toString().toLatin1().constData());
-       emit processStateInitialized(m_jobId, QFileInfo(m_audioFile.filePath()).fileName(), tr("Starting..."), ProgressModel::JobRunning);
-       handleMessage(QString().sprintf("LameXP v%u.%02u (Build #%u), compiled on %s at %s", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build(), lamexp_version_date().toString(Qt::ISODate).toLatin1().constData(), lamexp_version_time()));
-       handleMessage("\n-------------------------------\n");
 
-       //Generate output file name
-       QString outFileName;
-       switch(generateOutFileName(outFileName))
+       //Make sure object was initialized correctly
+       if(m_initialized < 1)
        {
-       case 1:
-               //File name generated successfully :-)
-               break;
-       case -1:
-               //File name already exists -> skipping!
-               emit processStateChanged(m_jobId, tr("Skipped."), ProgressModel::JobSkipped);
-               emit processStateFinished(m_jobId, outFileName, -1);
-               return;
-       default:
-               //File name could not be generated
-               emit processStateChanged(m_jobId, tr("Not found!"), ProgressModel::JobFailed);
-               emit processStateFinished(m_jobId, outFileName, 0);
-               return;
+               THROW("Object not initialized yet!");
        }
 
        QString sourceFile = m_audioFile.filePath();
@@ -152,10 +205,11 @@ void ProcessThread::processFile()
        //------------------
        //Decode source file
        //------------------
-       if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion()))
+       const AudioFileModel_TechInfo &formatInfo = m_audioFile.techInfo();
+       if(!m_filters.isEmpty() || !m_encoder->isFormatSupported(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion()))
        {
                m_currentStep = DecodingStep;
-               AbstractDecoder *decoder = DecoderRegistry::lookup(m_audioFile.formatContainerType(), m_audioFile.formatContainerProfile(), m_audioFile.formatAudioType(), m_audioFile.formatAudioProfile(), m_audioFile.formatAudioVersion());
+               AbstractDecoder *decoder = DecoderRegistry::lookup(formatInfo.containerType(), formatInfo.containerProfile(), formatInfo.audioType(), formatInfo.audioProfile(), formatInfo.audioVersion());
                
                if(decoder)
                {
@@ -170,8 +224,8 @@ void ProcessThread::processFile()
                        if(bSuccess)
                        {
                                sourceFile = tempFile;
-                               m_audioFile.setFormatContainerType(QString::fromLatin1("Wave"));
-                               m_audioFile.setFormatAudioType(QString::fromLatin1("PCM"));
+                               m_audioFile.techInfo().setContainerType(QString::fromLatin1("Wave"));
+                               m_audioFile.techInfo().setAudioType(QString::fromLatin1("PCM"));
 
                                if(QFileInfo(sourceFile).size() >= 4294967296i64)
                                {
@@ -183,10 +237,10 @@ void ProcessThread::processFile()
                }
                else
                {
-                       if(QFileInfo(outFileName).exists() && (QFileInfo(outFileName).size() < 512)) QFile::remove(outFileName);
-                       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.formatContainerInfo(), tr("Audio Format:"), m_audioFile.formatAudioCompressInfo()));
+                       if(QFileInfo(m_outFileName).exists() && (QFileInfo(m_outFileName).size() < 512)) QFile::remove(m_outFileName);
+                       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()));
                        emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
-                       emit processStateFinished(m_jobId, outFileName, 0);
+                       emit processStateFinished(m_jobId, m_outFileName, 0);
                        return;
                }
        }
@@ -194,12 +248,12 @@ void ProcessThread::processFile()
        //------------------------------------
        //Update audio properties after decode
        //------------------------------------
-       if(bSuccess && !m_aborted && IS_WAVE(m_audioFile))
+       if(bSuccess && !m_aborted && IS_WAVE(m_audioFile.techInfo()))
        {
                if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->supportedChannelCount() || m_encoder->needsTimingInfo() || !m_filters.isEmpty())
                {
                        m_currentStep = AnalyzeStep;
-                       bSuccess = m_propDetect->detect(sourceFile, &m_audioFile, &m_aborted);
+                       bSuccess = m_propDetect->detect(sourceFile, &m_audioFile.techInfo(), &m_aborted);
 
                        if(bSuccess)
                        {
@@ -234,7 +288,7 @@ void ProcessThread::processFile()
                        connect(poFilter, SIGNAL(statusUpdated(int)), this, SLOT(handleUpdate(int)), Qt::DirectConnection);
                        connect(poFilter, SIGNAL(messageLogged(QString)), this, SLOT(handleMessage(QString)), Qt::DirectConnection);
 
-                       if(poFilter->apply(sourceFile, tempFile, &m_audioFile, &m_aborted))
+                       if(poFilter->apply(sourceFile, tempFile, &m_audioFile.techInfo(), &m_aborted))
                        {
                                sourceFile = tempFile;
                        }
@@ -250,31 +304,31 @@ void ProcessThread::processFile()
        if(bSuccess && !m_aborted)
        {
                m_currentStep = EncodingStep;
-               bSuccess = m_encoder->encode(sourceFile, m_audioFileoutFileName, &m_aborted);
+               bSuccess = m_encoder->encode(sourceFile, m_audioFile.metaInfo(), m_audioFile.techInfo().duration(), m_outFileName, &m_aborted);
        }
 
        //Clean-up
        if((!bSuccess) || m_aborted)
        {
-               QFileInfo fileInfo(outFileName);
+               QFileInfo fileInfo(m_outFileName);
                if(fileInfo.exists() && (fileInfo.size() < 512))
                {
-                       QFile::remove(outFileName);
+                       QFile::remove(m_outFileName);
                }
        }
 
        //Make sure output file exists
        if(bSuccess && (!m_aborted))
        {
-               QFileInfo fileInfo(outFileName);
+               QFileInfo fileInfo(m_outFileName);
                bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
        }
 
-       QThread::msleep(125);
+       lamexp_sleep(125);
 
        //Report result
        emit processStateChanged(m_jobId, (m_aborted ? tr("Aborted!") : (bSuccess ? tr("Done.") : tr("Failed!"))), ((bSuccess && !m_aborted) ? ProgressModel::JobComplete : ProgressModel::JobFailed));
-       emit processStateFinished(m_jobId, outFileName, (bSuccess ? 1 : 0));
+       emit processStateFinished(m_jobId, m_outFileName, (bSuccess ? 1 : 0));
 
        qDebug("Process thread is done.");
 }
@@ -285,7 +339,7 @@ void ProcessThread::processFile()
 
 void ProcessThread::handleUpdate(int progress)
 {
-       //printf("Progress: %d\n", progress);
+       //qDebug("Progress: %d\n", progress);
        
        switch(m_currentStep)
        {
@@ -317,11 +371,9 @@ int ProcessThread::generateOutFileName(QString &outFileName)
 {
        outFileName.clear();
 
-       QMutexLocker lock(m_mutex_genFileName);
-
        //Make sure the source file exists
        QFileInfo sourceFile(m_audioFile.filePath());
-       if(!sourceFile.exists() || !sourceFile.isFile())
+       if(!(sourceFile.exists() && sourceFile.isFile()))
        {
                handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
                return 0;
@@ -373,26 +425,17 @@ int ProcessThread::generateOutFileName(QString &outFileName)
        }
        else
        {
-               writeTest.close();
                writeTest.remove();
        }
 
        //Apply rename pattern
-       QString fileName = m_renamePattern;
-       fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
-       fileName.replace("<TrackNo>", QString().sprintf("%02d", m_audioFile.filePosition()), Qt::CaseInsensitive);
-       fileName.replace("<Title>", STRDEF(m_audioFile.fileName(), tr("Unknown Title")) , Qt::CaseInsensitive);
-       fileName.replace("<Artist>", STRDEF(m_audioFile.fileArtist(), tr("Unknown Artist")), Qt::CaseInsensitive);
-       fileName.replace("<Album>", STRDEF(m_audioFile.fileAlbum(), tr("Unknown Album")), Qt::CaseInsensitive);
-       fileName.replace("<Year>", QString().sprintf("%04d", m_audioFile.fileYear()), Qt::CaseInsensitive);
-       fileName.replace("<Comment>", STRDEF(m_audioFile.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive);
-       fileName = lamexp_clean_filename(fileName).simplified();
+       QString fileName = applyRenamePattern(baseName, m_audioFile.metaInfo());
 
        //Generate full output path
        outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
 
        //Skip file, if target file exists (optional!)
-       if(m_overwriteSkipExistingFile && QFileInfo(outFileName).exists())
+       if((m_overwriteMode == OverwriteMode_SkipExisting) && QFileInfo(outFileName).exists())
        {
                handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to skip this file:"), QDir::toNativeSeparators(outFileName)));
                handleMessage(tr("If you don't want existing files to be skipped, please change the overwrite mode!"));
@@ -400,17 +443,21 @@ int ProcessThread::generateOutFileName(QString &outFileName)
        }
 
        //Delete file, if target file exists (optional!)
-       if(m_overwriteReplacesExisting && QFileInfo(outFileName).exists())
+       if((m_overwriteMode == OverwriteMode_Overwrite) && QFileInfo(outFileName).exists() && QFileInfo(outFileName).isFile())
        {
                handleMessage(QString("%1\n%2\n").arg(tr("Target output file already exists, going to delete existing file:"), QDir::toNativeSeparators(outFileName)));
-               bool bOkay = false;
-               for(int i = 0; i < 16; i++)
+               if(sourceFile.canonicalFilePath().compare(QFileInfo(outFileName).absoluteFilePath(), Qt::CaseInsensitive) != 0)
                {
-                       bOkay = QFile::remove(outFileName);
-                       if(bOkay) break;
-                       QThread::msleep(125);
+                       for(int i = 0; i < 16; i++)
+                       {
+                               if(QFile::remove(outFileName))
+                               {
+                                       break;
+                               }
+                               lamexp_sleep(125);
+                       }
                }
-               if(QFileInfo(outFileName).exists() || (!bOkay))
+               if(QFileInfo(outFileName).exists())
                {
                        handleMessage(QString("%1\n").arg(tr("Failed to delete existing target file, will save to another file name!")));
                }
@@ -419,7 +466,7 @@ int ProcessThread::generateOutFileName(QString &outFileName)
        int n = 1;
 
        //Generate final name
-       while(QFileInfo(outFileName).exists())
+       while(QFileInfo(outFileName).exists() && (n < (INT_MAX/2)))
        {
                outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
        }
@@ -434,20 +481,48 @@ int ProcessThread::generateOutFileName(QString &outFileName)
        return 1;
 }
 
-QString ProcessThread::generateTempFileName(void)
+QString ProcessThread::applyRenamePattern(const QString &baseName, const AudioFileModel_MetaInfo &metaInfo)
 {
-       QMutexLocker lock(m_mutex_genFileName);
-       QString tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
+       QString fileName = m_renamePattern;
+       
+       fileName.replace("<BaseName>", STRDEF(baseName, tr("Unknown File Name")), Qt::CaseInsensitive);
+       fileName.replace("<TrackNo>", QString().sprintf("%02d", metaInfo.position()), Qt::CaseInsensitive);
+       fileName.replace("<Title>", STRDEF(metaInfo.title(), tr("Unknown Title")) , Qt::CaseInsensitive);
+       fileName.replace("<Artist>", STRDEF(metaInfo.artist(), tr("Unknown Artist")), Qt::CaseInsensitive);
+       fileName.replace("<Album>", STRDEF(metaInfo.album(), tr("Unknown Album")), Qt::CaseInsensitive);
+       fileName.replace("<Year>", QString().sprintf("%04d", metaInfo.year()), Qt::CaseInsensitive);
+       fileName.replace("<Comment>", STRDEF(metaInfo.comment(), tr("Unknown Comment")), Qt::CaseInsensitive);
+       fileName = lamexp_clean_filename(fileName).simplified();
+
+       return fileName;
+}
 
-       while(QFileInfo(tempFileName).exists())
+QString ProcessThread::generateTempFileName(void)
+{
+       bool bOkay = false;
+       QString tempFileName;
+       
+       for(int i = 0; i < 4096; i++)
        {
                tempFileName = QString("%1/%2.wav").arg(m_tempDirectory, lamexp_rand_str());
+               if(m_tempFiles.contains(tempFileName, Qt::CaseInsensitive) || QFileInfo(tempFileName).exists())
+               {
+                       continue;
+               }
+
+               QFile file(tempFileName);
+               if(file.open(QFile::ReadWrite))
+               {
+                       file.close();
+                       bOkay = true;
+                       break;
+               }
        }
 
-       QFile file(tempFileName);
-       if(file.open(QFile::ReadWrite))
+       if(!bOkay)
        {
-               file.close();
+               qWarning("Failed to generate unique temp file name!");
+               return QString("%1/~whoops.wav").arg(m_tempDirectory);
        }
 
        m_tempFiles << tempFileName;
@@ -460,7 +535,7 @@ void ProcessThread::insertDownsampleFilter(void)
        int targetBitDepth = 0;
        
        /* Adjust sample rate */
-       if(m_encoder->supportedSamplerates() && m_audioFile.formatAudioSamplerate())
+       if(m_encoder->supportedSamplerates() && m_audioFile.techInfo().audioSamplerate())
        {
                bool applyDownsampling = true;
        
@@ -479,7 +554,7 @@ void ProcessThread::insertDownsampleFilter(void)
                if(applyDownsampling)
                {
                        const unsigned int *supportedRates = m_encoder->supportedSamplerates();
-                       const unsigned int inputRate = m_audioFile.formatAudioSamplerate();
+                       const unsigned int inputRate = m_audioFile.techInfo().audioSamplerate();
                        unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestRate = UINT_MAX;
 
                        //Find the most suitable supported sampling rate
@@ -502,14 +577,14 @@ void ProcessThread::insertDownsampleFilter(void)
        }
 
        /* Adjust bit depth (word size) */
-       if(m_encoder->supportedBitdepths() && m_audioFile.formatAudioBitdepth())
+       if(m_encoder->supportedBitdepths() && m_audioFile.techInfo().audioBitdepth())
        {
-               const unsigned int inputBPS = m_audioFile.formatAudioBitdepth();
+               const unsigned int inputBPS = m_audioFile.techInfo().audioBitdepth();
                const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
 
                bool bAdjustBitdepth = true;
 
-               //Is the input bit depth supported exactly? (inclduing IEEE Float)
+               //Is the input bit depth supported exactly? (including IEEE Float)
                for(int i = 0; supportedBPS[i]; i++)
                {
                        if(supportedBPS[i] == inputBPS) bAdjustBitdepth = false;
@@ -568,7 +643,7 @@ void ProcessThread::insertDownmixFilter(void)
        {
                bool requiresDownmix = true;
                const unsigned int *supportedChannels = m_encoder->supportedChannelCount();
-               unsigned int channels = m_audioFile.formatAudioChannels();
+               unsigned int channels = m_audioFile.techInfo().audioChannels();
 
                for(int i = 0; supportedChannels[i]; i++)
                {
@@ -601,17 +676,19 @@ void ProcessThread::setRenamePattern(const QString &pattern)
        if(!newPattern.isEmpty()) m_renamePattern = newPattern;
 }
 
-void ProcessThread::setOverwriteMode(const bool bSkipExistingFile, const bool bReplacesExisting)
+void ProcessThread::setOverwriteMode(const bool &bSkipExistingFile, const bool &bReplacesExisting)
 {
        if(bSkipExistingFile && bReplacesExisting)
        {
-               qWarning("Inconsistent overwrite flags, reverting to default!");
-               m_overwriteSkipExistingFile = false;
-               m_overwriteReplacesExisting = false;
+               qWarning("Inconsistent overwrite flags -> reverting to default!");
+               m_overwriteMode = OverwriteMode_KeepBoth;
+       }
+       else
+       {
+               m_overwriteMode = OverwriteMode_KeepBoth;
+               if(bSkipExistingFile) m_overwriteMode = OverwriteMode_SkipExisting;
+               if(bReplacesExisting) m_overwriteMode = OverwriteMode_Overwrite;
        }
-
-       m_overwriteSkipExistingFile = bSkipExistingFile;
-       m_overwriteReplacesExisting = bReplacesExisting;
 }
 
 ////////////////////////////////////////////////////////////