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"
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/regex.hpp>
36 #if BOOST_VERSION >= 106100
37 #include <boost/dll/runtime_symbol_info.hpp>
39 #include <ApplicationServices/ApplicationServices.h>
40 #include <sys/sysctl.h>
41 #include <mach-o/dyld.h>
42 #include <IOKit/pwr_mgt/IOPMLib.h>
43 #include <IOKit/storage/IOMedia.h>
44 #include <DiskArbitration/DADisk.h>
45 #include <DiskArbitration/DiskArbitration.h>
46 #include <CoreFoundation/CFURL.h>
47 #include <sys/types.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
65 using std::runtime_error;
67 using boost::shared_ptr;
68 using boost::optional;
69 using boost::function;
71 /** @param s Number of seconds to sleep for */
73 dcpomatic_sleep_seconds (int s)
79 dcpomatic_sleep_milliseconds (int ms)
84 /** @return A string of CPU information (model name etc.) */
91 size_t N = sizeof (buffer);
92 if (sysctlbyname ("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
100 boost::filesystem::path
101 directory_containing_executable ()
103 #if BOOST_VERSION >= 106100
104 return boost::dll::program_location().parent_path();
106 uint32_t size = 1024;
108 if (_NSGetExecutablePath (buffer, &size)) {
109 throw runtime_error ("_NSGetExecutablePath failed");
112 boost::filesystem::path path (buffer);
113 path = boost::filesystem::canonical (path);
114 return path.parent_path ();
119 boost::filesystem::path
122 return directory_containing_executable().parent_path() / "Resources";
126 boost::filesystem::path
129 return resources_path() / "xsd";
133 boost::filesystem::path
136 return resources_path() / "tags";
141 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
143 boost::filesystem::path path = directory_containing_executable () / "ffprobe";
145 string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
146 LOG_GENERAL (N_("Probing with %1"), ffprobe);
147 system (ffprobe.c_str ());
151 list<pair<string, string> >
154 list<pair<string, string> > m;
158 boost::filesystem::path
161 return directory_containing_executable() / "openssl";
165 #ifdef DCPOMATIC_DISK
166 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
167 boost::filesystem::path
170 return directory_containing_executable() / "dcpomatic2_disk_writer";
174 /* Apparently there is no way to create an ofstream using a UTF-8
175 filename under Windows. We are hence reduced to using fopen
179 fopen_boost (boost::filesystem::path p, string t)
181 return fopen (p.c_str(), t.c_str ());
185 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
187 return fseek (stream, offset, whence);
198 boost::mutex::scoped_lock lm (_mutex);
199 IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
204 boost::mutex::scoped_lock lm (_mutex);
205 IOPMAssertionRelease (_assertion_id);
209 start_tool (string executable, string app)
211 boost::filesystem::path exe_path = directory_containing_executable();
212 exe_path = exe_path.parent_path (); // MacOS
213 exe_path = exe_path.parent_path (); // Contents
214 exe_path = exe_path.parent_path (); // DCP-o-matic.app
215 exe_path = exe_path.parent_path (); // Applications
217 exe_path /= "Contents";
219 exe_path /= executable;
223 LOG_GENERAL ("start_tool %1 %2 with path %3", executable, app, exe_path.string());
224 int const r = system (exe_path.string().c_str());
225 exit (WEXITSTATUS (r));
226 } else if (pid == -1) {
227 LOG_ERROR_NC("Fork failed in start_tool");
233 start_batch_converter ()
235 start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
242 start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
249 return (uint64_t) pthread_self ();
253 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
255 return avio_open (s, file.c_str(), flags);
258 boost::filesystem::path
261 return getenv("HOME");
265 command_and_read (string)
270 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
274 /* I'm assuming nobody does this on OS X */
278 static optional<string>
279 get_vendor (CFDictionaryRef& description)
281 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
283 return optional<string>();
286 string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
287 boost::algorithm::trim (s);
291 static optional<string>
292 get_model (CFDictionaryRef& description)
294 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
296 return optional<string>();
299 string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
300 boost::algorithm::trim (s);
306 bool real; ///< true for a "real" disk, false for a synthesized APFS one
307 std::string prt; ///< "PRT" entry from the media path
310 static optional<MediaPath>
311 analyse_media_path (CFDictionaryRef& description)
313 using namespace boost::algorithm;
315 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
317 LOG_DISK_NC("There is no MediaPathKey");
318 return optional<MediaPath>();
321 string path(CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8));
322 LOG_DISK("MediaPathKey is %1", path);
324 if (path.find("/IOHDIXController") != string::npos) {
325 /* This is a disk image, so we completely ignore it */
326 LOG_DISK_NC("Ignoring this as it seems to be a disk image");
327 return optional<MediaPath>();
331 if (starts_with(path, "IODeviceTree:")) {
333 } else if (starts_with(path, "IOService:")) {
336 return optional<MediaPath>();
340 split(bits, path, boost::is_any_of("/"));
341 BOOST_FOREACH (string i, bits) {
342 if (starts_with(i, "PRT")) {
351 is_whole_drive (DADiskRef& disk)
353 io_service_t service = DADiskCopyIOMedia (disk);
354 CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
355 bool whole_media = false;
356 if (whole_media_ref) {
357 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
358 CFRelease (whole_media_ref);
360 IOObjectRelease (service);
364 static optional<boost::filesystem::path>
365 mount_point (CFDictionaryRef& description)
367 CFURLRef volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
368 char mount_path_buffer[1024];
369 if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
370 return boost::optional<boost::filesystem::path>();
372 return boost::filesystem::path(mount_path_buffer);
375 /* Here follows some rather intricate and (probably) fragile code to find the list of available
376 * "real" drives on macOS that we might want to write a DCP to.
378 * We use the Disk Arbitration framework to give us a series of mount_points (/dev/disk0, /dev/disk1,
379 * /dev/disk1s1 and so on) and we use the API to gather useful information about these mount_points into
380 * a vector of Disk structs.
382 * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
383 * user, with details of whether those drives are currently mounted or not.
385 * At the basic level we find the "disk"-level mount_points, looking at whether any of their partitions are mounted.
387 * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
388 * reflect data in `real' partitions. So, for example, we might have a real (physical) drive /dev/disk2 with
389 * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
390 * which are mounted. /dev/disk2s2 is not considered to be mounted, in this case. So we need to know that
391 * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are. In order to do
392 * this I am picking out what looks like a suitable identifier prefixed with PRT from the MediaContentKey.
393 * If disk2s2 and disk3 have the same PRT code I am assuming they are linked.
395 * Lots of this is guesswork and may be broken. In my defence the documentation that I have been able to
396 * unearth is, to put it impolitely, crap.
402 optional<string> vendor;
403 optional<string> model;
407 vector<boost::filesystem::path> mount_points;
412 disk_appeared (DADiskRef disk, void* context)
414 const char* bsd_name = DADiskGetBSDName (disk);
418 LOG_DISK("%1 appeared", bsd_name);
422 this_disk.mount_point = string("/dev/") + bsd_name;
424 CFDictionaryRef description = DADiskCopyDescription (disk);
426 this_disk.vendor = get_vendor (description);
427 this_disk.model = get_model (description);
428 LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
430 optional<MediaPath> media_path = analyse_media_path (description);
432 LOG_DISK("Finding media path for %1 failed", bsd_name);
436 this_disk.real = media_path->real;
437 this_disk.prt = media_path->prt;
438 this_disk.whole = is_whole_drive (disk);
439 optional<boost::filesystem::path> mp = mount_point (description);
441 this_disk.mount_points.push_back (*mp);
445 "%1 prt %2 whole %3 mounted %4",
446 this_disk.real ? "Real" : "Synth",
448 this_disk.whole ? "whole" : "part",
449 mp ? ("mounted at " + mp->string()) : "unmounted"
452 CFNumberGetValue ((CFNumberRef) CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey), kCFNumberLongType, &this_disk.size);
453 CFRelease (description);
455 reinterpret_cast<vector<Disk>*>(context)->push_back(this_disk);
461 using namespace boost::algorithm;
464 DASessionRef session = DASessionCreate(kCFAllocatorDefault);
466 return vector<Drive>();
469 DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
470 CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
471 DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
472 CFRunLoopStop (run_loop);
473 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
474 DAUnregisterCallback(session, (void *) disk_appeared, &disks);
477 /* Mark disks containing mounted partitions as themselves mounted */
478 BOOST_FOREACH (Disk& i, disks) {
482 BOOST_FOREACH (Disk& j, disks) {
483 if (!j.mount_points.empty() && starts_with(j.mount_point, i.mount_point)) {
484 LOG_DISK("Marking %1 as mounted because %2 is", i.mount_point, j.mount_point);
485 std::copy(j.mount_points.begin(), j.mount_points.end(), back_inserter(i.mount_points));
490 /* Make a map of the PRT codes and mount points of mounted, synthesized disks */
491 map<string, vector<boost::filesystem::path> > mounted_synths;
492 BOOST_FOREACH (Disk& i, disks) {
493 if (!i.real && !i.mount_points.empty()) {
494 LOG_DISK("Found a mounted synth %1 with %2", i.mount_point, i.prt);
495 mounted_synths[i.prt] = i.mount_points;
499 /* Mark containers of those mounted synths as themselves mounted */
500 BOOST_FOREACH (Disk& i, disks) {
502 map<string, vector<boost::filesystem::path> >::const_iterator j = mounted_synths.find(i.prt);
503 if (j != mounted_synths.end()) {
504 LOG_DISK("Marking %1 (%2) as mounted because it contains a mounted synth", i.mount_point, i.prt);
505 std::copy(j->second.begin(), j->second.end(), back_inserter(i.mount_points));
510 vector<Drive> drives;
511 BOOST_FOREACH (Disk& i, disks) {
513 /* A whole disk that is not a container for a mounted synth */
514 drives.push_back(Drive(i.mount_point, i.mount_points, i.size, i.vendor, i.model));
515 LOG_DISK_NC(drives.back().log_summary());
522 boost::filesystem::path
525 boost::filesystem::path p;
526 p /= g_get_home_dir ();
529 p /= "com.dcpomatic";
535 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
537 LOG_DISK_NC("Unmount finished");
538 bool* success = reinterpret_cast<bool*> (context);
540 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
543 LOG_DISK_NC("Successful");
552 LOG_DISK_NC("Unmount operation started");
554 DASessionRef session = DASessionCreate(kCFAllocatorDefault);
559 DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
563 LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
564 bool success = false;
565 DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &success);
568 CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
569 DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
570 CFRunLoopStop (run_loop);
571 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, 0);
574 LOG_DISK_NC("End of unmount");
580 disk_write_finished ()
587 make_foreground_application ()
589 ProcessSerialNumber serial;
590 DCPOMATIC_DISABLE_WARNINGS
591 GetCurrentProcess (&serial);
592 DCPOMATIC_ENABLE_WARNINGS
593 TransformProcessType (&serial, kProcessTransformToForegroundApplication);