OSDN Git Service

Bump version.
[x264-launcher/x264-launcher.git] / src / global.cpp
index f101cc7..73170c9 100644 (file)
@@ -1,6 +1,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 // Simple x264 Launcher
-// Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2016 LoRd_MuldeR <MuldeR2@GMX.de>
 //
 // This program is free software; you can redistribute it and/or modify
 // it under the terms of the GNU General Public License as published by
 // http://www.gnu.org/licenses/gpl-2.0.txt
 ///////////////////////////////////////////////////////////////////////////////
 
+//x264 includes
 #include "global.h"
+#include "targetver.h"
+
+//Windows includes
+#define NOMINMAX
+#define WIN32_LEAN_AND_MEAN
+#include <Windows.h>
+#include <MMSystem.h>
+#include <ShellAPI.h>
+#include <Objbase.h>
+#include <Psapi.h>
+#include <SensAPI.h>
+
+//C++ includes
+#include <stdio.h>
+#include <string.h>
+#include <iostream>
+#include <time.h>
+
+//VLD
+#include <vld.h>
+
+//Version
+#define ENABLE_X264_VERSION_INCLUDE
 #include "version.h"
+#undef  ENABLE_X264_VERSION_INCLUDE
+
+//MUtils includes
+#include <MUtils/Global.h>
 
 //Qt includes
 #include <QApplication>
@@ -36,6 +64,7 @@
 #include <QSysInfo>
 #include <QStringList>
 #include <QSystemSemaphore>
+#include <QDesktopServices>
 #include <QMutex>
 #include <QTextCodec>
 #include <QLibrary>
 #include <QTimer>
 #include <QLibraryInfo>
 #include <QEvent>
+#include <QReadLocker>
+#include <QWriteLocker>
+#include <QProcess>
 
 //CRT includes
 #include <fstream>
 #include <io.h>
 #include <fcntl.h>
 #include <intrin.h>
+#include <process.h>
 
 //Debug only includes
 #if X264_DEBUG
 #include <Psapi.h>
 #endif
 
-//Global vars
-static bool g_x264_console_attached = false;
-static QMutex g_x264_message_mutex;
-static const DWORD g_main_thread_id = GetCurrentThreadId();
-static FILE *g_x264_log_file = NULL;
-static QDate g_x264_version_date;
+//Global types
+typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
+typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
 
 //Const
 static const char *g_x264_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
@@ -74,273 +104,68 @@ static const struct
 {
        unsigned int ver_major;
        unsigned int ver_minor;
-       const char* ver_date;
-       const char* ver_time;
+       unsigned int ver_patch;
+       unsigned int ver_build;
 }
 g_x264_version =
 {
-       VER_X264_MAJOR,
-       VER_X264_MINOR,
-       __DATE__,
-       __TIME__
+       (VER_X264_MAJOR),
+       (VER_X264_MINOR),
+       (VER_X264_PATCH),
+       (VER_X264_BUILD),
 };
 
-//Compiler detection
-//The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
-#if defined(__INTEL_COMPILER)
-       #if (__INTEL_COMPILER >= 1200)
-               static const char *g_x264_version_compiler = "ICL 12.x";
-       #elif (__INTEL_COMPILER >= 1100)
-               static const char *g_x264_version_compiler = = "ICL 11.x";
-       #elif (__INTEL_COMPILER >= 1000)
-               static const char *g_x264_version_compiler = = "ICL 10.x";
-       #else
-               #error Compiler is not supported!
-       #endif
-#elif defined(_MSC_VER)
-       #if (_MSC_VER == 1600)
-               #if (_MSC_FULL_VER >= 160040219)
-                       static const char *g_x264_version_compiler = "MSVC 2010-SP1";
-               #else
-                       static const char *g_x264_version_compiler = "MSVC 2010";
-               #endif
-       #elif (_MSC_VER == 1500)
-               #if (_MSC_FULL_VER >= 150030729)
-                       static const char *g_x264_version_compiler = "MSVC 2008-SP1";
-               #else
-                       static const char *g_x264_version_compiler = "MSVC 2008";
-               #endif
-       #else
-               #error Compiler is not supported!
-       #endif
-
-       // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
-       #if !defined(_M_X64) && defined(_M_IX86_FP)
-               #if (_M_IX86_FP == 1)
-                       x264_COMPILER_WARNING("SSE instruction set is enabled!")
-               #elif (_M_IX86_FP == 2)
-                       x264_COMPILER_WARNING("SSE2 instruction set is enabled!")
-               #endif
-       #endif
-#else
-       #error Compiler is not supported!
-#endif
-
-//Architecture detection
-#if defined(_M_X64)
-       static const char *g_x264_version_arch = "x64";
-#elif defined(_M_IX86)
-       static const char *g_x264_version_arch = "x86";
-#else
-       #error Architecture is not supported!
-#endif
-
-/*
- * Global exception handler
- */
-LONG WINAPI x264_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
-{
-       if(GetCurrentThreadId() != g_main_thread_id)
-       {
-               HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
-               if(mainThread) TerminateThread(mainThread, ULONG_MAX);
-       }
-
-       FatalAppExit(0, L"Unhandeled exception handler invoked, application will exit!");
-       TerminateProcess(GetCurrentProcess(), -1);
-       return LONG_MAX;
-}
-
-/*
- * Invalid parameters handler
- */
-void x264_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
-{
-       if(GetCurrentThreadId() != g_main_thread_id)
-       {
-               HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
-               if(mainThread) TerminateThread(mainThread, ULONG_MAX);
-       }
+//Portable mode
+static QReadWriteLock g_portableModeLock;
+static bool           g_portableModeData = false;
+static bool           g_portableModeInit = false;
 
-       FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
-       TerminateProcess(GetCurrentProcess(), -1);
-}
+//Data path
+static QString        g_dataPathData;
+static QReadWriteLock g_dataPathLock;
 
-/*
- * Change console text color
- */
-static void x264_console_color(FILE* file, WORD attributes)
-{
-       const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
-       if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
-       {
-               SetConsoleTextAttribute(hConsole, attributes);
-       }
-}
+///////////////////////////////////////////////////////////////////////////////
+// MACROS
+///////////////////////////////////////////////////////////////////////////////
 
-/*
- * Qt message handler
- */
-void x264_message_handler(QtMsgType type, const char *msg)
+//String helper
+#define CLEAN_OUTPUT_STRING(STR) do \
+{ \
+       const char CTRL_CHARS[3] = { '\r', '\n', '\t' }; \
+       for(size_t i = 0; i < 3; i++) \
+       { \
+               while(char *pos = strchr((STR), CTRL_CHARS[i])) *pos = char(0x20); \
+       } \
+} \
+while(0)
+
+//String helper
+#define TRIM_LEFT(STR) do \
+{ \
+       const char WHITE_SPACE[4] = { char(0x20), '\r', '\n', '\t' }; \
+       for(size_t i = 0; i < 4; i++) \
+       { \
+               while(*(STR) == WHITE_SPACE[i]) (STR)++; \
+       } \
+} \
+while(0)
+
+//Check for CLI flag
+static inline bool _CHECK_FLAG(const int argc, char **argv, const char *flag)
 {
-       static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
-       
-       QMutexLocker lock(&g_x264_message_mutex);
-
-       if(g_x264_log_file)
-       {
-               static char prefix[] = "DWCF";
-               int index = qBound(0, static_cast<int>(type), 3);
-               unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
-               QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
-               fprintf(g_x264_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
-               fflush(g_x264_log_file);
-       }
-
-       if(g_x264_console_attached)
-       {
-               UINT oldOutputCP = GetConsoleOutputCP();
-               if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
-
-               switch(type)
-               {
-               case QtCriticalMsg:
-               case QtFatalMsg:
-                       fflush(stdout);
-                       fflush(stderr);
-                       x264_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
-                       fprintf(stderr, GURU_MEDITATION);
-                       fprintf(stderr, "%s\n", msg);
-                       fflush(stderr);
-                       break;
-               case QtWarningMsg:
-                       x264_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
-                       fprintf(stderr, "%s\n", msg);
-                       fflush(stderr);
-                       break;
-               default:
-                       x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
-                       fprintf(stderr, "%s\n", msg);
-                       fflush(stderr);
-                       break;
-               }
-       
-               x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
-               if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
-       }
-       else
-       {
-               QString temp("[x264][%1] %2");
-               
-               switch(type)
-               {
-               case QtCriticalMsg:
-               case QtFatalMsg:
-                       temp = temp.arg("C", QString::fromUtf8(msg));
-                       break;
-               case QtWarningMsg:
-                       temp = temp.arg("W", QString::fromUtf8(msg));
-                       break;
-               default:
-                       temp = temp.arg("I", QString::fromUtf8(msg));
-                       break;
-               }
-
-               temp.replace("\n", "\t").append("\n");
-               OutputDebugStringA(temp.toLatin1().constData());
-       }
-
-       if(type == QtCriticalMsg || type == QtFatalMsg)
+       for(int i = 1; i < argc; i++)
        {
-               lock.unlock();
-               MessageBoxW(NULL, QWCHAR(QString::fromUtf8(msg)), L"Simple x264 Launcher - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
-               FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
-               TerminateProcess(GetCurrentProcess(), -1);
+               if(_stricmp(argv[i], flag) == 0) return true;
        }
+       return false;
 }
 
-/*
- * Initialize the console
- */
-void x264_init_console(int argc, char* argv[])
-{
-       bool enableConsole = true; //x264_version_demo();
+#define CHECK_FLAG(FLAG) _CHECK_FLAG(argc, argv, "--" FLAG)
+#define X264_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
 
-       if(_environ)
-       {
-               wchar_t *logfile = NULL;
-               size_t logfile_len = 0;
-               if(!_wdupenv_s(&logfile, &logfile_len, L"X264_LAUNCHER_LOGFILE"))
-               {
-                       if(logfile && (logfile_len > 0))
-                       {
-                               FILE *temp = NULL;
-                               if(!_wfopen_s(&temp, logfile, L"wb"))
-                               {
-                                       fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
-                                       g_x264_log_file = temp;
-                               }
-                               free(logfile);
-                       }
-               }
-       }
-
-       if(!X264_DEBUG)
-       {
-               for(int i = 0; i < argc; i++)
-               {
-                       if(!_stricmp(argv[i], "--console"))
-                       {
-                               enableConsole = true;
-                       }
-                       else if(!_stricmp(argv[i], "--no-console"))
-                       {
-                               enableConsole = false;
-                       }
-               }
-       }
-
-       if(enableConsole)
-       {
-               if(!g_x264_console_attached)
-               {
-                       if(AllocConsole() != FALSE)
-                       {
-                               SetConsoleCtrlHandler(NULL, TRUE);
-                               SetConsoleTitle(L"Simple x264 Launcher | Debug Console");
-                               SetConsoleOutputCP(CP_UTF8);
-                               g_x264_console_attached = true;
-                       }
-               }
-               
-               if(g_x264_console_attached)
-               {
-                       //-------------------------------------------------------------------
-                       //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
-                       //-------------------------------------------------------------------
-                       const int flags = _O_WRONLY | _O_U8TEXT;
-                       int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
-                       int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
-                       FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
-                       FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
-                       if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
-                       if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
-               }
-
-               HWND hwndConsole = GetConsoleWindow();
-
-               if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
-               {
-                       HMENU hMenu = GetSystemMenu(hwndConsole, 0);
-                       EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
-                       RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
-
-                       SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
-                       SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
-                       SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
-               }
-       }
-}
+///////////////////////////////////////////////////////////////////////////////
+// GLOBAL FUNCTIONS
+///////////////////////////////////////////////////////////////////////////////
 
 /*
  * Version info
@@ -352,475 +177,157 @@ unsigned int x264_version_major(void)
 
 unsigned int x264_version_minor(void)
 {
-       return g_x264_version.ver_minor;
+       return (g_x264_version.ver_minor * 10) + (g_x264_version.ver_patch % 10);
 }
 
-const char *x264_version_compiler(void)
+unsigned int x264_version_build(void)
 {
-       return g_x264_version_compiler;
-}
-
-const char *x264_version_arch(void)
-{
-       return g_x264_version_arch;
+       return g_x264_version.ver_build;
 }
 
 /*
- * Get build date date
+ * Check for portable mode
  */
-const QDate &x264_version_date(void)
+bool x264_is_portable(void)
 {
-       if(!g_x264_version_date.isValid())
+       QReadLocker readLock(&g_portableModeLock);
+
+       if(g_portableModeInit)
        {
-               int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
-               strncpy_s(temp, 12, g_x264_version.ver_date, _TRUNCATE);
+               return g_portableModeData;
+       }
+       
+       readLock.unlock();
+       QWriteLocker writeLock(&g_portableModeLock);
 
-               if(strlen(temp) == 11)
+       if(!g_portableModeInit)
+       {
+               if(VER_X264_PORTABLE_EDITION)
                {
-                       temp[3] = temp[6] = '\0';
-                       date[2] = atoi(&temp[4]);
-                       date[0] = atoi(&temp[7]);
-                       
-                       for(int j = 0; j < 12; j++)
-                       {
-                               if(!_strcmpi(&temp[0], g_x264_months[j]))
-                               {
-                                       date[1] = j+1;
-                                       break;
-                               }
-                       }
-
-                       g_x264_version_date = QDate(date[0], date[1], date[2]);
+                       qWarning("Simple x264 Launcher portable edition!\n");
+                       g_portableModeData = true;
                }
-
-               if(!g_x264_version_date.isValid())
+               else
                {
-                       qFatal("Internal error: Date format could not be recognized!");
+                       QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
+                       int idx1 = baseName.indexOf("x264", 0, Qt::CaseInsensitive);
+                       int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
+                       g_portableModeData = (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
                }
+               g_portableModeInit = true;
        }
-
-       return g_x264_version_date;
-}
-
-const char *x264_version_time(void)
-{
-       return g_x264_version.ver_time;
+       
+       return g_portableModeData;
 }
 
 /*
- * Detect CPU features
+ * Get data path (i.e. path to store config files)
  */
-x264_cpu_t x264_detect_cpu_features(int argc, char **argv)
+const QString &x264_data_path(void)
 {
-       typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
-       typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
-       
-       static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
-       static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
-
-       x264_cpu_t features;
-       SYSTEM_INFO systemInfo;
-       int CPUInfo[4] = {-1};
-       char CPUIdentificationString[0x40];
-       char CPUBrandString[0x40];
-
-       memset(&features, 0, sizeof(x264_cpu_t));
-       memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
-       memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
-       memset(CPUBrandString, 0, sizeof(CPUBrandString));
-       
-       __cpuid(CPUInfo, 0);
-       memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
-       memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
-       memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
-       features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
-       strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
-
-       if(CPUInfo[0] >= 1)
-       {
-               __cpuid(CPUInfo, 1);
-               features.mmx = (CPUInfo[3] & 0x800000) || false;
-               features.sse = (CPUInfo[3] & 0x2000000) || false;
-               features.sse2 = (CPUInfo[3] & 0x4000000) || false;
-               features.ssse3 = (CPUInfo[2] & 0x200) || false;
-               features.sse3 = (CPUInfo[2] & 0x1) || false;
-               features.ssse3 = (CPUInfo[2] & 0x200) || false;
-               features.stepping = CPUInfo[0] & 0xf;
-               features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
-               features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
-       }
-
-       __cpuid(CPUInfo, 0x80000000);
-       int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
+       QReadLocker readLock(&g_dataPathLock);
 
-       for(int i = 0x80000002; i <= nExIds; ++i)
+       if(!g_dataPathData.isEmpty())
        {
-               __cpuid(CPUInfo, i);
-               switch(i)
-               {
-               case 0x80000002:
-                       memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
-                       break;
-               case 0x80000003:
-                       memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
-                       break;
-               case 0x80000004:
-                       memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
-                       break;
-               }
+               return g_dataPathData;
        }
-
-       strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
-
-       if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
-       if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
-
-#if !defined(_M_X64 ) && !defined(_M_IA64)
-       if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
-       {
-               QLibrary Kernel32Lib("kernel32.dll");
-               IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
-               GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
-       }
-       if(IsWow64ProcessPtr)
+       
+       readLock.unlock();
+       QWriteLocker writeLock(&g_dataPathLock);
+       
+       if(g_dataPathData.isEmpty())
        {
-               BOOL x64 = FALSE;
-               if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
+               g_dataPathData = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
+               if(g_dataPathData.isEmpty() || x264_is_portable())
                {
-                       features.x64 = x64;
+                       g_dataPathData = QApplication::applicationDirPath();
                }
-       }
-       if(GetNativeSystemInfoPtr)
-       {
-               GetNativeSystemInfoPtr(&systemInfo);
-       }
-       else
-       {
-               GetSystemInfo(&systemInfo);
-       }
-       features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
-#else
-       GetNativeSystemInfo(&systemInfo);
-       features.count = systemInfo.dwNumberOfProcessors;
-       features.x64 = true;
-#endif
-
-       if((argv != NULL) && (argc > 0))
-       {
-               bool flag = false;
-               for(int i = 0; i < argc; i++)
+               if(!QDir(g_dataPathData).mkpath("."))
                {
-                       if(!_stricmp("--force-cpu-no-64bit", argv[i])) { flag = true; features.x64 = false; }
-                       if(!_stricmp("--force-cpu-no-sse", argv[i])) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
-                       if(!_stricmp("--force-cpu-no-intel", argv[i])) { flag = true; features.intel = false; }
+                       qWarning("Data directory could not be created:\n%s\n", g_dataPathData.toUtf8().constData());
+                       g_dataPathData = QDir::currentPath();
                }
-               if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
        }
-
-       return features;
-}
-
-/*
- * Get the native operating system version
- */
-DWORD x264_get_os_version(void)
-{
-       OSVERSIONINFO osVerInfo;
-       memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
-       osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
-       DWORD version = 0;
        
-       if(GetVersionEx(&osVerInfo) == TRUE)
-       {
-               if(osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
-               {
-                       throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
-               }
-               version = (DWORD)((osVerInfo.dwMajorVersion << 16) | (osVerInfo.dwMinorVersion & 0xffff));
-       }
-
-       return version;
+       return g_dataPathData;
 }
 
 /*
- * Check for compatibility mode
+ * Is pre-release version?
  */
-static bool x264_check_compatibility_mode(const char *exportName, const char *executableName)
+bool x264_is_prerelease(void)
 {
-       QLibrary kernel32("kernel32.dll");
-
-       if(exportName != NULL)
-       {
-               if(kernel32.resolve(exportName) != NULL)
-               {
-                       qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
-                       qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
-                       return false;
-               }
-       }
-
-       return true;
+       return (VER_X264_PRE_RELEASE);
 }
 
 /*
- * Check for process elevation
+ * Convert path to short/ANSI path
  */
-static bool x264_check_elevation(void)
+QString x264_path2ansi(const QString &longPath, bool makeLowercase)
 {
-       typedef enum { x264_token_elevationType_class = 18, x264_token_elevation_class = 20 } X264_TOKEN_INFORMATION_CLASS;
-       typedef enum { x264_elevationType_default = 1, x264_elevationType_full, x264_elevationType_limited } X264_TOKEN_ELEVATION_TYPE;
-
-       HANDLE hToken = NULL;
-       bool bIsProcessElevated = false;
+       QString shortPath = longPath;
        
-       if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
-       {
-               X264_TOKEN_ELEVATION_TYPE tokenElevationType;
-               DWORD returnLength;
-               if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) x264_token_elevationType_class, &tokenElevationType, sizeof(X264_TOKEN_ELEVATION_TYPE), &returnLength))
-               {
-                       if(returnLength == sizeof(X264_TOKEN_ELEVATION_TYPE))
-                       {
-                               switch(tokenElevationType)
-                               {
-                               case x264_elevationType_default:
-                                       qDebug("Process token elevation type: Default -> UAC is disabled.\n");
-                                       break;
-                               case x264_elevationType_full:
-                                       qWarning("Process token elevation type: Full -> potential security risk!\n");
-                                       bIsProcessElevated = true;
-                                       break;
-                               case x264_elevationType_limited:
-                                       qDebug("Process token elevation type: Limited -> not elevated.\n");
-                                       break;
-                               }
-                       }
-               }
-               CloseHandle(hToken);
-       }
-       else
-       {
-               qWarning("Failed to open process token!");
-       }
-
-       return !bIsProcessElevated;
-}
-
-/*
- * Initialize Qt framework
- */
-bool x264_init_qt(int argc, char* argv[])
-{
-       static bool qt_initialized = false;
-       bool isWine = false;
-       typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
-
-       //Don't initialized again, if done already
-       if(qt_initialized)
-       {
-               return true;
-       }
+       const QString longPathNative = QDir::toNativeSeparators(longPath);
+       DWORD buffSize = GetShortPathNameW(MUTILS_WCHR(longPathNative), NULL, NULL);
        
-       //Secure DLL loading
-       QLibrary kernel32("kernel32.dll");
-       if(kernel32.load())
-       {
-               SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
-               if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
-               kernel32.unload();
-       }
-
-       //Extract executable name from argv[] array
-       char *executableName = argv[0];
-       while(char *temp = strpbrk(executableName, "\\/:?"))
-       {
-               executableName = temp + 1;
-       }
-
-       //Check Qt version
-       qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
-       qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
-       if(_stricmp(qVersion(), QT_VERSION_STR))
-       {
-               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());
-               return false;
-       }
-       if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
-       {
-               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());
-               return false;
-       }
-
-       //Check the Windows version
-       switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
-       {
-       case 0:
-       case QSysInfo::WV_NT:
-               qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
-               break;
-       case QSysInfo::WV_2000:
-               qDebug("Running on Windows 2000 (not officially supported!).\n");
-               x264_check_compatibility_mode("GetNativeSystemInfo", executableName);
-               break;
-       case QSysInfo::WV_XP:
-               qDebug("Running on Windows XP.\n");
-               x264_check_compatibility_mode("GetLargePageMinimum", executableName);
-               break;
-       case QSysInfo::WV_2003:
-               qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
-               x264_check_compatibility_mode("GetLocaleInfoEx", executableName);
-               break;
-       case QSysInfo::WV_VISTA:
-               qDebug("Running on Windows Vista or Windows Server 2008.\n");
-               x264_check_compatibility_mode("CreateRemoteThreadEx", executableName);
-               break;
-       case QSysInfo::WV_WINDOWS7:
-               qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
-               x264_check_compatibility_mode(NULL, executableName);
-               break;
-       default:
-               {
-                       DWORD osVersionNo = x264_get_os_version();
-                       qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", HIWORD(osVersionNo), LOWORD(osVersionNo));
-               }
-               break;
-       }
-
-       //Check for Wine
-       QLibrary ntdll("ntdll.dll");
-       if(ntdll.load())
+       if(buffSize > 0)
        {
-               if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
-               if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
-               if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
-               ntdll.unload();
-       }
-
-       //Create Qt application instance and setup version info
-       QApplication *application = new QApplication(argc, argv);
-       application->setApplicationName("Simple x264 Launcher");
-       application->setApplicationVersion(QString().sprintf("%d.%02d", x264_version_major(), x264_version_minor())); 
-       application->setOrganizationName("LoRd_MuldeR");
-       application->setOrganizationDomain("mulder.at.gg");
-       application->setWindowIcon(QIcon(":/icons/movie.ico"));
-       
-       //application->setEventFilter(x264_event_filter);
+               wchar_t *buffer = (wchar_t*) _malloca(sizeof(wchar_t) * buffSize);
+               DWORD result = GetShortPathNameW(MUTILS_WCHR(longPathNative), buffer, buffSize);
 
-       //Set text Codec for locale
-       QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
-
-       //Load plugins from application directory
-       QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
-       qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
-
-       //Check for supported image formats
-       QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
-       for(int i = 0; g_x264_imageformats[i]; i++)
-       {
-               if(!supportedFormats.contains(g_x264_imageformats[i]))
+               if((result > 0) && (result < buffSize))
                {
-                       qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_x264_imageformats[i]);
-                       return false;
-               }
-       }
-
-       //Add default translations
-       // g_x264_translation.files.insert(x264_DEFAULT_LANGID, "");
-       // g_x264_translation.names.insert(x264_DEFAULT_LANGID, "English");
+                       shortPath = QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer), result));
 
-       //Check for process elevation
-       if(!x264_check_elevation())
-       {
-               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)
-               {
-                       return false;
+                       if(makeLowercase)
+                       {
+                               QFileInfo info(shortPath);
+                               shortPath = QString("%1/%2").arg(info.absolutePath(), info.fileName().toLower());
+                       }
                }
-       }
 
-       //Update console icon, if a console is attached
-       if(g_x264_console_attached && !isWine)
-       {
-               typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
-               QLibrary kernel32("kernel32.dll");
-               if(kernel32.load())
-               {
-                       SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
-                       if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/movie.ico").pixmap(16, 16).toWinHICON());
-                       kernel32.unload();
-               }
+               _freea(buffer);
+               buffer = NULL;
        }
 
-       //Done
-       qt_initialized = true;
-       return true;
+       return shortPath;
 }
 
 /*
- * Check for debugger (detect routine)
+ * Read value from registry
  */
-static bool x264_check_for_debugger(void)
+QString x264_query_reg_string(const bool bUser, const QString &path, const QString &name)
 {
-       __try 
+       QString result; HKEY hKey = NULL;
+       if(RegOpenKey((bUser ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE), MUTILS_WCHR(path), &hKey) == ERROR_SUCCESS)
        {
-               DebugBreak();
-       }
-       __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) 
-       {
-               return false;
+               const size_t DATA_LEN = 2048; wchar_t data[DATA_LEN];
+               DWORD type = REG_NONE, size = sizeof(wchar_t) * DATA_LEN;
+               if(RegQueryValueEx(hKey, MUTILS_WCHR(name), NULL, &type, ((BYTE*)&data[0]), &size) == ERROR_SUCCESS)
+               {
+                       if((type == REG_SZ) || (type == REG_EXPAND_SZ))
+                       {
+                               result = MUTILS_QSTR(&data[0]);
+                       }
+               }
+               RegCloseKey(hKey);
        }
-       return true;
+       return result;
 }
 
 /*
- * Check for debugger (thread proc)
+ * Inform the system that it is in use, thereby preventing the system from entering sleep
  */
-static void WINAPI x264_debug_thread_proc(__in LPVOID lpParameter)
+bool x264_set_thread_execution_state(const bool systemRequired)
 {
-       while(!(IsDebuggerPresent() || x264_check_for_debugger()))
+       EXECUTION_STATE state = NULL;
+       if(systemRequired)
        {
-               Sleep(333);
+               state = SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);
        }
-       TerminateProcess(GetCurrentProcess(), -1);
-}
-
-/*
- * Check for debugger (startup routine)
- */
-static HANDLE x264_debug_thread_init(void)
-{
-       if(IsDebuggerPresent() || x264_check_for_debugger())
+       else
        {
-               FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
-               TerminateProcess(GetCurrentProcess(), -1);
+               state = SetThreadExecutionState(ES_CONTINUOUS);
        }
-
-       return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&x264_debug_thread_proc), NULL, NULL, NULL);
-}
-
-/*
- * Initialize debug thread
- */
-static const HANDLE g_debug_thread = X264_DEBUG ? NULL : x264_debug_thread_init();
-
-/*
- * Get number private bytes [debug only]
- */
-SIZE_T x264_dbg_private_bytes(void)
-{
-#if X264_DEBUG
-       PROCESS_MEMORY_COUNTERS_EX memoryCounters;
-       memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
-       GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
-       return memoryCounters.PrivateUsage;
-#else
-       throw "Cannot call this function in a non-debug build!";
-#endif //X264_DEBUG
-}
-
-/*
- * Finalization function
- */
-void x264_finalization(void)
-{
-       /* NOP */
+       return (state != NULL);
 }