2 Copyright (C) 2012-2014 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/thread.hpp>
40 #include <boost/filesystem.hpp>
41 #ifdef DCPOMATIC_WINDOWS
42 #include <boost/locale.hpp>
46 #include <pangomm/init.h>
47 #include <magick/MagickCore.h>
48 #include <magick/version.h>
49 #include <dcp/version.h>
51 #include <dcp/signer.h>
52 #include <dcp/raw_convert.h>
54 #include <libavcodec/avcodec.h>
55 #include <libavformat/avformat.h>
56 #include <libswscale/swscale.h>
57 #include <libavfilter/avfiltergraph.h>
58 #include <libavutil/pixfmt.h>
61 #include "exceptions.h"
63 #include "dcp_content_type.h"
65 #include "cinema_sound_processor.h"
70 #include "video_content.h"
72 #include "md5_digester.h"
73 #include "audio_processor.h"
74 #include "safe_stringstream.h"
75 #ifdef DCPOMATIC_WINDOWS
95 using std::numeric_limits;
100 using std::set_terminate;
101 using boost::shared_ptr;
103 using boost::optional;
105 using dcp::raw_convert;
107 static boost::thread::id ui_thread;
108 static boost::filesystem::path backtrace_file;
110 /** Convert some number of seconds to a string representation
111 * in hours, minutes and seconds.
114 * @return String of the form H:M:S (where H is hours, M
115 * is minutes and S is seconds).
118 seconds_to_hms (int s)
125 SafeStringStream hms;
128 hms << std::setfill ('0') << m << N_(":");
130 hms << std::setfill ('0') << s;
135 /** @param s Number of seconds.
136 * @return String containing an approximate description of s (e.g. "about 2 hours")
139 seconds_to_approximate_hms (int s)
148 bool const hours = h > 0;
149 bool const minutes = h < 10 && m > 0;
150 bool const seconds = m < 10 && s > 0;
153 if (m > 30 && !minutes) {
154 ap << (h + 1) << N_(" ") << _("hours");
164 if (minutes | seconds) {
171 if (s > 30 && !seconds) {
172 ap << (m + 1) << N_(" ") << _("minutes");
200 #ifdef DCPOMATIC_POSIX
201 /** @param l Mangled C++ identifier.
202 * @return Demangled version.
207 string::size_type const b = l.find_first_of (N_("("));
208 if (b == string::npos) {
212 string::size_type const p = l.find_last_of (N_("+"));
213 if (p == string::npos) {
221 string const fn = l.substr (b + 1, p - b - 1);
226 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
231 } catch (std::exception) {
238 /** Write a stacktrace to an ostream.
239 * @param out Stream to write to.
240 * @param levels Number of levels to go up the call stack.
243 stacktrace (ostream& out, int levels)
246 size_t size = backtrace (array, 200);
247 char** strings = backtrace_symbols (array, size);
250 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
251 out << N_(" ") << demangle (strings[i]) << "\n";
259 /** @param v Version as used by FFmpeg.
260 * @return A string representation of v.
263 ffmpeg_version_to_string (int v)
266 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
271 seconds (struct timeval t)
273 return t.tv_sec + (double (t.tv_usec) / 1e6);
276 #ifdef DCPOMATIC_WINDOWS
277 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
280 FILE* f = fopen_boost (backtrace_file, "w");
281 fprintf (f, "Exception thrown:");
282 for (dbg::stack::const_iterator i = s.begin(); i != s.end(); ++i) {
283 fprintf (f, "%p %s %d %s\n", i->instruction, i->function.c_str(), i->line, i->module.c_str());
286 return EXCEPTION_CONTINUE_SEARCH;
290 /* From http://stackoverflow.com/questions/2443135/how-do-i-find-where-an-exception-was-thrown-in-c */
294 static bool tried_throw = false;
297 // try once to re-throw currently active exception
303 catch (const std::exception &e) {
304 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
305 << e.what() << std::endl;
308 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
312 #ifdef DCPOMATIC_POSIX
313 stacktrace (cout, 50);
318 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
319 * Must be called from the UI thread, if there is one.
324 #ifdef DCPOMATIC_WINDOWS
325 backtrace_file /= g_get_user_config_dir ();
326 backtrace_file /= "backtrace.txt";
327 SetUnhandledExceptionFilter(exception_handler);
329 /* Dark voodoo which, I think, gets boost::filesystem::path to
330 correctly convert UTF-8 strings to paths, and also paths
331 back to UTF-8 strings (on path::string()).
333 After this, constructing boost::filesystem::paths from strings
334 converts from UTF-8 to UTF-16 inside the path. Then
335 path::string().c_str() gives UTF-8 and
336 path::c_str() gives UTF-16.
338 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
339 so things are much simpler.
341 std::locale::global (boost::locale::generator().generate (""));
342 boost::filesystem::path::imbue (std::locale ());
345 avfilter_register_all ();
348 /* Add our lib directory to the libltdl search path so that
349 xmlsec can find xmlsec1-openssl.
351 boost::filesystem::path lib = app_contents ();
353 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
356 set_terminate (terminate);
361 Ratio::setup_ratios ();
362 VideoContentScale::setup_scales ();
363 DCPContentType::setup_dcp_content_types ();
364 Scaler::setup_scalers ();
365 Filter::setup_filters ();
366 CinemaSoundProcessor::setup_cinema_sound_processors ();
367 AudioProcessor::setup_audio_processors ();
369 ui_thread = boost::this_thread::get_id ();
372 #ifdef DCPOMATIC_WINDOWS
373 boost::filesystem::path
377 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
378 boost::filesystem::path p (buffer);
379 p = p.parent_path ();
380 p = p.parent_path ();
387 boost::filesystem::path
390 return "DCP-o-matic.app/Contents/Resources";
395 dcpomatic_setup_gettext_i18n (string lang)
397 #ifdef DCPOMATIC_LINUX
401 if (!lang.empty ()) {
402 /* Override our environment language. Note that the caller must not
403 free the string passed into putenv().
405 string s = String::compose ("LANGUAGE=%1", lang);
406 putenv (strdup (s.c_str ()));
407 s = String::compose ("LANG=%1", lang);
408 putenv (strdup (s.c_str ()));
409 s = String::compose ("LC_ALL=%1", lang);
410 putenv (strdup (s.c_str ()));
413 setlocale (LC_ALL, "");
414 textdomain ("libdcpomatic");
416 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
417 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
418 bind_textdomain_codeset ("libdcpomatic", "UTF8");
421 #ifdef DCPOMATIC_LINUX
422 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
426 /** @param s A string.
427 * @return Parts of the string split at spaces, except when a space is within quotation marks.
430 split_at_spaces_considering_quotes (string s)
433 bool in_quotes = false;
435 for (string::size_type i = 0; i < s.length(); ++i) {
436 if (s[i] == ' ' && !in_quotes) {
439 } else if (s[i] == '"') {
440 in_quotes = !in_quotes;
450 /** @param job Optional job for which to report progress */
452 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
454 boost::uintmax_t const buffer_size = 64 * 1024;
455 char buffer[buffer_size];
457 MD5Digester digester;
459 vector<int64_t> sizes;
460 for (size_t i = 0; i < files.size(); ++i) {
461 sizes.push_back (boost::filesystem::file_size (files[i]));
464 for (size_t i = 0; i < files.size(); ++i) {
465 FILE* f = fopen_boost (files[i], "rb");
467 throw OpenFileError (files[i].string());
470 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
471 boost::uintmax_t remaining = bytes;
473 while (remaining > 0) {
474 int const t = min (remaining, buffer_size);
475 fread (buffer, 1, t, f);
476 digester.add (buffer, t);
480 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
487 return digester.get ();
490 /** @param An arbitrary audio frame rate.
491 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
494 dcp_audio_frame_rate (int fs)
503 Socket::Socket (int timeout)
504 : _deadline (_io_service)
505 , _socket (_io_service)
509 _deadline.expires_at (boost::posix_time::pos_infin);
521 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
523 _acceptor->cancel ();
527 _deadline.expires_at (boost::posix_time::pos_infin);
530 _deadline.async_wait (boost::bind (&Socket::check, this));
533 /** Blocking connect.
534 * @param endpoint End-point to connect to.
537 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
539 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
540 boost::system::error_code ec = boost::asio::error::would_block;
541 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
543 _io_service.run_one();
544 } while (ec == boost::asio::error::would_block);
547 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
550 if (!_socket.is_open ()) {
551 throw NetworkError (_("connect timed out"));
556 Socket::accept (int port)
558 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
560 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
561 boost::system::error_code ec = boost::asio::error::would_block;
562 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
564 _io_service.run_one ();
565 } while (ec == boost::asio::error::would_block );
571 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
576 * @param data Buffer to write.
577 * @param size Number of bytes to write.
580 Socket::write (uint8_t const * data, int size)
582 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
583 boost::system::error_code ec = boost::asio::error::would_block;
585 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
588 _io_service.run_one ();
589 } while (ec == boost::asio::error::would_block);
592 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
597 Socket::write (uint32_t v)
600 write (reinterpret_cast<uint8_t*> (&v), 4);
604 * @param data Buffer to read to.
605 * @param size Number of bytes to read.
608 Socket::read (uint8_t* data, int size)
610 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
611 boost::system::error_code ec = boost::asio::error::would_block;
613 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
616 _io_service.run_one ();
617 } while (ec == boost::asio::error::would_block);
620 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
625 Socket::read_uint32 ()
628 read (reinterpret_cast<uint8_t *> (&v), 4);
632 /** Round a number up to the nearest multiple of another number.
634 * @param s Array of numbers to round, indexed by c.
635 * @param t Multiple to round to.
636 * @return Rounded number.
639 stride_round_up (int c, int const * stride, int t)
641 int const a = stride[c] + (t - 1);
645 /** @param n A number.
646 * @param r Rounding `boundary' (must be a power of 2)
647 * @return n rounded to the nearest r
650 round_to (float n, int r)
652 assert (r == 1 || r == 2 || r == 4);
653 return int (n + float(r) / 2) &~ (r - 1);
656 /** Read a sequence of key / value pairs from a text stream;
657 * the keys are the first words on the line, and the values are
658 * the remainder of the line following the key. Lines beginning
659 * with # are ignored.
660 * @param s Stream to read.
661 * @return key/value pairs.
663 multimap<string, string>
664 read_key_value (istream &s)
666 multimap<string, string> kv;
669 while (getline (s, line)) {
674 if (line[0] == '#') {
678 if (line[line.size() - 1] == '\r') {
679 line = line.substr (0, line.size() - 1);
682 size_t const s = line.find (' ');
683 if (s == string::npos) {
687 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
694 get_required_string (multimap<string, string> const & kv, string k)
696 if (kv.count (k) > 1) {
697 throw StringError (N_("unexpected multiple keys in key-value set"));
700 multimap<string, string>::const_iterator i = kv.find (k);
702 if (i == kv.end ()) {
703 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
710 get_required_int (multimap<string, string> const & kv, string k)
712 string const v = get_required_string (kv, k);
713 return raw_convert<int> (v);
717 get_required_float (multimap<string, string> const & kv, string k)
719 string const v = get_required_string (kv, k);
720 return raw_convert<float> (v);
724 get_optional_string (multimap<string, string> const & kv, string k)
726 if (kv.count (k) > 1) {
727 throw StringError (N_("unexpected multiple keys in key-value set"));
730 multimap<string, string>::const_iterator i = kv.find (k);
731 if (i == kv.end ()) {
739 get_optional_int (multimap<string, string> const & kv, string k)
741 if (kv.count (k) > 1) {
742 throw StringError (N_("unexpected multiple keys in key-value set"));
745 multimap<string, string>::const_iterator i = kv.find (k);
746 if (i == kv.end ()) {
750 return raw_convert<int> (i->second);
753 /** Trip an assert if the caller is not in the UI thread */
757 assert (boost::this_thread::get_id() == ui_thread);
761 audio_channel_name (int c)
763 assert (MAX_DCP_AUDIO_CHANNELS == 12);
765 /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
766 enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
767 VI is the visually-impaired audio track (audio describe).
769 string const channels[] = {
776 _("Hearing impaired"),
777 _("Visually impaired"),
780 _("Left rear surround"),
781 _("Right rear surround"),
788 valid_image_file (boost::filesystem::path f)
790 string ext = f.extension().string();
791 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
792 return (ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx");
796 tidy_for_filename (string f)
799 for (size_t i = 0; i < f.length(); ++i) {
800 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
811 split_get_request (string url)
814 AWAITING_QUESTION_MARK,
817 } state = AWAITING_QUESTION_MARK;
819 map<string, string> r;
822 for (size_t i = 0; i < url.length(); ++i) {
824 case AWAITING_QUESTION_MARK:
839 r.insert (make_pair (k, v));
849 if (state == VALUE) {
850 r.insert (make_pair (k, v));
857 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
859 if (ratio < full_frame.ratio ()) {
860 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
863 return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
867 wrapped_av_malloc (size_t s)
869 void* p = av_malloc (s);
877 entities_to_text (string e)
879 boost::algorithm::replace_all (e, "%3A", ":");
880 boost::algorithm::replace_all (e, "%2F", "/");
885 divide_with_round (int64_t a, int64_t b)
887 if (a % b >= (b / 2)) {
888 return (a + b - 1) / b;
894 /** Return a user-readable string summarising the versions of our dependencies */
896 dependency_version_summary ()
899 s << N_("libopenjpeg ") << opj_version () << N_(", ")
900 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
901 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
902 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
903 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
904 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
905 << MagickVersion << N_(", ")
906 << N_("libssh ") << ssh_version (0) << N_(", ")
907 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
912 /** Construct a ScopedTemporary. A temporary filename is decided but the file is not opened
913 * until ::open() is called.
915 ScopedTemporary::ScopedTemporary ()
918 _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
921 /** Close and delete the temporary file */
922 ScopedTemporary::~ScopedTemporary ()
925 boost::system::error_code ec;
926 boost::filesystem::remove (_file, ec);
929 /** @return temporary filename */
931 ScopedTemporary::c_str () const
933 return _file.string().c_str ();
936 /** Open the temporary file.
937 * @return File's FILE pointer.
940 ScopedTemporary::open (char const * params)
942 _open = fopen (c_str(), params);
946 /** Close the file */
948 ScopedTemporary::close ()
957 subtitle_period (AVSubtitle const & sub)
959 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
961 ContentTimePeriod period (
962 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
963 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)