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;
95 using boost::shared_ptr;
97 using boost::lexical_cast;
98 using boost::optional;
101 static boost::thread::id ui_thread;
102 static boost::filesystem::path backtrace_file;
104 /** Convert some number of seconds to a string representation
105 * in hours, minutes and seconds.
108 * @return String of the form H:M:S (where H is hours, M
109 * is minutes and S is seconds).
112 seconds_to_hms (int s)
122 hms << std::setfill ('0') << m << N_(":");
124 hms << std::setfill ('0') << s;
129 /** @param s Number of seconds.
130 * @return String containing an approximate description of s (e.g. "about 2 hours")
133 seconds_to_approximate_hms (int s)
144 ap << (h + 1) << N_(" ") << _("hours");
147 ap << N_("1 ") << _("hour");
149 ap << h << N_(" ") << _("hours");
154 ap << N_("1 ") << _("minute");
156 ap << m << N_(" ") << _("minutes");
159 ap << s << N_(" ") << _("seconds");
165 #ifdef DCPOMATIC_POSIX
166 /** @param l Mangled C++ identifier.
167 * @return Demangled version.
172 string::size_type const b = l.find_first_of (N_("("));
173 if (b == string::npos) {
177 string::size_type const p = l.find_last_of (N_("+"));
178 if (p == string::npos) {
186 string const fn = l.substr (b + 1, p - b - 1);
191 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
196 } catch (std::exception) {
203 /** Write a stacktrace to an ostream.
204 * @param out Stream to write to.
205 * @param levels Number of levels to go up the call stack.
208 stacktrace (ostream& out, int levels)
211 size_t size = backtrace (array, 200);
212 char** strings = backtrace_symbols (array, size);
215 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
216 out << N_(" ") << demangle (strings[i]) << "\n";
224 /** @param v Version as used by FFmpeg.
225 * @return A string representation of v.
228 ffmpeg_version_to_string (int v)
231 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
235 /** Return a user-readable string summarising the versions of our dependencies */
237 dependency_version_summary ()
240 s << N_("libopenjpeg ") << opj_version () << N_(", ")
241 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
242 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
243 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
244 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
245 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
246 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
247 << MagickVersion << N_(", ")
248 << N_("libssh ") << ssh_version (0) << N_(", ")
249 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
255 seconds (struct timeval t)
257 return t.tv_sec + (double (t.tv_usec) / 1e6);
260 #ifdef DCPOMATIC_WINDOWS
261 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
264 FILE* f = fopen_boost (backtrace_file, "w");
265 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
266 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
269 return EXCEPTION_CONTINUE_SEARCH;
273 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
274 * Must be called from the UI thread, if there is one.
279 #ifdef DCPOMATIC_WINDOWS
280 backtrace_file /= g_get_user_config_dir ();
281 backtrace_file /= "backtrace.txt";
282 SetUnhandledExceptionFilter(exception_handler);
284 /* Dark voodoo which, I think, gets boost::filesystem::path to
285 correctly convert UTF-8 strings to paths, and also paths
286 back to UTF-8 strings (on path::string()).
288 After this, constructing boost::filesystem::paths from strings
289 converts from UTF-8 to UTF-16 inside the path. Then
290 path::string().c_str() gives UTF-8 and
291 path::c_str() gives UTF-16.
293 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
294 so things are much simpler.
296 std::locale::global (boost::locale::generator().generate (""));
297 boost::filesystem::path::imbue (std::locale ());
300 avfilter_register_all ();
303 /* Add our lib directory to the libltdl search path so that
304 xmlsec can find xmlsec1-openssl.
306 boost::filesystem::path lib = app_contents ();
308 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
313 Ratio::setup_ratios ();
314 DCPContentType::setup_dcp_content_types ();
315 Scaler::setup_scalers ();
316 Filter::setup_filters ();
317 SoundProcessor::setup_sound_processors ();
319 ui_thread = boost::this_thread::get_id ();
322 #ifdef DCPOMATIC_WINDOWS
323 boost::filesystem::path
327 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
328 boost::filesystem::path p (buffer);
329 p = p.parent_path ();
330 p = p.parent_path ();
337 dcpomatic_setup_gettext_i18n (string lang)
339 #ifdef DCPOMATIC_POSIX
343 if (!lang.empty ()) {
344 /* Override our environment language; this is essential on
348 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
350 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
354 setlocale (LC_ALL, "");
355 textdomain ("libdcpomatic");
357 #ifdef DCPOMATIC_WINDOWS
358 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
359 bind_textdomain_codeset ("libdcpomatic", "UTF8");
362 #ifdef DCPOMATIC_POSIX
363 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
367 /** @param s A string.
368 * @return Parts of the string split at spaces, except when a space is within quotation marks.
371 split_at_spaces_considering_quotes (string s)
374 bool in_quotes = false;
376 for (string::size_type i = 0; i < s.length(); ++i) {
377 if (s[i] == ' ' && !in_quotes) {
380 } else if (s[i] == '"') {
381 in_quotes = !in_quotes;
392 md5_digest (void const * data, int size)
395 MD5_Init (&md5_context);
396 MD5_Update (&md5_context, data, size);
397 unsigned char digest[MD5_DIGEST_LENGTH];
398 MD5_Final (digest, &md5_context);
401 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
402 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
408 /** @param file File name.
409 * @return MD5 digest of file's contents.
412 md5_digest (boost::filesystem::path file)
414 FILE* f = fopen_boost (file, "rb");
416 throw OpenFileError (file.string());
419 boost::uintmax_t bytes = boost::filesystem::file_size (file);
421 boost::uintmax_t const buffer_size = 64 * 1024;
422 char buffer[buffer_size];
425 MD5_Init (&md5_context);
427 int const t = min (bytes, buffer_size);
428 fread (buffer, 1, t, f);
429 MD5_Update (&md5_context, buffer, t);
433 unsigned char digest[MD5_DIGEST_LENGTH];
434 MD5_Final (digest, &md5_context);
438 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
439 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
445 /** @param job Optional job for which to report progress */
447 md5_digest_directory (boost::filesystem::path directory, shared_ptr<Job> job)
449 boost::uintmax_t const buffer_size = 64 * 1024;
450 char buffer[buffer_size];
453 MD5_Init (&md5_context);
457 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
463 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
464 FILE* f = fopen_boost (i->path(), "rb");
466 throw OpenFileError (i->path().string());
469 boost::uintmax_t bytes = boost::filesystem::file_size (i->path ());
472 int const t = min (bytes, buffer_size);
473 fread (buffer, 1, t, f);
474 MD5_Update (&md5_context, buffer, t);
479 job->set_progress (float (j) / files);
486 unsigned char digest[MD5_DIGEST_LENGTH];
487 MD5_Final (digest, &md5_context);
490 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
491 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
498 about_equal (float a, float b)
500 /* A film of F seconds at f FPS will be Ff frames;
501 Consider some delta FPS d, so if we run the same
502 film at (f + d) FPS it will last F(f + d) seconds.
504 Hence the difference in length over the length of the film will
505 be F(f + d) - Ff frames
506 = Ff + Fd - Ff frames
510 So if we accept a difference of 1 frame, ie 1/f seconds, we can
517 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
518 FPS error is 1/F ~= 0.0001 ~= 10-e4
521 return (fabs (a - b) < 1e-4);
524 /** @param An arbitrary audio frame rate.
525 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
528 dcp_audio_frame_rate (int fs)
537 Socket::Socket (int timeout)
538 : _deadline (_io_service)
539 , _socket (_io_service)
543 _deadline.expires_at (boost::posix_time::pos_infin);
555 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
557 _acceptor->cancel ();
561 _deadline.expires_at (boost::posix_time::pos_infin);
564 _deadline.async_wait (boost::bind (&Socket::check, this));
567 /** Blocking connect.
568 * @param endpoint End-point to connect to.
571 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
573 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
574 boost::system::error_code ec = boost::asio::error::would_block;
575 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
577 _io_service.run_one();
578 } while (ec == boost::asio::error::would_block);
581 throw NetworkError (ec.message ());
584 if (!_socket.is_open ()) {
585 throw NetworkError (_("connect timed out"));
590 Socket::accept (int port)
592 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
594 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
595 boost::system::error_code ec = boost::asio::error::would_block;
596 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
598 _io_service.run_one ();
599 } while (ec == boost::asio::error::would_block );
605 throw NetworkError (ec.message ());
610 * @param data Buffer to write.
611 * @param size Number of bytes to write.
614 Socket::write (uint8_t const * data, int size)
616 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
617 boost::system::error_code ec = boost::asio::error::would_block;
619 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
622 _io_service.run_one ();
623 } while (ec == boost::asio::error::would_block);
626 throw NetworkError (ec.message ());
631 Socket::write (uint32_t v)
634 write (reinterpret_cast<uint8_t*> (&v), 4);
638 * @param data Buffer to read to.
639 * @param size Number of bytes to read.
642 Socket::read (uint8_t* data, int size)
644 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
645 boost::system::error_code ec = boost::asio::error::would_block;
647 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
650 _io_service.run_one ();
651 } while (ec == boost::asio::error::would_block);
654 throw NetworkError (ec.message ());
659 Socket::read_uint32 ()
662 read (reinterpret_cast<uint8_t *> (&v), 4);
666 /** Round a number up to the nearest multiple of another number.
668 * @param s Array of numbers to round, indexed by c.
669 * @param t Multiple to round to.
670 * @return Rounded number.
673 stride_round_up (int c, int const * stride, int t)
675 int const a = stride[c] + (t - 1);
679 /** Read a sequence of key / value pairs from a text stream;
680 * the keys are the first words on the line, and the values are
681 * the remainder of the line following the key. Lines beginning
682 * with # are ignored.
683 * @param s Stream to read.
684 * @return key/value pairs.
686 multimap<string, string>
687 read_key_value (istream &s)
689 multimap<string, string> kv;
692 while (getline (s, line)) {
697 if (line[0] == '#') {
701 if (line[line.size() - 1] == '\r') {
702 line = line.substr (0, line.size() - 1);
705 size_t const s = line.find (' ');
706 if (s == string::npos) {
710 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
717 get_required_string (multimap<string, string> const & kv, string k)
719 if (kv.count (k) > 1) {
720 throw StringError (N_("unexpected multiple keys in key-value set"));
723 multimap<string, string>::const_iterator i = kv.find (k);
725 if (i == kv.end ()) {
726 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
733 get_required_int (multimap<string, string> const & kv, string k)
735 string const v = get_required_string (kv, k);
736 return lexical_cast<int> (v);
740 get_required_float (multimap<string, string> const & kv, string k)
742 string const v = get_required_string (kv, k);
743 return lexical_cast<float> (v);
747 get_optional_string (multimap<string, string> const & kv, string k)
749 if (kv.count (k) > 1) {
750 throw StringError (N_("unexpected multiple keys in key-value set"));
753 multimap<string, string>::const_iterator i = kv.find (k);
754 if (i == kv.end ()) {
762 get_optional_int (multimap<string, string> const & kv, string k)
764 if (kv.count (k) > 1) {
765 throw StringError (N_("unexpected multiple keys in key-value set"));
768 multimap<string, string>::const_iterator i = kv.find (k);
769 if (i == kv.end ()) {
773 return lexical_cast<int> (i->second);
776 /** Trip an assert if the caller is not in the UI thread */
780 assert (boost::this_thread::get_id() == ui_thread);
783 /** @param v Content video frame.
784 * @param audio_sample_rate Source audio sample rate.
785 * @param frames_per_second Number of video frames per second.
786 * @return Equivalent number of audio frames for `v'.
789 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
791 return ((int64_t) v * audio_sample_rate / frames_per_second);
795 audio_channel_name (int c)
797 assert (MAX_AUDIO_CHANNELS == 6);
799 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
800 enhancement channel (sub-woofer).
802 string const channels[] = {
814 FrameRateConversion::FrameRateConversion (float source, int dcp)
817 , change_speed (false)
819 if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
820 /* The difference between source and DCP frame rate will be lower
821 (i.e. better) if we skip.
824 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
825 /* The difference between source and DCP frame rate would be better
826 if we repeated each frame once; it may be better still if we
827 repeated more than once. Work out the required repeat.
829 repeat = round (dcp / source);
832 change_speed = !about_equal (source * factor(), dcp);
834 if (!skip && repeat == 1 && !change_speed) {
835 description = _("Content and DCP have the same rate.\n");
838 description = _("DCP will use every other frame of the content.\n");
839 } else if (repeat == 2) {
840 description = _("Each content frame will be doubled in the DCP.\n");
841 } else if (repeat > 2) {
842 description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
846 float const pc = dcp * 100 / (source * factor());
847 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
852 LocaleGuard::LocaleGuard ()
855 char const * old = setlocale (LC_NUMERIC, 0);
859 if (strcmp (_old, "C")) {
860 setlocale (LC_NUMERIC, "C");
865 LocaleGuard::~LocaleGuard ()
867 setlocale (LC_NUMERIC, _old);
872 valid_image_file (boost::filesystem::path f)
874 string ext = f.extension().string();
875 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
876 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
880 tidy_for_filename (string f)
883 for (size_t i = 0; i < f.length(); ++i) {
884 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
894 shared_ptr<const libdcp::Signer>
897 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
899 /* Remake the chain if any of it is missing */
901 list<boost::filesystem::path> files;
902 files.push_back ("ca.self-signed.pem");
903 files.push_back ("intermediate.signed.pem");
904 files.push_back ("leaf.signed.pem");
905 files.push_back ("leaf.key");
907 list<boost::filesystem::path>::const_iterator i = files.begin();
908 while (i != files.end()) {
909 boost::filesystem::path p (sd);
911 if (!boost::filesystem::exists (p)) {
912 boost::filesystem::remove_all (sd);
913 boost::filesystem::create_directories (sd);
914 libdcp::make_signer_chain (sd, openssl_path ());
921 libdcp::CertificateChain chain;
924 boost::filesystem::path p (sd);
925 p /= "ca.self-signed.pem";
926 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
930 boost::filesystem::path p (sd);
931 p /= "intermediate.signed.pem";
932 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
936 boost::filesystem::path p (sd);
937 p /= "leaf.signed.pem";
938 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
941 boost::filesystem::path signer_key (sd);
942 signer_key /= "leaf.key";
944 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
948 fit_ratio_within (float ratio, libdcp::Size full_frame)
950 if (ratio < full_frame.ratio ()) {
951 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
954 return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));