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>
48 #include <libdcp/util.h>
50 #include <libavcodec/avcodec.h>
51 #include <libavformat/avformat.h>
52 #include <libswscale/swscale.h>
53 #include <libavfilter/avfiltergraph.h>
54 #include <libpostproc/postprocess.h>
55 #include <libavutil/pixfmt.h>
58 #include "exceptions.h"
60 #include "dcp_content_type.h"
62 #include "sound_processor.h"
66 #ifdef DCPOMATIC_WINDOWS
73 using std::stringstream;
87 using std::numeric_limits;
90 using boost::shared_ptr;
92 using boost::lexical_cast;
93 using boost::optional;
96 static boost::thread::id ui_thread;
97 static boost::filesystem::path backtrace_file;
99 /** Convert some number of seconds to a string representation
100 * in hours, minutes and seconds.
103 * @return String of the form H:M:S (where H is hours, M
104 * is minutes and S is seconds).
107 seconds_to_hms (int s)
117 hms << std::setfill ('0') << m << N_(":");
119 hms << std::setfill ('0') << s;
124 /** @param s Number of seconds.
125 * @return String containing an approximate description of s (e.g. "about 2 hours")
128 seconds_to_approximate_hms (int s)
139 ap << (h + 1) << N_(" ") << _("hours");
142 ap << N_("1 ") << _("hour");
144 ap << h << N_(" ") << _("hours");
149 ap << N_("1 ") << _("minute");
151 ap << m << N_(" ") << _("minutes");
154 ap << s << N_(" ") << _("seconds");
160 #ifdef DCPOMATIC_POSIX
161 /** @param l Mangled C++ identifier.
162 * @return Demangled version.
167 string::size_type const b = l.find_first_of (N_("("));
168 if (b == string::npos) {
172 string::size_type const p = l.find_last_of (N_("+"));
173 if (p == string::npos) {
181 string const fn = l.substr (b + 1, p - b - 1);
186 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
191 } catch (std::exception) {
198 /** Write a stacktrace to an ostream.
199 * @param out Stream to write to.
200 * @param levels Number of levels to go up the call stack.
203 stacktrace (ostream& out, int levels)
206 size_t size = backtrace (array, 200);
207 char** strings = backtrace_symbols (array, size);
210 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
211 out << N_(" ") << demangle (strings[i]) << "\n";
219 /** @param v Version as used by FFmpeg.
220 * @return A string representation of v.
223 ffmpeg_version_to_string (int v)
226 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
230 /** Return a user-readable string summarising the versions of our dependencies */
232 dependency_version_summary ()
235 s << N_("libopenjpeg ") << opj_version () << N_(", ")
236 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
237 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
238 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
239 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
240 << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
241 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
242 << MagickVersion << N_(", ")
243 << N_("libssh ") << ssh_version (0) << N_(", ")
244 << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
250 seconds (struct timeval t)
252 return t.tv_sec + (double (t.tv_usec) / 1e6);
255 #ifdef DCPOMATIC_WINDOWS
256 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
259 ofstream f (backtrace_file.string().c_str());
260 std::copy(s.begin(), s.end(), std::ostream_iterator<dbg::stack_frame>(f, "\n"));
261 return EXCEPTION_CONTINUE_SEARCH;
265 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
266 * Must be called from the UI thread, if there is one.
271 #ifdef DCPOMATIC_WINDOWS
272 backtrace_file /= g_get_user_config_dir ();
273 backtrace_file /= "backtrace.txt";
274 SetUnhandledExceptionFilter(exception_handler);
277 avfilter_register_all ();
279 Ratio::setup_ratios ();
280 DCPContentType::setup_dcp_content_types ();
281 Scaler::setup_scalers ();
282 Filter::setup_filters ();
283 SoundProcessor::setup_sound_processors ();
285 ui_thread = boost::this_thread::get_id ();
288 #ifdef DCPOMATIC_WINDOWS
289 boost::filesystem::path
293 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
294 boost::filesystem::path p (buffer);
295 p = p.parent_path ();
296 p = p.parent_path ();
303 dcpomatic_setup_gettext_i18n (string lang)
305 #ifdef DCPOMATIC_POSIX
309 if (!lang.empty ()) {
310 /* Override our environment language; this is essential on
314 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
316 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
320 setlocale (LC_ALL, "");
321 textdomain ("libdcpomatic");
323 #ifdef DCPOMATIC_WINDOWS
324 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
325 bind_textdomain_codeset ("libdcpomatic", "UTF8");
328 #ifdef DCPOMATIC_POSIX
329 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
333 /** @param s A string.
334 * @return Parts of the string split at spaces, except when a space is within quotation marks.
337 split_at_spaces_considering_quotes (string s)
340 bool in_quotes = false;
342 for (string::size_type i = 0; i < s.length(); ++i) {
343 if (s[i] == ' ' && !in_quotes) {
346 } else if (s[i] == '"') {
347 in_quotes = !in_quotes;
358 md5_digest (void const * data, int size)
361 MD5_Init (&md5_context);
362 MD5_Update (&md5_context, data, size);
363 unsigned char digest[MD5_DIGEST_LENGTH];
364 MD5_Final (digest, &md5_context);
367 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
368 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
374 /** @param file File name.
375 * @return MD5 digest of file's contents.
378 md5_digest (boost::filesystem::path file)
380 ifstream f (file.string().c_str(), std::ios::binary);
382 throw OpenFileError (file.string());
385 f.seekg (0, std::ios::end);
386 int bytes = f.tellg ();
387 f.seekg (0, std::ios::beg);
389 int const buffer_size = 64 * 1024;
390 char buffer[buffer_size];
393 MD5_Init (&md5_context);
395 int const t = min (bytes, buffer_size);
397 MD5_Update (&md5_context, buffer, t);
401 unsigned char digest[MD5_DIGEST_LENGTH];
402 MD5_Final (digest, &md5_context);
405 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
406 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
412 /** @param job Optional job for which to report progress */
414 md5_digest_directory (boost::filesystem::path directory, shared_ptr<Job> job)
416 int const buffer_size = 64 * 1024;
417 char buffer[buffer_size];
420 MD5_Init (&md5_context);
424 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
430 for (boost::filesystem::directory_iterator i(directory); i != boost::filesystem::directory_iterator(); ++i) {
431 ifstream f (i->path().string().c_str(), std::ios::binary);
433 throw OpenFileError (i->path().string());
436 f.seekg (0, std::ios::end);
437 int bytes = f.tellg ();
438 f.seekg (0, std::ios::beg);
441 int const t = min (bytes, buffer_size);
443 MD5_Update (&md5_context, buffer, t);
448 job->set_progress (float (j) / files);
453 unsigned char digest[MD5_DIGEST_LENGTH];
454 MD5_Final (digest, &md5_context);
457 for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
458 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
465 about_equal (float a, float b)
467 /* A film of F seconds at f FPS will be Ff frames;
468 Consider some delta FPS d, so if we run the same
469 film at (f + d) FPS it will last F(f + d) seconds.
471 Hence the difference in length over the length of the film will
472 be F(f + d) - Ff frames
473 = Ff + Fd - Ff frames
477 So if we accept a difference of 1 frame, ie 1/f seconds, we can
484 So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
485 FPS error is 1/F ~= 0.0001 ~= 10-e4
488 return (fabs (a - b) < 1e-4);
491 /** @param An arbitrary audio frame rate.
492 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
495 dcp_audio_frame_rate (int fs)
504 Socket::Socket (int timeout)
505 : _deadline (_io_service)
506 , _socket (_io_service)
509 _deadline.expires_at (boost::posix_time::pos_infin);
516 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
518 _deadline.expires_at (boost::posix_time::pos_infin);
521 _deadline.async_wait (boost::bind (&Socket::check, this));
524 /** Blocking connect.
525 * @param endpoint End-point to connect to.
528 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
530 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
531 boost::system::error_code ec = boost::asio::error::would_block;
532 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
534 _io_service.run_one();
535 } while (ec == boost::asio::error::would_block);
537 if (ec || !_socket.is_open ()) {
538 throw NetworkError (_("connect timed out"));
543 * @param data Buffer to write.
544 * @param size Number of bytes to write.
547 Socket::write (uint8_t const * data, int size)
549 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
550 boost::system::error_code ec = boost::asio::error::would_block;
552 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
555 _io_service.run_one ();
556 } while (ec == boost::asio::error::would_block);
559 throw NetworkError (ec.message ());
564 Socket::write (uint32_t v)
567 write (reinterpret_cast<uint8_t*> (&v), 4);
571 * @param data Buffer to read to.
572 * @param size Number of bytes to read.
575 Socket::read (uint8_t* data, int size)
577 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
578 boost::system::error_code ec = boost::asio::error::would_block;
580 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
583 _io_service.run_one ();
584 } while (ec == boost::asio::error::would_block);
587 throw NetworkError (ec.message ());
592 Socket::read_uint32 ()
595 read (reinterpret_cast<uint8_t *> (&v), 4);
599 /** Round a number up to the nearest multiple of another number.
601 * @param s Array of numbers to round, indexed by c.
602 * @param t Multiple to round to.
603 * @return Rounded number.
606 stride_round_up (int c, int const * stride, int t)
608 int const a = stride[c] + (t - 1);
612 /** Read a sequence of key / value pairs from a text stream;
613 * the keys are the first words on the line, and the values are
614 * the remainder of the line following the key. Lines beginning
615 * with # are ignored.
616 * @param s Stream to read.
617 * @return key/value pairs.
619 multimap<string, string>
620 read_key_value (istream &s)
622 multimap<string, string> kv;
625 while (getline (s, line)) {
630 if (line[0] == '#') {
634 if (line[line.size() - 1] == '\r') {
635 line = line.substr (0, line.size() - 1);
638 size_t const s = line.find (' ');
639 if (s == string::npos) {
643 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
650 get_required_string (multimap<string, string> const & kv, string k)
652 if (kv.count (k) > 1) {
653 throw StringError (N_("unexpected multiple keys in key-value set"));
656 multimap<string, string>::const_iterator i = kv.find (k);
658 if (i == kv.end ()) {
659 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
666 get_required_int (multimap<string, string> const & kv, string k)
668 string const v = get_required_string (kv, k);
669 return lexical_cast<int> (v);
673 get_required_float (multimap<string, string> const & kv, string k)
675 string const v = get_required_string (kv, k);
676 return lexical_cast<float> (v);
680 get_optional_string (multimap<string, string> const & kv, string k)
682 if (kv.count (k) > 1) {
683 throw StringError (N_("unexpected multiple keys in key-value set"));
686 multimap<string, string>::const_iterator i = kv.find (k);
687 if (i == kv.end ()) {
695 get_optional_int (multimap<string, string> const & kv, string k)
697 if (kv.count (k) > 1) {
698 throw StringError (N_("unexpected multiple keys in key-value set"));
701 multimap<string, string>::const_iterator i = kv.find (k);
702 if (i == kv.end ()) {
706 return lexical_cast<int> (i->second);
709 /** Trip an assert if the caller is not in the UI thread */
713 assert (boost::this_thread::get_id() == ui_thread);
716 /** @param v Content video frame.
717 * @param audio_sample_rate Source audio sample rate.
718 * @param frames_per_second Number of video frames per second.
719 * @return Equivalent number of audio frames for `v'.
722 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
724 return ((int64_t) v * audio_sample_rate / frames_per_second);
728 audio_channel_name (int c)
730 assert (MAX_AUDIO_CHANNELS == 6);
732 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
733 enhancement channel (sub-woofer)./
735 string const channels[] = {
747 FrameRateConversion::FrameRateConversion (float source, int dcp)
750 , change_speed (false)
752 if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
754 } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
758 change_speed = !about_equal (source * factor(), dcp);
760 if (!skip && !repeat && !change_speed) {
761 description = _("Content and DCP have the same rate.\n");
764 description = _("DCP will use every other frame of the content.\n");
766 description = _("Each content frame will be doubled in the DCP.\n");
770 float const pc = dcp * 100 / (source * factor());
771 description += String::compose (_("DCP will run at %1%% of the content speed.\n"), pc);
776 LocaleGuard::LocaleGuard ()
779 char const * old = setlocale (LC_NUMERIC, 0);
783 if (strcmp (_old, "C")) {
784 setlocale (LC_NUMERIC, "C");
789 LocaleGuard::~LocaleGuard ()
791 setlocale (LC_NUMERIC, _old);
796 valid_image_file (boost::filesystem::path f)
798 string ext = f.extension().string();
799 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
800 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga");
804 tidy_for_filename (string f)
807 for (size_t i = 0; i < f.length(); ++i) {
808 if (isalpha (f[i]) || f[i] == '_' || f[i] == '-') {