OSDN Git Service

Added a new "--add-job <src_file> <out_file> <template>" command-line option. Also...
[x264-launcher/x264-launcher.git] / src / global.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Simple x264 Launcher
3 // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 //x264 includes
23 #include "global.h"
24 #include "targetver.h"
25
26 //Version
27 #define ENABLE_X264_VERSION_INCLUDE
28 #include "version.h"
29 #undef  ENABLE_X264_VERSION_INCLUDE
30
31 //Windows includes
32 #define NOMINMAX
33 #define WIN32_LEAN_AND_MEAN
34 #include <Windows.h>
35 #include <MMSystem.h>
36 #include <ShellAPI.h>
37 #include <Objbase.h>
38 #include <Psapi.h>
39 #include <SensAPI.h>
40
41 //C++ includes
42 #include <stdio.h>
43 #include <string.h>
44 #include <iostream>
45 #include <time.h>
46
47 //VLD
48 #include <vld.h>
49
50 //Qt includes
51 #include <QApplication>
52 #include <QMessageBox>
53 #include <QDir>
54 #include <QUuid>
55 #include <QMap>
56 #include <QDate>
57 #include <QIcon>
58 #include <QPlastiqueStyle>
59 #include <QImageReader>
60 #include <QSharedMemory>
61 #include <QSysInfo>
62 #include <QStringList>
63 #include <QSystemSemaphore>
64 #include <QDesktopServices>
65 #include <QMutex>
66 #include <QTextCodec>
67 #include <QLibrary>
68 #include <QRegExp>
69 #include <QResource>
70 #include <QTranslator>
71 #include <QEventLoop>
72 #include <QTimer>
73 #include <QLibraryInfo>
74 #include <QEvent>
75 #include <QReadLocker>
76 #include <QWriteLocker>
77 #include <QProcess>
78
79 //CRT includes
80 #include <fstream>
81 #include <io.h>
82 #include <fcntl.h>
83 #include <intrin.h>
84 #include <process.h>
85
86 //Debug only includes
87 #if X264_DEBUG
88 #include <Psapi.h>
89 #endif
90
91 //Global types
92 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
93 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
94
95 //Global vars
96 static bool g_x264_console_attached = false;
97 static QMutex g_x264_message_mutex;
98 static const DWORD g_main_thread_id = GetCurrentThreadId();
99 static FILE *g_x264_log_file = NULL;
100 static QDate g_x264_version_date;
101
102 //Const
103 static const char *g_x264_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
104 static const char *g_x264_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
105
106 //Build version
107 static const struct
108 {
109         unsigned int ver_major;
110         unsigned int ver_minor;
111         unsigned int ver_patch;
112         unsigned int ver_build;
113         const char* ver_date;
114         const char* ver_time;
115         unsigned int ver_x264_minimum_rev;
116         unsigned int ver_x264_current_api;
117         unsigned int ver_x264_avs2yuv_ver;
118 }
119 g_x264_version =
120 {
121         (VER_X264_MAJOR),
122         (VER_X264_MINOR),
123         (VER_X264_PATCH),
124         (VER_X264_BUILD),
125         __DATE__,
126         __TIME__,
127         (VER_X264_MINIMUM_REV),
128         (VER_X264_CURRENT_API),
129         (VER_X264_AVS2YUV_VER)
130 };
131
132 //CLI Arguments
133 static struct
134 {
135         QStringList *list;
136         QReadWriteLock lock;
137 }
138 g_x264_argv;
139
140 //OS Version
141 static struct
142 {
143         bool bInitialized;
144         x264_os_version_t version;
145         QReadWriteLock lock;
146 }
147 g_x264_os_version;
148
149 //Special folders
150 static struct
151 {
152         QMap<size_t, QString> *knownFolders;
153         SHGetKnownFolderPath_t getKnownFolderPath;
154         SHGetFolderPath_t getFolderPath;
155         QReadWriteLock lock;
156 }
157 g_x264_known_folder;
158
159 //%TEMP% folder
160 static struct
161 {
162         QString *path;
163         QReadWriteLock lock;
164 }
165 g_x264_temp_folder;
166
167 //Wine detection
168 static struct
169 {
170         bool bInitialized;
171         bool bIsWine;
172         QReadWriteLock lock;
173 }
174 g_x264_wine;
175
176 //Portable Mode
177 static struct
178 {
179         bool bInitialized;
180         bool bPortableModeEnabled;
181         QReadWriteLock lock;
182 }
183 g_x264_portable;
184
185 //Known Windows versions - maps marketing names to the actual Windows NT versions
186 const x264_os_version_t x264_winver_win2k = {5,0};
187 const x264_os_version_t x264_winver_winxp = {5,1};
188 const x264_os_version_t x264_winver_xpx64 = {5,2};
189 const x264_os_version_t x264_winver_vista = {6,0};
190 const x264_os_version_t x264_winver_win70 = {6,1};
191 const x264_os_version_t x264_winver_win80 = {6,2};
192 const x264_os_version_t x264_winver_win81 = {6,3};
193
194 //GURU MEDITATION
195 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
196
197 ///////////////////////////////////////////////////////////////////////////////
198 // MACROS
199 ///////////////////////////////////////////////////////////////////////////////
200
201 //String helper
202 #define CLEAN_OUTPUT_STRING(STR) do \
203 { \
204         const char CTRL_CHARS[3] = { '\r', '\n', '\t' }; \
205         for(size_t i = 0; i < 3; i++) \
206         { \
207                 while(char *pos = strchr((STR), CTRL_CHARS[i])) *pos = char(0x20); \
208         } \
209 } \
210 while(0)
211
212 //String helper
213 #define TRIM_LEFT(STR) do \
214 { \
215         const char WHITE_SPACE[4] = { char(0x20), '\r', '\n', '\t' }; \
216         for(size_t i = 0; i < 4; i++) \
217         { \
218                 while(*(STR) == WHITE_SPACE[i]) (STR)++; \
219         } \
220 } \
221 while(0)
222
223 #define X264_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
224
225 ///////////////////////////////////////////////////////////////////////////////
226 // COMPILER INFO
227 ///////////////////////////////////////////////////////////////////////////////
228
229 /*
230  * Disclaimer: Parts of the following code were borrowed from MPC-HC project: http://mpc-hc.sf.net/
231  */
232
233 //Compiler detection
234 #if defined(__INTEL_COMPILER)
235         #if (__INTEL_COMPILER >= 1300)
236                 static const char *g_x264_version_compiler = "ICL 13." X264_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
237         #elif (__INTEL_COMPILER >= 1200)
238                 static const char *g_x264_version_compiler = "ICL 12." X264_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
239         #elif (__INTEL_COMPILER >= 1100)
240                 static const char *g_x264_version_compiler = "ICL 11.x";
241         #elif (__INTEL_COMPILER >= 1000)
242                 static const char *g_x264_version_compiler = "ICL 10.x";
243         #else
244                 #error Compiler is not supported!
245         #endif
246 #elif defined(_MSC_VER)
247         #if (_MSC_VER == 1800)
248                 #if (_MSC_FULL_VER < 180021005)
249                         static const char *g_x264_version_compiler = "MSVC 2013-Beta";
250                 #elif (_MSC_FULL_VER == 180021005)
251                         static const char *g_x264_version_compiler = "MSVC 2013";
252                 #else
253                         #error Compiler version is not supported yet!
254                 #endif
255         #elif (_MSC_VER == 1700)
256                 #if (_MSC_FULL_VER < 170050727)
257                         static const char *g_x264_version_compiler = "MSVC 2012-Beta";
258                 #elif (_MSC_FULL_VER < 170051020)
259                         static const char *g_x264_version_compiler = "MSVC 2012";
260                 #elif (_MSC_FULL_VER < 170051106)
261                         static const char *g_x264_version_compiler = "MSVC 2012.1-CTP";
262                 #elif (_MSC_FULL_VER < 170060315)
263                         static const char *g_x264_version_compiler = "MSVC 2012.1";
264                 #elif (_MSC_FULL_VER < 170060610)
265                         static const char *g_x264_version_compiler = "MSVC 2012.2";
266                 #elif (_MSC_FULL_VER == 170060610)
267                         static const char *g_x264_version_compiler = "MSVC 2012.3";
268                 #else
269                         #error Compiler version is not supported yet!
270                 #endif
271         #elif (_MSC_VER == 1600)
272                 #if (_MSC_FULL_VER < 160040219)
273                         static const char *g_x264_version_compiler = "MSVC 2010";
274                 #elif (_MSC_FULL_VER == 160040219)
275                         static const char *g_x264_version_compiler = "MSVC 2010-SP1";
276                 #else
277                         #error Compiler version is not supported yet!
278                 #endif
279         #elif (_MSC_VER == 1500)
280                 #if (_MSC_FULL_VER >= 150030729)
281                         static const char *g_x264_version_compiler = "MSVC 2008-SP1";
282                 #else
283                         static const char *g_x264_version_compiler = "MSVC 2008";
284                 #endif
285         #else
286                 #error Compiler is not supported!
287         #endif
288
289         // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
290         #if !defined(_M_X64) && defined(_M_IX86_FP)
291                 #if (_M_IX86_FP == 1)
292                         X264_COMPILER_WARNING("SSE instruction set is enabled!")
293                 #elif (_M_IX86_FP == 2)
294                         X264_COMPILER_WARNING("SSE2 (or higher) instruction set is enabled!")
295                 #endif
296         #endif
297 #else
298         #error Compiler is not supported!
299 #endif
300
301 //Architecture detection
302 #if defined(_M_X64)
303         static const char *g_x264_version_arch = "x64";
304 #elif defined(_M_IX86)
305         static const char *g_x264_version_arch = "x86";
306 #else
307         #error Architecture is not supported!
308 #endif
309
310 ///////////////////////////////////////////////////////////////////////////////
311 // GLOBAL FUNCTIONS
312 ///////////////////////////////////////////////////////////////////////////////
313
314 static __forceinline bool x264_check_for_debugger(void);
315
316 /*
317  * Suspend calling thread for N milliseconds
318  */
319 inline void x264_sleep(const unsigned int delay)
320 {
321         Sleep(delay);
322 }
323
324 /*
325  * Global exception handler
326  */
327 LONG WINAPI x264_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
328 {
329         if(GetCurrentThreadId() != g_main_thread_id)
330         {
331                 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
332                 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
333         }
334
335         x264_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
336         return LONG_MAX;
337 }
338
339 /*
340  * Invalid parameters handler
341  */
342 void x264_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
343 {
344         if(GetCurrentThreadId() != g_main_thread_id)
345         {
346                 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
347                 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
348         }
349
350         x264_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
351 }
352
353 /*
354  * Get a random string
355  */
356 QString x264_rand_str(const bool bLong)
357 {
358         const QUuid uuid = QUuid::createUuid().toString();
359
360         const unsigned int u1 = uuid.data1;
361         const unsigned int u2 = (((unsigned int)(uuid.data2)) << 16) | ((unsigned int)(uuid.data3));
362         const unsigned int u3 = (((unsigned int)(uuid.data4[0])) << 24) | (((unsigned int)(uuid.data4[1])) << 16) | (((unsigned int)(uuid.data4[2])) << 8) | ((unsigned int)(uuid.data4[3]));
363         const unsigned int u4 = (((unsigned int)(uuid.data4[4])) << 24) | (((unsigned int)(uuid.data4[5])) << 16) | (((unsigned int)(uuid.data4[6])) << 8) | ((unsigned int)(uuid.data4[7]));
364
365         return bLong ? QString().sprintf("%08x%08x%08x%08x", u1, u2, u3, u4) : QString().sprintf("%08x%08x", (u1 ^ u2), (u3 ^ u4));
366 }
367
368 /*
369  * Robert Jenkins' 96 bit Mix Function
370  * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
371  */
372 static unsigned int x264_mix(const unsigned int x, const unsigned int y, const unsigned int z)
373 {
374         unsigned int a = x;
375         unsigned int b = y;
376         unsigned int c = z;
377         
378         a=a-b;  a=a-c;  a=a^(c >> 13);
379         b=b-c;  b=b-a;  b=b^(a << 8); 
380         c=c-a;  c=c-b;  c=c^(b >> 13);
381         a=a-b;  a=a-c;  a=a^(c >> 12);
382         b=b-c;  b=b-a;  b=b^(a << 16);
383         c=c-a;  c=c-b;  c=c^(b >> 5);
384         a=a-b;  a=a-c;  a=a^(c >> 3);
385         b=b-c;  b=b-a;  b=b^(a << 10);
386         c=c-a;  c=c-b;  c=c^(b >> 15);
387
388         return c;
389 }
390
391 /*
392  * Seeds the random number generator
393  * Note: Altough rand_s() doesn't need a seed, this must be called pripr to x264_rand(), just to to be sure!
394  */
395 void x264_seed_rand(void)
396 {
397         qsrand(x264_mix(clock(), time(NULL), _getpid()));
398 }
399
400 /*
401  * Returns a randum number
402  * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
403  */
404 unsigned int x264_rand(void)
405 {
406         quint32 rnd = 0;
407
408         if(rand_s(&rnd) == 0)
409         {
410                 return rnd;
411         }
412
413         for(size_t i = 0; i < sizeof(unsigned int); i++)
414         {
415                 rnd = (rnd << 8) ^ qrand();
416         }
417
418         return rnd;
419 }
420
421 /*
422  * Change console text color
423  */
424 static void x264_console_color(FILE* file, WORD attributes)
425 {
426         const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
427         if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
428         {
429                 SetConsoleTextAttribute(hConsole, attributes);
430         }
431 }
432
433 /*
434  * Determines the current date, resistant against certain manipulations
435  */
436 QDate x264_current_date_safe(void)
437 {
438         const DWORD MAX_PROC = 1024;
439         DWORD *processes = new DWORD[MAX_PROC];
440         DWORD bytesReturned = 0;
441         
442         if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
443         {
444                 X264_DELETE_ARRAY(processes);
445                 return QDate::currentDate();
446         }
447
448         const DWORD procCount = bytesReturned / sizeof(DWORD);
449         ULARGE_INTEGER lastStartTime;
450         memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
451
452         for(DWORD i = 0; i < procCount; i++)
453         {
454                 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
455                 if(hProc)
456                 {
457                         FILETIME processTime[4];
458                         if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
459                         {
460                                 ULARGE_INTEGER timeCreation;
461                                 timeCreation.LowPart = processTime[0].dwLowDateTime;
462                                 timeCreation.HighPart = processTime[0].dwHighDateTime;
463                                 if(timeCreation.QuadPart > lastStartTime.QuadPart)
464                                 {
465                                         lastStartTime.QuadPart = timeCreation.QuadPart;
466                                 }
467                         }
468                         CloseHandle(hProc);
469                 }
470         }
471
472         X264_DELETE_ARRAY(processes);
473         
474         FILETIME lastStartTime_fileTime;
475         lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
476         lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
477
478         FILETIME lastStartTime_localTime;
479         if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
480         {
481                 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
482         }
483         
484         SYSTEMTIME lastStartTime_system;
485         if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
486         {
487                 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
488                 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
489         }
490
491         const QDate currentDate = QDate::currentDate();
492         const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
493         return (currentDate >= processDate) ? currentDate : processDate;
494 }
495
496 /*
497  * Output logging message to console
498  */
499 static void x264_write_console(const int type, const char *msg)
500 {       
501         __try
502         {
503                 if(_isatty(_fileno(stderr)))
504                 {
505                         UINT oldOutputCP = GetConsoleOutputCP();
506                         if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
507
508                         switch(type)
509                         {
510                         case QtCriticalMsg:
511                         case QtFatalMsg:
512                                 x264_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
513                                 fprintf(stderr, GURU_MEDITATION);
514                                 fprintf(stderr, "%s\n", msg);
515                                 fflush(stderr);
516                                 break;
517                         case QtWarningMsg:
518                                 x264_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
519                                 fprintf(stderr, "%s\n", msg);
520                                 fflush(stderr);
521                                 break;
522                         default:
523                                 x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
524                                 fprintf(stderr, "%s\n", msg);
525                                 fflush(stderr);
526                                 break;
527                         }
528         
529                         x264_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
530                         if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
531                 }
532         }
533         __except(1)
534         {
535                 /*ignore any exception that might occur here!*/
536         }
537 }
538
539 /*
540  * Output logging message to debugger
541  */
542 static void x264_write_dbg_out(const int type, const char *msg)
543 {       
544         const char *FORMAT = "[sx264l][%c] %s\n";
545
546         __try
547         {
548                 char buffer[512];
549                 const char* input = msg;
550                 TRIM_LEFT(input);
551                 
552                 switch(type)
553                 {
554                 case QtCriticalMsg:
555                 case QtFatalMsg:
556                         _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'C', input);
557                         break;
558                 case QtWarningMsg:
559                         _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'W', input);
560                         break;
561                 default:
562                         _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'I', input);
563                         break;
564                 }
565
566                 char *temp = &buffer[0];
567                 CLEAN_OUTPUT_STRING(temp);
568                 OutputDebugStringA(temp);
569         }
570         __except(1)
571         {
572                 /*ignore any exception that might occur here!*/
573         }
574 }
575
576 /*
577  * Output logging message to logfile
578  */
579 static void x264_write_logfile(const int type, const char *msg)
580 {       
581         const char *FORMAT = "[%c][%04u] %s\r\n";
582
583         __try
584         {
585                 if(g_x264_log_file)
586                 {
587                         char buffer[512];
588                         strncpy_s(buffer, 512, msg, _TRUNCATE);
589
590                         char *temp = &buffer[0];
591                         TRIM_LEFT(temp);
592                         CLEAN_OUTPUT_STRING(temp);
593                         
594                         const unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
595
596                         switch(type)
597                         {
598                         case QtCriticalMsg:
599                         case QtFatalMsg:
600                                 fprintf(g_x264_log_file, FORMAT, 'C', timestamp, temp);
601                                 break;
602                         case QtWarningMsg:
603                                 fprintf(g_x264_log_file, FORMAT, 'W', timestamp, temp);
604                                 break;
605                         default:
606                                 fprintf(g_x264_log_file, FORMAT, 'I', timestamp, temp);
607                                 break;
608                         }
609
610                         fflush(g_x264_log_file);
611                 }
612         }
613         __except(1)
614         {
615                 /*ignore any exception that might occur here!*/
616         }
617 }
618
619 /*
620  * Qt message handler
621  */
622 void x264_message_handler(QtMsgType type, const char *msg)
623 {
624         if((!msg) || (!(msg[0])))
625         {
626                 return;
627         }
628
629         QMutexLocker lock(&g_x264_message_mutex);
630
631         if(g_x264_log_file)
632         {
633                 x264_write_logfile(type, msg);
634         }
635
636         if(g_x264_console_attached)
637         {
638                 x264_write_console(type, msg);
639         }
640         else
641         {
642                 x264_write_dbg_out(type, msg);
643         }
644
645         if((type == QtCriticalMsg) || (type == QtFatalMsg))
646         {
647                 lock.unlock();
648                 x264_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
649         }
650 }
651
652 /*
653  * Initialize the console
654  */
655 void x264_init_console(const QStringList &argv)
656 {
657         bool enableConsole = x264_is_prerelease() || (X264_DEBUG);
658
659         if(_environ)
660         {
661                 wchar_t *logfile = NULL;
662                 size_t logfile_len = 0;
663                 if(!_wdupenv_s(&logfile, &logfile_len, L"X264_LOGFILE"))
664                 {
665                         if(logfile && (logfile_len > 0))
666                         {
667                                 FILE *temp = NULL;
668                                 if(!_wfopen_s(&temp, logfile, L"wb"))
669                                 {
670                                         fprintf(temp, "%c%c%c", char(0xEF), char(0xBB), char(0xBF));
671                                         g_x264_log_file = temp;
672                                 }
673                                 free(logfile);
674                         }
675                 }
676         }
677
678         if(!X264_DEBUG)
679         {
680                 for(int i = 0; i < argv.count(); i++)
681                 {
682                         if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
683                         {
684                                 enableConsole = true;
685                         }
686                         else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
687                         {
688                                 enableConsole = false;
689                         }
690                 }
691         }
692
693         if(enableConsole)
694         {
695                 if(!g_x264_console_attached)
696                 {
697                         if(AllocConsole() != FALSE)
698                         {
699                                 SetConsoleCtrlHandler(NULL, TRUE);
700                                 SetConsoleTitle(L"Simple x264 Launcher | Debug Console");
701                                 SetConsoleOutputCP(CP_UTF8);
702                                 g_x264_console_attached = true;
703                         }
704                 }
705                 
706                 if(g_x264_console_attached)
707                 {
708                         //-------------------------------------------------------------------
709                         //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
710                         //-------------------------------------------------------------------
711                         const int flags = _O_WRONLY | _O_U8TEXT;
712                         int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
713                         int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE),  flags);
714                         FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
715                         FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
716                         if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
717                         if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
718                 }
719
720                 HWND hwndConsole = GetConsoleWindow();
721
722                 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
723                 {
724                         HMENU hMenu = GetSystemMenu(hwndConsole, 0);
725                         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
726                         RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
727
728                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
729                         SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
730                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
731                 }
732         }
733 }
734
735 /*
736  * Initialize the console
737  */
738 void x264_init_console(int argc, char* argv[])
739 {
740         bool enableConsole = x264_is_prerelease() || (X264_DEBUG);
741
742         if(_environ)
743         {
744                 wchar_t *logfile = NULL;
745                 size_t logfile_len = 0;
746                 if(!_wdupenv_s(&logfile, &logfile_len, L"X264_LAUNCHER_LOGFILE"))
747                 {
748                         if(logfile && (logfile_len > 0))
749                         {
750                                 FILE *temp = NULL;
751                                 if(!_wfopen_s(&temp, logfile, L"wb"))
752                                 {
753                                         fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
754                                         g_x264_log_file = temp;
755                                 }
756                                 free(logfile);
757                         }
758                 }
759         }
760
761         if(!X264_DEBUG)
762         {
763                 for(int i = 0; i < argc; i++)
764                 {
765                         if(!_stricmp(argv[i], "--console"))
766                         {
767                                 enableConsole = true;
768                         }
769                         else if(!_stricmp(argv[i], "--no-console"))
770                         {
771                                 enableConsole = false;
772                         }
773                 }
774         }
775
776         if(enableConsole)
777         {
778                 if(!g_x264_console_attached)
779                 {
780                         if(AllocConsole())
781                         {
782                                 SetConsoleCtrlHandler(NULL, TRUE);
783                                 SetConsoleTitle(L"Simple x264 Launcher | Debug Console");
784                                 SetConsoleOutputCP(CP_UTF8);
785                                 g_x264_console_attached = true;
786                         }
787                 }
788                 
789                 if(g_x264_console_attached)
790                 {
791                         //-------------------------------------------------------------------
792                         //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
793                         //-------------------------------------------------------------------
794                         const int flags = _O_WRONLY | _O_U8TEXT;
795                         int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
796                         int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
797                         FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
798                         FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
799                         if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
800                         if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
801                 }
802
803                 HWND hwndConsole = GetConsoleWindow();
804
805                 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
806                 {
807                         HMENU hMenu = GetSystemMenu(hwndConsole, 0);
808                         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
809                         RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
810
811                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
812                         SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
813                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
814                 }
815         }
816 }
817
818 /*
819  * Version info
820  */
821 unsigned int x264_version_major(void)
822 {
823         return g_x264_version.ver_major;
824 }
825
826 unsigned int x264_version_minor(void)
827 {
828         return (g_x264_version.ver_minor * 10) + (g_x264_version.ver_patch % 10);
829 }
830
831 unsigned int x264_version_build(void)
832 {
833         return g_x264_version.ver_build;
834 }
835
836 const char *x264_version_compiler(void)
837 {
838         return g_x264_version_compiler;
839 }
840
841 const char *x264_version_arch(void)
842 {
843         return g_x264_version_arch;
844 }
845
846 unsigned int x264_version_x264_minimum_rev(void)
847 {
848         return g_x264_version.ver_x264_minimum_rev;
849 }
850
851 unsigned int x264_version_x264_current_api(void)
852 {
853         return g_x264_version.ver_x264_current_api;
854 }
855
856 unsigned int x264_version_x264_avs2yuv_ver(void)
857 {
858         return g_x264_version.ver_x264_avs2yuv_ver;
859 }
860
861 /*
862  * Get CLI arguments
863  */
864 const QStringList &x264_arguments(void)
865 {
866         QReadLocker readLock(&g_x264_argv.lock);
867
868         if(!g_x264_argv.list)
869         {
870                 readLock.unlock();
871                 QWriteLocker writeLock(&g_x264_argv.lock);
872
873                 g_x264_argv.list = new QStringList;
874
875                 int nArgs = 0;
876                 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
877
878                 if(NULL != szArglist)
879                 {
880                         for(int i = 0; i < nArgs; i++)
881                         {
882                                 (*g_x264_argv.list) << WCHAR2QSTR(szArglist[i]);
883                         }
884                         LocalFree(szArglist);
885                 }
886                 else
887                 {
888                         qWarning("CommandLineToArgvW() has failed !!!");
889                 }
890         }
891
892         return (*g_x264_argv.list);
893 }
894
895 /*
896  * Check for portable mode
897  */
898 bool x264_portable(void)
899 {
900         QReadLocker readLock(&g_x264_portable.lock);
901
902         if(g_x264_portable.bInitialized)
903         {
904                 return g_x264_portable.bPortableModeEnabled;
905         }
906         
907         readLock.unlock();
908         QWriteLocker writeLock(&g_x264_portable.lock);
909
910         if(!g_x264_portable.bInitialized)
911         {
912                 if(VER_X264_PORTABLE_EDITION)
913                 {
914                         qWarning("Simple x264 Launcher portable edition!\n");
915                         g_x264_portable.bPortableModeEnabled = true;
916                 }
917                 else
918                 {
919                         QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
920                         int idx1 = baseName.indexOf("x264", 0, Qt::CaseInsensitive);
921                         int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
922                         g_x264_portable.bPortableModeEnabled = (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
923                 }
924                 g_x264_portable.bInitialized = true;
925         }
926         
927         return g_x264_portable.bPortableModeEnabled;
928 }
929
930 /*
931  * Get data path (i.e. path to store config files)
932  */
933 const QString &x264_data_path(void)
934 {
935         static QString pathCache;
936         
937         if(pathCache.isNull())
938         {
939                 if(!x264_portable())
940                 {
941                         pathCache = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
942                 }
943                 if(pathCache.isEmpty() || x264_portable())
944                 {
945                         pathCache = QApplication::applicationDirPath();
946                 }
947                 if(!QDir(pathCache).mkpath("."))
948                 {
949                         qWarning("Data directory could not be created:\n%s\n", pathCache.toUtf8().constData());
950                         pathCache = QDir::currentPath();
951                 }
952         }
953         
954         return pathCache;
955 }
956
957 /*
958  * Get build date date
959  */
960 const QDate &x264_version_date(void)
961 {
962         if(!g_x264_version_date.isValid())
963         {
964                 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
965                 strncpy_s(temp, 12, g_x264_version.ver_date, _TRUNCATE);
966
967                 if(strlen(temp) == 11)
968                 {
969                         temp[3] = temp[6] = '\0';
970                         date[2] = atoi(&temp[4]);
971                         date[0] = atoi(&temp[7]);
972                         
973                         for(int j = 0; j < 12; j++)
974                         {
975                                 if(!_strcmpi(&temp[0], g_x264_months[j]))
976                                 {
977                                         date[1] = j+1;
978                                         break;
979                                 }
980                         }
981
982                         g_x264_version_date = QDate(date[0], date[1], date[2]);
983                 }
984
985                 if(!g_x264_version_date.isValid())
986                 {
987                         qFatal("Internal error: Date format could not be recognized!");
988                 }
989         }
990
991         return g_x264_version_date;
992 }
993
994 const char *x264_version_time(void)
995 {
996         return g_x264_version.ver_time;
997 }
998
999 bool x264_is_prerelease(void)
1000 {
1001         return (VER_X264_PRE_RELEASE);
1002 }
1003
1004 /*
1005  * CPUID prototype (actual function is in ASM code)
1006  */
1007 extern "C"
1008 {
1009         void x264_cpu_cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx);
1010 }
1011
1012 /*
1013  * Detect CPU features
1014  */
1015 x264_cpu_t x264_detect_cpu_features(const QStringList &argv)
1016 {
1017         typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
1018
1019         x264_cpu_t features;
1020         SYSTEM_INFO systemInfo;
1021         unsigned int CPUInfo[4];
1022         char CPUIdentificationString[0x40];
1023         char CPUBrandString[0x40];
1024
1025         memset(&features, 0, sizeof(x264_cpu_t));
1026         memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
1027         memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
1028         memset(CPUBrandString, 0, sizeof(CPUBrandString));
1029         
1030         x264_cpu_cpuid(0, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1031         memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
1032         memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
1033         memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
1034         features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
1035         strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
1036
1037         if(CPUInfo[0] >= 1)
1038         {
1039                 x264_cpu_cpuid(1, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1040                 features.mmx = (CPUInfo[3] & 0x800000) || false;
1041                 features.sse = (CPUInfo[3] & 0x2000000) || false;
1042                 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
1043                 features.ssse3 = (CPUInfo[2] & 0x200) || false;
1044                 features.sse3 = (CPUInfo[2] & 0x1) || false;
1045                 features.ssse3 = (CPUInfo[2] & 0x200) || false;
1046                 features.stepping = CPUInfo[0] & 0xf;
1047                 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
1048                 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
1049                 if(features.sse) features.mmx2 = true; //MMXEXT is a subset of SSE!
1050         }
1051
1052         x264_cpu_cpuid(0x80000000, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1053         int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
1054
1055         if((_stricmp(CPUIdentificationString, "AuthenticAMD") == 0) && (nExIds >= 0x80000001U))
1056         {
1057                 x264_cpu_cpuid(0x80000001, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1058                 features.mmx2 = features.mmx2 || (CPUInfo[3] & 0x00400000U);
1059         }
1060
1061         for(int i = 0x80000002; i <= nExIds; ++i)
1062         {
1063                 x264_cpu_cpuid(i, &CPUInfo[0], &CPUInfo[1], &CPUInfo[2], &CPUInfo[3]);
1064                 switch(i)
1065                 {
1066                 case 0x80000002:
1067                         memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
1068                         break;
1069                 case 0x80000003:
1070                         memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
1071                         break;
1072                 case 0x80000004:
1073                         memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
1074                         break;
1075                 }
1076         }
1077
1078         strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
1079
1080         if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
1081         if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
1082
1083 #if (!(defined(_M_X64) || defined(_M_IA64)))
1084         QLibrary Kernel32Lib("kernel32.dll");
1085         if(IsWow64ProcessFun IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process"))
1086         {
1087                 BOOL x64flag = FALSE;
1088                 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64flag))
1089                 {
1090                         features.x64 = (x64flag == TRUE);
1091                 }
1092         }
1093 #else
1094         features.x64 = true;
1095 #endif
1096
1097         DWORD_PTR procAffinity, sysAffinity;
1098         if(GetProcessAffinityMask(GetCurrentProcess(), &procAffinity, &sysAffinity))
1099         {
1100                 for(DWORD_PTR mask = 1; mask; mask <<= 1)
1101                 {
1102                         features.count += ((sysAffinity & mask) ? (1) : (0));
1103                 }
1104         }
1105         if(features.count < 1)
1106         {
1107                 GetNativeSystemInfo(&systemInfo);
1108                 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
1109         }
1110
1111         if(argv.count() > 0)
1112         {
1113                 bool flag = false;
1114                 for(int i = 0; i < argv.count(); i++)
1115                 {
1116                         if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
1117                         if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
1118                         if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
1119                 }
1120                 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
1121         }
1122
1123         return features;
1124 }
1125
1126 /*
1127  * Verify a specific Windows version
1128  */
1129 static bool x264_verify_os_version(const DWORD major, const DWORD minor)
1130 {
1131         OSVERSIONINFOEXW osvi;
1132         DWORDLONG dwlConditionMask = 0;
1133
1134         //Initialize the OSVERSIONINFOEX structure
1135         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
1136         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
1137         osvi.dwMajorVersion = major;
1138         osvi.dwMinorVersion = minor;
1139         osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
1140
1141         //Initialize the condition mask
1142         VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
1143         VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
1144         VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
1145
1146         // Perform the test
1147         const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
1148
1149         //Error checking
1150         if(!ret)
1151         {
1152                 if(GetLastError() != ERROR_OLD_WIN_VERSION)
1153                 {
1154                         qWarning("VerifyVersionInfo() system call has failed!");
1155                 }
1156         }
1157
1158         return (ret != FALSE);
1159 }
1160
1161 /*
1162  * Determine the *real* Windows version
1163  */
1164 static bool x264_get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
1165 {
1166         *major = *minor = 0;
1167         *pbOverride = false;
1168         
1169         //Initialize local variables
1170         OSVERSIONINFOEXW osvi;
1171         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
1172         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
1173
1174         //Try GetVersionEx() first
1175         if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
1176         {
1177                 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
1178                 return false;
1179         }
1180
1181         //Make sure we are running on NT
1182         if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
1183         {
1184                 *major = osvi.dwMajorVersion;
1185                 *minor = osvi.dwMinorVersion;
1186         }
1187         else
1188         {
1189                 qWarning("Not running on Windows NT, unsupported operating system!");
1190                 return false;
1191         }
1192
1193         //Determine the real *major* version first
1194         forever
1195         {
1196                 const DWORD nextMajor = (*major) + 1;
1197                 if(x264_verify_os_version(nextMajor, 0))
1198                 {
1199                         *pbOverride = true;
1200                         *major = nextMajor;
1201                         *minor = 0;
1202                         continue;
1203                 }
1204                 break;
1205         }
1206
1207         //Now also determine the real *minor* version
1208         forever
1209         {
1210                 const DWORD nextMinor = (*minor) + 1;
1211                 if(x264_verify_os_version((*major), nextMinor))
1212                 {
1213                         *pbOverride = true;
1214                         *minor = nextMinor;
1215                         continue;
1216                 }
1217                 break;
1218         }
1219
1220         return true;
1221 }
1222
1223 /*
1224  * Get the native operating system version
1225  */
1226 const x264_os_version_t &x264_get_os_version(void)
1227 {
1228         QReadLocker readLock(&g_x264_os_version.lock);
1229
1230         //Already initialized?
1231         if(g_x264_os_version.bInitialized)
1232         {
1233                 return g_x264_os_version.version;
1234         }
1235         
1236         readLock.unlock();
1237         QWriteLocker writeLock(&g_x264_os_version.lock);
1238
1239         //Detect OS version
1240         if(!g_x264_os_version.bInitialized)
1241         {
1242                 unsigned int major, minor; bool oflag;
1243                 if(x264_get_real_os_version(&major, &minor, &oflag))
1244                 {
1245                         g_x264_os_version.version.versionMajor = major;
1246                         g_x264_os_version.version.versionMinor = minor;
1247                         g_x264_os_version.version.overrideFlag = oflag;
1248                         g_x264_os_version.bInitialized = true;
1249                 }
1250                 else
1251                 {
1252                         qWarning("Failed to determin the operating system version!");
1253                 }
1254         }
1255
1256         return g_x264_os_version.version;
1257 }
1258
1259 /*
1260  * Check for compatibility mode
1261  */
1262 static bool x264_check_compatibility_mode(const char *exportName, const char *executableName)
1263 {
1264         QLibrary kernel32("kernel32.dll");
1265
1266         if(exportName != NULL)
1267         {
1268                 if(kernel32.resolve(exportName) != NULL)
1269                 {
1270                         qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
1271                         qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
1272                         return false;
1273                 }
1274         }
1275
1276         return true;
1277 }
1278
1279 /*
1280  * Check if we are running under wine
1281  */
1282 bool x264_detect_wine(void)
1283 {
1284         QReadLocker readLock(&g_x264_wine.lock);
1285
1286         //Already initialized?
1287         if(g_x264_wine.bInitialized)
1288         {
1289                 return g_x264_wine.bIsWine;
1290         }
1291         
1292         readLock.unlock();
1293         QWriteLocker writeLock(&g_x264_wine.lock);
1294
1295         if(!g_x264_wine.bInitialized)
1296         {
1297                 g_x264_wine.bIsWine = false;
1298                 QLibrary ntdll("ntdll.dll");
1299                 if(ntdll.load())
1300                 {
1301                         if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) g_x264_wine.bIsWine = true;
1302                         if(ntdll.resolve("wine_get_version") != NULL) g_x264_wine.bIsWine = true;
1303                         ntdll.unload();
1304                 }
1305                 g_x264_wine.bInitialized = true;
1306         }
1307
1308         return g_x264_wine.bIsWine;
1309 }
1310
1311 /*
1312  * Qt event filter
1313  */
1314 static bool x264_event_filter(void *message, long *result)
1315
1316         if((!(X264_DEBUG)) && x264_check_for_debugger())
1317         {
1318                 x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1319         }
1320         
1321         //switch(reinterpret_cast<MSG*>(message)->message)
1322         //{
1323         //case WM_QUERYENDSESSION:
1324         //      qWarning("WM_QUERYENDSESSION message received!");
1325         //      *result = x264_broadcast(x264_event_queryendsession, false) ? TRUE : FALSE;
1326         //      return true;
1327         //case WM_ENDSESSION:
1328         //      qWarning("WM_ENDSESSION message received!");
1329         //      if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
1330         //      {
1331         //              x264_broadcast(x264_event_endsession, false);
1332         //              if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
1333         //              {
1334         //                      app->closeAllWindows();
1335         //                      app->quit();
1336         //              }
1337         //              x264_finalization();
1338         //              exit(1);
1339         //      }
1340         //      *result = 0;
1341         //      return true;
1342         //default:
1343         //      /*ignore this message and let Qt handle it*/
1344         //      return false;
1345         //}
1346
1347         return false;
1348 }
1349
1350 /*
1351  * Check for process elevation
1352  */
1353 static bool x264_process_is_elevated(bool *bIsUacEnabled = NULL)
1354 {
1355         bool bIsProcessElevated = false;
1356         if(bIsUacEnabled) *bIsUacEnabled = false;
1357         HANDLE hToken = NULL;
1358         
1359         if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1360         {
1361                 TOKEN_ELEVATION_TYPE tokenElevationType;
1362                 DWORD returnLength;
1363                 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
1364                 {
1365                         if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
1366                         {
1367                                 switch(tokenElevationType)
1368                                 {
1369                                 case TokenElevationTypeDefault:
1370                                         qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1371                                         break;
1372                                 case TokenElevationTypeFull:
1373                                         qWarning("Process token elevation type: Full -> potential security risk!\n");
1374                                         bIsProcessElevated = true;
1375                                         if(bIsUacEnabled) *bIsUacEnabled = true;
1376                                         break;
1377                                 case TokenElevationTypeLimited:
1378                                         qDebug("Process token elevation type: Limited -> not elevated.\n");
1379                                         if(bIsUacEnabled) *bIsUacEnabled = true;
1380                                         break;
1381                                 default:
1382                                         qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
1383                                         break;
1384                                 }
1385                         }
1386                         else
1387                         {
1388                                 qWarning("GetTokenInformation() return an unexpected size!");
1389                         }
1390                 }
1391                 CloseHandle(hToken);
1392         }
1393         else
1394         {
1395                 qWarning("Failed to open process token!");
1396         }
1397
1398         return bIsProcessElevated;
1399 }
1400
1401 /*
1402  * Check if the current user is an administartor (helper function)
1403  */
1404 static bool x264_user_is_admin_helper(void)
1405 {
1406         HANDLE hToken = NULL;
1407         if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1408         {
1409                 return false;
1410         }
1411
1412         DWORD dwSize = 0;
1413         if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
1414         {
1415                 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1416                 {
1417                         CloseHandle(hToken);
1418                         return false;
1419                 }
1420         }
1421
1422         PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
1423         if(!lpGroups)
1424         {
1425                 CloseHandle(hToken);
1426                 return false;
1427         }
1428
1429         if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
1430         {
1431                 free(lpGroups);
1432                 CloseHandle(hToken);
1433                 return false;
1434         }
1435
1436         PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
1437         if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
1438         {
1439                 free(lpGroups);
1440                 CloseHandle(hToken);
1441                 return false;
1442         }
1443
1444         bool bResult = false;
1445         for(DWORD i = 0; i < lpGroups->GroupCount; i++)
1446         {
1447                 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
1448                 {
1449                         bResult = true;
1450                         break;
1451                 }
1452         }
1453
1454         FreeSid(lpSid);
1455         free(lpGroups);
1456         CloseHandle(hToken);
1457         return bResult;
1458 }
1459
1460 /*
1461  * Check if the current user is an administartor
1462  */
1463 bool x264_user_is_admin(void)
1464 {
1465         bool isAdmin = false;
1466
1467         //Check for process elevation and UAC support first!
1468         if(x264_process_is_elevated(&isAdmin))
1469         {
1470                 qWarning("Process is elevated -> user is admin!");
1471                 return true;
1472         }
1473         
1474         //If not elevated and UAC is not available -> user must be in admin group!
1475         if(!isAdmin)
1476         {
1477                 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
1478                 isAdmin = x264_user_is_admin_helper();
1479         }
1480
1481         return isAdmin;
1482 }
1483
1484 /*
1485  * Initialize Qt framework
1486  */
1487 bool x264_init_qt(int argc, char* argv[])
1488 {
1489         static bool qt_initialized = false;
1490         typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1491         const QStringList &arguments = x264_arguments();
1492
1493         //Don't initialized again, if done already
1494         if(qt_initialized)
1495         {
1496                 return true;
1497         }
1498
1499         //Secure DLL loading
1500         QLibrary kernel32("kernel32.dll");
1501         if(kernel32.load())
1502         {
1503                 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1504                 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1505         }
1506
1507         //Extract executable name from argv[] array
1508         QString executableName = QLatin1String("x264_launcher.exe");
1509         if(arguments.count() > 0)
1510         {
1511                 static const char *delimiters = "\\/:?";
1512                 executableName = arguments[0].trimmed();
1513                 for(int i = 0; delimiters[i]; i++)
1514                 {
1515                         int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1516                         if(temp >= 0) executableName = executableName.mid(temp + 1);
1517                 }
1518                 executableName = executableName.trimmed();
1519                 if(executableName.isEmpty())
1520                 {
1521                         executableName = QLatin1String("x264_launcher.exe");
1522                 }
1523         }
1524
1525         //Check Qt version
1526 #ifdef QT_BUILD_KEY
1527         qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1528         qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1529         if(_stricmp(qVersion(), QT_VERSION_STR))
1530         {
1531                 qFatal("%s", QApplication::tr("Executable '%1' requires Qt v%2, but found Qt v%3.").arg(executableName, QString::fromLatin1(QT_VERSION_STR), QString::fromLatin1(qVersion())).toLatin1().constData());
1532                 return false;
1533         }
1534         if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1535         {
1536                 qFatal("%s", QApplication::tr("Executable '%1' was built for Qt '%2', but found Qt '%3'.").arg(executableName, QString::fromLatin1(QT_BUILD_KEY), QLibraryInfo::buildKey()).toLatin1().constData());
1537                 return false;
1538         }
1539 #else
1540         qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1541         qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1542 #endif
1543
1544         //Check the Windows version
1545         const x264_os_version_t &osVersionNo = x264_get_os_version();
1546         if(osVersionNo < x264_winver_winxp)
1547         {
1548                 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
1549         }
1550
1551         //Supported Windows version?
1552         if(osVersionNo == x264_winver_winxp)
1553         {
1554                 qDebug("Running on Windows XP or Windows XP Media Center Edition.\n");                                          //x264_check_compatibility_mode("GetLargePageMinimum", executableName);
1555         }
1556         else if(osVersionNo == x264_winver_xpx64)
1557         {
1558                 qDebug("Running on Windows Server 2003, Windows Server 2003 R2 or Windows XP x64.\n");          //x264_check_compatibility_mode("GetLocaleInfoEx", executableName);
1559         }
1560         else if(osVersionNo == x264_winver_vista)
1561         {
1562                 qDebug("Running on Windows Vista or Windows Server 2008.\n");                                                           //x264_check_compatibility_mode("CreateRemoteThreadEx", executableName*/);
1563         }
1564         else if(osVersionNo == x264_winver_win70)
1565         {
1566                 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");                                                            //x264_check_compatibility_mode("CreateFile2", executableName);
1567         }
1568         else if(osVersionNo == x264_winver_win80)
1569         {
1570                 qDebug("Running on Windows 8 or Windows Server 2012.\n");                                                                       //x264_check_compatibility_mode("FindPackagesByPackageFamily", executableName);
1571         }
1572         else if(osVersionNo == x264_winver_win81)
1573         {
1574                 qDebug("Running on Windows 8.1 or Windows Server 2012 R2.\n");                                                          //x264_check_compatibility_mode(NULL, executableName);
1575         }
1576         else
1577         {
1578                 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersionNo.versionMajor, osVersionNo.versionMinor);
1579                 qWarning("%s\n", QUTF8(message));
1580                 MessageBoxW(NULL, QWCHAR(message), L"Simple x264 Launcher", MB_OK | MB_TOPMOST | MB_ICONWARNING);
1581         }
1582
1583         //Check for compat mode
1584         if(osVersionNo.overrideFlag && (osVersionNo <= x264_winver_win81))
1585         {
1586                 qWarning("Windows compatibility mode detected!");
1587                 if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive))
1588                 {
1589                         qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
1590                         return false;
1591                 }
1592         }
1593
1594         //Check for Wine
1595         if(x264_detect_wine())
1596         {
1597                 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1598         }
1599
1600         //Set text Codec for locale
1601         QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1602
1603         //Create Qt application instance
1604         QApplication *application = new QApplication(argc, argv);
1605
1606         //Load plugins from application directory
1607         QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1608         qDebug("Library Path:\n%s\n", QUTF8(QApplication::libraryPaths().first()));
1609
1610         //Create Qt application instance and setup version info
1611         application->setApplicationName("Simple x264 Launcher");
1612         application->setApplicationVersion(QString().sprintf("%d.%02d", x264_version_major(), x264_version_minor())); 
1613         application->setOrganizationName("LoRd_MuldeR");
1614         application->setOrganizationDomain("mulder.at.gg");
1615         application->setWindowIcon(QIcon(":/icons/movie.ico"));
1616         application->setEventFilter(x264_event_filter);
1617
1618         //Check for supported image formats
1619         QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1620         for(int i = 0; g_x264_imageformats[i]; i++)
1621         {
1622                 if(!supportedFormats.contains(g_x264_imageformats[i]))
1623                 {
1624                         qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_x264_imageformats[i]);
1625                         return false;
1626                 }
1627         }
1628         
1629         //Add default translations
1630         /*
1631         QWriteLocker writeLockTranslations(&g_x264_translation.lock);
1632         if(!g_x264_translation.files) g_x264_translation.files = new QMap<QString, QString>();
1633         if(!g_x264_translation.names) g_x264_translation.names = new QMap<QString, QString>();
1634         g_x264_translation.files->insert(X264_DEFAULT_LANGID, "");
1635         g_x264_translation.names->insert(X264_DEFAULT_LANGID, "English");
1636         writeLockTranslations.unlock();
1637         */
1638
1639         //Check for process elevation
1640         if(x264_process_is_elevated() && (!x264_detect_wine()))
1641         {
1642                 QMessageBox messageBox(QMessageBox::Warning, "Simple x264 Launcher", "<nobr>Simple x264 Launcher was started with 'elevated' rights, altough it does not need these rights.<br>Running an applications with unnecessary rights is a potential security risk!</nobr>", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
1643                 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1644                 messageBox.addButton("Ignore", QMessageBox::NoRole);
1645                 if(messageBox.exec() == 0)
1646                 {
1647                         return false;
1648                 }
1649         }
1650
1651         //Update console icon, if a console is attached
1652 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1653         if(g_x264_console_attached && (!x264_detect_wine()))
1654         {
1655                 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1656                 QLibrary kernel32("kernel32.dll");
1657                 if(kernel32.load())
1658                 {
1659                         SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1660                         QPixmap pixmap = QIcon(":/icons/movie.ico").pixmap(16, 16);
1661                         if((SetConsoleIconPtr != NULL) && (!pixmap.isNull())) SetConsoleIconPtr(pixmap.toWinHICON());
1662                         kernel32.unload();
1663                 }
1664         }
1665 #endif
1666
1667         //Done
1668         qt_initialized = true;
1669         return true;
1670 }
1671
1672 /*
1673  * Suspend or resume process
1674  */
1675 bool x264_suspendProcess(const QProcess *proc, const bool suspend)
1676 {
1677         if(Q_PID pid = proc->pid())
1678         {
1679                 if(suspend)
1680                 {
1681                         return (SuspendThread(pid->hThread) != ((DWORD) -1));
1682                 }
1683                 else
1684                 {
1685                         return (ResumeThread(pid->hThread) != ((DWORD) -1));
1686                 }
1687         }
1688         else
1689         {
1690                 return false;
1691         }
1692 }
1693
1694 /*
1695  * Convert path to short/ANSI path
1696  */
1697 QString x264_path2ansi(const QString &longPath, bool makeLowercase)
1698 {
1699         QString shortPath = longPath;
1700         
1701         const QString longPathNative = QDir::toNativeSeparators(longPath);
1702         DWORD buffSize = GetShortPathNameW(QWCHAR(longPathNative), NULL, NULL);
1703         
1704         if(buffSize > 0)
1705         {
1706                 wchar_t *buffer = (wchar_t*) _malloca(sizeof(wchar_t) * buffSize);
1707                 DWORD result = GetShortPathNameW(QWCHAR(longPathNative), buffer, buffSize);
1708
1709                 if((result > 0) && (result < buffSize))
1710                 {
1711                         shortPath = QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer), result));
1712
1713                         if(makeLowercase)
1714                         {
1715                                 QFileInfo info(shortPath);
1716                                 shortPath = QString("%1/%2").arg(info.absolutePath(), info.fileName().toLower());
1717                         }
1718                 }
1719
1720                 _freea(buffer);
1721                 buffer = NULL;
1722         }
1723
1724         return shortPath;
1725 }
1726
1727 /*
1728  * Set the process priority class for current process
1729  */
1730 bool x264_change_process_priority(const int priority)
1731 {
1732         return x264_change_process_priority(GetCurrentProcess(), priority);
1733 }
1734
1735 /*
1736  * Set the process priority class for specified process
1737  */
1738 bool x264_change_process_priority(const QProcess *proc, const int priority)
1739 {
1740         if(Q_PID qPid = proc->pid())
1741         {
1742                 return x264_change_process_priority(qPid->hProcess, priority);
1743         }
1744         else
1745         {
1746                 return false;
1747         }
1748 }
1749
1750 /*
1751  * Set the process priority class for specified process
1752  */
1753 bool x264_change_process_priority(void *hProcess, const int priority)
1754 {
1755         bool ok = false;
1756
1757         switch(qBound(-2, priority, 2))
1758         {
1759         case 2:
1760                 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1761                 break;
1762         case 1:
1763                 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1764                 {
1765                         ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1766                 }
1767                 break;
1768         case 0:
1769                 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1770                 break;
1771         case -1:
1772                 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1773                 {
1774                         ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1775                 }
1776                 break;
1777         case -2:
1778                 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1779                 break;
1780         }
1781
1782         return ok;
1783 }
1784
1785 /*
1786  * Play a sound (from resources)
1787  */
1788 bool x264_play_sound(const unsigned short uiSoundIdx, const bool bAsync, const wchar_t *alias)
1789 {
1790         if(alias)
1791         {
1792                 return PlaySound(alias, GetModuleHandle(NULL), (SND_ALIAS | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE;
1793         }
1794         else
1795         {
1796                 return PlaySound(MAKEINTRESOURCE(uiSoundIdx), GetModuleHandle(NULL), (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE;
1797         }
1798 }
1799
1800 /*
1801  * Current process ID
1802  */
1803 unsigned int x264_process_id(void)
1804 {
1805         return GetCurrentProcessId();
1806 }
1807
1808 /*
1809  * Current process ID
1810  */
1811 unsigned int x264_process_id(QProcess &process)
1812 {
1813         if(Q_PID pid = process.pid())
1814         {
1815                 return pid->dwProcessId;
1816         }
1817         return NULL;
1818 }
1819
1820 /*
1821  * Make a window blink (to draw user's attention)
1822  */
1823 void x264_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
1824 {
1825         static QMutex blinkMutex;
1826
1827         const double maxOpac = 1.0;
1828         const double minOpac = 0.3;
1829         const double delOpac = 0.1;
1830
1831         if(!blinkMutex.tryLock())
1832         {
1833                 qWarning("Blinking is already in progress, skipping!");
1834                 return;
1835         }
1836         
1837         try
1838         {
1839                 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
1840                 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
1841                 const double opacity = poWindow->windowOpacity();
1842         
1843                 for(unsigned int i = 0; i < count; i++)
1844                 {
1845                         for(double x = maxOpac; x >= minOpac; x -= delOpac)
1846                         {
1847                                 poWindow->setWindowOpacity(x);
1848                                 QApplication::processEvents();
1849                                 Sleep(sleep);
1850                         }
1851
1852                         for(double x = minOpac; x <= maxOpac; x += delOpac)
1853                         {
1854                                 poWindow->setWindowOpacity(x);
1855                                 QApplication::processEvents();
1856                                 Sleep(sleep);
1857                         }
1858                 }
1859
1860                 poWindow->setWindowOpacity(opacity);
1861                 QApplication::processEvents();
1862                 blinkMutex.unlock();
1863         }
1864         catch(...)
1865         {
1866                 blinkMutex.unlock();
1867                 qWarning("Exception error while blinking!");
1868         }
1869 }
1870
1871 /*
1872  * Bring the specifed window to the front
1873  */
1874 static bool x264_bring_to_front(const HWND hWin)
1875 {
1876         if(hWin)
1877         {
1878                 const bool ret = (SetForegroundWindow(hWin) != FALSE);
1879                 SwitchToThisWindow(hWin, TRUE);
1880                 return ret;
1881         }
1882         return false;
1883 }
1884
1885 /*
1886  * Bring the specifed window to the front
1887  */
1888 bool x264_bring_to_front(const QWidget *win)
1889 {
1890         if(win)
1891         {
1892                 return x264_bring_to_front(win->winId());
1893         }
1894         return false;
1895 }
1896
1897 /*
1898  * Bring window of the specifed process to the front (callback)
1899  */
1900 static BOOL CALLBACK x264_bring_process_to_front_helper(HWND hwnd, LPARAM lParam)
1901 {
1902         DWORD processId = *reinterpret_cast<WORD*>(lParam);
1903         DWORD windowProcessId = NULL;
1904         GetWindowThreadProcessId(hwnd, &windowProcessId);
1905         if(windowProcessId == processId)
1906         {
1907                 x264_bring_to_front(hwnd);
1908                 return FALSE;
1909         }
1910         return TRUE;
1911 }
1912
1913 /*
1914  * Bring window of the specifed process to the front
1915  */
1916 bool x264_bring_process_to_front(const unsigned long pid)
1917 {
1918         return EnumWindows(x264_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE;
1919 }
1920
1921 /*
1922  * Check if file is a valid Win32/Win64 executable
1923  */
1924 bool x264_is_executable(const QString &path)
1925 {
1926         bool bIsExecutable = false;
1927         DWORD binaryType;
1928         if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(path)), &binaryType))
1929         {
1930                 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
1931         }
1932         return bIsExecutable;
1933 }
1934
1935 /*
1936  * Read value from registry
1937  */
1938 QString x264_query_reg_string(const bool bUser, const QString &path, const QString &name)
1939 {
1940         QString result; HKEY hKey = NULL;
1941         if(RegOpenKey((bUser ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE), QWCHAR(path), &hKey) == ERROR_SUCCESS)
1942         {
1943                 const size_t DATA_LEN = 2048; wchar_t data[DATA_LEN];
1944                 DWORD type = REG_NONE, size = sizeof(wchar_t) * DATA_LEN;
1945                 if(RegQueryValueEx(hKey, QWCHAR(name), NULL, &type, ((BYTE*)&data[0]), &size) == ERROR_SUCCESS)
1946                 {
1947                         if((type == REG_SZ) || (type == REG_EXPAND_SZ))
1948                         {
1949                                 result = WCHAR2QSTR(&data[0]);
1950                         }
1951                 }
1952                 RegCloseKey(hKey);
1953         }
1954         return result;
1955 }
1956
1957 /*
1958  * Locate known folder on local system
1959  */
1960 const QString &x264_known_folder(x264_known_folder_t folder_id)
1961 {
1962         static const int CSIDL_FLAG_CREATE = 0x8000;
1963         typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
1964         
1965         struct
1966         {
1967                 const int csidl;
1968                 const GUID guid;
1969         }
1970         static s_folders[] =
1971         {
1972                 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} },  //CSIDL_LOCAL_APPDATA
1973                 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} },  //CSIDL_PROGRAM_FILES
1974                 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} },  //CSIDL_WINDOWS_FOLDER
1975                 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} },  //CSIDL_SYSTEM_FOLDER
1976         };
1977
1978         size_t folderId = size_t(-1);
1979
1980         switch(folder_id)
1981         {
1982                 case x264_folder_localappdata: folderId = 0; break;
1983                 case x264_folder_programfiles: folderId = 1; break;
1984                 case x264_folder_systroot_dir: folderId = 2; break;
1985                 case x264_folder_systemfolder: folderId = 3; break;
1986         }
1987
1988         if(folderId == size_t(-1))
1989         {
1990                 qWarning("Invalid 'known' folder was requested!");
1991                 return *reinterpret_cast<QString*>(NULL);
1992         }
1993
1994         QReadLocker readLock(&g_x264_known_folder.lock);
1995
1996         //Already in cache?
1997         if(g_x264_known_folder.knownFolders)
1998         {
1999                 if(g_x264_known_folder.knownFolders->contains(folderId))
2000                 {
2001                         return (*g_x264_known_folder.knownFolders)[folderId];
2002                 }
2003         }
2004
2005         //Obtain write lock to initialize
2006         readLock.unlock();
2007         QWriteLocker writeLock(&g_x264_known_folder.lock);
2008
2009         //Still not in cache?
2010         if(g_x264_known_folder.knownFolders)
2011         {
2012                 if(g_x264_known_folder.knownFolders->contains(folderId))
2013                 {
2014                         return (*g_x264_known_folder.knownFolders)[folderId];
2015                 }
2016         }
2017
2018         //Initialize on first call
2019         if(!g_x264_known_folder.knownFolders)
2020         {
2021                 QLibrary shell32("shell32.dll");
2022                 if(shell32.load())
2023                 {
2024                         g_x264_known_folder.getFolderPath =      (SHGetFolderPath_t)      shell32.resolve("SHGetFolderPathW");
2025                         g_x264_known_folder.getKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
2026                 }
2027                 g_x264_known_folder.knownFolders = new QMap<size_t, QString>();
2028         }
2029
2030         QString folderPath;
2031
2032         //Now try to get the folder path!
2033         if(g_x264_known_folder.getKnownFolderPath)
2034         {
2035                 WCHAR *path = NULL;
2036                 if(g_x264_known_folder.getKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
2037                 {
2038                         //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
2039                         QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
2040                         if(folderTemp.exists())
2041                         {
2042                                 folderPath = folderTemp.canonicalPath();
2043                         }
2044                         CoTaskMemFree(path);
2045                 }
2046         }
2047         else if(g_x264_known_folder.getFolderPath)
2048         {
2049                 WCHAR *path = new WCHAR[4096];
2050                 if(g_x264_known_folder.getFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path) == S_OK)
2051                 {
2052                         //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
2053                         QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
2054                         if(folderTemp.exists())
2055                         {
2056                                 folderPath = folderTemp.canonicalPath();
2057                         }
2058                 }
2059                 X264_DELETE_ARRAY(path);
2060         }
2061
2062         //Update cache
2063         g_x264_known_folder.knownFolders->insert(folderId, folderPath);
2064         return (*g_x264_known_folder.knownFolders)[folderId];
2065 }
2066
2067 /*
2068  * Try to initialize the folder (with *write* access)
2069  */
2070 static QString x264_try_init_folder(const QString &folderPath)
2071 {
2072         static const char *DATA = "Lorem ipsum dolor sit amet, consectetur, adipisci velit!";
2073         
2074         bool success = false;
2075
2076         const QFileInfo folderInfo(folderPath);
2077         const QDir folderDir(folderInfo.absoluteFilePath());
2078
2079         //Create folder, if it does *not* exist yet
2080         for(int i = 0; i < 16; i++)
2081         {
2082                 if(folderDir.exists()) break;
2083                 folderDir.mkpath(".");
2084         }
2085
2086         //Make sure folder exists now *and* is writable
2087         if(folderDir.exists())
2088         {
2089                 const QByteArray testData = QByteArray(DATA);
2090                 for(int i = 0; i < 32; i++)
2091                 {
2092                         QFile testFile(folderDir.absoluteFilePath(QString("~%1.tmp").arg(x264_rand_str())));
2093                         if(testFile.open(QIODevice::ReadWrite | QIODevice::Truncate))
2094                         {
2095                                 if(testFile.write(testData) >= testData.size())
2096                                 {
2097                                         success = true;
2098                                 }
2099                                 testFile.remove();
2100                                 testFile.close();
2101                         }
2102                         if(success) break;
2103                 }
2104         }
2105
2106         return (success ? folderDir.canonicalPath() : QString());
2107 }
2108
2109 /*
2110  * Detect the TEMP directory
2111  */
2112 const QString &x264_temp_directory(void)
2113 {
2114         QReadLocker readLock(&g_x264_temp_folder.lock);
2115
2116         if(g_x264_temp_folder.path)
2117         {
2118                 return *g_x264_temp_folder.path;
2119         }
2120
2121         readLock.unlock();
2122         QWriteLocker writeLock(&g_x264_temp_folder.lock);
2123
2124         if(!g_x264_temp_folder.path)
2125         {
2126                 //Try %TEMP% first
2127                 g_x264_temp_folder.path = new QString(x264_try_init_folder(QDir::temp().absolutePath()));
2128
2129                 //Fall back to %LOCALAPPDATA%, if %TEMP% didn't work
2130                 if(g_x264_temp_folder.path->isEmpty())
2131                 {
2132                         qWarning("%%TEMP%% directory not found -> falling back to %%LOCALAPPDATA%%");
2133                         static const x264_known_folder_t folderId[2] = { x264_folder_localappdata, x264_folder_systroot_dir };
2134                         for(size_t id = 0; (g_x264_temp_folder.path->isEmpty() && (id < 2)); id++)
2135                         {
2136                                 const QString &localAppData = x264_known_folder(x264_folder_localappdata);
2137                                 if(!localAppData.isEmpty())
2138                                 {
2139                                         *g_x264_temp_folder.path = x264_try_init_folder(QString("%1/Temp").arg(localAppData));
2140                                 }
2141                                 else
2142                                 {
2143                                         qWarning("%%LOCALAPPDATA%% directory could not be found!");
2144                                 }
2145                         }
2146                 }
2147
2148                 //Failed to init TEMP folder?
2149                 if(g_x264_temp_folder.path->isEmpty())
2150                 {
2151                         qWarning("Temporary directory could not be initialized !!!");
2152                 }
2153         }
2154
2155         return *g_x264_temp_folder.path;
2156 }
2157
2158 /*
2159  * Display the window's close button
2160  */
2161 bool x264_enable_close_button(const QWidget *win, const bool bEnable)
2162 {
2163         bool ok = false;
2164
2165         if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
2166         {
2167                 ok = (EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (bEnable ? MF_ENABLED : MF_GRAYED)) == TRUE);
2168         }
2169
2170         return ok;
2171 }
2172
2173 /*
2174  * Play beep sound
2175  */
2176 bool x264_beep(int beepType)
2177 {
2178         switch(beepType)
2179         {
2180                 case x264_beep_info:    return MessageBeep(MB_ICONASTERISK) == TRUE;    break;
2181                 case x264_beep_warning: return MessageBeep(MB_ICONEXCLAMATION) == TRUE; break;
2182                 case x264_beep_error:   return MessageBeep(MB_ICONHAND) == TRUE;        break;
2183                 default: return false;
2184         }
2185 }
2186
2187 /*
2188  * Shutdown the computer
2189  */
2190 bool x264_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
2191 {
2192         HANDLE hToken = NULL;
2193
2194         if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2195         {
2196                 TOKEN_PRIVILEGES privileges;
2197                 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2198                 privileges.PrivilegeCount = 1;
2199                 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2200                 
2201                 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2202                 {
2203                         if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2204                         {
2205                                 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2206                                 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2207                         }
2208                 }
2209         }
2210         
2211         return false;
2212 }
2213
2214 /*
2215  * Check the network connection status
2216  */
2217 int x264_network_status(void)
2218 {
2219         DWORD dwFlags;
2220         const BOOL ret = IsNetworkAlive(&dwFlags);
2221         if(GetLastError() == 0)
2222         {
2223                 return (ret != FALSE) ? x264_network_yes : x264_network_non;
2224         }
2225         return x264_network_err;
2226 }
2227
2228 /*
2229  * Setup QPorcess object
2230  */
2231 void x264_init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
2232 {
2233         //Environment variable names
2234         static const char *const s_envvar_names_temp[] =
2235         {
2236                 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
2237         };
2238         static const char *const s_envvar_names_remove[] =
2239         {
2240                 "WGETRC", "SYSTEM_WGETRC", "HTTP_PROXY", "FTP_PROXY", "NO_PROXY", "GNUPGHOME", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LANG", NULL
2241         };
2242
2243         //Initialize environment
2244         QProcessEnvironment env = process.processEnvironment();
2245         if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
2246
2247         //Clean a number of enviroment variables that might affect our tools
2248         for(size_t i = 0; s_envvar_names_remove[i]; i++)
2249         {
2250                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
2251                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
2252         }
2253
2254         const QString tempDir = QDir::toNativeSeparators(x264_temp_directory());
2255
2256         //Replace TEMP directory in environment
2257         if(bReplaceTempDir)
2258         {
2259                 for(size_t i = 0; s_envvar_names_temp[i]; i++)
2260                 {
2261                         env.insert(s_envvar_names_temp[i], tempDir);
2262                 }
2263         }
2264
2265         //Setup PATH variable
2266         const QString path = env.value("PATH", QString()).trimmed();
2267         env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
2268         
2269         //Setup QPorcess object
2270         process.setWorkingDirectory(wokringDir);
2271         process.setProcessChannelMode(QProcess::MergedChannels);
2272         process.setReadChannel(QProcess::StandardOutput);
2273         process.setProcessEnvironment(env);
2274 }
2275
2276 /*
2277  * Inform the system that it is in use, thereby preventing the system from entering sleep
2278  */
2279 bool x264_set_thread_execution_state(const bool systemRequired)
2280 {
2281         EXECUTION_STATE state = NULL;
2282         if(systemRequired)
2283         {
2284                 state = SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED);
2285         }
2286         else
2287         {
2288                 state = SetThreadExecutionState(ES_CONTINUOUS);
2289         }
2290         return (state != NULL);
2291 }
2292
2293 /*
2294  * Check for debugger (detect routine)
2295  */
2296 static __forceinline bool x264_check_for_debugger(void)
2297 {
2298         __try
2299         {
2300                 CloseHandle((HANDLE)((DWORD_PTR)-3));
2301         }
2302         __except(1)
2303         {
2304                 return true;
2305         }
2306         __try 
2307         {
2308                 __debugbreak();
2309         }
2310         __except(1) 
2311         {
2312                 return IsDebuggerPresent();
2313         }
2314         return true;
2315 }
2316
2317 /*
2318  * Check for debugger (thread proc)
2319  */
2320 static unsigned int __stdcall x264_debug_thread_proc(LPVOID lpParameter)
2321 {
2322         SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
2323         forever
2324         {
2325                 if(x264_check_for_debugger())
2326                 {
2327                         x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2328                         return 666;
2329                 }
2330                 x264_sleep(100);
2331         }
2332 }
2333
2334 /*
2335  * Check for debugger (startup routine)
2336  */
2337 static HANDLE x264_debug_thread_init()
2338 {
2339         if(x264_check_for_debugger())
2340         {
2341                 x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2342         }
2343         const uintptr_t h = _beginthreadex(NULL, 0, x264_debug_thread_proc, NULL, 0, NULL);
2344         return (HANDLE)(h^0xdeadbeef);
2345 }
2346
2347 /*
2348  * Fatal application exit
2349  */
2350 #pragma intrinsic(_InterlockedExchange)
2351 void x264_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2352 {
2353         static volatile long bFatalFlag = 0L;
2354
2355         if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2356         {
2357                 if(GetCurrentThreadId() != g_main_thread_id)
2358                 {
2359                         HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2360                         if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2361                 }
2362         
2363                 if(errorBoxMessage)
2364                 {
2365                         MessageBoxW(NULL, errorBoxMessage, L"Simple x264 Launcher - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2366                 }
2367
2368                 FatalAppExit(0, exitMessage);
2369
2370                 for(;;)
2371                 {
2372                         TerminateProcess(GetCurrentProcess(), -1);
2373                 }
2374         }
2375 }
2376
2377 /*
2378  * Entry point checks
2379  */
2380 static DWORD x264_entry_check(void);
2381 static DWORD g_x264_entry_check_result = x264_entry_check();
2382 static DWORD g_x264_entry_check_flag = 0x789E09B2;
2383 static DWORD x264_entry_check(void)
2384 {
2385         volatile DWORD retVal = 0xA199B5AF;
2386         if(g_x264_entry_check_flag != 0x8761F64D)
2387         {
2388                 x264_fatal_exit(L"Application initialization has failed, take care!");
2389         }
2390         return retVal;
2391 }
2392
2393 /*
2394  * Application entry point (runs before static initializers)
2395  */
2396 extern "C"
2397 {
2398         int WinMainCRTStartup(void);
2399         
2400         int x264_entry_point(void)
2401         {
2402                 if((!X264_DEBUG) && x264_check_for_debugger())
2403                 {
2404                         x264_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2405                 }
2406                 if(g_x264_entry_check_flag != 0x789E09B2)
2407                 {
2408                         x264_fatal_exit(L"Application initialization has failed, take care!");
2409                 }
2410
2411                 //Zero *before* constructors are called
2412                 X264_ZERO_MEMORY(g_x264_argv);
2413                 X264_ZERO_MEMORY(g_x264_os_version);
2414                 X264_ZERO_MEMORY(g_x264_portable);
2415                 X264_ZERO_MEMORY(g_x264_known_folder);
2416                 X264_ZERO_MEMORY(g_x264_temp_folder);
2417
2418                 //Make sure we will pass the check
2419                 g_x264_entry_check_flag = ~g_x264_entry_check_flag;
2420
2421                 //Now initialize the C Runtime library!
2422                 return WinMainCRTStartup();
2423         }
2424 }
2425
2426 /*
2427  * Initialize debug thread
2428  */
2429 static const HANDLE g_debug_thread = X264_DEBUG ? NULL : x264_debug_thread_init();
2430
2431 /*
2432  * Get number private bytes [debug only]
2433  */
2434 size_t x264_dbg_private_bytes(void)
2435 {
2436 #if X264_DEBUG
2437         PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2438         memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2439         GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2440         return memoryCounters.PrivateUsage;
2441 #else
2442         throw "Cannot call this function in a non-debug build!";
2443 #endif //X264_DEBUG
2444 }
2445
2446 /*
2447  * Finalization function
2448  */
2449 void x264_finalization(void)
2450 {
2451         //Destroy Qt application object
2452         QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2453         X264_DELETE(application);
2454
2455         //Free STDOUT and STDERR buffers
2456         if(g_x264_console_attached)
2457         {
2458                 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2459                 {
2460                         std::cout.rdbuf(NULL);
2461                         X264_DELETE(tmp);
2462                 }
2463                 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2464                 {
2465                         std::cerr.rdbuf(NULL);
2466                         X264_DELETE(tmp);
2467                 }
2468         }
2469         
2470         //Clear CLI args
2471         X264_DELETE(g_x264_argv.list);
2472
2473         //Clear folders cache
2474         X264_DELETE(g_x264_known_folder.knownFolders);
2475         X264_DELETE(g_x264_temp_folder.path);
2476 }