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 <libdcp/version.h>
52 #include <libdcp/util.h>
53 #include <libdcp/signer_chain.h>
54 #include <libdcp/signer.h>
56 #include <libavcodec/avcodec.h>
57 #include <libavformat/avformat.h>
58 #include <libswscale/swscale.h>
59 #include <libavfilter/avfiltergraph.h>
60 #include <libpostproc/postprocess.h>
61 #include <libavutil/pixfmt.h>
64 #include "exceptions.h"
66 #include "dcp_content_type.h"
68 #include "sound_processor.h"
73 #ifdef DCPOMATIC_WINDOWS
80 using std::stringstream;
93 using std::numeric_limits;
98 using boost::shared_ptr;
100 using boost::lexical_cast;
101 using boost::optional;
104 static boost::thread::id ui_thread;
105 static boost::filesystem::path backtrace_file;
107 /** Convert some number of seconds to a string representation
108 * in hours, minutes and seconds.
111 * @return String of the form H:M:S (where H is hours, M
112 * is minutes and S is seconds).
115 seconds_to_hms (int s)
125 hms << std::setfill ('0') << m << N_(":");
127 hms << std::setfill ('0') << s;
132 /** @param s Number of seconds.
133 * @return String containing an approximate description of s (e.g. "about 2 hours")
136 seconds_to_approximate_hms (int s)
147 ap << (h + 1) << N_(" ") << _("hours");
150 ap << N_("1 ") << _("hour");
152 ap << h << N_(" ") << _("hours");
157 ap << N_("1 ") << _("minute");
159 ap << m << N_(" ") << _("minutes");
162 ap << s << N_(" ") << _("seconds");
168 #ifdef DCPOMATIC_POSIX
169 /** @param l Mangled C++ identifier.
170 * @return Demangled version.
175 string::size_type const b = l.find_first_of (N_("("));
176 if (b == string::npos) {
180 string::size_type const p = l.find_last_of (N_("+"));
181 if (p == string::npos) {
189 string const fn = l.substr (b + 1, p - b - 1);
194 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
199 } catch (std::exception) {
206 /** Write a stacktrace to an ostream.
207 * @param out Stream to write to.
208 * @param levels Number of levels to go up the call stack.
211 stacktrace (ostream& out, int levels)
214 size_t size = backtrace (array, 200);
215 char** strings = backtrace_symbols (array, size);
218 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
219 out << N_(" ") << demangle (strings[i]) << "\n";
227 /** @param v Version as used by FFmpeg.
228 * @return A string representation of v.
231 ffmpeg_version_to_string (int v)
234 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
238 /** Return a user-readable string summarising the versions of our dependencies */
240 dependency_version_summary ()
243 s << N_("libopenjpeg ") << opj_version () << N_(", ")
244 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
245 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
246 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
247 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
248 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
249 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
250 << MagickVersion << N_(", ")
251 << N_("libssh ") << ssh_version (0) << N_(", ")
252 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
258 seconds (struct timeval t)
260 return t.tv_sec + (double (t.tv_usec) / 1e6);
263 #ifdef DCPOMATIC_WINDOWS
264 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
267 FILE* f = fopen_boost (backtrace_file, "w");
268 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
269 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
272 return EXCEPTION_CONTINUE_SEARCH;
276 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
277 * Must be called from the UI thread, if there is one.
282 #ifdef DCPOMATIC_WINDOWS
283 backtrace_file /= g_get_user_config_dir ();
284 backtrace_file /= "backtrace.txt";
285 SetUnhandledExceptionFilter(exception_handler);
287 /* Dark voodoo which, I think, gets boost::filesystem::path to
288 correctly convert UTF-8 strings to paths, and also paths
289 back to UTF-8 strings (on path::string()).
291 After this, constructing boost::filesystem::paths from strings
292 converts from UTF-8 to UTF-16 inside the path. Then
293 path::string().c_str() gives UTF-8 and
294 path::c_str() gives UTF-16.
296 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
297 so things are much simpler.
299 std::locale::global (boost::locale::generator().generate (""));
300 boost::filesystem::path::imbue (std::locale ());
303 avfilter_register_all ();
306 /* Add our lib directory to the libltdl search path so that
307 xmlsec can find xmlsec1-openssl.
309 boost::filesystem::path lib = app_contents ();
311 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
316 Ratio::setup_ratios ();
317 DCPContentType::setup_dcp_content_types ();
318 Scaler::setup_scalers ();
319 Filter::setup_filters ();
320 SoundProcessor::setup_sound_processors ();
322 ui_thread = boost::this_thread::get_id ();
325 #ifdef DCPOMATIC_WINDOWS
326 boost::filesystem::path
330 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
331 boost::filesystem::path p (buffer);
332 p = p.parent_path ();
333 p = p.parent_path ();
340 dcpomatic_setup_gettext_i18n (string lang)
342 #ifdef DCPOMATIC_POSIX
346 if (!lang.empty ()) {
347 /* Override our environment language; this is essential on
351 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
353 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
355 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
359 setlocale (LC_ALL, "");
360 textdomain ("libdcpomatic");
362 #ifdef DCPOMATIC_WINDOWS
363 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
364 bind_textdomain_codeset ("libdcpomatic", "UTF8");
367 #ifdef DCPOMATIC_POSIX
368 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
372 /** @param s A string.
373 * @return Parts of the string split at spaces, except when a space is within quotation marks.
376 split_at_spaces_considering_quotes (string s)
379 bool in_quotes = false;
381 for (string::size_type i = 0; i < s.length(); ++i) {
382 if (s[i] == ' ' && !in_quotes) {
385 } else if (s[i] == '"') {
386 in_quotes = !in_quotes;
397 md5_digest (void const * data, int size)
400 MD5_Init (&md5_context);
401 MD5_Update (&md5_context, data, size);
402 unsigned char digest[MD5_DIGEST_LENGTH];
403 MD5_Final (digest, &md5_context);
406 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
407 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
413 /** @param job Optional job for which to report progress */
415 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
417 boost::uintmax_t const buffer_size = 64 * 1024;
418 char buffer[buffer_size];
421 MD5_Init (&md5_context);
423 vector<int64_t> sizes;
424 for (size_t i = 0; i < files.size(); ++i) {
425 sizes.push_back (boost::filesystem::file_size (files[i]));
428 for (size_t i = 0; i < files.size(); ++i) {
429 FILE* f = fopen_boost (files[i], "rb");
431 throw OpenFileError (files[i].string());
434 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
435 boost::uintmax_t remaining = bytes;
437 while (remaining > 0) {
438 int const t = min (remaining, buffer_size);
439 fread (buffer, 1, t, f);
440 MD5_Update (&md5_context, buffer, t);
444 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
451 unsigned char digest[MD5_DIGEST_LENGTH];
452 MD5_Final (digest, &md5_context);
455 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
456 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
463 about_equal (float a, float b)
465 /* A film of F seconds at f FPS will be Ff frames;
466 Consider some delta FPS d, so if we run the same
467 film at (f + d) FPS it will last F(f + d) seconds.
469 Hence the difference in length over the length of the film will
470 be F(f + d) - Ff frames
471 = Ff + Fd - Ff frames
475 So if we accept a difference of 1 frame, ie 1/f seconds, we can
482 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
483 FPS error is 1/F ~= 0.0001 ~= 10-e4
486 return (fabs (a - b) < 1e-4);
489 /** @param An arbitrary audio frame rate.
490 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
493 dcp_audio_frame_rate (int fs)
502 Socket::Socket (int timeout)
503 : _deadline (_io_service)
504 , _socket (_io_service)
508 _deadline.expires_at (boost::posix_time::pos_infin);
520 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
522 _acceptor->cancel ();
526 _deadline.expires_at (boost::posix_time::pos_infin);
529 _deadline.async_wait (boost::bind (&Socket::check, this));
532 /** Blocking connect.
533 * @param endpoint End-point to connect to.
536 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
538 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
539 boost::system::error_code ec = boost::asio::error::would_block;
540 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
542 _io_service.run_one();
543 } while (ec == boost::asio::error::would_block);
546 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
549 if (!_socket.is_open ()) {
550 throw NetworkError (_("connect timed out"));
555 Socket::accept (int port)
557 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
559 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
560 boost::system::error_code ec = boost::asio::error::would_block;
561 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
563 _io_service.run_one ();
564 } while (ec == boost::asio::error::would_block );
570 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
575 * @param data Buffer to write.
576 * @param size Number of bytes to write.
579 Socket::write (uint8_t const * data, int size)
581 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
582 boost::system::error_code ec = boost::asio::error::would_block;
584 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
587 _io_service.run_one ();
588 } while (ec == boost::asio::error::would_block);
591 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
596 Socket::write (uint32_t v)
599 write (reinterpret_cast<uint8_t*> (&v), 4);
603 * @param data Buffer to read to.
604 * @param size Number of bytes to read.
607 Socket::read (uint8_t* data, int size)
609 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
610 boost::system::error_code ec = boost::asio::error::would_block;
612 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
615 _io_service.run_one ();
616 } while (ec == boost::asio::error::would_block);
619 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
624 Socket::read_uint32 ()
627 read (reinterpret_cast<uint8_t *> (&v), 4);
631 /** Round a number up to the nearest multiple of another number.
633 * @param s Array of numbers to round, indexed by c.
634 * @param t Multiple to round to.
635 * @return Rounded number.
638 stride_round_up (int c, int const * stride, int t)
640 int const a = stride[c] + (t - 1);
644 /** Read a sequence of key / value pairs from a text stream;
645 * the keys are the first words on the line, and the values are
646 * the remainder of the line following the key. Lines beginning
647 * with # are ignored.
648 * @param s Stream to read.
649 * @return key/value pairs.
651 multimap<string, string>
652 read_key_value (istream &s)
654 multimap<string, string> kv;
657 while (getline (s, line)) {
662 if (line[0] == '#') {
666 if (line[line.size() - 1] == '\r') {
667 line = line.substr (0, line.size() - 1);
670 size_t const s = line.find (' ');
671 if (s == string::npos) {
675 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
682 get_required_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);
690 if (i == kv.end ()) {
691 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
698 get_required_int (multimap<string, string> const & kv, string k)
700 string const v = get_required_string (kv, k);
701 return lexical_cast<int> (v);
705 get_required_float (multimap<string, string> const & kv, string k)
707 string const v = get_required_string (kv, k);
708 return lexical_cast<float> (v);
712 get_optional_string (multimap<string, string> const & kv, string k)
714 if (kv.count (k) > 1) {
715 throw StringError (N_("unexpected multiple keys in key-value set"));
718 multimap<string, string>::const_iterator i = kv.find (k);
719 if (i == kv.end ()) {
727 get_optional_int (multimap<string, string> const & kv, string k)
729 if (kv.count (k) > 1) {
730 throw StringError (N_("unexpected multiple keys in key-value set"));
733 multimap<string, string>::const_iterator i = kv.find (k);
734 if (i == kv.end ()) {
738 return lexical_cast<int> (i->second);
741 /** Trip an assert if the caller is not in the UI thread */
745 assert (boost::this_thread::get_id() == ui_thread);
748 /** @param v Content video frame.
749 * @param audio_sample_rate Source audio sample rate.
750 * @param frames_per_second Number of video frames per second.
751 * @return Equivalent number of audio frames for `v'.
754 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
756 return ((int64_t) v * audio_sample_rate / frames_per_second);
760 audio_channel_name (int c)
762 assert (MAX_AUDIO_CHANNELS == 6);
764 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
765 enhancement channel (sub-woofer).
767 string const channels[] = {
779 FrameRateConversion::FrameRateConversion (float source, int dcp)
782 , change_speed (false)
784 if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
785 /* The difference between source and DCP frame rate will be lower
786 (i.e. better) if we skip.
789 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
790 /* The difference between source and DCP frame rate would be better
791 if we repeated each frame once; it may be better still if we
792 repeated more than once. Work out the required repeat.
794 repeat = round (dcp / source);
797 change_speed = !about_equal (source * factor(), dcp);
799 if (!skip && repeat == 1 && !change_speed) {
800 description = _("Content and DCP have the same rate.\n");
803 description = _("DCP will use every other frame of the content.\n");
804 } else if (repeat == 2) {
805 description = _("Each content frame will be doubled in the DCP.\n");
806 } else if (repeat > 2) {
807 description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
811 float const pc = dcp * 100 / (source * factor());
812 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
817 LocaleGuard::LocaleGuard ()
820 char const * old = setlocale (LC_NUMERIC, 0);
824 if (strcmp (_old, "C")) {
825 setlocale (LC_NUMERIC, "C");
830 LocaleGuard::~LocaleGuard ()
832 setlocale (LC_NUMERIC, _old);
837 valid_image_file (boost::filesystem::path f)
839 string ext = f.extension().string();
840 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
841 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
845 tidy_for_filename (string f)
848 for (size_t i = 0; i < f.length(); ++i) {
849 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
859 shared_ptr<const libdcp::Signer>
862 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
864 /* Remake the chain if any of it is missing */
866 list<boost::filesystem::path> files;
867 files.push_back ("ca.self-signed.pem");
868 files.push_back ("intermediate.signed.pem");
869 files.push_back ("leaf.signed.pem");
870 files.push_back ("leaf.key");
872 list<boost::filesystem::path>::const_iterator i = files.begin();
873 while (i != files.end()) {
874 boost::filesystem::path p (sd);
876 if (!boost::filesystem::exists (p)) {
877 boost::filesystem::remove_all (sd);
878 boost::filesystem::create_directories (sd);
879 libdcp::make_signer_chain (sd, openssl_path ());
886 libdcp::CertificateChain chain;
889 boost::filesystem::path p (sd);
890 p /= "ca.self-signed.pem";
891 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
895 boost::filesystem::path p (sd);
896 p /= "intermediate.signed.pem";
897 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
901 boost::filesystem::path p (sd);
902 p /= "leaf.signed.pem";
903 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
906 boost::filesystem::path signer_key (sd);
907 signer_key /= "leaf.key";
909 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
913 fit_ratio_within (float ratio, libdcp::Size full_frame)
915 if (ratio < full_frame.ratio ()) {
916 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
919 return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));
923 wrapped_av_malloc (size_t s)
925 void* p = av_malloc (s);