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