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