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