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>
42 #ifdef DCPOMATIC_WINDOWS
43 #include <boost/locale.hpp>
47 #include <openssl/md5.h>
48 #include <magick/MagickCore.h>
49 #include <magick/version.h>
50 #include <libdcp/version.h>
51 #include <libdcp/util.h>
52 #include <libdcp/signer_chain.h>
53 #include <libdcp/signer.h>
55 #include <libavcodec/avcodec.h>
56 #include <libavformat/avformat.h>
57 #include <libswscale/swscale.h>
58 #include <libavfilter/avfiltergraph.h>
59 #include <libpostproc/postprocess.h>
60 #include <libavutil/pixfmt.h>
63 #include "exceptions.h"
65 #include "dcp_content_type.h"
67 #include "sound_processor.h"
72 #ifdef DCPOMATIC_WINDOWS
79 using std::stringstream;
92 using std::numeric_limits;
96 using boost::shared_ptr;
98 using boost::lexical_cast;
99 using boost::optional;
102 static boost::thread::id ui_thread;
103 static boost::filesystem::path backtrace_file;
105 /** Convert some number of seconds to a string representation
106 * in hours, minutes and seconds.
109 * @return String of the form H:M:S (where H is hours, M
110 * is minutes and S is seconds).
113 seconds_to_hms (int s)
123 hms << std::setfill ('0') << m << N_(":");
125 hms << std::setfill ('0') << s;
130 /** @param s Number of seconds.
131 * @return String containing an approximate description of s (e.g. "about 2 hours")
134 seconds_to_approximate_hms (int s)
145 ap << (h + 1) << N_(" ") << _("hours");
148 ap << N_("1 ") << _("hour");
150 ap << h << N_(" ") << _("hours");
155 ap << N_("1 ") << _("minute");
157 ap << m << N_(" ") << _("minutes");
160 ap << s << N_(" ") << _("seconds");
166 #ifdef DCPOMATIC_POSIX
167 /** @param l Mangled C++ identifier.
168 * @return Demangled version.
173 string::size_type const b = l.find_first_of (N_("("));
174 if (b == string::npos) {
178 string::size_type const p = l.find_last_of (N_("+"));
179 if (p == string::npos) {
187 string const fn = l.substr (b + 1, p - b - 1);
192 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
197 } catch (std::exception) {
204 /** Write a stacktrace to an ostream.
205 * @param out Stream to write to.
206 * @param levels Number of levels to go up the call stack.
209 stacktrace (ostream& out, int levels)
212 size_t size = backtrace (array, 200);
213 char** strings = backtrace_symbols (array, size);
216 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
217 out << N_(" ") << demangle (strings[i]) << "\n";
225 /** @param v Version as used by FFmpeg.
226 * @return A string representation of v.
229 ffmpeg_version_to_string (int v)
232 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
236 /** Return a user-readable string summarising the versions of our dependencies */
238 dependency_version_summary ()
241 s << N_("libopenjpeg ") << opj_version () << N_(", ")
242 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
243 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
244 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
245 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
246 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
247 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
248 << MagickVersion << N_(", ")
249 << N_("libssh ") << ssh_version (0) << N_(", ")
250 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
256 seconds (struct timeval t)
258 return t.tv_sec + (double (t.tv_usec) / 1e6);
261 #ifdef DCPOMATIC_WINDOWS
262 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
265 FILE* f = fopen_boost (backtrace_file, "w");
266 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
267 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
270 return EXCEPTION_CONTINUE_SEARCH;
274 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
275 * Must be called from the UI thread, if there is one.
280 #ifdef DCPOMATIC_WINDOWS
281 backtrace_file /= g_get_user_config_dir ();
282 backtrace_file /= "backtrace.txt";
283 SetUnhandledExceptionFilter(exception_handler);
285 /* Dark voodoo which, I think, gets boost::filesystem::path to
286 correctly convert UTF-8 strings to paths, and also paths
287 back to UTF-8 strings (on path::string()).
289 After this, constructing boost::filesystem::paths from strings
290 converts from UTF-8 to UTF-16 inside the path. Then
291 path::string().c_str() gives UTF-8 and
292 path::c_str() gives UTF-16.
294 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
295 so things are much simpler.
297 std::locale::global (boost::locale::generator().generate (""));
298 boost::filesystem::path::imbue (std::locale ());
301 avfilter_register_all ();
304 /* Add our lib directory to the libltdl search path so that
305 xmlsec can find xmlsec1-openssl.
307 boost::filesystem::path lib = app_contents ();
309 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
314 Ratio::setup_ratios ();
315 DCPContentType::setup_dcp_content_types ();
316 Scaler::setup_scalers ();
317 Filter::setup_filters ();
318 SoundProcessor::setup_sound_processors ();
320 ui_thread = boost::this_thread::get_id ();
323 #ifdef DCPOMATIC_WINDOWS
324 boost::filesystem::path
328 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
329 boost::filesystem::path p (buffer);
330 p = p.parent_path ();
331 p = p.parent_path ();
338 dcpomatic_setup_gettext_i18n (string lang)
340 #ifdef DCPOMATIC_POSIX
344 if (!lang.empty ()) {
345 /* Override our environment language; this is essential on
349 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
351 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
353 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
357 setlocale (LC_ALL, "");
358 textdomain ("libdcpomatic");
360 #ifdef DCPOMATIC_WINDOWS
361 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
362 bind_textdomain_codeset ("libdcpomatic", "UTF8");
365 #ifdef DCPOMATIC_POSIX
366 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
370 /** @param s A string.
371 * @return Parts of the string split at spaces, except when a space is within quotation marks.
374 split_at_spaces_considering_quotes (string s)
377 bool in_quotes = false;
379 for (string::size_type i = 0; i < s.length(); ++i) {
380 if (s[i] == ' ' && !in_quotes) {
383 } else if (s[i] == '"') {
384 in_quotes = !in_quotes;
395 md5_digest (void const * data, int size)
398 MD5_Init (&md5_context);
399 MD5_Update (&md5_context, data, size);
400 unsigned char digest[MD5_DIGEST_LENGTH];
401 MD5_Final (digest, &md5_context);
404 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
405 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
411 /** @param job Optional job for which to report progress */
413 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
415 boost::uintmax_t const buffer_size = 64 * 1024;
416 char buffer[buffer_size];
419 MD5_Init (&md5_context);
421 vector<int64_t> sizes;
422 for (size_t i = 0; i < files.size(); ++i) {
423 sizes.push_back (boost::filesystem::file_size (files[i]));
426 for (size_t i = 0; i < files.size(); ++i) {
427 FILE* f = fopen_boost (files[i], "rb");
429 throw OpenFileError (files[i].string());
432 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
433 boost::uintmax_t remaining = bytes;
435 while (remaining > 0) {
436 int const t = min (remaining, buffer_size);
437 fread (buffer, 1, t, f);
438 MD5_Update (&md5_context, buffer, t);
442 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
449 unsigned char digest[MD5_DIGEST_LENGTH];
450 MD5_Final (digest, &md5_context);
453 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
454 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
461 about_equal (float a, float b)
463 /* A film of F seconds at f FPS will be Ff frames;
464 Consider some delta FPS d, so if we run the same
465 film at (f + d) FPS it will last F(f + d) seconds.
467 Hence the difference in length over the length of the film will
468 be F(f + d) - Ff frames
469 = Ff + Fd - Ff frames
473 So if we accept a difference of 1 frame, ie 1/f seconds, we can
480 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
481 FPS error is 1/F ~= 0.0001 ~= 10-e4
484 return (fabs (a - b) < 1e-4);
487 /** @param An arbitrary audio frame rate.
488 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
491 dcp_audio_frame_rate (int fs)
500 Socket::Socket (int timeout)
501 : _deadline (_io_service)
502 , _socket (_io_service)
506 _deadline.expires_at (boost::posix_time::pos_infin);
518 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
520 _acceptor->cancel ();
524 _deadline.expires_at (boost::posix_time::pos_infin);
527 _deadline.async_wait (boost::bind (&Socket::check, this));
530 /** Blocking connect.
531 * @param endpoint End-point to connect to.
534 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
536 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
537 boost::system::error_code ec = boost::asio::error::would_block;
538 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
540 _io_service.run_one();
541 } while (ec == boost::asio::error::would_block);
544 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
547 if (!_socket.is_open ()) {
548 throw NetworkError (_("connect timed out"));
553 Socket::accept (int port)
555 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
557 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
558 boost::system::error_code ec = boost::asio::error::would_block;
559 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
561 _io_service.run_one ();
562 } while (ec == boost::asio::error::would_block );
568 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
573 * @param data Buffer to write.
574 * @param size Number of bytes to write.
577 Socket::write (uint8_t const * 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_write (_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 (String::compose (_("error during async_write (%1)"), ec.value ()));
594 Socket::write (uint32_t v)
597 write (reinterpret_cast<uint8_t*> (&v), 4);
601 * @param data Buffer to read to.
602 * @param size Number of bytes to read.
605 Socket::read (uint8_t* data, int size)
607 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
608 boost::system::error_code ec = boost::asio::error::would_block;
610 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
613 _io_service.run_one ();
614 } while (ec == boost::asio::error::would_block);
617 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
622 Socket::read_uint32 ()
625 read (reinterpret_cast<uint8_t *> (&v), 4);
629 /** Round a number up to the nearest multiple of another number.
631 * @param s Array of numbers to round, indexed by c.
632 * @param t Multiple to round to.
633 * @return Rounded number.
636 stride_round_up (int c, int const * stride, int t)
638 int const a = stride[c] + (t - 1);
642 /** Read a sequence of key / value pairs from a text stream;
643 * the keys are the first words on the line, and the values are
644 * the remainder of the line following the key. Lines beginning
645 * with # are ignored.
646 * @param s Stream to read.
647 * @return key/value pairs.
649 multimap<string, string>
650 read_key_value (istream &s)
652 multimap<string, string> kv;
655 while (getline (s, line)) {
660 if (line[0] == '#') {
664 if (line[line.size() - 1] == '\r') {
665 line = line.substr (0, line.size() - 1);
668 size_t const s = line.find (' ');
669 if (s == string::npos) {
673 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
680 get_required_string (multimap<string, string> const & kv, string k)
682 if (kv.count (k) > 1) {
683 throw StringError (N_("unexpected multiple keys in key-value set"));
686 multimap<string, string>::const_iterator i = kv.find (k);
688 if (i == kv.end ()) {
689 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
696 get_required_int (multimap<string, string> const & kv, string k)
698 string const v = get_required_string (kv, k);
699 return lexical_cast<int> (v);
703 get_required_float (multimap<string, string> const & kv, string k)
705 string const v = get_required_string (kv, k);
706 return lexical_cast<float> (v);
710 get_optional_string (multimap<string, string> const & kv, string k)
712 if (kv.count (k) > 1) {
713 throw StringError (N_("unexpected multiple keys in key-value set"));
716 multimap<string, string>::const_iterator i = kv.find (k);
717 if (i == kv.end ()) {
725 get_optional_int (multimap<string, string> const & kv, string k)
727 if (kv.count (k) > 1) {
728 throw StringError (N_("unexpected multiple keys in key-value set"));
731 multimap<string, string>::const_iterator i = kv.find (k);
732 if (i == kv.end ()) {
736 return lexical_cast<int> (i->second);
739 /** Trip an assert if the caller is not in the UI thread */
743 assert (boost::this_thread::get_id() == ui_thread);
746 /** @param v Content video frame.
747 * @param audio_sample_rate Source audio sample rate.
748 * @param frames_per_second Number of video frames per second.
749 * @return Equivalent number of audio frames for `v'.
752 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
754 return ((int64_t) v * audio_sample_rate / frames_per_second);
758 audio_channel_name (int c)
760 assert (MAX_AUDIO_CHANNELS == 6);
762 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
763 enhancement channel (sub-woofer).
765 string const channels[] = {
777 FrameRateConversion::FrameRateConversion (float source, int dcp)
780 , change_speed (false)
782 if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
783 /* The difference between source and DCP frame rate will be lower
784 (i.e. better) if we skip.
787 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
788 /* The difference between source and DCP frame rate would be better
789 if we repeated each frame once; it may be better still if we
790 repeated more than once. Work out the required repeat.
792 repeat = round (dcp / source);
795 change_speed = !about_equal (source * factor(), dcp);
797 if (!skip && repeat == 1 && !change_speed) {
798 description = _("Content and DCP have the same rate.\n");
801 description = _("DCP will use every other frame of the content.\n");
802 } else if (repeat == 2) {
803 description = _("Each content frame will be doubled in the DCP.\n");
804 } else if (repeat > 2) {
805 description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
809 float const pc = dcp * 100 / (source * factor());
810 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
815 LocaleGuard::LocaleGuard ()
818 char const * old = setlocale (LC_NUMERIC, 0);
822 if (strcmp (_old, "C")) {
823 setlocale (LC_NUMERIC, "C");
828 LocaleGuard::~LocaleGuard ()
830 setlocale (LC_NUMERIC, _old);
835 valid_image_file (boost::filesystem::path f)
837 string ext = f.extension().string();
838 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
839 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
843 tidy_for_filename (string f)
846 for (size_t i = 0; i < f.length(); ++i) {
847 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
857 shared_ptr<const libdcp::Signer>
860 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
862 /* Remake the chain if any of it is missing */
864 list<boost::filesystem::path> files;
865 files.push_back ("ca.self-signed.pem");
866 files.push_back ("intermediate.signed.pem");
867 files.push_back ("leaf.signed.pem");
868 files.push_back ("leaf.key");
870 list<boost::filesystem::path>::const_iterator i = files.begin();
871 while (i != files.end()) {
872 boost::filesystem::path p (sd);
874 if (!boost::filesystem::exists (p)) {
875 boost::filesystem::remove_all (sd);
876 boost::filesystem::create_directories (sd);
877 libdcp::make_signer_chain (sd, openssl_path ());
884 libdcp::CertificateChain chain;
887 boost::filesystem::path p (sd);
888 p /= "ca.self-signed.pem";
889 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
893 boost::filesystem::path p (sd);
894 p /= "intermediate.signed.pem";
895 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
899 boost::filesystem::path p (sd);
900 p /= "leaf.signed.pem";
901 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
904 boost::filesystem::path signer_key (sd);
905 signer_key /= "leaf.key";
907 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
911 fit_ratio_within (float ratio, libdcp::Size full_frame)
913 if (ratio < full_frame.ratio ()) {
914 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
917 return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));