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"
40 #include <dcp/picture_asset.h>
41 #include <dcp/sound_asset.h>
42 #include <dcp/subtitle_asset.h>
44 #include <libavfilter/avfilter.h>
45 #include <libavcodec/avcodec.h>
47 #include <curl/curl.h>
48 #ifdef DCPOMATIC_GRAPHICS_MAGICK
52 #include <pangomm/init.h>
53 #include <boost/algorithm/string.hpp>
54 #include <boost/thread.hpp>
55 #include <boost/filesystem.hpp>
56 #ifdef DCPOMATIC_WINDOWS
57 #include <boost/locale.hpp>
66 #ifdef DCPOMATIC_POSIX
87 using std::set_terminate;
88 using boost::shared_ptr;
90 using boost::optional;
91 using boost::lexical_cast;
92 using boost::bad_lexical_cast;
95 /** Path to our executable, required by the stacktrace stuff and filled
96 * in during App::onInit().
99 static boost::thread::id ui_thread;
100 static boost::filesystem::path backtrace_file;
102 /** Convert some number of seconds to a string representation
103 * in hours, minutes and seconds.
106 * @return String of the form H:M:S (where H is hours, M
107 * is minutes and S is seconds).
110 seconds_to_hms (int s)
118 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
122 /** @param s Number of seconds.
123 * @return String containing an approximate description of s (e.g. "about 2 hours")
126 seconds_to_approximate_hms (int s)
135 bool const hours = h > 0;
136 bool const minutes = h < 6 && m > 0;
137 bool const seconds = h == 0 && m < 10 && s > 0;
140 if (m > 30 && !minutes) {
141 /// TRANSLATORS: h here is an abbreviation for hours
142 ap += raw_convert<string>(h + 1) + _("h");
144 /// TRANSLATORS: h here is an abbreviation for hours
145 ap += raw_convert<string>(h) + _("h");
148 if (minutes || seconds) {
155 if (s > 30 && !seconds) {
156 /// TRANSLATORS: m here is an abbreviation for minutes
157 ap += raw_convert<string>(m + 1) + _("m");
159 /// TRANSLATORS: m here is an abbreviation for minutes
160 ap += raw_convert<string>(m) + _("m");
170 /// TRANSLATORS: s here is an abbreviation for seconds
171 ap += raw_convert<string>(s) + _("s");
178 seconds (struct timeval t)
180 return t.tv_sec + (double (t.tv_usec) / 1e6);
183 #ifdef DCPOMATIC_WINDOWS
185 /** Resolve symbol name and source location given the path to the executable */
187 addr2line (void const * const addr)
189 char addr2line_cmd[512] = { 0 };
190 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
191 return system(addr2line_cmd);
194 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
195 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
196 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
199 exception_handler(struct _EXCEPTION_POINTERS * info)
201 FILE* f = fopen_boost (backtrace_file, "w");
202 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
205 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
206 CONTEXT* context = info->ContextRecord;
207 SymInitialize (GetCurrentProcess (), 0, true);
209 STACKFRAME frame = { 0 };
211 /* setup initial stack frame */
213 frame.AddrPC.Offset = context->Rip;
214 frame.AddrStack.Offset = context->Rsp;
215 frame.AddrFrame.Offset = context->Rbp;
217 frame.AddrPC.Offset = context->Eip;
218 frame.AddrStack.Offset = context->Esp;
219 frame.AddrFrame.Offset = context->Ebp;
221 frame.AddrPC.Mode = AddrModeFlat;
222 frame.AddrStack.Mode = AddrModeFlat;
223 frame.AddrFrame.Mode = AddrModeFlat;
227 IMAGE_FILE_MACHINE_I386,
228 GetCurrentProcess (),
233 SymFunctionTableAccess,
238 addr2line((void *) frame.AddrPC.Offset);
242 addr2line ((void *) info->ContextRecord->Rip);
244 addr2line ((void *) info->ContextRecord->Eip);
248 return EXCEPTION_CONTINUE_SEARCH;
253 set_backtrace_file (boost::filesystem::path p)
258 /** This is called when there is an unhandled exception. Any
259 * backtrace in this function is useless on Windows as the stack has
260 * already been unwound from the throw; we have the gdb wrap hack to
267 static bool tried_throw = false;
268 // try once to re-throw currently active exception
274 catch (const std::exception &e) {
275 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
276 << e.what() << std::endl;
279 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
287 dcpomatic_setup_path_encoding ()
289 #ifdef DCPOMATIC_WINDOWS
290 /* Dark voodoo which, I think, gets boost::filesystem::path to
291 correctly convert UTF-8 strings to paths, and also paths
292 back to UTF-8 strings (on path::string()).
294 After this, constructing boost::filesystem::paths from strings
295 converts from UTF-8 to UTF-16 inside the path. Then
296 path::string().c_str() gives UTF-8 and
297 path::c_str() gives UTF-16.
299 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
300 so things are much simpler.
302 std::locale::global (boost::locale::generator().generate (""));
303 boost::filesystem::path::imbue (std::locale ());
307 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
308 * Must be called from the UI thread, if there is one.
313 #ifdef DCPOMATIC_WINDOWS
314 boost::filesystem::path p = g_get_user_config_dir ();
315 p /= "backtrace.txt";
316 set_backtrace_file (p);
317 SetUnhandledExceptionFilter(exception_handler);
320 avfilter_register_all ();
323 /* Add our lib directory to the libltdl search path so that
324 xmlsec can find xmlsec1-openssl.
326 boost::filesystem::path lib = app_contents ();
328 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
331 set_terminate (terminate);
336 Ratio::setup_ratios ();
337 PresetColourConversion::setup_colour_conversion_presets ();
338 VideoContentScale::setup_scales ();
339 DCPContentType::setup_dcp_content_types ();
340 Filter::setup_filters ();
341 CinemaSoundProcessor::setup_cinema_sound_processors ();
342 AudioProcessor::setup_audio_processors ();
344 curl_global_init (CURL_GLOBAL_ALL);
346 #ifdef DCPOMATIC_GRAPHICS_MAGICK
347 Magick::InitializeMagick (0);
350 ui_thread = boost::this_thread::get_id ();
353 #ifdef DCPOMATIC_WINDOWS
354 boost::filesystem::path
358 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
359 boost::filesystem::path p (buffer);
360 p = p.parent_path ();
361 p = p.parent_path ();
368 boost::filesystem::path
371 return "DCP-o-matic 2.app/Contents/Resources";
376 dcpomatic_setup_gettext_i18n (string lang)
378 #ifdef DCPOMATIC_LINUX
382 if (!lang.empty ()) {
383 /* Override our environment language. Note that the caller must not
384 free the string passed into putenv().
386 string s = String::compose ("LANGUAGE=%1", lang);
387 putenv (strdup (s.c_str ()));
388 s = String::compose ("LANG=%1", lang);
389 putenv (strdup (s.c_str ()));
390 s = String::compose ("LC_ALL=%1", lang);
391 putenv (strdup (s.c_str ()));
394 setlocale (LC_ALL, "");
395 textdomain ("libdcpomatic2");
397 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
398 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
399 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
402 #ifdef DCPOMATIC_LINUX
403 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
407 /** Compute a digest of the first and last `size' bytes of a set of files. */
409 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
411 boost::scoped_array<char> buffer (new char[size]);
415 boost::uintmax_t to_do = size;
416 char* p = buffer.get ();
418 while (i < int64_t (files.size()) && to_do > 0) {
419 FILE* f = fopen_boost (files[i], "rb");
421 throw OpenFileError (files[i].string());
424 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
425 fread (p, 1, this_time, f);
432 digester.add (buffer.get(), size - to_do);
437 i = files.size() - 1;
438 while (i >= 0 && to_do > 0) {
439 FILE* f = fopen_boost (files[i], "rb");
441 throw OpenFileError (files[i].string());
444 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
445 dcpomatic_fseek (f, -this_time, SEEK_END);
446 fread (p, 1, this_time, f);
453 digester.add (buffer.get(), size - to_do);
455 return digester.get ();
458 /** Round a number up to the nearest multiple of another number.
460 * @param s Array of numbers to round, indexed by c.
461 * @param t Multiple to round to.
462 * @return Rounded number.
465 stride_round_up (int c, int const * stride, int t)
467 int const a = stride[c] + (t - 1);
471 /** Trip an assert if the caller is not in the UI thread */
475 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
479 audio_channel_name (int c)
481 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
483 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
484 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
485 /// VI is the visually-impaired audio track (audio describe).
486 string const channels[] = {
493 _("Hearing impaired"),
494 _("Visually impaired"),
497 _("Left rear surround"),
498 _("Right rear surround"),
500 _("D-BOX secondary"),
509 valid_image_file (boost::filesystem::path f)
511 if (boost::starts_with (f.leaf().string(), "._")) {
515 string ext = f.extension().string();
516 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
518 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
519 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
520 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
525 valid_j2k_file (boost::filesystem::path f)
527 string ext = f.extension().string();
528 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
529 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
533 tidy_for_filename (string f)
536 for (size_t i = 0; i < f.length(); ++i) {
537 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
548 fit_ratio_within (float ratio, dcp::Size full_frame)
550 if (ratio < full_frame.ratio ()) {
551 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
554 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
558 wrapped_av_malloc (size_t s)
560 void* p = av_malloc (s);
568 split_get_request (string url)
571 AWAITING_QUESTION_MARK,
574 } state = AWAITING_QUESTION_MARK;
576 map<string, string> r;
579 for (size_t i = 0; i < url.length(); ++i) {
581 case AWAITING_QUESTION_MARK:
596 r.insert (make_pair (k, v));
606 if (state == VALUE) {
607 r.insert (make_pair (k, v));
614 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
616 dcp::NameFormat::Map values;
618 values['i'] = asset->id();
619 values['r'] = raw_convert<string> (reel_index + 1);
620 values['n'] = raw_convert<string> (reel_count);
622 values['c'] = summary.get();
624 return Config::instance()->dcp_asset_filename_format().get(values) + ".mxf";
628 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
630 dcp::NameFormat::Map values;
632 values['i'] = asset->id();
633 values['r'] = raw_convert<string> (reel_index + 1);
634 values['n'] = raw_convert<string> (reel_count);
636 values['c'] = summary.get();
638 return Config::instance()->dcp_asset_filename_format().get(values) + ".mxf";
642 relaxed_string_to_float (string s)
645 boost::algorithm::replace_all (s, ",", ".");
646 return lexical_cast<float> (s);
647 } catch (bad_lexical_cast) {
648 boost::algorithm::replace_all (s, ".", ",");
649 return lexical_cast<float> (s);
654 string_not_empty (string s)