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