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