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>
43 #include <openssl/md5.h>
44 #include <magick/MagickCore.h>
45 #include <magick/version.h>
46 #include <libdcp/version.h>
48 #include <libavcodec/avcodec.h>
49 #include <libavformat/avformat.h>
50 #include <libswscale/swscale.h>
51 #include <libavfilter/avfiltergraph.h>
52 #include <libpostproc/postprocess.h>
53 #include <libavutil/pixfmt.h>
56 #include "exceptions.h"
59 #include "dcp_content_type.h"
61 #include "sound_processor.h"
67 using std::stringstream;
81 using std::numeric_limits;
83 using boost::shared_ptr;
85 using boost::lexical_cast;
86 using boost::optional;
89 boost::thread::id ui_thread;
91 /** Convert some number of seconds to a string representation
92 * in hours, minutes and seconds.
95 * @return String of the form H:M:S (where H is hours, M
96 * is minutes and S is seconds).
99 seconds_to_hms (int s)
109 hms << std::setfill ('0') << m << N_(":");
111 hms << std::setfill ('0') << s;
119 return seconds_to_hms (t / TIME_HZ);
122 /** @param s Number of seconds.
123 * @return String containing an approximate description of s (e.g. "about 2 hours")
126 seconds_to_approximate_hms (int s)
137 ap << (h + 1) << N_(" ") << _("hours");
140 ap << N_("1 ") << _("hour");
142 ap << h << N_(" ") << _("hours");
147 ap << N_("1 ") << _("minute");
149 ap << m << N_(" ") << _("minutes");
152 ap << s << N_(" ") << _("seconds");
158 #ifdef DCPOMATIC_POSIX
159 /** @param l Mangled C++ identifier.
160 * @return Demangled version.
165 string::size_type const b = l.find_first_of (N_("("));
166 if (b == string::npos) {
170 string::size_type const p = l.find_last_of (N_("+"));
171 if (p == string::npos) {
179 string const fn = l.substr (b + 1, p - b - 1);
184 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
189 } catch (std::exception) {
196 /** Write a stacktrace to an ostream.
197 * @param out Stream to write to.
198 * @param levels Number of levels to go up the call stack.
201 stacktrace (ostream& out, int levels)
208 size = backtrace (array, 200);
209 strings = backtrace_symbols (array, size);
212 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
213 out << N_(" ") << demangle (strings[i]) << "\n";
221 /** @param v Version as used by FFmpeg.
222 * @return A string representation of v.
225 ffmpeg_version_to_string (int v)
228 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
232 /** Return a user-readable string summarising the versions of our dependencies */
234 dependency_version_summary ()
237 s << N_("libopenjpeg ") << opj_version () << N_(", ")
238 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
239 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
240 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
241 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
242 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
243 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
244 << MagickVersion << N_(", ")
245 << N_("libssh ") << ssh_version (0) << N_(", ")
246 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
252 seconds (struct timeval t)
254 return t.tv_sec + (double (t.tv_usec) / 1e6);
257 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
258 * Must be called from the UI thread, if there is one.
263 avfilter_register_all ();
265 Format::setup_formats ();
266 DCPContentType::setup_dcp_content_types ();
267 Scaler::setup_scalers ();
268 Filter::setup_filters ();
269 SoundProcessor::setup_sound_processors ();
271 ui_thread = boost::this_thread::get_id ();
274 #ifdef DCPOMATIC_WINDOWS
275 boost::filesystem::path
279 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
280 boost::filesystem::path p (buffer);
281 p = p.parent_path ();
282 p = p.parent_path ();
289 dcpomatic_setup_gettext_i18n (string lang)
291 #ifdef DCPOMATIC_POSIX
295 if (!lang.empty ()) {
296 /* Override our environment language; this is essential on
300 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
302 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
306 setlocale (LC_ALL, "");
307 textdomain ("libdcpomatic");
309 #ifdef DCPOMATIC_WINDOWS
310 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
311 bind_textdomain_codeset ("libdcpomatic", "UTF8");
314 #ifdef DCPOMATIC_POSIX
315 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
319 /** @param start Start position for the crop within the image.
320 * @param size Size of the cropped area.
321 * @return FFmpeg crop filter string.
324 crop_string (Position start, libdcp::Size size)
327 s << N_("crop=") << size.width << N_(":") << size.height << N_(":") << start.x << N_(":") << start.y;
331 /** @param s A string.
332 * @return Parts of the string split at spaces, except when a space is within quotation marks.
335 split_at_spaces_considering_quotes (string s)
338 bool in_quotes = false;
340 for (string::size_type i = 0; i < s.length(); ++i) {
341 if (s[i] == ' ' && !in_quotes) {
344 } else if (s[i] == '"') {
345 in_quotes = !in_quotes;
356 md5_digest (void const * data, int size)
359 MD5_Init (&md5_context);
360 MD5_Update (&md5_context, data, size);
361 unsigned char digest[MD5_DIGEST_LENGTH];
362 MD5_Final (digest, &md5_context);
365 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
366 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
372 /** @param file File name.
373 * @return MD5 digest of file's contents.
376 md5_digest (boost::filesystem::path file)
378 ifstream f (file.string().c_str(), std::ios::binary);
380 throw OpenFileError (file.string());
383 f.seekg (0, std::ios::end);
384 int bytes = f.tellg ();
385 f.seekg (0, std::ios::beg);
387 int const buffer_size = 64 * 1024;
388 char buffer[buffer_size];
391 MD5_Init (&md5_context);
393 int const t = min (bytes, buffer_size);
395 MD5_Update (&md5_context, buffer, t);
399 unsigned char digest[MD5_DIGEST_LENGTH];
400 MD5_Final (digest, &md5_context);
403 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
404 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
411 about_equal (float a, float b)
413 /* A film of F seconds at f FPS will be Ff frames;
414 Consider some delta FPS d, so if we run the same
415 film at (f + d) FPS it will last F(f + d) seconds.
417 Hence the difference in length over the length of the film will
418 be F(f + d) - Ff frames
419 = Ff + Fd - Ff frames
423 So if we accept a difference of 1 frame, ie 1/f seconds, we can
430 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
431 FPS error is 1/F ~= 0.0001 ~= 10-e4
434 return (fabs (a - b) < 1e-4);
437 /** @param An arbitrary audio frame rate.
438 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
441 dcp_audio_frame_rate (int fs)
450 /** @param index Colour LUT index.
451 * @return Human-readable name.
454 colour_lut_index_to_name (int index)
467 Socket::Socket (int timeout)
468 : _deadline (_io_service)
469 , _socket (_io_service)
472 _deadline.expires_at (boost::posix_time::pos_infin);
479 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
481 _deadline.expires_at (boost::posix_time::pos_infin);
484 _deadline.async_wait (boost::bind (&Socket::check, this));
487 /** Blocking connect.
488 * @param endpoint End-point to connect to.
491 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
493 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
494 boost::system::error_code ec = boost::asio::error::would_block;
495 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
497 _io_service.run_one();
498 } while (ec == boost::asio::error::would_block);
500 if (ec || !_socket.is_open ()) {
501 throw NetworkError (_("connect timed out"));
506 * @param data Buffer to write.
507 * @param size Number of bytes to write.
510 Socket::write (uint8_t const * data, int size)
512 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
513 boost::system::error_code ec = boost::asio::error::would_block;
515 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
518 _io_service.run_one ();
519 } while (ec == boost::asio::error::would_block);
522 throw NetworkError (ec.message ());
527 Socket::write (uint32_t v)
530 write (reinterpret_cast<uint8_t*> (&v), 4);
534 * @param data Buffer to read to.
535 * @param size Number of bytes to read.
538 Socket::read (uint8_t* data, int size)
540 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
541 boost::system::error_code ec = boost::asio::error::would_block;
543 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
546 _io_service.run_one ();
547 } while (ec == boost::asio::error::would_block);
550 throw NetworkError (ec.message ());
555 Socket::read_uint32 ()
558 read (reinterpret_cast<uint8_t *> (&v), 4);
562 /** Round a number up to the nearest multiple of another number.
564 * @param s Array of numbers to round, indexed by c.
565 * @param t Multiple to round to.
566 * @return Rounded number.
569 stride_round_up (int c, int const * stride, int t)
571 int const a = stride[c] + (t - 1);
576 stride_lookup (int c, int const * stride)
581 /** Read a sequence of key / value pairs from a text stream;
582 * the keys are the first words on the line, and the values are
583 * the remainder of the line following the key. Lines beginning
584 * with # are ignored.
585 * @param s Stream to read.
586 * @return key/value pairs.
588 multimap<string, string>
589 read_key_value (istream &s)
591 multimap<string, string> kv;
594 while (getline (s, line)) {
599 if (line[0] == '#') {
603 if (line[line.size() - 1] == '\r') {
604 line = line.substr (0, line.size() - 1);
607 size_t const s = line.find (' ');
608 if (s == string::npos) {
612 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
619 get_required_string (multimap<string, string> const & kv, string k)
621 if (kv.count (k) > 1) {
622 throw StringError (N_("unexpected multiple keys in key-value set"));
625 multimap<string, string>::const_iterator i = kv.find (k);
627 if (i == kv.end ()) {
628 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
635 get_required_int (multimap<string, string> const & kv, string k)
637 string const v = get_required_string (kv, k);
638 return lexical_cast<int> (v);
642 get_required_float (multimap<string, string> const & kv, string k)
644 string const v = get_required_string (kv, k);
645 return lexical_cast<float> (v);
649 get_optional_string (multimap<string, string> const & kv, string k)
651 if (kv.count (k) > 1) {
652 throw StringError (N_("unexpected multiple keys in key-value set"));
655 multimap<string, string>::const_iterator i = kv.find (k);
656 if (i == kv.end ()) {
664 get_optional_int (multimap<string, string> const & kv, string k)
666 if (kv.count (k) > 1) {
667 throw StringError (N_("unexpected multiple keys in key-value set"));
670 multimap<string, string>::const_iterator i = kv.find (k);
671 if (i == kv.end ()) {
675 return lexical_cast<int> (i->second);
678 /** Trip an assert if the caller is not in the UI thread */
682 assert (boost::this_thread::get_id() == ui_thread);
685 /** @param v Content video frame.
686 * @param audio_sample_rate Source audio sample rate.
687 * @param frames_per_second Number of video frames per second.
688 * @return Equivalent number of audio frames for `v'.
691 video_frames_to_audio_frames (ContentVideoFrame v, float audio_sample_rate, float frames_per_second)
693 return ((int64_t) v * audio_sample_rate / frames_per_second);
696 /** @return A pair containing CPU model name and the number of processors */
700 pair<string, int> info;
703 #ifdef DCPOMATIC_POSIX
704 ifstream f (N_("/proc/cpuinfo"));
708 if (boost::algorithm::starts_with (l, N_("model name"))) {
709 string::size_type const c = l.find (':');
710 if (c != string::npos) {
711 info.first = l.substr (c + 2);
713 } else if (boost::algorithm::starts_with (l, N_("processor"))) {
723 audio_channel_name (int c)
725 assert (MAX_AUDIO_CHANNELS == 6);
727 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
728 enhancement channel (sub-woofer)./
730 string const channels[] = {
742 FrameRateConversion::FrameRateConversion (float source, int dcp)
745 , change_speed (false)
747 if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
749 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
753 change_speed = !about_equal (source * factor(), dcp);
755 if (!skip && !repeat && !change_speed) {
756 description = _("DCP and source have the same rate.\n");
759 description = _("DCP will use every other frame of the source.\n");
761 description = _("Each source frame will be doubled in the DCP.\n");
765 float const pc = dcp * 100 / (source * factor());
766 description += String::compose (_("DCP will run at %1%% of the source speed.\n"), pc);
771 LocaleGuard::LocaleGuard ()
774 char const * old = setlocale (LC_NUMERIC, 0);
778 if (strcmp (_old, "POSIX")) {
779 setlocale (LC_NUMERIC, "POSIX");
784 LocaleGuard::~LocaleGuard ()
786 setlocale (LC_NUMERIC, _old);