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