Rename TYPE_DEBUG_PLAYER to TYPE_DEBUG_VIDEO_VIEW.
[dcpomatic.git] / src / lib / cross_windows.cc
1 /*
2     Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "cross.h"
22 #include "compose.hpp"
23 #include "log.h"
24 #include "dcpomatic_log.h"
25 #include "config.h"
26 #include "exceptions.h"
27 #include "dcpomatic_assert.h"
28 #include <dcp/raw_convert.h>
29 #include <glib.h>
30 extern "C" {
31 #include <libavformat/avio.h>
32 }
33 #include <boost/algorithm/string.hpp>
34 #include <boost/foreach.hpp>
35 #include <boost/dll/runtime_symbol_info.hpp>
36 #include <windows.h>
37 #include <winternl.h>
38 #include <winioctl.h>
39 #include <ntdddisk.h>
40 #include <setupapi.h>
41 #include <fileapi.h>
42 #undef DATADIR
43 #include <shlwapi.h>
44 #include <shellapi.h>
45 #include <fcntl.h>
46 #include <fstream>
47 #include <map>
48
49 #include "i18n.h"
50
51 using std::pair;
52 using std::list;
53 using std::ifstream;
54 using std::string;
55 using std::wstring;
56 using std::make_pair;
57 using std::vector;
58 using std::cerr;
59 using std::cout;
60 using std::runtime_error;
61 using std::map;
62 using boost::shared_ptr;
63 using boost::optional;
64
65 static std::vector<pair<HANDLE, string> > locked_volumes;
66
67 /** @param s Number of seconds to sleep for */
68 void
69 dcpomatic_sleep_seconds (int s)
70 {
71         Sleep (s * 1000);
72 }
73
74 void
75 dcpomatic_sleep_milliseconds (int ms)
76 {
77         Sleep (ms);
78 }
79
80 /** @return A string of CPU information (model name etc.) */
81 string
82 cpu_info ()
83 {
84         string info;
85
86         HKEY key;
87         if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) {
88                 return info;
89         }
90
91         DWORD type;
92         DWORD data;
93         if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) {
94                 return info;
95         }
96
97         if (type != REG_SZ) {
98                 return info;
99         }
100
101         wstring value (data / sizeof (wchar_t), L'\0');
102         if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) {
103                 RegCloseKey (key);
104                 return info;
105         }
106
107         info = string (value.begin(), value.end());
108
109         RegCloseKey (key);
110
111         return info;
112 }
113
114 void
115 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
116 {
117         SECURITY_ATTRIBUTES security;
118         security.nLength = sizeof (security);
119         security.bInheritHandle = TRUE;
120         security.lpSecurityDescriptor = 0;
121
122         HANDLE child_stderr_read;
123         HANDLE child_stderr_write;
124         if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) {
125                 LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)");
126                 return;
127         }
128
129         wchar_t dir[512];
130         GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir));
131         PathRemoveFileSpec (dir);
132         SetCurrentDirectory (dir);
133
134         STARTUPINFO startup_info;
135         ZeroMemory (&startup_info, sizeof (startup_info));
136         startup_info.cb = sizeof (startup_info);
137         startup_info.hStdError = child_stderr_write;
138         startup_info.dwFlags |= STARTF_USESTDHANDLES;
139
140         wchar_t command[512];
141         wcscpy (command, L"ffprobe.exe \"");
142
143         wchar_t file[512];
144         MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file));
145         wcscat (command, file);
146
147         wcscat (command, L"\"");
148
149         PROCESS_INFORMATION process_info;
150         ZeroMemory (&process_info, sizeof (process_info));
151         if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
152                 LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)"));
153                 return;
154         }
155
156         FILE* o = fopen_boost (out, "w");
157         if (!o) {
158                 LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)"));
159                 return;
160         }
161
162         CloseHandle (child_stderr_write);
163
164         while (true) {
165                 char buffer[512];
166                 DWORD read;
167                 if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) {
168                         break;
169                 }
170                 fwrite (buffer, read, 1, o);
171         }
172
173         fclose (o);
174
175         WaitForSingleObject (process_info.hProcess, INFINITE);
176         CloseHandle (process_info.hProcess);
177         CloseHandle (process_info.hThread);
178         CloseHandle (child_stderr_read);
179 }
180
181 list<pair<string, string> >
182 mount_info ()
183 {
184         list<pair<string, string> > m;
185         return m;
186 }
187
188 static boost::filesystem::path
189 executable_path ()
190 {
191         return boost::dll::program_location().parent_path();
192 }
193
194 boost::filesystem::path
195 shared_path ()
196 {
197         return executable_path().parent_path();
198 }
199
200 boost::filesystem::path
201 openssl_path ()
202 {
203         return executable_path() / "openssl.exe";
204 }
205
206 #ifdef DCPOMATIC_DISK
207 boost::filesystem::path
208 disk_writer_path ()
209 {
210         return executable_path() / "dcpomatic2_disk_writer.exe";
211 }
212 #endif
213
214 /* Apparently there is no way to create an ofstream using a UTF-8
215    filename under Windows.  We are hence reduced to using fopen
216    with this wrapper.
217 */
218 FILE *
219 fopen_boost (boost::filesystem::path p, string t)
220 {
221         wstring w (t.begin(), t.end());
222         /* c_str() here should give a UTF-16 string */
223         return _wfopen (p.c_str(), w.c_str ());
224 }
225
226 int
227 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
228 {
229         return _fseeki64 (stream, offset, whence);
230 }
231
232 void
233 Waker::nudge ()
234 {
235         boost::mutex::scoped_lock lm (_mutex);
236         SetThreadExecutionState (ES_SYSTEM_REQUIRED);
237 }
238
239 Waker::Waker ()
240 {
241
242 }
243
244 Waker::~Waker ()
245 {
246
247 }
248
249 void
250 start_tool (boost::filesystem::path dcpomatic, string executable, string)
251 {
252         boost::filesystem::path batch = dcpomatic.parent_path() / executable;
253
254         STARTUPINFO startup_info;
255         ZeroMemory (&startup_info, sizeof (startup_info));
256         startup_info.cb = sizeof (startup_info);
257
258         PROCESS_INFORMATION process_info;
259         ZeroMemory (&process_info, sizeof (process_info));
260
261         wchar_t cmd[512];
262         MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
263         CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
264 }
265
266 void
267 start_batch_converter (boost::filesystem::path dcpomatic)
268 {
269         start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
270 }
271
272 void
273 start_player (boost::filesystem::path dcpomatic)
274 {
275         start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
276 }
277
278 uint64_t
279 thread_id ()
280 {
281         return (uint64_t) GetCurrentThreadId ();
282 }
283
284 static string
285 wchar_to_utf8 (wchar_t const * s)
286 {
287         int const length = (wcslen(s) + 1) * 2;
288         char* utf8 = new char[length];
289         WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8, length, 0, 0);
290         string u (utf8);
291         delete[] utf8;
292         return u;
293 }
294
295 int
296 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
297 {
298         return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags);
299 }
300
301 void
302 maybe_open_console ()
303 {
304         if (Config::instance()->win32_console ()) {
305                 AllocConsole();
306
307                 HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
308                 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
309                 FILE* hf_out = _fdopen(hCrt, "w");
310                 setvbuf(hf_out, NULL, _IONBF, 1);
311                 *stdout = *hf_out;
312
313                 HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
314                 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
315                 FILE* hf_in = _fdopen(hCrt, "r");
316                 setvbuf(hf_in, NULL, _IONBF, 128);
317                 *stdin = *hf_in;
318         }
319 }
320
321 boost::filesystem::path
322 home_directory ()
323 {
324         return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH"));
325 }
326
327 string
328 command_and_read (string)
329 {
330         return "";
331 }
332
333 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
334 bool
335 running_32_on_64 ()
336 {
337         BOOL p;
338         IsWow64Process (GetCurrentProcess(), &p);
339         return p;
340 }
341
342 static optional<string>
343 get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
344 {
345         wchar_t buffer[MAX_PATH];
346         ZeroMemory (&buffer, sizeof(buffer));
347         bool r = SetupDiGetDeviceRegistryPropertyW (
348                         device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0
349                         );
350         if (!r) {
351                 return optional<string>();
352         }
353         return wchar_to_utf8 (buffer);
354 }
355
356 static const GUID GUID_DEVICE_INTERFACE_DISK = {
357         0x53F56307L, 0xB6BF, 0x11D0, { 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B }
358 };
359
360 static optional<int>
361 get_device_number (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
362 {
363         /* Find the Windows path to the device */
364
365         SP_DEVICE_INTERFACE_DATA device_interface_data;
366         device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
367
368         BOOL r = SetupDiEnumDeviceInterfaces (device_info, device_info_data, &GUID_DEVICE_INTERFACE_DISK, 0, &device_interface_data);
369         if (!r) {
370                 LOG_DISK("SetupDiEnumDeviceInterfaces failed (%1)", GetLastError());
371                 return optional<int>();
372         }
373
374         /* Find out how much space we need for our SP_DEVICE_INTERFACE_DETAIL_DATA_W */
375         DWORD size;
376         r = SetupDiGetDeviceInterfaceDetailW(device_info, &device_interface_data, 0, 0, &size, 0);
377         PSP_DEVICE_INTERFACE_DETAIL_DATA_W device_detail_data = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W> (malloc(size));
378         if (!device_detail_data) {
379                 LOG_DISK_NC("malloc failed");
380                 return optional<int>();
381         }
382
383         device_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
384
385         /* And get the path */
386         r = SetupDiGetDeviceInterfaceDetailW (device_info, &device_interface_data, device_detail_data, size, &size, 0);
387         if (!r) {
388                 LOG_DISK_NC("SetupDiGetDeviceInterfaceDetailW failed");
389                 free (device_detail_data);
390                 return optional<int>();
391         }
392
393         /* Open it.  We would not be allowed GENERIC_READ access here but specifying 0 for
394            dwDesiredAccess allows us to query some metadata.
395         */
396         HANDLE device = CreateFileW (
397                         device_detail_data->DevicePath, 0,
398                         FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
399                         OPEN_EXISTING, 0, 0
400                         );
401
402         free (device_detail_data);
403
404         if (device == INVALID_HANDLE_VALUE) {
405                 LOG_DISK("CreateFileW failed with %1", GetLastError());
406                 return optional<int>();
407         }
408
409         /* Get the device number */
410         STORAGE_DEVICE_NUMBER device_number;
411         r = DeviceIoControl (
412                         device, IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0,
413                         &device_number, sizeof(device_number), &size, 0
414                         );
415
416         CloseHandle (device);
417
418         if (!r) {
419                 return optional<int>();
420         }
421
422         return device_number.DeviceNumber;
423 }
424
425 typedef map<int, vector<boost::filesystem::path> > MountPoints;
426
427 /** Take a volume path (with a trailing \) and add any disk numbers related to that volume
428  *  to @ref disks.
429  */
430 static void
431 add_volume_mount_points (wchar_t* volume, MountPoints& mount_points)
432 {
433         LOG_DISK("Looking at %1", wchar_to_utf8(volume));
434
435         wchar_t volume_path_names[512];
436         vector<boost::filesystem::path> mp;
437         DWORD returned;
438         if (GetVolumePathNamesForVolumeNameW(volume, volume_path_names, sizeof(volume_path_names) / sizeof(wchar_t), &returned)) {
439                 wchar_t* p = volume_path_names;
440                 while (*p != L'\0') {
441                         mp.push_back (wchar_to_utf8(p));
442                         LOG_DISK ("Found mount point %1", wchar_to_utf8(p));
443                         p += wcslen(p) + 1;
444                 }
445         }
446
447         /* Strip trailing \ */
448         size_t const len = wcslen (volume);
449         DCPOMATIC_ASSERT (len > 0);
450         volume[len - 1] = L'\0';
451
452         HANDLE handle = CreateFileW (
453                         volume, 0,
454                         FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
455                         OPEN_EXISTING, 0, 0
456                         );
457
458         DCPOMATIC_ASSERT (handle != INVALID_HANDLE_VALUE);
459
460         VOLUME_DISK_EXTENTS extents;
461         DWORD size;
462         BOOL r = DeviceIoControl (handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &extents, sizeof(extents), &size, 0);
463         CloseHandle (handle);
464         if (!r) {
465                 return;
466         }
467         DCPOMATIC_ASSERT (extents.NumberOfDiskExtents == 1);
468
469         mount_points[extents.Extents[0].DiskNumber] = mp;
470 }
471
472 MountPoints
473 find_mount_points ()
474 {
475         MountPoints mount_points;
476
477         wchar_t volume_name[512];
478         HANDLE volume = FindFirstVolumeW (volume_name, sizeof(volume_name) / sizeof(wchar_t));
479         if (volume == INVALID_HANDLE_VALUE) {
480                 return MountPoints();
481         }
482
483         add_volume_mount_points (volume_name, mount_points);
484         while (true) {
485                 if (!FindNextVolumeW(volume, volume_name, sizeof(volume_name) / sizeof(wchar_t))) {
486                         break;
487                 }
488                 add_volume_mount_points (volume_name, mount_points);
489         }
490         FindVolumeClose (volume);
491
492         return mount_points;
493 }
494
495 vector<Drive>
496 Drive::get ()
497 {
498         vector<Drive> drives;
499
500         MountPoints mount_points = find_mount_points ();
501
502         /* Get a `device information set' containing information about all disks */
503         HDEVINFO device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
504         if (device_info == INVALID_HANDLE_VALUE) {
505                 LOG_DISK_NC ("SetupDiClassDevsA failed");
506                 return drives;
507         }
508
509         int i = 0;
510         while (true) {
511                 /* Find out about the next disk */
512                 SP_DEVINFO_DATA device_info_data;
513                 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
514                 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) {
515                         DWORD e = GetLastError();
516                         if (e != ERROR_NO_MORE_ITEMS) {
517                                 LOG_DISK ("SetupDiEnumDeviceInfo failed (%1)", GetLastError());
518                         }
519                         break;
520                 }
521                 ++i;
522
523                 optional<string> const friendly_name = get_friendly_name (device_info, &device_info_data);
524                 optional<int> device_number = get_device_number (device_info, &device_info_data);
525                 if (!device_number) {
526                         continue;
527                 }
528
529                 string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number);
530
531                 HANDLE device = CreateFileA (
532                                 physical_drive.c_str(), 0,
533                                 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
534                                 OPEN_EXISTING, 0, 0
535                                 );
536
537                 if (device == INVALID_HANDLE_VALUE) {
538                         LOG_DISK_NC("Could not open PHYSICALDRIVE");
539                         continue;
540                 }
541
542                 DISK_GEOMETRY geom;
543                 DWORD returned;
544                 BOOL r = DeviceIoControl (
545                                 device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0,
546                                 &geom, sizeof(geom), &returned, 0
547                                 );
548
549                 LOG_DISK("Having a looky through %1 locked volumes", locked_volumes.size());
550                 bool locked = false;
551                 for (vector<pair<HANDLE, string> >::const_iterator i = locked_volumes.begin(); i != locked_volumes.end(); ++i) {
552                         if (i->second == physical_drive) {
553                                 locked = true;
554                         }
555                 }
556
557                 if (r) {
558                         uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
559                         drives.push_back (Drive(physical_drive, locked ? vector<boost::filesystem::path>() : mount_points[*device_number], disk_size, friendly_name, optional<string>()));
560                         LOG_DISK("Added drive %1%2", drives.back().log_summary(), locked ? "(locked by us)" : "");
561                 }
562
563                 CloseHandle (device);
564         }
565
566         return drives;
567 }
568
569
570 bool
571 Drive::unmount ()
572 {
573         LOG_DISK("Unmounting %1 with %2 mount points XXX! MMMYEAH!", _device, _mount_points.size());
574         DCPOMATIC_ASSERT (_mount_points.size() == 1);
575         string const device_name = String::compose ("\\\\.\\%1", _mount_points.front());
576         string const truncated = device_name.substr (0, device_name.length() - 1);
577         //LOG_DISK("Actually opening %1", _device);
578         //HANDLE device = CreateFileA (_device.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
579         LOG_DISK("Actually opening %1", truncated);
580         HANDLE device = CreateFileA (truncated.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
581         if (device == INVALID_HANDLE_VALUE) {
582                 LOG_DISK("Could not open %1 for unmount (%2)", truncated, GetLastError());
583                 return false;
584         }
585         DWORD returned;
586         BOOL r = DeviceIoControl (device, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &returned, 0);
587         if (!r) {
588                 LOG_DISK("Unmount of %1 failed (%2)", truncated, GetLastError());
589                 return false;
590         }
591
592         LOG_DISK("Unmount of %1 succeeded", _device);
593         locked_volumes.push_back (make_pair(device, _device));
594
595         return true;
596 }
597
598
599 boost::filesystem::path
600 config_path ()
601 {
602         boost::filesystem::path p;
603         p /= g_get_user_config_dir ();
604         p /= "dcpomatic2";
605         return p;
606 }
607
608 void
609 disk_write_finished ()
610 {
611         for (vector<pair<HANDLE, string> >::const_iterator i = locked_volumes.begin(); i != locked_volumes.end(); ++i) {
612                 CloseHandle (i->first);
613         }
614 }
615
616