Try to fix Windows build.
[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 (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         SetThreadExecutionState (ES_SYSTEM_REQUIRED);
341 #endif
342 }
343
344 Waker::Waker ()
345 {
346 #ifdef DCPOMATIC_OSX
347         /* We should use this */
348         // IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, CFSTR ("Encoding DCP"), &_assertion_id);
349         /* but it's not available on 10.5, so we use this */
350         IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &_assertion_id);
351 #endif
352 }
353
354 Waker::~Waker ()
355 {
356 #ifdef DCPOMATIC_OSX
357         IOPMAssertionRelease (_assertion_id);
358 #endif
359 }
360
361 void
362 start_tool (boost::filesystem::path dcpomatic, string executable,
363 #ifdef DCPOMATIC_OSX
364             string app
365 #else
366             string
367 #endif
368         )
369 {
370 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_WINDOWS)
371         boost::filesystem::path batch = dcpomatic.parent_path() / executable;
372 #endif
373
374 #ifdef DCPOMATIC_OSX
375         boost::filesystem::path batch = dcpomatic.parent_path ();
376         batch = batch.parent_path (); // MacOS
377         batch = batch.parent_path (); // Contents
378         batch = batch.parent_path (); // DCP-o-matic.app
379         batch = batch.parent_path (); // Applications
380         batch /= app;
381         batch /= "Contents";
382         batch /= "MacOS";
383         batch /= executable;
384 #endif
385
386 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_OSX)
387         pid_t pid = fork ();
388         if (pid == 0) {
389                 int const r = system (batch.string().c_str());
390                 exit (WEXITSTATUS (r));
391         }
392 #endif
393
394 #ifdef DCPOMATIC_WINDOWS
395         STARTUPINFO startup_info;
396         ZeroMemory (&startup_info, sizeof (startup_info));
397         startup_info.cb = sizeof (startup_info);
398
399         PROCESS_INFORMATION process_info;
400         ZeroMemory (&process_info, sizeof (process_info));
401
402         wchar_t cmd[512];
403         MultiByteToWideChar (CP_UTF8, 0, batch.string().c_str(), -1, cmd, sizeof(cmd));
404         CreateProcess (0, cmd, 0, 0, FALSE, 0, 0, 0, &startup_info, &process_info);
405 #endif
406 }
407
408 void
409 start_batch_converter (boost::filesystem::path dcpomatic)
410 {
411         start_tool (dcpomatic, "dcpomatic2_batch", "DCP-o-matic\\ 2\\ Batch\\ Converter.app");
412 }
413
414 void
415 start_player (boost::filesystem::path dcpomatic)
416 {
417         start_tool (dcpomatic, "dcpomatic2_player", "DCP-o-matic\\ 2\\ Player.app");
418 }
419
420 uint64_t
421 thread_id ()
422 {
423 #ifdef DCPOMATIC_WINDOWS
424         return (uint64_t) GetCurrentThreadId ();
425 #else
426         return (uint64_t) pthread_self ();
427 #endif
428 }
429
430 int
431 avio_open_boost (AVIOContext** s, boost::filesystem::path file, int flags)
432 {
433 #ifdef DCPOMATIC_WINDOWS
434         int const length = (file.string().length() + 1) * 2;
435         char* utf8 = new char[length];
436         WideCharToMultiByte (CP_UTF8, 0, file.c_str(), -1, utf8, length, 0, 0);
437         int const r = avio_open (s, utf8, flags);
438         delete[] utf8;
439         return r;
440 #else
441         return avio_open (s, file.c_str(), flags);
442 #endif
443 }
444
445 #ifdef DCPOMATIC_WINDOWS
446 void
447 maybe_open_console ()
448 {
449         if (Config::instance()->win32_console ()) {
450                 AllocConsole();
451
452                 HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
453                 int hCrt = _open_osfhandle((intptr_t) handle_out, _O_TEXT);
454                 FILE* hf_out = _fdopen(hCrt, "w");
455                 setvbuf(hf_out, NULL, _IONBF, 1);
456                 *stdout = *hf_out;
457
458                 HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
459                 hCrt = _open_osfhandle((intptr_t) handle_in, _O_TEXT);
460                 FILE* hf_in = _fdopen(hCrt, "r");
461                 setvbuf(hf_in, NULL, _IONBF, 128);
462                 *stdin = *hf_in;
463         }
464 }
465 #endif
466
467 boost::filesystem::path
468 home_directory ()
469 {
470 #if defined(DCPOMATIC_LINUX) || defined(DCPOMATIC_OSX)
471                 return getenv("HOME");
472 #endif
473 #ifdef DCPOMATIC_WINDOWS
474                 return boost::filesystem::path(getenv("HOMEDRIVE")) / boost::filesystem::path(getenv("HOMEPATH"));
475 #endif
476 }