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 <dcp/locale_convert.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>
48 #include <libavfilter/avfilter.h>
49 #include <libavformat/avformat.h>
50 #include <libavcodec/avcodec.h>
52 #include <curl/curl.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>
69 #ifdef DCPOMATIC_POSIX
90 using std::set_terminate;
92 using boost::shared_ptr;
94 using boost::optional;
95 using boost::lexical_cast;
96 using boost::bad_lexical_cast;
97 using boost::scoped_array;
99 using dcp::raw_convert;
100 using dcp::locale_convert;
102 /** Path to our executable, required by the stacktrace stuff and filled
103 * in during App::onInit().
106 bool is_batch_converter = false;
107 static boost::thread::id ui_thread;
108 static boost::filesystem::path backtrace_file;
110 /** Convert some number of seconds to a string representation
111 * in hours, minutes and seconds.
114 * @return String of the form H:M:S (where H is hours, M
115 * is minutes and S is seconds).
118 seconds_to_hms (int s)
126 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
131 time_to_hmsf (DCPTime time, Frame rate)
133 Frame f = time.frames_round (rate);
142 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d.%d", h, m, s, static_cast<int>(f));
146 /** @param s Number of seconds.
147 * @return String containing an approximate description of s (e.g. "about 2 hours")
150 seconds_to_approximate_hms (int s)
160 bool minutes = h < 6 && m > 0;
161 bool seconds = h == 0 && m < 10 && s > 0;
163 if (m > 30 && !minutes) {
164 /* round up the hours */
167 if (s > 30 && !seconds) {
168 /* round up the minutes */
178 /// TRANSLATORS: h here is an abbreviation for hours
179 ap += locale_convert<string>(h) + _("h");
181 if (minutes || seconds) {
187 /// TRANSLATORS: m here is an abbreviation for minutes
188 ap += locale_convert<string>(m) + _("m");
197 /// TRANSLATORS: s here is an abbreviation for seconds
198 ap += locale_convert<string>(s) + _("s");
205 seconds (struct timeval t)
207 return t.tv_sec + (double (t.tv_usec) / 1e6);
210 #ifdef DCPOMATIC_WINDOWS
212 /** Resolve symbol name and source location given the path to the executable */
214 addr2line (void const * const addr)
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);
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/
226 exception_handler(struct _EXCEPTION_POINTERS * info)
228 FILE* f = fopen_boost (backtrace_file, "w");
229 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
232 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
233 CONTEXT* context = info->ContextRecord;
234 SymInitialize (GetCurrentProcess (), 0, true);
236 STACKFRAME frame = { 0 };
238 /* setup initial stack frame */
240 frame.AddrPC.Offset = context->Rip;
241 frame.AddrStack.Offset = context->Rsp;
242 frame.AddrFrame.Offset = context->Rbp;
244 frame.AddrPC.Offset = context->Eip;
245 frame.AddrStack.Offset = context->Esp;
246 frame.AddrFrame.Offset = context->Ebp;
248 frame.AddrPC.Mode = AddrModeFlat;
249 frame.AddrStack.Mode = AddrModeFlat;
250 frame.AddrFrame.Mode = AddrModeFlat;
254 IMAGE_FILE_MACHINE_I386,
255 GetCurrentProcess (),
260 SymFunctionTableAccess,
265 addr2line((void *) frame.AddrPC.Offset);
269 addr2line ((void *) info->ContextRecord->Rip);
271 addr2line ((void *) info->ContextRecord->Eip);
275 return EXCEPTION_CONTINUE_SEARCH;
280 set_backtrace_file (boost::filesystem::path p)
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
294 static bool tried_throw = false;
295 // try once to re-throw currently active exception
301 catch (const std::exception &e) {
302 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
303 << e.what() << std::endl;
306 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
314 dcpomatic_setup_path_encoding ()
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()).
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.
326 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
327 so things are much simpler.
329 std::locale::global (boost::locale::generator().generate (""));
330 boost::filesystem::path::imbue (std::locale ());
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.
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);
348 avfilter_register_all ();
351 /* Add our library directory to the libltdl search path so that
352 xmlsec can find xmlsec1-openssl.
354 boost::filesystem::path lib = app_contents ();
356 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
359 set_terminate (terminate);
361 #ifdef DCPOMATIC_WINDOWS
362 putenv ("PANGOCAIRO_BACKEND=fontconfig");
363 putenv (String::compose("FONTCONFIG_PATH=%1", shared_path().string()).c_str());
369 Ratio::setup_ratios ();
370 PresetColourConversion::setup_colour_conversion_presets ();
371 VideoContentScale::setup_scales ();
372 DCPContentType::setup_dcp_content_types ();
373 Filter::setup_filters ();
374 CinemaSoundProcessor::setup_cinema_sound_processors ();
375 AudioProcessor::setup_audio_processors ();
377 curl_global_init (CURL_GLOBAL_ALL);
379 ui_thread = boost::this_thread::get_id ();
382 #ifdef DCPOMATIC_WINDOWS
383 boost::filesystem::path
387 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
388 boost::filesystem::path p (buffer);
389 p = p.parent_path ();
390 p = p.parent_path ();
397 boost::filesystem::path
400 return "DCP-o-matic 2.app/Contents/Resources";
405 dcpomatic_setup_gettext_i18n (string lang)
407 #ifdef DCPOMATIC_LINUX
411 if (!lang.empty ()) {
412 /* Override our environment language. Note that the caller must not
413 free the string passed into putenv().
415 string s = String::compose ("LANGUAGE=%1", lang);
416 putenv (strdup (s.c_str ()));
417 s = String::compose ("LANG=%1", lang);
418 putenv (strdup (s.c_str ()));
419 s = String::compose ("LC_ALL=%1", lang);
420 putenv (strdup (s.c_str ()));
423 setlocale (LC_ALL, "");
424 textdomain ("libdcpomatic2");
426 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
427 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
428 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
431 #ifdef DCPOMATIC_LINUX
432 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
436 /** Compute a digest of the first and last `size' bytes of a set of files. */
438 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
440 boost::scoped_array<char> buffer (new char[size]);
444 boost::uintmax_t to_do = size;
445 char* p = buffer.get ();
447 while (i < int64_t (files.size()) && to_do > 0) {
448 FILE* f = fopen_boost (files[i], "rb");
450 throw OpenFileError (files[i].string(), errno, true);
453 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
454 checked_fread (p, this_time, f, files[i]);
461 digester.add (buffer.get(), size - to_do);
466 i = files.size() - 1;
467 while (i >= 0 && to_do > 0) {
468 FILE* f = fopen_boost (files[i], "rb");
470 throw OpenFileError (files[i].string(), errno, true);
473 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
474 dcpomatic_fseek (f, -this_time, SEEK_END);
475 checked_fread (p, this_time, f, files[i]);
482 digester.add (buffer.get(), size - to_do);
484 return digester.get ();
487 /** Round a number up to the nearest multiple of another number.
489 * @param stride Array of numbers to round, indexed by c.
490 * @param t Multiple to round to.
491 * @return Rounded number.
494 stride_round_up (int c, int const * stride, int t)
496 int const a = stride[c] + (t - 1);
500 /** Trip an assert if the caller is not in the UI thread */
504 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
508 audio_channel_name (int c)
510 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
512 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
513 /// enhancement channel (sub-woofer).
514 string const channels[] = {
521 _("Hearing impaired"),
522 _("Visually impaired"),
525 _("Left rear surround"),
526 _("Right rear surround"),
528 _("D-BOX secondary"),
537 short_audio_channel_name (int c)
539 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
541 /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
542 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
543 /// VI is the visually-impaired audio track (audio describe). DBP is the D-BOX
544 /// primary channel and DBS is the D-BOX secondary channel.
545 string const channels[] = {
569 valid_image_file (boost::filesystem::path f)
571 if (boost::starts_with (f.leaf().string(), "._")) {
575 string ext = f.extension().string();
576 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
578 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
579 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
580 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr" ||
586 valid_sound_file (boost::filesystem::path f)
588 if (boost::starts_with (f.leaf().string(), "._")) {
592 string ext = f.extension().string();
593 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
594 return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
598 valid_j2k_file (boost::filesystem::path f)
600 string ext = f.extension().string();
601 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
602 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
606 tidy_for_filename (string f)
608 boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
613 fit_ratio_within (float ratio, dcp::Size full_frame)
615 if (ratio < full_frame.ratio ()) {
616 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
619 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
623 wrapped_av_malloc (size_t s)
625 void* p = av_malloc (s);
633 split_get_request (string url)
636 AWAITING_QUESTION_MARK,
639 } state = AWAITING_QUESTION_MARK;
641 map<string, string> r;
644 for (size_t i = 0; i < url.length(); ++i) {
646 case AWAITING_QUESTION_MARK:
661 r.insert (make_pair (k, v));
671 if (state == VALUE) {
672 r.insert (make_pair (k, v));
679 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
681 dcp::NameFormat::Map values;
683 values['r'] = raw_convert<string> (reel_index + 1);
684 values['n'] = raw_convert<string> (reel_count);
686 values['c'] = careful_string_filter (summary.get());
688 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
692 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
694 dcp::NameFormat::Map values;
696 values['r'] = raw_convert<string> (reel_index + 1);
697 values['n'] = raw_convert<string> (reel_count);
699 values['c'] = careful_string_filter (summary.get());
701 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
705 relaxed_string_to_float (string s)
708 boost::algorithm::replace_all (s, ",", ".");
709 return lexical_cast<float> (s);
710 } catch (bad_lexical_cast) {
711 boost::algorithm::replace_all (s, ".", ",");
712 return lexical_cast<float> (s);
717 careful_string_filter (string s)
719 /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
720 There's no apparent list of what really is allowed, so this is a guess.
721 Safety first and all that.
725 string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
726 for (size_t i = 0; i < s.size(); ++i) {
727 if (allowed.find (s[i]) != string::npos) {
735 /** @param mapped List of mapped audio channels from a Film.
736 * @param channels Total number of channels in the Film.
737 * @return First: number of non-LFE channels, second: number of LFE channels.
740 audio_channel_types (list<int> mapped, int channels)
745 BOOST_FOREACH (int i, mapped) {
747 /* This channel is mapped but is not included in the DCP */
751 if (static_cast<dcp::Channel> (i) == dcp::LFE) {
758 return make_pair (non_lfe, lfe);
761 shared_ptr<AudioBuffers>
762 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
764 shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
765 mapped->make_silent ();
767 for (int i = 0; i < map.input_channels(); ++i) {
768 for (int j = 0; j < mapped->channels(); ++j) {
769 if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
770 mapped->accumulate_channel (
773 static_cast<dcp::Channel> (j),
774 map.get (i, static_cast<dcp::Channel> (j))
784 increment_eyes (Eyes e)
786 if (e == EYES_LEFT) {
794 checked_fwrite (void const * ptr, size_t size, FILE* stream, boost::filesystem::path path)
796 size_t N = fwrite (ptr, 1, size, stream);
798 if (ferror(stream)) {
800 throw FileError (String::compose("fwrite error %1", errno), path);
803 throw FileError ("Unexpected short write", path);
809 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
811 size_t N = fread (ptr, 1, size, stream);
813 if (ferror(stream)) {
815 throw FileError (String::compose("fread error %1", errno), path);
818 throw FileError ("Unexpected short read", path);
824 utf8_strlen (string s)
826 size_t const len = s.length ();
828 for (size_t i = 0; i < len; ++i) {
829 unsigned char c = s[i];
830 if ((c & 0xe0) == 0xc0) {
832 } else if ((c & 0xf0) == 0xe0) {
834 } else if ((c & 0xf8) == 0xf0) {
843 day_of_week_to_string (boost::gregorian::greg_weekday d)
845 switch (d.as_enum()) {
846 case boost::date_time::Sunday:
848 case boost::date_time::Monday:
850 case boost::date_time::Tuesday:
852 case boost::date_time::Wednesday:
853 return _("Wednesday");
854 case boost::date_time::Thursday:
855 return _("Thursday");
856 case boost::date_time::Friday:
858 case boost::date_time::Saturday:
859 return _("Saturday");
862 return d.as_long_string ();
865 #ifdef DCPOMATIC_VARIANT_SWAROOP
867 /* Make up a key from the machine UUID */
871 dcp::Data key (dcpomatic::crypto_key_length());
872 memset (key.data().get(), 0, key.size());
873 string const magic = command_and_read ("dcpomatic2_uuid");
874 strncpy ((char *) key.data().get(), magic.c_str(), dcpomatic::crypto_key_length());
878 /* swaroop chain file format:
880 * 0 [int16_t] IV length
881 * 2 [int16_t] cert #1 length, or 0 for none
882 * 4 [int16_t] cert #2 length, or 0 for none
883 * 6 [int16_t] cert #3 length, or 0 for none
884 * 8 [int16_t] cert #4 length, or 0 for none
885 * 10 [int16_t] cert #5 length, or 0 for none
886 * 12 [int16_t] cert #6 length, or 0 for none
887 * 14 [int16_t] cert #7 length, or 0 for none
888 * 16 [int16_t] cert #8 length, or 0 for none
889 * 16 [int16_t] private key length
902 struct __attribute__ ((packed)) Header_ {
904 int16_t cert_length[8];
905 int16_t private_key_length;
908 typedef struct Header_ Header;
910 shared_ptr<dcp::CertificateChain>
911 read_swaroop_chain (boost::filesystem::path path)
913 dcp::Data data (path);
914 Header* header = (Header *) data.data().get();
915 uint8_t* p = data.data().get() + sizeof(Header);
917 dcp::Data iv (p, header->iv_length);
920 shared_ptr<dcp::CertificateChain> cc (new dcp::CertificateChain());
921 for (int i = 0; i < 8; ++i) {
922 if (header->cert_length[i] == 0) {
925 dcp::Data c(p, header->cert_length[i]);
927 cc->add (dcp::Certificate(dcpomatic::decrypt(c, key_from_uuid(), iv)));
930 dcp::Data k (p, header->private_key_length);
931 cc->set_key (dcpomatic::decrypt(k, key_from_uuid(), iv));
936 write_swaroop_chain (shared_ptr<const dcp::CertificateChain> chain, boost::filesystem::path output)
938 scoped_array<uint8_t> buffer (new uint8_t[65536]);
939 Header* header = (Header *) buffer.get();
940 memset (header, 0, sizeof(Header));
941 uint8_t* p = buffer.get() + sizeof(Header);
943 dcp::Data iv = dcpomatic::random_iv ();
944 header->iv_length = iv.size ();
945 memcpy (p, iv.data().get(), iv.size());
949 BOOST_FOREACH (dcp::Certificate i, chain->root_to_leaf()) {
950 dcp::Data e = dcpomatic::encrypt (i.certificate(true), key_from_uuid(), iv);
951 memcpy (p, e.data().get(), e.size());
953 DCPOMATIC_ASSERT (N < 8);
954 header->cert_length[N] = e.size ();
958 dcp::Data k = dcpomatic::encrypt (chain->key().get(), key_from_uuid(), iv);
959 memcpy (p, k.data().get(), k.size());
961 header->private_key_length = k.size ();
963 FILE* f = fopen_boost (output, "wb");
964 checked_fwrite (buffer.get(), p - buffer.get(), f, output);