2 Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
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.
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.
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/>.
22 #include "compose.hpp"
24 #include "dcpomatic_log.h"
26 #include "exceptions.h"
27 #include "dcpomatic_assert.h"
28 #include <dcp/raw_convert.h>
31 #include <libavformat/avio.h>
33 #include <boost/algorithm/string.hpp>
34 #include <boost/foreach.hpp>
35 #include <boost/dll/runtime_symbol_info.hpp>
60 using std::runtime_error;
62 using boost::shared_ptr;
63 using boost::optional;
65 static std::vector<pair<HANDLE, string> > locked_volumes;
67 /** @param s Number of seconds to sleep for */
69 dcpomatic_sleep_seconds (int s)
75 dcpomatic_sleep_milliseconds (int ms)
80 /** @return A string of CPU information (model name etc.) */
87 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) {
93 if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) {
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) {
107 info = string (value.begin(), value.end());
115 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
117 SECURITY_ATTRIBUTES security;
118 security.nLength = sizeof (security);
119 security.bInheritHandle = TRUE;
120 security.lpSecurityDescriptor = 0;
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)");
130 MultiByteToWideChar (CP_UTF8, 0, directory_containing_executable().string().c_str(), -1, dir, sizeof(dir));
131 SetCurrentDirectory (dir);
133 STARTUPINFO startup_info;
134 ZeroMemory (&startup_info, sizeof (startup_info));
135 startup_info.cb = sizeof (startup_info);
136 startup_info.hStdError = child_stderr_write;
137 startup_info.dwFlags |= STARTF_USESTDHANDLES;
139 wchar_t command[512];
140 wcscpy (command, L"ffprobe.exe \"");
143 MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file));
144 wcscat (command, file);
146 wcscat (command, L"\"");
148 PROCESS_INFORMATION process_info;
149 ZeroMemory (&process_info, sizeof (process_info));
150 if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
151 LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)"));
155 FILE* o = fopen_boost (out, "w");
157 LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)"));
161 CloseHandle (child_stderr_write);
166 if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) {
169 fwrite (buffer, read, 1, o);
174 WaitForSingleObject (process_info.hProcess, INFINITE);
175 CloseHandle (process_info.hProcess);
176 CloseHandle (process_info.hThread);
177 CloseHandle (child_stderr_read);
180 list<pair<string, string> >
183 list<pair<string, string> > m;
188 boost::filesystem::path
189 directory_containing_executable ()
191 return boost::dll::program_location().parent_path();
195 boost::filesystem::path
198 return directory_containing_executable().parent_path();
202 boost::filesystem::path
205 return directory_containing_executable().parent_path() / "xsd";
209 boost::filesystem::path
212 return directory_containing_executable().parent_path() / "tags";
216 boost::filesystem::path
219 return directory_containing_executable() / "openssl.exe";
223 #ifdef DCPOMATIC_DISK
224 boost::filesystem::path
227 return directory_containing_executable() / "dcpomatic2_disk_writer.exe";
232 /* Apparently there is no way to create an ofstream using a UTF-8
233 filename under Windows. We are hence reduced to using fopen
237 fopen_boost (boost::filesystem::path p, string t)
239 wstring w (t.begin(), t.end());
240 /* c_str() here should give a UTF-16 string */
241 return _wfopen (p.c_str(), w.c_str ());
245 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
247 return _fseeki64 (stream, offset, whence);
253 boost::mutex::scoped_lock lm (_mutex);
254 SetThreadExecutionState (ES_SYSTEM_REQUIRED);
269 start_tool (string executable)
271 boost::filesystem::path batch = directory_containing_executable() / executable;
273 STARTUPINFO startup_info;
274 ZeroMemory (&startup_info, sizeof (startup_info));
275 startup_info.cb = sizeof (startup_info);
277 PROCESS_INFORMATION process_info;
278 ZeroMemory (&process_info, sizeof (process_info));
281 MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
282 CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
287 start_batch_converter ()
289 start_tool ("dcpomatic2_batch");
296 start_tool ("dcpomatic2_player");
303 return (uint64_t) GetCurrentThreadId ();
307 wchar_to_utf8 (wchar_t const * s)
309 int const length = (wcslen(s) + 1) * 2;
310 char* utf8 = new char[length];
311 WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8, length, 0, 0);
318 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
320 return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags);
324 maybe_open_console ()
326 if (Config::instance()->win32_console ()) {
329 HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
330 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
331 FILE* hf_out = _fdopen(hCrt, "w");
332 setvbuf(hf_out, NULL, _IONBF, 1);
335 HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
336 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
337 FILE* hf_in = _fdopen(hCrt, "r");
338 setvbuf(hf_in, NULL, _IONBF, 128);
343 boost::filesystem::path
346 return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH"));
350 command_and_read (string)
355 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
360 IsWow64Process (GetCurrentProcess(), &p);
364 static optional<string>
365 get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
367 wchar_t buffer[MAX_PATH];
368 ZeroMemory (&buffer, sizeof(buffer));
369 bool r = SetupDiGetDeviceRegistryPropertyW (
370 device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0
373 return optional<string>();
375 return wchar_to_utf8 (buffer);
378 static const GUID GUID_DEVICE_INTERFACE_DISK = {
379 0x53F56307L, 0xB6BF, 0x11D0, { 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B }
383 get_device_number (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
385 /* Find the Windows path to the device */
387 SP_DEVICE_INTERFACE_DATA device_interface_data;
388 device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
390 BOOL r = SetupDiEnumDeviceInterfaces (device_info, device_info_data, &GUID_DEVICE_INTERFACE_DISK, 0, &device_interface_data);
392 LOG_DISK("SetupDiEnumDeviceInterfaces failed (%1)", GetLastError());
393 return optional<int>();
396 /* Find out how much space we need for our SP_DEVICE_INTERFACE_DETAIL_DATA_W */
398 r = SetupDiGetDeviceInterfaceDetailW(device_info, &device_interface_data, 0, 0, &size, 0);
399 PSP_DEVICE_INTERFACE_DETAIL_DATA_W device_detail_data = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W> (malloc(size));
400 if (!device_detail_data) {
401 LOG_DISK_NC("malloc failed");
402 return optional<int>();
405 device_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
407 /* And get the path */
408 r = SetupDiGetDeviceInterfaceDetailW (device_info, &device_interface_data, device_detail_data, size, &size, 0);
410 LOG_DISK_NC("SetupDiGetDeviceInterfaceDetailW failed");
411 free (device_detail_data);
412 return optional<int>();
415 /* Open it. We would not be allowed GENERIC_READ access here but specifying 0 for
416 dwDesiredAccess allows us to query some metadata.
418 HANDLE device = CreateFileW (
419 device_detail_data->DevicePath, 0,
420 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
424 free (device_detail_data);
426 if (device == INVALID_HANDLE_VALUE) {
427 LOG_DISK("CreateFileW failed with %1", GetLastError());
428 return optional<int>();
431 /* Get the device number */
432 STORAGE_DEVICE_NUMBER device_number;
433 r = DeviceIoControl (
434 device, IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0,
435 &device_number, sizeof(device_number), &size, 0
438 CloseHandle (device);
441 return optional<int>();
444 return device_number.DeviceNumber;
447 typedef map<int, vector<boost::filesystem::path> > MountPoints;
449 /** Take a volume path (with a trailing \) and add any disk numbers related to that volume
453 add_volume_mount_points (wchar_t* volume, MountPoints& mount_points)
455 LOG_DISK("Looking at %1", wchar_to_utf8(volume));
457 wchar_t volume_path_names[512];
458 vector<boost::filesystem::path> mp;
460 if (GetVolumePathNamesForVolumeNameW(volume, volume_path_names, sizeof(volume_path_names) / sizeof(wchar_t), &returned)) {
461 wchar_t* p = volume_path_names;
462 while (*p != L'\0') {
463 mp.push_back (wchar_to_utf8(p));
464 LOG_DISK ("Found mount point %1", wchar_to_utf8(p));
469 /* Strip trailing \ */
470 size_t const len = wcslen (volume);
471 DCPOMATIC_ASSERT (len > 0);
472 volume[len - 1] = L'\0';
474 HANDLE handle = CreateFileW (
476 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
480 DCPOMATIC_ASSERT (handle != INVALID_HANDLE_VALUE);
482 VOLUME_DISK_EXTENTS extents;
484 BOOL r = DeviceIoControl (handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &extents, sizeof(extents), &size, 0);
485 CloseHandle (handle);
489 DCPOMATIC_ASSERT (extents.NumberOfDiskExtents == 1);
491 mount_points[extents.Extents[0].DiskNumber] = mp;
497 MountPoints mount_points;
499 wchar_t volume_name[512];
500 HANDLE volume = FindFirstVolumeW (volume_name, sizeof(volume_name) / sizeof(wchar_t));
501 if (volume == INVALID_HANDLE_VALUE) {
502 return MountPoints();
505 add_volume_mount_points (volume_name, mount_points);
507 if (!FindNextVolumeW(volume, volume_name, sizeof(volume_name) / sizeof(wchar_t))) {
510 add_volume_mount_points (volume_name, mount_points);
512 FindVolumeClose (volume);
520 vector<Drive> drives;
522 MountPoints mount_points = find_mount_points ();
524 /* Get a `device information set' containing information about all disks */
525 HDEVINFO device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
526 if (device_info == INVALID_HANDLE_VALUE) {
527 LOG_DISK_NC ("SetupDiClassDevsA failed");
533 /* Find out about the next disk */
534 SP_DEVINFO_DATA device_info_data;
535 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
536 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) {
537 DWORD e = GetLastError();
538 if (e != ERROR_NO_MORE_ITEMS) {
539 LOG_DISK ("SetupDiEnumDeviceInfo failed (%1)", GetLastError());
545 optional<string> const friendly_name = get_friendly_name (device_info, &device_info_data);
546 optional<int> device_number = get_device_number (device_info, &device_info_data);
547 if (!device_number) {
551 string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number);
553 HANDLE device = CreateFileA (
554 physical_drive.c_str(), 0,
555 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
559 if (device == INVALID_HANDLE_VALUE) {
560 LOG_DISK_NC("Could not open PHYSICALDRIVE");
566 BOOL r = DeviceIoControl (
567 device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0,
568 &geom, sizeof(geom), &returned, 0
571 LOG_DISK("Having a look through %1 locked volumes", locked_volumes.size());
573 for (vector<pair<HANDLE, string> >::const_iterator i = locked_volumes.begin(); i != locked_volumes.end(); ++i) {
574 if (i->second == physical_drive) {
580 uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
581 drives.push_back (Drive(physical_drive, locked ? vector<boost::filesystem::path>() : mount_points[*device_number], disk_size, friendly_name, optional<string>()));
582 LOG_DISK("Added drive %1%2", drives.back().log_summary(), locked ? "(locked by us)" : "");
585 CloseHandle (device);
595 LOG_DISK("Unmounting %1 with %2 mount points", _device, _mount_points.size());
596 DCPOMATIC_ASSERT (_mount_points.size() == 1);
597 string const device_name = String::compose ("\\\\.\\%1", _mount_points.front());
598 string const truncated = device_name.substr (0, device_name.length() - 1);
599 //LOG_DISK("Actually opening %1", _device);
600 //HANDLE device = CreateFileA (_device.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
601 LOG_DISK("Actually opening %1", truncated);
602 HANDLE device = CreateFileA (truncated.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
603 if (device == INVALID_HANDLE_VALUE) {
604 LOG_DISK("Could not open %1 for unmount (%2)", truncated, GetLastError());
608 BOOL r = DeviceIoControl (device, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &returned, 0);
610 LOG_DISK("Unmount of %1 failed (%2)", truncated, GetLastError());
614 LOG_DISK("Unmount of %1 succeeded", _device);
615 locked_volumes.push_back (make_pair(device, _device));
621 boost::filesystem::path
624 boost::filesystem::path p;
625 p /= g_get_user_config_dir ();
631 disk_write_finished ()
633 for (vector<pair<HANDLE, string> >::const_iterator i = locked_volumes.begin(); i != locked_volumes.end(); ++i) {
634 CloseHandle (i->first);