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.
31 #ifdef DCPOMATIC_POSIX
35 #include <libssh/libssh.h>
37 #include <boost/algorithm/string.hpp>
38 #include <boost/bind.hpp>
39 #include <boost/lambda/lambda.hpp>
40 #include <boost/thread.hpp>
41 #include <boost/filesystem.hpp>
42 #ifdef DCPOMATIC_WINDOWS
43 #include <boost/locale.hpp>
47 #include <pangomm/init.h>
48 #include <magick/MagickCore.h>
49 #include <magick/version.h>
50 #include <dcp/version.h>
52 #include <dcp/signer.h>
53 #include <dcp/raw_convert.h>
55 #include <libavcodec/avcodec.h>
56 #include <libavformat/avformat.h>
57 #include <libswscale/swscale.h>
58 #include <libavfilter/avfiltergraph.h>
59 #include <libavutil/pixfmt.h>
62 #include "exceptions.h"
64 #include "dcp_content_type.h"
66 #include "cinema_sound_processor.h"
71 #include "video_content.h"
73 #include "md5_digester.h"
74 #include "audio_processor.h"
75 #ifdef DCPOMATIC_WINDOWS
82 using std::stringstream;
96 using std::numeric_limits;
100 using std::streampos;
101 using std::set_terminate;
102 using boost::shared_ptr;
104 using boost::optional;
106 using dcp::raw_convert;
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)
129 hms << std::setfill ('0') << m << N_(":");
131 hms << std::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 ap << (h + 1) << N_(" ") << _("hours");
165 if (minutes | seconds) {
172 if (s > 30 && !seconds) {
173 ap << (m + 1) << N_(" ") << _("minutes");
201 #ifdef DCPOMATIC_POSIX
202 /** @param l Mangled C++ identifier.
203 * @return Demangled version.
208 string::size_type const b = l.find_first_of (N_("("));
209 if (b == string::npos) {
213 string::size_type const p = l.find_last_of (N_("+"));
214 if (p == string::npos) {
222 string const fn = l.substr (b + 1, p - b - 1);
227 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
232 } catch (std::exception) {
239 /** Write a stacktrace to an ostream.
240 * @param out Stream to write to.
241 * @param levels Number of levels to go up the call stack.
244 stacktrace (ostream& out, int levels)
247 size_t size = backtrace (array, 200);
248 char** strings = backtrace_symbols (array, size);
251 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
252 out << N_(" ") << demangle (strings[i]) << "\n";
260 /** @param v Version as used by FFmpeg.
261 * @return A string representation of v.
264 ffmpeg_version_to_string (int v)
267 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
272 seconds (struct timeval t)
274 return t.tv_sec + (double (t.tv_usec) / 1e6);
277 #ifdef DCPOMATIC_WINDOWS
278 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
281 FILE* f = fopen_boost (backtrace_file, "w");
282 fprintf (f, "Exception thrown:");
283 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
284 fprintf (f, "%p %s %d %s\n", i->instruction, i->function.c_str(), i->line, i->module.c_str());
287 return EXCEPTION_CONTINUE_SEARCH;
291 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
295 static bool tried_throw = false;
298 // try once to re-throw currently active exception
304 catch (const std::exception &e) {
305 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
306 << e.what() << std::endl;
309 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
313 #ifdef DCPOMATIC_POSIX
314 stacktrace (cout, 50);
319 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
320 * Must be called from the UI thread, if there is one.
325 #ifdef DCPOMATIC_WINDOWS
326 backtrace_file /= g_get_user_config_dir ();
327 backtrace_file /= "backtrace.txt";
328 SetUnhandledExceptionFilter(exception_handler);
330 /* Dark voodoo which, I think, gets boost::filesystem::path to
331 correctly convert UTF-8 strings to paths, and also paths
332 back to UTF-8 strings (on path::string()).
334 After this, constructing boost::filesystem::paths from strings
335 converts from UTF-8 to UTF-16 inside the path. Then
336 path::string().c_str() gives UTF-8 and
337 path::c_str() gives UTF-16.
339 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
340 so things are much simpler.
342 std::locale::global (boost::locale::generator().generate (""));
343 boost::filesystem::path::imbue (std::locale ());
346 avfilter_register_all ();
349 /* Add our lib directory to the libltdl search path so that
350 xmlsec can find xmlsec1-openssl.
352 boost::filesystem::path lib = app_contents ();
354 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
357 set_terminate (terminate);
362 Ratio::setup_ratios ();
363 VideoContentScale::setup_scales ();
364 DCPContentType::setup_dcp_content_types ();
365 Scaler::setup_scalers ();
366 Filter::setup_filters ();
367 CinemaSoundProcessor::setup_cinema_sound_processors ();
368 AudioProcessor::setup_audio_processors ();
370 ui_thread = boost::this_thread::get_id ();
373 #ifdef DCPOMATIC_WINDOWS
374 boost::filesystem::path
378 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
379 boost::filesystem::path p (buffer);
380 p = p.parent_path ();
381 p = p.parent_path ();
388 dcpomatic_setup_gettext_i18n (string lang)
390 #ifdef DCPOMATIC_POSIX
394 if (!lang.empty ()) {
395 /* Override our environment language; this is essential on
399 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
401 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
403 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
407 setlocale (LC_ALL, "");
408 textdomain ("libdcpomatic");
410 #ifdef DCPOMATIC_WINDOWS
411 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
412 bind_textdomain_codeset ("libdcpomatic", "UTF8");
415 #ifdef DCPOMATIC_POSIX
416 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
420 /** @param s A string.
421 * @return Parts of the string split at spaces, except when a space is within quotation marks.
424 split_at_spaces_considering_quotes (string s)
427 bool in_quotes = false;
429 for (string::size_type i = 0; i < s.length(); ++i) {
430 if (s[i] == ' ' && !in_quotes) {
433 } else if (s[i] == '"') {
434 in_quotes = !in_quotes;
444 /** @param job Optional job for which to report progress */
446 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
448 boost::uintmax_t const buffer_size = 64 * 1024;
449 char buffer[buffer_size];
451 MD5Digester digester;
453 vector<int64_t> sizes;
454 for (size_t i = 0; i < files.size(); ++i) {
455 sizes.push_back (boost::filesystem::file_size (files[i]));
458 for (size_t i = 0; i < files.size(); ++i) {
459 FILE* f = fopen_boost (files[i], "rb");
461 throw OpenFileError (files[i].string());
464 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
465 boost::uintmax_t remaining = bytes;
467 while (remaining > 0) {
468 int const t = min (remaining, buffer_size);
469 fread (buffer, 1, t, f);
470 digester.add (buffer, t);
474 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
481 return digester.get ();
484 /** @param An arbitrary audio frame rate.
485 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
488 dcp_audio_frame_rate (int fs)
497 Socket::Socket (int timeout)
498 : _deadline (_io_service)
499 , _socket (_io_service)
503 _deadline.expires_at (boost::posix_time::pos_infin);
515 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
517 _acceptor->cancel ();
521 _deadline.expires_at (boost::posix_time::pos_infin);
524 _deadline.async_wait (boost::bind (&Socket::check, this));
527 /** Blocking connect.
528 * @param endpoint End-point to connect to.
531 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
533 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
534 boost::system::error_code ec = boost::asio::error::would_block;
535 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
537 _io_service.run_one();
538 } while (ec == boost::asio::error::would_block);
541 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
544 if (!_socket.is_open ()) {
545 throw NetworkError (_("connect timed out"));
550 Socket::accept (int port)
552 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
554 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
555 boost::system::error_code ec = boost::asio::error::would_block;
556 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
558 _io_service.run_one ();
559 } while (ec == boost::asio::error::would_block );
565 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
570 * @param data Buffer to write.
571 * @param size Number of bytes to write.
574 Socket::write (uint8_t const * data, int size)
576 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
577 boost::system::error_code ec = boost::asio::error::would_block;
579 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
582 _io_service.run_one ();
583 } while (ec == boost::asio::error::would_block);
586 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
591 Socket::write (uint32_t v)
594 write (reinterpret_cast<uint8_t*> (&v), 4);
598 * @param data Buffer to read to.
599 * @param size Number of bytes to read.
602 Socket::read (uint8_t* data, int size)
604 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
605 boost::system::error_code ec = boost::asio::error::would_block;
607 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
610 _io_service.run_one ();
611 } while (ec == boost::asio::error::would_block);
614 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
619 Socket::read_uint32 ()
622 read (reinterpret_cast<uint8_t *> (&v), 4);
626 /** Round a number up to the nearest multiple of another number.
628 * @param s Array of numbers to round, indexed by c.
629 * @param t Multiple to round to.
630 * @return Rounded number.
633 stride_round_up (int c, int const * stride, int t)
635 int const a = stride[c] + (t - 1);
639 /** @param n A number.
640 * @param r Rounding `boundary' (must be a power of 2)
641 * @return n rounded to the nearest r
644 round_to (float n, int r)
646 assert (r == 1 || r == 2 || r == 4);
647 return int (n + float(r) / 2) &~ (r - 1);
650 /** Read a sequence of key / value pairs from a text stream;
651 * the keys are the first words on the line, and the values are
652 * the remainder of the line following the key. Lines beginning
653 * with # are ignored.
654 * @param s Stream to read.
655 * @return key/value pairs.
657 multimap<string, string>
658 read_key_value (istream &s)
660 multimap<string, string> kv;
663 while (getline (s, line)) {
668 if (line[0] == '#') {
672 if (line[line.size() - 1] == '\r') {
673 line = line.substr (0, line.size() - 1);
676 size_t const s = line.find (' ');
677 if (s == string::npos) {
681 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
688 get_required_string (multimap<string, string> const & kv, string k)
690 if (kv.count (k) > 1) {
691 throw StringError (N_("unexpected multiple keys in key-value set"));
694 multimap<string, string>::const_iterator i = kv.find (k);
696 if (i == kv.end ()) {
697 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
704 get_required_int (multimap<string, string> const & kv, string k)
706 string const v = get_required_string (kv, k);
707 return raw_convert<int> (v);
711 get_required_float (multimap<string, string> const & kv, string k)
713 string const v = get_required_string (kv, k);
714 return raw_convert<float> (v);
718 get_optional_string (multimap<string, string> const & kv, string k)
720 if (kv.count (k) > 1) {
721 throw StringError (N_("unexpected multiple keys in key-value set"));
724 multimap<string, string>::const_iterator i = kv.find (k);
725 if (i == kv.end ()) {
733 get_optional_int (multimap<string, string> const & kv, string k)
735 if (kv.count (k) > 1) {
736 throw StringError (N_("unexpected multiple keys in key-value set"));
739 multimap<string, string>::const_iterator i = kv.find (k);
740 if (i == kv.end ()) {
744 return raw_convert<int> (i->second);
747 /** Trip an assert if the caller is not in the UI thread */
751 assert (boost::this_thread::get_id() == ui_thread);
755 audio_channel_name (int c)
757 assert (MAX_DCP_AUDIO_CHANNELS == 12);
759 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
760 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
761 VI is the visually-impaired audio track (audio describe).
763 string const channels[] = {
770 _("Hearing impaired"),
771 _("Visually impaired"),
774 _("Left rear surround"),
775 _("Right rear surround"),
782 valid_image_file (boost::filesystem::path f)
784 string ext = f.extension().string();
785 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
786 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
790 tidy_for_filename (string f)
793 for (size_t i = 0; i < f.length(); ++i) {
794 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
805 split_get_request (string url)
808 AWAITING_QUESTION_MARK,
811 } state = AWAITING_QUESTION_MARK;
813 map<string, string> r;
816 for (size_t i = 0; i < url.length(); ++i) {
818 case AWAITING_QUESTION_MARK:
833 r.insert (make_pair (k, v));
843 if (state == VALUE) {
844 r.insert (make_pair (k, v));
851 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
853 if (ratio < full_frame.ratio ()) {
854 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
857 return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
861 wrapped_av_malloc (size_t s)
863 void* p = av_malloc (s);
871 entities_to_text (string e)
873 boost::algorithm::replace_all (e, "%3A", ":");
874 boost::algorithm::replace_all (e, "%2F", "/");
879 divide_with_round (int64_t a, int64_t b)
881 if (a % b >= (b / 2)) {
882 return (a + b - 1) / b;
888 /** Return a user-readable string summarising the versions of our dependencies */
890 dependency_version_summary ()
893 s << N_("libopenjpeg ") << opj_version () << N_(", ")
894 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
895 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
896 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
897 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
898 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
899 << MagickVersion << N_(", ")
900 << N_("libssh ") << ssh_version (0) << N_(", ")
901 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
906 /** Construct a ScopedTemporary. A temporary filename is decided but the file is not opened
907 * until ::open() is called.
909 ScopedTemporary::ScopedTemporary ()
912 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
915 /** Close and delete the temporary file */
916 ScopedTemporary::~ScopedTemporary ()
919 boost::system::error_code ec;
920 boost::filesystem::remove (_file, ec);
923 /** @return temporary filename */
925 ScopedTemporary::c_str () const
927 return _file.string().c_str ();
930 /** Open the temporary file.
931 * @return File's FILE pointer.
934 ScopedTemporary::open (char const * params)
936 _open = fopen (c_str(), params);
940 /** Close the file */
942 ScopedTemporary::close ()
951 subtitle_period (AVSubtitle const & sub)
953 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
955 ContentTimePeriod period (
956 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
957 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)