Yet more waking (in hash computation).
[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 #else
304         /* We assume that it's on the path for Linux and OS X */
305         return "openssl";
306 #endif
307
308 }
309
310 /* Apparently there is no way to create an ofstream using a UTF-8
311    filename under Windows.  We are hence reduced to using fopen
312    with this wrapper.
313 */
314 FILE *
315 fopen_boost (boost::filesystem::path p, string t)
316 {
317 #ifdef DCPOMATIC_WINDOWS
318         wstring w (t.begin(), t.end());
319         /* c_str() here should give a UTF-16 string */
320         return _wfopen (p.c_str(), w.c_str ());
321 #else
322         return fopen (p.c_str(), t.c_str ());
323 #endif
324 }
325
326 int
327 dcpomatic_fseek (FILE* stream, int64_t offset, int whence)
328 {
329 #ifdef DCPOMATIC_WINDOWS
330         return _fseeki64 (stream, offset, whence);
331 #else
332         return fseek (stream, offset, whence);
333 #endif
334 }
335
336 void
337 Waker::nudge ()
338 {
339 #ifdef DCPOMATIC_WINDOWS
340         boost::mutex::scoped_lock lm (_mutex);
341         SetThreadExecutionState (ES_SYSTEM_REQUIRED);
342 #endif
343 }
344
345 Waker::Waker ()
346 {
347 #ifdef DCPOMATIC_OSX
348         boost::mutex::scoped_lock lm (_mutex);
349         /* We should use this */
350         // IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
351         /* but it's not available on 10.5, so we use this */
352         IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &_assertion_id);
353 #endif
354 }
355
356 Waker::~Waker ()
357 {
358 #ifdef DCPOMATIC_OSX
359         boost::mutex::scoped_lock lm (_mutex);
360         IOPMAssertionRelease (_assertion_id);
361 #endif
362 }
363
364 void
365 start_tool (boost::filesystem::path dcpomatic, string executable,
366 #ifdef DCPOMATIC_OSX
367             string app
368 #else
369             string
370 #endif
371         )
372 {
373 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_WINDOWS)
374         boost::filesystem::path batch = dcpomatic.parent_path() / executable;
375 #endif
376
377 #ifdef DCPOMATIC_OSX
378         boost::filesystem::path batch = dcpomatic.parent_path ();
379         batch = batch.parent_path (); // MacOS
380         batch = batch.parent_path (); // Contents
381         batch = batch.parent_path (); // DCP-o-matic.app
382         batch = batch.parent_path (); // Applications
383         batch /= app;
384         batch /= "Contents";
385         batch /= "MacOS";
386         batch /= executable;
387 #endif
388
389 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_OSX)
390         pid_t pid = fork ();
391         if (pid == 0) {
392                 int const r = system (batch.string().c_str());
393                 exit (WEXITSTATUS (r));
394         }
395 #endif
396
397 #ifdef DCPOMATIC_WINDOWS
398         STARTUPINFO startup_info;
399         ZeroMemory (&startup_info, sizeof (startup_info));
400         startup_info.cb = sizeof (startup_info);
401
402         PROCESS_INFORMATION process_info;
403         ZeroMemory (&process_info, sizeof (process_info));
404
405         wchar_t cmd[512];
406         MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
407         CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
408 #endif
409 }
410
411 void
412 start_batch_converter (boost::filesystem::path dcpomatic)
413 {
414         start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
415 }
416
417 void
418 start_player (boost::filesystem::path dcpomatic)
419 {
420         start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
421 }
422
423 uint64_t
424 thread_id ()
425 {
426 #ifdef DCPOMATIC_WINDOWS
427         return (uint64_t) GetCurrentThreadId ();
428 #else
429         return (uint64_t) pthread_self ();
430 #endif
431 }
432
433 int
434 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
435 {
436 #ifdef DCPOMATIC_WINDOWS
437         int const length = (file.string().length() + 1) * 2;
438         char* utf8 = new char[length];
439         WideCharToMultiByte (CP_UTF8, 0, file.c_str(), -1, utf8, length, 0, 0);
440         int const r = avio_open (s, utf8, flags);
441         delete[] utf8;
442         return r;
443 #else
444         return avio_open (s, file.c_str(), flags);
445 #endif
446 }
447
448 #ifdef DCPOMATIC_WINDOWS
449 void
450 maybe_open_console ()
451 {
452         if (Config::instance()->win32_console ()) {
453                 AllocConsole();
454
455                 HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
456                 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
457                 FILE* hf_out = _fdopen(hCrt, "w");
458                 setvbuf(hf_out, NULL, _IONBF, 1);
459                 *stdout = *hf_out;
460
461                 HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
462                 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
463                 FILE* hf_in = _fdopen(hCrt, "r");
464                 setvbuf(hf_in, NULL, _IONBF, 128);
465                 *stdin = *hf_in;
466         }
467 }
468 #endif
469
470 boost::filesystem::path
471 home_directory ()
472 {
473 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_OSX)
474                 return getenv("HOME");
475 #endif
476 #ifdef DCPOMATIC_WINDOWS
477                 return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH"));
478 #endif
479 }
480
481 string
482 command_and_read (string cmd)
483 {
484 #ifdef DCPOMATIC_LINUX
485         FILE* pipe = popen (cmd.c_str(), "r");
486         if (!pipe) {
487                 throw runtime_error ("popen failed");
488         }
489
490         string result;
491         char buffer[128];
492         try {
493                 while (fgets(buffer, sizeof(buffer), pipe)) {
494                         result += buffer;
495                 }
496         } catch (...) {
497                 pclose (pipe);
498                 throw;
499         }
500
501         pclose (pipe);
502         return result;
503 #endif
504
505         return "";
506 }
507
508 /** @return true if this process is a 32-bit one running on a 64-bit-capable OS */
509 bool
510 running_32_on_64 ()
511 {
512 #ifdef DCPOMATIC_WINDOWS
513         BOOL p;
514         IsWow64Process (GetCurrentProcess(), &p);
515         return p;
516 #endif
517         /* XXX: assuming nobody does this on Linux / OS X */
518         return false;
519 }