2 Copyright (C) 2012-2021 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/>.
25 #include "compose.hpp"
27 #include "dcpomatic_log.h"
29 #include "exceptions.h"
30 #include "dcpomatic_assert.h"
33 #include <dcp/raw_convert.h>
36 #include <libavformat/avio.h>
38 #include <boost/algorithm/string.hpp>
39 #include <boost/dll/runtime_symbol_info.hpp>
50 #include <knownfolders.h>
65 using std::runtime_error;
66 using std::shared_ptr;
70 using boost::optional;
73 static std::vector<pair<HANDLE, string>> locked_volumes;
76 /** @param s Number of seconds to sleep for */
78 dcpomatic_sleep_seconds (int s)
85 dcpomatic_sleep_milliseconds (int ms)
91 /** @return A string of CPU information (model name etc.) */
98 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) {
104 if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) {
108 if (type != REG_SZ) {
112 wstring value (data / sizeof (wchar_t), L'\0');
113 if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) {
118 info = string (value.begin(), value.end());
127 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
129 SECURITY_ATTRIBUTES security;
130 security.nLength = sizeof (security);
131 security.bInheritHandle = TRUE;
132 security.lpSecurityDescriptor = 0;
134 HANDLE child_stderr_read;
135 HANDLE child_stderr_write;
136 if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) {
137 LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)");
142 MultiByteToWideChar (CP_UTF8, 0, directory_containing_executable().string().c_str(), -1, dir, sizeof(dir));
144 STARTUPINFO startup_info;
145 ZeroMemory (&startup_info, sizeof (startup_info));
146 startup_info.cb = sizeof (startup_info);
147 startup_info.hStdError = child_stderr_write;
148 startup_info.dwFlags |= STARTF_USESTDHANDLES;
150 wchar_t command[512];
151 wcscpy (command, L"ffprobe.exe \"");
154 MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file));
155 wcscat (command, file);
157 wcscat (command, L"\"");
159 PROCESS_INFORMATION process_info;
160 ZeroMemory (&process_info, sizeof (process_info));
161 if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, dir, &startup_info, &process_info)) {
162 LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)"));
166 dcp::File o(out, "w");
168 LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)"));
172 CloseHandle (child_stderr_write);
177 if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) {
180 o.write(buffer, read, 1);
185 WaitForSingleObject (process_info.hProcess, INFINITE);
186 CloseHandle (process_info.hProcess);
187 CloseHandle (process_info.hThread);
188 CloseHandle (child_stderr_read);
192 list<pair<string, string>>
199 boost::filesystem::path
200 directory_containing_executable ()
202 return boost::dll::program_location().parent_path();
206 boost::filesystem::path
209 return directory_containing_executable().parent_path();
213 boost::filesystem::path
214 libdcp_resources_path ()
216 return resources_path ();
220 boost::filesystem::path
223 return directory_containing_executable() / "openssl.exe";
227 #ifdef DCPOMATIC_DISK
228 boost::filesystem::path
231 return directory_containing_executable() / "dcpomatic2_disk_writer.exe";
239 boost::mutex::scoped_lock lm (_mutex);
240 SetThreadExecutionState (ES_SYSTEM_REQUIRED);
257 start_tool (string executable)
259 auto batch = directory_containing_executable() / executable;
261 STARTUPINFO startup_info;
262 ZeroMemory (&startup_info, sizeof (startup_info));
263 startup_info.cb = sizeof (startup_info);
265 PROCESS_INFORMATION process_info;
266 ZeroMemory (&process_info, sizeof (process_info));
269 MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
270 CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
275 start_batch_converter ()
277 start_tool ("dcpomatic2_batch");
284 start_tool ("dcpomatic2_player");
291 return (uint64_t) GetCurrentThreadId ();
296 wchar_to_utf8 (wchar_t const * s)
298 int const length = (wcslen(s) + 1) * 2;
299 std::vector<char> utf8(length);
300 WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8.data(), length, 0, 0);
301 string u (utf8.data());
307 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
309 return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags);
314 maybe_open_console ()
316 if (Config::instance()->win32_console ()) {
319 auto handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
320 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
321 auto hf_out = _fdopen(hCrt, "w");
322 setvbuf(hf_out, NULL, _IONBF, 1);
325 auto handle_in = GetStdHandle(STD_INPUT_HANDLE);
326 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
327 auto hf_in = _fdopen(hCrt, "r");
328 setvbuf(hf_in, NULL, _IONBF, 128);
334 boost::filesystem::path
338 auto result = SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &wide_path);
340 if (result != S_OK) {
341 CoTaskMemFree(wide_path);
342 return boost::filesystem::path("c:\\");
345 auto path = wchar_to_utf8(wide_path);
346 CoTaskMemFree(wide_path);
351 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
356 IsWow64Process (GetCurrentProcess(), &p);
361 static optional<string>
362 get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
364 wchar_t buffer[MAX_PATH];
365 ZeroMemory (&buffer, sizeof(buffer));
366 bool r = SetupDiGetDeviceRegistryPropertyW (
367 device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0
370 return optional<string>();
372 return wchar_to_utf8 (buffer);
376 static const GUID GUID_DEVICE_INTERFACE_DISK = {
377 0x53F56307L, 0xB6BF, 0x11D0, { 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B }
382 get_device_number (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
384 /* Find the Windows path to the device */
386 SP_DEVICE_INTERFACE_DATA device_interface_data;
387 device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
389 auto r = SetupDiEnumDeviceInterfaces (device_info, device_info_data, &GUID_DEVICE_INTERFACE_DISK, 0, &device_interface_data);
391 LOG_DISK("SetupDiEnumDeviceInterfaces failed (%1)", GetLastError());
392 return optional<int>();
395 /* Find out how much space we need for our SP_DEVICE_INTERFACE_DETAIL_DATA_W */
397 r = SetupDiGetDeviceInterfaceDetailW(device_info, &device_interface_data, 0, 0, &size, 0);
398 PSP_DEVICE_INTERFACE_DETAIL_DATA_W device_detail_data = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W> (malloc(size));
399 if (!device_detail_data) {
400 LOG_DISK_NC("malloc failed");
401 return optional<int>();
404 device_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
406 /* And get the path */
407 r = SetupDiGetDeviceInterfaceDetailW (device_info, &device_interface_data, device_detail_data, size, &size, 0);
409 LOG_DISK_NC("SetupDiGetDeviceInterfaceDetailW failed");
410 free (device_detail_data);
411 return optional<int>();
414 /* Open it. We would not be allowed GENERIC_READ access here but specifying 0 for
415 dwDesiredAccess allows us to query some metadata.
417 auto device = CreateFileW (
418 device_detail_data->DevicePath, 0,
419 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
423 free (device_detail_data);
425 if (device == INVALID_HANDLE_VALUE) {
426 LOG_DISK("CreateFileW failed with %1", GetLastError());
427 return optional<int>();
430 /* Get the device number */
431 STORAGE_DEVICE_NUMBER device_number;
432 r = DeviceIoControl (
433 device, IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0,
434 &device_number, sizeof(device_number), &size, 0
437 CloseHandle (device);
443 return device_number.DeviceNumber;
447 typedef map<int, vector<boost::filesystem::path>> MountPoints;
450 /** Take a volume path (with a trailing \) and add any disk numbers related to that volume
454 add_volume_mount_points (wchar_t* volume, MountPoints& mount_points)
456 LOG_DISK("Looking at %1", wchar_to_utf8(volume));
458 wchar_t volume_path_names[512];
459 vector<boost::filesystem::path> mp;
461 if (GetVolumePathNamesForVolumeNameW(volume, volume_path_names, sizeof(volume_path_names) / sizeof(wchar_t), &returned)) {
462 wchar_t* p = volume_path_names;
463 while (*p != L'\0') {
464 mp.push_back (wchar_to_utf8(p));
465 LOG_DISK ("Found mount point %1", wchar_to_utf8(p));
470 /* Strip trailing \ */
471 size_t const len = wcslen (volume);
472 DCPOMATIC_ASSERT (len > 0);
473 volume[len - 1] = L'\0';
475 auto handle = CreateFileW (
477 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
481 DCPOMATIC_ASSERT (handle != INVALID_HANDLE_VALUE);
483 VOLUME_DISK_EXTENTS extents;
485 BOOL r = DeviceIoControl (handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &extents, sizeof(extents), &size, 0);
486 CloseHandle (handle);
490 DCPOMATIC_ASSERT (extents.NumberOfDiskExtents == 1);
492 mount_points[extents.Extents[0].DiskNumber] = mp;
499 MountPoints mount_points;
501 wchar_t volume_name[512];
502 auto volume = FindFirstVolumeW (volume_name, sizeof(volume_name) / sizeof(wchar_t));
503 if (volume == INVALID_HANDLE_VALUE) {
504 return MountPoints();
507 add_volume_mount_points (volume_name, mount_points);
509 if (!FindNextVolumeW(volume, volume_name, sizeof(volume_name) / sizeof(wchar_t))) {
512 add_volume_mount_points (volume_name, mount_points);
514 FindVolumeClose (volume);
523 vector<Drive> drives;
525 auto mount_points = find_mount_points ();
527 /* Get a `device information set' containing information about all disks */
528 auto device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
529 if (device_info == INVALID_HANDLE_VALUE) {
530 LOG_DISK_NC ("SetupDiClassDevsA failed");
536 /* Find out about the next disk */
537 SP_DEVINFO_DATA device_info_data;
538 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
539 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) {
540 DWORD e = GetLastError();
541 if (e != ERROR_NO_MORE_ITEMS) {
542 LOG_DISK ("SetupDiEnumDeviceInfo failed (%1)", GetLastError());
548 auto const friendly_name = get_friendly_name (device_info, &device_info_data);
549 auto device_number = get_device_number (device_info, &device_info_data);
550 if (!device_number) {
554 string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number);
556 HANDLE device = CreateFileA (
557 physical_drive.c_str(), 0,
558 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
562 if (device == INVALID_HANDLE_VALUE) {
563 LOG_DISK_NC("Could not open PHYSICALDRIVE");
569 BOOL r = DeviceIoControl (
570 device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0,
571 &geom, sizeof(geom), &returned, 0
574 LOG_DISK("Having a look through %1 locked volumes", locked_volumes.size());
576 for (auto const& i: locked_volumes) {
577 if (i.second == physical_drive) {
583 uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
584 drives.push_back (Drive(physical_drive, locked ? vector<boost::filesystem::path>() : mount_points[*device_number], disk_size, friendly_name, optional<string>()));
585 LOG_DISK("Added drive %1%2", drives.back().log_summary(), locked ? "(locked by us)" : "");
588 CloseHandle (device);
598 LOG_DISK("Unmounting %1 with %2 mount points", _device, _mount_points.size());
599 DCPOMATIC_ASSERT (_mount_points.size() == 1);
600 string const device_name = String::compose ("\\\\.\\%1", _mount_points.front());
601 string const truncated = device_name.substr (0, device_name.length() - 1);
602 LOG_DISK("Actually opening %1", truncated);
603 HANDLE device = CreateFileA (truncated.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
604 if (device == INVALID_HANDLE_VALUE) {
605 LOG_DISK("Could not open %1 for unmount (%2)", truncated, GetLastError());
609 BOOL r = DeviceIoControl (device, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &returned, 0);
611 LOG_DISK("Unmount of %1 failed (%2)", truncated, GetLastError());
615 LOG_DISK("Unmount of %1 succeeded", _device);
616 locked_volumes.push_back (make_pair(device, _device));
622 boost::filesystem::path
623 config_path (optional<string> version)
625 boost::filesystem::path p;
626 p /= g_get_user_config_dir ();
636 disk_write_finished ()
638 for (auto const& i: locked_volumes) {
639 CloseHandle (i.first);
645 dcpomatic::get_process_id ()
647 return dcp::raw_convert<string>(GetCurrentProcessId());
652 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
654 std::wstringstream args;
655 args << "/select," << select;
656 auto const r = ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
657 return (reinterpret_cast<int64_t>(r) <= 32);