2 Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3 Copyright (C) 2000-2007 Paul Davis
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 /** @file src/lib/util.cc
22 * @brief Some utility functions and classes.
26 #include "exceptions.h"
28 #include "dcp_content_type.h"
30 #include "cinema_sound_processor.h"
35 #include "video_content.h"
37 #include "md5_digester.h"
38 #include "audio_processor.h"
39 #include "safe_stringstream.h"
40 #include <dcp/version.h>
42 #include <dcp/signer.h>
43 #include <dcp/raw_convert.h>
45 #include <libavcodec/avcodec.h>
46 #include <libavformat/avformat.h>
47 #include <libswscale/swscale.h>
48 #include <libavfilter/avfiltergraph.h>
49 #include <libavutil/pixfmt.h>
53 #include <pangomm/init.h>
54 #ifdef DCPOMATIC_IMAGE_MAGICK
55 #include <magick/MagickCore.h>
57 #include <magick/common.h>
58 #include <magick/magick_config.h>
60 #include <magick/version.h>
61 #include <libssh/libssh.h>
62 #include <boost/algorithm/string.hpp>
63 #include <boost/bind.hpp>
64 #include <boost/lambda/lambda.hpp>
65 #include <boost/thread.hpp>
66 #include <boost/filesystem.hpp>
67 #ifdef DCPOMATIC_WINDOWS
68 #include <boost/locale.hpp>
77 #ifdef DCPOMATIC_POSIX
97 using std::set_terminate;
98 using boost::shared_ptr;
100 using boost::optional;
102 using dcp::raw_convert;
104 /** Path to our executable, required by the stacktrace stuff and filled
105 * in during App::onInit().
108 static boost::thread::id ui_thread;
109 static boost::filesystem::path backtrace_file;
111 /** Convert some number of seconds to a string representation
112 * in hours, minutes and seconds.
115 * @return String of the form H:M:S (where H is hours, M
116 * is minutes and S is seconds).
119 seconds_to_hms (int s)
126 SafeStringStream hms;
129 hms << setfill ('0') << m << N_(":");
131 hms << setfill ('0') << s;
136 /** @param s Number of seconds.
137 * @return String containing an approximate description of s (e.g. "about 2 hours")
140 seconds_to_approximate_hms (int s)
149 bool const hours = h > 0;
150 bool const minutes = h < 10 && m > 0;
151 bool const seconds = m < 10 && s > 0;
154 if (m > 30 && !minutes) {
155 /// TRANSLATORS: h here is an abbreviation for hours
156 ap << (h + 1) << _("h");
158 /// TRANSLATORS: h here is an abbreviation for hours
162 if (minutes | seconds) {
169 if (s > 30 && !seconds) {
170 /// TRANSLATORS: m here is an abbreviation for minutes
171 ap << (m + 1) << _("m");
173 /// TRANSLATORS: m here is an abbreviation for minutes
184 /// TRANSLATORS: s here is an abbreviation for seconds
191 #ifdef DCPOMATIC_POSIX
192 /** @param l Mangled C++ identifier.
193 * @return Demangled version.
198 string::size_type const b = l.find_first_of (N_("("));
199 if (b == string::npos) {
203 string::size_type const p = l.find_last_of (N_("+"));
204 if (p == string::npos) {
212 string const fn = l.substr (b + 1, p - b - 1);
217 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
222 } catch (std::exception) {
229 /** Write a stacktrace to an ostream.
230 * @param out Stream to write to.
231 * @param levels Number of levels to go up the call stack.
234 stacktrace (ostream& out, int levels)
237 size_t size = backtrace (array, 200);
238 char** strings = backtrace_symbols (array, size);
241 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
242 out << N_(" ") << demangle (strings[i]) << "\n";
250 /** @param v Version as used by FFmpeg.
251 * @return A string representation of v.
254 ffmpeg_version_to_string (int v)
257 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
262 seconds (struct timeval t)
264 return t.tv_sec + (double (t.tv_usec) / 1e6);
267 #ifdef DCPOMATIC_WINDOWS
269 /** Resolve symbol name and source location given the path to the executable */
271 addr2line (void const * const adr)
273 char addr2line_cmd[512] = { 0 };
274 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
275 return system(addr2line_cmd);
278 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
279 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
280 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
282 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
284 FILE* f = fopen_boost (backtrace_file, "w");
285 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
288 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
289 CONTEXT* context = info->ContextRecord;
290 SymInitialize (GetCurrentProcess (), 0, true);
292 STACKFRAME frame = { 0 };
294 /* setup initial stack frame */
296 frame.AddrPC.Offset = context->Rip;
297 frame.AddrStack.Offset = context->Rsp;
298 frame.AddrFrame.Offset = context->Rbp;
300 frame.AddrPC.Offset = context->Eip;
301 frame.AddrStack.Offset = context->Esp;
302 frame.AddrFrame.Offset = context->Ebp;
304 frame.AddrPC.Mode = AddrModeFlat;
305 frame.AddrStack.Mode = AddrModeFlat;
306 frame.AddrFrame.Mode = AddrModeFlat;
310 IMAGE_FILE_MACHINE_I386,
311 GetCurrentProcess (),
316 SymFunctionTableAccess,
321 addr2line((void *) frame.AddrPC.Offset);
325 addr2line ((void *) info->ContextRecord->Rip);
327 addr2line ((void *) info->ContextRecord->Eip);
331 return EXCEPTION_CONTINUE_SEARCH;
336 set_backtrace_file (boost::filesystem::path p)
341 /** This is called when there is an unhandled exception. Any
342 * backtrace in this function is useless on Windows as the stack has
343 * already been unwound from the throw; we have the gdb wrap hack to
349 static bool tried_throw = false;
352 // try once to re-throw currently active exception
358 catch (const std::exception &e) {
359 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
360 << e.what() << std::endl;
363 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
367 #ifdef DCPOMATIC_POSIX
368 stacktrace (cout, 50);
373 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
374 * Must be called from the UI thread, if there is one.
379 #ifdef DCPOMATIC_WINDOWS
380 boost::filesystem::path p = g_get_user_config_dir ();
381 p /= "backtrace.txt";
382 set_backtrace_file (p);
383 SetUnhandledExceptionFilter(exception_handler);
385 /* Dark voodoo which, I think, gets boost::filesystem::path to
386 correctly convert UTF-8 strings to paths, and also paths
387 back to UTF-8 strings (on path::string()).
389 After this, constructing boost::filesystem::paths from strings
390 converts from UTF-8 to UTF-16 inside the path. Then
391 path::string().c_str() gives UTF-8 and
392 path::c_str() gives UTF-16.
394 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
395 so things are much simpler.
397 std::locale::global (boost::locale::generator().generate (""));
398 boost::filesystem::path::imbue (std::locale ());
401 avfilter_register_all ();
404 /* Add our lib directory to the libltdl search path so that
405 xmlsec can find xmlsec1-openssl.
407 boost::filesystem::path lib = app_contents ();
409 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
412 set_terminate (terminate);
417 Ratio::setup_ratios ();
418 VideoContentScale::setup_scales ();
419 DCPContentType::setup_dcp_content_types ();
420 Scaler::setup_scalers ();
421 Filter::setup_filters ();
422 CinemaSoundProcessor::setup_cinema_sound_processors ();
423 AudioProcessor::setup_audio_processors ();
425 ui_thread = boost::this_thread::get_id ();
428 #ifdef DCPOMATIC_WINDOWS
429 boost::filesystem::path
433 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
434 boost::filesystem::path p (buffer);
435 p = p.parent_path ();
436 p = p.parent_path ();
443 boost::filesystem::path
446 return "DCP-o-matic 2.app/Contents/Resources";
451 dcpomatic_setup_gettext_i18n (string lang)
453 #ifdef DCPOMATIC_LINUX
457 if (!lang.empty ()) {
458 /* Override our environment language. Note that the caller must not
459 free the string passed into putenv().
461 string s = String::compose ("LANGUAGE=%1", lang);
462 putenv (strdup (s.c_str ()));
463 s = String::compose ("LANG=%1", lang);
464 putenv (strdup (s.c_str ()));
465 s = String::compose ("LC_ALL=%1", lang);
466 putenv (strdup (s.c_str ()));
469 setlocale (LC_ALL, "");
470 textdomain ("libdcpomatic");
472 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
473 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
474 bind_textdomain_codeset ("libdcpomatic", "UTF8");
477 #ifdef DCPOMATIC_LINUX
478 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
482 /** @param s A string.
483 * @return Parts of the string split at spaces, except when a space is within quotation marks.
486 split_at_spaces_considering_quotes (string s)
489 bool in_quotes = false;
491 for (string::size_type i = 0; i < s.length(); ++i) {
492 if (s[i] == ' ' && !in_quotes) {
495 } else if (s[i] == '"') {
496 in_quotes = !in_quotes;
506 /** @param job Optional job for which to report progress */
508 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
510 boost::uintmax_t const buffer_size = 64 * 1024;
511 char buffer[buffer_size];
513 MD5Digester digester;
515 vector<int64_t> sizes;
516 for (size_t i = 0; i < files.size(); ++i) {
517 sizes.push_back (boost::filesystem::file_size (files[i]));
520 for (size_t i = 0; i < files.size(); ++i) {
521 FILE* f = fopen_boost (files[i], "rb");
523 throw OpenFileError (files[i].string());
526 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
527 boost::uintmax_t remaining = bytes;
529 while (remaining > 0) {
530 int const t = min (remaining, buffer_size);
531 int const r = fread (buffer, 1, t, f);
533 throw ReadFileError (files[i], errno);
535 digester.add (buffer, t);
539 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
546 return digester.get ();
549 /** @param An arbitrary audio frame rate.
550 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
553 dcp_audio_frame_rate (int fs)
562 Socket::Socket (int timeout)
563 : _deadline (_io_service)
564 , _socket (_io_service)
568 _deadline.expires_at (boost::posix_time::pos_infin);
580 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
582 _acceptor->cancel ();
586 _deadline.expires_at (boost::posix_time::pos_infin);
589 _deadline.async_wait (boost::bind (&Socket::check, this));
592 /** Blocking connect.
593 * @param endpoint End-point to connect to.
596 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
598 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
599 boost::system::error_code ec = boost::asio::error::would_block;
600 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
602 _io_service.run_one();
603 } while (ec == boost::asio::error::would_block);
606 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
609 if (!_socket.is_open ()) {
610 throw NetworkError (_("connect timed out"));
615 Socket::accept (int port)
617 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
619 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
620 boost::system::error_code ec = boost::asio::error::would_block;
621 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
623 _io_service.run_one ();
624 } while (ec == boost::asio::error::would_block);
630 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
635 * @param data Buffer to write.
636 * @param size Number of bytes to write.
639 Socket::write (uint8_t const * data, int size)
641 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
642 boost::system::error_code ec = boost::asio::error::would_block;
644 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
647 _io_service.run_one ();
648 } while (ec == boost::asio::error::would_block);
651 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
656 Socket::write (uint32_t v)
659 write (reinterpret_cast<uint8_t*> (&v), 4);
663 * @param data Buffer to read to.
664 * @param size Number of bytes to read.
667 Socket::read (uint8_t* data, int size)
669 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
670 boost::system::error_code ec = boost::asio::error::would_block;
672 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
675 _io_service.run_one ();
676 } while (ec == boost::asio::error::would_block);
679 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
684 Socket::read_uint32 ()
687 read (reinterpret_cast<uint8_t *> (&v), 4);
691 /** Round a number up to the nearest multiple of another number.
693 * @param s Array of numbers to round, indexed by c.
694 * @param t Multiple to round to.
695 * @return Rounded number.
698 stride_round_up (int c, int const * stride, int t)
700 int const a = stride[c] + (t - 1);
704 /** @param n A number.
705 * @param r Rounding `boundary' (must be a power of 2)
706 * @return n rounded to the nearest r
709 round_to (float n, int r)
711 DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
712 return int (n + float(r) / 2) &~ (r - 1);
715 /** Read a sequence of key / value pairs from a text stream;
716 * the keys are the first words on the line, and the values are
717 * the remainder of the line following the key. Lines beginning
718 * with # are ignored.
719 * @param s Stream to read.
720 * @return key/value pairs.
722 multimap<string, string>
723 read_key_value (istream &s)
725 multimap<string, string> kv;
728 while (getline (s, line)) {
733 if (line[0] == '#') {
737 if (line[line.size() - 1] == '\r') {
738 line = line.substr (0, line.size() - 1);
741 size_t const s = line.find (' ');
742 if (s == string::npos) {
746 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
753 get_required_string (multimap<string, string> const & kv, string k)
755 if (kv.count (k) > 1) {
756 throw StringError (N_("unexpected multiple keys in key-value set"));
759 multimap<string, string>::const_iterator i = kv.find (k);
761 if (i == kv.end ()) {
762 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
769 get_required_int (multimap<string, string> const & kv, string k)
771 string const v = get_required_string (kv, k);
772 return raw_convert<int> (v);
776 get_required_float (multimap<string, string> const & kv, string k)
778 string const v = get_required_string (kv, k);
779 return raw_convert<float> (v);
783 get_optional_string (multimap<string, string> const & kv, string k)
785 if (kv.count (k) > 1) {
786 throw StringError (N_("unexpected multiple keys in key-value set"));
789 multimap<string, string>::const_iterator i = kv.find (k);
790 if (i == kv.end ()) {
798 get_optional_int (multimap<string, string> const & kv, string k)
800 if (kv.count (k) > 1) {
801 throw StringError (N_("unexpected multiple keys in key-value set"));
804 multimap<string, string>::const_iterator i = kv.find (k);
805 if (i == kv.end ()) {
809 return raw_convert<int> (i->second);
812 /** Trip an assert if the caller is not in the UI thread */
816 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
820 audio_channel_name (int c)
822 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
824 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
825 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
826 /// VI is the visually-impaired audio track (audio describe).
827 string const channels[] = {
834 _("Hearing impaired"),
835 _("Visually impaired"),
838 _("Left rear surround"),
839 _("Right rear surround"),
846 valid_image_file (boost::filesystem::path f)
848 string ext = f.extension().string();
849 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
851 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
852 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
853 ext == ".j2c" || ext == ".j2k"
858 valid_j2k_file (boost::filesystem::path f)
860 string ext = f.extension().string();
861 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
862 return (ext == ".j2k" || ext == ".j2c");
866 tidy_for_filename (string f)
869 for (size_t i = 0; i < f.length(); ++i) {
870 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
881 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
883 if (ratio < full_frame.ratio ()) {
884 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
887 return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
891 wrapped_av_malloc (size_t s)
893 void* p = av_malloc (s);
901 entities_to_text (string e)
903 boost::algorithm::replace_all (e, "%3A", ":");
904 boost::algorithm::replace_all (e, "%2F", "/");
909 divide_with_round (int64_t a, int64_t b)
911 if (a % b >= (b / 2)) {
912 return (a + b - 1) / b;
918 /** Return a user-readable string summarising the versions of our dependencies */
920 dependency_version_summary ()
923 s << N_("libopenjpeg ") << opj_version () << N_(", ")
924 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
925 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
926 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
927 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
928 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
929 << MagickVersion << N_(", ")
930 << N_("libssh ") << ssh_version (0) << N_(", ")
931 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
936 /** Construct a ScopedTemporary. A temporary filename is decided but the file is not opened
937 * until ::open() is called.
939 ScopedTemporary::ScopedTemporary ()
942 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
945 /** Close and delete the temporary file */
946 ScopedTemporary::~ScopedTemporary ()
949 boost::system::error_code ec;
950 boost::filesystem::remove (_file, ec);
953 /** @return temporary filename */
955 ScopedTemporary::c_str () const
957 return _file.string().c_str ();
960 /** Open the temporary file.
961 * @return File's FILE pointer.
964 ScopedTemporary::open (char const * params)
966 _open = fopen (c_str(), params);
970 /** Close the file */
972 ScopedTemporary::close ()
981 subtitle_period (AVSubtitle const & sub)
983 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
985 ContentTimePeriod period (
986 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
987 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)