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>
41 #include <pangomm/init.h>
42 #include <boost/algorithm/string.hpp>
43 #include <boost/bind.hpp>
44 #include <boost/lambda/lambda.hpp>
45 #include <boost/thread.hpp>
46 #include <boost/filesystem.hpp>
47 #ifdef DCPOMATIC_WINDOWS
48 #include <boost/locale.hpp>
57 #ifdef DCPOMATIC_POSIX
78 using std::set_terminate;
79 using boost::shared_ptr;
81 using boost::optional;
84 /** Path to our executable, required by the stacktrace stuff and filled
85 * in during App::onInit().
88 static boost::thread::id ui_thread;
89 static boost::filesystem::path backtrace_file;
91 /** Convert some number of seconds to a string representation
92 * in hours, minutes and seconds.
95 * @return String of the form H:M:S (where H is hours, M
96 * is minutes and S is seconds).
99 seconds_to_hms (int s)
106 SafeStringStream hms;
109 hms << setfill ('0') << m << N_(":");
111 hms << setfill ('0') << s;
116 /** @param s Number of seconds.
117 * @return String containing an approximate description of s (e.g. "about 2 hours")
120 seconds_to_approximate_hms (int s)
129 bool const hours = h > 0;
130 bool const minutes = h < 10 && m > 0;
131 bool const seconds = m < 10 && s > 0;
134 if (m > 30 && !minutes) {
135 /// TRANSLATORS: h here is an abbreviation for hours
136 ap << (h + 1) << _("h");
138 /// TRANSLATORS: h here is an abbreviation for hours
142 if (minutes | seconds) {
149 if (s > 30 && !seconds) {
150 /// TRANSLATORS: m here is an abbreviation for minutes
151 ap << (m + 1) << _("m");
153 /// TRANSLATORS: m here is an abbreviation for minutes
164 /// TRANSLATORS: s here is an abbreviation for seconds
172 seconds (struct timeval t)
174 return t.tv_sec + (double (t.tv_usec) / 1e6);
177 #ifdef DCPOMATIC_WINDOWS
179 /** Resolve symbol name and source location given the path to the executable */
181 addr2line (void const * const addr)
183 char addr2line_cmd[512] = { 0 };
184 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
185 return system(addr2line_cmd);
188 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
189 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
190 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
193 exception_handler(struct _EXCEPTION_POINTERS * info)
195 FILE* f = fopen_boost (backtrace_file, "w");
196 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
199 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
200 CONTEXT* context = info->ContextRecord;
201 SymInitialize (GetCurrentProcess (), 0, true);
203 STACKFRAME frame = { 0 };
205 /* setup initial stack frame */
207 frame.AddrPC.Offset = context->Rip;
208 frame.AddrStack.Offset = context->Rsp;
209 frame.AddrFrame.Offset = context->Rbp;
211 frame.AddrPC.Offset = context->Eip;
212 frame.AddrStack.Offset = context->Esp;
213 frame.AddrFrame.Offset = context->Ebp;
215 frame.AddrPC.Mode = AddrModeFlat;
216 frame.AddrStack.Mode = AddrModeFlat;
217 frame.AddrFrame.Mode = AddrModeFlat;
221 IMAGE_FILE_MACHINE_I386,
222 GetCurrentProcess (),
227 SymFunctionTableAccess,
232 addr2line((void *) frame.AddrPC.Offset);
236 addr2line ((void *) info->ContextRecord->Rip);
238 addr2line ((void *) info->ContextRecord->Eip);
242 return EXCEPTION_CONTINUE_SEARCH;
247 set_backtrace_file (boost::filesystem::path p)
252 /** This is called when there is an unhandled exception. Any
253 * backtrace in this function is useless on Windows as the stack has
254 * already been unwound from the throw; we have the gdb wrap hack to
261 static bool tried_throw = false;
262 // try once to re-throw currently active exception
268 catch (const std::exception &e) {
269 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
270 << e.what() << std::endl;
273 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
280 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
281 * Must be called from the UI thread, if there is one.
286 #ifdef DCPOMATIC_WINDOWS
287 boost::filesystem::path p = g_get_user_config_dir ();
288 p /= "backtrace.txt";
289 set_backtrace_file (p);
290 SetUnhandledExceptionFilter(exception_handler);
292 /* Dark voodoo which, I think, gets boost::filesystem::path to
293 correctly convert UTF-8 strings to paths, and also paths
294 back to UTF-8 strings (on path::string()).
296 After this, constructing boost::filesystem::paths from strings
297 converts from UTF-8 to UTF-16 inside the path. Then
298 path::string().c_str() gives UTF-8 and
299 path::c_str() gives UTF-16.
301 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
302 so things are much simpler.
304 std::locale::global (boost::locale::generator().generate (""));
305 boost::filesystem::path::imbue (std::locale ());
308 avfilter_register_all ();
311 /* Add our lib directory to the libltdl search path so that
312 xmlsec can find xmlsec1-openssl.
314 boost::filesystem::path lib = app_contents ();
316 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
319 set_terminate (terminate);
324 Ratio::setup_ratios ();
325 VideoContentScale::setup_scales ();
326 DCPContentType::setup_dcp_content_types ();
327 Filter::setup_filters ();
328 CinemaSoundProcessor::setup_cinema_sound_processors ();
329 AudioProcessor::setup_audio_processors ();
331 ui_thread = boost::this_thread::get_id ();
334 #ifdef DCPOMATIC_WINDOWS
335 boost::filesystem::path
339 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
340 boost::filesystem::path p (buffer);
341 p = p.parent_path ();
342 p = p.parent_path ();
349 boost::filesystem::path
352 return "DCP-o-matic 2.app/Contents/Resources";
357 dcpomatic_setup_gettext_i18n (string lang)
359 #ifdef DCPOMATIC_LINUX
363 if (!lang.empty ()) {
364 /* Override our environment language. Note that the caller must not
365 free the string passed into putenv().
367 string s = String::compose ("LANGUAGE=%1", lang);
368 putenv (strdup (s.c_str ()));
369 s = String::compose ("LANG=%1", lang);
370 putenv (strdup (s.c_str ()));
371 s = String::compose ("LC_ALL=%1", lang);
372 putenv (strdup (s.c_str ()));
375 setlocale (LC_ALL, "");
376 textdomain ("libdcpomatic");
378 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
379 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
380 bind_textdomain_codeset ("libdcpomatic", "UTF8");
383 #ifdef DCPOMATIC_LINUX
384 bindtextdomain ("libdcpomatic", LINUX_LOCALE_PREFIX);
388 /** Compute a digest of the first and last `size' bytes of a set of files. */
390 md5_digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
392 boost::scoped_array<char> buffer (new char[size]);
393 MD5Digester digester;
396 boost::uintmax_t to_do = size;
397 char* p = buffer.get ();
399 while (i < int64_t (files.size()) && to_do > 0) {
400 FILE* f = fopen_boost (files[i], "rb");
402 throw OpenFileError (files[i].string());
405 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
406 fread (p, 1, this_time, f);
413 digester.add (buffer.get(), size - to_do);
418 i = files.size() - 1;
419 while (i >= 0 && to_do > 0) {
420 FILE* f = fopen_boost (files[i], "rb");
422 throw OpenFileError (files[i].string());
425 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
426 dcpomatic_fseek (f, -this_time, SEEK_END);
427 fread (p, 1, this_time, f);
434 digester.add (buffer.get(), size - to_do);
436 return digester.get ();
439 /** @param An arbitrary audio frame rate.
440 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
443 dcp_audio_frame_rate (int fs)
452 /** Round a number up to the nearest multiple of another number.
454 * @param s Array of numbers to round, indexed by c.
455 * @param t Multiple to round to.
456 * @return Rounded number.
459 stride_round_up (int c, int const * stride, int t)
461 int const a = stride[c] + (t - 1);
465 /** @param n A number.
466 * @param r Rounding `boundary' (must be a power of 2)
467 * @return n rounded to the nearest r
470 round_to (float n, int r)
472 DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
473 return int (n + float(r) / 2) &~ (r - 1);
476 /** Trip an assert if the caller is not in the UI thread */
480 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
484 audio_channel_name (int c)
486 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
488 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
489 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
490 /// VI is the visually-impaired audio track (audio describe).
491 string const channels[] = {
498 _("Hearing impaired"),
499 _("Visually impaired"),
502 _("Left rear surround"),
503 _("Right rear surround"),
510 valid_image_file (boost::filesystem::path f)
512 if (boost::starts_with (f.leaf().string(), "._")) {
516 string ext = f.extension().string();
517 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
519 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
520 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
521 ext == ".j2c" || ext == ".j2k"
526 valid_j2k_file (boost::filesystem::path f)
528 string ext = f.extension().string();
529 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
530 return (ext == ".j2k" || ext == ".j2c");
534 tidy_for_filename (string f)
537 for (size_t i = 0; i < f.length(); ++i) {
538 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
549 fit_ratio_within (float ratio, dcp::Size full_frame)
551 if (ratio < full_frame.ratio ()) {
552 return dcp::Size (rint (full_frame.height * ratio), full_frame.height);
555 return dcp::Size (full_frame.width, rint (full_frame.width / ratio));
559 wrapped_av_malloc (size_t s)
561 void* p = av_malloc (s);
569 subtitle_period (AVSubtitle const & sub)
571 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
573 if (sub.end_display_time == static_cast<uint32_t> (-1)) {
574 /* End time is not known */
575 return FFmpegSubtitlePeriod (packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3));
578 return FFmpegSubtitlePeriod (
579 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
580 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
585 split_get_request (string url)
588 AWAITING_QUESTION_MARK,
591 } state = AWAITING_QUESTION_MARK;
593 map<string, string> r;
596 for (size_t i = 0; i < url.length(); ++i) {
598 case AWAITING_QUESTION_MARK:
613 r.insert (make_pair (k, v));
623 if (state == VALUE) {
624 r.insert (make_pair (k, v));
631 frame_info_position (int frame, Eyes eyes)
633 static int const info_size = 48;
637 return frame * info_size;
639 return frame * info_size * 2;
641 return frame * info_size * 2 + info_size;
643 DCPOMATIC_ASSERT (false);
646 DCPOMATIC_ASSERT (false);
650 read_frame_info (FILE* file, int frame, Eyes eyes)
653 dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
654 fread (&info.offset, sizeof (info.offset), 1, file);
655 fread (&info.size, sizeof (info.size), 1, file);
657 char hash_buffer[33];
658 fread (hash_buffer, 1, 32, file);
659 hash_buffer[32] = '\0';
660 info.hash = hash_buffer;
666 write_frame_info (FILE* file, int frame, Eyes eyes, dcp::FrameInfo info)
668 dcpomatic_fseek (file, frame_info_position (frame, eyes), SEEK_SET);
669 fwrite (&info.offset, sizeof (info.offset), 1, file);
670 fwrite (&info.size, sizeof (info.size), 1, file);
671 fwrite (info.hash.c_str(), 1, info.hash.size(), file);