OSDN Git Service

Small code clean-up.
[lamexp/LameXP.git] / src / Thread_Initialization.cpp
index 1770bc9..106bb10 100644 (file)
@@ -1,6 +1,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 // LameXP - Audio Encoder Front-End
-// Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2015 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
 
 #include "Thread_Initialization.h"
 
-#include "LockedFile.h"
+//Internal
+#define LAMEXP_INC_TOOLS 1
 #include "Tools.h"
+#include "LockedFile.h"
 #include "Tool_Abstract.h"
 
+//MUtils
+#include <MUtils/Global.h>
+#include <MUtils/OSSupport.h>
+#include <MUtils/Translation.h>
+#include <MUtils/Exception.h>
+
+//Qt
 #include <QFileInfo>
 #include <QCoreApplication>
 #include <QProcess>
 #include <QMap>
 #include <QDir>
-#include <QLibrary>
 #include <QResource>
 #include <QTextStream>
 #include <QRunnable>
 #include <QThreadPool>
 #include <QMutex>
 #include <QQueue>
+#include <QElapsedTimer>
 
 /* helper macros */
 #define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
 /* constants */
 static const double g_allowedExtractDelay = 12.0;
 static const size_t BUFF_SIZE = 512;
-static const size_t EXPECTED_TOOL_COUNT = 27;
+static const size_t EXPECTED_TOOL_COUNT = 28;
+
+/* number of CPU cores -> number of threads */
+static unsigned int cores2threads(const unsigned int cores)
+{
+       static const size_t LUT_LEN = 4;
+       
+       static const struct
+       {
+               const unsigned int upperBound;
+               const double coeffs[4];
+       }
+       LUT[LUT_LEN] =
+       {
+               {  4, { -0.052695810565,  0.158087431694, 4.982841530055, -1.088233151184 } },
+               {  8, {  0.042431693989, -0.983442622951, 9.548961748634, -7.176393442623 } },
+               { 12, { -0.006277322404,  0.185573770492, 0.196830601093, 17.762622950820 } },
+               { 32, {  0.000673497268, -0.064655737705, 3.199584699454,  5.751606557377 } }
+       };
 
-/* benchmark */
-#undef ENABLE_BENCHMARK
+       size_t index = 0;
+       while((cores > LUT[index].upperBound) && (index < (LUT_LEN-1))) index++;
+
+       const double x = qBound(1.0, double(cores), double(LUT[LUT_LEN-1].upperBound));
+       const double y = (LUT[index].coeffs[0] * pow(x, 3.0)) + (LUT[index].coeffs[1] * pow(x, 2.0)) + (LUT[index].coeffs[2] * x) + LUT[index].coeffs[3];
+
+       return qRound(abs(y));
+}
 
 ////////////////////////////////////////////////////////////
 // ExtractorTask class
@@ -144,12 +177,12 @@ protected:
                else
                {
                        qDebug("Extracting file: %s -> %s", m_toolName.toLatin1().constData(), toolShortName.toLatin1().constData());
-                       lockedFile = new LockedFile(m_toolResource, QString("%1/lxp_%2").arg(lamexp_temp_folder2(), toolShortName), m_toolHash);
+                       lockedFile = new LockedFile(m_toolResource, QString("%1/lxp_%2").arg(MUtils::temp_folder(), toolShortName), m_toolHash);
                }
 
                if(lockedFile)
                {
-                       lamexp_register_tool(toolShortName, lockedFile, version, &m_toolTag);
+                       lamexp_tools_register(toolShortName, lockedFile, version, m_toolTag);
                }
        }
 
@@ -176,46 +209,34 @@ volatile bool ExtractorTask::s_bCustom = false;
 // Constructor
 ////////////////////////////////////////////////////////////
 
-InitializationThread::InitializationThread(const lamexp_cpu_t *cpuFeatures)
+InitializationThread::InitializationThread(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures)
+:
+       m_bSuccess(false),
+       m_slowIndicator(false)
 {
-       m_bSuccess = false;
-       memset(&m_cpuFeatures, 0, sizeof(lamexp_cpu_t));
-       m_slowIndicator = false;
-       
-       if(cpuFeatures)
-       {
-               memcpy(&m_cpuFeatures, cpuFeatures, sizeof(lamexp_cpu_t));
-       }
+
+       memcpy(&m_cpuFeatures, &cpuFeatures, sizeof(MUtils::CPUFetaures::cpu_info_t));
 }
 
 ////////////////////////////////////////////////////////////
 // Thread Main
 ////////////////////////////////////////////////////////////
 
-#ifdef ENABLE_BENCHMARK
-#define DO_INIT_FUNCT runBenchmark
-void lamexp_clean_all_tools(void);
-#else //ENABLE_BENCHMARK
-#define DO_INIT_FUNCT doInit
-#endif //ENABLE_BENCHMARK
-
 void InitializationThread::run(void)
 {
        try
        {
-               DO_INIT_FUNCT();
+               doInit();
        }
        catch(const std::exception &error)
        {
-               fflush(stdout); fflush(stderr);
-               fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
-               lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
+               MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
+               MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
        }
        catch(...)
        {
-               fflush(stdout); fflush(stderr);
-               fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
-               lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
+               MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
+               MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
        }
 }
 
@@ -226,7 +247,7 @@ double InitializationThread::doInit(const size_t threadCount)
 
        //CPU type selection
        unsigned int cpuSupport = 0;
-       if(m_cpuFeatures.sse && m_cpuFeatures.sse2 && m_cpuFeatures.intel)
+       if((m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE) && (m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE2) && m_cpuFeatures.intel)
        {
                cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
        }
@@ -238,7 +259,7 @@ double InitializationThread::doInit(const size_t threadCount)
        //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
        if(cpuSupport & CPU_TYPE_X64_ALL)
        {
-               if(lamexp_detect_wine())
+               if(MUtils::OS::running_on_wine())
                {
                        qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
                        cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
@@ -252,7 +273,7 @@ double InitializationThread::doInit(const size_t threadCount)
                PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
                PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
                PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
-               default: THROW("CPU support undefined!");
+               default: MUTILS_THROW("CPU support undefined!");
        }
 
        //Allocate queues
@@ -286,12 +307,15 @@ double InitializationThread::doInit(const size_t threadCount)
        QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
 
        QThreadPool *pool = new QThreadPool();
-       pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, (m_cpuFeatures.count * 3U), EXPECTED_TOOL_COUNT));
-       
+       pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, cores2threads(m_cpuFeatures.count), EXPECTED_TOOL_COUNT));
+       /* qWarning("Using %u threads for extraction.", pool->maxThreadCount()); */
+
        LockedFile::selfTest();
        ExtractorTask::clearFlags();
 
-       const long long timeExtractStart = lamexp_perfcounter_value();
+       //Start the timer
+       QElapsedTimer timeExtractStart;
+       timeExtractStart.start();
        
        //Extract all files
        while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
@@ -305,15 +329,15 @@ double InitializationThread::doInit(const size_t threadCount)
                const QByteArray toolHash(checksum.toLatin1());
                if(toolHash.size() != 96)
                {
-                       qFatal("The checksum for \"%s\" has an invalid size!", QUTF8(toolName));
+                       qFatal("The checksum for \"%s\" has an invalid size!", MUTILS_UTF8(toolName));
                        return -1.0;
                }
                        
                QResource *resource = new QResource(QString(":/tools/%1").arg(toolName));
                if(!(resource->isValid() && resource->data()))
                {
-                       LAMEXP_DELETE(resource);
-                       qFatal("The resource for \"%s\" could not be found!", QUTF8(toolName));
+                       MUTILS_DELETE(resource);
+                       qFatal("The resource for \"%s\" could not be found!", MUTILS_UTF8(toolName));
                        return -1.0;
                }
                        
@@ -323,7 +347,7 @@ double InitializationThread::doInit(const size_t threadCount)
                        continue;
                }
 
-               LAMEXP_DELETE(resource);
+               MUTILS_DELETE(resource);
        }
 
        //Sanity Check
@@ -334,9 +358,11 @@ double InitializationThread::doInit(const size_t threadCount)
 
        //Wait for extrator threads to finish
        pool->waitForDone();
-       LAMEXP_DELETE(pool);
+       MUTILS_DELETE(pool);
 
-       const long long timeExtractEnd = lamexp_perfcounter_value();
+       //Performance measure
+       const double delayExtract = double(timeExtractStart.elapsed()) / 1000.0;
+       timeExtractStart.invalidate();
 
        //Make sure all files were extracted correctly
        if(ExtractorTask::getExcept())
@@ -360,7 +386,6 @@ double InitializationThread::doInit(const size_t threadCount)
        }
 
        //Check delay
-       const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(lamexp_perfcounter_frequ());
        if(delayExtract > g_allowedExtractDelay)
        {
                m_slowIndicator = true;
@@ -369,16 +394,16 @@ double InitializationThread::doInit(const size_t threadCount)
        }
        else
        {
-               qDebug("Extracting the tools took %.5f seconds (OK).\n", delayExtract);
+               qDebug("Extracting the tools took %.3f seconds (OK).\n", delayExtract);
        }
 
        //Register all translations
        initTranslations();
 
        //Look for AAC encoders
-       initNeroAac();
-       initFhgAac();
-       initQAac();
+       initAacEnc_Nero();
+       initAacEnc_FHG();
+       initAacEnc_QAAC();
 
        m_bSuccess = true;
        delay();
@@ -386,64 +411,24 @@ double InitializationThread::doInit(const size_t threadCount)
        return delayExtract;
 }
 
-void InitializationThread::runBenchmark(void)
-{
-#ifdef ENABLE_BENCHMARK
-       static const size_t nLoops = 5;
-       const size_t maxThreads = (5 * m_cpuFeatures.count);
-       QMap<size_t, double> results;
-
-       for(size_t c = 1; c <= maxThreads; c++)
-       {
-               double delayAcc = 0.0;
-               for(size_t i = 0; i < nLoops; i++)
-               {
-                       delayAcc += doInit(c);
-                       lamexp_clean_all_tools();
-               }
-               results.insert(c, (delayAcc / double(nLoops)));
-       }
-
-       qWarning("\n----------------------------------------------");
-       qWarning("Benchmark Results:");
-       qWarning("----------------------------------------------");
-
-       double bestTime = DBL_MAX; size_t bestVal = 0;
-       QList<size_t> keys = results.keys();
-       for(QList<size_t>::ConstIterator iter = keys.begin(); iter != keys.end(); iter++)
-       {
-               const double time = results.value((*iter), DBL_MAX);
-               qWarning("%02u -> %7.4f", (*iter), time);
-               if(time < bestTime)
-               {
-                       bestTime = time;
-                       bestVal = (*iter);
-               }
-       }
-
-       qWarning("----------------------------------------------");
-       qWarning("BEST: %u of %u (factor: %7.4f)", bestVal, m_cpuFeatures.count, (double(bestVal) / double(m_cpuFeatures.count)));
-       qWarning("----------------------------------------------\n");
-       
-       qFatal("Benchmark complete. Thanks and bye bye!");
-#else //ENABLE_BENCHMARK
-       THROW("Sorry, the benchmark is *not* available in this build!");
-#endif //ENABLE_BENCHMARK
-}
-
 ////////////////////////////////////////////////////////////
-// PUBLIC FUNCTIONS
+// INTERNAL FUNCTIONS
 ////////////////////////////////////////////////////////////
 
 void InitializationThread::delay(void)
 {
-       __noop();
+       MUtils::OS::sleep_ms(333);
 }
 
+////////////////////////////////////////////////////////////
+// Translation Support
+////////////////////////////////////////////////////////////
+
 void InitializationThread::initTranslations(void)
 {
        //Search for language files
-       QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
+       const QDir qmDirectory(":/localization");
+       const QStringList qmFiles = qmDirectory.entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
 
        //Make sure we found at least one translation
        if(qmFiles.count() < 1)
@@ -452,27 +437,31 @@ void InitializationThread::initTranslations(void)
                return;
        }
 
+       //Initialize variables
+       const QString langResTemplate(":/localization/%1.txt");
+       QRegExp langIdExp("^LameXP_(\\w\\w)\\.qm$", Qt::CaseInsensitive);
+
        //Add all available translations
-       while(!qmFiles.isEmpty())
+       for(QStringList::ConstIterator iter = qmFiles.constBegin(); iter != qmFiles.constEnd(); iter++)
        {
+               const QString langFile = qmDirectory.absoluteFilePath(*iter);
                QString langId, langName;
                unsigned int systemId = 0, country = 0;
-               QString qmFile = qmFiles.takeFirst();
                
-               QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
-               if(langIdExp.indexIn(qmFile) >= 0)
+               if(QFileInfo(langFile).isFile() && (langIdExp.indexIn(*iter) >= 0))
                {
                        langId = langIdExp.cap(1).toLower();
-                       QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
+                       QResource langRes = QResource(langResTemplate.arg(*iter));
                        if(langRes.isValid() && langRes.size() > 0)
                        {
                                QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
                                QTextStream stream(&data, QIODevice::ReadOnly);
                                stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
-                               while(!stream.atEnd())
+
+                               while(!(stream.atEnd() || (stream.status() != QTextStream::Ok)))
                                {
                                        QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
-                                       if(langInfo.count() == 3)
+                                       if(langInfo.count() >= 3)
                                        {
                                                systemId = langInfo.at(0).trimmed().toUInt();
                                                country  = langInfo.at(1).trimmed().toUInt();
@@ -483,15 +472,15 @@ void InitializationThread::initTranslations(void)
                        }
                }
 
-               if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
+               if(!(langId.isEmpty() || langName.isEmpty() || (systemId == 0)))
                {
-                       if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
+                       if(MUtils::Translation::insert(langId, langFile, langName, systemId, country))
                        {
-                               qDebug("Registering translation: %s = %s (%u) [%u]", QUTF8(qmFile), QUTF8(langName), systemId, country);
+                               qDebug("Registering translation: %s = %s (%u) [%u]", MUTILS_UTF8(*iter), MUTILS_UTF8(langName), systemId, country);
                        }
                        else
                        {
-                               qWarning("Failed to register: %s", qmFile.toLatin1().constData());
+                               qWarning("Failed to register: %s", langFile.toLatin1().constData());
                        }
                }
        }
@@ -499,46 +488,64 @@ void InitializationThread::initTranslations(void)
        qDebug("All registered.\n");
 }
 
-void InitializationThread::initNeroAac(void)
+////////////////////////////////////////////////////////////
+// AAC Encoder Detection
+////////////////////////////////////////////////////////////
+
+void InitializationThread::initAacEnc_Nero(void)
 {
        const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
        
-       QFileInfo neroFileInfo[3];
-       neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
-       neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
-       neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
+       const QFileInfo neroFileInfo[3] =
+       {
+               QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath)),
+               QFileInfo(QString("%1/neroAacDec.exe").arg(appPath)),
+               QFileInfo(QString("%1/neroAacTag.exe").arg(appPath))
+       };
        
        bool neroFilesFound = true;
-       for(int i = 0; i < 3; i++)      { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
+       for(int i = 0; i < 3; i++)
+       {
+               if(!(neroFileInfo[i].exists() && neroFileInfo[i].isFile()))
+               {
+                       neroFilesFound = false;
+               }
+       }
 
-       //Lock the Nero binaries
        if(!neroFilesFound)
        {
-               qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
+               qDebug("Nero encoder binaries not found -> NeroAAC encoding support will be disabled!\n");
                return;
        }
 
-       qDebug("Found Nero AAC encoder binary:\n%s\n", QUTF8(neroFileInfo[0].canonicalFilePath()));
+       for(int i = 0; i < 3; i++)
+       {
+               if(!MUtils::OS::is_executable_file(neroFileInfo[i].canonicalFilePath()))
+               {
+                       qDebug("%s executbale is invalid -> NeroAAC encoding support will be disabled!\n", MUTILS_UTF8(neroFileInfo[i].fileName()));
+                       return;
+               }
+       }
 
-       LockedFile *neroBin[3];
-       for(int i = 0; i < 3; i++) neroBin[i] = NULL;
+       qDebug("Found Nero AAC encoder binary:\n%s\n", MUTILS_UTF8(neroFileInfo[0].canonicalFilePath()));
 
+       //Lock the Nero binaries
+       QScopedPointer<LockedFile> neroBin[3];
        try
        {
                for(int i = 0; i < 3; i++)
                {
-                       neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
+                       neroBin[i].reset(new LockedFile(neroFileInfo[i].canonicalFilePath()));
                }
        }
        catch(...)
        {
-               for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
-               qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
+               qWarning("Failed to get excluive lock to Nero encoder binary -> NeroAAC encoding support will be disabled!");
                return;
        }
 
        QProcess process;
-       lamexp_init_process(process, neroFileInfo[0].absolutePath());
+       MUtils::init_process(process, neroFileInfo[0].absolutePath());
 
        process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
 
@@ -548,11 +555,14 @@ void InitializationThread::initNeroAac(void)
                qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
                process.kill();
                process.waitForFinished(-1);
-               for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
                return;
        }
 
-       unsigned int neroVersion = 0;
+       bool neroSigFound = false;
+       quint32 neroVersion = 0;
+
+       QRegExp neroAacEncSig("Nero\\s+AAC\\s+Encoder", Qt::CaseInsensitive);
+       QRegExp neroAacEncVer("Package\\s+version:\\s+(\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
 
        while(process.state() != QProcess::NotRunning)
        {
@@ -560,91 +570,105 @@ void InitializationThread::initNeroAac(void)
                {
                        if(process.state() == QProcess::Running)
                        {
-                               qWarning("Nero process time out -> killing!");
+                               qWarning("NeroAAC process time out -> killing!");
                                process.kill();
                                process.waitForFinished(-1);
-                               for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
                                return;
                        }
                }
-
                while(process.canReadLine())
                {
                        QString line = QString::fromUtf8(process.readLine().constData()).simplified();
-                       QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
-                       int index1 = tokens.indexOf("Package");
-                       int index2 = tokens.indexOf("version:");
-                       if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
+                       if(neroAacEncSig.lastIndexIn(line) >= 0)
+                       {
+                               neroSigFound = true;
+                               continue;
+                       }
+                       if(neroSigFound && (neroAacEncVer.lastIndexIn(line) >= 0))
                        {
-                               QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
-                               if(versionTokens.count() == 4)
+                               quint32 tmp[4];
+                               if(MUtils::regexp_parse_uint32(neroAacEncVer, tmp, 4))
                                {
-                                       neroVersion = 0;
-                                       neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
-                                       neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
-                                       neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
-                                       neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
+                                       neroVersion = (qBound(0U, tmp[0], 9U) * 1000U) + (qBound(0U, tmp[1], 9U) * 100U) + (qBound(0U, tmp[2], 9U) * 10U) + qBound(0U, tmp[3], 9U);
                                }
                        }
                }
        }
 
-       if(!(neroVersion > 0))
+       if(neroVersion <= 0)
        {
-               qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
-               for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
+               qWarning("NeroAAC version could not be determined -> NeroAAC encoding support will be disabled!");
                return;
        }
-       
+       else if(neroVersion < lamexp_toolver_neroaac())
+       {
+               qWarning("NeroAAC version is too much outdated (%s) -> NeroAAC support will be disabled!", MUTILS_UTF8(lamexp_version2string("v?.?.?.?", neroVersion,              "N/A")));
+               qWarning("Minimum required NeroAAC version currently is: %s\n",                            MUTILS_UTF8(lamexp_version2string("v?.?.?.?", lamexp_toolver_neroaac(), "N/A")));
+               return;
+       }
+
+       qDebug("Enabled NeroAAC encoder %s.\n", MUTILS_UTF8(lamexp_version2string("v?.?.?.?", neroVersion, "N/A")));
+
        for(int i = 0; i < 3; i++)
        {
-               lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
+               lamexp_tools_register(neroFileInfo[i].fileName(), neroBin[i].take(), neroVersion);
        }
 }
 
-void InitializationThread::initFhgAac(void)
+void InitializationThread::initAacEnc_FHG(void)
 {
        const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
        
-       QFileInfo fhgFileInfo[5];
-       fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
-       fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
-       fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
-       fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
-       fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
+       const QFileInfo fhgFileInfo[5] =
+       {
+               QFileInfo(QString("%1/fhgaacenc.exe")   .arg(appPath)),
+               QFileInfo(QString("%1/enc_fhgaac.dll")  .arg(appPath)),
+               QFileInfo(QString("%1/nsutil.dll")      .arg(appPath)),
+               QFileInfo(QString("%1/libmp4v2.dll")    .arg(appPath)),
+               QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath))
+       };
        
        bool fhgFilesFound = true;
-       for(int i = 0; i < 5; i++)      { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
+       for(int i = 0; i < 5; i++)
+       {
+               if(!(fhgFileInfo[i].exists() && fhgFileInfo[i].isFile()))
+               {
+                       fhgFilesFound = false;
+               }
+       }
 
-       //Lock the FhgAacEnc binaries
        if(!fhgFilesFound)
        {
                qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
                return;
        }
 
-       qDebug("Found FhgAacEnc cli_exe:\n%s\n", QUTF8(fhgFileInfo[0].canonicalFilePath()));
-       qDebug("Found FhgAacEnc enc_dll:\n%s\n", QUTF8(fhgFileInfo[1].canonicalFilePath()));
+       if(!MUtils::OS::is_executable_file(fhgFileInfo[0].canonicalFilePath()))
+       {
+               qDebug("FhgAacEnc executbale is invalid -> FhgAacEnc support will be disabled!\n");
+               return;
+       }
 
-       LockedFile *fhgBin[5];
-       for(int i = 0; i < 5; i++) fhgBin[i] = NULL;
+       qDebug("Found FhgAacEnc cli_exe:\n%s\n", MUTILS_UTF8(fhgFileInfo[0].canonicalFilePath()));
+       qDebug("Found FhgAacEnc enc_dll:\n%s\n", MUTILS_UTF8(fhgFileInfo[1].canonicalFilePath()));
 
+       //Lock the FhgAacEnc binaries
+       QScopedPointer<LockedFile> fhgBin[5];
        try
        {
                for(int i = 0; i < 5; i++)
                {
-                       fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
+                       fhgBin[i].reset(new LockedFile(fhgFileInfo[i].canonicalFilePath()));
                }
        }
        catch(...)
        {
-               for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
                qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
                return;
        }
 
        QProcess process;
-       lamexp_init_process(process, fhgFileInfo[0].absolutePath());
+       MUtils::init_process(process, fhgFileInfo[0].absolutePath());
 
        process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
 
@@ -654,12 +678,11 @@ void InitializationThread::initFhgAac(void)
                qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
                process.kill();
                process.waitForFinished(-1);
-               for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
                return;
        }
 
+       quint32 fhgVersion = 0;
        QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
-       unsigned int fhgVersion = 0;
 
        while(process.state() != QProcess::NotRunning)
        {
@@ -669,7 +692,6 @@ void InitializationThread::initFhgAac(void)
                        qWarning("FhgAacEnc process time out -> killing!");
                        process.kill();
                        process.waitForFinished(-1);
-                       for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
                        return;
                }
                while(process.bytesAvailable() > 0)
@@ -677,73 +699,86 @@ void InitializationThread::initFhgAac(void)
                        QString line = QString::fromUtf8(process.readLine().constData()).simplified();
                        if(fhgAacEncSig.lastIndexIn(line) >= 0)
                        {
-                               bool ok = false;
-                               unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
-                               if(ok) fhgVersion = temp;
+                               quint32 tmp;
+                               if(MUtils::regexp_parse_uint32(fhgAacEncSig, tmp))
+                               {
+                                       fhgVersion = tmp;
+                               }
                        }
                }
        }
 
-       if(!(fhgVersion > 0))
+       if(fhgVersion <= 0)
        {
                qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
-               for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
                return;
        }
        else if(fhgVersion < lamexp_toolver_fhgaacenc())
        {
-               qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", lamexp_version2string("????-??-??", fhgVersion, "N/A").toLatin1().constData());
-               qWarning("Minimum required FhgAacEnc version currently is: %s\n", lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A").toLatin1().constData());
-               for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
+               qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", MUTILS_UTF8(lamexp_version2string("????-??-??", fhgVersion,                 "N/A")));
+               qWarning("Minimum required FhgAacEnc version currently is: %s\n",                              MUTILS_UTF8(lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A")));
                return;
        }
        
+       qDebug("Enabled FhgAacEnc %s.\n", MUTILS_UTF8(lamexp_version2string("????-??-??", fhgVersion, "N/A")));
+
        for(int i = 0; i < 5; i++)
        {
-               lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
+               lamexp_tools_register(fhgFileInfo[i].fileName(), fhgBin[i].take(), fhgVersion);
        }
 }
 
-void InitializationThread::initQAac(void)
+void InitializationThread::initAacEnc_QAAC(void)
 {
        const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
 
-       QFileInfo qaacFileInfo[2];
-       qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
-       qaacFileInfo[1] = QFileInfo(QString("%1/libsoxrate.dll").arg(appPath));
+       const QFileInfo qaacFileInfo[3] =
+       {
+               QFileInfo(QString("%1/qaac.exe")           .arg(appPath)),
+               QFileInfo(QString("%1/libsoxr.dll")        .arg(appPath)),
+               QFileInfo(QString("%1/libsoxconvolver.dll").arg(appPath))
+       };
        
        bool qaacFilesFound = true;
-       for(int i = 0; i < 2; i++)      { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
+       for(int i = 0; i < 3; i++)
+       {
+               if(!(qaacFileInfo[i].exists() && qaacFileInfo[i].isFile()))
+               {
+                       qaacFilesFound = false;
+               }
+       }
 
-       //Lock the QAAC binaries
        if(!qaacFilesFound)
        {
-               qDebug("QAAC binaries not found -> QAAC support will be disabled!\n");
+               qDebug("QAAC binary or companion DLL's not found -> QAAC support will be disabled!\n");
                return;
        }
 
-       qDebug("Found QAAC encoder:\n%s\n", QUTF8(qaacFileInfo[0].canonicalFilePath()));
+       if(!MUtils::OS::is_executable_file(qaacFileInfo[0].canonicalFilePath()))
+       {
+               qDebug("QAAC executbale is invalid -> QAAC support will be disabled!\n");
+               return;
+       }
 
-       LockedFile *qaacBin[2];
-       for(int i = 0; i < 2; i++) qaacBin[i] = NULL;
+       qDebug("Found QAAC encoder:\n%s\n", MUTILS_UTF8(qaacFileInfo[0].canonicalFilePath()));
 
+       //Lock the required QAAC binaries
+       QScopedPointer<LockedFile> qaacBin[3];
        try
        {
-               for(int i = 0; i < 2; i++)
+               for(int i = 0; i < 3; i++)
                {
-                       qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
+                       qaacBin[i].reset(new LockedFile(qaacFileInfo[i].canonicalFilePath()));
                }
        }
        catch(...)
        {
-               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
                qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
                return;
        }
 
        QProcess process;
-       lamexp_init_process(process, qaacFileInfo[0].absolutePath());
-
+       MUtils::init_process(process, qaacFileInfo[0].absolutePath());
        process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
 
        if(!process.waitForStarted())
@@ -752,14 +787,18 @@ void InitializationThread::initQAac(void)
                qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
                process.kill();
                process.waitForFinished(-1);
-               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
                return;
        }
 
-       QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
+       QRegExp qaacEncSig("qaac (\\d)\\.(\\d+)", Qt::CaseInsensitive);
        QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
-       unsigned int qaacVersion = 0;
-       unsigned int coreVersion = 0;
+       QRegExp soxrEncSig("libsoxr-\\d\\.\\d\\.\\d", Qt::CaseInsensitive);
+       QRegExp soxcEncSig("libsoxconvolver \\d\\.\\d\\.\\d", Qt::CaseInsensitive);
+
+       quint32 qaacVersion = 0;
+       quint32 coreVersion = 0;
+       bool soxrFound = false;
+       bool soxcFound = false;
 
        while(process.state() != QProcess::NotRunning)
        {
@@ -769,7 +808,6 @@ void InitializationThread::initQAac(void)
                        qWarning("QAAC process time out -> killing!");
                        process.kill();
                        process.waitForFinished(-1);
-               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
                        return;
                }
                while(process.bytesAvailable() > 0)
@@ -777,66 +815,73 @@ void InitializationThread::initQAac(void)
                        QString line = QString::fromUtf8(process.readLine().constData()).simplified();
                        if(qaacEncSig.lastIndexIn(line) >= 0)
                        {
-                               unsigned int tmp[3] = {0, 0, 0};
-                               bool ok[3] = {false, false, false};
-                               tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
-                               tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
-                               tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
-                               if(ok[0] && ok[1] && ok[2])
+                               quint32 tmp[2];
+                               if(MUtils::regexp_parse_uint32(qaacEncSig, tmp, 2))
                                {
-                                       qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
+                                       qaacVersion = (qBound(0U, tmp[0], 9U) * 100) +  qBound(0U, tmp[1], 99U);
                                }
                        }
                        if(coreEncSig.lastIndexIn(line) >= 0)
                        {
-                               unsigned int tmp[4] = {0, 0, 0, 0};
-                               bool ok[4] = {false, false, false, false};
-                               tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
-                               tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
-                               tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
-                               tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
-                               if(ok[0] && ok[1] && ok[2] && ok[3])
+                               quint32 tmp[4];
+                               if(MUtils::regexp_parse_uint32(coreEncSig, tmp, 4))
                                {
-                                       coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
+                                       coreVersion = (qBound(0U, tmp[0], 9U) * 1000U) + (qBound(0U, tmp[1], 9U) * 100U) + (qBound(0U, tmp[2], 9U) * 10U) + qBound(0U, tmp[3], 9U);
                                }
                        }
+                       if(soxcEncSig.lastIndexIn(line) >= 0)
+                       {
+                               soxcFound = true;
+                       }
+                       if(soxrEncSig.lastIndexIn(line) >= 0)
+                       {
+                               soxrFound = true;
+                       }
                }
        }
 
-       //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
-
-       if(!(qaacVersion > 0))
+       if(qaacVersion <= 0)
        {
                qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
-               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
                return;
        }
        else if(qaacVersion < lamexp_toolver_qaacenc())
        {
-               qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
-               qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
-               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
+               qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", MUTILS_UTF8(lamexp_version2string("v?.??", qaacVersion,              "N/A")));
+               qWarning("Minimum required QAAC version currently is: %s.\n",                        MUTILS_UTF8(lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A")));
                return;
        }
 
-       if(!(coreVersion > 0))
+       if(coreVersion <= 0)
        {
                qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
-               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
                return;
        }
        else if(coreVersion < lamexp_toolver_coreaudio())
        {
-               qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
-               qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
-               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
+               qWarning("CoreAudioToolbox version is outdated (%s) -> QAAC support will be disabled!", MUTILS_UTF8(lamexp_version2string("v?.?.?.?", coreVersion,                "N/A")));
+               qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n",               MUTILS_UTF8(lamexp_version2string("v?.?.?.?", lamexp_toolver_coreaudio(), "N/A")));
                return;
        }
 
-       lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
-       lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
+       if(!(soxrFound && soxcFound))
+       {
+               qWarning("libsoxr and/or libsoxconvolver not available -> QAAC support will be disabled!\n");
+               return;
+       }
+
+       qDebug("Enabled qaac encoder %s (using CoreAudioToolbox %s).\n", MUTILS_UTF8(lamexp_version2string("v?.??", qaacVersion, "N/A")), MUTILS_UTF8(lamexp_version2string("v?.?.?.?", coreVersion, "N/A")));
+
+       for(int i = 0; i < 3; i++)
+       {
+               lamexp_tools_register(qaacFileInfo[i].fileName(), qaacBin[i].take(), qaacVersion);
+       }
 }
 
+////////////////////////////////////////////////////////////
+// Self-Test Function
+////////////////////////////////////////////////////////////
+
 void InitializationThread::selfTest(void)
 {
        const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
@@ -852,7 +897,7 @@ void InitializationThread::selfTest(void)
                        PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
                        PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
                        PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
-                       default: THROW("CPU support undefined!");
+                       default: MUTILS_THROW("CPU support undefined!");
                }
                unsigned int n = 0;
                for(int i = 0; true; i++)
@@ -867,17 +912,17 @@ void InitializationThread::selfTest(void)
                                const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
                                if(g_lamexp_tools[i].uiCpuType & cpu[k])
                                {
-                                       qDebug("%02i -> %s", ++n, QUTF8(toolName));
+                                       qDebug("%02i -> %s", ++n, MUTILS_UTF8(toolName));
                                        QFile resource(QString(":/tools/%1").arg(toolName));
                                        if(!resource.open(QIODevice::ReadOnly))
                                        {
-                                               qFatal("The resource for \"%s\" could not be opened!", QUTF8(toolName));
+                                               qFatal("The resource for \"%s\" could not be opened!", MUTILS_UTF8(toolName));
                                                break;
                                        }
                                        QByteArray hash = LockedFile::fileHash(resource);
                                        if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
                                        {
-                                               qFatal("Hash check for tool \"%s\" has failed!", QUTF8(toolName));
+                                               qFatal("Hash check for tool \"%s\" has failed!", MUTILS_UTF8(toolName));
                                                break;
                                        }
                                        resource.close();
@@ -890,7 +935,7 @@ void InitializationThread::selfTest(void)
                }
                if(n != EXPECTED_TOOL_COUNT)
                {
-                       qFatal("Tool count mismatch for CPU type %u !!!", cpu[4]);
+                       qFatal("Tool count mismatch for CPU type %u !!!", cpu[k]);
                }
                qDebug("Done.\n");
        }