Updated MediaInfo binaries to v0.7.70 (2014-09-03), compiled with ICL 15.0 and MSVC...
[LameXP.git] / src / Thread_Initialization.cpp
blob19e5f2f8e56aeb98be295e12f2a786dc1bca122f
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 <QResource>
35 #include <QTextStream>
36 #include <QRunnable>
37 #include <QThreadPool>
38 #include <QMutex>
39 #include <QQueue>
41 /* helper macros */
42 #define PRINT_CPU_TYPE(X) case X: qDebug("Selected CPU is: " #X)
44 /* constants */
45 static const double g_allowedExtractDelay = 12.0;
46 static const size_t BUFF_SIZE = 512;
47 static const size_t EXPECTED_TOOL_COUNT = 28;
49 /* benchmark */
50 #undef ENABLE_BENCHMARK
52 /* number of CPU cores -> number of threads */
53 static unsigned int cores2threads(const unsigned int cores)
55 static const size_t LUT_LEN = 4;
57 static const struct
59 const unsigned int upperBound;
60 const double coeffs[4];
62 LUT[LUT_LEN] =
64 { 4, { -0.052695810565, 0.158087431694, 4.982841530055, -1.088233151184 } },
65 { 8, { 0.042431693989, -0.983442622951, 9.548961748634, -7.176393442623 } },
66 { 12, { -0.006277322404, 0.185573770492, 0.196830601093, 17.762622950820 } },
67 { 32, { 0.000673497268, -0.064655737705, 3.199584699454, 5.751606557377 } }
70 size_t index = 0;
71 while((cores > LUT[index].upperBound) && (index < (LUT_LEN-1))) index++;
73 const double x = qBound(1.0, double(cores), double(LUT[LUT_LEN-1].upperBound));
74 const double y = (LUT[index].coeffs[0] * pow(x, 3.0)) + (LUT[index].coeffs[1] * pow(x, 2.0)) + (LUT[index].coeffs[2] * x) + LUT[index].coeffs[3];
76 return qRound(abs(y));
79 ////////////////////////////////////////////////////////////
80 // ExtractorTask class
81 ////////////////////////////////////////////////////////////
83 class ExtractorTask : public QRunnable
85 public:
86 ExtractorTask(QResource *const toolResource, const QDir &appDir, const QString &toolName, const QByteArray &toolHash, const unsigned int toolVersion, const QString &toolTag)
88 m_appDir(appDir),
89 m_toolName(toolName),
90 m_toolHash(toolHash),
91 m_toolVersion(toolVersion),
92 m_toolTag(toolTag),
93 m_toolResource(toolResource)
95 /* Nothing to do */
98 ~ExtractorTask(void)
100 delete m_toolResource;
103 static void clearFlags(void)
105 QMutexLocker lock(&s_mutex);
106 s_bExcept = false;
107 s_bCustom = false;
108 s_errMsg[0] = char(0);
111 static bool getExcept(void) { bool ret; QMutexLocker lock(&s_mutex); ret = s_bExcept; return ret; }
112 static bool getCustom(void) { bool ret; QMutexLocker lock(&s_mutex); ret = s_bCustom; return ret; }
114 static bool getErrMsg(char *buffer, const size_t buffSize)
116 QMutexLocker lock(&s_mutex);
117 if(s_errMsg[0])
119 strncpy_s(buffer, BUFF_SIZE, s_errMsg, _TRUNCATE);
120 return true;
122 return false;
125 protected:
126 void run(void)
130 if(!getExcept()) doExtract();
132 catch(const std::exception &e)
134 QMutexLocker lock(&s_mutex);
135 if(!s_bExcept)
137 s_bExcept = true;
138 strncpy_s(s_errMsg, BUFF_SIZE, e.what(), _TRUNCATE);
140 lock.unlock();
141 qWarning("ExtractorTask exception error:\n%s\n\n", e.what());
143 catch(...)
145 QMutexLocker lock(&s_mutex);
146 if(!s_bExcept)
148 s_bExcept = true;
149 strncpy_s(s_errMsg, BUFF_SIZE, "Unknown exception error!", _TRUNCATE);
151 lock.unlock();
152 qWarning("ExtractorTask encountered an unknown exception!");
156 void doExtract(void)
158 LockedFile *lockedFile = NULL;
159 unsigned int version = m_toolVersion;
161 QFileInfo toolFileInfo(m_toolName);
162 const QString toolShortName = QString("%1.%2").arg(toolFileInfo.baseName().toLower(), toolFileInfo.suffix().toLower());
164 QFileInfo customTool(QString("%1/tools/%2/%3").arg(m_appDir.canonicalPath(), QString::number(lamexp_version_build()), toolShortName));
165 if(customTool.exists() && customTool.isFile())
167 qDebug("Setting up file: %s <- %s", toolShortName.toLatin1().constData(), m_appDir.relativeFilePath(customTool.canonicalFilePath()).toLatin1().constData());
168 lockedFile = new LockedFile(customTool.canonicalFilePath()); version = UINT_MAX; s_bCustom = true;
170 else
172 qDebug("Extracting file: %s -> %s", m_toolName.toLatin1().constData(), toolShortName.toLatin1().constData());
173 lockedFile = new LockedFile(m_toolResource, QString("%1/lxp_%2").arg(lamexp_temp_folder2(), toolShortName), m_toolHash);
176 if(lockedFile)
178 lamexp_register_tool(toolShortName, lockedFile, version, &m_toolTag);
182 private:
183 QResource *const m_toolResource;
184 const QDir m_appDir;
185 const QString m_toolName;
186 const QByteArray m_toolHash;
187 const unsigned int m_toolVersion;
188 const QString m_toolTag;
190 static volatile bool s_bExcept;
191 static volatile bool s_bCustom;
192 static QMutex s_mutex;
193 static char s_errMsg[BUFF_SIZE];
196 QMutex ExtractorTask::s_mutex;
197 char ExtractorTask::s_errMsg[BUFF_SIZE] = {'\0'};
198 volatile bool ExtractorTask::s_bExcept = false;
199 volatile bool ExtractorTask::s_bCustom = false;
201 ////////////////////////////////////////////////////////////
202 // Constructor
203 ////////////////////////////////////////////////////////////
205 InitializationThread::InitializationThread(const lamexp_cpu_t *cpuFeatures)
207 m_bSuccess = false;
208 memset(&m_cpuFeatures, 0, sizeof(lamexp_cpu_t));
209 m_slowIndicator = false;
211 if(cpuFeatures)
213 memcpy(&m_cpuFeatures, cpuFeatures, sizeof(lamexp_cpu_t));
217 ////////////////////////////////////////////////////////////
218 // Thread Main
219 ////////////////////////////////////////////////////////////
221 #ifdef ENABLE_BENCHMARK
222 #define DO_INIT_FUNCT runBenchmark
223 #else //ENABLE_BENCHMARK
224 #define DO_INIT_FUNCT doInit
225 #endif //ENABLE_BENCHMARK
227 void InitializationThread::run(void)
231 DO_INIT_FUNCT();
233 catch(const std::exception &error)
235 PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
236 lamexp_fatal_exit("Unhandeled C++ exception error, application will exit!");
238 catch(...)
240 PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
241 lamexp_fatal_exit("Unhandeled C++ exception error, application will exit!");
245 double InitializationThread::doInit(const size_t threadCount)
247 m_bSuccess = false;
248 delay();
250 //CPU type selection
251 unsigned int cpuSupport = 0;
252 if(m_cpuFeatures.sse && m_cpuFeatures.sse2 && m_cpuFeatures.intel)
254 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
256 else
258 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
261 //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
262 if(cpuSupport & CPU_TYPE_X64_ALL)
264 if(lamexp_detect_wine())
266 qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
267 cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
271 //Print selected CPU type
272 switch(cpuSupport)
274 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
275 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
276 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
277 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
278 default: THROW("CPU support undefined!");
281 //Allocate queues
282 QQueue<QString> queueToolName;
283 QQueue<QString> queueChecksum;
284 QQueue<QString> queueVersInfo;
285 QQueue<unsigned int> queueVersions;
286 QQueue<unsigned int> queueCpuTypes;
288 //Init properties
289 for(int i = 0; true; i++)
291 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
293 break;
295 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
297 queueToolName.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcName));
298 queueChecksum.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcHash));
299 queueVersInfo.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcVersTag));
300 queueCpuTypes.enqueue(g_lamexp_tools[i].uiCpuType);
301 queueVersions.enqueue(g_lamexp_tools[i].uiVersion);
303 else
305 qFatal("Inconsistent checksum data detected. Take care!");
309 QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
311 QThreadPool *pool = new QThreadPool();
312 pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, cores2threads(m_cpuFeatures.count), EXPECTED_TOOL_COUNT));
313 /* qWarning("Using %u threads for extraction.", pool->maxThreadCount()); */
315 LockedFile::selfTest();
316 ExtractorTask::clearFlags();
318 const long long timeExtractStart = lamexp_perfcounter_value();
320 //Extract all files
321 while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
323 const QString toolName = queueToolName.dequeue();
324 const QString checksum = queueChecksum.dequeue();
325 const QString versInfo = queueVersInfo.dequeue();
326 const unsigned int cpuType = queueCpuTypes.dequeue();
327 const unsigned int version = queueVersions.dequeue();
329 const QByteArray toolHash(checksum.toLatin1());
330 if(toolHash.size() != 96)
332 qFatal("The checksum for \"%s\" has an invalid size!", QUTF8(toolName));
333 return -1.0;
336 QResource *resource = new QResource(QString(":/tools/%1").arg(toolName));
337 if(!(resource->isValid() && resource->data()))
339 LAMEXP_DELETE(resource);
340 qFatal("The resource for \"%s\" could not be found!", QUTF8(toolName));
341 return -1.0;
344 if(cpuType & cpuSupport)
346 pool->start(new ExtractorTask(resource, appDir, toolName, toolHash, version, versInfo));
347 continue;
350 LAMEXP_DELETE(resource);
353 //Sanity Check
354 if(!(queueToolName.isEmpty() && queueChecksum.isEmpty() && queueVersInfo.isEmpty() && queueCpuTypes.isEmpty() && queueVersions.isEmpty()))
356 qFatal("Checksum queues *not* empty fater verification completed. Take care!");
359 //Wait for extrator threads to finish
360 pool->waitForDone();
361 LAMEXP_DELETE(pool);
363 const long long timeExtractEnd = lamexp_perfcounter_value();
365 //Make sure all files were extracted correctly
366 if(ExtractorTask::getExcept())
368 char errorMsg[BUFF_SIZE];
369 if(ExtractorTask::getErrMsg(errorMsg, BUFF_SIZE))
371 qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
372 return -1.0;
374 qFatal("At least one of the required tools could not be initialized!");
375 return -1.0;
378 qDebug("All extracted.\n");
380 //Using any custom tools?
381 if(ExtractorTask::getCustom())
383 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
386 //Check delay
387 const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(lamexp_perfcounter_frequ());
388 if(delayExtract > g_allowedExtractDelay)
390 m_slowIndicator = true;
391 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
392 qWarning("Please report performance problems to your anti-virus developer !!!\n");
394 else
396 qDebug("Extracting the tools took %.5f seconds (OK).\n", delayExtract);
399 //Register all translations
400 initTranslations();
402 //Look for AAC encoders
403 initNeroAac();
404 initFhgAac();
405 initQAac();
407 m_bSuccess = true;
408 delay();
410 return delayExtract;
413 void InitializationThread::runBenchmark(void)
415 #ifdef ENABLE_BENCHMARK
416 static const size_t nLoops = 5;
417 const size_t maxThreads = (5 * m_cpuFeatures.count);
418 QMap<size_t, double> results;
420 for(size_t c = 1; c <= maxThreads; c++)
422 QList<double> delayLst;
423 double delayAvg = 0.0;
424 for(size_t i = 0; i < nLoops; i++)
426 delayLst << doInit(c);
427 lamexp_clean_all_tools();
429 qSort(delayLst.begin(), delayLst.end());
430 delayLst.takeLast();
431 delayLst.takeFirst();
432 for(QList<double>::ConstIterator iter = delayLst.constBegin(); iter != delayLst.constEnd(); iter++)
434 delayAvg += (*iter);
436 results.insert(c, (delayAvg / double(delayLst.count())));
439 qWarning("\n----------------------------------------------");
440 qWarning("Benchmark Results:");
441 qWarning("----------------------------------------------");
443 double bestTime = DBL_MAX; size_t bestVal = 0;
444 QList<size_t> keys = results.keys();
445 for(QList<size_t>::ConstIterator iter = keys.begin(); iter != keys.end(); iter++)
447 const double time = results.value((*iter), DBL_MAX);
448 qWarning("%02u -> %7.4f", (*iter), time);
449 if(time < bestTime)
451 bestTime = time;
452 bestVal = (*iter);
456 qWarning("----------------------------------------------");
457 qWarning("BEST: %u of %u (factor: %7.4f)", bestVal, m_cpuFeatures.count, (double(bestVal) / double(m_cpuFeatures.count)));
458 qWarning("----------------------------------------------\n");
460 qFatal("Benchmark complete. Thanks and bye bye!");
461 #else //ENABLE_BENCHMARK
462 THROW("Sorry, the benchmark is *not* available in this build!");
463 #endif //ENABLE_BENCHMARK
466 ////////////////////////////////////////////////////////////
467 // PUBLIC FUNCTIONS
468 ////////////////////////////////////////////////////////////
470 void InitializationThread::delay(void)
472 lamexp_sleep(333);
475 void InitializationThread::initTranslations(void)
477 //Search for language files
478 QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
480 //Make sure we found at least one translation
481 if(qmFiles.count() < 1)
483 qFatal("Could not find any translation files!");
484 return;
487 //Add all available translations
488 while(!qmFiles.isEmpty())
490 QString langId, langName;
491 unsigned int systemId = 0, country = 0;
492 QString qmFile = qmFiles.takeFirst();
494 QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
495 if(langIdExp.indexIn(qmFile) >= 0)
497 langId = langIdExp.cap(1).toLower();
498 QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
499 if(langRes.isValid() && langRes.size() > 0)
501 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
502 QTextStream stream(&data, QIODevice::ReadOnly);
503 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
504 while(!stream.atEnd())
506 QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
507 if(langInfo.count() == 3)
509 systemId = langInfo.at(0).trimmed().toUInt();
510 country = langInfo.at(1).trimmed().toUInt();
511 langName = langInfo.at(2).trimmed();
512 break;
518 if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
520 if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
522 qDebug("Registering translation: %s = %s (%u) [%u]", QUTF8(qmFile), QUTF8(langName), systemId, country);
524 else
526 qWarning("Failed to register: %s", qmFile.toLatin1().constData());
531 qDebug("All registered.\n");
534 void InitializationThread::initNeroAac(void)
536 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
538 QFileInfo neroFileInfo[3];
539 neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
540 neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
541 neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
543 bool neroFilesFound = true;
544 for(int i = 0; i < 3; i++) { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
546 if(!neroFilesFound)
548 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
549 return;
552 for(int i = 0; i < 3; i++)
554 if(!lamexp_is_executable(neroFileInfo[i].canonicalFilePath()))
556 qDebug("%s executbale is invalid -> AAC encoding support will be disabled!\n", QUTF8(neroFileInfo[i].fileName()));
557 return;
561 qDebug("Found Nero AAC encoder binary:\n%s\n", QUTF8(neroFileInfo[0].canonicalFilePath()));
563 //Lock the Nero binaries
564 LockedFile *neroBin[3];
565 for(int i = 0; i < 3; i++) neroBin[i] = NULL;
569 for(int i = 0; i < 3; i++)
571 neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
574 catch(...)
576 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
577 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
578 return;
581 QProcess process;
582 lamexp_init_process(process, neroFileInfo[0].absolutePath());
584 process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
586 if(!process.waitForStarted())
588 qWarning("Nero process failed to create!");
589 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
590 process.kill();
591 process.waitForFinished(-1);
592 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
593 return;
596 unsigned int neroVersion = 0;
598 while(process.state() != QProcess::NotRunning)
600 if(!process.waitForReadyRead())
602 if(process.state() == QProcess::Running)
604 qWarning("Nero process time out -> killing!");
605 process.kill();
606 process.waitForFinished(-1);
607 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
608 return;
612 while(process.canReadLine())
614 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
615 QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
616 int index1 = tokens.indexOf("Package");
617 int index2 = tokens.indexOf("version:");
618 if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
620 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
621 if(versionTokens.count() == 4)
623 neroVersion = 0;
624 neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
625 neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
626 neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
627 neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
633 if(!(neroVersion > 0))
635 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
636 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
637 return;
640 for(int i = 0; i < 3; i++)
642 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
646 void InitializationThread::initFhgAac(void)
648 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
650 QFileInfo fhgFileInfo[5];
651 fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
652 fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
653 fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
654 fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
655 fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
657 bool fhgFilesFound = true;
658 for(int i = 0; i < 5; i++) { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
660 if(!fhgFilesFound)
662 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
663 return;
666 if(!lamexp_is_executable(fhgFileInfo[0].canonicalFilePath()))
668 qDebug("FhgAacEnc executbale is invalid -> FhgAacEnc support will be disabled!\n");
669 return;
672 qDebug("Found FhgAacEnc cli_exe:\n%s\n", QUTF8(fhgFileInfo[0].canonicalFilePath()));
673 qDebug("Found FhgAacEnc enc_dll:\n%s\n", QUTF8(fhgFileInfo[1].canonicalFilePath()));
675 //Lock the FhgAacEnc binaries
676 LockedFile *fhgBin[5];
677 for(int i = 0; i < 5; i++) fhgBin[i] = NULL;
681 for(int i = 0; i < 5; i++)
683 fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
686 catch(...)
688 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
689 qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
690 return;
693 QProcess process;
694 lamexp_init_process(process, fhgFileInfo[0].absolutePath());
696 process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
698 if(!process.waitForStarted())
700 qWarning("FhgAacEnc process failed to create!");
701 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
702 process.kill();
703 process.waitForFinished(-1);
704 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
705 return;
708 QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
709 unsigned int fhgVersion = 0;
711 while(process.state() != QProcess::NotRunning)
713 process.waitForReadyRead();
714 if(!process.bytesAvailable() && process.state() == QProcess::Running)
716 qWarning("FhgAacEnc process time out -> killing!");
717 process.kill();
718 process.waitForFinished(-1);
719 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
720 return;
722 while(process.bytesAvailable() > 0)
724 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
725 if(fhgAacEncSig.lastIndexIn(line) >= 0)
727 bool ok = false;
728 unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
729 if(ok) fhgVersion = temp;
734 if(!(fhgVersion > 0))
736 qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
737 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
738 return;
740 else if(fhgVersion < lamexp_toolver_fhgaacenc())
742 qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", lamexp_version2string("????-??-??", fhgVersion, "N/A").toLatin1().constData());
743 qWarning("Minimum required FhgAacEnc version currently is: %s\n", lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A").toLatin1().constData());
744 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
745 return;
748 for(int i = 0; i < 5; i++)
750 lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
754 void InitializationThread::initQAac(void)
756 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
758 QFileInfo qaacFileInfo[4];
759 qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
760 qaacFileInfo[1] = QFileInfo(QString("%1/libsoxr.dll").arg(appPath));
761 qaacFileInfo[2] = QFileInfo(QString("%1/libsoxconvolver.dll").arg(appPath));
762 qaacFileInfo[3] = QFileInfo(QString("%1/libgcc_s_sjlj-1.dll").arg(appPath));
764 bool qaacFilesFound = true;
765 for(int i = 0; i < 4; i++) { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
767 if(!qaacFilesFound)
769 qDebug("QAAC binary or companion DLL's not found -> QAAC support will be disabled!\n");
770 return;
773 if(!lamexp_is_executable(qaacFileInfo[0].canonicalFilePath()))
775 qDebug("QAAC executbale is invalid -> QAAC support will be disabled!\n");
776 return;
779 qDebug("Found QAAC encoder:\n%s\n", QUTF8(qaacFileInfo[0].canonicalFilePath()));
781 //Lock the required QAAC binaries
782 LockedFile *qaacBin[4];
783 for(int i = 0; i < 4; i++) qaacBin[i] = NULL;
787 for(int i = 0; i < 4; i++)
789 qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
792 catch(...)
794 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
795 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
796 return;
799 QProcess process;
800 lamexp_init_process(process, qaacFileInfo[0].absolutePath());
802 process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
804 if(!process.waitForStarted())
806 qWarning("QAAC process failed to create!");
807 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
808 process.kill();
809 process.waitForFinished(-1);
810 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
811 return;
814 QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
815 QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
816 QRegExp soxrEncSig("libsoxr-\\d\\.\\d\\.\\d", Qt::CaseInsensitive);
817 QRegExp soxcEncSig("libsoxconvolver \\d\\.\\d\\.\\d", Qt::CaseInsensitive);
819 unsigned int qaacVersion = 0;
820 unsigned int coreVersion = 0;
821 bool soxrFound = false;
822 bool soxcFound = false;
824 while(process.state() != QProcess::NotRunning)
826 process.waitForReadyRead();
827 if(!process.bytesAvailable() && process.state() == QProcess::Running)
829 qWarning("QAAC process time out -> killing!");
830 process.kill();
831 process.waitForFinished(-1);
832 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
833 return;
835 while(process.bytesAvailable() > 0)
837 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
838 if(qaacEncSig.lastIndexIn(line) >= 0)
840 unsigned int tmp[3] = {0, 0, 0};
841 bool ok[3] = {false, false, false};
842 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
843 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
844 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
845 if(ok[0] && ok[1] && ok[2])
847 qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
850 if(coreEncSig.lastIndexIn(line) >= 0)
852 unsigned int tmp[4] = {0, 0, 0, 0};
853 bool ok[4] = {false, false, false, false};
854 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
855 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
856 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
857 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
858 if(ok[0] && ok[1] && ok[2] && ok[3])
860 coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
863 if(soxcEncSig.lastIndexIn(line) >= 0) { soxcFound = true; }
864 if(soxrEncSig.lastIndexIn(line) >= 0) { soxrFound = true; }
868 //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
870 if(!(qaacVersion > 0))
872 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
873 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
874 return;
876 else if(qaacVersion < lamexp_toolver_qaacenc())
878 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
879 qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
880 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
881 return;
884 if(!(coreVersion > 0))
886 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
887 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
888 return;
890 else if(coreVersion < lamexp_toolver_coreaudio())
892 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
893 qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
894 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
895 return;
898 if(!(soxrFound && soxcFound))
900 qWarning("libsoxr and/or libsoxconvolver not available -> QAAC support will be disabled!\n");
901 return;
904 lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
905 lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
906 lamexp_register_tool(qaacFileInfo[2].fileName(), qaacBin[2], qaacVersion);
907 lamexp_register_tool(qaacFileInfo[3].fileName(), qaacBin[3], qaacVersion);
910 void InitializationThread::selfTest(void)
912 const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
914 LockedFile::selfTest();
916 for(size_t k = 0; k < 4; k++)
918 qDebug("[TEST]");
919 switch(cpu[k])
921 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
922 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
923 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
924 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
925 default: THROW("CPU support undefined!");
927 unsigned int n = 0;
928 for(int i = 0; true; i++)
930 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
932 break;
934 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
936 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
937 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
938 if(g_lamexp_tools[i].uiCpuType & cpu[k])
940 qDebug("%02i -> %s", ++n, QUTF8(toolName));
941 QFile resource(QString(":/tools/%1").arg(toolName));
942 if(!resource.open(QIODevice::ReadOnly))
944 qFatal("The resource for \"%s\" could not be opened!", QUTF8(toolName));
945 break;
947 QByteArray hash = LockedFile::fileHash(resource);
948 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
950 qFatal("Hash check for tool \"%s\" has failed!", QUTF8(toolName));
951 break;
953 resource.close();
956 else
958 qFatal("Inconsistent checksum data detected. Take care!");
961 if(n != EXPECTED_TOOL_COUNT)
963 qFatal("Tool count mismatch for CPU type %u !!!", cpu[k]);
965 qDebug("Done.\n");
969 ////////////////////////////////////////////////////////////
970 // EVENTS
971 ////////////////////////////////////////////////////////////
973 /*NONE*/