Fix merge.
[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 /** @param n A number.
640  *  @param r Rounding `boundary' (must be a power of 2)
641  *  @return n rounded to the nearest r
642  */
643 int
644 round_to (float n, int r)
645 {
646         assert (r == 1 || r == 2 || r == 4);
647         return int (n + float(r) / 2) &~ (r - 1);
648 }
649
650 /** Read a sequence of key / value pairs from a text stream;
651  *  the keys are the first words on the line, and the values are
652  *  the remainder of the line following the key.  Lines beginning
653  *  with # are ignored.
654  *  @param s Stream to read.
655  *  @return key/value pairs.
656  */
657 multimap<string, string>
658 read_key_value (istream &s) 
659 {
660         multimap<string, string> kv;
661         
662         string line;
663         while (getline (s, line)) {
664                 if (line.empty ()) {
665                         continue;
666                 }
667
668                 if (line[0] == '#') {
669                         continue;
670                 }
671
672                 if (line[line.size() - 1] == '\r') {
673                         line = line.substr (0, line.size() - 1);
674                 }
675
676                 size_t const s = line.find (' ');
677                 if (s == string::npos) {
678                         continue;
679                 }
680
681                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
682         }
683
684         return kv;
685 }
686
687 string
688 get_required_string (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         
696         if (i == kv.end ()) {
697                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
698         }
699
700         return i->second;
701 }
702
703 int
704 get_required_int (multimap<string, string> const & kv, string k)
705 {
706         string const v = get_required_string (kv, k);
707         return raw_convert<int> (v);
708 }
709
710 float
711 get_required_float (multimap<string, string> const & kv, string k)
712 {
713         string const v = get_required_string (kv, k);
714         return raw_convert<float> (v);
715 }
716
717 string
718 get_optional_string (multimap<string, string> const & kv, string k)
719 {
720         if (kv.count (k) > 1) {
721                 throw StringError (N_("unexpected multiple keys in key-value set"));
722         }
723
724         multimap<string, string>::const_iterator i = kv.find (k);
725         if (i == kv.end ()) {
726                 return N_("");
727         }
728
729         return i->second;
730 }
731
732 int
733 get_optional_int (multimap<string, string> const & kv, string k)
734 {
735         if (kv.count (k) > 1) {
736                 throw StringError (N_("unexpected multiple keys in key-value set"));
737         }
738
739         multimap<string, string>::const_iterator i = kv.find (k);
740         if (i == kv.end ()) {
741                 return 0;
742         }
743
744         return raw_convert<int> (i->second);
745 }
746
747 /** Trip an assert if the caller is not in the UI thread */
748 void
749 ensure_ui_thread ()
750 {
751         assert (boost::this_thread::get_id() == ui_thread);
752 }
753
754 string
755 audio_channel_name (int c)
756 {
757         assert (MAX_DCP_AUDIO_CHANNELS == 12);
758
759         /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
760            enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
761            VI is the visually-impaired audio track (audio describe).
762         */
763         string const channels[] = {
764                 _("Left"),
765                 _("Right"),
766                 _("Centre"),
767                 _("Lfe (sub)"),
768                 _("Left surround"),
769                 _("Right surround"),
770                 _("Hearing impaired"),
771                 _("Visually impaired"),
772                 _("Left centre"),
773                 _("Right centre"),
774                 _("Left rear surround"),
775                 _("Right rear surround"),
776         };
777
778         return channels[c];
779 }
780
781 bool
782 valid_image_file (boost::filesystem::path f)
783 {
784         string ext = f.extension().string();
785         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
786         return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
787 }
788
789 string
790 tidy_for_filename (string f)
791 {
792         string t;
793         for (size_t i = 0; i < f.length(); ++i) {
794                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
795                         t += f[i];
796                 } else {
797                         t += '_';
798                 }
799         }
800
801         return t;
802 }
803
804 map<string, string>
805 split_get_request (string url)
806 {
807         enum {
808                 AWAITING_QUESTION_MARK,
809                 KEY,
810                 VALUE
811         } state = AWAITING_QUESTION_MARK;
812         
813         map<string, string> r;
814         string k;
815         string v;
816         for (size_t i = 0; i < url.length(); ++i) {
817                 switch (state) {
818                 case AWAITING_QUESTION_MARK:
819                         if (url[i] == '?') {
820                                 state = KEY;
821                         }
822                         break;
823                 case KEY:
824                         if (url[i] == '=') {
825                                 v.clear ();
826                                 state = VALUE;
827                         } else {
828                                 k += url[i];
829                         }
830                         break;
831                 case VALUE:
832                         if (url[i] == '&') {
833                                 r.insert (make_pair (k, v));
834                                 k.clear ();
835                                 state = KEY;
836                         } else {
837                                 v += url[i];
838                         }
839                         break;
840                 }
841         }
842
843         if (state == VALUE) {
844                 r.insert (make_pair (k, v));
845         }
846
847         return r;
848 }
849
850 dcp::Size
851 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
852 {
853         if (ratio < full_frame.ratio ()) {
854                 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
855         }
856         
857         return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
858 }
859
860 void *
861 wrapped_av_malloc (size_t s)
862 {
863         void* p = av_malloc (s);
864         if (!p) {
865                 throw bad_alloc ();
866         }
867         return p;
868 }
869                 
870 string
871 entities_to_text (string e)
872 {
873         boost::algorithm::replace_all (e, "%3A", ":");
874         boost::algorithm::replace_all (e, "%2F", "/");
875         return e;
876 }
877
878 int64_t
879 divide_with_round (int64_t a, int64_t b)
880 {
881         if (a % b >= (b / 2)) {
882                 return (a + b - 1) / b;
883         } else {
884                 return a / b;
885         }
886 }
887
888 /** Return a user-readable string summarising the versions of our dependencies */
889 string
890 dependency_version_summary ()
891 {
892         stringstream s;
893         s << N_("libopenjpeg ") << opj_version () << N_(", ")
894           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
895           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
896           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
897           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
898           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
899           << MagickVersion << N_(", ")
900           << N_("libssh ") << ssh_version (0) << N_(", ")
901           << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
902
903         return s.str ();
904 }
905
906 /** Construct a ScopedTemporary.  A temporary filename is decided but the file is not opened
907  *  until ::open() is called.
908  */
909 ScopedTemporary::ScopedTemporary ()
910         : _open (0)
911 {
912         _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
913 }
914
915 /** Close and delete the temporary file */
916 ScopedTemporary::~ScopedTemporary ()
917 {
918         close ();       
919         boost::system::error_code ec;
920         boost::filesystem::remove (_file, ec);
921 }
922
923 /** @return temporary filename */
924 char const *
925 ScopedTemporary::c_str () const
926 {
927         return _file.string().c_str ();
928 }
929
930 /** Open the temporary file.
931  *  @return File's FILE pointer.
932  */
933 FILE*
934 ScopedTemporary::open (char const * params)
935 {
936         _open = fopen (c_str(), params);
937         return _open;
938 }
939
940 /** Close the file */
941 void
942 ScopedTemporary::close ()
943 {
944         if (_open) {
945                 fclose (_open);
946                 _open = 0;
947         }
948 }
949
950 ContentTimePeriod
951 subtitle_period (AVSubtitle const & sub)
952 {
953         ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
954
955         ContentTimePeriod period (
956                 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
957                 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
958                 );
959
960         return period;
961 }