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 <locked_sstream.h>
41 #include <dcp/picture_asset.h>
42 #include <dcp/sound_asset.h>
43 #include <dcp/subtitle_asset.h>
45 #include <libavfilter/avfilter.h>
46 #include <libavcodec/avcodec.h>
48 #include <curl/curl.h>
49 #ifdef DCPOMATIC_GRAPHICS_MAGICK
53 #include <pangomm/init.h>
54 #include <boost/algorithm/string.hpp>
55 #include <boost/thread.hpp>
56 #include <boost/filesystem.hpp>
57 #ifdef DCPOMATIC_WINDOWS
58 #include <boost/locale.hpp>
67 #ifdef DCPOMATIC_POSIX
88 using std::set_terminate;
89 using boost::shared_ptr;
91 using boost::optional;
92 using boost::lexical_cast;
93 using boost::bad_lexical_cast;
96 /** Path to our executable, required by the stacktrace stuff and filled
97 * in during App::onInit().
100 static boost::thread::id ui_thread;
101 static boost::filesystem::path backtrace_file;
103 /** Convert some number of seconds to a string representation
104 * in hours, minutes and seconds.
107 * @return String of the form H:M:S (where H is hours, M
108 * is minutes and S is seconds).
111 seconds_to_hms (int s)
118 locked_stringstream hms;
121 hms << setfill ('0') << m << N_(":");
123 hms << setfill ('0') << 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)
139 locked_stringstream ap;
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 << (h + 1) << _("h");
150 /// TRANSLATORS: h here is an abbreviation for hours
154 if (minutes || seconds) {
161 if (s > 30 && !seconds) {
162 /// TRANSLATORS: m here is an abbreviation for minutes
163 ap << (m + 1) << _("m");
165 /// TRANSLATORS: m here is an abbreviation for minutes
176 /// TRANSLATORS: s here is an abbreviation for seconds
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());
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());
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 s 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). HI is the hearing-impaired audio track and
491 /// VI is the visually-impaired audio track (audio describe).
492 string const channels[] = {
499 _("Hearing impaired"),
500 _("Visually impaired"),
503 _("Left rear surround"),
504 _("Right rear surround"),
506 _("D-BOX secondary"),
515 valid_image_file (boost::filesystem::path f)
517 if (boost::starts_with (f.leaf().string(), "._")) {
521 string ext = f.extension().string();
522 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
524 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
525 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
526 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
531 valid_j2k_file (boost::filesystem::path f)
533 string ext = f.extension().string();
534 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
535 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
539 tidy_for_filename (string f)
542 for (size_t i = 0; i < f.length(); ++i) {
543 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
554 fit_ratio_within (float ratio, dcp::Size full_frame)
556 if (ratio < full_frame.ratio ()) {
557 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
560 return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
564 wrapped_av_malloc (size_t s)
566 void* p = av_malloc (s);
574 split_get_request (string url)
577 AWAITING_QUESTION_MARK,
580 } state = AWAITING_QUESTION_MARK;
582 map<string, string> r;
585 for (size_t i = 0; i < url.length(); ++i) {
587 case AWAITING_QUESTION_MARK:
602 r.insert (make_pair (k, v));
612 if (state == VALUE) {
613 r.insert (make_pair (k, v));
620 video_asset_filename (shared_ptr<dcp::PictureAsset> asset)
622 return "j2c_" + asset->id() + ".mxf";
626 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset)
628 return "pcm_" + asset->id() + ".mxf";
632 relaxed_string_to_float (string s)
635 boost::algorithm::replace_all (s, ",", ".");
636 return lexical_cast<float> (s);
637 } catch (bad_lexical_cast) {
638 boost::algorithm::replace_all (s, ".", ",");
639 return lexical_cast<float> (s);
644 string_not_empty (string s)