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
270 if (!tried_throw++) {
274 catch (const std::exception &e) {
275 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
276 << e.what() << std::endl;
279 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
283 #ifdef DCPOMATIC_POSIX
284 stacktrace (cout, 50);
289 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
290 * Must be called from the UI thread, if there is one.
295 #ifdef DCPOMATIC_WINDOWS
296 backtrace_file /= g_get_user_config_dir ();
297 backtrace_file /= "backtrace.txt";
298 SetUnhandledExceptionFilter(exception_handler);
300 /* Dark voodoo which, I think, gets boost::filesystem::path to
301 correctly convert UTF-8 strings to paths, and also paths
302 back to UTF-8 strings (on path::string()).
304 After this, constructing boost::filesystem::paths from strings
305 converts from UTF-8 to UTF-16 inside the path. Then
306 path::string().c_str() gives UTF-8 and
307 path::c_str() gives UTF-16.
309 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
310 so things are much simpler.
312 std::locale::global (boost::locale::generator().generate (""));
313 boost::filesystem::path::imbue (std::locale ());
316 avfilter_register_all ();
319 /* Add our lib directory to the libltdl search path so that
320 xmlsec can find xmlsec1-openssl.
322 boost::filesystem::path lib = app_contents ();
324 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
327 set_terminate (terminate);
332 Ratio::setup_ratios ();
333 VideoContentScale::setup_scales ();
334 DCPContentType::setup_dcp_content_types ();
335 Scaler::setup_scalers ();
336 Filter::setup_filters ();
337 SoundProcessor::setup_sound_processors ();
339 ui_thread = boost::this_thread::get_id ();
342 #ifdef DCPOMATIC_WINDOWS
343 boost::filesystem::path
347 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
348 boost::filesystem::path p (buffer);
349 p = p.parent_path ();
350 p = p.parent_path ();
357 dcpomatic_setup_gettext_i18n (string lang)
359 #ifdef DCPOMATIC_POSIX
363 if (!lang.empty ()) {
364 /* Override our environment language; this is essential on
368 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
370 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
372 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
376 setlocale (LC_ALL, "");
377 textdomain ("libdcpomatic");
379 #ifdef DCPOMATIC_WINDOWS
380 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
381 bind_textdomain_codeset ("libdcpomatic", "UTF8");
384 #ifdef DCPOMATIC_POSIX
385 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
389 /** @param s A string.
390 * @return Parts of the string split at spaces, except when a space is within quotation marks.
393 split_at_spaces_considering_quotes (string s)
396 bool in_quotes = false;
398 for (string::size_type i = 0; i < s.length(); ++i) {
399 if (s[i] == ' ' && !in_quotes) {
402 } else if (s[i] == '"') {
403 in_quotes = !in_quotes;
413 /** @param job Optional job for which to report progress */
415 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
417 boost::uintmax_t const buffer_size = 64 * 1024;
418 char buffer[buffer_size];
420 MD5Digester digester;
422 vector<int64_t> sizes;
423 for (size_t i = 0; i < files.size(); ++i) {
424 sizes.push_back (boost::filesystem::file_size (files[i]));
427 for (size_t i = 0; i < files.size(); ++i) {
428 FILE* f = fopen_boost (files[i], "rb");
430 throw OpenFileError (files[i].string());
433 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
434 boost::uintmax_t remaining = bytes;
436 while (remaining > 0) {
437 int const t = min (remaining, buffer_size);
438 fread (buffer, 1, t, f);
439 digester.add (buffer, t);
443 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
450 return digester.get ();
453 /** @param An arbitrary audio frame rate.
454 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
457 dcp_audio_frame_rate (int fs)
466 Socket::Socket (int timeout)
467 : _deadline (_io_service)
468 , _socket (_io_service)
472 _deadline.expires_at (boost::posix_time::pos_infin);
484 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
486 _acceptor->cancel ();
490 _deadline.expires_at (boost::posix_time::pos_infin);
493 _deadline.async_wait (boost::bind (&Socket::check, this));
496 /** Blocking connect.
497 * @param endpoint End-point to connect to.
500 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
502 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
503 boost::system::error_code ec = boost::asio::error::would_block;
504 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
506 _io_service.run_one();
507 } while (ec == boost::asio::error::would_block);
510 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
513 if (!_socket.is_open ()) {
514 throw NetworkError (_("connect timed out"));
519 Socket::accept (int port)
521 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
523 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
524 boost::system::error_code ec = boost::asio::error::would_block;
525 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
527 _io_service.run_one ();
528 } while (ec == boost::asio::error::would_block );
534 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
539 * @param data Buffer to write.
540 * @param size Number of bytes to write.
543 Socket::write (uint8_t const * data, int size)
545 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
546 boost::system::error_code ec = boost::asio::error::would_block;
548 boost::asio::async_write (_socket, boost::asio::buffer (data, size), 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_write (%1)"), ec.value ()));
560 Socket::write (uint32_t v)
563 write (reinterpret_cast<uint8_t*> (&v), 4);
567 * @param data Buffer to read to.
568 * @param size Number of bytes to read.
571 Socket::read (uint8_t* data, int size)
573 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
574 boost::system::error_code ec = boost::asio::error::would_block;
576 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
579 _io_service.run_one ();
580 } while (ec == boost::asio::error::would_block);
583 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
588 Socket::read_uint32 ()
591 read (reinterpret_cast<uint8_t *> (&v), 4);
595 /** Round a number up to the nearest multiple of another number.
597 * @param s Array of numbers to round, indexed by c.
598 * @param t Multiple to round to.
599 * @return Rounded number.
602 stride_round_up (int c, int const * stride, int t)
604 int const a = stride[c] + (t - 1);
608 /** Read a sequence of key / value pairs from a text stream;
609 * the keys are the first words on the line, and the values are
610 * the remainder of the line following the key. Lines beginning
611 * with # are ignored.
612 * @param s Stream to read.
613 * @return key/value pairs.
615 multimap<string, string>
616 read_key_value (istream &s)
618 multimap<string, string> kv;
621 while (getline (s, line)) {
626 if (line[0] == '#') {
630 if (line[line.size() - 1] == '\r') {
631 line = line.substr (0, line.size() - 1);
634 size_t const s = line.find (' ');
635 if (s == string::npos) {
639 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
646 get_required_string (multimap<string, string> const & kv, string k)
648 if (kv.count (k) > 1) {
649 throw StringError (N_("unexpected multiple keys in key-value set"));
652 multimap<string, string>::const_iterator i = kv.find (k);
654 if (i == kv.end ()) {
655 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
662 get_required_int (multimap<string, string> const & kv, string k)
664 string const v = get_required_string (kv, k);
665 return raw_convert<int> (v);
669 get_required_float (multimap<string, string> const & kv, string k)
671 string const v = get_required_string (kv, k);
672 return raw_convert<float> (v);
676 get_optional_string (multimap<string, string> const & kv, string k)
678 if (kv.count (k) > 1) {
679 throw StringError (N_("unexpected multiple keys in key-value set"));
682 multimap<string, string>::const_iterator i = kv.find (k);
683 if (i == kv.end ()) {
691 get_optional_int (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);
698 if (i == kv.end ()) {
702 return raw_convert<int> (i->second);
705 /** Trip an assert if the caller is not in the UI thread */
709 assert (boost::this_thread::get_id() == ui_thread);
713 audio_channel_name (int c)
715 assert (MAX_DCP_AUDIO_CHANNELS == 12);
717 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
718 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
719 VI is the visually-impaired audio track (audio describe).
721 string const channels[] = {
728 _("Hearing impaired"),
729 _("Visually impaired"),
732 _("Left rear surround"),
733 _("Right rear surround"),
740 valid_image_file (boost::filesystem::path f)
742 string ext = f.extension().string();
743 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
744 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
748 tidy_for_filename (string f)
751 for (size_t i = 0; i < f.length(); ++i) {
752 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
762 shared_ptr<const dcp::Signer>
765 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
767 /* Remake the chain if any of it is missing */
769 list<boost::filesystem::path> files;
770 files.push_back ("ca.self-signed.pem");
771 files.push_back ("intermediate.signed.pem");
772 files.push_back ("leaf.signed.pem");
773 files.push_back ("leaf.key");
775 list<boost::filesystem::path>::const_iterator i = files.begin();
776 while (i != files.end()) {
777 boost::filesystem::path p (sd);
779 if (!boost::filesystem::exists (p)) {
780 boost::filesystem::remove_all (sd);
781 boost::filesystem::create_directories (sd);
782 dcp::make_signer_chain (sd, openssl_path ());
789 dcp::CertificateChain chain;
792 boost::filesystem::path p (sd);
793 p /= "ca.self-signed.pem";
794 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
798 boost::filesystem::path p (sd);
799 p /= "intermediate.signed.pem";
800 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
804 boost::filesystem::path p (sd);
805 p /= "leaf.signed.pem";
806 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
809 boost::filesystem::path signer_key (sd);
810 signer_key /= "leaf.key";
812 return shared_ptr<const dcp::Signer> (new dcp::Signer (chain, signer_key));
816 split_get_request (string url)
819 AWAITING_QUESTION_MARK,
822 } state = AWAITING_QUESTION_MARK;
824 map<string, string> r;
827 for (size_t i = 0; i < url.length(); ++i) {
829 case AWAITING_QUESTION_MARK:
844 r.insert (make_pair (k, v));
854 if (state == VALUE) {
855 r.insert (make_pair (k, v));
862 fit_ratio_within (float ratio, dcp::Size full_frame)
864 if (ratio < full_frame.ratio ()) {
865 return dcp::Size (rint (full_frame.height * ratio), full_frame.height);
868 return dcp::Size (full_frame.width, rint (full_frame.width / ratio));
872 wrapped_av_malloc (size_t s)
874 void* p = av_malloc (s);
882 entities_to_text (string e)
884 boost::algorithm::replace_all (e, "%3A", ":");
885 boost::algorithm::replace_all (e, "%2F", "/");
890 divide_with_round (int64_t a, int64_t b)
892 if (a % b >= (b / 2)) {
893 return (a + b - 1) / b;
899 /** Return a user-readable string summarising the versions of our dependencies */
901 dependency_version_summary ()
904 s << N_("libopenjpeg ") << opj_version () << N_(", ")
905 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
906 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
907 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
908 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
909 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
910 << MagickVersion << N_(", ")
911 << N_("libssh ") << ssh_version (0) << N_(", ")
912 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
917 /** Construct a ScopedTemporary. A temporary filename is decided but the file is not opened
918 * until ::open() is called.
920 ScopedTemporary::ScopedTemporary ()
923 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
926 /** Close and delete the temporary file */
927 ScopedTemporary::~ScopedTemporary ()
930 boost::system::error_code ec;
931 boost::filesystem::remove (_file, ec);
934 /** @return temporary filename */
936 ScopedTemporary::c_str () const
938 return _file.string().c_str ();
941 /** Open the temporary file.
942 * @return File's FILE pointer.
945 ScopedTemporary::open (char const * params)
947 _open = fopen (c_str(), params);
951 /** Close the file */
953 ScopedTemporary::close ()
962 subtitle_period (AVSubtitle const & sub)
964 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
966 ContentTimePeriod period (
967 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
968 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)