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 <libavformat/avformat.h>
48 #include <libavcodec/avcodec.h>
50 #include <curl/curl.h>
51 #ifdef DCPOMATIC_GRAPHICS_MAGICK
55 #include <pangomm/init.h>
56 #include <boost/algorithm/string.hpp>
57 #include <boost/range/algorithm/replace_if.hpp>
58 #include <boost/thread.hpp>
59 #include <boost/filesystem.hpp>
60 #ifdef DCPOMATIC_WINDOWS
61 #include <boost/locale.hpp>
70 #ifdef DCPOMATIC_POSIX
91 using std::set_terminate;
93 using boost::shared_ptr;
95 using boost::optional;
96 using boost::lexical_cast;
97 using boost::bad_lexical_cast;
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 static boost::thread::id ui_thread;
107 static boost::filesystem::path backtrace_file;
109 /** Convert some number of seconds to a string representation
110 * in hours, minutes and seconds.
113 * @return String of the form H:M:S (where H is hours, M
114 * is minutes and S is seconds).
117 seconds_to_hms (int s)
125 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
129 /** @param s Number of seconds.
130 * @return String containing an approximate description of s (e.g. "about 2 hours")
133 seconds_to_approximate_hms (int s)
142 bool const hours = h > 0;
143 bool const minutes = h < 6 && m > 0;
144 bool const seconds = h == 0 && m < 10 && s > 0;
147 if (m > 30 && !minutes) {
148 /// TRANSLATORS: h here is an abbreviation for hours
149 ap += locale_convert<string>(h + 1) + _("h");
151 /// TRANSLATORS: h here is an abbreviation for hours
152 ap += locale_convert<string>(h) + _("h");
155 if (minutes || seconds) {
162 if (s > 30 && !seconds) {
163 /// TRANSLATORS: m here is an abbreviation for minutes
164 ap += locale_convert<string>(m + 1) + _("m");
166 /// TRANSLATORS: m here is an abbreviation for minutes
167 ap += locale_convert<string>(m) + _("m");
177 /// TRANSLATORS: s here is an abbreviation for seconds
178 ap += locale_convert<string>(s) + _("s");
185 seconds (struct timeval t)
187 return t.tv_sec + (double (t.tv_usec) / 1e6);
190 #ifdef DCPOMATIC_WINDOWS
192 /** Resolve symbol name and source location given the path to the executable */
194 addr2line (void const * const addr)
196 char addr2line_cmd[512] = { 0 };
197 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
198 return system(addr2line_cmd);
201 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
202 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
203 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
206 exception_handler(struct _EXCEPTION_POINTERS * info)
208 FILE* f = fopen_boost (backtrace_file, "w");
209 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
212 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
213 CONTEXT* context = info->ContextRecord;
214 SymInitialize (GetCurrentProcess (), 0, true);
216 STACKFRAME frame = { 0 };
218 /* setup initial stack frame */
220 frame.AddrPC.Offset = context->Rip;
221 frame.AddrStack.Offset = context->Rsp;
222 frame.AddrFrame.Offset = context->Rbp;
224 frame.AddrPC.Offset = context->Eip;
225 frame.AddrStack.Offset = context->Esp;
226 frame.AddrFrame.Offset = context->Ebp;
228 frame.AddrPC.Mode = AddrModeFlat;
229 frame.AddrStack.Mode = AddrModeFlat;
230 frame.AddrFrame.Mode = AddrModeFlat;
234 IMAGE_FILE_MACHINE_I386,
235 GetCurrentProcess (),
240 SymFunctionTableAccess,
245 addr2line((void *) frame.AddrPC.Offset);
249 addr2line ((void *) info->ContextRecord->Rip);
251 addr2line ((void *) info->ContextRecord->Eip);
255 return EXCEPTION_CONTINUE_SEARCH;
260 set_backtrace_file (boost::filesystem::path p)
265 /** This is called when there is an unhandled exception. Any
266 * backtrace in this function is useless on Windows as the stack has
267 * already been unwound from the throw; we have the gdb wrap hack to
274 static bool tried_throw = false;
275 // try once to re-throw currently active exception
281 catch (const std::exception &e) {
282 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
283 << e.what() << std::endl;
286 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
294 dcpomatic_setup_path_encoding ()
296 #ifdef DCPOMATIC_WINDOWS
297 /* Dark voodoo which, I think, gets boost::filesystem::path to
298 correctly convert UTF-8 strings to paths, and also paths
299 back to UTF-8 strings (on path::string()).
301 After this, constructing boost::filesystem::paths from strings
302 converts from UTF-8 to UTF-16 inside the path. Then
303 path::string().c_str() gives UTF-8 and
304 path::c_str() gives UTF-16.
306 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
307 so things are much simpler.
309 std::locale::global (boost::locale::generator().generate (""));
310 boost::filesystem::path::imbue (std::locale ());
314 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
315 * Must be called from the UI thread, if there is one.
320 #ifdef DCPOMATIC_WINDOWS
321 boost::filesystem::path p = g_get_user_config_dir ();
322 p /= "backtrace.txt";
323 set_backtrace_file (p);
324 SetUnhandledExceptionFilter(exception_handler);
328 avfilter_register_all ();
331 /* Add our lib directory to the libltdl search path so that
332 xmlsec can find xmlsec1-openssl.
334 boost::filesystem::path lib = app_contents ();
336 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
339 set_terminate (terminate);
344 Ratio::setup_ratios ();
345 PresetColourConversion::setup_colour_conversion_presets ();
346 VideoContentScale::setup_scales ();
347 DCPContentType::setup_dcp_content_types ();
348 Filter::setup_filters ();
349 CinemaSoundProcessor::setup_cinema_sound_processors ();
350 AudioProcessor::setup_audio_processors ();
352 curl_global_init (CURL_GLOBAL_ALL);
354 #ifdef DCPOMATIC_GRAPHICS_MAGICK
355 Magick::InitializeMagick (0);
358 ui_thread = boost::this_thread::get_id ();
361 #ifdef DCPOMATIC_WINDOWS
362 boost::filesystem::path
366 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
367 boost::filesystem::path p (buffer);
368 p = p.parent_path ();
369 p = p.parent_path ();
376 boost::filesystem::path
379 return "DCP-o-matic 2.app/Contents/Resources";
384 dcpomatic_setup_gettext_i18n (string lang)
386 #ifdef DCPOMATIC_LINUX
390 if (!lang.empty ()) {
391 /* Override our environment language. Note that the caller must not
392 free the string passed into putenv().
394 string s = String::compose ("LANGUAGE=%1", lang);
395 putenv (strdup (s.c_str ()));
396 s = String::compose ("LANG=%1", lang);
397 putenv (strdup (s.c_str ()));
398 s = String::compose ("LC_ALL=%1", lang);
399 putenv (strdup (s.c_str ()));
402 setlocale (LC_ALL, "");
403 textdomain ("libdcpomatic2");
405 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
406 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
407 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
410 #ifdef DCPOMATIC_LINUX
411 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
415 /** Compute a digest of the first and last `size' bytes of a set of files. */
417 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
419 boost::scoped_array<char> buffer (new char[size]);
423 boost::uintmax_t to_do = size;
424 char* p = buffer.get ();
426 while (i < int64_t (files.size()) && to_do > 0) {
427 FILE* f = fopen_boost (files[i], "rb");
429 throw OpenFileError (files[i].string(), errno, true);
432 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
433 fread (p, 1, this_time, f);
440 digester.add (buffer.get(), size - to_do);
445 i = files.size() - 1;
446 while (i >= 0 && to_do > 0) {
447 FILE* f = fopen_boost (files[i], "rb");
449 throw OpenFileError (files[i].string(), errno, true);
452 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
453 dcpomatic_fseek (f, -this_time, SEEK_END);
454 fread (p, 1, this_time, f);
461 digester.add (buffer.get(), size - to_do);
463 return digester.get ();
466 /** Round a number up to the nearest multiple of another number.
468 * @param stride Array of numbers to round, indexed by c.
469 * @param t Multiple to round to.
470 * @return Rounded number.
473 stride_round_up (int c, int const * stride, int t)
475 int const a = stride[c] + (t - 1);
479 /** Trip an assert if the caller is not in the UI thread */
483 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
487 audio_channel_name (int c)
489 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
491 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
492 /// enhancement channel (sub-woofer).
493 string const channels[] = {
500 _("Hearing impaired"),
501 _("Visually impaired"),
504 _("Left rear surround"),
505 _("Right rear surround"),
507 _("D-BOX secondary"),
516 short_audio_channel_name (int c)
518 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
520 /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
521 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
522 /// VI is the visually-impaired audio track (audio describe). DBP is the D-BOX
523 /// primary channel and DBS is the D-BOX secondary channel.
524 string const channels[] = {
548 valid_image_file (boost::filesystem::path f)
550 if (boost::starts_with (f.leaf().string(), "._")) {
554 string ext = f.extension().string();
555 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
557 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
558 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
559 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
564 valid_sound_file (boost::filesystem::path f)
566 if (boost::starts_with (f.leaf().string(), "._")) {
570 string ext = f.extension().string();
571 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
572 return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
576 valid_j2k_file (boost::filesystem::path f)
578 string ext = f.extension().string();
579 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
580 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
584 tidy_for_filename (string f)
586 boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
591 fit_ratio_within (float ratio, dcp::Size full_frame)
593 if (ratio < full_frame.ratio ()) {
594 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
597 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
601 wrapped_av_malloc (size_t s)
603 void* p = av_malloc (s);
611 split_get_request (string url)
614 AWAITING_QUESTION_MARK,
617 } state = AWAITING_QUESTION_MARK;
619 map<string, string> r;
622 for (size_t i = 0; i < url.length(); ++i) {
624 case AWAITING_QUESTION_MARK:
639 r.insert (make_pair (k, v));
649 if (state == VALUE) {
650 r.insert (make_pair (k, v));
657 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
659 dcp::NameFormat::Map values;
661 values['r'] = raw_convert<string> (reel_index + 1);
662 values['n'] = raw_convert<string> (reel_count);
664 values['c'] = careful_string_filter (summary.get());
666 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
670 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
672 dcp::NameFormat::Map values;
674 values['r'] = raw_convert<string> (reel_index + 1);
675 values['n'] = raw_convert<string> (reel_count);
677 values['c'] = careful_string_filter (summary.get());
679 return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
683 relaxed_string_to_float (string s)
686 boost::algorithm::replace_all (s, ",", ".");
687 return lexical_cast<float> (s);
688 } catch (bad_lexical_cast) {
689 boost::algorithm::replace_all (s, ".", ",");
690 return lexical_cast<float> (s);
695 careful_string_filter (string s)
697 /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
698 There's no apparent list of what really is allowed, so this is a guess.
699 Safety first and all that.
703 string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.";
704 for (size_t i = 0; i < s.size(); ++i) {
705 if (allowed.find (s[i]) != string::npos) {
713 /** @param mapped List of mapped audio channels from a Film.
714 * @param channels Total number of channels in the Film.
715 * @return First: number of non-LFE channels, second: number of LFE channels.
718 audio_channel_types (list<int> mapped, int channels)
723 BOOST_FOREACH (int i, mapped) {
725 /* This channel is mapped but is not included in the DCP */
729 if (static_cast<dcp::Channel> (i) == dcp::LFE) {
736 return make_pair (non_lfe, lfe);