2 Copyright (C) 2012-2014 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"
27 #include "dcp_content_type.h"
29 #include "cinema_sound_processor.h"
34 #include "video_content.h"
36 #include "md5_digester.h"
37 #include "audio_processor.h"
38 #include "safe_stringstream.h"
40 #include <dcp/signer.h>
41 #include <dcp/raw_convert.h>
43 #include <pangomm/init.h>
44 #include <boost/algorithm/string.hpp>
45 #include <boost/bind.hpp>
46 #include <boost/lambda/lambda.hpp>
47 #include <boost/thread.hpp>
48 #include <boost/filesystem.hpp>
49 #ifdef DCPOMATIC_WINDOWS
50 #include <boost/locale.hpp>
59 #ifdef DCPOMATIC_POSIX
79 using std::set_terminate;
80 using boost::shared_ptr;
82 using boost::optional;
84 using dcp::raw_convert;
86 /** Path to our executable, required by the stacktrace stuff and filled
87 * in during App::onInit().
90 static boost::thread::id ui_thread;
91 static boost::filesystem::path backtrace_file;
93 /** Convert some number of seconds to a string representation
94 * in hours, minutes and seconds.
97 * @return String of the form H:M:S (where H is hours, M
98 * is minutes and S is seconds).
101 seconds_to_hms (int s)
108 SafeStringStream hms;
111 hms << setfill ('0') << m << N_(":");
113 hms << setfill ('0') << s;
118 /** @param s Number of seconds.
119 * @return String containing an approximate description of s (e.g. "about 2 hours")
122 seconds_to_approximate_hms (int s)
131 bool const hours = h > 0;
132 bool const minutes = h < 10 && m > 0;
133 bool const seconds = m < 10 && s > 0;
136 if (m > 30 && !minutes) {
137 /// TRANSLATORS: h here is an abbreviation for hours
138 ap << (h + 1) << _("h");
140 /// TRANSLATORS: h here is an abbreviation for hours
144 if (minutes | seconds) {
151 if (s > 30 && !seconds) {
152 /// TRANSLATORS: m here is an abbreviation for minutes
153 ap << (m + 1) << _("m");
155 /// TRANSLATORS: m here is an abbreviation for minutes
166 /// TRANSLATORS: s here is an abbreviation for seconds
174 seconds (struct timeval t)
176 return t.tv_sec + (double (t.tv_usec) / 1e6);
179 #ifdef DCPOMATIC_WINDOWS
181 /** Resolve symbol name and source location given the path to the executable */
183 addr2line (void const * const addr)
185 char addr2line_cmd[512] = { 0 };
186 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
187 return system(addr2line_cmd);
190 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
191 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
192 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
195 exception_handler(struct _EXCEPTION_POINTERS * info)
197 FILE* f = fopen_boost (backtrace_file, "w");
198 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
201 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
202 CONTEXT* context = info->ContextRecord;
203 SymInitialize (GetCurrentProcess (), 0, true);
205 STACKFRAME frame = { 0 };
207 /* setup initial stack frame */
209 frame.AddrPC.Offset = context->Rip;
210 frame.AddrStack.Offset = context->Rsp;
211 frame.AddrFrame.Offset = context->Rbp;
213 frame.AddrPC.Offset = context->Eip;
214 frame.AddrStack.Offset = context->Esp;
215 frame.AddrFrame.Offset = context->Ebp;
217 frame.AddrPC.Mode = AddrModeFlat;
218 frame.AddrStack.Mode = AddrModeFlat;
219 frame.AddrFrame.Mode = AddrModeFlat;
223 IMAGE_FILE_MACHINE_I386,
224 GetCurrentProcess (),
229 SymFunctionTableAccess,
234 addr2line((void *) frame.AddrPC.Offset);
238 addr2line ((void *) info->ContextRecord->Rip);
240 addr2line ((void *) info->ContextRecord->Eip);
244 return EXCEPTION_CONTINUE_SEARCH;
249 set_backtrace_file (boost::filesystem::path p)
254 /** This is called when there is an unhandled exception. Any
255 * backtrace in this function is useless on Windows as the stack has
256 * already been unwound from the throw; we have the gdb wrap hack to
263 static bool tried_throw = false;
264 // try once to re-throw currently active exception
270 catch (const std::exception &e) {
271 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
272 << e.what() << std::endl;
275 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
282 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
283 * Must be called from the UI thread, if there is one.
288 #ifdef DCPOMATIC_WINDOWS
289 boost::filesystem::path p = g_get_user_config_dir ();
290 p /= "backtrace.txt";
291 set_backtrace_file (p);
292 SetUnhandledExceptionFilter(exception_handler);
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 ());
310 avfilter_register_all ();
313 /* Add our lib directory to the libltdl search path so that
314 xmlsec can find xmlsec1-openssl.
316 boost::filesystem::path lib = app_contents ();
318 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
321 set_terminate (terminate);
326 Ratio::setup_ratios ();
327 VideoContentScale::setup_scales ();
328 DCPContentType::setup_dcp_content_types ();
329 Scaler::setup_scalers ();
330 Filter::setup_filters ();
331 CinemaSoundProcessor::setup_cinema_sound_processors ();
332 AudioProcessor::setup_audio_processors ();
334 ui_thread = boost::this_thread::get_id ();
337 #ifdef DCPOMATIC_WINDOWS
338 boost::filesystem::path
342 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
343 boost::filesystem::path p (buffer);
344 p = p.parent_path ();
345 p = p.parent_path ();
352 boost::filesystem::path
355 return "DCP-o-matic 2.app/Contents/Resources";
360 dcpomatic_setup_gettext_i18n (string lang)
362 #ifdef DCPOMATIC_LINUX
366 if (!lang.empty ()) {
367 /* Override our environment language. Note that the caller must not
368 free the string passed into putenv().
370 string s = String::compose ("LANGUAGE=%1", lang);
371 putenv (strdup (s.c_str ()));
372 s = String::compose ("LANG=%1", lang);
373 putenv (strdup (s.c_str ()));
374 s = String::compose ("LC_ALL=%1", lang);
375 putenv (strdup (s.c_str ()));
378 setlocale (LC_ALL, "");
379 textdomain ("libdcpomatic");
381 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
382 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
383 bind_textdomain_codeset ("libdcpomatic", "UTF8");
386 #ifdef DCPOMATIC_LINUX
387 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
391 /** Compute a digest of the first and last `size' bytes of a set of files. */
393 md5_digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
395 boost::scoped_array<char> buffer (new char[size]);
396 MD5Digester digester;
399 boost::uintmax_t to_do = size;
400 char* p = buffer.get ();
402 while (i < int64_t (files.size()) && to_do > 0) {
403 FILE* f = fopen_boost (files[i], "rb");
405 throw OpenFileError (files[i].string());
408 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
409 fread (p, 1, this_time, f);
416 digester.add (buffer.get(), size - to_do);
421 i = files.size() - 1;
422 while (i >= 0 && 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 fseek (f, -this_time, SEEK_END);
430 fread (p, 1, this_time, f);
437 digester.add (buffer.get(), size - to_do);
439 return digester.get ();
442 /** @param An arbitrary audio frame rate.
443 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
446 dcp_audio_frame_rate (int fs)
455 /** Round a number up to the nearest multiple of another number.
457 * @param s Array of numbers to round, indexed by c.
458 * @param t Multiple to round to.
459 * @return Rounded number.
462 stride_round_up (int c, int const * stride, int t)
464 int const a = stride[c] + (t - 1);
468 /** @param n A number.
469 * @param r Rounding `boundary' (must be a power of 2)
470 * @return n rounded to the nearest r
473 round_to (float n, int r)
475 DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
476 return int (n + float(r) / 2) &~ (r - 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 == 12);
491 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
492 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
493 /// VI is the visually-impaired audio track (audio describe).
494 string const channels[] = {
501 _("Hearing impaired"),
502 _("Visually impaired"),
505 _("Left rear surround"),
506 _("Right rear surround"),
513 valid_image_file (boost::filesystem::path f)
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"
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");
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, int round)
550 if (ratio < full_frame.ratio ()) {
551 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
554 return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
558 wrapped_av_malloc (size_t s)
560 void* p = av_malloc (s);
568 subtitle_period (AVSubtitle const & sub)
570 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
572 ContentTimePeriod period (
573 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
574 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)