Clean up audio passing round a bit.
[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 <boost/bind.hpp>
37 #include <boost/lambda/lambda.hpp>
38 #include <boost/lexical_cast.hpp>
39 #include <openjpeg.h>
40 #include <openssl/md5.h>
41 #include <magick/MagickCore.h>
42 #include <magick/version.h>
43 #include <libdcp/version.h>
44 extern "C" {
45 #include <libavcodec/avcodec.h>
46 #include <libavformat/avformat.h>
47 #include <libswscale/swscale.h>
48 #include <libavfilter/avfiltergraph.h>
49 #include <libpostproc/postprocess.h>
50 #include <libavutil/pixfmt.h>
51 }
52 #include "util.h"
53 #include "exceptions.h"
54 #include "scaler.h"
55 #include "format.h"
56 #include "dcp_content_type.h"
57 #include "filter.h"
58 #include "screen.h"
59 #include "film_state.h"
60 #include "sound_processor.h"
61 #ifndef DVDOMATIC_DISABLE_PLAYER
62 #include "player_manager.h"
63 #endif
64
65 using namespace std;
66 using namespace boost;
67
68 /** Convert some number of seconds to a string representation
69  *  in hours, minutes and seconds.
70  *
71  *  @param s Seconds.
72  *  @return String of the form H:M:S (where H is hours, M
73  *  is minutes and S is seconds).
74  */
75 string
76 seconds_to_hms (int s)
77 {
78         int m = s / 60;
79         s -= (m * 60);
80         int h = m / 60;
81         m -= (h * 60);
82
83         stringstream hms;
84         hms << h << ":";
85         hms.width (2);
86         hms << setfill ('0') << m << ":";
87         hms.width (2);
88         hms << setfill ('0') << s;
89
90         return hms.str ();
91 }
92
93 /** @param s Number of seconds.
94  *  @return String containing an approximate description of s (e.g. "about 2 hours")
95  */
96 string
97 seconds_to_approximate_hms (int s)
98 {
99         int m = s / 60;
100         s -= (m * 60);
101         int h = m / 60;
102         m -= (h * 60);
103
104         stringstream ap;
105         
106         if (h > 0) {
107                 if (m > 30) {
108                         ap << (h + 1) << " hours";
109                 } else {
110                         if (h == 1) {
111                                 ap << "1 hour";
112                         } else {
113                                 ap << h << " hours";
114                         }
115                 }
116         } else if (m > 0) {
117                 if (m == 1) {
118                         ap << "1 minute";
119                 } else {
120                         ap << m << " minutes";
121                 }
122         } else {
123                 ap << s << " seconds";
124         }
125
126         return ap.str ();
127 }
128
129 #ifdef DVDOMATIC_POSIX
130 /** @param l Mangled C++ identifier.
131  *  @return Demangled version.
132  */
133 static string
134 demangle (string l)
135 {
136         string::size_type const b = l.find_first_of ("(");
137         if (b == string::npos) {
138                 return l;
139         }
140
141         string::size_type const p = l.find_last_of ("+");
142         if (p == string::npos) {
143                 return l;
144         }
145
146         if ((p - b) <= 1) {
147                 return l;
148         }
149         
150         string const fn = l.substr (b + 1, p - b - 1);
151
152         int status;
153         try {
154                 
155                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
156                 string d (realname);
157                 free (realname);
158                 return d;
159                 
160         } catch (std::exception) {
161                 
162         }
163         
164         return l;
165 }
166
167 /** Write a stacktrace to an ostream.
168  *  @param out Stream to write to.
169  *  @param levels Number of levels to go up the call stack.
170  */
171 void
172 stacktrace (ostream& out, int levels)
173 {
174         void *array[200];
175         size_t size;
176         char **strings;
177         size_t i;
178      
179         size = backtrace (array, 200);
180         strings = backtrace_symbols (array, size);
181      
182         if (strings) {
183                 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
184                         out << "  " << demangle (strings[i]) << endl;
185                 }
186                 
187                 free (strings);
188         }
189 }
190 #endif
191
192 /** @return Version of vobcopy that is on the path (and hence that we will use) */
193 static string
194 vobcopy_version ()
195 {
196         FILE* f = popen ("vobcopy -V 2>&1", "r");
197         if (f == 0) {
198                 throw EncodeError ("could not run vobcopy to check version");
199         }
200
201         string version = "unknown";
202         
203         while (!feof (f)) {
204                 char buf[256];
205                 if (fgets (buf, sizeof (buf), f)) {
206                         string s (buf);
207                         vector<string> b;
208                         split (b, s, is_any_of (" "));
209                         if (b.size() >= 2 && b[0] == "Vobcopy") {
210                                 version = b[1];
211                         }
212                 }
213         }
214
215         pclose (f);
216
217         return version;
218 }
219
220 /** @param v Version as used by FFmpeg.
221  *  @return A string representation of v.
222  */
223 static string
224 ffmpeg_version_to_string (int v)
225 {
226         stringstream s;
227         s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
228         return s.str ();
229 }
230
231 /** Return a user-readable string summarising the versions of our dependencies */
232 string
233 dependency_version_summary ()
234 {
235         stringstream s;
236         s << "libopenjpeg " << opj_version () << ", "
237           << "vobcopy " << vobcopy_version() << ", "
238           << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
239           << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
240           << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
241           << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
242           << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
243           << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
244           << MagickVersion << ", "
245           << "libssh " << ssh_version (0) << ", "
246           << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
247
248         return s.str ();
249 }
250
251 double
252 seconds (struct timeval t)
253 {
254         return t.tv_sec + (double (t.tv_usec) / 1e6);
255 }
256
257
258 #ifdef DVDOMATIC_POSIX
259 void
260 sigchld_handler (int, siginfo_t* info, void *)
261 {
262 #ifndef DVDOMATIC_DISABLE_PLAYER        
263         PlayerManager::instance()->child_exited (info->si_pid);
264 #endif  
265 }
266 #endif
267
268 /** Call the required functions to set up DVD-o-matic's static arrays, etc. */
269 void
270 dvdomatic_setup ()
271 {
272         Format::setup_formats ();
273         DCPContentType::setup_dcp_content_types ();
274         Scaler::setup_scalers ();
275         Filter::setup_filters ();
276         SoundProcessor::setup_sound_processors ();
277
278 #ifdef DVDOMATIC_POSIX  
279         struct sigaction sa;
280         sa.sa_flags = SA_SIGINFO;
281         sigemptyset (&sa.sa_mask);
282         sa.sa_sigaction = sigchld_handler;
283         sigaction (SIGCHLD, &sa, 0);
284 #endif  
285 }
286
287 string
288 crop_string (Position start, Size size)
289 {
290         stringstream s;
291         s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
292         return s.str ();
293 }
294
295 vector<string>
296 split_at_spaces_considering_quotes (string s)
297 {
298         vector<string> out;
299         bool in_quotes = false;
300         string c;
301         for (string::size_type i = 0; i < s.length(); ++i) {
302                 if (s[i] == ' ' && !in_quotes) {
303                         out.push_back (c);
304                         c = "";
305                 } else if (s[i] == '"') {
306                         in_quotes = !in_quotes;
307                 } else {
308                         c += s[i];
309                 }
310         }
311
312         out.push_back (c);
313         return out;
314 }
315
316 string
317 md5_digest (void const * data, int size)
318 {
319         MD5_CTX md5_context;
320         MD5_Init (&md5_context);
321         MD5_Update (&md5_context, data, size);
322         unsigned char digest[MD5_DIGEST_LENGTH];
323         MD5_Final (digest, &md5_context);
324         
325         stringstream s;
326         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
327                 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
328         }
329
330         return s.str ();
331 }
332
333 /** @param file File name.
334  *  @return MD5 digest of file's contents.
335  */
336 string
337 md5_digest (string file)
338 {
339         ifstream f (file.c_str(), ios::binary);
340         if (!f.good ()) {
341                 throw OpenFileError (file);
342         }
343         
344         f.seekg (0, ios::end);
345         int bytes = f.tellg ();
346         f.seekg (0, ios::beg);
347
348         int const buffer_size = 64 * 1024;
349         char buffer[buffer_size];
350
351         MD5_CTX md5_context;
352         MD5_Init (&md5_context);
353         while (bytes > 0) {
354                 int const t = min (bytes, buffer_size);
355                 f.read (buffer, t);
356                 MD5_Update (&md5_context, buffer, t);
357                 bytes -= t;
358         }
359
360         unsigned char digest[MD5_DIGEST_LENGTH];
361         MD5_Final (digest, &md5_context);
362
363         stringstream s;
364         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
365                 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
366         }
367
368         return s.str ();
369 }
370
371 /** @param An arbitrary sampling rate.
372  *  @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
373  */
374 int
375 dcp_audio_sample_rate (int fs)
376 {
377         if (fs <= 48000) {
378                 return 48000;
379         }
380
381         return 96000;
382 }
383
384 bool operator== (Crop const & a, Crop const & b)
385 {
386         return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
387 }
388
389 bool operator!= (Crop const & a, Crop const & b)
390 {
391         return !(a == b);
392 }
393
394 /** @param index Colour LUT index.
395  *  @return Human-readable name.
396  */
397 string
398 colour_lut_index_to_name (int index)
399 {
400         switch (index) {
401         case 0:
402                 return "sRGB";
403         case 1:
404                 return "Rec 709";
405         }
406
407         assert (false);
408         return "";
409 }
410
411 Socket::Socket ()
412         : _deadline (_io_service)
413         , _socket (_io_service)
414         , _buffer_data (0)
415 {
416         _deadline.expires_at (posix_time::pos_infin);
417         check ();
418 }
419
420 void
421 Socket::check ()
422 {
423         if (_deadline.expires_at() <= asio::deadline_timer::traits_type::now ()) {
424                 _socket.close ();
425                 _deadline.expires_at (posix_time::pos_infin);
426         }
427
428         _deadline.async_wait (boost::bind (&Socket::check, this));
429 }
430
431 /** Blocking connect with timeout.
432  *  @param endpoint End-point to connect to.
433  *  @param timeout Time-out in seconds.
434  */
435 void
436 Socket::connect (asio::ip::basic_resolver_entry<asio::ip::tcp> const & endpoint, int timeout)
437 {
438         system::error_code ec = asio::error::would_block;
439         _socket.async_connect (endpoint, lambda::var(ec) = lambda::_1);
440         do {
441                 _io_service.run_one();
442         } while (ec == asio::error::would_block);
443
444         if (ec || !_socket.is_open ()) {
445                 throw NetworkError ("connect timed out");
446         }
447 }
448
449 /** Blocking write with timeout.
450  *  @param data Buffer to write.
451  *  @param size Number of bytes to write.
452  *  @param timeout Time-out, in seconds.
453  */
454 void
455 Socket::write (uint8_t const * data, int size, int timeout)
456 {
457         _deadline.expires_from_now (posix_time::seconds (timeout));
458         system::error_code ec = asio::error::would_block;
459
460         asio::async_write (_socket, asio::buffer (data, size), lambda::var(ec) = lambda::_1);
461         do {
462                 _io_service.run_one ();
463         } while (ec == asio::error::would_block);
464
465         if (ec) {
466                 throw NetworkError ("write timed out");
467         }
468 }
469
470 /** Blocking read with timeout.
471  *  @param data Buffer to read to.
472  *  @param size Number of bytes to read.
473  *  @param timeout Time-out, in seconds.
474  */
475 int
476 Socket::read (uint8_t* data, int size, int timeout)
477 {
478         _deadline.expires_from_now (posix_time::seconds (timeout));
479         system::error_code ec = asio::error::would_block;
480
481         int amount_read = 0;
482
483         _socket.async_read_some (
484                 asio::buffer (data, size),
485                 (lambda::var(ec) = lambda::_1, lambda::var(amount_read) = lambda::_2)
486                 );
487
488         do {
489                 _io_service.run_one ();
490         } while (ec == asio::error::would_block);
491         
492         if (ec) {
493                 amount_read = 0;
494         }
495
496         return amount_read;
497 }
498
499 /** Mark some data as being `consumed', so that it will not be returned
500  *  as data again.
501  *  @param size Amount of data to consume, in bytes.
502  */
503 void
504 Socket::consume (int size)
505 {
506         assert (_buffer_data >= size);
507         
508         _buffer_data -= size;
509         if (_buffer_data > 0) {
510                 /* Shift still-valid data to the start of the buffer */
511                 memmove (_buffer, _buffer + size, _buffer_data);
512         }
513 }
514
515 /** Read a definite amount of data from our socket, and mark
516  *  it as consumed.
517  *  @param data Where to put the data.
518  *  @param size Number of bytes to read.
519  */
520 void
521 Socket::read_definite_and_consume (uint8_t* data, int size, int timeout)
522 {
523         int const from_buffer = min (_buffer_data, size);
524         if (from_buffer > 0) {
525                 /* Get data from our buffer */
526                 memcpy (data, _buffer, from_buffer);
527                 consume (from_buffer);
528                 /* Update our output state */
529                 data += from_buffer;
530                 size -= from_buffer;
531         }
532
533         /* read() the rest */
534         while (size > 0) {
535                 int const n = read (data, size, timeout);
536                 if (n <= 0) {
537                         throw NetworkError ("could not read");
538                 }
539
540                 data += n;
541                 size -= n;
542         }
543 }
544
545 /** Read as much data as is available, up to some limit.
546  *  @param data Where to put the data.
547  *  @param size Maximum amount of data to read.
548  */
549 void
550 Socket::read_indefinite (uint8_t* data, int size, int timeout)
551 {
552         assert (size < int (sizeof (_buffer)));
553
554         /* Amount of extra data we need to read () */
555         int to_read = size - _buffer_data;
556         while (to_read > 0) {
557                 /* read as much of it as we can (into our buffer) */
558                 int const n = read (_buffer + _buffer_data, to_read, timeout);
559                 if (n <= 0) {
560                         throw NetworkError ("could not read");
561                 }
562
563                 to_read -= n;
564                 _buffer_data += n;
565         }
566
567         assert (_buffer_data >= size);
568
569         /* copy data into the output buffer */
570         assert (size >= _buffer_data);
571         memcpy (data, _buffer, size);
572 }
573
574 Rect
575 Rect::intersection (Rect const & other) const
576 {
577         int const tx = max (x, other.x);
578         int const ty = max (y, other.y);
579         
580         return Rect (
581                 tx, ty,
582                 min (x + width, other.x + other.width) - tx,
583                 min (y + height, other.y + other.height) - ty
584                 );
585 }
586
587 /** Round a number up to the nearest multiple of another number.
588  *  @param a Number to round.
589  *  @param t Multiple to round to.
590  *  @return Rounded number.
591  */
592
593 int
594 round_up (int a, int t)
595 {
596         a += (t - 1);
597         return a - (a % t);
598 }
599
600 /** Read a sequence of key / value pairs from a text stream;
601  *  the keys are the first words on the line, and the values are
602  *  the remainder of the line following the key.  Lines beginning
603  *  with # are ignored.
604  *  @param s Stream to read.
605  *  @return key/value pairs.
606  */
607 multimap<string, string>
608 read_key_value (istream &s) 
609 {
610         multimap<string, string> kv;
611         
612         string line;
613         while (getline (s, line)) {
614                 if (line.empty ()) {
615                         continue;
616                 }
617                 
618                 if (line[0] == '#') {
619                         continue;
620                 }
621
622                 if (line[line.size() - 1] == '\r') {
623                         line = line.substr (0, line.size() - 1);
624                 }
625
626                 size_t const s = line.find (' ');
627                 if (s == string::npos) {
628                         continue;
629                 }
630
631                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
632         }
633
634         return kv;
635 }
636
637 string
638 get_required_string (multimap<string, string> const & kv, string k)
639 {
640         if (kv.count (k) > 1) {
641                 throw StringError ("unexpected multiple keys in key-value set");
642         }
643
644         multimap<string, string>::const_iterator i = kv.find (k);
645         
646         if (i == kv.end ()) {
647                 throw StringError (String::compose ("missing key %1 in key-value set", k));
648         }
649
650         return i->second;
651 }
652
653 int
654 get_required_int (multimap<string, string> const & kv, string k)
655 {
656         string const v = get_required_string (kv, k);
657         return lexical_cast<int> (v);
658 }
659
660 float
661 get_required_float (multimap<string, string> const & kv, string k)
662 {
663         string const v = get_required_string (kv, k);
664         return lexical_cast<float> (v);
665 }
666
667 string
668 get_optional_string (multimap<string, string> const & kv, string k)
669 {
670         if (kv.count (k) > 1) {
671                 throw StringError ("unexpected multiple keys in key-value set");
672         }
673
674         multimap<string, string>::const_iterator i = kv.find (k);
675         if (i == kv.end ()) {
676                 return "";
677         }
678
679         return i->second;
680 }
681
682 int
683 get_optional_int (multimap<string, string> const & kv, string k)
684 {
685         if (kv.count (k) > 1) {
686                 throw StringError ("unexpected multiple keys in key-value set");
687         }
688
689         multimap<string, string>::const_iterator i = kv.find (k);
690         if (i == kv.end ()) {
691                 return 0;
692         }
693
694         return lexical_cast<int> (i->second);
695 }
696
697 AudioBuffers::AudioBuffers (int channels, int frames)
698         : _channels (channels)
699         , _frames (frames)
700 {
701         _data = new float*[_channels];
702         for (int i = 0; i < _channels; ++i) {
703                 _data[i] = new float[frames];
704         }
705 }
706
707 AudioBuffers::~AudioBuffers ()
708 {
709         for (int i = 0; i < _channels; ++i) {
710                 delete[] _data[i];
711         }
712
713         delete[] _data;
714 }
715
716 float*
717 AudioBuffers::data (int c) const
718 {
719         assert (c >= 0 && c < _channels);
720         return _data[c];
721 }
722         
723 void
724 AudioBuffers::set_frames (int f)
725 {
726         assert (f <= _frames);
727         _frames = f;
728 }
729
730         
731