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>
47 #include <knownfolders.h>
48 #include <processenv.h>
66 using std::runtime_error;
67 using std::shared_ptr;
71 using boost::optional;
74 static std::vector<pair<HANDLE, string>> locked_volumes;
77 /** @param s Number of seconds to sleep for */
79 dcpomatic_sleep_seconds (int s)
86 dcpomatic_sleep_milliseconds (int ms)
92 /** @return A string of CPU information (model name etc.) */
99 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) {
105 if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) {
109 if (type != REG_SZ) {
113 wstring value (data / sizeof (wchar_t), L'\0');
114 if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) {
119 info = string (value.begin(), value.end());
128 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
130 SECURITY_ATTRIBUTES security;
131 security.nLength = sizeof (security);
132 security.bInheritHandle = TRUE;
133 security.lpSecurityDescriptor = 0;
135 HANDLE child_stderr_read;
136 HANDLE child_stderr_write;
137 if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) {
138 LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)");
143 MultiByteToWideChar (CP_UTF8, 0, directory_containing_executable().string().c_str(), -1, dir, sizeof(dir));
145 STARTUPINFO startup_info;
146 ZeroMemory (&startup_info, sizeof (startup_info));
147 startup_info.cb = sizeof (startup_info);
148 startup_info.hStdError = child_stderr_write;
149 startup_info.dwFlags |= STARTF_USESTDHANDLES;
151 wchar_t command[512];
152 wcscpy (command, L"ffprobe.exe \"");
155 MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file));
156 wcscat (command, file);
158 wcscat (command, L"\"");
160 PROCESS_INFORMATION process_info;
161 ZeroMemory (&process_info, sizeof (process_info));
162 if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, dir, &startup_info, &process_info)) {
163 LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)"));
167 dcp::File o(out, "w");
169 LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)"));
173 CloseHandle (child_stderr_write);
178 if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) {
181 o.write(buffer, read, 1);
186 WaitForSingleObject (process_info.hProcess, INFINITE);
187 CloseHandle (process_info.hProcess);
188 CloseHandle (process_info.hThread);
189 CloseHandle (child_stderr_read);
193 list<pair<string, string>>
200 boost::filesystem::path
201 directory_containing_executable ()
203 return boost::dll::program_location().parent_path();
207 boost::filesystem::path
210 return directory_containing_executable().parent_path();
214 boost::filesystem::path
215 libdcp_resources_path ()
217 return resources_path ();
221 boost::filesystem::path
224 return directory_containing_executable() / "openssl.exe";
228 #ifdef DCPOMATIC_DISK
229 boost::filesystem::path
232 return directory_containing_executable() / "dcpomatic2_disk_writer.exe";
240 boost::mutex::scoped_lock lm (_mutex);
241 SetThreadExecutionState (ES_SYSTEM_REQUIRED);
258 start_tool (string executable)
260 auto batch = directory_containing_executable() / executable;
262 STARTUPINFO startup_info;
263 ZeroMemory (&startup_info, sizeof (startup_info));
264 startup_info.cb = sizeof (startup_info);
266 PROCESS_INFORMATION process_info;
267 ZeroMemory (&process_info, sizeof (process_info));
270 MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
271 CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
276 start_batch_converter ()
278 start_tool ("dcpomatic2_batch");
285 start_tool ("dcpomatic2_player");
292 return (uint64_t) GetCurrentThreadId ();
297 wchar_to_utf8 (wchar_t const * s)
299 int const length = (wcslen(s) + 1) * 2;
300 std::vector<char> utf8(length);
301 WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8.data(), length, 0, 0);
302 string u (utf8.data());
308 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
310 return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags);
315 maybe_open_console ()
317 if (Config::instance()->win32_console ()) {
320 auto handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
321 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
322 auto hf_out = _fdopen(hCrt, "w");
323 setvbuf(hf_out, NULL, _IONBF, 1);
326 auto handle_in = GetStdHandle(STD_INPUT_HANDLE);
327 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
328 auto hf_in = _fdopen(hCrt, "r");
329 setvbuf(hf_in, NULL, _IONBF, 128);
335 boost::filesystem::path
339 auto result = SHGetKnownFolderPath(FOLDERID_Documents, 0, nullptr, &wide_path);
341 if (result != S_OK) {
342 CoTaskMemFree(wide_path);
343 return boost::filesystem::path("c:\\");
346 auto path = wchar_to_utf8(wide_path);
347 CoTaskMemFree(wide_path);
352 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
357 IsWow64Process (GetCurrentProcess(), &p);
362 static optional<string>
363 get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
365 wchar_t buffer[MAX_PATH];
366 ZeroMemory (&buffer, sizeof(buffer));
367 bool r = SetupDiGetDeviceRegistryPropertyW (
368 device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0
371 return optional<string>();
373 return wchar_to_utf8 (buffer);
377 static const GUID GUID_DEVICE_INTERFACE_DISK = {
378 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 auto 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 auto 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);
444 return device_number.DeviceNumber;
448 typedef map<int, vector<boost::filesystem::path>> MountPoints;
451 /** Take a volume path (with a trailing \) and add any disk numbers related to that volume
455 add_volume_mount_points (wchar_t* volume, MountPoints& mount_points)
457 LOG_DISK("Looking at %1", wchar_to_utf8(volume));
459 wchar_t volume_path_names[512];
460 vector<boost::filesystem::path> mp;
462 if (GetVolumePathNamesForVolumeNameW(volume, volume_path_names, sizeof(volume_path_names) / sizeof(wchar_t), &returned)) {
463 wchar_t* p = volume_path_names;
464 while (*p != L'\0') {
465 mp.push_back (wchar_to_utf8(p));
466 LOG_DISK ("Found mount point %1", wchar_to_utf8(p));
471 /* Strip trailing \ */
472 size_t const len = wcslen (volume);
473 DCPOMATIC_ASSERT (len > 0);
474 volume[len - 1] = L'\0';
476 auto handle = CreateFileW (
478 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
482 DCPOMATIC_ASSERT (handle != INVALID_HANDLE_VALUE);
484 VOLUME_DISK_EXTENTS extents;
486 BOOL r = DeviceIoControl (handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &extents, sizeof(extents), &size, 0);
487 CloseHandle (handle);
491 DCPOMATIC_ASSERT (extents.NumberOfDiskExtents == 1);
493 mount_points[extents.Extents[0].DiskNumber] = mp;
500 MountPoints mount_points;
502 wchar_t volume_name[512];
503 auto volume = FindFirstVolumeW (volume_name, sizeof(volume_name) / sizeof(wchar_t));
504 if (volume == INVALID_HANDLE_VALUE) {
505 return MountPoints();
508 add_volume_mount_points (volume_name, mount_points);
510 if (!FindNextVolumeW(volume, volume_name, sizeof(volume_name) / sizeof(wchar_t))) {
513 add_volume_mount_points (volume_name, mount_points);
515 FindVolumeClose (volume);
524 vector<Drive> drives;
526 auto mount_points = find_mount_points ();
528 /* Get a `device information set' containing information about all disks */
529 auto device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
530 if (device_info == INVALID_HANDLE_VALUE) {
531 LOG_DISK_NC ("SetupDiClassDevsA failed");
537 /* Find out about the next disk */
538 SP_DEVINFO_DATA device_info_data;
539 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
540 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) {
541 DWORD e = GetLastError();
542 if (e != ERROR_NO_MORE_ITEMS) {
543 LOG_DISK ("SetupDiEnumDeviceInfo failed (%1)", GetLastError());
549 auto const friendly_name = get_friendly_name (device_info, &device_info_data);
550 auto device_number = get_device_number (device_info, &device_info_data);
551 if (!device_number) {
555 string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number);
557 HANDLE device = CreateFileA (
558 physical_drive.c_str(), 0,
559 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
563 if (device == INVALID_HANDLE_VALUE) {
564 LOG_DISK_NC("Could not open PHYSICALDRIVE");
570 BOOL r = DeviceIoControl (
571 device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0,
572 &geom, sizeof(geom), &returned, 0
575 LOG_DISK("Having a look through %1 locked volumes", locked_volumes.size());
577 for (auto const& i: locked_volumes) {
578 if (i.second == physical_drive) {
584 uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
585 drives.push_back (Drive(physical_drive, locked ? vector<boost::filesystem::path>() : mount_points[*device_number], disk_size, friendly_name, optional<string>()));
586 LOG_DISK("Added drive %1%2", drives.back().log_summary(), locked ? "(locked by us)" : "");
589 CloseHandle (device);
599 LOG_DISK("Unmounting %1 with %2 mount points", _device, _mount_points.size());
600 DCPOMATIC_ASSERT (_mount_points.size() == 1);
601 string const device_name = String::compose ("\\\\.\\%1", _mount_points.front());
602 string const truncated = device_name.substr (0, device_name.length() - 1);
603 LOG_DISK("Actually opening %1", truncated);
604 HANDLE device = CreateFileA (truncated.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
605 if (device == INVALID_HANDLE_VALUE) {
606 LOG_DISK("Could not open %1 for unmount (%2)", truncated, GetLastError());
610 BOOL r = DeviceIoControl (device, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &returned, 0);
612 LOG_DISK("Unmount of %1 failed (%2)", truncated, GetLastError());
616 LOG_DISK("Unmount of %1 succeeded", _device);
617 locked_volumes.push_back (make_pair(device, _device));
623 boost::filesystem::path
624 config_path (optional<string> version)
626 boost::filesystem::path p;
627 p /= g_get_user_config_dir ();
637 disk_write_finished ()
639 for (auto const& i: locked_volumes) {
640 CloseHandle (i.first);
646 dcpomatic::get_process_id ()
648 return dcp::raw_convert<string>(GetCurrentProcessId());
653 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
655 std::wstringstream args;
656 args << "/select," << select;
657 auto const r = ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
658 return (reinterpret_cast<int64_t>(r) <= 32);
662 ArgFixer::ArgFixer(int, char**)
664 auto cmd_line = GetCommandLineW();
665 auto wide_argv = CommandLineToArgvW(cmd_line, &_argc);
667 _argv_strings.resize(_argc);
668 _argv = new char*[_argc];
669 for (int i = 0; i < _argc; ++i) {
670 _argv_strings[i] = wchar_to_utf8(wide_argv[i]);
671 _argv[i] = const_cast<char*>(_argv_strings[i].c_str());