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