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"
32 #include <dcp/raw_convert.h>
35 #include <libavformat/avio.h>
37 #include <boost/algorithm/string.hpp>
38 #include <boost/dll/runtime_symbol_info.hpp>
62 using std::runtime_error;
63 using std::shared_ptr;
67 using boost::optional;
70 static std::vector<pair<HANDLE, string>> locked_volumes;
73 /** @param s Number of seconds to sleep for */
75 dcpomatic_sleep_seconds (int s)
82 dcpomatic_sleep_milliseconds (int ms)
88 /** @return A string of CPU information (model name etc.) */
95 if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) {
101 if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) {
105 if (type != REG_SZ) {
109 wstring value (data / sizeof (wchar_t), L'\0');
110 if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) {
115 info = string (value.begin(), value.end());
124 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
126 SECURITY_ATTRIBUTES security;
127 security.nLength = sizeof (security);
128 security.bInheritHandle = TRUE;
129 security.lpSecurityDescriptor = 0;
131 HANDLE child_stderr_read;
132 HANDLE child_stderr_write;
133 if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) {
134 LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)");
139 MultiByteToWideChar (CP_UTF8, 0, directory_containing_executable().string().c_str(), -1, dir, sizeof(dir));
141 STARTUPINFO startup_info;
142 ZeroMemory (&startup_info, sizeof (startup_info));
143 startup_info.cb = sizeof (startup_info);
144 startup_info.hStdError = child_stderr_write;
145 startup_info.dwFlags |= STARTF_USESTDHANDLES;
147 wchar_t command[512];
148 wcscpy (command, L"ffprobe.exe \"");
151 MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file));
152 wcscat (command, file);
154 wcscat (command, L"\"");
156 PROCESS_INFORMATION process_info;
157 ZeroMemory (&process_info, sizeof (process_info));
158 if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, dir, &startup_info, &process_info)) {
159 LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)"));
163 auto o = fopen_boost (out, "w");
165 LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)"));
169 CloseHandle (child_stderr_write);
174 if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) {
177 fwrite (buffer, read, 1, o);
182 WaitForSingleObject (process_info.hProcess, INFINITE);
183 CloseHandle (process_info.hProcess);
184 CloseHandle (process_info.hThread);
185 CloseHandle (child_stderr_read);
189 list<pair<string, string>>
196 boost::filesystem::path
197 directory_containing_executable ()
199 return boost::dll::program_location().parent_path();
203 boost::filesystem::path
206 return directory_containing_executable().parent_path();
210 boost::filesystem::path
213 return directory_containing_executable().parent_path() / "xsd";
217 boost::filesystem::path
220 return directory_containing_executable().parent_path() / "tags";
224 boost::filesystem::path
227 return directory_containing_executable() / "openssl.exe";
231 #ifdef DCPOMATIC_DISK
232 boost::filesystem::path
235 return directory_containing_executable() / "dcpomatic2_disk_writer.exe";
240 /** Windows can't "by default" cope with paths longer than 260 characters, so if you pass such a path to
241 * any boost::filesystem method it will fail. There is a "fix" for this, which is to prepend
242 * the string \\?\ to the path. This will make it work, so long as:
243 * - the path is absolute.
244 * - the path only uses backslashes.
245 * - individual path components are "short enough" (probably less than 255 characters)
247 * See https://www.boost.org/doc/libs/1_57_0/libs/filesystem/doc/reference.html under
248 * "Warning: Long paths on Windows" for some details.
250 * Our fopen_boost uses this method to get this fix, but any other calls to boost::filesystem
251 * will not unless this method is explicitly called to pre-process the pathname.
253 boost::filesystem::path
254 fix_long_path (boost::filesystem::path long_path)
256 using namespace boost::filesystem;
258 if (boost::algorithm::starts_with(long_path.string(), "\\\\")) {
259 /* This could mean it starts with \\ (i.e. a SMB path) or \\?\ (a long path)
260 * or a variety of other things... anyway, we'll leave it alone.
265 /* We have to make the path canonical but we can't call canonical() on the long path
266 * as it will fail. So we'll sort of do it ourselves (possibly badly).
268 path fixed = "\\\\?\\";
269 if (long_path.is_absolute()) {
270 fixed += long_path.make_preferred();
272 fixed += boost::filesystem::current_path() / long_path.make_preferred();
278 /* Apparently there is no way to create an ofstream using a UTF-8
279 filename under Windows. We are hence reduced to using fopen
283 fopen_boost (boost::filesystem::path p, string t)
285 wstring w (t.begin(), t.end());
286 /* c_str() on fixed here should give a UTF-16 string */
287 return _wfopen (fix_long_path(p).c_str(), w.c_str());
292 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
294 return _fseeki64 (stream, offset, whence);
301 boost::mutex::scoped_lock lm (_mutex);
302 SetThreadExecutionState (ES_SYSTEM_REQUIRED);
319 start_tool (string executable)
321 auto batch = directory_containing_executable() / executable;
323 STARTUPINFO startup_info;
324 ZeroMemory (&startup_info, sizeof (startup_info));
325 startup_info.cb = sizeof (startup_info);
327 PROCESS_INFORMATION process_info;
328 ZeroMemory (&process_info, sizeof (process_info));
331 MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
332 CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
337 start_batch_converter ()
339 start_tool ("dcpomatic2_batch");
346 start_tool ("dcpomatic2_player");
353 return (uint64_t) GetCurrentThreadId ();
358 wchar_to_utf8 (wchar_t const * s)
360 int const length = (wcslen(s) + 1) * 2;
361 char* utf8 = new char[length];
362 WideCharToMultiByte (CP_UTF8, 0, s, -1, utf8, length, 0, 0);
370 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
372 return avio_open (s, wchar_to_utf8(file.c_str()).c_str(), flags);
377 maybe_open_console ()
379 if (Config::instance()->win32_console ()) {
382 auto handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
383 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
384 auto hf_out = _fdopen(hCrt, "w");
385 setvbuf(hf_out, NULL, _IONBF, 1);
388 auto handle_in = GetStdHandle(STD_INPUT_HANDLE);
389 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
390 auto hf_in = _fdopen(hCrt, "r");
391 setvbuf(hf_in, NULL, _IONBF, 128);
397 boost::filesystem::path
400 return boost::filesystem::path(getenv("userprofile"));
404 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
409 IsWow64Process (GetCurrentProcess(), &p);
414 static optional<string>
415 get_friendly_name (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
417 wchar_t buffer[MAX_PATH];
418 ZeroMemory (&buffer, sizeof(buffer));
419 bool r = SetupDiGetDeviceRegistryPropertyW (
420 device_info, device_info_data, SPDRP_FRIENDLYNAME, 0, reinterpret_cast<PBYTE>(buffer), sizeof(buffer), 0
423 return optional<string>();
425 return wchar_to_utf8 (buffer);
429 static const GUID GUID_DEVICE_INTERFACE_DISK = {
430 0x53F56307L, 0xB6BF, 0x11D0, { 0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B }
435 get_device_number (HDEVINFO device_info, SP_DEVINFO_DATA* device_info_data)
437 /* Find the Windows path to the device */
439 SP_DEVICE_INTERFACE_DATA device_interface_data;
440 device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
442 auto r = SetupDiEnumDeviceInterfaces (device_info, device_info_data, &GUID_DEVICE_INTERFACE_DISK, 0, &device_interface_data);
444 LOG_DISK("SetupDiEnumDeviceInterfaces failed (%1)", GetLastError());
445 return optional<int>();
448 /* Find out how much space we need for our SP_DEVICE_INTERFACE_DETAIL_DATA_W */
450 r = SetupDiGetDeviceInterfaceDetailW(device_info, &device_interface_data, 0, 0, &size, 0);
451 PSP_DEVICE_INTERFACE_DETAIL_DATA_W device_detail_data = static_cast<PSP_DEVICE_INTERFACE_DETAIL_DATA_W> (malloc(size));
452 if (!device_detail_data) {
453 LOG_DISK_NC("malloc failed");
454 return optional<int>();
457 device_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W);
459 /* And get the path */
460 r = SetupDiGetDeviceInterfaceDetailW (device_info, &device_interface_data, device_detail_data, size, &size, 0);
462 LOG_DISK_NC("SetupDiGetDeviceInterfaceDetailW failed");
463 free (device_detail_data);
464 return optional<int>();
467 /* Open it. We would not be allowed GENERIC_READ access here but specifying 0 for
468 dwDesiredAccess allows us to query some metadata.
470 auto device = CreateFileW (
471 device_detail_data->DevicePath, 0,
472 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
476 free (device_detail_data);
478 if (device == INVALID_HANDLE_VALUE) {
479 LOG_DISK("CreateFileW failed with %1", GetLastError());
480 return optional<int>();
483 /* Get the device number */
484 STORAGE_DEVICE_NUMBER device_number;
485 r = DeviceIoControl (
486 device, IOCTL_STORAGE_GET_DEVICE_NUMBER, 0, 0,
487 &device_number, sizeof(device_number), &size, 0
490 CloseHandle (device);
496 return device_number.DeviceNumber;
500 typedef map<int, vector<boost::filesystem::path>> MountPoints;
503 /** Take a volume path (with a trailing \) and add any disk numbers related to that volume
507 add_volume_mount_points (wchar_t* volume, MountPoints& mount_points)
509 LOG_DISK("Looking at %1", wchar_to_utf8(volume));
511 wchar_t volume_path_names[512];
512 vector<boost::filesystem::path> mp;
514 if (GetVolumePathNamesForVolumeNameW(volume, volume_path_names, sizeof(volume_path_names) / sizeof(wchar_t), &returned)) {
515 wchar_t* p = volume_path_names;
516 while (*p != L'\0') {
517 mp.push_back (wchar_to_utf8(p));
518 LOG_DISK ("Found mount point %1", wchar_to_utf8(p));
523 /* Strip trailing \ */
524 size_t const len = wcslen (volume);
525 DCPOMATIC_ASSERT (len > 0);
526 volume[len - 1] = L'\0';
528 auto handle = CreateFileW (
530 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
534 DCPOMATIC_ASSERT (handle != INVALID_HANDLE_VALUE);
536 VOLUME_DISK_EXTENTS extents;
538 BOOL r = DeviceIoControl (handle, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, 0, 0, &extents, sizeof(extents), &size, 0);
539 CloseHandle (handle);
543 DCPOMATIC_ASSERT (extents.NumberOfDiskExtents == 1);
545 mount_points[extents.Extents[0].DiskNumber] = mp;
552 MountPoints mount_points;
554 wchar_t volume_name[512];
555 auto volume = FindFirstVolumeW (volume_name, sizeof(volume_name) / sizeof(wchar_t));
556 if (volume == INVALID_HANDLE_VALUE) {
557 return MountPoints();
560 add_volume_mount_points (volume_name, mount_points);
562 if (!FindNextVolumeW(volume, volume_name, sizeof(volume_name) / sizeof(wchar_t))) {
565 add_volume_mount_points (volume_name, mount_points);
567 FindVolumeClose (volume);
576 vector<Drive> drives;
578 auto mount_points = find_mount_points ();
580 /* Get a `device information set' containing information about all disks */
581 auto device_info = SetupDiGetClassDevsA (&GUID_DEVICE_INTERFACE_DISK, 0, 0, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
582 if (device_info == INVALID_HANDLE_VALUE) {
583 LOG_DISK_NC ("SetupDiClassDevsA failed");
589 /* Find out about the next disk */
590 SP_DEVINFO_DATA device_info_data;
591 device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
592 if (!SetupDiEnumDeviceInfo(device_info, i, &device_info_data)) {
593 DWORD e = GetLastError();
594 if (e != ERROR_NO_MORE_ITEMS) {
595 LOG_DISK ("SetupDiEnumDeviceInfo failed (%1)", GetLastError());
601 auto const friendly_name = get_friendly_name (device_info, &device_info_data);
602 auto device_number = get_device_number (device_info, &device_info_data);
603 if (!device_number) {
607 string const physical_drive = String::compose("\\\\.\\PHYSICALDRIVE%1", *device_number);
609 HANDLE device = CreateFileA (
610 physical_drive.c_str(), 0,
611 FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
615 if (device == INVALID_HANDLE_VALUE) {
616 LOG_DISK_NC("Could not open PHYSICALDRIVE");
622 BOOL r = DeviceIoControl (
623 device, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0,
624 &geom, sizeof(geom), &returned, 0
627 LOG_DISK("Having a look through %1 locked volumes", locked_volumes.size());
629 for (auto const& i: locked_volumes) {
630 if (i.second == physical_drive) {
636 uint64_t const disk_size = geom.Cylinders.QuadPart * geom.TracksPerCylinder * geom.SectorsPerTrack * geom.BytesPerSector;
637 drives.push_back (Drive(physical_drive, locked ? vector<boost::filesystem::path>() : mount_points[*device_number], disk_size, friendly_name, optional<string>()));
638 LOG_DISK("Added drive %1%2", drives.back().log_summary(), locked ? "(locked by us)" : "");
641 CloseHandle (device);
651 LOG_DISK("Unmounting %1 with %2 mount points", _device, _mount_points.size());
652 DCPOMATIC_ASSERT (_mount_points.size() == 1);
653 string const device_name = String::compose ("\\\\.\\%1", _mount_points.front());
654 string const truncated = device_name.substr (0, device_name.length() - 1);
655 //LOG_DISK("Actually opening %1", _device);
656 //HANDLE device = CreateFileA (_device.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
657 LOG_DISK("Actually opening %1", truncated);
658 HANDLE device = CreateFileA (truncated.c_str(), (GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
659 if (device == INVALID_HANDLE_VALUE) {
660 LOG_DISK("Could not open %1 for unmount (%2)", truncated, GetLastError());
664 BOOL r = DeviceIoControl (device, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &returned, 0);
666 LOG_DISK("Unmount of %1 failed (%2)", truncated, GetLastError());
670 LOG_DISK("Unmount of %1 succeeded", _device);
671 locked_volumes.push_back (make_pair(device, _device));
677 boost::filesystem::path
678 config_path (optional<string> version)
680 boost::filesystem::path p;
681 p /= g_get_user_config_dir ();
691 disk_write_finished ()
693 for (auto const& i: locked_volumes) {
694 CloseHandle (i.first);
700 dcpomatic::get_process_id ()
702 return dcp::raw_convert<string>(GetCurrentProcessId());
707 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
709 std::wstringstream args;
710 args << "/select," << select;
711 auto const r = ShellExecute (0, L"open", L"explorer.exe", args.str().c_str(), 0, SW_SHOWDEFAULT);
712 return (reinterpret_cast<int64_t>(r) <= 32);