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