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"
38 #include "compose.hpp"
39 #include <dcp/locale_convert.h>
41 #include <dcp/raw_convert.h>
42 #include <dcp/picture_asset.h>
43 #include <dcp/sound_asset.h>
44 #include <dcp/subtitle_asset.h>
46 #include <libavfilter/avfilter.h>
47 #include <libavcodec/avcodec.h>
49 #include <curl/curl.h>
50 #ifdef DCPOMATIC_GRAPHICS_MAGICK
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;
98 using dcp::raw_convert;
99 using dcp::locale_convert;
101 /** Path to our executable, required by the stacktrace stuff and filled
102 * in during App::onInit().
105 static boost::thread::id ui_thread;
106 static boost::filesystem::path backtrace_file;
108 /** Convert some number of seconds to a string representation
109 * in hours, minutes and seconds.
112 * @return String of the form H:M:S (where H is hours, M
113 * is minutes and S is seconds).
116 seconds_to_hms (int s)
124 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
128 /** @param s Number of seconds.
129 * @return String containing an approximate description of s (e.g. "about 2 hours")
132 seconds_to_approximate_hms (int s)
141 bool const hours = h > 0;
142 bool const minutes = h < 6 && m > 0;
143 bool const seconds = h == 0 && m < 10 && s > 0;
146 if (m > 30 && !minutes) {
147 /// TRANSLATORS: h here is an abbreviation for hours
148 ap += locale_convert<string>(h + 1) + _("h");
150 /// TRANSLATORS: h here is an abbreviation for hours
151 ap += locale_convert<string>(h) + _("h");
154 if (minutes || seconds) {
161 if (s > 30 && !seconds) {
162 /// TRANSLATORS: m here is an abbreviation for minutes
163 ap += locale_convert<string>(m + 1) + _("m");
165 /// TRANSLATORS: m here is an abbreviation for minutes
166 ap += locale_convert<string>(m) + _("m");
176 /// TRANSLATORS: s here is an abbreviation for seconds
177 ap += locale_convert<string>(s) + _("s");
184 seconds (struct timeval t)
186 return t.tv_sec + (double (t.tv_usec) / 1e6);
189 #ifdef DCPOMATIC_WINDOWS
191 /** Resolve symbol name and source location given the path to the executable */
193 addr2line (void const * const addr)
195 char addr2line_cmd[512] = { 0 };
196 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
197 return system(addr2line_cmd);
200 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
201 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
202 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
205 exception_handler(struct _EXCEPTION_POINTERS * info)
207 FILE* f = fopen_boost (backtrace_file, "w");
208 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
211 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
212 CONTEXT* context = info->ContextRecord;
213 SymInitialize (GetCurrentProcess (), 0, true);
215 STACKFRAME frame = { 0 };
217 /* setup initial stack frame */
219 frame.AddrPC.Offset = context->Rip;
220 frame.AddrStack.Offset = context->Rsp;
221 frame.AddrFrame.Offset = context->Rbp;
223 frame.AddrPC.Offset = context->Eip;
224 frame.AddrStack.Offset = context->Esp;
225 frame.AddrFrame.Offset = context->Ebp;
227 frame.AddrPC.Mode = AddrModeFlat;
228 frame.AddrStack.Mode = AddrModeFlat;
229 frame.AddrFrame.Mode = AddrModeFlat;
233 IMAGE_FILE_MACHINE_I386,
234 GetCurrentProcess (),
239 SymFunctionTableAccess,
244 addr2line((void *) frame.AddrPC.Offset);
248 addr2line ((void *) info->ContextRecord->Rip);
250 addr2line ((void *) info->ContextRecord->Eip);
254 return EXCEPTION_CONTINUE_SEARCH;
259 set_backtrace_file (boost::filesystem::path p)
264 /** This is called when there is an unhandled exception. Any
265 * backtrace in this function is useless on Windows as the stack has
266 * already been unwound from the throw; we have the gdb wrap hack to
273 static bool tried_throw = false;
274 // try once to re-throw currently active exception
280 catch (const std::exception &e) {
281 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
282 << e.what() << std::endl;
285 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
293 dcpomatic_setup_path_encoding ()
295 #ifdef DCPOMATIC_WINDOWS
296 /* Dark voodoo which, I think, gets boost::filesystem::path to
297 correctly convert UTF-8 strings to paths, and also paths
298 back to UTF-8 strings (on path::string()).
300 After this, constructing boost::filesystem::paths from strings
301 converts from UTF-8 to UTF-16 inside the path. Then
302 path::string().c_str() gives UTF-8 and
303 path::c_str() gives UTF-16.
305 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
306 so things are much simpler.
308 std::locale::global (boost::locale::generator().generate (""));
309 boost::filesystem::path::imbue (std::locale ());
313 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
314 * Must be called from the UI thread, if there is one.
319 #ifdef DCPOMATIC_WINDOWS
320 boost::filesystem::path p = g_get_user_config_dir ();
321 p /= "backtrace.txt";
322 set_backtrace_file (p);
323 SetUnhandledExceptionFilter(exception_handler);
326 avfilter_register_all ();
329 /* Add our lib directory to the libltdl search path so that
330 xmlsec can find xmlsec1-openssl.
332 boost::filesystem::path lib = app_contents ();
334 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
337 set_terminate (terminate);
342 Ratio::setup_ratios ();
343 PresetColourConversion::setup_colour_conversion_presets ();
344 VideoContentScale::setup_scales ();
345 DCPContentType::setup_dcp_content_types ();
346 Filter::setup_filters ();
347 CinemaSoundProcessor::setup_cinema_sound_processors ();
348 AudioProcessor::setup_audio_processors ();
350 curl_global_init (CURL_GLOBAL_ALL);
352 #ifdef DCPOMATIC_GRAPHICS_MAGICK
353 Magick::InitializeMagick (0);
356 ui_thread = boost::this_thread::get_id ();
359 #ifdef DCPOMATIC_WINDOWS
360 boost::filesystem::path
364 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
365 boost::filesystem::path p (buffer);
366 p = p.parent_path ();
367 p = p.parent_path ();
374 boost::filesystem::path
377 return "DCP-o-matic 2.app/Contents/Resources";
382 dcpomatic_setup_gettext_i18n (string lang)
384 #ifdef DCPOMATIC_LINUX
388 if (!lang.empty ()) {
389 /* Override our environment language. Note that the caller must not
390 free the string passed into putenv().
392 string s = String::compose ("LANGUAGE=%1", lang);
393 putenv (strdup (s.c_str ()));
394 s = String::compose ("LANG=%1", lang);
395 putenv (strdup (s.c_str ()));
396 s = String::compose ("LC_ALL=%1", lang);
397 putenv (strdup (s.c_str ()));
400 setlocale (LC_ALL, "");
401 textdomain ("libdcpomatic2");
403 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
404 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
405 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
408 #ifdef DCPOMATIC_LINUX
409 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
413 /** Compute a digest of the first and last `size' bytes of a set of files. */
415 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
417 boost::scoped_array<char> buffer (new char[size]);
421 boost::uintmax_t to_do = size;
422 char* p = buffer.get ();
424 while (i < int64_t (files.size()) && to_do > 0) {
425 FILE* f = fopen_boost (files[i], "rb");
427 throw OpenFileError (files[i].string(), errno, true);
430 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
431 fread (p, 1, this_time, f);
438 digester.add (buffer.get(), size - to_do);
443 i = files.size() - 1;
444 while (i >= 0 && to_do > 0) {
445 FILE* f = fopen_boost (files[i], "rb");
447 throw OpenFileError (files[i].string(), errno, true);
450 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
451 dcpomatic_fseek (f, -this_time, SEEK_END);
452 fread (p, 1, this_time, f);
459 digester.add (buffer.get(), size - to_do);
461 return digester.get ();
464 /** Round a number up to the nearest multiple of another number.
466 * @param stride Array of numbers to round, indexed by c.
467 * @param t Multiple to round to.
468 * @return Rounded number.
471 stride_round_up (int c, int const * stride, int t)
473 int const a = stride[c] + (t - 1);
477 /** Trip an assert if the caller is not in the UI thread */
481 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
485 audio_channel_name (int c)
487 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
489 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
490 /// enhancement channel (sub-woofer).
491 string const channels[] = {
498 _("Hearing impaired"),
499 _("Visually impaired"),
502 _("Left rear surround"),
503 _("Right rear surround"),
505 _("D-BOX secondary"),
514 short_audio_channel_name (int c)
516 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
518 /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
519 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
520 /// VI is the visually-impaired audio track (audio describe). DBP is the D-BOX
521 /// primary channel and DBS is the D-BOX secondary channel.
522 string const channels[] = {
546 valid_image_file (boost::filesystem::path f)
548 if (boost::starts_with (f.leaf().string(), "._")) {
552 string ext = f.extension().string();
553 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
555 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
556 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
557 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
562 valid_sound_file (boost::filesystem::path f)
564 if (boost::starts_with (f.leaf().string(), "._")) {
568 string ext = f.extension().string();
569 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
570 return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
574 valid_j2k_file (boost::filesystem::path f)
576 string ext = f.extension().string();
577 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
578 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
582 tidy_for_filename (string f)
584 boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
589 fit_ratio_within (float ratio, dcp::Size full_frame)
591 if (ratio < full_frame.ratio ()) {
592 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
595 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
599 wrapped_av_malloc (size_t s)
601 void* p = av_malloc (s);
609 split_get_request (string url)
612 AWAITING_QUESTION_MARK,
615 } state = AWAITING_QUESTION_MARK;
617 map<string, string> r;
620 for (size_t i = 0; i < url.length(); ++i) {
622 case AWAITING_QUESTION_MARK:
637 r.insert (make_pair (k, v));
647 if (state == VALUE) {
648 r.insert (make_pair (k, v));
655 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
657 dcp::NameFormat::Map values;
659 values['r'] = raw_convert<string> (reel_index + 1);
660 values['n'] = raw_convert<string> (reel_count);
662 values['c'] = careful_string_filter (summary.get());
664 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
668 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
670 dcp::NameFormat::Map values;
672 values['r'] = raw_convert<string> (reel_index + 1);
673 values['n'] = raw_convert<string> (reel_count);
675 values['c'] = careful_string_filter (summary.get());
677 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
681 relaxed_string_to_float (string s)
684 boost::algorithm::replace_all (s, ",", ".");
685 return lexical_cast<float> (s);
686 } catch (bad_lexical_cast) {
687 boost::algorithm::replace_all (s, ".", ",");
688 return lexical_cast<float> (s);
693 careful_string_filter (string s)
695 /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
696 There's no apparent list of what really is allowed, so this is a guess.
697 Safety first and all that.
701 string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.";
702 for (size_t i = 0; i < s.size(); ++i) {
703 if (allowed.find (s[i]) != string::npos) {
711 /** @param mapped List of mapped audio channels from a Film.
712 * @param channels Total number of channels in the Film.
713 * @return First: number of non-LFE channels, second: number of LFE channels.
716 audio_channel_types (list<int> mapped, int channels)
721 BOOST_FOREACH (int i, mapped) {
723 /* This channel is mapped but is not included in the DCP */
727 if (static_cast<dcp::Channel> (i) == dcp::LFE) {
734 return make_pair (non_lfe, lfe);