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 <pangomm/init.h>
52 #include <libdcp/version.h>
53 #include <libdcp/util.h>
54 #include <libdcp/signer_chain.h>
55 #include <libdcp/signer.h>
57 #include <libavcodec/avcodec.h>
58 #include <libavformat/avformat.h>
59 #include <libswscale/swscale.h>
60 #include <libavfilter/avfiltergraph.h>
61 #include <libpostproc/postprocess.h>
62 #include <libavutil/pixfmt.h>
65 #include "exceptions.h"
67 #include "dcp_content_type.h"
69 #include "sound_processor.h"
74 #ifdef DCPOMATIC_WINDOWS
81 using std::stringstream;
95 using std::numeric_limits;
100 using std::set_terminate;
101 using boost::shared_ptr;
103 using boost::lexical_cast;
104 using boost::optional;
107 static boost::thread::id ui_thread;
108 static boost::filesystem::path backtrace_file;
110 /** Convert some number of seconds to a string representation
111 * in hours, minutes and seconds.
114 * @return String of the form H:M:S (where H is hours, M
115 * is minutes and S is seconds).
118 seconds_to_hms (int s)
128 hms << std::setfill ('0') << m << N_(":");
130 hms << std::setfill ('0') << s;
135 /** @param s Number of seconds.
136 * @return String containing an approximate description of s (e.g. "about 2 hours")
139 seconds_to_approximate_hms (int s)
150 ap << (h + 1) << N_(" ") << _("hours");
153 ap << N_("1 ") << _("hour");
155 ap << h << N_(" ") << _("hours");
160 ap << N_("1 ") << _("minute");
162 ap << m << N_(" ") << _("minutes");
165 ap << s << N_(" ") << _("seconds");
171 #ifdef DCPOMATIC_POSIX
172 /** @param l Mangled C++ identifier.
173 * @return Demangled version.
178 string::size_type const b = l.find_first_of (N_("("));
179 if (b == string::npos) {
183 string::size_type const p = l.find_last_of (N_("+"));
184 if (p == string::npos) {
192 string const fn = l.substr (b + 1, p - b - 1);
197 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
202 } catch (std::exception) {
209 /** Write a stacktrace to an ostream.
210 * @param out Stream to write to.
211 * @param levels Number of levels to go up the call stack.
214 stacktrace (ostream& out, int levels)
217 size_t size = backtrace (array, 200);
218 char** strings = backtrace_symbols (array, size);
221 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
222 out << N_(" ") << demangle (strings[i]) << "\n";
230 /** @param v Version as used by FFmpeg.
231 * @return A string representation of v.
234 ffmpeg_version_to_string (int v)
237 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
241 /** Return a user-readable string summarising the versions of our dependencies */
243 dependency_version_summary ()
246 s << N_("libopenjpeg ") << opj_version () << N_(", ")
247 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
248 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
249 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
250 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
251 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
252 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
253 << MagickVersion << N_(", ")
254 << N_("libssh ") << ssh_version (0) << N_(", ")
255 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
261 seconds (struct timeval t)
263 return t.tv_sec + (double (t.tv_usec) / 1e6);
266 #ifdef DCPOMATIC_WINDOWS
267 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
270 FILE* f = fopen_boost (backtrace_file, "w");
271 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
272 fprintf (f, "%p %s %d %s", i->instruction, i->function.c_str(), i->line, i->module.c_str());
275 return EXCEPTION_CONTINUE_SEARCH;
279 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
283 static bool tried_throw = false;
286 // try once to re-throw currently active exception
287 if (!tried_throw++) {
291 catch (const std::exception &e) {
292 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
293 << e.what() << std::endl;
296 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
300 #ifdef DCPOMATIC_POSIX
301 stacktrace (cout, 50);
306 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
307 * Must be called from the UI thread, if there is one.
312 #ifdef DCPOMATIC_WINDOWS
313 backtrace_file /= g_get_user_config_dir ();
314 backtrace_file /= "backtrace.txt";
315 SetUnhandledExceptionFilter(exception_handler);
317 /* Dark voodoo which, I think, gets boost::filesystem::path to
318 correctly convert UTF-8 strings to paths, and also paths
319 back to UTF-8 strings (on path::string()).
321 After this, constructing boost::filesystem::paths from strings
322 converts from UTF-8 to UTF-16 inside the path. Then
323 path::string().c_str() gives UTF-8 and
324 path::c_str() gives UTF-16.
326 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
327 so things are much simpler.
329 std::locale::global (boost::locale::generator().generate (""));
330 boost::filesystem::path::imbue (std::locale ());
333 avfilter_register_all ();
336 /* Add our lib directory to the libltdl search path so that
337 xmlsec can find xmlsec1-openssl.
339 boost::filesystem::path lib = app_contents ();
341 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
344 set_terminate (terminate);
349 Ratio::setup_ratios ();
350 DCPContentType::setup_dcp_content_types ();
351 Scaler::setup_scalers ();
352 Filter::setup_filters ();
353 SoundProcessor::setup_sound_processors ();
355 ui_thread = boost::this_thread::get_id ();
358 #ifdef DCPOMATIC_WINDOWS
359 boost::filesystem::path
363 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
364 boost::filesystem::path p (buffer);
365 p = p.parent_path ();
366 p = p.parent_path ();
373 dcpomatic_setup_gettext_i18n (string lang)
375 #ifdef DCPOMATIC_POSIX
379 if (!lang.empty ()) {
380 /* Override our environment language; this is essential on
384 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
386 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
388 snprintf (cmd, sizeof(cmd), "LC_ALL=%s", lang.c_str ());
392 setlocale (LC_ALL, "");
393 textdomain ("libdcpomatic");
395 #ifdef DCPOMATIC_WINDOWS
396 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
397 bind_textdomain_codeset ("libdcpomatic", "UTF8");
400 #ifdef DCPOMATIC_POSIX
401 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
405 /** @param s A string.
406 * @return Parts of the string split at spaces, except when a space is within quotation marks.
409 split_at_spaces_considering_quotes (string s)
412 bool in_quotes = false;
414 for (string::size_type i = 0; i < s.length(); ++i) {
415 if (s[i] == ' ' && !in_quotes) {
418 } else if (s[i] == '"') {
419 in_quotes = !in_quotes;
430 md5_digest (void const * data, int size)
433 MD5_Init (&md5_context);
434 MD5_Update (&md5_context, data, size);
435 unsigned char digest[MD5_DIGEST_LENGTH];
436 MD5_Final (digest, &md5_context);
439 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
440 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
446 /** @param job Optional job for which to report progress */
448 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
450 boost::uintmax_t const buffer_size = 64 * 1024;
451 char buffer[buffer_size];
454 MD5_Init (&md5_context);
456 vector<int64_t> sizes;
457 for (size_t i = 0; i < files.size(); ++i) {
458 sizes.push_back (boost::filesystem::file_size (files[i]));
461 for (size_t i = 0; i < files.size(); ++i) {
462 FILE* f = fopen_boost (files[i], "rb");
464 throw OpenFileError (files[i].string());
467 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
468 boost::uintmax_t remaining = bytes;
470 while (remaining > 0) {
471 int const t = min (remaining, buffer_size);
472 fread (buffer, 1, t, f);
473 MD5_Update (&md5_context, buffer, t);
477 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
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 (String::compose (_("error during async_connect (%1)"), ec.value ()));
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 (String::compose (_("error during async_accept (%1)"), ec.value ()));
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 (String::compose (_("error during async_write (%1)"), ec.value ()));
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 (String::compose (_("error during async_read (%1)"), ec.value ()));
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 (VideoFrame 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 == 8);
797 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
798 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
799 VI is the visually-impaired audio track (audio describe).
801 string const channels[] = {
815 FrameRateChange::FrameRateChange (float source, int dcp)
818 , change_speed (false)
820 if (fabs (source / 2.0 - dcp) < fabs (source - dcp)) {
821 /* The difference between source and DCP frame rate will be lower
822 (i.e. better) if we skip.
825 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
826 /* The difference between source and DCP frame rate would be better
827 if we repeated each frame once; it may be better still if we
828 repeated more than once. Work out the required repeat.
830 repeat = round (dcp / source);
833 speed_up = dcp / (source * factor());
834 change_speed = !about_equal (speed_up, 1.0);
836 if (!skip && repeat == 1 && !change_speed) {
837 description = _("Content and DCP have the same rate.\n");
840 description = _("DCP will use every other frame of the content.\n");
841 } else if (repeat == 2) {
842 description = _("Each content frame will be doubled in the DCP.\n");
843 } else if (repeat > 2) {
844 description = String::compose (_("Each content frame will be repeated %1 more times in the DCP.\n"), repeat - 1);
848 float const pc = dcp * 100 / (source * factor());
849 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
854 LocaleGuard::LocaleGuard ()
857 char const * old = setlocale (LC_NUMERIC, 0);
861 if (strcmp (_old, "C")) {
862 setlocale (LC_NUMERIC, "C");
867 LocaleGuard::~LocaleGuard ()
869 setlocale (LC_NUMERIC, _old);
874 valid_image_file (boost::filesystem::path f)
876 string ext = f.extension().string();
877 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
878 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
882 tidy_for_filename (string f)
885 for (size_t i = 0; i < f.length(); ++i) {
886 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
896 shared_ptr<const dcp::Signer>
899 boost::filesystem::path const sd = Config::instance()->signer_chain_directory ();
901 /* Remake the chain if any of it is missing */
903 list<boost::filesystem::path> files;
904 files.push_back ("ca.self-signed.pem");
905 files.push_back ("intermediate.signed.pem");
906 files.push_back ("leaf.signed.pem");
907 files.push_back ("leaf.key");
909 list<boost::filesystem::path>::const_iterator i = files.begin();
910 while (i != files.end()) {
911 boost::filesystem::path p (sd);
913 if (!boost::filesystem::exists (p)) {
914 boost::filesystem::remove_all (sd);
915 boost::filesystem::create_directories (sd);
916 dcp::make_signer_chain (sd, openssl_path ());
923 dcp::CertificateChain chain;
926 boost::filesystem::path p (sd);
927 p /= "ca.self-signed.pem";
928 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
932 boost::filesystem::path p (sd);
933 p /= "intermediate.signed.pem";
934 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
938 boost::filesystem::path p (sd);
939 p /= "leaf.signed.pem";
940 chain.add (shared_ptr<dcp::Certificate> (new dcp::Certificate (p)));
943 boost::filesystem::path signer_key (sd);
944 signer_key /= "leaf.key";
946 return shared_ptr<const dcp::Signer> (new dcp::Signer (chain, signer_key));
950 split_get_request (string url)
953 AWAITING_QUESTION_MARK,
956 } state = AWAITING_QUESTION_MARK;
958 map<string, string> r;
961 for (size_t i = 0; i < url.length(); ++i) {
963 case AWAITING_QUESTION_MARK:
978 r.insert (make_pair (k, v));
988 if (state == VALUE) {
989 r.insert (make_pair (k, v));
996 fit_ratio_within (float ratio, libdcp::Size full_frame)
998 if (ratio < full_frame.ratio ()) {
999 return dcp::Size (rint (full_frame.height * ratio), full_frame.height);
1002 return dcp::Size (full_frame.width, rint (full_frame.width / ratio));
1006 time_round_up (DCPTime t, DCPTime nearest)
1008 DCPTime const a = t + nearest - 1;
1009 return a - (a % nearest);
1013 wrapped_av_malloc (size_t s)
1015 void* p = av_malloc (s);
1023 entities_to_text (string e)
1025 boost::algorithm::replace_all (e, "%3A", ":");
1026 boost::algorithm::replace_all (e, "%2F", "/");