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 ());
355 setlocale (LC_ALL, "");
356 textdomain ("libdcpomatic");
358 #ifdef DCPOMATIC_WINDOWS
359 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
360 bind_textdomain_codeset ("libdcpomatic", "UTF8");
363 #ifdef DCPOMATIC_POSIX
364 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
368 /** @param s A string.
369 * @return Parts of the string split at spaces, except when a space is within quotation marks.
372 split_at_spaces_considering_quotes (string s)
375 bool in_quotes = false;
377 for (string::size_type i = 0; i < s.length(); ++i) {
378 if (s[i] == ' ' && !in_quotes) {
381 } else if (s[i] == '"') {
382 in_quotes = !in_quotes;
393 md5_digest (void const * data, int size)
396 MD5_Init (&md5_context);
397 MD5_Update (&md5_context, data, size);
398 unsigned char digest[MD5_DIGEST_LENGTH];
399 MD5_Final (digest, &md5_context);
402 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
403 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
409 /** @param job Optional job for which to report progress */
411 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
413 boost::uintmax_t const buffer_size = 64 * 1024;
414 char buffer[buffer_size];
417 MD5_Init (&md5_context);
419 vector<int64_t> sizes;
420 for (size_t i = 0; i < files.size(); ++i) {
421 sizes.push_back (boost::filesystem::file_size (files[i]));
424 for (size_t i = 0; i < files.size(); ++i) {
425 FILE* f = fopen_boost (files[i], "rb");
427 throw OpenFileError (files[i].string());
430 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
431 boost::uintmax_t remaining = bytes;
433 while (remaining > 0) {
434 int const t = min (remaining, buffer_size);
435 fread (buffer, 1, t, f);
436 MD5_Update (&md5_context, buffer, t);
440 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
447 unsigned char digest[MD5_DIGEST_LENGTH];
448 MD5_Final (digest, &md5_context);
451 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
452 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
459 about_equal (float a, float b)
461 /* A film of F seconds at f FPS will be Ff frames;
462 Consider some delta FPS d, so if we run the same
463 film at (f + d) FPS it will last F(f + d) seconds.
465 Hence the difference in length over the length of the film will
466 be F(f + d) - Ff frames
467 = Ff + Fd - Ff frames
471 So if we accept a difference of 1 frame, ie 1/f seconds, we can
478 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
479 FPS error is 1/F ~= 0.0001 ~= 10-e4
482 return (fabs (a - b) < 1e-4);
485 /** @param An arbitrary audio frame rate.
486 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
489 dcp_audio_frame_rate (int fs)
498 Socket::Socket (int timeout)
499 : _deadline (_io_service)
500 , _socket (_io_service)
504 _deadline.expires_at (boost::posix_time::pos_infin);
516 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
518 _acceptor->cancel ();
522 _deadline.expires_at (boost::posix_time::pos_infin);
525 _deadline.async_wait (boost::bind (&Socket::check, this));
528 /** Blocking connect.
529 * @param endpoint End-point to connect to.
532 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
534 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
535 boost::system::error_code ec = boost::asio::error::would_block;
536 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
538 _io_service.run_one();
539 } while (ec == boost::asio::error::would_block);
542 throw NetworkError (ec.message ());
545 if (!_socket.is_open ()) {
546 throw NetworkError (_("connect timed out"));
551 Socket::accept (int port)
553 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
555 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
556 boost::system::error_code ec = boost::asio::error::would_block;
557 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
559 _io_service.run_one ();
560 } while (ec == boost::asio::error::would_block );
566 throw NetworkError (ec.message ());
571 * @param data Buffer to write.
572 * @param size Number of bytes to write.
575 Socket::write (uint8_t const * data, int size)
577 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
578 boost::system::error_code ec = boost::asio::error::would_block;
580 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
583 _io_service.run_one ();
584 } while (ec == boost::asio::error::would_block);
587 throw NetworkError (ec.message ());
592 Socket::write (uint32_t v)
595 write (reinterpret_cast<uint8_t*> (&v), 4);
599 * @param data Buffer to read to.
600 * @param size Number of bytes to read.
603 Socket::read (uint8_t* data, int size)
605 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
606 boost::system::error_code ec = boost::asio::error::would_block;
608 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
611 _io_service.run_one ();
612 } while (ec == boost::asio::error::would_block);
615 throw NetworkError (ec.message ());
620 Socket::read_uint32 ()
623 read (reinterpret_cast<uint8_t *> (&v), 4);
627 /** Round a number up to the nearest multiple of another number.
629 * @param s Array of numbers to round, indexed by c.
630 * @param t Multiple to round to.
631 * @return Rounded number.
634 stride_round_up (int c, int const * stride, int t)
636 int const a = stride[c] + (t - 1);
640 /** Read a sequence of key / value pairs from a text stream;
641 * the keys are the first words on the line, and the values are
642 * the remainder of the line following the key. Lines beginning
643 * with # are ignored.
644 * @param s Stream to read.
645 * @return key/value pairs.
647 multimap<string, string>
648 read_key_value (istream &s)
650 multimap<string, string> kv;
653 while (getline (s, line)) {
658 if (line[0] == '#') {
662 if (line[line.size() - 1] == '\r') {
663 line = line.substr (0, line.size() - 1);
666 size_t const s = line.find (' ');
667 if (s == string::npos) {
671 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
678 get_required_string (multimap<string, string> const & kv, string k)
680 if (kv.count (k) > 1) {
681 throw StringError (N_("unexpected multiple keys in key-value set"));
684 multimap<string, string>::const_iterator i = kv.find (k);
686 if (i == kv.end ()) {
687 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
694 get_required_int (multimap<string, string> const & kv, string k)
696 string const v = get_required_string (kv, k);
697 return lexical_cast<int> (v);
701 get_required_float (multimap<string, string> const & kv, string k)
703 string const v = get_required_string (kv, k);
704 return lexical_cast<float> (v);
708 get_optional_string (multimap<string, string> const & kv, string k)
710 if (kv.count (k) > 1) {
711 throw StringError (N_("unexpected multiple keys in key-value set"));
714 multimap<string, string>::const_iterator i = kv.find (k);
715 if (i == kv.end ()) {
723 get_optional_int (multimap<string, string> const & kv, string k)
725 if (kv.count (k) > 1) {
726 throw StringError (N_("unexpected multiple keys in key-value set"));
729 multimap<string, string>::const_iterator i = kv.find (k);
730 if (i == kv.end ()) {
734 return lexical_cast<int> (i->second);
737 /** Trip an assert if the caller is not in the UI thread */
741 assert (boost::this_thread::get_id() == ui_thread);
744 /** @param v Content video frame.
745 * @param audio_sample_rate Source audio sample rate.
746 * @param frames_per_second Number of video frames per second.
747 * @return Equivalent number of audio frames for `v'.
750 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
752 return ((int64_t) v * audio_sample_rate / frames_per_second);
756 audio_channel_name (int c)
758 assert (MAX_AUDIO_CHANNELS == 6);
760 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
761 enhancement channel (sub-woofer).
763 string const channels[] = {
775 FrameRateConversion::FrameRateConversion (float source, int dcp)
778 , change_speed (false)
780 if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
781 /* The difference between source and DCP frame rate will be lower
782 (i.e. better) if we skip.
785 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
786 /* The difference between source and DCP frame rate would be better
787 if we repeated each frame once; it may be better still if we
788 repeated more than once. Work out the required repeat.
790 repeat = round (dcp / source);
793 change_speed = !about_equal (source * factor(), dcp);
795 if (!skip && repeat == 1 && !change_speed) {
796 description = _("Content and DCP have the same rate.\n");
799 description = _("DCP will use every other frame of the content.\n");
800 } else if (repeat == 2) {
801 description = _("Each content frame will be doubled in the DCP.\n");
802 } else if (repeat > 2) {
803 description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
807 float const pc = dcp * 100 / (source * factor());
808 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
813 LocaleGuard::LocaleGuard ()
816 char const * old = setlocale (LC_NUMERIC, 0);
820 if (strcmp (_old, "C")) {
821 setlocale (LC_NUMERIC, "C");
826 LocaleGuard::~LocaleGuard ()
828 setlocale (LC_NUMERIC, _old);
833 valid_image_file (boost::filesystem::path f)
835 string ext = f.extension().string();
836 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
837 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
841 tidy_for_filename (string f)
844 for (size_t i = 0; i < f.length(); ++i) {
845 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
855 shared_ptr<const libdcp::Signer>
858 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
860 /* Remake the chain if any of it is missing */
862 list<boost::filesystem::path> files;
863 files.push_back ("ca.self-signed.pem");
864 files.push_back ("intermediate.signed.pem");
865 files.push_back ("leaf.signed.pem");
866 files.push_back ("leaf.key");
868 list<boost::filesystem::path>::const_iterator i = files.begin();
869 while (i != files.end()) {
870 boost::filesystem::path p (sd);
872 if (!boost::filesystem::exists (p)) {
873 boost::filesystem::remove_all (sd);
874 boost::filesystem::create_directories (sd);
875 libdcp::make_signer_chain (sd, openssl_path ());
882 libdcp::CertificateChain chain;
885 boost::filesystem::path p (sd);
886 p /= "ca.self-signed.pem";
887 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
891 boost::filesystem::path p (sd);
892 p /= "intermediate.signed.pem";
893 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
897 boost::filesystem::path p (sd);
898 p /= "leaf.signed.pem";
899 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
902 boost::filesystem::path signer_key (sd);
903 signer_key /= "leaf.key";
905 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));
909 fit_ratio_within (float ratio, libdcp::Size full_frame)
911 if (ratio < full_frame.ratio ()) {
912 return libdcp::Size (rint (full_frame.height * ratio), full_frame.height);
915 return libdcp::Size (full_frame.width, rint (full_frame.width / ratio));