Added function to calculate the number threads from the number of cores. This functio...
[LameXP.git] / src / Thread_Initialization.cpp
blob0912e276eda7776bebc5aa5b616fd343f9083589
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 void lamexp_clean_all_tools(void);
225 #else //ENABLE_BENCHMARK
226 #define DO_INIT_FUNCT doInit
227 #endif //ENABLE_BENCHMARK
229 void InitializationThread::run(void)
233 DO_INIT_FUNCT();
235 catch(const std::exception &error)
237 fflush(stdout); fflush(stderr);
238 fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
239 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
241 catch(...)
243 fflush(stdout); fflush(stderr);
244 fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
245 lamexp_fatal_exit(L"Unhandeled C++ exception error, application will exit!");
249 double InitializationThread::doInit(const size_t threadCount)
251 m_bSuccess = false;
252 delay();
254 //CPU type selection
255 unsigned int cpuSupport = 0;
256 if(m_cpuFeatures.sse && m_cpuFeatures.sse2 && m_cpuFeatures.intel)
258 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_SSE : CPU_TYPE_X86_SSE;
260 else
262 cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64_GEN : CPU_TYPE_X86_GEN;
265 //Hack to disable x64 on Wine, as x64 binaries won't run under Wine (tested with Wine 1.4 under Ubuntu 12.04 x64)
266 if(cpuSupport & CPU_TYPE_X64_ALL)
268 if(lamexp_detect_wine())
270 qWarning("Running under Wine on a 64-Bit system. Going to disable all x64 support!\n");
271 cpuSupport = (cpuSupport == CPU_TYPE_X64_SSE) ? CPU_TYPE_X86_SSE : CPU_TYPE_X86_GEN;
275 //Print selected CPU type
276 switch(cpuSupport)
278 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
279 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
280 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
281 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
282 default: THROW("CPU support undefined!");
285 //Allocate queues
286 QQueue<QString> queueToolName;
287 QQueue<QString> queueChecksum;
288 QQueue<QString> queueVersInfo;
289 QQueue<unsigned int> queueVersions;
290 QQueue<unsigned int> queueCpuTypes;
292 //Init properties
293 for(int i = 0; true; i++)
295 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
297 break;
299 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
301 queueToolName.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcName));
302 queueChecksum.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcHash));
303 queueVersInfo.enqueue(QString::fromLatin1(g_lamexp_tools[i].pcVersTag));
304 queueCpuTypes.enqueue(g_lamexp_tools[i].uiCpuType);
305 queueVersions.enqueue(g_lamexp_tools[i].uiVersion);
307 else
309 qFatal("Inconsistent checksum data detected. Take care!");
313 QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
315 QThreadPool *pool = new QThreadPool();
316 pool->setMaxThreadCount((threadCount > 0) ? threadCount : qBound(2U, cores2threads(m_cpuFeatures.count), EXPECTED_TOOL_COUNT));
317 //qWarning("Using %u threads for extraction.", pool->maxThreadCount());
319 LockedFile::selfTest();
320 ExtractorTask::clearFlags();
322 const long long timeExtractStart = lamexp_perfcounter_value();
324 //Extract all files
325 while(!(queueToolName.isEmpty() || queueChecksum.isEmpty() || queueVersInfo.isEmpty() || queueCpuTypes.isEmpty() || queueVersions.isEmpty()))
327 const QString toolName = queueToolName.dequeue();
328 const QString checksum = queueChecksum.dequeue();
329 const QString versInfo = queueVersInfo.dequeue();
330 const unsigned int cpuType = queueCpuTypes.dequeue();
331 const unsigned int version = queueVersions.dequeue();
333 const QByteArray toolHash(checksum.toLatin1());
334 if(toolHash.size() != 96)
336 qFatal("The checksum for \"%s\" has an invalid size!", QUTF8(toolName));
337 return -1.0;
340 QResource *resource = new QResource(QString(":/tools/%1").arg(toolName));
341 if(!(resource->isValid() && resource->data()))
343 LAMEXP_DELETE(resource);
344 qFatal("The resource for \"%s\" could not be found!", QUTF8(toolName));
345 return -1.0;
348 if(cpuType & cpuSupport)
350 pool->start(new ExtractorTask(resource, appDir, toolName, toolHash, version, versInfo));
351 continue;
354 LAMEXP_DELETE(resource);
357 //Sanity Check
358 if(!(queueToolName.isEmpty() && queueChecksum.isEmpty() && queueVersInfo.isEmpty() && queueCpuTypes.isEmpty() && queueVersions.isEmpty()))
360 qFatal("Checksum queues *not* empty fater verification completed. Take care!");
363 //Wait for extrator threads to finish
364 pool->waitForDone();
365 LAMEXP_DELETE(pool);
367 const long long timeExtractEnd = lamexp_perfcounter_value();
369 //Make sure all files were extracted correctly
370 if(ExtractorTask::getExcept())
372 char errorMsg[BUFF_SIZE];
373 if(ExtractorTask::getErrMsg(errorMsg, BUFF_SIZE))
375 qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
376 return -1.0;
378 qFatal("At least one of the required tools could not be initialized!");
379 return -1.0;
382 qDebug("All extracted.\n");
384 //Using any custom tools?
385 if(ExtractorTask::getCustom())
387 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
390 //Check delay
391 const double delayExtract = static_cast<double>(timeExtractEnd - timeExtractStart) / static_cast<double>(lamexp_perfcounter_frequ());
392 if(delayExtract > g_allowedExtractDelay)
394 m_slowIndicator = true;
395 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
396 qWarning("Please report performance problems to your anti-virus developer !!!\n");
398 else
400 qDebug("Extracting the tools took %.5f seconds (OK).\n", delayExtract);
403 //Register all translations
404 initTranslations();
406 //Look for AAC encoders
407 initNeroAac();
408 initFhgAac();
409 initQAac();
411 m_bSuccess = true;
412 delay();
414 return delayExtract;
417 void InitializationThread::runBenchmark(void)
419 #ifdef ENABLE_BENCHMARK
420 static const size_t nLoops = 5;
421 const size_t maxThreads = (5 * m_cpuFeatures.count);
422 QMap<size_t, double> results;
424 for(size_t c = 1; c <= maxThreads; c++)
426 QList<double> delayLst;
427 double delayAvg = 0.0;
428 for(size_t i = 0; i < nLoops; i++)
430 delayLst << doInit(c);
431 lamexp_clean_all_tools();
433 qSort(delayLst.begin(), delayLst.end());
434 delayLst.takeLast();
435 delayLst.takeFirst();
436 for(QList<double>::ConstIterator iter = delayLst.constBegin(); iter != delayLst.constEnd(); iter++)
438 delayAvg += (*iter);
440 results.insert(c, (delayAvg / double(delayLst.count())));
443 qWarning("\n----------------------------------------------");
444 qWarning("Benchmark Results:");
445 qWarning("----------------------------------------------");
447 double bestTime = DBL_MAX; size_t bestVal = 0;
448 QList<size_t> keys = results.keys();
449 for(QList<size_t>::ConstIterator iter = keys.begin(); iter != keys.end(); iter++)
451 const double time = results.value((*iter), DBL_MAX);
452 qWarning("%02u -> %7.4f", (*iter), time);
453 if(time < bestTime)
455 bestTime = time;
456 bestVal = (*iter);
460 qWarning("----------------------------------------------");
461 qWarning("BEST: %u of %u (factor: %7.4f)", bestVal, m_cpuFeatures.count, (double(bestVal) / double(m_cpuFeatures.count)));
462 qWarning("----------------------------------------------\n");
464 qFatal("Benchmark complete. Thanks and bye bye!");
465 #else //ENABLE_BENCHMARK
466 THROW("Sorry, the benchmark is *not* available in this build!");
467 #endif //ENABLE_BENCHMARK
470 ////////////////////////////////////////////////////////////
471 // PUBLIC FUNCTIONS
472 ////////////////////////////////////////////////////////////
474 void InitializationThread::delay(void)
476 __noop();
479 void InitializationThread::initTranslations(void)
481 //Search for language files
482 QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
484 //Make sure we found at least one translation
485 if(qmFiles.count() < 1)
487 qFatal("Could not find any translation files!");
488 return;
491 //Add all available translations
492 while(!qmFiles.isEmpty())
494 QString langId, langName;
495 unsigned int systemId = 0, country = 0;
496 QString qmFile = qmFiles.takeFirst();
498 QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
499 if(langIdExp.indexIn(qmFile) >= 0)
501 langId = langIdExp.cap(1).toLower();
502 QResource langRes = QResource(QString(":/localization/%1.txt").arg(qmFile));
503 if(langRes.isValid() && langRes.size() > 0)
505 QByteArray data = QByteArray::fromRawData(reinterpret_cast<const char*>(langRes.data()), langRes.size());
506 QTextStream stream(&data, QIODevice::ReadOnly);
507 stream.setAutoDetectUnicode(false); stream.setCodec("UTF-8");
508 while(!stream.atEnd())
510 QStringList langInfo = stream.readLine().simplified().split(",", QString::SkipEmptyParts);
511 if(langInfo.count() == 3)
513 systemId = langInfo.at(0).trimmed().toUInt();
514 country = langInfo.at(1).trimmed().toUInt();
515 langName = langInfo.at(2).trimmed();
516 break;
522 if(!(langId.isEmpty() || langName.isEmpty() || systemId == 0))
524 if(lamexp_translation_register(langId, qmFile, langName, systemId, country))
526 qDebug("Registering translation: %s = %s (%u) [%u]", QUTF8(qmFile), QUTF8(langName), systemId, country);
528 else
530 qWarning("Failed to register: %s", qmFile.toLatin1().constData());
535 qDebug("All registered.\n");
538 void InitializationThread::initNeroAac(void)
540 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
542 QFileInfo neroFileInfo[3];
543 neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
544 neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
545 neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
547 bool neroFilesFound = true;
548 for(int i = 0; i < 3; i++) { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
550 //Lock the Nero binaries
551 if(!neroFilesFound)
553 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
554 return;
557 qDebug("Found Nero AAC encoder binary:\n%s\n", QUTF8(neroFileInfo[0].canonicalFilePath()));
559 LockedFile *neroBin[3];
560 for(int i = 0; i < 3; i++) neroBin[i] = NULL;
564 for(int i = 0; i < 3; i++)
566 neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
569 catch(...)
571 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
572 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
573 return;
576 QProcess process;
577 lamexp_init_process(process, neroFileInfo[0].absolutePath());
579 process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
581 if(!process.waitForStarted())
583 qWarning("Nero process failed to create!");
584 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
585 process.kill();
586 process.waitForFinished(-1);
587 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
588 return;
591 unsigned int neroVersion = 0;
593 while(process.state() != QProcess::NotRunning)
595 if(!process.waitForReadyRead())
597 if(process.state() == QProcess::Running)
599 qWarning("Nero process time out -> killing!");
600 process.kill();
601 process.waitForFinished(-1);
602 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
603 return;
607 while(process.canReadLine())
609 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
610 QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
611 int index1 = tokens.indexOf("Package");
612 int index2 = tokens.indexOf("version:");
613 if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
615 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
616 if(versionTokens.count() == 4)
618 neroVersion = 0;
619 neroVersion += qMin(9, qMax(0, versionTokens.at(3).toInt()));
620 neroVersion += qMin(9, qMax(0, versionTokens.at(2).toInt())) * 10;
621 neroVersion += qMin(9, qMax(0, versionTokens.at(1).toInt())) * 100;
622 neroVersion += qMin(9, qMax(0, versionTokens.at(0).toInt())) * 1000;
628 if(!(neroVersion > 0))
630 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
631 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
632 return;
635 for(int i = 0; i < 3; i++)
637 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
641 void InitializationThread::initFhgAac(void)
643 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
645 QFileInfo fhgFileInfo[5];
646 fhgFileInfo[0] = QFileInfo(QString("%1/fhgaacenc.exe").arg(appPath));
647 fhgFileInfo[1] = QFileInfo(QString("%1/enc_fhgaac.dll").arg(appPath));
648 fhgFileInfo[2] = QFileInfo(QString("%1/nsutil.dll").arg(appPath));
649 fhgFileInfo[3] = QFileInfo(QString("%1/libmp4v2.dll").arg(appPath));
650 fhgFileInfo[4] = QFileInfo(QString("%1/libsndfile-1.dll").arg(appPath));
652 bool fhgFilesFound = true;
653 for(int i = 0; i < 5; i++) { if(!fhgFileInfo[i].exists()) fhgFilesFound = false; }
655 //Lock the FhgAacEnc binaries
656 if(!fhgFilesFound)
658 qDebug("FhgAacEnc binaries not found -> FhgAacEnc support will be disabled!\n");
659 return;
662 qDebug("Found FhgAacEnc cli_exe:\n%s\n", QUTF8(fhgFileInfo[0].canonicalFilePath()));
663 qDebug("Found FhgAacEnc enc_dll:\n%s\n", QUTF8(fhgFileInfo[1].canonicalFilePath()));
665 LockedFile *fhgBin[5];
666 for(int i = 0; i < 5; i++) fhgBin[i] = NULL;
670 for(int i = 0; i < 5; i++)
672 fhgBin[i] = new LockedFile(fhgFileInfo[i].canonicalFilePath());
675 catch(...)
677 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
678 qWarning("Failed to get excluive lock to FhgAacEnc binary -> FhgAacEnc support will be disabled!");
679 return;
682 QProcess process;
683 lamexp_init_process(process, fhgFileInfo[0].absolutePath());
685 process.start(fhgFileInfo[0].canonicalFilePath(), QStringList() << "--version");
687 if(!process.waitForStarted())
689 qWarning("FhgAacEnc process failed to create!");
690 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
691 process.kill();
692 process.waitForFinished(-1);
693 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
694 return;
697 QRegExp fhgAacEncSig("fhgaacenc version (\\d+) by tmkk", Qt::CaseInsensitive);
698 unsigned int fhgVersion = 0;
700 while(process.state() != QProcess::NotRunning)
702 process.waitForReadyRead();
703 if(!process.bytesAvailable() && process.state() == QProcess::Running)
705 qWarning("FhgAacEnc process time out -> killing!");
706 process.kill();
707 process.waitForFinished(-1);
708 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
709 return;
711 while(process.bytesAvailable() > 0)
713 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
714 if(fhgAacEncSig.lastIndexIn(line) >= 0)
716 bool ok = false;
717 unsigned int temp = fhgAacEncSig.cap(1).toUInt(&ok);
718 if(ok) fhgVersion = temp;
723 if(!(fhgVersion > 0))
725 qWarning("FhgAacEnc version couldn't be determined -> FhgAacEnc support will be disabled!");
726 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
727 return;
729 else if(fhgVersion < lamexp_toolver_fhgaacenc())
731 qWarning("FhgAacEnc version is too much outdated (%s) -> FhgAacEnc support will be disabled!", lamexp_version2string("????-??-??", fhgVersion, "N/A").toLatin1().constData());
732 qWarning("Minimum required FhgAacEnc version currently is: %s\n", lamexp_version2string("????-??-??", lamexp_toolver_fhgaacenc(), "N/A").toLatin1().constData());
733 for(int i = 0; i < 5; i++) LAMEXP_DELETE(fhgBin[i]);
734 return;
737 for(int i = 0; i < 5; i++)
739 lamexp_register_tool(fhgFileInfo[i].fileName(), fhgBin[i], fhgVersion);
743 void InitializationThread::initQAac(void)
745 const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
747 QFileInfo qaacFileInfo[2];
748 qaacFileInfo[0] = QFileInfo(QString("%1/qaac.exe").arg(appPath));
749 qaacFileInfo[1] = QFileInfo(QString("%1/libsoxrate.dll").arg(appPath));
751 bool qaacFilesFound = true;
752 for(int i = 0; i < 2; i++) { if(!qaacFileInfo[i].exists()) qaacFilesFound = false; }
754 //Lock the QAAC binaries
755 if(!qaacFilesFound)
757 qDebug("QAAC binaries not found -> QAAC support will be disabled!\n");
758 return;
761 qDebug("Found QAAC encoder:\n%s\n", QUTF8(qaacFileInfo[0].canonicalFilePath()));
763 LockedFile *qaacBin[2];
764 for(int i = 0; i < 2; i++) qaacBin[i] = NULL;
768 for(int i = 0; i < 2; i++)
770 qaacBin[i] = new LockedFile(qaacFileInfo[i].canonicalFilePath());
773 catch(...)
775 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
776 qWarning("Failed to get excluive lock to QAAC binary -> QAAC support will be disabled!");
777 return;
780 QProcess process;
781 lamexp_init_process(process, qaacFileInfo[0].absolutePath());
783 process.start(qaacFileInfo[0].canonicalFilePath(), QStringList() << "--check");
785 if(!process.waitForStarted())
787 qWarning("QAAC process failed to create!");
788 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
789 process.kill();
790 process.waitForFinished(-1);
791 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
792 return;
795 QRegExp qaacEncSig("qaac (\\d)\\.(\\d)(\\d)", Qt::CaseInsensitive);
796 QRegExp coreEncSig("CoreAudioToolbox (\\d)\\.(\\d)\\.(\\d)\\.(\\d)", Qt::CaseInsensitive);
797 unsigned int qaacVersion = 0;
798 unsigned int coreVersion = 0;
800 while(process.state() != QProcess::NotRunning)
802 process.waitForReadyRead();
803 if(!process.bytesAvailable() && process.state() == QProcess::Running)
805 qWarning("QAAC process time out -> killing!");
806 process.kill();
807 process.waitForFinished(-1);
808 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
809 return;
811 while(process.bytesAvailable() > 0)
813 QString line = QString::fromUtf8(process.readLine().constData()).simplified();
814 if(qaacEncSig.lastIndexIn(line) >= 0)
816 unsigned int tmp[3] = {0, 0, 0};
817 bool ok[3] = {false, false, false};
818 tmp[0] = qaacEncSig.cap(1).toUInt(&ok[0]);
819 tmp[1] = qaacEncSig.cap(2).toUInt(&ok[1]);
820 tmp[2] = qaacEncSig.cap(3).toUInt(&ok[2]);
821 if(ok[0] && ok[1] && ok[2])
823 qaacVersion = (qBound(0U, tmp[0], 9U) * 100) + (qBound(0U, tmp[1], 9U) * 10) + qBound(0U, tmp[2], 9U);
826 if(coreEncSig.lastIndexIn(line) >= 0)
828 unsigned int tmp[4] = {0, 0, 0, 0};
829 bool ok[4] = {false, false, false, false};
830 tmp[0] = coreEncSig.cap(1).toUInt(&ok[0]);
831 tmp[1] = coreEncSig.cap(2).toUInt(&ok[1]);
832 tmp[2] = coreEncSig.cap(3).toUInt(&ok[2]);
833 tmp[3] = coreEncSig.cap(4).toUInt(&ok[3]);
834 if(ok[0] && ok[1] && ok[2] && ok[3])
836 coreVersion = (qBound(0U, tmp[0], 9U) * 1000) + (qBound(0U, tmp[1], 9U) * 100) + (qBound(0U, tmp[2], 9U) * 10) + qBound(0U, tmp[3], 9U);
842 //qDebug("qaac %d, CoreAudioToolbox %d", qaacVersion, coreVersion);
844 if(!(qaacVersion > 0))
846 qWarning("QAAC version couldn't be determined -> QAAC support will be disabled!");
847 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
848 return;
850 else if(qaacVersion < lamexp_toolver_qaacenc())
852 qWarning("QAAC version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.??", qaacVersion, "N/A").toLatin1().constData());
853 qWarning("Minimum required QAAC version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_qaacenc(), "N/A").toLatin1().constData());
854 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
855 return;
858 if(!(coreVersion > 0))
860 qWarning("CoreAudioToolbox version couldn't be determined -> QAAC support will be disabled!");
861 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
862 return;
864 else if(coreVersion < lamexp_toolver_coreaudio())
866 qWarning("CoreAudioToolbox version is too much outdated (%s) -> QAAC support will be disabled!", lamexp_version2string("v?.?.?.?", coreVersion, "N/A").toLatin1().constData());
867 qWarning("Minimum required CoreAudioToolbox version currently is: %s.\n", lamexp_version2string("v?.??", lamexp_toolver_coreaudio(), "N/A").toLatin1().constData());
868 for(int i = 0; i < 2; i++) LAMEXP_DELETE(qaacBin[i]);
869 return;
872 lamexp_register_tool(qaacFileInfo[0].fileName(), qaacBin[0], qaacVersion);
873 lamexp_register_tool(qaacFileInfo[1].fileName(), qaacBin[1], qaacVersion);
876 void InitializationThread::selfTest(void)
878 const unsigned int cpu[4] = {CPU_TYPE_X86_GEN, CPU_TYPE_X86_SSE, CPU_TYPE_X64_GEN, CPU_TYPE_X64_SSE};
880 LockedFile::selfTest();
882 for(size_t k = 0; k < 4; k++)
884 qDebug("[TEST]");
885 switch(cpu[k])
887 PRINT_CPU_TYPE(CPU_TYPE_X86_GEN); break;
888 PRINT_CPU_TYPE(CPU_TYPE_X86_SSE); break;
889 PRINT_CPU_TYPE(CPU_TYPE_X64_GEN); break;
890 PRINT_CPU_TYPE(CPU_TYPE_X64_SSE); break;
891 default: THROW("CPU support undefined!");
893 unsigned int n = 0;
894 for(int i = 0; true; i++)
896 if(!(g_lamexp_tools[i].pcName || g_lamexp_tools[i].pcHash || g_lamexp_tools[i].uiVersion))
898 break;
900 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
902 const QString toolName = QString::fromLatin1(g_lamexp_tools[i].pcName);
903 const QByteArray expectedHash = QByteArray(g_lamexp_tools[i].pcHash);
904 if(g_lamexp_tools[i].uiCpuType & cpu[k])
906 qDebug("%02i -> %s", ++n, QUTF8(toolName));
907 QFile resource(QString(":/tools/%1").arg(toolName));
908 if(!resource.open(QIODevice::ReadOnly))
910 qFatal("The resource for \"%s\" could not be opened!", QUTF8(toolName));
911 break;
913 QByteArray hash = LockedFile::fileHash(resource);
914 if(hash.isNull() || _stricmp(hash.constData(), expectedHash.constData()))
916 qFatal("Hash check for tool \"%s\" has failed!", QUTF8(toolName));
917 break;
919 resource.close();
922 else
924 qFatal("Inconsistent checksum data detected. Take care!");
927 if(n != EXPECTED_TOOL_COUNT)
929 qFatal("Tool count mismatch for CPU type %u !!!", cpu[4]);
931 qDebug("Done.\n");
935 ////////////////////////////////////////////////////////////
936 // EVENTS
937 ////////////////////////////////////////////////////////////
939 /*NONE*/