Merge branch 'prefs' of ssh://carlh.dyndns.org/home/carl/git/dcpomatic into prefs
[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 <libdcp/version.h>
52 #include <libdcp/util.h>
53 #include <libdcp/signer_chain.h>
54 #include <libdcp/signer.h>
55 extern "C" {
56 #include <libavcodec/avcodec.h>
57 #include <libavformat/avformat.h>
58 #include <libswscale/swscale.h>
59 #include <libavfilter/avfiltergraph.h>
60 #include <libpostproc/postprocess.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 #ifdef DCPOMATIC_WINDOWS
75 #include "stack.hpp"
76 #endif
77
78 #include "i18n.h"
79
80 using std::string;
81 using std::stringstream;
82 using std::setfill;
83 using std::ostream;
84 using std::endl;
85 using std::vector;
86 using std::hex;
87 using std::setw;
88 using std::ios;
89 using std::min;
90 using std::max;
91 using std::list;
92 using std::multimap;
93 using std::map;
94 using std::istream;
95 using std::numeric_limits;
96 using std::pair;
97 using std::cout;
98 using std::bad_alloc;
99 using std::streampos;
100 using std::set_terminate;
101 using boost::shared_ptr;
102 using boost::thread;
103 using boost::lexical_cast;
104 using boost::optional;
105 using libdcp::Size;
106
107 static boost::thread::id ui_thread;
108 static boost::filesystem::path backtrace_file;
109
110 /** Convert some number of seconds to a string representation
111  *  in hours, minutes and seconds.
112  *
113  *  @param s Seconds.
114  *  @return String of the form H:M:S (where H is hours, M
115  *  is minutes and S is seconds).
116  */
117 string
118 seconds_to_hms (int s)
119 {
120         int m = s / 60;
121         s -= (m * 60);
122         int h = m / 60;
123         m -= (h * 60);
124
125         stringstream hms;
126         hms << h << N_(":");
127         hms.width (2);
128         hms << std::setfill ('0') << m << N_(":");
129         hms.width (2);
130         hms << std::setfill ('0') << s;
131
132         return hms.str ();
133 }
134
135 /** @param s Number of seconds.
136  *  @return String containing an approximate description of s (e.g. "about 2 hours")
137  */
138 string
139 seconds_to_approximate_hms (int s)
140 {
141         int m = s / 60;
142         s -= (m * 60);
143         int h = m / 60;
144         m -= (h * 60);
145
146         stringstream ap;
147         
148         if (h > 0) {
149                 if (m > 30) {
150                         ap << (h + 1) << N_(" ") << _("hours");
151                 } else {
152                         if (h == 1) {
153                                 ap << N_("1 ") << _("hour");
154                         } else {
155                                 ap << h << N_(" ") << _("hours");
156                         }
157                 }
158         } else if (m > 0) {
159                 if (m == 1) {
160                         ap << N_("1 ") << _("minute");
161                 } else {
162                         ap << m << N_(" ") << _("minutes");
163                 }
164         } else {
165                 ap << s << N_(" ") << _("seconds");
166         }
167
168         return ap.str ();
169 }
170
171 #ifdef DCPOMATIC_POSIX
172 /** @param l Mangled C++ identifier.
173  *  @return Demangled version.
174  */
175 static string
176 demangle (string l)
177 {
178         string::size_type const b = l.find_first_of (N_("("));
179         if (b == string::npos) {
180                 return l;
181         }
182
183         string::size_type const p = l.find_last_of (N_("+"));
184         if (p == string::npos) {
185                 return l;
186         }
187
188         if ((p - b) <= 1) {
189                 return l;
190         }
191         
192         string const fn = l.substr (b + 1, p - b - 1);
193
194         int status;
195         try {
196                 
197                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
198                 string d (realname);
199                 free (realname);
200                 return d;
201                 
202         } catch (std::exception) {
203                 
204         }
205         
206         return l;
207 }
208
209 /** Write a stacktrace to an ostream.
210  *  @param out Stream to write to.
211  *  @param levels Number of levels to go up the call stack.
212  */
213 void
214 stacktrace (ostream& out, int levels)
215 {
216         void *array[200];
217         size_t size = backtrace (array, 200);
218         char** strings = backtrace_symbols (array, size);
219      
220         if (strings) {
221                 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
222                         out << N_("  ") << demangle (strings[i]) << "\n";
223                 }
224                 
225                 free (strings);
226         }
227 }
228 #endif
229
230 /** @param v Version as used by FFmpeg.
231  *  @return A string representation of v.
232  */
233 static string
234 ffmpeg_version_to_string (int v)
235 {
236         stringstream s;
237         s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
238         return s.str ();
239 }
240
241 /** Return a user-readable string summarising the versions of our dependencies */
242 string
243 dependency_version_summary ()
244 {
245         stringstream s;
246         s << N_("libopenjpeg ") << opj_version () << N_(", ")
247           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
248           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
249           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
250           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
251           << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
252           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
253           << MagickVersion << N_(", ")
254           << N_("libssh ") << ssh_version (0) << N_(", ")
255           << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
256
257         return s.str ();
258 }
259
260 double
261 seconds (struct timeval t)
262 {
263         return t.tv_sec + (double (t.tv_usec) / 1e6);
264 }
265
266 #ifdef DCPOMATIC_WINDOWS
267 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
268 {
269         dbg::stack s;
270         FILE* f = fopen_boost (backtrace_file, "w");
271         for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
272                 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
273         }
274         fclose (f);
275         return EXCEPTION_CONTINUE_SEARCH;
276 }
277 #endif
278
279 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
280 void
281 terminate ()
282 {
283         static bool tried_throw = false;
284
285         try {
286                 // try once to re-throw currently active exception
287                 if (!tried_throw++) {
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 string
430 md5_digest (void const * data, int size)
431 {
432         MD5_CTX md5_context;
433         MD5_Init (&md5_context);
434         MD5_Update (&md5_context, data, size);
435         unsigned char digest[MD5_DIGEST_LENGTH];
436         MD5_Final (digest, &md5_context);
437         
438         stringstream s;
439         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
440                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
441         }
442
443         return s.str ();
444 }
445
446 /** @param job Optional job for which to report progress */
447 string
448 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
449 {
450         boost::uintmax_t const buffer_size = 64 * 1024;
451         char buffer[buffer_size];
452
453         MD5_CTX md5_context;
454         MD5_Init (&md5_context);
455
456         vector<int64_t> sizes;
457         for (size_t i = 0; i < files.size(); ++i) {
458                 sizes.push_back (boost::filesystem::file_size (files[i]));
459         }
460
461         for (size_t i = 0; i < files.size(); ++i) {
462                 FILE* f = fopen_boost (files[i], "rb");
463                 if (!f) {
464                         throw OpenFileError (files[i].string());
465                 }
466
467                 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
468                 boost::uintmax_t remaining = bytes;
469
470                 while (remaining > 0) {
471                         int const t = min (remaining, buffer_size);
472                         fread (buffer, 1, t, f);
473                         MD5_Update (&md5_context, buffer, t);
474                         remaining -= t;
475
476                         if (job) {
477                                 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
478                         }
479                 }
480
481                 fclose (f);
482         }
483
484         unsigned char digest[MD5_DIGEST_LENGTH];
485         MD5_Final (digest, &md5_context);
486
487         stringstream s;
488         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
489                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
490         }
491
492         return s.str ();
493 }
494
495 static bool
496 about_equal (float a, float b)
497 {
498         /* A film of F seconds at f FPS will be Ff frames;
499            Consider some delta FPS d, so if we run the same
500            film at (f + d) FPS it will last F(f + d) seconds.
501
502            Hence the difference in length over the length of the film will
503            be F(f + d) - Ff frames
504             = Ff + Fd - Ff frames
505             = Fd frames
506             = Fd/f seconds
507  
508            So if we accept a difference of 1 frame, ie 1/f seconds, we can
509            say that
510
511            1/f = Fd/f
512         ie 1 = Fd
513         ie d = 1/F
514  
515            So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
516            FPS error is 1/F ~= 0.0001 ~= 10-e4
517         */
518
519         return (fabs (a - b) < 1e-4);
520 }
521
522 /** @param An arbitrary audio frame rate.
523  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
524  */
525 int
526 dcp_audio_frame_rate (int fs)
527 {
528         if (fs <= 48000) {
529                 return 48000;
530         }
531
532         return 96000;
533 }
534
535 Socket::Socket (int timeout)
536         : _deadline (_io_service)
537         , _socket (_io_service)
538         , _acceptor (0)
539         , _timeout (timeout)
540 {
541         _deadline.expires_at (boost::posix_time::pos_infin);
542         check ();
543 }
544
545 Socket::~Socket ()
546 {
547         delete _acceptor;
548 }
549
550 void
551 Socket::check ()
552 {
553         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
554                 if (_acceptor) {
555                         _acceptor->cancel ();
556                 } else {
557                         _socket.close ();
558                 }
559                 _deadline.expires_at (boost::posix_time::pos_infin);
560         }
561
562         _deadline.async_wait (boost::bind (&Socket::check, this));
563 }
564
565 /** Blocking connect.
566  *  @param endpoint End-point to connect to.
567  */
568 void
569 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
570 {
571         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
572         boost::system::error_code ec = boost::asio::error::would_block;
573         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
574         do {
575                 _io_service.run_one();
576         } while (ec == boost::asio::error::would_block);
577
578         if (ec) {
579                 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
580         }
581
582         if (!_socket.is_open ()) {
583                 throw NetworkError (_("connect timed out"));
584         }
585 }
586
587 void
588 Socket::accept (int port)
589 {
590         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
591         
592         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
593         boost::system::error_code ec = boost::asio::error::would_block;
594         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
595         do {
596                 _io_service.run_one ();
597         } while (ec == boost::asio::error::would_block );
598
599         delete _acceptor;
600         _acceptor = 0;
601         
602         if (ec) {
603                 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
604         }
605 }
606
607 /** Blocking write.
608  *  @param data Buffer to write.
609  *  @param size Number of bytes to write.
610  */
611 void
612 Socket::write (uint8_t const * data, int size)
613 {
614         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
615         boost::system::error_code ec = boost::asio::error::would_block;
616
617         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
618         
619         do {
620                 _io_service.run_one ();
621         } while (ec == boost::asio::error::would_block);
622
623         if (ec) {
624                 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
625         }
626 }
627
628 void
629 Socket::write (uint32_t v)
630 {
631         v = htonl (v);
632         write (reinterpret_cast<uint8_t*> (&v), 4);
633 }
634
635 /** Blocking read.
636  *  @param data Buffer to read to.
637  *  @param size Number of bytes to read.
638  */
639 void
640 Socket::read (uint8_t* data, int size)
641 {
642         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
643         boost::system::error_code ec = boost::asio::error::would_block;
644
645         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
646
647         do {
648                 _io_service.run_one ();
649         } while (ec == boost::asio::error::would_block);
650         
651         if (ec) {
652                 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
653         }
654 }
655
656 uint32_t
657 Socket::read_uint32 ()
658 {
659         uint32_t v;
660         read (reinterpret_cast<uint8_t *> (&v), 4);
661         return ntohl (v);
662 }
663
664 /** Round a number up to the nearest multiple of another number.
665  *  @param c Index.
666  *  @param s Array of numbers to round, indexed by c.
667  *  @param t Multiple to round to.
668  *  @return Rounded number.
669  */
670 int
671 stride_round_up (int c, int const * stride, int t)
672 {
673         int const a = stride[c] + (t - 1);
674         return a - (a % t);
675 }
676
677 /** Read a sequence of key / value pairs from a text stream;
678  *  the keys are the first words on the line, and the values are
679  *  the remainder of the line following the key.  Lines beginning
680  *  with # are ignored.
681  *  @param s Stream to read.
682  *  @return key/value pairs.
683  */
684 multimap<string, string>
685 read_key_value (istream &s) 
686 {
687         multimap<string, string> kv;
688         
689         string line;
690         while (getline (s, line)) {
691                 if (line.empty ()) {
692                         continue;
693                 }
694
695                 if (line[0] == '#') {
696                         continue;
697                 }
698
699                 if (line[line.size() - 1] == '\r') {
700                         line = line.substr (0, line.size() - 1);
701                 }
702
703                 size_t const s = line.find (' ');
704                 if (s == string::npos) {
705                         continue;
706                 }
707
708                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
709         }
710
711         return kv;
712 }
713
714 string
715 get_required_string (multimap<string, string> const & kv, string k)
716 {
717         if (kv.count (k) > 1) {
718                 throw StringError (N_("unexpected multiple keys in key-value set"));
719         }
720
721         multimap<string, string>::const_iterator i = kv.find (k);
722         
723         if (i == kv.end ()) {
724                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
725         }
726
727         return i->second;
728 }
729
730 int
731 get_required_int (multimap<string, string> const & kv, string k)
732 {
733         string const v = get_required_string (kv, k);
734         return lexical_cast<int> (v);
735 }
736
737 float
738 get_required_float (multimap<string, string> const & kv, string k)
739 {
740         string const v = get_required_string (kv, k);
741         return lexical_cast<float> (v);
742 }
743
744 string
745 get_optional_string (multimap<string, string> const & kv, string k)
746 {
747         if (kv.count (k) > 1) {
748                 throw StringError (N_("unexpected multiple keys in key-value set"));
749         }
750
751         multimap<string, string>::const_iterator i = kv.find (k);
752         if (i == kv.end ()) {
753                 return N_("");
754         }
755
756         return i->second;
757 }
758
759 int
760 get_optional_int (multimap<string, string> const & kv, string k)
761 {
762         if (kv.count (k) > 1) {
763                 throw StringError (N_("unexpected multiple keys in key-value set"));
764         }
765
766         multimap<string, string>::const_iterator i = kv.find (k);
767         if (i == kv.end ()) {
768                 return 0;
769         }
770
771         return lexical_cast<int> (i->second);
772 }
773
774 /** Trip an assert if the caller is not in the UI thread */
775 void
776 ensure_ui_thread ()
777 {
778         assert (boost::this_thread::get_id() == ui_thread);
779 }
780
781 /** @param v Content video frame.
782  *  @param audio_sample_rate Source audio sample rate.
783  *  @param frames_per_second Number of video frames per second.
784  *  @return Equivalent number of audio frames for `v'.
785  */
786 int64_t
787 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
788 {
789         return ((int64_t) v * audio_sample_rate / frames_per_second);
790 }
791
792 string
793 audio_channel_name (int c)
794 {
795         assert (MAX_AUDIO_CHANNELS == 12);
796
797         /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
798            enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
799            VI is the visually-impaired audio track (audio describe).
800         */
801         string const channels[] = {
802                 _("Left"),
803                 _("Right"),
804                 _("Centre"),
805                 _("Lfe (sub)"),
806                 _("Left surround"),
807                 _("Right surround"),
808                 _("Hearing impaired"),
809                 _("Visually impaired"),
810                 _("Left centre"),
811                 _("Right centre"),
812                 _("Left rear surround"),
813                 _("Right rear surround"),
814         };
815
816         return channels[c];
817 }
818
819 FrameRateConversion::FrameRateConversion (float source, int dcp)
820         : skip (false)
821         , repeat (1)
822         , change_speed (false)
823 {
824         if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
825                 /* The difference between source and DCP frame rate will be lower
826                    (i.e. better) if we skip.
827                 */
828                 skip = true;
829         } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
830                 /* The difference between source and DCP frame rate would be better
831                    if we repeated each frame once; it may be better still if we
832                    repeated more than once.  Work out the required repeat.
833                 */
834                 repeat = round (dcp / source);
835         }
836
837         change_speed = !about_equal (source * factor(), dcp);
838
839         if (!skip && repeat == 1 && !change_speed) {
840                 description = _("Content and DCP have the same rate.\n");
841         } else {
842                 if (skip) {
843                         description = _("DCP will use every other frame of the content.\n");
844                 } else if (repeat == 2) {
845                         description = _("Each content frame will be doubled in the DCP.\n");
846                 } else if (repeat > 2) {
847                         description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
848                 }
849
850                 if (change_speed) {
851                         float const pc = dcp * 100 / (source * factor());
852                         description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
853                 }
854         }
855 }
856
857 LocaleGuard::LocaleGuard ()
858         : _old (0)
859 {
860         char const * old = setlocale (LC_NUMERIC, 0);
861
862         if (old) {
863                 _old = strdup (old);
864                 if (strcmp (_old, "C")) {
865                         setlocale (LC_NUMERIC, "C");
866                 }
867         }
868 }
869
870 LocaleGuard::~LocaleGuard ()
871 {
872         setlocale (LC_NUMERIC, _old);
873         free (_old);
874 }
875
876 bool
877 valid_image_file (boost::filesystem::path f)
878 {
879         string ext = f.extension().string();
880         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
881         return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
882 }
883
884 string
885 tidy_for_filename (string f)
886 {
887         string t;
888         for (size_t i = 0; i < f.length(); ++i) {
889                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
890                         t += f[i];
891                 } else {
892                         t += '_';
893                 }
894         }
895
896         return t;
897 }
898
899 shared_ptr<const libdcp::Signer>
900 make_signer ()
901 {
902         boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
903
904         /* Remake the chain if any of it is missing */
905         
906         list<boost::filesystem::path> files;
907         files.push_back ("ca.self-signed.pem");
908         files.push_back ("intermediate.signed.pem");
909         files.push_back ("leaf.signed.pem");
910         files.push_back ("leaf.key");
911
912         list<boost::filesystem::path>::const_iterator i = files.begin();
913         while (i != files.end()) {
914                 boost::filesystem::path p (sd);
915                 p /= *i;
916                 if (!boost::filesystem::exists (p)) {
917                         boost::filesystem::remove_all (sd);
918                         boost::filesystem::create_directories (sd);
919                         libdcp::make_signer_chain (sd, openssl_path ());
920                         break;
921                 }
922
923                 ++i;
924         }
925         
926         libdcp::CertificateChain chain;
927
928         {
929                 boost::filesystem::path p (sd);
930                 p /= "ca.self-signed.pem";
931                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
932         }
933
934         {
935                 boost::filesystem::path p (sd);
936                 p /= "intermediate.signed.pem";
937                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
938         }
939
940         {
941                 boost::filesystem::path p (sd);
942                 p /= "leaf.signed.pem";
943                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
944         }
945
946         boost::filesystem::path signer_key (sd);
947         signer_key /= "leaf.key";
948
949         return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
950 }
951
952 map<string, string>
953 split_get_request (string url)
954 {
955         enum {
956                 AWAITING_QUESTION_MARK,
957                 KEY,
958                 VALUE
959         } state = AWAITING_QUESTION_MARK;
960         
961         map<string, string> r;
962         string k;
963         string v;
964         for (size_t i = 0; i < url.length(); ++i) {
965                 switch (state) {
966                 case AWAITING_QUESTION_MARK:
967                         if (url[i] == '?') {
968                                 state = KEY;
969                         }
970                         break;
971                 case KEY:
972                         if (url[i] == '=') {
973                                 v.clear ();
974                                 state = VALUE;
975                         } else {
976                                 k += url[i];
977                         }
978                         break;
979                 case VALUE:
980                         if (url[i] == '&') {
981                                 r.insert (make_pair (k, v));
982                                 k.clear ();
983                                 state = KEY;
984                         } else {
985                                 v += url[i];
986                         }
987                         break;
988                 }
989         }
990
991         if (state == VALUE) {
992                 r.insert (make_pair (k, v));
993         }
994
995         return r;
996 }
997
998 libdcp::Size
999 fit_ratio_within (float ratio, libdcp::Size full_frame)
1000 {
1001         if (ratio < full_frame.ratio ()) {
1002                 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
1003         }
1004         
1005         return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));
1006 }
1007
1008 void *
1009 wrapped_av_malloc (size_t s)
1010 {
1011         void* p = av_malloc (s);
1012         if (!p) {
1013                 throw bad_alloc ();
1014         }
1015         return p;
1016 }
1017                 
1018 string
1019 entities_to_text (string e)
1020 {
1021         boost::algorithm::replace_all (e, "%3A", ":");
1022         boost::algorithm::replace_all (e, "%2F", "/");
1023         return e;
1024 }
1025
1026 int64_t
1027 divide_with_round (int64_t a, int64_t b)
1028 {
1029         if (a % b >= (b / 2)) {
1030                 return (a + b - 1) / b;
1031         } else {
1032                 return a / b;
1033         }
1034 }