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