Add DCPOMATIC_DISK define and don't build stuff needing boost dll library if we don...
[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 #ifdef DCPOMATIC_DISK
135 boost::filesystem::path
136 disk_writer_path ()
137 {
138         boost::filesystem::path path = app_contents();
139         path /= "MacOS";
140         path /= "dcpomatic2_disk_writer";
141         return path;
142 }
143 #endif
144
145 /* Apparently there is no way to create an ofstream using a UTF-8
146    filename under Windows.  We are hence reduced to using fopen
147    with this wrapper.
148 */
149 FILE *
150 fopen_boost (boost::filesystem::path p, string t)
151 {
152         return fopen (p.c_str(), t.c_str ());
153 }
154
155 int
156 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
157 {
158         return fseek (stream, offset, whence);
159 }
160
161 void
162 Waker::nudge ()
163 {
164
165 }
166
167 Waker::Waker ()
168 {
169         boost::mutex::scoped_lock lm (_mutex);
170         /* We should use this */
171         // IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
172         /* but it's not available on 10.5, so we use this */
173         IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &_assertion_id);
174 }
175
176 Waker::~Waker ()
177 {
178         boost::mutex::scoped_lock lm (_mutex);
179         IOPMAssertionRelease (_assertion_id);
180 }
181
182 void
183 start_tool (boost::filesystem::path dcpomatic, string executable, string app)
184 {
185         boost::filesystem::path batch = dcpomatic.parent_path ();
186         batch = batch.parent_path (); // MacOS
187         batch = batch.parent_path (); // Contents
188         batch = batch.parent_path (); // DCP-o-matic.app
189         batch = batch.parent_path (); // Applications
190         batch /= app;
191         batch /= "Contents";
192         batch /= "MacOS";
193         batch /= executable;
194
195         pid_t pid = fork ();
196         if (pid == 0) {
197                 int const r = system (batch.string().c_str());
198                 exit (WEXITSTATUS (r));
199         }
200 }
201
202 void
203 start_batch_converter (boost::filesystem::path dcpomatic)
204 {
205         start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
206 }
207
208 void
209 start_player (boost::filesystem::path dcpomatic)
210 {
211         start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
212 }
213
214 uint64_t
215 thread_id ()
216 {
217         return (uint64_t) pthread_self ();
218 }
219
220 int
221 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
222 {
223         return avio_open (s, file.c_str(), flags);
224 }
225
226 boost::filesystem::path
227 home_directory ()
228 {
229                 return getenv("HOME");
230 }
231
232 string
233 command_and_read (string cmd)
234 {
235         return "";
236 }
237
238 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
239 bool
240 running_32_on_64 ()
241 {
242         /* I'm assuming nobody does this on OS X */
243         return false;
244 }
245
246 static optional<string>
247 get_vendor (CFDictionaryRef& description)
248 {
249         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
250         if (!str) {
251                 return optional<string>();
252         }
253
254         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
255         boost::algorithm::trim (s);
256         return s;
257 }
258
259 static optional<string>
260 get_model (CFDictionaryRef& description)
261 {
262         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
263         if (!str) {
264                 return optional<string>();
265         }
266
267         string s = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
268         boost::algorithm::trim (s);
269         return s;
270 }
271
272 struct MediaPath
273 {
274         bool real;       ///< true for a "real" disk, false for a synthesized APFS one
275         std::string prt; ///< "PRT" entry from the media path
276 };
277
278 static optional<MediaPath>
279 analyse_media_path (CFDictionaryRef& description)
280 {
281         using namespace boost::algorithm;
282
283         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
284         if (!str) {
285                 return optional<MediaPath>();
286         }
287
288         string path(CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8));
289         MediaPath mp;
290         if (starts_with(path, "IODeviceTree:")) {
291                 mp.real = true;
292         } else if (starts_with(path, "IOService:")) {
293                 mp.real = false;
294         } else {
295                 return optional<MediaPath>();
296         }
297
298         vector<string> bits;
299         split(bits, path, boost::is_any_of("/"));
300         BOOST_FOREACH (string i, bits) {
301                 if (starts_with(i, "PRT")) {
302                         mp.prt = i;
303                 }
304         }
305
306         return mp;
307 }
308
309 static bool
310 is_whole_drive (DADiskRef& disk)
311 {
312         io_service_t service = DADiskCopyIOMedia (disk);
313         CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
314         bool whole_media = false;
315         if (whole_media_ref) {
316                 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
317                 CFRelease (whole_media_ref);
318         }
319         IOObjectRelease (service);
320         return whole_media;
321 }
322
323 static bool
324 is_mounted (CFDictionaryRef& description)
325 {
326         CFURLRef volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
327         char mount_path_buffer[1024];
328         return CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer));
329 }
330
331 /* Here follows some rather intricate and (probably) fragile code to find the list of available
332  * "real" drives on macOS that we might want to write a DCP to.
333  *
334  * We use the Disk Arbitration framework to give us a series of devices (/dev/disk0, /dev/disk1,
335  * /dev/disk1s1 and so on) and we use the API to gather useful information about these devices into
336  * a vector of Disk structs.
337  *
338  * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
339  * user, with details of whether those drives are currently mounted or not.
340  *
341  * At the basic level we find the "disk"-level devices, looking at whether any of their partitions are mounted.
342  *
343  * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
344  * reflect data in `real' partitions.  So, for example, we might have a real (physical) drive /dev/disk2 with
345  * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
346  * which are mounted.  /dev/disk2s2 is not considered to be mounted, in this case.  So we need to know that
347  * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are.  In order to do
348  * this I am picking out what looks like a suitable identifier prefixed with PRT from the MediaContentKey.
349  * If disk2s2 and disk3 have the same PRT code I am assuming they are linked.
350  *
351  * Lots of this is guesswork and may be broken.  In my defence the documentation that I have been able to
352  * unearth is, to put it impolitely, crap.
353  */
354
355 struct Disk
356 {
357         string device;
358         optional<string> vendor;
359         optional<string> model;
360         bool real;
361         string prt;
362         bool whole;
363         bool mounted;
364         unsigned long size;
365 };
366
367 static void
368 disk_appeared (DADiskRef disk, void* context)
369 {
370         const char* bsd_name = DADiskGetBSDName (disk);
371         if (!bsd_name) {
372                 return;
373         }
374         LOG_DISK("%1 appeared", bsd_name);
375
376         Disk this_disk;
377
378         this_disk.device = string("/dev/") + bsd_name;
379
380         CFDictionaryRef description = DADiskCopyDescription (disk);
381
382         this_disk.vendor = get_vendor (description);
383         this_disk.model = get_model (description);
384         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
385
386         optional<MediaPath> media_path = analyse_media_path (description);
387         if (!media_path) {
388                 LOG_DISK("Finding media path for %1 failed", bsd_name);
389                 return;
390         }
391
392         this_disk.real = media_path->real;
393         this_disk.prt = media_path->prt;
394         this_disk.whole = is_whole_drive (disk);
395         this_disk.mounted = is_mounted (description);
396         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");
397
398         CFNumberGetValue ((CFNumberRef) CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey), kCFNumberLongType, &this_disk.size);
399         CFRelease (description);
400
401         reinterpret_cast<vector<Disk>*>(context)->push_back(this_disk);
402 }
403
404 vector<Drive>
405 get_drives ()
406 {
407         using namespace boost::algorithm;
408         vector<Disk> disks;
409
410         DASessionRef session = DASessionCreate(kCFAllocatorDefault);
411         if (!session) {
412                 return vector<Drive>();
413         }
414
415         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
416         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
417         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
418         CFRunLoopStop (run_loop);
419         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
420         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
421         CFRelease(session);
422
423         /* Mark disks containing mounted partitions as themselves mounted */
424         BOOST_FOREACH (Disk& i, disks) {
425                 if (!i.whole) {
426                         continue;
427                 }
428                 BOOST_FOREACH (Disk& j, disks) {
429                         if (j.mounted && starts_with(j.device, i.device)) {
430                                 LOG_DISK("Marking %1 as mounted because %2 is", i.device, j.device);
431                                 i.mounted = true;
432                         }
433                 }
434         }
435
436         /* Make a list of the PRT codes of mounted, synthesized disks */
437         vector<string> mounted_synths;
438         BOOST_FOREACH (Disk& i, disks) {
439                 if (!i.real && i.mounted) {
440                         LOG_DISK("Found a mounted synth %1 with %2", i.device, i.prt);
441                         mounted_synths.push_back (i.prt);
442                 }
443         }
444
445         /* Mark containers of those mounted synths as themselves mounted */
446         BOOST_FOREACH (Disk& i, disks) {
447                 if (i.real && find(mounted_synths.begin(), mounted_synths.end(), i.prt) != mounted_synths.end()) {
448                         LOG_DISK("Marking %1 (%2) as mounted because it contains a mounted synth", i.device, i.prt);
449                         i.mounted = true;
450                 }
451         }
452
453         vector<Drive> drives;
454         BOOST_FOREACH (Disk& i, disks) {
455                 if (i.whole) {
456                         /* A whole disk that is not a container for a mounted synth */
457                         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]"));
458                         drives.push_back(Drive(i.device, i.size, i.mounted, i.vendor, i.model));
459                 }
460         }
461         return drives;
462 }
463
464 boost::filesystem::path
465 config_path ()
466 {
467         boost::filesystem::path p;
468         p /= g_get_home_dir ();
469         p /= "Library";
470         p /= "Preferences";
471         p /= "com.dcpomatic";
472         p /= "2";
473         return p;
474 }