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