2 Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 /** @file src/lib/util.cc
21 * @brief Some utility functions and classes.
25 #include "exceptions.h"
27 #include "dcp_content_type.h"
29 #include "cinema_sound_processor.h"
34 #include "video_content.h"
36 #include "md5_digester.h"
37 #include "audio_processor.h"
38 #include "safe_stringstream.h"
39 #include <dcp/version.h>
41 #include <dcp/signer.h>
42 #include <dcp/raw_convert.h>
44 #include <libavcodec/avcodec.h>
45 #include <libavformat/avformat.h>
46 #include <libswscale/swscale.h>
47 #include <libavfilter/avfiltergraph.h>
48 #include <libavutil/pixfmt.h>
52 #include <pangomm/init.h>
53 #ifdef DCPOMATIC_IMAGE_MAGICK
54 #include <magick/MagickCore.h>
56 #include <magick/common.h>
57 #include <magick/magick_config.h>
59 #include <magick/version.h>
60 #include <libssh/libssh.h>
61 #include <boost/algorithm/string.hpp>
62 #include <boost/bind.hpp>
63 #include <boost/lambda/lambda.hpp>
64 #include <boost/thread.hpp>
65 #include <boost/filesystem.hpp>
66 #ifdef DCPOMATIC_WINDOWS
67 #include <boost/locale.hpp>
76 #ifdef DCPOMATIC_POSIX
96 using std::set_terminate;
97 using boost::shared_ptr;
99 using boost::optional;
101 using dcp::raw_convert;
103 /** Path to our executable, required by the stacktrace stuff and filled
104 * in during App::onInit().
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 << setfill ('0') << m << N_(":");
130 hms << 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 /// TRANSLATORS: h here is an abbreviation for hours
155 ap << (h + 1) << _("h");
157 /// TRANSLATORS: h here is an abbreviation for hours
161 if (minutes | seconds) {
168 if (s > 30 && !seconds) {
169 /// TRANSLATORS: m here is an abbreviation for minutes
170 ap << (m + 1) << _("m");
172 /// TRANSLATORS: m here is an abbreviation for minutes
183 /// TRANSLATORS: s here is an abbreviation for seconds
190 /** @param v Version as used by FFmpeg.
191 * @return A string representation of v.
194 ffmpeg_version_to_string (int v)
197 s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
202 seconds (struct timeval t)
204 return t.tv_sec + (double (t.tv_usec) / 1e6);
207 #ifdef DCPOMATIC_WINDOWS
209 /** Resolve symbol name and source location given the path to the executable */
211 addr2line (void const * const addr)
213 char addr2line_cmd[512] = { 0 };
214 sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
215 return system(addr2line_cmd);
218 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
219 * (NOT C++ exceptions!). We write a backtrace to backtrace_file by dark means.
220 * Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
223 exception_handler(struct _EXCEPTION_POINTERS * info)
225 FILE* f = fopen_boost (backtrace_file, "w");
226 fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
229 if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
230 CONTEXT* context = info->ContextRecord;
231 SymInitialize (GetCurrentProcess (), 0, true);
233 STACKFRAME frame = { 0 };
235 /* setup initial stack frame */
237 frame.AddrPC.Offset = context->Rip;
238 frame.AddrStack.Offset = context->Rsp;
239 frame.AddrFrame.Offset = context->Rbp;
241 frame.AddrPC.Offset = context->Eip;
242 frame.AddrStack.Offset = context->Esp;
243 frame.AddrFrame.Offset = context->Ebp;
245 frame.AddrPC.Mode = AddrModeFlat;
246 frame.AddrStack.Mode = AddrModeFlat;
247 frame.AddrFrame.Mode = AddrModeFlat;
251 IMAGE_FILE_MACHINE_I386,
252 GetCurrentProcess (),
257 SymFunctionTableAccess,
262 addr2line((void *) frame.AddrPC.Offset);
266 addr2line ((void *) info->ContextRecord->Rip);
268 addr2line ((void *) info->ContextRecord->Eip);
272 return EXCEPTION_CONTINUE_SEARCH;
277 set_backtrace_file (boost::filesystem::path p)
282 /** This is called when there is an unhandled exception. Any
283 * backtrace in this function is useless on Windows as the stack has
284 * already been unwound from the throw; we have the gdb wrap hack to
291 static bool tried_throw = false;
292 // try once to re-throw currently active exception
298 catch (const std::exception &e) {
299 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
300 << e.what() << std::endl;
303 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
310 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
311 * Must be called from the UI thread, if there is one.
316 #ifdef DCPOMATIC_WINDOWS
317 boost::filesystem::path p = g_get_user_config_dir ();
318 p /= "backtrace.txt";
319 set_backtrace_file (p);
320 SetUnhandledExceptionFilter(exception_handler);
322 /* Dark voodoo which, I think, gets boost::filesystem::path to
323 correctly convert UTF-8 strings to paths, and also paths
324 back to UTF-8 strings (on path::string()).
326 After this, constructing boost::filesystem::paths from strings
327 converts from UTF-8 to UTF-16 inside the path. Then
328 path::string().c_str() gives UTF-8 and
329 path::c_str() gives UTF-16.
331 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
332 so things are much simpler.
334 std::locale::global (boost::locale::generator().generate (""));
335 boost::filesystem::path::imbue (std::locale ());
338 avfilter_register_all ();
341 /* Add our lib directory to the libltdl search path so that
342 xmlsec can find xmlsec1-openssl.
344 boost::filesystem::path lib = app_contents ();
346 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
349 set_terminate (terminate);
354 Ratio::setup_ratios ();
355 VideoContentScale::setup_scales ();
356 DCPContentType::setup_dcp_content_types ();
357 Scaler::setup_scalers ();
358 Filter::setup_filters ();
359 CinemaSoundProcessor::setup_cinema_sound_processors ();
360 AudioProcessor::setup_audio_processors ();
362 ui_thread = boost::this_thread::get_id ();
365 #ifdef DCPOMATIC_WINDOWS
366 boost::filesystem::path
370 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
371 boost::filesystem::path p (buffer);
372 p = p.parent_path ();
373 p = p.parent_path ();
380 boost::filesystem::path
383 return "DCP-o-matic 2.app/Contents/Resources";
388 dcpomatic_setup_gettext_i18n (string lang)
390 #ifdef DCPOMATIC_LINUX
394 if (!lang.empty ()) {
395 /* Override our environment language. Note that the caller must not
396 free the string passed into putenv().
398 string s = String::compose ("LANGUAGE=%1", lang);
399 putenv (strdup (s.c_str ()));
400 s = String::compose ("LANG=%1", lang);
401 putenv (strdup (s.c_str ()));
402 s = String::compose ("LC_ALL=%1", lang);
403 putenv (strdup (s.c_str ()));
406 setlocale (LC_ALL, "");
407 textdomain ("libdcpomatic");
409 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
410 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
411 bind_textdomain_codeset ("libdcpomatic", "UTF8");
414 #ifdef DCPOMATIC_LINUX
415 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
419 /** Compute a digest of the first and last `size' bytes of a set of files. */
421 md5_digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
423 boost::scoped_array<char> buffer (new char[size]);
424 MD5Digester digester;
427 boost::uintmax_t to_do = size;
428 char* p = buffer.get ();
430 while (i < int64_t (files.size()) && to_do > 0) {
431 FILE* f = fopen_boost (files[i], "rb");
433 throw OpenFileError (files[i].string());
436 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
437 fread (p, 1, this_time, f);
444 digester.add (buffer.get(), size - to_do);
449 i = files.size() - 1;
450 while (i >= 0 && to_do > 0) {
451 FILE* f = fopen_boost (files[i], "rb");
453 throw OpenFileError (files[i].string());
456 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
457 fseek (f, -this_time, SEEK_END);
458 fread (p, 1, this_time, f);
465 digester.add (buffer.get(), size - to_do);
467 return digester.get ();
470 /** @param An arbitrary audio frame rate.
471 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
474 dcp_audio_frame_rate (int fs)
483 Socket::Socket (int timeout)
484 : _deadline (_io_service)
485 , _socket (_io_service)
489 _deadline.expires_at (boost::posix_time::pos_infin);
501 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
503 _acceptor->cancel ();
507 _deadline.expires_at (boost::posix_time::pos_infin);
510 _deadline.async_wait (boost::bind (&Socket::check, this));
513 /** Blocking connect.
514 * @param endpoint End-point to connect to.
517 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
519 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
520 boost::system::error_code ec = boost::asio::error::would_block;
521 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
523 _io_service.run_one();
524 } while (ec == boost::asio::error::would_block);
527 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
530 if (!_socket.is_open ()) {
531 throw NetworkError (_("connect timed out"));
536 Socket::accept (int port)
538 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
540 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
541 boost::system::error_code ec = boost::asio::error::would_block;
542 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
544 _io_service.run_one ();
545 } while (ec == boost::asio::error::would_block);
551 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
556 * @param data Buffer to write.
557 * @param size Number of bytes to write.
560 Socket::write (uint8_t const * data, int size)
562 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
563 boost::system::error_code ec = boost::asio::error::would_block;
565 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
568 _io_service.run_one ();
569 } while (ec == boost::asio::error::would_block);
572 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
577 Socket::write (uint32_t v)
580 write (reinterpret_cast<uint8_t*> (&v), 4);
584 * @param data Buffer to read to.
585 * @param size Number of bytes to read.
588 Socket::read (uint8_t* data, int size)
590 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
591 boost::system::error_code ec = boost::asio::error::would_block;
593 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
596 _io_service.run_one ();
597 } while (ec == boost::asio::error::would_block);
600 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
605 Socket::read_uint32 ()
608 read (reinterpret_cast<uint8_t *> (&v), 4);
612 /** Round a number up to the nearest multiple of another number.
614 * @param s Array of numbers to round, indexed by c.
615 * @param t Multiple to round to.
616 * @return Rounded number.
619 stride_round_up (int c, int const * stride, int t)
621 int const a = stride[c] + (t - 1);
625 /** @param n A number.
626 * @param r Rounding `boundary' (must be a power of 2)
627 * @return n rounded to the nearest r
630 round_to (float n, int r)
632 DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
633 return int (n + float(r) / 2) &~ (r - 1);
636 /** Trip an assert if the caller is not in the UI thread */
640 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
644 audio_channel_name (int c)
646 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
648 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
649 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
650 /// VI is the visually-impaired audio track (audio describe).
651 string const channels[] = {
658 _("Hearing impaired"),
659 _("Visually impaired"),
662 _("Left rear surround"),
663 _("Right rear surround"),
670 valid_image_file (boost::filesystem::path f)
672 string ext = f.extension().string();
673 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
675 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
676 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
677 ext == ".j2c" || ext == ".j2k"
682 valid_j2k_file (boost::filesystem::path f)
684 string ext = f.extension().string();
685 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
686 return (ext == ".j2k" || ext == ".j2c");
690 tidy_for_filename (string f)
693 for (size_t i = 0; i < f.length(); ++i) {
694 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
705 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
707 if (ratio < full_frame.ratio ()) {
708 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
711 return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
715 wrapped_av_malloc (size_t s)
717 void* p = av_malloc (s);
724 /** Return a user-readable string summarising the versions of our dependencies */
726 dependency_version_summary ()
729 s << N_("libopenjpeg ") << opj_version () << N_(", ")
730 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
731 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
732 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
733 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
734 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
735 << MagickVersion << N_(", ")
736 << N_("libssh ") << ssh_version (0) << N_(", ")
737 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
743 subtitle_period (AVSubtitle const & sub)
745 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
747 ContentTimePeriod period (
748 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
749 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)