Remove uses of boost::system::error_code::message(), which seem to cause the pure...
[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         }
354
355         setlocale (LC_ALL, "");
356         textdomain ("libdcpomatic");
357
358 #ifdef DCPOMATIC_WINDOWS
359         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
360         bind_textdomain_codeset ("libdcpomatic", "UTF8");
361 #endif  
362
363 #ifdef DCPOMATIC_POSIX
364         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
365 #endif
366 }
367
368 /** @param s A string.
369  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
370  */
371 vector<string>
372 split_at_spaces_considering_quotes (string s)
373 {
374         vector<string> out;
375         bool in_quotes = false;
376         string c;
377         for (string::size_type i = 0; i < s.length(); ++i) {
378                 if (s[i] == ' ' && !in_quotes) {
379                         out.push_back (c);
380                         c = N_("");
381                 } else if (s[i] == '"') {
382                         in_quotes = !in_quotes;
383                 } else {
384                         c += s[i];
385                 }
386         }
387
388         out.push_back (c);
389         return out;
390 }
391
392 string
393 md5_digest (void const * data, int size)
394 {
395         MD5_CTX md5_context;
396         MD5_Init (&md5_context);
397         MD5_Update (&md5_context, data, size);
398         unsigned char digest[MD5_DIGEST_LENGTH];
399         MD5_Final (digest, &md5_context);
400         
401         stringstream s;
402         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
403                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
404         }
405
406         return s.str ();
407 }
408
409 /** @param job Optional job for which to report progress */
410 string
411 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
412 {
413         boost::uintmax_t const buffer_size = 64 * 1024;
414         char buffer[buffer_size];
415
416         MD5_CTX md5_context;
417         MD5_Init (&md5_context);
418
419         vector<int64_t> sizes;
420         for (size_t i = 0; i < files.size(); ++i) {
421                 sizes.push_back (boost::filesystem::file_size (files[i]));
422         }
423
424         for (size_t i = 0; i < files.size(); ++i) {
425                 FILE* f = fopen_boost (files[i], "rb");
426                 if (!f) {
427                         throw OpenFileError (files[i].string());
428                 }
429
430                 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
431                 boost::uintmax_t remaining = bytes;
432
433                 while (remaining > 0) {
434                         int const t = min (remaining, buffer_size);
435                         fread (buffer, 1, t, f);
436                         MD5_Update (&md5_context, buffer, t);
437                         remaining -= t;
438
439                         if (job) {
440                                 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
441                         }
442                 }
443
444                 fclose (f);
445         }
446
447         unsigned char digest[MD5_DIGEST_LENGTH];
448         MD5_Final (digest, &md5_context);
449
450         stringstream s;
451         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
452                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
453         }
454
455         return s.str ();
456 }
457
458 static bool
459 about_equal (float a, float b)
460 {
461         /* A film of F seconds at f FPS will be Ff frames;
462            Consider some delta FPS d, so if we run the same
463            film at (f + d) FPS it will last F(f + d) seconds.
464
465            Hence the difference in length over the length of the film will
466            be F(f + d) - Ff frames
467             = Ff + Fd - Ff frames
468             = Fd frames
469             = Fd/f seconds
470  
471            So if we accept a difference of 1 frame, ie 1/f seconds, we can
472            say that
473
474            1/f = Fd/f
475         ie 1 = Fd
476         ie d = 1/F
477  
478            So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
479            FPS error is 1/F ~= 0.0001 ~= 10-e4
480         */
481
482         return (fabs (a - b) < 1e-4);
483 }
484
485 /** @param An arbitrary audio frame rate.
486  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
487  */
488 int
489 dcp_audio_frame_rate (int fs)
490 {
491         if (fs <= 48000) {
492                 return 48000;
493         }
494
495         return 96000;
496 }
497
498 Socket::Socket (int timeout)
499         : _deadline (_io_service)
500         , _socket (_io_service)
501         , _acceptor (0)
502         , _timeout (timeout)
503 {
504         _deadline.expires_at (boost::posix_time::pos_infin);
505         check ();
506 }
507
508 Socket::~Socket ()
509 {
510         delete _acceptor;
511 }
512
513 void
514 Socket::check ()
515 {
516         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
517                 if (_acceptor) {
518                         _acceptor->cancel ();
519                 } else {
520                         _socket.close ();
521                 }
522                 _deadline.expires_at (boost::posix_time::pos_infin);
523         }
524
525         _deadline.async_wait (boost::bind (&Socket::check, this));
526 }
527
528 /** Blocking connect.
529  *  @param endpoint End-point to connect to.
530  */
531 void
532 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
533 {
534         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
535         boost::system::error_code ec = boost::asio::error::would_block;
536         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
537         do {
538                 _io_service.run_one();
539         } while (ec == boost::asio::error::would_block);
540
541         if (ec) {
542                 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
543         }
544
545         if (!_socket.is_open ()) {
546                 throw NetworkError (_("connect timed out"));
547         }
548 }
549
550 void
551 Socket::accept (int port)
552 {
553         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
554         
555         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
556         boost::system::error_code ec = boost::asio::error::would_block;
557         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
558         do {
559                 _io_service.run_one ();
560         } while (ec == boost::asio::error::would_block );
561
562         delete _acceptor;
563         _acceptor = 0;
564         
565         if (ec) {
566                 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
567         }
568 }
569
570 /** Blocking write.
571  *  @param data Buffer to write.
572  *  @param size Number of bytes to write.
573  */
574 void
575 Socket::write (uint8_t const * data, int size)
576 {
577         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
578         boost::system::error_code ec = boost::asio::error::would_block;
579
580         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
581         
582         do {
583                 _io_service.run_one ();
584         } while (ec == boost::asio::error::would_block);
585
586         if (ec) {
587                 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
588         }
589 }
590
591 void
592 Socket::write (uint32_t v)
593 {
594         v = htonl (v);
595         write (reinterpret_cast<uint8_t*> (&v), 4);
596 }
597
598 /** Blocking read.
599  *  @param data Buffer to read to.
600  *  @param size Number of bytes to read.
601  */
602 void
603 Socket::read (uint8_t* data, int size)
604 {
605         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
606         boost::system::error_code ec = boost::asio::error::would_block;
607
608         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
609
610         do {
611                 _io_service.run_one ();
612         } while (ec == boost::asio::error::would_block);
613         
614         if (ec) {
615                 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
616         }
617 }
618
619 uint32_t
620 Socket::read_uint32 ()
621 {
622         uint32_t v;
623         read (reinterpret_cast<uint8_t *> (&v), 4);
624         return ntohl (v);
625 }
626
627 /** Round a number up to the nearest multiple of another number.
628  *  @param c Index.
629  *  @param s Array of numbers to round, indexed by c.
630  *  @param t Multiple to round to.
631  *  @return Rounded number.
632  */
633 int
634 stride_round_up (int c, int const * stride, int t)
635 {
636         int const a = stride[c] + (t - 1);
637         return a - (a % t);
638 }
639
640 /** Read a sequence of key / value pairs from a text stream;
641  *  the keys are the first words on the line, and the values are
642  *  the remainder of the line following the key.  Lines beginning
643  *  with # are ignored.
644  *  @param s Stream to read.
645  *  @return key/value pairs.
646  */
647 multimap<string, string>
648 read_key_value (istream &s) 
649 {
650         multimap<string, string> kv;
651         
652         string line;
653         while (getline (s, line)) {
654                 if (line.empty ()) {
655                         continue;
656                 }
657
658                 if (line[0] == '#') {
659                         continue;
660                 }
661
662                 if (line[line.size() - 1] == '\r') {
663                         line = line.substr (0, line.size() - 1);
664                 }
665
666                 size_t const s = line.find (' ');
667                 if (s == string::npos) {
668                         continue;
669                 }
670
671                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
672         }
673
674         return kv;
675 }
676
677 string
678 get_required_string (multimap<string, string> const & kv, string k)
679 {
680         if (kv.count (k) > 1) {
681                 throw StringError (N_("unexpected multiple keys in key-value set"));
682         }
683
684         multimap<string, string>::const_iterator i = kv.find (k);
685         
686         if (i == kv.end ()) {
687                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
688         }
689
690         return i->second;
691 }
692
693 int
694 get_required_int (multimap<string, string> const & kv, string k)
695 {
696         string const v = get_required_string (kv, k);
697         return lexical_cast<int> (v);
698 }
699
700 float
701 get_required_float (multimap<string, string> const & kv, string k)
702 {
703         string const v = get_required_string (kv, k);
704         return lexical_cast<float> (v);
705 }
706
707 string
708 get_optional_string (multimap<string, string> const & kv, string k)
709 {
710         if (kv.count (k) > 1) {
711                 throw StringError (N_("unexpected multiple keys in key-value set"));
712         }
713
714         multimap<string, string>::const_iterator i = kv.find (k);
715         if (i == kv.end ()) {
716                 return N_("");
717         }
718
719         return i->second;
720 }
721
722 int
723 get_optional_int (multimap<string, string> const & kv, string k)
724 {
725         if (kv.count (k) > 1) {
726                 throw StringError (N_("unexpected multiple keys in key-value set"));
727         }
728
729         multimap<string, string>::const_iterator i = kv.find (k);
730         if (i == kv.end ()) {
731                 return 0;
732         }
733
734         return lexical_cast<int> (i->second);
735 }
736
737 /** Trip an assert if the caller is not in the UI thread */
738 void
739 ensure_ui_thread ()
740 {
741         assert (boost::this_thread::get_id() == ui_thread);
742 }
743
744 /** @param v Content video frame.
745  *  @param audio_sample_rate Source audio sample rate.
746  *  @param frames_per_second Number of video frames per second.
747  *  @return Equivalent number of audio frames for `v'.
748  */
749 int64_t
750 video_frames_to_audio_frames (VideoFrame v, float audio_sample_rate, float frames_per_second)
751 {
752         return ((int64_t) v * audio_sample_rate / frames_per_second);
753 }
754
755 string
756 audio_channel_name (int c)
757 {
758         assert (MAX_AUDIO_CHANNELS == 6);
759
760         /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
761            enhancement channel (sub-woofer).
762         */
763         string const channels[] = {
764                 _("Left"),
765                 _("Right"),
766                 _("Centre"),
767                 _("Lfe (sub)"),
768                 _("Left surround"),
769                 _("Right surround"),
770         };
771
772         return channels[c];
773 }
774
775 FrameRateChange::FrameRateChange (float source, int dcp)
776         : skip (false)
777         , repeat (1)
778         , change_speed (false)
779 {
780         if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
781                 /* The difference between source and DCP frame rate will be lower
782                    (i.e. better) if we skip.
783                 */
784                 skip = true;
785         } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
786                 /* The difference between source and DCP frame rate would be better
787                    if we repeated each frame once; it may be better still if we
788                    repeated more than once.  Work out the required repeat.
789                 */
790                 repeat = round (dcp / source);
791         }
792
793         speed_up = dcp / (source * factor());
794         change_speed = !about_equal (speed_up, 1.0);
795
796         if (!skip && repeat == 1 && !change_speed) {
797                 description = _("Content and DCP have the same rate.\n");
798         } else {
799                 if (skip) {
800                         description = _("DCP will use every other frame of the content.\n");
801                 } else if (repeat == 2) {
802                         description = _("Each content frame will be doubled in the DCP.\n");
803                 } else if (repeat > 2) {
804                         description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
805                 }
806
807                 if (change_speed) {
808                         float const pc = dcp * 100 / (source * factor());
809                         description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
810                 }
811         }
812 }
813
814 LocaleGuard::LocaleGuard ()
815         : _old (0)
816 {
817         char const * old = setlocale (LC_NUMERIC, 0);
818
819         if (old) {
820                 _old = strdup (old);
821                 if (strcmp (_old, "C")) {
822                         setlocale (LC_NUMERIC, "C");
823                 }
824         }
825 }
826
827 LocaleGuard::~LocaleGuard ()
828 {
829         setlocale (LC_NUMERIC, _old);
830         free (_old);
831 }
832
833 bool
834 valid_image_file (boost::filesystem::path f)
835 {
836         string ext = f.extension().string();
837         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
838         return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
839 }
840
841 string
842 tidy_for_filename (string f)
843 {
844         string t;
845         for (size_t i = 0; i < f.length(); ++i) {
846                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
847                         t += f[i];
848                 } else {
849                         t += '_';
850                 }
851         }
852
853         return t;
854 }
855
856 shared_ptr<const libdcp::Signer>
857 make_signer ()
858 {
859         boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
860
861         /* Remake the chain if any of it is missing */
862         
863         list<boost::filesystem::path> files;
864         files.push_back ("ca.self-signed.pem");
865         files.push_back ("intermediate.signed.pem");
866         files.push_back ("leaf.signed.pem");
867         files.push_back ("leaf.key");
868
869         list<boost::filesystem::path>::const_iterator i = files.begin();
870         while (i != files.end()) {
871                 boost::filesystem::path p (sd);
872                 p /= *i;
873                 if (!boost::filesystem::exists (p)) {
874                         boost::filesystem::remove_all (sd);
875                         boost::filesystem::create_directories (sd);
876                         libdcp::make_signer_chain (sd, openssl_path ());
877                         break;
878                 }
879
880                 ++i;
881         }
882         
883         libdcp::CertificateChain chain;
884
885         {
886                 boost::filesystem::path p (sd);
887                 p /= "ca.self-signed.pem";
888                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
889         }
890
891         {
892                 boost::filesystem::path p (sd);
893                 p /= "intermediate.signed.pem";
894                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
895         }
896
897         {
898                 boost::filesystem::path p (sd);
899                 p /= "leaf.signed.pem";
900                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
901         }
902
903         boost::filesystem::path signer_key (sd);
904         signer_key /= "leaf.key";
905
906         return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
907 }
908
909 libdcp::Size
910 fit_ratio_within (float ratio, libdcp::Size full_frame)
911 {
912         if (ratio < full_frame.ratio ()) {
913                 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
914         }
915         
916         return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));
917 }
918
919 DCPTime
920 time_round_up (DCPTime t, DCPTime nearest)
921 {
922         DCPTime const a = t + nearest - 1;
923         return a - (a % nearest);
924 }