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 ///////////////////////////////////////////////////////////////////////////////
24 #include "targetver.h"
27 #define ENABLE_X264_VERSION_INCLUDE
29 #undef ENABLE_X264_VERSION_INCLUDE
33 #define WIN32_LEAN_AND_MEAN
51 #include <QApplication>
52 #include <QMessageBox>
58 #include <QPlastiqueStyle>
59 #include <QImageReader>
60 #include <QSharedMemory>
62 #include <QStringList>
63 #include <QSystemSemaphore>
64 #include <QDesktopServices>
70 #include <QTranslator>
73 #include <QLibraryInfo>
75 #include <QReadLocker>
76 #include <QWriteLocker>
92 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
93 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
96 static bool g_x264_console_attached = false;
97 static QMutex g_x264_message_mutex;
98 static const DWORD g_main_thread_id = GetCurrentThreadId();
99 static FILE *g_x264_log_file = NULL;
100 static QDate g_x264_version_date;
103 static const char *g_x264_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
104 static const char *g_x264_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
109 unsigned int ver_major;
110 unsigned int ver_minor;
111 unsigned int ver_patch;
112 unsigned int ver_build;
113 const char* ver_date;
114 const char* ver_time;
115 unsigned int ver_x264_minimum_rev;
116 unsigned int ver_x264_current_api;
117 unsigned int ver_x264_avs2yuv_ver;
127 (VER_X264_MINIMUM_REV),
128 (VER_X264_CURRENT_API),
129 (VER_X264_AVS2YUV_VER)
144 x264_os_version_t version;
152 QMap<size_t, QString> *knownFolders;
153 SHGetKnownFolderPath_t getKnownFolderPath;
154 SHGetFolderPath_t getFolderPath;
180 bool bPortableModeEnabled;
185 //Known Windows versions - maps marketing names to the actual Windows NT versions
186 const x264_os_version_t x264_winver_win2k = {5,0};
187 const x264_os_version_t x264_winver_winxp = {5,1};
188 const x264_os_version_t x264_winver_xpx64 = {5,2};
189 const x264_os_version_t x264_winver_vista = {6,0};
190 const x264_os_version_t x264_winver_win70 = {6,1};
191 const x264_os_version_t x264_winver_win80 = {6,2};
192 const x264_os_version_t x264_winver_win81 = {6,3};
195 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
197 ///////////////////////////////////////////////////////////////////////////////
199 ///////////////////////////////////////////////////////////////////////////////
202 #define CLEAN_OUTPUT_STRING(STR) do \
204 const char CTRL_CHARS[3] = { '\r', '\n', '\t' }; \
205 for(size_t i = 0; i < 3; i++) \
207 while(char *pos = strchr((STR), CTRL_CHARS[i])) *pos = char(0x20); \
213 #define TRIM_LEFT(STR) do \
215 const char WHITE_SPACE[4] = { char(0x20), '\r', '\n', '\t' }; \
216 for(size_t i = 0; i < 4; i++) \
218 while(*(STR) == WHITE_SPACE[i]) (STR)++; \
223 #define X264_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
225 ///////////////////////////////////////////////////////////////////////////////
227 ///////////////////////////////////////////////////////////////////////////////
230 * Disclaimer: Parts of the following code were borrowed from MPC-HC project: http://mpc-hc.sf.net/
234 #if defined(__INTEL_COMPILER)
235 #if (__INTEL_COMPILER >= 1300)
236 static const char *g_x264_version_compiler = "ICL 13." X264_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
237 #elif (__INTEL_COMPILER >= 1200)
238 static const char *g_x264_version_compiler = "ICL 12." X264_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
239 #elif (__INTEL_COMPILER >= 1100)
240 static const char *g_x264_version_compiler = "ICL 11.x";
241 #elif (__INTEL_COMPILER >= 1000)
242 static const char *g_x264_version_compiler = "ICL 10.x";
244 #error Compiler is not supported!
246 #elif defined(_MSC_VER)
247 #if (_MSC_VER == 1800)
248 #if (_MSC_FULL_VER < 180021005)
249 static const char *g_x264_version_compiler = "MSVC 2013-Beta";
250 #elif (_MSC_FULL_VER == 180021005)
251 static const char *g_x264_version_compiler = "MSVC 2013";
253 #error Compiler version is not supported yet!
255 #elif (_MSC_VER == 1700)
256 #if (_MSC_FULL_VER < 170050727)
257 static const char *g_x264_version_compiler = "MSVC 2012-Beta";
258 #elif (_MSC_FULL_VER < 170051020)
259 static const char *g_x264_version_compiler = "MSVC 2012";
260 #elif (_MSC_FULL_VER < 170051106)
261 static const char *g_x264_version_compiler = "MSVC 2012.1-CTP";
262 #elif (_MSC_FULL_VER < 170060315)
263 static const char *g_x264_version_compiler = "MSVC 2012.1";
264 #elif (_MSC_FULL_VER < 170060610)
265 static const char *g_x264_version_compiler = "MSVC 2012.2";
266 #elif (_MSC_FULL_VER == 170060610)
267 static const char *g_x264_version_compiler = "MSVC 2012.3";
269 #error Compiler version is not supported yet!
271 #elif (_MSC_VER == 1600)
272 #if (_MSC_FULL_VER < 160040219)
273 static const char *g_x264_version_compiler = "MSVC 2010";
274 #elif (_MSC_FULL_VER == 160040219)
275 static const char *g_x264_version_compiler = "MSVC 2010-SP1";
277 #error Compiler version is not supported yet!
279 #elif (_MSC_VER == 1500)
280 #if (_MSC_FULL_VER >= 150030729)
281 static const char *g_x264_version_compiler = "MSVC 2008-SP1";
283 static const char *g_x264_version_compiler = "MSVC 2008";
286 #error Compiler is not supported!
289 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
290 #if !defined(_M_X64) && defined(_M_IX86_FP)
291 #if (_M_IX86_FP == 1)
292 X264_COMPILER_WARNING("SSE instruction set is enabled!")
293 #elif (_M_IX86_FP == 2)
294 X264_COMPILER_WARNING("SSE2 (or higher) instruction set is enabled!")
298 #error Compiler is not supported!
301 //Architecture detection
303 static const char *g_x264_version_arch = "x64";
304 #elif defined(_M_IX86)
305 static const char *g_x264_version_arch = "x86";
307 #error Architecture is not supported!
310 ///////////////////////////////////////////////////////////////////////////////
312 ///////////////////////////////////////////////////////////////////////////////
314 static __forceinline bool x264_check_for_debugger(void);
317 * Suspend calling thread for N milliseconds
319 inline void x264_sleep(const unsigned int delay)
325 * Global exception handler
327 LONG WINAPI x264_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
329 if(GetCurrentThreadId() != g_main_thread_id)
331 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
332 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
335 x264_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
340 * Invalid parameters handler
342 void x264_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
344 if(GetCurrentThreadId() != g_main_thread_id)
346 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
347 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
350 x264_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
354 * Get a random string
356 QString x264_rand_str(const bool bLong)
358 const QUuid uuid = QUuid::createUuid().toString();
360 const unsigned int u1 = uuid.data1;
361 const unsigned int u2 = (((unsigned int)(uuid.data2)) << 16) | ((unsigned int)(uuid.data3));
362 const unsigned int u3 = (((unsigned int)(uuid.data4[0])) << 24) | (((unsigned int)(uuid.data4[1])) << 16) | (((unsigned int)(uuid.data4[2])) << 8) | ((unsigned int)(uuid.data4[3]));
363 const unsigned int u4 = (((unsigned int)(uuid.data4[4])) << 24) | (((unsigned int)(uuid.data4[5])) << 16) | (((unsigned int)(uuid.data4[6])) << 8) | ((unsigned int)(uuid.data4[7]));
365 return bLong ? QString().sprintf("%08x%08x%08x%08x", u1, u2, u3, u4) : QString().sprintf("%08x%08x", (u1 ^ u2), (u3 ^ u4));
369 * Robert Jenkins' 96 bit Mix Function
370 * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
372 static unsigned int x264_mix(const unsigned int x, const unsigned int y, const unsigned int z)
378 a=a-b; a=a-c; a=a^(c >> 13);
379 b=b-c; b=b-a; b=b^(a << 8);
380 c=c-a; c=c-b; c=c^(b >> 13);
381 a=a-b; a=a-c; a=a^(c >> 12);
382 b=b-c; b=b-a; b=b^(a << 16);
383 c=c-a; c=c-b; c=c^(b >> 5);
384 a=a-b; a=a-c; a=a^(c >> 3);
385 b=b-c; b=b-a; b=b^(a << 10);
386 c=c-a; c=c-b; c=c^(b >> 15);
392 * Seeds the random number generator
393 * Note: Altough rand_s() doesn't need a seed, this must be called pripr to x264_rand(), just to to be sure!
395 void x264_seed_rand(void)
397 qsrand(x264_mix(clock(), time(NULL), _getpid()));
401 * Returns a randum number
402 * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
404 unsigned int x264_rand(void)
408 if(rand_s(&rnd) == 0)
413 for(size_t i = 0; i < sizeof(unsigned int); i++)
415 rnd = (rnd << 8) ^ qrand();
422 * Change console text color
424 static void x264_console_color(FILE* file, WORD attributes)
426 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
427 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
429 SetConsoleTextAttribute(hConsole, attributes);
434 * Determines the current date, resistant against certain manipulations
436 QDate x264_current_date_safe(void)
438 const DWORD MAX_PROC = 1024;
439 DWORD *processes = new DWORD[MAX_PROC];
440 DWORD bytesReturned = 0;
442 if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
444 X264_DELETE_ARRAY(processes);
445 return QDate::currentDate();
448 const DWORD procCount = bytesReturned / sizeof(DWORD);
449 ULARGE_INTEGER lastStartTime;
450 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
452 for(DWORD i = 0; i < procCount; i++)
454 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
457 FILETIME processTime[4];
458 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
460 ULARGE_INTEGER timeCreation;
461 timeCreation.LowPart = processTime[0].dwLowDateTime;
462 timeCreation.HighPart = processTime[0].dwHighDateTime;
463 if(timeCreation.QuadPart > lastStartTime.QuadPart)
465 lastStartTime.QuadPart = timeCreation.QuadPart;
472 X264_DELETE_ARRAY(processes);
474 FILETIME lastStartTime_fileTime;
475 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
476 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
478 FILETIME lastStartTime_localTime;
479 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
481 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
484 SYSTEMTIME lastStartTime_system;
485 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
487 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
488 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
491 const QDate currentDate = QDate::currentDate();
492 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
493 return (currentDate >= processDate) ? currentDate : processDate;
497 * Output logging message to console
499 static void x264_write_console(const int type, const char *msg)
503 if(_isatty(_fileno(stderr)))
505 UINT oldOutputCP = GetConsoleOutputCP();
506 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
512 x264_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
513 fprintf(stderr, GURU_MEDITATION);
514 fprintf(stderr, "%s\n", msg);
518 x264_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
519 fprintf(stderr, "%s\n", msg);
523 x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
524 fprintf(stderr, "%s\n", msg);
529 x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
530 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
535 /*ignore any exception that might occur here!*/
540 * Output logging message to debugger
542 static void x264_write_dbg_out(const int type, const char *msg)
544 const char *FORMAT = "[sx264l][%c] %s\n";
549 const char* input = msg;
556 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'C', input);
559 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'W', input);
562 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'I', input);
566 char *temp = &buffer[0];
567 CLEAN_OUTPUT_STRING(temp);
568 OutputDebugStringA(temp);
572 /*ignore any exception that might occur here!*/
577 * Output logging message to logfile
579 static void x264_write_logfile(const int type, const char *msg)
581 const char *FORMAT = "[%c][%04u] %s\r\n";
588 strncpy_s(buffer, 512, msg, _TRUNCATE);
590 char *temp = &buffer[0];
592 CLEAN_OUTPUT_STRING(temp);
594 const unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
600 fprintf(g_x264_log_file, FORMAT, 'C', timestamp, temp);
603 fprintf(g_x264_log_file, FORMAT, 'W', timestamp, temp);
606 fprintf(g_x264_log_file, FORMAT, 'I', timestamp, temp);
610 fflush(g_x264_log_file);
615 /*ignore any exception that might occur here!*/
622 void x264_message_handler(QtMsgType type, const char *msg)
624 if((!msg) || (!(msg[0])))
629 QMutexLocker lock(&g_x264_message_mutex);
633 x264_write_logfile(type, msg);
636 if(g_x264_console_attached)
638 x264_write_console(type, msg);
642 x264_write_dbg_out(type, msg);
645 if((type == QtCriticalMsg) || (type == QtFatalMsg))
648 x264_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
653 * Initialize the console
655 void x264_init_console(const QStringList &argv)
657 bool enableConsole = x264_is_prerelease() || (X264_DEBUG);
661 wchar_t *logfile = NULL;
662 size_t logfile_len = 0;
663 if(!_wdupenv_s(&logfile, &logfile_len, L"X264_LOGFILE"))
665 if(logfile && (logfile_len > 0))
668 if(!_wfopen_s(&temp, logfile, L"wb"))
670 fprintf(temp, "%c%c%c", char(0xEF), char(0xBB), char(0xBF));
671 g_x264_log_file = temp;
680 for(int i = 0; i < argv.count(); i++)
682 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
684 enableConsole = true;
686 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
688 enableConsole = false;
695 if(!g_x264_console_attached)
697 if(AllocConsole() != FALSE)
699 SetConsoleCtrlHandler(NULL, TRUE);
700 SetConsoleTitle(L"Simple x264 Launcher | Debug Console");
701 SetConsoleOutputCP(CP_UTF8);
702 g_x264_console_attached = true;
706 if(g_x264_console_attached)
708 //-------------------------------------------------------------------
709 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
710 //-------------------------------------------------------------------
711 const int flags = _O_WRONLY | _O_U8TEXT;
712 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
713 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
714 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
715 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
716 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
717 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
720 HWND hwndConsole = GetConsoleWindow();
722 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
724 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
725 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
726 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
728 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
729 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
730 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
736 * Initialize the console
738 void x264_init_console(int argc, char* argv[])
740 bool enableConsole = x264_is_prerelease() || (X264_DEBUG);
744 wchar_t *logfile = NULL;
745 size_t logfile_len = 0;
746 if(!_wdupenv_s(&logfile, &logfile_len, L"X264_LAUNCHER_LOGFILE"))
748 if(logfile && (logfile_len > 0))
751 if(!_wfopen_s(&temp, logfile, L"wb"))
753 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
754 g_x264_log_file = temp;
763 for(int i = 0; i < argc; i++)
765 if(!_stricmp(argv[i], "--console"))
767 enableConsole = true;
769 else if(!_stricmp(argv[i], "--no-console"))
771 enableConsole = false;
778 if(!g_x264_console_attached)
782 SetConsoleCtrlHandler(NULL, TRUE);
783 SetConsoleTitle(L"Simple x264 Launcher | Debug Console");
784 SetConsoleOutputCP(CP_UTF8);
785 g_x264_console_attached = true;
789 if(g_x264_console_attached)
791 //-------------------------------------------------------------------
792 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
793 //-------------------------------------------------------------------
794 const int flags = _O_WRONLY | _O_U8TEXT;
795 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
796 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
797 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
798 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
799 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
800 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
803 HWND hwndConsole = GetConsoleWindow();
805 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
807 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
808 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
809 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
811 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
812 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
813 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
821 unsigned int x264_version_major(void)
823 return g_x264_version.ver_major;
826 unsigned int x264_version_minor(void)
828 return (g_x264_version.ver_minor * 10) + (g_x264_version.ver_patch % 10);
831 unsigned int x264_version_build(void)
833 return g_x264_version.ver_build;
836 const char *x264_version_compiler(void)
838 return g_x264_version_compiler;
841 const char *x264_version_arch(void)
843 return g_x264_version_arch;
846 unsigned int x264_version_x264_minimum_rev(void)
848 return g_x264_version.ver_x264_minimum_rev;
851 unsigned int x264_version_x264_current_api(void)
853 return g_x264_version.ver_x264_current_api;
856 unsigned int x264_version_x264_avs2yuv_ver(void)
858 return g_x264_version.ver_x264_avs2yuv_ver;
864 const QStringList &x264_arguments(void)
866 QReadLocker readLock(&g_x264_argv.lock);
868 if(!g_x264_argv.list)
871 QWriteLocker writeLock(&g_x264_argv.lock);
873 g_x264_argv.list = new QStringList;
876 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
878 if(NULL != szArglist)
880 for(int i = 0; i < nArgs; i++)
882 (*g_x264_argv.list) << WCHAR2QSTR(szArglist[i]);
884 LocalFree(szArglist);
888 qWarning("CommandLineToArgvW() has failed !!!");
892 return (*g_x264_argv.list);
896 * Check for portable mode
898 bool x264_portable(void)
900 QReadLocker readLock(&g_x264_portable.lock);
902 if(g_x264_portable.bInitialized)
904 return g_x264_portable.bPortableModeEnabled;
908 QWriteLocker writeLock(&g_x264_portable.lock);
910 if(!g_x264_portable.bInitialized)
912 if(VER_X264_PORTABLE_EDITION)
914 qWarning("Simple x264 Launcher portable edition!\n");
915 g_x264_portable.bPortableModeEnabled = true;
919 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
920 int idx1 = baseName.indexOf("x264", 0, Qt::CaseInsensitive);
921 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
922 g_x264_portable.bPortableModeEnabled = (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
924 g_x264_portable.bInitialized = true;
927 return g_x264_portable.bPortableModeEnabled;
931 * Get data path (i.e. path to store config files)
933 const QString &x264_data_path(void)
935 static QString pathCache;
937 if(pathCache.isNull())
941 pathCache = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
943 if(pathCache.isEmpty() || x264_portable())
945 pathCache = QApplication::applicationDirPath();
947 if(!QDir(pathCache).mkpath("."))
949 qWarning("Data directory could not be created:\n%s\n", pathCache.toUtf8().constData());
950 pathCache = QDir::currentPath();
958 * Get build date date
960 const QDate &x264_version_date(void)
962 if(!g_x264_version_date.isValid())
964 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
965 strncpy_s(temp, 12, g_x264_version.ver_date, _TRUNCATE);
967 if(strlen(temp) == 11)
969 temp[3] = temp[6] = '\0';
970 date[2] = atoi(&temp[4]);
971 date[0] = atoi(&temp[7]);
973 for(int j = 0; j < 12; j++)
975 if(!_strcmpi(&temp[0], g_x264_months[j]))
982 g_x264_version_date = QDate(date[0], date[1], date[2]);
985 if(!g_x264_version_date.isValid())
987 qFatal("Internal error: Date format could not be recognized!");
991 return g_x264_version_date;
994 const char *x264_version_time(void)
996 return g_x264_version.ver_time;
999 bool x264_is_prerelease(void)
1001 return (VER_X264_PRE_RELEASE);
1005 * CPUID prototype (actual function is in ASM code)
1009 void x264_cpu_cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx);
1013 * Detect CPU features
1015 x264_cpu_t x264_detect_cpu_features(const QStringList &argv)
1017 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
1019 x264_cpu_t features;
1020 SYSTEM_INFO systemInfo;
1021 unsigned int CPUInfo[4];
1022 char CPUIdentificationString[0x40];
1023 char CPUBrandString[0x40];
1025 memset(&features, 0, sizeof(x264_cpu_t));
1026 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
1027 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
1028 memset(CPUBrandString, 0, sizeof(CPUBrandString));
1030 x264_cpu_cpuid(0, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1031 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
1032 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
1033 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
1034 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
1035 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
1039 x264_cpu_cpuid(1, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1040 features.mmx = (CPUInfo[3] & 0x800000) || false;
1041 features.sse = (CPUInfo[3] & 0x2000000) || false;
1042 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
1043 features.ssse3 = (CPUInfo[2] & 0x200) || false;
1044 features.sse3 = (CPUInfo[2] & 0x1) || false;
1045 features.ssse3 = (CPUInfo[2] & 0x200) || false;
1046 features.stepping = CPUInfo[0] & 0xf;
1047 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
1048 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
1049 if(features.sse) features.mmx2 = true; //MMXEXT is a subset of SSE!
1052 x264_cpu_cpuid(0x80000000, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1053 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
1055 if((_stricmp(CPUIdentificationString, "AuthenticAMD") == 0) && (nExIds >= 0x80000001U))
1057 x264_cpu_cpuid(0x80000001, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1058 features.mmx2 = features.mmx2 || (CPUInfo[3] & 0x00400000U);
1061 for(int i = 0x80000002; i <= nExIds; ++i)
1063 x264_cpu_cpuid(i, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1067 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
1070 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
1073 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
1078 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
1080 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
1081 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
1083 #if (!(defined(_M_X64) || defined(_M_IA64)))
1084 QLibrary Kernel32Lib("kernel32.dll");
1085 if(IsWow64ProcessFun IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process"))
1087 BOOL x64flag = FALSE;
1088 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64flag))
1090 features.x64 = (x64flag == TRUE);
1094 features.x64 = true;
1097 DWORD_PTR procAffinity, sysAffinity;
1098 if(GetProcessAffinityMask(GetCurrentProcess(), &procAffinity, &sysAffinity))
1100 for(DWORD_PTR mask = 1; mask; mask <<= 1)
1102 features.count += ((sysAffinity & mask) ? (1) : (0));
1105 if(features.count < 1)
1107 GetNativeSystemInfo(&systemInfo);
1108 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
1111 if(argv.count() > 0)
1114 for(int i = 0; i < argv.count(); i++)
1116 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
1117 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
1118 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
1120 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
1127 * Verify a specific Windows version
1129 static bool x264_verify_os_version(const DWORD major, const DWORD minor)
1131 OSVERSIONINFOEXW osvi;
1132 DWORDLONG dwlConditionMask = 0;
1134 //Initialize the OSVERSIONINFOEX structure
1135 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
1136 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
1137 osvi.dwMajorVersion = major;
1138 osvi.dwMinorVersion = minor;
1139 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
1141 //Initialize the condition mask
1142 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
1143 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
1144 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
1147 const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
1152 if(GetLastError() != ERROR_OLD_WIN_VERSION)
1154 qWarning("VerifyVersionInfo() system call has failed!");
1158 return (ret != FALSE);
1162 * Determine the *real* Windows version
1164 static bool x264_get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
1166 *major = *minor = 0;
1167 *pbOverride = false;
1169 //Initialize local variables
1170 OSVERSIONINFOEXW osvi;
1171 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
1172 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
1174 //Try GetVersionEx() first
1175 if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
1177 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
1181 //Make sure we are running on NT
1182 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
1184 *major = osvi.dwMajorVersion;
1185 *minor = osvi.dwMinorVersion;
1189 qWarning("Not running on Windows NT, unsupported operating system!");
1193 //Determine the real *major* version first
1196 const DWORD nextMajor = (*major) + 1;
1197 if(x264_verify_os_version(nextMajor, 0))
1207 //Now also determine the real *minor* version
1210 const DWORD nextMinor = (*minor) + 1;
1211 if(x264_verify_os_version((*major), nextMinor))
1224 * Get the native operating system version
1226 const x264_os_version_t &x264_get_os_version(void)
1228 QReadLocker readLock(&g_x264_os_version.lock);
1230 //Already initialized?
1231 if(g_x264_os_version.bInitialized)
1233 return g_x264_os_version.version;
1237 QWriteLocker writeLock(&g_x264_os_version.lock);
1240 if(!g_x264_os_version.bInitialized)
1242 unsigned int major, minor; bool oflag;
1243 if(x264_get_real_os_version(&major, &minor, &oflag))
1245 g_x264_os_version.version.versionMajor = major;
1246 g_x264_os_version.version.versionMinor = minor;
1247 g_x264_os_version.version.overrideFlag = oflag;
1248 g_x264_os_version.bInitialized = true;
1252 qWarning("Failed to determin the operating system version!");
1256 return g_x264_os_version.version;
1260 * Check for compatibility mode
1262 static bool x264_check_compatibility_mode(const char *exportName, const char *executableName)
1264 QLibrary kernel32("kernel32.dll");
1266 if(exportName != NULL)
1268 if(kernel32.resolve(exportName) != NULL)
1270 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
1271 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
1280 * Check if we are running under wine
1282 bool x264_detect_wine(void)
1284 QReadLocker readLock(&g_x264_wine.lock);
1286 //Already initialized?
1287 if(g_x264_wine.bInitialized)
1289 return g_x264_wine.bIsWine;
1293 QWriteLocker writeLock(&g_x264_wine.lock);
1295 if(!g_x264_wine.bInitialized)
1297 g_x264_wine.bIsWine = false;
1298 QLibrary ntdll("ntdll.dll");
1301 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) g_x264_wine.bIsWine = true;
1302 if(ntdll.resolve("wine_get_version") != NULL) g_x264_wine.bIsWine = true;
1305 g_x264_wine.bInitialized = true;
1308 return g_x264_wine.bIsWine;
1314 static bool x264_event_filter(void *message, long *result)
1316 if((!(X264_DEBUG)) && x264_check_for_debugger())
1318 x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1321 //switch(reinterpret_cast<MSG*>(message)->message)
1323 //case WM_QUERYENDSESSION:
1324 // qWarning("WM_QUERYENDSESSION message received!");
1325 // *result = x264_broadcast(x264_event_queryendsession, false) ? TRUE : FALSE;
1327 //case WM_ENDSESSION:
1328 // qWarning("WM_ENDSESSION message received!");
1329 // if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
1331 // x264_broadcast(x264_event_endsession, false);
1332 // if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
1334 // app->closeAllWindows();
1337 // x264_finalization();
1343 // /*ignore this message and let Qt handle it*/
1351 * Check for process elevation
1353 static bool x264_process_is_elevated(bool *bIsUacEnabled = NULL)
1355 bool bIsProcessElevated = false;
1356 if(bIsUacEnabled) *bIsUacEnabled = false;
1357 HANDLE hToken = NULL;
1359 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1361 TOKEN_ELEVATION_TYPE tokenElevationType;
1363 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
1365 if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
1367 switch(tokenElevationType)
1369 case TokenElevationTypeDefault:
1370 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1372 case TokenElevationTypeFull:
1373 qWarning("Process token elevation type: Full -> potential security risk!\n");
1374 bIsProcessElevated = true;
1375 if(bIsUacEnabled) *bIsUacEnabled = true;
1377 case TokenElevationTypeLimited:
1378 qDebug("Process token elevation type: Limited -> not elevated.\n");
1379 if(bIsUacEnabled) *bIsUacEnabled = true;
1382 qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
1388 qWarning("GetTokenInformation() return an unexpected size!");
1391 CloseHandle(hToken);
1395 qWarning("Failed to open process token!");
1398 return bIsProcessElevated;
1402 * Check if the current user is an administartor (helper function)
1404 static bool x264_user_is_admin_helper(void)
1406 HANDLE hToken = NULL;
1407 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1413 if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
1415 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1417 CloseHandle(hToken);
1422 PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
1425 CloseHandle(hToken);
1429 if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
1432 CloseHandle(hToken);
1436 PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
1437 if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
1440 CloseHandle(hToken);
1444 bool bResult = false;
1445 for(DWORD i = 0; i < lpGroups->GroupCount; i++)
1447 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
1456 CloseHandle(hToken);
1461 * Check if the current user is an administartor
1463 bool x264_user_is_admin(void)
1465 bool isAdmin = false;
1467 //Check for process elevation and UAC support first!
1468 if(x264_process_is_elevated(&isAdmin))
1470 qWarning("Process is elevated -> user is admin!");
1474 //If not elevated and UAC is not available -> user must be in admin group!
1477 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
1478 isAdmin = x264_user_is_admin_helper();
1485 * Initialize Qt framework
1487 bool x264_init_qt(int argc, char* argv[])
1489 static bool qt_initialized = false;
1490 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1491 const QStringList &arguments = x264_arguments();
1493 //Don't initialized again, if done already
1499 //Secure DLL loading
1500 QLibrary kernel32("kernel32.dll");
1503 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1504 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1507 //Extract executable name from argv[] array
1508 QString executableName = QLatin1String("x264_launcher.exe");
1509 if(arguments.count() > 0)
1511 static const char *delimiters = "\\/:?";
1512 executableName = arguments[0].trimmed();
1513 for(int i = 0; delimiters[i]; i++)
1515 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1516 if(temp >= 0) executableName = executableName.mid(temp + 1);
1518 executableName = executableName.trimmed();
1519 if(executableName.isEmpty())
1521 executableName = QLatin1String("x264_launcher.exe");
1527 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1528 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1529 if(_stricmp(qVersion(), QT_VERSION_STR))
1531 qFatal("%s", QApplication::tr("Executable '%1' requires Qt v%2, but found Qt v%3.").arg(executableName, QString::fromLatin1(QT_VERSION_STR), QString::fromLatin1(qVersion())).toLatin1().constData());
1534 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1536 qFatal("%s", QApplication::tr("Executable '%1' was built for Qt '%2', but found Qt '%3'.").arg(executableName, QString::fromLatin1(QT_BUILD_KEY), QLibraryInfo::buildKey()).toLatin1().constData());
1540 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1541 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1544 //Check the Windows version
1545 const x264_os_version_t &osVersionNo = x264_get_os_version();
1546 if(osVersionNo < x264_winver_winxp)
1548 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
1551 //Supported Windows version?
1552 if(osVersionNo == x264_winver_winxp)
1554 qDebug("Running on Windows XP or Windows XP Media Center Edition.\n"); //x264_check_compatibility_mode("GetLargePageMinimum", executableName);
1556 else if(osVersionNo == x264_winver_xpx64)
1558 qDebug("Running on Windows Server 2003, Windows Server 2003 R2 or Windows XP x64.\n"); //x264_check_compatibility_mode("GetLocaleInfoEx", executableName);
1560 else if(osVersionNo == x264_winver_vista)
1562 qDebug("Running on Windows Vista or Windows Server 2008.\n"); //x264_check_compatibility_mode("CreateRemoteThreadEx", executableName*/);
1564 else if(osVersionNo == x264_winver_win70)
1566 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n"); //x264_check_compatibility_mode("CreateFile2", executableName);
1568 else if(osVersionNo == x264_winver_win80)
1570 qDebug("Running on Windows 8 or Windows Server 2012.\n"); //x264_check_compatibility_mode("FindPackagesByPackageFamily", executableName);
1572 else if(osVersionNo == x264_winver_win81)
1574 qDebug("Running on Windows 8.1 or Windows Server 2012 R2.\n"); //x264_check_compatibility_mode(NULL, executableName);
1578 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersionNo.versionMajor, osVersionNo.versionMinor);
1579 qWarning("%s\n", QUTF8(message));
1580 MessageBoxW(NULL, QWCHAR(message), L"Simple x264 Launcher", MB_OK | MB_TOPMOST | MB_ICONWARNING);
1583 //Check for compat mode
1584 if(osVersionNo.overrideFlag && (osVersionNo <= x264_winver_win81))
1586 qWarning("Windows compatibility mode detected!");
1587 if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive))
1589 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
1595 if(x264_detect_wine())
1597 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1600 //Set text Codec for locale
1601 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1603 //Create Qt application instance
1604 QApplication *application = new QApplication(argc, argv);
1606 //Load plugins from application directory
1607 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1608 qDebug("Library Path:\n%s\n", QUTF8(QApplication::libraryPaths().first()));
1610 //Create Qt application instance and setup version info
1611 application->setApplicationName("Simple x264 Launcher");
1612 application->setApplicationVersion(QString().sprintf("%d.%02d", x264_version_major(), x264_version_minor()));
1613 application->setOrganizationName("LoRd_MuldeR");
1614 application->setOrganizationDomain("mulder.at.gg");
1615 application->setWindowIcon(QIcon(":/icons/movie.ico"));
1616 application->setEventFilter(x264_event_filter);
1618 //Check for supported image formats
1619 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1620 for(int i = 0; g_x264_imageformats[i]; i++)
1622 if(!supportedFormats.contains(g_x264_imageformats[i]))
1624 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_x264_imageformats[i]);
1629 //Add default translations
1631 QWriteLocker writeLockTranslations(&g_x264_translation.lock);
1632 if(!g_x264_translation.files) g_x264_translation.files = new QMap<QString, QString>();
1633 if(!g_x264_translation.names) g_x264_translation.names = new QMap<QString, QString>();
1634 g_x264_translation.files->insert(X264_DEFAULT_LANGID, "");
1635 g_x264_translation.names->insert(X264_DEFAULT_LANGID, "English");
1636 writeLockTranslations.unlock();
1639 //Check for process elevation
1640 if(x264_process_is_elevated() && (!x264_detect_wine()))
1642 QMessageBox messageBox(QMessageBox::Warning, "Simple x264 Launcher", "<nobr>Simple x264 Launcher was started with 'elevated' rights, altough it does not need these rights.<br>Running an applications with unnecessary rights is a potential security risk!</nobr>", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
1643 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1644 messageBox.addButton("Ignore", QMessageBox::NoRole);
1645 if(messageBox.exec() == 0)
1651 //Update console icon, if a console is attached
1652 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1653 if(g_x264_console_attached && (!x264_detect_wine()))
1655 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1656 QLibrary kernel32("kernel32.dll");
1659 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1660 QPixmap pixmap = QIcon(":/icons/movie.ico").pixmap(16, 16);
1661 if((SetConsoleIconPtr != NULL) && (!pixmap.isNull())) SetConsoleIconPtr(pixmap.toWinHICON());
1668 qt_initialized = true;
1673 * Suspend or resume process
1675 bool x264_suspendProcess(const QProcess *proc, const bool suspend)
1677 if(Q_PID pid = proc->pid())
1681 return (SuspendThread(pid->hThread) != ((DWORD) -1));
1685 return (ResumeThread(pid->hThread) != ((DWORD) -1));
1695 * Convert path to short/ANSI path
1697 QString x264_path2ansi(const QString &longPath, bool makeLowercase)
1699 QString shortPath = longPath;
1701 const QString longPathNative = QDir::toNativeSeparators(longPath);
1702 DWORD buffSize = GetShortPathNameW(QWCHAR(longPathNative), NULL, NULL);
1706 wchar_t *buffer = (wchar_t*) _malloca(sizeof(wchar_t) * buffSize);
1707 DWORD result = GetShortPathNameW(QWCHAR(longPathNative), buffer, buffSize);
1709 if((result > 0) && (result < buffSize))
1711 shortPath = QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer), result));
1715 QFileInfo info(shortPath);
1716 shortPath = QString("%1/%2").arg(info.absolutePath(), info.fileName().toLower());
1728 * Set the process priority class for current process
1730 bool x264_change_process_priority(const int priority)
1732 return x264_change_process_priority(GetCurrentProcess(), priority);
1736 * Set the process priority class for specified process
1738 bool x264_change_process_priority(const QProcess *proc, const int priority)
1740 if(Q_PID qPid = proc->pid())
1742 return x264_change_process_priority(qPid->hProcess, priority);
1751 * Set the process priority class for specified process
1753 bool x264_change_process_priority(void *hProcess, const int priority)
1757 switch(qBound(-2, priority, 2))
1760 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1763 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1765 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1769 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1772 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1774 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1778 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1786 * Play a sound (from resources)
1788 bool x264_play_sound(const unsigned short uiSoundIdx, const bool bAsync, const wchar_t *alias)
1792 return PlaySound(alias, GetModuleHandle(NULL), (SND_ALIAS | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE;
1796 return PlaySound(MAKEINTRESOURCE(uiSoundIdx), GetModuleHandle(NULL), (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE;
1801 * Current process ID
1803 unsigned int x264_process_id(void)
1805 return GetCurrentProcessId();
1809 * Current process ID
1811 unsigned int x264_process_id(QProcess &process)
1813 if(Q_PID pid = process.pid())
1815 return pid->dwProcessId;
1821 * Make a window blink (to draw user's attention)
1823 void x264_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
1825 static QMutex blinkMutex;
1827 const double maxOpac = 1.0;
1828 const double minOpac = 0.3;
1829 const double delOpac = 0.1;
1831 if(!blinkMutex.tryLock())
1833 qWarning("Blinking is already in progress, skipping!");
1839 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
1840 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
1841 const double opacity = poWindow->windowOpacity();
1843 for(unsigned int i = 0; i < count; i++)
1845 for(double x = maxOpac; x >= minOpac; x -= delOpac)
1847 poWindow->setWindowOpacity(x);
1848 QApplication::processEvents();
1852 for(double x = minOpac; x <= maxOpac; x += delOpac)
1854 poWindow->setWindowOpacity(x);
1855 QApplication::processEvents();
1860 poWindow->setWindowOpacity(opacity);
1861 QApplication::processEvents();
1862 blinkMutex.unlock();
1866 blinkMutex.unlock();
1867 qWarning("Exception error while blinking!");
1872 * Bring the specifed window to the front
1874 static bool x264_bring_to_front(const HWND hWin)
1878 const bool ret = (SetForegroundWindow(hWin) != FALSE);
1879 SwitchToThisWindow(hWin, TRUE);
1886 * Bring the specifed window to the front
1888 bool x264_bring_to_front(const QWidget *win)
1892 return x264_bring_to_front(win->winId());
1898 * Bring window of the specifed process to the front (callback)
1900 static BOOL CALLBACK x264_bring_process_to_front_helper(HWND hwnd, LPARAM lParam)
1902 DWORD processId = *reinterpret_cast<WORD*>(lParam);
1903 DWORD windowProcessId = NULL;
1904 GetWindowThreadProcessId(hwnd, &windowProcessId);
1905 if(windowProcessId == processId)
1907 x264_bring_to_front(hwnd);
1914 * Bring window of the specifed process to the front
1916 bool x264_bring_process_to_front(const unsigned long pid)
1918 return EnumWindows(x264_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE;
1922 * Check if file is a valid Win32/Win64 executable
1924 bool x264_is_executable(const QString &path)
1926 bool bIsExecutable = false;
1928 if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(path)), &binaryType))
1930 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
1932 return bIsExecutable;
1936 * Read value from registry
1938 QString x264_query_reg_string(const bool bUser, const QString &path, const QString &name)
1940 QString result; HKEY hKey = NULL;
1941 if(RegOpenKey((bUser ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE), QWCHAR(path), &hKey) == ERROR_SUCCESS)
1943 const size_t DATA_LEN = 2048; wchar_t data[DATA_LEN];
1944 DWORD type = REG_NONE, size = sizeof(wchar_t) * DATA_LEN;
1945 if(RegQueryValueEx(hKey, QWCHAR(name), NULL, &type, ((BYTE*)&data[0]), &size) == ERROR_SUCCESS)
1947 if((type == REG_SZ) || (type == REG_EXPAND_SZ))
1949 result = WCHAR2QSTR(&data[0]);
1958 * Locate known folder on local system
1960 const QString &x264_known_folder(x264_known_folder_t folder_id)
1962 static const int CSIDL_FLAG_CREATE = 0x8000;
1963 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
1970 static s_folders[] =
1972 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
1973 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
1974 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
1975 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
1978 size_t folderId = size_t(-1);
1982 case x264_folder_localappdata: folderId = 0; break;
1983 case x264_folder_programfiles: folderId = 1; break;
1984 case x264_folder_systroot_dir: folderId = 2; break;
1985 case x264_folder_systemfolder: folderId = 3; break;
1988 if(folderId == size_t(-1))
1990 qWarning("Invalid 'known' folder was requested!");
1991 return *reinterpret_cast<QString*>(NULL);
1994 QReadLocker readLock(&g_x264_known_folder.lock);
1997 if(g_x264_known_folder.knownFolders)
1999 if(g_x264_known_folder.knownFolders->contains(folderId))
2001 return (*g_x264_known_folder.knownFolders)[folderId];
2005 //Obtain write lock to initialize
2007 QWriteLocker writeLock(&g_x264_known_folder.lock);
2009 //Still not in cache?
2010 if(g_x264_known_folder.knownFolders)
2012 if(g_x264_known_folder.knownFolders->contains(folderId))
2014 return (*g_x264_known_folder.knownFolders)[folderId];
2018 //Initialize on first call
2019 if(!g_x264_known_folder.knownFolders)
2021 QLibrary shell32("shell32.dll");
2024 g_x264_known_folder.getFolderPath = (SHGetFolderPath_t) shell32.resolve("SHGetFolderPathW");
2025 g_x264_known_folder.getKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
2027 g_x264_known_folder.knownFolders = new QMap<size_t, QString>();
2032 //Now try to get the folder path!
2033 if(g_x264_known_folder.getKnownFolderPath)
2036 if(g_x264_known_folder.getKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
2038 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
2039 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
2040 if(folderTemp.exists())
2042 folderPath = folderTemp.canonicalPath();
2044 CoTaskMemFree(path);
2047 else if(g_x264_known_folder.getFolderPath)
2049 WCHAR *path = new WCHAR[4096];
2050 if(g_x264_known_folder.getFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path) == S_OK)
2052 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
2053 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
2054 if(folderTemp.exists())
2056 folderPath = folderTemp.canonicalPath();
2059 X264_DELETE_ARRAY(path);
2063 g_x264_known_folder.knownFolders->insert(folderId, folderPath);
2064 return (*g_x264_known_folder.knownFolders)[folderId];
2068 * Try to initialize the folder (with *write* access)
2070 static QString x264_try_init_folder(const QString &folderPath)
2072 static const char *DATA = "Lorem ipsum dolor sit amet, consectetur, adipisci velit!";
2074 bool success = false;
2076 const QFileInfo folderInfo(folderPath);
2077 const QDir folderDir(folderInfo.absoluteFilePath());
2079 //Create folder, if it does *not* exist yet
2080 for(int i = 0; i < 16; i++)
2082 if(folderDir.exists()) break;
2083 folderDir.mkpath(".");
2086 //Make sure folder exists now *and* is writable
2087 if(folderDir.exists())
2089 const QByteArray testData = QByteArray(DATA);
2090 for(int i = 0; i < 32; i++)
2092 QFile testFile(folderDir.absoluteFilePath(QString("~%1.tmp").arg(x264_rand_str())));
2093 if(testFile.open(QIODevice::ReadWrite | QIODevice::Truncate))
2095 if(testFile.write(testData) >= testData.size())
2106 return (success ? folderDir.canonicalPath() : QString());
2110 * Detect the TEMP directory
2112 const QString &x264_temp_directory(void)
2114 QReadLocker readLock(&g_x264_temp_folder.lock);
2116 if(g_x264_temp_folder.path)
2118 return *g_x264_temp_folder.path;
2122 QWriteLocker writeLock(&g_x264_temp_folder.lock);
2124 if(!g_x264_temp_folder.path)
2127 g_x264_temp_folder.path = new QString(x264_try_init_folder(QDir::temp().absolutePath()));
2129 //Fall back to %LOCALAPPDATA%, if %TEMP% didn't work
2130 if(g_x264_temp_folder.path->isEmpty())
2132 qWarning("%%TEMP%% directory not found -> falling back to %%LOCALAPPDATA%%");
2133 static const x264_known_folder_t folderId[2] = { x264_folder_localappdata, x264_folder_systroot_dir };
2134 for(size_t id = 0; (g_x264_temp_folder.path->isEmpty() && (id < 2)); id++)
2136 const QString &localAppData = x264_known_folder(x264_folder_localappdata);
2137 if(!localAppData.isEmpty())
2139 *g_x264_temp_folder.path = x264_try_init_folder(QString("%1/Temp").arg(localAppData));
2143 qWarning("%%LOCALAPPDATA%% directory could not be found!");
2148 //Failed to init TEMP folder?
2149 if(g_x264_temp_folder.path->isEmpty())
2151 qWarning("Temporary directory could not be initialized !!!");
2155 return *g_x264_temp_folder.path;
2159 * Display the window's close button
2161 bool x264_enable_close_button(const QWidget *win, const bool bEnable)
2165 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
2167 ok = (EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (bEnable ? MF_ENABLED : MF_GRAYED)) == TRUE);
2176 bool x264_beep(int beepType)
2180 case x264_beep_info: return MessageBeep(MB_ICONASTERISK) == TRUE; break;
2181 case x264_beep_warning: return MessageBeep(MB_ICONEXCLAMATION) == TRUE; break;
2182 case x264_beep_error: return MessageBeep(MB_ICONHAND) == TRUE; break;
2183 default: return false;
2188 * Shutdown the computer
2190 bool x264_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
2192 HANDLE hToken = NULL;
2194 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2196 TOKEN_PRIVILEGES privileges;
2197 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2198 privileges.PrivilegeCount = 1;
2199 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2201 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2203 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2205 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2206 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2215 * Check the network connection status
2217 int x264_network_status(void)
2220 const BOOL ret = IsNetworkAlive(&dwFlags);
2221 if(GetLastError() == 0)
2223 return (ret != FALSE) ? x264_network_yes : x264_network_non;
2225 return x264_network_err;
2229 * Setup QPorcess object
2231 void x264_init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
2233 //Environment variable names
2234 static const char *const s_envvar_names_temp[] =
2236 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
2238 static const char *const s_envvar_names_remove[] =
2240 "WGETRC", "SYSTEM_WGETRC", "HTTP_PROXY", "FTP_PROXY", "NO_PROXY", "GNUPGHOME", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LANG", NULL
2243 //Initialize environment
2244 QProcessEnvironment env = process.processEnvironment();
2245 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
2247 //Clean a number of enviroment variables that might affect our tools
2248 for(size_t i = 0; s_envvar_names_remove[i]; i++)
2250 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
2251 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
2254 const QString tempDir = QDir::toNativeSeparators(x264_temp_directory());
2256 //Replace TEMP directory in environment
2259 for(size_t i = 0; s_envvar_names_temp[i]; i++)
2261 env.insert(s_envvar_names_temp[i], tempDir);
2265 //Setup PATH variable
2266 const QString path = env.value("PATH", QString()).trimmed();
2267 env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
2269 //Setup QPorcess object
2270 process.setWorkingDirectory(wokringDir);
2271 process.setProcessChannelMode(QProcess::MergedChannels);
2272 process.setReadChannel(QProcess::StandardOutput);
2273 process.setProcessEnvironment(env);
2277 * Inform the system that it is in use, thereby preventing the system from entering sleep
2279 bool x264_set_thread_execution_state(const bool systemRequired)
2281 EXECUTION_STATE state = NULL;
2284 state = SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);
2288 state = SetThreadExecutionState(ES_CONTINUOUS);
2290 return (state != NULL);
2294 * Check for debugger (detect routine)
2296 static __forceinline bool x264_check_for_debugger(void)
2300 CloseHandle((HANDLE)((DWORD_PTR)-3));
2312 return IsDebuggerPresent();
2318 * Check for debugger (thread proc)
2320 static unsigned int __stdcall x264_debug_thread_proc(LPVOID lpParameter)
2322 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
2325 if(x264_check_for_debugger())
2327 x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2335 * Check for debugger (startup routine)
2337 static HANDLE x264_debug_thread_init()
2339 if(x264_check_for_debugger())
2341 x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2343 const uintptr_t h = _beginthreadex(NULL, 0, x264_debug_thread_proc, NULL, 0, NULL);
2344 return (HANDLE)(h^0xdeadbeef);
2348 * Fatal application exit
2350 #pragma intrinsic(_InterlockedExchange)
2351 void x264_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2353 static volatile long bFatalFlag = 0L;
2355 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2357 if(GetCurrentThreadId() != g_main_thread_id)
2359 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2360 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2365 MessageBoxW(NULL, errorBoxMessage, L"Simple x264 Launcher - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2368 FatalAppExit(0, exitMessage);
2372 TerminateProcess(GetCurrentProcess(), -1);
2378 * Entry point checks
2380 static DWORD x264_entry_check(void);
2381 static DWORD g_x264_entry_check_result = x264_entry_check();
2382 static DWORD g_x264_entry_check_flag = 0x789E09B2;
2383 static DWORD x264_entry_check(void)
2385 volatile DWORD retVal = 0xA199B5AF;
2386 if(g_x264_entry_check_flag != 0x8761F64D)
2388 x264_fatal_exit(L"Application initialization has failed, take care!");
2394 * Application entry point (runs before static initializers)
2398 int WinMainCRTStartup(void);
2400 int x264_entry_point(void)
2402 if((!X264_DEBUG) && x264_check_for_debugger())
2404 x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2406 if(g_x264_entry_check_flag != 0x789E09B2)
2408 x264_fatal_exit(L"Application initialization has failed, take care!");
2411 //Zero *before* constructors are called
2412 X264_ZERO_MEMORY(g_x264_argv);
2413 X264_ZERO_MEMORY(g_x264_os_version);
2414 X264_ZERO_MEMORY(g_x264_portable);
2415 X264_ZERO_MEMORY(g_x264_known_folder);
2416 X264_ZERO_MEMORY(g_x264_temp_folder);
2418 //Make sure we will pass the check
2419 g_x264_entry_check_flag = ~g_x264_entry_check_flag;
2421 //Now initialize the C Runtime library!
2422 return WinMainCRTStartup();
2427 * Initialize debug thread
2429 static const HANDLE g_debug_thread = X264_DEBUG ? NULL : x264_debug_thread_init();
2432 * Get number private bytes [debug only]
2434 size_t x264_dbg_private_bytes(void)
2437 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2438 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2439 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2440 return memoryCounters.PrivateUsage;
2442 throw "Cannot call this function in a non-debug build!";
2447 * Finalization function
2449 void x264_finalization(void)
2451 //Destroy Qt application object
2452 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2453 X264_DELETE(application);
2455 //Free STDOUT and STDERR buffers
2456 if(g_x264_console_attached)
2458 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2460 std::cout.rdbuf(NULL);
2463 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2465 std::cerr.rdbuf(NULL);
2471 X264_DELETE(g_x264_argv.list);
2473 //Clear folders cache
2474 X264_DELETE(g_x264_known_folder.knownFolders);
2475 X264_DELETE(g_x264_temp_folder.path);