2 Copyright (C) 2012-2020 Carl Hetherington <cth@carlh.net>
4 This file is part of DCP-o-matic.
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.
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.
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/>.
21 /** @file src/lib/util.cc
22 * @brief Some utility functions and classes.
26 #include "exceptions.h"
27 #include "dcp_content_type.h"
29 #include "cinema_sound_processor.h"
34 #include "video_content.h"
37 #include "audio_processor.h"
39 #include "compose.hpp"
40 #include "audio_buffers.h"
41 #include "string_text.h"
43 #include "render_text.h"
44 #include "ffmpeg_image_proxy.h"
46 #include "text_decoder.h"
47 #include "job_manager.h"
48 #include <dcp/locale_convert.h>
50 #include <dcp/raw_convert.h>
51 #include <dcp/picture_asset.h>
52 #include <dcp/sound_asset.h>
53 #include <dcp/subtitle_asset.h>
55 #include <libavfilter/avfilter.h>
56 #include <libavformat/avformat.h>
57 #include <libavcodec/avcodec.h>
59 #include <curl/curl.h>
61 #include <pangomm/init.h>
62 #include <boost/algorithm/string.hpp>
63 #include <boost/range/algorithm/replace_if.hpp>
64 #include <boost/thread.hpp>
65 #include <boost/filesystem.hpp>
66 #include <boost/locale.hpp>
67 #ifdef DCPOMATIC_WINDOWS
68 #include <boost/locale.hpp>
77 #ifdef DCPOMATIC_POSIX
99 using std::set_terminate;
100 using std::make_pair;
101 using boost::shared_ptr;
103 using boost::optional;
104 using boost::lexical_cast;
105 using boost::bad_lexical_cast;
106 using boost::scoped_array;
108 using dcp::raw_convert;
109 using dcp::locale_convert;
110 using namespace dcpomatic;
112 /** Path to our executable, required by the stacktrace stuff and filled
113 * in during App::onInit().
116 bool is_batch_converter = false;
117 static boost::thread::id ui_thread;
118 static boost::filesystem::path backtrace_file;
120 /** Convert some number of seconds to a string representation
121 * in hours, minutes and seconds.
124 * @return String of the form H:M:S (where H is hours, M
125 * is minutes and S is seconds).
128 seconds_to_hms (int s)
136 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
141 time_to_hmsf (DCPTime time, Frame rate)
143 Frame f = time.frames_round (rate);
152 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d.%d", h, m, s, static_cast<int>(f));
156 /** @param s Number of seconds.
157 * @return String containing an approximate description of s (e.g. "about 2 hours")
160 seconds_to_approximate_hms (int s)
170 bool minutes = h < 6 && m > 0;
171 bool seconds = h == 0 && m < 10 && s > 0;
173 if (m > 30 && !minutes) {
174 /* round up the hours */
177 if (s > 30 && !seconds) {
178 /* round up the minutes */
188 /// TRANSLATORS: h here is an abbreviation for hours
189 ap += locale_convert<string>(h) + _("h");
191 if (minutes || seconds) {
197 /// TRANSLATORS: m here is an abbreviation for minutes
198 ap += locale_convert<string>(m) + _("m");
207 /// TRANSLATORS: s here is an abbreviation for seconds
208 ap += locale_convert<string>(s) + _("s");
215 seconds (struct timeval t)
217 return t.tv_sec + (double (t.tv_usec) / 1e6);
220 #ifdef DCPOMATIC_WINDOWS
222 /** Resolve symbol name and source location given the path to the executable */
224 addr2line (void const * const addr)
226 char addr2line_cmd[512] = { 0 };
227 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
228 return system(addr2line_cmd);
231 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
232 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
233 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
236 exception_handler(struct _EXCEPTION_POINTERS * info)
238 FILE* f = fopen_boost (backtrace_file, "w");
239 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
242 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
243 CONTEXT* context = info->ContextRecord;
244 SymInitialize (GetCurrentProcess (), 0, true);
246 STACKFRAME frame = { 0 };
248 /* setup initial stack frame */
250 frame.AddrPC.Offset = context->Rip;
251 frame.AddrStack.Offset = context->Rsp;
252 frame.AddrFrame.Offset = context->Rbp;
254 frame.AddrPC.Offset = context->Eip;
255 frame.AddrStack.Offset = context->Esp;
256 frame.AddrFrame.Offset = context->Ebp;
258 frame.AddrPC.Mode = AddrModeFlat;
259 frame.AddrStack.Mode = AddrModeFlat;
260 frame.AddrFrame.Mode = AddrModeFlat;
264 IMAGE_FILE_MACHINE_I386,
265 GetCurrentProcess (),
270 SymFunctionTableAccess,
275 addr2line((void *) frame.AddrPC.Offset);
279 addr2line ((void *) info->ContextRecord->Rip);
281 addr2line ((void *) info->ContextRecord->Eip);
285 return EXCEPTION_CONTINUE_SEARCH;
290 set_backtrace_file (boost::filesystem::path p)
295 /** This is called when there is an unhandled exception. Any
296 * backtrace in this function is useless on Windows as the stack has
297 * already been unwound from the throw; we have the gdb wrap hack to
304 static bool tried_throw = false;
305 // try once to re-throw currently active exception
311 catch (const std::exception &e) {
312 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
313 << e.what() << std::endl;
316 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
324 dcpomatic_setup_path_encoding ()
326 #ifdef DCPOMATIC_WINDOWS
327 /* Dark voodoo which, I think, gets boost::filesystem::path to
328 correctly convert UTF-8 strings to paths, and also paths
329 back to UTF-8 strings (on path::string()).
331 After this, constructing boost::filesystem::paths from strings
332 converts from UTF-8 to UTF-16 inside the path. Then
333 path::string().c_str() gives UTF-8 and
334 path::c_str() gives UTF-16.
336 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
337 so things are much simpler.
339 std::locale::global (boost::locale::generator().generate (""));
340 boost::filesystem::path::imbue (std::locale ());
344 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
345 * Must be called from the UI thread, if there is one.
350 #ifdef DCPOMATIC_WINDOWS
351 boost::filesystem::path p = g_get_user_config_dir ();
352 p /= "backtrace.txt";
353 set_backtrace_file (p);
354 SetUnhandledExceptionFilter(exception_handler);
358 avfilter_register_all ();
361 /* Add our library directory to the libltdl search path so that
362 xmlsec can find xmlsec1-openssl.
364 boost::filesystem::path lib = app_contents ();
366 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
369 set_terminate (terminate);
371 #ifdef DCPOMATIC_WINDOWS
372 putenv ("PANGOCAIRO_BACKEND=fontconfig");
373 putenv (String::compose("FONTCONFIG_PATH=%1", shared_path().string()).c_str());
377 setenv ("PANGOCAIRO_BACKEND", "fontconfig", 1);
378 setenv ("FONTCONFIG_PATH", shared_path().string().c_str(), 1);
384 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
385 /* Render something to fontconfig to create its cache */
386 list<StringText> subs;
387 dcp::SubtitleString ss(
388 optional<string>(), false, false, false, dcp::Colour(), 42, 1, dcp::Time(), dcp::Time(), 0, dcp::HALIGN_CENTER, 0, dcp::VALIGN_CENTER, dcp::DIRECTION_LTR,
389 "Hello dolly", dcp::NONE, dcp::Colour(), dcp::Time(), dcp::Time()
391 subs.push_back (StringText(ss, 0));
392 render_text (subs, list<shared_ptr<Font> >(), dcp::Size(640, 480), DCPTime(), 24);
395 Ratio::setup_ratios ();
396 PresetColourConversion::setup_colour_conversion_presets ();
397 VideoContentScale::setup_scales ();
398 DCPContentType::setup_dcp_content_types ();
399 Filter::setup_filters ();
400 CinemaSoundProcessor::setup_cinema_sound_processors ();
401 AudioProcessor::setup_audio_processors ();
403 curl_global_init (CURL_GLOBAL_ALL);
405 ui_thread = boost::this_thread::get_id ();
408 #ifdef DCPOMATIC_WINDOWS
409 boost::filesystem::path
413 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
414 boost::filesystem::path p (buffer);
415 p = p.parent_path ();
416 p = p.parent_path ();
423 boost::filesystem::path
426 return "DCP-o-matic 2.app/Contents/Resources";
431 dcpomatic_setup_gettext_i18n (string lang)
433 #ifdef DCPOMATIC_LINUX
437 if (!lang.empty ()) {
438 /* Override our environment language. Note that the caller must not
439 free the string passed into putenv().
441 string s = String::compose ("LANGUAGE=%1", lang);
442 putenv (strdup (s.c_str ()));
443 s = String::compose ("LANG=%1", lang);
444 putenv (strdup (s.c_str ()));
445 s = String::compose ("LC_ALL=%1", lang);
446 putenv (strdup (s.c_str ()));
449 setlocale (LC_ALL, "");
450 textdomain ("libdcpomatic2");
452 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
453 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
454 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
457 #ifdef DCPOMATIC_LINUX
458 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
462 /** Compute a digest of the first and last `size' bytes of a set of files. */
464 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
466 boost::scoped_array<char> buffer (new char[size]);
470 boost::uintmax_t to_do = size;
471 char* p = buffer.get ();
473 while (i < int64_t (files.size()) && to_do > 0) {
474 FILE* f = fopen_boost (files[i], "rb");
476 throw OpenFileError (files[i].string(), errno, OpenFileError::READ);
479 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
480 checked_fread (p, this_time, f, files[i]);
487 digester.add (buffer.get(), size - to_do);
492 i = files.size() - 1;
493 while (i >= 0 && to_do > 0) {
494 FILE* f = fopen_boost (files[i], "rb");
496 throw OpenFileError (files[i].string(), errno, OpenFileError::READ);
499 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
500 dcpomatic_fseek (f, -this_time, SEEK_END);
501 checked_fread (p, this_time, f, files[i]);
508 digester.add (buffer.get(), size - to_do);
510 return digester.get ();
513 /** Round a number up to the nearest multiple of another number.
515 * @param stride Array of numbers to round, indexed by c.
516 * @param t Multiple to round to.
517 * @return Rounded number.
520 stride_round_up (int c, int const * stride, int t)
522 int const a = stride[c] + (t - 1);
526 /** Trip an assert if the caller is not in the UI thread */
530 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
534 audio_channel_name (int c)
536 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
538 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
539 /// enhancement channel (sub-woofer).
540 string const channels[] = {
547 _("Hearing impaired"),
548 _("Visually impaired"),
551 _("Left rear surround"),
552 _("Right rear surround"),
554 _("D-BOX secondary"),
563 short_audio_channel_name (int c)
565 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
567 /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
568 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
569 /// VI is the visually-impaired audio track (audio describe). DBP is the D-BOX
570 /// primary channel and DBS is the D-BOX secondary channel.
571 string const channels[] = {
595 valid_image_file (boost::filesystem::path f)
597 if (boost::starts_with (f.leaf().string(), "._")) {
601 string ext = f.extension().string();
602 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
604 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
605 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
606 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr" ||
612 valid_sound_file (boost::filesystem::path f)
614 if (boost::starts_with (f.leaf().string(), "._")) {
618 string ext = f.extension().string();
619 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
620 return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
624 valid_j2k_file (boost::filesystem::path f)
626 string ext = f.extension().string();
627 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
628 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
632 tidy_for_filename (string f)
634 boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
639 fit_ratio_within (float ratio, dcp::Size full_frame)
641 if (ratio < full_frame.ratio ()) {
642 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
645 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
649 wrapped_av_malloc (size_t s)
651 void* p = av_malloc (s);
659 split_get_request (string url)
662 AWAITING_QUESTION_MARK,
665 } state = AWAITING_QUESTION_MARK;
667 map<string, string> r;
670 for (size_t i = 0; i < url.length(); ++i) {
672 case AWAITING_QUESTION_MARK:
687 r.insert (make_pair (k, v));
697 if (state == VALUE) {
698 r.insert (make_pair (k, v));
705 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
707 dcp::NameFormat::Map values;
709 values['r'] = raw_convert<string> (reel_index + 1);
710 values['n'] = raw_convert<string> (reel_count);
712 values['c'] = careful_string_filter (summary.get());
714 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
718 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
720 dcp::NameFormat::Map values;
722 values['r'] = raw_convert<string> (reel_index + 1);
723 values['n'] = raw_convert<string> (reel_count);
725 values['c'] = careful_string_filter (summary.get());
727 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
731 relaxed_string_to_float (string s)
734 boost::algorithm::replace_all (s, ",", ".");
735 return lexical_cast<float> (s);
736 } catch (bad_lexical_cast &) {
737 boost::algorithm::replace_all (s, ".", ",");
738 return lexical_cast<float> (s);
743 careful_string_filter (string s)
745 /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
746 There's no apparent list of what really is allowed, so this is a guess.
747 Safety first and all that.
750 wstring ws = boost::locale::conv::utf_to_utf<wchar_t>(s);
753 string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
754 for (size_t i = 0; i < ws.size(); ++i) {
758 /* Remove some accents */
759 if (wstring(L"áà â").find(c) != string::npos) {
762 if (wstring(L"éèêë").find(c) != string::npos) {
765 if (wstring(L"ö").find(c) != string::npos) {
768 if (wstring(L"ü").find(c) != string::npos) {
772 if (allowed.find(c) != string::npos) {
777 return boost::locale::conv::utf_to_utf<char>(out);
780 /** @param mapped List of mapped audio channels from a Film.
781 * @param channels Total number of channels in the Film.
782 * @return First: number of non-LFE soundtrack channels (L/R/C/Ls/Rs/Lc/Rc/Bsl/Bsr), second: number of LFE channels.
785 audio_channel_types (list<int> mapped, int channels)
790 BOOST_FOREACH (int i, mapped) {
792 /* This channel is mapped but is not included in the DCP */
796 switch (static_cast<dcp::Channel>(i)) {
817 return make_pair (non_lfe, lfe);
820 shared_ptr<AudioBuffers>
821 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
823 shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
824 mapped->make_silent ();
826 for (int i = 0; i < map.input_channels(); ++i) {
827 for (int j = 0; j < mapped->channels(); ++j) {
828 if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
829 mapped->accumulate_channel (
832 static_cast<dcp::Channel> (j),
833 map.get (i, static_cast<dcp::Channel> (j))
843 increment_eyes (Eyes e)
845 if (e == EYES_LEFT) {
853 checked_fwrite (void const * ptr, size_t size, FILE* stream, boost::filesystem::path path)
855 size_t N = fwrite (ptr, 1, size, stream);
857 if (ferror(stream)) {
859 throw FileError (String::compose("fwrite error %1", errno), path);
862 throw FileError ("Unexpected short write", path);
868 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
870 size_t N = fread (ptr, 1, size, stream);
872 if (ferror(stream)) {
874 throw FileError (String::compose("fread error %1", errno), path);
877 throw FileError ("Unexpected short read", path);
883 utf8_strlen (string s)
885 size_t const len = s.length ();
887 for (size_t i = 0; i < len; ++i) {
888 unsigned char c = s[i];
889 if ((c & 0xe0) == 0xc0) {
891 } else if ((c & 0xf0) == 0xe0) {
893 } else if ((c & 0xf8) == 0xf0) {
902 day_of_week_to_string (boost::gregorian::greg_weekday d)
904 switch (d.as_enum()) {
905 case boost::date_time::Sunday:
907 case boost::date_time::Monday:
909 case boost::date_time::Tuesday:
911 case boost::date_time::Wednesday:
912 return _("Wednesday");
913 case boost::date_time::Thursday:
914 return _("Thursday");
915 case boost::date_time::Friday:
917 case boost::date_time::Saturday:
918 return _("Saturday");
921 return d.as_long_string ();
924 /** @param size Size of picture that the subtitle will be overlaid onto */
926 emit_subtitle_image (ContentTimePeriod period, dcp::SubtitleImage sub, dcp::Size size, shared_ptr<TextDecoder> decoder)
928 /* XXX: this is rather inefficient; decoding the image just to get its size */
929 FFmpegImageProxy proxy (sub.png_image());
930 shared_ptr<Image> image = proxy.image().first;
931 /* set up rect with height and width */
932 dcpomatic::Rect<double> rect(0, 0, image->size().width / double(size.width), image->size().height / double(size.height));
934 /* add in position */
936 switch (sub.h_align()) {
937 case dcp::HALIGN_LEFT:
938 rect.x += sub.h_position();
940 case dcp::HALIGN_CENTER:
941 rect.x += 0.5 + sub.h_position() - rect.width / 2;
943 case dcp::HALIGN_RIGHT:
944 rect.x += 1 - sub.h_position() - rect.width;
948 switch (sub.v_align()) {
949 case dcp::VALIGN_TOP:
950 rect.y += sub.v_position();
952 case dcp::VALIGN_CENTER:
953 rect.y += 0.5 + sub.v_position() - rect.height / 2;
955 case dcp::VALIGN_BOTTOM:
956 rect.y += 1 - sub.v_position() - rect.height;
960 decoder->emit_bitmap (period, image, rect);
964 show_jobs_on_console (bool progress)
970 dcpomatic_sleep_seconds (5);
972 list<shared_ptr<Job> > jobs = JobManager::instance()->get();
974 if (!first && progress) {
975 for (size_t i = 0; i < jobs.size(); ++i) {
976 cout << "\033[1A\033[2K";
983 BOOST_FOREACH (shared_ptr<Job> i, jobs) {
986 if (!i->sub_name().empty()) {
987 cout << "; " << i->sub_name();
991 if (i->progress ()) {
992 cout << i->status() << " \n";
994 cout << ": Running \n";
998 if (!progress && i->finished_in_error()) {
999 /* We won't see this error if we haven't been showing progress,
1002 cout << i->status() << "\n";
1005 if (i->finished_in_error()) {
1010 if (!JobManager::instance()->work_to_do()) {
1018 /** XXX: could use mmap? */
1020 copy_in_bits (boost::filesystem::path from, boost::filesystem::path to, boost::function<void (float)> progress)
1022 FILE* f = fopen_boost (from, "rb");
1024 throw OpenFileError (from, errno, OpenFileError::READ);
1026 FILE* t = fopen_boost (to, "wb");
1029 throw OpenFileError (to, errno, OpenFileError::WRITE);
1032 /* on the order of a second's worth of copying */
1033 boost::uintmax_t const chunk = 20 * 1024 * 1024;
1035 uint8_t* buffer = static_cast<uint8_t*> (malloc(chunk));
1037 throw std::bad_alloc ();
1040 boost::uintmax_t const total = boost::filesystem::file_size (from);
1041 boost::uintmax_t remaining = total;
1044 boost::uintmax_t this_time = min (chunk, remaining);
1045 size_t N = fread (buffer, 1, chunk, f);
1046 if (N < this_time) {
1050 throw ReadFileError (from, errno);
1053 N = fwrite (buffer, 1, this_time, t);
1054 if (N < this_time) {
1058 throw WriteFileError (to, errno);
1061 progress (1 - float(remaining) / total);
1062 remaining -= this_time;
1070 #ifdef DCPOMATIC_VARIANT_SWAROOP
1072 /* Make up a key from the machine UUID */
1076 dcp::Data key (dcpomatic::crypto_key_length());
1077 memset (key.data().get(), 0, key.size());
1078 string const magic = command_and_read ("dcpomatic2_uuid");
1079 strncpy ((char *) key.data().get(), magic.c_str(), dcpomatic::crypto_key_length());
1083 /* swaroop chain file format:
1085 * 0 [int16_t] IV length
1086 * 2 [int16_t] cert #1 length, or 0 for none
1087 * 4 [int16_t] cert #2 length, or 0 for none
1088 * 6 [int16_t] cert #3 length, or 0 for none
1089 * 8 [int16_t] cert #4 length, or 0 for none
1090 * 10 [int16_t] cert #5 length, or 0 for none
1091 * 12 [int16_t] cert #6 length, or 0 for none
1092 * 14 [int16_t] cert #7 length, or 0 for none
1093 * 16 [int16_t] cert #8 length, or 0 for none
1094 * 16 [int16_t] private key length
1107 struct __attribute__ ((packed)) Header_ {
1109 int16_t cert_length[8];
1110 int16_t private_key_length;
1113 typedef struct Header_ Header;
1115 shared_ptr<dcp::CertificateChain>
1116 read_swaroop_chain (boost::filesystem::path path)
1118 dcp::Data data (path);
1119 Header* header = (Header *) data.data().get();
1120 uint8_t* p = data.data().get() + sizeof(Header);
1122 dcp::Data iv (p, header->iv_length);
1125 shared_ptr<dcp::CertificateChain> cc (new dcp::CertificateChain());
1126 for (int i = 0; i < 8; ++i) {
1127 if (header->cert_length[i] == 0) {
1130 dcp::Data c(p, header->cert_length[i]);
1132 cc->add (dcp::Certificate(dcpomatic::decrypt(c, key_from_uuid(), iv)));
1135 dcp::Data k (p, header->private_key_length);
1136 cc->set_key (dcpomatic::decrypt(k, key_from_uuid(), iv));
1141 write_swaroop_chain (shared_ptr<const dcp::CertificateChain> chain, boost::filesystem::path output)
1143 scoped_array<uint8_t> buffer (new uint8_t[65536]);
1144 Header* header = (Header *) buffer.get();
1145 memset (header, 0, sizeof(Header));
1146 uint8_t* p = buffer.get() + sizeof(Header);
1148 dcp::Data iv = dcpomatic::random_iv ();
1149 header->iv_length = iv.size ();
1150 memcpy (p, iv.data().get(), iv.size());
1154 BOOST_FOREACH (dcp::Certificate i, chain->root_to_leaf()) {
1155 dcp::Data e = dcpomatic::encrypt (i.certificate(true), key_from_uuid(), iv);
1156 memcpy (p, e.data().get(), e.size());
1158 DCPOMATIC_ASSERT (N < 8);
1159 header->cert_length[N] = e.size ();
1163 dcp::Data k = dcpomatic::encrypt (chain->key().get(), key_from_uuid(), iv);
1164 memcpy (p, k.data().get(), k.size());
1166 header->private_key_length = k.size ();
1168 FILE* f = fopen_boost (output, "wb");
1169 checked_fwrite (buffer.get(), p - buffer.get(), f, output);
1176 db_to_linear (double db)
1178 return pow(10, db / 20);
1182 linear_to_db (double linear)
1184 return 20 * log10(linear);