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