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