Fix build.
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2014 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 #include <stdexcept>
31 #ifdef DCPOMATIC_POSIX
32 #include <execinfo.h>
33 #include <cxxabi.h>
34 #endif
35 #include <libssh/libssh.h>
36 #include <signal.h>
37 #include <boost/algorithm/string.hpp>
38 #include <boost/bind.hpp>
39 #include <boost/lambda/lambda.hpp>
40 #include <boost/thread.hpp>
41 #include <boost/filesystem.hpp>
42 #ifdef DCPOMATIC_WINDOWS
43 #include <boost/locale.hpp>
44 #endif
45 #include <glib.h>
46 #include <openjpeg.h>
47 #include <pangomm/init.h>
48 #include <magick/MagickCore.h>
49 #include <magick/version.h>
50 #include <dcp/version.h>
51 #include <dcp/util.h>
52 #include <dcp/signer.h>
53 #include <dcp/raw_convert.h>
54 extern "C" {
55 #include <libavcodec/avcodec.h>
56 #include <libavformat/avformat.h>
57 #include <libswscale/swscale.h>
58 #include <libavfilter/avfiltergraph.h>
59 #include <libavutil/pixfmt.h>
60 }
61 #include "util.h"
62 #include "exceptions.h"
63 #include "scaler.h"
64 #include "dcp_content_type.h"
65 #include "filter.h"
66 #include "cinema_sound_processor.h"
67 #include "config.h"
68 #include "ratio.h"
69 #include "job.h"
70 #include "cross.h"
71 #include "video_content.h"
72 #include "rect.h"
73 #include "md5_digester.h"
74 #include "audio_processor.h"
75 #ifdef DCPOMATIC_WINDOWS
76 #include "stack.hpp"
77 #endif
78
79 #include "i18n.h"
80
81 using std::string;
82 using std::stringstream;
83 using std::setfill;
84 using std::ostream;
85 using std::endl;
86 using std::vector;
87 using std::hex;
88 using std::setw;
89 using std::ios;
90 using std::min;
91 using std::max;
92 using std::list;
93 using std::multimap;
94 using std::map;
95 using std::istream;
96 using std::numeric_limits;
97 using std::pair;
98 using std::cout;
99 using std::bad_alloc;
100 using std::streampos;
101 using std::set_terminate;
102 using boost::shared_ptr;
103 using boost::thread;
104 using boost::optional;
105 using dcp::Size;
106 using dcp::raw_convert;
107
108 static boost::thread::id ui_thread;
109 static boost::filesystem::path backtrace_file;
110
111 /** Convert some number of seconds to a string representation
112  *  in hours, minutes and seconds.
113  *
114  *  @param s Seconds.
115  *  @return String of the form H:M:S (where H is hours, M
116  *  is minutes and S is seconds).
117  */
118 string
119 seconds_to_hms (int s)
120 {
121         int m = s / 60;
122         s -= (m * 60);
123         int h = m / 60;
124         m -= (h * 60);
125
126         stringstream hms;
127         hms << h << N_(":");
128         hms.width (2);
129         hms << std::setfill ('0') << m << N_(":");
130         hms.width (2);
131         hms << std::setfill ('0') << s;
132
133         return hms.str ();
134 }
135
136 /** @param s Number of seconds.
137  *  @return String containing an approximate description of s (e.g. "about 2 hours")
138  */
139 string
140 seconds_to_approximate_hms (int s)
141 {
142         int m = s / 60;
143         s -= (m * 60);
144         int h = m / 60;
145         m -= (h * 60);
146
147         stringstream ap;
148
149         bool const hours = h > 0;
150         bool const minutes = h < 10 && m > 0;
151         bool const seconds = m < 10 && s > 0;
152
153         if (hours) {
154                 if (m > 30 && !minutes) {
155                         ap << (h + 1) << N_(" ") << _("hours");
156                 } else {
157                         ap << h << N_(" ");
158                         if (h == 1) {
159                                 ap << _("hour");
160                         } else {
161                                 ap << _("hours");
162                         }
163                 }
164
165                 if (minutes | seconds) {
166                         ap << N_(" ");
167                 }
168         }
169
170         if (minutes) {
171                 /* Minutes */
172                 if (s > 30 && !seconds) {
173                         ap << (m + 1) << N_(" ") << _("minutes");
174                 } else {
175                         ap << m << N_(" ");
176                         if (m == 1) {
177                                 ap << _("minute");
178                         } else {
179                                 ap << _("minutes");
180                         }
181                 }
182
183                 if (seconds) {
184                         ap << N_(" ");
185                 }
186         }
187
188         if (seconds) {
189                 /* Seconds */
190                 ap << s << N_(" ");
191                 if (s == 1) {
192                         ap << _("second");
193                 } else {
194                         ap << _("seconds");
195                 }
196         }
197
198         return ap.str ();
199 }
200
201 #ifdef DCPOMATIC_POSIX
202 /** @param l Mangled C++ identifier.
203  *  @return Demangled version.
204  */
205 static string
206 demangle (string l)
207 {
208         string::size_type const b = l.find_first_of (N_("("));
209         if (b == string::npos) {
210                 return l;
211         }
212
213         string::size_type const p = l.find_last_of (N_("+"));
214         if (p == string::npos) {
215                 return l;
216         }
217
218         if ((p - b) <= 1) {
219                 return l;
220         }
221         
222         string const fn = l.substr (b + 1, p - b - 1);
223
224         int status;
225         try {
226                 
227                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
228                 string d (realname);
229                 free (realname);
230                 return d;
231                 
232         } catch (std::exception) {
233                 
234         }
235         
236         return l;
237 }
238
239 /** Write a stacktrace to an ostream.
240  *  @param out Stream to write to.
241  *  @param levels Number of levels to go up the call stack.
242  */
243 void
244 stacktrace (ostream& out, int levels)
245 {
246         void *array[200];
247         size_t size = backtrace (array, 200);
248         char** strings = backtrace_symbols (array, size);
249      
250         if (strings) {
251                 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
252                         out << N_("  ") << demangle (strings[i]) << "\n";
253                 }
254                 
255                 free (strings);
256         }
257 }
258 #endif
259
260 /** @param v Version as used by FFmpeg.
261  *  @return A string representation of v.
262  */
263 static string
264 ffmpeg_version_to_string (int v)
265 {
266         stringstream s;
267         s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
268         return s.str ();
269 }
270
271 double
272 seconds (struct timeval t)
273 {
274         return t.tv_sec + (double (t.tv_usec) / 1e6);
275 }
276
277 #ifdef DCPOMATIC_WINDOWS
278 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
279 {
280         dbg::stack s;
281         FILE* f = fopen_boost (backtrace_file, "w");
282         fprintf (f, "Exception thrown:");
283         for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
284                 fprintf (f, "%p %s %d %s\n", i->instruction, i->function.c_str(), i->line, i->module.c_str());
285         }
286         fclose (f);
287         return EXCEPTION_CONTINUE_SEARCH;
288 }
289 #endif
290
291 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
292 void
293 terminate ()
294 {
295         static bool tried_throw = false;
296
297         try {
298                 // try once to re-throw currently active exception
299                 if (!tried_throw) {
300                         tried_throw = true;
301                         throw;
302                 }
303         }
304         catch (const std::exception &e) {
305                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
306                           << e.what() << std::endl;
307         }
308         catch (...) {
309                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception." 
310                           << std::endl;
311         }
312
313 #ifdef DCPOMATIC_POSIX
314         stacktrace (cout, 50);
315 #endif
316         abort();
317 }
318
319 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
320  *  Must be called from the UI thread, if there is one.
321  */
322 void
323 dcpomatic_setup ()
324 {
325 #ifdef DCPOMATIC_WINDOWS
326         backtrace_file /= g_get_user_config_dir ();
327         backtrace_file /= "backtrace.txt";
328         SetUnhandledExceptionFilter(exception_handler);
329
330         /* Dark voodoo which, I think, gets boost::filesystem::path to
331            correctly convert UTF-8 strings to paths, and also paths
332            back to UTF-8 strings (on path::string()).
333
334            After this, constructing boost::filesystem::paths from strings
335            converts from UTF-8 to UTF-16 inside the path.  Then
336            path::string().c_str() gives UTF-8 and
337            path::c_str()          gives UTF-16.
338
339            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
340            so things are much simpler.
341         */
342         std::locale::global (boost::locale::generator().generate (""));
343         boost::filesystem::path::imbue (std::locale ());
344 #endif  
345         
346         avfilter_register_all ();
347
348 #ifdef DCPOMATIC_OSX
349         /* Add our lib directory to the libltdl search path so that
350            xmlsec can find xmlsec1-openssl.
351         */
352         boost::filesystem::path lib = app_contents ();
353         lib /= "lib";
354         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
355 #endif
356
357         set_terminate (terminate);
358
359         Pango::init ();
360         dcp::init ();
361         
362         Ratio::setup_ratios ();
363         VideoContentScale::setup_scales ();
364         DCPContentType::setup_dcp_content_types ();
365         Scaler::setup_scalers ();
366         Filter::setup_filters ();
367         CinemaSoundProcessor::setup_cinema_sound_processors ();
368         AudioProcessor::setup_audio_processors ();
369
370         ui_thread = boost::this_thread::get_id ();
371 }
372
373 #ifdef DCPOMATIC_WINDOWS
374 boost::filesystem::path
375 mo_path ()
376 {
377         wchar_t buffer[512];
378         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
379         boost::filesystem::path p (buffer);
380         p = p.parent_path ();
381         p = p.parent_path ();
382         p /= "locale";
383         return p;
384 }
385 #endif
386
387 void
388 dcpomatic_setup_gettext_i18n (string lang)
389 {
390 #ifdef DCPOMATIC_POSIX
391         lang += ".UTF8";
392 #endif
393
394         if (!lang.empty ()) {
395                 /* Override our environment language; this is essential on
396                    Windows.
397                 */
398                 char cmd[64];
399                 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
400                 putenv (cmd);
401                 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
402                 putenv (cmd);
403                 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
404                 putenv (cmd);
405         }
406
407         setlocale (LC_ALL, "");
408         textdomain ("libdcpomatic");
409
410 #ifdef DCPOMATIC_WINDOWS
411         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
412         bind_textdomain_codeset ("libdcpomatic", "UTF8");
413 #endif  
414
415 #ifdef DCPOMATIC_POSIX
416         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
417 #endif
418 }
419
420 /** @param s A string.
421  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
422  */
423 vector<string>
424 split_at_spaces_considering_quotes (string s)
425 {
426         vector<string> out;
427         bool in_quotes = false;
428         string c;
429         for (string::size_type i = 0; i < s.length(); ++i) {
430                 if (s[i] == ' ' && !in_quotes) {
431                         out.push_back (c);
432                         c = N_("");
433                 } else if (s[i] == '"') {
434                         in_quotes = !in_quotes;
435                 } else {
436                         c += s[i];
437                 }
438         }
439
440         out.push_back (c);
441         return out;
442 }
443
444 /** @param job Optional job for which to report progress */
445 string
446 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
447 {
448         boost::uintmax_t const buffer_size = 64 * 1024;
449         char buffer[buffer_size];
450
451         MD5Digester digester;
452
453         vector<int64_t> sizes;
454         for (size_t i = 0; i < files.size(); ++i) {
455                 sizes.push_back (boost::filesystem::file_size (files[i]));
456         }
457
458         for (size_t i = 0; i < files.size(); ++i) {
459                 FILE* f = fopen_boost (files[i], "rb");
460                 if (!f) {
461                         throw OpenFileError (files[i].string());
462                 }
463
464                 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
465                 boost::uintmax_t remaining = bytes;
466
467                 while (remaining > 0) {
468                         int const t = min (remaining, buffer_size);
469                         fread (buffer, 1, t, f);
470                         digester.add (buffer, t);
471                         remaining -= t;
472
473                         if (job) {
474                                 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
475                         }
476                 }
477
478                 fclose (f);
479         }
480
481         return digester.get ();
482 }
483
484 /** @param An arbitrary audio frame rate.
485  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
486  */
487 int
488 dcp_audio_frame_rate (int fs)
489 {
490         if (fs <= 48000) {
491                 return 48000;
492         }
493
494         return 96000;
495 }
496
497 Socket::Socket (int timeout)
498         : _deadline (_io_service)
499         , _socket (_io_service)
500         , _acceptor (0)
501         , _timeout (timeout)
502 {
503         _deadline.expires_at (boost::posix_time::pos_infin);
504         check ();
505 }
506
507 Socket::~Socket ()
508 {
509         delete _acceptor;
510 }
511
512 void
513 Socket::check ()
514 {
515         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
516                 if (_acceptor) {
517                         _acceptor->cancel ();
518                 } else {
519                         _socket.close ();
520                 }
521                 _deadline.expires_at (boost::posix_time::pos_infin);
522         }
523
524         _deadline.async_wait (boost::bind (&Socket::check, this));
525 }
526
527 /** Blocking connect.
528  *  @param endpoint End-point to connect to.
529  */
530 void
531 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
532 {
533         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
534         boost::system::error_code ec = boost::asio::error::would_block;
535         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
536         do {
537                 _io_service.run_one();
538         } while (ec == boost::asio::error::would_block);
539
540         if (ec) {
541                 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
542         }
543
544         if (!_socket.is_open ()) {
545                 throw NetworkError (_("connect timed out"));
546         }
547 }
548
549 void
550 Socket::accept (int port)
551 {
552         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
553         
554         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
555         boost::system::error_code ec = boost::asio::error::would_block;
556         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
557         do {
558                 _io_service.run_one ();
559         } while (ec == boost::asio::error::would_block );
560
561         delete _acceptor;
562         _acceptor = 0;
563         
564         if (ec) {
565                 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
566         }
567 }
568
569 /** Blocking write.
570  *  @param data Buffer to write.
571  *  @param size Number of bytes to write.
572  */
573 void
574 Socket::write (uint8_t const * 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_write (_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 (String::compose (_("error during async_write (%1)"), ec.value ()));
587         }
588 }
589
590 void
591 Socket::write (uint32_t v)
592 {
593         v = htonl (v);
594         write (reinterpret_cast<uint8_t*> (&v), 4);
595 }
596
597 /** Blocking read.
598  *  @param data Buffer to read to.
599  *  @param size Number of bytes to read.
600  */
601 void
602 Socket::read (uint8_t* data, int size)
603 {
604         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
605         boost::system::error_code ec = boost::asio::error::would_block;
606
607         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
608
609         do {
610                 _io_service.run_one ();
611         } while (ec == boost::asio::error::would_block);
612         
613         if (ec) {
614                 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
615         }
616 }
617
618 uint32_t
619 Socket::read_uint32 ()
620 {
621         uint32_t v;
622         read (reinterpret_cast<uint8_t *> (&v), 4);
623         return ntohl (v);
624 }
625
626 /** Round a number up to the nearest multiple of another number.
627  *  @param c Index.
628  *  @param s Array of numbers to round, indexed by c.
629  *  @param t Multiple to round to.
630  *  @return Rounded number.
631  */
632 int
633 stride_round_up (int c, int const * stride, int t)
634 {
635         int const a = stride[c] + (t - 1);
636         return a - (a % t);
637 }
638
639 /** Read a sequence of key / value pairs from a text stream;
640  *  the keys are the first words on the line, and the values are
641  *  the remainder of the line following the key.  Lines beginning
642  *  with # are ignored.
643  *  @param s Stream to read.
644  *  @return key/value pairs.
645  */
646 multimap<string, string>
647 read_key_value (istream &s) 
648 {
649         multimap<string, string> kv;
650         
651         string line;
652         while (getline (s, line)) {
653                 if (line.empty ()) {
654                         continue;
655                 }
656
657                 if (line[0] == '#') {
658                         continue;
659                 }
660
661                 if (line[line.size() - 1] == '\r') {
662                         line = line.substr (0, line.size() - 1);
663                 }
664
665                 size_t const s = line.find (' ');
666                 if (s == string::npos) {
667                         continue;
668                 }
669
670                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
671         }
672
673         return kv;
674 }
675
676 string
677 get_required_string (multimap<string, string> const & kv, string k)
678 {
679         if (kv.count (k) > 1) {
680                 throw StringError (N_("unexpected multiple keys in key-value set"));
681         }
682
683         multimap<string, string>::const_iterator i = kv.find (k);
684         
685         if (i == kv.end ()) {
686                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
687         }
688
689         return i->second;
690 }
691
692 int
693 get_required_int (multimap<string, string> const & kv, string k)
694 {
695         string const v = get_required_string (kv, k);
696         return raw_convert<int> (v);
697 }
698
699 float
700 get_required_float (multimap<string, string> const & kv, string k)
701 {
702         string const v = get_required_string (kv, k);
703         return raw_convert<float> (v);
704 }
705
706 string
707 get_optional_string (multimap<string, string> const & kv, string k)
708 {
709         if (kv.count (k) > 1) {
710                 throw StringError (N_("unexpected multiple keys in key-value set"));
711         }
712
713         multimap<string, string>::const_iterator i = kv.find (k);
714         if (i == kv.end ()) {
715                 return N_("");
716         }
717
718         return i->second;
719 }
720
721 int
722 get_optional_int (multimap<string, string> const & kv, string k)
723 {
724         if (kv.count (k) > 1) {
725                 throw StringError (N_("unexpected multiple keys in key-value set"));
726         }
727
728         multimap<string, string>::const_iterator i = kv.find (k);
729         if (i == kv.end ()) {
730                 return 0;
731         }
732
733         return raw_convert<int> (i->second);
734 }
735
736 /** Trip an assert if the caller is not in the UI thread */
737 void
738 ensure_ui_thread ()
739 {
740         assert (boost::this_thread::get_id() == ui_thread);
741 }
742
743 string
744 audio_channel_name (int c)
745 {
746         assert (MAX_DCP_AUDIO_CHANNELS == 12);
747
748         /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
749            enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
750            VI is the visually-impaired audio track (audio describe).
751         */
752         string const channels[] = {
753                 _("Left"),
754                 _("Right"),
755                 _("Centre"),
756                 _("Lfe (sub)"),
757                 _("Left surround"),
758                 _("Right surround"),
759                 _("Hearing impaired"),
760                 _("Visually impaired"),
761                 _("Left centre"),
762                 _("Right centre"),
763                 _("Left rear surround"),
764                 _("Right rear surround"),
765         };
766
767         return channels[c];
768 }
769
770 bool
771 valid_image_file (boost::filesystem::path f)
772 {
773         string ext = f.extension().string();
774         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
775         return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
776 }
777
778 string
779 tidy_for_filename (string f)
780 {
781         string t;
782         for (size_t i = 0; i < f.length(); ++i) {
783                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
784                         t += f[i];
785                 } else {
786                         t += '_';
787                 }
788         }
789
790         return t;
791 }
792
793 map<string, string>
794 split_get_request (string url)
795 {
796         enum {
797                 AWAITING_QUESTION_MARK,
798                 KEY,
799                 VALUE
800         } state = AWAITING_QUESTION_MARK;
801         
802         map<string, string> r;
803         string k;
804         string v;
805         for (size_t i = 0; i < url.length(); ++i) {
806                 switch (state) {
807                 case AWAITING_QUESTION_MARK:
808                         if (url[i] == '?') {
809                                 state = KEY;
810                         }
811                         break;
812                 case KEY:
813                         if (url[i] == '=') {
814                                 v.clear ();
815                                 state = VALUE;
816                         } else {
817                                 k += url[i];
818                         }
819                         break;
820                 case VALUE:
821                         if (url[i] == '&') {
822                                 r.insert (make_pair (k, v));
823                                 k.clear ();
824                                 state = KEY;
825                         } else {
826                                 v += url[i];
827                         }
828                         break;
829                 }
830         }
831
832         if (state == VALUE) {
833                 r.insert (make_pair (k, v));
834         }
835
836         return r;
837 }
838
839 dcp::Size
840 fit_ratio_within (float ratio, dcp::Size full_frame)
841 {
842         if (ratio < full_frame.ratio ()) {
843                 return dcp::Size (rint (full_frame.height * ratio), full_frame.height);
844         }
845         
846         return dcp::Size (full_frame.width, rint (full_frame.width / ratio));
847 }
848
849 void *
850 wrapped_av_malloc (size_t s)
851 {
852         void* p = av_malloc (s);
853         if (!p) {
854                 throw bad_alloc ();
855         }
856         return p;
857 }
858                 
859 string
860 entities_to_text (string e)
861 {
862         boost::algorithm::replace_all (e, "%3A", ":");
863         boost::algorithm::replace_all (e, "%2F", "/");
864         return e;
865 }
866
867 int64_t
868 divide_with_round (int64_t a, int64_t b)
869 {
870         if (a % b >= (b / 2)) {
871                 return (a + b - 1) / b;
872         } else {
873                 return a / b;
874         }
875 }
876
877 /** Return a user-readable string summarising the versions of our dependencies */
878 string
879 dependency_version_summary ()
880 {
881         stringstream s;
882         s << N_("libopenjpeg ") << opj_version () << N_(", ")
883           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
884           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
885           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
886           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
887           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
888           << MagickVersion << N_(", ")
889           << N_("libssh ") << ssh_version (0) << N_(", ")
890           << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
891
892         return s.str ();
893 }
894
895 /** Construct a ScopedTemporary.  A temporary filename is decided but the file is not opened
896  *  until ::open() is called.
897  */
898 ScopedTemporary::ScopedTemporary ()
899         : _open (0)
900 {
901         _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
902 }
903
904 /** Close and delete the temporary file */
905 ScopedTemporary::~ScopedTemporary ()
906 {
907         close ();       
908         boost::system::error_code ec;
909         boost::filesystem::remove (_file, ec);
910 }
911
912 /** @return temporary filename */
913 char const *
914 ScopedTemporary::c_str () const
915 {
916         return _file.string().c_str ();
917 }
918
919 /** Open the temporary file.
920  *  @return File's FILE pointer.
921  */
922 FILE*
923 ScopedTemporary::open (char const * params)
924 {
925         _open = fopen (c_str(), params);
926         return _open;
927 }
928
929 /** Close the file */
930 void
931 ScopedTemporary::close ()
932 {
933         if (_open) {
934                 fclose (_open);
935                 _open = 0;
936         }
937 }
938
939 ContentTimePeriod
940 subtitle_period (AVSubtitle const & sub)
941 {
942         ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
943
944         ContentTimePeriod period (
945                 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
946                 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
947                 );
948
949         return period;
950 }