Fixed MSVC 11.0 (VS2012) project file.
[LameXP.git] / src / Thread_Initialization.cpp
blob23fa83430a9bbbffa9f0334b3bbf11a10576ad4d
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 fflush(stdout); fflush(stderr);
236 fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
237 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
239 catch(...)
241 fflush(stdout); fflush(stderr);
242 fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
243 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
247 double InitializationThread::doInit(const size_t threadCount)
249 m_bSuccess = false;
250 delay();
252 //CPU type selection
253 unsigned int cpuSupport = 0;
254 if(m_cpuFeatures.sse && m_cpuFeatures.sse2 && m_cpuFeatures.intel)
256 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
258 else
260 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
263 //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
264 if(cpuSupport & CPU_TYPE_X64_ALL)
266 if(lamexp_detect_wine())
268 qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
269 cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
273 //Print selected CPU type
274 switch(cpuSupport)
276 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
277 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
278 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
279 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
280 default: THROW("CPU support undefined!");
283 //Allocate queues
284 QQueue<QString> queueToolName;
285 QQueue<QString> queueChecksum;
286 QQueue<QString> queueVersInfo;
287 QQueue<unsigned int> queueVersions;
288 QQueue<unsigned int> queueCpuTypes;
290 //Init properties
291 for(int i = 0; true; i++)
293 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
295 break;
297 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
299 queueToolName.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcName));
300 queueChecksum.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcHash));
301 queueVersInfo.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcVersTag));
302 queueCpuTypes.enqueue(g_lamexp_tools[i].uiCpuType);
303 queueVersions.enqueue(g_lamexp_tools[i].uiVersion);
305 else
307 qFatal("Inconsistent checksum data detected. Take care!");
311 QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
313 QThreadPool *pool = new QThreadPool();
314 pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, cores2threads(m_cpuFeatures.count), EXPECTED_TOOL_COUNT));
315 /* qWarning("Using %u threads for extraction.", pool->maxThreadCount()); */
317 LockedFile::selfTest();
318 ExtractorTask::clearFlags();
320 const long long timeExtractStart = lamexp_perfcounter_value();
322 //Extract all files
323 while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
325 const QString toolName = queueToolName.dequeue();
326 const QString checksum = queueChecksum.dequeue();
327 const QString versInfo = queueVersInfo.dequeue();
328 const unsigned int cpuType = queueCpuTypes.dequeue();
329 const unsigned int version = queueVersions.dequeue();
331 const QByteArray toolHash(checksum.toLatin1());
332 if(toolHash.size() != 96)
334 qFatal("The checksum for \"%s\" has an invalid size!", QUTF8(toolName));
335 return -1.0;
338 QResource *resource = new QResource(QString(":/tools/%1").arg(toolName));
339 if(!(resource->isValid() && resource->data()))
341 LAMEXP_DELETE(resource);
342 qFatal("The resource for \"%s\" could not be found!", QUTF8(toolName));
343 return -1.0;
346 if(cpuType & cpuSupport)
348 pool->start(new ExtractorTask(resource, appDir, toolName, toolHash, version, versInfo));
349 continue;
352 LAMEXP_DELETE(resource);
355 //Sanity Check
356 if(!(queueToolName.isEmpty() && queueChecksum.isEmpty() && queueVersInfo.isEmpty() && queueCpuTypes.isEmpty() && queueVersions.isEmpty()))
358 qFatal("Checksum queues *not* empty fater verification completed. Take care!");
361 //Wait for extrator threads to finish
362 pool->waitForDone();
363 LAMEXP_DELETE(pool);
365 const long long timeExtractEnd = lamexp_perfcounter_value();
367 //Make sure all files were extracted correctly
368 if(ExtractorTask::getExcept())
370 char errorMsg[BUFF_SIZE];
371 if(ExtractorTask::getErrMsg(errorMsg, BUFF_SIZE))
373 qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
374 return -1.0;
376 qFatal("At least one of the required tools could not be initialized!");
377 return -1.0;
380 qDebug("All extracted.\n");
382 //Using any custom tools?
383 if(ExtractorTask::getCustom())
385 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
388 //Check delay
389 const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(lamexp_perfcounter_frequ());
390 if(delayExtract > g_allowedExtractDelay)
392 m_slowIndicator = true;
393 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
394 qWarning("Please report performance problems to your anti-virus developer !!!\n");
396 else
398 qDebug("Extracting the tools took %.5f seconds (OK).\n", delayExtract);
401 //Register all translations
402 initTranslations();
404 //Look for AAC encoders
405 initNeroAac();
406 initFhgAac();
407 initQAac();
409 m_bSuccess = true;
410 delay();
412 return delayExtract;
415 void InitializationThread::runBenchmark(void)
417 #ifdef ENABLE_BENCHMARK
418 static const size_t nLoops = 5;
419 const size_t maxThreads = (5 * m_cpuFeatures.count);
420 QMap<size_t, double> results;
422 for(size_t c = 1; c <= maxThreads; c++)
424 QList<double> delayLst;
425 double delayAvg = 0.0;
426 for(size_t i = 0; i < nLoops; i++)
428 delayLst << doInit(c);
429 lamexp_clean_all_tools();
431 qSort(delayLst.begin(), delayLst.end());
432 delayLst.takeLast();
433 delayLst.takeFirst();
434 for(QList<double>::ConstIterator iter = delayLst.constBegin(); iter != delayLst.constEnd(); iter++)
436 delayAvg += (*iter);
438 results.insert(c, (delayAvg / double(delayLst.count())));
441 qWarning("\n----------------------------------------------");
442 qWarning("Benchmark Results:");
443 qWarning("----------------------------------------------");
445 double bestTime = DBL_MAX; size_t bestVal = 0;
446 QList<size_t> keys = results.keys();
447 for(QList<size_t>::ConstIterator iter = keys.begin(); iter != keys.end(); iter++)
449 const double time = results.value((*iter), DBL_MAX);
450 qWarning("%02u -> %7.4f", (*iter), time);
451 if(time < bestTime)
453 bestTime = time;
454 bestVal = (*iter);
458 qWarning("----------------------------------------------");
459 qWarning("BEST: %u of %u (factor: %7.4f)", bestVal, m_cpuFeatures.count, (double(bestVal) / double(m_cpuFeatures.count)));
460 qWarning("----------------------------------------------\n");
462 qFatal("Benchmark complete. Thanks and bye bye!");
463 #else //ENABLE_BENCHMARK
464 THROW("Sorry, the benchmark is *not* available in this build!");
465 #endif //ENABLE_BENCHMARK
468 ////////////////////////////////////////////////////////////
469 // PUBLIC FUNCTIONS
470 ////////////////////////////////////////////////////////////
472 void InitializationThread::delay(void)
474 lamexp_sleep(333);
477 void InitializationThread::initTranslations(void)
479 //Search for language files
480 QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
482 //Make sure we found at least one translation
483 if(qmFiles.count() < 1)
485 qFatal("Could not find any translation files!");
486 return;
489 //Add all available translations
490 while(!qmFiles.isEmpty())
492 QString langId, langName;
493 unsigned int systemId = 0, country = 0;
494 QString qmFile = qmFiles.takeFirst();
496 QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
497 if(langIdExp.indexIn(qmFile) >= 0)
499 langId = langIdExp.cap(1).toLower();
500 QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
501 if(langRes.isValid() && langRes.size() > 0)
503 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
504 QTextStream stream(&data, QIODevice::ReadOnly);
505 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
506 while(!stream.atEnd())
508 QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
509 if(langInfo.count() == 3)
511 systemId = langInfo.at(0).trimmed().toUInt();
512 country = langInfo.at(1).trimmed().toUInt();
513 langName = langInfo.at(2).trimmed();
514 break;
520 if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
522 if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
524 qDebug("Registering translation: %s = %s (%u) [%u]", QUTF8(qmFile), QUTF8(langName), systemId, country);
526 else
528 qWarning("Failed to register: %s", qmFile.toLatin1().constData());
533 qDebug("All registered.\n");
536 void InitializationThread::initNeroAac(void)
538 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
540 QFileInfo neroFileInfo[3];
541 neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
542 neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
543 neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
545 bool neroFilesFound = true;
546 for(int i = 0; i < 3; i++) { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
548 if(!neroFilesFound)
550 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
551 return;
554 for(int i = 0; i < 3; i++)
556 if(!lamexp_is_executable(neroFileInfo[i].canonicalFilePath()))
558 qDebug("%s executbale is invalid -> AAC encoding support will be disabled!\n", QUTF8(neroFileInfo[i].fileName()));
559 return;
563 qDebug("Found Nero AAC encoder binary:\n%s\n", QUTF8(neroFileInfo[0].canonicalFilePath()));
565 //Lock the Nero binaries
566 LockedFile *neroBin[3];
567 for(int i = 0; i < 3; i++) neroBin[i] = NULL;
571 for(int i = 0; i < 3; i++)
573 neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
576 catch(...)
578 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
579 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
580 return;
583 QProcess process;
584 lamexp_init_process(process, neroFileInfo[0].absolutePath());
586 process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
588 if(!process.waitForStarted())
590 qWarning("Nero process failed to create!");
591 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
592 process.kill();
593 process.waitForFinished(-1);
594 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
595 return;
598 unsigned int neroVersion = 0;
600 while(process.state() != QProcess::NotRunning)
602 if(!process.waitForReadyRead())
604 if(process.state() == QProcess::Running)
606 qWarning("Nero process time out -> killing!");
607 process.kill();
608 process.waitForFinished(-1);
609 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
610 return;
614 while(process.canReadLine())
616 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
617 QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
618 int index1 = tokens.indexOf("Package");
619 int index2 = tokens.indexOf("version:");
620 if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
622 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
623 if(versionTokens.count() == 4)
625 neroVersion = 0;
626 neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
627 neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
628 neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
629 neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
635 if(!(neroVersion > 0))
637 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
638 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
639 return;
642 for(int i = 0; i < 3; i++)
644 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
648 void InitializationThread::initFhgAac(void)
650 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
652 QFileInfo fhgFileInfo[5];
653 fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
654 fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
655 fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
656 fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
657 fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
659 bool fhgFilesFound = true;
660 for(int i = 0; i < 5; i++) { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
662 if(!fhgFilesFound)
664 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
665 return;
668 if(!lamexp_is_executable(fhgFileInfo[0].canonicalFilePath()))
670 qDebug("FhgAacEnc executbale is invalid -> FhgAacEnc support will be disabled!\n");
671 return;
674 qDebug("Found FhgAacEnc cli_exe:\n%s\n", QUTF8(fhgFileInfo[0].canonicalFilePath()));
675 qDebug("Found FhgAacEnc enc_dll:\n%s\n", QUTF8(fhgFileInfo[1].canonicalFilePath()));
677 //Lock the FhgAacEnc binaries
678 LockedFile *fhgBin[5];
679 for(int i = 0; i < 5; i++) fhgBin[i] = NULL;
683 for(int i = 0; i < 5; i++)
685 fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
688 catch(...)
690 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
691 qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
692 return;
695 QProcess process;
696 lamexp_init_process(process, fhgFileInfo[0].absolutePath());
698 process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
700 if(!process.waitForStarted())
702 qWarning("FhgAacEnc process failed to create!");
703 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
704 process.kill();
705 process.waitForFinished(-1);
706 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
707 return;
710 QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
711 unsigned int fhgVersion = 0;
713 while(process.state() != QProcess::NotRunning)
715 process.waitForReadyRead();
716 if(!process.bytesAvailable() && process.state() == QProcess::Running)
718 qWarning("FhgAacEnc process time out -> killing!");
719 process.kill();
720 process.waitForFinished(-1);
721 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
722 return;
724 while(process.bytesAvailable() > 0)
726 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
727 if(fhgAacEncSig.lastIndexIn(line) >= 0)
729 bool ok = false;
730 unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
731 if(ok) fhgVersion = temp;
736 if(!(fhgVersion > 0))
738 qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
739 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
740 return;
742 else if(fhgVersion < lamexp_toolver_fhgaacenc())
744 qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", lamexp_version2string("????-??-??", fhgVersion, "N/A").toLatin1().constData());
745 qWarning("Minimum required FhgAacEnc version currently is: %s\n", lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A").toLatin1().constData());
746 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
747 return;
750 for(int i = 0; i < 5; i++)
752 lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
756 void InitializationThread::initQAac(void)
758 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
760 QFileInfo qaacFileInfo[4];
761 qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
762 qaacFileInfo[1] = QFileInfo(QString("%1/libsoxr.dll").arg(appPath));
763 qaacFileInfo[2] = QFileInfo(QString("%1/libsoxconvolver.dll").arg(appPath));
764 qaacFileInfo[3] = QFileInfo(QString("%1/libgcc_s_sjlj-1.dll").arg(appPath));
766 bool qaacFilesFound = true;
767 for(int i = 0; i < 4; i++) { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
769 if(!qaacFilesFound)
771 qDebug("QAAC binary or companion DLL's not found -> QAAC support will be disabled!\n");
772 return;
775 if(!lamexp_is_executable(qaacFileInfo[0].canonicalFilePath()))
777 qDebug("QAAC executbale is invalid -> QAAC support will be disabled!\n");
778 return;
781 qDebug("Found QAAC encoder:\n%s\n", QUTF8(qaacFileInfo[0].canonicalFilePath()));
783 //Lock the required QAAC binaries
784 LockedFile *qaacBin[4];
785 for(int i = 0; i < 4; i++) qaacBin[i] = NULL;
789 for(int i = 0; i < 4; i++)
791 qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
794 catch(...)
796 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
797 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
798 return;
801 QProcess process;
802 lamexp_init_process(process, qaacFileInfo[0].absolutePath());
804 process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
806 if(!process.waitForStarted())
808 qWarning("QAAC process failed to create!");
809 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
810 process.kill();
811 process.waitForFinished(-1);
812 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
813 return;
816 QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
817 QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
818 QRegExp soxrEncSig("libsoxr-\\d\\.\\d\\.\\d", Qt::CaseInsensitive);
819 QRegExp soxcEncSig("libsoxconvolver \\d\\.\\d\\.\\d", Qt::CaseInsensitive);
821 unsigned int qaacVersion = 0;
822 unsigned int coreVersion = 0;
823 bool soxrFound = false;
824 bool soxcFound = false;
826 while(process.state() != QProcess::NotRunning)
828 process.waitForReadyRead();
829 if(!process.bytesAvailable() && process.state() == QProcess::Running)
831 qWarning("QAAC process time out -> killing!");
832 process.kill();
833 process.waitForFinished(-1);
834 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
835 return;
837 while(process.bytesAvailable() > 0)
839 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
840 if(qaacEncSig.lastIndexIn(line) >= 0)
842 unsigned int tmp[3] = {0, 0, 0};
843 bool ok[3] = {false, false, false};
844 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
845 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
846 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
847 if(ok[0] && ok[1] && ok[2])
849 qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
852 if(coreEncSig.lastIndexIn(line) >= 0)
854 unsigned int tmp[4] = {0, 0, 0, 0};
855 bool ok[4] = {false, false, false, false};
856 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
857 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
858 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
859 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
860 if(ok[0] && ok[1] && ok[2] && ok[3])
862 coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
865 if(soxcEncSig.lastIndexIn(line) >= 0) { soxcFound = true; }
866 if(soxrEncSig.lastIndexIn(line) >= 0) { soxrFound = true; }
870 //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
872 if(!(qaacVersion > 0))
874 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
875 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
876 return;
878 else if(qaacVersion < lamexp_toolver_qaacenc())
880 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
881 qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
882 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
883 return;
886 if(!(coreVersion > 0))
888 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
889 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
890 return;
892 else if(coreVersion < lamexp_toolver_coreaudio())
894 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
895 qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
896 for(int i = 0; i < 4; i++) LAMEXP_DELETE(qaacBin[i]);
897 return;
900 if(!(soxrFound && soxcFound))
902 qWarning("libsoxr and/or libsoxconvolver not available -> QAAC support will be disabled!\n");
903 return;
906 lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
907 lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
908 lamexp_register_tool(qaacFileInfo[2].fileName(), qaacBin[2], qaacVersion);
909 lamexp_register_tool(qaacFileInfo[3].fileName(), qaacBin[3], qaacVersion);
912 void InitializationThread::selfTest(void)
914 const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
916 LockedFile::selfTest();
918 for(size_t k = 0; k < 4; k++)
920 qDebug("[TEST]");
921 switch(cpu[k])
923 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
924 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
925 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
926 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
927 default: THROW("CPU support undefined!");
929 unsigned int n = 0;
930 for(int i = 0; true; i++)
932 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
934 break;
936 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
938 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
939 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
940 if(g_lamexp_tools[i].uiCpuType & cpu[k])
942 qDebug("%02i -> %s", ++n, QUTF8(toolName));
943 QFile resource(QString(":/tools/%1").arg(toolName));
944 if(!resource.open(QIODevice::ReadOnly))
946 qFatal("The resource for \"%s\" could not be opened!", QUTF8(toolName));
947 break;
949 QByteArray hash = LockedFile::fileHash(resource);
950 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
952 qFatal("Hash check for tool \"%s\" has failed!", QUTF8(toolName));
953 break;
955 resource.close();
958 else
960 qFatal("Inconsistent checksum data detected. Take care!");
963 if(n != EXPECTED_TOOL_COUNT)
965 qFatal("Tool count mismatch for CPU type %u !!!", cpu[k]);
967 qDebug("Done.\n");
971 ////////////////////////////////////////////////////////////
972 // EVENTS
973 ////////////////////////////////////////////////////////////
975 /*NONE*/