Reorganized global functions: The file "Global.h" was split into multiple file in...
[LameXP.git] / src / Thread_Initialization.cpp
bloba3e03a9009ae13d7355ba9210281f3944857aef4
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, 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 = 27;
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 __noop();
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 //Lock the Nero binaries
550 if(!neroFilesFound)
552 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
553 return;
556 qDebug("Found Nero AAC encoder binary:\n%s\n", QUTF8(neroFileInfo[0].canonicalFilePath()));
558 LockedFile *neroBin[3];
559 for(int i = 0; i < 3; i++) neroBin[i] = NULL;
563 for(int i = 0; i < 3; i++)
565 neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
568 catch(...)
570 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
571 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
572 return;
575 QProcess process;
576 lamexp_init_process(process, neroFileInfo[0].absolutePath());
578 process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
580 if(!process.waitForStarted())
582 qWarning("Nero process failed to create!");
583 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
584 process.kill();
585 process.waitForFinished(-1);
586 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
587 return;
590 unsigned int neroVersion = 0;
592 while(process.state() != QProcess::NotRunning)
594 if(!process.waitForReadyRead())
596 if(process.state() == QProcess::Running)
598 qWarning("Nero process time out -> killing!");
599 process.kill();
600 process.waitForFinished(-1);
601 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
602 return;
606 while(process.canReadLine())
608 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
609 QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
610 int index1 = tokens.indexOf("Package");
611 int index2 = tokens.indexOf("version:");
612 if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
614 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
615 if(versionTokens.count() == 4)
617 neroVersion = 0;
618 neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
619 neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
620 neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
621 neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
627 if(!(neroVersion > 0))
629 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
630 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
631 return;
634 for(int i = 0; i < 3; i++)
636 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
640 void InitializationThread::initFhgAac(void)
642 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
644 QFileInfo fhgFileInfo[5];
645 fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
646 fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
647 fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
648 fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
649 fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
651 bool fhgFilesFound = true;
652 for(int i = 0; i < 5; i++) { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
654 //Lock the FhgAacEnc binaries
655 if(!fhgFilesFound)
657 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
658 return;
661 qDebug("Found FhgAacEnc cli_exe:\n%s\n", QUTF8(fhgFileInfo[0].canonicalFilePath()));
662 qDebug("Found FhgAacEnc enc_dll:\n%s\n", QUTF8(fhgFileInfo[1].canonicalFilePath()));
664 LockedFile *fhgBin[5];
665 for(int i = 0; i < 5; i++) fhgBin[i] = NULL;
669 for(int i = 0; i < 5; i++)
671 fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
674 catch(...)
676 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
677 qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
678 return;
681 QProcess process;
682 lamexp_init_process(process, fhgFileInfo[0].absolutePath());
684 process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
686 if(!process.waitForStarted())
688 qWarning("FhgAacEnc process failed to create!");
689 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
690 process.kill();
691 process.waitForFinished(-1);
692 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
693 return;
696 QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
697 unsigned int fhgVersion = 0;
699 while(process.state() != QProcess::NotRunning)
701 process.waitForReadyRead();
702 if(!process.bytesAvailable() && process.state() == QProcess::Running)
704 qWarning("FhgAacEnc process time out -> killing!");
705 process.kill();
706 process.waitForFinished(-1);
707 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
708 return;
710 while(process.bytesAvailable() > 0)
712 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
713 if(fhgAacEncSig.lastIndexIn(line) >= 0)
715 bool ok = false;
716 unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
717 if(ok) fhgVersion = temp;
722 if(!(fhgVersion > 0))
724 qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
725 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
726 return;
728 else if(fhgVersion < lamexp_toolver_fhgaacenc())
730 qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", lamexp_version2string("????-??-??", fhgVersion, "N/A").toLatin1().constData());
731 qWarning("Minimum required FhgAacEnc version currently is: %s\n", lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A").toLatin1().constData());
732 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
733 return;
736 for(int i = 0; i < 5; i++)
738 lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
742 void InitializationThread::initQAac(void)
744 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
746 QFileInfo qaacFileInfo[2];
747 qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
748 qaacFileInfo[1] = QFileInfo(QString("%1/libsoxrate.dll").arg(appPath));
750 bool qaacFilesFound = true;
751 for(int i = 0; i < 2; i++) { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
753 //Lock the QAAC binaries
754 if(!qaacFilesFound)
756 qDebug("QAAC binaries not found -> QAAC support will be disabled!\n");
757 return;
760 qDebug("Found QAAC encoder:\n%s\n", QUTF8(qaacFileInfo[0].canonicalFilePath()));
762 LockedFile *qaacBin[2];
763 for(int i = 0; i < 2; i++) qaacBin[i] = NULL;
767 for(int i = 0; i < 2; i++)
769 qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
772 catch(...)
774 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
775 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
776 return;
779 QProcess process;
780 lamexp_init_process(process, qaacFileInfo[0].absolutePath());
782 process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
784 if(!process.waitForStarted())
786 qWarning("QAAC process failed to create!");
787 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
788 process.kill();
789 process.waitForFinished(-1);
790 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
791 return;
794 QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
795 QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
796 unsigned int qaacVersion = 0;
797 unsigned int coreVersion = 0;
799 while(process.state() != QProcess::NotRunning)
801 process.waitForReadyRead();
802 if(!process.bytesAvailable() && process.state() == QProcess::Running)
804 qWarning("QAAC process time out -> killing!");
805 process.kill();
806 process.waitForFinished(-1);
807 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
808 return;
810 while(process.bytesAvailable() > 0)
812 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
813 if(qaacEncSig.lastIndexIn(line) >= 0)
815 unsigned int tmp[3] = {0, 0, 0};
816 bool ok[3] = {false, false, false};
817 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
818 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
819 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
820 if(ok[0] && ok[1] && ok[2])
822 qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
825 if(coreEncSig.lastIndexIn(line) >= 0)
827 unsigned int tmp[4] = {0, 0, 0, 0};
828 bool ok[4] = {false, false, false, false};
829 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
830 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
831 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
832 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
833 if(ok[0] && ok[1] && ok[2] && ok[3])
835 coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
841 //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
843 if(!(qaacVersion > 0))
845 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
846 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
847 return;
849 else if(qaacVersion < lamexp_toolver_qaacenc())
851 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
852 qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
853 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
854 return;
857 if(!(coreVersion > 0))
859 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
860 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
861 return;
863 else if(coreVersion < lamexp_toolver_coreaudio())
865 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
866 qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
867 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
868 return;
871 lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
872 lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
875 void InitializationThread::selfTest(void)
877 const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
879 LockedFile::selfTest();
881 for(size_t k = 0; k < 4; k++)
883 qDebug("[TEST]");
884 switch(cpu[k])
886 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
887 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
888 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
889 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
890 default: THROW("CPU support undefined!");
892 unsigned int n = 0;
893 for(int i = 0; true; i++)
895 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
897 break;
899 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
901 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
902 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
903 if(g_lamexp_tools[i].uiCpuType & cpu[k])
905 qDebug("%02i -> %s", ++n, QUTF8(toolName));
906 QFile resource(QString(":/tools/%1").arg(toolName));
907 if(!resource.open(QIODevice::ReadOnly))
909 qFatal("The resource for \"%s\" could not be opened!", QUTF8(toolName));
910 break;
912 QByteArray hash = LockedFile::fileHash(resource);
913 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
915 qFatal("Hash check for tool \"%s\" has failed!", QUTF8(toolName));
916 break;
918 resource.close();
921 else
923 qFatal("Inconsistent checksum data detected. Take care!");
926 if(n != EXPECTED_TOOL_COUNT)
928 qFatal("Tool count mismatch for CPU type %u !!!", cpu[4]);
930 qDebug("Done.\n");
934 ////////////////////////////////////////////////////////////
935 // EVENTS
936 ////////////////////////////////////////////////////////////
938 /*NONE*/