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 "film_state.h"
61 #include "sound_processor.h"
62 #ifndef DVDOMATIC_DISABLE_PLAYER
63 #include "player_manager.h"
67 using namespace boost;
71 /** Convert some number of seconds to a string representation
72 * in hours, minutes and seconds.
75 * @return String of the form H:M:S (where H is hours, M
76 * is minutes and S is seconds).
79 seconds_to_hms (int s)
89 hms << setfill ('0') << m << ":";
91 hms << setfill ('0') << s;
96 /** @param s Number of seconds.
97 * @return String containing an approximate description of s (e.g. "about 2 hours")
100 seconds_to_approximate_hms (int s)
111 ap << (h + 1) << " hours";
123 ap << m << " minutes";
126 ap << s << " seconds";
132 #ifdef DVDOMATIC_POSIX
133 /** @param l Mangled C++ identifier.
134 * @return Demangled version.
139 string::size_type const b = l.find_first_of ("(");
140 if (b == string::npos) {
144 string::size_type const p = l.find_last_of ("+");
145 if (p == string::npos) {
153 string const fn = l.substr (b + 1, p - b - 1);
158 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
163 } catch (std::exception) {
170 /** Write a stacktrace to an ostream.
171 * @param out Stream to write to.
172 * @param levels Number of levels to go up the call stack.
175 stacktrace (ostream& out, int levels)
182 size = backtrace (array, 200);
183 strings = backtrace_symbols (array, size);
186 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
187 out << " " << demangle (strings[i]) << endl;
195 /** @return Version of vobcopy that is on the path (and hence that we will use) */
199 FILE* f = popen ("vobcopy -V 2>&1", "r");
201 throw EncodeError ("could not run vobcopy to check version");
204 string version = "unknown";
208 if (fgets (buf, sizeof (buf), f)) {
211 split (b, s, is_any_of (" "));
212 if (b.size() >= 2 && b[0] == "Vobcopy") {
223 /** @param v Version as used by FFmpeg.
224 * @return A string representation of v.
227 ffmpeg_version_to_string (int v)
230 s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
234 /** Return a user-readable string summarising the versions of our dependencies */
236 dependency_version_summary ()
239 s << "libopenjpeg " << opj_version () << ", "
240 << "vobcopy " << vobcopy_version() << ", "
241 << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
242 << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
243 << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
244 << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
245 << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
246 << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
247 << MagickVersion << ", "
248 << "libssh " << ssh_version (0) << ", "
249 << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
255 seconds (struct timeval t)
257 return t.tv_sec + (double (t.tv_usec) / 1e6);
261 #ifdef DVDOMATIC_POSIX
263 sigchld_handler (int, siginfo_t* info, void *)
265 #ifndef DVDOMATIC_DISABLE_PLAYER
266 PlayerManager::instance()->child_exited (info->si_pid);
271 /** Call the required functions to set up DVD-o-matic's static arrays, etc.
272 * Must be called from the UI thread, if there is one.
277 Format::setup_formats ();
278 DCPContentType::setup_dcp_content_types ();
279 Scaler::setup_scalers ();
280 Filter::setup_filters ();
281 SoundProcessor::setup_sound_processors ();
283 ui_thread = this_thread::get_id ();
285 #ifdef DVDOMATIC_POSIX
287 sa.sa_flags = SA_SIGINFO;
288 sigemptyset (&sa.sa_mask);
289 sa.sa_sigaction = sigchld_handler;
290 sigaction (SIGCHLD, &sa, 0);
295 crop_string (Position start, Size size)
298 s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
303 split_at_spaces_considering_quotes (string s)
306 bool in_quotes = false;
308 for (string::size_type i = 0; i < s.length(); ++i) {
309 if (s[i] == ' ' && !in_quotes) {
312 } else if (s[i] == '"') {
313 in_quotes = !in_quotes;
324 md5_digest (void const * data, int size)
327 MD5_Init (&md5_context);
328 MD5_Update (&md5_context, data, size);
329 unsigned char digest[MD5_DIGEST_LENGTH];
330 MD5_Final (digest, &md5_context);
333 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
334 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
340 /** @param file File name.
341 * @return MD5 digest of file's contents.
344 md5_digest (string file)
346 ifstream f (file.c_str(), ios::binary);
348 throw OpenFileError (file);
351 f.seekg (0, ios::end);
352 int bytes = f.tellg ();
353 f.seekg (0, ios::beg);
355 int const buffer_size = 64 * 1024;
356 char buffer[buffer_size];
359 MD5_Init (&md5_context);
361 int const t = min (bytes, buffer_size);
363 MD5_Update (&md5_context, buffer, t);
367 unsigned char digest[MD5_DIGEST_LENGTH];
368 MD5_Final (digest, &md5_context);
371 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
372 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
378 /** @param An arbitrary sampling rate.
379 * @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
382 dcp_audio_sample_rate (int fs)
391 bool operator== (Crop const & a, Crop const & b)
393 return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
396 bool operator!= (Crop const & a, Crop const & b)
401 /** @param index Colour LUT index.
402 * @return Human-readable name.
405 colour_lut_index_to_name (int index)
419 : _deadline (_io_service)
420 , _socket (_io_service)
423 _deadline.expires_at (posix_time::pos_infin);
430 if (_deadline.expires_at() <= asio::deadline_timer::traits_type::now ()) {
432 _deadline.expires_at (posix_time::pos_infin);
435 _deadline.async_wait (boost::bind (&Socket::check, this));
438 /** Blocking connect with timeout.
439 * @param endpoint End-point to connect to.
440 * @param timeout Time-out in seconds.
443 Socket::connect (asio::ip::basic_resolver_entry<asio::ip::tcp> const & endpoint, int timeout)
445 system::error_code ec = asio::error::would_block;
446 _socket.async_connect (endpoint, lambda::var(ec) = lambda::_1);
448 _io_service.run_one();
449 } while (ec == asio::error::would_block);
451 if (ec || !_socket.is_open ()) {
452 throw NetworkError ("connect timed out");
456 /** Blocking write with timeout.
457 * @param data Buffer to write.
458 * @param size Number of bytes to write.
459 * @param timeout Time-out, in seconds.
462 Socket::write (uint8_t const * data, int size, int timeout)
464 _deadline.expires_from_now (posix_time::seconds (timeout));
465 system::error_code ec = asio::error::would_block;
467 asio::async_write (_socket, asio::buffer (data, size), lambda::var(ec) = lambda::_1);
469 _io_service.run_one ();
470 } while (ec == asio::error::would_block);
473 throw NetworkError ("write timed out");
477 /** Blocking read with timeout.
478 * @param data Buffer to read to.
479 * @param size Number of bytes to read.
480 * @param timeout Time-out, in seconds.
483 Socket::read (uint8_t* data, int size, int timeout)
485 _deadline.expires_from_now (posix_time::seconds (timeout));
486 system::error_code ec = asio::error::would_block;
490 _socket.async_read_some (
491 asio::buffer (data, size),
492 (lambda::var(ec) = lambda::_1, lambda::var(amount_read) = lambda::_2)
496 _io_service.run_one ();
497 } while (ec == asio::error::would_block);
506 /** Mark some data as being `consumed', so that it will not be returned
508 * @param size Amount of data to consume, in bytes.
511 Socket::consume (int size)
513 assert (_buffer_data >= size);
515 _buffer_data -= size;
516 if (_buffer_data > 0) {
517 /* Shift still-valid data to the start of the buffer */
518 memmove (_buffer, _buffer + size, _buffer_data);
522 /** Read a definite amount of data from our socket, and mark
524 * @param data Where to put the data.
525 * @param size Number of bytes to read.
528 Socket::read_definite_and_consume (uint8_t* data, int size, int timeout)
530 int const from_buffer = min (_buffer_data, size);
531 if (from_buffer > 0) {
532 /* Get data from our buffer */
533 memcpy (data, _buffer, from_buffer);
534 consume (from_buffer);
535 /* Update our output state */
540 /* read() the rest */
542 int const n = read (data, size, timeout);
544 throw NetworkError ("could not read");
552 /** Read as much data as is available, up to some limit.
553 * @param data Where to put the data.
554 * @param size Maximum amount of data to read.
557 Socket::read_indefinite (uint8_t* data, int size, int timeout)
559 assert (size < int (sizeof (_buffer)));
561 /* Amount of extra data we need to read () */
562 int to_read = size - _buffer_data;
563 while (to_read > 0) {
564 /* read as much of it as we can (into our buffer) */
565 int const n = read (_buffer + _buffer_data, to_read, timeout);
567 throw NetworkError ("could not read");
574 assert (_buffer_data >= size);
576 /* copy data into the output buffer */
577 assert (size >= _buffer_data);
578 memcpy (data, _buffer, size);
582 Rect::intersection (Rect const & other) const
584 int const tx = max (x, other.x);
585 int const ty = max (y, other.y);
589 min (x + width, other.x + other.width) - tx,
590 min (y + height, other.y + other.height) - ty
594 /** Round a number up to the nearest multiple of another number.
595 * @param a Number to round.
596 * @param t Multiple to round to.
597 * @return Rounded number.
601 round_up (int a, int t)
607 /** Read a sequence of key / value pairs from a text stream;
608 * the keys are the first words on the line, and the values are
609 * the remainder of the line following the key. Lines beginning
610 * with # are ignored.
611 * @param s Stream to read.
612 * @return key/value pairs.
614 multimap<string, string>
615 read_key_value (istream &s)
617 multimap<string, string> kv;
620 while (getline (s, line)) {
625 if (line[0] == '#') {
629 if (line[line.size() - 1] == '\r') {
630 line = line.substr (0, line.size() - 1);
633 size_t const s = line.find (' ');
634 if (s == string::npos) {
638 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
645 get_required_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);
653 if (i == kv.end ()) {
654 throw StringError (String::compose ("missing key %1 in key-value set", k));
661 get_required_int (multimap<string, string> const & kv, string k)
663 string const v = get_required_string (kv, k);
664 return lexical_cast<int> (v);
668 get_required_float (multimap<string, string> const & kv, string k)
670 string const v = get_required_string (kv, k);
671 return lexical_cast<float> (v);
675 get_optional_string (multimap<string, string> const & kv, string k)
677 if (kv.count (k) > 1) {
678 throw StringError ("unexpected multiple keys in key-value set");
681 multimap<string, string>::const_iterator i = kv.find (k);
682 if (i == kv.end ()) {
690 get_optional_int (multimap<string, string> const & kv, string k)
692 if (kv.count (k) > 1) {
693 throw StringError ("unexpected multiple keys in key-value set");
696 multimap<string, string>::const_iterator i = kv.find (k);
697 if (i == kv.end ()) {
701 return lexical_cast<int> (i->second);
704 AudioBuffers::AudioBuffers (int channels, int frames)
705 : _channels (channels)
708 _data = new float*[_channels];
709 for (int i = 0; i < _channels; ++i) {
710 _data[i] = new float[frames];
714 AudioBuffers::~AudioBuffers ()
716 for (int i = 0; i < _channels; ++i) {
724 AudioBuffers::data (int c) const
726 assert (c >= 0 && c < _channels);
731 AudioBuffers::set_frames (int f)
733 assert (f <= _frames);
740 assert (this_thread::get_id() == ui_thread);