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/decrypted_kdm.h>
49 #include <dcp/locale_convert.h>
51 #include <dcp/raw_convert.h>
52 #include <dcp/picture_asset.h>
53 #include <dcp/sound_asset.h>
54 #include <dcp/subtitle_asset.h>
55 #include <dcp/atmos_asset.h>
57 #include <libavfilter/avfilter.h>
58 #include <libavformat/avformat.h>
59 #include <libavcodec/avcodec.h>
61 #include <curl/curl.h>
63 #include <pangomm/init.h>
64 #include <boost/algorithm/string.hpp>
65 #include <boost/range/algorithm/replace_if.hpp>
66 #include <boost/thread.hpp>
67 #include <boost/filesystem.hpp>
68 #include <boost/locale.hpp>
69 #ifdef DCPOMATIC_WINDOWS
70 #include <boost/locale.hpp>
79 #ifdef DCPOMATIC_POSIX
100 using std::bad_alloc;
101 using std::set_terminate;
102 using std::make_pair;
103 using boost::shared_ptr;
105 using boost::optional;
106 using boost::lexical_cast;
107 using boost::bad_lexical_cast;
108 using boost::scoped_array;
110 using dcp::raw_convert;
111 using dcp::locale_convert;
112 using namespace dcpomatic;
114 /** Path to our executable, required by the stacktrace stuff and filled
115 * in during App::onInit().
118 bool is_batch_converter = false;
119 static boost::thread::id ui_thread;
120 static boost::filesystem::path backtrace_file;
122 /** Convert some number of seconds to a string representation
123 * in hours, minutes and seconds.
126 * @return String of the form H:M:S (where H is hours, M
127 * is minutes and S is seconds).
130 seconds_to_hms (int s)
138 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
143 time_to_hmsf (DCPTime time, Frame rate)
145 Frame f = time.frames_round (rate);
154 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d.%d", h, m, s, static_cast<int>(f));
158 /** @param s Number of seconds.
159 * @return String containing an approximate description of s (e.g. "about 2 hours")
162 seconds_to_approximate_hms (int s)
172 bool minutes = h < 6 && m > 0;
173 bool seconds = h == 0 && m < 10 && s > 0;
175 if (m > 30 && !minutes) {
176 /* round up the hours */
179 if (s > 30 && !seconds) {
180 /* round up the minutes */
190 /// TRANSLATORS: h here is an abbreviation for hours
191 ap += locale_convert<string>(h) + _("h");
193 if (minutes || seconds) {
199 /// TRANSLATORS: m here is an abbreviation for minutes
200 ap += locale_convert<string>(m) + _("m");
209 /// TRANSLATORS: s here is an abbreviation for seconds
210 ap += locale_convert<string>(s) + _("s");
217 seconds (struct timeval t)
219 return t.tv_sec + (double (t.tv_usec) / 1e6);
222 #ifdef DCPOMATIC_WINDOWS
224 /** Resolve symbol name and source location given the path to the executable */
226 addr2line (void const * const addr)
228 char addr2line_cmd[512] = { 0 };
229 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
230 return system(addr2line_cmd);
233 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
234 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
235 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
238 exception_handler(struct _EXCEPTION_POINTERS * info)
240 FILE* f = fopen_boost (backtrace_file, "w");
241 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
244 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
245 CONTEXT* context = info->ContextRecord;
246 SymInitialize (GetCurrentProcess (), 0, true);
248 STACKFRAME frame = { 0 };
250 /* setup initial stack frame */
252 frame.AddrPC.Offset = context->Rip;
253 frame.AddrStack.Offset = context->Rsp;
254 frame.AddrFrame.Offset = context->Rbp;
256 frame.AddrPC.Offset = context->Eip;
257 frame.AddrStack.Offset = context->Esp;
258 frame.AddrFrame.Offset = context->Ebp;
260 frame.AddrPC.Mode = AddrModeFlat;
261 frame.AddrStack.Mode = AddrModeFlat;
262 frame.AddrFrame.Mode = AddrModeFlat;
266 IMAGE_FILE_MACHINE_I386,
267 GetCurrentProcess (),
272 SymFunctionTableAccess,
277 addr2line((void *) frame.AddrPC.Offset);
281 addr2line ((void *) info->ContextRecord->Rip);
283 addr2line ((void *) info->ContextRecord->Eip);
287 return EXCEPTION_CONTINUE_SEARCH;
292 set_backtrace_file (boost::filesystem::path p)
297 /** This is called when there is an unhandled exception. Any
298 * backtrace in this function is useless on Windows as the stack has
299 * already been unwound from the throw; we have the gdb wrap hack to
306 static bool tried_throw = false;
307 // try once to re-throw currently active exception
313 catch (const std::exception &e) {
314 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
315 << e.what() << std::endl;
318 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
326 dcpomatic_setup_path_encoding ()
328 #ifdef DCPOMATIC_WINDOWS
329 /* Dark voodoo which, I think, gets boost::filesystem::path to
330 correctly convert UTF-8 strings to paths, and also paths
331 back to UTF-8 strings (on path::string()).
333 After this, constructing boost::filesystem::paths from strings
334 converts from UTF-8 to UTF-16 inside the path. Then
335 path::string().c_str() gives UTF-8 and
336 path::c_str() gives UTF-16.
338 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
339 so things are much simpler.
341 std::locale::global (boost::locale::generator().generate (""));
342 boost::filesystem::path::imbue (std::locale ());
346 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
347 * Must be called from the UI thread, if there is one.
352 #ifdef DCPOMATIC_WINDOWS
353 boost::filesystem::path p = g_get_user_config_dir ();
354 p /= "backtrace.txt";
355 set_backtrace_file (p);
356 SetUnhandledExceptionFilter(exception_handler);
360 avfilter_register_all ();
363 /* Add our library directory to the libltdl search path so that
364 xmlsec can find xmlsec1-openssl.
366 boost::filesystem::path lib = directory_containing_executable().parent_path();
368 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
371 set_terminate (terminate);
373 #ifdef DCPOMATIC_WINDOWS
374 putenv ("PANGOCAIRO_BACKEND=fontconfig");
375 putenv (String::compose("FONTCONFIG_PATH=%1", shared_path().string()).c_str());
379 setenv ("PANGOCAIRO_BACKEND", "fontconfig", 1);
380 setenv ("FONTCONFIG_PATH", shared_path().string().c_str(), 1);
386 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
387 /* Render something to fontconfig to create its cache */
388 list<StringText> subs;
389 dcp::SubtitleString ss(
390 optional<string>(), false, false, false, dcp::Colour(), 42, 1, dcp::Time(), dcp::Time(), 0, dcp::HALIGN_CENTER, 0, dcp::VALIGN_CENTER, dcp::DIRECTION_LTR,
391 "Hello dolly", dcp::NONE, dcp::Colour(), dcp::Time(), dcp::Time()
393 subs.push_back (StringText(ss, 0));
394 render_text (subs, list<shared_ptr<Font> >(), dcp::Size(640, 480), DCPTime(), 24);
397 Ratio::setup_ratios ();
398 PresetColourConversion::setup_colour_conversion_presets ();
399 DCPContentType::setup_dcp_content_types ();
400 Filter::setup_filters ();
401 CinemaSoundProcessor::setup_cinema_sound_processors ();
402 AudioProcessor::setup_audio_processors ();
404 curl_global_init (CURL_GLOBAL_ALL);
406 ui_thread = boost::this_thread::get_id ();
409 #ifdef DCPOMATIC_WINDOWS
410 boost::filesystem::path
414 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
415 boost::filesystem::path p (buffer);
416 p = p.parent_path ();
417 p = p.parent_path ();
424 boost::filesystem::path
427 return "DCP-o-matic 2.app/Contents/Resources";
432 dcpomatic_setup_gettext_i18n (string lang)
434 #ifdef DCPOMATIC_LINUX
438 if (!lang.empty ()) {
439 /* Override our environment language. Note that the caller must not
440 free the string passed into putenv().
442 string s = String::compose ("LANGUAGE=%1", lang);
443 putenv (strdup (s.c_str ()));
444 s = String::compose ("LANG=%1", lang);
445 putenv (strdup (s.c_str ()));
446 s = String::compose ("LC_ALL=%1", lang);
447 putenv (strdup (s.c_str ()));
450 setlocale (LC_ALL, "");
451 textdomain ("libdcpomatic2");
453 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
454 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
455 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
458 #ifdef DCPOMATIC_LINUX
459 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
463 /** Compute a digest of the first and last `size' bytes of a set of files. */
465 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
467 boost::scoped_array<char> buffer (new char[size]);
471 boost::uintmax_t to_do = size;
472 char* p = buffer.get ();
474 while (i < int64_t (files.size()) && to_do > 0) {
475 FILE* f = fopen_boost (files[i], "rb");
477 throw OpenFileError (files[i].string(), errno, OpenFileError::READ);
480 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
481 checked_fread (p, this_time, f, files[i]);
488 digester.add (buffer.get(), size - to_do);
493 i = files.size() - 1;
494 while (i >= 0 && to_do > 0) {
495 FILE* f = fopen_boost (files[i], "rb");
497 throw OpenFileError (files[i].string(), errno, OpenFileError::READ);
500 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
501 dcpomatic_fseek (f, -this_time, SEEK_END);
502 checked_fread (p, this_time, f, files[i]);
509 digester.add (buffer.get(), size - to_do);
511 return digester.get ();
514 /** Round a number up to the nearest multiple of another number.
516 * @param stride Array of numbers to round, indexed by c.
517 * @param t Multiple to round to.
518 * @return Rounded number.
521 stride_round_up (int c, int const * stride, int t)
523 int const a = stride[c] + (t - 1);
527 /** Trip an assert if the caller is not in the UI thread */
531 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
535 audio_channel_name (int c)
537 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
539 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
540 /// enhancement channel (sub-woofer).
541 string const channels[] = {
548 _("Hearing impaired"),
549 _("Visually impaired"),
552 _("Left rear surround"),
553 _("Right rear surround"),
555 _("D-BOX secondary"),
564 short_audio_channel_name (int c)
566 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
568 /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
569 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
570 /// VI is the visually-impaired audio track (audio describe). DBP is the D-BOX
571 /// primary channel and DBS is the D-BOX secondary channel.
572 string const channels[] = {
596 valid_image_file (boost::filesystem::path f)
598 if (boost::starts_with (f.leaf().string(), "._")) {
602 string ext = f.extension().string();
603 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
605 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
606 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
607 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr" ||
613 valid_sound_file (boost::filesystem::path f)
615 if (boost::starts_with (f.leaf().string(), "._")) {
619 string ext = f.extension().string();
620 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
621 return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
625 valid_j2k_file (boost::filesystem::path f)
627 string ext = f.extension().string();
628 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
629 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
633 tidy_for_filename (string f)
635 boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
640 fit_ratio_within (float ratio, dcp::Size full_frame)
642 if (ratio < full_frame.ratio ()) {
643 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
646 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
650 wrapped_av_malloc (size_t s)
652 void* p = av_malloc (s);
660 split_get_request (string url)
663 AWAITING_QUESTION_MARK,
666 } state = AWAITING_QUESTION_MARK;
668 map<string, string> r;
671 for (size_t i = 0; i < url.length(); ++i) {
673 case AWAITING_QUESTION_MARK:
688 r.insert (make_pair (k, v));
698 if (state == VALUE) {
699 r.insert (make_pair (k, v));
706 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
708 dcp::NameFormat::Map values;
710 values['r'] = raw_convert<string> (reel_index + 1);
711 values['n'] = raw_convert<string> (reel_count);
713 values['c'] = careful_string_filter (summary.get());
715 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
719 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
721 dcp::NameFormat::Map values;
723 values['r'] = raw_convert<string> (reel_index + 1);
724 values['n'] = raw_convert<string> (reel_count);
726 values['c'] = careful_string_filter (summary.get());
728 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
733 atmos_asset_filename (shared_ptr<dcp::AtmosAsset> asset, int reel_index, int reel_count, optional<string> summary)
735 dcp::NameFormat::Map values;
736 values['t'] = "atmos";
737 values['r'] = raw_convert<string> (reel_index + 1);
738 values['n'] = raw_convert<string> (reel_count);
740 values['c'] = careful_string_filter (summary.get());
742 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
747 relaxed_string_to_float (string s)
750 boost::algorithm::replace_all (s, ",", ".");
751 return lexical_cast<float> (s);
752 } catch (bad_lexical_cast &) {
753 boost::algorithm::replace_all (s, ".", ",");
754 return lexical_cast<float> (s);
759 careful_string_filter (string s)
761 /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
762 There's no apparent list of what really is allowed, so this is a guess.
763 Safety first and all that.
766 wstring ws = boost::locale::conv::utf_to_utf<wchar_t>(s);
769 string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
770 for (size_t i = 0; i < ws.size(); ++i) {
774 /* Remove some accents */
775 if (wstring(L"áà â").find(c) != string::npos) {
778 if (wstring(L"éèêë").find(c) != string::npos) {
781 if (wstring(L"ö").find(c) != string::npos) {
784 if (wstring(L"ü").find(c) != string::npos) {
788 if (allowed.find(c) != string::npos) {
793 return boost::locale::conv::utf_to_utf<char>(out);
796 /** @param mapped List of mapped audio channels from a Film.
797 * @param channels Total number of channels in the Film.
798 * @return First: number of non-LFE soundtrack channels (L/R/C/Ls/Rs/Lc/Rc/Bsl/Bsr), second: number of LFE channels.
801 audio_channel_types (list<int> mapped, int channels)
806 BOOST_FOREACH (int i, mapped) {
808 /* This channel is mapped but is not included in the DCP */
812 switch (static_cast<dcp::Channel>(i)) {
833 return make_pair (non_lfe, lfe);
836 shared_ptr<AudioBuffers>
837 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
839 shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
840 mapped->make_silent ();
842 int to_do = min (map.input_channels(), input->channels());
844 for (int i = 0; i < to_do; ++i) {
845 for (int j = 0; j < mapped->channels(); ++j) {
846 if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
847 mapped->accumulate_channel (
850 static_cast<dcp::Channel> (j),
851 map.get (i, static_cast<dcp::Channel> (j))
861 increment_eyes (Eyes e)
863 if (e == EYES_LEFT) {
871 checked_fwrite (void const * ptr, size_t size, FILE* stream, boost::filesystem::path path)
873 size_t N = fwrite (ptr, 1, size, stream);
875 if (ferror(stream)) {
877 throw FileError (String::compose("fwrite error %1", errno), path);
880 throw FileError ("Unexpected short write", path);
886 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
888 size_t N = fread (ptr, 1, size, stream);
890 if (ferror(stream)) {
892 throw FileError (String::compose("fread error %1", errno), path);
895 throw FileError ("Unexpected short read", path);
901 utf8_strlen (string s)
903 size_t const len = s.length ();
905 for (size_t i = 0; i < len; ++i) {
906 unsigned char c = s[i];
907 if ((c & 0xe0) == 0xc0) {
909 } else if ((c & 0xf0) == 0xe0) {
911 } else if ((c & 0xf8) == 0xf0) {
920 day_of_week_to_string (boost::gregorian::greg_weekday d)
922 switch (d.as_enum()) {
923 case boost::date_time::Sunday:
925 case boost::date_time::Monday:
927 case boost::date_time::Tuesday:
929 case boost::date_time::Wednesday:
930 return _("Wednesday");
931 case boost::date_time::Thursday:
932 return _("Thursday");
933 case boost::date_time::Friday:
935 case boost::date_time::Saturday:
936 return _("Saturday");
939 return d.as_long_string ();
942 /** @param size Size of picture that the subtitle will be overlaid onto */
944 emit_subtitle_image (ContentTimePeriod period, dcp::SubtitleImage sub, dcp::Size size, shared_ptr<TextDecoder> decoder)
946 /* XXX: this is rather inefficient; decoding the image just to get its size */
947 FFmpegImageProxy proxy (sub.png_image());
948 shared_ptr<Image> image = proxy.image().image;
949 /* set up rect with height and width */
950 dcpomatic::Rect<double> rect(0, 0, image->size().width / double(size.width), image->size().height / double(size.height));
952 /* add in position */
954 switch (sub.h_align()) {
955 case dcp::HALIGN_LEFT:
956 rect.x += sub.h_position();
958 case dcp::HALIGN_CENTER:
959 rect.x += 0.5 + sub.h_position() - rect.width / 2;
961 case dcp::HALIGN_RIGHT:
962 rect.x += 1 - sub.h_position() - rect.width;
966 switch (sub.v_align()) {
967 case dcp::VALIGN_TOP:
968 rect.y += sub.v_position();
970 case dcp::VALIGN_CENTER:
971 rect.y += 0.5 + sub.v_position() - rect.height / 2;
973 case dcp::VALIGN_BOTTOM:
974 rect.y += 1 - sub.v_position() - rect.height;
978 decoder->emit_bitmap (period, image, rect);
982 show_jobs_on_console (bool progress)
988 dcpomatic_sleep_seconds (5);
990 list<shared_ptr<Job> > jobs = JobManager::instance()->get();
992 if (!first && progress) {
993 for (size_t i = 0; i < jobs.size(); ++i) {
994 cout << "\033[1A\033[2K";
1001 BOOST_FOREACH (shared_ptr<Job> i, jobs) {
1004 if (!i->sub_name().empty()) {
1005 cout << "; " << i->sub_name();
1009 if (i->progress ()) {
1010 cout << i->status() << " \n";
1012 cout << ": Running \n";
1016 if (!progress && i->finished_in_error()) {
1017 /* We won't see this error if we haven't been showing progress,
1020 cout << i->status() << "\n";
1023 if (i->finished_in_error()) {
1028 if (!JobManager::instance()->work_to_do()) {
1036 /** XXX: could use mmap? */
1038 copy_in_bits (boost::filesystem::path from, boost::filesystem::path to, boost::function<void (float)> progress)
1040 FILE* f = fopen_boost (from, "rb");
1042 throw OpenFileError (from, errno, OpenFileError::READ);
1044 FILE* t = fopen_boost (to, "wb");
1047 throw OpenFileError (to, errno, OpenFileError::WRITE);
1050 /* on the order of a second's worth of copying */
1051 boost::uintmax_t const chunk = 20 * 1024 * 1024;
1053 uint8_t* buffer = static_cast<uint8_t*> (malloc(chunk));
1055 throw std::bad_alloc ();
1058 boost::uintmax_t const total = boost::filesystem::file_size (from);
1059 boost::uintmax_t remaining = total;
1062 boost::uintmax_t this_time = min (chunk, remaining);
1063 size_t N = fread (buffer, 1, chunk, f);
1064 if (N < this_time) {
1068 throw ReadFileError (from, errno);
1071 N = fwrite (buffer, 1, this_time, t);
1072 if (N < this_time) {
1076 throw WriteFileError (to, errno);
1079 progress (1 - float(remaining) / total);
1080 remaining -= this_time;
1088 #ifdef DCPOMATIC_VARIANT_SWAROOP
1090 /* Make up a key from the machine UUID */
1094 dcp::Data key (dcpomatic::crypto_key_length());
1095 memset (key.data().get(), 0, key.size());
1096 string const magic = command_and_read ("dcpomatic2_uuid");
1097 strncpy ((char *) key.data().get(), magic.c_str(), dcpomatic::crypto_key_length());
1101 /* swaroop chain file format:
1103 * 0 [int16_t] IV length
1104 * 2 [int16_t] cert #1 length, or 0 for none
1105 * 4 [int16_t] cert #2 length, or 0 for none
1106 * 6 [int16_t] cert #3 length, or 0 for none
1107 * 8 [int16_t] cert #4 length, or 0 for none
1108 * 10 [int16_t] cert #5 length, or 0 for none
1109 * 12 [int16_t] cert #6 length, or 0 for none
1110 * 14 [int16_t] cert #7 length, or 0 for none
1111 * 16 [int16_t] cert #8 length, or 0 for none
1112 * 16 [int16_t] private key length
1125 struct __attribute__ ((packed)) Header_ {
1127 int16_t cert_length[8];
1128 int16_t private_key_length;
1131 typedef struct Header_ Header;
1133 shared_ptr<dcp::CertificateChain>
1134 read_swaroop_chain (boost::filesystem::path path)
1136 dcp::Data data (path);
1137 Header* header = (Header *) data.data().get();
1138 uint8_t* p = data.data().get() + sizeof(Header);
1140 dcp::Data iv (p, header->iv_length);
1143 shared_ptr<dcp::CertificateChain> cc (new dcp::CertificateChain());
1144 for (int i = 0; i < 8; ++i) {
1145 if (header->cert_length[i] == 0) {
1148 dcp::Data c(p, header->cert_length[i]);
1150 cc->add (dcp::Certificate(dcpomatic::decrypt(c, key_from_uuid(), iv)));
1153 dcp::Data k (p, header->private_key_length);
1154 cc->set_key (dcpomatic::decrypt(k, key_from_uuid(), iv));
1159 write_swaroop_chain (shared_ptr<const dcp::CertificateChain> chain, boost::filesystem::path output)
1161 scoped_array<uint8_t> buffer (new uint8_t[65536]);
1162 Header* header = (Header *) buffer.get();
1163 memset (header, 0, sizeof(Header));
1164 uint8_t* p = buffer.get() + sizeof(Header);
1166 dcp::Data iv = dcpomatic::random_iv ();
1167 header->iv_length = iv.size ();
1168 memcpy (p, iv.data().get(), iv.size());
1172 BOOST_FOREACH (dcp::Certificate i, chain->root_to_leaf()) {
1173 dcp::Data e = dcpomatic::encrypt (i.certificate(true), key_from_uuid(), iv);
1174 memcpy (p, e.data().get(), e.size());
1176 DCPOMATIC_ASSERT (N < 8);
1177 header->cert_length[N] = e.size ();
1181 dcp::Data k = dcpomatic::encrypt (chain->key().get(), key_from_uuid(), iv);
1182 memcpy (p, k.data().get(), k.size());
1184 header->private_key_length = k.size ();
1186 FILE* f = fopen_boost (output, "wb");
1187 checked_fwrite (buffer.get(), p - buffer.get(), f, output);
1194 db_to_linear (double db)
1196 return pow(10, db / 20);
1200 linear_to_db (double linear)
1202 return 20 * log10(linear);
1207 scale_for_display (dcp::Size s, dcp::Size display_container, dcp::Size film_container)
1209 /* Now scale it down if the display container is smaller than the film container */
1210 if (display_container != film_container) {
1211 float const scale = min (
1212 float (display_container.width) / film_container.width,
1213 float (display_container.height) / film_container.height
1216 s.width = lrintf (s.width * scale);
1217 s.height = lrintf (s.height * scale);
1225 decrypt_kdm_with_helpful_error (dcp::EncryptedKDM kdm)
1228 return dcp::DecryptedKDM (kdm, Config::instance()->decryption_chain()->key().get());
1229 } catch (dcp::KDMDecryptionError& e) {
1230 /* Try to flesh out the error a bit */
1231 string const kdm_subject_name = kdm.recipient_x509_subject_name();
1232 bool on_chain = false;
1233 shared_ptr<const dcp::CertificateChain> dc = Config::instance()->decryption_chain();
1234 BOOST_FOREACH (dcp::Certificate i, dc->root_to_leaf()) {
1235 if (i.subject() == kdm_subject_name) {
1240 throw KDMError (_("This KDM was not made for DCP-o-matic's decryption certificate."), e.what());
1241 } else if (on_chain && kdm_subject_name != dc->leaf().subject()) {
1242 throw KDMError (_("This KDM was made for DCP-o-matic but not for its leaf certificate."), e.what());