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