OSDN Git Service

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