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"
65 using namespace boost;
69 /** Convert some number of seconds to a string representation
70 * in hours, minutes and seconds.
73 * @return String of the form H:M:S (where H is hours, M
74 * is minutes and S is seconds).
77 seconds_to_hms (int s)
87 hms << setfill ('0') << m << ":";
89 hms << setfill ('0') << s;
94 /** @param s Number of seconds.
95 * @return String containing an approximate description of s (e.g. "about 2 hours")
98 seconds_to_approximate_hms (int s)
109 ap << (h + 1) << " hours";
121 ap << m << " minutes";
124 ap << s << " seconds";
130 #ifdef DVDOMATIC_POSIX
131 /** @param l Mangled C++ identifier.
132 * @return Demangled version.
137 string::size_type const b = l.find_first_of ("(");
138 if (b == string::npos) {
142 string::size_type const p = l.find_last_of ("+");
143 if (p == string::npos) {
151 string const fn = l.substr (b + 1, p - b - 1);
156 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
161 } catch (std::exception) {
168 /** Write a stacktrace to an ostream.
169 * @param out Stream to write to.
170 * @param levels Number of levels to go up the call stack.
173 stacktrace (ostream& out, int levels)
180 size = backtrace (array, 200);
181 strings = backtrace_symbols (array, size);
184 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
185 out << " " << demangle (strings[i]) << endl;
193 /** @param v Version as used by FFmpeg.
194 * @return A string representation of v.
197 ffmpeg_version_to_string (int v)
200 s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
204 /** Return a user-readable string summarising the versions of our dependencies */
206 dependency_version_summary ()
209 s << "libopenjpeg " << opj_version () << ", "
210 << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
211 << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
212 << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
213 << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
214 << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
215 << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
216 << MagickVersion << ", "
217 << "libssh " << ssh_version (0) << ", "
218 << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
224 seconds (struct timeval t)
226 return t.tv_sec + (double (t.tv_usec) / 1e6);
229 /** Call the required functions to set up DVD-o-matic's static arrays, etc.
230 * Must be called from the UI thread, if there is one.
235 Format::setup_formats ();
236 DCPContentType::setup_dcp_content_types ();
237 Scaler::setup_scalers ();
238 Filter::setup_filters ();
239 SoundProcessor::setup_sound_processors ();
241 ui_thread = this_thread::get_id ();
244 /** @param start Start position for the crop within the image.
245 * @param size Size of the cropped area.
246 * @return FFmpeg crop filter string.
249 crop_string (Position start, Size size)
252 s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
256 /** @param s A string.
257 * @return Parts of the string split at spaces, except when a space is within quotation marks.
260 split_at_spaces_considering_quotes (string s)
263 bool in_quotes = false;
265 for (string::size_type i = 0; i < s.length(); ++i) {
266 if (s[i] == ' ' && !in_quotes) {
269 } else if (s[i] == '"') {
270 in_quotes = !in_quotes;
281 md5_digest (void const * data, int size)
284 MD5_Init (&md5_context);
285 MD5_Update (&md5_context, data, size);
286 unsigned char digest[MD5_DIGEST_LENGTH];
287 MD5_Final (digest, &md5_context);
290 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
291 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
297 /** @param file File name.
298 * @return MD5 digest of file's contents.
301 md5_digest (string file)
303 ifstream f (file.c_str(), ios::binary);
305 throw OpenFileError (file);
308 f.seekg (0, ios::end);
309 int bytes = f.tellg ();
310 f.seekg (0, ios::beg);
312 int const buffer_size = 64 * 1024;
313 char buffer[buffer_size];
316 MD5_Init (&md5_context);
318 int const t = min (bytes, buffer_size);
320 MD5_Update (&md5_context, buffer, t);
324 unsigned char digest[MD5_DIGEST_LENGTH];
325 MD5_Final (digest, &md5_context);
328 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
329 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
335 static bool about_equal (float a, float b)
337 /* A film of F seconds at f FPS will be Ff frames;
338 Consider some delta FPS d, so if we run the same
339 film at (f + d) FPS it will last F(f + d) seconds.
341 Hence the difference in length over the length of the film will
342 be F(f + d) - Ff frames
343 = Ff + Fd - Ff frames
347 So if we accept a difference of 1 frame, ie 1/f seconds, we can
354 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
355 FPS error is 1/F ~= 0.0001 ~= 10-e4
358 return (fabs (a - b) < 1e-4);
361 class FrameRateCandidate
364 FrameRateCandidate (float source_, int dcp_)
370 return !about_equal (source, dcp) && source > dcp;
373 bool repeat () const {
374 return !about_equal (source, dcp) && source < dcp;
381 /** @param fps Arbitrary source frames-per-second value */
382 /** XXX: this could be slow-ish */
383 DCPFrameRate::DCPFrameRate (float source_fps)
385 list<int> const allowed_dcp_frame_rates = Config::instance()->allowed_dcp_frame_rates ();
387 /* Work out what rates we could manage, including those achieved by using skip / repeat. */
388 list<FrameRateCandidate> candidates;
390 /* Start with the ones without skip / repeat so they will get matched in preference to skipped/repeated ones */
391 for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
392 candidates.push_back (FrameRateCandidate (*i, *i));
395 /* Then the skip/repeat ones */
396 for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
397 candidates.push_back (FrameRateCandidate (float (*i) / 2, *i));
398 candidates.push_back (FrameRateCandidate (float (*i) * 2, *i));
401 /* Pick the best one, bailing early if we hit an exact match */
402 float error = numeric_limits<float>::max ();
403 boost::optional<FrameRateCandidate> best;
404 list<FrameRateCandidate>::iterator i = candidates.begin();
405 while (i != candidates.end()) {
407 if (about_equal (i->source, source_fps)) {
412 float const e = fabs (i->source - source_fps);
422 throw EncodeError ("cannot find a suitable DCP frame rate for this source");
425 frames_per_second = best->dcp;
426 skip = best->skip ();
427 repeat = best->repeat ();
428 change_speed = !about_equal (source_fps * factor(), frames_per_second);
431 /** @param An arbitrary sampling rate.
432 * @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
435 dcp_audio_sample_rate (int fs)
445 dcp_audio_channels (int f)
448 /* The source is mono, so to put the mono channel into
449 the centre we need to generate a 5.1 soundtrack.
458 bool operator== (Size const & a, Size const & b)
460 return (a.width == b.width && a.height == b.height);
463 bool operator!= (Size const & a, Size const & b)
468 bool operator== (Crop const & a, Crop const & b)
470 return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
473 bool operator!= (Crop const & a, Crop const & b)
478 /** @param index Colour LUT index.
479 * @return Human-readable name.
482 colour_lut_index_to_name (int index)
496 : _deadline (_io_service)
497 , _socket (_io_service)
500 _deadline.expires_at (posix_time::pos_infin);
507 if (_deadline.expires_at() <= asio::deadline_timer::traits_type::now ()) {
509 _deadline.expires_at (posix_time::pos_infin);
512 _deadline.async_wait (boost::bind (&Socket::check, this));
515 /** Blocking connect with timeout.
516 * @param endpoint End-point to connect to.
517 * @param timeout Time-out in seconds.
520 Socket::connect (asio::ip::basic_resolver_entry<asio::ip::tcp> const & endpoint, int timeout)
522 _deadline.expires_from_now (posix_time::seconds (timeout));
523 system::error_code ec = asio::error::would_block;
524 _socket.async_connect (endpoint, lambda::var(ec) = lambda::_1);
526 _io_service.run_one();
527 } while (ec == asio::error::would_block);
529 if (ec || !_socket.is_open ()) {
530 throw NetworkError ("connect timed out");
534 /** Blocking write with timeout.
535 * @param data Buffer to write.
536 * @param size Number of bytes to write.
537 * @param timeout Time-out, in seconds.
540 Socket::write (uint8_t const * data, int size, int timeout)
542 _deadline.expires_from_now (posix_time::seconds (timeout));
543 system::error_code ec = asio::error::would_block;
545 asio::async_write (_socket, asio::buffer (data, size), lambda::var(ec) = lambda::_1);
547 _io_service.run_one ();
548 } while (ec == asio::error::would_block);
551 throw NetworkError ("write timed out");
555 /** Blocking read with timeout.
556 * @param data Buffer to read to.
557 * @param size Number of bytes to read.
558 * @param timeout Time-out, in seconds.
561 Socket::read (uint8_t* data, int size, int timeout)
563 _deadline.expires_from_now (posix_time::seconds (timeout));
564 system::error_code ec = asio::error::would_block;
568 _socket.async_read_some (
569 asio::buffer (data, size),
570 (lambda::var(ec) = lambda::_1, lambda::var(amount_read) = lambda::_2)
574 _io_service.run_one ();
575 } while (ec == asio::error::would_block);
584 /** Mark some data as being `consumed', so that it will not be returned
586 * @param size Amount of data to consume, in bytes.
589 Socket::consume (int size)
591 assert (_buffer_data >= size);
593 _buffer_data -= size;
594 if (_buffer_data > 0) {
595 /* Shift still-valid data to the start of the buffer */
596 memmove (_buffer, _buffer + size, _buffer_data);
600 /** Read a definite amount of data from our socket, and mark
602 * @param data Where to put the data.
603 * @param size Number of bytes to read.
606 Socket::read_definite_and_consume (uint8_t* data, int size, int timeout)
608 int const from_buffer = min (_buffer_data, size);
609 if (from_buffer > 0) {
610 /* Get data from our buffer */
611 memcpy (data, _buffer, from_buffer);
612 consume (from_buffer);
613 /* Update our output state */
618 /* read() the rest */
620 int const n = read (data, size, timeout);
622 throw NetworkError ("could not read");
630 /** Read as much data as is available, up to some limit.
631 * @param data Where to put the data.
632 * @param size Maximum amount of data to read.
635 Socket::read_indefinite (uint8_t* data, int size, int timeout)
637 assert (size < int (sizeof (_buffer)));
639 /* Amount of extra data we need to read () */
640 int to_read = size - _buffer_data;
641 while (to_read > 0) {
642 /* read as much of it as we can (into our buffer) */
643 int const n = read (_buffer + _buffer_data, to_read, timeout);
645 throw NetworkError ("could not read");
652 assert (_buffer_data >= size);
654 /* copy data into the output buffer */
655 assert (size >= _buffer_data);
656 memcpy (data, _buffer, size);
659 /** @param other A Rect.
660 * @return The intersection of this with `other'.
663 Rect::intersection (Rect const & other) const
665 int const tx = max (x, other.x);
666 int const ty = max (y, other.y);
670 min (x + width, other.x + other.width) - tx,
671 min (y + height, other.y + other.height) - ty
675 /** Round a number up to the nearest multiple of another number.
677 * @param s Array of numbers to round, indexed by c.
678 * @param t Multiple to round to.
679 * @return Rounded number.
682 stride_round_up (int c, int const * stride, int t)
684 int const a = stride[c] + (t - 1);
689 stride_lookup (int c, int const * stride)
694 /** Read a sequence of key / value pairs from a text stream;
695 * the keys are the first words on the line, and the values are
696 * the remainder of the line following the key. Lines beginning
697 * with # are ignored.
698 * @param s Stream to read.
699 * @return key/value pairs.
701 multimap<string, string>
702 read_key_value (istream &s)
704 multimap<string, string> kv;
707 while (getline (s, line)) {
712 if (line[0] == '#') {
716 if (line[line.size() - 1] == '\r') {
717 line = line.substr (0, line.size() - 1);
720 size_t const s = line.find (' ');
721 if (s == string::npos) {
725 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
732 get_required_string (multimap<string, string> const & kv, string k)
734 if (kv.count (k) > 1) {
735 throw StringError ("unexpected multiple keys in key-value set");
738 multimap<string, string>::const_iterator i = kv.find (k);
740 if (i == kv.end ()) {
741 throw StringError (String::compose ("missing key %1 in key-value set", k));
748 get_required_int (multimap<string, string> const & kv, string k)
750 string const v = get_required_string (kv, k);
751 return lexical_cast<int> (v);
755 get_required_float (multimap<string, string> const & kv, string k)
757 string const v = get_required_string (kv, k);
758 return lexical_cast<float> (v);
762 get_optional_string (multimap<string, string> const & kv, string k)
764 if (kv.count (k) > 1) {
765 throw StringError ("unexpected multiple keys in key-value set");
768 multimap<string, string>::const_iterator i = kv.find (k);
769 if (i == kv.end ()) {
777 get_optional_int (multimap<string, string> const & kv, string k)
779 if (kv.count (k) > 1) {
780 throw StringError ("unexpected multiple keys in key-value set");
783 multimap<string, string>::const_iterator i = kv.find (k);
784 if (i == kv.end ()) {
788 return lexical_cast<int> (i->second);
791 /** Construct an AudioBuffers. Audio data is undefined after this constructor.
792 * @param channels Number of channels.
793 * @param frames Number of frames to reserve space for.
795 AudioBuffers::AudioBuffers (int channels, int frames)
796 : _channels (channels)
798 , _allocated_frames (frames)
800 _data = new float*[_channels];
801 for (int i = 0; i < _channels; ++i) {
802 _data[i] = new float[frames];
806 /** Copy constructor.
807 * @param other Other AudioBuffers; data is copied.
809 AudioBuffers::AudioBuffers (AudioBuffers const & other)
810 : _channels (other._channels)
811 , _frames (other._frames)
812 , _allocated_frames (other._frames)
814 _data = new float*[_channels];
815 for (int i = 0; i < _channels; ++i) {
816 _data[i] = new float[_frames];
817 memcpy (_data[i], other._data[i], _frames * sizeof (float));
821 /** AudioBuffers destructor */
822 AudioBuffers::~AudioBuffers ()
824 for (int i = 0; i < _channels; ++i) {
831 /** @param c Channel index.
832 * @return Buffer for this channel.
835 AudioBuffers::data (int c) const
837 assert (c >= 0 && c < _channels);
841 /** Set the number of frames that these AudioBuffers will report themselves
843 * @param f Frames; must be less than or equal to the number of allocated frames.
846 AudioBuffers::set_frames (int f)
848 assert (f <= _allocated_frames);
852 /** Make all samples on all channels silent */
854 AudioBuffers::make_silent ()
856 for (int i = 0; i < _channels; ++i) {
861 /** Make all samples on a given channel silent.
865 AudioBuffers::make_silent (int c)
867 assert (c >= 0 && c < _channels);
869 for (int i = 0; i < _frames; ++i) {
874 /** Copy data from another AudioBuffers to this one. All channels are copied.
875 * @param from AudioBuffers to copy from; must have the same number of channels as this.
876 * @param frames_to_copy Number of frames to copy.
877 * @param read_offset Offset to read from in `from'.
878 * @param write_offset Offset to write to in `to'.
881 AudioBuffers::copy_from (AudioBuffers* from, int frames_to_copy, int read_offset, int write_offset)
883 assert (from->channels() == channels());
886 assert (read_offset >= 0 && (read_offset + frames_to_copy) <= from->_allocated_frames);
887 assert (write_offset >= 0 && (write_offset + frames_to_copy) <= _allocated_frames);
889 for (int i = 0; i < _channels; ++i) {
890 memcpy (_data[i] + write_offset, from->_data[i] + read_offset, frames_to_copy * sizeof(float));
894 /** Move audio data around.
895 * @param from Offset to move from.
896 * @param to Offset to move to.
897 * @param frames Number of frames to move.
901 AudioBuffers::move (int from, int to, int frames)
908 assert (from < _frames);
910 assert (to < _frames);
912 assert (frames <= _frames);
913 assert ((from + frames) <= _frames);
914 assert ((to + frames) <= _frames);
916 for (int i = 0; i < _channels; ++i) {
917 memmove (_data[i] + to, _data[i] + from, frames * sizeof(float));
921 /** Trip an assert if the caller is not in the UI thread */
925 assert (this_thread::get_id() == ui_thread);
928 /** @param v Source video frame.
929 * @param audio_sample_rate Source audio sample rate.
930 * @param frames_per_second Number of video frames per second.
931 * @return Equivalent number of audio frames for `v'.
934 video_frames_to_audio_frames (SourceFrame v, float audio_sample_rate, float frames_per_second)
936 return ((int64_t) v * audio_sample_rate / frames_per_second);
939 /** @param f Filename.
940 * @return true if this file is a still image, false if it is something else.
943 still_image_file (string f)
945 #if BOOST_FILESYSTEM_VERSION == 3
946 string ext = boost::filesystem::path(f).extension().string();
948 string ext = boost::filesystem::path(f).extension();
951 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
953 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png");
956 /** @return A pair containing CPU model name and the number of processors */
960 pair<string, int> info;
963 #ifdef DVDOMATIC_POSIX
964 ifstream f ("/proc/cpuinfo");
968 if (boost::algorithm::starts_with (l, "model name")) {
969 string::size_type const c = l.find (':');
970 if (c != string::npos) {
971 info.first = l.substr (c + 2);
973 } else if (boost::algorithm::starts_with (l, "processor")) {