OSDN Git Service

Updated README file.
[x264-launcher/x264-launcher.git] / src / global.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
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.
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 "global.h"
23 #include "version.h"
24
25 //Qt includes
26 #include <QApplication>
27 #include <QMessageBox>
28 #include <QDir>
29 #include <QUuid>
30 #include <QMap>
31 #include <QDate>
32 #include <QIcon>
33 #include <QPlastiqueStyle>
34 #include <QImageReader>
35 #include <QSharedMemory>
36 #include <QSysInfo>
37 #include <QStringList>
38 #include <QSystemSemaphore>
39 #include <QDesktopServices>
40 #include <QMutex>
41 #include <QTextCodec>
42 #include <QLibrary>
43 #include <QRegExp>
44 #include <QResource>
45 #include <QTranslator>
46 #include <QEventLoop>
47 #include <QTimer>
48 #include <QLibraryInfo>
49 #include <QEvent>
50
51 //CRT includes
52 #include <fstream>
53 #include <io.h>
54 #include <fcntl.h>
55 #include <intrin.h>
56
57 //Debug only includes
58 #if X264_DEBUG
59 #include <Psapi.h>
60 #endif
61
62 //Global vars
63 static bool g_x264_console_attached = false;
64 static QMutex g_x264_message_mutex;
65 static const DWORD g_main_thread_id = GetCurrentThreadId();
66 static FILE *g_x264_log_file = NULL;
67 static QDate g_x264_version_date;
68
69 //Const
70 static const char *g_x264_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
71 static const char *g_x264_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
72
73 //Build version
74 static const struct
75 {
76         unsigned int ver_major;
77         unsigned int ver_minor;
78         unsigned int ver_patch;
79         unsigned int ver_build;
80         const char* ver_date;
81         const char* ver_time;
82 }
83 g_x264_version =
84 {
85         (VER_X264_MAJOR),
86         (VER_X264_MINOR),
87         (VER_X264_PATCH),
88         (VER_X264_BUILD),
89         __DATE__,
90         __TIME__
91 };
92
93 //Compiler detection
94 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
95 #if defined(__INTEL_COMPILER)
96         #if (__INTEL_COMPILER >= 1300)
97                 static const char *g_x264_version_compiler = "ICL 13." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
98         #elif (__INTEL_COMPILER >= 1200)
99                 static const char *g_x264_version_compiler = "ICL 12." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
100         #elif (__INTEL_COMPILER >= 1100)
101                 static const char *g_x264_version_compiler = "ICL 11.x";
102         #elif (__INTEL_COMPILER >= 1000)
103                 static const char *g_x264_version_compiler = "ICL 10.x";
104         #else
105                 #error Compiler is not supported!
106         #endif
107 #elif defined(_MSC_VER)
108         #if (_MSC_VER == 1700)
109                 #if (_MSC_FULL_VER < 170050727)
110                         static const char *g_x264_version_compiler = "MSVC 2012-Beta";
111                 #elif (_MSC_FULL_VER < 170051020)
112                         static const char *g_x264_version_compiler = "MSVC 2012-RTM";
113                 #elif (_MSC_FULL_VER < 170051106)
114                         static const char *g_x264_version_compiler = "MSVC 2012-U1 CTP";
115                 #elif (_MSC_FULL_VER < 170060315)
116                         static const char *g_x264_version_compiler = "MSVC 2012-U1";
117                 #elif (_MSC_FULL_VER < 170060610)
118                         static const char *g_x264_version_compiler = "MSVC 2012-U2";
119                 #elif (_MSC_FULL_VER == 170060610)
120                         static const char *g_x264_version_compiler = "MSVC 2012-U3";
121                 #else
122                         #error Compiler version is not supported yet!
123                 #endif
124         #elif (_MSC_VER == 1600)
125                 #if (_MSC_FULL_VER < 160040219)
126                         static const char *g_x264_version_compiler = "MSVC 2010-RTM";
127                 #elif (_MSC_FULL_VER == 160040219)
128                         static const char *g_x264_version_compiler = "MSVC 2010-SP1";
129                 #else
130                         #error Compiler version is not supported yet!
131                 #endif
132         #elif (_MSC_VER == 1500)
133                 #if (_MSC_FULL_VER >= 150030729)
134                         static const char *g_x264_version_compiler = "MSVC 2008-SP1";
135                 #else
136                         static const char *g_x264_version_compiler = "MSVC 2008";
137                 #endif
138         #else
139                 #error Compiler is not supported!
140         #endif
141
142         // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
143         #if !defined(_M_X64) && defined(_M_IX86_FP)
144                 #if (_M_IX86_FP == 1)
145                         X264_COMPILER_WARNING("SSE instruction set is enabled!")
146                 #elif (_M_IX86_FP == 2)
147                         X264_COMPILER_WARNING("SSE2 instruction set is enabled!")
148                 #endif
149         #endif
150 #else
151         #error Compiler is not supported!
152 #endif
153
154 //Architecture detection
155 #if defined(_M_X64)
156         static const char *g_x264_version_arch = "x64";
157 #elif defined(_M_IX86)
158         static const char *g_x264_version_arch = "x86";
159 #else
160         #error Architecture is not supported!
161 #endif
162
163 /*
164  * Global exception handler
165  */
166 LONG WINAPI x264_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
167 {
168         if(GetCurrentThreadId() != g_main_thread_id)
169         {
170                 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
171                 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
172         }
173
174         x264_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
175         return LONG_MAX;
176 }
177
178 /*
179  * Invalid parameters handler
180  */
181 void x264_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
182 {
183         if(GetCurrentThreadId() != g_main_thread_id)
184         {
185                 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
186                 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
187         }
188
189         x264_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
190 }
191
192 /*
193  * Change console text color
194  */
195 static void x264_console_color(FILE* file, WORD attributes)
196 {
197         const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
198         if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
199         {
200                 SetConsoleTextAttribute(hConsole, attributes);
201         }
202 }
203
204 /*
205  * Qt message handler
206  */
207 void x264_message_handler(QtMsgType type, const char *msg)
208 {
209         static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
210         
211         QMutexLocker lock(&g_x264_message_mutex);
212
213         if(g_x264_log_file)
214         {
215                 static char prefix[] = "DWCF";
216                 int index = qBound(0, static_cast<int>(type), 3);
217                 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
218                 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
219                 fprintf(g_x264_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
220                 fflush(g_x264_log_file);
221         }
222
223         if(g_x264_console_attached)
224         {
225                 UINT oldOutputCP = GetConsoleOutputCP();
226                 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
227
228                 switch(type)
229                 {
230                 case QtCriticalMsg:
231                 case QtFatalMsg:
232                         fflush(stdout);
233                         fflush(stderr);
234                         x264_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
235                         fprintf(stderr, GURU_MEDITATION);
236                         fprintf(stderr, "%s\n", msg);
237                         fflush(stderr);
238                         break;
239                 case QtWarningMsg:
240                         x264_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
241                         fprintf(stderr, "%s\n", msg);
242                         fflush(stderr);
243                         break;
244                 default:
245                         x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
246                         fprintf(stderr, "%s\n", msg);
247                         fflush(stderr);
248                         break;
249                 }
250         
251                 x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
252                 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
253         }
254         else
255         {
256                 QString temp("[x264][%1] %2");
257                 
258                 switch(type)
259                 {
260                 case QtCriticalMsg:
261                 case QtFatalMsg:
262                         temp = temp.arg("C", QString::fromUtf8(msg));
263                         break;
264                 case QtWarningMsg:
265                         temp = temp.arg("W", QString::fromUtf8(msg));
266                         break;
267                 default:
268                         temp = temp.arg("I", QString::fromUtf8(msg));
269                         break;
270                 }
271
272                 temp.replace("\n", "\t").append("\n");
273                 OutputDebugStringA(temp.toLatin1().constData());
274         }
275
276         if(type == QtCriticalMsg || type == QtFatalMsg)
277         {
278                 lock.unlock();
279                 x264_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
280         }
281 }
282
283 /*
284  * Initialize the console
285  */
286 void x264_init_console(int argc, char* argv[])
287 {
288         bool enableConsole = x264_is_prerelease() || (X264_DEBUG);
289
290         if(_environ)
291         {
292                 wchar_t *logfile = NULL;
293                 size_t logfile_len = 0;
294                 if(!_wdupenv_s(&logfile, &logfile_len, L"X264_LAUNCHER_LOGFILE"))
295                 {
296                         if(logfile && (logfile_len > 0))
297                         {
298                                 FILE *temp = NULL;
299                                 if(!_wfopen_s(&temp, logfile, L"wb"))
300                                 {
301                                         fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
302                                         g_x264_log_file = temp;
303                                 }
304                                 free(logfile);
305                         }
306                 }
307         }
308
309         if(!X264_DEBUG)
310         {
311                 for(int i = 0; i < argc; i++)
312                 {
313                         if(!_stricmp(argv[i], "--console"))
314                         {
315                                 enableConsole = true;
316                         }
317                         else if(!_stricmp(argv[i], "--no-console"))
318                         {
319                                 enableConsole = false;
320                         }
321                 }
322         }
323
324         if(enableConsole)
325         {
326                 if(!g_x264_console_attached)
327                 {
328                         if(AllocConsole())
329                         {
330                                 SetConsoleCtrlHandler(NULL, TRUE);
331                                 SetConsoleTitle(L"Simple x264 Launcher | Debug Console");
332                                 SetConsoleOutputCP(CP_UTF8);
333                                 g_x264_console_attached = true;
334                         }
335                 }
336                 
337                 if(g_x264_console_attached)
338                 {
339                         //-------------------------------------------------------------------
340                         //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
341                         //-------------------------------------------------------------------
342                         const int flags = _O_WRONLY | _O_U8TEXT;
343                         int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
344                         int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
345                         FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
346                         FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
347                         if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
348                         if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
349                 }
350
351                 HWND hwndConsole = GetConsoleWindow();
352
353                 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
354                 {
355                         HMENU hMenu = GetSystemMenu(hwndConsole, 0);
356                         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
357                         RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
358
359                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
360                         SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
361                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
362                 }
363         }
364 }
365
366 /*
367  * Version info
368  */
369 unsigned int x264_version_major(void)
370 {
371         return g_x264_version.ver_major;
372 }
373
374 unsigned int x264_version_minor(void)
375 {
376         return (g_x264_version.ver_minor * 10) + (g_x264_version.ver_patch % 10);
377 }
378
379 unsigned int x264_version_build(void)
380 {
381         return g_x264_version.ver_build;
382 }
383
384 const char *x264_version_compiler(void)
385 {
386         return g_x264_version_compiler;
387 }
388
389 const char *x264_version_arch(void)
390 {
391         return g_x264_version_arch;
392 }
393
394 /*
395  * Check for portable mode
396  */
397 bool x264_portable(void)
398 {
399         static bool detected = false;
400         static bool portable = false;
401
402         if(!detected)
403         {
404                 portable = portable || QFileInfo(QApplication::applicationFilePath()).baseName().contains(QRegExp("^portable[^A-Za-z0-9]", Qt::CaseInsensitive));
405                 portable = portable || QFileInfo(QApplication::applicationFilePath()).baseName().contains(QRegExp("[^A-Za-z0-9]portable[^A-Za-z0-9]", Qt::CaseInsensitive));
406                 portable = portable || QFileInfo(QApplication::applicationFilePath()).baseName().contains(QRegExp("[^A-Za-z0-9]portable$", Qt::CaseInsensitive));
407                 detected = true;
408         }
409
410         return portable;
411 }
412
413 /*
414  * Get data path (i.e. path to store config files)
415  */
416 const QString &x264_data_path(void)
417 {
418         static QString pathCache;
419         
420         if(pathCache.isNull())
421         {
422                 if(!x264_portable())
423                 {
424                         pathCache = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
425                 }
426                 if(pathCache.isEmpty() || x264_portable())
427                 {
428                         pathCache = QApplication::applicationDirPath();
429                 }
430                 if(!QDir(pathCache).mkpath("."))
431                 {
432                         qWarning("Data directory could not be created:\n%s\n", pathCache.toUtf8().constData());
433                         pathCache = QDir::currentPath();
434                 }
435         }
436         
437         return pathCache;
438 }
439
440 /*
441  * Get build date date
442  */
443 const QDate &x264_version_date(void)
444 {
445         if(!g_x264_version_date.isValid())
446         {
447                 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
448                 strncpy_s(temp, 12, g_x264_version.ver_date, _TRUNCATE);
449
450                 if(strlen(temp) == 11)
451                 {
452                         temp[3] = temp[6] = '\0';
453                         date[2] = atoi(&temp[4]);
454                         date[0] = atoi(&temp[7]);
455                         
456                         for(int j = 0; j < 12; j++)
457                         {
458                                 if(!_strcmpi(&temp[0], g_x264_months[j]))
459                                 {
460                                         date[1] = j+1;
461                                         break;
462                                 }
463                         }
464
465                         g_x264_version_date = QDate(date[0], date[1], date[2]);
466                 }
467
468                 if(!g_x264_version_date.isValid())
469                 {
470                         qFatal("Internal error: Date format could not be recognized!");
471                 }
472         }
473
474         return g_x264_version_date;
475 }
476
477 const char *x264_version_time(void)
478 {
479         return g_x264_version.ver_time;
480 }
481
482 bool x264_is_prerelease(void)
483 {
484         return (VER_X264_PRE_RELEASE);
485 }
486
487 /*
488  * CPUID prototype (actual function is in ASM code)
489  */
490 extern "C"
491 {
492         void x264_cpu_cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx);
493 }
494
495 /*
496  * Detect CPU features
497  */
498 const x264_cpu_t x264_detect_cpu_features(int argc, char **argv)
499 {
500         typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
501         typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
502         
503         static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
504         static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
505
506         x264_cpu_t features;
507         SYSTEM_INFO systemInfo;
508         unsigned int CPUInfo[4];
509         char CPUIdentificationString[0x40];
510         char CPUBrandString[0x40];
511
512         memset(&features, 0, sizeof(x264_cpu_t));
513         memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
514         memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
515         memset(CPUBrandString, 0, sizeof(CPUBrandString));
516         
517         x264_cpu_cpuid(0, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
518         memcpy(CPUIdentificationString, &CPUInfo[1], 4);
519         memcpy(CPUIdentificationString + 4, &CPUInfo[3], 4);
520         memcpy(CPUIdentificationString + 8, &CPUInfo[2], 4);
521         features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
522         strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
523
524         if(CPUInfo[0] >= 1)
525         {
526                 x264_cpu_cpuid(1, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
527                 features.mmx = (CPUInfo[3] & 0x800000U) || false;
528                 features.sse = (CPUInfo[3] & 0x2000000U) || false;
529                 features.sse2 = (CPUInfo[3] & 0x4000000U) || false;
530                 features.ssse3 = (CPUInfo[2] & 0x200U) || false;
531                 features.sse3 = (CPUInfo[2] & 0x1U) || false;
532                 features.ssse3 = (CPUInfo[2] & 0x200U) || false;
533                 features.stepping = CPUInfo[0] & 0xf;
534                 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
535                 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
536                 if(features.sse) features.mmx2 = true; //MMXEXT is a subset of SSE!
537         }
538
539         x264_cpu_cpuid(0x80000000U, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
540         unsigned int nExIds = qBound(0x80000000U, CPUInfo[0], 0x80000004U);
541
542         if((_stricmp(CPUIdentificationString, "AuthenticAMD") == 0) && (nExIds >= 0x80000001U))
543         {
544                 x264_cpu_cpuid(0x80000001U, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
545                 features.mmx2 = features.mmx2 || (CPUInfo[3] & 0x00400000U);
546         }
547
548         for(unsigned int i = 0x80000002U; i <= nExIds; ++i)
549         {
550                 x264_cpu_cpuid(i, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
551                 switch(i)
552                 {
553                 case 0x80000002U:
554                         memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
555                         break;
556                 case 0x80000003U:
557                         memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
558                         break;
559                 case 0x80000004U:
560                         memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
561                         break;
562                 }
563         }
564
565         strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
566
567         if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
568         if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
569
570 #if !defined(_M_X64 ) && !defined(_M_IA64)
571         if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
572         {
573                 QLibrary Kernel32Lib("kernel32.dll");
574                 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
575                 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
576         }
577         if(IsWow64ProcessPtr)
578         {
579                 BOOL x64 = FALSE;
580                 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
581                 {
582                         features.x64 = x64;
583                 }
584         }
585         if(GetNativeSystemInfoPtr)
586         {
587                 GetNativeSystemInfoPtr(&systemInfo);
588         }
589         else
590         {
591                 GetSystemInfo(&systemInfo);
592         }
593         features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
594 #else
595         GetNativeSystemInfo(&systemInfo);
596         features.count = systemInfo.dwNumberOfProcessors;
597         features.x64 = true;
598 #endif
599
600         if((argv != NULL) && (argc > 0))
601         {
602                 bool flag = false;
603                 for(int i = 0; i < argc; i++)
604                 {
605                         if(!_stricmp("--force-cpu-no-64bit", argv[i])) { flag = true; features.x64 = false; }
606                         if(!_stricmp("--force-cpu-no-mmx", argv[i])) { flag = true; features.mmx = false; }
607                         if(!_stricmp("--force-cpu-no-mmx2", argv[i])) { flag = true; features.mmx2 = false; }
608                         if(!_stricmp("--force-cpu-no-sse", argv[i])) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
609                         if(!_stricmp("--force-cpu-no-intel", argv[i])) { flag = true; features.intel = false; }
610                         
611                         if(!_stricmp("--force-cpu-have-64bit", argv[i])) { flag = true; features.x64 = true; }
612                         if(!_stricmp("--force-cpu-have-mmx", argv[i])) { flag = true; features.mmx = true; }
613                         if(!_stricmp("--force-cpu-have-mmx2", argv[i])) { flag = true; features.mmx2 = true; }
614                         if(!_stricmp("--force-cpu-have-sse", argv[i])) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = true; }
615                         if(!_stricmp("--force-cpu-have-intel", argv[i])) { flag = true; features.intel = true; }
616                 }
617                 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
618         }
619
620         return features;
621 }
622
623 /*
624  * Get the native operating system version
625  */
626 DWORD x264_get_os_version(void)
627 {
628         OSVERSIONINFO osVerInfo;
629         memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
630         osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
631         DWORD version = 0;
632         
633         if(GetVersionEx(&osVerInfo) == TRUE)
634         {
635                 if(osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
636                 {
637                         throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
638                 }
639                 version = (DWORD)((osVerInfo.dwMajorVersion << 16) | (osVerInfo.dwMinorVersion & 0xffff));
640         }
641
642         return version;
643 }
644
645 /*
646  * Check for compatibility mode
647  */
648 static bool x264_check_compatibility_mode(const char *exportName, const char *executableName)
649 {
650         QLibrary kernel32("kernel32.dll");
651
652         if(exportName != NULL)
653         {
654                 if(kernel32.resolve(exportName) != NULL)
655                 {
656                         qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
657                         qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
658                         return false;
659                 }
660         }
661
662         return true;
663 }
664
665 /*
666  * Check for process elevation
667  */
668 static bool x264_check_elevation(void)
669 {
670         typedef enum { x264_token_elevationType_class = 18, x264_token_elevation_class = 20 } X264_TOKEN_INFORMATION_CLASS;
671         typedef enum { x264_elevationType_default = 1, x264_elevationType_full, x264_elevationType_limited } X264_TOKEN_ELEVATION_TYPE;
672
673         HANDLE hToken = NULL;
674         bool bIsProcessElevated = false;
675         
676         if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
677         {
678                 X264_TOKEN_ELEVATION_TYPE tokenElevationType;
679                 DWORD returnLength;
680                 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) x264_token_elevationType_class, &tokenElevationType, sizeof(X264_TOKEN_ELEVATION_TYPE), &returnLength))
681                 {
682                         if(returnLength == sizeof(X264_TOKEN_ELEVATION_TYPE))
683                         {
684                                 switch(tokenElevationType)
685                                 {
686                                 case x264_elevationType_default:
687                                         qDebug("Process token elevation type: Default -> UAC is disabled.\n");
688                                         break;
689                                 case x264_elevationType_full:
690                                         qWarning("Process token elevation type: Full -> potential security risk!\n");
691                                         bIsProcessElevated = true;
692                                         break;
693                                 case x264_elevationType_limited:
694                                         qDebug("Process token elevation type: Limited -> not elevated.\n");
695                                         break;
696                                 }
697                         }
698                 }
699                 CloseHandle(hToken);
700         }
701         else
702         {
703                 qWarning("Failed to open process token!");
704         }
705
706         return !bIsProcessElevated;
707 }
708
709 /*
710  * Initialize Qt framework
711  */
712 bool x264_init_qt(int argc, char* argv[])
713 {
714         static bool qt_initialized = false;
715         bool isWine = false;
716         typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
717
718         //Don't initialized again, if done already
719         if(qt_initialized)
720         {
721                 return true;
722         }
723         
724         //Secure DLL loading
725         QLibrary kernel32("kernel32.dll");
726         if(kernel32.load())
727         {
728                 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
729                 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
730                 kernel32.unload();
731         }
732
733         //Extract executable name from argv[] array
734         char *executableName = argv[0];
735         while(char *temp = strpbrk(executableName, "\\/:?"))
736         {
737                 executableName = temp + 1;
738         }
739
740         //Check Qt version
741         qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
742         qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
743         if(_stricmp(qVersion(), QT_VERSION_STR))
744         {
745                 qFatal("%s", QApplication::tr("Executable '%1' requires Qt v%2, but found Qt v%3.").arg(QString::fromLatin1(executableName), QString::fromLatin1(QT_VERSION_STR), QString::fromLatin1(qVersion())).toLatin1().constData());
746                 return false;
747         }
748         if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
749         {
750                 qFatal("%s", QApplication::tr("Executable '%1' was built for Qt '%2', but found Qt '%3'.").arg(QString::fromLatin1(executableName), QString::fromLatin1(QT_BUILD_KEY), QLibraryInfo::buildKey()).toLatin1().constData());
751                 return false;
752         }
753
754         //Check the Windows version
755         switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
756         {
757         case 0:
758         case QSysInfo::WV_NT:
759         case QSysInfo::WV_2000:
760                 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
761                 break;
762                 //qDebug("Running on Windows 2000 (not officially supported!).\n");
763                 //x264_check_compatibility_mode("GetNativeSystemInfo", executableName);
764         case QSysInfo::WV_XP:
765                 qDebug("Running on Windows XP.\n");
766                 x264_check_compatibility_mode("GetLargePageMinimum", executableName);
767                 break;
768         case QSysInfo::WV_2003:
769                 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
770                 x264_check_compatibility_mode("GetLocaleInfoEx", executableName);
771                 break;
772         case QSysInfo::WV_VISTA:
773                 qDebug("Running on Windows Vista or Windows Server 2008.\n");
774                 x264_check_compatibility_mode("CreateRemoteThreadEx", executableName);
775                 break;
776         case QSysInfo::WV_WINDOWS7:
777                 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
778                 x264_check_compatibility_mode(NULL, executableName);
779                 break;
780         default:
781                 {
782                         DWORD osVersionNo = x264_get_os_version();
783                         qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", HIWORD(osVersionNo), LOWORD(osVersionNo));
784                 }
785                 break;
786         }
787
788         //Check for Wine
789         QLibrary ntdll("ntdll.dll");
790         if(ntdll.load())
791         {
792                 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
793                 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
794                 if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
795                 ntdll.unload();
796         }
797
798         //Create Qt application instance and setup version info
799         QApplication *application = new QApplication(argc, argv);
800         application->setApplicationName("Simple x264 Launcher");
801         application->setApplicationVersion(QString().sprintf("%d.%02d", x264_version_major(), x264_version_minor())); 
802         application->setOrganizationName("LoRd_MuldeR");
803         application->setOrganizationDomain("mulder.at.gg");
804         application->setWindowIcon(QIcon(":/icons/movie.ico"));
805         
806         //application->setEventFilter(x264_event_filter);
807
808         //Set text Codec for locale
809         QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
810
811         //Load plugins from application directory
812         QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
813         qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
814
815         //Check for supported image formats
816         QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
817         for(int i = 0; g_x264_imageformats[i]; i++)
818         {
819                 if(!supportedFormats.contains(g_x264_imageformats[i]))
820                 {
821                         qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_x264_imageformats[i]);
822                         return false;
823                 }
824         }
825
826         //Add default translations
827         // g_x264_translation.files.insert(x264_DEFAULT_LANGID, "");
828         // g_x264_translation.names.insert(x264_DEFAULT_LANGID, "English");
829
830         //Check for process elevation
831         if(!x264_check_elevation())
832         {
833                 if(QMessageBox::warning(NULL, "Simple x264 Launcher", "<nobr>Program was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
834                 {
835                         return false;
836                 }
837         }
838
839         //Update console icon, if a console is attached
840         if(g_x264_console_attached && !isWine)
841         {
842                 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
843                 QLibrary kernel32("kernel32.dll");
844                 if(kernel32.load())
845                 {
846                         SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
847                         if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/movie.ico").pixmap(16, 16).toWinHICON());
848                         kernel32.unload();
849                 }
850         }
851
852         //Done
853         qt_initialized = true;
854         return true;
855 }
856
857 /*
858  * Shutdown the computer
859  */
860 bool x264_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
861 {
862         HANDLE hToken = NULL;
863
864         if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
865         {
866                 TOKEN_PRIVILEGES privileges;
867                 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
868                 privileges.PrivilegeCount = 1;
869                 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
870                 
871                 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
872                 {
873                         if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
874                         {
875                                 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
876                                 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
877                         }
878                 }
879         }
880         
881         return false;
882 }
883
884 /*
885  * Check for debugger (detect routine)
886  */
887 static bool x264_check_for_debugger(void)
888 {
889         __try 
890         {
891                 DebugBreak();
892         }
893         __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) 
894         {
895                 return false;
896         }
897         return true;
898 }
899
900 /*
901  * Check for debugger (thread proc)
902  */
903 static void WINAPI x264_debug_thread_proc(__in LPVOID lpParameter)
904 {
905         while(!(IsDebuggerPresent() || x264_check_for_debugger()))
906         {
907                 Sleep(333);
908         }
909         for(;;)
910         {
911                 TerminateProcess(GetCurrentProcess(), -1);
912         }
913 }
914
915 /*
916  * Check for debugger (startup routine)
917  */
918 static HANDLE x264_debug_thread_init(void)
919 {
920         if(IsDebuggerPresent() || x264_check_for_debugger())
921         {
922                 x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
923         }
924
925         return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&x264_debug_thread_proc), NULL, NULL, NULL);
926 }
927
928 /*
929  * Fatal application exit
930  */
931 #pragma intrinsic(_InterlockedExchange)
932 void x264_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
933 {
934         static volatile long bFatalFlag = 0L;
935
936         if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
937         {
938                 if(GetCurrentThreadId() != g_main_thread_id)
939                 {
940                         HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
941                         if(mainThread) TerminateThread(mainThread, ULONG_MAX);
942                 }
943         
944                 if(errorBoxMessage)
945                 {
946                         MessageBoxW(NULL, errorBoxMessage, L"Simple x264 Launcher - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
947                 }
948
949                 FatalAppExit(0, exitMessage);
950
951                 for(;;)
952                 {
953                         TerminateProcess(GetCurrentProcess(), -1);
954                 }
955         }
956 }
957
958 /*
959  * Initialize debug thread
960  */
961 static const HANDLE g_debug_thread = X264_DEBUG ? NULL : x264_debug_thread_init();
962
963 /*
964  * Get number private bytes [debug only]
965  */
966 SIZE_T x264_dbg_private_bytes(void)
967 {
968 #if X264_DEBUG
969         PROCESS_MEMORY_COUNTERS_EX memoryCounters;
970         memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
971         GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
972         return memoryCounters.PrivateUsage;
973 #else
974         throw "Cannot call this function in a non-debug build!";
975 #endif //X264_DEBUG
976 }
977
978 /*
979  * Finalization function
980  */
981 void x264_finalization(void)
982 {
983         //Destroy Qt application object
984         QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
985         X264_DELETE(application);
986
987         //Free STDOUT and STDERR buffers
988         if(g_x264_console_attached)
989         {
990                 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
991                 {
992                         std::cout.rdbuf(NULL);
993                         X264_DELETE(tmp);
994                 }
995                 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
996                 {
997                         std::cerr.rdbuf(NULL);
998                         X264_DELETE(tmp);
999                 }
1000         }
1001 }