Add FIXME.
[dcpomatic.git] / src / lib / cross.cc
1 /*
2     Copyright (C) 2012-2018 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 extern "C" {
28 #include <libavformat/avio.h>
29 }
30 #include <boost/algorithm/string.hpp>
31 #ifdef DCPOMATIC_LINUX
32 #include <unistd.h>
33 #include <mntent.h>
34 #endif
35 #ifdef DCPOMATIC_WINDOWS
36 #include <windows.h>
37 #undef DATADIR
38 #include <shlwapi.h>
39 #include <shellapi.h>
40 #include <fcntl.h>
41 #endif
42 #ifdef DCPOMATIC_OSX
43 #include <sys/sysctl.h>
44 #include <mach-o/dyld.h>
45 #include <IOKit/pwr_mgt/IOPMLib.h>
46 #endif
47 #ifdef DCPOMATIC_POSIX
48 #include <sys/types.h>
49 #include <ifaddrs.h>
50 #include <netinet/in.h>
51 #include <arpa/inet.h>
52 #endif
53 #include <fstream>
54
55 #include "i18n.h"
56
57 using std::pair;
58 using std::list;
59 using std::ifstream;
60 using std::string;
61 using std::wstring;
62 using std::make_pair;
63 using std::runtime_error;
64 using boost::shared_ptr;
65
66 /** @param s Number of seconds to sleep for */
67 void
68 dcpomatic_sleep_seconds (int s)
69 {
70 #ifdef DCPOMATIC_POSIX
71         sleep (s);
72 #endif
73 #ifdef DCPOMATIC_WINDOWS
74         Sleep (s * 1000);
75 #endif
76 }
77
78 /** @return A string of CPU information (model name etc.) */
79 string
80 cpu_info ()
81 {
82         string info;
83
84 #ifdef DCPOMATIC_LINUX
85         /* This use of ifstream is ok; the filename can never
86            be non-Latin
87         */
88         ifstream f ("/proc/cpuinfo");
89         while (f.good ()) {
90                 string l;
91                 getline (f, l);
92                 if (boost::algorithm::starts_with (l, "model name")) {
93                         string::size_type const c = l.find (':');
94                         if (c != string::npos) {
95                                 info = l.substr (c + 2);
96                         }
97                 }
98         }
99 #endif
100
101 #ifdef DCPOMATIC_OSX
102         char buffer[64];
103         size_t N = sizeof (buffer);
104         if (sysctlbyname ("machdep.cpu.brand_string", buffer, &N, 0, 0) == 0) {
105                 info = buffer;
106         }
107 #endif
108
109 #ifdef DCPOMATIC_WINDOWS
110         HKEY key;
111         if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0, KEY_READ, &key) != ERROR_SUCCESS) {
112                 return info;
113         }
114
115         DWORD type;
116         DWORD data;
117         if (RegQueryValueEx (key, L"ProcessorNameString", 0, &type, 0, &data) != ERROR_SUCCESS) {
118                 return info;
119         }
120
121         if (type != REG_SZ) {
122                 return info;
123         }
124
125         wstring value (data / sizeof (wchar_t), L'\0');
126         if (RegQueryValueEx (key, L"ProcessorNameString", 0, 0, reinterpret_cast<LPBYTE> (&value[0]), &data) != ERROR_SUCCESS) {
127                 RegCloseKey (key);
128                 return info;
129         }
130
131         info = string (value.begin(), value.end());
132
133         RegCloseKey (key);
134
135 #endif
136
137         return info;
138 }
139
140 #ifdef DCPOMATIC_OSX
141 /** @return Path of the Contents directory in the .app */
142 boost::filesystem::path
143 app_contents ()
144 {
145         uint32_t size = 1024;
146         char buffer[size];
147         if (_NSGetExecutablePath (buffer, &size)) {
148                 throw runtime_error ("_NSGetExecutablePath failed");
149         }
150
151         boost::filesystem::path path (buffer);
152         path = boost::filesystem::canonical (path);
153         path = path.parent_path ();
154         path = path.parent_path ();
155         return path;
156 }
157 #endif
158
159 boost::filesystem::path
160 shared_path ()
161 {
162 #ifdef DCPOMATIC_LINUX
163         char const * p = getenv ("DCPOMATIC_LINUX_SHARE_PREFIX");
164         if (p) {
165                 return p;
166         }
167         return boost::filesystem::canonical (LINUX_SHARE_PREFIX);
168 #endif
169 #ifdef DCPOMATIC_WINDOWS
170         wchar_t dir[512];
171         GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir));
172         PathRemoveFileSpec (dir);
173         boost::filesystem::path path = dir;
174         return path.parent_path();
175 #endif
176 #ifdef DCPOMATIC_OSX
177         return app_contents() / "Resources";
178 #endif
179 }
180
181 void
182 run_ffprobe (boost::filesystem::path content, boost::filesystem::path out)
183 {
184 #ifdef DCPOMATIC_WINDOWS
185         SECURITY_ATTRIBUTES security;
186         security.nLength = sizeof (security);
187         security.bInheritHandle = TRUE;
188         security.lpSecurityDescriptor = 0;
189
190         HANDLE child_stderr_read;
191         HANDLE child_stderr_write;
192         if (!CreatePipe (&child_stderr_read, &child_stderr_write, &security, 0)) {
193                 LOG_ERROR_NC ("ffprobe call failed (could not CreatePipe)");
194                 return;
195         }
196
197         wchar_t dir[512];
198         GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir));
199         PathRemoveFileSpec (dir);
200         SetCurrentDirectory (dir);
201
202         STARTUPINFO startup_info;
203         ZeroMemory (&startup_info, sizeof (startup_info));
204         startup_info.cb = sizeof (startup_info);
205         startup_info.hStdError = child_stderr_write;
206         startup_info.dwFlags |= STARTF_USESTDHANDLES;
207
208         wchar_t command[512];
209         wcscpy (command, L"ffprobe.exe \"");
210
211         wchar_t file[512];
212         MultiByteToWideChar (CP_UTF8, 0, content.string().c_str(), -1, file, sizeof(file));
213         wcscat (command, file);
214
215         wcscat (command, L"\"");
216
217         PROCESS_INFORMATION process_info;
218         ZeroMemory (&process_info, sizeof (process_info));
219         if (!CreateProcess (0, command, 0, 0, TRUE, CREATE_NO_WINDOW, 0, 0, &startup_info, &process_info)) {
220                 LOG_ERROR_NC (N_("ffprobe call failed (could not CreateProcess)"));
221                 return;
222         }
223
224         FILE* o = fopen_boost (out, "w");
225         if (!o) {
226                 LOG_ERROR_NC (N_("ffprobe call failed (could not create output file)"));
227                 return;
228         }
229
230         CloseHandle (child_stderr_write);
231
232         while (true) {
233                 char buffer[512];
234                 DWORD read;
235                 if (!ReadFile(child_stderr_read, buffer, sizeof(buffer), &read, 0) || read == 0) {
236                         break;
237                 }
238                 fwrite (buffer, read, 1, o);
239         }
240
241         fclose (o);
242
243         WaitForSingleObject (process_info.hProcess, INFINITE);
244         CloseHandle (process_info.hProcess);
245         CloseHandle (process_info.hThread);
246         CloseHandle (child_stderr_read);
247 #endif
248
249 #ifdef DCPOMATIC_LINUX
250         string ffprobe = "ffprobe \"" + content.string() + "\" 2> \"" + out.string() + "\"";
251         LOG_GENERAL (N_("Probing with %1"), ffprobe);
252         system (ffprobe.c_str ());
253 #endif
254
255 #ifdef DCPOMATIC_OSX
256         boost::filesystem::path path = app_contents();
257         path /= "MacOS";
258         path /= "ffprobe";
259
260         string ffprobe = "\"" + path.string() + "\" \"" + content.string() + "\" 2> \"" + out.string() + "\"";
261         LOG_GENERAL (N_("Probing with %1"), ffprobe);
262         system (ffprobe.c_str ());
263 #endif
264 }
265
266 list<pair<string, string> >
267 mount_info ()
268 {
269         list<pair<string, string> > m;
270
271 #ifdef DCPOMATIC_LINUX
272         FILE* f = setmntent ("/etc/mtab", "r");
273         if (!f) {
274                 return m;
275         }
276
277         while (true) {
278                 struct mntent* mnt = getmntent (f);
279                 if (!mnt) {
280                         break;
281                 }
282
283                 m.push_back (make_pair (mnt->mnt_dir, mnt->mnt_type));
284         }
285
286         endmntent (f);
287 #endif
288
289         return m;
290 }
291
292 boost::filesystem::path
293 openssl_path ()
294 {
295 #ifdef DCPOMATIC_WINDOWS
296         wchar_t dir[512];
297         GetModuleFileName (GetModuleHandle (0), dir, sizeof (dir));
298         PathRemoveFileSpec (dir);
299
300         boost::filesystem::path path = dir;
301         path /= "openssl.exe";
302         return path;
303 #endif
304
305 #ifdef DCPOMATIC_OSX
306         boost::filesystem::path path = app_contents();
307         path /= "MacOS";
308         path /= "openssl";
309         return path;
310 #endif
311
312 #ifdef DCPOMATIC_LINUX
313         return "dcpomatic2_openssl";
314 #endif
315
316 }
317
318 /* Apparently there is no way to create an ofstream using a UTF-8
319    filename under Windows.  We are hence reduced to using fopen
320    with this wrapper.
321 */
322 FILE *
323 fopen_boost (boost::filesystem::path p, string t)
324 {
325 #ifdef DCPOMATIC_WINDOWS
326         wstring w (t.begin(), t.end());
327         /* c_str() here should give a UTF-16 string */
328         return _wfopen (p.c_str(), w.c_str ());
329 #else
330         return fopen (p.c_str(), t.c_str ());
331 #endif
332 }
333
334 int
335 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
336 {
337 #ifdef DCPOMATIC_WINDOWS
338         return _fseeki64 (stream, offset, whence);
339 #else
340         return fseek (stream, offset, whence);
341 #endif
342 }
343
344 void
345 Waker::nudge ()
346 {
347 #ifdef DCPOMATIC_WINDOWS
348         boost::mutex::scoped_lock lm (_mutex);
349         SetThreadExecutionState (ES_SYSTEM_REQUIRED);
350 #endif
351 }
352
353 Waker::Waker ()
354 {
355 #ifdef DCPOMATIC_OSX
356         boost::mutex::scoped_lock lm (_mutex);
357         /* We should use this */
358         // IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
359         /* but it's not available on 10.5, so we use this */
360         IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &_assertion_id);
361 #endif
362 }
363
364 Waker::~Waker ()
365 {
366 #ifdef DCPOMATIC_OSX
367         boost::mutex::scoped_lock lm (_mutex);
368         IOPMAssertionRelease (_assertion_id);
369 #endif
370 }
371
372 void
373 start_tool (boost::filesystem::path dcpomatic, string executable,
374 #ifdef DCPOMATIC_OSX
375             string app
376 #else
377             string
378 #endif
379         )
380 {
381 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_WINDOWS)
382         boost::filesystem::path batch = dcpomatic.parent_path() / executable;
383 #endif
384
385 #ifdef DCPOMATIC_OSX
386         boost::filesystem::path batch = dcpomatic.parent_path ();
387         batch = batch.parent_path (); // MacOS
388         batch = batch.parent_path (); // Contents
389         batch = batch.parent_path (); // DCP-o-matic.app
390         batch = batch.parent_path (); // Applications
391         batch /= app;
392         batch /= "Contents";
393         batch /= "MacOS";
394         batch /= executable;
395 #endif
396
397 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_OSX)
398         pid_t pid = fork ();
399         if (pid == 0) {
400                 int const r = system (batch.string().c_str());
401                 exit (WEXITSTATUS (r));
402         }
403 #endif
404
405 #ifdef DCPOMATIC_WINDOWS
406         STARTUPINFO startup_info;
407         ZeroMemory (&startup_info, sizeof (startup_info));
408         startup_info.cb = sizeof (startup_info);
409
410         PROCESS_INFORMATION process_info;
411         ZeroMemory (&process_info, sizeof (process_info));
412
413         wchar_t cmd[512];
414         MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
415         CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
416 #endif
417 }
418
419 void
420 start_batch_converter (boost::filesystem::path dcpomatic)
421 {
422         start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
423 }
424
425 void
426 start_player (boost::filesystem::path dcpomatic)
427 {
428         start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
429 }
430
431 uint64_t
432 thread_id ()
433 {
434 #ifdef DCPOMATIC_WINDOWS
435         return (uint64_t) GetCurrentThreadId ();
436 #else
437         return (uint64_t) pthread_self ();
438 #endif
439 }
440
441 int
442 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
443 {
444 #ifdef DCPOMATIC_WINDOWS
445         int const length = (file.string().length() + 1) * 2;
446         char* utf8 = new char[length];
447         WideCharToMultiByte (CP_UTF8, 0, file.c_str(), -1, utf8, length, 0, 0);
448         int const r = avio_open (s, utf8, flags);
449         delete[] utf8;
450         return r;
451 #else
452         return avio_open (s, file.c_str(), flags);
453 #endif
454 }
455
456 #ifdef DCPOMATIC_WINDOWS
457 void
458 maybe_open_console ()
459 {
460         if (Config::instance()->win32_console ()) {
461                 AllocConsole();
462
463                 HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
464                 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
465                 FILE* hf_out = _fdopen(hCrt, "w");
466                 setvbuf(hf_out, NULL, _IONBF, 1);
467                 *stdout = *hf_out;
468
469                 HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
470                 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
471                 FILE* hf_in = _fdopen(hCrt, "r");
472                 setvbuf(hf_in, NULL, _IONBF, 128);
473                 *stdin = *hf_in;
474         }
475 }
476 #endif
477
478 boost::filesystem::path
479 home_directory ()
480 {
481 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_OSX)
482                 return getenv("HOME");
483 #endif
484 #ifdef DCPOMATIC_WINDOWS
485                 return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH"));
486 #endif
487 }
488
489 string
490 command_and_read (string cmd)
491 {
492 #ifdef DCPOMATIC_LINUX
493         FILE* pipe = popen (cmd.c_str(), "r");
494         if (!pipe) {
495                 throw runtime_error ("popen failed");
496         }
497
498         string result;
499         char buffer[128];
500         try {
501                 while (fgets(buffer, sizeof(buffer), pipe)) {
502                         result += buffer;
503                 }
504         } catch (...) {
505                 pclose (pipe);
506                 throw;
507         }
508
509         pclose (pipe);
510         return result;
511 #endif
512
513         return "";
514 }
515
516 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
517 bool
518 running_32_on_64 ()
519 {
520 #ifdef DCPOMATIC_WINDOWS
521         BOOL p;
522         IsWow64Process (GetCurrentProcess(), &p);
523         return p;
524 #endif
525         /* XXX: assuming nobody does this on Linux / OS X */
526         return false;
527 }