OSDN Git Service

Make the initialization time measurement work again.
[lamexp/LameXP.git] / src / Thread_Initialization.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 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 //Internal
26 #define LAMEXP_INC_TOOLS 1
27 #include "Tools.h"
28 #include "LockedFile.h"
29 #include "Tool_Abstract.h"
30
31 //MUtils
32 #include <MUtils/Global.h>
33 #include <MUtils/OSSupport.h>
34 #include <MUtils/Translation.h>
35 #include <MUtils/Exception.h>
36
37 //Qt
38 #include <QFileInfo>
39 #include <QCoreApplication>
40 #include <QProcess>
41 #include <QMap>
42 #include <QDir>
43 #include <QResource>
44 #include <QTextStream>
45 #include <QRunnable>
46 #include <QThreadPool>
47 #include <QMutex>
48 #include <QQueue>
49 #include <QElapsedTimer>
50
51 /* helper macros */
52 #define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
53
54 /* constants */
55 static const double g_allowedExtractDelay = 12.0;
56 static const size_t BUFF_SIZE = 512;
57 static const size_t EXPECTED_TOOL_COUNT = 28;
58
59 /* number of CPU cores -> number of threads */
60 static unsigned int cores2threads(const unsigned int cores)
61 {
62         static const size_t LUT_LEN = 4;
63         
64         static const struct
65         {
66                 const unsigned int upperBound;
67                 const double coeffs[4];
68         }
69         LUT[LUT_LEN] =
70         {
71                 {  4, { -0.052695810565,  0.158087431694, 4.982841530055, -1.088233151184 } },
72                 {  8, {  0.042431693989, -0.983442622951, 9.548961748634, -7.176393442623 } },
73                 { 12, { -0.006277322404,  0.185573770492, 0.196830601093, 17.762622950820 } },
74                 { 32, {  0.000673497268, -0.064655737705, 3.199584699454,  5.751606557377 } }
75         };
76
77         size_t index = 0;
78         while((cores > LUT[index].upperBound) && (index < (LUT_LEN-1))) index++;
79
80         const double x = qBound(1.0, double(cores), double(LUT[LUT_LEN-1].upperBound));
81         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];
82
83         return qRound(abs(y));
84 }
85
86 ////////////////////////////////////////////////////////////
87 // ExtractorTask class
88 ////////////////////////////////////////////////////////////
89
90 class ExtractorTask : public QRunnable
91 {
92 public:
93         ExtractorTask(QResource *const toolResource, const QDir &appDir, const QString &toolName, const QByteArray &toolHash, const unsigned int toolVersion, const QString &toolTag)
94         :
95                 m_appDir(appDir),
96                 m_toolName(toolName),
97                 m_toolHash(toolHash),
98                 m_toolVersion(toolVersion),
99                 m_toolTag(toolTag),
100                 m_toolResource(toolResource)
101         {
102                 /* Nothing to do */
103         }
104
105         ~ExtractorTask(void)
106         {
107                 delete m_toolResource;
108         }
109
110         static void clearFlags(void)
111         {
112                 QMutexLocker lock(&s_mutex);
113                 s_bExcept = false;
114                 s_bCustom = false;
115                 s_errMsg[0] = char(0);
116         }
117
118         static bool getExcept(void) { bool ret; QMutexLocker lock(&s_mutex); ret = s_bExcept; return ret; }
119         static bool getCustom(void) { bool ret; QMutexLocker lock(&s_mutex); ret = s_bCustom; return ret; }
120
121         static bool getErrMsg(char *buffer, const size_t buffSize)
122         {
123                 QMutexLocker lock(&s_mutex);
124                 if(s_errMsg[0])
125                 {
126                         strncpy_s(buffer, BUFF_SIZE, s_errMsg, _TRUNCATE);
127                         return true;
128                 }
129                 return false;
130         }
131
132 protected:
133         void run(void)
134         {
135                 try
136                 {
137                         if(!getExcept()) doExtract();
138                 }
139                 catch(const std::exception &e)
140                 {
141                         QMutexLocker lock(&s_mutex);
142                         if(!s_bExcept)
143                         {
144                                 s_bExcept = true;
145                                 strncpy_s(s_errMsg, BUFF_SIZE, e.what(), _TRUNCATE);
146                         }
147                         lock.unlock();
148                         qWarning("ExtractorTask exception error:\n%s\n\n", e.what());
149                 }
150                 catch(...)
151                 {
152                         QMutexLocker lock(&s_mutex);
153                         if(!s_bExcept)
154                         {
155                                 s_bExcept = true;
156                                 strncpy_s(s_errMsg, BUFF_SIZE, "Unknown exception error!", _TRUNCATE);
157                         }
158                         lock.unlock();
159                         qWarning("ExtractorTask encountered an unknown exception!");
160                 }
161         }
162
163         void doExtract(void)
164         {
165                 LockedFile *lockedFile = NULL;
166                 unsigned int version = m_toolVersion;
167
168                 QFileInfo toolFileInfo(m_toolName);
169                 const QString toolShortName = QString("%1.%2").arg(toolFileInfo.baseName().toLower(), toolFileInfo.suffix().toLower());
170
171                 QFileInfo customTool(QString("%1/tools/%2/%3").arg(m_appDir.canonicalPath(), QString::number(lamexp_version_build()), toolShortName));
172                 if(customTool.exists() && customTool.isFile())
173                 {
174                         qDebug("Setting up file: %s <- %s", toolShortName.toLatin1().constData(), m_appDir.relativeFilePath(customTool.canonicalFilePath()).toLatin1().constData());
175                         lockedFile = new LockedFile(customTool.canonicalFilePath()); version = UINT_MAX; s_bCustom = true;
176                 }
177                 else
178                 {
179                         qDebug("Extracting file: %s -> %s", m_toolName.toLatin1().constData(), toolShortName.toLatin1().constData());
180                         lockedFile = new LockedFile(m_toolResource, QString("%1/lxp_%2").arg(MUtils::temp_folder(), toolShortName), m_toolHash);
181                 }
182
183                 if(lockedFile)
184                 {
185                         lamexp_tools_register(toolShortName, lockedFile, version, m_toolTag);
186                 }
187         }
188
189 private:
190         QResource *const m_toolResource;
191         const QDir m_appDir;
192         const QString m_toolName;
193         const QByteArray m_toolHash;
194         const unsigned int m_toolVersion;
195         const QString m_toolTag;
196
197         static volatile bool s_bExcept;
198         static volatile bool s_bCustom;
199         static QMutex s_mutex;
200         static char s_errMsg[BUFF_SIZE];
201 };
202
203 QMutex ExtractorTask::s_mutex;
204 char ExtractorTask::s_errMsg[BUFF_SIZE] = {'\0'};
205 volatile bool ExtractorTask::s_bExcept = false;
206 volatile bool ExtractorTask::s_bCustom = false;
207
208 ////////////////////////////////////////////////////////////
209 // Constructor
210 ////////////////////////////////////////////////////////////
211
212 InitializationThread::InitializationThread(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures)
213 :
214         m_bSuccess(false),
215         m_slowIndicator(false)
216 {
217
218         memcpy(&m_cpuFeatures, &cpuFeatures, sizeof(MUtils::CPUFetaures::cpu_info_t));
219 }
220
221 ////////////////////////////////////////////////////////////
222 // Thread Main
223 ////////////////////////////////////////////////////////////
224
225 void InitializationThread::run(void)
226 {
227         try
228         {
229                 doInit();
230         }
231         catch(const std::exception &error)
232         {
233                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
234                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
235         }
236         catch(...)
237         {
238                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
239                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
240         }
241 }
242
243 double InitializationThread::doInit(const size_t threadCount)
244 {
245         m_bSuccess = false;
246         delay();
247
248         //CPU type selection
249         unsigned int cpuSupport = 0;
250         if((m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE) && (m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE2) && m_cpuFeatures.intel)
251         {
252                 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
253         }
254         else
255         {
256                 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
257         }
258
259         //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
260         if(cpuSupport & CPU_TYPE_X64_ALL)
261         {
262                 if(MUtils::OS::running_on_wine())
263                 {
264                         qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
265                         cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
266                 }
267         }
268
269         //Print selected CPU type
270         switch(cpuSupport)
271         {
272                 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
273                 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
274                 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
275                 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
276                 default: MUTILS_THROW("CPU support undefined!");
277         }
278
279         //Allocate queues
280         QQueue<QString> queueToolName;
281         QQueue<QString> queueChecksum;
282         QQueue<QString> queueVersInfo;
283         QQueue<unsigned int> queueVersions;
284         QQueue<unsigned int> queueCpuTypes;
285
286         //Init properties
287         for(int i = 0; true; i++)
288         {
289                 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash  || g_lamexp_tools[i].uiVersion))
290                 {
291                         break;
292                 }
293                 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
294                 {
295                         queueToolName.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcName));
296                         queueChecksum.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcHash));
297                         queueVersInfo.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcVersTag));
298                         queueCpuTypes.enqueue(g_lamexp_tools[i].uiCpuType);
299                         queueVersions.enqueue(g_lamexp_tools[i].uiVersion);
300                 }
301                 else
302                 {
303                         qFatal("Inconsistent checksum data detected. Take care!");
304                 }
305         }
306
307         QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
308
309         QThreadPool *pool = new QThreadPool();
310         pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, cores2threads(m_cpuFeatures.count), EXPECTED_TOOL_COUNT));
311         /* qWarning("Using %u threads for extraction.", pool->maxThreadCount()); */
312
313         LockedFile::selfTest();
314         ExtractorTask::clearFlags();
315
316         //Start the timer
317         QElapsedTimer timeExtractStart;
318         timeExtractStart.start();
319         
320         //Extract all files
321         while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
322         {
323                 const QString toolName = queueToolName.dequeue();
324                 const QString checksum = queueChecksum.dequeue();
325                 const QString versInfo = queueVersInfo.dequeue();
326                 const unsigned int cpuType = queueCpuTypes.dequeue();
327                 const unsigned int version = queueVersions.dequeue();
328                         
329                 const QByteArray toolHash(checksum.toLatin1());
330                 if(toolHash.size() != 96)
331                 {
332                         qFatal("The checksum for \"%s\" has an invalid size!", MUTILS_UTF8(toolName));
333                         return -1.0;
334                 }
335                         
336                 QResource *resource = new QResource(QString(":/tools/%1").arg(toolName));
337                 if(!(resource->isValid() && resource->data()))
338                 {
339                         MUTILS_DELETE(resource);
340                         qFatal("The resource for \"%s\" could not be found!", MUTILS_UTF8(toolName));
341                         return -1.0;
342                 }
343                         
344                 if(cpuType & cpuSupport)
345                 {
346                         pool->start(new ExtractorTask(resource, appDir, toolName, toolHash, version, versInfo));
347                         continue;
348                 }
349
350                 MUTILS_DELETE(resource);
351         }
352
353         //Sanity Check
354         if(!(queueToolName.isEmpty() && queueChecksum.isEmpty() && queueVersInfo.isEmpty() && queueCpuTypes.isEmpty() && queueVersions.isEmpty()))
355         {
356                 qFatal("Checksum queues *not* empty fater verification completed. Take care!");
357         }
358
359         //Wait for extrator threads to finish
360         pool->waitForDone();
361         MUTILS_DELETE(pool);
362
363         //Performance measure
364         const double delayExtract = double(timeExtractStart.elapsed()) / 1000.0;
365         timeExtractStart.invalidate();
366
367         //Make sure all files were extracted correctly
368         if(ExtractorTask::getExcept())
369         {
370                 char errorMsg[BUFF_SIZE];
371                 if(ExtractorTask::getErrMsg(errorMsg, BUFF_SIZE))
372                 {
373                         qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
374                         return -1.0;
375                 }
376                 qFatal("At least one of the required tools could not be initialized!");
377                 return -1.0;
378         }
379
380         qDebug("All extracted.\n");
381
382         //Using any custom tools?
383         if(ExtractorTask::getCustom())
384         {
385                 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
386         }
387
388         //Check delay
389         if(delayExtract > g_allowedExtractDelay)
390         {
391                 m_slowIndicator = true;
392                 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
393                 qWarning("Please report performance problems to your anti-virus developer !!!\n");
394         }
395         else
396         {
397                 qDebug("Extracting the tools took %.3f seconds (OK).\n", delayExtract);
398         }
399
400         //Register all translations
401         initTranslations();
402
403         //Look for AAC encoders
404         initNeroAac();
405         initFhgAac();
406         initQAac();
407
408         m_bSuccess = true;
409         delay();
410
411         return delayExtract;
412 }
413
414 ////////////////////////////////////////////////////////////
415 // PUBLIC FUNCTIONS
416 ////////////////////////////////////////////////////////////
417
418 void InitializationThread::delay(void)
419 {
420         MUtils::OS::sleep_ms(333);
421 }
422
423 void InitializationThread::initTranslations(void)
424 {
425         //Search for language files
426         const QDir qmDirectory(":/localization");
427         const QStringList qmFiles = qmDirectory.entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
428
429         //Make sure we found at least one translation
430         if(qmFiles.count() < 1)
431         {
432                 qFatal("Could not find any translation files!");
433                 return;
434         }
435
436         //Initialize variables
437         const QString langResTemplate(":/localization/%1.txt");
438         QRegExp langIdExp("^LameXP_(\\w\\w)\\.qm$", Qt::CaseInsensitive);
439
440         //Add all available translations
441         for(QStringList::ConstIterator iter = qmFiles.constBegin(); iter != qmFiles.constEnd(); iter++)
442         {
443                 const QString langFile = qmDirectory.absoluteFilePath(*iter);
444                 QString langId, langName;
445                 unsigned int systemId = 0, country = 0;
446                 
447                 if(QFileInfo(langFile).isFile() && (langIdExp.indexIn(*iter) >= 0))
448                 {
449                         langId = langIdExp.cap(1).toLower();
450                         QResource langRes = QResource(langResTemplate.arg(*iter));
451                         if(langRes.isValid() && langRes.size() > 0)
452                         {
453                                 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
454                                 QTextStream stream(&data, QIODevice::ReadOnly);
455                                 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
456
457                                 while(!(stream.atEnd() || (stream.status() != QTextStream::Ok)))
458                                 {
459                                         QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
460                                         if(langInfo.count() >= 3)
461                                         {
462                                                 systemId = langInfo.at(0).trimmed().toUInt();
463                                                 country  = langInfo.at(1).trimmed().toUInt();
464                                                 langName = langInfo.at(2).trimmed();
465                                                 break;
466                                         }
467                                 }
468                         }
469                 }
470
471                 if(!(langId.isEmpty() || langName.isEmpty() || (systemId == 0)))
472                 {
473                         if(MUtils::Translation::insert(langId, langFile, langName, systemId, country))
474                         {
475                                 qDebug("Registering translation: %s = %s (%u) [%u]", MUTILS_UTF8(*iter), MUTILS_UTF8(langName), systemId, country);
476                         }
477                         else
478                         {
479                                 qWarning("Failed to register: %s", langFile.toLatin1().constData());
480                         }
481                 }
482         }
483
484         qDebug("All registered.\n");
485 }
486
487 void InitializationThread::initNeroAac(void)
488 {
489         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
490         
491         QFileInfo neroFileInfo[3];
492         neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
493         neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
494         neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
495         
496         bool neroFilesFound = true;
497         for(int i = 0; i < 3; i++)      { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
498
499         if(!neroFilesFound)
500         {
501                 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
502                 return;
503         }
504
505         for(int i = 0; i < 3; i++)
506         {
507                 if(!MUtils::OS::is_executable_file(neroFileInfo[i].canonicalFilePath()))
508                 {
509                         qDebug("%s executbale is invalid -> AAC encoding support will be disabled!\n", MUTILS_UTF8(neroFileInfo[i].fileName()));
510                         return;
511                 }
512         }
513
514         qDebug("Found Nero AAC encoder binary:\n%s\n", MUTILS_UTF8(neroFileInfo[0].canonicalFilePath()));
515
516         //Lock the Nero binaries
517         LockedFile *neroBin[3];
518         for(int i = 0; i < 3; i++) neroBin[i] = NULL;
519
520         try
521         {
522                 for(int i = 0; i < 3; i++)
523                 {
524                         neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
525                 }
526         }
527         catch(...)
528         {
529                 for(int i = 0; i < 3; i++) MUTILS_DELETE(neroBin[i]);
530                 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
531                 return;
532         }
533
534         QProcess process;
535         MUtils::init_process(process, neroFileInfo[0].absolutePath());
536
537         process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
538
539         if(!process.waitForStarted())
540         {
541                 qWarning("Nero process failed to create!");
542                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
543                 process.kill();
544                 process.waitForFinished(-1);
545                 for(int i = 0; i < 3; i++) MUTILS_DELETE(neroBin[i]);
546                 return;
547         }
548
549         unsigned int neroVersion = 0;
550
551         while(process.state() != QProcess::NotRunning)
552         {
553                 if(!process.waitForReadyRead())
554                 {
555                         if(process.state() == QProcess::Running)
556                         {
557                                 qWarning("Nero process time out -> killing!");
558                                 process.kill();
559                                 process.waitForFinished(-1);
560                                 for(int i = 0; i < 3; i++) MUTILS_DELETE(neroBin[i]);
561                                 return;
562                         }
563                 }
564
565                 while(process.canReadLine())
566                 {
567                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
568                         QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
569                         int index1 = tokens.indexOf("Package");
570                         int index2 = tokens.indexOf("version:");
571                         if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
572                         {
573                                 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
574                                 if(versionTokens.count() == 4)
575                                 {
576                                         neroVersion = 0;
577                                         neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
578                                         neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
579                                         neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
580                                         neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
581                                 }
582                         }
583                 }
584         }
585
586         if(!(neroVersion > 0))
587         {
588                 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
589                 for(int i = 0; i < 3; i++) MUTILS_DELETE(neroBin[i]);
590                 return;
591         }
592         
593         for(int i = 0; i < 3; i++)
594         {
595                 lamexp_tools_register(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
596         }
597 }
598
599 void InitializationThread::initFhgAac(void)
600 {
601         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
602         
603         QFileInfo fhgFileInfo[5];
604         fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
605         fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
606         fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
607         fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
608         fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
609         
610         bool fhgFilesFound = true;
611         for(int i = 0; i < 5; i++)      { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
612
613         if(!fhgFilesFound)
614         {
615                 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
616                 return;
617         }
618
619         if(!MUtils::OS::is_executable_file(fhgFileInfo[0].canonicalFilePath()))
620         {
621                 qDebug("FhgAacEnc executbale is invalid -> FhgAacEnc support will be disabled!\n");
622                 return;
623         }
624
625         qDebug("Found FhgAacEnc cli_exe:\n%s\n", MUTILS_UTF8(fhgFileInfo[0].canonicalFilePath()));
626         qDebug("Found FhgAacEnc enc_dll:\n%s\n", MUTILS_UTF8(fhgFileInfo[1].canonicalFilePath()));
627
628         //Lock the FhgAacEnc binaries
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++) MUTILS_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         MUtils::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++) MUTILS_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++) MUTILS_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++) MUTILS_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++) MUTILS_DELETE(fhgBin[i]);
698                 return;
699         }
700         
701         for(int i = 0; i < 5; i++)
702         {
703                 lamexp_tools_register(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[4];
712         qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
713         qaacFileInfo[1] = QFileInfo(QString("%1/libsoxr.dll").arg(appPath));
714         qaacFileInfo[2] = QFileInfo(QString("%1/libsoxconvolver.dll").arg(appPath));
715         qaacFileInfo[3] = QFileInfo(QString("%1/libgcc_s_sjlj-1.dll").arg(appPath));
716         
717         bool qaacFilesFound = true;
718         for(int i = 0; i < 4; i++)      { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
719
720         if(!qaacFilesFound)
721         {
722                 qDebug("QAAC binary or companion DLL's not found -> QAAC support will be disabled!\n");
723                 return;
724         }
725
726         if(!MUtils::OS::is_executable_file(qaacFileInfo[0].canonicalFilePath()))
727         {
728                 qDebug("QAAC executbale is invalid -> QAAC support will be disabled!\n");
729                 return;
730         }
731
732         qDebug("Found QAAC encoder:\n%s\n", MUTILS_UTF8(qaacFileInfo[0].canonicalFilePath()));
733
734         //Lock the required QAAC binaries
735         LockedFile *qaacBin[4];
736         for(int i = 0; i < 4; i++) qaacBin[i] = NULL;
737
738         try
739         {
740                 for(int i = 0; i < 4; i++)
741                 {
742                         qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
743                 }
744         }
745         catch(...)
746         {
747                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
748                 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
749                 return;
750         }
751
752         QProcess process;
753         MUtils::init_process(process, qaacFileInfo[0].absolutePath());
754
755         process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
756
757         if(!process.waitForStarted())
758         {
759                 qWarning("QAAC process failed to create!");
760                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
761                 process.kill();
762                 process.waitForFinished(-1);
763                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
764                 return;
765         }
766
767         QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
768         QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
769         QRegExp soxrEncSig("libsoxr-\\d\\.\\d\\.\\d", Qt::CaseInsensitive);
770         QRegExp soxcEncSig("libsoxconvolver \\d\\.\\d\\.\\d", Qt::CaseInsensitive);
771
772         unsigned int qaacVersion = 0;
773         unsigned int coreVersion = 0;
774         bool soxrFound = false;
775         bool soxcFound = false;
776
777         while(process.state() != QProcess::NotRunning)
778         {
779                 process.waitForReadyRead();
780                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
781                 {
782                         qWarning("QAAC process time out -> killing!");
783                         process.kill();
784                         process.waitForFinished(-1);
785                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
786                         return;
787                 }
788                 while(process.bytesAvailable() > 0)
789                 {
790                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
791                         if(qaacEncSig.lastIndexIn(line) >= 0)
792                         {
793                                 unsigned int tmp[3] = {0, 0, 0};
794                                 bool ok[3] = {false, false, false};
795                                 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
796                                 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
797                                 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
798                                 if(ok[0] && ok[1] && ok[2])
799                                 {
800                                         qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
801                                 }
802                         }
803                         if(coreEncSig.lastIndexIn(line) >= 0)
804                         {
805                                 unsigned int tmp[4] = {0, 0, 0, 0};
806                                 bool ok[4] = {false, false, false, false};
807                                 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
808                                 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
809                                 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
810                                 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
811                                 if(ok[0] && ok[1] && ok[2] && ok[3])
812                                 {
813                                         coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
814                                 }
815                         }
816                         if(soxcEncSig.lastIndexIn(line) >= 0) { soxcFound = true; }
817                         if(soxrEncSig.lastIndexIn(line) >= 0) { soxrFound = true; }
818                 }
819         }
820
821         //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
822
823         if(!(qaacVersion > 0))
824         {
825                 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
826                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
827                 return;
828         }
829         else if(qaacVersion < lamexp_toolver_qaacenc())
830         {
831                 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
832                 qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
833                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
834                 return;
835         }
836
837         if(!(coreVersion > 0))
838         {
839                 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
840                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
841                 return;
842         }
843         else if(coreVersion < lamexp_toolver_coreaudio())
844         {
845                 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
846                 qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
847                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
848                 return;
849         }
850
851         if(!(soxrFound && soxcFound))
852         {
853                 qWarning("libsoxr and/or libsoxconvolver not available -> QAAC support will be disabled!\n");
854                 return;
855         }
856
857         lamexp_tools_register(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
858         lamexp_tools_register(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
859         lamexp_tools_register(qaacFileInfo[2].fileName(), qaacBin[2], qaacVersion);
860         lamexp_tools_register(qaacFileInfo[3].fileName(), qaacBin[3], qaacVersion);
861 }
862
863 void InitializationThread::selfTest(void)
864 {
865         const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
866
867         LockedFile::selfTest();
868
869         for(size_t k = 0; k < 4; k++)
870         {
871                 qDebug("[TEST]");
872                 switch(cpu[k])
873                 {
874                         PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
875                         PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
876                         PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
877                         PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
878                         default: MUTILS_THROW("CPU support undefined!");
879                 }
880                 unsigned int n = 0;
881                 for(int i = 0; true; i++)
882                 {
883                         if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash  || g_lamexp_tools[i].uiVersion))
884                         {
885                                 break;
886                         }
887                         else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
888                         {
889                                 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
890                                 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
891                                 if(g_lamexp_tools[i].uiCpuType & cpu[k])
892                                 {
893                                         qDebug("%02i -> %s", ++n, MUTILS_UTF8(toolName));
894                                         QFile resource(QString(":/tools/%1").arg(toolName));
895                                         if(!resource.open(QIODevice::ReadOnly))
896                                         {
897                                                 qFatal("The resource for \"%s\" could not be opened!", MUTILS_UTF8(toolName));
898                                                 break;
899                                         }
900                                         QByteArray hash = LockedFile::fileHash(resource);
901                                         if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
902                                         {
903                                                 qFatal("Hash check for tool \"%s\" has failed!", MUTILS_UTF8(toolName));
904                                                 break;
905                                         }
906                                         resource.close();
907                                 }
908                         }
909                         else
910                         {
911                                 qFatal("Inconsistent checksum data detected. Take care!");
912                         }
913                 }
914                 if(n != EXPECTED_TOOL_COUNT)
915                 {
916                         qFatal("Tool count mismatch for CPU type %u !!!", cpu[k]);
917                 }
918                 qDebug("Done.\n");
919         }
920 }
921
922 ////////////////////////////////////////////////////////////
923 // EVENTS
924 ////////////////////////////////////////////////////////////
925
926 /*NONE*/