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