OSDN Git Service

Added a method to use custom binaries instead of the "built-in" ones: Simply put...
[lamexp/LameXP.git] / src / Thread_Initialization.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Thread_Initialization.h"
23
24 #include "LockedFile.h"
25
26 #include <QFileInfo>
27 #include <QCoreApplication>
28 #include <QProcess>
29 #include <QMap>
30 #include <QDir>
31 #include <QLibrary>
32 #include <QResource>
33 #include <QTime>
34
35 ////////////////////////////////////////////////////////////
36 // TOOLS
37 ////////////////////////////////////////////////////////////
38
39 #define CPU_TYPE_X86 0x000001 //x86-32
40 #define CPU_TYPE_SSE 0x000002 //x86-32 + SSE2 (Intel only!)
41 #define CPU_TYPE_X64 0x000004 //x86-64
42
43 #define CPU_TYPE_GEN (CPU_TYPE_X86|CPU_TYPE_SSE)              //Use for all CPU's, except for x86-64
44 #define CPU_TYPE_ALL (CPU_TYPE_X86|CPU_TYPE_SSE|CPU_TYPE_X64) //Use for all CPU's, x86-32 and x86-64
45
46 static const struct
47 {
48         char *pcHash;
49         unsigned int uiCpuType;
50         char *pcName;
51         unsigned int uiVersion;
52 }
53 g_lamexp_tools[] =
54 {
55         {"3b41f85dde8d4a5a0f4cd5f461099d0db24610ba", CPU_TYPE_ALL, "alac.exe", UINT_MAX},
56         {"fb74ac8b73ad8cba2c3b4e6e61f23401d630dc22", CPU_TYPE_ALL, "elevator.exe", UINT_MAX},
57         {"3c647950bccfcc75d0746c0772e7115684be4dc5", CPU_TYPE_ALL, "faad.exe", 27},
58         {"d33cd86f04bd4067e244d2804466583c7b90a4e2", CPU_TYPE_ALL, "flac.exe", 121},
59         {"9328a50e89b54ec065637496d9681a7e3eebf915", CPU_TYPE_ALL, "gpgv.exe", 1411},
60         {"d837bf6ee4dab557d8b02d46c75a24e58980fffa", CPU_TYPE_ALL, "gpgv.gpg", UINT_MAX},
61         {"d5b3b80220d85a9fd2f486e37c1fb6511f3c2d72", CPU_TYPE_ALL, "lame.exe", 3990},
62         {"a4e929cfaa42fa2e61a3d0c6434c77a06d45aef3", CPU_TYPE_ALL, "mac.exe", 406},
63         {"9ee3074dc3232c61c0ffd6ae6755f65974695c51", CPU_TYPE_GEN, "mediainfo.i386.exe", 743},
64         {"3691da33a4efd7625d1bd01cbf5ce6ffd8a12d19", CPU_TYPE_X64, "mediainfo.x64.exe", 743},
65         {"aa89763a5ba4d1a5986549b9ee53e005c51940c1", CPU_TYPE_ALL, "mpcdec.exe", 435},
66         {"38f81efca6c1eeab0b9dc39d06c2ac750267217f", CPU_TYPE_ALL, "mpg123.exe", 1132},
67         {"8dd7138714c3bcb39f5a3213413addba13d06f1e", CPU_TYPE_ALL, "oggdec.exe", UINT_MAX},
68         {"14a99d3b1f0b166dbd68db45196da871e58e14ec", CPU_TYPE_X86, "oggenc2.i386.exe", 287602},
69         {"36f8d93ef3df6a420a73a9b5cf02dafdaf4321f0", CPU_TYPE_SSE, "oggenc2.sse2.exe", 287602},
70         {"87ad1af73e9b9db3da3db645e5c2253cb0c2a2ea", CPU_TYPE_X64, "oggenc2.x64.exe", 287602},
71         {"0d9035bb62bdf46a2785261f8be5a4a0972abd15", CPU_TYPE_ALL, "shorten.exe", 361},
72         {"50ead3b852cbfc067a402e6c2d0d0d8879663dec", CPU_TYPE_ALL, "sox.exe", 1432},
73         {"8671e16497a2d217d3707d4aa418678d02b16bcc", CPU_TYPE_ALL, "speexdec.exe", 12},
74         {"093bfdec22872ca99e40183937c88785468be989", CPU_TYPE_ALL, "tta.exe", 21},
75         {"8c842eef65248b46fa6cb9a9e5714f575672d999", CPU_TYPE_ALL, "valdec.exe", 31},
76         {"62e2805d1b2eb2a4d86a5ca6e6ea58010d05d2a7", CPU_TYPE_ALL, "wget.exe", 1114},
77         {"a7e8aad52213e339ad985829722f35eab62be182", CPU_TYPE_ALL, "wupdate.exe", UINT_MAX},
78         {"b7d14b3540d24df13119a55d97623a61412de6e3", CPU_TYPE_ALL, "wvunpack.exe", 4601},
79         {NULL, NULL, NULL, NULL}
80 };
81
82 ////////////////////////////////////////////////////////////
83 // Constructor
84 ////////////////////////////////////////////////////////////
85
86 InitializationThread::InitializationThread(const lamexp_cpu_t *cpuFeatures)
87 {
88         m_bSuccess = false;
89         memset(&m_cpuFeatures, 0, sizeof(lamexp_cpu_t));
90         
91         if(cpuFeatures)
92         {
93                 memcpy(&m_cpuFeatures, cpuFeatures, sizeof(lamexp_cpu_t));
94         }
95 }
96
97 ////////////////////////////////////////////////////////////
98 // Thread Main
99 ////////////////////////////////////////////////////////////
100
101 void InitializationThread::run()
102 {
103         m_bSuccess = false;
104         bool bCustom = false;
105         delay();
106
107         //CPU type selection
108         unsigned int cpuSupport = m_cpuFeatures.x64 ? CPU_TYPE_X64 : ((m_cpuFeatures.intel && m_cpuFeatures.sse && m_cpuFeatures.sse2) ? CPU_TYPE_SSE : CPU_TYPE_X86);
109         
110         //Allocate maps
111         QMap<QString, QString> mapChecksum;
112         QMap<QString, unsigned int> mapVersion;
113         QMap<QString, unsigned int> mapCpuType;
114
115         //Init properties
116         for(int i = 0; i < INT_MAX; i++)
117         {
118                 if(!g_lamexp_tools[i].pcName && !g_lamexp_tools[i].pcHash && !g_lamexp_tools[i].uiVersion)
119                 {
120                         break;
121                 }
122                 else if(g_lamexp_tools[i].pcName && g_lamexp_tools[i].pcHash && g_lamexp_tools[i].uiVersion)
123                 {
124                         const QString currentTool = QString::fromLatin1(g_lamexp_tools[i].pcName);
125                         mapChecksum.insert(currentTool, QString::fromLatin1(g_lamexp_tools[i].pcHash));
126                         mapCpuType.insert(currentTool, g_lamexp_tools[i].uiCpuType);
127                         mapVersion.insert(currentTool, g_lamexp_tools[i].uiVersion);
128                 }
129                 else
130                 {
131                         qFatal("Inconsistent checksum data detected. Take care!");
132                 }
133         }
134
135         QDir toolsDir(":/tools/");
136         QList<QFileInfo> toolsList = toolsDir.entryInfoList(QStringList("*.*"), QDir::Files, QDir::Name);
137         QDir appDir = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
138
139         QTime timer;
140         timer.start();
141         
142         //Extract all files
143         while(!toolsList.isEmpty())
144         {
145                 try
146                 {
147                         QFileInfo currentTool = toolsList.takeFirst();
148                         QString toolName = currentTool.fileName().toLower();
149                         QString toolShortName = QString("%1.%2").arg(currentTool.baseName().toLower(), currentTool.suffix().toLower());
150                         
151                         QByteArray toolHash = mapChecksum.take(toolName).toLatin1();
152                         unsigned int toolCpuType = mapCpuType.take(toolName);
153                         unsigned int toolVersion = mapVersion.take(toolName);
154                         
155                         if(toolHash.size() != 40)
156                         {
157                                 throw "The required checksum is missing, take care!";
158                         }
159                         
160                         if(toolCpuType & cpuSupport)
161                         {
162                                 QFileInfo customTool(QString("%1/tools/%2/%3").arg(appDir.canonicalPath(), QString::number(lamexp_version_build()), toolShortName));
163                                 if(customTool.exists() && customTool.isFile())
164                                 {
165                                         bCustom = true;
166                                         qDebug("Setting up file: %s <- %s", toolShortName.toLatin1().constData(), appDir.relativeFilePath(customTool.canonicalFilePath()).toLatin1().constData());
167                                         LockedFile *lockedFile = new LockedFile(customTool.canonicalFilePath());
168                                         lamexp_register_tool(toolShortName, lockedFile, UINT_MAX);
169                                 }
170                                 else
171                                 {
172                                         qDebug("Extracting file: %s -> %s", toolName.toLatin1().constData(),  toolShortName.toLatin1().constData());
173                                         LockedFile *lockedFile = new LockedFile(QString(":/tools/%1").arg(toolName), QString("%1/tool_%2").arg(lamexp_temp_folder2(), toolShortName), toolHash);
174                                         lamexp_register_tool(toolShortName, lockedFile, toolVersion);
175                                 }
176                         }
177                 }
178                 catch(char *errorMsg)
179                 {
180                         qFatal("At least one of the required tools could not be initialized:\n%s", errorMsg);
181                         return;
182                 }
183         }
184         
185         //Make sure all files were extracted
186         if(!mapChecksum.isEmpty())
187         {
188                 qFatal("At least one required tool could not be found:\n%s", toolsDir.filePath(mapChecksum.keys().first()).toLatin1().constData());
189                 return;
190         }
191         
192         qDebug("All extracted.\n");
193
194         //Clean-up
195         mapChecksum.clear();
196         mapVersion.clear();
197         mapCpuType.clear();
198         
199         //Using any custom tools?
200         if(bCustom)
201         {
202                 qWarning("Warning: Using custom tools, you might encounter unexpected problems!\n");
203         }
204
205         //Check delay
206         double delayExtract = static_cast<double>(timer.elapsed()) / 1000.0;
207         if(delayExtract > 8.0)
208         {
209                 qWarning("Extracting tools took %.3f seconds -> probably slow realtime virus scanner.", delayExtract);
210                 qWarning("Please report performance problems to your anti-virus developer !!!\n");
211         }
212
213         //Register all translations
214         initTranslations();
215
216         //Look for Nero encoder
217         initNeroAac();
218         
219         //Look for WMA File decoder
220         initWmaDec();
221
222         delay();
223         m_bSuccess = true;
224 }
225
226 ////////////////////////////////////////////////////////////
227 // PUBLIC FUNCTIONS
228 ////////////////////////////////////////////////////////////
229
230 void InitializationThread::delay(void)
231 {
232         const char *temp = "|/-\\";
233         printf("Thread is doing something important... ?\b", temp[4]);
234
235         for(int i = 0; i < 20; i++)
236         {
237                 printf("%c\b", temp[i%4]);
238                 msleep(25);
239         }
240
241         printf("Done\n\n");
242 }
243
244 void InitializationThread::initTranslations(void)
245 {
246         //Search for language files
247         QStringList qmFiles = QDir(":/localization").entryList(QStringList() << "LameXP_??.qm", QDir::Files, QDir::Name);
248
249         //Make sure we found at least one translation
250         if(qmFiles.count() < 1)
251         {
252                 qFatal("Could not find any translation files!");
253                 return;
254         }
255
256         //Add all available translations
257         while(!qmFiles.isEmpty())
258         {
259                 QString langId, langName;
260                 unsigned int systemId = 0;
261                 QString qmFile = qmFiles.takeFirst();
262                 
263                 QRegExp langIdExp("LameXP_(\\w\\w)\\.qm", Qt::CaseInsensitive);
264                 if(langIdExp.indexIn(qmFile) >= 0)
265                 {
266                         langId = langIdExp.cap(1).toLower();
267                 }
268
269                 QResource langRes = (QString(":/localization/%1.txt").arg(qmFile));
270                 if(langRes.isValid() && langRes.size() > 0)
271                 {
272                         QStringList langInfo = QString::fromUtf8(reinterpret_cast<const char*>(langRes.data()), langRes.size()).simplified().split(",", QString::SkipEmptyParts);
273                         if(langInfo.count() == 2)
274                         {
275                                 systemId = langInfo.at(0).toUInt();
276                                 langName = langInfo.at(1);
277                         }
278                 }
279                 
280                 if(lamexp_translation_register(langId, qmFile, langName, systemId))
281                 {
282                         qDebug64("Registering translation: %1 = %2 (%3)", qmFile, langName, QString::number(systemId));
283                 }
284                 else
285                 {
286                         qWarning("Failed to register: %s", qmFile.toLatin1().constData());
287                 }
288         }
289
290         qDebug("All registered.\n");
291 }
292
293 void InitializationThread::initNeroAac(void)
294 {
295         const QString appPath = QDir(QCoreApplication::applicationDirPath()).canonicalPath();
296         
297         QFileInfo neroFileInfo[3];
298         neroFileInfo[0] = QFileInfo(QString("%1/neroAacEnc.exe").arg(appPath));
299         neroFileInfo[1] = QFileInfo(QString("%1/neroAacDec.exe").arg(appPath));
300         neroFileInfo[2] = QFileInfo(QString("%1/neroAacTag.exe").arg(appPath));
301         
302         bool neroFilesFound = true;
303         for(int i = 0; i < 3; i++)      { if(!neroFileInfo[i].exists()) neroFilesFound = false; }
304
305         //Lock the Nero binaries
306         if(!neroFilesFound)
307         {
308                 qDebug("Nero encoder binaries not found -> AAC encoding support will be disabled!\n");
309                 return;
310         }
311
312         qDebug("Found Nero AAC encoder binary:\n%s\n", neroFileInfo[0].canonicalFilePath().toUtf8().constData());
313
314         LockedFile *neroBin[3];
315         for(int i = 0; i < 3; i++) neroBin[i] = NULL;
316
317         try
318         {
319                 for(int i = 0; i < 3; i++)
320                 {
321                         neroBin[i] = new LockedFile(neroFileInfo[i].canonicalFilePath());
322                 }
323         }
324         catch(...)
325         {
326                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
327                 qWarning("Failed to get excluive lock to Nero encoder binary -> AAC encoding support will be disabled!");
328                 return;
329         }
330
331         QProcess process;
332         process.setProcessChannelMode(QProcess::MergedChannels);
333         process.setReadChannel(QProcess::StandardOutput);
334         process.start(neroFileInfo[0].canonicalFilePath(), QStringList() << "-help");
335
336         if(!process.waitForStarted())
337         {
338                 qWarning("Nero process failed to create!");
339                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
340                 process.kill();
341                 process.waitForFinished(-1);
342                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
343                 return;
344         }
345
346         unsigned int neroVersion = 0;
347
348         while(process.state() != QProcess::NotRunning)
349         {
350                 if(!process.waitForReadyRead())
351                 {
352                         if(process.state() == QProcess::Running)
353                         {
354                                 qWarning("Nero process time out -> killing!");
355                                 process.kill();
356                                 process.waitForFinished(-1);
357                                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
358                                 return;
359                         }
360                 }
361
362                 while(process.canReadLine())
363                 {
364                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
365                         QStringList tokens = line.split(" ", QString::SkipEmptyParts, Qt::CaseInsensitive);
366                         int index1 = tokens.indexOf("Package");
367                         int index2 = tokens.indexOf("version:");
368                         if(index1 >= 0 && index2 >= 0 && index1 + 1 == index2 && index2 < tokens.count() - 1)
369                         {
370                                 QStringList versionTokens = tokens.at(index2 + 1).split(".", QString::SkipEmptyParts, Qt::CaseInsensitive);
371                                 if(versionTokens.count() == 4)
372                                 {
373                                         neroVersion = 0;
374                                         neroVersion += min(9, max(0, versionTokens.at(3).toInt()));
375                                         neroVersion += min(9, max(0, versionTokens.at(2).toInt())) * 10;
376                                         neroVersion += min(9, max(0, versionTokens.at(1).toInt())) * 100;
377                                         neroVersion += min(9, max(0, versionTokens.at(0).toInt())) * 1000;
378                                 }
379                         }
380                 }
381         }
382
383         if(!(neroVersion > 0))
384         {
385                 qWarning("Nero AAC version could not be determined -> AAC encoding support will be disabled!");
386                 for(int i = 0; i < 3; i++) LAMEXP_DELETE(neroBin[i]);
387                 return;
388         }
389         
390         for(int i = 0; i < 3; i++)
391         {
392                 lamexp_register_tool(neroFileInfo[i].fileName(), neroBin[i], neroVersion);
393         }
394 }
395
396
397 void InitializationThread::initWmaDec(void)
398 {
399         static const char* wmaDecoderComponentPath = "NCH Software/Components/wmawav/wmawav.exe";
400
401         LockedFile *wmaFileBin = NULL;
402         QFileInfo wmaFileInfo = QFileInfo(QString("%1/%2").arg(lamexp_known_folder(lamexp_folder_programfiles), wmaDecoderComponentPath));
403
404         if(!wmaFileInfo.exists())
405         {
406                 qDebug("WMA File Decoder not found -> WMA decoding support will be disabled!\n");
407                 return;
408         }
409
410         try
411         {
412                 wmaFileBin = new LockedFile(wmaFileInfo.canonicalFilePath());
413         }
414         catch(...)
415         {
416                 qWarning("Failed to get excluive lock to WMA File Decoder binary -> WMA decoding support will be disabled!");
417                 return;
418         }
419
420         QProcess process;
421         process.setProcessChannelMode(QProcess::MergedChannels);
422         process.setReadChannel(QProcess::StandardOutput);
423         process.start(wmaFileInfo.canonicalFilePath(), QStringList());
424
425         if(!process.waitForStarted())
426         {
427                 qWarning("WmaWav process failed to create!");
428                 qWarning("Error message: \"%s\"\n", process.errorString().toLatin1().constData());
429                 process.kill();
430                 process.waitForFinished(-1);
431                 return;
432         }
433
434         bool b_wmaWavFound = false;
435
436         while(process.state() != QProcess::NotRunning)
437         {
438                 if(!process.waitForReadyRead())
439                 {
440                         if(process.state() == QProcess::Running)
441                         {
442                                 qWarning("WmaWav process time out -> killing!");
443                                 process.kill();
444                                 process.waitForFinished(-1);
445                                 return;
446                         }
447                 }
448                 while(process.canReadLine())
449                 {
450                         QString line = QString::fromUtf8(process.readLine().constData()).simplified();
451                         if(line.contains("Usage: wmatowav.exe WMAFileSpec WAVFileSpec", Qt::CaseInsensitive))
452                         {
453                                 b_wmaWavFound = true;
454                         }
455                 }
456         }
457
458         if(!b_wmaWavFound)
459         {
460                 qWarning("WmaWav could not be identified -> WMA decoding support will be disabled!\n");
461                 LAMEXP_DELETE(wmaFileBin);
462                 return;
463         }
464
465         qDebug("Found WMA File Decoder binary:\n%s\n", wmaFileInfo.canonicalFilePath().toUtf8().constData());
466
467         if(wmaFileBin)
468         {
469                 lamexp_register_tool(wmaFileInfo.fileName(), wmaFileBin);
470         }
471 }
472
473 ////////////////////////////////////////////////////////////
474 // EVENTS
475 ////////////////////////////////////////////////////////////
476
477 /*NONE*/