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