Add disk writer tool.
[dcpomatic.git] / src / lib / cross_osx.cc
1 /*
2     Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
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.
10
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.
15
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/>.
18
19 */
20
21 #include "cross.h"
22 #include "compose.hpp"
23 #include "log.h"
24 #include "dcpomatic_log.h"
25 #include "config.h"
26 #include "exceptions.h"
27 #include <dcp/raw_convert.h>
28 #include <glib.h>
29 extern "C" {
30 #include <libavformat/avio.h>
31 }
32 #include <boost/algorithm/string.hpp>
33 #include <boost/foreach.hpp>
34 #include <boost/dll/runtime_symbol_info.hpp>
35 #include <boost/regex.hpp>
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>
44 #include <ifaddrs.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <fstream>
48 #include <cstring>
49
50 #include "i18n.h"
51
52 using std::pair;
53 using std::list;
54 using std::ifstream;
55 using std::string;
56 using std::wstring;
57 using std::make_pair;
58 using std::vector;
59 using std::cerr;
60 using std::cout;
61 using std::runtime_error;
62 using boost::shared_ptr;
63 using boost::optional;
64
65 /** @param s Number of seconds to sleep for */
66 void
67 dcpomatic_sleep_seconds (int s)
68 {
69         sleep (s);
70 }
71
72 void
73 dcpomatic_sleep_milliseconds (int ms)
74 {
75         usleep (ms * 1000);
76 }
77
78 /** @return A string of CPU information (model name etc.) */
79 string
80 cpu_info ()
81 {
82         string info;
83
84         char buffer[64];
85         size_t N = sizeof (buffer);
86         if (sysctlbyname ("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
87                 info = buffer;
88         }
89
90         return info;
91 }
92
93 /** @return Path of the Contents directory in the .app */
94 boost::filesystem::path
95 app_contents ()
96 {
97         return boost::dll::program_location().parent_path().parent_path();
98 }
99
100 boost::filesystem::path
101 shared_path ()
102 {
103         return app_contents() / "Resources";
104 }
105
106 void
107 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
108 {
109         boost::filesystem::path path = app_contents();
110         path /= "MacOS";
111         path /= "ffprobe";
112
113         string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
114         LOG_GENERAL (N_("Probing with %1"), ffprobe);
115         system (ffprobe.c_str ());
116 }
117
118 list<pair<string, string> >
119 mount_info ()
120 {
121         list<pair<string, string> > m;
122         return m;
123 }
124
125 boost::filesystem::path
126 openssl_path ()
127 {
128         boost::filesystem::path path = app_contents();
129         path /= "MacOS";
130         path /= "openssl";
131         return path;
132 }
133
134 boost::filesystem::path
135 disk_writer_path ()
136 {
137         boost::filesystem::path path = app_contents();
138         path /= "MacOS";
139         path /= "dcpomatic2_disk_writer";
140         return path;
141 }
142
143 /* Apparently there is no way to create an ofstream using a UTF-8
144    filename under Windows.  We are hence reduced to using fopen
145    with this wrapper.
146 */
147 FILE *
148 fopen_boost (boost::filesystem::path p, string t)
149 {
150         return fopen (p.c_str(), t.c_str ());
151 }
152
153 int
154 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
155 {
156         return fseek (stream, offset, whence);
157 }
158
159 void
160 Waker::nudge ()
161 {
162
163 }
164
165 Waker::Waker ()
166 {
167         boost::mutex::scoped_lock lm (_mutex);
168         /* We should use this */
169         // IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
170         /* but it's not available on 10.5, so we use this */
171         IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &_assertion_id);
172 }
173
174 Waker::~Waker ()
175 {
176         boost::mutex::scoped_lock lm (_mutex);
177         IOPMAssertionRelease (_assertion_id);
178 }
179
180 void
181 start_tool (boost::filesystem::path dcpomatic, string executable, string app)
182 {
183         boost::filesystem::path batch = dcpomatic.parent_path ();
184         batch = batch.parent_path (); // MacOS
185         batch = batch.parent_path (); // Contents
186         batch = batch.parent_path (); // DCP-o-matic.app
187         batch = batch.parent_path (); // Applications
188         batch /= app;
189         batch /= "Contents";
190         batch /= "MacOS";
191         batch /= executable;
192
193         pid_t pid = fork ();
194         if (pid == 0) {
195                 int const r = system (batch.string().c_str());
196                 exit (WEXITSTATUS (r));
197         }
198 }
199
200 void
201 start_batch_converter (boost::filesystem::path dcpomatic)
202 {
203         start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
204 }
205
206 void
207 start_player (boost::filesystem::path dcpomatic)
208 {
209         start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
210 }
211
212 uint64_t
213 thread_id ()
214 {
215         return (uint64_t) pthread_self ();
216 }
217
218 int
219 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
220 {
221         return avio_open (s, file.c_str(), flags);
222 }
223
224 boost::filesystem::path
225 home_directory ()
226 {
227                 return getenv("HOME");
228 }
229
230 string
231 command_and_read (string cmd)
232 {
233         return "";
234 }
235
236 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
237 bool
238 running_32_on_64 ()
239 {
240         /* I'm assuming nobody does this on OS X */
241         return false;
242 }
243
244 static optional<string>
245 get_vendor (CFDictionaryRef& description)
246 {
247         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
248         if (!str) {
249                 return optional<string>();
250         }
251
252         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
253         boost::algorithm::trim (s);
254         return s;
255 }
256
257 static optional<string>
258 get_model (CFDictionaryRef& description)
259 {
260         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
261         if (!str) {
262                 return optional<string>();
263         }
264
265         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
266         boost::algorithm::trim (s);
267         return s;
268 }
269
270 struct MediaPath
271 {
272         bool real;       ///< true for a "real" disk, false for a synthesized APFS one
273         std::string prt; ///< "PRT" entry from the media path
274 };
275
276 static optional<MediaPath>
277 analyse_media_path (CFDictionaryRef& description)
278 {
279         using namespace boost::algorithm;
280
281         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
282         if (!str) {
283                 return optional<MediaPath>();
284         }
285
286         string path(CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8));
287         MediaPath mp;
288         if (starts_with(path, "IODeviceTree:")) {
289                 mp.real = true;
290         } else if (starts_with(path, "IOService:")) {
291                 mp.real = false;
292         } else {
293                 return optional<MediaPath>();
294         }
295
296         vector<string> bits;
297         split(bits, path, boost::is_any_of("/"));
298         BOOST_FOREACH (string i, bits) {
299                 if (starts_with(i, "PRT")) {
300                         mp.prt = i;
301                 }
302         }
303
304         return mp;
305 }
306
307 static bool
308 is_whole_drive (DADiskRef& disk)
309 {
310         io_service_t service = DADiskCopyIOMedia (disk);
311         CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
312         bool whole_media = false;
313         if (whole_media_ref) {
314                 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
315                 CFRelease (whole_media_ref);
316         }
317         IOObjectRelease (service);
318         return whole_media;
319 }
320
321 static bool
322 is_mounted (CFDictionaryRef& description)
323 {
324         CFURLRef volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
325         char mount_path_buffer[1024];
326         return CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer));
327 }
328
329 /* Here follows some rather intricate and (probably) fragile code to find the list of available
330  * "real" drives on macOS that we might want to write a DCP to.
331  *
332  * We use the Disk Arbitration framework to give us a series of devices (/dev/disk0, /dev/disk1,
333  * /dev/disk1s1 and so on) and we use the API to gather useful information about these devices into
334  * a vector of Disk structs.
335  *
336  * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
337  * user, with details of whether those drives are currently mounted or not.
338  *
339  * At the basic level we find the "disk"-level devices, looking at whether any of their partitions are mounted.
340  *
341  * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
342  * reflect data in `real' partitions.  So, for example, we might have a real (physical) drive /dev/disk2 with
343  * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
344  * which are mounted.  /dev/disk2s2 is not considered to be mounted, in this case.  So we need to know that
345  * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are.  In order to do
346  * this I am picking out what looks like a suitable identifier prefixed with PRT from the MediaContentKey.
347  * If disk2s2 and disk3 have the same PRT code I am assuming they are linked.
348  *
349  * Lots of this is guesswork and may be broken.  In my defence the documentation that I have been able to
350  * unearth is, to put it impolitely, crap.
351  */
352
353 struct Disk
354 {
355         string device;
356         optional<string> vendor;
357         optional<string> model;
358         bool real;
359         string prt;
360         bool whole;
361         bool mounted;
362         unsigned long size;
363 };
364
365 static void
366 disk_appeared (DADiskRef disk, void* context)
367 {
368         const char* bsd_name = DADiskGetBSDName (disk);
369         if (!bsd_name) {
370                 return;
371         }
372         LOG_DISK("%1 appeared", bsd_name);
373
374         Disk this_disk;
375
376         this_disk.device = string("/dev/") + bsd_name;
377
378         CFDictionaryRef description = DADiskCopyDescription (disk);
379
380         this_disk.vendor = get_vendor (description);
381         this_disk.model = get_model (description);
382         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
383
384         optional<MediaPath> media_path = analyse_media_path (description);
385         if (!media_path) {
386                 LOG_DISK("Finding media path for %1 failed", bsd_name);
387                 return;
388         }
389
390         this_disk.real = media_path->real;
391         this_disk.prt = media_path->prt;
392         this_disk.whole = is_whole_drive (disk);
393         this_disk.mounted = is_mounted (description);
394         LOG_DISK("%1 prt %2 whole %3 mounted %4", this_disk.real ? "Real" : "Synth", this_disk.prt, this_disk.whole ? "whole" : "part", this_disk.mounted ? "mounted" : "unmounted");
395
396         CFNumberGetValue ((CFNumberRef) CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey), kCFNumberLongType, &this_disk.size);
397         CFRelease (description);
398
399         reinterpret_cast<vector<Disk>*>(context)->push_back(this_disk);
400 }
401
402 vector<Drive>
403 get_drives ()
404 {
405         using namespace boost::algorithm;
406         vector<Disk> disks;
407
408         DASessionRef session = DASessionCreate(kCFAllocatorDefault);
409         if (!session) {
410                 return vector<Drive>();
411         }
412
413         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
414         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
415         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
416         CFRunLoopStop (run_loop);
417         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
418         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
419         CFRelease(session);
420
421         /* Mark disks containing mounted partitions as themselves mounted */
422         BOOST_FOREACH (Disk& i, disks) {
423                 if (!i.whole) {
424                         continue;
425                 }
426                 BOOST_FOREACH (Disk& j, disks) {
427                         if (j.mounted && starts_with(j.device, i.device)) {
428                                 LOG_DISK("Marking %1 as mounted because %2 is", i.device, j.device);
429                                 i.mounted = true;
430                         }
431                 }
432         }
433
434         /* Make a list of the PRT codes of mounted, synthesized disks */
435         vector<string> mounted_synths;
436         BOOST_FOREACH (Disk& i, disks) {
437                 if (!i.real && i.mounted) {
438                         LOG_DISK("Found a mounted synth %1 with %2", i.device, i.prt);
439                         mounted_synths.push_back (i.prt);
440                 }
441         }
442
443         /* Mark containers of those mounted synths as themselves mounted */
444         BOOST_FOREACH (Disk& i, disks) {
445                 if (i.real && find(mounted_synths.begin(), mounted_synths.end(), i.prt) != mounted_synths.end()) {
446                         LOG_DISK("Marking %1 (%2) as mounted because it contains a mounted synth", i.device, i.prt);
447                         i.mounted = true;
448                 }
449         }
450
451         vector<Drive> drives;
452         BOOST_FOREACH (Disk& i, disks) {
453                 if (i.whole) {
454                         /* A whole disk that is not a container for a mounted synth */
455                         LOG_DISK("Adding drive: %1 %2 %3 %4 %5", i.device, i.size, i.mounted ? "mounted" : "unmounted", i.vendor.get_value_or("[none]"), i.model.get_value_or("[none]"));
456                         drives.push_back(Drive(i.device, i.size, i.mounted, i.vendor, i.model));
457                 }
458         }
459         return drives;
460 }
461
462 boost::filesystem::path
463 config_path ()
464 {
465         boost::filesystem::path p;
466         p /= g_get_home_dir ();
467         p /= "Library";
468         p /= "Preferences";
469         p /= "com.dcpomatic";
470         p /= "2";
471         return p;
472 }