OSDN Git Service

Tweaked the number of extractor threads. Also added a simple benchmark function ...
[lamexp/LameXP.git] / src / Thread_Initialization.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "Thread_Initialization.h"
24
25 #include "LockedFile.h"
26 #include "Tools.h"
27 #include "Tool_Abstract.h"
28
29 #include <QFileInfo>
30 #include <QCoreApplication>
31 #include <QProcess>
32 #include <QMap>
33 #include <QDir>
34 #include <QLibrary>
35 #include <QResource>
36 #include <QTextStream>
37 #include <QRunnable>
38 #include <QThreadPool>
39 #include <QMutex>
40 #include <QQueue>
41
42 /* helper macros */
43 #define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
44
45 /* constants */
46 static const double g_allowedExtractDelay = 12.0;
47 static const size_t BUFF_SIZE = 512;
48 static const size_t EXPECTED_TOOL_COUNT = 27;
49
50 /* benchmark */
51 #undef ENABLE_BENCHMARK
52
53 ////////////////////////////////////////////////////////////
54 // ExtractorTask class
55 ////////////////////////////////////////////////////////////
56
57 class ExtractorTask : public QRunnable
58 {
59 public:
60         ExtractorTask(QResource *const toolResource, const QDir &appDir, const QString &toolName, const QByteArray &toolHash, const unsigned int toolVersion, const QString &toolTag)
61         :
62                 m_appDir(appDir),
63                 m_toolName(toolName),
64                 m_toolHash(toolHash),
65                 m_toolVersion(toolVersion),
66                 m_toolTag(toolTag),
67                 m_toolResource(toolResource)
68         {
69                 /* Nothing to do */
70         }
71
72         ~ExtractorTask(void)
73         {
74                 delete m_toolResource;
75         }
76
77         static void clearFlags(void)
78         {
79                 QMutexLocker lock(&s_mutex);
80                 s_bExcept = false;
81                 s_bCustom = false;
82                 s_errMsg[0] = char(0);
83         }
84
85         static bool getExcept(void) { bool ret; QMutexLocker lock(&s_mutex); ret = s_bExcept; return ret; }
86         static bool getCustom(void) { bool ret; QMutexLocker lock(&s_mutex); ret = s_bCustom; return ret; }
87
88         static bool getErrMsg(char *buffer, const size_t buffSize)
89         {
90                 QMutexLocker lock(&s_mutex);
91                 if(s_errMsg[0])
92                 {
93                         strncpy_s(buffer, BUFF_SIZE, s_errMsg, _TRUNCATE);
94                         return true;
95                 }
96                 return false;
97         }
98
99 protected:
100         void run(void)
101         {
102                 try
103                 {
104                         if(!getExcept()) doExtract();
105                 }
106                 catch(const std::exception &e)
107                 {
108                         QMutexLocker lock(&s_mutex);
109                         if(!s_bExcept)
110                         {
111                                 s_bExcept = true;
112                                 strncpy_s(s_errMsg, BUFF_SIZE, e.what(), _TRUNCATE);
113                         }
114                         lock.unlock();
115                         qWarning("ExtractorTask exception error:\n%s\n\n", e.what());
116                 }
117                 catch(...)
118                 {
119                         QMutexLocker lock(&s_mutex);
120                         if(!s_bExcept)
121                         {
122                                 s_bExcept = true;
123                                 strncpy_s(s_errMsg, BUFF_SIZE, "Unknown exception error!", _TRUNCATE);
124                         }
125                         lock.unlock();
126                         qWarning("ExtractorTask encountered an unknown exception!");
127                 }
128         }
129
130         void doExtract(void)
131         {
132                 LockedFile *lockedFile = NULL;
133                 unsigned int version = m_toolVersion;
134
135                 QFileInfo toolFileInfo(m_toolName);
136                 const QString toolShortName = QString("%1.%2").arg(toolFileInfo.baseName().toLower(), toolFileInfo.suffix().toLower());
137
138                 QFileInfo customTool(QString("%1/tools/%2/%3").arg(m_appDir.canonicalPath(), QString::number(lamexp_version_build()), toolShortName));
139                 if(customTool.exists() && customTool.isFile())
140                 {
141                         qDebug("Setting up file: %s <- %s", toolShortName.toLatin1().constData(), m_appDir.relativeFilePath(customTool.canonicalFilePath()).toLatin1().constData());
142                         lockedFile = new LockedFile(customTool.canonicalFilePath()); version = UINT_MAX; s_bCustom = true;
143                 }
144                 else
145                 {
146                         qDebug("Extracting file: %s -> %s", m_toolName.toLatin1().constData(), toolShortName.toLatin1().constData());
147                         lockedFile = new LockedFile(m_toolResource, QString("%1/lxp_%2").arg(lamexp_temp_folder2(), toolShortName), m_toolHash);
148                 }
149
150                 if(lockedFile)
151                 {
152                         lamexp_register_tool(toolShortName, lockedFile, version, &m_toolTag);
153                 }
154         }
155
156 private:
157         QResource *const m_toolResource;
158         const QDir m_appDir;
159         const QString m_toolName;
160         const QByteArray m_toolHash;
161         const unsigned int m_toolVersion;
162         const QString m_toolTag;
163
164         static volatile bool s_bExcept;
165         static volatile bool s_bCustom;
166         static QMutex s_mutex;
167         static char s_errMsg[BUFF_SIZE];
168 };
169
170 QMutex ExtractorTask::s_mutex;
171 char ExtractorTask::s_errMsg[BUFF_SIZE] = {'\0'};
172 volatile bool ExtractorTask::s_bExcept = false;
173 volatile bool ExtractorTask::s_bCustom = false;
174
175 ////////////////////////////////////////////////////////////
176 // Constructor
177 ////////////////////////////////////////////////////////////
178
179 InitializationThread::InitializationThread(const lamexp_cpu_t *cpuFeatures)
180 {
181         m_bSuccess = false;
182         memset(&m_cpuFeatures, 0, sizeof(lamexp_cpu_t));
183         m_slowIndicator = false;
184         
185         if(cpuFeatures)
186         {
187                 memcpy(&m_cpuFeatures, cpuFeatures, sizeof(lamexp_cpu_t));
188         }
189 }
190
191 ////////////////////////////////////////////////////////////
192 // Thread Main
193 ////////////////////////////////////////////////////////////
194
195 #ifdef ENABLE_BENCHMARK
196 #define DO_INIT_FUNCT runBenchmark
197 void lamexp_clean_all_tools(void);
198 #else //ENABLE_BENCHMARK
199 #define DO_INIT_FUNCT doInit
200 #endif //ENABLE_BENCHMARK
201
202 void InitializationThread::run(void)
203 {
204         try
205         {
206                 DO_INIT_FUNCT();
207         }
208         catch(const std::exception &error)
209         {
210                 fflush(stdout); fflush(stderr);
211                 fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
212                 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
213         }
214         catch(...)
215         {
216                 fflush(stdout); fflush(stderr);
217                 fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
218                 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
219         }
220 }
221
222 double InitializationThread::doInit(const size_t threadCount)
223 {
224         m_bSuccess = false;
225         delay();
226
227         //CPU type selection
228         unsigned int cpuSupport = 0;
229         if(m_cpuFeatures.sse && m_cpuFeatures.sse2 && m_cpuFeatures.intel)
230         {
231                 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
232         }
233         else
234         {
235                 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
236         }
237
238         //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
239         if(cpuSupport & CPU_TYPE_X64_ALL)
240         {
241                 if(lamexp_detect_wine())
242                 {
243                         qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
244                         cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
245                 }
246         }
247
248         //Print selected CPU type
249         switch(cpuSupport)
250         {
251                 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
252                 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
253                 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
254                 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
255                 default: THROW("CPU support undefined!");
256         }
257
258         //Allocate queues
259         QQueue<QString> queueToolName;
260         QQueue<QString> queueChecksum;
261         QQueue<QString> queueVersInfo;
262         QQueue<unsigned int> queueVersions;
263         QQueue<unsigned int> queueCpuTypes;
264
265         //Init properties
266         for(int i = 0; true; i++)
267         {
268                 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash  || g_lamexp_tools[i].uiVersion))
269                 {
270                         break;
271                 }
272                 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
273                 {
274                         queueToolName.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcName));
275                         queueChecksum.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcHash));
276                         queueVersInfo.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcVersTag));
277                         queueCpuTypes.enqueue(g_lamexp_tools[i].uiCpuType);
278                         queueVersions.enqueue(g_lamexp_tools[i].uiVersion);
279                 }
280                 else
281                 {
282                         qFatal("Inconsistent checksum data detected. Take care!");
283                 }
284         }
285
286         QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
287
288         QThreadPool *pool = new QThreadPool();
289         pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, (m_cpuFeatures.count * 2U), EXPECTED_TOOL_COUNT));
290         
291         LockedFile::selfTest();
292         ExtractorTask::clearFlags();
293
294         const long long timeExtractStart = lamexp_perfcounter_value();
295         
296         //Extract all files
297         while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
298         {
299                 const QString toolName = queueToolName.dequeue();
300                 const QString checksum = queueChecksum.dequeue();
301                 const QString versInfo = queueVersInfo.dequeue();
302                 const unsigned int cpuType = queueCpuTypes.dequeue();
303                 const unsigned int version = queueVersions.dequeue();
304                         
305                 const QByteArray toolHash(checksum.toLatin1());
306                 if(toolHash.size() != 96)
307                 {
308                         qFatal("The checksum for \"%s\" has an invalid size!", QUTF8(toolName));
309                         return -1.0;
310                 }
311                         
312                 QResource *resource = new QResource(QString(":/tools/%1").arg(toolName));
313                 if(!(resource->isValid() && resource->data()))
314                 {
315                         LAMEXP_DELETE(resource);
316                         qFatal("The resource for \"%s\" could not be found!", QUTF8(toolName));
317                         return -1.0;
318                 }
319                         
320                 if(cpuType & cpuSupport)
321                 {
322                         pool->start(new ExtractorTask(resource, appDir, toolName, toolHash, version, versInfo));
323                         continue;
324                 }
325
326                 LAMEXP_DELETE(resource);
327         }
328
329         //Sanity Check
330         if(!(queueToolName.isEmpty() && queueChecksum.isEmpty() && queueVersInfo.isEmpty() && queueCpuTypes.isEmpty() && queueVersions.isEmpty()))
331         {
332                 qFatal("Checksum queues *not* empty fater verification completed. Take care!");
333         }
334
335         //Wait for extrator threads to finish
336         pool->waitForDone();
337         LAMEXP_DELETE(pool);
338
339         const long long timeExtractEnd = lamexp_perfcounter_value();
340
341         //Make sure all files were extracted correctly
342         if(ExtractorTask::getExcept())
343         {
344                 char errorMsg[BUFF_SIZE];
345                 if(ExtractorTask::getErrMsg(errorMsg, BUFF_SIZE))
346                 {
347                         qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
348                         return -1.0;
349                 }
350                 qFatal("At least one of the required tools could not be initialized!");
351                 return -1.0;
352         }
353
354         qDebug("All extracted.\n");
355
356         //Using any custom tools?
357         if(ExtractorTask::getCustom())
358         {
359                 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
360         }
361
362         //Check delay
363         const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(lamexp_perfcounter_frequ());
364         if(delayExtract > g_allowedExtractDelay)
365         {
366                 m_slowIndicator = true;
367                 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
368                 qWarning("Please report performance problems to your anti-virus developer !!!\n");
369         }
370         else
371         {
372                 qDebug("Extracting the tools took %.5f seconds (OK).\n", delayExtract);
373         }
374
375         //Register all translations
376         initTranslations();
377
378         //Look for AAC encoders
379         initNeroAac();
380         initFhgAac();
381         initQAac();
382
383         m_bSuccess = true;
384         delay();
385
386         return delayExtract;
387 }
388
389 void InitializationThread::runBenchmark(void)
390 {
391 #ifdef ENABLE_BENCHMARK
392         static const size_t nLoops = 5;
393         const size_t maxThreads = (5 * m_cpuFeatures.count);
394         QMap<size_t, double> results;
395
396         for(size_t c = 1; c <= maxThreads; c++)
397         {
398                 double delayAcc = 0.0;
399                 for(size_t i = 0; i < nLoops; i++)
400                 {
401                         delayAcc += doInit(c);
402                         lamexp_clean_all_tools();
403                 }
404                 results.insert(c, (delayAcc / double(nLoops)));
405         }
406
407         qWarning("\n----------------------------------------------");
408         qWarning("Benchmark Results:");
409         qWarning("----------------------------------------------");
410
411         double bestTime = DBL_MAX; size_t bestVal = 0;
412         QList<size_t> keys = results.keys();
413         for(QList<size_t>::ConstIterator iter = keys.begin(); iter != keys.end(); iter++)
414         {
415                 const double time = results.value((*iter), DBL_MAX);
416                 qWarning("%02u -> %7.4f", (*iter), time);
417                 if(time < bestTime)
418                 {
419                         bestTime = time;
420                         bestVal = (*iter);
421                 }
422         }
423
424         qWarning("----------------------------------------------");
425         qWarning("BEST: %u of %u (factor: %7.4f)", bestVal, m_cpuFeatures.count, (double(bestVal) / double(m_cpuFeatures.count)));
426         qWarning("----------------------------------------------\n");
427         
428         qFatal("Benchmark complete. Thanks and bye bye!");
429 #else //ENABLE_BENCHMARK
430         THROW("Sorry, the benchmark is *not* available in this build!");
431 #endif //ENABLE_BENCHMARK
432 }
433
434 ////////////////////////////////////////////////////////////
435 // PUBLIC FUNCTIONS
436 ////////////////////////////////////////////////////////////
437
438 void InitializationThread::delay(void)
439 {
440         __noop();
441 }
442
443 void InitializationThread::initTranslations(void)
444 {
445         //Search for language files
446         QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
447
448         //Make sure we found at least one translation
449         if(qmFiles.count() < 1)
450         {
451                 qFatal("Could not find any translation files!");
452                 return;
453         }
454
455         //Add all available translations
456         while(!qmFiles.isEmpty())
457         {
458                 QString langId, langName;
459                 unsigned int systemId = 0, country = 0;
460                 QString qmFile = qmFiles.takeFirst();
461                 
462                 QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
463                 if(langIdExp.indexIn(qmFile) >= 0)
464                 {
465                         langId = langIdExp.cap(1).toLower();
466                         QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
467                         if(langRes.isValid() && langRes.size() > 0)
468                         {
469                                 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
470                                 QTextStream stream(&data, QIODevice::ReadOnly);
471                                 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
472                                 while(!stream.atEnd())
473                                 {
474                                         QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
475                                         if(langInfo.count() == 3)
476                                         {
477                                                 systemId = langInfo.at(0).trimmed().toUInt();
478                                                 country  = langInfo.at(1).trimmed().toUInt();
479                                                 langName = langInfo.at(2).trimmed();
480                                                 break;
481                                         }
482                                 }
483                         }
484                 }
485
486                 if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
487                 {
488                         if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
489                         {
490                                 qDebug("Registering translation: %s = %s (%u) [%u]", QUTF8(qmFile), QUTF8(langName), systemId, country);
491                         }
492                         else
493                         {
494                                 qWarning("Failed to register: %s", qmFile.toLatin1().constData());
495                         }
496                 }
497         }
498
499         qDebug("All registered.\n");
500 }
501
502 void InitializationThread::initNeroAac(void)
503 {
504         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
505         
506         QFileInfo neroFileInfo[3];
507         neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
508         neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
509         neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
510         
511         bool neroFilesFound = true;
512         for(int i = 0; i < 3; i++)      { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
513
514         //Lock the Nero binaries
515         if(!neroFilesFound)
516         {
517                 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
518                 return;
519         }
520
521         qDebug("Found Nero AAC encoder binary:\n%s\n", QUTF8(neroFileInfo[0].canonicalFilePath()));
522
523         LockedFile *neroBin[3];
524         for(int i = 0; i < 3; i++) neroBin[i] = NULL;
525
526         try
527         {
528                 for(int i = 0; i < 3; i++)
529                 {
530                         neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
531                 }
532         }
533         catch(...)
534         {
535                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
536                 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
537                 return;
538         }
539
540         QProcess process;
541         lamexp_init_process(process, neroFileInfo[0].absolutePath());
542
543         process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
544
545         if(!process.waitForStarted())
546         {
547                 qWarning("Nero process failed to create!");
548                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
549                 process.kill();
550                 process.waitForFinished(-1);
551                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
552                 return;
553         }
554
555         unsigned int neroVersion = 0;
556
557         while(process.state() != QProcess::NotRunning)
558         {
559                 if(!process.waitForReadyRead())
560                 {
561                         if(process.state() == QProcess::Running)
562                         {
563                                 qWarning("Nero process time out -> killing!");
564                                 process.kill();
565                                 process.waitForFinished(-1);
566                                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
567                                 return;
568                         }
569                 }
570
571                 while(process.canReadLine())
572                 {
573                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
574                         QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
575                         int index1 = tokens.indexOf("Package");
576                         int index2 = tokens.indexOf("version:");
577                         if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
578                         {
579                                 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
580                                 if(versionTokens.count() == 4)
581                                 {
582                                         neroVersion = 0;
583                                         neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
584                                         neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
585                                         neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
586                                         neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
587                                 }
588                         }
589                 }
590         }
591
592         if(!(neroVersion > 0))
593         {
594                 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
595                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
596                 return;
597         }
598         
599         for(int i = 0; i < 3; i++)
600         {
601                 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
602         }
603 }
604
605 void InitializationThread::initFhgAac(void)
606 {
607         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
608         
609         QFileInfo fhgFileInfo[5];
610         fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
611         fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
612         fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
613         fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
614         fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
615         
616         bool fhgFilesFound = true;
617         for(int i = 0; i < 5; i++)      { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
618
619         //Lock the FhgAacEnc binaries
620         if(!fhgFilesFound)
621         {
622                 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
623                 return;
624         }
625
626         qDebug("Found FhgAacEnc cli_exe:\n%s\n", QUTF8(fhgFileInfo[0].canonicalFilePath()));
627         qDebug("Found FhgAacEnc enc_dll:\n%s\n", QUTF8(fhgFileInfo[1].canonicalFilePath()));
628
629         LockedFile *fhgBin[5];
630         for(int i = 0; i < 5; i++) fhgBin[i] = NULL;
631
632         try
633         {
634                 for(int i = 0; i < 5; i++)
635                 {
636                         fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
637                 }
638         }
639         catch(...)
640         {
641                 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
642                 qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
643                 return;
644         }
645
646         QProcess process;
647         lamexp_init_process(process, fhgFileInfo[0].absolutePath());
648
649         process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
650
651         if(!process.waitForStarted())
652         {
653                 qWarning("FhgAacEnc process failed to create!");
654                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
655                 process.kill();
656                 process.waitForFinished(-1);
657                 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
658                 return;
659         }
660
661         QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
662         unsigned int fhgVersion = 0;
663
664         while(process.state() != QProcess::NotRunning)
665         {
666                 process.waitForReadyRead();
667                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
668                 {
669                         qWarning("FhgAacEnc process time out -> killing!");
670                         process.kill();
671                         process.waitForFinished(-1);
672                         for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
673                         return;
674                 }
675                 while(process.bytesAvailable() > 0)
676                 {
677                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
678                         if(fhgAacEncSig.lastIndexIn(line) >= 0)
679                         {
680                                 bool ok = false;
681                                 unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
682                                 if(ok) fhgVersion = temp;
683                         }
684                 }
685         }
686
687         if(!(fhgVersion > 0))
688         {
689                 qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
690                 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
691                 return;
692         }
693         else if(fhgVersion < lamexp_toolver_fhgaacenc())
694         {
695                 qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", lamexp_version2string("????-??-??", fhgVersion, "N/A").toLatin1().constData());
696                 qWarning("Minimum required FhgAacEnc version currently is: %s\n", lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A").toLatin1().constData());
697                 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
698                 return;
699         }
700         
701         for(int i = 0; i < 5; i++)
702         {
703                 lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
704         }
705 }
706
707 void InitializationThread::initQAac(void)
708 {
709         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
710
711         QFileInfo qaacFileInfo[2];
712         qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
713         qaacFileInfo[1] = QFileInfo(QString("%1/libsoxrate.dll").arg(appPath));
714         
715         bool qaacFilesFound = true;
716         for(int i = 0; i < 2; i++)      { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
717
718         //Lock the QAAC binaries
719         if(!qaacFilesFound)
720         {
721                 qDebug("QAAC binaries not found -> QAAC support will be disabled!\n");
722                 return;
723         }
724
725         qDebug("Found QAAC encoder:\n%s\n", QUTF8(qaacFileInfo[0].canonicalFilePath()));
726
727         LockedFile *qaacBin[2];
728         for(int i = 0; i < 2; i++) qaacBin[i] = NULL;
729
730         try
731         {
732                 for(int i = 0; i < 2; i++)
733                 {
734                         qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
735                 }
736         }
737         catch(...)
738         {
739                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
740                 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
741                 return;
742         }
743
744         QProcess process;
745         lamexp_init_process(process, qaacFileInfo[0].absolutePath());
746
747         process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
748
749         if(!process.waitForStarted())
750         {
751                 qWarning("QAAC process failed to create!");
752                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
753                 process.kill();
754                 process.waitForFinished(-1);
755                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
756                 return;
757         }
758
759         QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
760         QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
761         unsigned int qaacVersion = 0;
762         unsigned int coreVersion = 0;
763
764         while(process.state() != QProcess::NotRunning)
765         {
766                 process.waitForReadyRead();
767                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
768                 {
769                         qWarning("QAAC process time out -> killing!");
770                         process.kill();
771                         process.waitForFinished(-1);
772                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
773                         return;
774                 }
775                 while(process.bytesAvailable() > 0)
776                 {
777                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
778                         if(qaacEncSig.lastIndexIn(line) >= 0)
779                         {
780                                 unsigned int tmp[3] = {0, 0, 0};
781                                 bool ok[3] = {false, false, false};
782                                 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
783                                 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
784                                 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
785                                 if(ok[0] && ok[1] && ok[2])
786                                 {
787                                         qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
788                                 }
789                         }
790                         if(coreEncSig.lastIndexIn(line) >= 0)
791                         {
792                                 unsigned int tmp[4] = {0, 0, 0, 0};
793                                 bool ok[4] = {false, false, false, false};
794                                 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
795                                 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
796                                 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
797                                 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
798                                 if(ok[0] && ok[1] && ok[2] && ok[3])
799                                 {
800                                         coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
801                                 }
802                         }
803                 }
804         }
805
806         //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
807
808         if(!(qaacVersion > 0))
809         {
810                 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
811                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
812                 return;
813         }
814         else if(qaacVersion < lamexp_toolver_qaacenc())
815         {
816                 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
817                 qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
818                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
819                 return;
820         }
821
822         if(!(coreVersion > 0))
823         {
824                 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
825                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
826                 return;
827         }
828         else if(coreVersion < lamexp_toolver_coreaudio())
829         {
830                 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
831                 qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
832                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
833                 return;
834         }
835
836         lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
837         lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
838 }
839
840 void InitializationThread::selfTest(void)
841 {
842         const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
843
844         LockedFile::selfTest();
845
846         for(size_t k = 0; k < 4; k++)
847         {
848                 qDebug("[TEST]");
849                 switch(cpu[k])
850                 {
851                         PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
852                         PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
853                         PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
854                         PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
855                         default: THROW("CPU support undefined!");
856                 }
857                 unsigned int n = 0;
858                 for(int i = 0; true; i++)
859                 {
860                         if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash  || g_lamexp_tools[i].uiVersion))
861                         {
862                                 break;
863                         }
864                         else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
865                         {
866                                 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
867                                 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
868                                 if(g_lamexp_tools[i].uiCpuType & cpu[k])
869                                 {
870                                         qDebug("%02i -> %s", ++n, QUTF8(toolName));
871                                         QFile resource(QString(":/tools/%1").arg(toolName));
872                                         if(!resource.open(QIODevice::ReadOnly))
873                                         {
874                                                 qFatal("The resource for \"%s\" could not be opened!", QUTF8(toolName));
875                                                 break;
876                                         }
877                                         QByteArray hash = LockedFile::fileHash(resource);
878                                         if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
879                                         {
880                                                 qFatal("Hash check for tool \"%s\" has failed!", QUTF8(toolName));
881                                                 break;
882                                         }
883                                         resource.close();
884                                 }
885                         }
886                         else
887                         {
888                                 qFatal("Inconsistent checksum data detected. Take care!");
889                         }
890                 }
891                 if(n != EXPECTED_TOOL_COUNT)
892                 {
893                         qFatal("Tool count mismatch for CPU type %u !!!", cpu[4]);
894                 }
895                 qDebug("Done.\n");
896         }
897 }
898
899 ////////////////////////////////////////////////////////////
900 // EVENTS
901 ////////////////////////////////////////////////////////////
902
903 /*NONE*/