Merge branch '1.0' of ssh://houllier/home/carl/git/dvdomatic into 1.0
[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 #include <climits>
30 #ifdef DCPOMATIC_POSIX
31 #include <execinfo.h>
32 #include <cxxabi.h>
33 #endif
34 #include <libssh/libssh.h>
35 #include <signal.h>
36 #include <boost/algorithm/string.hpp>
37 #include <boost/bind.hpp>
38 #include <boost/lambda/lambda.hpp>
39 #include <boost/lexical_cast.hpp>
40 #include <boost/thread.hpp>
41 #include <boost/filesystem.hpp>
42 #include <glib.h>
43 #include <openjpeg.h>
44 #include <openssl/md5.h>
45 #include <magick/MagickCore.h>
46 #include <magick/version.h>
47 #include <libdcp/version.h>
48 extern "C" {
49 #include <libavcodec/avcodec.h>
50 #include <libavformat/avformat.h>
51 #include <libswscale/swscale.h>
52 #include <libavfilter/avfiltergraph.h>
53 #include <libpostproc/postprocess.h>
54 #include <libavutil/pixfmt.h>
55 }
56 #include "util.h"
57 #include "exceptions.h"
58 #include "scaler.h"
59 #include "dcp_content_type.h"
60 #include "filter.h"
61 #include "sound_processor.h"
62 #include "config.h"
63 #include "ratio.h"
64 #ifdef DVDOMATIC_WINDOWS
65 #include "stack.hpp"
66 #endif
67
68 #include "i18n.h"
69
70 using std::string;
71 using std::stringstream;
72 using std::setfill;
73 using std::ostream;
74 using std::endl;
75 using std::vector;
76 using std::hex;
77 using std::setw;
78 using std::ifstream;
79 using std::ios;
80 using std::min;
81 using std::max;
82 using std::list;
83 using std::multimap;
84 using std::istream;
85 using std::numeric_limits;
86 using std::pair;
87 using std::ofstream;
88 using boost::shared_ptr;
89 using boost::thread;
90 using boost::lexical_cast;
91 using boost::optional;
92 using libdcp::Size;
93
94 boost::thread::id ui_thread;
95 boost::filesystem::path backtrace_file;
96
97 /** Convert some number of seconds to a string representation
98  *  in hours, minutes and seconds.
99  *
100  *  @param s Seconds.
101  *  @return String of the form H:M:S (where H is hours, M
102  *  is minutes and S is seconds).
103  */
104 string
105 seconds_to_hms (int s)
106 {
107         int m = s / 60;
108         s -= (m * 60);
109         int h = m / 60;
110         m -= (h * 60);
111
112         stringstream hms;
113         hms << h << N_(":");
114         hms.width (2);
115         hms << std::setfill ('0') << m << N_(":");
116         hms.width (2);
117         hms << std::setfill ('0') << s;
118
119         return hms.str ();
120 }
121
122 string
123 time_to_hms (Time t)
124 {
125         return seconds_to_hms (t / TIME_HZ);
126 }
127
128 /** @param s Number of seconds.
129  *  @return String containing an approximate description of s (e.g. "about 2 hours")
130  */
131 string
132 seconds_to_approximate_hms (int s)
133 {
134         int m = s / 60;
135         s -= (m * 60);
136         int h = m / 60;
137         m -= (h * 60);
138
139         stringstream ap;
140         
141         if (h > 0) {
142                 if (m > 30) {
143                         ap << (h + 1) << N_(" ") << _("hours");
144                 } else {
145                         if (h == 1) {
146                                 ap << N_("1 ") << _("hour");
147                         } else {
148                                 ap << h << N_(" ") << _("hours");
149                         }
150                 }
151         } else if (m > 0) {
152                 if (m == 1) {
153                         ap << N_("1 ") << _("minute");
154                 } else {
155                         ap << m << N_(" ") << _("minutes");
156                 }
157         } else {
158                 ap << s << N_(" ") << _("seconds");
159         }
160
161         return ap.str ();
162 }
163
164 #ifdef DCPOMATIC_POSIX
165 /** @param l Mangled C++ identifier.
166  *  @return Demangled version.
167  */
168 static string
169 demangle (string l)
170 {
171         string::size_type const b = l.find_first_of (N_("("));
172         if (b == string::npos) {
173                 return l;
174         }
175
176         string::size_type const p = l.find_last_of (N_("+"));
177         if (p == string::npos) {
178                 return l;
179         }
180
181         if ((p - b) <= 1) {
182                 return l;
183         }
184         
185         string const fn = l.substr (b + 1, p - b - 1);
186
187         int status;
188         try {
189                 
190                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
191                 string d (realname);
192                 free (realname);
193                 return d;
194                 
195         } catch (std::exception) {
196                 
197         }
198         
199         return l;
200 }
201
202 /** Write a stacktrace to an ostream.
203  *  @param out Stream to write to.
204  *  @param levels Number of levels to go up the call stack.
205  */
206 void
207 stacktrace (ostream& out, int levels)
208 {
209         void *array[200];
210         size_t size;
211         char **strings;
212         size_t i;
213      
214         size = backtrace (array, 200);
215         strings = backtrace_symbols (array, size);
216      
217         if (strings) {
218                 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
219                         out << N_("  ") << demangle (strings[i]) << "\n";
220                 }
221                 
222                 free (strings);
223         }
224 }
225 #endif
226
227 /** @param v Version as used by FFmpeg.
228  *  @return A string representation of v.
229  */
230 static string
231 ffmpeg_version_to_string (int v)
232 {
233         stringstream s;
234         s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
235         return s.str ();
236 }
237
238 /** Return a user-readable string summarising the versions of our dependencies */
239 string
240 dependency_version_summary ()
241 {
242         stringstream s;
243         s << N_("libopenjpeg ") << opj_version () << N_(", ")
244           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
245           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
246           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
247           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
248           << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
249           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
250           << MagickVersion << N_(", ")
251           << N_("libssh ") << ssh_version (0) << N_(", ")
252           << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
253
254         return s.str ();
255 }
256
257 double
258 seconds (struct timeval t)
259 {
260         return t.tv_sec + (double (t.tv_usec) / 1e6);
261 }
262
263 #ifdef DVDOMATIC_WINDOWS
264 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
265 {
266         dbg::stack s;
267         ofstream f (backtrace_file.string().c_str());
268         std::copy(s.begin(), s.end(), std::ostream_iterator<dbg::stack_frame>(f, "\n"));
269         return EXCEPTION_CONTINUE_SEARCH;
270 }
271 #endif
272
273 /** Call the required functions to set up DVD-o-matic's static arrays, etc.
274  *  Must be called from the UI thread, if there is one.
275  */
276 void
277 dcpomatic_setup ()
278 {
279 #ifdef DVDOMATIC_WINDOWS
280         backtrace_file /= g_get_user_config_dir ();
281         backtrace_file /= "backtrace.txt";
282         SetUnhandledExceptionFilter(exception_handler);
283 #endif  
284         
285         avfilter_register_all ();
286         
287         Ratio::setup_ratios ();
288         DCPContentType::setup_dcp_content_types ();
289         Scaler::setup_scalers ();
290         Filter::setup_filters ();
291         SoundProcessor::setup_sound_processors ();
292
293         ui_thread = boost::this_thread::get_id ();
294 }
295
296 #ifdef DCPOMATIC_WINDOWS
297 boost::filesystem::path
298 mo_path ()
299 {
300         wchar_t buffer[512];
301         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
302         boost::filesystem::path p (buffer);
303         p = p.parent_path ();
304         p = p.parent_path ();
305         p /= "locale";
306         return p;
307 }
308 #endif
309
310 void
311 dcpomatic_setup_gettext_i18n (string lang)
312 {
313 #ifdef DCPOMATIC_POSIX
314         lang += ".UTF8";
315 #endif
316
317         if (!lang.empty ()) {
318                 /* Override our environment language; this is essential on
319                    Windows.
320                 */
321                 char cmd[64];
322                 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
323                 putenv (cmd);
324                 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
325                 putenv (cmd);
326         }
327
328         setlocale (LC_ALL, "");
329         textdomain ("libdcpomatic");
330
331 #ifdef DCPOMATIC_WINDOWS
332         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
333         bind_textdomain_codeset ("libdcpomatic", "UTF8");
334 #endif  
335
336 #ifdef DCPOMATIC_POSIX
337         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
338 #endif
339 }
340
341 /** @param start Start position for the crop within the image.
342  *  @param size Size of the cropped area.
343  *  @return FFmpeg crop filter string.
344  */
345 string
346 crop_string (Position start, libdcp::Size size)
347 {
348         stringstream s;
349         s << N_("crop=") << size.width << N_(":") << size.height << N_(":") << start.x << N_(":") << start.y;
350         return s.str ();
351 }
352
353 /** @param s A string.
354  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
355  */
356 vector<string>
357 split_at_spaces_considering_quotes (string s)
358 {
359         vector<string> out;
360         bool in_quotes = false;
361         string c;
362         for (string::size_type i = 0; i < s.length(); ++i) {
363                 if (s[i] == ' ' && !in_quotes) {
364                         out.push_back (c);
365                         c = N_("");
366                 } else if (s[i] == '"') {
367                         in_quotes = !in_quotes;
368                 } else {
369                         c += s[i];
370                 }
371         }
372
373         out.push_back (c);
374         return out;
375 }
376
377 string
378 md5_digest (void const * data, int size)
379 {
380         MD5_CTX md5_context;
381         MD5_Init (&md5_context);
382         MD5_Update (&md5_context, data, size);
383         unsigned char digest[MD5_DIGEST_LENGTH];
384         MD5_Final (digest, &md5_context);
385         
386         stringstream s;
387         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
388                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
389         }
390
391         return s.str ();
392 }
393
394 /** @param file File name.
395  *  @return MD5 digest of file's contents.
396  */
397 string
398 md5_digest (boost::filesystem::path file)
399 {
400         ifstream f (file.string().c_str(), std::ios::binary);
401         if (!f.good ()) {
402                 throw OpenFileError (file.string());
403         }
404         
405         f.seekg (0, std::ios::end);
406         int bytes = f.tellg ();
407         f.seekg (0, std::ios::beg);
408
409         int const buffer_size = 64 * 1024;
410         char buffer[buffer_size];
411
412         MD5_CTX md5_context;
413         MD5_Init (&md5_context);
414         while (bytes > 0) {
415                 int const t = min (bytes, buffer_size);
416                 f.read (buffer, t);
417                 MD5_Update (&md5_context, buffer, t);
418                 bytes -= t;
419         }
420
421         unsigned char digest[MD5_DIGEST_LENGTH];
422         MD5_Final (digest, &md5_context);
423
424         stringstream s;
425         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
426                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
427         }
428
429         return s.str ();
430 }
431
432 static bool
433 about_equal (float a, float b)
434 {
435         /* A film of F seconds at f FPS will be Ff frames;
436            Consider some delta FPS d, so if we run the same
437            film at (f + d) FPS it will last F(f + d) seconds.
438
439            Hence the difference in length over the length of the film will
440            be F(f + d) - Ff frames
441             = Ff + Fd - Ff frames
442             = Fd frames
443             = Fd/f seconds
444  
445            So if we accept a difference of 1 frame, ie 1/f seconds, we can
446            say that
447
448            1/f = Fd/f
449         ie 1 = Fd
450         ie d = 1/F
451  
452            So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
453            FPS error is 1/F ~= 0.0001 ~= 10-e4
454         */
455
456         return (fabs (a - b) < 1e-4);
457 }
458
459 /** @param An arbitrary audio frame rate.
460  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
461  */
462 int
463 dcp_audio_frame_rate (int fs)
464 {
465         if (fs <= 48000) {
466                 return 48000;
467         }
468
469         return 96000;
470 }
471
472 /** @param index Colour LUT index.
473  *  @return Human-readable name.
474  */
475 string
476 colour_lut_index_to_name (int index)
477 {
478         switch (index) {
479         case 0:
480                 return _("sRGB");
481         case 1:
482                 return _("Rec 709");
483         }
484
485         assert (false);
486         return N_("");
487 }
488
489 Socket::Socket (int timeout)
490         : _deadline (_io_service)
491         , _socket (_io_service)
492         , _timeout (timeout)
493 {
494         _deadline.expires_at (boost::posix_time::pos_infin);
495         check ();
496 }
497
498 void
499 Socket::check ()
500 {
501         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
502                 _socket.close ();
503                 _deadline.expires_at (boost::posix_time::pos_infin);
504         }
505
506         _deadline.async_wait (boost::bind (&Socket::check, this));
507 }
508
509 /** Blocking connect.
510  *  @param endpoint End-point to connect to.
511  */
512 void
513 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
514 {
515         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
516         boost::system::error_code ec = boost::asio::error::would_block;
517         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
518         do {
519                 _io_service.run_one();
520         } while (ec == boost::asio::error::would_block);
521
522         if (ec || !_socket.is_open ()) {
523                 throw NetworkError (_("connect timed out"));
524         }
525 }
526
527 /** Blocking write.
528  *  @param data Buffer to write.
529  *  @param size Number of bytes to write.
530  */
531 void
532 Socket::write (uint8_t const * data, int size)
533 {
534         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
535         boost::system::error_code ec = boost::asio::error::would_block;
536
537         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
538         
539         do {
540                 _io_service.run_one ();
541         } while (ec == boost::asio::error::would_block);
542
543         if (ec) {
544                 throw NetworkError (ec.message ());
545         }
546 }
547
548 void
549 Socket::write (uint32_t v)
550 {
551         v = htonl (v);
552         write (reinterpret_cast<uint8_t*> (&v), 4);
553 }
554
555 /** Blocking read.
556  *  @param data Buffer to read to.
557  *  @param size Number of bytes to read.
558  */
559 void
560 Socket::read (uint8_t* data, int size)
561 {
562         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
563         boost::system::error_code ec = boost::asio::error::would_block;
564
565         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
566
567         do {
568                 _io_service.run_one ();
569         } while (ec == boost::asio::error::would_block);
570         
571         if (ec) {
572                 throw NetworkError (ec.message ());
573         }
574 }
575
576 uint32_t
577 Socket::read_uint32 ()
578 {
579         uint32_t v;
580         read (reinterpret_cast<uint8_t *> (&v), 4);
581         return ntohl (v);
582 }
583
584 /** Round a number up to the nearest multiple of another number.
585  *  @param c Index.
586  *  @param s Array of numbers to round, indexed by c.
587  *  @param t Multiple to round to.
588  *  @return Rounded number.
589  */
590 int
591 stride_round_up (int c, int const * stride, int t)
592 {
593         int const a = stride[c] + (t - 1);
594         return a - (a % t);
595 }
596
597 int
598 stride_lookup (int c, int const * stride)
599 {
600         return stride[c];
601 }
602
603 /** Read a sequence of key / value pairs from a text stream;
604  *  the keys are the first words on the line, and the values are
605  *  the remainder of the line following the key.  Lines beginning
606  *  with # are ignored.
607  *  @param s Stream to read.
608  *  @return key/value pairs.
609  */
610 multimap<string, string>
611 read_key_value (istream &s) 
612 {
613         multimap<string, string> kv;
614         
615         string line;
616         while (getline (s, line)) {
617                 if (line.empty ()) {
618                         continue;
619                 }
620
621                 if (line[0] == '#') {
622                         continue;
623                 }
624
625                 if (line[line.size() - 1] == '\r') {
626                         line = line.substr (0, line.size() - 1);
627                 }
628
629                 size_t const s = line.find (' ');
630                 if (s == string::npos) {
631                         continue;
632                 }
633
634                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
635         }
636
637         return kv;
638 }
639
640 string
641 get_required_string (multimap<string, string> const & kv, string k)
642 {
643         if (kv.count (k) > 1) {
644                 throw StringError (N_("unexpected multiple keys in key-value set"));
645         }
646
647         multimap<string, string>::const_iterator i = kv.find (k);
648         
649         if (i == kv.end ()) {
650                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
651         }
652
653         return i->second;
654 }
655
656 int
657 get_required_int (multimap<string, string> const & kv, string k)
658 {
659         string const v = get_required_string (kv, k);
660         return lexical_cast<int> (v);
661 }
662
663 float
664 get_required_float (multimap<string, string> const & kv, string k)
665 {
666         string const v = get_required_string (kv, k);
667         return lexical_cast<float> (v);
668 }
669
670 string
671 get_optional_string (multimap<string, string> const & kv, string k)
672 {
673         if (kv.count (k) > 1) {
674                 throw StringError (N_("unexpected multiple keys in key-value set"));
675         }
676
677         multimap<string, string>::const_iterator i = kv.find (k);
678         if (i == kv.end ()) {
679                 return N_("");
680         }
681
682         return i->second;
683 }
684
685 int
686 get_optional_int (multimap<string, string> const & kv, string k)
687 {
688         if (kv.count (k) > 1) {
689                 throw StringError (N_("unexpected multiple keys in key-value set"));
690         }
691
692         multimap<string, string>::const_iterator i = kv.find (k);
693         if (i == kv.end ()) {
694                 return 0;
695         }
696
697         return lexical_cast<int> (i->second);
698 }
699
700 /** Trip an assert if the caller is not in the UI thread */
701 void
702 ensure_ui_thread ()
703 {
704         assert (boost::this_thread::get_id() == ui_thread);
705 }
706
707 /** @param v Content video frame.
708  *  @param audio_sample_rate Source audio sample rate.
709  *  @param frames_per_second Number of video frames per second.
710  *  @return Equivalent number of audio frames for `v'.
711  */
712 int64_t
713 video_frames_to_audio_frames (ContentVideoFrame v, float audio_sample_rate, float frames_per_second)
714 {
715         return ((int64_t) v * audio_sample_rate / frames_per_second);
716 }
717
718 /** @return A pair containing CPU model name and the number of processors */
719 pair<string, int>
720 cpu_info ()
721 {
722         pair<string, int> info;
723         info.second = 0;
724         
725 #ifdef DCPOMATIC_POSIX
726         ifstream f (N_("/proc/cpuinfo"));
727         while (f.good ()) {
728                 string l;
729                 getline (f, l);
730                 if (boost::algorithm::starts_with (l, N_("model name"))) {
731                         string::size_type const c = l.find (':');
732                         if (c != string::npos) {
733                                 info.first = l.substr (c + 2);
734                         }
735                 } else if (boost::algorithm::starts_with (l, N_("processor"))) {
736                         ++info.second;
737                 }
738         }
739 #endif  
740
741         return info;
742 }
743
744 string
745 audio_channel_name (int c)
746 {
747         assert (MAX_AUDIO_CHANNELS == 6);
748
749         /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
750            enhancement channel (sub-woofer)./
751         */
752         string const channels[] = {
753                 _("Left"),
754                 _("Right"),
755                 _("Centre"),
756                 _("Lfe (sub)"),
757                 _("Left surround"),
758                 _("Right surround"),
759         };
760
761         return channels[c];
762 }
763
764 FrameRateConversion::FrameRateConversion (float source, int dcp)
765         : skip (false)
766         , repeat (false)
767         , change_speed (false)
768 {
769         if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
770                 skip = true;
771         } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
772                 repeat = true;
773         }
774
775         change_speed = !about_equal (source * factor(), dcp);
776
777         if (!skip && !repeat && !change_speed) {
778                 description = _("DCP and source have the same rate.\n");
779         } else {
780                 if (skip) {
781                         description = _("DCP will use every other frame of the source.\n");
782                 } else if (repeat) {
783                         description = _("Each source frame will be doubled in the DCP.\n");
784                 }
785
786                 if (change_speed) {
787                         float const pc = dcp * 100 / (source * factor());
788                         description += String::compose (_("DCP will run at %1%% of the source speed.\n"), pc);
789                 }
790         }
791 }
792
793 LocaleGuard::LocaleGuard ()
794         : _old (0)
795 {
796         char const * old = setlocale (LC_NUMERIC, 0);
797
798         if (old) {
799                 _old = strdup (old);
800                 if (strcmp (_old, "C")) {
801                         setlocale (LC_NUMERIC, "C");
802                 }
803         }
804 }
805
806 LocaleGuard::~LocaleGuard ()
807 {
808         setlocale (LC_NUMERIC, _old);
809         free (_old);
810 }