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