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