Adapt for changes to libdcp API.
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file src/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include "util.h"
26 #include "exceptions.h"
27 #include "dcp_content_type.h"
28 #include "filter.h"
29 #include "cinema_sound_processor.h"
30 #include "config.h"
31 #include "ratio.h"
32 #include "job.h"
33 #include "cross.h"
34 #include "video_content.h"
35 #include "rect.h"
36 #include "digester.h"
37 #include "audio_processor.h"
38 #include "crypto.h"
39 #include "compose.hpp"
40 #include "audio_buffers.h"
41 #include "string_text.h"
42 #include "font.h"
43 #include "render_text.h"
44 #include "ffmpeg_image_proxy.h"
45 #include "image.h"
46 #include "text_decoder.h"
47 #include "job_manager.h"
48 #include "warnings.h"
49 #include <dcp/decrypted_kdm.h>
50 #include <dcp/locale_convert.h>
51 #include <dcp/util.h>
52 #include <dcp/raw_convert.h>
53 #include <dcp/picture_asset.h>
54 #include <dcp/sound_asset.h>
55 #include <dcp/subtitle_asset.h>
56 #include <dcp/atmos_asset.h>
57 extern "C" {
58 #include <libavfilter/avfilter.h>
59 #include <libavformat/avformat.h>
60 #include <libavcodec/avcodec.h>
61 }
62 #include <curl/curl.h>
63 #include <glib.h>
64 #include <pangomm/init.h>
65 #include <boost/algorithm/string.hpp>
66 #include <boost/range/algorithm/replace_if.hpp>
67 #include <boost/thread.hpp>
68 #include <boost/filesystem.hpp>
69 DCPOMATIC_DISABLE_WARNINGS
70 #include <boost/locale.hpp>
71 DCPOMATIC_ENABLE_WARNINGS
72 #ifdef DCPOMATIC_WINDOWS
73 #include <boost/locale.hpp>
74 #include <dbghelp.h>
75 #endif
76 #include <signal.h>
77 #include <iomanip>
78 #include <iostream>
79 #include <fstream>
80 #include <climits>
81 #include <stdexcept>
82 #ifdef DCPOMATIC_POSIX
83 #include <execinfo.h>
84 #include <cxxabi.h>
85 #endif
86
87 #include "i18n.h"
88
89 using std::string;
90 using std::wstring;
91 using std::setfill;
92 using std::ostream;
93 using std::endl;
94 using std::vector;
95 using std::min;
96 using std::max;
97 using std::map;
98 using std::list;
99 using std::multimap;
100 using std::istream;
101 using std::pair;
102 using std::cout;
103 using std::bad_alloc;
104 using std::set_terminate;
105 using std::make_pair;
106 using boost::shared_ptr;
107 using boost::thread;
108 using boost::optional;
109 using boost::lexical_cast;
110 using boost::bad_lexical_cast;
111 using boost::scoped_array;
112 using dcp::Size;
113 using dcp::raw_convert;
114 using dcp::locale_convert;
115 using namespace dcpomatic;
116
117 /** Path to our executable, required by the stacktrace stuff and filled
118  *  in during App::onInit().
119  */
120 string program_name;
121 bool is_batch_converter = false;
122 static boost::thread::id ui_thread;
123 static boost::filesystem::path backtrace_file;
124
125 /** Convert some number of seconds to a string representation
126  *  in hours, minutes and seconds.
127  *
128  *  @param s Seconds.
129  *  @return String of the form H:M:S (where H is hours, M
130  *  is minutes and S is seconds).
131  */
132 string
133 seconds_to_hms (int s)
134 {
135         int m = s / 60;
136         s -= (m * 60);
137         int h = m / 60;
138         m -= (h * 60);
139
140         char buffer[64];
141         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
142         return buffer;
143 }
144
145 string
146 time_to_hmsf (DCPTime time, Frame rate)
147 {
148         Frame f = time.frames_round (rate);
149         int s = f / rate;
150         f -= (s * rate);
151         int m = s / 60;
152         s -= m * 60;
153         int h = m / 60;
154         m -= h * 60;
155
156         char buffer[64];
157         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d.%d", h, m, s, static_cast<int>(f));
158         return buffer;
159 }
160
161 /** @param s Number of seconds.
162  *  @return String containing an approximate description of s (e.g. "about 2 hours")
163  */
164 string
165 seconds_to_approximate_hms (int s)
166 {
167         int m = s / 60;
168         s -= (m * 60);
169         int h = m / 60;
170         m -= (h * 60);
171
172         string ap;
173
174         bool hours = h > 0;
175         bool minutes = h < 6 && m > 0;
176         bool seconds = h == 0 && m < 10 && s > 0;
177
178         if (m > 30 && !minutes) {
179                 /* round up the hours */
180                 ++h;
181         }
182         if (s > 30 && !seconds) {
183                 /* round up the minutes */
184                 ++m;
185                 if (m == 60) {
186                         m = 0;
187                         minutes = false;
188                         ++h;
189                 }
190         }
191
192         if (hours) {
193                 /// TRANSLATORS: h here is an abbreviation for hours
194                 ap += locale_convert<string>(h) + _("h");
195
196                 if (minutes || seconds) {
197                         ap += N_(" ");
198                 }
199         }
200
201         if (minutes) {
202                 /// TRANSLATORS: m here is an abbreviation for minutes
203                 ap += locale_convert<string>(m) + _("m");
204
205                 if (seconds) {
206                         ap += N_(" ");
207                 }
208         }
209
210         if (seconds) {
211                 /* Seconds */
212                 /// TRANSLATORS: s here is an abbreviation for seconds
213                 ap += locale_convert<string>(s) + _("s");
214         }
215
216         return ap;
217 }
218
219 double
220 seconds (struct timeval t)
221 {
222         return t.tv_sec + (double (t.tv_usec) / 1e6);
223 }
224
225 #ifdef DCPOMATIC_WINDOWS
226
227 /** Resolve symbol name and source location given the path to the executable */
228 int
229 addr2line (void const * const addr)
230 {
231         char addr2line_cmd[512] = { 0 };
232         sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
233         return system(addr2line_cmd);
234 }
235
236 DCPOMATIC_DISABLE_WARNINGS
237 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
238  *  (NOT C++ exceptions!).  We write a backtrace to backtrace_file by dark means.
239  *  Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
240  */
241 LONG WINAPI
242 exception_handler(struct _EXCEPTION_POINTERS * info)
243 {
244         FILE* f = fopen_boost (backtrace_file, "w");
245         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
246         fclose(f);
247
248         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
249                 CONTEXT* context = info->ContextRecord;
250                 SymInitialize (GetCurrentProcess (), 0, true);
251
252                 STACKFRAME frame = { 0 };
253
254                 /* setup initial stack frame */
255 #if _WIN64
256                 frame.AddrPC.Offset    = context->Rip;
257                 frame.AddrStack.Offset = context->Rsp;
258                 frame.AddrFrame.Offset = context->Rbp;
259 #else
260                 frame.AddrPC.Offset    = context->Eip;
261                 frame.AddrStack.Offset = context->Esp;
262                 frame.AddrFrame.Offset = context->Ebp;
263 #endif
264                 frame.AddrPC.Mode      = AddrModeFlat;
265                 frame.AddrStack.Mode   = AddrModeFlat;
266                 frame.AddrFrame.Mode   = AddrModeFlat;
267
268                 while (
269                         StackWalk (
270                                 IMAGE_FILE_MACHINE_I386,
271                                 GetCurrentProcess (),
272                                 GetCurrentThread (),
273                                 &frame,
274                                 context,
275                                 0,
276                                 SymFunctionTableAccess,
277                                 SymGetModuleBase,
278                                 0
279                                 )
280                         ) {
281                         addr2line((void *) frame.AddrPC.Offset);
282                 }
283         } else {
284 #ifdef _WIN64
285                 addr2line ((void *) info->ContextRecord->Rip);
286 #else
287                 addr2line ((void *) info->ContextRecord->Eip);
288 #endif
289         }
290
291         return EXCEPTION_CONTINUE_SEARCH;
292 }
293 DCPOMATIC_ENABLE_WARNINGS
294 #endif
295
296 void
297 set_backtrace_file (boost::filesystem::path p)
298 {
299         backtrace_file = p;
300 }
301
302 /** This is called when there is an unhandled exception.  Any
303  *  backtrace in this function is useless on Windows as the stack has
304  *  already been unwound from the throw; we have the gdb wrap hack to
305  *  cope with that.
306  */
307 void
308 terminate ()
309 {
310         try {
311                 static bool tried_throw = false;
312                 // try once to re-throw currently active exception
313                 if (!tried_throw) {
314                         tried_throw = true;
315                         throw;
316                 }
317         }
318         catch (const std::exception &e) {
319                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
320                           << e.what() << std::endl;
321         }
322         catch (...) {
323                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
324                           << std::endl;
325         }
326
327         abort();
328 }
329
330 void
331 dcpomatic_setup_path_encoding ()
332 {
333 #ifdef DCPOMATIC_WINDOWS
334         /* Dark voodoo which, I think, gets boost::filesystem::path to
335            correctly convert UTF-8 strings to paths, and also paths
336            back to UTF-8 strings (on path::string()).
337
338            After this, constructing boost::filesystem::paths from strings
339            converts from UTF-8 to UTF-16 inside the path.  Then
340            path::string().c_str() gives UTF-8 and
341            path::c_str()          gives UTF-16.
342
343            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
344            so things are much simpler.
345         */
346         std::locale::global (boost::locale::generator().generate (""));
347         boost::filesystem::path::imbue (std::locale ());
348 #endif
349 }
350
351 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
352  *  Must be called from the UI thread, if there is one.
353  */
354 void
355 dcpomatic_setup ()
356 {
357 #ifdef DCPOMATIC_WINDOWS
358         boost::filesystem::path p = g_get_user_config_dir ();
359         p /= "backtrace.txt";
360         set_backtrace_file (p);
361         SetUnhandledExceptionFilter(exception_handler);
362 #endif
363
364 DCPOMATIC_DISABLE_WARNINGS
365         av_register_all ();
366         avfilter_register_all ();
367 DCPOMATIC_ENABLE_WARNINGS
368
369 #ifdef DCPOMATIC_OSX
370         /* Add our library directory to the libltdl search path so that
371            xmlsec can find xmlsec1-openssl.
372         */
373         boost::filesystem::path lib = directory_containing_executable().parent_path();
374         lib /= "Frameworks";
375         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
376 #endif
377
378         set_terminate (terminate);
379
380 #ifdef DCPOMATIC_WINDOWS
381         putenv ("PANGOCAIRO_BACKEND=fontconfig");
382         putenv (String::compose("FONTCONFIG_PATH=%1", resources_path().string()).c_str());
383 #endif
384
385 #ifdef DCPOMATIC_OSX
386         setenv ("PANGOCAIRO_BACKEND", "fontconfig", 1);
387         setenv ("FONTCONFIG_PATH", resources_path().string().c_str(), 1);
388 #endif
389
390         Pango::init ();
391         dcp::init ();
392
393 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
394         /* Render something to fontconfig to create its cache */
395         list<StringText> subs;
396         dcp::SubtitleString ss(
397                 optional<string>(), false, false, false, dcp::Colour(), 42, 1, dcp::Time(), dcp::Time(), 0, dcp::HALIGN_CENTER, 0, dcp::VALIGN_CENTER, dcp::DIRECTION_LTR,
398                 "Hello dolly", dcp::NONE, dcp::Colour(), dcp::Time(), dcp::Time()
399                 );
400         subs.push_back (StringText(ss, 0));
401         render_text (subs, list<shared_ptr<Font> >(), dcp::Size(640, 480), DCPTime(), 24);
402 #endif
403
404         Ratio::setup_ratios ();
405         PresetColourConversion::setup_colour_conversion_presets ();
406         DCPContentType::setup_dcp_content_types ();
407         Filter::setup_filters ();
408         CinemaSoundProcessor::setup_cinema_sound_processors ();
409         AudioProcessor::setup_audio_processors ();
410
411         curl_global_init (CURL_GLOBAL_ALL);
412
413         ui_thread = boost::this_thread::get_id ();
414 }
415
416 #ifdef DCPOMATIC_WINDOWS
417 boost::filesystem::path
418 mo_path ()
419 {
420         wchar_t buffer[512];
421         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
422         boost::filesystem::path p (buffer);
423         p = p.parent_path ();
424         p = p.parent_path ();
425         p /= "locale";
426         return p;
427 }
428 #endif
429
430 #ifdef DCPOMATIC_OSX
431 boost::filesystem::path
432 mo_path ()
433 {
434         return "DCP-o-matic 2.app/Contents/Resources";
435 }
436 #endif
437
438 void
439 dcpomatic_setup_gettext_i18n (string lang)
440 {
441 #ifdef DCPOMATIC_LINUX
442         lang += ".UTF8";
443 #endif
444
445         if (!lang.empty ()) {
446                 /* Override our environment language.  Note that the caller must not
447                    free the string passed into putenv().
448                 */
449                 string s = String::compose ("LANGUAGE=%1", lang);
450                 putenv (strdup (s.c_str ()));
451                 s = String::compose ("LANG=%1", lang);
452                 putenv (strdup (s.c_str ()));
453                 s = String::compose ("LC_ALL=%1", lang);
454                 putenv (strdup (s.c_str ()));
455         }
456
457         setlocale (LC_ALL, "");
458         textdomain ("libdcpomatic2");
459
460 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
461         bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
462         bind_textdomain_codeset ("libdcpomatic2", "UTF8");
463 #endif
464
465 #ifdef DCPOMATIC_LINUX
466         bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
467 #endif
468 }
469
470 /** Compute a digest of the first and last `size' bytes of a set of files. */
471 string
472 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
473 {
474         boost::scoped_array<char> buffer (new char[size]);
475         Digester digester;
476
477         /* Head */
478         boost::uintmax_t to_do = size;
479         char* p = buffer.get ();
480         int i = 0;
481         while (i < int64_t (files.size()) && to_do > 0) {
482                 FILE* f = fopen_boost (files[i], "rb");
483                 if (!f) {
484                         throw OpenFileError (files[i].string(), errno, OpenFileError::READ);
485                 }
486
487                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
488                 checked_fread (p, this_time, f, files[i]);
489                 p += this_time;
490                 to_do -= this_time;
491                 fclose (f);
492
493                 ++i;
494         }
495         digester.add (buffer.get(), size - to_do);
496
497         /* Tail */
498         to_do = size;
499         p = buffer.get ();
500         i = files.size() - 1;
501         while (i >= 0 && to_do > 0) {
502                 FILE* f = fopen_boost (files[i], "rb");
503                 if (!f) {
504                         throw OpenFileError (files[i].string(), errno, OpenFileError::READ);
505                 }
506
507                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
508                 dcpomatic_fseek (f, -this_time, SEEK_END);
509                 checked_fread (p, this_time, f, files[i]);
510                 p += this_time;
511                 to_do -= this_time;
512                 fclose (f);
513
514                 --i;
515         }
516         digester.add (buffer.get(), size - to_do);
517
518         return digester.get ();
519 }
520
521 /** Round a number up to the nearest multiple of another number.
522  *  @param c Index.
523  *  @param stride Array of numbers to round, indexed by c.
524  *  @param t Multiple to round to.
525  *  @return Rounded number.
526  */
527 int
528 stride_round_up (int c, int const * stride, int t)
529 {
530         int const a = stride[c] + (t - 1);
531         return a - (a % t);
532 }
533
534 /** Trip an assert if the caller is not in the UI thread */
535 void
536 ensure_ui_thread ()
537 {
538         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
539 }
540
541 string
542 audio_channel_name (int c)
543 {
544         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
545
546         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
547         /// enhancement channel (sub-woofer).
548         string const channels[] = {
549                 _("Left"),
550                 _("Right"),
551                 _("Centre"),
552                 _("Lfe (sub)"),
553                 _("Left surround"),
554                 _("Right surround"),
555                 _("Hearing impaired"),
556                 _("Visually impaired"),
557                 _("Left centre"),
558                 _("Right centre"),
559                 _("Left rear surround"),
560                 _("Right rear surround"),
561                 _("D-BOX primary"),
562                 _("D-BOX secondary"),
563                 _("Unused"),
564                 _("Unused")
565         };
566
567         return channels[c];
568 }
569
570 string
571 short_audio_channel_name (int c)
572 {
573         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
574
575         /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
576         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
577         /// VI is the visually-impaired audio track (audio describe).  DBP is the D-BOX
578         /// primary channel and DBS is the D-BOX secondary channel.
579         string const channels[] = {
580                 _("L"),
581                 _("R"),
582                 _("C"),
583                 _("Lfe"),
584                 _("Ls"),
585                 _("Rs"),
586                 _("HI"),
587                 _("VI"),
588                 _("Lc"),
589                 _("Rc"),
590                 _("BsL"),
591                 _("BsR"),
592                 _("DBP"),
593                 _("DBS"),
594                 "",
595                 ""
596         };
597
598         return channels[c];
599 }
600
601
602 bool
603 valid_image_file (boost::filesystem::path f)
604 {
605         if (boost::starts_with (f.leaf().string(), "._")) {
606                 return false;
607         }
608
609         string ext = f.extension().string();
610         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
611         return (
612                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
613                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
614                 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr" ||
615                 ext == ".jpf"
616                 );
617 }
618
619 bool
620 valid_sound_file (boost::filesystem::path f)
621 {
622         if (boost::starts_with (f.leaf().string(), "._")) {
623                 return false;
624         }
625
626         string ext = f.extension().string();
627         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
628         return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
629 }
630
631 bool
632 valid_j2k_file (boost::filesystem::path f)
633 {
634         string ext = f.extension().string();
635         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
636         return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
637 }
638
639 string
640 tidy_for_filename (string f)
641 {
642         boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
643         return f;
644 }
645
646 dcp::Size
647 fit_ratio_within (float ratio, dcp::Size full_frame)
648 {
649         if (ratio < full_frame.ratio ()) {
650                 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
651         }
652
653         return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
654 }
655
656 void *
657 wrapped_av_malloc (size_t s)
658 {
659         void* p = av_malloc (s);
660         if (!p) {
661                 throw bad_alloc ();
662         }
663         return p;
664 }
665
666 map<string, string>
667 split_get_request (string url)
668 {
669         enum {
670                 AWAITING_QUESTION_MARK,
671                 KEY,
672                 VALUE
673         } state = AWAITING_QUESTION_MARK;
674
675         map<string, string> r;
676         string k;
677         string v;
678         for (size_t i = 0; i < url.length(); ++i) {
679                 switch (state) {
680                 case AWAITING_QUESTION_MARK:
681                         if (url[i] == '?') {
682                                 state = KEY;
683                         }
684                         break;
685                 case KEY:
686                         if (url[i] == '=') {
687                                 v.clear ();
688                                 state = VALUE;
689                         } else {
690                                 k += url[i];
691                         }
692                         break;
693                 case VALUE:
694                         if (url[i] == '&') {
695                                 r.insert (make_pair (k, v));
696                                 k.clear ();
697                                 state = KEY;
698                         } else {
699                                 v += url[i];
700                         }
701                         break;
702                 }
703         }
704
705         if (state == VALUE) {
706                 r.insert (make_pair (k, v));
707         }
708
709         return r;
710 }
711
712 string
713 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
714 {
715         dcp::NameFormat::Map values;
716         values['t'] = "j2c";
717         values['r'] = raw_convert<string> (reel_index + 1);
718         values['n'] = raw_convert<string> (reel_count);
719         if (summary) {
720                 values['c'] = careful_string_filter (summary.get());
721         }
722         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
723 }
724
725 string
726 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
727 {
728         dcp::NameFormat::Map values;
729         values['t'] = "pcm";
730         values['r'] = raw_convert<string> (reel_index + 1);
731         values['n'] = raw_convert<string> (reel_count);
732         if (summary) {
733                 values['c'] = careful_string_filter (summary.get());
734         }
735         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
736 }
737
738
739 string
740 atmos_asset_filename (shared_ptr<dcp::AtmosAsset> asset, int reel_index, int reel_count, optional<string> summary)
741 {
742         dcp::NameFormat::Map values;
743         values['t'] = "atmos";
744         values['r'] = raw_convert<string> (reel_index + 1);
745         values['n'] = raw_convert<string> (reel_count);
746         if (summary) {
747                 values['c'] = careful_string_filter (summary.get());
748         }
749         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
750 }
751
752
753 float
754 relaxed_string_to_float (string s)
755 {
756         try {
757                 boost::algorithm::replace_all (s, ",", ".");
758                 return lexical_cast<float> (s);
759         } catch (bad_lexical_cast &) {
760                 boost::algorithm::replace_all (s, ".", ",");
761                 return lexical_cast<float> (s);
762         }
763 }
764
765 string
766 careful_string_filter (string s)
767 {
768         /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
769            There's no apparent list of what really is allowed, so this is a guess.
770            Safety first and all that.
771         */
772
773         wstring ws = boost::locale::conv::utf_to_utf<wchar_t>(s);
774
775         string out;
776         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
777         for (size_t i = 0; i < ws.size(); ++i) {
778
779                 wchar_t c = ws[i];
780
781                 /* Remove some accents */
782                 if (wstring(L"áàâ").find(c) != string::npos) {
783                         c = 'a';
784                 }
785                 if (wstring(L"éèêë").find(c) != string::npos) {
786                         c = 'e';
787                 }
788                 if (wstring(L"ö").find(c) != string::npos) {
789                         c = 'o';
790                 }
791                 if (wstring(L"ü").find(c) != string::npos) {
792                         c = 'u';
793                 }
794
795                 if (allowed.find(c) != string::npos) {
796                         out += c;
797                 }
798         }
799
800         return boost::locale::conv::utf_to_utf<char>(out);
801 }
802
803 /** @param mapped List of mapped audio channels from a Film.
804  *  @param channels Total number of channels in the Film.
805  *  @return First: number of non-LFE soundtrack channels (L/R/C/Ls/Rs/Lc/Rc/Bsl/Bsr), second: number of LFE channels.
806  */
807 pair<int, int>
808 audio_channel_types (list<int> mapped, int channels)
809 {
810         int non_lfe = 0;
811         int lfe = 0;
812
813         BOOST_FOREACH (int i, mapped) {
814                 if (i >= channels) {
815                         /* This channel is mapped but is not included in the DCP */
816                         continue;
817                 }
818
819                 switch (static_cast<dcp::Channel>(i)) {
820                 case dcp::LFE:
821                         ++lfe;
822                         break;
823                 case dcp::LEFT:
824                 case dcp::RIGHT:
825                 case dcp::CENTRE:
826                 case dcp::LS:
827                 case dcp::RS:
828                 case dcp::LC:
829                 case dcp::RC:
830                 case dcp::BSL:
831                 case dcp::BSR:
832                         ++non_lfe;
833                         break;
834                 case dcp::HI:
835                 case dcp::VI:
836                 case dcp::SYNC_SIGNAL:
837                 case dcp::SIGN_LANGUAGE:
838                 case dcp::UNUSED:
839                 case dcp::CHANNEL_COUNT:
840                         break;
841                 }
842         }
843
844         return make_pair (non_lfe, lfe);
845 }
846
847 shared_ptr<AudioBuffers>
848 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
849 {
850         shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
851         mapped->make_silent ();
852
853         int to_do = min (map.input_channels(), input->channels());
854
855         for (int i = 0; i < to_do; ++i) {
856                 for (int j = 0; j < mapped->channels(); ++j) {
857                         if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
858                                 mapped->accumulate_channel (
859                                         input.get(),
860                                         i,
861                                         static_cast<dcp::Channel> (j),
862                                         map.get (i, static_cast<dcp::Channel> (j))
863                                         );
864                         }
865                 }
866         }
867
868         return mapped;
869 }
870
871 Eyes
872 increment_eyes (Eyes e)
873 {
874         if (e == EYES_LEFT) {
875                 return EYES_RIGHT;
876         }
877
878         return EYES_LEFT;
879 }
880
881 void
882 checked_fwrite (void const * ptr, size_t size, FILE* stream, boost::filesystem::path path)
883 {
884         size_t N = fwrite (ptr, 1, size, stream);
885         if (N != size) {
886                 if (ferror(stream)) {
887                         fclose (stream);
888                         throw FileError (String::compose("fwrite error %1", errno), path);
889                 } else {
890                         fclose (stream);
891                         throw FileError ("Unexpected short write", path);
892                 }
893         }
894 }
895
896 void
897 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
898 {
899         size_t N = fread (ptr, 1, size, stream);
900         if (N != size) {
901                 if (ferror(stream)) {
902                         fclose (stream);
903                         throw FileError (String::compose("fread error %1", errno), path);
904                 } else {
905                         fclose (stream);
906                         throw FileError ("Unexpected short read", path);
907                 }
908         }
909 }
910
911 size_t
912 utf8_strlen (string s)
913 {
914         size_t const len = s.length ();
915         int N = 0;
916         for (size_t i = 0; i < len; ++i) {
917                 unsigned char c = s[i];
918                 if ((c & 0xe0) == 0xc0) {
919                         ++i;
920                 } else if ((c & 0xf0) == 0xe0) {
921                         i += 2;
922                 } else if ((c & 0xf8) == 0xf0) {
923                         i += 3;
924                 }
925                 ++N;
926         }
927         return N;
928 }
929
930 string
931 day_of_week_to_string (boost::gregorian::greg_weekday d)
932 {
933         switch (d.as_enum()) {
934         case boost::date_time::Sunday:
935                 return _("Sunday");
936         case boost::date_time::Monday:
937                 return _("Monday");
938         case boost::date_time::Tuesday:
939                 return _("Tuesday");
940         case boost::date_time::Wednesday:
941                 return _("Wednesday");
942         case boost::date_time::Thursday:
943                 return _("Thursday");
944         case boost::date_time::Friday:
945                 return _("Friday");
946         case boost::date_time::Saturday:
947                 return _("Saturday");
948         }
949
950         return d.as_long_string ();
951 }
952
953 /** @param size Size of picture that the subtitle will be overlaid onto */
954 void
955 emit_subtitle_image (ContentTimePeriod period, dcp::SubtitleImage sub, dcp::Size size, shared_ptr<TextDecoder> decoder)
956 {
957         /* XXX: this is rather inefficient; decoding the image just to get its size */
958         FFmpegImageProxy proxy (sub.png_image());
959         shared_ptr<Image> image = proxy.image().image;
960         /* set up rect with height and width */
961         dcpomatic::Rect<double> rect(0, 0, image->size().width / double(size.width), image->size().height / double(size.height));
962
963         /* add in position */
964
965         switch (sub.h_align()) {
966         case dcp::HALIGN_LEFT:
967                 rect.x += sub.h_position();
968                 break;
969         case dcp::HALIGN_CENTER:
970                 rect.x += 0.5 + sub.h_position() - rect.width / 2;
971                 break;
972         case dcp::HALIGN_RIGHT:
973                 rect.x += 1 - sub.h_position() - rect.width;
974                 break;
975         }
976
977         switch (sub.v_align()) {
978         case dcp::VALIGN_TOP:
979                 rect.y += sub.v_position();
980                 break;
981         case dcp::VALIGN_CENTER:
982                 rect.y += 0.5 + sub.v_position() - rect.height / 2;
983                 break;
984         case dcp::VALIGN_BOTTOM:
985                 rect.y += 1 - sub.v_position() - rect.height;
986                 break;
987         }
988
989         decoder->emit_bitmap (period, image, rect);
990 }
991
992 bool
993 show_jobs_on_console (bool progress)
994 {
995         bool first = true;
996         bool error = false;
997         while (true) {
998
999                 dcpomatic_sleep_seconds (5);
1000
1001                 list<shared_ptr<Job> > jobs = JobManager::instance()->get();
1002
1003                 if (!first && progress) {
1004                         for (size_t i = 0; i < jobs.size(); ++i) {
1005                                 cout << "\033[1A\033[2K";
1006                         }
1007                         cout.flush ();
1008                 }
1009
1010                 first = false;
1011
1012                 BOOST_FOREACH (shared_ptr<Job> i, jobs) {
1013                         if (progress) {
1014                                 cout << i->name();
1015                                 if (!i->sub_name().empty()) {
1016                                         cout << "; " << i->sub_name();
1017                                 }
1018                                 cout << ": ";
1019
1020                                 if (i->progress ()) {
1021                                         cout << i->status() << "                            \n";
1022                                 } else {
1023                                         cout << ": Running           \n";
1024                                 }
1025                         }
1026
1027                         if (!progress && i->finished_in_error()) {
1028                                 /* We won't see this error if we haven't been showing progress,
1029                                    so show it now.
1030                                 */
1031                                 cout << i->status() << "\n";
1032                         }
1033
1034                         if (i->finished_in_error()) {
1035                                 error = true;
1036                         }
1037                 }
1038
1039                 if (!JobManager::instance()->work_to_do()) {
1040                         break;
1041                 }
1042         }
1043
1044         return error;
1045 }
1046
1047 /** XXX: could use mmap? */
1048 void
1049 copy_in_bits (boost::filesystem::path from, boost::filesystem::path to, boost::function<void (float)> progress)
1050 {
1051         FILE* f = fopen_boost (from, "rb");
1052         if (!f) {
1053                 throw OpenFileError (from, errno, OpenFileError::READ);
1054         }
1055         FILE* t = fopen_boost (to, "wb");
1056         if (!t) {
1057                 fclose (f);
1058                 throw OpenFileError (to, errno, OpenFileError::WRITE);
1059         }
1060
1061         /* on the order of a second's worth of copying */
1062         boost::uintmax_t const chunk = 20 * 1024 * 1024;
1063
1064         uint8_t* buffer = static_cast<uint8_t*> (malloc(chunk));
1065         if (!buffer) {
1066                 throw std::bad_alloc ();
1067         }
1068
1069         boost::uintmax_t const total = boost::filesystem::file_size (from);
1070         boost::uintmax_t remaining = total;
1071
1072         while (remaining) {
1073                 boost::uintmax_t this_time = min (chunk, remaining);
1074                 size_t N = fread (buffer, 1, chunk, f);
1075                 if (N < this_time) {
1076                         fclose (f);
1077                         fclose (t);
1078                         free (buffer);
1079                         throw ReadFileError (from, errno);
1080                 }
1081
1082                 N = fwrite (buffer, 1, this_time, t);
1083                 if (N < this_time) {
1084                         fclose (f);
1085                         fclose (t);
1086                         free (buffer);
1087                         throw WriteFileError (to, errno);
1088                 }
1089
1090                 progress (1 - float(remaining) / total);
1091                 remaining -= this_time;
1092         }
1093
1094         fclose (f);
1095         fclose (t);
1096         free (buffer);
1097 }
1098
1099 #ifdef DCPOMATIC_VARIANT_SWAROOP
1100
1101 /* Make up a key from the machine UUID */
1102 dcp::Data
1103 key_from_uuid ()
1104 {
1105         dcp::Data key (dcpomatic::crypto_key_length());
1106         memset (key.data().get(), 0, key.size());
1107         string const magic = command_and_read ("dcpomatic2_uuid");
1108         strncpy ((char *) key.data().get(), magic.c_str(), dcpomatic::crypto_key_length());
1109         return key;
1110 }
1111
1112 /* swaroop chain file format:
1113  *
1114  *  0 [int16_t] IV length
1115  *  2 [int16_t] cert #1 length, or 0 for none
1116  *  4 [int16_t] cert #2 length, or 0 for none
1117  *  6 [int16_t] cert #3 length, or 0 for none
1118  *  8 [int16_t] cert #4 length, or 0 for none
1119  * 10 [int16_t] cert #5 length, or 0 for none
1120  * 12 [int16_t] cert #6 length, or 0 for none
1121  * 14 [int16_t] cert #7 length, or 0 for none
1122  * 16 [int16_t] cert #8 length, or 0 for none
1123  * 16 [int16_t] private key length
1124  * 20 IV
1125  *    cert #1
1126  *    cert #2
1127  *    cert #3
1128  *    cert #4
1129  *    cert #5
1130  *    cert #6
1131  *    cert #7
1132  *    cert #8
1133  *    private key
1134  */
1135
1136 struct __attribute__ ((packed)) Header_ {
1137         int16_t iv_length;
1138         int16_t cert_length[8];
1139         int16_t private_key_length;
1140 };
1141
1142 typedef struct Header_ Header;
1143
1144 shared_ptr<dcp::CertificateChain>
1145 read_swaroop_chain (boost::filesystem::path path)
1146 {
1147         dcp::Data data (path);
1148         Header* header = (Header *) data.data().get();
1149         uint8_t* p = data.data().get() + sizeof(Header);
1150
1151         dcp::Data iv (p, header->iv_length);
1152         p += iv.size();
1153
1154         shared_ptr<dcp::CertificateChain> cc (new dcp::CertificateChain());
1155         for (int i = 0; i < 8; ++i) {
1156                 if (header->cert_length[i] == 0) {
1157                         break;
1158                 }
1159                 dcp::Data c(p, header->cert_length[i]);
1160                 p += c.size();
1161                 cc->add (dcp::Certificate(dcpomatic::decrypt(c, key_from_uuid(), iv)));
1162         }
1163
1164         dcp::Data k (p, header->private_key_length);
1165         cc->set_key (dcpomatic::decrypt(k, key_from_uuid(), iv));
1166         return cc;
1167 }
1168
1169 void
1170 write_swaroop_chain (shared_ptr<const dcp::CertificateChain> chain, boost::filesystem::path output)
1171 {
1172         scoped_array<uint8_t> buffer (new uint8_t[65536]);
1173         Header* header = (Header *) buffer.get();
1174         memset (header, 0, sizeof(Header));
1175         uint8_t* p = buffer.get() + sizeof(Header);
1176
1177         dcp::Data iv = dcpomatic::random_iv ();
1178         header->iv_length = iv.size ();
1179         memcpy (p, iv.data().get(), iv.size());
1180         p += iv.size();
1181
1182         int N = 0;
1183         BOOST_FOREACH (dcp::Certificate i, chain->root_to_leaf()) {
1184                 dcp::Data e = dcpomatic::encrypt (i.certificate(true), key_from_uuid(), iv);
1185                 memcpy (p, e.data().get(), e.size());
1186                 p += e.size();
1187                 DCPOMATIC_ASSERT (N < 8);
1188                 header->cert_length[N] = e.size ();
1189                 ++N;
1190         }
1191
1192         dcp::Data k = dcpomatic::encrypt (chain->key().get(), key_from_uuid(), iv);
1193         memcpy (p, k.data().get(), k.size());
1194         p += k.size();
1195         header->private_key_length = k.size ();
1196
1197         FILE* f = fopen_boost (output, "wb");
1198         checked_fwrite (buffer.get(), p - buffer.get(), f, output);
1199         fclose (f);
1200 }
1201
1202 #endif
1203
1204 double
1205 db_to_linear (double db)
1206 {
1207         return pow(10, db / 20);
1208 }
1209
1210 double
1211 linear_to_db (double linear)
1212 {
1213         return 20 * log10(linear);
1214 }
1215
1216
1217 dcp::Size
1218 scale_for_display (dcp::Size s, dcp::Size display_container, dcp::Size film_container)
1219 {
1220         /* Now scale it down if the display container is smaller than the film container */
1221         if (display_container != film_container) {
1222                 float const scale = min (
1223                         float (display_container.width) / film_container.width,
1224                         float (display_container.height) / film_container.height
1225                         );
1226
1227                 s.width = lrintf (s.width * scale);
1228                 s.height = lrintf (s.height * scale);
1229         }
1230
1231         return s;
1232 }
1233
1234
1235 dcp::DecryptedKDM
1236 decrypt_kdm_with_helpful_error (dcp::EncryptedKDM kdm)
1237 {
1238         try {
1239                 return dcp::DecryptedKDM (kdm, Config::instance()->decryption_chain()->key().get());
1240         } catch (dcp::KDMDecryptionError& e) {
1241                 /* Try to flesh out the error a bit */
1242                 string const kdm_subject_name = kdm.recipient_x509_subject_name();
1243                 bool on_chain = false;
1244                 shared_ptr<const dcp::CertificateChain> dc = Config::instance()->decryption_chain();
1245                 BOOST_FOREACH (dcp::Certificate i, dc->root_to_leaf()) {
1246                         if (i.subject() == kdm_subject_name) {
1247                                 on_chain = true;
1248                         }
1249                 }
1250                 if (!on_chain) {
1251                         throw KDMError (_("This KDM was not made for DCP-o-matic's decryption certificate."), e.what());
1252                 } else if (on_chain && kdm_subject_name != dc->leaf().subject()) {
1253                         throw KDMError (_("This KDM was made for DCP-o-matic but not for its leaf certificate."), e.what());
1254                 } else {
1255                         throw;
1256                 }
1257         }
1258 }
1259
1260
1261 boost::filesystem::path
1262 default_font_file ()
1263 {
1264         boost::filesystem::path liberation_normal;
1265         try {
1266                 liberation_normal = resources_path() / "LiberationSans-Regular.ttf";
1267                 if (!boost::filesystem::exists (liberation_normal)) {
1268                         /* Hack for unit tests */
1269                         liberation_normal = resources_path() / "fonts" / "LiberationSans-Regular.ttf";
1270                 }
1271         } catch (boost::filesystem::filesystem_error& e) {
1272
1273         }
1274
1275         if (!boost::filesystem::exists(liberation_normal)) {
1276                 liberation_normal = "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf";
1277         }
1278
1279         return liberation_normal;
1280 }