A whole load of UTF-8/-16 confusion fixes for Windows.
[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 <boost/locale.hpp>
43 #include <glib.h>
44 #include <openjpeg.h>
45 #include <openssl/md5.h>
46 #include <magick/MagickCore.h>
47 #include <magick/version.h>
48 #include <libdcp/version.h>
49 #include <libdcp/util.h>
50 #include <libdcp/signer_chain.h>
51 #include <libdcp/signer.h>
52 extern "C" {
53 #include <libavcodec/avcodec.h>
54 #include <libavformat/avformat.h>
55 #include <libswscale/swscale.h>
56 #include <libavfilter/avfiltergraph.h>
57 #include <libpostproc/postprocess.h>
58 #include <libavutil/pixfmt.h>
59 }
60 #include "util.h"
61 #include "exceptions.h"
62 #include "scaler.h"
63 #include "dcp_content_type.h"
64 #include "filter.h"
65 #include "sound_processor.h"
66 #include "config.h"
67 #include "ratio.h"
68 #include "job.h"
69 #include "cross.h"
70 #ifdef DCPOMATIC_WINDOWS
71 #include "stack.hpp"
72 #endif
73
74 #include "i18n.h"
75
76 using std::string;
77 using std::stringstream;
78 using std::setfill;
79 using std::ostream;
80 using std::endl;
81 using std::vector;
82 using std::hex;
83 using std::setw;
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::cout;
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         FILE* f = fopen_boost (backtrace_file, "w");
263         for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
264                 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
265         }
266         fclose (f);
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
282         /* Dark voodoo which, I think, gets boost::filesystem::path to
283            correctly convert UTF-8 strings to paths, and also paths
284            back to UTF-8 strings (on path::string()).
285
286            After this, constructing boost::filesystem::paths from strings
287            converts from UTF-8 to UTF-16 inside the path.  Then
288            path::string().c_str() gives UTF-8 and
289            path::c_str()          gives UTF-16.
290
291            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
292            so things are much simpler.
293         */
294         std::locale::global (boost::locale::generator().generate (""));
295         boost::filesystem::path::imbue (std::locale ());
296 #endif  
297         
298         avfilter_register_all ();
299
300 #ifdef DCPOMATIC_OSX
301         /* Add our lib directory to the libltdl search path so that
302            xmlsec can find xmlsec1-openssl.
303         */
304         boost::filesystem::path lib = app_contents ();
305         lib /= "lib";
306         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
307 #endif  
308
309         libdcp::init ();
310         
311         Ratio::setup_ratios ();
312         DCPContentType::setup_dcp_content_types ();
313         Scaler::setup_scalers ();
314         Filter::setup_filters ();
315         SoundProcessor::setup_sound_processors ();
316
317         ui_thread = boost::this_thread::get_id ();
318 }
319
320 #ifdef DCPOMATIC_WINDOWS
321 boost::filesystem::path
322 mo_path ()
323 {
324         wchar_t buffer[512];
325         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
326         boost::filesystem::path p (buffer);
327         p = p.parent_path ();
328         p = p.parent_path ();
329         p /= "locale";
330         return p;
331 }
332 #endif
333
334 void
335 dcpomatic_setup_gettext_i18n (string lang)
336 {
337 #ifdef DCPOMATIC_POSIX
338         lang += ".UTF8";
339 #endif
340
341         if (!lang.empty ()) {
342                 /* Override our environment language; this is essential on
343                    Windows.
344                 */
345                 char cmd[64];
346                 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
347                 putenv (cmd);
348                 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
349                 putenv (cmd);
350         }
351
352         setlocale (LC_ALL, "");
353         textdomain ("libdcpomatic");
354
355 #ifdef DCPOMATIC_WINDOWS
356         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
357         bind_textdomain_codeset ("libdcpomatic", "UTF8");
358 #endif  
359
360 #ifdef DCPOMATIC_POSIX
361         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
362 #endif
363 }
364
365 /** @param s A string.
366  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
367  */
368 vector<string>
369 split_at_spaces_considering_quotes (string s)
370 {
371         vector<string> out;
372         bool in_quotes = false;
373         string c;
374         for (string::size_type i = 0; i < s.length(); ++i) {
375                 if (s[i] == ' ' && !in_quotes) {
376                         out.push_back (c);
377                         c = N_("");
378                 } else if (s[i] == '"') {
379                         in_quotes = !in_quotes;
380                 } else {
381                         c += s[i];
382                 }
383         }
384
385         out.push_back (c);
386         return out;
387 }
388
389 string
390 md5_digest (void const * data, int size)
391 {
392         MD5_CTX md5_context;
393         MD5_Init (&md5_context);
394         MD5_Update (&md5_context, data, size);
395         unsigned char digest[MD5_DIGEST_LENGTH];
396         MD5_Final (digest, &md5_context);
397         
398         stringstream s;
399         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
400                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
401         }
402
403         return s.str ();
404 }
405
406 /** @param file File name.
407  *  @return MD5 digest of file's contents.
408  */
409 string
410 md5_digest (boost::filesystem::path file)
411 {
412         FILE* f = fopen_boost (file, "rb");
413         if (!f) {
414                 throw OpenFileError (file.string());
415         }
416
417         boost::uintmax_t bytes = boost::filesystem::file_size (file);
418
419         boost::uintmax_t const buffer_size = 64 * 1024;
420         char buffer[buffer_size];
421
422         MD5_CTX md5_context;
423         MD5_Init (&md5_context);
424         while (bytes > 0) {
425                 int const t = min (bytes, buffer_size);
426                 fread (buffer, 1, t, f);
427                 MD5_Update (&md5_context, buffer, t);
428                 bytes -= t;
429         }
430
431         unsigned char digest[MD5_DIGEST_LENGTH];
432         MD5_Final (digest, &md5_context);
433         fclose (f);
434
435         stringstream s;
436         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
437                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
438         }
439
440         return s.str ();
441 }
442
443 /** @param job Optional job for which to report progress */
444 string
445 md5_digest_directory (boost::filesystem::path directory, shared_ptr<Job> job)
446 {
447         boost::uintmax_t const buffer_size = 64 * 1024;
448         char buffer[buffer_size];
449
450         MD5_CTX md5_context;
451         MD5_Init (&md5_context);
452
453         int files = 0;
454         if (job) {
455                 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
456                         ++files;
457                 }
458         }
459
460         int j = 0;
461         for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
462                 FILE* f = fopen_boost (i->path(), "rb");
463                 if (!f) {
464                         throw OpenFileError (i->path().string());
465                 }
466
467                 boost::uintmax_t bytes = boost::filesystem::file_size (i->path ());
468
469                 while (bytes > 0) {
470                         int const t = min (bytes, buffer_size);
471                         fread (buffer, 1, t, f);
472                         MD5_Update (&md5_context, buffer, t);
473                         bytes -= t;
474                 }
475
476                 if (job) {
477                         job->set_progress (float (j) / files);
478                         ++j;
479                 }
480
481                 fclose (f);
482         }
483
484         unsigned char digest[MD5_DIGEST_LENGTH];
485         MD5_Final (digest, &md5_context);
486
487         stringstream s;
488         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
489                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
490         }
491
492         return s.str ();
493 }
494
495 static bool
496 about_equal (float a, float b)
497 {
498         /* A film of F seconds at f FPS will be Ff frames;
499            Consider some delta FPS d, so if we run the same
500            film at (f + d) FPS it will last F(f + d) seconds.
501
502            Hence the difference in length over the length of the film will
503            be F(f + d) - Ff frames
504             = Ff + Fd - Ff frames
505             = Fd frames
506             = Fd/f seconds
507  
508            So if we accept a difference of 1 frame, ie 1/f seconds, we can
509            say that
510
511            1/f = Fd/f
512         ie 1 = Fd
513         ie d = 1/F
514  
515            So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
516            FPS error is 1/F ~= 0.0001 ~= 10-e4
517         */
518
519         return (fabs (a - b) < 1e-4);
520 }
521
522 /** @param An arbitrary audio frame rate.
523  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
524  */
525 int
526 dcp_audio_frame_rate (int fs)
527 {
528         if (fs <= 48000) {
529                 return 48000;
530         }
531
532         return 96000;
533 }
534
535 Socket::Socket (int timeout)
536         : _deadline (_io_service)
537         , _socket (_io_service)
538         , _acceptor (0)
539         , _timeout (timeout)
540 {
541         _deadline.expires_at (boost::posix_time::pos_infin);
542         check ();
543 }
544
545 Socket::~Socket ()
546 {
547         delete _acceptor;
548 }
549
550 void
551 Socket::check ()
552 {
553         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
554                 if (_acceptor) {
555                         _acceptor->cancel ();
556                 } else {
557                         _socket.close ();
558                 }
559                 _deadline.expires_at (boost::posix_time::pos_infin);
560         }
561
562         _deadline.async_wait (boost::bind (&Socket::check, this));
563 }
564
565 /** Blocking connect.
566  *  @param endpoint End-point to connect to.
567  */
568 void
569 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
570 {
571         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
572         boost::system::error_code ec = boost::asio::error::would_block;
573         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
574         do {
575                 _io_service.run_one();
576         } while (ec == boost::asio::error::would_block);
577
578         if (ec) {
579                 throw NetworkError (ec.message ());
580         }
581
582         if (!_socket.is_open ()) {
583                 throw NetworkError (_("connect timed out"));
584         }
585 }
586
587 void
588 Socket::accept (int port)
589 {
590         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
591         
592         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
593         boost::system::error_code ec = boost::asio::error::would_block;
594         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
595         do {
596                 _io_service.run_one ();
597         } while (ec == boost::asio::error::would_block );
598
599         delete _acceptor;
600         _acceptor = 0;
601         
602         if (ec) {
603                 throw NetworkError (ec.message ());
604         }
605 }
606
607 /** Blocking write.
608  *  @param data Buffer to write.
609  *  @param size Number of bytes to write.
610  */
611 void
612 Socket::write (uint8_t const * data, int size)
613 {
614         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
615         boost::system::error_code ec = boost::asio::error::would_block;
616
617         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
618         
619         do {
620                 _io_service.run_one ();
621         } while (ec == boost::asio::error::would_block);
622
623         if (ec) {
624                 throw NetworkError (ec.message ());
625         }
626 }
627
628 void
629 Socket::write (uint32_t v)
630 {
631         v = htonl (v);
632         write (reinterpret_cast<uint8_t*> (&v), 4);
633 }
634
635 /** Blocking read.
636  *  @param data Buffer to read to.
637  *  @param size Number of bytes to read.
638  */
639 void
640 Socket::read (uint8_t* data, int size)
641 {
642         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
643         boost::system::error_code ec = boost::asio::error::would_block;
644
645         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
646
647         do {
648                 _io_service.run_one ();
649         } while (ec == boost::asio::error::would_block);
650         
651         if (ec) {
652                 throw NetworkError (ec.message ());
653         }
654 }
655
656 uint32_t
657 Socket::read_uint32 ()
658 {
659         uint32_t v;
660         read (reinterpret_cast<uint8_t *> (&v), 4);
661         return ntohl (v);
662 }
663
664 /** Round a number up to the nearest multiple of another number.
665  *  @param c Index.
666  *  @param s Array of numbers to round, indexed by c.
667  *  @param t Multiple to round to.
668  *  @return Rounded number.
669  */
670 int
671 stride_round_up (int c, int const * stride, int t)
672 {
673         int const a = stride[c] + (t - 1);
674         return a - (a % t);
675 }
676
677 /** Read a sequence of key / value pairs from a text stream;
678  *  the keys are the first words on the line, and the values are
679  *  the remainder of the line following the key.  Lines beginning
680  *  with # are ignored.
681  *  @param s Stream to read.
682  *  @return key/value pairs.
683  */
684 multimap<string, string>
685 read_key_value (istream &s) 
686 {
687         multimap<string, string> kv;
688         
689         string line;
690         while (getline (s, line)) {
691                 if (line.empty ()) {
692                         continue;
693                 }
694
695                 if (line[0] == '#') {
696                         continue;
697                 }
698
699                 if (line[line.size() - 1] == '\r') {
700                         line = line.substr (0, line.size() - 1);
701                 }
702
703                 size_t const s = line.find (' ');
704                 if (s == string::npos) {
705                         continue;
706                 }
707
708                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
709         }
710
711         return kv;
712 }
713
714 string
715 get_required_string (multimap<string, string> const & kv, string k)
716 {
717         if (kv.count (k) > 1) {
718                 throw StringError (N_("unexpected multiple keys in key-value set"));
719         }
720
721         multimap<string, string>::const_iterator i = kv.find (k);
722         
723         if (i == kv.end ()) {
724                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
725         }
726
727         return i->second;
728 }
729
730 int
731 get_required_int (multimap<string, string> const & kv, string k)
732 {
733         string const v = get_required_string (kv, k);
734         return lexical_cast<int> (v);
735 }
736
737 float
738 get_required_float (multimap<string, string> const & kv, string k)
739 {
740         string const v = get_required_string (kv, k);
741         return lexical_cast<float> (v);
742 }
743
744 string
745 get_optional_string (multimap<string, string> const & kv, string k)
746 {
747         if (kv.count (k) > 1) {
748                 throw StringError (N_("unexpected multiple keys in key-value set"));
749         }
750
751         multimap<string, string>::const_iterator i = kv.find (k);
752         if (i == kv.end ()) {
753                 return N_("");
754         }
755
756         return i->second;
757 }
758
759 int
760 get_optional_int (multimap<string, string> const & kv, string k)
761 {
762         if (kv.count (k) > 1) {
763                 throw StringError (N_("unexpected multiple keys in key-value set"));
764         }
765
766         multimap<string, string>::const_iterator i = kv.find (k);
767         if (i == kv.end ()) {
768                 return 0;
769         }
770
771         return lexical_cast<int> (i->second);
772 }
773
774 /** Trip an assert if the caller is not in the UI thread */
775 void
776 ensure_ui_thread ()
777 {
778         assert (boost::this_thread::get_id() == ui_thread);
779 }
780
781 /** @param v Content video frame.
782  *  @param audio_sample_rate Source audio sample rate.
783  *  @param frames_per_second Number of video frames per second.
784  *  @return Equivalent number of audio frames for `v'.
785  */
786 int64_t
787 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
788 {
789         return ((int64_t) v * audio_sample_rate / frames_per_second);
790 }
791
792 string
793 audio_channel_name (int c)
794 {
795         assert (MAX_AUDIO_CHANNELS == 6);
796
797         /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
798            enhancement channel (sub-woofer).
799         */
800         string const channels[] = {
801                 _("Left"),
802                 _("Right"),
803                 _("Centre"),
804                 _("Lfe (sub)"),
805                 _("Left surround"),
806                 _("Right surround"),
807         };
808
809         return channels[c];
810 }
811
812 FrameRateConversion::FrameRateConversion (float source, int dcp)
813         : skip (false)
814         , repeat (1)
815         , change_speed (false)
816 {
817         if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
818                 /* The difference between source and DCP frame rate will be lower
819                    (i.e. better) if we skip.
820                 */
821                 skip = true;
822         } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
823                 /* The difference between source and DCP frame rate would be better
824                    if we repeated each frame once; it may be better still if we
825                    repeated more than once.  Work out the required repeat.
826                 */
827                 repeat = round (dcp / source);
828         }
829
830         change_speed = !about_equal (source * factor(), dcp);
831
832         if (!skip && repeat == 1 && !change_speed) {
833                 description = _("Content and DCP have the same rate.\n");
834         } else {
835                 if (skip) {
836                         description = _("DCP will use every other frame of the content.\n");
837                 } else if (repeat == 2) {
838                         description = _("Each content frame will be doubled in the DCP.\n");
839                 } else if (repeat > 2) {
840                         description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
841                 }
842
843                 if (change_speed) {
844                         float const pc = dcp * 100 / (source * factor());
845                         description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
846                 }
847         }
848 }
849
850 LocaleGuard::LocaleGuard ()
851         : _old (0)
852 {
853         char const * old = setlocale (LC_NUMERIC, 0);
854
855         if (old) {
856                 _old = strdup (old);
857                 if (strcmp (_old, "C")) {
858                         setlocale (LC_NUMERIC, "C");
859                 }
860         }
861 }
862
863 LocaleGuard::~LocaleGuard ()
864 {
865         setlocale (LC_NUMERIC, _old);
866         free (_old);
867 }
868
869 bool
870 valid_image_file (boost::filesystem::path f)
871 {
872         string ext = f.extension().string();
873         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
874         return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
875 }
876
877 string
878 tidy_for_filename (string f)
879 {
880         string t;
881         for (size_t i = 0; i < f.length(); ++i) {
882                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
883                         t += f[i];
884                 } else {
885                         t += '_';
886                 }
887         }
888
889         return t;
890 }
891
892 shared_ptr<const libdcp::Signer>
893 make_signer ()
894 {
895         boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
896
897         /* Remake the chain if any of it is missing */
898         
899         list<boost::filesystem::path> files;
900         files.push_back ("ca.self-signed.pem");
901         files.push_back ("intermediate.signed.pem");
902         files.push_back ("leaf.signed.pem");
903         files.push_back ("leaf.key");
904
905         list<boost::filesystem::path>::const_iterator i = files.begin();
906         while (i != files.end()) {
907                 boost::filesystem::path p (sd);
908                 p /= *i;
909                 if (!boost::filesystem::exists (p)) {
910                         boost::filesystem::remove_all (sd);
911                         boost::filesystem::create_directories (sd);
912                         libdcp::make_signer_chain (sd, openssl_path ());
913                         break;
914                 }
915
916                 ++i;
917         }
918         
919         libdcp::CertificateChain chain;
920
921         {
922                 boost::filesystem::path p (sd);
923                 p /= "ca.self-signed.pem";
924                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
925         }
926
927         {
928                 boost::filesystem::path p (sd);
929                 p /= "intermediate.signed.pem";
930                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
931         }
932
933         {
934                 boost::filesystem::path p (sd);
935                 p /= "leaf.signed.pem";
936                 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
937         }
938
939         boost::filesystem::path signer_key (sd);
940         signer_key /= "leaf.key";
941
942         return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
943 }
944
945 libdcp::Size
946 fit_ratio_within (float ratio, libdcp::Size full_frame)
947 {
948         if (ratio < full_frame.ratio ()) {
949                 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
950         }
951         
952         return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));
953 }