1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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.
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.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
26 #include <QApplication>
27 #include <QMessageBox>
33 #include <QPlastiqueStyle>
34 #include <QImageReader>
35 #include <QSharedMemory>
37 #include <QStringList>
38 #include <QSystemSemaphore>
39 #include <QDesktopServices>
45 #include <QTranslator>
48 #include <QLibraryInfo>
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;
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};
76 unsigned int ver_major;
77 unsigned int ver_minor;
78 unsigned int ver_patch;
79 unsigned int ver_build;
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";
105 #error Compiler is not supported!
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";
122 #error Compiler version is not supported yet!
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";
130 #error Compiler version is not supported yet!
132 #elif (_MSC_VER == 1500)
133 #if (_MSC_FULL_VER >= 150030729)
134 static const char *g_x264_version_compiler = "MSVC 2008-SP1";
136 static const char *g_x264_version_compiler = "MSVC 2008";
139 #error Compiler is not supported!
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!")
151 #error Compiler is not supported!
154 //Architecture detection
156 static const char *g_x264_version_arch = "x64";
157 #elif defined(_M_IX86)
158 static const char *g_x264_version_arch = "x86";
160 #error Architecture is not supported!
164 * Global exception handler
166 LONG WINAPI x264_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
168 if(GetCurrentThreadId() != g_main_thread_id)
170 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
171 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
174 x264_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
179 * Invalid parameters handler
181 void x264_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
183 if(GetCurrentThreadId() != g_main_thread_id)
185 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
186 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
189 x264_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
193 * Change console text color
195 static void x264_console_color(FILE* file, WORD attributes)
197 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
198 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
200 SetConsoleTextAttribute(hConsole, attributes);
207 void x264_message_handler(QtMsgType type, const char *msg)
209 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
211 QMutexLocker lock(&g_x264_message_mutex);
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);
223 if(g_x264_console_attached)
225 UINT oldOutputCP = GetConsoleOutputCP();
226 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
234 x264_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
235 fprintf(stderr, GURU_MEDITATION);
236 fprintf(stderr, "%s\n", msg);
240 x264_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
241 fprintf(stderr, "%s\n", msg);
245 x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
246 fprintf(stderr, "%s\n", msg);
251 x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
252 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
256 QString temp("[x264][%1] %2");
262 temp = temp.arg("C", QString::fromUtf8(msg));
265 temp = temp.arg("W", QString::fromUtf8(msg));
268 temp = temp.arg("I", QString::fromUtf8(msg));
272 temp.replace("\n", "\t").append("\n");
273 OutputDebugStringA(temp.toLatin1().constData());
276 if(type == QtCriticalMsg || type == QtFatalMsg)
279 x264_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
284 * Initialize the console
286 void x264_init_console(int argc, char* argv[])
288 bool enableConsole = x264_is_prerelease() || (X264_DEBUG);
292 wchar_t *logfile = NULL;
293 size_t logfile_len = 0;
294 if(!_wdupenv_s(&logfile, &logfile_len, L"X264_LAUNCHER_LOGFILE"))
296 if(logfile && (logfile_len > 0))
299 if(!_wfopen_s(&temp, logfile, L"wb"))
301 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
302 g_x264_log_file = temp;
311 for(int i = 0; i < argc; i++)
313 if(!_stricmp(argv[i], "--console"))
315 enableConsole = true;
317 else if(!_stricmp(argv[i], "--no-console"))
319 enableConsole = false;
326 if(!g_x264_console_attached)
330 SetConsoleCtrlHandler(NULL, TRUE);
331 SetConsoleTitle(L"Simple x264 Launcher | Debug Console");
332 SetConsoleOutputCP(CP_UTF8);
333 g_x264_console_attached = true;
337 if(g_x264_console_attached)
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)); }
351 HWND hwndConsole = GetConsoleWindow();
353 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
355 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
356 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
357 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
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);
369 unsigned int x264_version_major(void)
371 return g_x264_version.ver_major;
374 unsigned int x264_version_minor(void)
376 return (g_x264_version.ver_minor * 10) + (g_x264_version.ver_patch % 10);
379 unsigned int x264_version_build(void)
381 return g_x264_version.ver_build;
384 const char *x264_version_compiler(void)
386 return g_x264_version_compiler;
389 const char *x264_version_arch(void)
391 return g_x264_version_arch;
395 * Check for portable mode
397 bool x264_portable(void)
399 static bool detected = false;
400 static bool portable = false;
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));
414 * Get data path (i.e. path to store config files)
416 const QString &x264_data_path(void)
418 static QString pathCache;
420 if(pathCache.isNull())
424 pathCache = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
426 if(pathCache.isEmpty() || x264_portable())
428 pathCache = QApplication::applicationDirPath();
430 if(!QDir(pathCache).mkpath("."))
432 qWarning("Data directory could not be created:\n%s\n", pathCache.toUtf8().constData());
433 pathCache = QDir::currentPath();
441 * Get build date date
443 const QDate &x264_version_date(void)
445 if(!g_x264_version_date.isValid())
447 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
448 strncpy_s(temp, 12, g_x264_version.ver_date, _TRUNCATE);
450 if(strlen(temp) == 11)
452 temp[3] = temp[6] = '\0';
453 date[2] = atoi(&temp[4]);
454 date[0] = atoi(&temp[7]);
456 for(int j = 0; j < 12; j++)
458 if(!_strcmpi(&temp[0], g_x264_months[j]))
465 g_x264_version_date = QDate(date[0], date[1], date[2]);
468 if(!g_x264_version_date.isValid())
470 qFatal("Internal error: Date format could not be recognized!");
474 return g_x264_version_date;
477 const char *x264_version_time(void)
479 return g_x264_version.ver_time;
482 bool x264_is_prerelease(void)
484 return (VER_X264_PRE_RELEASE);
488 * CPUID prototype (actual function is in ASM code)
492 void x264_cpu_cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx);
496 * Detect CPU features
498 const x264_cpu_t x264_detect_cpu_features(int argc, char **argv)
500 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
501 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
503 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
504 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
507 SYSTEM_INFO systemInfo;
508 unsigned int CPUInfo[4];
509 char CPUIdentificationString[0x40];
510 char CPUBrandString[0x40];
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));
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);
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!
539 x264_cpu_cpuid(0x80000000U, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
540 unsigned int nExIds = qBound(0x80000000U, CPUInfo[0], 0x80000004U);
542 if((_stricmp(CPUIdentificationString, "AuthenticAMD") == 0) && (nExIds >= 0x80000001U))
544 x264_cpu_cpuid(0x80000001U, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
545 features.mmx2 = features.mmx2 || (CPUInfo[3] & 0x00400000U);
548 for(unsigned int i = 0x80000002U; i <= nExIds; ++i)
550 x264_cpu_cpuid(i, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
554 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
557 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
560 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
565 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
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);
570 #if !defined(_M_X64 ) && !defined(_M_IA64)
571 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
573 QLibrary Kernel32Lib("kernel32.dll");
574 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
575 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
577 if(IsWow64ProcessPtr)
580 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
585 if(GetNativeSystemInfoPtr)
587 GetNativeSystemInfoPtr(&systemInfo);
591 GetSystemInfo(&systemInfo);
593 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
595 GetNativeSystemInfo(&systemInfo);
596 features.count = systemInfo.dwNumberOfProcessors;
600 if((argv != NULL) && (argc > 0))
603 for(int i = 0; i < argc; i++)
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; }
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; }
617 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
624 * Get the native operating system version
626 DWORD x264_get_os_version(void)
628 OSVERSIONINFO osVerInfo;
629 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
630 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
633 if(GetVersionEx(&osVerInfo) == TRUE)
635 if(osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
637 throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
639 version = (DWORD)((osVerInfo.dwMajorVersion << 16) | (osVerInfo.dwMinorVersion & 0xffff));
646 * Check for compatibility mode
648 static bool x264_check_compatibility_mode(const char *exportName, const char *executableName)
650 QLibrary kernel32("kernel32.dll");
652 if(exportName != NULL)
654 if(kernel32.resolve(exportName) != NULL)
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());
666 * Check for process elevation
668 static bool x264_check_elevation(void)
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;
673 HANDLE hToken = NULL;
674 bool bIsProcessElevated = false;
676 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
678 X264_TOKEN_ELEVATION_TYPE tokenElevationType;
680 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) x264_token_elevationType_class, &tokenElevationType, sizeof(X264_TOKEN_ELEVATION_TYPE), &returnLength))
682 if(returnLength == sizeof(X264_TOKEN_ELEVATION_TYPE))
684 switch(tokenElevationType)
686 case x264_elevationType_default:
687 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
689 case x264_elevationType_full:
690 qWarning("Process token elevation type: Full -> potential security risk!\n");
691 bIsProcessElevated = true;
693 case x264_elevationType_limited:
694 qDebug("Process token elevation type: Limited -> not elevated.\n");
703 qWarning("Failed to open process token!");
706 return !bIsProcessElevated;
710 * Initialize Qt framework
712 bool x264_init_qt(int argc, char* argv[])
714 static bool qt_initialized = false;
716 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
718 //Don't initialized again, if done already
725 QLibrary kernel32("kernel32.dll");
728 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
729 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
733 //Extract executable name from argv[] array
734 char *executableName = argv[0];
735 while(char *temp = strpbrk(executableName, "\\/:?"))
737 executableName = temp + 1;
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))
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());
748 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
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());
754 //Check the Windows version
755 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
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());
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);
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);
772 case QSysInfo::WV_VISTA:
773 qDebug("Running on Windows Vista or Windows Server 2008.\n");
774 x264_check_compatibility_mode("CreateRemoteThreadEx", executableName);
776 case QSysInfo::WV_WINDOWS7:
777 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
778 x264_check_compatibility_mode(NULL, executableName);
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));
789 QLibrary ntdll("ntdll.dll");
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");
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"));
806 //application->setEventFilter(x264_event_filter);
808 //Set text Codec for locale
809 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
811 //Load plugins from application directory
812 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
813 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
815 //Check for supported image formats
816 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
817 for(int i = 0; g_x264_imageformats[i]; i++)
819 if(!supportedFormats.contains(g_x264_imageformats[i]))
821 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_x264_imageformats[i]);
826 //Add default translations
827 // g_x264_translation.files.insert(x264_DEFAULT_LANGID, "");
828 // g_x264_translation.names.insert(x264_DEFAULT_LANGID, "English");
830 //Check for process elevation
831 if(!x264_check_elevation())
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)
839 //Update console icon, if a console is attached
840 if(g_x264_console_attached && !isWine)
842 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
843 QLibrary kernel32("kernel32.dll");
846 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
847 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/movie.ico").pixmap(16, 16).toWinHICON());
853 qt_initialized = true;
858 * Shutdown the computer
860 bool x264_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
862 HANDLE hToken = NULL;
864 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
866 TOKEN_PRIVILEGES privileges;
867 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
868 privileges.PrivilegeCount = 1;
869 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
871 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
873 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
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);
885 * Check for debugger (detect routine)
887 static bool x264_check_for_debugger(void)
893 __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
901 * Check for debugger (thread proc)
903 static void WINAPI x264_debug_thread_proc(__in LPVOID lpParameter)
905 while(!(IsDebuggerPresent() || x264_check_for_debugger()))
911 TerminateProcess(GetCurrentProcess(), -1);
916 * Check for debugger (startup routine)
918 static HANDLE x264_debug_thread_init(void)
920 if(IsDebuggerPresent() || x264_check_for_debugger())
922 x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
925 return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&x264_debug_thread_proc), NULL, NULL, NULL);
929 * Fatal application exit
931 #pragma intrinsic(_InterlockedExchange)
932 void x264_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
934 static volatile long bFatalFlag = 0L;
936 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
938 if(GetCurrentThreadId() != g_main_thread_id)
940 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
941 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
946 MessageBoxW(NULL, errorBoxMessage, L"Simple x264 Launcher - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
949 FatalAppExit(0, exitMessage);
953 TerminateProcess(GetCurrentProcess(), -1);
959 * Initialize debug thread
961 static const HANDLE g_debug_thread = X264_DEBUG ? NULL : x264_debug_thread_init();
964 * Get number private bytes [debug only]
966 SIZE_T x264_dbg_private_bytes(void)
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;
974 throw "Cannot call this function in a non-debug build!";
979 * Finalization function
981 void x264_finalization(void)
983 //Destroy Qt application object
984 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
985 X264_DELETE(application);
987 //Free STDOUT and STDERR buffers
988 if(g_x264_console_attached)
990 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
992 std::cout.rdbuf(NULL);
995 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
997 std::cerr.rdbuf(NULL);