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