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/lexical_cast.hpp>
41 #include <boost/thread.hpp>
42 #include <boost/filesystem.hpp>
43 #ifdef DCPOMATIC_WINDOWS
44 #include <boost/locale.hpp>
48 #include <openssl/md5.h>
49 #include <pangomm/init.h>
50 #include <magick/MagickCore.h>
51 #include <magick/version.h>
52 #include <dcp/version.h>
54 #include <dcp/signer_chain.h>
55 #include <dcp/signer.h>
57 #include <libavcodec/avcodec.h>
58 #include <libavformat/avformat.h>
59 #include <libswscale/swscale.h>
60 #include <libavfilter/avfiltergraph.h>
61 #include <libavutil/pixfmt.h>
64 #include "exceptions.h"
66 #include "dcp_content_type.h"
68 #include "sound_processor.h"
73 #include "video_content.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::lexical_cast;
105 using boost::optional;
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 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
254 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
257 return EXCEPTION_CONTINUE_SEARCH;
261 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
265 static bool tried_throw = false;
268 // try once to re-throw currently active exception
269 if (!tried_throw++) {
273 catch (const std::exception &e) {
274 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
275 << e.what() << std::endl;
278 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
282 #ifdef DCPOMATIC_POSIX
283 stacktrace (cout, 50);
288 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
289 * Must be called from the UI thread, if there is one.
294 #ifdef DCPOMATIC_WINDOWS
295 backtrace_file /= g_get_user_config_dir ();
296 backtrace_file /= "backtrace.txt";
297 SetUnhandledExceptionFilter(exception_handler);
299 /* Dark voodoo which, I think, gets boost::filesystem::path to
300 correctly convert UTF-8 strings to paths, and also paths
301 back to UTF-8 strings (on path::string()).
303 After this, constructing boost::filesystem::paths from strings
304 converts from UTF-8 to UTF-16 inside the path. Then
305 path::string().c_str() gives UTF-8 and
306 path::c_str() gives UTF-16.
308 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
309 so things are much simpler.
311 std::locale::global (boost::locale::generator().generate (""));
312 boost::filesystem::path::imbue (std::locale ());
315 avfilter_register_all ();
318 /* Add our lib directory to the libltdl search path so that
319 xmlsec can find xmlsec1-openssl.
321 boost::filesystem::path lib = app_contents ();
323 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
326 set_terminate (terminate);
331 Ratio::setup_ratios ();
332 VideoContentScale::setup_scales ();
333 DCPContentType::setup_dcp_content_types ();
334 Scaler::setup_scalers ();
335 Filter::setup_filters ();
336 SoundProcessor::setup_sound_processors ();
338 ui_thread = boost::this_thread::get_id ();
341 #ifdef DCPOMATIC_WINDOWS
342 boost::filesystem::path
346 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
347 boost::filesystem::path p (buffer);
348 p = p.parent_path ();
349 p = p.parent_path ();
356 dcpomatic_setup_gettext_i18n (string lang)
358 #ifdef DCPOMATIC_POSIX
362 if (!lang.empty ()) {
363 /* Override our environment language; this is essential on
367 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
369 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
371 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
375 setlocale (LC_ALL, "");
376 textdomain ("libdcpomatic");
378 #ifdef DCPOMATIC_WINDOWS
379 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
380 bind_textdomain_codeset ("libdcpomatic", "UTF8");
383 #ifdef DCPOMATIC_POSIX
384 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
388 /** @param s A string.
389 * @return Parts of the string split at spaces, except when a space is within quotation marks.
392 split_at_spaces_considering_quotes (string s)
395 bool in_quotes = false;
397 for (string::size_type i = 0; i < s.length(); ++i) {
398 if (s[i] == ' ' && !in_quotes) {
401 } else if (s[i] == '"') {
402 in_quotes = !in_quotes;
413 md5_digest (void const * data, int size)
416 MD5_Init (&md5_context);
417 MD5_Update (&md5_context, data, size);
418 unsigned char digest[MD5_DIGEST_LENGTH];
419 MD5_Final (digest, &md5_context);
422 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
423 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
429 /** @param job Optional job for which to report progress */
431 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
433 boost::uintmax_t const buffer_size = 64 * 1024;
434 char buffer[buffer_size];
437 MD5_Init (&md5_context);
439 vector<int64_t> sizes;
440 for (size_t i = 0; i < files.size(); ++i) {
441 sizes.push_back (boost::filesystem::file_size (files[i]));
444 for (size_t i = 0; i < files.size(); ++i) {
445 FILE* f = fopen_boost (files[i], "rb");
447 throw OpenFileError (files[i].string());
450 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
451 boost::uintmax_t remaining = bytes;
453 while (remaining > 0) {
454 int const t = min (remaining, buffer_size);
455 fread (buffer, 1, t, f);
456 MD5_Update (&md5_context, buffer, t);
460 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
467 unsigned char digest[MD5_DIGEST_LENGTH];
468 MD5_Final (digest, &md5_context);
471 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
472 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
478 /** @param An arbitrary audio frame rate.
479 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
482 dcp_audio_frame_rate (int fs)
491 Socket::Socket (int timeout)
492 : _deadline (_io_service)
493 , _socket (_io_service)
497 _deadline.expires_at (boost::posix_time::pos_infin);
509 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
511 _acceptor->cancel ();
515 _deadline.expires_at (boost::posix_time::pos_infin);
518 _deadline.async_wait (boost::bind (&Socket::check, this));
521 /** Blocking connect.
522 * @param endpoint End-point to connect to.
525 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
527 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
528 boost::system::error_code ec = boost::asio::error::would_block;
529 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
531 _io_service.run_one();
532 } while (ec == boost::asio::error::would_block);
535 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
538 if (!_socket.is_open ()) {
539 throw NetworkError (_("connect timed out"));
544 Socket::accept (int port)
546 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
548 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
549 boost::system::error_code ec = boost::asio::error::would_block;
550 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
552 _io_service.run_one ();
553 } while (ec == boost::asio::error::would_block );
559 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
564 * @param data Buffer to write.
565 * @param size Number of bytes to write.
568 Socket::write (uint8_t const * data, int size)
570 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
571 boost::system::error_code ec = boost::asio::error::would_block;
573 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
576 _io_service.run_one ();
577 } while (ec == boost::asio::error::would_block);
580 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
585 Socket::write (uint32_t v)
588 write (reinterpret_cast<uint8_t*> (&v), 4);
592 * @param data Buffer to read to.
593 * @param size Number of bytes to read.
596 Socket::read (uint8_t* data, int size)
598 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
599 boost::system::error_code ec = boost::asio::error::would_block;
601 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
604 _io_service.run_one ();
605 } while (ec == boost::asio::error::would_block);
608 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
613 Socket::read_uint32 ()
616 read (reinterpret_cast<uint8_t *> (&v), 4);
620 /** Round a number up to the nearest multiple of another number.
622 * @param s Array of numbers to round, indexed by c.
623 * @param t Multiple to round to.
624 * @return Rounded number.
627 stride_round_up (int c, int const * stride, int t)
629 int const a = stride[c] + (t - 1);
633 /** Read a sequence of key / value pairs from a text stream;
634 * the keys are the first words on the line, and the values are
635 * the remainder of the line following the key. Lines beginning
636 * with # are ignored.
637 * @param s Stream to read.
638 * @return key/value pairs.
640 multimap<string, string>
641 read_key_value (istream &s)
643 multimap<string, string> kv;
646 while (getline (s, line)) {
651 if (line[0] == '#') {
655 if (line[line.size() - 1] == '\r') {
656 line = line.substr (0, line.size() - 1);
659 size_t const s = line.find (' ');
660 if (s == string::npos) {
664 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
671 get_required_string (multimap<string, string> const & kv, string k)
673 if (kv.count (k) > 1) {
674 throw StringError (N_("unexpected multiple keys in key-value set"));
677 multimap<string, string>::const_iterator i = kv.find (k);
679 if (i == kv.end ()) {
680 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
687 get_required_int (multimap<string, string> const & kv, string k)
689 string const v = get_required_string (kv, k);
690 return lexical_cast<int> (v);
694 get_required_float (multimap<string, string> const & kv, string k)
696 string const v = get_required_string (kv, k);
697 return lexical_cast<float> (v);
701 get_optional_string (multimap<string, string> const & kv, string k)
703 if (kv.count (k) > 1) {
704 throw StringError (N_("unexpected multiple keys in key-value set"));
707 multimap<string, string>::const_iterator i = kv.find (k);
708 if (i == kv.end ()) {
716 get_optional_int (multimap<string, string> const & kv, string k)
718 if (kv.count (k) > 1) {
719 throw StringError (N_("unexpected multiple keys in key-value set"));
722 multimap<string, string>::const_iterator i = kv.find (k);
723 if (i == kv.end ()) {
727 return lexical_cast<int> (i->second);
730 /** Trip an assert if the caller is not in the UI thread */
734 assert (boost::this_thread::get_id() == ui_thread);
738 audio_channel_name (int c)
740 assert (MAX_DCP_AUDIO_CHANNELS == 12);
742 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
743 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
744 VI is the visually-impaired audio track (audio describe).
746 string const channels[] = {
753 _("Hearing impaired"),
754 _("Visually impaired"),
757 _("Left rear surround"),
758 _("Right rear surround"),
764 LocaleGuard::LocaleGuard ()
767 char const * old = setlocale (LC_NUMERIC, 0);
771 if (strcmp (_old, "C")) {
772 setlocale (LC_NUMERIC, "C");
777 LocaleGuard::~LocaleGuard ()
779 setlocale (LC_NUMERIC, _old);
784 valid_image_file (boost::filesystem::path f)
786 string ext = f.extension().string();
787 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
788 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
792 tidy_for_filename (string f)
795 for (size_t i = 0; i < f.length(); ++i) {
796 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
806 shared_ptr<const dcp::Signer>
809 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
811 /* Remake the chain if any of it is missing */
813 list<boost::filesystem::path> files;
814 files.push_back ("ca.self-signed.pem");
815 files.push_back ("intermediate.signed.pem");
816 files.push_back ("leaf.signed.pem");
817 files.push_back ("leaf.key");
819 list<boost::filesystem::path>::const_iterator i = files.begin();
820 while (i != files.end()) {
821 boost::filesystem::path p (sd);
823 if (!boost::filesystem::exists (p)) {
824 boost::filesystem::remove_all (sd);
825 boost::filesystem::create_directories (sd);
826 dcp::make_signer_chain (sd, openssl_path ());
833 dcp::CertificateChain chain;
836 boost::filesystem::path p (sd);
837 p /= "ca.self-signed.pem";
838 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
842 boost::filesystem::path p (sd);
843 p /= "intermediate.signed.pem";
844 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
848 boost::filesystem::path p (sd);
849 p /= "leaf.signed.pem";
850 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
853 boost::filesystem::path signer_key (sd);
854 signer_key /= "leaf.key";
856 return shared_ptr<const dcp::Signer> (new dcp::Signer (chain, signer_key));
860 split_get_request (string url)
863 AWAITING_QUESTION_MARK,
866 } state = AWAITING_QUESTION_MARK;
868 map<string, string> r;
871 for (size_t i = 0; i < url.length(); ++i) {
873 case AWAITING_QUESTION_MARK:
888 r.insert (make_pair (k, v));
898 if (state == VALUE) {
899 r.insert (make_pair (k, v));
906 fit_ratio_within (float ratio, dcp::Size full_frame)
908 if (ratio < full_frame.ratio ()) {
909 return dcp::Size (rint (full_frame.height * ratio), full_frame.height);
912 return dcp::Size (full_frame.width, rint (full_frame.width / ratio));
916 wrapped_av_malloc (size_t s)
918 void* p = av_malloc (s);
926 entities_to_text (string e)
928 boost::algorithm::replace_all (e, "%3A", ":");
929 boost::algorithm::replace_all (e, "%2F", "/");
934 divide_with_round (int64_t a, int64_t b)
936 if (a % b >= (b / 2)) {
937 return (a + b - 1) / b;
943 /** Return a user-readable string summarising the versions of our dependencies */
945 dependency_version_summary ()
948 s << N_("libopenjpeg ") << opj_version () << N_(", ")
949 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
950 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
951 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
952 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
953 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
954 << MagickVersion << N_(", ")
955 << N_("libssh ") << ssh_version (0) << N_(", ")
956 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
961 /** Construct a ScopedTemporary. A temporary filename is decided but the file is not opened
962 * until ::open() is called.
964 ScopedTemporary::ScopedTemporary ()
967 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
970 /** Close and delete the temporary file */
971 ScopedTemporary::~ScopedTemporary ()
974 boost::system::error_code ec;
975 boost::filesystem::remove (_file, ec);
978 /** @return temporary filename */
980 ScopedTemporary::c_str () const
982 return _file.string().c_str ();
985 /** Open the temporary file.
986 * @return File's FILE pointer.
989 ScopedTemporary::open (char const * params)
991 _open = fopen (c_str(), params);
995 /** Close the file */
997 ScopedTemporary::close ()