a1ea8f9f16c645436fc830cc9ada4e75c48bf4bb
[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         Pango::init ();
362         dcp::init ();
363
364         Ratio::setup_ratios ();
365         PresetColourConversion::setup_colour_conversion_presets ();
366         VideoContentScale::setup_scales ();
367         DCPContentType::setup_dcp_content_types ();
368         Filter::setup_filters ();
369         CinemaSoundProcessor::setup_cinema_sound_processors ();
370         AudioProcessor::setup_audio_processors ();
371
372         curl_global_init (CURL_GLOBAL_ALL);
373
374         ui_thread = boost::this_thread::get_id ();
375 }
376
377 #ifdef DCPOMATIC_WINDOWS
378 boost::filesystem::path
379 mo_path ()
380 {
381         wchar_t buffer[512];
382         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
383         boost::filesystem::path p (buffer);
384         p = p.parent_path ();
385         p = p.parent_path ();
386         p /= "locale";
387         return p;
388 }
389 #endif
390
391 #ifdef DCPOMATIC_OSX
392 boost::filesystem::path
393 mo_path ()
394 {
395         return "DCP-o-matic 2.app/Contents/Resources";
396 }
397 #endif
398
399 void
400 dcpomatic_setup_gettext_i18n (string lang)
401 {
402 #ifdef DCPOMATIC_LINUX
403         lang += ".UTF8";
404 #endif
405
406         if (!lang.empty ()) {
407                 /* Override our environment language.  Note that the caller must not
408                    free the string passed into putenv().
409                 */
410                 string s = String::compose ("LANGUAGE=%1", lang);
411                 putenv (strdup (s.c_str ()));
412                 s = String::compose ("LANG=%1", lang);
413                 putenv (strdup (s.c_str ()));
414                 s = String::compose ("LC_ALL=%1", lang);
415                 putenv (strdup (s.c_str ()));
416         }
417
418         setlocale (LC_ALL, "");
419         textdomain ("libdcpomatic2");
420
421 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
422         bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
423         bind_textdomain_codeset ("libdcpomatic2", "UTF8");
424 #endif
425
426 #ifdef DCPOMATIC_LINUX
427         bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
428 #endif
429 }
430
431 /** Compute a digest of the first and last `size' bytes of a set of files. */
432 string
433 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
434 {
435         boost::scoped_array<char> buffer (new char[size]);
436         Digester digester;
437
438         /* Head */
439         boost::uintmax_t to_do = size;
440         char* p = buffer.get ();
441         int i = 0;
442         while (i < int64_t (files.size()) && to_do > 0) {
443                 FILE* f = fopen_boost (files[i], "rb");
444                 if (!f) {
445                         throw OpenFileError (files[i].string(), errno, true);
446                 }
447
448                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
449                 checked_fread (p, this_time, f, files[i]);
450                 p += this_time;
451                 to_do -= this_time;
452                 fclose (f);
453
454                 ++i;
455         }
456         digester.add (buffer.get(), size - to_do);
457
458         /* Tail */
459         to_do = size;
460         p = buffer.get ();
461         i = files.size() - 1;
462         while (i >= 0 && to_do > 0) {
463                 FILE* f = fopen_boost (files[i], "rb");
464                 if (!f) {
465                         throw OpenFileError (files[i].string(), errno, true);
466                 }
467
468                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
469                 dcpomatic_fseek (f, -this_time, SEEK_END);
470                 checked_fread (p, this_time, f, files[i]);
471                 p += this_time;
472                 to_do -= this_time;
473                 fclose (f);
474
475                 --i;
476         }
477         digester.add (buffer.get(), size - to_do);
478
479         return digester.get ();
480 }
481
482 /** Round a number up to the nearest multiple of another number.
483  *  @param c Index.
484  *  @param stride Array of numbers to round, indexed by c.
485  *  @param t Multiple to round to.
486  *  @return Rounded number.
487  */
488 int
489 stride_round_up (int c, int const * stride, int t)
490 {
491         int const a = stride[c] + (t - 1);
492         return a - (a % t);
493 }
494
495 /** Trip an assert if the caller is not in the UI thread */
496 void
497 ensure_ui_thread ()
498 {
499         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
500 }
501
502 string
503 audio_channel_name (int c)
504 {
505         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
506
507         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
508         /// enhancement channel (sub-woofer).
509         string const channels[] = {
510                 _("Left"),
511                 _("Right"),
512                 _("Centre"),
513                 _("Lfe (sub)"),
514                 _("Left surround"),
515                 _("Right surround"),
516                 _("Hearing impaired"),
517                 _("Visually impaired"),
518                 _("Left centre"),
519                 _("Right centre"),
520                 _("Left rear surround"),
521                 _("Right rear surround"),
522                 _("D-BOX primary"),
523                 _("D-BOX secondary"),
524                 _("Unused"),
525                 _("Unused")
526         };
527
528         return channels[c];
529 }
530
531 string
532 short_audio_channel_name (int c)
533 {
534         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
535
536         /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
537         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
538         /// VI is the visually-impaired audio track (audio describe).  DBP is the D-BOX
539         /// primary channel and DBS is the D-BOX secondary channel.
540         string const channels[] = {
541                 _("L"),
542                 _("R"),
543                 _("C"),
544                 _("Lfe"),
545                 _("Ls"),
546                 _("Rs"),
547                 _("HI"),
548                 _("VI"),
549                 _("Lc"),
550                 _("Rc"),
551                 _("BsL"),
552                 _("BsR"),
553                 _("DBP"),
554                 _("DBS"),
555                 "",
556                 ""
557         };
558
559         return channels[c];
560 }
561
562
563 bool
564 valid_image_file (boost::filesystem::path f)
565 {
566         if (boost::starts_with (f.leaf().string(), "._")) {
567                 return false;
568         }
569
570         string ext = f.extension().string();
571         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
572         return (
573                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
574                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
575                 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr" ||
576                 ext == ".jpf"
577                 );
578 }
579
580 bool
581 valid_sound_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 (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
590 }
591
592 bool
593 valid_j2k_file (boost::filesystem::path f)
594 {
595         string ext = f.extension().string();
596         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
597         return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
598 }
599
600 string
601 tidy_for_filename (string f)
602 {
603         boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
604         return f;
605 }
606
607 dcp::Size
608 fit_ratio_within (float ratio, dcp::Size full_frame)
609 {
610         if (ratio < full_frame.ratio ()) {
611                 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
612         }
613
614         return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
615 }
616
617 void *
618 wrapped_av_malloc (size_t s)
619 {
620         void* p = av_malloc (s);
621         if (!p) {
622                 throw bad_alloc ();
623         }
624         return p;
625 }
626
627 map<string, string>
628 split_get_request (string url)
629 {
630         enum {
631                 AWAITING_QUESTION_MARK,
632                 KEY,
633                 VALUE
634         } state = AWAITING_QUESTION_MARK;
635
636         map<string, string> r;
637         string k;
638         string v;
639         for (size_t i = 0; i < url.length(); ++i) {
640                 switch (state) {
641                 case AWAITING_QUESTION_MARK:
642                         if (url[i] == '?') {
643                                 state = KEY;
644                         }
645                         break;
646                 case KEY:
647                         if (url[i] == '=') {
648                                 v.clear ();
649                                 state = VALUE;
650                         } else {
651                                 k += url[i];
652                         }
653                         break;
654                 case VALUE:
655                         if (url[i] == '&') {
656                                 r.insert (make_pair (k, v));
657                                 k.clear ();
658                                 state = KEY;
659                         } else {
660                                 v += url[i];
661                         }
662                         break;
663                 }
664         }
665
666         if (state == VALUE) {
667                 r.insert (make_pair (k, v));
668         }
669
670         return r;
671 }
672
673 string
674 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
675 {
676         dcp::NameFormat::Map values;
677         values['t'] = "j2c";
678         values['r'] = raw_convert<string> (reel_index + 1);
679         values['n'] = raw_convert<string> (reel_count);
680         if (summary) {
681                 values['c'] = careful_string_filter (summary.get());
682         }
683         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
684 }
685
686 string
687 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
688 {
689         dcp::NameFormat::Map values;
690         values['t'] = "pcm";
691         values['r'] = raw_convert<string> (reel_index + 1);
692         values['n'] = raw_convert<string> (reel_count);
693         if (summary) {
694                 values['c'] = careful_string_filter (summary.get());
695         }
696         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
697 }
698
699 float
700 relaxed_string_to_float (string s)
701 {
702         try {
703                 boost::algorithm::replace_all (s, ",", ".");
704                 return lexical_cast<float> (s);
705         } catch (bad_lexical_cast) {
706                 boost::algorithm::replace_all (s, ".", ",");
707                 return lexical_cast<float> (s);
708         }
709 }
710
711 string
712 careful_string_filter (string s)
713 {
714         /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
715            There's no apparent list of what really is allowed, so this is a guess.
716            Safety first and all that.
717         */
718
719         string out;
720         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
721         for (size_t i = 0; i < s.size(); ++i) {
722                 if (allowed.find (s[i]) != string::npos) {
723                         out += s[i];
724                 }
725         }
726
727         return out;
728 }
729
730 /** @param mapped List of mapped audio channels from a Film.
731  *  @param channels Total number of channels in the Film.
732  *  @return First: number of non-LFE channels, second: number of LFE channels.
733  */
734 pair<int, int>
735 audio_channel_types (list<int> mapped, int channels)
736 {
737         int non_lfe = 0;
738         int lfe = 0;
739
740         BOOST_FOREACH (int i, mapped) {
741                 if (i >= channels) {
742                         /* This channel is mapped but is not included in the DCP */
743                         continue;
744                 }
745
746                 if (static_cast<dcp::Channel> (i) == dcp::LFE) {
747                         ++lfe;
748                 } else {
749                         ++non_lfe;
750                 }
751         }
752
753         return make_pair (non_lfe, lfe);
754 }
755
756 shared_ptr<AudioBuffers>
757 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
758 {
759         shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
760         mapped->make_silent ();
761
762         for (int i = 0; i < map.input_channels(); ++i) {
763                 for (int j = 0; j < mapped->channels(); ++j) {
764                         if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
765                                 mapped->accumulate_channel (
766                                         input.get(),
767                                         i,
768                                         static_cast<dcp::Channel> (j),
769                                         map.get (i, static_cast<dcp::Channel> (j))
770                                         );
771                         }
772                 }
773         }
774
775         return mapped;
776 }
777
778 Eyes
779 increment_eyes (Eyes e)
780 {
781         if (e == EYES_LEFT) {
782                 return EYES_RIGHT;
783         }
784
785         return EYES_LEFT;
786 }
787
788 void
789 checked_fwrite (void const * ptr, size_t size, FILE* stream, boost::filesystem::path path)
790 {
791         size_t N = fwrite (ptr, 1, size, stream);
792         if (N != size) {
793                 if (ferror(stream)) {
794                         fclose (stream);
795                         throw FileError (String::compose("fwrite error %1", errno), path);
796                 } else {
797                         fclose (stream);
798                         throw FileError ("Unexpected short write", path);
799                 }
800         }
801 }
802
803 void
804 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
805 {
806         size_t N = fread (ptr, 1, size, stream);
807         if (N != size) {
808                 if (ferror(stream)) {
809                         fclose (stream);
810                         throw FileError (String::compose("fread error %1", errno), path);
811                 } else {
812                         fclose (stream);
813                         throw FileError ("Unexpected short read", path);
814                 }
815         }
816 }
817
818 #ifdef DCPOMATIC_VARIANT_SWAROOP
819
820 /* Make up a key from the machine UUID */
821 dcp::Data
822 key_from_uuid ()
823 {
824         dcp::Data key (dcpomatic::crypto_key_length());
825         memset (key.data().get(), 0, key.size());
826         string const magic = command_and_read ("dcpomatic2_uuid");
827         strncpy ((char *) key.data().get(), magic.c_str(), dcpomatic::crypto_key_length());
828         return key;
829 }
830
831 /* swaroop chain file format:
832  *
833  *  0 [int16_t] IV length
834  *  2 [int16_t] cert #1 length, or 0 for none
835  *  4 [int16_t] cert #2 length, or 0 for none
836  *  6 [int16_t] cert #3 length, or 0 for none
837  *  8 [int16_t] cert #4 length, or 0 for none
838  * 10 [int16_t] cert #5 length, or 0 for none
839  * 12 [int16_t] cert #6 length, or 0 for none
840  * 14 [int16_t] cert #7 length, or 0 for none
841  * 16 [int16_t] cert #8 length, or 0 for none
842  * 16 [int16_t] private key length
843  * 20 IV
844  *    cert #1
845  *    cert #2
846  *    cert #3
847  *    cert #4
848  *    cert #5
849  *    cert #6
850  *    cert #7
851  *    cert #8
852  *    private key
853  */
854
855 struct __attribute__ ((packed)) Header_ {
856         int16_t iv_length;
857         int16_t cert_length[8];
858         int16_t private_key_length;
859 };
860
861 typedef struct Header_ Header;
862
863 shared_ptr<dcp::CertificateChain>
864 read_swaroop_chain (boost::filesystem::path path)
865 {
866         dcp::Data data (path);
867         Header* header = (Header *) data.data().get();
868         uint8_t* p = data.data().get() + sizeof(Header);
869
870         dcp::Data iv (p, header->iv_length);
871         p += iv.size();
872
873         shared_ptr<dcp::CertificateChain> cc (new dcp::CertificateChain());
874         for (int i = 0; i < 8; ++i) {
875                 if (header->cert_length[i] == 0) {
876                         break;
877                 }
878                 dcp::Data c(p, header->cert_length[i]);
879                 p += c.size();
880                 cc->add (dcp::Certificate(dcpomatic::decrypt(c, key_from_uuid(), iv)));
881         }
882
883         dcp::Data k (p, header->private_key_length);
884         cc->set_key (dcpomatic::decrypt(k, key_from_uuid(), iv));
885         return cc;
886 }
887
888 void
889 write_swaroop_chain (shared_ptr<const dcp::CertificateChain> chain, boost::filesystem::path output)
890 {
891         cout << "write " << output.string() << "\n";
892
893         scoped_array<uint8_t> buffer (new uint8_t[65536]);
894         Header* header = (Header *) buffer.get();
895         memset (header, 0, sizeof(Header));
896         uint8_t* p = buffer.get() + sizeof(Header);
897
898         dcp::Data iv = dcpomatic::random_iv ();
899         header->iv_length = iv.size ();
900         memcpy (p, iv.data().get(), iv.size());
901         p += iv.size();
902
903         int N = 0;
904         BOOST_FOREACH (dcp::Certificate i, chain->root_to_leaf()) {
905                 dcp::Data e = dcpomatic::encrypt (i.certificate(true), key_from_uuid(), iv);
906                 memcpy (p, e.data().get(), e.size());
907                 p += e.size();
908                 DCPOMATIC_ASSERT (N < 8);
909                 header->cert_length[N] = e.size ();
910                 ++N;
911         }
912
913         dcp::Data k = dcpomatic::encrypt (chain->key().get(), key_from_uuid(), iv);
914         memcpy (p, k.data().get(), k.size());
915         p += k.size();
916         header->private_key_length = k.size ();
917
918         FILE* f = fopen_boost (output, "wb");
919         checked_fwrite (buffer.get(), p - buffer.get(), f, output);
920         fclose (f);
921 }
922
923 #endif