OSDN Git Service

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