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 DCPOMATIC_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>
44 #include <openssl/md5.h>
45 #include <magick/MagickCore.h>
46 #include <magick/version.h>
47 #include <libdcp/version.h>
49 #include <libavcodec/avcodec.h>
50 #include <libavformat/avformat.h>
51 #include <libswscale/swscale.h>
52 #include <libavfilter/avfiltergraph.h>
53 #include <libpostproc/postprocess.h>
54 #include <libavutil/pixfmt.h>
57 #include "exceptions.h"
59 #include "dcp_content_type.h"
61 #include "sound_processor.h"
64 #ifdef DCPOMATIC_WINDOWS
71 using std::stringstream;
85 using std::numeric_limits;
88 using boost::shared_ptr;
90 using boost::lexical_cast;
91 using boost::optional;
94 static boost::thread::id ui_thread;
95 static boost::filesystem::path backtrace_file;
97 /** Convert some number of seconds to a string representation
98 * in hours, minutes and seconds.
101 * @return String of the form H:M:S (where H is hours, M
102 * is minutes and S is seconds).
105 seconds_to_hms (int s)
115 hms << std::setfill ('0') << m << N_(":");
117 hms << std::setfill ('0') << s;
125 return seconds_to_hms (t / TIME_HZ);
128 /** @param s Number of seconds.
129 * @return String containing an approximate description of s (e.g. "about 2 hours")
132 seconds_to_approximate_hms (int s)
143 ap << (h + 1) << N_(" ") << _("hours");
146 ap << N_("1 ") << _("hour");
148 ap << h << N_(" ") << _("hours");
153 ap << N_("1 ") << _("minute");
155 ap << m << N_(" ") << _("minutes");
158 ap << s << N_(" ") << _("seconds");
164 #ifdef DCPOMATIC_POSIX
165 /** @param l Mangled C++ identifier.
166 * @return Demangled version.
171 string::size_type const b = l.find_first_of (N_("("));
172 if (b == string::npos) {
176 string::size_type const p = l.find_last_of (N_("+"));
177 if (p == string::npos) {
185 string const fn = l.substr (b + 1, p - b - 1);
190 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
195 } catch (std::exception) {
202 /** Write a stacktrace to an ostream.
203 * @param out Stream to write to.
204 * @param levels Number of levels to go up the call stack.
207 stacktrace (ostream& out, int levels)
214 size = backtrace (array, 200);
215 strings = backtrace_symbols (array, size);
218 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
219 out << N_(" ") << demangle (strings[i]) << "\n";
227 /** @param v Version as used by FFmpeg.
228 * @return A string representation of v.
231 ffmpeg_version_to_string (int v)
234 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
238 /** Return a user-readable string summarising the versions of our dependencies */
240 dependency_version_summary ()
243 s << N_("libopenjpeg ") << opj_version () << N_(", ")
244 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
245 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
246 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
247 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
248 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
249 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
250 << MagickVersion << N_(", ")
251 << N_("libssh ") << ssh_version (0) << N_(", ")
252 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
258 seconds (struct timeval t)
260 return t.tv_sec + (double (t.tv_usec) / 1e6);
263 #ifdef DCPOMATIC_WINDOWS
264 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
267 ofstream f (backtrace_file.string().c_str());
268 std::copy(s.begin(), s.end(), std::ostream_iterator<dbg::stack_frame>(f, "\n"));
269 return EXCEPTION_CONTINUE_SEARCH;
273 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
274 * Must be called from the UI thread, if there is one.
279 #ifdef DCPOMATIC_WINDOWS
280 backtrace_file /= g_get_user_config_dir ();
281 backtrace_file /= "backtrace.txt";
282 SetUnhandledExceptionFilter(exception_handler);
285 avfilter_register_all ();
287 Ratio::setup_ratios ();
288 DCPContentType::setup_dcp_content_types ();
289 Scaler::setup_scalers ();
290 Filter::setup_filters ();
291 SoundProcessor::setup_sound_processors ();
293 ui_thread = boost::this_thread::get_id ();
296 #ifdef DCPOMATIC_WINDOWS
297 boost::filesystem::path
301 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
302 boost::filesystem::path p (buffer);
303 p = p.parent_path ();
304 p = p.parent_path ();
311 dcpomatic_setup_gettext_i18n (string lang)
313 #ifdef DCPOMATIC_POSIX
317 if (!lang.empty ()) {
318 /* Override our environment language; this is essential on
322 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
324 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
328 setlocale (LC_ALL, "");
329 textdomain ("libdcpomatic");
331 #ifdef DCPOMATIC_WINDOWS
332 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
333 bind_textdomain_codeset ("libdcpomatic", "UTF8");
336 #ifdef DCPOMATIC_POSIX
337 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
341 /** @param s A string.
342 * @return Parts of the string split at spaces, except when a space is within quotation marks.
345 split_at_spaces_considering_quotes (string s)
348 bool in_quotes = false;
350 for (string::size_type i = 0; i < s.length(); ++i) {
351 if (s[i] == ' ' && !in_quotes) {
354 } else if (s[i] == '"') {
355 in_quotes = !in_quotes;
366 md5_digest (void const * data, int size)
369 MD5_Init (&md5_context);
370 MD5_Update (&md5_context, data, size);
371 unsigned char digest[MD5_DIGEST_LENGTH];
372 MD5_Final (digest, &md5_context);
375 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
376 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
382 /** @param file File name.
383 * @return MD5 digest of file's contents.
386 md5_digest (boost::filesystem::path file)
388 ifstream f (file.string().c_str(), std::ios::binary);
390 throw OpenFileError (file.string());
393 f.seekg (0, std::ios::end);
394 int bytes = f.tellg ();
395 f.seekg (0, std::ios::beg);
397 int const buffer_size = 64 * 1024;
398 char buffer[buffer_size];
401 MD5_Init (&md5_context);
403 int const t = min (bytes, buffer_size);
405 MD5_Update (&md5_context, buffer, t);
409 unsigned char digest[MD5_DIGEST_LENGTH];
410 MD5_Final (digest, &md5_context);
413 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
414 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
421 about_equal (float a, float b)
423 /* A film of F seconds at f FPS will be Ff frames;
424 Consider some delta FPS d, so if we run the same
425 film at (f + d) FPS it will last F(f + d) seconds.
427 Hence the difference in length over the length of the film will
428 be F(f + d) - Ff frames
429 = Ff + Fd - Ff frames
433 So if we accept a difference of 1 frame, ie 1/f seconds, we can
440 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
441 FPS error is 1/F ~= 0.0001 ~= 10-e4
444 return (fabs (a - b) < 1e-4);
447 /** @param An arbitrary audio frame rate.
448 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
451 dcp_audio_frame_rate (int fs)
460 /** @param index Colour LUT index.
461 * @return Human-readable name.
464 colour_lut_index_to_name (int index)
477 Socket::Socket (int timeout)
478 : _deadline (_io_service)
479 , _socket (_io_service)
482 _deadline.expires_at (boost::posix_time::pos_infin);
489 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
491 _deadline.expires_at (boost::posix_time::pos_infin);
494 _deadline.async_wait (boost::bind (&Socket::check, this));
497 /** Blocking connect.
498 * @param endpoint End-point to connect to.
501 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
503 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
504 boost::system::error_code ec = boost::asio::error::would_block;
505 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
507 _io_service.run_one();
508 } while (ec == boost::asio::error::would_block);
510 if (ec || !_socket.is_open ()) {
511 throw NetworkError (_("connect timed out"));
516 * @param data Buffer to write.
517 * @param size Number of bytes to write.
520 Socket::write (uint8_t const * data, int size)
522 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
523 boost::system::error_code ec = boost::asio::error::would_block;
525 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
528 _io_service.run_one ();
529 } while (ec == boost::asio::error::would_block);
532 throw NetworkError (ec.message ());
537 Socket::write (uint32_t v)
540 write (reinterpret_cast<uint8_t*> (&v), 4);
544 * @param data Buffer to read to.
545 * @param size Number of bytes to read.
548 Socket::read (uint8_t* data, int size)
550 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
551 boost::system::error_code ec = boost::asio::error::would_block;
553 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
556 _io_service.run_one ();
557 } while (ec == boost::asio::error::would_block);
560 throw NetworkError (ec.message ());
565 Socket::read_uint32 ()
568 read (reinterpret_cast<uint8_t *> (&v), 4);
572 /** Round a number up to the nearest multiple of another number.
574 * @param s Array of numbers to round, indexed by c.
575 * @param t Multiple to round to.
576 * @return Rounded number.
579 stride_round_up (int c, int const * stride, int t)
581 int const a = stride[c] + (t - 1);
586 stride_lookup (int c, int const * stride)
591 /** Read a sequence of key / value pairs from a text stream;
592 * the keys are the first words on the line, and the values are
593 * the remainder of the line following the key. Lines beginning
594 * with # are ignored.
595 * @param s Stream to read.
596 * @return key/value pairs.
598 multimap<string, string>
599 read_key_value (istream &s)
601 multimap<string, string> kv;
604 while (getline (s, line)) {
609 if (line[0] == '#') {
613 if (line[line.size() - 1] == '\r') {
614 line = line.substr (0, line.size() - 1);
617 size_t const s = line.find (' ');
618 if (s == string::npos) {
622 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
629 get_required_string (multimap<string, string> const & kv, string k)
631 if (kv.count (k) > 1) {
632 throw StringError (N_("unexpected multiple keys in key-value set"));
635 multimap<string, string>::const_iterator i = kv.find (k);
637 if (i == kv.end ()) {
638 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
645 get_required_int (multimap<string, string> const & kv, string k)
647 string const v = get_required_string (kv, k);
648 return lexical_cast<int> (v);
652 get_required_float (multimap<string, string> const & kv, string k)
654 string const v = get_required_string (kv, k);
655 return lexical_cast<float> (v);
659 get_optional_string (multimap<string, string> const & kv, string k)
661 if (kv.count (k) > 1) {
662 throw StringError (N_("unexpected multiple keys in key-value set"));
665 multimap<string, string>::const_iterator i = kv.find (k);
666 if (i == kv.end ()) {
674 get_optional_int (multimap<string, string> const & kv, string k)
676 if (kv.count (k) > 1) {
677 throw StringError (N_("unexpected multiple keys in key-value set"));
680 multimap<string, string>::const_iterator i = kv.find (k);
681 if (i == kv.end ()) {
685 return lexical_cast<int> (i->second);
688 /** Trip an assert if the caller is not in the UI thread */
692 assert (boost::this_thread::get_id() == ui_thread);
695 /** @param v Content video frame.
696 * @param audio_sample_rate Source audio sample rate.
697 * @param frames_per_second Number of video frames per second.
698 * @return Equivalent number of audio frames for `v'.
701 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
703 return ((int64_t) v * audio_sample_rate / frames_per_second);
707 audio_channel_name (int c)
709 assert (MAX_AUDIO_CHANNELS == 6);
711 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
712 enhancement channel (sub-woofer)./
714 string const channels[] = {
726 FrameRateConversion::FrameRateConversion (float source, int dcp)
729 , change_speed (false)
731 if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
733 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
737 change_speed = !about_equal (source * factor(), dcp);
739 if (!skip && !repeat && !change_speed) {
740 description = _("DCP and source have the same rate.\n");
743 description = _("DCP will use every other frame of the source.\n");
745 description = _("Each source frame will be doubled in the DCP.\n");
749 float const pc = dcp * 100 / (source * factor());
750 description += String::compose (_("DCP will run at %1%% of the source speed.\n"), pc);
755 LocaleGuard::LocaleGuard ()
758 char const * old = setlocale (LC_NUMERIC, 0);
762 if (strcmp (_old, "C")) {
763 setlocale (LC_NUMERIC, "C");
768 LocaleGuard::~LocaleGuard ()
770 setlocale (LC_NUMERIC, _old);