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