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