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 #include <boost/locale.hpp>
45 #include <openssl/md5.h>
46 #include <magick/MagickCore.h>
47 #include <magick/version.h>
48 #include <libdcp/version.h>
49 #include <libdcp/util.h>
50 #include <libdcp/signer_chain.h>
51 #include <libdcp/signer.h>
53 #include <libavcodec/avcodec.h>
54 #include <libavformat/avformat.h>
55 #include <libswscale/swscale.h>
56 #include <libavfilter/avfiltergraph.h>
57 #include <libpostproc/postprocess.h>
58 #include <libavutil/pixfmt.h>
61 #include "exceptions.h"
63 #include "dcp_content_type.h"
65 #include "sound_processor.h"
70 #ifdef DCPOMATIC_WINDOWS
77 using std::stringstream;
90 using std::numeric_limits;
93 using boost::shared_ptr;
95 using boost::lexical_cast;
96 using boost::optional;
99 static boost::thread::id ui_thread;
100 static boost::filesystem::path backtrace_file;
102 /** Convert some number of seconds to a string representation
103 * in hours, minutes and seconds.
106 * @return String of the form H:M:S (where H is hours, M
107 * is minutes and S is seconds).
110 seconds_to_hms (int s)
120 hms << std::setfill ('0') << m << N_(":");
122 hms << std::setfill ('0') << s;
127 /** @param s Number of seconds.
128 * @return String containing an approximate description of s (e.g. "about 2 hours")
131 seconds_to_approximate_hms (int s)
142 ap << (h + 1) << N_(" ") << _("hours");
145 ap << N_("1 ") << _("hour");
147 ap << h << N_(" ") << _("hours");
152 ap << N_("1 ") << _("minute");
154 ap << m << N_(" ") << _("minutes");
157 ap << s << N_(" ") << _("seconds");
163 #ifdef DCPOMATIC_POSIX
164 /** @param l Mangled C++ identifier.
165 * @return Demangled version.
170 string::size_type const b = l.find_first_of (N_("("));
171 if (b == string::npos) {
175 string::size_type const p = l.find_last_of (N_("+"));
176 if (p == string::npos) {
184 string const fn = l.substr (b + 1, p - b - 1);
189 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
194 } catch (std::exception) {
201 /** Write a stacktrace to an ostream.
202 * @param out Stream to write to.
203 * @param levels Number of levels to go up the call stack.
206 stacktrace (ostream& out, int levels)
209 size_t size = backtrace (array, 200);
210 char** strings = backtrace_symbols (array, size);
213 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
214 out << N_(" ") << demangle (strings[i]) << "\n";
222 /** @param v Version as used by FFmpeg.
223 * @return A string representation of v.
226 ffmpeg_version_to_string (int v)
229 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
233 /** Return a user-readable string summarising the versions of our dependencies */
235 dependency_version_summary ()
238 s << N_("libopenjpeg ") << opj_version () << N_(", ")
239 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
240 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
241 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
242 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
243 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
244 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
245 << MagickVersion << N_(", ")
246 << N_("libssh ") << ssh_version (0) << N_(", ")
247 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
253 seconds (struct timeval t)
255 return t.tv_sec + (double (t.tv_usec) / 1e6);
258 #ifdef DCPOMATIC_WINDOWS
259 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
262 FILE* f = fopen_boost (backtrace_file, "w");
263 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
264 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
267 return EXCEPTION_CONTINUE_SEARCH;
271 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
272 * Must be called from the UI thread, if there is one.
277 #ifdef DCPOMATIC_WINDOWS
278 backtrace_file /= g_get_user_config_dir ();
279 backtrace_file /= "backtrace.txt";
280 SetUnhandledExceptionFilter(exception_handler);
282 /* Dark voodoo which, I think, gets boost::filesystem::path to
283 correctly convert UTF-8 strings to paths, and also paths
284 back to UTF-8 strings (on path::string()).
286 After this, constructing boost::filesystem::paths from strings
287 converts from UTF-8 to UTF-16 inside the path. Then
288 path::string().c_str() gives UTF-8 and
289 path::c_str() gives UTF-16.
291 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
292 so things are much simpler.
294 std::locale::global (boost::locale::generator().generate (""));
295 boost::filesystem::path::imbue (std::locale ());
298 avfilter_register_all ();
301 /* Add our lib directory to the libltdl search path so that
302 xmlsec can find xmlsec1-openssl.
304 boost::filesystem::path lib = app_contents ();
306 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
311 Ratio::setup_ratios ();
312 DCPContentType::setup_dcp_content_types ();
313 Scaler::setup_scalers ();
314 Filter::setup_filters ();
315 SoundProcessor::setup_sound_processors ();
317 ui_thread = boost::this_thread::get_id ();
320 #ifdef DCPOMATIC_WINDOWS
321 boost::filesystem::path
325 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
326 boost::filesystem::path p (buffer);
327 p = p.parent_path ();
328 p = p.parent_path ();
335 dcpomatic_setup_gettext_i18n (string lang)
337 #ifdef DCPOMATIC_POSIX
341 if (!lang.empty ()) {
342 /* Override our environment language; this is essential on
346 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
348 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
352 setlocale (LC_ALL, "");
353 textdomain ("libdcpomatic");
355 #ifdef DCPOMATIC_WINDOWS
356 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
357 bind_textdomain_codeset ("libdcpomatic", "UTF8");
360 #ifdef DCPOMATIC_POSIX
361 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
365 /** @param s A string.
366 * @return Parts of the string split at spaces, except when a space is within quotation marks.
369 split_at_spaces_considering_quotes (string s)
372 bool in_quotes = false;
374 for (string::size_type i = 0; i < s.length(); ++i) {
375 if (s[i] == ' ' && !in_quotes) {
378 } else if (s[i] == '"') {
379 in_quotes = !in_quotes;
390 md5_digest (void const * data, int size)
393 MD5_Init (&md5_context);
394 MD5_Update (&md5_context, data, size);
395 unsigned char digest[MD5_DIGEST_LENGTH];
396 MD5_Final (digest, &md5_context);
399 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
400 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
406 /** @param file File name.
407 * @return MD5 digest of file's contents.
410 md5_digest (boost::filesystem::path file)
412 FILE* f = fopen_boost (file, "rb");
414 throw OpenFileError (file.string());
417 boost::uintmax_t bytes = boost::filesystem::file_size (file);
419 boost::uintmax_t const buffer_size = 64 * 1024;
420 char buffer[buffer_size];
423 MD5_Init (&md5_context);
425 int const t = min (bytes, buffer_size);
426 fread (buffer, 1, t, f);
427 MD5_Update (&md5_context, buffer, t);
431 unsigned char digest[MD5_DIGEST_LENGTH];
432 MD5_Final (digest, &md5_context);
436 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
437 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
443 /** @param job Optional job for which to report progress */
445 md5_digest_directory (boost::filesystem::path directory, shared_ptr<Job> job)
447 boost::uintmax_t const buffer_size = 64 * 1024;
448 char buffer[buffer_size];
451 MD5_Init (&md5_context);
455 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
461 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
462 FILE* f = fopen_boost (i->path(), "rb");
464 throw OpenFileError (i->path().string());
467 boost::uintmax_t bytes = boost::filesystem::file_size (i->path ());
470 int const t = min (bytes, buffer_size);
471 fread (buffer, 1, t, f);
472 MD5_Update (&md5_context, buffer, t);
477 job->set_progress (float (j) / files);
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]);
496 about_equal (float a, float b)
498 /* A film of F seconds at f FPS will be Ff frames;
499 Consider some delta FPS d, so if we run the same
500 film at (f + d) FPS it will last F(f + d) seconds.
502 Hence the difference in length over the length of the film will
503 be F(f + d) - Ff frames
504 = Ff + Fd - Ff frames
508 So if we accept a difference of 1 frame, ie 1/f seconds, we can
515 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
516 FPS error is 1/F ~= 0.0001 ~= 10-e4
519 return (fabs (a - b) < 1e-4);
522 /** @param An arbitrary audio frame rate.
523 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
526 dcp_audio_frame_rate (int fs)
535 Socket::Socket (int timeout)
536 : _deadline (_io_service)
537 , _socket (_io_service)
541 _deadline.expires_at (boost::posix_time::pos_infin);
553 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
555 _acceptor->cancel ();
559 _deadline.expires_at (boost::posix_time::pos_infin);
562 _deadline.async_wait (boost::bind (&Socket::check, this));
565 /** Blocking connect.
566 * @param endpoint End-point to connect to.
569 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
571 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
572 boost::system::error_code ec = boost::asio::error::would_block;
573 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
575 _io_service.run_one();
576 } while (ec == boost::asio::error::would_block);
579 throw NetworkError (ec.message ());
582 if (!_socket.is_open ()) {
583 throw NetworkError (_("connect timed out"));
588 Socket::accept (int port)
590 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
592 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
593 boost::system::error_code ec = boost::asio::error::would_block;
594 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
596 _io_service.run_one ();
597 } while (ec == boost::asio::error::would_block );
603 throw NetworkError (ec.message ());
608 * @param data Buffer to write.
609 * @param size Number of bytes to write.
612 Socket::write (uint8_t const * data, int size)
614 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
615 boost::system::error_code ec = boost::asio::error::would_block;
617 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
620 _io_service.run_one ();
621 } while (ec == boost::asio::error::would_block);
624 throw NetworkError (ec.message ());
629 Socket::write (uint32_t v)
632 write (reinterpret_cast<uint8_t*> (&v), 4);
636 * @param data Buffer to read to.
637 * @param size Number of bytes to read.
640 Socket::read (uint8_t* data, int size)
642 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
643 boost::system::error_code ec = boost::asio::error::would_block;
645 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
648 _io_service.run_one ();
649 } while (ec == boost::asio::error::would_block);
652 throw NetworkError (ec.message ());
657 Socket::read_uint32 ()
660 read (reinterpret_cast<uint8_t *> (&v), 4);
664 /** Round a number up to the nearest multiple of another number.
666 * @param s Array of numbers to round, indexed by c.
667 * @param t Multiple to round to.
668 * @return Rounded number.
671 stride_round_up (int c, int const * stride, int t)
673 int const a = stride[c] + (t - 1);
677 /** Read a sequence of key / value pairs from a text stream;
678 * the keys are the first words on the line, and the values are
679 * the remainder of the line following the key. Lines beginning
680 * with # are ignored.
681 * @param s Stream to read.
682 * @return key/value pairs.
684 multimap<string, string>
685 read_key_value (istream &s)
687 multimap<string, string> kv;
690 while (getline (s, line)) {
695 if (line[0] == '#') {
699 if (line[line.size() - 1] == '\r') {
700 line = line.substr (0, line.size() - 1);
703 size_t const s = line.find (' ');
704 if (s == string::npos) {
708 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
715 get_required_string (multimap<string, string> const & kv, string k)
717 if (kv.count (k) > 1) {
718 throw StringError (N_("unexpected multiple keys in key-value set"));
721 multimap<string, string>::const_iterator i = kv.find (k);
723 if (i == kv.end ()) {
724 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
731 get_required_int (multimap<string, string> const & kv, string k)
733 string const v = get_required_string (kv, k);
734 return lexical_cast<int> (v);
738 get_required_float (multimap<string, string> const & kv, string k)
740 string const v = get_required_string (kv, k);
741 return lexical_cast<float> (v);
745 get_optional_string (multimap<string, string> const & kv, string k)
747 if (kv.count (k) > 1) {
748 throw StringError (N_("unexpected multiple keys in key-value set"));
751 multimap<string, string>::const_iterator i = kv.find (k);
752 if (i == kv.end ()) {
760 get_optional_int (multimap<string, string> const & kv, string k)
762 if (kv.count (k) > 1) {
763 throw StringError (N_("unexpected multiple keys in key-value set"));
766 multimap<string, string>::const_iterator i = kv.find (k);
767 if (i == kv.end ()) {
771 return lexical_cast<int> (i->second);
774 /** Trip an assert if the caller is not in the UI thread */
778 assert (boost::this_thread::get_id() == ui_thread);
781 /** @param v Content video frame.
782 * @param audio_sample_rate Source audio sample rate.
783 * @param frames_per_second Number of video frames per second.
784 * @return Equivalent number of audio frames for `v'.
787 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
789 return ((int64_t) v * audio_sample_rate / frames_per_second);
793 audio_channel_name (int c)
795 assert (MAX_AUDIO_CHANNELS == 6);
797 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
798 enhancement channel (sub-woofer).
800 string const channels[] = {
812 FrameRateConversion::FrameRateConversion (float source, int dcp)
815 , change_speed (false)
817 if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
818 /* The difference between source and DCP frame rate will be lower
819 (i.e. better) if we skip.
822 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
823 /* The difference between source and DCP frame rate would be better
824 if we repeated each frame once; it may be better still if we
825 repeated more than once. Work out the required repeat.
827 repeat = round (dcp / source);
830 change_speed = !about_equal (source * factor(), dcp);
832 if (!skip && repeat == 1 && !change_speed) {
833 description = _("Content and DCP have the same rate.\n");
836 description = _("DCP will use every other frame of the content.\n");
837 } else if (repeat == 2) {
838 description = _("Each content frame will be doubled in the DCP.\n");
839 } else if (repeat > 2) {
840 description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
844 float const pc = dcp * 100 / (source * factor());
845 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
850 LocaleGuard::LocaleGuard ()
853 char const * old = setlocale (LC_NUMERIC, 0);
857 if (strcmp (_old, "C")) {
858 setlocale (LC_NUMERIC, "C");
863 LocaleGuard::~LocaleGuard ()
865 setlocale (LC_NUMERIC, _old);
870 valid_image_file (boost::filesystem::path f)
872 string ext = f.extension().string();
873 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
874 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
878 tidy_for_filename (string f)
881 for (size_t i = 0; i < f.length(); ++i) {
882 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
892 shared_ptr<const libdcp::Signer>
895 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
897 /* Remake the chain if any of it is missing */
899 list<boost::filesystem::path> files;
900 files.push_back ("ca.self-signed.pem");
901 files.push_back ("intermediate.signed.pem");
902 files.push_back ("leaf.signed.pem");
903 files.push_back ("leaf.key");
905 list<boost::filesystem::path>::const_iterator i = files.begin();
906 while (i != files.end()) {
907 boost::filesystem::path p (sd);
909 if (!boost::filesystem::exists (p)) {
910 boost::filesystem::remove_all (sd);
911 boost::filesystem::create_directories (sd);
912 libdcp::make_signer_chain (sd, openssl_path ());
919 libdcp::CertificateChain chain;
922 boost::filesystem::path p (sd);
923 p /= "ca.self-signed.pem";
924 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
928 boost::filesystem::path p (sd);
929 p /= "intermediate.signed.pem";
930 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
934 boost::filesystem::path p (sd);
935 p /= "leaf.signed.pem";
936 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
939 boost::filesystem::path signer_key (sd);
940 signer_key /= "leaf.key";
942 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
946 fit_ratio_within (float ratio, libdcp::Size full_frame)
948 if (ratio < full_frame.ratio ()) {
949 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
952 return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));