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