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.
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/lexical_cast.hpp>
40 #include <boost/thread.hpp>
41 #include <boost/filesystem.hpp>
44 #include <openssl/md5.h>
45 #include <magick/MagickCore.h>
46 #include <magick/version.h>
47 #include <libdcp/version.h>
48 #include <libdcp/util.h>
49 #include <libdcp/signer_chain.h>
50 #include <libdcp/signer.h>
52 #include <libavcodec/avcodec.h>
53 #include <libavformat/avformat.h>
54 #include <libswscale/swscale.h>
55 #include <libavfilter/avfiltergraph.h>
56 #include <libpostproc/postprocess.h>
57 #include <libavutil/pixfmt.h>
60 #include "exceptions.h"
62 #include "dcp_content_type.h"
64 #include "sound_processor.h"
69 #ifdef DCPOMATIC_WINDOWS
76 using std::stringstream;
90 using std::numeric_limits;
94 using boost::shared_ptr;
96 using boost::lexical_cast;
97 using boost::optional;
100 static boost::thread::id ui_thread;
101 static boost::filesystem::path backtrace_file;
103 /** Convert some number of seconds to a string representation
104 * in hours, minutes and seconds.
107 * @return String of the form H:M:S (where H is hours, M
108 * is minutes and S is seconds).
111 seconds_to_hms (int s)
121 hms << std::setfill ('0') << m << N_(":");
123 hms << std::setfill ('0') << s;
128 /** @param s Number of seconds.
129 * @return String containing an approximate description of s (e.g. "about 2 hours")
132 seconds_to_approximate_hms (int s)
143 ap << (h + 1) << N_(" ") << _("hours");
146 ap << N_("1 ") << _("hour");
148 ap << h << N_(" ") << _("hours");
153 ap << N_("1 ") << _("minute");
155 ap << m << N_(" ") << _("minutes");
158 ap << s << N_(" ") << _("seconds");
164 #ifdef DCPOMATIC_POSIX
165 /** @param l Mangled C++ identifier.
166 * @return Demangled version.
171 string::size_type const b = l.find_first_of (N_("("));
172 if (b == string::npos) {
176 string::size_type const p = l.find_last_of (N_("+"));
177 if (p == string::npos) {
185 string const fn = l.substr (b + 1, p - b - 1);
190 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
195 } catch (std::exception) {
202 /** Write a stacktrace to an ostream.
203 * @param out Stream to write to.
204 * @param levels Number of levels to go up the call stack.
207 stacktrace (ostream& out, int levels)
210 size_t size = backtrace (array, 200);
211 char** strings = backtrace_symbols (array, size);
214 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
215 out << N_(" ") << demangle (strings[i]) << "\n";
223 /** @param v Version as used by FFmpeg.
224 * @return A string representation of v.
227 ffmpeg_version_to_string (int v)
230 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
234 /** Return a user-readable string summarising the versions of our dependencies */
236 dependency_version_summary ()
239 s << N_("libopenjpeg ") << opj_version () << N_(", ")
240 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
241 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
242 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
243 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
244 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
245 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
246 << MagickVersion << N_(", ")
247 << N_("libssh ") << ssh_version (0) << N_(", ")
248 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
254 seconds (struct timeval t)
256 return t.tv_sec + (double (t.tv_usec) / 1e6);
259 #ifdef DCPOMATIC_WINDOWS
260 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
263 ofstream f (backtrace_file.string().c_str());
264 std::copy(s.begin(), s.end(), std::ostream_iterator<dbg::stack_frame>(f, "\n"));
265 return EXCEPTION_CONTINUE_SEARCH;
269 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
270 * Must be called from the UI thread, if there is one.
275 #ifdef DCPOMATIC_WINDOWS
276 backtrace_file /= g_get_user_config_dir ();
277 backtrace_file /= "backtrace.txt";
278 SetUnhandledExceptionFilter(exception_handler);
281 avfilter_register_all ();
284 /* Add our lib directory to the libltdl search path so that
285 xmlsec can find xmlsec1-openssl.
287 boost::filesystem::path lib = app_contents ();
289 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
294 Ratio::setup_ratios ();
295 DCPContentType::setup_dcp_content_types ();
296 Scaler::setup_scalers ();
297 Filter::setup_filters ();
298 SoundProcessor::setup_sound_processors ();
300 ui_thread = boost::this_thread::get_id ();
303 #ifdef DCPOMATIC_WINDOWS
304 boost::filesystem::path
308 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
309 boost::filesystem::path p (buffer);
310 p = p.parent_path ();
311 p = p.parent_path ();
318 dcpomatic_setup_gettext_i18n (string lang)
320 #ifdef DCPOMATIC_POSIX
324 if (!lang.empty ()) {
325 /* Override our environment language; this is essential on
329 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
331 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
335 setlocale (LC_ALL, "");
336 textdomain ("libdcpomatic");
338 #ifdef DCPOMATIC_WINDOWS
339 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
340 bind_textdomain_codeset ("libdcpomatic", "UTF8");
343 #ifdef DCPOMATIC_POSIX
344 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
348 /** @param s A string.
349 * @return Parts of the string split at spaces, except when a space is within quotation marks.
352 split_at_spaces_considering_quotes (string s)
355 bool in_quotes = false;
357 for (string::size_type i = 0; i < s.length(); ++i) {
358 if (s[i] == ' ' && !in_quotes) {
361 } else if (s[i] == '"') {
362 in_quotes = !in_quotes;
373 md5_digest (void const * data, int size)
376 MD5_Init (&md5_context);
377 MD5_Update (&md5_context, data, size);
378 unsigned char digest[MD5_DIGEST_LENGTH];
379 MD5_Final (digest, &md5_context);
382 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
383 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
389 /** @param job Optional job for which to report progress */
391 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
393 int const buffer_size = 64 * 1024;
394 char buffer[buffer_size];
397 MD5_Init (&md5_context);
399 for (size_t i = 0; i < files.size(); ++i) {
400 ifstream f (files[i].string().c_str(), std::ios::binary);
402 throw OpenFileError (files[i].string());
405 f.seekg (0, std::ios::end);
406 int bytes = f.tellg ();
407 f.seekg (0, std::ios::beg);
410 int const t = min (bytes, buffer_size);
412 MD5_Update (&md5_context, buffer, t);
417 job->set_progress (float (i) / files.size ());
421 unsigned char digest[MD5_DIGEST_LENGTH];
422 MD5_Final (digest, &md5_context);
425 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
426 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
433 about_equal (float a, float b)
435 /* A film of F seconds at f FPS will be Ff frames;
436 Consider some delta FPS d, so if we run the same
437 film at (f + d) FPS it will last F(f + d) seconds.
439 Hence the difference in length over the length of the film will
440 be F(f + d) - Ff frames
441 = Ff + Fd - Ff frames
445 So if we accept a difference of 1 frame, ie 1/f seconds, we can
452 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
453 FPS error is 1/F ~= 0.0001 ~= 10-e4
456 return (fabs (a - b) < 1e-4);
459 /** @param An arbitrary audio frame rate.
460 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
463 dcp_audio_frame_rate (int fs)
472 Socket::Socket (int timeout)
473 : _deadline (_io_service)
474 , _socket (_io_service)
478 _deadline.expires_at (boost::posix_time::pos_infin);
490 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
492 _acceptor->cancel ();
496 _deadline.expires_at (boost::posix_time::pos_infin);
499 _deadline.async_wait (boost::bind (&Socket::check, this));
502 /** Blocking connect.
503 * @param endpoint End-point to connect to.
506 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
508 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
509 boost::system::error_code ec = boost::asio::error::would_block;
510 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
512 _io_service.run_one();
513 } while (ec == boost::asio::error::would_block);
516 throw NetworkError (ec.message ());
519 if (!_socket.is_open ()) {
520 throw NetworkError (_("connect timed out"));
525 Socket::accept (int port)
527 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
529 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
530 boost::system::error_code ec = boost::asio::error::would_block;
531 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
533 _io_service.run_one ();
534 } while (ec == boost::asio::error::would_block );
540 throw NetworkError (ec.message ());
545 * @param data Buffer to write.
546 * @param size Number of bytes to write.
549 Socket::write (uint8_t const * data, int size)
551 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
552 boost::system::error_code ec = boost::asio::error::would_block;
554 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
557 _io_service.run_one ();
558 } while (ec == boost::asio::error::would_block);
561 throw NetworkError (ec.message ());
566 Socket::write (uint32_t v)
569 write (reinterpret_cast<uint8_t*> (&v), 4);
573 * @param data Buffer to read to.
574 * @param size Number of bytes to read.
577 Socket::read (uint8_t* data, int size)
579 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
580 boost::system::error_code ec = boost::asio::error::would_block;
582 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
585 _io_service.run_one ();
586 } while (ec == boost::asio::error::would_block);
589 throw NetworkError (ec.message ());
594 Socket::read_uint32 ()
597 read (reinterpret_cast<uint8_t *> (&v), 4);
601 /** Round a number up to the nearest multiple of another number.
603 * @param s Array of numbers to round, indexed by c.
604 * @param t Multiple to round to.
605 * @return Rounded number.
608 stride_round_up (int c, int const * stride, int t)
610 int const a = stride[c] + (t - 1);
614 /** Read a sequence of key / value pairs from a text stream;
615 * the keys are the first words on the line, and the values are
616 * the remainder of the line following the key. Lines beginning
617 * with # are ignored.
618 * @param s Stream to read.
619 * @return key/value pairs.
621 multimap<string, string>
622 read_key_value (istream &s)
624 multimap<string, string> kv;
627 while (getline (s, line)) {
632 if (line[0] == '#') {
636 if (line[line.size() - 1] == '\r') {
637 line = line.substr (0, line.size() - 1);
640 size_t const s = line.find (' ');
641 if (s == string::npos) {
645 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
652 get_required_string (multimap<string, string> const & kv, string k)
654 if (kv.count (k) > 1) {
655 throw StringError (N_("unexpected multiple keys in key-value set"));
658 multimap<string, string>::const_iterator i = kv.find (k);
660 if (i == kv.end ()) {
661 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
668 get_required_int (multimap<string, string> const & kv, string k)
670 string const v = get_required_string (kv, k);
671 return lexical_cast<int> (v);
675 get_required_float (multimap<string, string> const & kv, string k)
677 string const v = get_required_string (kv, k);
678 return lexical_cast<float> (v);
682 get_optional_string (multimap<string, string> const & kv, string k)
684 if (kv.count (k) > 1) {
685 throw StringError (N_("unexpected multiple keys in key-value set"));
688 multimap<string, string>::const_iterator i = kv.find (k);
689 if (i == kv.end ()) {
697 get_optional_int (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);
704 if (i == kv.end ()) {
708 return lexical_cast<int> (i->second);
711 /** Trip an assert if the caller is not in the UI thread */
715 assert (boost::this_thread::get_id() == ui_thread);
718 /** @param v Content video frame.
719 * @param audio_sample_rate Source audio sample rate.
720 * @param frames_per_second Number of video frames per second.
721 * @return Equivalent number of audio frames for `v'.
724 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
726 return ((int64_t) v * audio_sample_rate / frames_per_second);
730 audio_channel_name (int c)
732 assert (MAX_AUDIO_CHANNELS == 6);
734 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
735 enhancement channel (sub-woofer).
737 string const channels[] = {
749 FrameRateConversion::FrameRateConversion (float source, int dcp)
752 , change_speed (false)
754 if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
755 /* The difference between source and DCP frame rate will be lower
756 (i.e. better) if we skip.
759 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
760 /* The difference between source and DCP frame rate would be better
761 if we repeated each frame once; it may be better still if we
762 repeated more than once. Work out the required repeat.
764 repeat = round (dcp / source);
767 change_speed = !about_equal (source * factor(), dcp);
769 if (!skip && repeat == 1 && !change_speed) {
770 description = _("Content and DCP have the same rate.\n");
773 description = _("DCP will use every other frame of the content.\n");
774 } else if (repeat == 2) {
775 description = _("Each content frame will be doubled in the DCP.\n");
776 } else if (repeat > 2) {
777 description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
781 float const pc = dcp * 100 / (source * factor());
782 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
787 LocaleGuard::LocaleGuard ()
790 char const * old = setlocale (LC_NUMERIC, 0);
794 if (strcmp (_old, "C")) {
795 setlocale (LC_NUMERIC, "C");
800 LocaleGuard::~LocaleGuard ()
802 setlocale (LC_NUMERIC, _old);
807 valid_image_file (boost::filesystem::path f)
809 string ext = f.extension().string();
810 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
811 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
815 tidy_for_filename (string f)
818 for (size_t i = 0; i < f.length(); ++i) {
819 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
829 shared_ptr<const libdcp::Signer>
832 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
834 /* Remake the chain if any of it is missing */
836 list<boost::filesystem::path> files;
837 files.push_back ("ca.self-signed.pem");
838 files.push_back ("intermediate.signed.pem");
839 files.push_back ("leaf.signed.pem");
840 files.push_back ("leaf.key");
842 list<boost::filesystem::path>::const_iterator i = files.begin();
843 while (i != files.end()) {
844 boost::filesystem::path p (sd);
846 if (!boost::filesystem::exists (p)) {
847 boost::filesystem::remove_all (sd);
848 boost::filesystem::create_directories (sd);
849 libdcp::make_signer_chain (sd, openssl_path ());
856 libdcp::CertificateChain chain;
859 boost::filesystem::path p (sd);
860 p /= "ca.self-signed.pem";
861 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
865 boost::filesystem::path p (sd);
866 p /= "intermediate.signed.pem";
867 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
871 boost::filesystem::path p (sd);
872 p /= "leaf.signed.pem";
873 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
876 boost::filesystem::path signer_key (sd);
877 signer_key /= "leaf.key";
879 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
883 fit_ratio_within (float ratio, libdcp::Size full_frame)
885 if (ratio < full_frame.ratio ()) {
886 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
889 return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));