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