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