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