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 DVDOMATIC_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>
43 #include <openssl/md5.h>
44 #include <magick/MagickCore.h>
45 #include <magick/version.h>
46 #include <libdcp/version.h>
48 #include <libavcodec/avcodec.h>
49 #include <libavformat/avformat.h>
50 #include <libswscale/swscale.h>
51 #include <libavfilter/avfiltergraph.h>
52 #include <libpostproc/postprocess.h>
53 #include <libavutil/pixfmt.h>
56 #include "exceptions.h"
59 #include "dcp_content_type.h"
61 #include "sound_processor.h"
68 using std::stringstream;
78 using boost::shared_ptr;
79 using boost::lexical_cast;
80 using boost::optional;
83 boost::thread::id ui_thread;
85 /** Convert some number of seconds to a string representation
86 * in hours, minutes and seconds.
89 * @return String of the form H:M:S (where H is hours, M
90 * is minutes and S is seconds).
93 seconds_to_hms (int s)
103 hms << std::setfill ('0') << m << N_(":");
105 hms << std::setfill ('0') << s;
110 /** @param s Number of seconds.
111 * @return String containing an approximate description of s (e.g. "about 2 hours")
114 seconds_to_approximate_hms (int s)
125 ap << (h + 1) << N_(" ") << _("hours");
128 ap << N_("1 ") << _("hour");
130 ap << h << N_(" ") << _("hours");
135 ap << N_("1 ") << _("minute");
137 ap << m << N_(" ") << _("minutes");
140 ap << s << N_(" ") << _("seconds");
146 #ifdef DVDOMATIC_POSIX
147 /** @param l Mangled C++ identifier.
148 * @return Demangled version.
153 string::size_type const b = l.find_first_of (N_("("));
154 if (b == string::npos) {
158 string::size_type const p = l.find_last_of (N_("+"));
159 if (p == string::npos) {
167 string const fn = l.substr (b + 1, p - b - 1);
172 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
177 } catch (std::exception) {
184 /** Write a stacktrace to an ostream.
185 * @param out Stream to write to.
186 * @param levels Number of levels to go up the call stack.
189 stacktrace (ostream& out, int levels)
196 size = backtrace (array, 200);
197 strings = backtrace_symbols (array, size);
200 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
201 out << N_(" ") << demangle (strings[i]) << "\n";
209 /** @param v Version as used by FFmpeg.
210 * @return A string representation of v.
213 ffmpeg_version_to_string (int v)
216 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
220 /** Return a user-readable string summarising the versions of our dependencies */
222 dependency_version_summary ()
225 s << N_("libopenjpeg ") << opj_version () << N_(", ")
226 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
227 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
228 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
229 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
230 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
231 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
232 << MagickVersion << N_(", ")
233 << N_("libssh ") << ssh_version (0) << N_(", ")
234 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
240 seconds (struct timeval t)
242 return t.tv_sec + (double (t.tv_usec) / 1e6);
245 /** Call the required functions to set up DVD-o-matic's static arrays, etc.
246 * Must be called from the UI thread, if there is one.
251 avfilter_register_all ();
253 Format::setup_formats ();
254 DCPContentType::setup_dcp_content_types ();
255 Scaler::setup_scalers ();
256 Filter::setup_filters ();
257 SoundProcessor::setup_sound_processors ();
259 ui_thread = boost::this_thread::get_id ();
262 #ifdef DVDOMATIC_WINDOWS
263 boost::filesystem::path
267 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
268 boost::filesystem::path p (buffer);
269 p = p.parent_path ();
270 p = p.parent_path ();
277 dvdomatic_setup_i18n (string lang)
279 #ifdef DVDOMATIC_POSIX
283 if (!lang.empty ()) {
284 /* Override our environment language; this is essential on
288 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
290 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
294 setlocale (LC_ALL, "");
295 textdomain ("libdvdomatic");
297 #ifdef DVDOMATIC_WINDOWS
298 bindtextdomain ("libdvdomatic", mo_path().string().c_str());
299 bind_textdomain_codeset ("libdvdomatic", "UTF8");
302 #ifdef DVDOMATIC_POSIX
303 bindtextdomain ("libdvdomatic", POSIX_LOCALE_PREFIX);
307 /** @param start Start position for the crop within the image.
308 * @param size Size of the cropped area.
309 * @return FFmpeg crop filter string.
312 crop_string (Position start, libdcp::Size size)
315 s << N_("crop=") << size.width << N_(":") << size.height << N_(":") << start.x << N_(":") << start.y;
319 /** @param s A string.
320 * @return Parts of the string split at spaces, except when a space is within quotation marks.
323 split_at_spaces_considering_quotes (string s)
326 bool in_quotes = false;
328 for (string::size_type i = 0; i < s.length(); ++i) {
329 if (s[i] == ' ' && !in_quotes) {
332 } else if (s[i] == '"') {
333 in_quotes = !in_quotes;
344 md5_digest (void const * data, int size)
347 MD5_Init (&md5_context);
348 MD5_Update (&md5_context, data, size);
349 unsigned char digest[MD5_DIGEST_LENGTH];
350 MD5_Final (digest, &md5_context);
353 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
354 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
360 /** @param file File name.
361 * @return MD5 digest of file's contents.
364 md5_digest (string file)
366 ifstream f (file.c_str(), std::ios::binary);
368 throw OpenFileError (file);
371 f.seekg (0, std::ios::end);
372 int bytes = f.tellg ();
373 f.seekg (0, std::ios::beg);
375 int const buffer_size = 64 * 1024;
376 char buffer[buffer_size];
379 MD5_Init (&md5_context);
381 int const t = min (bytes, buffer_size);
383 MD5_Update (&md5_context, buffer, t);
387 unsigned char digest[MD5_DIGEST_LENGTH];
388 MD5_Final (digest, &md5_context);
391 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
392 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
399 about_equal (float a, float b)
401 /* A film of F seconds at f FPS will be Ff frames;
402 Consider some delta FPS d, so if we run the same
403 film at (f + d) FPS it will last F(f + d) seconds.
405 Hence the difference in length over the length of the film will
406 be F(f + d) - Ff frames
407 = Ff + Fd - Ff frames
411 So if we accept a difference of 1 frame, ie 1/f seconds, we can
418 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
419 FPS error is 1/F ~= 0.0001 ~= 10-e4
422 return (fabs (a - b) < 1e-4);
425 class FrameRateCandidate
428 FrameRateCandidate (float source_, int dcp_)
438 best_dcp_frame_rate (float source_fps)
440 list<int> const allowed_dcp_frame_rates = Config::instance()->allowed_dcp_frame_rates ();
442 /* Work out what rates we could manage, including those achieved by using skip / repeat. */
443 list<FrameRateCandidate> candidates;
445 /* Start with the ones without skip / repeat so they will get matched in preference to skipped/repeated ones */
446 for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
447 candidates.push_back (FrameRateCandidate (*i, *i));
450 /* Then the skip/repeat ones */
451 for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
452 candidates.push_back (FrameRateCandidate (float (*i) / 2, *i));
453 candidates.push_back (FrameRateCandidate (float (*i) * 2, *i));
456 /* Pick the best one, bailing early if we hit an exact match */
457 float error = std::numeric_limits<float>::max ();
458 optional<FrameRateCandidate> best;
459 list<FrameRateCandidate>::iterator i = candidates.begin();
460 while (i != candidates.end()) {
462 if (about_equal (i->source, source_fps)) {
467 float const e = fabs (i->source - source_fps);
480 /** @param An arbitrary sampling rate.
481 * @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
484 dcp_audio_sample_rate (int fs)
493 bool operator== (Crop const & a, Crop const & b)
495 return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
498 bool operator!= (Crop const & a, Crop const & b)
503 /** @param index Colour LUT index.
504 * @return Human-readable name.
507 colour_lut_index_to_name (int index)
520 Socket::Socket (int timeout)
521 : _deadline (_io_service)
522 , _socket (_io_service)
525 _deadline.expires_at (boost::posix_time::pos_infin);
532 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
534 _deadline.expires_at (boost::posix_time::pos_infin);
537 _deadline.async_wait (boost::bind (&Socket::check, this));
540 /** Blocking connect.
541 * @param endpoint End-point to connect to.
544 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
546 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
547 boost::system::error_code ec = boost::asio::error::would_block;
548 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
550 _io_service.run_one();
551 } while (ec == boost::asio::error::would_block);
553 if (ec || !_socket.is_open ()) {
554 throw NetworkError (_("connect timed out"));
559 * @param data Buffer to write.
560 * @param size Number of bytes to write.
563 Socket::write (uint8_t const * data, int size)
565 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
566 boost::system::error_code ec = boost::asio::error::would_block;
568 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
571 _io_service.run_one ();
572 } while (ec == boost::asio::error::would_block);
575 throw NetworkError (ec.message ());
580 Socket::write (uint32_t v)
583 write (reinterpret_cast<uint8_t*> (&v), 4);
587 * @param data Buffer to read to.
588 * @param size Number of bytes to read.
591 Socket::read (uint8_t* data, int size)
593 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
594 boost::system::error_code ec = boost::asio::error::would_block;
596 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
599 _io_service.run_one ();
600 } while (ec == boost::asio::error::would_block);
603 throw NetworkError (ec.message ());
608 Socket::read_uint32 ()
611 read (reinterpret_cast<uint8_t *> (&v), 4);
615 /** @param other A Rect.
616 * @return The intersection of this with `other'.
619 Rect::intersection (Rect const & other) const
621 int const tx = max (x, other.x);
622 int const ty = max (y, other.y);
626 min (x + width, other.x + other.width) - tx,
627 min (y + height, other.y + other.height) - ty
631 /** Round a number up to the nearest multiple of another number.
633 * @param s Array of numbers to round, indexed by c.
634 * @param t Multiple to round to.
635 * @return Rounded number.
638 stride_round_up (int c, int const * stride, int t)
640 int const a = stride[c] + (t - 1);
645 stride_lookup (int c, int const * stride)
650 /** Read a sequence of key / value pairs from a text stream;
651 * the keys are the first words on the line, and the values are
652 * the remainder of the line following the key. Lines beginning
653 * with # are ignored.
654 * @param s Stream to read.
655 * @return key/value pairs.
657 multimap<string, string>
658 read_key_value (istream &s)
660 multimap<string, string> kv;
663 while (getline (s, line)) {
668 if (line[0] == '#') {
672 if (line[line.size() - 1] == '\r') {
673 line = line.substr (0, line.size() - 1);
676 size_t const s = line.find (' ');
677 if (s == string::npos) {
681 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
688 get_required_string (multimap<string, string> const & kv, string k)
690 if (kv.count (k) > 1) {
691 throw StringError (N_("unexpected multiple keys in key-value set"));
694 multimap<string, string>::const_iterator i = kv.find (k);
696 if (i == kv.end ()) {
697 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
704 get_required_int (multimap<string, string> const & kv, string k)
706 string const v = get_required_string (kv, k);
707 return lexical_cast<int> (v);
711 get_required_float (multimap<string, string> const & kv, string k)
713 string const v = get_required_string (kv, k);
714 return lexical_cast<float> (v);
718 get_optional_string (multimap<string, string> const & kv, string k)
720 if (kv.count (k) > 1) {
721 throw StringError (N_("unexpected multiple keys in key-value set"));
724 multimap<string, string>::const_iterator i = kv.find (k);
725 if (i == kv.end ()) {
733 get_optional_int (multimap<string, string> const & kv, string k)
735 if (kv.count (k) > 1) {
736 throw StringError (N_("unexpected multiple keys in key-value set"));
739 multimap<string, string>::const_iterator i = kv.find (k);
740 if (i == kv.end ()) {
744 return lexical_cast<int> (i->second);
747 /** Construct an AudioBuffers. Audio data is undefined after this constructor.
748 * @param channels Number of channels.
749 * @param frames Number of frames to reserve space for.
751 AudioBuffers::AudioBuffers (int channels, int frames)
752 : _channels (channels)
754 , _allocated_frames (frames)
756 _data = new float*[_channels];
757 for (int i = 0; i < _channels; ++i) {
758 _data[i] = new float[frames];
762 /** Copy constructor.
763 * @param other Other AudioBuffers; data is copied.
765 AudioBuffers::AudioBuffers (AudioBuffers const & other)
766 : _channels (other._channels)
767 , _frames (other._frames)
768 , _allocated_frames (other._frames)
770 _data = new float*[_channels];
771 for (int i = 0; i < _channels; ++i) {
772 _data[i] = new float[_frames];
773 memcpy (_data[i], other._data[i], _frames * sizeof (float));
777 /* XXX: it's a shame that this is a copy-and-paste of the above;
778 probably fixable with c++0x.
780 AudioBuffers::AudioBuffers (boost::shared_ptr<const AudioBuffers> other)
781 : _channels (other->_channels)
782 , _frames (other->_frames)
783 , _allocated_frames (other->_frames)
785 _data = new float*[_channels];
786 for (int i = 0; i < _channels; ++i) {
787 _data[i] = new float[_frames];
788 memcpy (_data[i], other->_data[i], _frames * sizeof (float));
792 /** AudioBuffers destructor */
793 AudioBuffers::~AudioBuffers ()
795 for (int i = 0; i < _channels; ++i) {
802 /** @param c Channel index.
803 * @return Buffer for this channel.
806 AudioBuffers::data (int c) const
808 assert (c >= 0 && c < _channels);
812 /** Set the number of frames that these AudioBuffers will report themselves
814 * @param f Frames; must be less than or equal to the number of allocated frames.
817 AudioBuffers::set_frames (int f)
819 assert (f <= _allocated_frames);
823 /** Make all samples on all channels silent */
825 AudioBuffers::make_silent ()
827 for (int i = 0; i < _channels; ++i) {
832 /** Make all samples on a given channel silent.
836 AudioBuffers::make_silent (int c)
838 assert (c >= 0 && c < _channels);
840 for (int i = 0; i < _frames; ++i) {
845 /** Copy data from another AudioBuffers to this one. All channels are copied.
846 * @param from AudioBuffers to copy from; must have the same number of channels as this.
847 * @param frames_to_copy Number of frames to copy.
848 * @param read_offset Offset to read from in `from'.
849 * @param write_offset Offset to write to in `to'.
852 AudioBuffers::copy_from (AudioBuffers* from, int frames_to_copy, int read_offset, int write_offset)
854 assert (from->channels() == channels());
857 assert (read_offset >= 0 && (read_offset + frames_to_copy) <= from->_allocated_frames);
858 assert (write_offset >= 0 && (write_offset + frames_to_copy) <= _allocated_frames);
860 for (int i = 0; i < _channels; ++i) {
861 memcpy (_data[i] + write_offset, from->_data[i] + read_offset, frames_to_copy * sizeof(float));
865 /** Move audio data around.
866 * @param from Offset to move from.
867 * @param to Offset to move to.
868 * @param frames Number of frames to move.
872 AudioBuffers::move (int from, int to, int frames)
879 assert (from < _frames);
881 assert (to < _frames);
883 assert (frames <= _frames);
884 assert ((from + frames) <= _frames);
885 assert ((to + frames) <= _frames);
887 for (int i = 0; i < _channels; ++i) {
888 memmove (_data[i] + to, _data[i] + from, frames * sizeof(float));
892 /** Trip an assert if the caller is not in the UI thread */
896 assert (boost::this_thread::get_id() == ui_thread);
899 /** @param v Source video frame.
900 * @param audio_sample_rate Source audio sample rate.
901 * @param frames_per_second Number of video frames per second.
902 * @return Equivalent number of audio frames for `v'.
905 video_frames_to_audio_frames (SourceFrame v, float audio_sample_rate, float frames_per_second)
907 return ((int64_t) v * audio_sample_rate / frames_per_second);
910 /** @param f Filename.
911 * @return true if this file is a still image, false if it is something else.
914 still_image_file (string f)
916 string ext = boost::filesystem::path(f).extension().string();
918 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
920 return (ext == N_(".tif") || ext == N_(".tiff") || ext == N_(".jpg") || ext == N_(".jpeg") || ext == N_(".png") || ext == N_(".bmp"));
923 /** @return A pair containing CPU model name and the number of processors */
927 pair<string, int> info;
930 #ifdef DVDOMATIC_POSIX
931 ifstream f (N_("/proc/cpuinfo"));
935 if (boost::algorithm::starts_with (l, N_("model name"))) {
936 string::size_type const c = l.find (':');
937 if (c != string::npos) {
938 info.first = l.substr (c + 2);
940 } else if (boost::algorithm::starts_with (l, N_("processor"))) {
950 audio_channel_name (int c)
952 assert (MAX_AUDIO_CHANNELS == 6);
954 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
955 enhancement channel (sub-woofer)./
957 string const channels[] = {
969 AudioMapping::AudioMapping (int c)
970 : _source_channels (c)
975 optional<libdcp::Channel>
976 AudioMapping::source_to_dcp (int c) const
978 if (c >= _source_channels) {
979 return optional<libdcp::Channel> ();
982 if (_source_channels == 1) {
983 /* mono sources to centre */
984 return libdcp::CENTRE;
987 return static_cast<libdcp::Channel> (c);
991 AudioMapping::dcp_to_source (libdcp::Channel c) const
993 if (_source_channels == 1) {
994 if (c == libdcp::CENTRE) {
997 return optional<int> ();
1001 if (static_cast<int> (c) >= _source_channels) {
1002 return optional<int> ();
1005 return static_cast<int> (c);
1009 AudioMapping::dcp_channels () const
1011 if (_source_channels == 1) {
1012 /* The source is mono, so to put the mono channel into
1013 the centre we need to generate a 5.1 soundtrack.
1018 return _source_channels;
1021 FrameRateConversion::FrameRateConversion (float source, int dcp)
1024 , change_speed (false)
1026 if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
1028 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
1032 change_speed = !about_equal (source * factor(), dcp);
1034 if (!skip && !repeat && !change_speed) {
1035 description = _("DCP and source have the same rate.\n");
1038 description = _("DCP will use every other frame of the source.\n");
1039 } else if (repeat) {
1040 description = _("Each source frame will be doubled in the DCP.\n");
1044 float const pc = dcp * 100 / (source * factor());
1045 description += String::compose (_("DCP will run at %1%% of the source speed.\n"), pc);
1050 LocaleGuard::LocaleGuard ()
1053 char const * old = setlocale (LC_NUMERIC, 0);
1056 _old = strdup (old);
1057 if (strcmp (_old, "POSIX")) {
1058 setlocale (LC_NUMERIC, "POSIX");
1063 LocaleGuard::~LocaleGuard ()
1065 setlocale (LC_NUMERIC, _old);