OSDN Git Service

Updated Valdec decoder binary to v1.4.0a (2013-03-17).
[lamexp/LameXP.git] / src / Thread_Process.cpp
index b784224..8578be0 100644 (file)
@@ -1,6 +1,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 // LameXP - Audio Encoder Front-End
-// Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2013 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
@@ -63,6 +63,8 @@ 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_aborted(false),
        m_propDetect(new WaveProperties())
 {
@@ -111,8 +113,7 @@ void ProcessThread::run()
                fflush(stdout);
                fflush(stderr);
                fprintf(stderr, "\nGURU MEDITATION !!!\n");
-               FatalAppExit(0, L"Unhandeled exception error, application will exit!");
-               TerminateProcess(GetCurrentProcess(), -1);
+               lamexp_fatal_exit(L"Unhandeled exception error, application will exit!");
        }
 }
 
@@ -127,11 +128,21 @@ void ProcessThread::processFile()
        handleMessage("\n-------------------------------\n");
 
        //Generate output file name
-       QString outFileName = generateOutFileName();
-       if(outFileName.isEmpty())
+       QString outFileName;
+       switch(generateOutFileName(outFileName))
        {
+       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, false);
+               emit processStateFinished(m_jobId, outFileName, 0);
                return;
        }
 
@@ -158,16 +169,23 @@ void ProcessThread::processFile()
                        if(bSuccess)
                        {
                                sourceFile = tempFile;
-                               handleMessage("\n-------------------------------\n");
                                m_audioFile.setFormatContainerType(QString::fromLatin1("Wave"));
                                m_audioFile.setFormatAudioType(QString::fromLatin1("PCM"));
+
+                               if(QFileInfo(sourceFile).size() >= 4294967296i64)
+                               {
+                                       handleMessage(tr("WARNING: Decoded file size exceeds 4 GB, problems might occur!\n"));
+                               }
+
+                               handleMessage("\n-------------------------------\n");
                        }
                }
                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()));
                        emit processStateChanged(m_jobId, tr("Unsupported!"), ProgressModel::JobFailed);
-                       emit processStateFinished(m_jobId, outFileName, false);
+                       emit processStateFinished(m_jobId, outFileName, 0);
                        return;
                }
        }
@@ -175,9 +193,9 @@ void ProcessThread::processFile()
        //------------------------------------
        //Update audio properties after decode
        //------------------------------------
-       if(bSuccess && IS_WAVE(m_audioFile))
+       if(bSuccess && !m_aborted && IS_WAVE(m_audioFile))
        {
-               if(m_encoder->supportedSamplerates() || m_encoder->supportedBitdepths() || m_encoder->requiresDownmix())
+               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);
@@ -187,7 +205,7 @@ void ProcessThread::processFile()
                                handleMessage("\n-------------------------------\n");
 
                                //Do we need to take care if Stereo downmix?
-                               if(m_encoder->requiresDownmix())
+                               if(m_encoder->supportedChannelCount())
                                {
                                        insertDownmixFilter();
                                }
@@ -206,7 +224,7 @@ void ProcessThread::processFile()
        //-----------------------
        if(bSuccess)
        {
-               while(!m_filters.isEmpty())
+               while(!m_filters.isEmpty() && !m_aborted)
                {
                        QString tempFile = generateTempFileName();
                        AbstractFilter *poFilter = m_filters.takeFirst();
@@ -215,7 +233,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_aborted))
+                       if(poFilter->apply(sourceFile, tempFile, &m_audioFile, &m_aborted))
                        {
                                sourceFile = tempFile;
                        }
@@ -228,24 +246,34 @@ void ProcessThread::processFile()
        //-----------------
        //Encode audio file
        //-----------------
-       if(bSuccess)
+       if(bSuccess && !m_aborted)
        {
                m_currentStep = EncodingStep;
                bSuccess = m_encoder->encode(sourceFile, m_audioFile, outFileName, &m_aborted);
        }
 
+       //Clean-up
+       if((!bSuccess) || m_aborted)
+       {
+               QFileInfo fileInfo(outFileName);
+               if(fileInfo.exists() && (fileInfo.size() < 512))
+               {
+                       QFile::remove(outFileName);
+               }
+       }
+
        //Make sure output file exists
-       if(bSuccess)
+       if(bSuccess && (!m_aborted))
        {
                QFileInfo fileInfo(outFileName);
                bSuccess = fileInfo.exists() && fileInfo.isFile() && (fileInfo.size() > 0);
        }
 
-       QThread::msleep(500);
+       QThread::msleep(125);
 
        //Report result
-       emit processStateChanged(m_jobId, (bSuccess ? tr("Done.") : (m_aborted ? tr("Aborted!") : tr("Failed!"))), (bSuccess ? ProgressModel::JobComplete : ProgressModel::JobFailed));
-       emit processStateFinished(m_jobId, outFileName, bSuccess);
+       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));
 
        qDebug("Process thread is done.");
 }
@@ -284,24 +312,26 @@ void ProcessThread::handleMessage(const QString &line)
 // PRIVAE FUNCTIONS
 ////////////////////////////////////////////////////////////
 
-QString ProcessThread::generateOutFileName(void)
+int ProcessThread::generateOutFileName(QString &outFileName)
 {
+       outFileName.clear();
+
        QMutexLocker lock(m_mutex_genFileName);
-       
-       int n = 1;
 
+       //Make sure the source file exists
        QFileInfo sourceFile(m_audioFile.filePath());
        if(!sourceFile.exists() || !sourceFile.isFile())
        {
                handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be found:"), sourceFile.absoluteFilePath()));
-               return QString();
+               return 0;
        }
 
+       //Make sure the source file readable
        QFile readTest(sourceFile.canonicalFilePath());
        if(!readTest.open(QIODevice::ReadOnly))
        {
-               handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), readTest.fileName()));
-               return QString();
+               handleMessage(QString("%1\n%2").arg(tr("The source audio file could not be opened for reading:"), QDir::toNativeSeparators(readTest.fileName())));
+               return 0;
        }
        else
        {
@@ -311,6 +341,7 @@ QString ProcessThread::generateOutFileName(void)
        QString baseName = sourceFile.completeBaseName();
        QDir targetDir(m_outputDirectory.isEmpty() ? sourceFile.canonicalPath() : m_outputDirectory);
 
+       //Prepend relative source file path?
        if(m_prependRelativeSourcePath && !m_outputDirectory.isEmpty())
        {
                QDir rootDir = sourceFile.dir();
@@ -321,21 +352,23 @@ QString ProcessThread::generateOutFileName(void)
                targetDir.setPath(QString("%1/%2").arg(targetDir.absolutePath(), QFileInfo(rootDir.relativeFilePath(sourceFile.canonicalFilePath())).path()));
        }
        
+       //Make sure output directory does exist
        if(!targetDir.exists())
        {
                targetDir.mkpath(".");
                if(!targetDir.exists())
                {
-                       handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), targetDir.absolutePath()));
-                       return QString();
+                       handleMessage(QString("%1\n%2").arg(tr("The target output directory doesn't exist and could NOT be created:"), QDir::toNativeSeparators(targetDir.absolutePath())));
+                       return 0;
                }
        }
        
+       //Make sure that the output dir is writable
        QFile writeTest(QString("%1/.%2").arg(targetDir.canonicalPath(), lamexp_rand_str()));
        if(!writeTest.open(QIODevice::ReadWrite))
        {
-               handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), targetDir.absolutePath()));
-               return QString();
+               handleMessage(QString("%1\n%2").arg(tr("The target output directory is NOT writable:"), QDir::toNativeSeparators(targetDir.absolutePath())));
+               return 0;
        }
        else
        {
@@ -343,6 +376,7 @@ QString ProcessThread::generateOutFileName(void)
                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);
@@ -353,19 +387,50 @@ QString ProcessThread::generateOutFileName(void)
        fileName.replace("<Comment>", STRDEF(m_audioFile.fileComment(), tr("Unknown Comment")), Qt::CaseInsensitive);
        fileName = lamexp_clean_filename(fileName).simplified();
 
-       QString outFileName = QString("%1/%2.%3").arg(targetDir.canonicalPath(), fileName, m_encoder->extension());
+       //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())
+       {
+               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!"));
+               return -1;
+       }
+
+       //Delete file, if target file exists (optional!)
+       if(m_overwriteReplacesExisting && QFileInfo(outFileName).exists())
+       {
+               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++)
+               {
+                       bOkay = QFile::remove(outFileName);
+                       if(bOkay) break;
+                       QThread::msleep(125);
+               }
+               if(QFileInfo(outFileName).exists() || (!bOkay))
+               {
+                       handleMessage(QString("%1\n").arg(tr("Failed to delete existing target file, will save to another file name!")));
+               }
+       }
+
+       int n = 1;
+
+       //Generate final name
        while(QFileInfo(outFileName).exists())
        {
                outFileName = QString("%1/%2 (%3).%4").arg(targetDir.canonicalPath(), fileName, QString::number(++n), m_encoder->extension());
        }
 
+       //Create placeholder
        QFile placeholder(outFileName);
        if(placeholder.open(QIODevice::WriteOnly))
        {
                placeholder.close();
        }
 
-       return outFileName;
+       return 1;
 }
 
 QString ProcessThread::generateTempFileName(void)
@@ -438,25 +503,40 @@ void ProcessThread::insertDownsampleFilter(void)
        /* Adjust bit depth (word size) */
        if(m_encoder->supportedBitdepths() && m_audioFile.formatAudioBitdepth())
        {
-               const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
                const unsigned int inputBPS = m_audioFile.formatAudioBitdepth();
-               unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
+               const unsigned int *supportedBPS = m_encoder->supportedBitdepths();
 
-               //Find the most suitable supported bit depth
+               bool bAdjustBitdepth = true;
+
+               //Is the input bit depth supported exactly? (inclduing IEEE Float)
                for(int i = 0; supportedBPS[i]; i++)
                {
-                       currentDiff = DIFF(inputBPS, supportedBPS[i]);
-                       if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBPS[i])))
+                       if(supportedBPS[i] == inputBPS) bAdjustBitdepth = false;
+               }
+               
+               if(bAdjustBitdepth)
+               {
+                       unsigned int currentDiff = UINT_MAX, minimumDiff = UINT_MAX, bestBPS = UINT_MAX;
+                       const unsigned int originalBPS = (inputBPS == AudioFileModel::BITDEPTH_IEEE_FLOAT32) ? 32 : inputBPS;
+
+                       //Find the most suitable supported bit depth
+                       for(int i = 0; supportedBPS[i]; i++)
                        {
-                               bestBPS = supportedBPS[i];
-                               minimumDiff = currentDiff;
-                               if(!(minimumDiff > 0)) break;
+                               if(supportedBPS[i] == AudioFileModel::BITDEPTH_IEEE_FLOAT32) continue;
+                               
+                               currentDiff = DIFF(originalBPS, supportedBPS[i]);
+                               if((currentDiff < minimumDiff) || ((currentDiff == minimumDiff) && (bestBPS < supportedBPS[i])))
+                               {
+                                       bestBPS = supportedBPS[i];
+                                       minimumDiff = currentDiff;
+                                       if(!(minimumDiff > 0)) break;
+                               }
                        }
-               }
 
-               if(bestBPS != inputBPS)
-               {
-                       targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBPS[0];
+                       if(bestBPS != originalBPS)
+                       {
+                               targetBitDepth = (bestBPS != UINT_MAX) ? bestBPS : supportedBPS[0];
+                       }
                }
        }
 
@@ -477,6 +557,7 @@ void ProcessThread::insertDownmixFilter(void)
                if(dynamic_cast<DownmixFilter*>(m_filters.at(i)))
                {
                        qWarning("Encoder requires Stereo downmix, but user has already forced downmix!");
+                       handleMessage("WARNING: Encoder may need downmixning, but already using downmixning filter. Encoding *may* fail!\n");
                        applyDownmixing = false;
                }
        }
@@ -484,8 +565,20 @@ void ProcessThread::insertDownmixFilter(void)
        //Now add the downmixing filter, if needed
        if(applyDownmixing)
        {
+               bool requiresDownmix = true;
+               const unsigned int *supportedChannels = m_encoder->supportedChannelCount();
                unsigned int channels = m_audioFile.formatAudioChannels();
-               if((channels == 0) || (channels > 2))
+
+               for(int i = 0; supportedChannels[i]; i++)
+               {
+                       if(supportedChannels[i] == channels)
+                       {
+                               requiresDownmix = false;
+                               break;
+                       }
+               }
+
+               if(requiresDownmix)
                {
                        m_filters.append(new DownmixFilter());
                }
@@ -507,6 +600,19 @@ void ProcessThread::setRenamePattern(const QString &pattern)
        if(!newPattern.isEmpty()) m_renamePattern = newPattern;
 }
 
+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;
+       }
+
+       m_overwriteSkipExistingFile = bSkipExistingFile;
+       m_overwriteReplacesExisting = bReplacesExisting;
+}
+
 ////////////////////////////////////////////////////////////
 // EVENTS
 ////////////////////////////////////////////////////////////