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/thread.hpp>
57 #include <boost/filesystem.hpp>
58 #ifdef DCPOMATIC_WINDOWS
59 #include <boost/locale.hpp>
68 #ifdef DCPOMATIC_POSIX
89 using std::set_terminate;
90 using boost::shared_ptr;
92 using boost::optional;
93 using boost::lexical_cast;
94 using boost::bad_lexical_cast;
96 using dcp::raw_convert;
97 using dcp::locale_convert;
99 /** Path to our executable, required by the stacktrace stuff and filled
100 * in during App::onInit().
103 static boost::thread::id ui_thread;
104 static boost::filesystem::path backtrace_file;
106 /** Convert some number of seconds to a string representation
107 * in hours, minutes and seconds.
110 * @return String of the form H:M:S (where H is hours, M
111 * is minutes and S is seconds).
114 seconds_to_hms (int s)
122 snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
126 /** @param s Number of seconds.
127 * @return String containing an approximate description of s (e.g. "about 2 hours")
130 seconds_to_approximate_hms (int s)
139 bool const hours = h > 0;
140 bool const minutes = h < 6 && m > 0;
141 bool const seconds = h == 0 && m < 10 && s > 0;
144 if (m > 30 && !minutes) {
145 /// TRANSLATORS: h here is an abbreviation for hours
146 ap += locale_convert<string>(h + 1) + _("h");
148 /// TRANSLATORS: h here is an abbreviation for hours
149 ap += locale_convert<string>(h) + _("h");
152 if (minutes || seconds) {
159 if (s > 30 && !seconds) {
160 /// TRANSLATORS: m here is an abbreviation for minutes
161 ap += locale_convert<string>(m + 1) + _("m");
163 /// TRANSLATORS: m here is an abbreviation for minutes
164 ap += locale_convert<string>(m) + _("m");
174 /// TRANSLATORS: s here is an abbreviation for seconds
175 ap += locale_convert<string>(s) + _("s");
182 seconds (struct timeval t)
184 return t.tv_sec + (double (t.tv_usec) / 1e6);
187 #ifdef DCPOMATIC_WINDOWS
189 /** Resolve symbol name and source location given the path to the executable */
191 addr2line (void const * const addr)
193 char addr2line_cmd[512] = { 0 };
194 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
195 return system(addr2line_cmd);
198 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
199 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
200 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
203 exception_handler(struct _EXCEPTION_POINTERS * info)
205 FILE* f = fopen_boost (backtrace_file, "w");
206 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
209 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
210 CONTEXT* context = info->ContextRecord;
211 SymInitialize (GetCurrentProcess (), 0, true);
213 STACKFRAME frame = { 0 };
215 /* setup initial stack frame */
217 frame.AddrPC.Offset = context->Rip;
218 frame.AddrStack.Offset = context->Rsp;
219 frame.AddrFrame.Offset = context->Rbp;
221 frame.AddrPC.Offset = context->Eip;
222 frame.AddrStack.Offset = context->Esp;
223 frame.AddrFrame.Offset = context->Ebp;
225 frame.AddrPC.Mode = AddrModeFlat;
226 frame.AddrStack.Mode = AddrModeFlat;
227 frame.AddrFrame.Mode = AddrModeFlat;
231 IMAGE_FILE_MACHINE_I386,
232 GetCurrentProcess (),
237 SymFunctionTableAccess,
242 addr2line((void *) frame.AddrPC.Offset);
246 addr2line ((void *) info->ContextRecord->Rip);
248 addr2line ((void *) info->ContextRecord->Eip);
252 return EXCEPTION_CONTINUE_SEARCH;
257 set_backtrace_file (boost::filesystem::path p)
262 /** This is called when there is an unhandled exception. Any
263 * backtrace in this function is useless on Windows as the stack has
264 * already been unwound from the throw; we have the gdb wrap hack to
271 static bool tried_throw = false;
272 // try once to re-throw currently active exception
278 catch (const std::exception &e) {
279 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
280 << e.what() << std::endl;
283 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
291 dcpomatic_setup_path_encoding ()
293 #ifdef DCPOMATIC_WINDOWS
294 /* Dark voodoo which, I think, gets boost::filesystem::path to
295 correctly convert UTF-8 strings to paths, and also paths
296 back to UTF-8 strings (on path::string()).
298 After this, constructing boost::filesystem::paths from strings
299 converts from UTF-8 to UTF-16 inside the path. Then
300 path::string().c_str() gives UTF-8 and
301 path::c_str() gives UTF-16.
303 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
304 so things are much simpler.
306 std::locale::global (boost::locale::generator().generate (""));
307 boost::filesystem::path::imbue (std::locale ());
311 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
312 * Must be called from the UI thread, if there is one.
317 #ifdef DCPOMATIC_WINDOWS
318 boost::filesystem::path p = g_get_user_config_dir ();
319 p /= "backtrace.txt";
320 set_backtrace_file (p);
321 SetUnhandledExceptionFilter(exception_handler);
324 avfilter_register_all ();
327 /* Add our lib directory to the libltdl search path so that
328 xmlsec can find xmlsec1-openssl.
330 boost::filesystem::path lib = app_contents ();
332 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
335 set_terminate (terminate);
340 Ratio::setup_ratios ();
341 PresetColourConversion::setup_colour_conversion_presets ();
342 VideoContentScale::setup_scales ();
343 DCPContentType::setup_dcp_content_types ();
344 Filter::setup_filters ();
345 CinemaSoundProcessor::setup_cinema_sound_processors ();
346 AudioProcessor::setup_audio_processors ();
348 curl_global_init (CURL_GLOBAL_ALL);
350 #ifdef DCPOMATIC_GRAPHICS_MAGICK
351 Magick::InitializeMagick (0);
354 ui_thread = boost::this_thread::get_id ();
357 #ifdef DCPOMATIC_WINDOWS
358 boost::filesystem::path
362 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
363 boost::filesystem::path p (buffer);
364 p = p.parent_path ();
365 p = p.parent_path ();
372 boost::filesystem::path
375 return "DCP-o-matic 2.app/Contents/Resources";
380 dcpomatic_setup_gettext_i18n (string lang)
382 #ifdef DCPOMATIC_LINUX
386 if (!lang.empty ()) {
387 /* Override our environment language. Note that the caller must not
388 free the string passed into putenv().
390 string s = String::compose ("LANGUAGE=%1", lang);
391 putenv (strdup (s.c_str ()));
392 s = String::compose ("LANG=%1", lang);
393 putenv (strdup (s.c_str ()));
394 s = String::compose ("LC_ALL=%1", lang);
395 putenv (strdup (s.c_str ()));
398 setlocale (LC_ALL, "");
399 textdomain ("libdcpomatic2");
401 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
402 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
403 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
406 #ifdef DCPOMATIC_LINUX
407 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
411 /** Compute a digest of the first and last `size' bytes of a set of files. */
413 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
415 boost::scoped_array<char> buffer (new char[size]);
419 boost::uintmax_t to_do = size;
420 char* p = buffer.get ();
422 while (i < int64_t (files.size()) && to_do > 0) {
423 FILE* f = fopen_boost (files[i], "rb");
425 throw OpenFileError (files[i].string());
428 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
429 fread (p, 1, this_time, f);
436 digester.add (buffer.get(), size - to_do);
441 i = files.size() - 1;
442 while (i >= 0 && to_do > 0) {
443 FILE* f = fopen_boost (files[i], "rb");
445 throw OpenFileError (files[i].string());
448 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
449 dcpomatic_fseek (f, -this_time, SEEK_END);
450 fread (p, 1, this_time, f);
457 digester.add (buffer.get(), size - to_do);
459 return digester.get ();
462 /** Round a number up to the nearest multiple of another number.
464 * @param s Array of numbers to round, indexed by c.
465 * @param t Multiple to round to.
466 * @return Rounded number.
469 stride_round_up (int c, int const * stride, int t)
471 int const a = stride[c] + (t - 1);
475 /** Trip an assert if the caller is not in the UI thread */
479 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
483 audio_channel_name (int c)
485 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
487 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
488 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
489 /// VI is the visually-impaired audio track (audio describe).
490 string const channels[] = {
497 _("Hearing impaired"),
498 _("Visually impaired"),
501 _("Left rear surround"),
502 _("Right rear surround"),
504 _("D-BOX secondary"),
513 valid_image_file (boost::filesystem::path f)
515 if (boost::starts_with (f.leaf().string(), "._")) {
519 string ext = f.extension().string();
520 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
522 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
523 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
524 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
529 valid_j2k_file (boost::filesystem::path f)
531 string ext = f.extension().string();
532 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
533 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
537 tidy_for_filename (string f)
540 for (size_t i = 0; i < f.length(); ++i) {
541 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
552 fit_ratio_within (float ratio, dcp::Size full_frame)
554 if (ratio < full_frame.ratio ()) {
555 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
558 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
562 wrapped_av_malloc (size_t s)
564 void* p = av_malloc (s);
572 split_get_request (string url)
575 AWAITING_QUESTION_MARK,
578 } state = AWAITING_QUESTION_MARK;
580 map<string, string> r;
583 for (size_t i = 0; i < url.length(); ++i) {
585 case AWAITING_QUESTION_MARK:
600 r.insert (make_pair (k, v));
610 if (state == VALUE) {
611 r.insert (make_pair (k, v));
618 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
620 dcp::NameFormat::Map values;
622 values['i'] = asset->id();
623 values['r'] = raw_convert<string> (reel_index + 1);
624 values['n'] = raw_convert<string> (reel_count);
626 values['c'] = summary.get();
628 return Config::instance()->dcp_asset_filename_format().get(values) + ".mxf";
632 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
634 dcp::NameFormat::Map values;
636 values['i'] = asset->id();
637 values['r'] = raw_convert<string> (reel_index + 1);
638 values['n'] = raw_convert<string> (reel_count);
640 values['c'] = summary.get();
642 return Config::instance()->dcp_asset_filename_format().get(values) + ".mxf";
646 relaxed_string_to_float (string s)
649 boost::algorithm::replace_all (s, ",", ".");
650 return lexical_cast<float> (s);
651 } catch (bad_lexical_cast) {
652 boost::algorithm::replace_all (s, ".", ",");
653 return lexical_cast<float> (s);
658 string_not_empty (string s)