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