OSDN Git Service

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