2 Copyright (C) 2012-2016 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 <dcp/locale_convert.h>
46 #include <dcp/raw_convert.h>
47 #include <dcp/picture_asset.h>
48 #include <dcp/sound_asset.h>
49 #include <dcp/subtitle_asset.h>
51 #include <libavfilter/avfilter.h>
52 #include <libavformat/avformat.h>
53 #include <libavcodec/avcodec.h>
55 #include <curl/curl.h>
57 #include <pangomm/init.h>
58 #include <boost/algorithm/string.hpp>
59 #include <boost/range/algorithm/replace_if.hpp>
60 #include <boost/thread.hpp>
61 #include <boost/filesystem.hpp>
62 #ifdef DCPOMATIC_WINDOWS
63 #include <boost/locale.hpp>
72 #ifdef DCPOMATIC_POSIX
93 using std::set_terminate;
95 using boost::shared_ptr;
97 using boost::optional;
98 using boost::lexical_cast;
99 using boost::bad_lexical_cast;
100 using boost::scoped_array;
102 using dcp::raw_convert;
103 using dcp::locale_convert;
105 /** Path to our executable, required by the stacktrace stuff and filled
106 * in during App::onInit().
109 bool is_batch_converter = false;
110 static boost::thread::id ui_thread;
111 static boost::filesystem::path backtrace_file;
113 /** Convert some number of seconds to a string representation
114 * in hours, minutes and seconds.
117 * @return String of the form H:M:S (where H is hours, M
118 * is minutes and S is seconds).
121 seconds_to_hms (int s)
129 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
134 time_to_hmsf (DCPTime time, Frame rate)
136 Frame f = time.frames_round (rate);
145 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d.%d", h, m, s, static_cast<int>(f));
149 /** @param s Number of seconds.
150 * @return String containing an approximate description of s (e.g. "about 2 hours")
153 seconds_to_approximate_hms (int s)
163 bool minutes = h < 6 && m > 0;
164 bool seconds = h == 0 && m < 10 && s > 0;
166 if (m > 30 && !minutes) {
167 /* round up the hours */
170 if (s > 30 && !seconds) {
171 /* round up the minutes */
181 /// TRANSLATORS: h here is an abbreviation for hours
182 ap += locale_convert<string>(h) + _("h");
184 if (minutes || seconds) {
190 /// TRANSLATORS: m here is an abbreviation for minutes
191 ap += locale_convert<string>(m) + _("m");
200 /// TRANSLATORS: s here is an abbreviation for seconds
201 ap += locale_convert<string>(s) + _("s");
208 seconds (struct timeval t)
210 return t.tv_sec + (double (t.tv_usec) / 1e6);
213 #ifdef DCPOMATIC_WINDOWS
215 /** Resolve symbol name and source location given the path to the executable */
217 addr2line (void const * const addr)
219 char addr2line_cmd[512] = { 0 };
220 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
221 return system(addr2line_cmd);
224 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
225 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
226 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
229 exception_handler(struct _EXCEPTION_POINTERS * info)
231 FILE* f = fopen_boost (backtrace_file, "w");
232 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
235 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
236 CONTEXT* context = info->ContextRecord;
237 SymInitialize (GetCurrentProcess (), 0, true);
239 STACKFRAME frame = { 0 };
241 /* setup initial stack frame */
243 frame.AddrPC.Offset = context->Rip;
244 frame.AddrStack.Offset = context->Rsp;
245 frame.AddrFrame.Offset = context->Rbp;
247 frame.AddrPC.Offset = context->Eip;
248 frame.AddrStack.Offset = context->Esp;
249 frame.AddrFrame.Offset = context->Ebp;
251 frame.AddrPC.Mode = AddrModeFlat;
252 frame.AddrStack.Mode = AddrModeFlat;
253 frame.AddrFrame.Mode = AddrModeFlat;
257 IMAGE_FILE_MACHINE_I386,
258 GetCurrentProcess (),
263 SymFunctionTableAccess,
268 addr2line((void *) frame.AddrPC.Offset);
272 addr2line ((void *) info->ContextRecord->Rip);
274 addr2line ((void *) info->ContextRecord->Eip);
278 return EXCEPTION_CONTINUE_SEARCH;
283 set_backtrace_file (boost::filesystem::path p)
288 /** This is called when there is an unhandled exception. Any
289 * backtrace in this function is useless on Windows as the stack has
290 * already been unwound from the throw; we have the gdb wrap hack to
297 static bool tried_throw = false;
298 // try once to re-throw currently active exception
304 catch (const std::exception &e) {
305 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
306 << e.what() << std::endl;
309 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
317 dcpomatic_setup_path_encoding ()
319 #ifdef DCPOMATIC_WINDOWS
320 /* Dark voodoo which, I think, gets boost::filesystem::path to
321 correctly convert UTF-8 strings to paths, and also paths
322 back to UTF-8 strings (on path::string()).
324 After this, constructing boost::filesystem::paths from strings
325 converts from UTF-8 to UTF-16 inside the path. Then
326 path::string().c_str() gives UTF-8 and
327 path::c_str() gives UTF-16.
329 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
330 so things are much simpler.
332 std::locale::global (boost::locale::generator().generate (""));
333 boost::filesystem::path::imbue (std::locale ());
337 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
338 * Must be called from the UI thread, if there is one.
343 #ifdef DCPOMATIC_WINDOWS
344 boost::filesystem::path p = g_get_user_config_dir ();
345 p /= "backtrace.txt";
346 set_backtrace_file (p);
347 SetUnhandledExceptionFilter(exception_handler);
351 avfilter_register_all ();
354 /* Add our library directory to the libltdl search path so that
355 xmlsec can find xmlsec1-openssl.
357 boost::filesystem::path lib = app_contents ();
359 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
362 set_terminate (terminate);
364 #ifdef DCPOMATIC_WINDOWS
365 putenv ("PANGOCAIRO_BACKEND=fontconfig");
366 putenv (String::compose("FONTCONFIG_PATH=%1", shared_path().string()).c_str());
370 setenv ("PANGOCAIRO_BACKEND", "fontconfig", 1);
371 setenv ("FONTCONFIG_PATH", shared_path().string().c_str(), 1);
377 #ifdef DCPOMATIC_WINDOWS
378 /* Render something to fontconfig to create its cache */
379 list<StringText> subs;
380 dcp::SubtitleString ss(
381 optional<string>(), false, false, false, dcp::Colour(), 42, 1, dcp::Time(), dcp::Time(), 0, dcp::HALIGN_CENTER, 0, dcp::VALIGN_CENTER, dcp::DIRECTION_LTR,
382 "Hello dolly", dcp::NONE, dcp::Colour(), dcp::Time(), dcp::Time()
384 subs.push_back (StringText(ss, 0));
385 render_text (subs, list<shared_ptr<Font> >(), dcp::Size(640, 480), DCPTime(), 24);
388 Ratio::setup_ratios ();
389 PresetColourConversion::setup_colour_conversion_presets ();
390 VideoContentScale::setup_scales ();
391 DCPContentType::setup_dcp_content_types ();
392 Filter::setup_filters ();
393 CinemaSoundProcessor::setup_cinema_sound_processors ();
394 AudioProcessor::setup_audio_processors ();
396 curl_global_init (CURL_GLOBAL_ALL);
398 ui_thread = boost::this_thread::get_id ();
401 #ifdef DCPOMATIC_WINDOWS
402 boost::filesystem::path
406 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
407 boost::filesystem::path p (buffer);
408 p = p.parent_path ();
409 p = p.parent_path ();
416 boost::filesystem::path
419 return "DCP-o-matic 2.app/Contents/Resources";
424 dcpomatic_setup_gettext_i18n (string lang)
426 #ifdef DCPOMATIC_LINUX
430 if (!lang.empty ()) {
431 /* Override our environment language. Note that the caller must not
432 free the string passed into putenv().
434 string s = String::compose ("LANGUAGE=%1", lang);
435 putenv (strdup (s.c_str ()));
436 s = String::compose ("LANG=%1", lang);
437 putenv (strdup (s.c_str ()));
438 s = String::compose ("LC_ALL=%1", lang);
439 putenv (strdup (s.c_str ()));
442 setlocale (LC_ALL, "");
443 textdomain ("libdcpomatic2");
445 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
446 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
447 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
450 #ifdef DCPOMATIC_LINUX
451 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
455 /** Compute a digest of the first and last `size' bytes of a set of files. */
457 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
459 boost::scoped_array<char> buffer (new char[size]);
463 boost::uintmax_t to_do = size;
464 char* p = buffer.get ();
466 while (i < int64_t (files.size()) && to_do > 0) {
467 FILE* f = fopen_boost (files[i], "rb");
469 throw OpenFileError (files[i].string(), errno, true);
472 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
473 checked_fread (p, this_time, f, files[i]);
480 digester.add (buffer.get(), size - to_do);
485 i = files.size() - 1;
486 while (i >= 0 && to_do > 0) {
487 FILE* f = fopen_boost (files[i], "rb");
489 throw OpenFileError (files[i].string(), errno, true);
492 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
493 dcpomatic_fseek (f, -this_time, SEEK_END);
494 checked_fread (p, this_time, f, files[i]);
501 digester.add (buffer.get(), size - to_do);
503 return digester.get ();
506 /** Round a number up to the nearest multiple of another number.
508 * @param stride Array of numbers to round, indexed by c.
509 * @param t Multiple to round to.
510 * @return Rounded number.
513 stride_round_up (int c, int const * stride, int t)
515 int const a = stride[c] + (t - 1);
519 /** Trip an assert if the caller is not in the UI thread */
523 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
527 audio_channel_name (int c)
529 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
531 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
532 /// enhancement channel (sub-woofer).
533 string const channels[] = {
540 _("Hearing impaired"),
541 _("Visually impaired"),
544 _("Left rear surround"),
545 _("Right rear surround"),
547 _("D-BOX secondary"),
556 short_audio_channel_name (int c)
558 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
560 /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
561 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
562 /// VI is the visually-impaired audio track (audio describe). DBP is the D-BOX
563 /// primary channel and DBS is the D-BOX secondary channel.
564 string const channels[] = {
588 valid_image_file (boost::filesystem::path f)
590 if (boost::starts_with (f.leaf().string(), "._")) {
594 string ext = f.extension().string();
595 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
597 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
598 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
599 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr" ||
605 valid_sound_file (boost::filesystem::path f)
607 if (boost::starts_with (f.leaf().string(), "._")) {
611 string ext = f.extension().string();
612 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
613 return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
617 valid_j2k_file (boost::filesystem::path f)
619 string ext = f.extension().string();
620 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
621 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
625 tidy_for_filename (string f)
627 boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
632 fit_ratio_within (float ratio, dcp::Size full_frame)
634 if (ratio < full_frame.ratio ()) {
635 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
638 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
642 wrapped_av_malloc (size_t s)
644 void* p = av_malloc (s);
652 split_get_request (string url)
655 AWAITING_QUESTION_MARK,
658 } state = AWAITING_QUESTION_MARK;
660 map<string, string> r;
663 for (size_t i = 0; i < url.length(); ++i) {
665 case AWAITING_QUESTION_MARK:
680 r.insert (make_pair (k, v));
690 if (state == VALUE) {
691 r.insert (make_pair (k, v));
698 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
700 dcp::NameFormat::Map values;
702 values['r'] = raw_convert<string> (reel_index + 1);
703 values['n'] = raw_convert<string> (reel_count);
705 values['c'] = careful_string_filter (summary.get());
707 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
711 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
713 dcp::NameFormat::Map values;
715 values['r'] = raw_convert<string> (reel_index + 1);
716 values['n'] = raw_convert<string> (reel_count);
718 values['c'] = careful_string_filter (summary.get());
720 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
724 relaxed_string_to_float (string s)
727 boost::algorithm::replace_all (s, ",", ".");
728 return lexical_cast<float> (s);
729 } catch (bad_lexical_cast &) {
730 boost::algorithm::replace_all (s, ".", ",");
731 return lexical_cast<float> (s);
736 careful_string_filter (string s)
738 /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
739 There's no apparent list of what really is allowed, so this is a guess.
740 Safety first and all that.
744 string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
745 for (size_t i = 0; i < s.size(); ++i) {
746 if (allowed.find (s[i]) != string::npos) {
754 /** @param mapped List of mapped audio channels from a Film.
755 * @param channels Total number of channels in the Film.
756 * @return First: number of non-LFE channels, second: number of LFE channels.
759 audio_channel_types (list<int> mapped, int channels)
764 BOOST_FOREACH (int i, mapped) {
766 /* This channel is mapped but is not included in the DCP */
770 if (static_cast<dcp::Channel> (i) == dcp::LFE) {
777 return make_pair (non_lfe, lfe);
780 shared_ptr<AudioBuffers>
781 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
783 shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
784 mapped->make_silent ();
786 for (int i = 0; i < map.input_channels(); ++i) {
787 for (int j = 0; j < mapped->channels(); ++j) {
788 if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
789 mapped->accumulate_channel (
792 static_cast<dcp::Channel> (j),
793 map.get (i, static_cast<dcp::Channel> (j))
803 increment_eyes (Eyes e)
805 if (e == EYES_LEFT) {
813 checked_fwrite (void const * ptr, size_t size, FILE* stream, boost::filesystem::path path)
815 size_t N = fwrite (ptr, 1, size, stream);
817 if (ferror(stream)) {
819 throw FileError (String::compose("fwrite error %1", errno), path);
822 throw FileError ("Unexpected short write", path);
828 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
830 size_t N = fread (ptr, 1, size, stream);
832 if (ferror(stream)) {
834 throw FileError (String::compose("fread error %1", errno), path);
837 throw FileError ("Unexpected short read", path);
843 utf8_strlen (string s)
845 size_t const len = s.length ();
847 for (size_t i = 0; i < len; ++i) {
848 unsigned char c = s[i];
849 if ((c & 0xe0) == 0xc0) {
851 } else if ((c & 0xf0) == 0xe0) {
853 } else if ((c & 0xf8) == 0xf0) {
862 day_of_week_to_string (boost::gregorian::greg_weekday d)
864 switch (d.as_enum()) {
865 case boost::date_time::Sunday:
867 case boost::date_time::Monday:
869 case boost::date_time::Tuesday:
871 case boost::date_time::Wednesday:
872 return _("Wednesday");
873 case boost::date_time::Thursday:
874 return _("Thursday");
875 case boost::date_time::Friday:
877 case boost::date_time::Saturday:
878 return _("Saturday");
881 return d.as_long_string ();
884 #ifdef DCPOMATIC_VARIANT_SWAROOP
886 /* Make up a key from the machine UUID */
890 dcp::Data key (dcpomatic::crypto_key_length());
891 memset (key.data().get(), 0, key.size());
892 string const magic = command_and_read ("dcpomatic2_uuid");
893 strncpy ((char *) key.data().get(), magic.c_str(), dcpomatic::crypto_key_length());
897 /* swaroop chain file format:
899 * 0 [int16_t] IV length
900 * 2 [int16_t] cert #1 length, or 0 for none
901 * 4 [int16_t] cert #2 length, or 0 for none
902 * 6 [int16_t] cert #3 length, or 0 for none
903 * 8 [int16_t] cert #4 length, or 0 for none
904 * 10 [int16_t] cert #5 length, or 0 for none
905 * 12 [int16_t] cert #6 length, or 0 for none
906 * 14 [int16_t] cert #7 length, or 0 for none
907 * 16 [int16_t] cert #8 length, or 0 for none
908 * 16 [int16_t] private key length
921 struct __attribute__ ((packed)) Header_ {
923 int16_t cert_length[8];
924 int16_t private_key_length;
927 typedef struct Header_ Header;
929 shared_ptr<dcp::CertificateChain>
930 read_swaroop_chain (boost::filesystem::path path)
932 dcp::Data data (path);
933 Header* header = (Header *) data.data().get();
934 uint8_t* p = data.data().get() + sizeof(Header);
936 dcp::Data iv (p, header->iv_length);
939 shared_ptr<dcp::CertificateChain> cc (new dcp::CertificateChain());
940 for (int i = 0; i < 8; ++i) {
941 if (header->cert_length[i] == 0) {
944 dcp::Data c(p, header->cert_length[i]);
946 cc->add (dcp::Certificate(dcpomatic::decrypt(c, key_from_uuid(), iv)));
949 dcp::Data k (p, header->private_key_length);
950 cc->set_key (dcpomatic::decrypt(k, key_from_uuid(), iv));
955 write_swaroop_chain (shared_ptr<const dcp::CertificateChain> chain, boost::filesystem::path output)
957 scoped_array<uint8_t> buffer (new uint8_t[65536]);
958 Header* header = (Header *) buffer.get();
959 memset (header, 0, sizeof(Header));
960 uint8_t* p = buffer.get() + sizeof(Header);
962 dcp::Data iv = dcpomatic::random_iv ();
963 header->iv_length = iv.size ();
964 memcpy (p, iv.data().get(), iv.size());
968 BOOST_FOREACH (dcp::Certificate i, chain->root_to_leaf()) {
969 dcp::Data e = dcpomatic::encrypt (i.certificate(true), key_from_uuid(), iv);
970 memcpy (p, e.data().get(), e.size());
972 DCPOMATIC_ASSERT (N < 8);
973 header->cert_length[N] = e.size ();
977 dcp::Data k = dcpomatic::encrypt (chain->key().get(), key_from_uuid(), iv);
978 memcpy (p, k.data().get(), k.size());
980 header->private_key_length = k.size ();
982 FILE* f = fopen_boost (output, "wb");
983 checked_fwrite (buffer.get(), p - buffer.get(), f, output);