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