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