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