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