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"
29 #include <dcp/raw_convert.h>
32 #include <libavformat/avio.h>
34 #include <boost/algorithm/string.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 std::shared_ptr;
68 using boost::optional;
72 /** @param s Number of seconds to sleep for */
74 dcpomatic_sleep_seconds (int s)
81 dcpomatic_sleep_milliseconds (int ms)
87 /** @return A string of CPU information (model name etc.) */
94 size_t N = sizeof (buffer);
95 if (sysctlbyname("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
103 boost::filesystem::path
104 directory_containing_executable ()
106 return boost::filesystem::canonical(boost::dll::program_location()).parent_path();
110 boost::filesystem::path
113 return directory_containing_executable().parent_path() / "Resources";
117 boost::filesystem::path
118 libdcp_resources_path ()
120 return resources_path();
125 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
127 auto path = directory_containing_executable () / "ffprobe";
129 string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
130 LOG_GENERAL (N_("Probing with %1"), ffprobe);
131 system (ffprobe.c_str ());
136 list<pair<string, string>>
143 boost::filesystem::path
146 return directory_containing_executable() / "openssl";
150 #ifdef DCPOMATIC_DISK
151 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
152 boost::filesystem::path
155 return directory_containing_executable() / "dcpomatic2_disk_writer";
160 /* Apparently there is no way to create an ofstream using a UTF-8
161 filename under Windows. We are hence reduced to using fopen
165 fopen_boost (boost::filesystem::path p, string t)
167 return fopen (p.c_str(), t.c_str());
172 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
174 return fseek (stream, offset, whence);
187 boost::mutex::scoped_lock lm (_mutex);
188 IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
194 boost::mutex::scoped_lock lm (_mutex);
195 IOPMAssertionRelease (_assertion_id);
200 start_tool (string executable, string app)
202 auto exe_path = directory_containing_executable();
203 exe_path = exe_path.parent_path(); // Contents
204 exe_path = exe_path.parent_path(); // DCP-o-matic 2.app
205 exe_path = exe_path.parent_path(); // Applications
207 exe_path /= "Contents";
209 exe_path /= executable;
213 LOG_GENERAL ("start_tool %1 %2 with path %3", executable, app, exe_path.string());
214 int const r = system (exe_path.string().c_str());
215 exit (WEXITSTATUS (r));
216 } else if (pid == -1) {
217 LOG_ERROR_NC("Fork failed in start_tool");
223 start_batch_converter ()
225 start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
232 start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
239 return (uint64_t) pthread_self ();
244 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
246 return avio_open (s, file.c_str(), flags);
250 boost::filesystem::path
253 return getenv("HOME");
257 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
261 /* I'm assuming nobody does this on OS X */
266 static optional<string>
267 get_vendor (CFDictionaryRef& description)
269 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
274 auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
280 boost::algorithm::trim (s);
285 static optional<string>
286 get_model (CFDictionaryRef& description)
288 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
293 auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
299 boost::algorithm::trim (s);
304 static optional<OSXMediaPath>
305 analyse_media_path (CFDictionaryRef& description)
307 using namespace boost::algorithm;
309 void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
311 LOG_DISK_NC("There is no MediaPathKey (no dictionary value)");
315 auto path_key_cstr = CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8);
316 if (!path_key_cstr) {
317 LOG_DISK_NC("There is no MediaPathKey (no cstring)");
321 string path(path_key_cstr);
322 LOG_DISK("MediaPathKey is %1", path);
323 return analyse_osx_media_path (path);
328 is_whole_drive (DADiskRef& disk)
330 io_service_t service = DADiskCopyIOMedia (disk);
331 CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
332 bool whole_media = false;
333 if (whole_media_ref) {
334 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
335 CFRelease (whole_media_ref);
337 IOObjectRelease (service);
342 static optional<boost::filesystem::path>
343 mount_point (CFDictionaryRef& description)
345 auto volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
346 if (!volume_path_key) {
350 char mount_path_buffer[1024];
351 if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
354 return boost::filesystem::path(mount_path_buffer);
358 /* Here follows some rather intricate and (probably) fragile code to find the list of available
359 * "real" drives on macOS that we might want to write a DCP to.
361 * We use the Disk Arbitration framework to give us a series of mount_points (/dev/disk0, /dev/disk1,
362 * /dev/disk1s1 and so on) and we use the API to gather useful information about these mount_points into
363 * a vector of Disk structs.
365 * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
366 * user, with details of whether those drives are currently mounted or not.
368 * At the basic level we find the "disk"-level mount_points, looking at whether any of their partitions are mounted.
370 * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
371 * reflect data in `real' partitions. So, for example, we might have a real (physical) drive /dev/disk2 with
372 * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
373 * which are mounted. /dev/disk2s2 is not considered to be mounted, in this case. So we need to know that
374 * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are. In order to do
375 * this I am taking the first two parts of the IODeviceTree and seeing if they exist anywhere in a
376 * IOService identifier. If they do, I am assuming the IOService device is on the matching IODeviceTree device.
378 * Lots of this is guesswork and may be broken. In my defence the documentation that I have been able to
379 * unearth is, to put it impolitely, crap.
383 disk_appeared (DADiskRef disk, void* context)
385 auto bsd_name = DADiskGetBSDName (disk);
387 LOG_DISK_NC("Disk with no BSDName appeared");
390 LOG_DISK("%1 appeared", bsd_name);
394 this_disk.device = string("/dev/") + bsd_name;
395 LOG_DISK("Device is %1", this_disk.device);
397 CFDictionaryRef description = DADiskCopyDescription (disk);
399 this_disk.vendor = get_vendor (description);
400 this_disk.model = get_model (description);
401 LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
403 auto media_path = analyse_media_path (description);
405 LOG_DISK("Finding media path for %1 failed", bsd_name);
409 this_disk.media_path = *media_path;
410 this_disk.whole = is_whole_drive (disk);
411 auto mp = mount_point (description);
413 this_disk.mount_points.push_back (*mp);
417 "%1 %2 mounted at %3",
418 this_disk.media_path.real ? "Real" : "Synth",
419 this_disk.whole ? "whole" : "part",
420 mp ? mp->string() : "[nowhere]"
423 auto media_size_cstr = CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey);
424 if (!media_size_cstr) {
425 LOG_DISK_NC("Could not read media size");
429 CFNumberGetValue ((CFNumberRef) media_size_cstr, kCFNumberLongType, &this_disk.size);
430 CFRelease (description);
432 reinterpret_cast<vector<OSXDisk>*>(context)->push_back(this_disk);
439 using namespace boost::algorithm;
440 vector<OSXDisk> disks;
442 auto session = DASessionCreate(kCFAllocatorDefault);
447 DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
448 auto run_loop = CFRunLoopGetCurrent ();
449 DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
450 CFRunLoopStop (run_loop);
451 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
452 DAUnregisterCallback(session, (void *) disk_appeared, &disks);
455 return osx_disks_to_drives (disks);
459 boost::filesystem::path
460 config_path (optional<string> version)
462 boost::filesystem::path p;
463 p /= g_get_home_dir ();
466 p /= "com.dcpomatic";
475 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
477 LOG_DISK_NC("Unmount finished");
478 bool* success = reinterpret_cast<bool*> (context);
480 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
483 LOG_DISK_NC("Successful");
492 LOG_DISK_NC("Unmount operation started");
494 auto session = DASessionCreate(kCFAllocatorDefault);
499 auto disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
503 LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
504 bool success = false;
505 DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &success);
508 CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
509 DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
510 CFRunLoopStop (run_loop);
511 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, 0);
514 LOG_DISK_NC("End of unmount");
520 disk_write_finished ()
527 make_foreground_application ()
529 ProcessSerialNumber serial;
530 DCPOMATIC_DISABLE_WARNINGS
531 GetCurrentProcess (&serial);
532 DCPOMATIC_ENABLE_WARNINGS
533 TransformProcessType (&serial, kProcessTransformToForegroundApplication);
538 dcpomatic::get_process_id ()
540 return dcp::raw_convert<string>(getpid());
544 boost::filesystem::path
545 fix_long_path (boost::filesystem::path path)
552 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
554 int r = system (String::compose("open -R \"%1\"", select.string()).c_str());
555 return static_cast<bool>(WEXITSTATUS(r));