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