Updated the QAAC add-in for LameXP to QAAC v2.33 (2014-01-14), compiled with MSVC...
[LameXP.git] / src / Thread_Initialization.cpp
blobe49b6478493ef82729f689da3f6427db1ab8b6ca
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Thread_Initialization.h"
25 #include "LockedFile.h"
26 #include "Tools.h"
27 #include "Tool_Abstract.h"
29 #include <QFileInfo>
30 #include <QCoreApplication>
31 #include <QProcess>
32 #include <QMap>
33 #include <QDir>
34 #include <QLibrary>
35 #include <QResource>
36 #include <QTextStream>
37 #include <QRunnable>
38 #include <QThreadPool>
39 #include <QMutex>
40 #include <QQueue>
42 /* helper macros */
43 #define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
45 /* constants */
46 static const double g_allowedExtractDelay = 12.0;
47 static const size_t BUFF_SIZE = 512;
48 static const size_t EXPECTED_TOOL_COUNT = 28;
50 /* benchmark */
51 #undef ENABLE_BENCHMARK
53 /* number of CPU cores -> number of threads */
54 static unsigned int cores2threads(const unsigned int cores)
56 static const size_t LUT_LEN = 4;
58 static const struct
60 const unsigned int upperBound;
61 const double coeffs[4];
63 LUT[LUT_LEN] =
65 { 4, { -0.052695810565, 0.158087431694, 4.982841530055, -1.088233151184 } },
66 { 8, { 0.042431693989, -0.983442622951, 9.548961748634, -7.176393442623 } },
67 { 12, { -0.006277322404, 0.185573770492, 0.196830601093, 17.762622950820 } },
68 { 32, { 0.000673497268, -0.064655737705, 3.199584699454, 5.751606557377 } }
71 size_t index = 0;
72 while((cores > LUT[index].upperBound) && (index < (LUT_LEN-1))) index++;
74 const double x = qBound(1.0, double(cores), double(LUT[LUT_LEN-1].upperBound));
75 const double y = (LUT[index].coeffs[0] * pow(x, 3.0)) + (LUT[index].coeffs[1] * pow(x, 2.0)) + (LUT[index].coeffs[2] * x) + LUT[index].coeffs[3];
77 return qRound(abs(y));
80 ////////////////////////////////////////////////////////////
81 // ExtractorTask class
82 ////////////////////////////////////////////////////////////
84 class ExtractorTask : public QRunnable
86 public:
87 ExtractorTask(QResource *const toolResource, const QDir &appDir, const QString &toolName, const QByteArray &toolHash, const unsigned int toolVersion, const QString &toolTag)
89 m_appDir(appDir),
90 m_toolName(toolName),
91 m_toolHash(toolHash),
92 m_toolVersion(toolVersion),
93 m_toolTag(toolTag),
94 m_toolResource(toolResource)
96 /* Nothing to do */
99 ~ExtractorTask(void)
101 delete m_toolResource;
104 static void clearFlags(void)
106 QMutexLocker lock(&s_mutex);
107 s_bExcept = false;
108 s_bCustom = false;
109 s_errMsg[0] = char(0);
112 static bool getExcept(void) { bool ret; QMutexLocker lock(&s_mutex); ret = s_bExcept; return ret; }
113 static bool getCustom(void) { bool ret; QMutexLocker lock(&s_mutex); ret = s_bCustom; return ret; }
115 static bool getErrMsg(char *buffer, const size_t buffSize)
117 QMutexLocker lock(&s_mutex);
118 if(s_errMsg[0])
120 strncpy_s(buffer, BUFF_SIZE, s_errMsg, _TRUNCATE);
121 return true;
123 return false;
126 protected:
127 void run(void)
131 if(!getExcept()) doExtract();
133 catch(const std::exception &e)
135 QMutexLocker lock(&s_mutex);
136 if(!s_bExcept)
138 s_bExcept = true;
139 strncpy_s(s_errMsg, BUFF_SIZE, e.what(), _TRUNCATE);
141 lock.unlock();
142 qWarning("ExtractorTask exception error:\n%s\n\n", e.what());
144 catch(...)
146 QMutexLocker lock(&s_mutex);
147 if(!s_bExcept)
149 s_bExcept = true;
150 strncpy_s(s_errMsg, BUFF_SIZE, "Unknown exception error!", _TRUNCATE);
152 lock.unlock();
153 qWarning("ExtractorTask encountered an unknown exception!");
157 void doExtract(void)
159 LockedFile *lockedFile = NULL;
160 unsigned int version = m_toolVersion;
162 QFileInfo toolFileInfo(m_toolName);
163 const QString toolShortName = QString("%1.%2").arg(toolFileInfo.baseName().toLower(), toolFileInfo.suffix().toLower());
165 QFileInfo customTool(QString("%1/tools/%2/%3").arg(m_appDir.canonicalPath(), QString::number(lamexp_version_build()), toolShortName));
166 if(customTool.exists() && customTool.isFile())
168 qDebug("Setting up file: %s <- %s", toolShortName.toLatin1().constData(), m_appDir.relativeFilePath(customTool.canonicalFilePath()).toLatin1().constData());
169 lockedFile = new LockedFile(customTool.canonicalFilePath()); version = UINT_MAX; s_bCustom = true;
171 else
173 qDebug("Extracting file: %s -> %s", m_toolName.toLatin1().constData(), toolShortName.toLatin1().constData());
174 lockedFile = new LockedFile(m_toolResource, QString("%1/lxp_%2").arg(lamexp_temp_folder2(), toolShortName), m_toolHash);
177 if(lockedFile)
179 lamexp_register_tool(toolShortName, lockedFile, version, &m_toolTag);
183 private:
184 QResource *const m_toolResource;
185 const QDir m_appDir;
186 const QString m_toolName;
187 const QByteArray m_toolHash;
188 const unsigned int m_toolVersion;
189 const QString m_toolTag;
191 static volatile bool s_bExcept;
192 static volatile bool s_bCustom;
193 static QMutex s_mutex;
194 static char s_errMsg[BUFF_SIZE];
197 QMutex ExtractorTask::s_mutex;
198 char ExtractorTask::s_errMsg[BUFF_SIZE] = {'\0'};
199 volatile bool ExtractorTask::s_bExcept = false;
200 volatile bool ExtractorTask::s_bCustom = false;
202 ////////////////////////////////////////////////////////////
203 // Constructor
204 ////////////////////////////////////////////////////////////
206 InitializationThread::InitializationThread(const lamexp_cpu_t *cpuFeatures)
208 m_bSuccess = false;
209 memset(&m_cpuFeatures, 0, sizeof(lamexp_cpu_t));
210 m_slowIndicator = false;
212 if(cpuFeatures)
214 memcpy(&m_cpuFeatures, cpuFeatures, sizeof(lamexp_cpu_t));
218 ////////////////////////////////////////////////////////////
219 // Thread Main
220 ////////////////////////////////////////////////////////////
222 #ifdef ENABLE_BENCHMARK
223 #define DO_INIT_FUNCT runBenchmark
224 #else //ENABLE_BENCHMARK
225 #define DO_INIT_FUNCT doInit
226 #endif //ENABLE_BENCHMARK
228 void InitializationThread::run(void)
232 DO_INIT_FUNCT();
234 catch(const std::exception &error)
236 fflush(stdout); fflush(stderr);
237 fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
238 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
240 catch(...)
242 fflush(stdout); fflush(stderr);
243 fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
244 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
248 double InitializationThread::doInit(const size_t threadCount)
250 m_bSuccess = false;
251 delay();
253 //CPU type selection
254 unsigned int cpuSupport = 0;
255 if(m_cpuFeatures.sse && m_cpuFeatures.sse2 && m_cpuFeatures.intel)
257 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
259 else
261 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
264 //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
265 if(cpuSupport & CPU_TYPE_X64_ALL)
267 if(lamexp_detect_wine())
269 qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
270 cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
274 //Print selected CPU type
275 switch(cpuSupport)
277 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
278 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
279 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
280 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
281 default: THROW("CPU support undefined!");
284 //Allocate queues
285 QQueue<QString> queueToolName;
286 QQueue<QString> queueChecksum;
287 QQueue<QString> queueVersInfo;
288 QQueue<unsigned int> queueVersions;
289 QQueue<unsigned int> queueCpuTypes;
291 //Init properties
292 for(int i = 0; true; i++)
294 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
296 break;
298 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
300 queueToolName.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcName));
301 queueChecksum.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcHash));
302 queueVersInfo.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcVersTag));
303 queueCpuTypes.enqueue(g_lamexp_tools[i].uiCpuType);
304 queueVersions.enqueue(g_lamexp_tools[i].uiVersion);
306 else
308 qFatal("Inconsistent checksum data detected. Take care!");
312 QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
314 QThreadPool *pool = new QThreadPool();
315 pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, cores2threads(m_cpuFeatures.count), EXPECTED_TOOL_COUNT));
316 /* qWarning("Using %u threads for extraction.", pool->maxThreadCount()); */
318 LockedFile::selfTest();
319 ExtractorTask::clearFlags();
321 const long long timeExtractStart = lamexp_perfcounter_value();
323 //Extract all files
324 while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
326 const QString toolName = queueToolName.dequeue();
327 const QString checksum = queueChecksum.dequeue();
328 const QString versInfo = queueVersInfo.dequeue();
329 const unsigned int cpuType = queueCpuTypes.dequeue();
330 const unsigned int version = queueVersions.dequeue();
332 const QByteArray toolHash(checksum.toLatin1());
333 if(toolHash.size() != 96)
335 qFatal("The checksum for \"%s\" has an invalid size!", QUTF8(toolName));
336 return -1.0;
339 QResource *resource = new QResource(QString(":/tools/%1").arg(toolName));
340 if(!(resource->isValid() && resource->data()))
342 LAMEXP_DELETE(resource);
343 qFatal("The resource for \"%s\" could not be found!", QUTF8(toolName));
344 return -1.0;
347 if(cpuType & cpuSupport)
349 pool->start(new ExtractorTask(resource, appDir, toolName, toolHash, version, versInfo));
350 continue;
353 LAMEXP_DELETE(resource);
356 //Sanity Check
357 if(!(queueToolName.isEmpty() && queueChecksum.isEmpty() && queueVersInfo.isEmpty() && queueCpuTypes.isEmpty() && queueVersions.isEmpty()))
359 qFatal("Checksum queues *not* empty fater verification completed. Take care!");
362 //Wait for extrator threads to finish
363 pool->waitForDone();
364 LAMEXP_DELETE(pool);
366 const long long timeExtractEnd = lamexp_perfcounter_value();
368 //Make sure all files were extracted correctly
369 if(ExtractorTask::getExcept())
371 char errorMsg[BUFF_SIZE];
372 if(ExtractorTask::getErrMsg(errorMsg, BUFF_SIZE))
374 qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
375 return -1.0;
377 qFatal("At least one of the required tools could not be initialized!");
378 return -1.0;
381 qDebug("All extracted.\n");
383 //Using any custom tools?
384 if(ExtractorTask::getCustom())
386 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
389 //Check delay
390 const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(lamexp_perfcounter_frequ());
391 if(delayExtract > g_allowedExtractDelay)
393 m_slowIndicator = true;
394 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
395 qWarning("Please report performance problems to your anti-virus developer !!!\n");
397 else
399 qDebug("Extracting the tools took %.5f seconds (OK).\n", delayExtract);
402 //Register all translations
403 initTranslations();
405 //Look for AAC encoders
406 initNeroAac();
407 initFhgAac();
408 initQAac();
410 m_bSuccess = true;
411 delay();
413 return delayExtract;
416 void InitializationThread::runBenchmark(void)
418 #ifdef ENABLE_BENCHMARK
419 static const size_t nLoops = 5;
420 const size_t maxThreads = (5 * m_cpuFeatures.count);
421 QMap<size_t, double> results;
423 for(size_t c = 1; c <= maxThreads; c++)
425 QList<double> delayLst;
426 double delayAvg = 0.0;
427 for(size_t i = 0; i < nLoops; i++)
429 delayLst << doInit(c);
430 lamexp_clean_all_tools();
432 qSort(delayLst.begin(), delayLst.end());
433 delayLst.takeLast();
434 delayLst.takeFirst();
435 for(QList<double>::ConstIterator iter = delayLst.constBegin(); iter != delayLst.constEnd(); iter++)
437 delayAvg += (*iter);
439 results.insert(c, (delayAvg / double(delayLst.count())));
442 qWarning("\n----------------------------------------------");
443 qWarning("Benchmark Results:");
444 qWarning("----------------------------------------------");
446 double bestTime = DBL_MAX; size_t bestVal = 0;
447 QList<size_t> keys = results.keys();
448 for(QList<size_t>::ConstIterator iter = keys.begin(); iter != keys.end(); iter++)
450 const double time = results.value((*iter), DBL_MAX);
451 qWarning("%02u -> %7.4f", (*iter), time);
452 if(time < bestTime)
454 bestTime = time;
455 bestVal = (*iter);
459 qWarning("----------------------------------------------");
460 qWarning("BEST: %u of %u (factor: %7.4f)", bestVal, m_cpuFeatures.count, (double(bestVal) / double(m_cpuFeatures.count)));
461 qWarning("----------------------------------------------\n");
463 qFatal("Benchmark complete. Thanks and bye bye!");
464 #else //ENABLE_BENCHMARK
465 THROW("Sorry, the benchmark is *not* available in this build!");
466 #endif //ENABLE_BENCHMARK
469 ////////////////////////////////////////////////////////////
470 // PUBLIC FUNCTIONS
471 ////////////////////////////////////////////////////////////
473 void InitializationThread::delay(void)
475 lamexp_sleep(333);
478 void InitializationThread::initTranslations(void)
480 //Search for language files
481 QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
483 //Make sure we found at least one translation
484 if(qmFiles.count() < 1)
486 qFatal("Could not find any translation files!");
487 return;
490 //Add all available translations
491 while(!qmFiles.isEmpty())
493 QString langId, langName;
494 unsigned int systemId = 0, country = 0;
495 QString qmFile = qmFiles.takeFirst();
497 QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
498 if(langIdExp.indexIn(qmFile) >= 0)
500 langId = langIdExp.cap(1).toLower();
501 QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
502 if(langRes.isValid() && langRes.size() > 0)
504 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
505 QTextStream stream(&data, QIODevice::ReadOnly);
506 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
507 while(!stream.atEnd())
509 QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
510 if(langInfo.count() == 3)
512 systemId = langInfo.at(0).trimmed().toUInt();
513 country = langInfo.at(1).trimmed().toUInt();
514 langName = langInfo.at(2).trimmed();
515 break;
521 if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
523 if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
525 qDebug("Registering translation: %s = %s (%u) [%u]", QUTF8(qmFile), QUTF8(langName), systemId, country);
527 else
529 qWarning("Failed to register: %s", qmFile.toLatin1().constData());
534 qDebug("All registered.\n");
537 void InitializationThread::initNeroAac(void)
539 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
541 QFileInfo neroFileInfo[3];
542 neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
543 neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
544 neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
546 bool neroFilesFound = true;
547 for(int i = 0; i < 3; i++) { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
549 if(!neroFilesFound)
551 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
552 return;
555 for(int i = 0; i < 3; i++)
557 if(!lamexp_is_executable(neroFileInfo[i].canonicalFilePath()))
559 qDebug("%s executbale is invalid -> AAC encoding support will be disabled!\n", QUTF8(neroFileInfo[i].fileName()));
560 return;
564 qDebug("Found Nero AAC encoder binary:\n%s\n", QUTF8(neroFileInfo[0].canonicalFilePath()));
566 //Lock the Nero binaries
567 LockedFile *neroBin[3];
568 for(int i = 0; i < 3; i++) neroBin[i] = NULL;
572 for(int i = 0; i < 3; i++)
574 neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
577 catch(...)
579 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
580 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
581 return;
584 QProcess process;
585 lamexp_init_process(process, neroFileInfo[0].absolutePath());
587 process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
589 if(!process.waitForStarted())
591 qWarning("Nero process failed to create!");
592 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
593 process.kill();
594 process.waitForFinished(-1);
595 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
596 return;
599 unsigned int neroVersion = 0;
601 while(process.state() != QProcess::NotRunning)
603 if(!process.waitForReadyRead())
605 if(process.state() == QProcess::Running)
607 qWarning("Nero process time out -> killing!");
608 process.kill();
609 process.waitForFinished(-1);
610 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
611 return;
615 while(process.canReadLine())
617 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
618 QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
619 int index1 = tokens.indexOf("Package");
620 int index2 = tokens.indexOf("version:");
621 if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
623 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
624 if(versionTokens.count() == 4)
626 neroVersion = 0;
627 neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
628 neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
629 neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
630 neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
636 if(!(neroVersion > 0))
638 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
639 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
640 return;
643 for(int i = 0; i < 3; i++)
645 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
649 void InitializationThread::initFhgAac(void)
651 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
653 QFileInfo fhgFileInfo[5];
654 fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
655 fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
656 fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
657 fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
658 fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
660 bool fhgFilesFound = true;
661 for(int i = 0; i < 5; i++) { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
663 if(!fhgFilesFound)
665 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
666 return;
669 if(!lamexp_is_executable(fhgFileInfo[0].canonicalFilePath()))
671 qDebug("FhgAacEnc executbale is invalid -> FhgAacEnc support will be disabled!\n");
672 return;
675 qDebug("Found FhgAacEnc cli_exe:\n%s\n", QUTF8(fhgFileInfo[0].canonicalFilePath()));
676 qDebug("Found FhgAacEnc enc_dll:\n%s\n", QUTF8(fhgFileInfo[1].canonicalFilePath()));
678 //Lock the FhgAacEnc binaries
679 LockedFile *fhgBin[5];
680 for(int i = 0; i < 5; i++) fhgBin[i] = NULL;
684 for(int i = 0; i < 5; i++)
686 fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
689 catch(...)
691 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
692 qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
693 return;
696 QProcess process;
697 lamexp_init_process(process, fhgFileInfo[0].absolutePath());
699 process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
701 if(!process.waitForStarted())
703 qWarning("FhgAacEnc process failed to create!");
704 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
705 process.kill();
706 process.waitForFinished(-1);
707 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
708 return;
711 QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
712 unsigned int fhgVersion = 0;
714 while(process.state() != QProcess::NotRunning)
716 process.waitForReadyRead();
717 if(!process.bytesAvailable() && process.state() == QProcess::Running)
719 qWarning("FhgAacEnc process time out -> killing!");
720 process.kill();
721 process.waitForFinished(-1);
722 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
723 return;
725 while(process.bytesAvailable() > 0)
727 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
728 if(fhgAacEncSig.lastIndexIn(line) >= 0)
730 bool ok = false;
731 unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
732 if(ok) fhgVersion = temp;
737 if(!(fhgVersion > 0))
739 qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
740 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
741 return;
743 else if(fhgVersion < lamexp_toolver_fhgaacenc())
745 qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", lamexp_version2string("????-??-??", fhgVersion, "N/A").toLatin1().constData());
746 qWarning("Minimum required FhgAacEnc version currently is: %s\n", lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A").toLatin1().constData());
747 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
748 return;
751 for(int i = 0; i < 5; i++)
753 lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
757 void InitializationThread::initQAac(void)
759 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
761 QFileInfo qaacFileInfo[4];
762 qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
763 qaacFileInfo[1] = QFileInfo(QString("%1/libsoxr.dll").arg(appPath));
764 qaacFileInfo[2] = QFileInfo(QString("%1/libsoxconvolver.dll").arg(appPath));
765 qaacFileInfo[3] = QFileInfo(QString("%1/libgcc_s_sjlj-1.dll").arg(appPath));
767 bool qaacFilesFound = true;
768 for(int i = 0; i < 4; i++) { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
770 if(!qaacFilesFound)
772 qDebug("QAAC binary or companion DLL's not found -> QAAC support will be disabled!\n");
773 return;
776 if(!lamexp_is_executable(qaacFileInfo[0].canonicalFilePath()))
778 qDebug("QAAC executbale is invalid -> QAAC support will be disabled!\n");
779 return;
782 qDebug("Found QAAC encoder:\n%s\n", QUTF8(qaacFileInfo[0].canonicalFilePath()));
784 //Lock the required QAAC binaries
785 LockedFile *qaacBin[4];
786 for(int i = 0; i < 4; i++) qaacBin[i] = NULL;
790 for(int i = 0; i < 4; i++)
792 qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
795 catch(...)
797 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
798 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
799 return;
802 QProcess process;
803 lamexp_init_process(process, qaacFileInfo[0].absolutePath());
805 process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
807 if(!process.waitForStarted())
809 qWarning("QAAC process failed to create!");
810 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
811 process.kill();
812 process.waitForFinished(-1);
813 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
814 return;
817 QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
818 QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
819 QRegExp soxrEncSig("libsoxr-\\d\\.\\d\\.\\d", Qt::CaseInsensitive);
820 QRegExp soxcEncSig("libsoxconvolver \\d\\.\\d\\.\\d", Qt::CaseInsensitive);
822 unsigned int qaacVersion = 0;
823 unsigned int coreVersion = 0;
824 bool soxrFound = false;
825 bool soxcFound = false;
827 while(process.state() != QProcess::NotRunning)
829 process.waitForReadyRead();
830 if(!process.bytesAvailable() && process.state() == QProcess::Running)
832 qWarning("QAAC process time out -> killing!");
833 process.kill();
834 process.waitForFinished(-1);
835 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
836 return;
838 while(process.bytesAvailable() > 0)
840 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
841 if(qaacEncSig.lastIndexIn(line) >= 0)
843 unsigned int tmp[3] = {0, 0, 0};
844 bool ok[3] = {false, false, false};
845 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
846 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
847 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
848 if(ok[0] && ok[1] && ok[2])
850 qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
853 if(coreEncSig.lastIndexIn(line) >= 0)
855 unsigned int tmp[4] = {0, 0, 0, 0};
856 bool ok[4] = {false, false, false, false};
857 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
858 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
859 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
860 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
861 if(ok[0] && ok[1] && ok[2] && ok[3])
863 coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
866 if(soxcEncSig.lastIndexIn(line) >= 0) { soxcFound = true; }
867 if(soxrEncSig.lastIndexIn(line) >= 0) { soxrFound = true; }
871 //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
873 if(!(qaacVersion > 0))
875 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
876 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
877 return;
879 else if(qaacVersion < lamexp_toolver_qaacenc())
881 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
882 qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
883 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
884 return;
887 if(!(coreVersion > 0))
889 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
890 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
891 return;
893 else if(coreVersion < lamexp_toolver_coreaudio())
895 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
896 qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
897 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
898 return;
901 if(!(soxrFound && soxcFound))
903 qWarning("libsoxr and/or libsoxconvolver not available -> QAAC support will be disabled!\n");
904 return;
907 lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
908 lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
909 lamexp_register_tool(qaacFileInfo[2].fileName(), qaacBin[2], qaacVersion);
910 lamexp_register_tool(qaacFileInfo[3].fileName(), qaacBin[3], qaacVersion);
913 void InitializationThread::selfTest(void)
915 const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
917 LockedFile::selfTest();
919 for(size_t k = 0; k < 4; k++)
921 qDebug("[TEST]");
922 switch(cpu[k])
924 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
925 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
926 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
927 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
928 default: THROW("CPU support undefined!");
930 unsigned int n = 0;
931 for(int i = 0; true; i++)
933 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
935 break;
937 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
939 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
940 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
941 if(g_lamexp_tools[i].uiCpuType & cpu[k])
943 qDebug("%02i -> %s", ++n, QUTF8(toolName));
944 QFile resource(QString(":/tools/%1").arg(toolName));
945 if(!resource.open(QIODevice::ReadOnly))
947 qFatal("The resource for \"%s\" could not be opened!", QUTF8(toolName));
948 break;
950 QByteArray hash = LockedFile::fileHash(resource);
951 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
953 qFatal("Hash check for tool \"%s\" has failed!", QUTF8(toolName));
954 break;
956 resource.close();
959 else
961 qFatal("Inconsistent checksum data detected. Take care!");
964 if(n != EXPECTED_TOOL_COUNT)
966 qFatal("Tool count mismatch for CPU type %u !!!", cpu[k]);
968 qDebug("Done.\n");
972 ////////////////////////////////////////////////////////////
973 // EVENTS
974 ////////////////////////////////////////////////////////////
976 /*NONE*/