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