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.
26 #include "exceptions.h"
28 #include "dcp_content_type.h"
30 #include "cinema_sound_processor.h"
35 #include "video_content.h"
37 #include "md5_digester.h"
38 #include "audio_processor.h"
39 #include "safe_stringstream.h"
40 #include <dcp/version.h>
42 #include <dcp/signer.h>
43 #include <dcp/raw_convert.h>
45 #include <libavcodec/avcodec.h>
46 #include <libavformat/avformat.h>
47 #include <libswscale/swscale.h>
48 #include <libavfilter/avfiltergraph.h>
49 #include <libavutil/pixfmt.h>
53 #include <pangomm/init.h>
54 #ifdef DCPOMATIC_IMAGE_MAGICK
55 #include <magick/MagickCore.h>
57 #include <magick/common.h>
58 #include <magick/magick_config.h>
60 #include <magick/version.h>
61 #include <libssh/libssh.h>
62 #include <boost/algorithm/string.hpp>
63 #include <boost/bind.hpp>
64 #include <boost/lambda/lambda.hpp>
65 #include <boost/thread.hpp>
66 #include <boost/filesystem.hpp>
67 #ifdef DCPOMATIC_WINDOWS
68 #include <boost/locale.hpp>
77 #ifdef DCPOMATIC_POSIX
97 using std::set_terminate;
98 using boost::shared_ptr;
100 using boost::optional;
102 using dcp::raw_convert;
104 /** Path to our executable, required by the stacktrace stuff and filled
105 * in during App::onInit().
108 static boost::thread::id ui_thread;
109 static boost::filesystem::path backtrace_file;
111 /** Convert some number of seconds to a string representation
112 * in hours, minutes and seconds.
115 * @return String of the form H:M:S (where H is hours, M
116 * is minutes and S is seconds).
119 seconds_to_hms (int s)
126 SafeStringStream hms;
129 hms << setfill ('0') << m << N_(":");
131 hms << setfill ('0') << s;
136 /** @param s Number of seconds.
137 * @return String containing an approximate description of s (e.g. "about 2 hours")
140 seconds_to_approximate_hms (int s)
149 bool const hours = h > 0;
150 bool const minutes = h < 10 && m > 0;
151 bool const seconds = m < 10 && s > 0;
154 if (m > 30 && !minutes) {
155 /// TRANSLATORS: h here is an abbreviation for hours
156 ap << (h + 1) << _("h");
158 /// TRANSLATORS: h here is an abbreviation for hours
162 if (minutes | seconds) {
169 if (s > 30 && !seconds) {
170 /// TRANSLATORS: m here is an abbreviation for minutes
171 ap << (m + 1) << _("m");
173 /// TRANSLATORS: m here is an abbreviation for minutes
184 /// TRANSLATORS: s here is an abbreviation for seconds
191 /** @param v Version as used by FFmpeg.
192 * @return A string representation of v.
195 ffmpeg_version_to_string (int v)
198 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
203 seconds (struct timeval t)
205 return t.tv_sec + (double (t.tv_usec) / 1e6);
208 #ifdef DCPOMATIC_WINDOWS
210 /** Resolve symbol name and source location given the path to the executable */
212 addr2line (void const * const addr)
214 char addr2line_cmd[512] = { 0 };
215 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
216 return system(addr2line_cmd);
219 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
220 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
221 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
224 exception_handler(struct _EXCEPTION_POINTERS * info)
226 FILE* f = fopen_boost (backtrace_file, "w");
227 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
230 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
231 CONTEXT* context = info->ContextRecord;
232 SymInitialize (GetCurrentProcess (), 0, true);
234 STACKFRAME frame = { 0 };
236 /* setup initial stack frame */
238 frame.AddrPC.Offset = context->Rip;
239 frame.AddrStack.Offset = context->Rsp;
240 frame.AddrFrame.Offset = context->Rbp;
242 frame.AddrPC.Offset = context->Eip;
243 frame.AddrStack.Offset = context->Esp;
244 frame.AddrFrame.Offset = context->Ebp;
246 frame.AddrPC.Mode = AddrModeFlat;
247 frame.AddrStack.Mode = AddrModeFlat;
248 frame.AddrFrame.Mode = AddrModeFlat;
252 IMAGE_FILE_MACHINE_I386,
253 GetCurrentProcess (),
258 SymFunctionTableAccess,
263 addr2line((void *) frame.AddrPC.Offset);
267 addr2line ((void *) info->ContextRecord->Rip);
269 addr2line ((void *) info->ContextRecord->Eip);
273 return EXCEPTION_CONTINUE_SEARCH;
278 set_backtrace_file (boost::filesystem::path p)
283 /** This is called when there is an unhandled exception. Any
284 * backtrace in this function is useless on Windows as the stack has
285 * already been unwound from the throw; we have the gdb wrap hack to
291 static bool tried_throw = false;
294 // try once to re-throw currently active exception
300 catch (const std::exception &e) {
301 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
302 << e.what() << std::endl;
305 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
312 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
313 * Must be called from the UI thread, if there is one.
318 #ifdef DCPOMATIC_WINDOWS
319 boost::filesystem::path p = g_get_user_config_dir ();
320 p /= "backtrace.txt";
321 set_backtrace_file (p);
322 SetUnhandledExceptionFilter(exception_handler);
324 /* Dark voodoo which, I think, gets boost::filesystem::path to
325 correctly convert UTF-8 strings to paths, and also paths
326 back to UTF-8 strings (on path::string()).
328 After this, constructing boost::filesystem::paths from strings
329 converts from UTF-8 to UTF-16 inside the path. Then
330 path::string().c_str() gives UTF-8 and
331 path::c_str() gives UTF-16.
333 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
334 so things are much simpler.
336 std::locale::global (boost::locale::generator().generate (""));
337 boost::filesystem::path::imbue (std::locale ());
340 avfilter_register_all ();
343 /* Add our lib directory to the libltdl search path so that
344 xmlsec can find xmlsec1-openssl.
346 boost::filesystem::path lib = app_contents ();
348 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
351 set_terminate (terminate);
356 Ratio::setup_ratios ();
357 VideoContentScale::setup_scales ();
358 DCPContentType::setup_dcp_content_types ();
359 Scaler::setup_scalers ();
360 Filter::setup_filters ();
361 CinemaSoundProcessor::setup_cinema_sound_processors ();
362 AudioProcessor::setup_audio_processors ();
364 ui_thread = boost::this_thread::get_id ();
367 #ifdef DCPOMATIC_WINDOWS
368 boost::filesystem::path
372 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
373 boost::filesystem::path p (buffer);
374 p = p.parent_path ();
375 p = p.parent_path ();
382 boost::filesystem::path
385 return "DCP-o-matic 2.app/Contents/Resources";
390 dcpomatic_setup_gettext_i18n (string lang)
392 #ifdef DCPOMATIC_LINUX
396 if (!lang.empty ()) {
397 /* Override our environment language. Note that the caller must not
398 free the string passed into putenv().
400 string s = String::compose ("LANGUAGE=%1", lang);
401 putenv (strdup (s.c_str ()));
402 s = String::compose ("LANG=%1", lang);
403 putenv (strdup (s.c_str ()));
404 s = String::compose ("LC_ALL=%1", lang);
405 putenv (strdup (s.c_str ()));
408 setlocale (LC_ALL, "");
409 textdomain ("libdcpomatic");
411 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
412 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
413 bind_textdomain_codeset ("libdcpomatic", "UTF8");
416 #ifdef DCPOMATIC_LINUX
417 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
421 /** @param s A string.
422 * @return Parts of the string split at spaces, except when a space is within quotation marks.
425 split_at_spaces_considering_quotes (string s)
428 bool in_quotes = false;
430 for (string::size_type i = 0; i < s.length(); ++i) {
431 if (s[i] == ' ' && !in_quotes) {
434 } else if (s[i] == '"') {
435 in_quotes = !in_quotes;
445 /** @param job Optional job for which to report progress */
447 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
449 boost::uintmax_t const buffer_size = 64 * 1024;
450 char buffer[buffer_size];
452 MD5Digester digester;
454 vector<int64_t> sizes;
455 for (size_t i = 0; i < files.size(); ++i) {
456 sizes.push_back (boost::filesystem::file_size (files[i]));
459 for (size_t i = 0; i < files.size(); ++i) {
460 FILE* f = fopen_boost (files[i], "rb");
462 throw OpenFileError (files[i].string());
465 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
466 boost::uintmax_t remaining = bytes;
468 while (remaining > 0) {
469 int const t = min (remaining, buffer_size);
470 int const r = fread (buffer, 1, t, f);
472 throw ReadFileError (files[i], errno);
474 digester.add (buffer, t);
478 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
485 return digester.get ();
488 /** @param An arbitrary audio frame rate.
489 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
492 dcp_audio_frame_rate (int fs)
501 Socket::Socket (int timeout)
502 : _deadline (_io_service)
503 , _socket (_io_service)
507 _deadline.expires_at (boost::posix_time::pos_infin);
519 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
521 _acceptor->cancel ();
525 _deadline.expires_at (boost::posix_time::pos_infin);
528 _deadline.async_wait (boost::bind (&Socket::check, this));
531 /** Blocking connect.
532 * @param endpoint End-point to connect to.
535 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
537 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
538 boost::system::error_code ec = boost::asio::error::would_block;
539 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
541 _io_service.run_one();
542 } while (ec == boost::asio::error::would_block);
545 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
548 if (!_socket.is_open ()) {
549 throw NetworkError (_("connect timed out"));
554 Socket::accept (int port)
556 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
558 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
559 boost::system::error_code ec = boost::asio::error::would_block;
560 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
562 _io_service.run_one ();
563 } while (ec == boost::asio::error::would_block);
569 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
574 * @param data Buffer to write.
575 * @param size Number of bytes to write.
578 Socket::write (uint8_t const * data, int size)
580 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
581 boost::system::error_code ec = boost::asio::error::would_block;
583 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
586 _io_service.run_one ();
587 } while (ec == boost::asio::error::would_block);
590 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
595 Socket::write (uint32_t v)
598 write (reinterpret_cast<uint8_t*> (&v), 4);
602 * @param data Buffer to read to.
603 * @param size Number of bytes to read.
606 Socket::read (uint8_t* data, int size)
608 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
609 boost::system::error_code ec = boost::asio::error::would_block;
611 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
614 _io_service.run_one ();
615 } while (ec == boost::asio::error::would_block);
618 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
623 Socket::read_uint32 ()
626 read (reinterpret_cast<uint8_t *> (&v), 4);
630 /** Round a number up to the nearest multiple of another number.
632 * @param s Array of numbers to round, indexed by c.
633 * @param t Multiple to round to.
634 * @return Rounded number.
637 stride_round_up (int c, int const * stride, int t)
639 int const a = stride[c] + (t - 1);
643 /** @param n A number.
644 * @param r Rounding `boundary' (must be a power of 2)
645 * @return n rounded to the nearest r
648 round_to (float n, int r)
650 DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
651 return int (n + float(r) / 2) &~ (r - 1);
654 /** Read a sequence of key / value pairs from a text stream;
655 * the keys are the first words on the line, and the values are
656 * the remainder of the line following the key. Lines beginning
657 * with # are ignored.
658 * @param s Stream to read.
659 * @return key/value pairs.
661 multimap<string, string>
662 read_key_value (istream &s)
664 multimap<string, string> kv;
667 while (getline (s, line)) {
672 if (line[0] == '#') {
676 if (line[line.size() - 1] == '\r') {
677 line = line.substr (0, line.size() - 1);
680 size_t const s = line.find (' ');
681 if (s == string::npos) {
685 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
692 get_required_string (multimap<string, string> const & kv, string k)
694 if (kv.count (k) > 1) {
695 throw StringError (N_("unexpected multiple keys in key-value set"));
698 multimap<string, string>::const_iterator i = kv.find (k);
700 if (i == kv.end ()) {
701 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
708 get_required_int (multimap<string, string> const & kv, string k)
710 string const v = get_required_string (kv, k);
711 return raw_convert<int> (v);
715 get_required_float (multimap<string, string> const & kv, string k)
717 string const v = get_required_string (kv, k);
718 return raw_convert<float> (v);
722 get_optional_string (multimap<string, string> const & kv, string k)
724 if (kv.count (k) > 1) {
725 throw StringError (N_("unexpected multiple keys in key-value set"));
728 multimap<string, string>::const_iterator i = kv.find (k);
729 if (i == kv.end ()) {
737 get_optional_int (multimap<string, string> const & kv, string k)
739 if (kv.count (k) > 1) {
740 throw StringError (N_("unexpected multiple keys in key-value set"));
743 multimap<string, string>::const_iterator i = kv.find (k);
744 if (i == kv.end ()) {
748 return raw_convert<int> (i->second);
751 /** Trip an assert if the caller is not in the UI thread */
755 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
759 audio_channel_name (int c)
761 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
763 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
764 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
765 /// VI is the visually-impaired audio track (audio describe).
766 string const channels[] = {
773 _("Hearing impaired"),
774 _("Visually impaired"),
777 _("Left rear surround"),
778 _("Right rear surround"),
785 valid_image_file (boost::filesystem::path f)
787 string ext = f.extension().string();
788 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
790 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
791 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
792 ext == ".j2c" || ext == ".j2k"
797 valid_j2k_file (boost::filesystem::path f)
799 string ext = f.extension().string();
800 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
801 return (ext == ".j2k" || ext == ".j2c");
805 tidy_for_filename (string f)
808 for (size_t i = 0; i < f.length(); ++i) {
809 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
820 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
822 if (ratio < full_frame.ratio ()) {
823 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
826 return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
830 wrapped_av_malloc (size_t s)
832 void* p = av_malloc (s);
840 entities_to_text (string e)
842 boost::algorithm::replace_all (e, "%3A", ":");
843 boost::algorithm::replace_all (e, "%2F", "/");
848 divide_with_round (int64_t a, int64_t b)
850 if (a % b >= (b / 2)) {
851 return (a + b - 1) / b;
857 /** Return a user-readable string summarising the versions of our dependencies */
859 dependency_version_summary ()
862 s << N_("libopenjpeg ") << opj_version () << N_(", ")
863 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
864 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
865 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
866 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
867 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
868 << MagickVersion << N_(", ")
869 << N_("libssh ") << ssh_version (0) << N_(", ")
870 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
876 subtitle_period (AVSubtitle const & sub)
878 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
880 ContentTimePeriod period (
881 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
882 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)