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>
39 #include <openssl/md5.h>
40 #include <magick/MagickCore.h>
41 #include <magick/version.h>
42 #include <libdcp/version.h>
44 #include <libavcodec/avcodec.h>
45 #include <libavformat/avformat.h>
46 #include <libswscale/swscale.h>
47 #include <libavfilter/avfiltergraph.h>
48 #include <libpostproc/postprocess.h>
49 #include <libavutil/pixfmt.h>
52 #include "exceptions.h"
55 #include "dcp_content_type.h"
58 #include "film_state.h"
59 #include "sound_processor.h"
60 #ifndef DVDOMATIC_DISABLE_PLAYER
61 #include "player_manager.h"
69 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 /** @param s Sample format.
196 * @return String representation.
199 audio_sample_format_to_string (AVSampleFormat s)
201 /* Our sample format handling is not exactly complete */
204 case AV_SAMPLE_FMT_S16:
213 /** @param s String representation of a sample format, as returned from audio_sample_format_to_string().
214 * @return Sample format.
217 audio_sample_format_from_string (string s)
220 return AV_SAMPLE_FMT_S16;
223 return AV_SAMPLE_FMT_NONE;
226 /** @return Version of vobcopy that is on the path (and hence that we will use) */
230 FILE* f = popen ("vobcopy -V 2>&1", "r");
232 throw EncodeError ("could not run vobcopy to check version");
235 string version = "unknown";
239 if (fgets (buf, sizeof (buf), f)) {
242 split (b, s, is_any_of (" "));
243 if (b.size() >= 2 && b[0] == "Vobcopy") {
254 /** @param v Version as used by FFmpeg.
255 * @return A string representation of v.
258 ffmpeg_version_to_string (int v)
261 s << ((v & 0xff0000) >> 16) << "." << ((v & 0xff00) >> 8) << "." << (v & 0xff);
265 /** Return a user-readable string summarising the versions of our dependencies */
267 dependency_version_summary ()
270 s << "libopenjpeg " << opj_version () << ", "
271 << "vobcopy " << vobcopy_version() << ", "
272 << "libavcodec " << ffmpeg_version_to_string (avcodec_version()) << ", "
273 << "libavfilter " << ffmpeg_version_to_string (avfilter_version()) << ", "
274 << "libavformat " << ffmpeg_version_to_string (avformat_version()) << ", "
275 << "libavutil " << ffmpeg_version_to_string (avutil_version()) << ", "
276 << "libpostproc " << ffmpeg_version_to_string (postproc_version()) << ", "
277 << "libswscale " << ffmpeg_version_to_string (swscale_version()) << ", "
278 << MagickVersion << ", "
279 << "libssh " << ssh_version (0) << ", "
280 << "libdcp " << libdcp::version << " git " << libdcp::git_commit;
286 seconds (struct timeval t)
288 return t.tv_sec + (double (t.tv_usec) / 1e6);
292 #ifdef DVDOMATIC_POSIX
294 sigchld_handler (int, siginfo_t* info, void *)
296 #ifndef DVDOMATIC_DISABLE_PLAYER
297 PlayerManager::instance()->child_exited (info->si_pid);
302 /** Call the required functions to set up DVD-o-matic's static arrays, etc. */
306 Format::setup_formats ();
307 DCPContentType::setup_dcp_content_types ();
308 Scaler::setup_scalers ();
309 Filter::setup_filters ();
310 SoundProcessor::setup_sound_processors ();
312 #ifdef DVDOMATIC_POSIX
314 sa.sa_flags = SA_SIGINFO;
315 sigemptyset (&sa.sa_mask);
316 sa.sa_sigaction = sigchld_handler;
317 sigaction (SIGCHLD, &sa, 0);
322 crop_string (Position start, Size size)
325 s << "crop=" << size.width << ":" << size.height << ":" << start.x << ":" << start.y;
330 split_at_spaces_considering_quotes (string s)
333 bool in_quotes = false;
335 for (string::size_type i = 0; i < s.length(); ++i) {
336 if (s[i] == ' ' && !in_quotes) {
339 } else if (s[i] == '"') {
340 in_quotes = !in_quotes;
352 md5_data (string title, void const * data, int size)
354 MHASH ht = mhash_init (MHASH_MD5);
355 if (ht == MHASH_FAILED) {
356 throw EncodeError ("could not create hash thread");
359 mhash (ht, data, size);
362 mhash_deinit (ht, hash);
364 printf ("%s [%d]: ", title.c_str (), size);
365 for (int i = 0; i < int (mhash_get_block_size (MHASH_MD5)); ++i) {
366 printf ("%.2x", hash[i]);
373 md5_digest (string file)
375 ifstream f (file.c_str(), ios::binary);
377 throw OpenFileError (file);
380 f.seekg (0, ios::end);
381 int bytes = f.tellg ();
382 f.seekg (0, ios::beg);
384 int const buffer_size = 64 * 1024;
385 char buffer[buffer_size];
388 MD5_Init (&md5_context);
390 int const t = min (bytes, buffer_size);
392 MD5_Update (&md5_context, buffer, t);
396 unsigned char digest[MD5_DIGEST_LENGTH];
397 MD5_Final (digest, &md5_context);
400 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
401 s << hex << setfill('0') << setw(2) << ((int) digest[i]);
408 dcp_audio_sample_rate (int fs)
417 bool operator== (Crop const & a, Crop const & b)
419 return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
422 bool operator!= (Crop const & a, Crop const & b)
428 colour_lut_index_to_name (int index)
441 DeadlineWrapper::DeadlineWrapper ()
442 : _deadline (_io_service)
443 , _socket (_io_service)
446 _deadline.expires_at (posix_time::pos_infin);
451 DeadlineWrapper::check ()
453 if (_deadline.expires_at() <= asio::deadline_timer::traits_type::now ()) {
455 _deadline.expires_at (posix_time::pos_infin);
458 _deadline.async_wait (boost::bind (&DeadlineWrapper::check, this));
462 DeadlineWrapper::connect (asio::ip::basic_resolver_entry<asio::ip::tcp> const & endpoint, int timeout)
464 system::error_code ec = asio::error::would_block;
465 _socket.async_connect (endpoint, lambda::var(ec) = lambda::_1);
467 _io_service.run_one();
468 } while (ec == asio::error::would_block);
470 if (ec || !_socket.is_open ()) {
471 throw NetworkError ("connect timed out");
476 DeadlineWrapper::write (uint8_t const * data, int size, int timeout)
478 _deadline.expires_from_now (posix_time::seconds (timeout));
479 system::error_code ec = asio::error::would_block;
481 asio::async_write (_socket, asio::buffer (data, size), lambda::var(ec) = lambda::_1);
483 _io_service.run_one ();
484 } while (ec == asio::error::would_block);
487 throw NetworkError ("write timed out");
492 DeadlineWrapper::read (uint8_t* data, int size, int timeout)
494 _deadline.expires_from_now (posix_time::seconds (timeout));
495 system::error_code ec = asio::error::would_block;
499 _socket.async_read_some (
500 asio::buffer (data, size),
501 (lambda::var(ec) = lambda::_1, lambda::var(amount_read) = lambda::_2)
505 _io_service.run_one ();
506 } while (ec == asio::error::would_block);
515 /** Mark some data as being `consumed', so that it will not be returned
517 * @param size Amount of data to consume, in bytes.
520 DeadlineWrapper::consume (int size)
522 assert (_buffer_data >= size);
524 _buffer_data -= size;
525 if (_buffer_data > 0) {
526 /* Shift still-valid data to the start of the buffer */
527 memmove (_buffer, _buffer + size, _buffer_data);
531 /** Read a definite amount of data from our socket, and mark
533 * @param data Where to put the data.
534 * @param size Number of bytes to read.
537 DeadlineWrapper::read_definite_and_consume (uint8_t* data, int size, int timeout)
539 int const from_buffer = min (_buffer_data, size);
540 if (from_buffer > 0) {
541 /* Get data from our buffer */
542 memcpy (data, _buffer, from_buffer);
543 consume (from_buffer);
544 /* Update our output state */
549 /* read() the rest */
551 int const n = read (data, size, timeout);
553 throw NetworkError ("could not read");
561 /** Read as much data as is available, up to some limit.
562 * @param data Where to put the data.
563 * @param size Maximum amount of data to read.
566 DeadlineWrapper::read_indefinite (uint8_t* data, int size, int timeout)
568 assert (size < int (sizeof (_buffer)));
570 /* Amount of extra data we need to read () */
571 int to_read = size - _buffer_data;
572 while (to_read > 0) {
573 /* read as much of it as we can (into our buffer) */
574 int const n = read (_buffer + _buffer_data, to_read, timeout);
576 throw NetworkError ("could not read");
583 assert (_buffer_data >= size);
585 /* copy data into the output buffer */
586 assert (size >= _buffer_data);
587 memcpy (data, _buffer, size);