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