Merge branch 'master' of /home/carl/git/dvdomatic
[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 /** @param s Sample format.
193  *  @return String representation.
194  */
195 string
196 audio_sample_format_to_string (AVSampleFormat s)
197 {
198         /* Our sample format handling is not exactly complete */
199         
200         switch (s) {
201         case AV_SAMPLE_FMT_S16:
202                 return "S16";
203         default:
204                 break;
205         }
206
207         return "Unknown";
208 }
209
210 /** @param s String representation of a sample format, as returned from audio_sample_format_to_string().
211  *  @return Sample format.
212  */
213 AVSampleFormat
214 audio_sample_format_from_string (string s)
215 {
216         if (s == "S16") {
217                 return AV_SAMPLE_FMT_S16;
218         }
219
220         return AV_SAMPLE_FMT_NONE;
221 }
222
223 /** @return Version of vobcopy that is on the path (and hence that we will use) */
224 static string
225 vobcopy_version ()
226 {
227         FILE* f = popen ("vobcopy -V 2>&1", "r");
228         if (f == 0) {
229                 throw EncodeError ("could not run vobcopy to check version");
230         }
231
232         string version = "unknown";
233         
234         while (!feof (f)) {
235                 char buf[256];
236                 if (fgets (buf, sizeof (buf), f)) {
237                         string s (buf);
238                         vector<string> b;
239                         split (b, s, is_any_of (" "));
240                         if (b.size() >= 2 && b[0] == "Vobcopy") {
241                                 version = b[1];
242                         }
243                 }
244         }
245
246         pclose (f);
247
248         return version;
249 }
250
251 /** @param v Version as used by FFmpeg.
252  *  @return A string representation of v.
253  */
254 static string
255 ffmpeg_version_to_string (int v)
256 {
257         stringstream s;
258         s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
259         return s.str ();
260 }
261
262 /** Return a user-readable string summarising the versions of our dependencies */
263 string
264 dependency_version_summary ()
265 {
266         stringstream s;
267         s << "libopenjpeg " << opj_version () << ", "
268           << "vobcopy " << vobcopy_version() << ", "
269           << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
270           << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
271           << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
272           << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
273           << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
274           << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
275           << MagickVersion << ", "
276           << "libssh " << ssh_version (0) << ", "
277           << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
278
279         return s.str ();
280 }
281
282 double
283 seconds (struct timeval t)
284 {
285         return t.tv_sec + (double (t.tv_usec) / 1e6);
286 }
287
288
289 #ifdef DVDOMATIC_POSIX
290 void
291 sigchld_handler (int, siginfo_t* info, void *)
292 {
293 #ifndef DVDOMATIC_DISABLE_PLAYER        
294         PlayerManager::instance()->child_exited (info->si_pid);
295 #endif  
296 }
297 #endif
298
299 /** Call the required functions to set up DVD-o-matic's static arrays, etc. */
300 void
301 dvdomatic_setup ()
302 {
303         Format::setup_formats ();
304         DCPContentType::setup_dcp_content_types ();
305         Scaler::setup_scalers ();
306         Filter::setup_filters ();
307         SoundProcessor::setup_sound_processors ();
308
309 #ifdef DVDOMATIC_POSIX  
310         struct sigaction sa;
311         sa.sa_flags = SA_SIGINFO;
312         sigemptyset (&sa.sa_mask);
313         sa.sa_sigaction = sigchld_handler;
314         sigaction (SIGCHLD, &sa, 0);
315 #endif  
316 }
317
318 string
319 crop_string (Position start, Size size)
320 {
321         stringstream s;
322         s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
323         return s.str ();
324 }
325
326 vector<string>
327 split_at_spaces_considering_quotes (string s)
328 {
329         vector<string> out;
330         bool in_quotes = false;
331         string c;
332         for (string::size_type i = 0; i < s.length(); ++i) {
333                 if (s[i] == ' ' && !in_quotes) {
334                         out.push_back (c);
335                         c = "";
336                 } else if (s[i] == '"') {
337                         in_quotes = !in_quotes;
338                 } else {
339                         c += s[i];
340                 }
341         }
342
343         out.push_back (c);
344         return out;
345 }
346
347 string
348 md5_digest (void const * data, int size)
349 {
350         MD5_CTX md5_context;
351         MD5_Init (&md5_context);
352         MD5_Update (&md5_context, data, size);
353         unsigned char digest[MD5_DIGEST_LENGTH];
354         MD5_Final (digest, &md5_context);
355         
356         stringstream s;
357         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
358                 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
359         }
360
361         return s.str ();
362 }
363
364 /** @param file File name.
365  *  @return MD5 digest of file's contents.
366  */
367 string
368 md5_digest (string file)
369 {
370         ifstream f (file.c_str(), ios::binary);
371         if (!f.good ()) {
372                 throw OpenFileError (file);
373         }
374         
375         f.seekg (0, ios::end);
376         int bytes = f.tellg ();
377         f.seekg (0, ios::beg);
378
379         int const buffer_size = 64 * 1024;
380         char buffer[buffer_size];
381
382         MD5_CTX md5_context;
383         MD5_Init (&md5_context);
384         while (bytes > 0) {
385                 int const t = min (bytes, buffer_size);
386                 f.read (buffer, t);
387                 MD5_Update (&md5_context, buffer, t);
388                 bytes -= t;
389         }
390
391         unsigned char digest[MD5_DIGEST_LENGTH];
392         MD5_Final (digest, &md5_context);
393
394         stringstream s;
395         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
396                 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
397         }
398
399         return s.str ();
400 }
401
402 /** @param An arbitrary sampling rate.
403  *  @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
404  */
405 int
406 dcp_audio_sample_rate (int fs)
407 {
408         if (fs <= 48000) {
409                 return 48000;
410         }
411
412         return 96000;
413 }
414
415 bool operator== (Crop const & a, Crop const & b)
416 {
417         return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
418 }
419
420 bool operator!= (Crop const & a, Crop const & b)
421 {
422         return !(a == b);
423 }
424
425 /** @param index Colour LUT index.
426  *  @return Human-readable name.
427  */
428 string
429 colour_lut_index_to_name (int index)
430 {
431         switch (index) {
432         case 0:
433                 return "sRGB";
434         case 1:
435                 return "Rec 709";
436         }
437
438         assert (false);
439         return "";
440 }
441
442 Socket::Socket ()
443         : _deadline (_io_service)
444         , _socket (_io_service)
445         , _buffer_data (0)
446 {
447         _deadline.expires_at (posix_time::pos_infin);
448         check ();
449 }
450
451 void
452 Socket::check ()
453 {
454         if (_deadline.expires_at() <= asio::deadline_timer::traits_type::now ()) {
455                 _socket.close ();
456                 _deadline.expires_at (posix_time::pos_infin);
457         }
458
459         _deadline.async_wait (boost::bind (&Socket::check, this));
460 }
461
462 /** Blocking connect with timeout.
463  *  @param endpoint End-point to connect to.
464  *  @param timeout Time-out in seconds.
465  */
466 void
467 Socket::connect (asio::ip::basic_resolver_entry<asio::ip::tcp> const & endpoint, int timeout)
468 {
469         system::error_code ec = asio::error::would_block;
470         _socket.async_connect (endpoint, lambda::var(ec) = lambda::_1);
471         do {
472                 _io_service.run_one();
473         } while (ec == asio::error::would_block);
474
475         if (ec || !_socket.is_open ()) {
476                 throw NetworkError ("connect timed out");
477         }
478 }
479
480 /** Blocking write with timeout.
481  *  @param data Buffer to write.
482  *  @param size Number of bytes to write.
483  *  @param timeout Time-out, in seconds.
484  */
485 void
486 Socket::write (uint8_t const * data, int size, int timeout)
487 {
488         _deadline.expires_from_now (posix_time::seconds (timeout));
489         system::error_code ec = asio::error::would_block;
490
491         asio::async_write (_socket, asio::buffer (data, size), lambda::var(ec) = lambda::_1);
492         do {
493                 _io_service.run_one ();
494         } while (ec == asio::error::would_block);
495
496         if (ec) {
497                 throw NetworkError ("write timed out");
498         }
499 }
500
501 /** Blocking read with timeout.
502  *  @param data Buffer to read to.
503  *  @param size Number of bytes to read.
504  *  @param timeout Time-out, in seconds.
505  */
506 int
507 Socket::read (uint8_t* data, int size, int timeout)
508 {
509         _deadline.expires_from_now (posix_time::seconds (timeout));
510         system::error_code ec = asio::error::would_block;
511
512         int amount_read = 0;
513
514         _socket.async_read_some (
515                 asio::buffer (data, size),
516                 (lambda::var(ec) = lambda::_1, lambda::var(amount_read) = lambda::_2)
517                 );
518
519         do {
520                 _io_service.run_one ();
521         } while (ec == asio::error::would_block);
522         
523         if (ec) {
524                 amount_read = 0;
525         }
526
527         return amount_read;
528 }
529
530 /** Mark some data as being `consumed', so that it will not be returned
531  *  as data again.
532  *  @param size Amount of data to consume, in bytes.
533  */
534 void
535 Socket::consume (int size)
536 {
537         assert (_buffer_data >= size);
538         
539         _buffer_data -= size;
540         if (_buffer_data > 0) {
541                 /* Shift still-valid data to the start of the buffer */
542                 memmove (_buffer, _buffer + size, _buffer_data);
543         }
544 }
545
546 /** Read a definite amount of data from our socket, and mark
547  *  it as consumed.
548  *  @param data Where to put the data.
549  *  @param size Number of bytes to read.
550  */
551 void
552 Socket::read_definite_and_consume (uint8_t* data, int size, int timeout)
553 {
554         int const from_buffer = min (_buffer_data, size);
555         if (from_buffer > 0) {
556                 /* Get data from our buffer */
557                 memcpy (data, _buffer, from_buffer);
558                 consume (from_buffer);
559                 /* Update our output state */
560                 data += from_buffer;
561                 size -= from_buffer;
562         }
563
564         /* read() the rest */
565         while (size > 0) {
566                 int const n = read (data, size, timeout);
567                 if (n <= 0) {
568                         throw NetworkError ("could not read");
569                 }
570
571                 data += n;
572                 size -= n;
573         }
574 }
575
576 /** Read as much data as is available, up to some limit.
577  *  @param data Where to put the data.
578  *  @param size Maximum amount of data to read.
579  */
580 void
581 Socket::read_indefinite (uint8_t* data, int size, int timeout)
582 {
583         assert (size < int (sizeof (_buffer)));
584
585         /* Amount of extra data we need to read () */
586         int to_read = size - _buffer_data;
587         while (to_read > 0) {
588                 /* read as much of it as we can (into our buffer) */
589                 int const n = read (_buffer + _buffer_data, to_read, timeout);
590                 if (n <= 0) {
591                         throw NetworkError ("could not read");
592                 }
593
594                 to_read -= n;
595                 _buffer_data += n;
596         }
597
598         assert (_buffer_data >= size);
599
600         /* copy data into the output buffer */
601         assert (size >= _buffer_data);
602         memcpy (data, _buffer, size);
603 }
604
605 Rectangle
606 Rectangle::intersection (Rectangle const & other) const
607 {
608         int const tx = max (x, other.x);
609         int const ty = max (y, other.y);
610         
611         return Rectangle (
612                 tx, ty,
613                 min (x + width, other.x + other.width) - tx,
614                 min (y + height, other.y + other.height) - ty
615                 );
616 }
617
618 int
619 round_up (int a, int t)
620 {
621         a += (t - 1);
622         return a - (a % t);
623 }
624
625 multimap<string, string>
626 read_key_value (istream &s) 
627 {
628         multimap<string, string> kv;
629         
630         string line;
631         while (getline (s, line)) {
632                 if (line.empty ()) {
633                         continue;
634                 }
635                 
636                 if (line[0] == '#') {
637                         continue;
638                 }
639
640                 if (line[line.size() - 1] == '\r') {
641                         line = line.substr (0, line.size() - 1);
642                 }
643
644                 size_t const s = line.find (' ');
645                 if (s == string::npos) {
646                         continue;
647                 }
648
649                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
650         }
651
652         return kv;
653 }
654
655 string
656 get_required_string (multimap<string, string> const & kv, string k)
657 {
658         if (kv.count (k) > 1) {
659                 throw StringError ("unexpected multiple keys in key-value set");
660         }
661
662         multimap<string, string>::const_iterator i = kv.find (k);
663         
664         if (i == kv.end ()) {
665                 throw StringError (String::compose ("missing key %1 in key-value set", k));
666         }
667
668         return i->second;
669 }
670
671 int
672 get_required_int (multimap<string, string> const & kv, string k)
673 {
674         string const v = get_required_string (kv, k);
675         return lexical_cast<int> (v);
676 }
677
678 string
679 get_optional_string (multimap<string, string> const & kv, string k)
680 {
681         if (kv.count (k) > 1) {
682                 throw StringError ("unexpected multiple keys in key-value set");
683         }
684
685         multimap<string, string>::const_iterator i = kv.find (k);
686         if (i == kv.end ()) {
687                 return "";
688         }
689
690         return i->second;
691 }
692
693 int
694 get_optional_int (multimap<string, string> const & kv, string k)
695 {
696         if (kv.count (k) > 1) {
697                 throw StringError ("unexpected multiple keys in key-value set");
698         }
699
700         multimap<string, string>::const_iterator i = kv.find (k);
701         if (i == kv.end ()) {
702                 return 0;
703         }
704
705         return lexical_cast<int> (i->second);
706 }