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