OSDN Git Service

Implemented multi-threading for file analyzer. Now multiple files can be analyzed...
[lamexp/LameXP.git] / src / Thread_Initialization.cpp
index 6b908d3..f037ce6 100644 (file)
@@ -1,6 +1,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 // LameXP - Audio Encoder Front-End
-// Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2012 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
@@ -21,8 +21,8 @@
 
 #include "Thread_Initialization.h"
 
-#include "Global.h"
 #include "LockedFile.h"
+#include "Tools.h"
 
 #include <QFileInfo>
 #include <QCoreApplication>
 #include <QLibrary>
 #include <QResource>
 #include <QTime>
+#include <QTextStream>
+#include <QRunnable>
+#include <QThreadPool>
+#include <QMutex>
 
-#include <Windows.h>
+/* helper macros */
+#define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
+static const double g_allowedExtractDelay = 12.0;
 
 ////////////////////////////////////////////////////////////
-// TOOLS
+// ExtractorTask class
 ////////////////////////////////////////////////////////////
 
-static const struct
+class ExtractorTask : public QRunnable
 {
-       char *pcHash;
-       char *pcName;
-       unsigned int uiVersion;
-}
-g_lamexp_tools[] =
-{
-       {"3b41f85dde8d4a5a0f4cd5f461099d0db24610ba", "alac.exe", UINT_MAX},
-       {"fb74ac8b73ad8cba2c3b4e6e61f23401d630dc22", "elevator.exe", UINT_MAX},
-       {"3c647950bccfcc75d0746c0772e7115684be4dc5", "faad.exe", 27},
-       {"d33cd86f04bd4067e244d2804466583c7b90a4e2", "flac.exe", 121},
-       {"9328a50e89b54ec065637496d9681a7e3eebf915", "gpgv.exe", 1411},
-       {"d837bf6ee4dab557d8b02d46c75a24e58980fffa", "gpgv.gpg", UINT_MAX},
-       {"b8800842893e2900eea7cda5c2556661333bc5db", "lame.exe", 39916},
-       {"a4e929cfaa42fa2e61a3d0c6434c77a06d45aef3", "mac.exe", 406},
-       {"ff65938a9d9b2f453887ca5e731fb75b98015683", "mediainfo_i386.exe", 743},
-       {"470b433b7ee06830f382266cc2680a3d6e1d3993", "mediainfo_x64.exe", 743},
-       {"aa89763a5ba4d1a5986549b9ee53e005c51940c1", "mpcdec.exe", 435},
-       {"38f81efca6c1eeab0b9dc39d06c2ac750267217f", "mpg123.exe", 1132},
-       {"8dd7138714c3bcb39f5a3213413addba13d06f1e", "oggdec.exe", UINT_MAX},
-       {"14a99d3b1f0b166dbd68db45196da871e58e14ec", "oggenc2_i386.exe", 287602},
-       {"36f8d93ef3df6a420a73a9b5cf02dafdaf4321f0", "oggenc2_sse2.exe", 287602},
-       {"87ad1af73e9b9db3da3db645e5c2253cb0c2a2ea", "oggenc2_x64.exe", 287602},
-       {"0d9035bb62bdf46a2785261f8be5a4a0972abd15", "shorten.exe", 361},
-       {"50ead3b852cbfc067a402e6c2d0d0d8879663dec", "sox.exe", 1432},
-       {"8671e16497a2d217d3707d4aa418678d02b16bcc", "speexdec.exe", 12},
-       {"093bfdec22872ca99e40183937c88785468be989", "tta.exe", 21},
-       {"8c842eef65248b46fa6cb9a9e5714f575672d999", "valdec.exe", 31},
-       {"62e2805d1b2eb2a4d86a5ca6e6ea58010d05d2a7", "wget.exe", 1114},
-       {"a7e8aad52213e339ad985829722f35eab62be182", "wupdate.exe", UINT_MAX},
-       {"b7d14b3540d24df13119a55d97623a61412de6e3", "wvunpack.exe", 4601},
-       {NULL, NULL, NULL}
+public:
+       ExtractorTask(const QDir &appDir, const QString &toolName, const QString &toolShortName, const QByteArray &toolHash, const unsigned int toolVersion)
+       :
+               QRunnable(), m_appDir(appDir), m_toolName(toolName), m_toolShortName(toolShortName), m_toolHash(toolHash), m_toolVersion(toolVersion)
+       {
+               /* Nothing to do */
+       }
+
+       static void clearFlags(void)
+       {
+               s_bAbort = s_bCustom = false;
+               s_errMsg[0] = '\0';
+       }
+
+       static bool getAbort(void) { return s_bAbort; }
+       static bool getCustom(void) { return s_bCustom; }
+       static char *const getError(void) { return s_errMsg; }
+
+protected:
+       void run(void)
+       {
+               try
+               {
+                       LockedFile *lockedFile = NULL;
+                       unsigned int version = m_toolVersion;
+                       
+                       if(!s_bAbort)
+                       {
+                               QFileInfo customTool(QString("%1/tools/%2/%3").arg(m_appDir.canonicalPath(), QString::number(lamexp_version_build()), m_toolShortName));
+                               if(customTool.exists() && customTool.isFile())
+                               {
+                                       qDebug("Setting up file: %s <- %s", m_toolShortName.toLatin1().constData(), m_appDir.relativeFilePath(customTool.canonicalFilePath()).toLatin1().constData());
+                                       lockedFile = new LockedFile(customTool.canonicalFilePath()); version = UINT_MAX; s_bCustom = true;
+                               }
+                               else
+                               {
+                                       qDebug("Extracting file: %s -> %s", m_toolName.toLatin1().constData(), m_toolShortName.toLatin1().constData());
+                                       lockedFile = new LockedFile(QString(":/tools/%1").arg(m_toolName), QString("%1/lamexp_%2").arg(lamexp_temp_folder2(), m_toolShortName), m_toolHash);
+                               }
+
+                               if(lockedFile)
+                               {
+                                       QMutexLocker lock(&s_mutex);
+                                       lamexp_register_tool(m_toolShortName, lockedFile, version);
+                               }
+                       }
+               }
+               catch(char *errorMsg)
+               {
+                       qWarning("At least one of the required tools could not be initialized:\n%s", errorMsg);
+                       if(s_mutex.tryLock())
+                       {
+                               if(!s_bAbort) { s_bAbort = true; strncpy_s(s_errMsg, 1024, errorMsg, _TRUNCATE); }
+                               s_mutex.unlock();
+                       }
+               }
+       }
+
+private:
+       const QDir m_appDir;
+       const QString m_toolName;
+       const QString m_toolShortName;
+       const QByteArray m_toolHash;
+       const unsigned int m_toolVersion;
+
+       static volatile bool s_bAbort;
+       static volatile bool s_bCustom;
+       static QMutex s_mutex;
+       static char s_errMsg[1024];
 };
 
+volatile bool ExtractorTask::s_bAbort = false;
+volatile bool ExtractorTask::s_bCustom = false;
+char ExtractorTask::s_errMsg[1024] = {'\0'};
+QMutex ExtractorTask::s_mutex;
+
 ////////////////////////////////////////////////////////////
 // Constructor
 ////////////////////////////////////////////////////////////
 
-InitializationThread::InitializationThread(void)
+InitializationThread::InitializationThread(const lamexp_cpu_t *cpuFeatures)
 {
        m_bSuccess = false;
+       memset(&m_cpuFeatures, 0, sizeof(lamexp_cpu_t));
+       m_slowIndicator = false;
+       
+       if(cpuFeatures)
+       {
+               memcpy(&m_cpuFeatures, cpuFeatures, sizeof(lamexp_cpu_t));
+       }
 }
 
 ////////////////////////////////////////////////////////////
@@ -92,10 +148,45 @@ void InitializationThread::run()
        m_bSuccess = false;
        delay();
 
-       QMap<QString, QString> checksum;
-       QMap<QString, unsigned int> version;
+       //CPU type selection
+       unsigned int cpuSupport = 0;
+       if(m_cpuFeatures.sse && m_cpuFeatures.sse2 && m_cpuFeatures.intel)
+       {
+               cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
+       }
+       else
+       {
+               cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
+       }
+
+       //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)
+       {
+               //DWORD osVerNo = lamexp_get_os_version();
+               //if((HIWORD(osVerNo) == 6) && (LOWORD(osVerNo) == 2))
+               if(lamexp_detect_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;
+               }
+       }
+
+       //Print selected CPU type
+       switch(cpuSupport)
+       {
+               PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
+               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!";
+       }
+
+       //Allocate maps
+       QMap<QString, QString> mapChecksum;
+       QMap<QString, unsigned int> mapVersion;
+       QMap<QString, unsigned int> mapCpuType;
 
-       //Init checksums
+       //Init properties
        for(int i = 0; i < INT_MAX; i++)
        {
                if(!g_lamexp_tools[i].pcName && !g_lamexp_tools[i].pcHash && !g_lamexp_tools[i].uiVersion)
@@ -105,8 +196,9 @@ void InitializationThread::run()
                else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
                {
                        const QString currentTool = QString::fromLatin1(g_lamexp_tools[i].pcName);
-                       checksum.insert(currentTool, QString::fromLatin1(g_lamexp_tools[i].pcHash));
-                       version.insert(currentTool, g_lamexp_tools[i].uiVersion);
+                       mapChecksum.insert(currentTool, QString::fromLatin1(g_lamexp_tools[i].pcHash));
+                       mapCpuType.insert(currentTool, g_lamexp_tools[i].uiCpuType);
+                       mapVersion.insert(currentTool, g_lamexp_tools[i].uiVersion);
                }
                else
                {
@@ -116,45 +208,87 @@ void InitializationThread::run()
 
        QDir toolsDir(":/tools/");
        QList<QFileInfo> toolsList = toolsDir.entryInfoList(QStringList("*.*"), QDir::Files, QDir::Name);
+       QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
+
+       QThreadPool *pool = new QThreadPool();
+       int idealThreadCount = QThread::idealThreadCount();
+       if(idealThreadCount > 0)
+       {
+               pool->setMaxThreadCount(idealThreadCount * 2);
+       }
        
+       ExtractorTask::clearFlags();
+
        QTime timer;
        timer.start();
-
+       
        //Extract all files
-       for(int i = 0; i < toolsList.count(); i++)
+       while(!toolsList.isEmpty())
        {
                try
                {
-                       QString toolName = toolsList.at(i).fileName().toLower();
-                       qDebug("Extracting file: %s", toolName.toLatin1().constData());
-                       QByteArray toolHash = checksum.take(toolName).toLatin1();
-                       unsigned int toolVersion = version.take(toolName);
-                       if(toolHash.size() != 40)
+                       QFileInfo currentTool = toolsList.takeFirst();
+                       QString toolName = currentTool.fileName().toLower();
+                       QString toolShortName = QString("%1.%2").arg(currentTool.baseName().toLower(), currentTool.suffix().toLower());
+                       
+                       QByteArray toolHash = mapChecksum.take(toolName).toLatin1();
+                       unsigned int toolCpuType = mapCpuType.take(toolName);
+                       unsigned int toolVersion = mapVersion.take(toolName);
+                       
+                       if(toolHash.size() != 72)
                        {
                                throw "The required checksum is missing, take care!";
                        }
-                       LockedFile *lockedFile = new LockedFile(QString(":/tools/%1").arg(toolName), QString(lamexp_temp_folder2()).append(QString("/tool_%1").arg(toolName)), toolHash);
-                       lamexp_register_tool(toolName, lockedFile, toolVersion);
+                       
+                       if(toolCpuType & cpuSupport)
+                       {
+                               pool->start(new ExtractorTask(appDir, toolName, toolShortName, toolHash, toolVersion));
+                               QThread::yieldCurrentThread();
+                       }
                }
                catch(char *errorMsg)
                {
-                       qFatal("At least one of the required tools could not be extracted:\n%s", errorMsg);
+                       qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
                        return;
                }
        }
-       
-       if(!checksum.isEmpty())
+
+       //Wait for extrator threads to finish
+       pool->waitForDone();
+       LAMEXP_DELETE(pool);
+
+       //Make sure all files were extracted correctly
+       if(ExtractorTask::getAbort())
        {
-               qFatal("At least one required tool could not be found:\n%s", toolsDir.filePath(checksum.keys().first()).toLatin1().constData());
+               qFatal("At least one of the required tools could not be initialized:\n%s", ExtractorTask::getError());
                return;
        }
-       
+
+       //Make sure all files were extracted
+       if(!mapChecksum.isEmpty())
+       {
+               qFatal("At least one required tool could not be found:\n%s", toolsDir.filePath(mapChecksum.keys().first()).toLatin1().constData());
+               return;
+       }
+
        qDebug("All extracted.\n");
 
+       //Clean-up
+       mapChecksum.clear();
+       mapVersion.clear();
+       mapCpuType.clear();
+       
+       //Using any custom tools?
+       if(ExtractorTask::getCustom())
+       {
+               qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
+       }
+
        //Check delay
        double delayExtract = static_cast<double>(timer.elapsed()) / 1000.0;
-       if(delayExtract > 8.0)
+       if(delayExtract > g_allowedExtractDelay)
        {
+               m_slowIndicator = true;
                qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
                qWarning("Please report performance problems to your anti-virus developer !!!\n");
        }
@@ -162,11 +296,10 @@ void InitializationThread::run()
        //Register all translations
        initTranslations();
 
-       //Look for Nero encoder
+       //Look for AAC encoders
        initNeroAac();
-       
-       //Look for WMA File decoder
-       initWmaDec();
+       initFhgAac();
+       initQAac();
 
        delay();
        m_bSuccess = true;
@@ -206,33 +339,43 @@ void InitializationThread::initTranslations(void)
        while(!qmFiles.isEmpty())
        {
                QString langId, langName;
-               unsigned int systemId = 0;
+               unsigned int systemId = 0, country = 0;
                QString qmFile = qmFiles.takeFirst();
                
                QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
                if(langIdExp.indexIn(qmFile) >= 0)
                {
                        langId = langIdExp.cap(1).toLower();
+                       QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
+                       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())
+                               {
+                                       QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
+                                       if(langInfo.count() == 3)
+                                       {
+                                               systemId = langInfo.at(0).trimmed().toUInt();
+                                               country  = langInfo.at(1).trimmed().toUInt();
+                                               langName = langInfo.at(2).trimmed();
+                                               break;
+                                       }
+                               }
+                       }
                }
 
-               QResource langRes = (QString(":/localization/%1.txt").arg(qmFile));
-               if(langRes.isValid() && langRes.size() > 0)
+               if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
                {
-                       QStringList langInfo = QString::fromUtf8(reinterpret_cast<const char*>(langRes.data()), langRes.size()).simplified().split(",", QString::SkipEmptyParts);
-                       if(langInfo.count() == 2)
+                       if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
                        {
-                               systemId = langInfo.at(0).toUInt();
-                               langName = langInfo.at(1);
+                               qDebug("Registering translation: %s = %s (%u) [%u]", qmFile.toUtf8().constData(), langName.toUtf8().constData(), systemId, country);
+                       }
+                       else
+                       {
+                               qWarning("Failed to register: %s", qmFile.toLatin1().constData());
                        }
-               }
-               
-               if(lamexp_translation_register(langId, qmFile, langName, systemId))
-               {
-                       qDebug64("Registering translation: %1 = %2 (%3)", qmFile, langName, QString::number(systemId));
-               }
-               else
-               {
-                       qWarning("Failed to register: %s", qmFile.toLatin1().constData());
                }
        }
 
@@ -241,10 +384,12 @@ void InitializationThread::initTranslations(void)
 
 void InitializationThread::initNeroAac(void)
 {
+       const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
+       
        QFileInfo neroFileInfo[3];
-       neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(QCoreApplication::applicationDirPath()));
-       neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(QCoreApplication::applicationDirPath()));
-       neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(QCoreApplication::applicationDirPath()));
+       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));
        
        bool neroFilesFound = true;
        for(int i = 0; i < 3; i++)      { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
@@ -318,10 +463,10 @@ void InitializationThread::initNeroAac(void)
                                if(versionTokens.count() == 4)
                                {
                                        neroVersion = 0;
-                                       neroVersion += min(9, max(0, versionTokens.at(3).toInt()));
-                                       neroVersion += min(9, max(0, versionTokens.at(2).toInt())) * 10;
-                                       neroVersion += min(9, max(0, versionTokens.at(1).toInt())) * 100;
-                                       neroVersion += min(9, max(0, versionTokens.at(0).toInt())) * 1000;
+                                       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;
                                }
                        }
                }
@@ -340,80 +485,269 @@ void InitializationThread::initNeroAac(void)
        }
 }
 
-
-void InitializationThread::initWmaDec(void)
+void InitializationThread::initFhgAac(void)
 {
-       static const char* wmaDecoderComponentPath = "NCH Software/Components/wmawav/wmawav.exe";
-
-       LockedFile *wmaFileBin = NULL;
-       QFileInfo wmaFileInfo = QFileInfo(QString("%1/%2").arg(lamexp_known_folder(lamexp_folder_programfiles), wmaDecoderComponentPath));
+       const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
+       
+       QFileInfo fhgFileInfo[4];
+       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));
+       
+       bool fhgFilesFound = true;
+       for(int i = 0; i < 4; i++)      { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
 
-       if(!wmaFileInfo.exists())
+       //Lock the FhgAacEnc binaries
+       if(!fhgFilesFound)
        {
-               qDebug("WMA File Decoder not found -> WMA decoding support will be disabled!\n");
+               qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
                return;
        }
 
+       qDebug("Found FhgAacEnc cli_exe:\n%s\n", fhgFileInfo[0].canonicalFilePath().toUtf8().constData());
+       qDebug("Found FhgAacEnc enc_dll:\n%s\n", fhgFileInfo[1].canonicalFilePath().toUtf8().constData());
+
+       LockedFile *fhgBin[4];
+       for(int i = 0; i < 4; i++) fhgBin[i] = NULL;
+
        try
        {
-               wmaFileBin = new LockedFile(wmaFileInfo.canonicalFilePath());
+               for(int i = 0; i < 4; i++)
+               {
+                       fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
+               }
        }
        catch(...)
        {
-               qWarning("Failed to get excluive lock to WMA File Decoder binary -> WMA decoding support will be disabled!");
+               for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
+               qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
                return;
        }
 
        QProcess process;
        process.setProcessChannelMode(QProcess::MergedChannels);
        process.setReadChannel(QProcess::StandardOutput);
-       process.start(wmaFileInfo.canonicalFilePath(), QStringList());
+       process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
 
        if(!process.waitForStarted())
        {
-               qWarning("WmaWav process failed to create!");
+               qWarning("FhgAacEnc process failed to create!");
                qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
                process.kill();
                process.waitForFinished(-1);
+               for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
                return;
        }
 
-       bool b_wmaWavFound = false;
+       QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
+       unsigned int fhgVersion = 0;
 
        while(process.state() != QProcess::NotRunning)
        {
-               if(!process.waitForReadyRead())
+               process.waitForReadyRead();
+               if(!process.bytesAvailable() && process.state() == QProcess::Running)
                {
-                       if(process.state() == QProcess::Running)
+                       qWarning("FhgAacEnc process time out -> killing!");
+                       process.kill();
+                       process.waitForFinished(-1);
+                       for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
+                       return;
+               }
+               while(process.bytesAvailable() > 0)
+               {
+                       QString line = QString::fromUtf8(process.readLine().constData()).simplified();
+                       if(fhgAacEncSig.lastIndexIn(line) >= 0)
                        {
-                               qWarning("WmaWav process time out -> killing!");
-                               process.kill();
-                               process.waitForFinished(-1);
-                               return;
+                               bool ok = false;
+                               unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
+                               if(ok) fhgVersion = temp;
                        }
                }
-               while(process.canReadLine())
+       }
+
+       if(!(fhgVersion > 0))
+       {
+               qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
+               for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
+               return;
+       }
+       else if(fhgVersion < lamexp_toolver_fhgaacenc())
+       {
+               qWarning("FhgAacEnc version is too much outdated -> FhgAacEnc support will be disabled!");
+               for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
+               return;
+       }
+       
+       for(int i = 0; i < 4; i++)
+       {
+               lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
+       }
+}
+
+void InitializationThread::initQAac(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));
+       
+       bool qaacFilesFound = true;
+       for(int i = 0; i < 2; i++)      { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
+
+       //Lock the QAAC binaries
+       if(!qaacFilesFound)
+       {
+               qDebug("QAAC binaries not found -> QAAC support will be disabled!\n");
+               return;
+       }
+
+       qDebug("Found QAAC encoder:\n%s\n", qaacFileInfo[0].canonicalFilePath().toUtf8().constData());
+
+       LockedFile *qaacBin[2];
+       for(int i = 0; i < 2; i++) qaacBin[i] = NULL;
+
+       try
+       {
+               for(int i = 0; i < 2; i++)
+               {
+                       qaacBin[i] = 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;
+       process.setProcessChannelMode(QProcess::MergedChannels);
+       process.setReadChannel(QProcess::StandardOutput);
+       process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
+
+       if(!process.waitForStarted())
+       {
+               qWarning("QAAC process failed to create!");
+               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 coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
+       unsigned int qaacVersion = 0;
+       unsigned int coreVersion = 0;
+
+       while(process.state() != QProcess::NotRunning)
+       {
+               process.waitForReadyRead();
+               if(!process.bytesAvailable() && process.state() == QProcess::Running)
+               {
+                       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)
                {
                        QString line = QString::fromUtf8(process.readLine().constData()).simplified();
-                       if(line.contains("Usage: wmatowav.exe WMAFileSpec WAVFileSpec", Qt::CaseInsensitive))
+                       if(qaacEncSig.lastIndexIn(line) >= 0)
                        {
-                               b_wmaWavFound = true;
+                               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])
+                               {
+                                       qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
+                               }
+                       }
+                       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])
+                               {
+                                       coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
+                               }
                        }
                }
        }
 
-       if(!b_wmaWavFound)
+       //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
+
+       if(!(qaacVersion > 0))
        {
-               qWarning("WmaWav could not be identified -> WMA decoding support will be disabled!\n");
-               LAMEXP_DELETE(wmaFileBin);
+               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());
+               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
+               return;
+       }
+
+       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());
+               for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
+               return;
+       }
+
+       lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
+       lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
+}
 
-       qDebug("Found WMA File Decoder binary:\n%s\n", wmaFileInfo.canonicalFilePath().toUtf8().constData());
+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};
 
-       if(wmaFileBin)
+       for(size_t k = 0; k < 4; k++)
        {
-               lamexp_register_tool(wmaFileInfo.fileName(), wmaFileBin);
+               qDebug("[TEST]");
+               switch(cpu[k])
+               {
+                       PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
+                       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!";
+               }
+               int n = 0;
+               for(int i = 0; i < INT_MAX; i++)
+               {
+                       if(!g_lamexp_tools[i].pcName && !g_lamexp_tools[i].pcHash && !g_lamexp_tools[i].uiVersion)
+                       {
+                               break;
+                       }
+                       if(g_lamexp_tools[i].uiCpuType & cpu[k])
+                       {
+                               qDebug("%02i -> %s", ++n, g_lamexp_tools[i].pcName);
+                       }
+               }
+               if(n != 25)
+               {
+                       qFatal("Tool count mismatch !!!");
+               }
+               qDebug("Done.\n");
        }
 }