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