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/regex.hpp>
35 #if BOOST_VERSION >= 106100
36 #include <boost/dll/runtime_symbol_info.hpp>
38 #include <ApplicationServices/ApplicationServices.h>
39 #include <sys/sysctl.h>
40 #include <mach-o/dyld.h>
41 #include <IOKit/pwr_mgt/IOPMLib.h>
42 #include <IOKit/storage/IOMedia.h>
43 #include <DiskArbitration/DADisk.h>
44 #include <DiskArbitration/DiskArbitration.h>
45 #include <CoreFoundation/CFURL.h>
46 #include <sys/types.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
64 using std::runtime_error;
66 using std::shared_ptr;
67 using boost::optional;
68 using boost::function;
70 /** @param s Number of seconds to sleep for */
72 dcpomatic_sleep_seconds (int s)
78 dcpomatic_sleep_milliseconds (int ms)
83 /** @return A string of CPU information (model name etc.) */
90 size_t N = sizeof (buffer);
91 if (sysctlbyname ("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
99 boost::filesystem::path
100 directory_containing_executable ()
102 #if BOOST_VERSION >= 106100
103 return boost::dll::program_location().parent_path();
105 uint32_t size = 1024;
107 if (_NSGetExecutablePath (buffer, &size)) {
108 throw runtime_error ("_NSGetExecutablePath failed");
111 boost::filesystem::path path (buffer);
112 path = boost::filesystem::canonical (path);
113 return path.parent_path ();
118 boost::filesystem::path
121 return directory_containing_executable().parent_path() / "Resources";
125 boost::filesystem::path
128 return resources_path() / "xsd";
132 boost::filesystem::path
135 return resources_path() / "tags";
140 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
142 boost::filesystem::path path = directory_containing_executable () / "ffprobe";
144 string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
145 LOG_GENERAL (N_("Probing with %1"), ffprobe);
146 system (ffprobe.c_str ());
150 list<pair<string, string> >
153 list<pair<string, string> > m;
157 boost::filesystem::path
160 return directory_containing_executable() / "openssl";
164 #ifdef DCPOMATIC_DISK
165 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
166 boost::filesystem::path
169 return directory_containing_executable() / "dcpomatic2_disk_writer";
173 /* Apparently there is no way to create an ofstream using a UTF-8
174 filename under Windows. We are hence reduced to using fopen
178 fopen_boost (boost::filesystem::path p, string t)
180 return fopen (p.c_str(), t.c_str ());
184 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
186 return fseek (stream, offset, whence);
197 boost::mutex::scoped_lock lm (_mutex);
198 IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
203 boost::mutex::scoped_lock lm (_mutex);
204 IOPMAssertionRelease (_assertion_id);
208 start_tool (string executable, string app)
210 boost::filesystem::path exe_path = directory_containing_executable();
211 exe_path = exe_path.parent_path (); // Contents
212 exe_path = exe_path.parent_path (); // DCP-o-matic 2.app
213 exe_path = exe_path.parent_path (); // Applications
215 exe_path /= "Contents";
217 exe_path /= executable;
221 LOG_GENERAL ("start_tool %1 %2 with path %3", executable, app, exe_path.string());
222 int const r = system (exe_path.string().c_str());
223 exit (WEXITSTATUS (r));
224 } else if (pid == -1) {
225 LOG_ERROR_NC("Fork failed in start_tool");
231 start_batch_converter ()
233 start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
240 start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
247 return (uint64_t) pthread_self ();
251 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
253 return avio_open (s, file.c_str(), flags);
256 boost::filesystem::path
259 return getenv("HOME");
262 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
266 /* I'm assuming nobody does this on OS X */
270 static optional<string>
271 get_vendor (CFDictionaryRef& description)
273 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
278 auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
284 boost::algorithm::trim (s);
288 static optional<string>
289 get_model (CFDictionaryRef& description)
291 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
296 auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
302 boost::algorithm::trim (s);
308 bool real; ///< true for a "real" disk, false for a synthesized APFS one
309 std::string prt; ///< "PRT" entry from the media path
312 static optional<MediaPath>
313 analyse_media_path (CFDictionaryRef& description)
315 using namespace boost::algorithm;
317 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
319 LOG_DISK_NC("There is no MediaPathKey (no dictionary value)");
323 auto path_key_cstr = CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8);
324 if (!path_key_cstr) {
325 LOG_DISK_NC("There is no MediaPathKey (no cstring)");
329 string path(path_key_cstr);
330 LOG_DISK("MediaPathKey is %1", path);
332 if (path.find("/IOHDIXController") != string::npos) {
333 /* This is a disk image, so we completely ignore it */
334 LOG_DISK_NC("Ignoring this as it seems to be a disk image");
339 if (starts_with(path, "IODeviceTree:")) {
341 } else if (starts_with(path, "IOService:")) {
348 split(bits, path, boost::is_any_of("/"));
350 if (starts_with(i, "PRT")) {
359 is_whole_drive (DADiskRef& disk)
361 io_service_t service = DADiskCopyIOMedia (disk);
362 CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
363 bool whole_media = false;
364 if (whole_media_ref) {
365 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
366 CFRelease (whole_media_ref);
368 IOObjectRelease (service);
372 static optional<boost::filesystem::path>
373 mount_point (CFDictionaryRef& description)
375 auto volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
376 if (!volume_path_key) {
380 char mount_path_buffer[1024];
381 if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
384 return boost::filesystem::path(mount_path_buffer);
387 /* Here follows some rather intricate and (probably) fragile code to find the list of available
388 * "real" drives on macOS that we might want to write a DCP to.
390 * We use the Disk Arbitration framework to give us a series of mount_points (/dev/disk0, /dev/disk1,
391 * /dev/disk1s1 and so on) and we use the API to gather useful information about these mount_points into
392 * a vector of Disk structs.
394 * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
395 * user, with details of whether those drives are currently mounted or not.
397 * At the basic level we find the "disk"-level mount_points, looking at whether any of their partitions are mounted.
399 * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
400 * reflect data in `real' partitions. So, for example, we might have a real (physical) drive /dev/disk2 with
401 * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
402 * which are mounted. /dev/disk2s2 is not considered to be mounted, in this case. So we need to know that
403 * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are. In order to do
404 * this I am picking out what looks like a suitable identifier prefixed with PRT from the MediaContentKey.
405 * If disk2s2 and disk3 have the same PRT code I am assuming they are linked.
407 * Lots of this is guesswork and may be broken. In my defence the documentation that I have been able to
408 * unearth is, to put it impolitely, crap.
414 optional<string> vendor;
415 optional<string> model;
419 vector<boost::filesystem::path> mount_points;
424 disk_appeared (DADiskRef disk, void* context)
426 auto bsd_name = DADiskGetBSDName (disk);
428 LOG_DISK_NC("Disk with no BSDName appeared");
431 LOG_DISK("%1 appeared", bsd_name);
435 this_disk.mount_point = string("/dev/") + bsd_name;
436 LOG_DISK("Mount point is %1", this_disk.mount_point);
438 CFDictionaryRef description = DADiskCopyDescription (disk);
440 this_disk.vendor = get_vendor (description);
441 this_disk.model = get_model (description);
442 LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
444 auto media_path = analyse_media_path (description);
446 LOG_DISK("Finding media path for %1 failed", bsd_name);
450 this_disk.real = media_path->real;
451 this_disk.prt = media_path->prt;
452 this_disk.whole = is_whole_drive (disk);
453 auto mp = mount_point (description);
455 this_disk.mount_points.push_back (*mp);
459 "%1 prt %2 whole %3 mounted %4",
460 this_disk.real ? "Real" : "Synth",
462 this_disk.whole ? "whole" : "part",
463 mp ? ("mounted at " + mp->string()) : "unmounted"
466 auto media_size_cstr = CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey);
467 if (!media_size_cstr) {
468 LOG_DISK_NC("Could not read media size");
472 CFNumberGetValue ((CFNumberRef) media_size_cstr, kCFNumberLongType, &this_disk.size);
473 CFRelease (description);
475 reinterpret_cast<vector<Disk>*>(context)->push_back(this_disk);
481 using namespace boost::algorithm;
484 DASessionRef session = DASessionCreate(kCFAllocatorDefault);
489 DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
490 CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
491 DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
492 CFRunLoopStop (run_loop);
493 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
494 DAUnregisterCallback(session, (void *) disk_appeared, &disks);
497 /* Mark disks containing mounted partitions as themselves mounted */
498 for (auto& i: disks) {
502 for (auto& j: disks) {
503 if (!j.mount_points.empty() && starts_with(j.mount_point, i.mount_point)) {
504 LOG_DISK("Marking %1 as mounted because %2 is", i.mount_point, j.mount_point);
505 std::copy(j.mount_points.begin(), j.mount_points.end(), back_inserter(i.mount_points));
510 /* Make a map of the PRT codes and mount points of mounted, synthesized disks */
511 map<string, vector<boost::filesystem::path> > mounted_synths;
512 for (auto& i: disks) {
513 if (!i.real && !i.mount_points.empty()) {
514 LOG_DISK("Found a mounted synth %1 with %2", i.mount_point, i.prt);
515 mounted_synths[i.prt] = i.mount_points;
519 /* Mark containers of those mounted synths as themselves mounted */
520 for (auto& i: disks) {
522 auto j = mounted_synths.find(i.prt);
523 if (j != mounted_synths.end()) {
524 LOG_DISK("Marking %1 (%2) as mounted because it contains a mounted synth", i.mount_point, i.prt);
525 std::copy(j->second.begin(), j->second.end(), back_inserter(i.mount_points));
530 vector<Drive> drives;
531 for (auto& i: disks) {
533 /* A whole disk that is not a container for a mounted synth */
534 drives.push_back(Drive(i.mount_point, i.mount_points, i.size, i.vendor, i.model));
535 LOG_DISK_NC(drives.back().log_summary());
542 boost::filesystem::path
545 boost::filesystem::path p;
546 p /= g_get_home_dir ();
549 p /= "com.dcpomatic";
555 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
557 LOG_DISK_NC("Unmount finished");
558 bool* success = reinterpret_cast<bool*> (context);
560 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
563 LOG_DISK_NC("Successful");
572 LOG_DISK_NC("Unmount operation started");
574 DASessionRef session = DASessionCreate(kCFAllocatorDefault);
579 DADiskRef disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
583 LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
584 bool success = false;
585 DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &success);
588 CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
589 DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
590 CFRunLoopStop (run_loop);
591 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, 0);
594 LOG_DISK_NC("End of unmount");
600 disk_write_finished ()
607 make_foreground_application ()
609 ProcessSerialNumber serial;
610 DCPOMATIC_DISABLE_WARNINGS
611 GetCurrentProcess (&serial);
612 DCPOMATIC_ENABLE_WARNINGS
613 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
618 dcpomatic::get_process_id ()
620 return dcp::raw_convert<string>(getpid());