diff --git a/res/resources.qrc b/res/resources.qrc index 6c45468..c18a2b3 100644 --- a/res/resources.qrc +++ b/res/resources.qrc @@ -61,5 +61,11 @@ images/update_wizard.png images/x264.png images/x265.png + sounds/shutdown.wav + sounds/beep.wav + sounds/beep2.wav + sounds/tada.wav + sounds/shattering.wav + sounds/failure.wav diff --git a/src/binaries.cpp b/src/binaries.cpp index 75d42f4..66993f3 100644 --- a/src/binaries.cpp +++ b/src/binaries.cpp @@ -21,11 +21,15 @@ #include "binaries.h" +//Internal #include "global.h" #include "model_sysinfo.h" #include "model_preferences.h" #include "model_options.h" +//MUtils +#include + /* --- Encooders --- */ QString ENC_BINARY(const SysinfoModel *sysinfo, const OptionsModel::EncType &encType, const OptionsModel::EncArch &encArch, const OptionsModel::EncVariant &encVariant) @@ -68,7 +72,7 @@ QString ENC_BINARY(const SysinfoModel *sysinfo, const OptionsModel::EncType &enc //Sanity check if(baseName.isEmpty() || arch.isEmpty() || variant.isEmpty()) { - THROW("Failed to determine the encoder binarty path!"); + MUTILS_THROW("Failed to determine the encoder binarty path!"); } //Return path diff --git a/src/encoder_abstract.cpp b/src/encoder_abstract.cpp index c031474..e2db8ef 100644 --- a/src/encoder_abstract.cpp +++ b/src/encoder_abstract.cpp @@ -21,6 +21,7 @@ #include "encoder_abstract.h" +//Internal #include "global.h" #include "model_options.h" #include "model_preferences.h" @@ -29,6 +30,11 @@ #include "source_abstract.h" #include "binaries.h" +//MUtils +#include +#include + +//Qt #include #include #include @@ -206,7 +212,7 @@ bool AbstractEncoder::runEncodingPass(AbstractSource* pipedSource, const QString while(!patterns.isEmpty()) { QRegExp *pattern = patterns.takeFirst(); - X264_DELETE(pattern); + MUTILS_DELETE(pattern); } if(bTimeout || bAborted || processEncode.exitCode() != EXIT_SUCCESS) @@ -335,5 +341,5 @@ QString AbstractEncoder::sizeToString(qint64 size) const AbstractEncoderInfo& AbstractEncoder::getEncoderInfo(void) { - THROW("[getEncoderInfo] This function must be overwritten in sub-classes!"); + MUTILS_THROW("[getEncoderInfo] This function must be overwritten in sub-classes!"); } diff --git a/src/encoder_factory.cpp b/src/encoder_factory.cpp index c190bc5..c99aee2 100644 --- a/src/encoder_factory.cpp +++ b/src/encoder_factory.cpp @@ -21,11 +21,15 @@ #include "encoder_factory.h" +//Internal #include "global.h" #include "model_options.h" #include "encoder_x264.h" #include "encoder_x265.h" +//MUtils +#include + AbstractEncoder *EncoderFactory::createEncoder(JobObject *jobObject, const OptionsModel *options, const SysinfoModel *const sysinfo, const PreferencesModel *const preferences, JobStatus &jobStatus, volatile bool *abort, volatile bool *pause, QSemaphore *semaphorePause, const QString &sourceFile, const QString &outputFile) { AbstractEncoder *encoder = NULL; @@ -39,7 +43,7 @@ AbstractEncoder *EncoderFactory::createEncoder(JobObject *jobObject, const Optio encoder = new X265Encoder(jobObject, options, sysinfo, preferences, jobStatus, abort, pause, semaphorePause, sourceFile, outputFile); break; default: - THROW("Unknown encoder type encountered!"); + MUTILS_THROW("Unknown encoder type encountered!"); } return encoder; @@ -54,7 +58,7 @@ const AbstractEncoderInfo& EncoderFactory::getEncoderInfo(const int &encoderType case OptionsModel::EncType_X265: return X265Encoder::getEncoderInfo(); default: - THROW("Unknown encoder type encountered!"); + MUTILS_THROW("Unknown encoder type encountered!"); } return *((AbstractEncoderInfo*)NULL); diff --git a/src/encoder_x264.cpp b/src/encoder_x264.cpp index d633c98..b0a24f2 100644 --- a/src/encoder_x264.cpp +++ b/src/encoder_x264.cpp @@ -21,12 +21,17 @@ #include "encoder_x264.h" +//Internal #include "global.h" #include "model_options.h" #include "model_status.h" #include "binaries.h" #include "mediainfo.h" +//MUtils +#include + +//Qt #include #include #include @@ -185,7 +190,7 @@ X264Encoder::X264Encoder(JobObject *jobObject, const OptionsModel *options, cons { if(options->encType() != OptionsModel::EncType_X264) { - THROW("Invalid encoder type!"); + MUTILS_THROW("Invalid encoder type!"); } } @@ -300,7 +305,7 @@ void X264Encoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, co cmdLine << "--bitrate" << QString::number(m_options->bitrate()); break; default: - THROW("Bad rate-control mode !!!"); + MUTILS_THROW("Bad rate-control mode !!!"); } if((pass == 1) || (pass == 2)) @@ -348,7 +353,7 @@ void X264Encoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, co if(usePipe) { - if(frames < 1) THROW("Frames not set!"); + if(frames < 1) MUTILS_THROW("Frames not set!"); cmdLine << "--frames" << QString::number(frames); cmdLine << "--demuxer" << "y4m"; cmdLine << "--stdin" << "y4m" << "-"; diff --git a/src/encoder_x265.cpp b/src/encoder_x265.cpp index a190f05..4c81bcb 100644 --- a/src/encoder_x265.cpp +++ b/src/encoder_x265.cpp @@ -21,12 +21,17 @@ #include "encoder_x265.h" +//Internal #include "global.h" #include "model_options.h" #include "model_status.h" #include "binaries.h" #include "mediainfo.h" +//MUtils +#include + +//Qt #include #include #include @@ -168,7 +173,7 @@ X265Encoder::X265Encoder(JobObject *jobObject, const OptionsModel *options, cons { if(options->encType() != OptionsModel::EncType_X265) { - THROW("Invalid encoder type!"); + MUTILS_THROW("Invalid encoder type!"); } } @@ -278,7 +283,7 @@ void X265Encoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, co cmdLine << "--bitrate" << QString::number(m_options->bitrate()); break; default: - THROW("Bad rate-control mode !!!"); + MUTILS_THROW("Bad rate-control mode !!!"); break; } @@ -327,7 +332,7 @@ void X265Encoder::buildCommandLine(QStringList &cmdLine, const bool &usePipe, co if(usePipe) { - if(frames < 1) THROW("Frames not set!"); + if(frames < 1) MUTILS_THROW("Frames not set!"); cmdLine << "--frames" << QString::number(frames); cmdLine << "--y4m" << "-"; } diff --git a/src/global.cpp b/src/global.cpp index 5d27b19..b69bab0 100644 --- a/src/global.cpp +++ b/src/global.cpp @@ -47,6 +47,9 @@ #include "version.h" #undef ENABLE_X264_VERSION_INCLUDE +//MUtils includes +#include + //Qt includes #include #include @@ -92,14 +95,6 @@ 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); -//OS version info -typedef struct _x264_os_info_t -{ - const x264_os_version_t version; - const char friendlyName[128]; -} -x264_os_info_t; - //Global vars static bool g_x264_console_attached = false; static QMutex g_x264_message_mutex; @@ -131,50 +126,6 @@ g_x264_version = __TIME__, }; -//CLI Arguments -static struct -{ - QStringList *list; - QReadWriteLock lock; -} -g_x264_argv; - -//OS Version -static struct -{ - bool bInitialized; - x264_os_version_t version; - QReadWriteLock lock; -} -g_x264_os_version; - -//Special folders -static struct -{ - QMap *knownFolders; - SHGetKnownFolderPath_t getKnownFolderPath; - SHGetFolderPath_t getFolderPath; - QReadWriteLock lock; -} -g_x264_known_folder; - -//%TEMP% folder -static struct -{ - QString *path; - QReadWriteLock lock; -} -g_x264_temp_folder; - -//Wine detection -static struct -{ - bool bInitialized; - bool bIsWine; - QReadWriteLock lock; -} -g_x264_wine; - //Portable Mode static struct { @@ -184,31 +135,6 @@ static struct } g_x264_portable; -//Known Windows NT versions -const x264_os_version_t x264_winver_error = { 0,0}; //N/A -const x264_os_version_t x264_winver_win2k = { 5,0}; //2000 -const x264_os_version_t x264_winver_winxp = { 5,1}; //XP -const x264_os_version_t x264_winver_xpx64 = { 5,2}; //XP_x64 -const x264_os_version_t x264_winver_vista = { 6,0}; //Vista -const x264_os_version_t x264_winver_win70 = { 6,1}; //7 -const x264_os_version_t x264_winver_win80 = { 6,2}; //8 -const x264_os_version_t x264_winver_win81 = { 6,3}; //8.1 -const x264_os_version_t x264_winver_wn100 = {10,0}; //10 - -//Maps marketing names to the actual Windows NT versions -static const x264_os_info_t x264_winver_lut[] = -{ - { x264_winver_win2k, "Windows 2000" }, //2000 - { x264_winver_winxp, "Windows XP or Windows XP Media Center Edition" }, //XP - { x264_winver_xpx64, "Windows Server 2003 or Windows XP x64" }, //XP_x64 - { x264_winver_vista, "Windows Vista or Windows Server 2008" }, //Vista - { x264_winver_win70, "Windows 7 or Windows Server 2008 R2" }, //7 - { x264_winver_win80, "Windows 8 or Windows Server 2012" }, //8 - { x264_winver_win81, "Windows 8.1 or Windows Server 2012 R2" }, //8.1 - { x264_winver_wn100, "Windows 10 or Windows Server 2014 (Preview)" }, //10 - { x264_winver_error, "" } -}; - //GURU MEDITATION static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n"; @@ -340,419 +266,6 @@ static inline bool _CHECK_FLAG(const int argc, char **argv, const char *flag) // GLOBAL FUNCTIONS /////////////////////////////////////////////////////////////////////////////// -static __forceinline bool x264_check_for_debugger(void); - -/* - * Suspend calling thread for N milliseconds - */ -inline void x264_sleep(const unsigned int delay) -{ - Sleep(delay); -} - -/* - * 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); - } - - x264_fatal_exit(L"Unhandeled exception handler invoked, application will exit!"); - 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); - } - - x264_fatal_exit(L"Invalid parameter handler invoked, application will exit!"); -} - -/* - * Get a random string - */ -QString x264_rand_str(const bool bLong) -{ - const QUuid uuid = QUuid::createUuid().toString(); - - const unsigned int u1 = uuid.data1; - const unsigned int u2 = (((unsigned int)(uuid.data2)) << 16) | ((unsigned int)(uuid.data3)); - 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])); - 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])); - - return bLong ? QString().sprintf("%08x%08x%08x%08x", u1, u2, u3, u4) : QString().sprintf("%08x%08x", (u1 ^ u2), (u3 ^ u4)); -} - -/* - * Robert Jenkins' 96 bit Mix Function - * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm - */ -static unsigned int x264_mix(const unsigned int x, const unsigned int y, const unsigned int z) -{ - unsigned int a = x; - unsigned int b = y; - unsigned int c = z; - - a=a-b; a=a-c; a=a^(c >> 13); - b=b-c; b=b-a; b=b^(a << 8); - c=c-a; c=c-b; c=c^(b >> 13); - a=a-b; a=a-c; a=a^(c >> 12); - b=b-c; b=b-a; b=b^(a << 16); - c=c-a; c=c-b; c=c^(b >> 5); - a=a-b; a=a-c; a=a^(c >> 3); - b=b-c; b=b-a; b=b^(a << 10); - c=c-a; c=c-b; c=c^(b >> 15); - - return c; -} - -/* - * Seeds the random number generator - * Note: Altough rand_s() doesn't need a seed, this must be called pripr to x264_rand(), just to to be sure! - */ -void x264_seed_rand(void) -{ - qsrand(x264_mix(clock(), time(NULL), _getpid())); -} - -/* - * Returns a randum number - * Note: This function uses rand_s() if available, but falls back to qrand() otherwise - */ -unsigned int x264_rand(void) -{ - quint32 rnd = 0; - - if(rand_s(&rnd) == 0) - { - return rnd; - } - - for(size_t i = 0; i < sizeof(unsigned int); i++) - { - rnd = (rnd << 8) ^ qrand(); - } - - return rnd; -} - -/* - * 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); - } -} - -/* - * Determines the current date, resistant against certain manipulations - */ -QDate x264_current_date_safe(void) -{ - const DWORD MAX_PROC = 1024; - DWORD *processes = new DWORD[MAX_PROC]; - DWORD bytesReturned = 0; - - if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned)) - { - X264_DELETE_ARRAY(processes); - return QDate::currentDate(); - } - - const DWORD procCount = bytesReturned / sizeof(DWORD); - ULARGE_INTEGER lastStartTime; - memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER)); - - for(DWORD i = 0; i < procCount; i++) - { - HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]); - if(hProc) - { - FILETIME processTime[4]; - if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3])) - { - ULARGE_INTEGER timeCreation; - timeCreation.LowPart = processTime[0].dwLowDateTime; - timeCreation.HighPart = processTime[0].dwHighDateTime; - if(timeCreation.QuadPart > lastStartTime.QuadPart) - { - lastStartTime.QuadPart = timeCreation.QuadPart; - } - } - CloseHandle(hProc); - } - } - - X264_DELETE_ARRAY(processes); - - FILETIME lastStartTime_fileTime; - lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart; - lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart; - - FILETIME lastStartTime_localTime; - if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime)) - { - memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME)); - } - - SYSTEMTIME lastStartTime_system; - if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system)) - { - memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME)); - lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1; - } - - const QDate currentDate = QDate::currentDate(); - const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay); - return (currentDate >= processDate) ? currentDate : processDate; -} - -/* - * Output logging message to console - */ -static void x264_write_console(const int type, const char *msg) -{ - __try - { - if(_isatty(_fileno(stderr))) - { - UINT oldOutputCP = GetConsoleOutputCP(); - if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8); - - switch(type) - { - case QtCriticalMsg: - case QtFatalMsg: - 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); - } - } - __except(1) - { - /*ignore any exception that might occur here!*/ - } -} - -/* - * Output logging message to debugger - */ -static void x264_write_dbg_out(const int type, const char *msg) -{ - const char *FORMAT = "[sx264l][%c] %s\n"; - - __try - { - char buffer[512]; - const char* input = msg; - TRIM_LEFT(input); - - switch(type) - { - case QtCriticalMsg: - case QtFatalMsg: - _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'C', input); - break; - case QtWarningMsg: - _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'W', input); - break; - default: - _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'I', input); - break; - } - - char *temp = &buffer[0]; - CLEAN_OUTPUT_STRING(temp); - OutputDebugStringA(temp); - } - __except(1) - { - /*ignore any exception that might occur here!*/ - } -} - -/* - * Output logging message to logfile - */ -static void x264_write_logfile(const int type, const char *msg) -{ - const char *FORMAT = "[%c][%04u] %s\r\n"; - - __try - { - if(g_x264_log_file) - { - char buffer[512]; - strncpy_s(buffer, 512, msg, _TRUNCATE); - - char *temp = &buffer[0]; - TRIM_LEFT(temp); - CLEAN_OUTPUT_STRING(temp); - - const unsigned int timestamp = static_cast(_time64(NULL) % 3600I64); - - switch(type) - { - case QtCriticalMsg: - case QtFatalMsg: - fprintf(g_x264_log_file, FORMAT, 'C', timestamp, temp); - break; - case QtWarningMsg: - fprintf(g_x264_log_file, FORMAT, 'W', timestamp, temp); - break; - default: - fprintf(g_x264_log_file, FORMAT, 'I', timestamp, temp); - break; - } - - fflush(g_x264_log_file); - } - } - __except(1) - { - /*ignore any exception that might occur here!*/ - } -} - -/* - * Qt message handler - */ -void x264_message_handler(QtMsgType type, const char *msg) -{ - if((!msg) || (!(msg[0]))) - { - return; - } - - QMutexLocker lock(&g_x264_message_mutex); - - if(g_x264_log_file) - { - x264_write_logfile(type, msg); - } - - if(g_x264_console_attached) - { - x264_write_console(type, msg); - } - else - { - x264_write_dbg_out(type, msg); - } - - if((type == QtCriticalMsg) || (type == QtFatalMsg)) - { - lock.unlock(); - x264_fatal_exit(L"The application has encountered a critical error and will exit now!", QString::fromUtf8(msg).toLatin1().constData()); - } -} - -/* - * Initialize the console - */ -void x264_init_console(const int argc, char **argv) -{ - bool enableConsole = x264_is_prerelease() || (X264_DEBUG); - - 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) - { - - if(CHECK_FLAG("console")) enableConsole = true; - if(CHECK_FLAG("no-console")) enableConsole = false; - } - - if(enableConsole) - { - if(!g_x264_console_attached) - { - if(AllocConsole()) - { - 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); - } - } -} - /* * Version info */ @@ -781,42 +294,6 @@ const char *x264_version_arch(void) return g_x264_version_arch; } -/* - * Get CLI arguments - */ -/* -const QStringList &x264_arguments(void) -{ - QReadLocker readLock(&g_x264_argv.lock); - - if(!g_x264_argv.list) - { - readLock.unlock(); - QWriteLocker writeLock(&g_x264_argv.lock); - - g_x264_argv.list = new QStringList; - - int nArgs = 0; - LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); - - if(NULL != szArglist) - { - for(int i = 0; i < nArgs; i++) - { - (*g_x264_argv.list) << WCHAR2QSTR(szArglist[i]); - } - LocalFree(szArglist); - } - else - { - qWarning("CommandLineToArgvW() has failed !!!"); - } - } - - return (*g_x264_argv.list); -} -*/ - /* * Check for portable mode */ @@ -926,659 +403,6 @@ bool x264_is_prerelease(void) return (VER_X264_PRE_RELEASE); } -/* - * CPUID prototype (actual function is in ASM code) - */ -/* -extern "C" -{ - void x264_cpu_cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx); -} -*/ - -/* - * Detect CPU features - */ -/* -x264_cpu_t x264_detect_cpu_features(const int argc, char **argv) -{ - typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process); - - x264_cpu_t features; - SYSTEM_INFO systemInfo; - unsigned int CPUInfo[4]; - 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)); - - x264_cpu_cpuid(0, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]); - 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) - { - x264_cpu_cpuid(1, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]); - 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); - if(features.sse) features.mmx2 = true; //MMXEXT is a subset of SSE! - } - - x264_cpu_cpuid(0x80000000, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]); - int nExIds = qMax(qMin(CPUInfo[0], 0x80000004), 0x80000000); - - if((_stricmp(CPUIdentificationString, "AuthenticAMD") == 0) && (nExIds >= 0x80000001U)) - { - x264_cpu_cpuid(0x80000001, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]); - features.mmx2 = features.mmx2 || (CPUInfo[3] & 0x00400000U); - } - - for(int i = 0x80000002; i <= nExIds; ++i) - { - x264_cpu_cpuid(i, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]); - 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; - } - } - - 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))) - QLibrary Kernel32Lib("kernel32.dll"); - if(IsWow64ProcessFun IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process")) - { - BOOL x64flag = FALSE; - if(IsWow64ProcessPtr(GetCurrentProcess(), &x64flag)) - { - features.x64 = (x64flag == TRUE); - } - } -#else - features.x64 = true; -#endif - - DWORD_PTR procAffinity, sysAffinity; - if(GetProcessAffinityMask(GetCurrentProcess(), &procAffinity, &sysAffinity)) - { - for(DWORD_PTR mask = 1; mask; mask <<= 1) - { - features.count += ((sysAffinity & mask) ? (1) : (0)); - } - } - if(features.count < 1) - { - GetNativeSystemInfo(&systemInfo); - features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL); - } - - bool flag = false; - if(CHECK_FLAG("force-cpu-no-64bit")) { flag = true; features.x64 = false; } - if(CHECK_FLAG("force-cpu-no-sse")) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; } - if(CHECK_FLAG("force-cpu-no-intel")) { flag = true; features.intel = false; } - if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n"); - - return features; -} -*/ - -/* - * Verify a specific Windows version - */ -static bool x264_verify_os_version(const DWORD major, const DWORD minor) -{ - OSVERSIONINFOEXW osvi; - DWORDLONG dwlConditionMask = 0; - - //Initialize the OSVERSIONINFOEX structure - memset(&osvi, 0, sizeof(OSVERSIONINFOEXW)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); - osvi.dwMajorVersion = major; - osvi.dwMinorVersion = minor; - osvi.dwPlatformId = VER_PLATFORM_WIN32_NT; - - //Initialize the condition mask - VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); - VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); - VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL); - - // Perform the test - const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask); - - //Error checking - if(!ret) - { - if(GetLastError() != ERROR_OLD_WIN_VERSION) - { - qWarning("VerifyVersionInfo() system call has failed!"); - } - } - - return (ret != FALSE); -} - -/* - * Determine the *real* Windows version - */ -static bool x264_get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride) -{ - *major = *minor = 0; - *pbOverride = false; - - //Initialize local variables - OSVERSIONINFOEXW osvi; - memset(&osvi, 0, sizeof(OSVERSIONINFOEXW)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); - - //Try GetVersionEx() first - if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE) - { - qWarning("GetVersionEx() has failed, cannot detect Windows version!"); - return false; - } - - //Make sure we are running on NT - if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) - { - *major = osvi.dwMajorVersion; - *minor = osvi.dwMinorVersion; - } - else - { - qWarning("Not running on Windows NT, unsupported operating system!"); - return false; - } - - //Determine the real *major* version first - forever - { - const DWORD nextMajor = (*major) + 1; - if(x264_verify_os_version(nextMajor, 0)) - { - *pbOverride = true; - *major = nextMajor; - *minor = 0; - continue; - } - break; - } - - //Now also determine the real *minor* version - forever - { - const DWORD nextMinor = (*minor) + 1; - if(x264_verify_os_version((*major), nextMinor)) - { - *pbOverride = true; - *minor = nextMinor; - continue; - } - break; - } - - return true; -} - -/* - * Get the native operating system version - */ -const x264_os_version_t &x264_get_os_version(void) -{ - QReadLocker readLock(&g_x264_os_version.lock); - - //Already initialized? - if(g_x264_os_version.bInitialized) - { - return g_x264_os_version.version; - } - - readLock.unlock(); - QWriteLocker writeLock(&g_x264_os_version.lock); - - //Detect OS version - if(!g_x264_os_version.bInitialized) - { - unsigned int major, minor; bool oflag; - if(x264_get_real_os_version(&major, &minor, &oflag)) - { - g_x264_os_version.version.versionMajor = major; - g_x264_os_version.version.versionMinor = minor; - g_x264_os_version.version.overrideFlag = oflag; - g_x264_os_version.bInitialized = true; - } - else - { - qWarning("Failed to determin the operating system version!"); - } - } - - return g_x264_os_version.version; -} - -/* - * Check for compatibility mode - */ -static bool x264_check_compatibility_mode(const char *exportName, const char *executableName) -{ - 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; -} - -/* - * Check if we are running under wine - */ -bool x264_detect_wine(void) -{ - QReadLocker readLock(&g_x264_wine.lock); - - //Already initialized? - if(g_x264_wine.bInitialized) - { - return g_x264_wine.bIsWine; - } - - readLock.unlock(); - QWriteLocker writeLock(&g_x264_wine.lock); - - if(!g_x264_wine.bInitialized) - { - g_x264_wine.bIsWine = false; - QLibrary ntdll("ntdll.dll"); - if(ntdll.load()) - { - if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) g_x264_wine.bIsWine = true; - if(ntdll.resolve("wine_get_version") != NULL) g_x264_wine.bIsWine = true; - ntdll.unload(); - } - g_x264_wine.bInitialized = true; - } - - return g_x264_wine.bIsWine; -} - -/* - * Qt event filter - */ -static bool x264_event_filter(void *message, long *result) -{ - if((!(X264_DEBUG)) && x264_check_for_debugger()) - { - x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!"); - } - - //switch(reinterpret_cast(message)->message) - //{ - //case WM_QUERYENDSESSION: - // qWarning("WM_QUERYENDSESSION message received!"); - // *result = x264_broadcast(x264_event_queryendsession, false) ? TRUE : FALSE; - // return true; - //case WM_ENDSESSION: - // qWarning("WM_ENDSESSION message received!"); - // if(reinterpret_cast(message)->wParam == TRUE) - // { - // x264_broadcast(x264_event_endsession, false); - // if(QApplication *app = reinterpret_cast(QApplication::instance())) - // { - // app->closeAllWindows(); - // app->quit(); - // } - // x264_finalization(); - // exit(1); - // } - // *result = 0; - // return true; - //default: - // /*ignore this message and let Qt handle it*/ - // return false; - //} - - return false; -} - -/* - * Check for process elevation - */ -static bool x264_process_is_elevated(bool *bIsUacEnabled = NULL) -{ - bool bIsProcessElevated = false; - if(bIsUacEnabled) *bIsUacEnabled = false; - HANDLE hToken = NULL; - - if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) - { - TOKEN_ELEVATION_TYPE tokenElevationType; - DWORD returnLength; - if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength)) - { - if(returnLength == sizeof(TOKEN_ELEVATION_TYPE)) - { - switch(tokenElevationType) - { - case TokenElevationTypeDefault: - qDebug("Process token elevation type: Default -> UAC is disabled.\n"); - break; - case TokenElevationTypeFull: - qWarning("Process token elevation type: Full -> potential security risk!\n"); - bIsProcessElevated = true; - if(bIsUacEnabled) *bIsUacEnabled = true; - break; - case TokenElevationTypeLimited: - qDebug("Process token elevation type: Limited -> not elevated.\n"); - if(bIsUacEnabled) *bIsUacEnabled = true; - break; - default: - qWarning("Unknown tokenElevationType value: %d", tokenElevationType); - break; - } - } - else - { - qWarning("GetTokenInformation() return an unexpected size!"); - } - } - CloseHandle(hToken); - } - else - { - qWarning("Failed to open process token!"); - } - - return bIsProcessElevated; -} - -/* - * Check if the current user is an administartor (helper function) - */ -static bool x264_user_is_admin_helper(void) -{ - HANDLE hToken = NULL; - if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) - { - return false; - } - - DWORD dwSize = 0; - if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize)) - { - if(GetLastError() != ERROR_INSUFFICIENT_BUFFER) - { - CloseHandle(hToken); - return false; - } - } - - PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize); - if(!lpGroups) - { - CloseHandle(hToken); - return false; - } - - if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize)) - { - free(lpGroups); - CloseHandle(hToken); - return false; - } - - PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY}; - if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid)) - { - free(lpGroups); - CloseHandle(hToken); - return false; - } - - bool bResult = false; - for(DWORD i = 0; i < lpGroups->GroupCount; i++) - { - if(EqualSid(lpSid, lpGroups->Groups[i].Sid)) - { - bResult = true; - break; - } - } - - FreeSid(lpSid); - free(lpGroups); - CloseHandle(hToken); - return bResult; -} - -/* - * Check if the current user is an administartor - */ -bool x264_user_is_admin(void) -{ - bool isAdmin = false; - - //Check for process elevation and UAC support first! - if(x264_process_is_elevated(&isAdmin)) - { - qWarning("Process is elevated -> user is admin!"); - return true; - } - - //If not elevated and UAC is not available -> user must be in admin group! - if(!isAdmin) - { - qDebug("UAC is disabled/unavailable -> checking for Administrators group"); - isAdmin = x264_user_is_admin_helper(); - } - - return isAdmin; -} - -/* - * Initialize Qt framework - */ -//bool x264_init_qt(int &argc, char **argv) -//{ -// static bool qt_initialized = false; -// typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName); -// const QStringList &arguments = x264_arguments(); -// -// //Don't initialized again, if done already -// if(qt_initialized) -// { -// return true; -// } -// -// //Secure DLL loading -// QLibrary kernel32("kernel32.dll"); -// if(kernel32.load()) -// { -// SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW"); -// if(pSetDllDirectory != NULL) pSetDllDirectory(L""); -// } -// -// //Extract executable name from argv[] array -// QString executableName = QLatin1String("x264_launcher.exe"); -// if(arguments.count() > 0) -// { -// static const char *delimiters = "\\/:?"; -// executableName = arguments[0].trimmed(); -// for(int i = 0; delimiters[i]; i++) -// { -// int temp = executableName.lastIndexOf(QChar(delimiters[i])); -// if(temp >= 0) executableName = executableName.mid(temp + 1); -// } -// executableName = executableName.trimmed(); -// if(executableName.isEmpty()) -// { -// executableName = QLatin1String("x264_launcher.exe"); -// } -// } -// -// //Check Qt version -//#ifdef QT_BUILD_KEY -// 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(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(executableName, QString::fromLatin1(QT_BUILD_KEY), QLibraryInfo::buildKey()).toLatin1().constData()); -// return false; -// } -//#else -// qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static")); -// qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR); -//#endif -// -// //Check the Windows version -// const x264_os_version_t &osVersionNo = x264_get_os_version(); -// if(osVersionNo < x264_winver_winxp) -// { -// qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData()); -// } -// -// //Check whether we are running on a supported Windows version -// bool runningOnSupportedOSVersion = false; -// for(size_t i = 0; x264_winver_lut[i].version != x264_winver_error; i++) -// { -// if(osVersionNo == x264_winver_lut[i].version) -// { -// runningOnSupportedOSVersion = true; -// qDebug("Running on %s (NT v%u.%u).\n", x264_winver_lut[i].friendlyName, osVersionNo.versionMajor, osVersionNo.versionMinor); -// break; -// } -// } -// if(!runningOnSupportedOSVersion) -// { -// const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersionNo.versionMajor, osVersionNo.versionMinor); -// qWarning("%s\n", QUTF8(message)); -// MessageBoxW(NULL, QWCHAR(message), L"LameXP", MB_OK | MB_TOPMOST | MB_ICONWARNING); -// } -// -// //Check for compat mode -// if(osVersionNo.overrideFlag && (osVersionNo <= x264_winver_wn100)) -// { -// qWarning("Windows compatibility mode detected!"); -// if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive)) -// { -// qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData()); -// return false; -// } -// } -// -// //Check for Wine -// if(x264_detect_wine()) -// { -// qWarning("It appears we are running under Wine, unexpected things might happen!\n"); -// } -// -// //Set text Codec for locale -// QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); -// -// //Create Qt application instance -// QApplication *application = new QApplication(argc, argv); -// -// //Load plugins from application directory -// QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath()); -// qDebug("Library Path:\n%s\n", QUTF8(QApplication::libraryPaths().first())); -// -// //Create Qt application instance and setup version info -// 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); -// -// //Check for supported image formats -// QList supportedFormats = QImageReader::supportedImageFormats(); -// for(int i = 0; g_x264_imageformats[i]; i++) -// { -// if(!supportedFormats.contains(g_x264_imageformats[i])) -// { -// qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_x264_imageformats[i]); -// return false; -// } -// } -// -// //Add default translations -// /* -// QWriteLocker writeLockTranslations(&g_x264_translation.lock); -// if(!g_x264_translation.files) g_x264_translation.files = new QMap(); -// if(!g_x264_translation.names) g_x264_translation.names = new QMap(); -// g_x264_translation.files->insert(X264_DEFAULT_LANGID, ""); -// g_x264_translation.names->insert(X264_DEFAULT_LANGID, "English"); -// writeLockTranslations.unlock(); -// */ -// -// //Check for process elevation -// if(x264_process_is_elevated() && (!x264_detect_wine())) -// { -// QMessageBox messageBox(QMessageBox::Warning, "Simple x264 Launcher", "Simple x264 Launcher was started with 'elevated' rights, altough it does not need these rights.
Running an applications with unnecessary rights is a potential security risk!
", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint); -// messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole); -// messageBox.addButton("Ignore", QMessageBox::NoRole); -// if(messageBox.exec() == 0) -// { -// return false; -// } -// } -// -// //Update console icon, if a console is attached -//#if QT_VERSION < QT_VERSION_CHECK(5,0,0) -// if(g_x264_console_attached && (!x264_detect_wine())) -// { -// typedef DWORD (__stdcall *SetConsoleIconFun)(HICON); -// QLibrary kernel32("kernel32.dll"); -// if(kernel32.load()) -// { -// SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon"); -// QPixmap pixmap = QIcon(":/icons/movie.ico").pixmap(16, 16); -// if((SetConsoleIconPtr != NULL) && (!pixmap.isNull())) SetConsoleIconPtr(pixmap.toWinHICON()); -// kernel32.unload(); -// } -// } -//#endif -// -// //Done -// qt_initialized = true; -// return true; -//} - - /* * Suspend or resume process */ @@ -1609,12 +433,12 @@ QString x264_path2ansi(const QString &longPath, bool makeLowercase) QString shortPath = longPath; const QString longPathNative = QDir::toNativeSeparators(longPath); - DWORD buffSize = GetShortPathNameW(QWCHAR(longPathNative), NULL, NULL); + DWORD buffSize = GetShortPathNameW(MUTILS_WCHR(longPathNative), NULL, NULL); if(buffSize > 0) { wchar_t *buffer = (wchar_t*) _malloca(sizeof(wchar_t) * buffSize); - DWORD result = GetShortPathNameW(QWCHAR(longPathNative), buffer, buffSize); + DWORD result = GetShortPathNameW(MUTILS_WCHR(longPathNative), buffer, buffSize); if((result > 0) && (result < buffSize)) { @@ -1634,229 +458,21 @@ QString x264_path2ansi(const QString &longPath, bool makeLowercase) return shortPath; } -/* - * Set the process priority class for current process - */ -bool x264_change_process_priority(const int priority) -{ - return x264_change_process_priority(GetCurrentProcess(), priority); -} - -/* - * Set the process priority class for specified process - */ -bool x264_change_process_priority(const QProcess *proc, const int priority) -{ - if(Q_PID qPid = proc->pid()) - { - return x264_change_process_priority(qPid->hProcess, priority); - } - else - { - return false; - } -} - -/* - * Set the process priority class for specified process - */ -bool x264_change_process_priority(void *hProcess, const int priority) -{ - bool ok = false; - - switch(qBound(-2, priority, 2)) - { - case 2: - ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE); - break; - case 1: - if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE))) - { - ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE); - } - break; - case 0: - ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE); - break; - case -1: - if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE))) - { - ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE); - } - break; - case -2: - ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE); - break; - } - - return ok; -} - -/* - * Play a sound (from resources) - */ -bool x264_play_sound(const unsigned short uiSoundIdx, const bool bAsync, const wchar_t *alias) -{ - if(alias) - { - return PlaySound(alias, GetModuleHandle(NULL), (SND_ALIAS | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE; - } - else - { - return PlaySound(MAKEINTRESOURCE(uiSoundIdx), GetModuleHandle(NULL), (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE; - } -} - -/* - * Current process ID - */ -unsigned int x264_process_id(void) -{ - return GetCurrentProcessId(); -} - -/* - * Current process ID - */ -unsigned int x264_process_id(QProcess &process) -{ - if(Q_PID pid = process.pid()) - { - return pid->dwProcessId; - } - return NULL; -} - -/* - * Make a window blink (to draw user's attention) - */ -void x264_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay) -{ - static QMutex blinkMutex; - - const double maxOpac = 1.0; - const double minOpac = 0.3; - const double delOpac = 0.1; - - if(!blinkMutex.tryLock()) - { - qWarning("Blinking is already in progress, skipping!"); - return; - } - - try - { - const int steps = static_cast(ceil(maxOpac - minOpac) / delOpac); - const int sleep = static_cast(floor(static_cast(delay) / static_cast(steps))); - const double opacity = poWindow->windowOpacity(); - - for(unsigned int i = 0; i < count; i++) - { - for(double x = maxOpac; x >= minOpac; x -= delOpac) - { - poWindow->setWindowOpacity(x); - QApplication::processEvents(); - Sleep(sleep); - } - - for(double x = minOpac; x <= maxOpac; x += delOpac) - { - poWindow->setWindowOpacity(x); - QApplication::processEvents(); - Sleep(sleep); - } - } - - poWindow->setWindowOpacity(opacity); - QApplication::processEvents(); - blinkMutex.unlock(); - } - catch(...) - { - blinkMutex.unlock(); - qWarning("Exception error while blinking!"); - } -} - -/* - * Bring the specifed window to the front - */ -static bool x264_bring_to_front(const HWND hWin) -{ - if(hWin) - { - const bool ret = (SetForegroundWindow(hWin) != FALSE); - SwitchToThisWindow(hWin, TRUE); - return ret; - } - return false; -} - -/* - * Bring the specifed window to the front - */ -bool x264_bring_to_front(const QWidget *win) -{ - if(win) - { - return x264_bring_to_front(win->winId()); - } - return false; -} - -/* - * Bring window of the specifed process to the front (callback) - */ -static BOOL CALLBACK x264_bring_process_to_front_helper(HWND hwnd, LPARAM lParam) -{ - DWORD processId = *reinterpret_cast(lParam); - DWORD windowProcessId = NULL; - GetWindowThreadProcessId(hwnd, &windowProcessId); - if(windowProcessId == processId) - { - x264_bring_to_front(hwnd); - return FALSE; - } - return TRUE; -} - -/* - * Bring window of the specifed process to the front - */ -bool x264_bring_process_to_front(const unsigned long pid) -{ - return EnumWindows(x264_bring_process_to_front_helper, reinterpret_cast(&pid)) == TRUE; -} - -/* - * Check if file is a valid Win32/Win64 executable - */ -bool x264_is_executable(const QString &path) -{ - bool bIsExecutable = false; - DWORD binaryType; - if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(path)), &binaryType)) - { - bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY); - } - return bIsExecutable; -} - /* * Read value from registry */ QString x264_query_reg_string(const bool bUser, const QString &path, const QString &name) { QString result; HKEY hKey = NULL; - if(RegOpenKey((bUser ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE), QWCHAR(path), &hKey) == ERROR_SUCCESS) + if(RegOpenKey((bUser ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE), MUTILS_WCHR(path), &hKey) == ERROR_SUCCESS) { const size_t DATA_LEN = 2048; wchar_t data[DATA_LEN]; DWORD type = REG_NONE, size = sizeof(wchar_t) * DATA_LEN; - if(RegQueryValueEx(hKey, QWCHAR(name), NULL, &type, ((BYTE*)&data[0]), &size) == ERROR_SUCCESS) + if(RegQueryValueEx(hKey, MUTILS_WCHR(name), NULL, &type, ((BYTE*)&data[0]), &size) == ERROR_SUCCESS) { if((type == REG_SZ) || (type == REG_EXPAND_SZ)) { - result = WCHAR2QSTR(&data[0]); + result = MUTILS_QSTR(&data[0]); } } RegCloseKey(hKey); @@ -1864,325 +480,6 @@ QString x264_query_reg_string(const bool bUser, const QString &path, const QStri return result; } -/* - * Locate known folder on local system - */ -const QString &x264_known_folder(x264_known_folder_t folder_id) -{ - static const int CSIDL_FLAG_CREATE = 0x8000; - typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t; - - struct - { - const int csidl; - const GUID guid; - } - static s_folders[] = - { - { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA - { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES - { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER - { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER - }; - - size_t folderId = size_t(-1); - - switch(folder_id) - { - case x264_folder_localappdata: folderId = 0; break; - case x264_folder_programfiles: folderId = 1; break; - case x264_folder_systroot_dir: folderId = 2; break; - case x264_folder_systemfolder: folderId = 3; break; - } - - if(folderId == size_t(-1)) - { - qWarning("Invalid 'known' folder was requested!"); - return *reinterpret_cast(NULL); - } - - QReadLocker readLock(&g_x264_known_folder.lock); - - //Already in cache? - if(g_x264_known_folder.knownFolders) - { - if(g_x264_known_folder.knownFolders->contains(folderId)) - { - return (*g_x264_known_folder.knownFolders)[folderId]; - } - } - - //Obtain write lock to initialize - readLock.unlock(); - QWriteLocker writeLock(&g_x264_known_folder.lock); - - //Still not in cache? - if(g_x264_known_folder.knownFolders) - { - if(g_x264_known_folder.knownFolders->contains(folderId)) - { - return (*g_x264_known_folder.knownFolders)[folderId]; - } - } - - //Initialize on first call - if(!g_x264_known_folder.knownFolders) - { - QLibrary shell32("shell32.dll"); - if(shell32.load()) - { - g_x264_known_folder.getFolderPath = (SHGetFolderPath_t) shell32.resolve("SHGetFolderPathW"); - g_x264_known_folder.getKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath"); - } - g_x264_known_folder.knownFolders = new QMap(); - } - - QString folderPath; - - //Now try to get the folder path! - if(g_x264_known_folder.getKnownFolderPath) - { - WCHAR *path = NULL; - if(g_x264_known_folder.getKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK) - { - //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST); - QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast(path)))); - if(folderTemp.exists()) - { - folderPath = folderTemp.canonicalPath(); - } - CoTaskMemFree(path); - } - } - else if(g_x264_known_folder.getFolderPath) - { - WCHAR *path = new WCHAR[4096]; - if(g_x264_known_folder.getFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path) == S_OK) - { - //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST); - QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast(path)))); - if(folderTemp.exists()) - { - folderPath = folderTemp.canonicalPath(); - } - } - X264_DELETE_ARRAY(path); - } - - //Update cache - g_x264_known_folder.knownFolders->insert(folderId, folderPath); - return (*g_x264_known_folder.knownFolders)[folderId]; -} - -/* - * Try to initialize the folder (with *write* access) - */ -static QString x264_try_init_folder(const QString &folderPath) -{ - static const char *DATA = "Lorem ipsum dolor sit amet, consectetur, adipisci velit!"; - - bool success = false; - - const QFileInfo folderInfo(folderPath); - const QDir folderDir(folderInfo.absoluteFilePath()); - - //Create folder, if it does *not* exist yet - for(int i = 0; i < 16; i++) - { - if(folderDir.exists()) break; - folderDir.mkpath("."); - } - - //Make sure folder exists now *and* is writable - if(folderDir.exists()) - { - const QByteArray testData = QByteArray(DATA); - for(int i = 0; i < 32; i++) - { - QFile testFile(folderDir.absoluteFilePath(QString("~%1.tmp").arg(x264_rand_str()))); - if(testFile.open(QIODevice::ReadWrite | QIODevice::Truncate)) - { - if(testFile.write(testData) >= testData.size()) - { - success = true; - } - testFile.remove(); - testFile.close(); - } - if(success) break; - } - } - - return (success ? folderDir.canonicalPath() : QString()); -} - -/* - * Detect the TEMP directory - */ -const QString &x264_temp_directory(void) -{ - QReadLocker readLock(&g_x264_temp_folder.lock); - - if(g_x264_temp_folder.path) - { - return *g_x264_temp_folder.path; - } - - readLock.unlock(); - QWriteLocker writeLock(&g_x264_temp_folder.lock); - - if(!g_x264_temp_folder.path) - { - //Try %TEMP% first - g_x264_temp_folder.path = new QString(x264_try_init_folder(QDir::temp().absolutePath())); - - //Fall back to %LOCALAPPDATA%, if %TEMP% didn't work - if(g_x264_temp_folder.path->isEmpty()) - { - qWarning("%%TEMP%% directory not found -> falling back to %%LOCALAPPDATA%%"); - static const x264_known_folder_t folderId[2] = { x264_folder_localappdata, x264_folder_systroot_dir }; - for(size_t id = 0; (g_x264_temp_folder.path->isEmpty() && (id < 2)); id++) - { - const QString &localAppData = x264_known_folder(x264_folder_localappdata); - if(!localAppData.isEmpty()) - { - *g_x264_temp_folder.path = x264_try_init_folder(QString("%1/Temp").arg(localAppData)); - } - else - { - qWarning("%%LOCALAPPDATA%% directory could not be found!"); - } - } - } - - //Failed to init TEMP folder? - if(g_x264_temp_folder.path->isEmpty()) - { - qWarning("Temporary directory could not be initialized !!!"); - } - } - - return *g_x264_temp_folder.path; -} - -/* - * Display the window's close button - */ -bool x264_enable_close_button(const QWidget *win, const bool bEnable) -{ - bool ok = false; - - if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE)) - { - ok = (EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (bEnable ? MF_ENABLED : MF_GRAYED)) == TRUE); - } - - return ok; -} - -/* - * Play beep sound - */ -bool x264_beep(int beepType) -{ - switch(beepType) - { - case x264_beep_info: return MessageBeep(MB_ICONASTERISK) == TRUE; break; - case x264_beep_warning: return MessageBeep(MB_ICONEXCLAMATION) == TRUE; break; - case x264_beep_error: return MessageBeep(MB_ICONHAND) == TRUE; break; - default: return false; - } -} - -/* - * Shutdown the computer - */ -bool x264_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown) -{ - HANDLE hToken = NULL; - - if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) - { - TOKEN_PRIVILEGES privileges; - memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES)); - privileges.PrivilegeCount = 1; - privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - - if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid)) - { - if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL)) - { - const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED; - return InitiateSystemShutdownEx(NULL, const_cast(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason); - } - } - } - - return false; -} - -/* - * Check the network connection status - */ -int x264_network_status(void) -{ - DWORD dwFlags; - const BOOL ret = IsNetworkAlive(&dwFlags); - if(GetLastError() == 0) - { - return (ret != FALSE) ? x264_network_yes : x264_network_non; - } - return x264_network_err; -} - -/* - * Setup QPorcess object - */ -void x264_init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir) -{ - //Environment variable names - static const char *const s_envvar_names_temp[] = - { - "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL - }; - static const char *const s_envvar_names_remove[] = - { - "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 - }; - - //Initialize environment - QProcessEnvironment env = process.processEnvironment(); - if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment(); - - //Clean a number of enviroment variables that might affect our tools - for(size_t i = 0; s_envvar_names_remove[i]; i++) - { - env.remove(QString::fromLatin1(s_envvar_names_remove[i])); - env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower()); - } - - const QString tempDir = QDir::toNativeSeparators(x264_temp_directory()); - - //Replace TEMP directory in environment - if(bReplaceTempDir) - { - for(size_t i = 0; s_envvar_names_temp[i]; i++) - { - env.insert(s_envvar_names_temp[i], tempDir); - } - } - - //Setup PATH variable - const QString path = env.value("PATH", QString()).trimmed(); - env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path)); - - //Setup QPorcess object - process.setWorkingDirectory(wokringDir); - process.setProcessChannelMode(QProcess::MergedChannels); - process.setReadChannel(QProcess::StandardOutput); - process.setProcessEnvironment(env); -} - /* * Inform the system that it is in use, thereby preventing the system from entering sleep */ @@ -2199,182 +496,3 @@ bool x264_set_thread_execution_state(const bool systemRequired) } return (state != NULL); } - -/* - * Exception class - */ -X264Exception::X264Exception(const char *message, ...) -: - runtime_error(message) -{ - va_list args; - va_start(args, message); - vsnprintf_s(m_message, MAX_MSGLEN, _TRUNCATE, message, args); - va_end(args); -} - -/* - * Check for debugger (detect routine) - */ -static __forceinline bool x264_check_for_debugger(void) -{ - __try - { - CloseHandle((HANDLE)((DWORD_PTR)-3)); - } - __except(1) - { - return true; - } - __try - { - __debugbreak(); - } - __except(1) - { - return IsDebuggerPresent(); - } - return true; -} - -/* - * Check for debugger (thread proc) - */ -static unsigned int __stdcall x264_debug_thread_proc(LPVOID lpParameter) -{ - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); - forever - { - if(x264_check_for_debugger()) - { - x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!"); - return 666; - } - x264_sleep(100); - } -} - -/* - * Check for debugger (startup routine) - */ -static HANDLE x264_debug_thread_init() -{ - if(x264_check_for_debugger()) - { - x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!"); - } - const uintptr_t h = _beginthreadex(NULL, 0, x264_debug_thread_proc, NULL, 0, NULL); - return (HANDLE)(h^0xdeadbeef); -} - -/* - * Fatal application exit - */ -#pragma intrinsic(_InterlockedExchange) -void x264_fatal_exit(const wchar_t* exitMessage, const char* errorBoxMessage) -{ - static volatile long bFatalFlag = 0L; - - if(_InterlockedExchange(&bFatalFlag, 1L) == 0L) - { - if(GetCurrentThreadId() != g_main_thread_id) - { - HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id); - if(mainThread) TerminateThread(mainThread, ULONG_MAX); - } - - if(errorBoxMessage) - { - MessageBoxA(NULL, errorBoxMessage, "Simple x264 Launcher - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL); - } - - FatalAppExit(0, exitMessage); - - for(;;) - { - TerminateProcess(GetCurrentProcess(), -1); - } - } -} - -/* - * Output string to debugger [debug only] - */ -void x264_dbg_output_string(const char* format, ...) -{ -#if X264_DEBUG - char buffer[256]; - va_list args; - va_start (args, format); - vsnprintf_s(buffer, 256, _TRUNCATE, format, args); - OutputDebugStringA(buffer); - va_end(args); -#else - THROW("Cannot call this function in a non-debug build!"); -#endif //X264_DEBUG -} - -/* - * 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 -} - -/* - * Initialization function - */ -void x264_initialization(void) -{ - //Zero *before* constructors are called - X264_ZERO_MEMORY(g_x264_argv); - X264_ZERO_MEMORY(g_x264_os_version); - X264_ZERO_MEMORY(g_x264_portable); - X264_ZERO_MEMORY(g_x264_known_folder); - X264_ZERO_MEMORY(g_x264_temp_folder); -} - -/* - * Finalization function - */ -void x264_finalization(void) -{ - //Destroy Qt application object - QApplication *application = dynamic_cast(QApplication::instance()); - X264_DELETE(application); - - //Free STDOUT and STDERR buffers - if(g_x264_console_attached) - { - if(std::filebuf *tmp = dynamic_cast(std::cout.rdbuf())) - { - std::cout.rdbuf(NULL); - X264_DELETE(tmp); - } - if(std::filebuf *tmp = dynamic_cast(std::cerr.rdbuf())) - { - std::cerr.rdbuf(NULL); - X264_DELETE(tmp); - } - } - - //Clear CLI args - X264_DELETE(g_x264_argv.list); - - //Clear folders cache - X264_DELETE(g_x264_known_folder.knownFolders); - X264_DELETE(g_x264_temp_folder.path); -} diff --git a/src/global.h b/src/global.h index 83e42c8..fc93e71 100644 --- a/src/global.h +++ b/src/global.h @@ -34,144 +34,18 @@ class QIcon; class QWidget; class LockedFile; class QProcess; -enum QtMsgType; - -/////////////////////////////////////////////////////////////////////////////// -// TYPE DEFINITIONS -/////////////////////////////////////////////////////////////////////////////// - -//Types definitions -/* -typedef struct -{ - int family; - int model; - int stepping; - int count; - bool x64; - bool mmx; - bool mmx2; - bool sse; - bool sse2; - bool sse3; - bool ssse3; - char vendor[0x40]; - char brand[0x40]; - bool intel; -} -x264_cpu_t; -*/ - -//OS version number -typedef struct _x264_os_version_t -{ - unsigned int versionMajor; - unsigned int versionMinor; - bool overrideFlag; - - //comparision operators - inline bool operator== (const _x264_os_version_t &rhs) const { return (versionMajor == rhs.versionMajor) && (versionMinor == rhs.versionMinor); } - inline bool operator!= (const _x264_os_version_t &rhs) const { return (versionMajor != rhs.versionMajor) || (versionMinor != rhs.versionMinor); } - inline bool operator> (const _x264_os_version_t &rhs) const { return (versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor > rhs.versionMinor)); } - inline bool operator>= (const _x264_os_version_t &rhs) const { return (versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >= rhs.versionMinor)); } - inline bool operator< (const _x264_os_version_t &rhs) const { return (versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor < rhs.versionMinor)); } - inline bool operator<= (const _x264_os_version_t &rhs) const { return (versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <= rhs.versionMinor)); } -} -x264_os_version_t; - -//Beep types -typedef enum -{ - x264_beep_info = 0, - x264_beep_warning = 1, - x264_beep_error = 2 -} -x264_beep_t; - -//Known folders -typedef enum -{ - x264_folder_localappdata = 0, - x264_folder_programfiles = 2, - x264_folder_systemfolder = 3, - x264_folder_systroot_dir = 4 -} -x264_known_folder_t; - -//Network connection types -typedef enum -{ - x264_network_err = 0, /*unknown*/ - x264_network_non = 1, /*not connected*/ - x264_network_yes = 2 /*connected*/ -} -x264_network_t; - -//Known Windows versions -extern const x264_os_version_t x264_winver_error; //N/A -extern const x264_os_version_t x264_winver_win2k; //2000 -extern const x264_os_version_t x264_winver_winxp; //XP -extern const x264_os_version_t x264_winver_xpx64; //XP_x64 -extern const x264_os_version_t x264_winver_vista; //Vista -extern const x264_os_version_t x264_winver_win70; //7 -extern const x264_os_version_t x264_winver_win80; //8 -extern const x264_os_version_t x264_winver_win81; //8.1 -extern const x264_os_version_t x264_winver_wn100; //10 - -//Exception class -class X264Exception : public std::runtime_error -{ -public: - X264Exception(const char *message, ...); - virtual const char* what() const { return m_message; } -private: - static const size_t MAX_MSGLEN = 256; - char m_message[MAX_MSGLEN]; -}; /////////////////////////////////////////////////////////////////////////////// // GLOBAL FUNCTIONS /////////////////////////////////////////////////////////////////////////////// -//const QStringList &x264_arguments(void); -bool x264_beep(int beepType); -void x264_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay); -bool x264_bring_process_to_front(const unsigned long pid); -bool x264_bring_to_front(const QWidget *win); -bool x264_change_process_priority(const QProcess *proc, const int priority); -bool x264_change_process_priority(const int priority); -bool x264_change_process_priority(void *hProcess, const int priority); -QDate x264_current_date_safe(void); const QString &x264_data_path(void); -void x264_dbg_output_string(const char* format, ...); -size_t x264_dbg_private_bytes(void); -//x264_cpu_t x264_detect_cpu_features(const int argc, char **argv); -bool x264_enable_close_button(const QWidget *win, const bool bEnable); -void x264_fatal_exit(const wchar_t* exitMessage, const char* errorBoxMessage = NULL); -void x264_finalization(void); -void x264_init_console(const int argc, char **argv); -void x264_init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir = true); -//bool x264_init_qt(int &argc, char **argv); -bool x264_is_executable(const QString &path); bool x264_is_prerelease(void); -const QString &x264_known_folder(x264_known_folder_t folder_id); -void x264_message_handler(QtMsgType type, const char *msg); -int x264_network_status(void); QString x264_path2ansi(const QString &longPath, bool makeLowercase = false); -bool x264_play_sound(const unsigned short uiSoundIdx, const bool bAsync, const wchar_t *alias = NULL); bool x264_portable(void); -unsigned int x264_process_id(void); -unsigned int x264_process_id(QProcess &process); QString x264_query_reg_string(const bool bUser, const QString &path, const QString &name); -unsigned int x264_rand(void); -QString x264_rand_str(const bool bLong = false); -void x264_seed_rand(void); bool x264_set_thread_execution_state(const bool systemRequired); -bool x264_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown); -void x264_sleep(const unsigned int delay); bool x264_suspendProcess(const QProcess *proc, const bool suspend); -const QString &x264_temp_directory(void); -bool x264_user_is_admin(void); const char *x264_version_arch(void); unsigned int x264_version_build(void); const char *x264_version_compiler(void); @@ -184,54 +58,9 @@ const char *x264_version_time(void); // HELPER MACROS /////////////////////////////////////////////////////////////////////////////// -#define QWCHAR(STR) reinterpret_cast(STR.utf16()) -#define QUTF8(STR) ((STR).toUtf8().constData()) -#define WCHAR2QSTR(STR) (QString::fromUtf16(reinterpret_cast((STR)))) -#define X264_BOOL(X) ((X) ? "1" : "0") -#define X264_DELETE(PTR) if(PTR) { delete PTR; PTR = NULL; } -#define X264_DELETE_ARRAY(PTR) if(PTR) { delete [] PTR; PTR = NULL; } -#define _X264_MAKE_STRING_(X) #X -#define X264_MAKE_STRING(X) _X264_MAKE_STRING_(X) -#define X264_COMPILER_WARNING(TXT) __pragma(message(__FILE__ "(" X264_MAKE_STRING(__LINE__) ") : warning: " TXT)) -#define X264_STRCMP(X,Y) ((X).compare((Y), Qt::CaseInsensitive) == 0) - -//Debug build -#if defined(_DEBUG) && defined(QT_DEBUG) && !defined(NDEBUG) && !defined(QT_NO_DEBUG) - #define X264_DEBUG (1) -#else - #define X264_DEBUG (0) -#endif - //Check for CPU-compatibility options #if !defined(_M_X64) && defined(_MSC_VER) && defined(_M_IX86_FP) #if (_M_IX86_FP != 0) #error We should not enabled SSE or SSE2 in release builds! #endif #endif - -//Helper macro for throwing exceptions -#define THROW(MESSAGE, ...) do \ -{ \ - throw X264Exception((MESSAGE), __VA_ARGS__); \ -} \ -while(0) - -//Memory check -#if X264_DEBUG - #define X264_MEMORY_CHECK(FUNC, RETV, ...) do \ - { \ - size_t _privateBytesBefore = x264_dbg_private_bytes(); \ - RETV = FUNC(__VA_ARGS__); \ - size_t _privateBytesLeak = (x264_dbg_private_bytes() - _privateBytesBefore) / 1024; \ - if(_privateBytesLeak > 0) { \ - x264_dbg_output_string("\nMemory leak: Lost %u KiloBytes of PrivateUsage memory!\n\n", _privateBytesLeak); \ - } \ - } \ - while(0) -#else - #define X264_MEMORY_CHECK(FUNC, RETV, ...) do \ - { \ - RETV = __noop(__VA_ARGS__); \ - } \ - while(0) -#endif diff --git a/src/input_filter.cpp b/src/input_filter.cpp index d3bfb18..5a2dd87 100644 --- a/src/input_filter.cpp +++ b/src/input_filter.cpp @@ -21,8 +21,13 @@ #include "input_filter.h" +//Internal #include "global.h" +//MUTils +#include + +//Qt #include #include #include @@ -40,8 +45,8 @@ InputEventFilter::InputEventFilter(QWidget *target) InputEventFilter::~InputEventFilter(void) { m_target->removeEventFilter(this); - X264_DELETE(m_keyMapping); - X264_DELETE(m_mouseMapping); + MUTILS_DELETE(m_keyMapping); + MUTILS_DELETE(m_mouseMapping); } void InputEventFilter::addKeyFilter(const int &keyCode, const int &tag) diff --git a/src/main.cpp b/src/main.cpp index 7db5ad7..4ce7a05 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -64,7 +64,7 @@ static void x264_print_logo(void) qDebug("This application is powerd by MUtils library v%u.%02u (%s, %s).\n", MUtils::Version::lib_version_major(), MUtils::Version::lib_version_minor(), MUTILS_UTF8(MUtils::Version::lib_build_date().toString(Qt::ISODate)), MUTILS_UTF8(MUtils::Version::lib_build_time().toString(Qt::ISODate))); //Print warning, if this is a "debug" build - if(X264_DEBUG) + if(MUTILS_DEBUG) { qWarning("---------------------------------------------------------"); qWarning("DEBUG BUILD: DO NOT RELEASE THIS BINARY TO THE PUBLIC !!!"); diff --git a/src/model_jobList.cpp b/src/model_jobList.cpp index 496a3f2..87367a1 100644 --- a/src/model_jobList.cpp +++ b/src/model_jobList.cpp @@ -19,6 +19,7 @@ // http://www.gnu.org/licenses/gpl-2.0.txt /////////////////////////////////////////////////////////////////////////////// +//Internal #include "global.h" #include "model_jobList.h" #include "thread_encode.h" @@ -26,6 +27,10 @@ #include "model_preferences.h" #include "resource.h" +//MUtils +#include + +//Qt #include #include #include @@ -51,8 +56,8 @@ JobListModel::~JobListModel(void) QUuid id = m_jobs.takeFirst(); EncodeThread *thread = m_threads.value(id, NULL); LogFileModel *logFile = m_logFile.value(id, NULL); - X264_DELETE(thread); - X264_DELETE(logFile); + MUTILS_DELETE(thread); + MUTILS_DELETE(logFile); } } @@ -404,8 +409,8 @@ bool JobListModel::deleteJob(const QModelIndex &index) m_logFile.remove(id); m_details.remove(id); endRemoveRows(); - X264_DELETE(thread); - X264_DELETE(logFile); + MUTILS_DELETE(thread); + MUTILS_DELETE(logFile); return true; } } @@ -534,13 +539,13 @@ void JobListModel::updateStatus(const QUuid &jobId, JobStatus newStatus) switch(newStatus) { case JobStatus_Completed: - x264_play_sound(IDR_WAVE4, true); + MUtils::Sound::play_sound("tada", true); break; case JobStatus_Aborted: - x264_play_sound(IDR_WAVE5, true); + MUtils::Sound::play_sound("shattering", true); break; case JobStatus_Failed: - x264_play_sound(IDR_WAVE6, true); + MUtils::Sound::play_sound("failure", true); break; } } diff --git a/src/model_options.cpp b/src/model_options.cpp index bd36982..3908729 100644 --- a/src/model_options.cpp +++ b/src/model_options.cpp @@ -21,9 +21,14 @@ #include "model_options.h" +//Internal #include "global.h" #include "model_sysinfo.h" +//Mutils +#include + +//Qt #include #include #include @@ -181,7 +186,7 @@ QMap OptionsModel::loadAllTemplates(const SysinfoModel * list.insert(name, options); continue; } - X264_DELETE(options); + MUTILS_DELETE(options); } } diff --git a/src/source_abstract.cpp b/src/source_abstract.cpp index 2fc8fe5..02396fe 100644 --- a/src/source_abstract.cpp +++ b/src/source_abstract.cpp @@ -21,11 +21,16 @@ #include "source_abstract.h" +//Internal #include "global.h" #include "model_sysinfo.h" #include "model_options.h" #include "model_preferences.h" +//MUtils +#include + +//Qt #include #include #include @@ -131,7 +136,7 @@ bool AbstractSource::checkSourceProperties(unsigned int &frames) while(!patterns.isEmpty()) { QRegExp *pattern = patterns.takeFirst(); - X264_DELETE(pattern); + MUTILS_DELETE(pattern); } if(bTimeout || bAborted || process.exitCode() != EXIT_SUCCESS) diff --git a/src/taskbar7.cpp b/src/taskbar7.cpp index bde9d8f..3a92662 100644 --- a/src/taskbar7.cpp +++ b/src/taskbar7.cpp @@ -21,16 +21,23 @@ #include "taskbar7.h" +//Mutils +#include + +//Qt #include #include + +//Win32 #include + static UINT s_winMsg = 0; static ITaskbarList3 *s_ptbl = NULL; WinSevenTaskbar::WinSevenTaskbar(void) { - THROW("Cannot create instance of this class!"); + MUTILS_THROW("Cannot create instance of this class!"); } WinSevenTaskbar::~WinSevenTaskbar(void) diff --git a/src/thread_avisynth.cpp b/src/thread_avisynth.cpp index f2bfb4d..97f24d3 100644 --- a/src/thread_avisynth.cpp +++ b/src/thread_avisynth.cpp @@ -27,9 +27,13 @@ #include #include +//Internal #include "global.h" #include "3rd_party/avisynth_c.h" +//MUtils +#include + QMutex AvisynthCheckThread::m_avsLock; QLibrary *AvisynthCheckThread::m_avsLib = NULL; @@ -96,7 +100,7 @@ void AvisynthCheckThread::unload(void) } } - X264_DELETE(m_avsLib); + MUTILS_DELETE(m_avsLib); } //------------------------------------- diff --git a/src/thread_encode.cpp b/src/thread_encode.cpp index 8f6eb02..f9e408e 100644 --- a/src/thread_encode.cpp +++ b/src/thread_encode.cpp @@ -37,6 +37,9 @@ #include "source_avisynth.h" #include "source_vapoursynth.h" +//MUtils +#include + //Qt Framework #include #include @@ -153,10 +156,10 @@ EncodeThread::EncodeThread(const QString &sourceFileName, const QString &outputF EncodeThread::~EncodeThread(void) { - X264_DELETE(m_encoder); - X264_DELETE(m_jobObject); - X264_DELETE(m_options); - X264_DELETE(m_pipedSource); + MUTILS_DELETE(m_encoder); + MUTILS_DELETE(m_jobObject); + MUTILS_DELETE(m_options); + MUTILS_DELETE(m_pipedSource); } /////////////////////////////////////////////////////////////////////////////// @@ -181,7 +184,7 @@ void EncodeThread::run(void) if(m_jobObject) { m_jobObject->terminateJob(42); - X264_DELETE(m_jobObject); + MUTILS_DELETE(m_jobObject); } } @@ -215,7 +218,7 @@ void EncodeThread::checkedRun(void) } catch(...) { - x264_fatal_exit(L"Unhandeled exception error in encode thread!"); + MUtils::OS::fatal_exit(L"Unhandeled exception error in encode thread!"); } } diff --git a/src/thread_vapoursynth.cpp b/src/thread_vapoursynth.cpp index 19dd078..90c9d8e 100644 --- a/src/thread_vapoursynth.cpp +++ b/src/thread_vapoursynth.cpp @@ -21,6 +21,10 @@ #include "thread_vapoursynth.h" +//Mutils +#include + +//Qt #include #include #include @@ -130,9 +134,9 @@ void VapourSynthCheckThread::unload(void) } } - X264_DELETE(m_vpsExePath); - X264_DELETE(m_vpsDllPath); - X264_DELETE(m_vpsLib); + MUTILS_DELETE(m_vpsExePath); + MUTILS_DELETE(m_vpsDllPath); + MUTILS_DELETE(m_vpsLib); } //------------------------------------- @@ -187,8 +191,8 @@ bool VapourSynthCheckThread::detectVapourSynthPath2(QString &path, volatile bool bool VapourSynthCheckThread::detectVapourSynthPath3(QString &path) { bool success = false; - X264_DELETE(m_vpsExePath); - X264_DELETE(m_vpsDllPath); + MUTILS_DELETE(m_vpsExePath); + MUTILS_DELETE(m_vpsDllPath); path.clear(); static const char *VPS_REG_KEYS[] = @@ -242,14 +246,14 @@ bool VapourSynthCheckThread::detectVapourSynthPath3(QString &path) m_vpsDllPath = new QFile(vpsDllInfo.canonicalFilePath()); if(m_vpsExePath->open(QIODevice::ReadOnly) && m_vpsDllPath->open(QIODevice::ReadOnly)) { - if(vapoursynthComplete = x264_is_executable(m_vpsExePath->fileName())) + if(vapoursynthComplete = MUtils::OS::is_executable_file(m_vpsExePath->fileName())) { vapoursynthPath.append("/").append(CORE_PATH[i]); } break; } - X264_DELETE(m_vpsExePath); - X264_DELETE(m_vpsDllPath); + MUTILS_DELETE(m_vpsExePath); + MUTILS_DELETE(m_vpsDllPath); } } if(!vapoursynthComplete) diff --git a/src/tool_abstract.cpp b/src/tool_abstract.cpp index 4898178..f2bbd88 100644 --- a/src/tool_abstract.cpp +++ b/src/tool_abstract.cpp @@ -21,6 +21,7 @@ #include "tool_abstract.h" +//Internal #include "global.h" #include "model_options.h" #include "model_preferences.h" @@ -28,6 +29,10 @@ #include "binaries.h" #include "job_object.h" +//MUtils +#include + +//Qt #include #include #include @@ -122,7 +127,7 @@ unsigned int AbstractTool::checkVersion(bool &modified) while(!patterns.isEmpty()) { QRegExp *pattern = patterns.takeFirst(); - X264_DELETE(pattern); + MUTILS_DELETE(pattern); } if(bTimeout || bAborted || (!checkVersion_succeeded(process.exitCode()))) @@ -175,7 +180,7 @@ bool AbstractTool::startProcess(QProcess &process, const QString &program, const if(process.waitForStarted()) { m_jobObject->addProcessToJob(&process); - x264_change_process_priority(&process, m_preferences->getProcessPriority()); + MUtils::OS::change_process_priority(&process, m_preferences->getProcessPriority()); lock.unlock(); return true; } diff --git a/src/version.h b/src/version.h index 52f06af..91a7842 100644 --- a/src/version.h +++ b/src/version.h @@ -26,7 +26,7 @@ #define VER_X264_MAJOR 2 #define VER_X264_MINOR 4 #define VER_X264_PATCH 6 -#define VER_X264_BUILD 911 +#define VER_X264_BUILD 914 #define VER_X264_PORTABLE_EDITION (0) diff --git a/src/win_addJob.cpp b/src/win_addJob.cpp index c3e55b4..aaead3d 100644 --- a/src/win_addJob.cpp +++ b/src/win_addJob.cpp @@ -22,6 +22,7 @@ #include "win_addJob.h" #include "UIC_win_addJob.h" +//Internal #include "global.h" #include "model_options.h" #include "model_preferences.h" @@ -32,6 +33,10 @@ #include "win_help.h" #include "win_editor.h" +//MUtils +#include + +//Qt #include #include #include @@ -320,22 +325,22 @@ AddJobDialog::~AddJobDialog(void) } const OptionsModel *item = reinterpret_cast(ui->cbxTemplate->itemData(i).value()); ui->cbxTemplate->setItemData(i, QVariant::fromValue(NULL)); - X264_DELETE(item); + MUTILS_DELETE(item); } //Free validators if(const QValidator *tmp = ui->editCustomX264Params->validator()) { ui->editCustomX264Params->setValidator(NULL); - X264_DELETE(tmp); + MUTILS_DELETE(tmp); } if(const QValidator *tmp = ui->editCustomAvs2YUVParams->validator()) { ui->editCustomAvs2YUVParams->setValidator(NULL); - X264_DELETE(tmp); + MUTILS_DELETE(tmp); } - X264_DELETE(m_defaults); + MUTILS_DELETE(m_defaults); delete ui; } @@ -834,7 +839,7 @@ void AddJobDialog::deleteTemplateButtonClicked(void) OptionsModel::deleteTemplate(name); const OptionsModel *item = reinterpret_cast(ui->cbxTemplate->itemData(index).value()); ui->cbxTemplate->removeItem(index); - X264_DELETE(item); + MUTILS_DELETE(item); } void AddJobDialog::editorActionTriggered(void) @@ -852,7 +857,7 @@ void AddJobDialog::editorActionTriggered(void) lineEdit->setText(editor->getEditText()); } - X264_DELETE(editor); + MUTILS_DELETE(editor); } } diff --git a/src/win_help.cpp b/src/win_help.cpp index 2c6fed6..308ef5e 100644 --- a/src/win_help.cpp +++ b/src/win_help.cpp @@ -22,10 +22,15 @@ #include "win_help.h" #include "UIC_win_help.h" +//Internal #include "global.h" #include "model_options.h" #include "binaries.h" +//MUtils +#include + +//Qt #include #include #include @@ -99,7 +104,7 @@ void HelpDialog::closeEvent(QCloseEvent *e) if(m_process->state() != QProcess::NotRunning) { e->ignore(); - x264_beep(x264_beep_warning); + MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); return; } diff --git a/src/win_main.cpp b/src/win_main.cpp index aa1f1a5..aae7079 100644 --- a/src/win_main.cpp +++ b/src/win_main.cpp @@ -49,6 +49,9 @@ #include #include #include +#include +#include +#include //Qt #include @@ -86,7 +89,8 @@ static const int vsynth_rev = 24; #define NEXT(X) ((*reinterpret_cast(&(X)))++) #define SETUP_WEBLINK(OBJ, URL) do { (OBJ)->setData(QVariant(QUrl(URL))); connect((OBJ), SIGNAL(triggered()), this, SLOT(showWebLink())); } while(0) #define APP_IS_READY (m_initialized && (!m_fileTimer->isActive()) && (QApplication::activeModalWidget() == NULL)) -#define ENSURE_APP_IS_READY() do { if(!APP_IS_READY) { x264_beep(x264_beep_warning); qWarning("Cannot perfrom this action at this time!"); return; } } while(0) +#define ENSURE_APP_IS_READY() do { if(!APP_IS_READY) { MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); qWarning("Cannot perfrom this action at this time!"); return; } } while(0) +#define X264_STRCMP(X,Y) ((X).compare((Y), Qt::CaseInsensitive) == 0) /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor @@ -142,7 +146,7 @@ MainWindow::MainWindow(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures, MUtil //Update title ui->labelBuildDate->setText(tr("Built on %1 at %2").arg(x264_version_date().toString(Qt::ISODate), QString::fromLatin1(x264_version_time()))); - if(X264_DEBUG) + if(MUTILS_DEBUG) { setWindowTitle(QString("%1 | !!! DEBUG VERSION !!!").arg(windowTitle())); setStyleSheet("QMenuBar, QMainWindow { background-color: yellow }"); @@ -272,7 +276,7 @@ MainWindow::~MainWindow(void) while(!m_toolsList->isEmpty()) { QFile *temp = m_toolsList->takeFirst(); - X264_DELETE(temp); + MUTILS_DELETE(temp); } if(!m_ipcThread.isNull()) @@ -402,7 +406,7 @@ void MainWindow::moveButtonPressed(void) qDebug("Move job %d (direction: UP)", ui->jobsView->currentIndex().row()); if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_UP)) { - x264_beep(x264_beep_error); + MUtils::Sound::beep(MUtils::Sound::BEEP_ERR); } ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter); } @@ -411,7 +415,7 @@ void MainWindow::moveButtonPressed(void) qDebug("Move job %d (direction: DOWN)", ui->jobsView->currentIndex().row()); if(!m_jobList->moveJob(ui->jobsView->currentIndex(), JobListModel::MOVE_DOWN)) { - x264_beep(x264_beep_error); + MUtils::Sound::beep(MUtils::Sound::BEEP_ERR); } ui->jobsView->scrollTo(ui->jobsView->currentIndex(), QAbstractItemView::PositionAtCenter); } @@ -428,7 +432,7 @@ void MainWindow::pauseButtonPressed(bool checked) { if(!APP_IS_READY) { - x264_beep(x264_beep_warning); + MUtils::Sound::beep(MUtils::Sound::BEEP_WRN); qWarning("Cannot perfrom this action at this time!"); ui->buttonPauseJob->setChecked(!checked); } @@ -463,7 +467,7 @@ void MainWindow::restartButtonPressed(void) { appendJob(sourceFileName, outputFileName, tempOptions, runImmediately); } - X264_DELETE(tempOptions); + MUTILS_DELETE(tempOptions); } } @@ -572,7 +576,7 @@ void MainWindow::showAbout(void) if(AboutDialog *aboutDialog = new AboutDialog(this)) { aboutDialog->exec(); - X264_DELETE(aboutDialog); + MUTILS_DELETE(aboutDialog); } } @@ -605,7 +609,7 @@ void MainWindow::showPreferences(void) PreferencesDialog *preferences = new PreferencesDialog(this, m_preferences.data(), m_sysinfo.data()); preferences->exec(); - X264_DELETE(preferences); + MUTILS_DELETE(preferences); } /* @@ -709,7 +713,7 @@ void MainWindow::shutdownComputer(void) QApplication::processEvents(QEventLoop::ExcludeUserInputEvents); QApplication::setOverrideCursor(Qt::WaitCursor); - x264_play_sound(IDR_WAVE1, false); + MUtils::Sound::play_sound("shutdown", false); QApplication::restoreOverrideCursor(); QTimer timer; @@ -732,12 +736,12 @@ void MainWindow::shutdownComputer(void) progressDialog.setLabelText(text.arg(iTimeout-i)); if(iTimeout-i == 3) progressDialog.setCancelButton(NULL); QApplication::processEvents(); - x264_play_sound(((i < iTimeout) ? IDR_WAVE2 : IDR_WAVE3), false); + MUtils::Sound::play_sound(((i < iTimeout) ? "beep" : "beep2"), false); } qWarning("Shutting down !!!"); - if(x264_shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true)) + if(MUtils::OS::shutdown_computer("Simple x264 Launcher: All jobs completed, shutting down!", 10, true, false)) { qApp->closeAllWindows(); } @@ -790,11 +794,11 @@ void MainWindow::init(void) qDebug("%s", file->fileName().toLatin1().constData()); if(file->open(QIODevice::ReadOnly)) { - if(!x264_is_executable(file->fileName())) + if(!MUtils::OS::is_executable_file(file->fileName())) { QMessageBox::critical(this, tr("Invalid File!"), tr("At least on required tool is not a valid Win32 or Win64 binary:
%1

Please re-install the program in order to fix the problem!
").arg(QDir::toNativeSeparators(file->fileName())).replace("-", "−")); qFatal(QString("Binary is invalid: %1").arg(file->fileName()).toLatin1().constData()); - X264_DELETE(file); + MUTILS_DELETE(file); INIT_ERROR_EXIT(); } if(m_toolsList.isNull()) @@ -807,7 +811,7 @@ void MainWindow::init(void) { QMessageBox::critical(this, tr("File Not Found!"), tr("At least on required tool could not be found:
%1

Please re-install the program in order to fix the problem!
").arg(QDir::toNativeSeparators(file->fileName())).replace("-", "−")); qFatal(QString("Binary not found: %1/toolset/%2").arg(m_sysinfo->getAppPath(), file->fileName()).toLatin1().constData()); - X264_DELETE(file); + MUTILS_DELETE(file); INIT_ERROR_EXIT(); } } @@ -972,7 +976,7 @@ void MainWindow::init(void) // Check for Expiration //--------------------------------------- - if(x264_version_date().addMonths(6) < x264_current_date_safe()) + if(x264_version_date().addMonths(6) < MUtils::OS::current_date()) { if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show(); QString text; @@ -1006,7 +1010,7 @@ void MainWindow::init(void) m_recentlyUsed->setLastUpdateCheck(0); RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data()); } - else if(m_recentlyUsed->lastUpdateCheck() + 14 < x264_current_date_safe().toJulianDay()) + else if(m_recentlyUsed->lastUpdateCheck() + 14 < MUtils::OS::current_date().toJulianDay()) { if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->show(); if(!m_preferences->getNoUpdateReminder()) @@ -1058,7 +1062,7 @@ void MainWindow::copyLogToClipboard(bool checked) if(LogFileModel *log = dynamic_cast(ui->logView->model())) { log->copyToClipboard(); - x264_beep(x264_beep_info); + MUtils::Sound::beep(MUtils::Sound::BEEP_NFO); } } @@ -1095,7 +1099,7 @@ void MainWindow::handleCommand(const int &command, const QStringList &args, cons sysTrayActived(); } - x264_bring_to_front(this); + MUtils::GUI::bring_to_front(this); #ifdef IPC_LOGGING qDebug("\n---------- IPC ----------"); @@ -1112,7 +1116,7 @@ void MainWindow::handleCommand(const int &command, const QStringList &args, cons { case IPC_OPCODE_PING: qDebug("Received a PING request from another instance!"); - x264_blink_window(this, 5, 125); + MUtils::GUI::blink_window(this, 5, 125); break; case IPC_OPCODE_ADD_FILE: if(!args.isEmpty()) @@ -1157,7 +1161,7 @@ void MainWindow::handleCommand(const int &command, const QStringList &args, cons } break; default: - THROW("Unknown command received!"); + MUTILS_THROW("Unknown command received!"); } } @@ -1179,7 +1183,7 @@ void MainWindow::checkUpdates(void) if(updater->getSuccess()) { - m_recentlyUsed->setLastUpdateCheck(x264_current_date_safe().toJulianDay()); + m_recentlyUsed->setLastUpdateCheck(MUtils::OS::current_date().toJulianDay()); RecentlyUsed::saveRecentlyUsed(m_recentlyUsed.data()); if(QWidget *cornerWidget = ui->menubar->cornerWidget()) cornerWidget->hide(); } @@ -1191,7 +1195,7 @@ void MainWindow::checkUpdates(void) QApplication::quit(); } - X264_DELETE(updater); + MUTILS_DELETE(updater); } /* @@ -1228,7 +1232,7 @@ void MainWindow::sysTrayActived(void) { m_sysTray->hide(); showNormal(); - x264_bring_to_front(this); + MUtils::GUI::bring_to_front(this); } /////////////////////////////////////////////////////////////////////////////// @@ -1423,7 +1427,7 @@ bool MainWindow::createJob(QString &sourceFileName, QString &outputFileName, Opt okay = true; } - X264_DELETE(addDialog); + MUTILS_DELETE(addDialog); return okay; } diff --git a/src/win_preferences.cpp b/src/win_preferences.cpp index 4370ccb..5a12bb3 100644 --- a/src/win_preferences.cpp +++ b/src/win_preferences.cpp @@ -22,10 +22,15 @@ #include "win_preferences.h" #include "UIC_win_preferences.h" +//Internal #include "global.h" #include "model_preferences.h" #include "model_sysinfo.h" +//MUtils +#include + +//Qt #include #include #include @@ -62,7 +67,7 @@ PreferencesDialog::PreferencesDialog(QWidget *parent, PreferencesModel *preferen ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); setFixedSize(minimumSize()); - x264_enable_close_button(this, false); + MUtils::GUI::enable_close_button(this, false); ui->comboBoxPriority->setItemData(0, QVariant::fromValue( 1)); //Above Normal ui->comboBoxPriority->setItemData(1, QVariant::fromValue( 0)); //Normal diff --git a/src/win_updater.cpp b/src/win_updater.cpp index a90f6a9..913839d 100644 --- a/src/win_updater.cpp +++ b/src/win_updater.cpp @@ -29,7 +29,11 @@ //MUtils #include #include +#include +#include +#include +//Qt #include #include #include @@ -139,7 +143,7 @@ bool UpdaterDialog::event(QEvent *e) { if((e->type() == QEvent::ActivationChange) && (m_updaterProcess != NULL)) { - x264_bring_process_to_front(m_updaterProcess); + MUtils::GUI::bring_to_front(m_updaterProcess); } return QDialog::event(e); } @@ -165,7 +169,7 @@ void UpdaterDialog::keyPressEvent(QKeyEvent *event) { if(event->key() == Qt::Key_F11) { - QFile logFile(QString("%1/%2.log").arg(x264_temp_directory(), x264_rand_str())); + QFile logFile(QString("%1/%2.log").arg(MUtils::temp_folder(), MUtils::rand_str())); if(logFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { logFile.write("\xEF\xBB\xBF"); @@ -206,7 +210,7 @@ void UpdaterDialog::initUpdate(void) } //Make sure user does have admin access - if(!x264_user_is_admin()) + if(!MUtils::OS::user_is_admin()) { qWarning("User is not in the \"admin\" group, cannot update!"); QString message; @@ -312,7 +316,7 @@ void UpdaterDialog::threadStatusChanged(int status) UPDATE_ICON(3, "play"); break; default: - THROW("Unknown status code!"); + MUTILS_THROW("Unknown status code!"); } } @@ -405,7 +409,7 @@ void UpdaterDialog::installUpdate(void) QStringList args; QEventLoop loop; - x264_init_process(process, x264_temp_directory(), false); + MUtils::init_process(process, MUtils::temp_folder(), false); connect(&process, SIGNAL(error(QProcess::ProcessError)), &loop, SLOT(quit())); connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit())); @@ -428,7 +432,7 @@ void UpdaterDialog::installUpdate(void) return; } - m_updaterProcess = x264_process_id(process); + m_updaterProcess = MUtils::OS::process_id(&process); loop.exec(QEventLoop::ExcludeUserInputEvents); if(!process.waitForFinished()) diff --git a/src/zero.cpp b/src/zero.cpp index 788944f..c933cce 100644 --- a/src/zero.cpp +++ b/src/zero.cpp @@ -49,7 +49,6 @@ static size_t x264_entry_check(void) /* * Function declarations */ -void x264_initialization(void); extern "C" int mainCRTStartup(void); /* @@ -65,9 +64,6 @@ extern "C" int x264_entry_point(void) //Make sure we will pass the check g_x264_entry_check_flag = ~g_x264_entry_check_flag; - //Call global initialization function - x264_initialization(); - //Now initialize the C Runtime library! return mainCRTStartup(); }