02f720fee421835f511924874036304b6767bba9
[dcpomatic.git] / src / lib / cross_osx.cc
1 /*
2     Copyright (C) 2012-2021 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
22 #include "cross.h"
23 #include "compose.hpp"
24 #include "log.h"
25 #include "dcpomatic_log.h"
26 #include "config.h"
27 #include "exceptions.h"
28 #include <dcp/raw_convert.h>
29 #include <glib.h>
30 extern "C" {
31 #include <libavformat/avio.h>
32 }
33 #include <boost/algorithm/string.hpp>
34 #include <boost/regex.hpp>
35 #if BOOST_VERSION >= 106100
36 #include <boost/dll/runtime_symbol_info.hpp>
37 #endif
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>
47 #include <ifaddrs.h>
48 #include <netinet/in.h>
49 #include <arpa/inet.h>
50 #include <fstream>
51 #include <cstring>
52
53 #include "i18n.h"
54
55
56 using std::pair;
57 using std::list;
58 using std::ifstream;
59 using std::string;
60 using std::make_pair;
61 using std::vector;
62 using std::cerr;
63 using std::cout;
64 using std::runtime_error;
65 using std::map;
66 using std::shared_ptr;
67 using boost::optional;
68 using std::function;
69
70
71 /** @param s Number of seconds to sleep for */
72 void
73 dcpomatic_sleep_seconds (int s)
74 {
75         sleep (s);
76 }
77
78
79 void
80 dcpomatic_sleep_milliseconds (int ms)
81 {
82         usleep (ms * 1000);
83 }
84
85
86 /** @return A string of CPU information (model name etc.) */
87 string
88 cpu_info ()
89 {
90         string info;
91
92         char buffer[64];
93         size_t N = sizeof (buffer);
94         if (sysctlbyname("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
95                 info = buffer;
96         }
97
98         return info;
99 }
100
101
102 boost::filesystem::path
103 directory_containing_executable ()
104 {
105         return boost::filesystem::canonical(boost::dll::program_location()).parent_path();
106 }
107
108
109 boost::filesystem::path
110 resources_path ()
111 {
112         return directory_containing_executable().parent_path() / "Resources";
113 }
114
115
116 boost::filesystem::path
117 libdcp_resources_path ()
118 {
119         return resources_path();
120 }
121
122
123 void
124 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
125 {
126         auto path = directory_containing_executable () / "ffprobe";
127
128         string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
129         LOG_GENERAL (N_("Probing with %1"), ffprobe);
130         system (ffprobe.c_str ());
131 }
132
133
134
135 list<pair<string, string>>
136 mount_info ()
137 {
138         return {};
139 }
140
141
142 boost::filesystem::path
143 openssl_path ()
144 {
145         return directory_containing_executable() / "openssl";
146 }
147
148
149 #ifdef DCPOMATIC_DISK
150 /* Note: this isn't actually used at the moment as the disk writer is started as a service */
151 boost::filesystem::path
152 disk_writer_path ()
153 {
154         return directory_containing_executable() / "dcpomatic2_disk_writer";
155 }
156 #endif
157
158
159 /* Apparently there is no way to create an ofstream using a UTF-8
160    filename under Windows.  We are hence reduced to using fopen
161    with this wrapper.
162 */
163 FILE *
164 fopen_boost (boost::filesystem::path p, string t)
165 {
166         return fopen (p.c_str(), t.c_str());
167 }
168
169
170 int
171 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
172 {
173         return fseek (stream, offset, whence);
174 }
175
176
177 void
178 Waker::nudge ()
179 {
180
181 }
182
183
184 Waker::Waker ()
185 {
186         boost::mutex::scoped_lock lm (_mutex);
187         IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
188 }
189
190
191 Waker::~Waker ()
192 {
193         boost::mutex::scoped_lock lm (_mutex);
194         IOPMAssertionRelease (_assertion_id);
195 }
196
197
198 void
199 start_tool (string executable, string app)
200 {
201         auto exe_path = directory_containing_executable();
202         exe_path = exe_path.parent_path(); // Contents
203         exe_path = exe_path.parent_path(); // DCP-o-matic 2.app
204         exe_path = exe_path.parent_path(); // Applications
205         exe_path /= app;
206         exe_path /= "Contents";
207         exe_path /= "MacOS";
208         exe_path /= executable;
209
210         pid_t pid = fork ();
211         if (pid == 0) {
212                 LOG_GENERAL ("start_tool %1 %2 with path %3", executable, app, exe_path.string());
213                 int const r = system (exe_path.string().c_str());
214                 exit (WEXITSTATUS (r));
215         } else if (pid == -1) {
216                 LOG_ERROR_NC("Fork failed in start_tool");
217         }
218 }
219
220
221 void
222 start_batch_converter ()
223 {
224         start_tool ("dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
225 }
226
227
228 void
229 start_player ()
230 {
231         start_tool ("dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
232 }
233
234
235 uint64_t
236 thread_id ()
237 {
238         return (uint64_t) pthread_self ();
239 }
240
241
242 int
243 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
244 {
245         return avio_open (s, file.c_str(), flags);
246 }
247
248
249 boost::filesystem::path
250 home_directory ()
251 {
252         return getenv("HOME");
253 }
254
255
256 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
257 bool
258 running_32_on_64 ()
259 {
260         /* I'm assuming nobody does this on OS X */
261         return false;
262 }
263
264
265 static optional<string>
266 get_vendor (CFDictionaryRef& description)
267 {
268         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceVendorKey);
269         if (!str) {
270                 return {};
271         }
272
273         auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
274         if (!c_str) {
275                 return {};
276         }
277
278         string s (c_str);
279         boost::algorithm::trim (s);
280         return s;
281 }
282
283
284 static optional<string>
285 get_model (CFDictionaryRef& description)
286 {
287         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionDeviceModelKey);
288         if (!str) {
289                 return {};
290         }
291
292         auto c_str = CFStringGetCStringPtr ((CFStringRef) str, kCFStringEncodingUTF8);
293         if (!c_str) {
294                 return {};
295         }
296
297         string s (c_str);
298         boost::algorithm::trim (s);
299         return s;
300 }
301
302
303 static optional<OSXMediaPath>
304 analyse_media_path (CFDictionaryRef& description)
305 {
306         using namespace boost::algorithm;
307
308         void const* str = CFDictionaryGetValue (description, kDADiskDescriptionMediaPathKey);
309         if (!str) {
310                 LOG_DISK_NC("There is no MediaPathKey (no dictionary value)");
311                 return {};
312         }
313
314         auto path_key_cstr = CFStringGetCStringPtr((CFStringRef) str, kCFStringEncodingUTF8);
315         if (!path_key_cstr) {
316                 LOG_DISK_NC("There is no MediaPathKey (no cstring)");
317                 return {};
318         }
319
320         string path(path_key_cstr);
321         LOG_DISK("MediaPathKey is %1", path);
322         return analyse_osx_media_path (path);
323 }
324
325
326 static bool
327 is_whole_drive (DADiskRef& disk)
328 {
329         io_service_t service = DADiskCopyIOMedia (disk);
330         CFTypeRef whole_media_ref = IORegistryEntryCreateCFProperty (service, CFSTR(kIOMediaWholeKey), kCFAllocatorDefault, 0);
331         bool whole_media = false;
332         if (whole_media_ref) {
333                 whole_media = CFBooleanGetValue((CFBooleanRef) whole_media_ref);
334                 CFRelease (whole_media_ref);
335         }
336         IOObjectRelease (service);
337         return whole_media;
338 }
339
340
341 static optional<boost::filesystem::path>
342 mount_point (CFDictionaryRef& description)
343 {
344         auto volume_path_key = (CFURLRef) CFDictionaryGetValue (description, kDADiskDescriptionVolumePathKey);
345         if (!volume_path_key) {
346                 return {};
347         }
348
349         char mount_path_buffer[1024];
350         if (!CFURLGetFileSystemRepresentation(volume_path_key, false, (UInt8 *) mount_path_buffer, sizeof(mount_path_buffer))) {
351                 return {};
352         }
353         return boost::filesystem::path(mount_path_buffer);
354 }
355
356
357 /* Here follows some rather intricate and (probably) fragile code to find the list of available
358  * "real" drives on macOS that we might want to write a DCP to.
359  *
360  * We use the Disk Arbitration framework to give us a series of mount_points (/dev/disk0, /dev/disk1,
361  * /dev/disk1s1 and so on) and we use the API to gather useful information about these mount_points into
362  * a vector of Disk structs.
363  *
364  * Then we read the Disks that we found and try to derive a list of drives that we should offer to the
365  * user, with details of whether those drives are currently mounted or not.
366  *
367  * At the basic level we find the "disk"-level mount_points, looking at whether any of their partitions are mounted.
368  *
369  * This is complicated enormously by recent-ish macOS versions' habit of making `synthesized' volumes which
370  * reflect data in `real' partitions.  So, for example, we might have a real (physical) drive /dev/disk2 with
371  * a partition /dev/disk2s2 whose content is made into a synthesized /dev/disk3, itself containing some partitions
372  * which are mounted.  /dev/disk2s2 is not considered to be mounted, in this case.  So we need to know that
373  * disk2s2 is related to disk3 so we can consider disk2s2 as mounted if any parts of disk3 are.  In order to do
374  * this I am taking the first two parts of the IODeviceTree and seeing if they exist anywhere in a
375  * IOService identifier.  If they do, I am assuming the IOService device is on the matching IODeviceTree device.
376  *
377  * Lots of this is guesswork and may be broken.  In my defence the documentation that I have been able to
378  * unearth is, to put it impolitely, crap.
379  */
380
381 static void
382 disk_appeared (DADiskRef disk, void* context)
383 {
384         auto bsd_name = DADiskGetBSDName (disk);
385         if (!bsd_name) {
386                 LOG_DISK_NC("Disk with no BSDName appeared");
387                 return;
388         }
389         LOG_DISK("%1 appeared", bsd_name);
390
391         OSXDisk this_disk;
392
393         this_disk.device = string("/dev/") + bsd_name;
394         LOG_DISK("Device is %1", this_disk.device);
395
396         CFDictionaryRef description = DADiskCopyDescription (disk);
397
398         this_disk.vendor = get_vendor (description);
399         this_disk.model = get_model (description);
400         LOG_DISK("Vendor/model: %1 %2", this_disk.vendor.get_value_or("[none]"), this_disk.model.get_value_or("[none]"));
401
402         auto media_path = analyse_media_path (description);
403         if (!media_path) {
404                 LOG_DISK("Finding media path for %1 failed", bsd_name);
405                 return;
406         }
407
408         this_disk.media_path = *media_path;
409         this_disk.whole = is_whole_drive (disk);
410         auto mp = mount_point (description);
411         if (mp) {
412                 this_disk.mount_points.push_back (*mp);
413         }
414
415         LOG_DISK(
416                 "%1 %2 mounted at %3",
417                  this_disk.media_path.real ? "Real" : "Synth",
418                  this_disk.whole ? "whole" : "part",
419                  mp ? mp->string() : "[nowhere]"
420                 );
421
422         auto media_size_cstr = CFDictionaryGetValue (description, kDADiskDescriptionMediaSizeKey);
423         if (!media_size_cstr) {
424                 LOG_DISK_NC("Could not read media size");
425                 return;
426         }
427
428         CFNumberGetValue ((CFNumberRef) media_size_cstr, kCFNumberLongType, &this_disk.size);
429         CFRelease (description);
430
431         reinterpret_cast<vector<OSXDisk>*>(context)->push_back(this_disk);
432 }
433
434
435 vector<Drive>
436 Drive::get ()
437 {
438         using namespace boost::algorithm;
439         vector<OSXDisk> disks;
440
441         auto session = DASessionCreate(kCFAllocatorDefault);
442         if (!session) {
443                 return {};
444         }
445
446         DARegisterDiskAppearedCallback (session, NULL, disk_appeared, &disks);
447         auto run_loop = CFRunLoopGetCurrent ();
448         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
449         CFRunLoopStop (run_loop);
450         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.05, 0);
451         DAUnregisterCallback(session, (void *) disk_appeared, &disks);
452         CFRelease(session);
453
454         return osx_disks_to_drives (disks);
455 }
456
457
458 boost::filesystem::path
459 config_path (optional<string> version)
460 {
461         boost::filesystem::path p;
462         p /= g_get_home_dir ();
463         p /= "Library";
464         p /= "Preferences";
465         p /= "com.dcpomatic";
466         p /= "2";
467         if (version) {
468                 p /= *version;
469         }
470         return p;
471 }
472
473
474 void done_callback(DADiskRef, DADissenterRef dissenter, void* context)
475 {
476         LOG_DISK_NC("Unmount finished");
477         bool* success = reinterpret_cast<bool*> (context);
478         if (dissenter) {
479                 LOG_DISK("Error: %1", DADissenterGetStatus(dissenter));
480                 *success = false;
481         } else {
482                 LOG_DISK_NC("Successful");
483                 *success = true;
484         }
485 }
486
487
488 bool
489 Drive::unmount ()
490 {
491         LOG_DISK_NC("Unmount operation started");
492
493         auto session = DASessionCreate(kCFAllocatorDefault);
494         if (!session) {
495                 return false;
496         }
497
498         auto disk = DADiskCreateFromBSDName(kCFAllocatorDefault, session, _device.c_str());
499         if (!disk) {
500                 return false;
501         }
502         LOG_DISK("Requesting unmount of %1 from %2", _device, thread_id());
503         bool success = false;
504         DADiskUnmount(disk, kDADiskUnmountOptionWhole, &done_callback, &success);
505         CFRelease (disk);
506
507         CFRunLoopRef run_loop = CFRunLoopGetCurrent ();
508         DASessionScheduleWithRunLoop (session, run_loop, kCFRunLoopDefaultMode);
509         CFRunLoopStop (run_loop);
510         CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.5, 0);
511         CFRelease(session);
512
513         LOG_DISK_NC("End of unmount");
514         return success;
515 }
516
517
518 void
519 disk_write_finished ()
520 {
521
522 }
523
524
525 void
526 make_foreground_application ()
527 {
528         ProcessSerialNumber serial;
529 LIBDCP_DISABLE_WARNINGS
530         GetCurrentProcess (&serial);
531 LIBDCP_ENABLE_WARNINGS
532         TransformProcessType (&serial, kProcessTransformToForegroundApplication);
533 }
534
535
536 string
537 dcpomatic::get_process_id ()
538 {
539         return dcp::raw_convert<string>(getpid());
540 }
541
542
543 boost::filesystem::path
544 fix_long_path (boost::filesystem::path path)
545 {
546         return path;
547 }
548
549
550 bool
551 show_in_file_manager (boost::filesystem::path, boost::filesystem::path select)
552 {
553         int r = system (String::compose("open -R \"%1\"", select.string()).c_str());
554         return static_cast<bool>(WEXITSTATUS(r));
555 }
556