2 Copyright (C) 2012 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 <magick/MagickCore.h>
50 #include <magick/version.h>
51 #include <pangomm/init.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"
74 #ifdef DCPOMATIC_WINDOWS
81 using std::stringstream;
95 using std::numeric_limits;
100 using std::set_terminate;
101 using boost::shared_ptr;
103 using boost::lexical_cast;
104 using boost::optional;
107 static boost::thread::id ui_thread;
108 static boost::filesystem::path backtrace_file;
110 /** Convert some number of seconds to a string representation
111 * in hours, minutes and seconds.
114 * @return String of the form H:M:S (where H is hours, M
115 * is minutes and S is seconds).
118 seconds_to_hms (int s)
128 hms << std::setfill ('0') << m << N_(":");
130 hms << std::setfill ('0') << s;
135 /** @param s Number of seconds.
136 * @return String containing an approximate description of s (e.g. "about 2 hours")
139 seconds_to_approximate_hms (int s)
150 ap << (h + 1) << N_(" ") << _("hours");
153 ap << N_("1 ") << _("hour");
155 ap << h << N_(" ") << _("hours");
160 ap << N_("1 ") << _("minute");
162 ap << m << N_(" ") << _("minutes");
165 ap << s << N_(" ") << _("seconds");
171 #ifdef DCPOMATIC_POSIX
172 /** @param l Mangled C++ identifier.
173 * @return Demangled version.
178 string::size_type const b = l.find_first_of (N_("("));
179 if (b == string::npos) {
183 string::size_type const p = l.find_last_of (N_("+"));
184 if (p == string::npos) {
192 string const fn = l.substr (b + 1, p - b - 1);
197 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
202 } catch (std::exception) {
209 /** Write a stacktrace to an ostream.
210 * @param out Stream to write to.
211 * @param levels Number of levels to go up the call stack.
214 stacktrace (ostream& out, int levels)
217 size_t size = backtrace (array, 200);
218 char** strings = backtrace_symbols (array, size);
221 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
222 out << N_(" ") << demangle (strings[i]) << "\n";
230 /** @param v Version as used by FFmpeg.
231 * @return A string representation of v.
234 ffmpeg_version_to_string (int v)
237 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
241 /** Return a user-readable string summarising the versions of our dependencies */
243 dependency_version_summary ()
246 s << N_("libopenjpeg ") << opj_version () << N_(", ")
247 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
248 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
249 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
250 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
251 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
252 << MagickVersion << N_(", ")
253 << N_("libssh ") << ssh_version (0) << N_(", ")
254 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
260 seconds (struct timeval t)
262 return t.tv_sec + (double (t.tv_usec) / 1e6);
265 #ifdef DCPOMATIC_WINDOWS
266 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
269 FILE* f = fopen_boost (backtrace_file, "w");
270 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
271 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
274 return EXCEPTION_CONTINUE_SEARCH;
278 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
282 static bool tried_throw = false;
285 // try once to re-throw currently active exception
286 if (!tried_throw++) {
290 catch (const std::exception &e) {
291 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
292 << e.what() << std::endl;
295 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
299 #ifdef DCPOMATIC_POSIX
300 stacktrace (cout, 50);
305 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
306 * Must be called from the UI thread, if there is one.
311 #ifdef DCPOMATIC_WINDOWS
312 backtrace_file /= g_get_user_config_dir ();
313 backtrace_file /= "backtrace.txt";
314 SetUnhandledExceptionFilter(exception_handler);
316 /* Dark voodoo which, I think, gets boost::filesystem::path to
317 correctly convert UTF-8 strings to paths, and also paths
318 back to UTF-8 strings (on path::string()).
320 After this, constructing boost::filesystem::paths from strings
321 converts from UTF-8 to UTF-16 inside the path. Then
322 path::string().c_str() gives UTF-8 and
323 path::c_str() gives UTF-16.
325 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
326 so things are much simpler.
328 std::locale::global (boost::locale::generator().generate (""));
329 boost::filesystem::path::imbue (std::locale ());
332 avfilter_register_all ();
335 /* Add our lib directory to the libltdl search path so that
336 xmlsec can find xmlsec1-openssl.
338 boost::filesystem::path lib = app_contents ();
340 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
343 set_terminate (terminate);
348 Ratio::setup_ratios ();
349 VideoContentScale::setup_scales ();
350 DCPContentType::setup_dcp_content_types ();
351 Scaler::setup_scalers ();
352 Filter::setup_filters ();
353 SoundProcessor::setup_sound_processors ();
355 ui_thread = boost::this_thread::get_id ();
358 #ifdef DCPOMATIC_WINDOWS
359 boost::filesystem::path
363 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
364 boost::filesystem::path p (buffer);
365 p = p.parent_path ();
366 p = p.parent_path ();
373 dcpomatic_setup_gettext_i18n (string lang)
375 #ifdef DCPOMATIC_POSIX
379 if (!lang.empty ()) {
380 /* Override our environment language; this is essential on
384 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
386 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
388 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
392 setlocale (LC_ALL, "");
393 textdomain ("libdcpomatic");
395 #ifdef DCPOMATIC_WINDOWS
396 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
397 bind_textdomain_codeset ("libdcpomatic", "UTF8");
400 #ifdef DCPOMATIC_POSIX
401 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
405 /** @param s A string.
406 * @return Parts of the string split at spaces, except when a space is within quotation marks.
409 split_at_spaces_considering_quotes (string s)
412 bool in_quotes = false;
414 for (string::size_type i = 0; i < s.length(); ++i) {
415 if (s[i] == ' ' && !in_quotes) {
418 } else if (s[i] == '"') {
419 in_quotes = !in_quotes;
430 md5_digest (void const * data, int size)
433 MD5_Init (&md5_context);
434 MD5_Update (&md5_context, data, size);
435 unsigned char digest[MD5_DIGEST_LENGTH];
436 MD5_Final (digest, &md5_context);
439 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
440 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
446 /** @param job Optional job for which to report progress */
448 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
450 boost::uintmax_t const buffer_size = 64 * 1024;
451 char buffer[buffer_size];
454 MD5_Init (&md5_context);
456 vector<int64_t> sizes;
457 for (size_t i = 0; i < files.size(); ++i) {
458 sizes.push_back (boost::filesystem::file_size (files[i]));
461 for (size_t i = 0; i < files.size(); ++i) {
462 FILE* f = fopen_boost (files[i], "rb");
464 throw OpenFileError (files[i].string());
467 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
468 boost::uintmax_t remaining = bytes;
470 while (remaining > 0) {
471 int const t = min (remaining, buffer_size);
472 fread (buffer, 1, t, f);
473 MD5_Update (&md5_context, buffer, t);
477 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
484 unsigned char digest[MD5_DIGEST_LENGTH];
485 MD5_Final (digest, &md5_context);
488 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
489 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
495 /** @param An arbitrary audio frame rate.
496 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
499 dcp_audio_frame_rate (int fs)
508 Socket::Socket (int timeout)
509 : _deadline (_io_service)
510 , _socket (_io_service)
514 _deadline.expires_at (boost::posix_time::pos_infin);
526 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
528 _acceptor->cancel ();
532 _deadline.expires_at (boost::posix_time::pos_infin);
535 _deadline.async_wait (boost::bind (&Socket::check, this));
538 /** Blocking connect.
539 * @param endpoint End-point to connect to.
542 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
544 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
545 boost::system::error_code ec = boost::asio::error::would_block;
546 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
548 _io_service.run_one();
549 } while (ec == boost::asio::error::would_block);
552 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
555 if (!_socket.is_open ()) {
556 throw NetworkError (_("connect timed out"));
561 Socket::accept (int port)
563 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
565 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
566 boost::system::error_code ec = boost::asio::error::would_block;
567 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
569 _io_service.run_one ();
570 } while (ec == boost::asio::error::would_block );
576 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
581 * @param data Buffer to write.
582 * @param size Number of bytes to write.
585 Socket::write (uint8_t const * data, int size)
587 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
588 boost::system::error_code ec = boost::asio::error::would_block;
590 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
593 _io_service.run_one ();
594 } while (ec == boost::asio::error::would_block);
597 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
602 Socket::write (uint32_t v)
605 write (reinterpret_cast<uint8_t*> (&v), 4);
609 * @param data Buffer to read to.
610 * @param size Number of bytes to read.
613 Socket::read (uint8_t* data, int size)
615 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
616 boost::system::error_code ec = boost::asio::error::would_block;
618 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
621 _io_service.run_one ();
622 } while (ec == boost::asio::error::would_block);
625 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
630 Socket::read_uint32 ()
633 read (reinterpret_cast<uint8_t *> (&v), 4);
637 /** Round a number up to the nearest multiple of another number.
639 * @param s Array of numbers to round, indexed by c.
640 * @param t Multiple to round to.
641 * @return Rounded number.
644 stride_round_up (int c, int const * stride, int t)
646 int const a = stride[c] + (t - 1);
650 /** Read a sequence of key / value pairs from a text stream;
651 * the keys are the first words on the line, and the values are
652 * the remainder of the line following the key. Lines beginning
653 * with # are ignored.
654 * @param s Stream to read.
655 * @return key/value pairs.
657 multimap<string, string>
658 read_key_value (istream &s)
660 multimap<string, string> kv;
663 while (getline (s, line)) {
668 if (line[0] == '#') {
672 if (line[line.size() - 1] == '\r') {
673 line = line.substr (0, line.size() - 1);
676 size_t const s = line.find (' ');
677 if (s == string::npos) {
681 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
688 get_required_string (multimap<string, string> const & kv, string k)
690 if (kv.count (k) > 1) {
691 throw StringError (N_("unexpected multiple keys in key-value set"));
694 multimap<string, string>::const_iterator i = kv.find (k);
696 if (i == kv.end ()) {
697 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
704 get_required_int (multimap<string, string> const & kv, string k)
706 string const v = get_required_string (kv, k);
707 return lexical_cast<int> (v);
711 get_required_float (multimap<string, string> const & kv, string k)
713 string const v = get_required_string (kv, k);
714 return lexical_cast<float> (v);
718 get_optional_string (multimap<string, string> const & kv, string k)
720 if (kv.count (k) > 1) {
721 throw StringError (N_("unexpected multiple keys in key-value set"));
724 multimap<string, string>::const_iterator i = kv.find (k);
725 if (i == kv.end ()) {
733 get_optional_int (multimap<string, string> const & kv, string k)
735 if (kv.count (k) > 1) {
736 throw StringError (N_("unexpected multiple keys in key-value set"));
739 multimap<string, string>::const_iterator i = kv.find (k);
740 if (i == kv.end ()) {
744 return lexical_cast<int> (i->second);
747 /** Trip an assert if the caller is not in the UI thread */
751 assert (boost::this_thread::get_id() == ui_thread);
755 audio_channel_name (int c)
757 assert (MAX_AUDIO_CHANNELS == 12);
759 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
760 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
761 VI is the visually-impaired audio track (audio describe).
763 string const channels[] = {
770 _("Hearing impaired"),
771 _("Visually impaired"),
774 _("Left rear surround"),
775 _("Right rear surround"),
781 LocaleGuard::LocaleGuard ()
784 char const * old = setlocale (LC_NUMERIC, 0);
788 if (strcmp (_old, "C")) {
789 setlocale (LC_NUMERIC, "C");
794 LocaleGuard::~LocaleGuard ()
796 setlocale (LC_NUMERIC, _old);
801 valid_image_file (boost::filesystem::path f)
803 string ext = f.extension().string();
804 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
805 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
809 tidy_for_filename (string f)
812 for (size_t i = 0; i < f.length(); ++i) {
813 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
823 shared_ptr<const dcp::Signer>
826 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
828 /* Remake the chain if any of it is missing */
830 list<boost::filesystem::path> files;
831 files.push_back ("ca.self-signed.pem");
832 files.push_back ("intermediate.signed.pem");
833 files.push_back ("leaf.signed.pem");
834 files.push_back ("leaf.key");
836 list<boost::filesystem::path>::const_iterator i = files.begin();
837 while (i != files.end()) {
838 boost::filesystem::path p (sd);
840 if (!boost::filesystem::exists (p)) {
841 boost::filesystem::remove_all (sd);
842 boost::filesystem::create_directories (sd);
843 dcp::make_signer_chain (sd, openssl_path ());
850 dcp::CertificateChain chain;
853 boost::filesystem::path p (sd);
854 p /= "ca.self-signed.pem";
855 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
859 boost::filesystem::path p (sd);
860 p /= "intermediate.signed.pem";
861 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
865 boost::filesystem::path p (sd);
866 p /= "leaf.signed.pem";
867 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
870 boost::filesystem::path signer_key (sd);
871 signer_key /= "leaf.key";
873 return shared_ptr<const dcp::Signer> (new dcp::Signer (chain, signer_key));
877 split_get_request (string url)
880 AWAITING_QUESTION_MARK,
883 } state = AWAITING_QUESTION_MARK;
885 map<string, string> r;
888 for (size_t i = 0; i < url.length(); ++i) {
890 case AWAITING_QUESTION_MARK:
905 r.insert (make_pair (k, v));
915 if (state == VALUE) {
916 r.insert (make_pair (k, v));
923 fit_ratio_within (float ratio, dcp::Size full_frame)
925 if (ratio < full_frame.ratio ()) {
926 return dcp::Size (rint (full_frame.height * ratio), full_frame.height);
929 return dcp::Size (full_frame.width, rint (full_frame.width / ratio));
933 wrapped_av_malloc (size_t s)
935 void* p = av_malloc (s);
943 entities_to_text (string e)
945 boost::algorithm::replace_all (e, "%3A", ":");
946 boost::algorithm::replace_all (e, "%2F", "/");
951 divide_with_round (int64_t a, int64_t b)
953 if (a % b >= (b / 2)) {
954 return (a + b - 1) / b;