2 Copyright (C) 2012-2015 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 /** @file src/lib/util.cc
21 * @brief Some utility functions and classes.
25 #include "exceptions.h"
26 #include "dcp_content_type.h"
28 #include "cinema_sound_processor.h"
33 #include "video_content.h"
35 #include "md5_digester.h"
36 #include "audio_processor.h"
37 #include "safe_stringstream.h"
39 #include <dcp/signer.h>
40 #include <dcp/picture_asset.h>
41 #include <dcp/sound_asset.h>
42 #include <dcp/subtitle_asset.h>
44 #include <pangomm/init.h>
45 #include <boost/algorithm/string.hpp>
46 #include <boost/bind.hpp>
47 #include <boost/lambda/lambda.hpp>
48 #include <boost/thread.hpp>
49 #include <boost/filesystem.hpp>
50 #ifdef DCPOMATIC_WINDOWS
51 #include <boost/locale.hpp>
60 #ifdef DCPOMATIC_POSIX
81 using std::set_terminate;
82 using boost::shared_ptr;
84 using boost::optional;
87 /** Path to our executable, required by the stacktrace stuff and filled
88 * in during App::onInit().
91 static boost::thread::id ui_thread;
92 static boost::filesystem::path backtrace_file;
94 /** Convert some number of seconds to a string representation
95 * in hours, minutes and seconds.
98 * @return String of the form H:M:S (where H is hours, M
99 * is minutes and S is seconds).
102 seconds_to_hms (int s)
109 SafeStringStream hms;
112 hms << setfill ('0') << m << N_(":");
114 hms << setfill ('0') << s;
119 /** @param s Number of seconds.
120 * @return String containing an approximate description of s (e.g. "about 2 hours")
123 seconds_to_approximate_hms (int s)
132 bool const hours = h > 0;
133 bool const minutes = h < 10 && m > 0;
134 bool const seconds = m < 10 && s > 0;
137 if (m > 30 && !minutes) {
138 /// TRANSLATORS: h here is an abbreviation for hours
139 ap << (h + 1) << _("h");
141 /// TRANSLATORS: h here is an abbreviation for hours
145 if (minutes | seconds) {
152 if (s > 30 && !seconds) {
153 /// TRANSLATORS: m here is an abbreviation for minutes
154 ap << (m + 1) << _("m");
156 /// TRANSLATORS: m here is an abbreviation for minutes
167 /// TRANSLATORS: s here is an abbreviation for seconds
175 seconds (struct timeval t)
177 return t.tv_sec + (double (t.tv_usec) / 1e6);
180 #ifdef DCPOMATIC_WINDOWS
182 /** Resolve symbol name and source location given the path to the executable */
184 addr2line (void const * const addr)
186 char addr2line_cmd[512] = { 0 };
187 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
188 return system(addr2line_cmd);
191 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
192 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
193 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
196 exception_handler(struct _EXCEPTION_POINTERS * info)
198 FILE* f = fopen_boost (backtrace_file, "w");
199 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
202 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
203 CONTEXT* context = info->ContextRecord;
204 SymInitialize (GetCurrentProcess (), 0, true);
206 STACKFRAME frame = { 0 };
208 /* setup initial stack frame */
210 frame.AddrPC.Offset = context->Rip;
211 frame.AddrStack.Offset = context->Rsp;
212 frame.AddrFrame.Offset = context->Rbp;
214 frame.AddrPC.Offset = context->Eip;
215 frame.AddrStack.Offset = context->Esp;
216 frame.AddrFrame.Offset = context->Ebp;
218 frame.AddrPC.Mode = AddrModeFlat;
219 frame.AddrStack.Mode = AddrModeFlat;
220 frame.AddrFrame.Mode = AddrModeFlat;
224 IMAGE_FILE_MACHINE_I386,
225 GetCurrentProcess (),
230 SymFunctionTableAccess,
235 addr2line((void *) frame.AddrPC.Offset);
239 addr2line ((void *) info->ContextRecord->Rip);
241 addr2line ((void *) info->ContextRecord->Eip);
245 return EXCEPTION_CONTINUE_SEARCH;
250 set_backtrace_file (boost::filesystem::path p)
255 /** This is called when there is an unhandled exception. Any
256 * backtrace in this function is useless on Windows as the stack has
257 * already been unwound from the throw; we have the gdb wrap hack to
264 static bool tried_throw = false;
265 // try once to re-throw currently active exception
271 catch (const std::exception &e) {
272 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
273 << e.what() << std::endl;
276 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
283 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
284 * Must be called from the UI thread, if there is one.
289 #ifdef DCPOMATIC_WINDOWS
290 boost::filesystem::path p = g_get_user_config_dir ();
291 p /= "backtrace.txt";
292 set_backtrace_file (p);
293 SetUnhandledExceptionFilter(exception_handler);
295 /* Dark voodoo which, I think, gets boost::filesystem::path to
296 correctly convert UTF-8 strings to paths, and also paths
297 back to UTF-8 strings (on path::string()).
299 After this, constructing boost::filesystem::paths from strings
300 converts from UTF-8 to UTF-16 inside the path. Then
301 path::string().c_str() gives UTF-8 and
302 path::c_str() gives UTF-16.
304 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
305 so things are much simpler.
307 std::locale::global (boost::locale::generator().generate (""));
308 boost::filesystem::path::imbue (std::locale ());
311 avfilter_register_all ();
314 /* Add our lib directory to the libltdl search path so that
315 xmlsec can find xmlsec1-openssl.
317 boost::filesystem::path lib = app_contents ();
319 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
322 set_terminate (terminate);
327 Ratio::setup_ratios ();
328 PresetColourConversion::setup_colour_conversion_presets ();
329 VideoContentScale::setup_scales ();
330 DCPContentType::setup_dcp_content_types ();
331 Filter::setup_filters ();
332 CinemaSoundProcessor::setup_cinema_sound_processors ();
333 AudioProcessor::setup_audio_processors ();
335 ui_thread = boost::this_thread::get_id ();
338 #ifdef DCPOMATIC_WINDOWS
339 boost::filesystem::path
343 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
344 boost::filesystem::path p (buffer);
345 p = p.parent_path ();
346 p = p.parent_path ();
353 boost::filesystem::path
356 return "DCP-o-matic 2.app/Contents/Resources";
361 dcpomatic_setup_gettext_i18n (string lang)
363 #ifdef DCPOMATIC_LINUX
367 if (!lang.empty ()) {
368 /* Override our environment language. Note that the caller must not
369 free the string passed into putenv().
371 string s = String::compose ("LANGUAGE=%1", lang);
372 putenv (strdup (s.c_str ()));
373 s = String::compose ("LANG=%1", lang);
374 putenv (strdup (s.c_str ()));
375 s = String::compose ("LC_ALL=%1", lang);
376 putenv (strdup (s.c_str ()));
379 setlocale (LC_ALL, "");
380 textdomain ("libdcpomatic2");
382 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
383 bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
384 bind_textdomain_codeset ("libdcpomatic2", "UTF8");
387 #ifdef DCPOMATIC_LINUX
388 bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
392 /** Compute a digest of the first and last `size' bytes of a set of files. */
394 md5_digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
396 boost::scoped_array<char> buffer (new char[size]);
397 MD5Digester digester;
400 boost::uintmax_t to_do = size;
401 char* p = buffer.get ();
403 while (i < int64_t (files.size()) && to_do > 0) {
404 FILE* f = fopen_boost (files[i], "rb");
406 throw OpenFileError (files[i].string());
409 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
410 fread (p, 1, this_time, f);
417 digester.add (buffer.get(), size - to_do);
422 i = files.size() - 1;
423 while (i >= 0 && to_do > 0) {
424 FILE* f = fopen_boost (files[i], "rb");
426 throw OpenFileError (files[i].string());
429 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
430 dcpomatic_fseek (f, -this_time, SEEK_END);
431 fread (p, 1, this_time, f);
438 digester.add (buffer.get(), size - to_do);
440 return digester.get ();
443 /** @param An arbitrary audio frame rate.
444 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
447 dcp_audio_frame_rate (int fs)
456 /** Round a number up to the nearest multiple of another number.
458 * @param s Array of numbers to round, indexed by c.
459 * @param t Multiple to round to.
460 * @return Rounded number.
463 stride_round_up (int c, int const * stride, int t)
465 int const a = stride[c] + (t - 1);
469 /** @param n A number.
470 * @param r Rounding `boundary' (must be a power of 2)
471 * @return n rounded to the nearest r
474 round_to (float n, int r)
476 DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
477 return int (n + float(r) / 2) &~ (r - 1);
480 /** Trip an assert if the caller is not in the UI thread */
484 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
488 audio_channel_name (int c)
490 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
492 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
493 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
494 /// VI is the visually-impaired audio track (audio describe).
495 string const channels[] = {
502 _("Hearing impaired"),
503 _("Visually impaired"),
506 _("Left rear surround"),
507 _("Right rear surround"),
514 valid_image_file (boost::filesystem::path f)
516 if (boost::starts_with (f.leaf().string(), "._")) {
520 string ext = f.extension().string();
521 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
523 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
524 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
525 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
530 valid_j2k_file (boost::filesystem::path f)
532 string ext = f.extension().string();
533 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
534 return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
538 tidy_for_filename (string f)
541 for (size_t i = 0; i < f.length(); ++i) {
542 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
553 fit_ratio_within (float ratio, dcp::Size full_frame)
555 if (ratio < full_frame.ratio ()) {
556 return dcp::Size (rint (full_frame.height * ratio), full_frame.height);
559 return dcp::Size (full_frame.width, rint (full_frame.width / ratio));
563 wrapped_av_malloc (size_t s)
565 void* p = av_malloc (s);
573 subtitle_period (AVSubtitle const & sub)
575 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
577 if (sub.end_display_time == static_cast<uint32_t> (-1)) {
578 /* End time is not known */
579 return FFmpegSubtitlePeriod (packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3));
582 return FFmpegSubtitlePeriod (
583 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
584 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
589 split_get_request (string url)
592 AWAITING_QUESTION_MARK,
595 } state = AWAITING_QUESTION_MARK;
597 map<string, string> r;
600 for (size_t i = 0; i < url.length(); ++i) {
602 case AWAITING_QUESTION_MARK:
617 r.insert (make_pair (k, v));
627 if (state == VALUE) {
628 r.insert (make_pair (k, v));
635 video_asset_filename (shared_ptr<dcp::PictureAsset> asset)
637 return "j2c_" + asset->id() + ".mxf";
641 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset)
643 return "pcm_" + asset->id() + ".mxf";