OSDN Git Service

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