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"
60 #include "sound_processor.h"
61 #ifndef DVDOMATIC_DISABLE_PLAYER
62 #include "player_manager.h"
66 using namespace boost;
70 /** Convert some number of seconds to a string representation
71 * in hours, minutes and seconds.
74 * @return String of the form H:M:S (where H is hours, M
75 * is minutes and S is seconds).
78 seconds_to_hms (int s)
88 hms << setfill ('0') << m << ":";
90 hms << setfill ('0') << s;
95 /** @param s Number of seconds.
96 * @return String containing an approximate description of s (e.g. "about 2 hours")
99 seconds_to_approximate_hms (int s)
110 ap << (h + 1) << " hours";
122 ap << m << " minutes";
125 ap << s << " seconds";
131 #ifdef DVDOMATIC_POSIX
132 /** @param l Mangled C++ identifier.
133 * @return Demangled version.
138 string::size_type const b = l.find_first_of ("(");
139 if (b == string::npos) {
143 string::size_type const p = l.find_last_of ("+");
144 if (p == string::npos) {
152 string const fn = l.substr (b + 1, p - b - 1);
157 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
162 } catch (std::exception) {
169 /** Write a stacktrace to an ostream.
170 * @param out Stream to write to.
171 * @param levels Number of levels to go up the call stack.
174 stacktrace (ostream& out, int levels)
181 size = backtrace (array, 200);
182 strings = backtrace_symbols (array, size);
185 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
186 out << " " << demangle (strings[i]) << endl;
194 /** @return Version of vobcopy that is on the path (and hence that we will use) */
198 FILE* f = popen ("vobcopy -V 2>&1", "r");
200 throw EncodeError ("could not run vobcopy to check version");
203 string version = "unknown";
207 if (fgets (buf, sizeof (buf), f)) {
210 split (b, s, is_any_of (" "));
211 if (b.size() >= 2 && b[0] == "Vobcopy") {
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) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
233 /** Return a user-readable string summarising the versions of our dependencies */
235 dependency_version_summary ()
238 s << "libopenjpeg " << opj_version () << ", "
239 << "vobcopy " << vobcopy_version() << ", "
240 << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
241 << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
242 << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
243 << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
244 << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
245 << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
246 << MagickVersion << ", "
247 << "libssh " << ssh_version (0) << ", "
248 << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
254 seconds (struct timeval t)
256 return t.tv_sec + (double (t.tv_usec) / 1e6);
260 #ifdef DVDOMATIC_POSIX
262 sigchld_handler (int, siginfo_t* info, void *)
264 #ifndef DVDOMATIC_DISABLE_PLAYER
265 PlayerManager::instance()->child_exited (info->si_pid);
270 /** Call the required functions to set up DVD-o-matic's static arrays, etc.
271 * Must be called from the UI thread, if there is one.
276 Format::setup_formats ();
277 DCPContentType::setup_dcp_content_types ();
278 Scaler::setup_scalers ();
279 Filter::setup_filters ();
280 SoundProcessor::setup_sound_processors ();
282 ui_thread = this_thread::get_id ();
284 #ifdef DVDOMATIC_POSIX
286 sa.sa_flags = SA_SIGINFO;
287 sigemptyset (&sa.sa_mask);
288 sa.sa_sigaction = sigchld_handler;
289 sigaction (SIGCHLD, &sa, 0);
294 crop_string (Position start, Size size)
297 s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
302 split_at_spaces_considering_quotes (string s)
305 bool in_quotes = false;
307 for (string::size_type i = 0; i < s.length(); ++i) {
308 if (s[i] == ' ' && !in_quotes) {
311 } else if (s[i] == '"') {
312 in_quotes = !in_quotes;
323 md5_digest (void const * data, int size)
326 MD5_Init (&md5_context);
327 MD5_Update (&md5_context, data, size);
328 unsigned char digest[MD5_DIGEST_LENGTH];
329 MD5_Final (digest, &md5_context);
332 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
333 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
339 /** @param file File name.
340 * @return MD5 digest of file's contents.
343 md5_digest (string file)
345 ifstream f (file.c_str(), ios::binary);
347 throw OpenFileError (file);
350 f.seekg (0, ios::end);
351 int bytes = f.tellg ();
352 f.seekg (0, ios::beg);
354 int const buffer_size = 64 * 1024;
355 char buffer[buffer_size];
358 MD5_Init (&md5_context);
360 int const t = min (bytes, buffer_size);
362 MD5_Update (&md5_context, buffer, t);
366 unsigned char digest[MD5_DIGEST_LENGTH];
367 MD5_Final (digest, &md5_context);
370 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
371 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
378 dcp_frame_rate (float fps)
382 dfr.run_fast = (fps != rint (fps));
383 dfr.frames_per_second = rint (fps);
386 /* XXX: somewhat arbitrary */
388 dfr.frames_per_second = 25;
395 /** @param An arbitrary sampling rate.
396 * @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
399 dcp_audio_sample_rate (int fs)
408 bool operator== (Size const & a, Size const & b)
410 return (a.width == b.width && a.height == b.height);
413 bool operator== (Crop const & a, Crop const & b)
415 return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
418 bool operator!= (Crop const & a, Crop const & b)
423 /** @param index Colour LUT index.
424 * @return Human-readable name.
427 colour_lut_index_to_name (int index)
441 : _deadline (_io_service)
442 , _socket (_io_service)
445 _deadline.expires_at (posix_time::pos_infin);
452 if (_deadline.expires_at() <= asio::deadline_timer::traits_type::now ()) {
454 _deadline.expires_at (posix_time::pos_infin);
457 _deadline.async_wait (boost::bind (&Socket::check, this));
460 /** Blocking connect with timeout.
461 * @param endpoint End-point to connect to.
462 * @param timeout Time-out in seconds.
465 Socket::connect (asio::ip::basic_resolver_entry<asio::ip::tcp> const & endpoint, int timeout)
467 system::error_code ec = asio::error::would_block;
468 _socket.async_connect (endpoint, lambda::var(ec) = lambda::_1);
470 _io_service.run_one();
471 } while (ec == asio::error::would_block);
473 if (ec || !_socket.is_open ()) {
474 throw NetworkError ("connect timed out");
478 /** Blocking write with timeout.
479 * @param data Buffer to write.
480 * @param size Number of bytes to write.
481 * @param timeout Time-out, in seconds.
484 Socket::write (uint8_t const * data, int size, int timeout)
486 _deadline.expires_from_now (posix_time::seconds (timeout));
487 system::error_code ec = asio::error::would_block;
489 asio::async_write (_socket, asio::buffer (data, size), lambda::var(ec) = lambda::_1);
491 _io_service.run_one ();
492 } while (ec == asio::error::would_block);
495 throw NetworkError ("write timed out");
499 /** Blocking read with timeout.
500 * @param data Buffer to read to.
501 * @param size Number of bytes to read.
502 * @param timeout Time-out, in seconds.
505 Socket::read (uint8_t* data, int size, int timeout)
507 _deadline.expires_from_now (posix_time::seconds (timeout));
508 system::error_code ec = asio::error::would_block;
512 _socket.async_read_some (
513 asio::buffer (data, size),
514 (lambda::var(ec) = lambda::_1, lambda::var(amount_read) = lambda::_2)
518 _io_service.run_one ();
519 } while (ec == asio::error::would_block);
528 /** Mark some data as being `consumed', so that it will not be returned
530 * @param size Amount of data to consume, in bytes.
533 Socket::consume (int size)
535 assert (_buffer_data >= size);
537 _buffer_data -= size;
538 if (_buffer_data > 0) {
539 /* Shift still-valid data to the start of the buffer */
540 memmove (_buffer, _buffer + size, _buffer_data);
544 /** Read a definite amount of data from our socket, and mark
546 * @param data Where to put the data.
547 * @param size Number of bytes to read.
550 Socket::read_definite_and_consume (uint8_t* data, int size, int timeout)
552 int const from_buffer = min (_buffer_data, size);
553 if (from_buffer > 0) {
554 /* Get data from our buffer */
555 memcpy (data, _buffer, from_buffer);
556 consume (from_buffer);
557 /* Update our output state */
562 /* read() the rest */
564 int const n = read (data, size, timeout);
566 throw NetworkError ("could not read");
574 /** Read as much data as is available, up to some limit.
575 * @param data Where to put the data.
576 * @param size Maximum amount of data to read.
579 Socket::read_indefinite (uint8_t* data, int size, int timeout)
581 assert (size < int (sizeof (_buffer)));
583 /* Amount of extra data we need to read () */
584 int to_read = size - _buffer_data;
585 while (to_read > 0) {
586 /* read as much of it as we can (into our buffer) */
587 int const n = read (_buffer + _buffer_data, to_read, timeout);
589 throw NetworkError ("could not read");
596 assert (_buffer_data >= size);
598 /* copy data into the output buffer */
599 assert (size >= _buffer_data);
600 memcpy (data, _buffer, size);
604 Rect::intersection (Rect const & other) const
606 int const tx = max (x, other.x);
607 int const ty = max (y, other.y);
611 min (x + width, other.x + other.width) - tx,
612 min (y + height, other.y + other.height) - ty
616 /** Round a number up to the nearest multiple of another number.
617 * @param a Number to round.
618 * @param t Multiple to round to.
619 * @return Rounded number.
623 round_up (int a, int t)
629 /** Read a sequence of key / value pairs from a text stream;
630 * the keys are the first words on the line, and the values are
631 * the remainder of the line following the key. Lines beginning
632 * with # are ignored.
633 * @param s Stream to read.
634 * @return key/value pairs.
636 multimap<string, string>
637 read_key_value (istream &s)
639 multimap<string, string> kv;
642 while (getline (s, line)) {
647 if (line[0] == '#') {
651 if (line[line.size() - 1] == '\r') {
652 line = line.substr (0, line.size() - 1);
655 size_t const s = line.find (' ');
656 if (s == string::npos) {
660 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
667 get_required_string (multimap<string, string> const & kv, string k)
669 if (kv.count (k) > 1) {
670 throw StringError ("unexpected multiple keys in key-value set");
673 multimap<string, string>::const_iterator i = kv.find (k);
675 if (i == kv.end ()) {
676 throw StringError (String::compose ("missing key %1 in key-value set", k));
683 get_required_int (multimap<string, string> const & kv, string k)
685 string const v = get_required_string (kv, k);
686 return lexical_cast<int> (v);
690 get_required_float (multimap<string, string> const & kv, string k)
692 string const v = get_required_string (kv, k);
693 return lexical_cast<float> (v);
697 get_optional_string (multimap<string, string> const & kv, string k)
699 if (kv.count (k) > 1) {
700 throw StringError ("unexpected multiple keys in key-value set");
703 multimap<string, string>::const_iterator i = kv.find (k);
704 if (i == kv.end ()) {
712 get_optional_int (multimap<string, string> const & kv, string k)
714 if (kv.count (k) > 1) {
715 throw StringError ("unexpected multiple keys in key-value set");
718 multimap<string, string>::const_iterator i = kv.find (k);
719 if (i == kv.end ()) {
723 return lexical_cast<int> (i->second);
726 AudioBuffers::AudioBuffers (int channels, int frames)
727 : _channels (channels)
729 , _allocated_frames (frames)
731 _data = new float*[_channels];
732 for (int i = 0; i < _channels; ++i) {
733 _data[i] = new float[frames];
737 AudioBuffers::AudioBuffers (AudioBuffers const & other)
738 : _channels (other._channels)
739 , _frames (other._frames)
740 , _allocated_frames (other._frames)
742 _data = new float*[_channels];
743 for (int i = 0; i < _channels; ++i) {
744 _data[i] = new float[_frames];
745 memcpy (_data[i], other._data[i], _frames * sizeof (float));
749 AudioBuffers::~AudioBuffers ()
751 for (int i = 0; i < _channels; ++i) {
759 AudioBuffers::data (int c) const
761 assert (c >= 0 && c < _channels);
766 AudioBuffers::set_frames (int f)
768 assert (f <= _allocated_frames);
773 AudioBuffers::make_silent ()
775 for (int i = 0; i < _channels; ++i) {
776 for (int j = 0; j < _frames; ++j) {
783 AudioBuffers::copy_from (AudioBuffers* from, int frames_to_copy, int read_offset, int write_offset)
785 assert (from->channels() == channels());
787 for (int i = 0; i < _channels; ++i) {
788 memcpy (_data[i] + write_offset, from->_data[i] + read_offset, frames_to_copy * sizeof(float));
793 AudioBuffers::move (int from, int to, int frames)
800 assert (from < _frames);
802 assert (to < _frames);
804 assert (frames <= _frames);
805 assert ((from + frames) <= _frames);
806 assert ((to + frames) <= _frames);
808 for (int i = 0; i < _channels; ++i) {
809 memmove (_data[i] + to, _data[i] + from, frames * sizeof(float));
816 assert (this_thread::get_id() == ui_thread);
820 video_frames_to_audio_frames (SourceFrame v, float audio_sample_rate, float frames_per_second)
822 return ((int64_t) v * audio_sample_rate / frames_per_second);