OSDN Git Service

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