9896bff602f073e89caf50d29606c5bbf1424793
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3     Copyright (C) 2000-2007 Paul Davis
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 /** @file src/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include <sstream>
26 #include <iomanip>
27 #include <iostream>
28 #include <fstream>
29 #ifdef DVDOMATIC_POSIX
30 #include <execinfo.h>
31 #include <cxxabi.h>
32 #include <sys/types.h> 
33 #include <sys/socket.h>
34 #endif
35 #include <libssh/libssh.h>
36 #include <signal.h>
37 #include <boost/algorithm/string.hpp>
38 #include <openjpeg.h>
39 #include <openssl/md5.h>
40 #include <magick/MagickCore.h>
41 #include <magick/version.h>
42 #include <libdcp/version.h>
43 extern "C" {
44 #include <libavcodec/avcodec.h>
45 #include <libavformat/avformat.h>
46 #include <libswscale/swscale.h>
47 #include <libavfilter/avfiltergraph.h>
48 #include <libpostproc/postprocess.h>
49 #include <libavutil/pixfmt.h>
50 }
51 #include "util.h"
52 #include "exceptions.h"
53 #include "scaler.h"
54 #include "format.h"
55 #include "dcp_content_type.h"
56 #include "filter.h"
57 #include "screen.h"
58 #include "film_state.h"
59 #ifndef DVDOMATIC_DISABLE_PLAYER
60 #include "player_manager.h"
61 #endif
62
63 #ifdef DEBUG_HASH
64 #include <mhash.h>
65 #endif
66
67 using namespace std;
68 using namespace boost;
69
70 /** Convert some number of seconds to a string representation
71  *  in hours, minutes and seconds.
72  *
73  *  @param s Seconds.
74  *  @return String of the form H:M:S (where H is hours, M
75  *  is minutes and S is seconds).
76  */
77 string
78 seconds_to_hms (int s)
79 {
80         int m = s / 60;
81         s -= (m * 60);
82         int h = m / 60;
83         m -= (h * 60);
84
85         stringstream hms;
86         hms << h << ":";
87         hms.width (2);
88         hms << setfill ('0') << m << ":";
89         hms.width (2);
90         hms << setfill ('0') << s;
91
92         return hms.str ();
93 }
94
95 /** @param s Number of seconds.
96  *  @return String containing an approximate description of s (e.g. "about 2 hours")
97  */
98 string
99 seconds_to_approximate_hms (int s)
100 {
101         int m = s / 60;
102         s -= (m * 60);
103         int h = m / 60;
104         m -= (h * 60);
105
106         stringstream ap;
107         
108         if (h > 0) {
109                 if (m > 30) {
110                         ap << (h + 1) << " hours";
111                 } else {
112                         if (h == 1) {
113                                 ap << "1 hour";
114                         } else {
115                                 ap << h << " hours";
116                         }
117                 }
118         } else if (m > 0) {
119                 if (m == 1) {
120                         ap << "1 minute";
121                 } else {
122                         ap << m << " minutes";
123                 }
124         } else {
125                 ap << s << " seconds";
126         }
127
128         return ap.str ();
129 }
130
131 #ifdef DVDOMATIC_POSIX
132 /** @param l Mangled C++ identifier.
133  *  @return Demangled version.
134  */
135 static string
136 demangle (string l)
137 {
138         string::size_type const b = l.find_first_of ("(");
139         if (b == string::npos) {
140                 return l;
141         }
142
143         string::size_type const p = l.find_last_of ("+");
144         if (p == string::npos) {
145                 return l;
146         }
147
148         if ((p - b) <= 1) {
149                 return l;
150         }
151         
152         string const fn = l.substr (b + 1, p - b - 1);
153
154         int status;
155         try {
156                 
157                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
158                 string d (realname);
159                 free (realname);
160                 return d;
161                 
162         } catch (std::exception) {
163                 
164         }
165         
166         return l;
167 }
168
169 /** Write a stacktrace to an ostream.
170  *  @param out Stream to write to.
171  *  @param levels Number of levels to go up the call stack.
172  */
173 void
174 stacktrace (ostream& out, int levels)
175 {
176         void *array[200];
177         size_t size;
178         char **strings;
179         size_t i;
180      
181         size = backtrace (array, 200);
182         strings = backtrace_symbols (array, size);
183      
184         if (strings) {
185                 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
186                         out << "  " << demangle (strings[i]) << endl;
187                 }
188                 
189                 free (strings);
190         }
191 }
192 #endif
193
194 /** @param s Sample format.
195  *  @return String representation.
196  */
197 string
198 audio_sample_format_to_string (AVSampleFormat s)
199 {
200         /* Our sample format handling is not exactly complete */
201         
202         switch (s) {
203         case AV_SAMPLE_FMT_S16:
204                 return "S16";
205         default:
206                 break;
207         }
208
209         return "Unknown";
210 }
211
212 /** @param s String representation of a sample format, as returned from audio_sample_format_to_string().
213  *  @return Sample format.
214  */
215 AVSampleFormat
216 audio_sample_format_from_string (string s)
217 {
218         if (s == "S16") {
219                 return AV_SAMPLE_FMT_S16;
220         }
221
222         return AV_SAMPLE_FMT_NONE;
223 }
224
225 /** @return Version of vobcopy that is on the path (and hence that we will use) */
226 static string
227 vobcopy_version ()
228 {
229         FILE* f = popen ("vobcopy -V 2>&1", "r");
230         if (f == 0) {
231                 throw EncodeError ("could not run vobcopy to check version");
232         }
233
234         string version = "unknown";
235         
236         while (!feof (f)) {
237                 char buf[256];
238                 if (fgets (buf, sizeof (buf), f)) {
239                         string s (buf);
240                         vector<string> b;
241                         split (b, s, is_any_of (" "));
242                         if (b.size() >= 2 && b[0] == "Vobcopy") {
243                                 version = b[1];
244                         }
245                 }
246         }
247
248         pclose (f);
249
250         return version;
251 }
252
253 /** @param v Version as used by FFmpeg.
254  *  @return A string representation of v.
255  */
256 static string
257 ffmpeg_version_to_string (int v)
258 {
259         stringstream s;
260         s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
261         return s.str ();
262 }
263
264 /** Return a user-readable string summarising the versions of our dependencies */
265 string
266 dependency_version_summary ()
267 {
268         stringstream s;
269         s << "libopenjpeg " << opj_version () << ", "
270           << "vobcopy " << vobcopy_version() << ", "
271           << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
272           << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
273           << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
274           << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
275           << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
276           << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
277           << MagickVersion << ", "
278           << "libssh " << ssh_version (0) << ", "
279           << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
280
281         return s.str ();
282 }
283
284 #ifdef DVDOMATIC_POSIX
285 /** Write some data to a socket.
286  *  @param fd Socket file descriptor.
287  *  @param data Data.
288  *  @param size Amount to write, in bytes.
289  */
290 void
291 socket_write (int fd, uint8_t const * data, int size)
292 {
293         uint8_t const * p = data;
294         while (size) {
295                 int const n = send (fd, p, size, MSG_NOSIGNAL);
296                 if (n < 0) {
297                         stringstream s;
298                         s << "could not write (" << strerror (errno) << ")";
299                         throw NetworkError (s.str ());
300                 }
301
302                 size -= n;
303                 p += n;
304         }
305 }
306 #endif
307
308 double
309 seconds (struct timeval t)
310 {
311         return t.tv_sec + (double (t.tv_usec) / 1e6);
312 }
313
314 #ifdef DVDOMATIC_POSIX
315 /** @param fd File descriptor to read from */
316 SocketReader::SocketReader (int fd)
317         : _fd (fd)
318         , _buffer_data (0)
319 {
320
321 }
322
323 /** Mark some data as being `consumed', so that it will not be returned
324  *  as data again.
325  *  @param size Amount of data to consume, in bytes.
326  */
327 void
328 SocketReader::consume (int size)
329 {
330         assert (_buffer_data >= size);
331         
332         _buffer_data -= size;
333         if (_buffer_data > 0) {
334                 /* Shift still-valid data to the start of the buffer */
335                 memmove (_buffer, _buffer + size, _buffer_data);
336         }
337 }
338
339 /** Read a definite amount of data from our socket, and mark
340  *  it as consumed.
341  *  @param data Where to put the data.
342  *  @param size Number of bytes to read.
343  */
344 void
345 SocketReader::read_definite_and_consume (uint8_t* data, int size)
346 {
347         int const from_buffer = min (_buffer_data, size);
348         if (from_buffer > 0) {
349                 /* Get data from our buffer */
350                 memcpy (data, _buffer, from_buffer);
351                 consume (from_buffer);
352                 /* Update our output state */
353                 data += from_buffer;
354                 size -= from_buffer;
355         }
356
357         /* read() the rest */
358         while (size > 0) {
359                 int const n = ::read (_fd, data, size);
360                 if (n <= 0) {
361                         throw NetworkError ("could not read");
362                 }
363
364                 data += n;
365                 size -= n;
366         }
367 }
368
369 /** Read as much data as is available, up to some limit.
370  *  @param data Where to put the data.
371  *  @param size Maximum amount of data to read.
372  */
373 void
374 SocketReader::read_indefinite (uint8_t* data, int size)
375 {
376         assert (size < int (sizeof (_buffer)));
377
378         /* Amount of extra data we need to read () */
379         int to_read = size - _buffer_data;
380         while (to_read > 0) {
381                 /* read as much of it as we can (into our buffer) */
382                 int const n = ::read (_fd, _buffer + _buffer_data, to_read);
383                 if (n <= 0) {
384                         throw NetworkError ("could not read");
385                 }
386
387                 to_read -= n;
388                 _buffer_data += n;
389         }
390
391         assert (_buffer_data >= size);
392
393         /* copy data into the output buffer */
394         assert (size >= _buffer_data);
395         memcpy (data, _buffer, size);
396 }
397 #endif
398
399 #ifdef DVDOMATIC_POSIX
400 void
401 sigchld_handler (int, siginfo_t* info, void *)
402 {
403 #ifndef DVDOMATIC_DISABLE_PLAYER        
404         PlayerManager::instance()->child_exited (info->si_pid);
405 #endif  
406 }
407 #endif
408
409 /** Call the required functions to set up DVD-o-matic's static arrays, etc. */
410 void
411 dvdomatic_setup ()
412 {
413         Format::setup_formats ();
414         DCPContentType::setup_dcp_content_types ();
415         Scaler::setup_scalers ();
416         Filter::setup_filters ();
417
418 #ifdef DVDOMATIC_POSIX  
419         struct sigaction sa;
420         sa.sa_flags = SA_SIGINFO;
421         sigemptyset (&sa.sa_mask);
422         sa.sa_sigaction = sigchld_handler;
423         sigaction (SIGCHLD, &sa, 0);
424 #endif  
425 }
426
427 string
428 crop_string (Position start, Size size)
429 {
430         stringstream s;
431         s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
432         return s.str ();
433 }
434
435 vector<string>
436 split_at_spaces_considering_quotes (string s)
437 {
438         vector<string> out;
439         bool in_quotes = false;
440         string c;
441         for (string::size_type i = 0; i < s.length(); ++i) {
442                 if (s[i] == ' ' && !in_quotes) {
443                         out.push_back (c);
444                         c = "";
445                 } else if (s[i] == '"') {
446                         in_quotes = !in_quotes;
447                 } else {
448                         c += s[i];
449                 }
450         }
451
452         out.push_back (c);
453         return out;
454 }
455
456 #ifdef DEBUG_HASH
457 void
458 md5_data (string title, void const * data, int size)
459 {
460         MHASH ht = mhash_init (MHASH_MD5);
461         if (ht == MHASH_FAILED) {
462                 throw EncodeError ("could not create hash thread");
463         }
464
465         mhash (ht, data, size);
466         
467         uint8_t hash[16];
468         mhash_deinit (ht, hash);
469         
470         printf ("%s [%d]: ", title.c_str (), size);
471         for (int i = 0; i < int (mhash_get_block_size (MHASH_MD5)); ++i) {
472                 printf ("%.2x", hash[i]);
473         }
474         printf ("\n");
475 }
476 #endif
477
478 string
479 md5_digest (string file)
480 {
481         ifstream f (file.c_str(), ios::binary);
482         if (!f.good ()) {
483                 throw OpenFileError (file);
484         }
485         
486         f.seekg (0, ios::end);
487         int bytes = f.tellg ();
488         f.seekg (0, ios::beg);
489
490         int const buffer_size = 64 * 1024;
491         char buffer[buffer_size];
492
493         MD5_CTX md5_context;
494         MD5_Init (&md5_context);
495         while (bytes > 0) {
496                 int const t = min (bytes, buffer_size);
497                 f.read (buffer, t);
498                 MD5_Update (&md5_context, buffer, t);
499                 bytes -= t;
500         }
501
502         unsigned char digest[MD5_DIGEST_LENGTH];
503         MD5_Final (digest, &md5_context);
504
505         stringstream s;
506         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
507                 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
508         }
509
510         return s.str ();
511 }
512
513 int
514 dcp_audio_sample_rate (int fs)
515 {
516         if (fs <= 48000) {
517                 return 48000;
518         }
519
520         return 96000;
521 }