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_chain.h>
53 #include <dcp/signer.h>
54 #include <dcp/raw_convert.h>
56 #include <libavcodec/avcodec.h>
57 #include <libavformat/avformat.h>
58 #include <libswscale/swscale.h>
59 #include <libavfilter/avfiltergraph.h>
60 #include <libavutil/pixfmt.h>
63 #include "exceptions.h"
65 #include "dcp_content_type.h"
67 #include "sound_processor.h"
72 #include "video_content.h"
74 #include "md5_digester.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)
151 ap << (h + 1) << N_(" ") << _("hours");
154 ap << N_("1 ") << _("hour");
156 ap << h << N_(" ") << _("hours");
161 ap << N_("1 ") << _("minute");
163 ap << m << N_(" ") << _("minutes");
166 ap << s << N_(" ") << _("seconds");
172 #ifdef DCPOMATIC_POSIX
173 /** @param l Mangled C++ identifier.
174 * @return Demangled version.
179 string::size_type const b = l.find_first_of (N_("("));
180 if (b == string::npos) {
184 string::size_type const p = l.find_last_of (N_("+"));
185 if (p == string::npos) {
193 string const fn = l.substr (b + 1, p - b - 1);
198 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
203 } catch (std::exception) {
210 /** Write a stacktrace to an ostream.
211 * @param out Stream to write to.
212 * @param levels Number of levels to go up the call stack.
215 stacktrace (ostream& out, int levels)
218 size_t size = backtrace (array, 200);
219 char** strings = backtrace_symbols (array, size);
222 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
223 out << N_(" ") << demangle (strings[i]) << "\n";
231 /** @param v Version as used by FFmpeg.
232 * @return A string representation of v.
235 ffmpeg_version_to_string (int v)
238 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
243 seconds (struct timeval t)
245 return t.tv_sec + (double (t.tv_usec) / 1e6);
248 #ifdef DCPOMATIC_WINDOWS
249 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
252 FILE* f = fopen_boost (backtrace_file, "w");
253 fprintf (f, "Exception thrown:");
254 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
255 fprintf (f, "%p %s %d %s\n", i->instruction, i->function.c_str(), i->line, i->module.c_str());
258 return EXCEPTION_CONTINUE_SEARCH;
262 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
266 static bool tried_throw = false;
269 // try once to re-throw currently active exception
275 catch (const std::exception &e) {
276 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
277 << e.what() << std::endl;
280 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
284 #ifdef DCPOMATIC_POSIX
285 stacktrace (cout, 50);
290 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
291 * Must be called from the UI thread, if there is one.
296 #ifdef DCPOMATIC_WINDOWS
297 backtrace_file /= g_get_user_config_dir ();
298 backtrace_file /= "backtrace.txt";
299 SetUnhandledExceptionFilter(exception_handler);
301 /* Dark voodoo which, I think, gets boost::filesystem::path to
302 correctly convert UTF-8 strings to paths, and also paths
303 back to UTF-8 strings (on path::string()).
305 After this, constructing boost::filesystem::paths from strings
306 converts from UTF-8 to UTF-16 inside the path. Then
307 path::string().c_str() gives UTF-8 and
308 path::c_str() gives UTF-16.
310 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
311 so things are much simpler.
313 std::locale::global (boost::locale::generator().generate (""));
314 boost::filesystem::path::imbue (std::locale ());
317 avfilter_register_all ();
320 /* Add our lib directory to the libltdl search path so that
321 xmlsec can find xmlsec1-openssl.
323 boost::filesystem::path lib = app_contents ();
325 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
328 set_terminate (terminate);
333 Ratio::setup_ratios ();
334 VideoContentScale::setup_scales ();
335 DCPContentType::setup_dcp_content_types ();
336 Scaler::setup_scalers ();
337 Filter::setup_filters ();
338 SoundProcessor::setup_sound_processors ();
340 ui_thread = boost::this_thread::get_id ();
343 #ifdef DCPOMATIC_WINDOWS
344 boost::filesystem::path
348 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
349 boost::filesystem::path p (buffer);
350 p = p.parent_path ();
351 p = p.parent_path ();
358 dcpomatic_setup_gettext_i18n (string lang)
360 #ifdef DCPOMATIC_POSIX
364 if (!lang.empty ()) {
365 /* Override our environment language; this is essential on
369 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
371 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
373 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
377 setlocale (LC_ALL, "");
378 textdomain ("libdcpomatic");
380 #ifdef DCPOMATIC_WINDOWS
381 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
382 bind_textdomain_codeset ("libdcpomatic", "UTF8");
385 #ifdef DCPOMATIC_POSIX
386 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
390 /** @param s A string.
391 * @return Parts of the string split at spaces, except when a space is within quotation marks.
394 split_at_spaces_considering_quotes (string s)
397 bool in_quotes = false;
399 for (string::size_type i = 0; i < s.length(); ++i) {
400 if (s[i] == ' ' && !in_quotes) {
403 } else if (s[i] == '"') {
404 in_quotes = !in_quotes;
414 /** @param job Optional job for which to report progress */
416 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
418 boost::uintmax_t const buffer_size = 64 * 1024;
419 char buffer[buffer_size];
421 MD5Digester digester;
423 vector<int64_t> sizes;
424 for (size_t i = 0; i < files.size(); ++i) {
425 sizes.push_back (boost::filesystem::file_size (files[i]));
428 for (size_t i = 0; i < files.size(); ++i) {
429 FILE* f = fopen_boost (files[i], "rb");
431 throw OpenFileError (files[i].string());
434 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
435 boost::uintmax_t remaining = bytes;
437 while (remaining > 0) {
438 int const t = min (remaining, buffer_size);
439 fread (buffer, 1, t, f);
440 digester.add (buffer, t);
444 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
451 return digester.get ();
454 /** @param An arbitrary audio frame rate.
455 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
458 dcp_audio_frame_rate (int fs)
467 Socket::Socket (int timeout)
468 : _deadline (_io_service)
469 , _socket (_io_service)
473 _deadline.expires_at (boost::posix_time::pos_infin);
485 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
487 _acceptor->cancel ();
491 _deadline.expires_at (boost::posix_time::pos_infin);
494 _deadline.async_wait (boost::bind (&Socket::check, this));
497 /** Blocking connect.
498 * @param endpoint End-point to connect to.
501 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
503 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
504 boost::system::error_code ec = boost::asio::error::would_block;
505 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
507 _io_service.run_one();
508 } while (ec == boost::asio::error::would_block);
511 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
514 if (!_socket.is_open ()) {
515 throw NetworkError (_("connect timed out"));
520 Socket::accept (int port)
522 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
524 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
525 boost::system::error_code ec = boost::asio::error::would_block;
526 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
528 _io_service.run_one ();
529 } while (ec == boost::asio::error::would_block );
535 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
540 * @param data Buffer to write.
541 * @param size Number of bytes to write.
544 Socket::write (uint8_t const * data, int size)
546 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
547 boost::system::error_code ec = boost::asio::error::would_block;
549 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
552 _io_service.run_one ();
553 } while (ec == boost::asio::error::would_block);
556 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
561 Socket::write (uint32_t v)
564 write (reinterpret_cast<uint8_t*> (&v), 4);
568 * @param data Buffer to read to.
569 * @param size Number of bytes to read.
572 Socket::read (uint8_t* data, int size)
574 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
575 boost::system::error_code ec = boost::asio::error::would_block;
577 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
580 _io_service.run_one ();
581 } while (ec == boost::asio::error::would_block);
584 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
589 Socket::read_uint32 ()
592 read (reinterpret_cast<uint8_t *> (&v), 4);
596 /** Round a number up to the nearest multiple of another number.
598 * @param s Array of numbers to round, indexed by c.
599 * @param t Multiple to round to.
600 * @return Rounded number.
603 stride_round_up (int c, int const * stride, int t)
605 int const a = stride[c] + (t - 1);
609 /** Read a sequence of key / value pairs from a text stream;
610 * the keys are the first words on the line, and the values are
611 * the remainder of the line following the key. Lines beginning
612 * with # are ignored.
613 * @param s Stream to read.
614 * @return key/value pairs.
616 multimap<string, string>
617 read_key_value (istream &s)
619 multimap<string, string> kv;
622 while (getline (s, line)) {
627 if (line[0] == '#') {
631 if (line[line.size() - 1] == '\r') {
632 line = line.substr (0, line.size() - 1);
635 size_t const s = line.find (' ');
636 if (s == string::npos) {
640 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
647 get_required_string (multimap<string, string> const & kv, string k)
649 if (kv.count (k) > 1) {
650 throw StringError (N_("unexpected multiple keys in key-value set"));
653 multimap<string, string>::const_iterator i = kv.find (k);
655 if (i == kv.end ()) {
656 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
663 get_required_int (multimap<string, string> const & kv, string k)
665 string const v = get_required_string (kv, k);
666 return raw_convert<int> (v);
670 get_required_float (multimap<string, string> const & kv, string k)
672 string const v = get_required_string (kv, k);
673 return raw_convert<float> (v);
677 get_optional_string (multimap<string, string> const & kv, string k)
679 if (kv.count (k) > 1) {
680 throw StringError (N_("unexpected multiple keys in key-value set"));
683 multimap<string, string>::const_iterator i = kv.find (k);
684 if (i == kv.end ()) {
692 get_optional_int (multimap<string, string> const & kv, string k)
694 if (kv.count (k) > 1) {
695 throw StringError (N_("unexpected multiple keys in key-value set"));
698 multimap<string, string>::const_iterator i = kv.find (k);
699 if (i == kv.end ()) {
703 return raw_convert<int> (i->second);
706 /** Trip an assert if the caller is not in the UI thread */
710 assert (boost::this_thread::get_id() == ui_thread);
714 audio_channel_name (int c)
716 assert (MAX_DCP_AUDIO_CHANNELS == 12);
718 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
719 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
720 VI is the visually-impaired audio track (audio describe).
722 string const channels[] = {
729 _("Hearing impaired"),
730 _("Visually impaired"),
733 _("Left rear surround"),
734 _("Right rear surround"),
741 valid_image_file (boost::filesystem::path f)
743 string ext = f.extension().string();
744 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
745 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
749 tidy_for_filename (string f)
752 for (size_t i = 0; i < f.length(); ++i) {
753 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
763 shared_ptr<const dcp::Signer>
766 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
768 /* Remake the chain if any of it is missing */
770 list<boost::filesystem::path> files;
771 files.push_back ("ca.self-signed.pem");
772 files.push_back ("intermediate.signed.pem");
773 files.push_back ("leaf.signed.pem");
774 files.push_back ("leaf.key");
776 list<boost::filesystem::path>::const_iterator i = files.begin();
777 while (i != files.end()) {
778 boost::filesystem::path p (sd);
780 if (!boost::filesystem::exists (p)) {
781 boost::filesystem::remove_all (sd);
782 boost::filesystem::create_directories (sd);
783 dcp::make_signer_chain (sd, openssl_path ());
790 dcp::CertificateChain chain;
793 boost::filesystem::path p (sd);
794 p /= "ca.self-signed.pem";
795 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
799 boost::filesystem::path p (sd);
800 p /= "intermediate.signed.pem";
801 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
805 boost::filesystem::path p (sd);
806 p /= "leaf.signed.pem";
807 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
810 boost::filesystem::path signer_key (sd);
811 signer_key /= "leaf.key";
813 return shared_ptr<const dcp::Signer> (new dcp::Signer (chain, signer_key));
817 split_get_request (string url)
820 AWAITING_QUESTION_MARK,
823 } state = AWAITING_QUESTION_MARK;
825 map<string, string> r;
828 for (size_t i = 0; i < url.length(); ++i) {
830 case AWAITING_QUESTION_MARK:
845 r.insert (make_pair (k, v));
855 if (state == VALUE) {
856 r.insert (make_pair (k, v));
863 fit_ratio_within (float ratio, dcp::Size full_frame)
865 if (ratio < full_frame.ratio ()) {
866 return dcp::Size (rint (full_frame.height * ratio), full_frame.height);
869 return dcp::Size (full_frame.width, rint (full_frame.width / ratio));
873 wrapped_av_malloc (size_t s)
875 void* p = av_malloc (s);
883 entities_to_text (string e)
885 boost::algorithm::replace_all (e, "%3A", ":");
886 boost::algorithm::replace_all (e, "%2F", "/");
891 divide_with_round (int64_t a, int64_t b)
893 if (a % b >= (b / 2)) {
894 return (a + b - 1) / b;
900 /** Return a user-readable string summarising the versions of our dependencies */
902 dependency_version_summary ()
905 s << N_("libopenjpeg ") << opj_version () << N_(", ")
906 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
907 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
908 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
909 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
910 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
911 << MagickVersion << N_(", ")
912 << N_("libssh ") << ssh_version (0) << N_(", ")
913 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
918 /** Construct a ScopedTemporary. A temporary filename is decided but the file is not opened
919 * until ::open() is called.
921 ScopedTemporary::ScopedTemporary ()
924 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
927 /** Close and delete the temporary file */
928 ScopedTemporary::~ScopedTemporary ()
931 boost::system::error_code ec;
932 boost::filesystem::remove (_file, ec);
935 /** @return temporary filename */
937 ScopedTemporary::c_str () const
939 return _file.string().c_str ();
942 /** Open the temporary file.
943 * @return File's FILE pointer.
946 ScopedTemporary::open (char const * params)
948 _open = fopen (c_str(), params);
952 /** Close the file */
954 ScopedTemporary::close ()
963 subtitle_period (AVSubtitle const & sub)
965 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
967 ContentTimePeriod period (
968 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
969 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)