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 addr)
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/
283 exception_handler(struct _EXCEPTION_POINTERS * info)
285 FILE* f = fopen_boost (backtrace_file, "w");
286 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
289 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
290 CONTEXT* context = info->ContextRecord;
291 SymInitialize (GetCurrentProcess (), 0, true);
293 STACKFRAME frame = { 0 };
295 /* setup initial stack frame */
297 frame.AddrPC.Offset = context->Rip;
298 frame.AddrStack.Offset = context->Rsp;
299 frame.AddrFrame.Offset = context->Rbp;
301 frame.AddrPC.Offset = context->Eip;
302 frame.AddrStack.Offset = context->Esp;
303 frame.AddrFrame.Offset = context->Ebp;
305 frame.AddrPC.Mode = AddrModeFlat;
306 frame.AddrStack.Mode = AddrModeFlat;
307 frame.AddrFrame.Mode = AddrModeFlat;
311 IMAGE_FILE_MACHINE_I386,
312 GetCurrentProcess (),
317 SymFunctionTableAccess,
322 addr2line((void *) frame.AddrPC.Offset);
326 addr2line ((void *) info->ContextRecord->Rip);
328 addr2line ((void *) info->ContextRecord->Eip);
332 return EXCEPTION_CONTINUE_SEARCH;
337 set_backtrace_file (boost::filesystem::path p)
342 /** This is called when there is an unhandled exception. Any
343 * backtrace in this function is useless on Windows as the stack has
344 * already been unwound from the throw; we have the gdb wrap hack to
350 static bool tried_throw = false;
353 // try once to re-throw currently active exception
359 catch (const std::exception &e) {
360 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
361 << e.what() << std::endl;
364 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
368 #ifdef DCPOMATIC_POSIX
369 stacktrace (cout, 50);
374 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
375 * Must be called from the UI thread, if there is one.
380 #ifdef DCPOMATIC_WINDOWS
381 boost::filesystem::path p = g_get_user_config_dir ();
382 p /= "backtrace.txt";
383 set_backtrace_file (p);
384 SetUnhandledExceptionFilter(exception_handler);
386 /* Dark voodoo which, I think, gets boost::filesystem::path to
387 correctly convert UTF-8 strings to paths, and also paths
388 back to UTF-8 strings (on path::string()).
390 After this, constructing boost::filesystem::paths from strings
391 converts from UTF-8 to UTF-16 inside the path. Then
392 path::string().c_str() gives UTF-8 and
393 path::c_str() gives UTF-16.
395 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
396 so things are much simpler.
398 std::locale::global (boost::locale::generator().generate (""));
399 boost::filesystem::path::imbue (std::locale ());
402 avfilter_register_all ();
405 /* Add our lib directory to the libltdl search path so that
406 xmlsec can find xmlsec1-openssl.
408 boost::filesystem::path lib = app_contents ();
410 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
413 set_terminate (terminate);
418 Ratio::setup_ratios ();
419 VideoContentScale::setup_scales ();
420 DCPContentType::setup_dcp_content_types ();
421 Scaler::setup_scalers ();
422 Filter::setup_filters ();
423 CinemaSoundProcessor::setup_cinema_sound_processors ();
424 AudioProcessor::setup_audio_processors ();
426 ui_thread = boost::this_thread::get_id ();
429 #ifdef DCPOMATIC_WINDOWS
430 boost::filesystem::path
434 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
435 boost::filesystem::path p (buffer);
436 p = p.parent_path ();
437 p = p.parent_path ();
444 boost::filesystem::path
447 return "DCP-o-matic 2.app/Contents/Resources";
452 dcpomatic_setup_gettext_i18n (string lang)
454 #ifdef DCPOMATIC_LINUX
458 if (!lang.empty ()) {
459 /* Override our environment language. Note that the caller must not
460 free the string passed into putenv().
462 string s = String::compose ("LANGUAGE=%1", lang);
463 putenv (strdup (s.c_str ()));
464 s = String::compose ("LANG=%1", lang);
465 putenv (strdup (s.c_str ()));
466 s = String::compose ("LC_ALL=%1", lang);
467 putenv (strdup (s.c_str ()));
470 setlocale (LC_ALL, "");
471 textdomain ("libdcpomatic");
473 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
474 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
475 bind_textdomain_codeset ("libdcpomatic", "UTF8");
478 #ifdef DCPOMATIC_LINUX
479 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
483 /** @param s A string.
484 * @return Parts of the string split at spaces, except when a space is within quotation marks.
487 split_at_spaces_considering_quotes (string s)
490 bool in_quotes = false;
492 for (string::size_type i = 0; i < s.length(); ++i) {
493 if (s[i] == ' ' && !in_quotes) {
496 } else if (s[i] == '"') {
497 in_quotes = !in_quotes;
507 /** @param job Optional job for which to report progress */
509 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
511 boost::uintmax_t const buffer_size = 64 * 1024;
512 char buffer[buffer_size];
514 MD5Digester digester;
516 vector<int64_t> sizes;
517 for (size_t i = 0; i < files.size(); ++i) {
518 sizes.push_back (boost::filesystem::file_size (files[i]));
521 for (size_t i = 0; i < files.size(); ++i) {
522 FILE* f = fopen_boost (files[i], "rb");
524 throw OpenFileError (files[i].string());
527 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
528 boost::uintmax_t remaining = bytes;
530 while (remaining > 0) {
531 int const t = min (remaining, buffer_size);
532 int const r = fread (buffer, 1, t, f);
534 throw ReadFileError (files[i], errno);
536 digester.add (buffer, t);
540 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
547 return digester.get ();
550 /** @param An arbitrary audio frame rate.
551 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
554 dcp_audio_frame_rate (int fs)
563 Socket::Socket (int timeout)
564 : _deadline (_io_service)
565 , _socket (_io_service)
569 _deadline.expires_at (boost::posix_time::pos_infin);
581 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
583 _acceptor->cancel ();
587 _deadline.expires_at (boost::posix_time::pos_infin);
590 _deadline.async_wait (boost::bind (&Socket::check, this));
593 /** Blocking connect.
594 * @param endpoint End-point to connect to.
597 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
599 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
600 boost::system::error_code ec = boost::asio::error::would_block;
601 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
603 _io_service.run_one();
604 } while (ec == boost::asio::error::would_block);
607 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
610 if (!_socket.is_open ()) {
611 throw NetworkError (_("connect timed out"));
616 Socket::accept (int port)
618 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
620 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
621 boost::system::error_code ec = boost::asio::error::would_block;
622 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
624 _io_service.run_one ();
625 } while (ec == boost::asio::error::would_block);
631 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
636 * @param data Buffer to write.
637 * @param size Number of bytes to write.
640 Socket::write (uint8_t const * data, int size)
642 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
643 boost::system::error_code ec = boost::asio::error::would_block;
645 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
648 _io_service.run_one ();
649 } while (ec == boost::asio::error::would_block);
652 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
657 Socket::write (uint32_t v)
660 write (reinterpret_cast<uint8_t*> (&v), 4);
664 * @param data Buffer to read to.
665 * @param size Number of bytes to read.
668 Socket::read (uint8_t* data, int size)
670 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
671 boost::system::error_code ec = boost::asio::error::would_block;
673 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
676 _io_service.run_one ();
677 } while (ec == boost::asio::error::would_block);
680 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
685 Socket::read_uint32 ()
688 read (reinterpret_cast<uint8_t *> (&v), 4);
692 /** Round a number up to the nearest multiple of another number.
694 * @param s Array of numbers to round, indexed by c.
695 * @param t Multiple to round to.
696 * @return Rounded number.
699 stride_round_up (int c, int const * stride, int t)
701 int const a = stride[c] + (t - 1);
705 /** @param n A number.
706 * @param r Rounding `boundary' (must be a power of 2)
707 * @return n rounded to the nearest r
710 round_to (float n, int r)
712 DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
713 return int (n + float(r) / 2) &~ (r - 1);
716 /** Read a sequence of key / value pairs from a text stream;
717 * the keys are the first words on the line, and the values are
718 * the remainder of the line following the key. Lines beginning
719 * with # are ignored.
720 * @param s Stream to read.
721 * @return key/value pairs.
723 multimap<string, string>
724 read_key_value (istream &s)
726 multimap<string, string> kv;
729 while (getline (s, line)) {
734 if (line[0] == '#') {
738 if (line[line.size() - 1] == '\r') {
739 line = line.substr (0, line.size() - 1);
742 size_t const s = line.find (' ');
743 if (s == string::npos) {
747 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
754 get_required_string (multimap<string, string> const & kv, string k)
756 if (kv.count (k) > 1) {
757 throw StringError (N_("unexpected multiple keys in key-value set"));
760 multimap<string, string>::const_iterator i = kv.find (k);
762 if (i == kv.end ()) {
763 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
770 get_required_int (multimap<string, string> const & kv, string k)
772 string const v = get_required_string (kv, k);
773 return raw_convert<int> (v);
777 get_required_float (multimap<string, string> const & kv, string k)
779 string const v = get_required_string (kv, k);
780 return raw_convert<float> (v);
784 get_optional_string (multimap<string, string> const & kv, string k)
786 if (kv.count (k) > 1) {
787 throw StringError (N_("unexpected multiple keys in key-value set"));
790 multimap<string, string>::const_iterator i = kv.find (k);
791 if (i == kv.end ()) {
799 get_optional_int (multimap<string, string> const & kv, string k)
801 if (kv.count (k) > 1) {
802 throw StringError (N_("unexpected multiple keys in key-value set"));
805 multimap<string, string>::const_iterator i = kv.find (k);
806 if (i == kv.end ()) {
810 return raw_convert<int> (i->second);
813 /** Trip an assert if the caller is not in the UI thread */
817 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
821 audio_channel_name (int c)
823 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
825 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
826 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
827 /// VI is the visually-impaired audio track (audio describe).
828 string const channels[] = {
835 _("Hearing impaired"),
836 _("Visually impaired"),
839 _("Left rear surround"),
840 _("Right rear surround"),
847 valid_image_file (boost::filesystem::path f)
849 string ext = f.extension().string();
850 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
852 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
853 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
854 ext == ".j2c" || ext == ".j2k"
859 valid_j2k_file (boost::filesystem::path f)
861 string ext = f.extension().string();
862 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
863 return (ext == ".j2k" || ext == ".j2c");
867 tidy_for_filename (string f)
870 for (size_t i = 0; i < f.length(); ++i) {
871 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
882 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
884 if (ratio < full_frame.ratio ()) {
885 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
888 return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
892 wrapped_av_malloc (size_t s)
894 void* p = av_malloc (s);
902 entities_to_text (string e)
904 boost::algorithm::replace_all (e, "%3A", ":");
905 boost::algorithm::replace_all (e, "%2F", "/");
910 divide_with_round (int64_t a, int64_t b)
912 if (a % b >= (b / 2)) {
913 return (a + b - 1) / b;
919 /** Return a user-readable string summarising the versions of our dependencies */
921 dependency_version_summary ()
924 s << N_("libopenjpeg ") << opj_version () << N_(", ")
925 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
926 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
927 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
928 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
929 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
930 << MagickVersion << N_(", ")
931 << N_("libssh ") << ssh_version (0) << N_(", ")
932 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
937 /** Construct a ScopedTemporary. A temporary filename is decided but the file is not opened
938 * until ::open() is called.
940 ScopedTemporary::ScopedTemporary ()
943 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
946 /** Close and delete the temporary file */
947 ScopedTemporary::~ScopedTemporary ()
950 boost::system::error_code ec;
951 boost::filesystem::remove (_file, ec);
954 /** @return temporary filename */
956 ScopedTemporary::c_str () const
958 return _file.string().c_str ();
961 /** Open the temporary file.
962 * @return File's FILE pointer.
965 ScopedTemporary::open (char const * params)
967 _open = fopen (c_str(), params);
971 /** Close the file */
973 ScopedTemporary::close ()
982 subtitle_period (AVSubtitle const & sub)
984 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
986 ContentTimePeriod period (
987 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
988 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)