OSDN Git Service

Implemented multi-threading for tool extraction. The extraction of the tools is limit...
[lamexp/LameXP.git] / src / Thread_Initialization.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 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.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Thread_Initialization.h"
23
24 #include "LockedFile.h"
25 #include "Tools.h"
26
27 #include <QFileInfo>
28 #include <QCoreApplication>
29 #include <QProcess>
30 #include <QMap>
31 #include <QDir>
32 #include <QLibrary>
33 #include <QResource>
34 #include <QTime>
35 #include <QTextStream>
36 #include <QRunnable>
37 #include <QThreadPool>
38 #include <QMutex>
39 #include <QMutexLocker>
40
41 /* helper macros */
42 #define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
43 static const double g_allowedExtractDelay = 12.0;
44
45 ////////////////////////////////////////////////////////////
46 // ExtractorTask class
47 ////////////////////////////////////////////////////////////
48
49 class ExtractorTask : public QRunnable
50 {
51 public:
52         ExtractorTask(const QDir &appDir, const QString &toolName, const QString &toolShortName, const QByteArray &toolHash, const unsigned int toolVersion)
53         :
54                 QRunnable(), m_appDir(appDir), m_toolName(toolName), m_toolShortName(toolShortName), m_toolHash(toolHash), m_toolVersion(toolVersion)
55         {
56                 /* Nothing to do */
57         }
58
59         static void clearFlags(void)
60         {
61                 s_bAbort = s_bCustom = false;
62                 s_errMsg[0] = '\0';
63         }
64
65         static bool getAbort(void) { return s_bAbort; }
66         static bool getCustom(void) { return s_bCustom; }
67         static char *const getError(void) { return s_errMsg; }
68
69 protected:
70         void run()
71         {
72                 try
73                 {
74                         LockedFile *lockedFile = NULL;
75                         unsigned int version = m_toolVersion;
76                         
77                         if(!s_bAbort)
78                         {
79                                 QFileInfo customTool(QString("%1/tools/%2/%3").arg(m_appDir.canonicalPath(), QString::number(lamexp_version_build()), m_toolShortName));
80                                 if(customTool.exists() && customTool.isFile())
81                                 {
82                                         qDebug("Setting up file: %s <- %s", m_toolShortName.toLatin1().constData(), m_appDir.relativeFilePath(customTool.canonicalFilePath()).toLatin1().constData());
83                                         lockedFile = new LockedFile(customTool.canonicalFilePath()); version = UINT_MAX; s_bCustom = true;
84                                 }
85                                 else
86                                 {
87                                         qDebug("Extracting file: %s -> %s", m_toolName.toLatin1().constData(), m_toolShortName.toLatin1().constData());
88                                         lockedFile = new LockedFile(QString(":/tools/%1").arg(m_toolName), QString("%1/lamexp_%2").arg(lamexp_temp_folder2(), m_toolShortName), m_toolHash);
89                                 }
90
91                                 if(lockedFile)
92                                 {
93                                         QMutexLocker lock(&s_mutex);
94                                         lamexp_register_tool(m_toolShortName, lockedFile, version);
95                                 }
96                         }
97                 }
98                 catch(char *errorMsg)
99                 {
100                         qWarning("At least one of the required tools could not be initialized:\n%s", errorMsg);
101                         QMutexLocker lock(&s_mutex);
102                         if(!s_bAbort) { s_bAbort = true; strncpy_s(s_errMsg, 1024, errorMsg, _TRUNCATE); }
103                 }
104         }
105
106 private:
107         const QDir m_appDir;
108         const QString m_toolName;
109         const QString m_toolShortName;
110         const QByteArray m_toolHash;
111         const unsigned int m_toolVersion;
112
113         static volatile bool s_bAbort;
114         static volatile bool s_bCustom;
115         static QMutex s_mutex;
116         static char s_errMsg[1024];
117 };
118
119 volatile bool ExtractorTask::s_bAbort = false;
120 volatile bool ExtractorTask::s_bCustom = false;
121 char ExtractorTask::s_errMsg[1024] = {'\0'};
122 QMutex ExtractorTask::s_mutex;
123
124 ////////////////////////////////////////////////////////////
125 // Constructor
126 ////////////////////////////////////////////////////////////
127
128 InitializationThread::InitializationThread(const lamexp_cpu_t *cpuFeatures)
129 {
130         m_bSuccess = false;
131         memset(&m_cpuFeatures, 0, sizeof(lamexp_cpu_t));
132         m_slowIndicator = false;
133         
134         if(cpuFeatures)
135         {
136                 memcpy(&m_cpuFeatures, cpuFeatures, sizeof(lamexp_cpu_t));
137         }
138 }
139
140 ////////////////////////////////////////////////////////////
141 // Thread Main
142 ////////////////////////////////////////////////////////////
143
144 void InitializationThread::run()
145 {
146         m_bSuccess = false;
147         delay();
148
149         //CPU type selection
150         unsigned int cpuSupport = 0;
151         if(m_cpuFeatures.sse && m_cpuFeatures.sse2 && m_cpuFeatures.intel)
152         {
153                 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
154         }
155         else
156         {
157                 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
158         }
159
160         //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
161         if(cpuSupport & CPU_TYPE_X64_ALL)
162         {
163                 //DWORD osVerNo = lamexp_get_os_version();
164                 //if((HIWORD(osVerNo) == 6) && (LOWORD(osVerNo) == 2))
165                 if(lamexp_detect_wine())
166                 {
167                         qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
168                         cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
169                 }
170         }
171
172         //Print selected CPU type
173         switch(cpuSupport)
174         {
175                 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
176                 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
177                 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
178                 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
179                 default: throw "CPU support undefined!";
180         }
181
182         //Allocate maps
183         QMap<QString, QString> mapChecksum;
184         QMap<QString, unsigned int> mapVersion;
185         QMap<QString, unsigned int> mapCpuType;
186
187         //Init properties
188         for(int i = 0; i < INT_MAX; i++)
189         {
190                 if(!g_lamexp_tools[i].pcName && !g_lamexp_tools[i].pcHash && !g_lamexp_tools[i].uiVersion)
191                 {
192                         break;
193                 }
194                 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
195                 {
196                         const QString currentTool = QString::fromLatin1(g_lamexp_tools[i].pcName);
197                         mapChecksum.insert(currentTool, QString::fromLatin1(g_lamexp_tools[i].pcHash));
198                         mapCpuType.insert(currentTool, g_lamexp_tools[i].uiCpuType);
199                         mapVersion.insert(currentTool, g_lamexp_tools[i].uiVersion);
200                 }
201                 else
202                 {
203                         qFatal("Inconsistent checksum data detected. Take care!");
204                 }
205         }
206
207         QDir toolsDir(":/tools/");
208         QList<QFileInfo> toolsList = toolsDir.entryInfoList(QStringList("*.*"), QDir::Files, QDir::Name);
209         QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
210
211         QThreadPool *pool = new QThreadPool();
212         int idealThreadCount = QThread::idealThreadCount();
213         if(idealThreadCount > 0)
214         {
215                 pool->setMaxThreadCount(idealThreadCount * 2);
216         }
217         
218         ExtractorTask::clearFlags();
219
220         QTime timer;
221         timer.start();
222         
223         //Extract all files
224         while(!toolsList.isEmpty())
225         {
226                 try
227                 {
228                         QFileInfo currentTool = toolsList.takeFirst();
229                         QString toolName = currentTool.fileName().toLower();
230                         QString toolShortName = QString("%1.%2").arg(currentTool.baseName().toLower(), currentTool.suffix().toLower());
231                         
232                         QByteArray toolHash = mapChecksum.take(toolName).toLatin1();
233                         unsigned int toolCpuType = mapCpuType.take(toolName);
234                         unsigned int toolVersion = mapVersion.take(toolName);
235                         
236                         if(toolHash.size() != 72)
237                         {
238                                 throw "The required checksum is missing, take care!";
239                         }
240                         
241                         if(toolCpuType & cpuSupport)
242                         {
243                                 pool->start(new ExtractorTask(appDir, toolName, toolShortName, toolHash, toolVersion));
244                                 QThread::yieldCurrentThread();
245                         }
246                 }
247                 catch(char *errorMsg)
248                 {
249                         qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
250                         return;
251                 }
252         }
253         
254         //Wait for extrator threads to finish
255         pool->waitForDone();
256         LAMEXP_DELETE(pool);
257
258         //Make sure all files were extracted correctly
259         if(ExtractorTask::getAbort())
260         {
261                 qFatal("At least one of the required tools could not be initialized:\n%s", ExtractorTask::getError());
262                 return;
263         }
264
265         //Make sure all files were extracted
266         if(!mapChecksum.isEmpty())
267         {
268                 qFatal("At least one required tool could not be found:\n%s", toolsDir.filePath(mapChecksum.keys().first()).toLatin1().constData());
269                 return;
270         }
271
272         qDebug("All extracted.\n");
273
274         //Clean-up
275         mapChecksum.clear();
276         mapVersion.clear();
277         mapCpuType.clear();
278         
279         //Using any custom tools?
280         if(ExtractorTask::getCustom())
281         {
282                 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
283         }
284
285         //Check delay
286         double delayExtract = static_cast<double>(timer.elapsed()) / 1000.0;
287         if(delayExtract > g_allowedExtractDelay)
288         {
289                 m_slowIndicator = true;
290                 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
291                 qWarning("Please report performance problems to your anti-virus developer !!!\n");
292         }
293
294         //Register all translations
295         initTranslations();
296
297         //Look for AAC encoders
298         initNeroAac();
299         initFhgAac();
300         initQAac();
301
302         delay();
303         m_bSuccess = true;
304 }
305
306 ////////////////////////////////////////////////////////////
307 // PUBLIC FUNCTIONS
308 ////////////////////////////////////////////////////////////
309
310 void InitializationThread::delay(void)
311 {
312         const char *temp = "|/-\\";
313         printf("Thread is doing something important... ?\b", temp[4]);
314
315         for(int i = 0; i < 20; i++)
316         {
317                 printf("%c\b", temp[i%4]);
318                 msleep(25);
319         }
320
321         printf("Done\n\n");
322 }
323
324 void InitializationThread::initTranslations(void)
325 {
326         //Search for language files
327         QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
328
329         //Make sure we found at least one translation
330         if(qmFiles.count() < 1)
331         {
332                 qFatal("Could not find any translation files!");
333                 return;
334         }
335
336         //Add all available translations
337         while(!qmFiles.isEmpty())
338         {
339                 QString langId, langName;
340                 unsigned int systemId = 0, country = 0;
341                 QString qmFile = qmFiles.takeFirst();
342                 
343                 QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
344                 if(langIdExp.indexIn(qmFile) >= 0)
345                 {
346                         langId = langIdExp.cap(1).toLower();
347                         QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
348                         if(langRes.isValid() && langRes.size() > 0)
349                         {
350                                 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
351                                 QTextStream stream(&data, QIODevice::ReadOnly);
352                                 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
353                                 while(!stream.atEnd())
354                                 {
355                                         QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
356                                         if(langInfo.count() == 3)
357                                         {
358                                                 systemId = langInfo.at(0).trimmed().toUInt();
359                                                 country  = langInfo.at(1).trimmed().toUInt();
360                                                 langName = langInfo.at(2).trimmed();
361                                                 break;
362                                         }
363                                 }
364                         }
365                 }
366
367                 if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
368                 {
369                         if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
370                         {
371                                 qDebug("Registering translation: %s = %s (%u) [%u]", qmFile.toUtf8().constData(), langName.toUtf8().constData(), systemId, country);
372                         }
373                         else
374                         {
375                                 qWarning("Failed to register: %s", qmFile.toLatin1().constData());
376                         }
377                 }
378         }
379
380         qDebug("All registered.\n");
381 }
382
383 void InitializationThread::initNeroAac(void)
384 {
385         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
386         
387         QFileInfo neroFileInfo[3];
388         neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
389         neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
390         neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
391         
392         bool neroFilesFound = true;
393         for(int i = 0; i < 3; i++)      { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
394
395         //Lock the Nero binaries
396         if(!neroFilesFound)
397         {
398                 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
399                 return;
400         }
401
402         qDebug("Found Nero AAC encoder binary:\n%s\n", neroFileInfo[0].canonicalFilePath().toUtf8().constData());
403
404         LockedFile *neroBin[3];
405         for(int i = 0; i < 3; i++) neroBin[i] = NULL;
406
407         try
408         {
409                 for(int i = 0; i < 3; i++)
410                 {
411                         neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
412                 }
413         }
414         catch(...)
415         {
416                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
417                 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
418                 return;
419         }
420
421         QProcess process;
422         process.setProcessChannelMode(QProcess::MergedChannels);
423         process.setReadChannel(QProcess::StandardOutput);
424         process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
425
426         if(!process.waitForStarted())
427         {
428                 qWarning("Nero process failed to create!");
429                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
430                 process.kill();
431                 process.waitForFinished(-1);
432                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
433                 return;
434         }
435
436         unsigned int neroVersion = 0;
437
438         while(process.state() != QProcess::NotRunning)
439         {
440                 if(!process.waitForReadyRead())
441                 {
442                         if(process.state() == QProcess::Running)
443                         {
444                                 qWarning("Nero process time out -> killing!");
445                                 process.kill();
446                                 process.waitForFinished(-1);
447                                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
448                                 return;
449                         }
450                 }
451
452                 while(process.canReadLine())
453                 {
454                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
455                         QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
456                         int index1 = tokens.indexOf("Package");
457                         int index2 = tokens.indexOf("version:");
458                         if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
459                         {
460                                 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
461                                 if(versionTokens.count() == 4)
462                                 {
463                                         neroVersion = 0;
464                                         neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
465                                         neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
466                                         neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
467                                         neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
468                                 }
469                         }
470                 }
471         }
472
473         if(!(neroVersion > 0))
474         {
475                 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
476                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
477                 return;
478         }
479         
480         for(int i = 0; i < 3; i++)
481         {
482                 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
483         }
484 }
485
486 void InitializationThread::initFhgAac(void)
487 {
488         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
489         
490         QFileInfo fhgFileInfo[4];
491         fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
492         fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
493         fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
494         fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
495         
496         bool fhgFilesFound = true;
497         for(int i = 0; i < 4; i++)      { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
498
499         //Lock the FhgAacEnc binaries
500         if(!fhgFilesFound)
501         {
502                 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
503                 return;
504         }
505
506         qDebug("Found FhgAacEnc cli_exe:\n%s\n", fhgFileInfo[0].canonicalFilePath().toUtf8().constData());
507         qDebug("Found FhgAacEnc enc_dll:\n%s\n", fhgFileInfo[1].canonicalFilePath().toUtf8().constData());
508
509         LockedFile *fhgBin[4];
510         for(int i = 0; i < 4; i++) fhgBin[i] = NULL;
511
512         try
513         {
514                 for(int i = 0; i < 4; i++)
515                 {
516                         fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
517                 }
518         }
519         catch(...)
520         {
521                 for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
522                 qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
523                 return;
524         }
525
526         QProcess process;
527         process.setProcessChannelMode(QProcess::MergedChannels);
528         process.setReadChannel(QProcess::StandardOutput);
529         process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
530
531         if(!process.waitForStarted())
532         {
533                 qWarning("FhgAacEnc process failed to create!");
534                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
535                 process.kill();
536                 process.waitForFinished(-1);
537                 for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
538                 return;
539         }
540
541         QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
542         unsigned int fhgVersion = 0;
543
544         while(process.state() != QProcess::NotRunning)
545         {
546                 process.waitForReadyRead();
547                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
548                 {
549                         qWarning("FhgAacEnc process time out -> killing!");
550                         process.kill();
551                         process.waitForFinished(-1);
552                         for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
553                         return;
554                 }
555                 while(process.bytesAvailable() > 0)
556                 {
557                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
558                         if(fhgAacEncSig.lastIndexIn(line) >= 0)
559                         {
560                                 bool ok = false;
561                                 unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
562                                 if(ok) fhgVersion = temp;
563                         }
564                 }
565         }
566
567         if(!(fhgVersion > 0))
568         {
569                 qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
570                 for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
571                 return;
572         }
573         else if(fhgVersion < lamexp_toolver_fhgaacenc())
574         {
575                 qWarning("FhgAacEnc version is too much outdated -> FhgAacEnc support will be disabled!");
576                 for(int i = 0; i < 4; i++) LAMEXP_DELETE(fhgBin[i]);
577                 return;
578         }
579         
580         for(int i = 0; i < 4; i++)
581         {
582                 lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
583         }
584 }
585
586 void InitializationThread::initQAac(void)
587 {
588         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
589
590         QFileInfo qaacFileInfo[2];
591         qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
592         qaacFileInfo[1] = QFileInfo(QString("%1/libsoxrate.dll").arg(appPath));
593         
594         bool qaacFilesFound = true;
595         for(int i = 0; i < 2; i++)      { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
596
597         //Lock the QAAC binaries
598         if(!qaacFilesFound)
599         {
600                 qDebug("QAAC binaries not found -> QAAC support will be disabled!\n");
601                 return;
602         }
603
604         qDebug("Found QAAC encoder:\n%s\n", qaacFileInfo[0].canonicalFilePath().toUtf8().constData());
605
606         LockedFile *qaacBin[2];
607         for(int i = 0; i < 2; i++) qaacBin[i] = NULL;
608
609         try
610         {
611                 for(int i = 0; i < 2; i++)
612                 {
613                         qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
614                 }
615         }
616         catch(...)
617         {
618                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
619                 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
620                 return;
621         }
622
623         QProcess process;
624         process.setProcessChannelMode(QProcess::MergedChannels);
625         process.setReadChannel(QProcess::StandardOutput);
626         process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
627
628         if(!process.waitForStarted())
629         {
630                 qWarning("QAAC process failed to create!");
631                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
632                 process.kill();
633                 process.waitForFinished(-1);
634                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
635                 return;
636         }
637
638         QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
639         QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
640         unsigned int qaacVersion = 0;
641         unsigned int coreVersion = 0;
642
643         while(process.state() != QProcess::NotRunning)
644         {
645                 process.waitForReadyRead();
646                 if(!process.bytesAvailable() && process.state() == QProcess::Running)
647                 {
648                         qWarning("QAAC process time out -> killing!");
649                         process.kill();
650                         process.waitForFinished(-1);
651                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
652                         return;
653                 }
654                 while(process.bytesAvailable() > 0)
655                 {
656                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
657                         if(qaacEncSig.lastIndexIn(line) >= 0)
658                         {
659                                 unsigned int tmp[3] = {0, 0, 0};
660                                 bool ok[3] = {false, false, false};
661                                 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
662                                 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
663                                 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
664                                 if(ok[0] && ok[1] && ok[2])
665                                 {
666                                         qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
667                                 }
668                         }
669                         if(coreEncSig.lastIndexIn(line) >= 0)
670                         {
671                                 unsigned int tmp[4] = {0, 0, 0, 0};
672                                 bool ok[4] = {false, false, false, false};
673                                 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
674                                 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
675                                 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
676                                 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
677                                 if(ok[0] && ok[1] && ok[2] && ok[3])
678                                 {
679                                         coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
680                                 }
681                         }
682                 }
683         }
684
685         //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
686
687         if(!(qaacVersion > 0))
688         {
689                 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
690                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
691                 return;
692         }
693         else if(qaacVersion < lamexp_toolver_qaacenc())
694         {
695                 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
696                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
697                 return;
698         }
699
700         if(!(coreVersion > 0))
701         {
702                 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
703                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
704                 return;
705         }
706         else if(coreVersion < lamexp_toolver_coreaudio())
707         {
708                 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
709                 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
710                 return;
711         }
712
713         lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
714         lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
715 }
716
717 void InitializationThread::selfTest(void)
718 {
719         const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
720
721         for(size_t k = 0; k < 4; k++)
722         {
723                 qDebug("[TEST]");
724                 switch(cpu[k])
725                 {
726                         PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
727                         PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
728                         PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
729                         PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
730                         default: throw "CPU support undefined!";
731                 }
732                 int n = 0;
733                 for(int i = 0; i < INT_MAX; i++)
734                 {
735                         if(!g_lamexp_tools[i].pcName && !g_lamexp_tools[i].pcHash && !g_lamexp_tools[i].uiVersion)
736                         {
737                                 break;
738                         }
739                         if(g_lamexp_tools[i].uiCpuType & cpu[k])
740                         {
741                                 qDebug("%02i -> %s", ++n, g_lamexp_tools[i].pcName);
742                         }
743                 }
744                 if(n != 25)
745                 {
746                         qFatal("Tool count mismatch !!!");
747                 }
748                 qDebug("Done.\n");
749         }
750 }
751
752 ////////////////////////////////////////////////////////////
753 // EVENTS
754 ////////////////////////////////////////////////////////////
755
756 /*NONE*/