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/>.
23 #include "compose.hpp"
25 #include "dcpomatic_log.h"
27 #include "exceptions.h"
28 #include <dcp/raw_convert.h>
30 #include <boost/algorithm/string.hpp>
31 #include <boost/regex.hpp>
32 #if BOOST_VERSION >= 106100
33 #include <boost/dll/runtime_symbol_info.hpp>
35 #include <ApplicationServices/ApplicationServices.h>
36 #include <sys/sysctl.h>
37 #include <mach-o/dyld.h>
38 #include <IOKit/pwr_mgt/IOPMLib.h>
39 #include <IOKit/storage/IOMedia.h>
40 #include <DiskArbitration/DADisk.h>
41 #include <DiskArbitration/DiskArbitration.h>
42 #include <CoreFoundation/CFURL.h>
43 #include <sys/types.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
61 using std::runtime_error;
63 using std::shared_ptr;
64 using boost::optional;
68 /** @return A string of CPU information (model name etc.) */
75 size_t N = sizeof (buffer);
76 if (sysctlbyname("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
84 boost::filesystem::path
85 directory_containing_executable ()
87 return boost::filesystem::canonical(boost::dll::program_location()).parent_path();
91 boost::filesystem::path
94 return directory_containing_executable().parent_path() / "Resources";
98 boost::filesystem::path
99 libdcp_resources_path ()
101 return resources_path();
106 run_ffprobe(boost::filesystem::path content, boost::filesystem::path out, bool err, string args)
108 auto path = directory_containing_executable () / "ffprobe";
109 if (!boost::filesystem::exists(path)) {
110 /* This is a hack but we need ffprobe during tests */
111 path = "/Users/ci/workspace/bin/ffprobe";
113 string const redirect = err ? "2>" : ">";
115 auto const ffprobe = String::compose("\"%1\" %2 \"%3\" %4 \"%5\"", path, args.empty() ? " " : args, content.string(), redirect, out.string());
116 LOG_GENERAL (N_("Probing with %1"), ffprobe);
117 system (ffprobe.c_str());
122 list<pair<string, string>>
129 boost::filesystem::path
132 return directory_containing_executable() / "openssl";
136 #ifdef DCPOMATIC_DISK
137 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
138 boost::filesystem::path
141 return directory_containing_executable() / "dcpomatic2_disk_writer";
155 boost::mutex::scoped_lock lm (_mutex);
156 IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
162 boost::mutex::scoped_lock lm (_mutex);
163 IOPMAssertionRelease (_assertion_id);
168 start_tool (string executable, string app)
170 auto exe_path = directory_containing_executable();
171 exe_path = exe_path.parent_path(); // Contents
172 exe_path = exe_path.parent_path(); // DCP-o-matic 2.app
173 exe_path = exe_path.parent_path(); // Applications
175 exe_path /= "Contents";
177 exe_path /= executable;
181 LOG_GENERAL ("start_tool %1 %2 with path %3", executable, app, exe_path.string());
182 int const r = system (exe_path.string().c_str());
183 exit (WEXITSTATUS (r));
184 } else if (pid == -1) {
185 LOG_ERROR_NC("Fork failed in start_tool");
191 start_batch_converter ()
193 start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
200 start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
204 static optional<string>
205 get_vendor (CFDictionaryRef& description)
207 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
212 auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
218 boost::algorithm::trim (s);
223 static optional<string>
224 get_model (CFDictionaryRef& description)
226 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
231 auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
237 boost::algorithm::trim (s);
242 static optional<OSXMediaPath>
243 analyse_media_path (CFDictionaryRef& description)
245 using namespace boost::algorithm;
247 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
249 LOG_DISK_NC("There is no MediaPathKey (no dictionary value)");
253 auto path_key_cstr = CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8);
254 if (!path_key_cstr) {
255 LOG_DISK_NC("There is no MediaPathKey (no cstring)");
259 string path(path_key_cstr);
260 LOG_DISK("MediaPathKey is %1", path);
261 return analyse_osx_media_path (path);
266 is_whole_drive (DADiskRef& disk)
268 io_service_t service = DADiskCopyIOMedia (disk);
269 CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
270 bool whole_media = false;
271 if (whole_media_ref) {
272 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
273 CFRelease (whole_media_ref);
275 IOObjectRelease (service);
280 static optional<boost::filesystem::path>
281 mount_point (CFDictionaryRef& description)
283 auto volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
284 if (!volume_path_key) {
288 char mount_path_buffer[1024];
289 if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
292 return boost::filesystem::path(mount_path_buffer);
296 /* Here follows some rather intricate and (probably) fragile code to find the list of available
297 * "real" drives on macOS that we might want to write a DCP to.
299 * We use the Disk Arbitration framework to give us a series of mount_points (/dev/disk0, /dev/disk1,
300 * /dev/disk1s1 and so on) and we use the API to gather useful information about these mount_points into
301 * a vector of Disk structs.
303 * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
304 * user, with details of whether those drives are currently mounted or not.
306 * At the basic level we find the "disk"-level mount_points, looking at whether any of their partitions are mounted.
308 * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
309 * reflect data in `real' partitions. So, for example, we might have a real (physical) drive /dev/disk2 with
310 * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
311 * which are mounted. /dev/disk2s2 is not considered to be mounted, in this case. So we need to know that
312 * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are. In order to do
313 * this I am taking the first two parts of the IODeviceTree and seeing if they exist anywhere in a
314 * IOService identifier. If they do, I am assuming the IOService device is on the matching IODeviceTree device.
316 * Lots of this is guesswork and may be broken. In my defence the documentation that I have been able to
317 * unearth is, to put it impolitely, crap.
321 disk_appeared (DADiskRef disk, void* context)
323 auto bsd_name = DADiskGetBSDName (disk);
325 LOG_DISK_NC("Disk with no BSDName appeared");
328 LOG_DISK("%1 appeared", bsd_name);
332 this_disk.device = string("/dev/") + bsd_name;
333 LOG_DISK("Device is %1", this_disk.device);
335 CFDictionaryRef description = DADiskCopyDescription (disk);
337 this_disk.vendor = get_vendor (description);
338 this_disk.model = get_model (description);
339 LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
341 auto media_path = analyse_media_path (description);
343 LOG_DISK("Finding media path for %1 failed", bsd_name);
347 this_disk.media_path = *media_path;
348 this_disk.whole = is_whole_drive (disk);
349 auto mp = mount_point (description);
351 this_disk.mount_points.push_back (*mp);
355 "%1 %2 mounted at %3",
356 this_disk.media_path.real ? "Real" : "Synth",
357 this_disk.whole ? "whole" : "part",
358 mp ? mp->string() : "[nowhere]"
361 auto media_size_cstr = CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey);
362 if (!media_size_cstr) {
363 LOG_DISK_NC("Could not read media size");
367 CFNumberGetValue ((CFNumberRef) media_size_cstr, kCFNumberLongType, &this_disk.size);
368 CFRelease (description);
370 reinterpret_cast<vector<OSXDisk>*>(context)->push_back(this_disk);
377 using namespace boost::algorithm;
378 vector<OSXDisk> disks;
380 auto session = DASessionCreate(kCFAllocatorDefault);
385 DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
386 auto run_loop = CFRunLoopGetCurrent ();
387 DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
388 CFRunLoopStop (run_loop);
389 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
390 DAUnregisterCallback(session, (void *) disk_appeared, &disks);
393 return osx_disks_to_drives (disks);
397 boost::filesystem::path
398 config_path (optional<string> version)
400 boost::filesystem::path p;
401 p /= g_get_home_dir ();
404 p /= "com.dcpomatic";
415 bool success = false;
416 bool callback = false;
420 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
422 LOG_DISK_NC("Unmount finished");
423 auto state = reinterpret_cast<UnmountState*>(context);
424 state->callback = true;
426 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
428 LOG_DISK_NC("Successful");
429 state->success = true;
437 LOG_DISK_NC("Unmount operation started");
439 auto session = DASessionCreate(kCFAllocatorDefault);
444 auto disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
448 LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
450 DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &state);
453 CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
454 DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
455 CFRunLoopStop (run_loop);
456 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 5, 0);
459 if (!state.callback) {
460 LOG_DISK_NC("End of unmount: timeout");
462 LOG_DISK("End of unmount: %1", state.success ? "success" : "failure");
464 return state.success;
469 disk_write_finished ()
476 make_foreground_application ()
478 ProcessSerialNumber serial;
479 LIBDCP_DISABLE_WARNINGS
480 GetCurrentProcess (&serial);
481 LIBDCP_ENABLE_WARNINGS
482 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
487 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
489 int r = system (String::compose("open -R \"%1\"", select.string()).c_str());
490 return static_cast<bool>(WEXITSTATUS(r));