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.
29 #ifdef DVDOMATIC_POSIX
33 #include <libssh/libssh.h>
35 #include <boost/algorithm/string.hpp>
36 #include <boost/bind.hpp>
37 #include <boost/lambda/lambda.hpp>
38 #include <boost/lexical_cast.hpp>
39 #include <boost/thread.hpp>
41 #include <openssl/md5.h>
42 #include <magick/MagickCore.h>
43 #include <magick/version.h>
44 #include <libdcp/version.h>
46 #include <libavcodec/avcodec.h>
47 #include <libavformat/avformat.h>
48 #include <libswscale/swscale.h>
49 #include <libavfilter/avfiltergraph.h>
50 #include <libpostproc/postprocess.h>
51 #include <libavutil/pixfmt.h>
54 #include "exceptions.h"
57 #include "dcp_content_type.h"
59 #include "sound_processor.h"
62 using namespace boost;
66 /** Convert some number of seconds to a string representation
67 * in hours, minutes and seconds.
70 * @return String of the form H:M:S (where H is hours, M
71 * is minutes and S is seconds).
74 seconds_to_hms (int s)
84 hms << setfill ('0') << m << ":";
86 hms << setfill ('0') << s;
91 /** @param s Number of seconds.
92 * @return String containing an approximate description of s (e.g. "about 2 hours")
95 seconds_to_approximate_hms (int s)
106 ap << (h + 1) << " hours";
118 ap << m << " minutes";
121 ap << s << " seconds";
127 #ifdef DVDOMATIC_POSIX
128 /** @param l Mangled C++ identifier.
129 * @return Demangled version.
134 string::size_type const b = l.find_first_of ("(");
135 if (b == string::npos) {
139 string::size_type const p = l.find_last_of ("+");
140 if (p == string::npos) {
148 string const fn = l.substr (b + 1, p - b - 1);
153 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
158 } catch (std::exception) {
165 /** Write a stacktrace to an ostream.
166 * @param out Stream to write to.
167 * @param levels Number of levels to go up the call stack.
170 stacktrace (ostream& out, int levels)
177 size = backtrace (array, 200);
178 strings = backtrace_symbols (array, size);
181 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
182 out << " " << demangle (strings[i]) << endl;
190 /** @param v Version as used by FFmpeg.
191 * @return A string representation of v.
194 ffmpeg_version_to_string (int v)
197 s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
201 /** Return a user-readable string summarising the versions of our dependencies */
203 dependency_version_summary ()
206 s << "libopenjpeg " << opj_version () << ", "
207 << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
208 << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
209 << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
210 << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
211 << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
212 << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
213 << MagickVersion << ", "
214 << "libssh " << ssh_version (0) << ", "
215 << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
221 seconds (struct timeval t)
223 return t.tv_sec + (double (t.tv_usec) / 1e6);
226 /** Call the required functions to set up DVD-o-matic's static arrays, etc.
227 * Must be called from the UI thread, if there is one.
232 Format::setup_formats ();
233 DCPContentType::setup_dcp_content_types ();
234 Scaler::setup_scalers ();
235 Filter::setup_filters ();
236 SoundProcessor::setup_sound_processors ();
238 ui_thread = this_thread::get_id ();
242 crop_string (Position start, Size size)
245 s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
250 split_at_spaces_considering_quotes (string s)
253 bool in_quotes = false;
255 for (string::size_type i = 0; i < s.length(); ++i) {
256 if (s[i] == ' ' && !in_quotes) {
259 } else if (s[i] == '"') {
260 in_quotes = !in_quotes;
271 md5_digest (void const * data, int size)
274 MD5_Init (&md5_context);
275 MD5_Update (&md5_context, data, size);
276 unsigned char digest[MD5_DIGEST_LENGTH];
277 MD5_Final (digest, &md5_context);
280 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
281 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
287 /** @param file File name.
288 * @return MD5 digest of file's contents.
291 md5_digest (string file)
293 ifstream f (file.c_str(), ios::binary);
295 throw OpenFileError (file);
298 f.seekg (0, ios::end);
299 int bytes = f.tellg ();
300 f.seekg (0, ios::beg);
302 int const buffer_size = 64 * 1024;
303 char buffer[buffer_size];
306 MD5_Init (&md5_context);
308 int const t = min (bytes, buffer_size);
310 MD5_Update (&md5_context, buffer, t);
314 unsigned char digest[MD5_DIGEST_LENGTH];
315 MD5_Final (digest, &md5_context);
318 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
319 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
326 dcp_frame_rate (float fps)
330 dfr.run_fast = (fps != rint (fps));
331 dfr.frames_per_second = rint (fps);
334 /* XXX: somewhat arbitrary */
336 dfr.frames_per_second = 25;
343 /** @param An arbitrary sampling rate.
344 * @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
347 dcp_audio_sample_rate (int fs)
356 bool operator== (Size const & a, Size const & b)
358 return (a.width == b.width && a.height == b.height);
361 bool operator== (Crop const & a, Crop const & b)
363 return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
366 bool operator!= (Crop const & a, Crop const & b)
371 /** @param index Colour LUT index.
372 * @return Human-readable name.
375 colour_lut_index_to_name (int index)
389 : _deadline (_io_service)
390 , _socket (_io_service)
393 _deadline.expires_at (posix_time::pos_infin);
400 if (_deadline.expires_at() <= asio::deadline_timer::traits_type::now ()) {
402 _deadline.expires_at (posix_time::pos_infin);
405 _deadline.async_wait (boost::bind (&Socket::check, this));
408 /** Blocking connect with timeout.
409 * @param endpoint End-point to connect to.
410 * @param timeout Time-out in seconds.
413 Socket::connect (asio::ip::basic_resolver_entry<asio::ip::tcp> const & endpoint, int timeout)
415 system::error_code ec = asio::error::would_block;
416 _socket.async_connect (endpoint, lambda::var(ec) = lambda::_1);
418 _io_service.run_one();
419 } while (ec == asio::error::would_block);
421 if (ec || !_socket.is_open ()) {
422 throw NetworkError ("connect timed out");
426 /** Blocking write with timeout.
427 * @param data Buffer to write.
428 * @param size Number of bytes to write.
429 * @param timeout Time-out, in seconds.
432 Socket::write (uint8_t const * data, int size, int timeout)
434 _deadline.expires_from_now (posix_time::seconds (timeout));
435 system::error_code ec = asio::error::would_block;
437 asio::async_write (_socket, asio::buffer (data, size), lambda::var(ec) = lambda::_1);
439 _io_service.run_one ();
440 } while (ec == asio::error::would_block);
443 throw NetworkError ("write timed out");
447 /** Blocking read with timeout.
448 * @param data Buffer to read to.
449 * @param size Number of bytes to read.
450 * @param timeout Time-out, in seconds.
453 Socket::read (uint8_t* data, int size, int timeout)
455 _deadline.expires_from_now (posix_time::seconds (timeout));
456 system::error_code ec = asio::error::would_block;
460 _socket.async_read_some (
461 asio::buffer (data, size),
462 (lambda::var(ec) = lambda::_1, lambda::var(amount_read) = lambda::_2)
466 _io_service.run_one ();
467 } while (ec == asio::error::would_block);
476 /** Mark some data as being `consumed', so that it will not be returned
478 * @param size Amount of data to consume, in bytes.
481 Socket::consume (int size)
483 assert (_buffer_data >= size);
485 _buffer_data -= size;
486 if (_buffer_data > 0) {
487 /* Shift still-valid data to the start of the buffer */
488 memmove (_buffer, _buffer + size, _buffer_data);
492 /** Read a definite amount of data from our socket, and mark
494 * @param data Where to put the data.
495 * @param size Number of bytes to read.
498 Socket::read_definite_and_consume (uint8_t* data, int size, int timeout)
500 int const from_buffer = min (_buffer_data, size);
501 if (from_buffer > 0) {
502 /* Get data from our buffer */
503 memcpy (data, _buffer, from_buffer);
504 consume (from_buffer);
505 /* Update our output state */
510 /* read() the rest */
512 int const n = read (data, size, timeout);
514 throw NetworkError ("could not read");
522 /** Read as much data as is available, up to some limit.
523 * @param data Where to put the data.
524 * @param size Maximum amount of data to read.
527 Socket::read_indefinite (uint8_t* data, int size, int timeout)
529 assert (size < int (sizeof (_buffer)));
531 /* Amount of extra data we need to read () */
532 int to_read = size - _buffer_data;
533 while (to_read > 0) {
534 /* read as much of it as we can (into our buffer) */
535 int const n = read (_buffer + _buffer_data, to_read, timeout);
537 throw NetworkError ("could not read");
544 assert (_buffer_data >= size);
546 /* copy data into the output buffer */
547 assert (size >= _buffer_data);
548 memcpy (data, _buffer, size);
552 Rect::intersection (Rect const & other) const
554 int const tx = max (x, other.x);
555 int const ty = max (y, other.y);
559 min (x + width, other.x + other.width) - tx,
560 min (y + height, other.y + other.height) - ty
564 /** Round a number up to the nearest multiple of another number.
565 * @param a Number to round.
566 * @param t Multiple to round to.
567 * @return Rounded number.
571 round_up (int a, int t)
577 /** Read a sequence of key / value pairs from a text stream;
578 * the keys are the first words on the line, and the values are
579 * the remainder of the line following the key. Lines beginning
580 * with # are ignored.
581 * @param s Stream to read.
582 * @return key/value pairs.
584 multimap<string, string>
585 read_key_value (istream &s)
587 multimap<string, string> kv;
590 while (getline (s, line)) {
595 if (line[0] == '#') {
599 if (line[line.size() - 1] == '\r') {
600 line = line.substr (0, line.size() - 1);
603 size_t const s = line.find (' ');
604 if (s == string::npos) {
608 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
615 get_required_string (multimap<string, string> const & kv, string k)
617 if (kv.count (k) > 1) {
618 throw StringError ("unexpected multiple keys in key-value set");
621 multimap<string, string>::const_iterator i = kv.find (k);
623 if (i == kv.end ()) {
624 throw StringError (String::compose ("missing key %1 in key-value set", k));
631 get_required_int (multimap<string, string> const & kv, string k)
633 string const v = get_required_string (kv, k);
634 return lexical_cast<int> (v);
638 get_required_float (multimap<string, string> const & kv, string k)
640 string const v = get_required_string (kv, k);
641 return lexical_cast<float> (v);
645 get_optional_string (multimap<string, string> const & kv, string k)
647 if (kv.count (k) > 1) {
648 throw StringError ("unexpected multiple keys in key-value set");
651 multimap<string, string>::const_iterator i = kv.find (k);
652 if (i == kv.end ()) {
660 get_optional_int (multimap<string, string> const & kv, string k)
662 if (kv.count (k) > 1) {
663 throw StringError ("unexpected multiple keys in key-value set");
666 multimap<string, string>::const_iterator i = kv.find (k);
667 if (i == kv.end ()) {
671 return lexical_cast<int> (i->second);
674 AudioBuffers::AudioBuffers (int channels, int frames)
675 : _channels (channels)
677 , _allocated_frames (frames)
679 _data = new float*[_channels];
680 for (int i = 0; i < _channels; ++i) {
681 _data[i] = new float[frames];
685 AudioBuffers::AudioBuffers (AudioBuffers const & other)
686 : _channels (other._channels)
687 , _frames (other._frames)
688 , _allocated_frames (other._frames)
690 _data = new float*[_channels];
691 for (int i = 0; i < _channels; ++i) {
692 _data[i] = new float[_frames];
693 memcpy (_data[i], other._data[i], _frames * sizeof (float));
697 AudioBuffers::~AudioBuffers ()
699 for (int i = 0; i < _channels; ++i) {
707 AudioBuffers::data (int c) const
709 assert (c >= 0 && c < _channels);
714 AudioBuffers::set_frames (int f)
716 assert (f <= _allocated_frames);
721 AudioBuffers::make_silent ()
723 for (int i = 0; i < _channels; ++i) {
724 for (int j = 0; j < _frames; ++j) {
731 AudioBuffers::copy_from (AudioBuffers* from, int frames_to_copy, int read_offset, int write_offset)
733 assert (from->channels() == channels());
735 for (int i = 0; i < _channels; ++i) {
736 memcpy (_data[i] + write_offset, from->_data[i] + read_offset, frames_to_copy * sizeof(float));
741 AudioBuffers::move (int from, int to, int frames)
748 assert (from < _frames);
750 assert (to < _frames);
752 assert (frames <= _frames);
753 assert ((from + frames) <= _frames);
754 assert ((to + frames) <= _frames);
756 for (int i = 0; i < _channels; ++i) {
757 memmove (_data[i] + to, _data[i] + from, frames * sizeof(float));
764 assert (this_thread::get_id() == ui_thread);
768 video_frames_to_audio_frames (SourceFrame v, float audio_sample_rate, float frames_per_second)
770 return ((int64_t) v * audio_sample_rate / frames_per_second);