OSDN Git Service

b2021303661a2c6bc2ccc75a0a1115187967fd94
[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 #include "LockedFile.h"
27 #include "Tools.h"
28 #include "Tool_Abstract.h"
29
30 //MUtils
31 #include <MUtils/Global.h>
32 #include <MUtils/OSSupport.h>
33 #include <MUtils/Exception.h>
34
35 //Qt
36 #include <QFileInfo>
37 #include <QCoreApplication>
38 #include <QProcess>
39 #include <QMap>
40 #include <QDir>
41 #include <QResource>
42 #include <QTextStream>
43 #include <QRunnable>
44 #include <QThreadPool>
45 #include <QMutex>
46 #include <QQueue>
47
48 /* helper macros */
49 #define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
50
51 /* constants */
52 static const double g_allowedExtractDelay = 12.0;
53 static const size_t BUFF_SIZE = 512;
54 static const size_t EXPECTED_TOOL_COUNT = 28;
55
56 /* benchmark */
57 #undef ENABLE_BENCHMARK
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_register_tool(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 #ifdef ENABLE_BENCHMARK
226 #define DO_INIT_FUNCT runBenchmark
227 #else //ENABLE_BENCHMARK
228 #define DO_INIT_FUNCT doInit
229 #endif //ENABLE_BENCHMARK
230
231 void InitializationThread::run(void)
232 {
233         try
234         {
235                 DO_INIT_FUNCT();
236         }
237         catch(const std::exception &error)
238         {
239                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
240                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
241         }
242         catch(...)
243         {
244                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
245                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
246         }
247 }
248
249 double InitializationThread::doInit(const size_t threadCount)
250 {
251         m_bSuccess = false;
252         delay();
253
254         //CPU type selection
255         unsigned int cpuSupport = 0;
256         if((m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE) && (m_cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE2) && m_cpuFeatures.intel)
257         {
258                 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
259         }
260         else
261         {
262                 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
263         }
264
265         //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
266         if(cpuSupport & CPU_TYPE_X64_ALL)
267         {
268                 if(MUtils::OS::running_on_wine())
269                 {
270                         qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
271                         cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
272                 }
273         }
274
275         //Print selected CPU type
276         switch(cpuSupport)
277         {
278                 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
279                 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
280                 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
281                 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
282                 default: MUTILS_THROW("CPU support undefined!");
283         }
284
285         //Allocate queues
286         QQueue<QString> queueToolName;
287         QQueue<QString> queueChecksum;
288         QQueue<QString> queueVersInfo;
289         QQueue<unsigned int> queueVersions;
290         QQueue<unsigned int> queueCpuTypes;
291
292         //Init properties
293         for(int i = 0; true; i++)
294         {
295                 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash  || g_lamexp_tools[i].uiVersion))
296                 {
297                         break;
298                 }
299                 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
300                 {
301                         queueToolName.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcName));
302                         queueChecksum.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcHash));
303                         queueVersInfo.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcVersTag));
304                         queueCpuTypes.enqueue(g_lamexp_tools[i].uiCpuType);
305                         queueVersions.enqueue(g_lamexp_tools[i].uiVersion);
306                 }
307                 else
308                 {
309                         qFatal("Inconsistent checksum data detected. Take care!");
310                 }
311         }
312
313         QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
314
315         QThreadPool *pool = new QThreadPool();
316         pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, cores2threads(m_cpuFeatures.count), EXPECTED_TOOL_COUNT));
317         /* qWarning("Using %u threads for extraction.", pool->maxThreadCount()); */
318
319         LockedFile::selfTest();
320         ExtractorTask::clearFlags();
321
322         const long long timeExtractStart = MUtils::OS::perfcounter_read();
323         
324         //Extract all files
325         while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
326         {
327                 const QString toolName = queueToolName.dequeue();
328                 const QString checksum = queueChecksum.dequeue();
329                 const QString versInfo = queueVersInfo.dequeue();
330                 const unsigned int cpuType = queueCpuTypes.dequeue();
331                 const unsigned int version = queueVersions.dequeue();
332                         
333                 const QByteArray toolHash(checksum.toLatin1());
334                 if(toolHash.size() != 96)
335                 {
336                         qFatal("The checksum for \"%s\" has an invalid size!", MUTILS_UTF8(toolName));
337                         return -1.0;
338                 }
339                         
340                 QResource *resource = new QResource(QString(":/tools/%1").arg(toolName));
341                 if(!(resource->isValid() && resource->data()))
342                 {
343                         MUTILS_DELETE(resource);
344                         qFatal("The resource for \"%s\" could not be found!", MUTILS_UTF8(toolName));
345                         return -1.0;
346                 }
347                         
348                 if(cpuType & cpuSupport)
349                 {
350                         pool->start(new ExtractorTask(resource, appDir, toolName, toolHash, version, versInfo));
351                         continue;
352                 }
353
354                 MUTILS_DELETE(resource);
355         }
356
357         //Sanity Check
358         if(!(queueToolName.isEmpty() && queueChecksum.isEmpty() && queueVersInfo.isEmpty() && queueCpuTypes.isEmpty() && queueVersions.isEmpty()))
359         {
360                 qFatal("Checksum queues *not* empty fater verification completed. Take care!");
361         }
362
363         //Wait for extrator threads to finish
364         pool->waitForDone();
365         MUTILS_DELETE(pool);
366
367         const long long timeExtractEnd = MUtils::OS::perfcounter_read();
368
369         //Make sure all files were extracted correctly
370         if(ExtractorTask::getExcept())
371         {
372                 char errorMsg[BUFF_SIZE];
373                 if(ExtractorTask::getErrMsg(errorMsg, BUFF_SIZE))
374                 {
375                         qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
376                         return -1.0;
377                 }
378                 qFatal("At least one of the required tools could not be initialized!");
379                 return -1.0;
380         }
381
382         qDebug("All extracted.\n");
383
384         //Using any custom tools?
385         if(ExtractorTask::getCustom())
386         {
387                 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
388         }
389
390         //Check delay
391         const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(MUtils::OS::perfcounter_freq());
392         if(delayExtract > g_allowedExtractDelay)
393         {
394                 m_slowIndicator = true;
395                 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
396                 qWarning("Please report performance problems to your anti-virus developer !!!\n");
397         }
398         else
399         {
400                 qDebug("Extracting the tools took %.5f seconds (OK).\n", delayExtract);
401         }
402
403         //Register all translations
404         initTranslations();
405
406         //Look for AAC encoders
407         initNeroAac();
408         initFhgAac();
409         initQAac();
410
411         m_bSuccess = true;
412         delay();
413
414         return delayExtract;
415 }
416
417 void InitializationThread::runBenchmark(void)
418 {
419 #ifdef ENABLE_BENCHMARK
420         static const size_t nLoops = 5;
421         const size_t maxThreads = (5 * m_cpuFeatures.count);
422         QMap<size_t, double> results;
423
424         for(size_t c = 1; c <= maxThreads; c++)
425         {
426                 QList<double> delayLst;
427                 double delayAvg = 0.0;
428                 for(size_t i = 0; i < nLoops; i++)
429                 {
430                         delayLst << doInit(c);
431                         lamexp_clean_all_tools();
432                 }
433                 qSort(delayLst.begin(), delayLst.end());
434                 delayLst.takeLast();
435                 delayLst.takeFirst();
436                 for(QList<double>::ConstIterator iter = delayLst.constBegin(); iter != delayLst.constEnd(); iter++)
437                 {
438                         delayAvg += (*iter);
439                 }
440                 results.insert(c, (delayAvg / double(delayLst.count())));
441         }
442
443         qWarning("\n----------------------------------------------");
444         qWarning("Benchmark Results:");
445         qWarning("----------------------------------------------");
446
447         double bestTime = DBL_MAX; size_t bestVal = 0;
448         QList<size_t> keys = results.keys();
449         for(QList<size_t>::ConstIterator iter = keys.begin(); iter != keys.end(); iter++)
450         {
451                 const double time = results.value((*iter), DBL_MAX);
452                 qWarning("%02u -> %7.4f", (*iter), time);
453                 if(time < bestTime)
454                 {
455                         bestTime = time;
456                         bestVal = (*iter);
457                 }
458         }
459
460         qWarning("----------------------------------------------");
461         qWarning("BEST: %u of %u (factor: %7.4f)", bestVal, m_cpuFeatures.count, (double(bestVal) / double(m_cpuFeatures.count)));
462         qWarning("----------------------------------------------\n");
463         
464         qFatal("Benchmark complete. Thanks and bye bye!");
465 #else //ENABLE_BENCHMARK
466         MUTILS_THROW("Sorry, the benchmark is *not* available in this build!");
467 #endif //ENABLE_BENCHMARK
468 }
469
470 ////////////////////////////////////////////////////////////
471 // PUBLIC FUNCTIONS
472 ////////////////////////////////////////////////////////////
473
474 void InitializationThread::delay(void)
475 {
476         MUtils::OS::sleep_ms(333);
477 }
478
479 void InitializationThread::initTranslations(void)
480 {
481         //Search for language files
482         QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
483
484         //Make sure we found at least one translation
485         if(qmFiles.count() < 1)
486         {
487                 qFatal("Could not find any translation files!");
488                 return;
489         }
490
491         //Add all available translations
492         while(!qmFiles.isEmpty())
493         {
494                 QString langId, langName;
495                 unsigned int systemId = 0, country = 0;
496                 QString qmFile = qmFiles.takeFirst();
497                 
498                 QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
499                 if(langIdExp.indexIn(qmFile) >= 0)
500                 {
501                         langId = langIdExp.cap(1).toLower();
502                         QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
503                         if(langRes.isValid() && langRes.size() > 0)
504                         {
505                                 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
506                                 QTextStream stream(&data, QIODevice::ReadOnly);
507                                 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
508                                 while(!stream.atEnd())
509                                 {
510                                         QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
511                                         if(langInfo.count() == 3)
512                                         {
513                                                 systemId = langInfo.at(0).trimmed().toUInt();
514                                                 country  = langInfo.at(1).trimmed().toUInt();
515                                                 langName = langInfo.at(2).trimmed();
516                                                 break;
517                                         }
518                                 }
519                         }
520                 }
521
522                 if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
523                 {
524                         if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
525                         {
526                                 qDebug("Registering translation: %s = %s (%u) [%u]", MUTILS_UTF8(qmFile), MUTILS_UTF8(langName), systemId, country);
527                         }
528                         else
529                         {
530                                 qWarning("Failed to register: %s", qmFile.toLatin1().constData());
531                         }
532                 }
533         }
534
535         qDebug("All registered.\n");
536 }
537
538 void InitializationThread::initNeroAac(void)
539 {
540         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
541         
542         QFileInfo neroFileInfo[3];
543         neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
544         neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
545         neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
546         
547         bool neroFilesFound = true;
548         for(int i = 0; i < 3; i++)      { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
549
550         if(!neroFilesFound)
551         {
552                 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
553                 return;
554         }
555
556         for(int i = 0; i < 3; i++)
557         {
558                 if(!MUtils::OS::is_executable_file(neroFileInfo[i].canonicalFilePath()))
559                 {
560                         qDebug("%s executbale is invalid -> AAC encoding support will be disabled!\n", MUTILS_UTF8(neroFileInfo[i].fileName()));
561                         return;
562                 }
563         }
564
565         qDebug("Found Nero AAC encoder binary:\n%s\n", MUTILS_UTF8(neroFileInfo[0].canonicalFilePath()));
566
567         //Lock the Nero binaries
568         LockedFile *neroBin[3];
569         for(int i = 0; i < 3; i++) neroBin[i] = NULL;
570
571         try
572         {
573                 for(int i = 0; i < 3; i++)
574                 {
575                         neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
576                 }
577         }
578         catch(...)
579         {
580                 for(int i = 0; i < 3; i++) MUTILS_DELETE(neroBin[i]);
581                 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
582                 return;
583         }
584
585         QProcess process;
586         MUtils::init_process(process, neroFileInfo[0].absolutePath());
587
588         process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
589
590         if(!process.waitForStarted())
591         {
592                 qWarning("Nero process failed to create!");
593                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
594                 process.kill();
595                 process.waitForFinished(-1);
596                 for(int i = 0; i < 3; i++) MUTILS_DELETE(neroBin[i]);
597                 return;
598         }
599
600         unsigned int neroVersion = 0;
601
602         while(process.state() != QProcess::NotRunning)
603         {
604                 if(!process.waitForReadyRead())
605                 {
606                         if(process.state() == QProcess::Running)
607                         {
608                                 qWarning("Nero process time out -> killing!");
609                                 process.kill();
610                                 process.waitForFinished(-1);
611                                 for(int i = 0; i < 3; i++) MUTILS_DELETE(neroBin[i]);
612                                 return;
613                         }
614                 }
615
616                 while(process.canReadLine())
617                 {
618                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
619                         QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
620                         int index1 = tokens.indexOf("Package");
621                         int index2 = tokens.indexOf("version:");
622                         if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
623                         {
624                                 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
625                                 if(versionTokens.count() == 4)
626                                 {
627                                         neroVersion = 0;
628                                         neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
629                                         neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
630                                         neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
631                                         neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
632                                 }
633                         }
634                 }
635         }
636
637         if(!(neroVersion > 0))
638         {
639                 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
640                 for(int i = 0; i < 3; i++) MUTILS_DELETE(neroBin[i]);
641                 return;
642         }
643         
644         for(int i = 0; i < 3; i++)
645         {
646                 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
647         }
648 }
649
650 void InitializationThread::initFhgAac(void)
651 {
652         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
653         
654         QFileInfo fhgFileInfo[5];
655         fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
656         fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
657         fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
658         fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
659         fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
660         
661         bool fhgFilesFound = true;
662         for(int i = 0; i < 5; i++)      { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
663
664         if(!fhgFilesFound)
665         {
666                 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
667                 return;
668         }
669
670         if(!MUtils::OS::is_executable_file(fhgFileInfo[0].canonicalFilePath()))
671         {
672                 qDebug("FhgAacEnc executbale is invalid -> FhgAacEnc support will be disabled!\n");
673                 return;
674         }
675
676         qDebug("Found FhgAacEnc cli_exe:\n%s\n", MUTILS_UTF8(fhgFileInfo[0].canonicalFilePath()));
677         qDebug("Found FhgAacEnc enc_dll:\n%s\n", MUTILS_UTF8(fhgFileInfo[1].canonicalFilePath()));
678
679         //Lock the FhgAacEnc binaries
680         LockedFile *fhgBin[5];
681         for(int i = 0; i < 5; i++) fhgBin[i] = NULL;
682
683         try
684         {
685                 for(int i = 0; i < 5; i++)
686                 {
687                         fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
688                 }
689         }
690         catch(...)
691         {
692                 for(int i = 0; i < 5; i++) MUTILS_DELETE(fhgBin[i]);
693                 qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
694                 return;
695         }
696
697         QProcess process;
698         MUtils::init_process(process, fhgFileInfo[0].absolutePath());
699
700         process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
701
702         if(!process.waitForStarted())
703         {
704                 qWarning("FhgAacEnc process failed to create!");
705                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
706                 process.kill();
707                 process.waitForFinished(-1);
708                 for(int i = 0; i < 5; i++) MUTILS_DELETE(fhgBin[i]);
709                 return;
710         }
711
712         QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
713         unsigned int fhgVersion = 0;
714
715         while(process.state() != QProcess::NotRunning)
716         {
717                 process.waitForReadyRead();
718                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
719                 {
720                         qWarning("FhgAacEnc process time out -> killing!");
721                         process.kill();
722                         process.waitForFinished(-1);
723                         for(int i = 0; i < 5; i++) MUTILS_DELETE(fhgBin[i]);
724                         return;
725                 }
726                 while(process.bytesAvailable() > 0)
727                 {
728                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
729                         if(fhgAacEncSig.lastIndexIn(line) >= 0)
730                         {
731                                 bool ok = false;
732                                 unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
733                                 if(ok) fhgVersion = temp;
734                         }
735                 }
736         }
737
738         if(!(fhgVersion > 0))
739         {
740                 qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
741                 for(int i = 0; i < 5; i++) MUTILS_DELETE(fhgBin[i]);
742                 return;
743         }
744         else if(fhgVersion < lamexp_toolver_fhgaacenc())
745         {
746                 qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", lamexp_version2string("????-??-??", fhgVersion, "N/A").toLatin1().constData());
747                 qWarning("Minimum required FhgAacEnc version currently is: %s\n", lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A").toLatin1().constData());
748                 for(int i = 0; i < 5; i++) MUTILS_DELETE(fhgBin[i]);
749                 return;
750         }
751         
752         for(int i = 0; i < 5; i++)
753         {
754                 lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
755         }
756 }
757
758 void InitializationThread::initQAac(void)
759 {
760         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
761
762         QFileInfo qaacFileInfo[4];
763         qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
764         qaacFileInfo[1] = QFileInfo(QString("%1/libsoxr.dll").arg(appPath));
765         qaacFileInfo[2] = QFileInfo(QString("%1/libsoxconvolver.dll").arg(appPath));
766         qaacFileInfo[3] = QFileInfo(QString("%1/libgcc_s_sjlj-1.dll").arg(appPath));
767         
768         bool qaacFilesFound = true;
769         for(int i = 0; i < 4; i++)      { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
770
771         if(!qaacFilesFound)
772         {
773                 qDebug("QAAC binary or companion DLL's not found -> QAAC support will be disabled!\n");
774                 return;
775         }
776
777         if(!MUtils::OS::is_executable_file(qaacFileInfo[0].canonicalFilePath()))
778         {
779                 qDebug("QAAC executbale is invalid -> QAAC support will be disabled!\n");
780                 return;
781         }
782
783         qDebug("Found QAAC encoder:\n%s\n", MUTILS_UTF8(qaacFileInfo[0].canonicalFilePath()));
784
785         //Lock the required QAAC binaries
786         LockedFile *qaacBin[4];
787         for(int i = 0; i < 4; i++) qaacBin[i] = NULL;
788
789         try
790         {
791                 for(int i = 0; i < 4; i++)
792                 {
793                         qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
794                 }
795         }
796         catch(...)
797         {
798                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
799                 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
800                 return;
801         }
802
803         QProcess process;
804         MUtils::init_process(process, qaacFileInfo[0].absolutePath());
805
806         process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
807
808         if(!process.waitForStarted())
809         {
810                 qWarning("QAAC process failed to create!");
811                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
812                 process.kill();
813                 process.waitForFinished(-1);
814                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
815                 return;
816         }
817
818         QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
819         QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
820         QRegExp soxrEncSig("libsoxr-\\d\\.\\d\\.\\d", Qt::CaseInsensitive);
821         QRegExp soxcEncSig("libsoxconvolver \\d\\.\\d\\.\\d", Qt::CaseInsensitive);
822
823         unsigned int qaacVersion = 0;
824         unsigned int coreVersion = 0;
825         bool soxrFound = false;
826         bool soxcFound = false;
827
828         while(process.state() != QProcess::NotRunning)
829         {
830                 process.waitForReadyRead();
831                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
832                 {
833                         qWarning("QAAC process time out -> killing!");
834                         process.kill();
835                         process.waitForFinished(-1);
836                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
837                         return;
838                 }
839                 while(process.bytesAvailable() > 0)
840                 {
841                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
842                         if(qaacEncSig.lastIndexIn(line) >= 0)
843                         {
844                                 unsigned int tmp[3] = {0, 0, 0};
845                                 bool ok[3] = {false, false, false};
846                                 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
847                                 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
848                                 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
849                                 if(ok[0] && ok[1] && ok[2])
850                                 {
851                                         qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
852                                 }
853                         }
854                         if(coreEncSig.lastIndexIn(line) >= 0)
855                         {
856                                 unsigned int tmp[4] = {0, 0, 0, 0};
857                                 bool ok[4] = {false, false, false, false};
858                                 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
859                                 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
860                                 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
861                                 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
862                                 if(ok[0] && ok[1] && ok[2] && ok[3])
863                                 {
864                                         coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
865                                 }
866                         }
867                         if(soxcEncSig.lastIndexIn(line) >= 0) { soxcFound = true; }
868                         if(soxrEncSig.lastIndexIn(line) >= 0) { soxrFound = true; }
869                 }
870         }
871
872         //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
873
874         if(!(qaacVersion > 0))
875         {
876                 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
877                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
878                 return;
879         }
880         else if(qaacVersion < lamexp_toolver_qaacenc())
881         {
882                 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
883                 qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
884                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
885                 return;
886         }
887
888         if(!(coreVersion > 0))
889         {
890                 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
891                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
892                 return;
893         }
894         else if(coreVersion < lamexp_toolver_coreaudio())
895         {
896                 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
897                 qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
898                 for(int i = 0; i < 4; i++) MUTILS_DELETE(qaacBin[i]);
899                 return;
900         }
901
902         if(!(soxrFound && soxcFound))
903         {
904                 qWarning("libsoxr and/or libsoxconvolver not available -> QAAC support will be disabled!\n");
905                 return;
906         }
907
908         lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
909         lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
910         lamexp_register_tool(qaacFileInfo[2].fileName(), qaacBin[2], qaacVersion);
911         lamexp_register_tool(qaacFileInfo[3].fileName(), qaacBin[3], qaacVersion);
912 }
913
914 void InitializationThread::selfTest(void)
915 {
916         const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
917
918         LockedFile::selfTest();
919
920         for(size_t k = 0; k < 4; k++)
921         {
922                 qDebug("[TEST]");
923                 switch(cpu[k])
924                 {
925                         PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
926                         PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
927                         PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
928                         PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
929                         default: MUTILS_THROW("CPU support undefined!");
930                 }
931                 unsigned int n = 0;
932                 for(int i = 0; true; i++)
933                 {
934                         if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash  || g_lamexp_tools[i].uiVersion))
935                         {
936                                 break;
937                         }
938                         else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
939                         {
940                                 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
941                                 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
942                                 if(g_lamexp_tools[i].uiCpuType & cpu[k])
943                                 {
944                                         qDebug("%02i -> %s", ++n, MUTILS_UTF8(toolName));
945                                         QFile resource(QString(":/tools/%1").arg(toolName));
946                                         if(!resource.open(QIODevice::ReadOnly))
947                                         {
948                                                 qFatal("The resource for \"%s\" could not be opened!", MUTILS_UTF8(toolName));
949                                                 break;
950                                         }
951                                         QByteArray hash = LockedFile::fileHash(resource);
952                                         if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
953                                         {
954                                                 qFatal("Hash check for tool \"%s\" has failed!", MUTILS_UTF8(toolName));
955                                                 break;
956                                         }
957                                         resource.close();
958                                 }
959                         }
960                         else
961                         {
962                                 qFatal("Inconsistent checksum data detected. Take care!");
963                         }
964                 }
965                 if(n != EXPECTED_TOOL_COUNT)
966                 {
967                         qFatal("Tool count mismatch for CPU type %u !!!", cpu[k]);
968                 }
969                 qDebug("Done.\n");
970         }
971 }
972
973 ////////////////////////////////////////////////////////////
974 // EVENTS
975 ////////////////////////////////////////////////////////////
976
977 /*NONE*/