Merge branch 'master' into video-player
[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 <boost/filesystem.hpp>
41 #include <openjpeg.h>
42 #include <openssl/md5.h>
43 #include <magick/MagickCore.h>
44 #include <magick/version.h>
45 #include <libdcp/version.h>
46 extern "C" {
47 #include <libavcodec/avcodec.h>
48 #include <libavformat/avformat.h>
49 #include <libswscale/swscale.h>
50 #include <libavfilter/avfiltergraph.h>
51 #include <libpostproc/postprocess.h>
52 #include <libavutil/pixfmt.h>
53 }
54 #include "util.h"
55 #include "exceptions.h"
56 #include "scaler.h"
57 #include "format.h"
58 #include "dcp_content_type.h"
59 #include "filter.h"
60 #include "sound_processor.h"
61
62 using namespace std;
63 using namespace boost;
64
65 thread::id ui_thread;
66
67 /** Convert some number of seconds to a string representation
68  *  in hours, minutes and seconds.
69  *
70  *  @param s Seconds.
71  *  @return String of the form H:M:S (where H is hours, M
72  *  is minutes and S is seconds).
73  */
74 string
75 seconds_to_hms (int s)
76 {
77         int m = s / 60;
78         s -= (m * 60);
79         int h = m / 60;
80         m -= (h * 60);
81
82         stringstream hms;
83         hms << h << ":";
84         hms.width (2);
85         hms << setfill ('0') << m << ":";
86         hms.width (2);
87         hms << setfill ('0') << s;
88
89         return hms.str ();
90 }
91
92 /** @param s Number of seconds.
93  *  @return String containing an approximate description of s (e.g. "about 2 hours")
94  */
95 string
96 seconds_to_approximate_hms (int s)
97 {
98         int m = s / 60;
99         s -= (m * 60);
100         int h = m / 60;
101         m -= (h * 60);
102
103         stringstream ap;
104         
105         if (h > 0) {
106                 if (m > 30) {
107                         ap << (h + 1) << " hours";
108                 } else {
109                         if (h == 1) {
110                                 ap << "1 hour";
111                         } else {
112                                 ap << h << " hours";
113                         }
114                 }
115         } else if (m > 0) {
116                 if (m == 1) {
117                         ap << "1 minute";
118                 } else {
119                         ap << m << " minutes";
120                 }
121         } else {
122                 ap << s << " seconds";
123         }
124
125         return ap.str ();
126 }
127
128 #ifdef DVDOMATIC_POSIX
129 /** @param l Mangled C++ identifier.
130  *  @return Demangled version.
131  */
132 static string
133 demangle (string l)
134 {
135         string::size_type const b = l.find_first_of ("(");
136         if (b == string::npos) {
137                 return l;
138         }
139
140         string::size_type const p = l.find_last_of ("+");
141         if (p == string::npos) {
142                 return l;
143         }
144
145         if ((p - b) <= 1) {
146                 return l;
147         }
148         
149         string const fn = l.substr (b + 1, p - b - 1);
150
151         int status;
152         try {
153                 
154                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
155                 string d (realname);
156                 free (realname);
157                 return d;
158                 
159         } catch (std::exception) {
160                 
161         }
162         
163         return l;
164 }
165
166 /** Write a stacktrace to an ostream.
167  *  @param out Stream to write to.
168  *  @param levels Number of levels to go up the call stack.
169  */
170 void
171 stacktrace (ostream& out, int levels)
172 {
173         void *array[200];
174         size_t size;
175         char **strings;
176         size_t i;
177      
178         size = backtrace (array, 200);
179         strings = backtrace_symbols (array, size);
180      
181         if (strings) {
182                 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
183                         out << "  " << demangle (strings[i]) << endl;
184                 }
185                 
186                 free (strings);
187         }
188 }
189 #endif
190
191 /** @param v Version as used by FFmpeg.
192  *  @return A string representation of v.
193  */
194 static string
195 ffmpeg_version_to_string (int v)
196 {
197         stringstream s;
198         s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
199         return s.str ();
200 }
201
202 /** Return a user-readable string summarising the versions of our dependencies */
203 string
204 dependency_version_summary ()
205 {
206         stringstream s;
207         s << "libopenjpeg " << opj_version () << ", "
208           << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
209           << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
210           << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
211           << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
212           << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
213           << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
214           << MagickVersion << ", "
215           << "libssh " << ssh_version (0) << ", "
216           << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
217
218         return s.str ();
219 }
220
221 double
222 seconds (struct timeval t)
223 {
224         return t.tv_sec + (double (t.tv_usec) / 1e6);
225 }
226
227 /** Call the required functions to set up DVD-o-matic's static arrays, etc.
228  *  Must be called from the UI thread, if there is one.
229  */
230 void
231 dvdomatic_setup ()
232 {
233         Format::setup_formats ();
234         DCPContentType::setup_dcp_content_types ();
235         Scaler::setup_scalers ();
236         Filter::setup_filters ();
237         SoundProcessor::setup_sound_processors ();
238
239         ui_thread = this_thread::get_id ();
240 }
241
242 /** @param start Start position for the crop within the image.
243  *  @param size Size of the cropped area.
244  *  @return FFmpeg crop filter string.
245  */
246 string
247 crop_string (Position start, Size size)
248 {
249         stringstream s;
250         s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
251         return s.str ();
252 }
253
254 /** @param s A string.
255  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
256  */
257 vector<string>
258 split_at_spaces_considering_quotes (string s)
259 {
260         vector<string> out;
261         bool in_quotes = false;
262         string c;
263         for (string::size_type i = 0; i < s.length(); ++i) {
264                 if (s[i] == ' ' && !in_quotes) {
265                         out.push_back (c);
266                         c = "";
267                 } else if (s[i] == '"') {
268                         in_quotes = !in_quotes;
269                 } else {
270                         c += s[i];
271                 }
272         }
273
274         out.push_back (c);
275         return out;
276 }
277
278 string
279 md5_digest (void const * data, int size)
280 {
281         MD5_CTX md5_context;
282         MD5_Init (&md5_context);
283         MD5_Update (&md5_context, data, size);
284         unsigned char digest[MD5_DIGEST_LENGTH];
285         MD5_Final (digest, &md5_context);
286         
287         stringstream s;
288         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
289                 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
290         }
291
292         return s.str ();
293 }
294
295 /** @param file File name.
296  *  @return MD5 digest of file's contents.
297  */
298 string
299 md5_digest (string file)
300 {
301         ifstream f (file.c_str(), ios::binary);
302         if (!f.good ()) {
303                 throw OpenFileError (file);
304         }
305         
306         f.seekg (0, ios::end);
307         int bytes = f.tellg ();
308         f.seekg (0, ios::beg);
309
310         int const buffer_size = 64 * 1024;
311         char buffer[buffer_size];
312
313         MD5_CTX md5_context;
314         MD5_Init (&md5_context);
315         while (bytes > 0) {
316                 int const t = min (bytes, buffer_size);
317                 f.read (buffer, t);
318                 MD5_Update (&md5_context, buffer, t);
319                 bytes -= t;
320         }
321
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 fps Arbitrary frames-per-second value.
334  *  @return DCPFrameRate for this frames-per-second.
335  */
336 DCPFrameRate
337 dcp_frame_rate (float fps)
338 {
339         DCPFrameRate dfr;
340
341         dfr.run_fast = (fps != rint (fps));
342         dfr.frames_per_second = rint (fps);
343         dfr.skip = 1;
344
345         /* XXX: somewhat arbitrary */
346         if (fps == 50) {
347                 dfr.frames_per_second = 25;
348                 dfr.skip = 2;
349         }
350
351         return dfr;
352 }
353
354 /** @param An arbitrary sampling rate.
355  *  @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
356  */
357 int
358 dcp_audio_sample_rate (int fs)
359 {
360         if (fs <= 48000) {
361                 return 48000;
362         }
363
364         return 96000;
365 }
366
367 bool operator== (Size const & a, Size const & b)
368 {
369         return (a.width == b.width && a.height == b.height);
370 }
371
372 bool operator== (Crop const & a, Crop const & b)
373 {
374         return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
375 }
376
377 bool operator!= (Crop const & a, Crop const & b)
378 {
379         return !(a == b);
380 }
381
382 /** @param index Colour LUT index.
383  *  @return Human-readable name.
384  */
385 string
386 colour_lut_index_to_name (int index)
387 {
388         switch (index) {
389         case 0:
390                 return "sRGB";
391         case 1:
392                 return "Rec 709";
393         }
394
395         assert (false);
396         return "";
397 }
398
399 Socket::Socket ()
400         : _deadline (_io_service)
401         , _socket (_io_service)
402         , _buffer_data (0)
403 {
404         _deadline.expires_at (posix_time::pos_infin);
405         check ();
406 }
407
408 void
409 Socket::check ()
410 {
411         if (_deadline.expires_at() <= asio::deadline_timer::traits_type::now ()) {
412                 _socket.close ();
413                 _deadline.expires_at (posix_time::pos_infin);
414         }
415
416         _deadline.async_wait (boost::bind (&Socket::check, this));
417 }
418
419 /** Blocking connect with timeout.
420  *  @param endpoint End-point to connect to.
421  *  @param timeout Time-out in seconds.
422  */
423 void
424 Socket::connect (asio::ip::basic_resolver_entry<asio::ip::tcp> const & endpoint, int timeout)
425 {
426         system::error_code ec = asio::error::would_block;
427         _socket.async_connect (endpoint, lambda::var(ec) = lambda::_1);
428         do {
429                 _io_service.run_one();
430         } while (ec == asio::error::would_block);
431
432         if (ec || !_socket.is_open ()) {
433                 throw NetworkError ("connect timed out");
434         }
435 }
436
437 /** Blocking write with timeout.
438  *  @param data Buffer to write.
439  *  @param size Number of bytes to write.
440  *  @param timeout Time-out, in seconds.
441  */
442 void
443 Socket::write (uint8_t const * data, int size, int timeout)
444 {
445         _deadline.expires_from_now (posix_time::seconds (timeout));
446         system::error_code ec = asio::error::would_block;
447
448         asio::async_write (_socket, asio::buffer (data, size), lambda::var(ec) = lambda::_1);
449         do {
450                 _io_service.run_one ();
451         } while (ec == asio::error::would_block);
452
453         if (ec) {
454                 throw NetworkError ("write timed out");
455         }
456 }
457
458 /** Blocking read with timeout.
459  *  @param data Buffer to read to.
460  *  @param size Number of bytes to read.
461  *  @param timeout Time-out, in seconds.
462  */
463 int
464 Socket::read (uint8_t* data, int size, int timeout)
465 {
466         _deadline.expires_from_now (posix_time::seconds (timeout));
467         system::error_code ec = asio::error::would_block;
468
469         int amount_read = 0;
470
471         _socket.async_read_some (
472                 asio::buffer (data, size),
473                 (lambda::var(ec) = lambda::_1, lambda::var(amount_read) = lambda::_2)
474                 );
475
476         do {
477                 _io_service.run_one ();
478         } while (ec == asio::error::would_block);
479         
480         if (ec) {
481                 amount_read = 0;
482         }
483
484         return amount_read;
485 }
486
487 /** Mark some data as being `consumed', so that it will not be returned
488  *  as data again.
489  *  @param size Amount of data to consume, in bytes.
490  */
491 void
492 Socket::consume (int size)
493 {
494         assert (_buffer_data >= size);
495         
496         _buffer_data -= size;
497         if (_buffer_data > 0) {
498                 /* Shift still-valid data to the start of the buffer */
499                 memmove (_buffer, _buffer + size, _buffer_data);
500         }
501 }
502
503 /** Read a definite amount of data from our socket, and mark
504  *  it as consumed.
505  *  @param data Where to put the data.
506  *  @param size Number of bytes to read.
507  */
508 void
509 Socket::read_definite_and_consume (uint8_t* data, int size, int timeout)
510 {
511         int const from_buffer = min (_buffer_data, size);
512         if (from_buffer > 0) {
513                 /* Get data from our buffer */
514                 memcpy (data, _buffer, from_buffer);
515                 consume (from_buffer);
516                 /* Update our output state */
517                 data += from_buffer;
518                 size -= from_buffer;
519         }
520
521         /* read() the rest */
522         while (size > 0) {
523                 int const n = read (data, size, timeout);
524                 if (n <= 0) {
525                         throw NetworkError ("could not read");
526                 }
527
528                 data += n;
529                 size -= n;
530         }
531 }
532
533 /** Read as much data as is available, up to some limit.
534  *  @param data Where to put the data.
535  *  @param size Maximum amount of data to read.
536  */
537 void
538 Socket::read_indefinite (uint8_t* data, int size, int timeout)
539 {
540         assert (size < int (sizeof (_buffer)));
541
542         /* Amount of extra data we need to read () */
543         int to_read = size - _buffer_data;
544         while (to_read > 0) {
545                 /* read as much of it as we can (into our buffer) */
546                 int const n = read (_buffer + _buffer_data, to_read, timeout);
547                 if (n <= 0) {
548                         throw NetworkError ("could not read");
549                 }
550
551                 to_read -= n;
552                 _buffer_data += n;
553         }
554
555         assert (_buffer_data >= size);
556
557         /* copy data into the output buffer */
558         assert (size >= _buffer_data);
559         memcpy (data, _buffer, size);
560 }
561
562 /** @param other A Rect.
563  *  @return The intersection of this with `other'.
564  */
565 Rect
566 Rect::intersection (Rect const & other) const
567 {
568         int const tx = max (x, other.x);
569         int const ty = max (y, other.y);
570         
571         return Rect (
572                 tx, ty,
573                 min (x + width, other.x + other.width) - tx,
574                 min (y + height, other.y + other.height) - ty
575                 );
576 }
577
578 /** Round a number up to the nearest multiple of another number.
579  *  @param c Index.
580  *  @param s Array of numbers to round, indexed by c.
581  *  @param t Multiple to round to.
582  *  @return Rounded number.
583  */
584 int
585 stride_round_up (int c, int const * stride, int t)
586 {
587         int const a = stride[c] + (t - 1);
588         return a - (a % t);
589 }
590
591 int
592 stride_lookup (int c, int const * stride)
593 {
594         return stride[c];
595 }
596
597 /** Read a sequence of key / value pairs from a text stream;
598  *  the keys are the first words on the line, and the values are
599  *  the remainder of the line following the key.  Lines beginning
600  *  with # are ignored.
601  *  @param s Stream to read.
602  *  @return key/value pairs.
603  */
604 multimap<string, string>
605 read_key_value (istream &s) 
606 {
607         multimap<string, string> kv;
608         
609         string line;
610         while (getline (s, line)) {
611                 if (line.empty ()) {
612                         continue;
613                 }
614
615                 if (line[0] == '#') {
616                         continue;
617                 }
618
619                 if (line[line.size() - 1] == '\r') {
620                         line = line.substr (0, line.size() - 1);
621                 }
622
623                 size_t const s = line.find (' ');
624                 if (s == string::npos) {
625                         continue;
626                 }
627
628                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
629         }
630
631         return kv;
632 }
633
634 string
635 get_required_string (multimap<string, string> const & kv, string k)
636 {
637         if (kv.count (k) > 1) {
638                 throw StringError ("unexpected multiple keys in key-value set");
639         }
640
641         multimap<string, string>::const_iterator i = kv.find (k);
642         
643         if (i == kv.end ()) {
644                 throw StringError (String::compose ("missing key %1 in key-value set", k));
645         }
646
647         return i->second;
648 }
649
650 int
651 get_required_int (multimap<string, string> const & kv, string k)
652 {
653         string const v = get_required_string (kv, k);
654         return lexical_cast<int> (v);
655 }
656
657 float
658 get_required_float (multimap<string, string> const & kv, string k)
659 {
660         string const v = get_required_string (kv, k);
661         return lexical_cast<float> (v);
662 }
663
664 string
665 get_optional_string (multimap<string, string> const & kv, string k)
666 {
667         if (kv.count (k) > 1) {
668                 throw StringError ("unexpected multiple keys in key-value set");
669         }
670
671         multimap<string, string>::const_iterator i = kv.find (k);
672         if (i == kv.end ()) {
673                 return "";
674         }
675
676         return i->second;
677 }
678
679 int
680 get_optional_int (multimap<string, string> const & kv, string k)
681 {
682         if (kv.count (k) > 1) {
683                 throw StringError ("unexpected multiple keys in key-value set");
684         }
685
686         multimap<string, string>::const_iterator i = kv.find (k);
687         if (i == kv.end ()) {
688                 return 0;
689         }
690
691         return lexical_cast<int> (i->second);
692 }
693
694 /** Construct an AudioBuffers.  Audio data is undefined after this constructor.
695  *  @param channels Number of channels.
696  *  @param frames Number of frames to reserve space for.
697  */
698 AudioBuffers::AudioBuffers (int channels, int frames)
699         : _channels (channels)
700         , _frames (frames)
701         , _allocated_frames (frames)
702 {
703         _data = new float*[_channels];
704         for (int i = 0; i < _channels; ++i) {
705                 _data[i] = new float[frames];
706         }
707 }
708
709 /** Copy constructor.
710  *  @param other Other AudioBuffers; data is copied.
711  */
712 AudioBuffers::AudioBuffers (AudioBuffers const & other)
713         : _channels (other._channels)
714         , _frames (other._frames)
715         , _allocated_frames (other._frames)
716 {
717         _data = new float*[_channels];
718         for (int i = 0; i < _channels; ++i) {
719                 _data[i] = new float[_frames];
720                 memcpy (_data[i], other._data[i], _frames * sizeof (float));
721         }
722 }
723
724 /** AudioBuffers destructor */
725 AudioBuffers::~AudioBuffers ()
726 {
727         for (int i = 0; i < _channels; ++i) {
728                 delete[] _data[i];
729         }
730
731         delete[] _data;
732 }
733
734 /** @param c Channel index.
735  *  @return Buffer for this channel.
736  */
737 float*
738 AudioBuffers::data (int c) const
739 {
740         assert (c >= 0 && c < _channels);
741         return _data[c];
742 }
743
744 /** Set the number of frames that these AudioBuffers will report themselves
745  *  as having.
746  *  @param f Frames; must be less than or equal to the number of allocated frames.
747  */
748 void
749 AudioBuffers::set_frames (int f)
750 {
751         assert (f <= _allocated_frames);
752         _frames = f;
753 }
754
755 /** Make all samples on all channels silent */
756 void
757 AudioBuffers::make_silent ()
758 {
759         for (int i = 0; i < _channels; ++i) {
760                 make_silent (i);
761         }
762 }
763
764 /** Make all samples on a given channel silent.
765  *  @param c Channel.
766  */
767 void
768 AudioBuffers::make_silent (int c)
769 {
770         assert (c >= 0 && c < _channels);
771         
772         for (int i = 0; i < _frames; ++i) {
773                 _data[c][i] = 0;
774         }
775 }
776
777 /** Copy data from another AudioBuffers to this one.  All channels are copied.
778  *  @param from AudioBuffers to copy from; must have the same number of channels as this.
779  *  @param frames_to_copy Number of frames to copy.
780  *  @param read_offset Offset to read from in `from'.
781  *  @param write_offset Offset to write to in `to'.
782  */
783 void
784 AudioBuffers::copy_from (AudioBuffers* from, int frames_to_copy, int read_offset, int write_offset)
785 {
786         assert (from->channels() == channels());
787
788         assert (from);
789         assert (read_offset >= 0 && (read_offset + frames_to_copy) <= from->_allocated_frames);
790         assert (write_offset >= 0 && (write_offset + frames_to_copy) <= _allocated_frames);
791
792         for (int i = 0; i < _channels; ++i) {
793                 memcpy (_data[i] + write_offset, from->_data[i] + read_offset, frames_to_copy * sizeof(float));
794         }
795 }
796
797 /** Move audio data around.
798  *  @param from Offset to move from.
799  *  @param to Offset to move to.
800  *  @param frames Number of frames to move.
801  */
802     
803 void
804 AudioBuffers::move (int from, int to, int frames)
805 {
806         if (frames == 0) {
807                 return;
808         }
809         
810         assert (from >= 0);
811         assert (from < _frames);
812         assert (to >= 0);
813         assert (to < _frames);
814         assert (frames > 0);
815         assert (frames <= _frames);
816         assert ((from + frames) <= _frames);
817         assert ((to + frames) <= _frames);
818         
819         for (int i = 0; i < _channels; ++i) {
820                 memmove (_data[i] + to, _data[i] + from, frames * sizeof(float));
821         }
822 }
823
824 /** Trip an assert if the caller is not in the UI thread */
825 void
826 ensure_ui_thread ()
827 {
828         assert (this_thread::get_id() == ui_thread);
829 }
830
831 /** @param v Source video frame.
832  *  @param audio_sample_rate Source audio sample rate.
833  *  @param frames_per_second Number of video frames per second.
834  *  @return Equivalent number of audio frames for `v'.
835  */
836 int64_t
837 video_frames_to_audio_frames (SourceFrame v, float audio_sample_rate, float frames_per_second)
838 {
839         return ((int64_t) v * audio_sample_rate / frames_per_second);
840 }
841
842 /** @param f Filename.
843  *  @return true if this file is a still image, false if it is something else.
844  */
845 bool
846 still_image_file (string f)
847 {
848 #if BOOST_FILESYSTEM_VERSION == 3
849         string ext = boost::filesystem::path(f).extension().string();
850 #else
851         string ext = boost::filesystem::path(f).extension();
852 #endif
853
854         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
855         
856         return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png");
857 }