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