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