1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2012 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 >= 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";
103 #error Compiler is not supported!
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";
110 static const char *g_x264_version_compiler = "MSVC 2010";
112 #elif (_MSC_VER == 1500)
113 #if (_MSC_FULL_VER >= 150030729)
114 static const char *g_x264_version_compiler = "MSVC 2008-SP1";
116 static const char *g_x264_version_compiler = "MSVC 2008";
119 #error Compiler is not supported!
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!")
131 #error Compiler is not supported!
134 //Architecture detection
136 static const char *g_x264_version_arch = "x64";
137 #elif defined(_M_IX86)
138 static const char *g_x264_version_arch = "x86";
140 #error Architecture is not supported!
144 * Global exception handler
146 LONG WINAPI x264_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
148 if(GetCurrentThreadId() != g_main_thread_id)
150 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
151 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
154 FatalAppExit(0, L"Unhandeled exception handler invoked, application will exit!");
155 TerminateProcess(GetCurrentProcess(), -1);
160 * Invalid parameters handler
162 void x264_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
164 if(GetCurrentThreadId() != g_main_thread_id)
166 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
167 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
170 FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
171 TerminateProcess(GetCurrentProcess(), -1);
175 * Change console text color
177 static void x264_console_color(FILE* file, WORD attributes)
179 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
180 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
182 SetConsoleTextAttribute(hConsole, attributes);
189 void x264_message_handler(QtMsgType type, const char *msg)
191 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
193 QMutexLocker lock(&g_x264_message_mutex);
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);
205 if(g_x264_console_attached)
207 UINT oldOutputCP = GetConsoleOutputCP();
208 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
216 x264_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
217 fprintf(stderr, GURU_MEDITATION);
218 fprintf(stderr, "%s\n", msg);
222 x264_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
223 fprintf(stderr, "%s\n", msg);
227 x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
228 fprintf(stderr, "%s\n", msg);
233 x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
234 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
238 QString temp("[x264][%1] %2");
244 temp = temp.arg("C", QString::fromUtf8(msg));
247 temp = temp.arg("W", QString::fromUtf8(msg));
250 temp = temp.arg("I", QString::fromUtf8(msg));
254 temp.replace("\n", "\t").append("\n");
255 OutputDebugStringA(temp.toLatin1().constData());
258 if(type == QtCriticalMsg || type == QtFatalMsg)
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);
268 * Initialize the console
270 void x264_init_console(int argc, char* argv[])
272 bool enableConsole = x264_is_prerelease() || (X264_DEBUG);
276 wchar_t *logfile = NULL;
277 size_t logfile_len = 0;
278 if(!_wdupenv_s(&logfile, &logfile_len, L"X264_LAUNCHER_LOGFILE"))
280 if(logfile && (logfile_len > 0))
283 if(!_wfopen_s(&temp, logfile, L"wb"))
285 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
286 g_x264_log_file = temp;
295 for(int i = 0; i < argc; i++)
297 if(!_stricmp(argv[i], "--console"))
299 enableConsole = true;
301 else if(!_stricmp(argv[i], "--no-console"))
303 enableConsole = false;
310 if(!g_x264_console_attached)
314 SetConsoleCtrlHandler(NULL, TRUE);
315 SetConsoleTitle(L"Simple x264 Launcher | Debug Console");
316 SetConsoleOutputCP(CP_UTF8);
317 g_x264_console_attached = true;
321 if(g_x264_console_attached)
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)); }
335 HWND hwndConsole = GetConsoleWindow();
337 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
339 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
340 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
341 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
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);
353 unsigned int x264_version_major(void)
355 return g_x264_version.ver_major;
358 unsigned int x264_version_minor(void)
360 return (g_x264_version.ver_minor * 10) + (g_x264_version.ver_patch % 10);
363 unsigned int x264_version_build(void)
365 return g_x264_version.ver_build;
368 const char *x264_version_compiler(void)
370 return g_x264_version_compiler;
373 const char *x264_version_arch(void)
375 return g_x264_version_arch;
379 * Check for portable mode
381 bool x264_portable(void)
383 static bool detected = false;
384 static bool portable = false;
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));
398 * Get data path (i.e. path to store config files)
400 const QString &x264_data_path(void)
402 static QString *pathCache = NULL;
406 pathCache = new QString();
409 *pathCache = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
411 if(pathCache->isEmpty() || x264_portable())
413 *pathCache = QApplication::applicationDirPath();
415 if(!QDir(*pathCache).mkpath("."))
417 qWarning("Data directory could not be created:\n%s\n", pathCache->toUtf8().constData());
418 *pathCache = QDir::currentPath();
426 * Get build date date
428 const QDate &x264_version_date(void)
430 if(!g_x264_version_date.isValid())
432 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
433 strncpy_s(temp, 12, g_x264_version.ver_date, _TRUNCATE);
435 if(strlen(temp) == 11)
437 temp[3] = temp[6] = '\0';
438 date[2] = atoi(&temp[4]);
439 date[0] = atoi(&temp[7]);
441 for(int j = 0; j < 12; j++)
443 if(!_strcmpi(&temp[0], g_x264_months[j]))
450 g_x264_version_date = QDate(date[0], date[1], date[2]);
453 if(!g_x264_version_date.isValid())
455 qFatal("Internal error: Date format could not be recognized!");
459 return g_x264_version_date;
462 const char *x264_version_time(void)
464 return g_x264_version.ver_time;
467 bool x264_is_prerelease(void)
469 return (VER_X264_PRE_RELEASE);
473 * CPUID prototype (actual function is in ASM code)
477 void x264_cpu_cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx);
481 * Detect CPU features
483 const x264_cpu_t x264_detect_cpu_features(int argc, char **argv)
485 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
486 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
488 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
489 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
492 SYSTEM_INFO systemInfo;
493 unsigned int CPUInfo[4];
494 char CPUIdentificationString[0x40];
495 char CPUBrandString[0x40];
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));
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);
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!
524 x264_cpu_cpuid(0x80000000U, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
525 unsigned int nExIds = qBound(0x80000000U, CPUInfo[0], 0x80000004U);
527 if((_stricmp(CPUIdentificationString, "AuthenticAMD") == 0) && (nExIds >= 0x80000001U))
529 x264_cpu_cpuid(0x80000001U, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
530 features.mmx2 = features.mmx2 || (CPUInfo[3] & 0x00400000U);
533 for(unsigned int i = 0x80000002U; i <= nExIds; ++i)
535 x264_cpu_cpuid(i, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
539 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
542 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
545 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
550 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
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);
555 #if !defined(_M_X64 ) && !defined(_M_IA64)
556 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
558 QLibrary Kernel32Lib("kernel32.dll");
559 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
560 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
562 if(IsWow64ProcessPtr)
565 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
570 if(GetNativeSystemInfoPtr)
572 GetNativeSystemInfoPtr(&systemInfo);
576 GetSystemInfo(&systemInfo);
578 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
580 GetNativeSystemInfo(&systemInfo);
581 features.count = systemInfo.dwNumberOfProcessors;
585 if((argv != NULL) && (argc > 0))
588 for(int i = 0; i < argc; i++)
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; }
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; }
602 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
609 * Get the native operating system version
611 DWORD x264_get_os_version(void)
613 OSVERSIONINFO osVerInfo;
614 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
615 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
618 if(GetVersionEx(&osVerInfo) == TRUE)
620 if(osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
622 throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
624 version = (DWORD)((osVerInfo.dwMajorVersion << 16) | (osVerInfo.dwMinorVersion & 0xffff));
631 * Check for compatibility mode
633 static bool x264_check_compatibility_mode(const char *exportName, const char *executableName)
635 QLibrary kernel32("kernel32.dll");
637 if(exportName != NULL)
639 if(kernel32.resolve(exportName) != NULL)
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());
651 * Check for process elevation
653 static bool x264_check_elevation(void)
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;
658 HANDLE hToken = NULL;
659 bool bIsProcessElevated = false;
661 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
663 X264_TOKEN_ELEVATION_TYPE tokenElevationType;
665 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) x264_token_elevationType_class, &tokenElevationType, sizeof(X264_TOKEN_ELEVATION_TYPE), &returnLength))
667 if(returnLength == sizeof(X264_TOKEN_ELEVATION_TYPE))
669 switch(tokenElevationType)
671 case x264_elevationType_default:
672 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
674 case x264_elevationType_full:
675 qWarning("Process token elevation type: Full -> potential security risk!\n");
676 bIsProcessElevated = true;
678 case x264_elevationType_limited:
679 qDebug("Process token elevation type: Limited -> not elevated.\n");
688 qWarning("Failed to open process token!");
691 return !bIsProcessElevated;
695 * Initialize Qt framework
697 bool x264_init_qt(int argc, char* argv[])
699 static bool qt_initialized = false;
701 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
703 //Don't initialized again, if done already
710 QLibrary kernel32("kernel32.dll");
713 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
714 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
718 //Extract executable name from argv[] array
719 char *executableName = argv[0];
720 while(char *temp = strpbrk(executableName, "\\/:?"))
722 executableName = temp + 1;
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))
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());
733 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
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());
739 //Check the Windows version
740 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
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());
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);
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);
757 case QSysInfo::WV_VISTA:
758 qDebug("Running on Windows Vista or Windows Server 2008.\n");
759 x264_check_compatibility_mode("CreateRemoteThreadEx", executableName);
761 case QSysInfo::WV_WINDOWS7:
762 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
763 x264_check_compatibility_mode(NULL, executableName);
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));
774 QLibrary ntdll("ntdll.dll");
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");
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"));
791 //application->setEventFilter(x264_event_filter);
793 //Set text Codec for locale
794 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
796 //Load plugins from application directory
797 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
798 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
800 //Check for supported image formats
801 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
802 for(int i = 0; g_x264_imageformats[i]; i++)
804 if(!supportedFormats.contains(g_x264_imageformats[i]))
806 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_x264_imageformats[i]);
811 //Add default translations
812 // g_x264_translation.files.insert(x264_DEFAULT_LANGID, "");
813 // g_x264_translation.names.insert(x264_DEFAULT_LANGID, "English");
815 //Check for process elevation
816 if(!x264_check_elevation())
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)
824 //Update console icon, if a console is attached
825 if(g_x264_console_attached && !isWine)
827 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
828 QLibrary kernel32("kernel32.dll");
831 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
832 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/movie.ico").pixmap(16, 16).toWinHICON());
838 qt_initialized = true;
843 * Shutdown the computer
845 bool x264_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
847 HANDLE hToken = NULL;
849 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
851 TOKEN_PRIVILEGES privileges;
852 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
853 privileges.PrivilegeCount = 1;
854 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
856 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
858 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
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);
870 * Check for debugger (detect routine)
872 static bool x264_check_for_debugger(void)
878 __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
886 * Check for debugger (thread proc)
888 static void WINAPI x264_debug_thread_proc(__in LPVOID lpParameter)
890 while(!(IsDebuggerPresent() || x264_check_for_debugger()))
894 TerminateProcess(GetCurrentProcess(), -1);
898 * Check for debugger (startup routine)
900 static HANDLE x264_debug_thread_init(void)
902 if(IsDebuggerPresent() || x264_check_for_debugger())
904 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
905 TerminateProcess(GetCurrentProcess(), -1);
908 return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&x264_debug_thread_proc), NULL, NULL, NULL);
912 * Initialize debug thread
914 static const HANDLE g_debug_thread = X264_DEBUG ? NULL : x264_debug_thread_init();
917 * Get number private bytes [debug only]
919 SIZE_T x264_dbg_private_bytes(void)
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;
927 throw "Cannot call this function in a non-debug build!";
932 * Finalization function
934 void x264_finalization(void)