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