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.
30 #ifdef DCPOMATIC_POSIX
34 #include <libssh/libssh.h>
36 #include <boost/algorithm/string.hpp>
37 #include <boost/bind.hpp>
38 #include <boost/lambda/lambda.hpp>
39 #include <boost/thread.hpp>
40 #include <boost/filesystem.hpp>
41 #ifdef DCPOMATIC_WINDOWS
42 #include <boost/locale.hpp>
46 #include <magick/MagickCore.h>
47 #include <magick/version.h>
48 #include <libdcp/version.h>
49 #include <libdcp/util.h>
50 #include <libdcp/signer_chain.h>
51 #include <libdcp/signer.h>
52 #include <libdcp/raw_convert.h>
54 #include <libavcodec/avcodec.h>
55 #include <libavformat/avformat.h>
56 #include <libswscale/swscale.h>
57 #include <libavfilter/avfiltergraph.h>
58 #include <libavutil/pixfmt.h>
61 #include "exceptions.h"
63 #include "dcp_content_type.h"
65 #include "sound_processor.h"
70 #include "video_content.h"
71 #include "md5_digester.h"
72 #include "safe_stringstream.h"
73 #ifdef DCPOMATIC_WINDOWS
93 using std::numeric_limits;
98 using std::set_terminate;
99 using boost::shared_ptr;
101 using boost::optional;
103 using libdcp::raw_convert;
105 static boost::thread::id ui_thread;
106 static boost::filesystem::path backtrace_file;
108 /** Convert some number of seconds to a string representation
109 * in hours, minutes and seconds.
112 * @return String of the form H:M:S (where H is hours, M
113 * is minutes and S is seconds).
116 seconds_to_hms (int s)
123 SafeStringStream hms;
126 hms << std::setfill ('0') << m << N_(":");
128 hms << std::setfill ('0') << s;
133 /** @param s Number of seconds.
134 * @return String containing an approximate description of s (e.g. "about 2 hours")
137 seconds_to_approximate_hms (int s)
146 bool const hours = h > 0;
147 bool const minutes = h < 10 && m > 0;
148 bool const seconds = m < 10 && s > 0;
151 if (m > 30 && !minutes) {
152 ap << (h + 1) << N_(" ") << _("hours");
162 if (minutes | seconds) {
169 if (s > 30 && !seconds) {
170 ap << (m + 1) << N_(" ") << _("minutes");
198 #ifdef DCPOMATIC_POSIX
199 /** @param l Mangled C++ identifier.
200 * @return Demangled version.
205 string::size_type const b = l.find_first_of (N_("("));
206 if (b == string::npos) {
210 string::size_type const p = l.find_last_of (N_("+"));
211 if (p == string::npos) {
219 string const fn = l.substr (b + 1, p - b - 1);
224 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
229 } catch (std::exception) {
236 /** Write a stacktrace to an ostream.
237 * @param out Stream to write to.
238 * @param levels Number of levels to go up the call stack.
241 stacktrace (ostream& out, int levels)
244 size_t size = backtrace (array, 200);
245 char** strings = backtrace_symbols (array, size);
248 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
249 out << N_(" ") << demangle (strings[i]) << "\n";
257 /** @param v Version as used by FFmpeg.
258 * @return A string representation of v.
261 ffmpeg_version_to_string (int v)
264 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
268 /** Return a user-readable string summarising the versions of our dependencies */
270 dependency_version_summary ()
273 s << N_("libopenjpeg ") << opj_version () << N_(", ")
274 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
275 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
276 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
277 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
278 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
279 << MagickVersion << N_(", ")
280 << N_("libssh ") << ssh_version (0) << N_(", ")
281 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
287 seconds (struct timeval t)
289 return t.tv_sec + (double (t.tv_usec) / 1e6);
292 #ifdef DCPOMATIC_WINDOWS
293 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
296 FILE* f = fopen_boost (backtrace_file, "w");
297 fprintf (f, "Exception thrown:");
298 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
299 fprintf (f, "%p %s %d %s\n", i->instruction, i->function.c_str(), i->line, i->module.c_str());
302 return EXCEPTION_CONTINUE_SEARCH;
306 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
310 static bool tried_throw = false;
313 // try once to re-throw currently active exception
319 catch (const std::exception &e) {
320 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
321 << e.what() << std::endl;
324 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
328 #ifdef DCPOMATIC_POSIX
329 stacktrace (cout, 50);
334 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
335 * Must be called from the UI thread, if there is one.
340 #ifdef DCPOMATIC_WINDOWS
341 backtrace_file /= g_get_user_config_dir ();
342 backtrace_file /= "backtrace.txt";
343 SetUnhandledExceptionFilter(exception_handler);
345 /* Dark voodoo which, I think, gets boost::filesystem::path to
346 correctly convert UTF-8 strings to paths, and also paths
347 back to UTF-8 strings (on path::string()).
349 After this, constructing boost::filesystem::paths from strings
350 converts from UTF-8 to UTF-16 inside the path. Then
351 path::string().c_str() gives UTF-8 and
352 path::c_str() gives UTF-16.
354 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
355 so things are much simpler.
357 std::locale::global (boost::locale::generator().generate (""));
358 boost::filesystem::path::imbue (std::locale ());
361 avfilter_register_all ();
364 /* Add our lib directory to the libltdl search path so that
365 xmlsec can find xmlsec1-openssl.
367 boost::filesystem::path lib = app_contents ();
369 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
372 set_terminate (terminate);
376 Ratio::setup_ratios ();
377 VideoContentScale::setup_scales ();
378 DCPContentType::setup_dcp_content_types ();
379 Scaler::setup_scalers ();
380 Filter::setup_filters ();
381 SoundProcessor::setup_sound_processors ();
383 ui_thread = boost::this_thread::get_id ();
386 #ifdef DCPOMATIC_WINDOWS
387 boost::filesystem::path
391 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
392 boost::filesystem::path p (buffer);
393 p = p.parent_path ();
394 p = p.parent_path ();
401 boost::filesystem::path
404 return "DCP-o-matic.app/Contents/Resources";
409 dcpomatic_setup_gettext_i18n (string lang)
411 #ifdef DCPOMATIC_LINUX
415 if (!lang.empty ()) {
416 /* Override our environment language. Note that the caller must not
417 free the string passed into putenv().
419 string s = String::compose ("LANGUAGE=%1", lang);
420 putenv (strdup (s.c_str ()));
421 s = String::compose ("LANG=%1", lang);
422 putenv (strdup (s.c_str ()));
423 s = String::compose ("LC_ALL=%1", lang);
424 putenv (strdup (s.c_str ()));
427 setlocale (LC_ALL, "");
428 textdomain ("libdcpomatic");
430 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
431 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
432 bind_textdomain_codeset ("libdcpomatic", "UTF8");
435 #ifdef DCPOMATIC_LINUX
436 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
440 /** @param s A string.
441 * @return Parts of the string split at spaces, except when a space is within quotation marks.
444 split_at_spaces_considering_quotes (string s)
447 bool in_quotes = false;
449 for (string::size_type i = 0; i < s.length(); ++i) {
450 if (s[i] == ' ' && !in_quotes) {
453 } else if (s[i] == '"') {
454 in_quotes = !in_quotes;
464 /** @param job Optional job for which to report progress */
466 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
468 boost::uintmax_t const buffer_size = 64 * 1024;
469 char buffer[buffer_size];
471 MD5Digester digester;
473 vector<int64_t> sizes;
474 for (size_t i = 0; i < files.size(); ++i) {
475 sizes.push_back (boost::filesystem::file_size (files[i]));
478 for (size_t i = 0; i < files.size(); ++i) {
479 FILE* f = fopen_boost (files[i], "rb");
481 throw OpenFileError (files[i].string());
484 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
485 boost::uintmax_t remaining = bytes;
487 while (remaining > 0) {
488 int const t = min (remaining, buffer_size);
489 fread (buffer, 1, t, f);
490 digester.add (buffer, t);
494 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
501 return digester.get ();
504 /** @param An arbitrary audio frame rate.
505 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
508 dcp_audio_frame_rate (int fs)
517 Socket::Socket (int timeout)
518 : _deadline (_io_service)
519 , _socket (_io_service)
523 _deadline.expires_at (boost::posix_time::pos_infin);
535 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
537 _acceptor->cancel ();
541 _deadline.expires_at (boost::posix_time::pos_infin);
544 _deadline.async_wait (boost::bind (&Socket::check, this));
547 /** Blocking connect.
548 * @param endpoint End-point to connect to.
551 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
553 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
554 boost::system::error_code ec = boost::asio::error::would_block;
555 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
557 _io_service.run_one();
558 } while (ec == boost::asio::error::would_block);
561 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
564 if (!_socket.is_open ()) {
565 throw NetworkError (_("connect timed out"));
570 Socket::accept (int port)
572 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
574 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
575 boost::system::error_code ec = boost::asio::error::would_block;
576 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
578 _io_service.run_one ();
579 } while (ec == boost::asio::error::would_block);
585 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
590 * @param data Buffer to write.
591 * @param size Number of bytes to write.
594 Socket::write (uint8_t const * data, int size)
596 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
597 boost::system::error_code ec = boost::asio::error::would_block;
599 boost::asio::async_write (_socket, boost::asio::buffer (data, size), 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_write (%1)"), ec.value ()));
611 Socket::write (uint32_t v)
614 write (reinterpret_cast<uint8_t*> (&v), 4);
618 * @param data Buffer to read to.
619 * @param size Number of bytes to read.
622 Socket::read (uint8_t* data, int size)
624 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
625 boost::system::error_code ec = boost::asio::error::would_block;
627 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
630 _io_service.run_one ();
631 } while (ec == boost::asio::error::would_block);
634 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
639 Socket::read_uint32 ()
642 read (reinterpret_cast<uint8_t *> (&v), 4);
646 /** Round a number up to the nearest multiple of another number.
648 * @param s Array of numbers to round, indexed by c.
649 * @param t Multiple to round to.
650 * @return Rounded number.
653 stride_round_up (int c, int const * stride, int t)
655 int const a = stride[c] + (t - 1);
659 /** Read a sequence of key / value pairs from a text stream;
660 * the keys are the first words on the line, and the values are
661 * the remainder of the line following the key. Lines beginning
662 * with # are ignored.
663 * @param s Stream to read.
664 * @return key/value pairs.
666 multimap<string, string>
667 read_key_value (istream &s)
669 multimap<string, string> kv;
672 while (getline (s, line)) {
677 if (line[0] == '#') {
681 if (line[line.size() - 1] == '\r') {
682 line = line.substr (0, line.size() - 1);
685 size_t const s = line.find (' ');
686 if (s == string::npos) {
690 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
697 get_required_string (multimap<string, string> const & kv, string k)
699 if (kv.count (k) > 1) {
700 throw StringError (N_("unexpected multiple keys in key-value set"));
703 multimap<string, string>::const_iterator i = kv.find (k);
705 if (i == kv.end ()) {
706 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
713 get_required_int (multimap<string, string> const & kv, string k)
715 string const v = get_required_string (kv, k);
716 return raw_convert<int> (v);
720 get_required_float (multimap<string, string> const & kv, string k)
722 string const v = get_required_string (kv, k);
723 return raw_convert<float> (v);
727 get_optional_string (multimap<string, string> const & kv, string k)
729 if (kv.count (k) > 1) {
730 throw StringError (N_("unexpected multiple keys in key-value set"));
733 multimap<string, string>::const_iterator i = kv.find (k);
734 if (i == kv.end ()) {
742 get_optional_int (multimap<string, string> const & kv, string k)
744 if (kv.count (k) > 1) {
745 throw StringError (N_("unexpected multiple keys in key-value set"));
748 multimap<string, string>::const_iterator i = kv.find (k);
749 if (i == kv.end ()) {
753 return raw_convert<int> (i->second);
756 /** Trip an assert if the caller is not in the UI thread */
760 assert (boost::this_thread::get_id() == ui_thread);
763 /** @param v Content video frame.
764 * @param audio_sample_rate Source audio sample rate.
765 * @param frames_per_second Number of video frames per second.
766 * @return Equivalent number of audio frames for `v'.
769 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
771 return ((int64_t) v * audio_sample_rate / frames_per_second);
775 audio_channel_name (int c)
777 assert (MAX_DCP_AUDIO_CHANNELS == 12);
779 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
780 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
781 VI is the visually-impaired audio track (audio describe).
783 string const channels[] = {
790 _("Hearing impaired"),
791 _("Visually impaired"),
794 _("Left rear surround"),
795 _("Right rear surround"),
802 valid_image_file (boost::filesystem::path f)
804 string ext = f.extension().string();
805 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
806 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
810 tidy_for_filename (string f)
813 for (size_t i = 0; i < f.length(); ++i) {
814 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
824 shared_ptr<const libdcp::Signer>
827 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
829 /* Remake the chain if any of it is missing */
831 list<boost::filesystem::path> files;
832 files.push_back ("ca.self-signed.pem");
833 files.push_back ("intermediate.signed.pem");
834 files.push_back ("leaf.signed.pem");
835 files.push_back ("leaf.key");
837 list<boost::filesystem::path>::const_iterator i = files.begin();
838 while (i != files.end()) {
839 boost::filesystem::path p (sd);
841 if (!boost::filesystem::exists (p)) {
842 boost::filesystem::remove_all (sd);
843 boost::filesystem::create_directories (sd);
844 libdcp::make_signer_chain (sd, openssl_path ());
851 libdcp::CertificateChain chain;
854 boost::filesystem::path p (sd);
855 p /= "ca.self-signed.pem";
856 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
860 boost::filesystem::path p (sd);
861 p /= "intermediate.signed.pem";
862 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
866 boost::filesystem::path p (sd);
867 p /= "leaf.signed.pem";
868 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
871 boost::filesystem::path signer_key (sd);
872 signer_key /= "leaf.key";
874 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
878 split_get_request (string url)
881 AWAITING_QUESTION_MARK,
884 } state = AWAITING_QUESTION_MARK;
886 map<string, string> r;
889 for (size_t i = 0; i < url.length(); ++i) {
891 case AWAITING_QUESTION_MARK:
906 r.insert (make_pair (k, v));
916 if (state == VALUE) {
917 r.insert (make_pair (k, v));
924 fit_ratio_within (float ratio, libdcp::Size full_frame)
926 if (ratio < full_frame.ratio ()) {
927 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
930 return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));
934 wrapped_av_malloc (size_t s)
936 void* p = av_malloc (s);
944 entities_to_text (string e)
946 boost::algorithm::replace_all (e, "%3A", ":");
947 boost::algorithm::replace_all (e, "%2F", "/");
952 divide_with_round (int64_t a, int64_t b)
954 if (a % b >= (b / 2)) {
955 return (a + b - 1) / b;
961 ScopedTemporary::ScopedTemporary ()
964 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
967 ScopedTemporary::~ScopedTemporary ()
970 boost::system::error_code ec;
971 boost::filesystem::remove (_file, ec);
975 ScopedTemporary::c_str () const
977 return _file.string().c_str ();
981 ScopedTemporary::open (char const * params)
983 _open = fopen (c_str(), params);
988 ScopedTemporary::close ()