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