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 <magick/MagickCore.h>
48 #include <magick/version.h>
49 #include <libdcp/version.h>
50 #include <libdcp/util.h>
51 #include <libdcp/signer_chain.h>
52 #include <libdcp/signer.h>
53 #include <libdcp/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 "sound_processor.h"
71 #include "video_content.h"
72 #include "md5_digester.h"
73 #ifdef DCPOMATIC_WINDOWS
80 using std::stringstream;
94 using std::numeric_limits;
99 using std::set_terminate;
100 using boost::shared_ptr;
102 using boost::optional;
104 using libdcp::raw_convert;
106 static boost::thread::id ui_thread;
107 static boost::filesystem::path backtrace_file;
109 /** Convert some number of seconds to a string representation
110 * in hours, minutes and seconds.
113 * @return String of the form H:M:S (where H is hours, M
114 * is minutes and S is seconds).
117 seconds_to_hms (int s)
127 hms << std::setfill ('0') << m << N_(":");
129 hms << std::setfill ('0') << s;
134 /** @param s Number of seconds.
135 * @return String containing an approximate description of s (e.g. "about 2 hours")
138 seconds_to_approximate_hms (int s)
147 bool const hours = h > 0;
148 bool const minutes = h < 10 && m > 0;
149 bool const seconds = m < 10 && s > 0;
152 if (m > 30 && !minutes) {
153 ap << (h + 1) << N_(" ") << _("hours");
163 if (minutes | seconds) {
170 if (s > 30 && !seconds) {
171 ap << (m + 1) << N_(" ") << _("minutes");
199 #ifdef DCPOMATIC_POSIX
200 /** @param l Mangled C++ identifier.
201 * @return Demangled version.
206 string::size_type const b = l.find_first_of (N_("("));
207 if (b == string::npos) {
211 string::size_type const p = l.find_last_of (N_("+"));
212 if (p == string::npos) {
220 string const fn = l.substr (b + 1, p - b - 1);
225 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
230 } catch (std::exception) {
237 /** Write a stacktrace to an ostream.
238 * @param out Stream to write to.
239 * @param levels Number of levels to go up the call stack.
242 stacktrace (ostream& out, int levels)
245 size_t size = backtrace (array, 200);
246 char** strings = backtrace_symbols (array, size);
249 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
250 out << N_(" ") << demangle (strings[i]) << "\n";
258 /** @param v Version as used by FFmpeg.
259 * @return A string representation of v.
262 ffmpeg_version_to_string (int v)
265 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
269 /** Return a user-readable string summarising the versions of our dependencies */
271 dependency_version_summary ()
274 s << N_("libopenjpeg ") << opj_version () << N_(", ")
275 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
276 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
277 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
278 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
279 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
280 << MagickVersion << N_(", ")
281 << N_("libssh ") << ssh_version (0) << N_(", ")
282 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
288 seconds (struct timeval t)
290 return t.tv_sec + (double (t.tv_usec) / 1e6);
293 #ifdef DCPOMATIC_WINDOWS
294 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
297 FILE* f = fopen_boost (backtrace_file, "w");
298 fprintf (f, "Exception thrown:");
299 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
300 fprintf (f, "%p %s %d %s\n", i->instruction, i->function.c_str(), i->line, i->module.c_str());
303 return EXCEPTION_CONTINUE_SEARCH;
307 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
311 static bool tried_throw = false;
314 // try once to re-throw currently active exception
320 catch (const std::exception &e) {
321 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
322 << e.what() << std::endl;
325 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
329 #ifdef DCPOMATIC_POSIX
330 stacktrace (cout, 50);
335 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
336 * Must be called from the UI thread, if there is one.
341 #ifdef DCPOMATIC_WINDOWS
342 backtrace_file /= g_get_user_config_dir ();
343 backtrace_file /= "backtrace.txt";
344 SetUnhandledExceptionFilter(exception_handler);
346 /* Dark voodoo which, I think, gets boost::filesystem::path to
347 correctly convert UTF-8 strings to paths, and also paths
348 back to UTF-8 strings (on path::string()).
350 After this, constructing boost::filesystem::paths from strings
351 converts from UTF-8 to UTF-16 inside the path. Then
352 path::string().c_str() gives UTF-8 and
353 path::c_str() gives UTF-16.
355 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
356 so things are much simpler.
358 std::locale::global (boost::locale::generator().generate (""));
359 boost::filesystem::path::imbue (std::locale ());
362 avfilter_register_all ();
365 /* Add our lib directory to the libltdl search path so that
366 xmlsec can find xmlsec1-openssl.
368 boost::filesystem::path lib = app_contents ();
370 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
373 set_terminate (terminate);
377 Ratio::setup_ratios ();
378 VideoContentScale::setup_scales ();
379 DCPContentType::setup_dcp_content_types ();
380 Scaler::setup_scalers ();
381 Filter::setup_filters ();
382 SoundProcessor::setup_sound_processors ();
384 ui_thread = boost::this_thread::get_id ();
387 #ifdef DCPOMATIC_WINDOWS
388 boost::filesystem::path
392 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
393 boost::filesystem::path p (buffer);
394 p = p.parent_path ();
395 p = p.parent_path ();
402 dcpomatic_setup_gettext_i18n (string lang)
404 #ifdef DCPOMATIC_POSIX
408 if (!lang.empty ()) {
409 /* Override our environment language; this is essential on
413 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
415 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
417 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
421 setlocale (LC_ALL, "");
422 textdomain ("libdcpomatic");
424 #ifdef DCPOMATIC_WINDOWS
425 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
426 bind_textdomain_codeset ("libdcpomatic", "UTF8");
429 #ifdef DCPOMATIC_POSIX
430 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
434 /** @param s A string.
435 * @return Parts of the string split at spaces, except when a space is within quotation marks.
438 split_at_spaces_considering_quotes (string s)
441 bool in_quotes = false;
443 for (string::size_type i = 0; i < s.length(); ++i) {
444 if (s[i] == ' ' && !in_quotes) {
447 } else if (s[i] == '"') {
448 in_quotes = !in_quotes;
458 /** @param job Optional job for which to report progress */
460 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
462 boost::uintmax_t const buffer_size = 64 * 1024;
463 char buffer[buffer_size];
465 MD5Digester digester;
467 vector<int64_t> sizes;
468 for (size_t i = 0; i < files.size(); ++i) {
469 sizes.push_back (boost::filesystem::file_size (files[i]));
472 for (size_t i = 0; i < files.size(); ++i) {
473 FILE* f = fopen_boost (files[i], "rb");
475 throw OpenFileError (files[i].string());
478 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
479 boost::uintmax_t remaining = bytes;
481 while (remaining > 0) {
482 int const t = min (remaining, buffer_size);
483 fread (buffer, 1, t, f);
484 digester.add (buffer, t);
488 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
495 return digester.get ();
498 /** @param An arbitrary audio frame rate.
499 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
502 dcp_audio_frame_rate (int fs)
511 Socket::Socket (int timeout)
512 : _deadline (_io_service)
513 , _socket (_io_service)
517 _deadline.expires_at (boost::posix_time::pos_infin);
529 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
531 _acceptor->cancel ();
535 _deadline.expires_at (boost::posix_time::pos_infin);
538 _deadline.async_wait (boost::bind (&Socket::check, this));
541 /** Blocking connect.
542 * @param endpoint End-point to connect to.
545 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
547 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
548 boost::system::error_code ec = boost::asio::error::would_block;
549 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
551 _io_service.run_one();
552 } while (ec == boost::asio::error::would_block);
555 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
558 if (!_socket.is_open ()) {
559 throw NetworkError (_("connect timed out"));
564 Socket::accept (int port)
566 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
568 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
569 boost::system::error_code ec = boost::asio::error::would_block;
570 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
572 _io_service.run_one ();
573 } while (ec == boost::asio::error::would_block );
579 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
584 * @param data Buffer to write.
585 * @param size Number of bytes to write.
588 Socket::write (uint8_t const * data, int size)
590 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
591 boost::system::error_code ec = boost::asio::error::would_block;
593 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
596 _io_service.run_one ();
597 } while (ec == boost::asio::error::would_block);
600 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
605 Socket::write (uint32_t v)
608 write (reinterpret_cast<uint8_t*> (&v), 4);
612 * @param data Buffer to read to.
613 * @param size Number of bytes to read.
616 Socket::read (uint8_t* data, int size)
618 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
619 boost::system::error_code ec = boost::asio::error::would_block;
621 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
624 _io_service.run_one ();
625 } while (ec == boost::asio::error::would_block);
628 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
633 Socket::read_uint32 ()
636 read (reinterpret_cast<uint8_t *> (&v), 4);
640 /** Round a number up to the nearest multiple of another number.
642 * @param s Array of numbers to round, indexed by c.
643 * @param t Multiple to round to.
644 * @return Rounded number.
647 stride_round_up (int c, int const * stride, int t)
649 int const a = stride[c] + (t - 1);
653 /** Read a sequence of key / value pairs from a text stream;
654 * the keys are the first words on the line, and the values are
655 * the remainder of the line following the key. Lines beginning
656 * with # are ignored.
657 * @param s Stream to read.
658 * @return key/value pairs.
660 multimap<string, string>
661 read_key_value (istream &s)
663 multimap<string, string> kv;
666 while (getline (s, line)) {
671 if (line[0] == '#') {
675 if (line[line.size() - 1] == '\r') {
676 line = line.substr (0, line.size() - 1);
679 size_t const s = line.find (' ');
680 if (s == string::npos) {
684 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
691 get_required_string (multimap<string, string> const & kv, string k)
693 if (kv.count (k) > 1) {
694 throw StringError (N_("unexpected multiple keys in key-value set"));
697 multimap<string, string>::const_iterator i = kv.find (k);
699 if (i == kv.end ()) {
700 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
707 get_required_int (multimap<string, string> const & kv, string k)
709 string const v = get_required_string (kv, k);
710 return raw_convert<int> (v);
714 get_required_float (multimap<string, string> const & kv, string k)
716 string const v = get_required_string (kv, k);
717 return raw_convert<float> (v);
721 get_optional_string (multimap<string, string> const & kv, string k)
723 if (kv.count (k) > 1) {
724 throw StringError (N_("unexpected multiple keys in key-value set"));
727 multimap<string, string>::const_iterator i = kv.find (k);
728 if (i == kv.end ()) {
736 get_optional_int (multimap<string, string> const & kv, string k)
738 if (kv.count (k) > 1) {
739 throw StringError (N_("unexpected multiple keys in key-value set"));
742 multimap<string, string>::const_iterator i = kv.find (k);
743 if (i == kv.end ()) {
747 return raw_convert<int> (i->second);
750 /** Trip an assert if the caller is not in the UI thread */
754 assert (boost::this_thread::get_id() == ui_thread);
757 /** @param v Content video frame.
758 * @param audio_sample_rate Source audio sample rate.
759 * @param frames_per_second Number of video frames per second.
760 * @return Equivalent number of audio frames for `v'.
763 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
765 return ((int64_t) v * audio_sample_rate / frames_per_second);
769 audio_channel_name (int c)
771 assert (MAX_DCP_AUDIO_CHANNELS == 12);
773 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
774 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
775 VI is the visually-impaired audio track (audio describe).
777 string const channels[] = {
784 _("Hearing impaired"),
785 _("Visually impaired"),
788 _("Left rear surround"),
789 _("Right rear surround"),
796 valid_image_file (boost::filesystem::path f)
798 string ext = f.extension().string();
799 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
800 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
804 tidy_for_filename (string f)
807 for (size_t i = 0; i < f.length(); ++i) {
808 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
818 shared_ptr<const libdcp::Signer>
821 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
823 /* Remake the chain if any of it is missing */
825 list<boost::filesystem::path> files;
826 files.push_back ("ca.self-signed.pem");
827 files.push_back ("intermediate.signed.pem");
828 files.push_back ("leaf.signed.pem");
829 files.push_back ("leaf.key");
831 list<boost::filesystem::path>::const_iterator i = files.begin();
832 while (i != files.end()) {
833 boost::filesystem::path p (sd);
835 if (!boost::filesystem::exists (p)) {
836 boost::filesystem::remove_all (sd);
837 boost::filesystem::create_directories (sd);
838 libdcp::make_signer_chain (sd, openssl_path ());
845 libdcp::CertificateChain chain;
848 boost::filesystem::path p (sd);
849 p /= "ca.self-signed.pem";
850 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
854 boost::filesystem::path p (sd);
855 p /= "intermediate.signed.pem";
856 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
860 boost::filesystem::path p (sd);
861 p /= "leaf.signed.pem";
862 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
865 boost::filesystem::path signer_key (sd);
866 signer_key /= "leaf.key";
868 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
872 split_get_request (string url)
875 AWAITING_QUESTION_MARK,
878 } state = AWAITING_QUESTION_MARK;
880 map<string, string> r;
883 for (size_t i = 0; i < url.length(); ++i) {
885 case AWAITING_QUESTION_MARK:
900 r.insert (make_pair (k, v));
910 if (state == VALUE) {
911 r.insert (make_pair (k, v));
918 fit_ratio_within (float ratio, libdcp::Size full_frame)
920 if (ratio < full_frame.ratio ()) {
921 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
924 return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));
928 wrapped_av_malloc (size_t s)
930 void* p = av_malloc (s);
938 entities_to_text (string e)
940 boost::algorithm::replace_all (e, "%3A", ":");
941 boost::algorithm::replace_all (e, "%2F", "/");
946 divide_with_round (int64_t a, int64_t b)
948 if (a % b >= (b / 2)) {
949 return (a + b - 1) / b;
955 ScopedTemporary::ScopedTemporary ()
958 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
961 ScopedTemporary::~ScopedTemporary ()
964 boost::system::error_code ec;
965 boost::filesystem::remove (_file, ec);
969 ScopedTemporary::c_str () const
971 return _file.string().c_str ();
975 ScopedTemporary::open (char const * params)
977 _open = fopen (c_str(), params);
982 ScopedTemporary::close ()