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>
44 #include <openssl/md5.h>
45 #include <magick/MagickCore.h>
46 #include <magick/version.h>
47 #include <libdcp/version.h>
48 #include <libdcp/util.h>
49 #include <libdcp/signer_chain.h>
50 #include <libdcp/signer.h>
52 #include <libavcodec/avcodec.h>
53 #include <libavformat/avformat.h>
54 #include <libswscale/swscale.h>
55 #include <libavfilter/avfiltergraph.h>
56 #include <libpostproc/postprocess.h>
57 #include <libavutil/pixfmt.h>
60 #include "exceptions.h"
62 #include "dcp_content_type.h"
64 #include "sound_processor.h"
69 #ifdef DCPOMATIC_WINDOWS
79 using std::stringstream;
93 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 ofstream f (backtrace_file.string().c_str());
266 std::copy(s.begin(), s.end(), std::ostream_iterator<dbg::stack_frame>(f, "\n"));
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);
283 avfilter_register_all ();
286 /* Add our lib directory to the libltdl search path so that
287 xmlsec can find xmlsec1-openssl.
289 boost::filesystem::path lib = app_contents ();
291 cout << "adding search dir " << lib.c_str() << "\n";
292 lt_dladdsearchdir (lib.c_str ());
297 Ratio::setup_ratios ();
298 DCPContentType::setup_dcp_content_types ();
299 Scaler::setup_scalers ();
300 Filter::setup_filters ();
301 SoundProcessor::setup_sound_processors ();
303 ui_thread = boost::this_thread::get_id ();
306 #ifdef DCPOMATIC_WINDOWS
307 boost::filesystem::path
311 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
312 boost::filesystem::path p (buffer);
313 p = p.parent_path ();
314 p = p.parent_path ();
321 dcpomatic_setup_gettext_i18n (string lang)
323 #ifdef DCPOMATIC_POSIX
327 if (!lang.empty ()) {
328 /* Override our environment language; this is essential on
332 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
334 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
338 setlocale (LC_ALL, "");
339 textdomain ("libdcpomatic");
341 #ifdef DCPOMATIC_WINDOWS
342 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
343 bind_textdomain_codeset ("libdcpomatic", "UTF8");
346 #ifdef DCPOMATIC_POSIX
347 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
351 /** @param s A string.
352 * @return Parts of the string split at spaces, except when a space is within quotation marks.
355 split_at_spaces_considering_quotes (string s)
358 bool in_quotes = false;
360 for (string::size_type i = 0; i < s.length(); ++i) {
361 if (s[i] == ' ' && !in_quotes) {
364 } else if (s[i] == '"') {
365 in_quotes = !in_quotes;
376 md5_digest (void const * data, int size)
379 MD5_Init (&md5_context);
380 MD5_Update (&md5_context, data, size);
381 unsigned char digest[MD5_DIGEST_LENGTH];
382 MD5_Final (digest, &md5_context);
385 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
386 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
392 /** @param file File name.
393 * @return MD5 digest of file's contents.
396 md5_digest (boost::filesystem::path file)
398 ifstream f (file.string().c_str(), std::ios::binary);
400 throw OpenFileError (file.string());
403 f.seekg (0, std::ios::end);
404 int bytes = f.tellg ();
405 f.seekg (0, std::ios::beg);
407 int const buffer_size = 64 * 1024;
408 char buffer[buffer_size];
411 MD5_Init (&md5_context);
413 int const t = min (bytes, buffer_size);
415 MD5_Update (&md5_context, buffer, t);
419 unsigned char digest[MD5_DIGEST_LENGTH];
420 MD5_Final (digest, &md5_context);
423 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
424 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
430 /** @param job Optional job for which to report progress */
432 md5_digest_directory (boost::filesystem::path directory, shared_ptr<Job> job)
434 int const buffer_size = 64 * 1024;
435 char buffer[buffer_size];
438 MD5_Init (&md5_context);
442 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
448 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
449 ifstream f (i->path().string().c_str(), std::ios::binary);
451 throw OpenFileError (i->path().string());
454 f.seekg (0, std::ios::end);
455 int bytes = f.tellg ();
456 f.seekg (0, std::ios::beg);
459 int const t = min (bytes, buffer_size);
461 MD5_Update (&md5_context, buffer, t);
466 job->set_progress (float (j) / files);
471 unsigned char digest[MD5_DIGEST_LENGTH];
472 MD5_Final (digest, &md5_context);
475 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
476 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
483 about_equal (float a, float b)
485 /* A film of F seconds at f FPS will be Ff frames;
486 Consider some delta FPS d, so if we run the same
487 film at (f + d) FPS it will last F(f + d) seconds.
489 Hence the difference in length over the length of the film will
490 be F(f + d) - Ff frames
491 = Ff + Fd - Ff frames
495 So if we accept a difference of 1 frame, ie 1/f seconds, we can
502 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
503 FPS error is 1/F ~= 0.0001 ~= 10-e4
506 return (fabs (a - b) < 1e-4);
509 /** @param An arbitrary audio frame rate.
510 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
513 dcp_audio_frame_rate (int fs)
522 Socket::Socket (int timeout)
523 : _deadline (_io_service)
524 , _socket (_io_service)
527 _deadline.expires_at (boost::posix_time::pos_infin);
534 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
536 _deadline.expires_at (boost::posix_time::pos_infin);
539 _deadline.async_wait (boost::bind (&Socket::check, this));
542 /** Blocking connect.
543 * @param endpoint End-point to connect to.
546 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
548 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
549 boost::system::error_code ec = boost::asio::error::would_block;
550 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
552 _io_service.run_one();
553 } while (ec == boost::asio::error::would_block);
555 if (ec || !_socket.is_open ()) {
556 throw NetworkError (_("connect timed out"));
561 * @param data Buffer to write.
562 * @param size Number of bytes to write.
565 Socket::write (uint8_t const * data, int size)
567 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
568 boost::system::error_code ec = boost::asio::error::would_block;
570 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
573 _io_service.run_one ();
574 } while (ec == boost::asio::error::would_block);
577 throw NetworkError (ec.message ());
582 Socket::write (uint32_t v)
585 write (reinterpret_cast<uint8_t*> (&v), 4);
589 * @param data Buffer to read to.
590 * @param size Number of bytes to read.
593 Socket::read (uint8_t* data, int size)
595 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
596 boost::system::error_code ec = boost::asio::error::would_block;
598 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
601 _io_service.run_one ();
602 } while (ec == boost::asio::error::would_block);
605 throw NetworkError (ec.message ());
610 Socket::read_uint32 ()
613 read (reinterpret_cast<uint8_t *> (&v), 4);
617 /** Round a number up to the nearest multiple of another number.
619 * @param s Array of numbers to round, indexed by c.
620 * @param t Multiple to round to.
621 * @return Rounded number.
624 stride_round_up (int c, int const * stride, int t)
626 int const a = stride[c] + (t - 1);
630 /** Read a sequence of key / value pairs from a text stream;
631 * the keys are the first words on the line, and the values are
632 * the remainder of the line following the key. Lines beginning
633 * with # are ignored.
634 * @param s Stream to read.
635 * @return key/value pairs.
637 multimap<string, string>
638 read_key_value (istream &s)
640 multimap<string, string> kv;
643 while (getline (s, line)) {
648 if (line[0] == '#') {
652 if (line[line.size() - 1] == '\r') {
653 line = line.substr (0, line.size() - 1);
656 size_t const s = line.find (' ');
657 if (s == string::npos) {
661 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
668 get_required_string (multimap<string, string> const & kv, string k)
670 if (kv.count (k) > 1) {
671 throw StringError (N_("unexpected multiple keys in key-value set"));
674 multimap<string, string>::const_iterator i = kv.find (k);
676 if (i == kv.end ()) {
677 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
684 get_required_int (multimap<string, string> const & kv, string k)
686 string const v = get_required_string (kv, k);
687 return lexical_cast<int> (v);
691 get_required_float (multimap<string, string> const & kv, string k)
693 string const v = get_required_string (kv, k);
694 return lexical_cast<float> (v);
698 get_optional_string (multimap<string, string> const & kv, string k)
700 if (kv.count (k) > 1) {
701 throw StringError (N_("unexpected multiple keys in key-value set"));
704 multimap<string, string>::const_iterator i = kv.find (k);
705 if (i == kv.end ()) {
713 get_optional_int (multimap<string, string> const & kv, string k)
715 if (kv.count (k) > 1) {
716 throw StringError (N_("unexpected multiple keys in key-value set"));
719 multimap<string, string>::const_iterator i = kv.find (k);
720 if (i == kv.end ()) {
724 return lexical_cast<int> (i->second);
727 /** Trip an assert if the caller is not in the UI thread */
731 assert (boost::this_thread::get_id() == ui_thread);
734 /** @param v Content video frame.
735 * @param audio_sample_rate Source audio sample rate.
736 * @param frames_per_second Number of video frames per second.
737 * @return Equivalent number of audio frames for `v'.
740 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
742 return ((int64_t) v * audio_sample_rate / frames_per_second);
746 audio_channel_name (int c)
748 assert (MAX_AUDIO_CHANNELS == 6);
750 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
751 enhancement channel (sub-woofer)./
753 string const channels[] = {
765 FrameRateConversion::FrameRateConversion (float source, int dcp)
768 , change_speed (false)
770 if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
772 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
776 change_speed = !about_equal (source * factor(), dcp);
778 if (!skip && !repeat && !change_speed) {
779 description = _("Content and DCP have the same rate.\n");
782 description = _("DCP will use every other frame of the content.\n");
784 description = _("Each content frame will be doubled in the DCP.\n");
788 float const pc = dcp * 100 / (source * factor());
789 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
794 LocaleGuard::LocaleGuard ()
797 char const * old = setlocale (LC_NUMERIC, 0);
801 if (strcmp (_old, "C")) {
802 setlocale (LC_NUMERIC, "C");
807 LocaleGuard::~LocaleGuard ()
809 setlocale (LC_NUMERIC, _old);
814 valid_image_file (boost::filesystem::path f)
816 string ext = f.extension().string();
817 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
818 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
822 tidy_for_filename (string f)
825 for (size_t i = 0; i < f.length(); ++i) {
826 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
836 shared_ptr<const libdcp::Signer>
839 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
841 /* Remake the chain if any of it is missing */
843 list<boost::filesystem::path> files;
844 files.push_back ("ca.self-signed.pem");
845 files.push_back ("intermediate.signed.pem");
846 files.push_back ("leaf.signed.pem");
847 files.push_back ("leaf.key");
849 list<boost::filesystem::path>::const_iterator i = files.begin();
850 while (i != files.end()) {
851 boost::filesystem::path p (sd);
853 if (!boost::filesystem::exists (p)) {
854 boost::filesystem::remove_all (sd);
855 boost::filesystem::create_directories (sd);
856 libdcp::make_signer_chain (sd, openssl_path ());
863 libdcp::CertificateChain chain;
866 boost::filesystem::path p (sd);
867 p /= "ca.self-signed.pem";
868 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
872 boost::filesystem::path p (sd);
873 p /= "intermediate.signed.pem";
874 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
878 boost::filesystem::path p (sd);
879 p /= "leaf.signed.pem";
880 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
883 boost::filesystem::path signer_key (sd);
884 signer_key /= "leaf.key";
886 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));