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
76 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 ofstream f (backtrace_file.string().c_str());
263 std::copy(s.begin(), s.end(), std::ostream_iterator<dbg::stack_frame>(f, "\n"));
264 return EXCEPTION_CONTINUE_SEARCH;
268 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
269 * Must be called from the UI thread, if there is one.
274 #ifdef DCPOMATIC_WINDOWS
275 backtrace_file /= g_get_user_config_dir ();
276 backtrace_file /= "backtrace.txt";
277 SetUnhandledExceptionFilter(exception_handler);
280 avfilter_register_all ();
284 Ratio::setup_ratios ();
285 DCPContentType::setup_dcp_content_types ();
286 Scaler::setup_scalers ();
287 Filter::setup_filters ();
288 SoundProcessor::setup_sound_processors ();
290 ui_thread = boost::this_thread::get_id ();
293 #ifdef DCPOMATIC_WINDOWS
294 boost::filesystem::path
298 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
299 boost::filesystem::path p (buffer);
300 p = p.parent_path ();
301 p = p.parent_path ();
308 dcpomatic_setup_gettext_i18n (string lang)
310 #ifdef DCPOMATIC_POSIX
314 if (!lang.empty ()) {
315 /* Override our environment language; this is essential on
319 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
321 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
325 setlocale (LC_ALL, "");
326 textdomain ("libdcpomatic");
328 #ifdef DCPOMATIC_WINDOWS
329 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
330 bind_textdomain_codeset ("libdcpomatic", "UTF8");
333 #ifdef DCPOMATIC_POSIX
334 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
338 /** @param s A string.
339 * @return Parts of the string split at spaces, except when a space is within quotation marks.
342 split_at_spaces_considering_quotes (string s)
345 bool in_quotes = false;
347 for (string::size_type i = 0; i < s.length(); ++i) {
348 if (s[i] == ' ' && !in_quotes) {
351 } else if (s[i] == '"') {
352 in_quotes = !in_quotes;
363 md5_digest (void const * data, int size)
366 MD5_Init (&md5_context);
367 MD5_Update (&md5_context, data, size);
368 unsigned char digest[MD5_DIGEST_LENGTH];
369 MD5_Final (digest, &md5_context);
372 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
373 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
379 /** @param file File name.
380 * @return MD5 digest of file's contents.
383 md5_digest (boost::filesystem::path file)
385 ifstream f (file.string().c_str(), std::ios::binary);
387 throw OpenFileError (file.string());
390 f.seekg (0, std::ios::end);
391 int bytes = f.tellg ();
392 f.seekg (0, std::ios::beg);
394 int const buffer_size = 64 * 1024;
395 char buffer[buffer_size];
398 MD5_Init (&md5_context);
400 int const t = min (bytes, buffer_size);
402 MD5_Update (&md5_context, buffer, t);
406 unsigned char digest[MD5_DIGEST_LENGTH];
407 MD5_Final (digest, &md5_context);
410 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
411 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
417 /** @param job Optional job for which to report progress */
419 md5_digest_directory (boost::filesystem::path directory, shared_ptr<Job> job)
421 int const buffer_size = 64 * 1024;
422 char buffer[buffer_size];
425 MD5_Init (&md5_context);
429 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
435 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
436 ifstream f (i->path().string().c_str(), std::ios::binary);
438 throw OpenFileError (i->path().string());
441 f.seekg (0, std::ios::end);
442 int bytes = f.tellg ();
443 f.seekg (0, std::ios::beg);
446 int const t = min (bytes, buffer_size);
448 MD5_Update (&md5_context, buffer, t);
453 job->set_progress (float (j) / files);
458 unsigned char digest[MD5_DIGEST_LENGTH];
459 MD5_Final (digest, &md5_context);
462 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
463 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
470 about_equal (float a, float b)
472 /* A film of F seconds at f FPS will be Ff frames;
473 Consider some delta FPS d, so if we run the same
474 film at (f + d) FPS it will last F(f + d) seconds.
476 Hence the difference in length over the length of the film will
477 be F(f + d) - Ff frames
478 = Ff + Fd - Ff frames
482 So if we accept a difference of 1 frame, ie 1/f seconds, we can
489 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
490 FPS error is 1/F ~= 0.0001 ~= 10-e4
493 return (fabs (a - b) < 1e-4);
496 /** @param An arbitrary audio frame rate.
497 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
500 dcp_audio_frame_rate (int fs)
509 Socket::Socket (int timeout)
510 : _deadline (_io_service)
511 , _socket (_io_service)
514 _deadline.expires_at (boost::posix_time::pos_infin);
521 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
523 _deadline.expires_at (boost::posix_time::pos_infin);
526 _deadline.async_wait (boost::bind (&Socket::check, this));
529 /** Blocking connect.
530 * @param endpoint End-point to connect to.
533 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
535 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
536 boost::system::error_code ec = boost::asio::error::would_block;
537 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
539 _io_service.run_one();
540 } while (ec == boost::asio::error::would_block);
542 if (ec || !_socket.is_open ()) {
543 throw NetworkError (_("connect timed out"));
548 * @param data Buffer to write.
549 * @param size Number of bytes to write.
552 Socket::write (uint8_t const * data, int size)
554 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
555 boost::system::error_code ec = boost::asio::error::would_block;
557 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
560 _io_service.run_one ();
561 } while (ec == boost::asio::error::would_block);
564 throw NetworkError (ec.message ());
569 Socket::write (uint32_t v)
572 write (reinterpret_cast<uint8_t*> (&v), 4);
576 * @param data Buffer to read to.
577 * @param size Number of bytes to read.
580 Socket::read (uint8_t* data, int size)
582 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
583 boost::system::error_code ec = boost::asio::error::would_block;
585 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
588 _io_service.run_one ();
589 } while (ec == boost::asio::error::would_block);
592 throw NetworkError (ec.message ());
597 Socket::read_uint32 ()
600 read (reinterpret_cast<uint8_t *> (&v), 4);
604 /** Round a number up to the nearest multiple of another number.
606 * @param s Array of numbers to round, indexed by c.
607 * @param t Multiple to round to.
608 * @return Rounded number.
611 stride_round_up (int c, int const * stride, int t)
613 int const a = stride[c] + (t - 1);
617 /** Read a sequence of key / value pairs from a text stream;
618 * the keys are the first words on the line, and the values are
619 * the remainder of the line following the key. Lines beginning
620 * with # are ignored.
621 * @param s Stream to read.
622 * @return key/value pairs.
624 multimap<string, string>
625 read_key_value (istream &s)
627 multimap<string, string> kv;
630 while (getline (s, line)) {
635 if (line[0] == '#') {
639 if (line[line.size() - 1] == '\r') {
640 line = line.substr (0, line.size() - 1);
643 size_t const s = line.find (' ');
644 if (s == string::npos) {
648 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
655 get_required_string (multimap<string, string> const & kv, string k)
657 if (kv.count (k) > 1) {
658 throw StringError (N_("unexpected multiple keys in key-value set"));
661 multimap<string, string>::const_iterator i = kv.find (k);
663 if (i == kv.end ()) {
664 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
671 get_required_int (multimap<string, string> const & kv, string k)
673 string const v = get_required_string (kv, k);
674 return lexical_cast<int> (v);
678 get_required_float (multimap<string, string> const & kv, string k)
680 string const v = get_required_string (kv, k);
681 return lexical_cast<float> (v);
685 get_optional_string (multimap<string, string> const & kv, string k)
687 if (kv.count (k) > 1) {
688 throw StringError (N_("unexpected multiple keys in key-value set"));
691 multimap<string, string>::const_iterator i = kv.find (k);
692 if (i == kv.end ()) {
700 get_optional_int (multimap<string, string> const & kv, string k)
702 if (kv.count (k) > 1) {
703 throw StringError (N_("unexpected multiple keys in key-value set"));
706 multimap<string, string>::const_iterator i = kv.find (k);
707 if (i == kv.end ()) {
711 return lexical_cast<int> (i->second);
714 /** Trip an assert if the caller is not in the UI thread */
718 assert (boost::this_thread::get_id() == ui_thread);
721 /** @param v Content video frame.
722 * @param audio_sample_rate Source audio sample rate.
723 * @param frames_per_second Number of video frames per second.
724 * @return Equivalent number of audio frames for `v'.
727 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
729 return ((int64_t) v * audio_sample_rate / frames_per_second);
733 audio_channel_name (int c)
735 assert (MAX_AUDIO_CHANNELS == 6);
737 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
738 enhancement channel (sub-woofer)./
740 string const channels[] = {
752 FrameRateConversion::FrameRateConversion (float source, int dcp)
755 , change_speed (false)
757 if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
759 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
763 change_speed = !about_equal (source * factor(), dcp);
765 if (!skip && !repeat && !change_speed) {
766 description = _("Content and DCP have the same rate.\n");
769 description = _("DCP will use every other frame of the content.\n");
771 description = _("Each content frame will be doubled in the DCP.\n");
775 float const pc = dcp * 100 / (source * factor());
776 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
781 LocaleGuard::LocaleGuard ()
784 char const * old = setlocale (LC_NUMERIC, 0);
788 if (strcmp (_old, "C")) {
789 setlocale (LC_NUMERIC, "C");
794 LocaleGuard::~LocaleGuard ()
796 setlocale (LC_NUMERIC, _old);
801 valid_image_file (boost::filesystem::path f)
803 string ext = f.extension().string();
804 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
805 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
809 tidy_for_filename (string f)
812 for (size_t i = 0; i < f.length(); ++i) {
813 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
823 shared_ptr<const libdcp::Signer>
826 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
828 /* Remake the chain if any of it is missing */
830 list<boost::filesystem::path> files;
831 files.push_back ("ca.self-signed.pem");
832 files.push_back ("intermediate.signed.pem");
833 files.push_back ("leaf.signed.pem");
834 files.push_back ("leaf.key");
836 list<boost::filesystem::path>::const_iterator i = files.begin();
837 while (i != files.end()) {
838 boost::filesystem::path p (sd);
840 if (!boost::filesystem::exists (p)) {
841 boost::filesystem::remove_all (sd);
842 boost::filesystem::create_directories (sd);
843 libdcp::make_signer_chain (sd, openssl_path ());
850 libdcp::CertificateChain chain;
853 boost::filesystem::path p (sd);
854 p /= "ca.self-signed.pem";
855 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
859 boost::filesystem::path p (sd);
860 p /= "intermediate.signed.pem";
861 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
865 boost::filesystem::path p (sd);
866 p /= "leaf.signed.pem";
867 chain.add (shared_ptr<libdcp::Certificate> (new libdcp::Certificate (p)));
870 boost::filesystem::path signer_key (sd);
871 signer_key /= "leaf.key";
873 return shared_ptr<const libdcp::Signer> (new libdcp::Signer (chain, signer_key));