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
290 static bool tried_throw = false;
293 // try once to re-throw currently active exception
299 catch (const std::exception &e) {
300 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
301 << e.what() << std::endl;
304 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
311 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
312 * Must be called from the UI thread, if there is one.
317 #ifdef DCPOMATIC_WINDOWS
318 boost::filesystem::path p = g_get_user_config_dir ();
319 p /= "backtrace.txt";
320 set_backtrace_file (p);
321 SetUnhandledExceptionFilter(exception_handler);
323 /* Dark voodoo which, I think, gets boost::filesystem::path to
324 correctly convert UTF-8 strings to paths, and also paths
325 back to UTF-8 strings (on path::string()).
327 After this, constructing boost::filesystem::paths from strings
328 converts from UTF-8 to UTF-16 inside the path. Then
329 path::string().c_str() gives UTF-8 and
330 path::c_str() gives UTF-16.
332 This is all Windows-only. AFAICT Linux/OS X use UTF-8 everywhere,
333 so things are much simpler.
335 std::locale::global (boost::locale::generator().generate (""));
336 boost::filesystem::path::imbue (std::locale ());
339 avfilter_register_all ();
342 /* Add our lib directory to the libltdl search path so that
343 xmlsec can find xmlsec1-openssl.
345 boost::filesystem::path lib = app_contents ();
347 setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
350 set_terminate (terminate);
355 Ratio::setup_ratios ();
356 VideoContentScale::setup_scales ();
357 DCPContentType::setup_dcp_content_types ();
358 Scaler::setup_scalers ();
359 Filter::setup_filters ();
360 CinemaSoundProcessor::setup_cinema_sound_processors ();
361 AudioProcessor::setup_audio_processors ();
363 ui_thread = boost::this_thread::get_id ();
366 #ifdef DCPOMATIC_WINDOWS
367 boost::filesystem::path
371 GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
372 boost::filesystem::path p (buffer);
373 p = p.parent_path ();
374 p = p.parent_path ();
381 boost::filesystem::path
384 return "DCP-o-matic 2.app/Contents/Resources";
389 dcpomatic_setup_gettext_i18n (string lang)
391 #ifdef DCPOMATIC_LINUX
395 if (!lang.empty ()) {
396 /* Override our environment language. Note that the caller must not
397 free the string passed into putenv().
399 string s = String::compose ("LANGUAGE=%1", lang);
400 putenv (strdup (s.c_str ()));
401 s = String::compose ("LANG=%1", lang);
402 putenv (strdup (s.c_str ()));
403 s = String::compose ("LC_ALL=%1", lang);
404 putenv (strdup (s.c_str ()));
407 setlocale (LC_ALL, "");
408 textdomain ("libdcpomatic");
410 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
411 bindtextdomain ("libdcpomatic", mo_path().string().c_str());
412 bind_textdomain_codeset ("libdcpomatic", "UTF8");
415 #ifdef DCPOMATIC_LINUX
416 bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
420 /** @param job Optional job for which to report progress */
422 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
424 boost::uintmax_t const buffer_size = 64 * 1024;
425 char buffer[buffer_size];
427 MD5Digester digester;
429 vector<int64_t> sizes;
430 for (size_t i = 0; i < files.size(); ++i) {
431 sizes.push_back (boost::filesystem::file_size (files[i]));
434 for (size_t i = 0; i < files.size(); ++i) {
435 FILE* f = fopen_boost (files[i], "rb");
437 throw OpenFileError (files[i].string());
440 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
441 boost::uintmax_t remaining = bytes;
443 while (remaining > 0) {
444 int const t = min (remaining, buffer_size);
445 int const r = fread (buffer, 1, t, f);
447 throw ReadFileError (files[i], errno);
449 digester.add (buffer, t);
453 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
460 return digester.get ();
463 /** @param An arbitrary audio frame rate.
464 * @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
467 dcp_audio_frame_rate (int fs)
476 Socket::Socket (int timeout)
477 : _deadline (_io_service)
478 , _socket (_io_service)
482 _deadline.expires_at (boost::posix_time::pos_infin);
494 if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
496 _acceptor->cancel ();
500 _deadline.expires_at (boost::posix_time::pos_infin);
503 _deadline.async_wait (boost::bind (&Socket::check, this));
506 /** Blocking connect.
507 * @param endpoint End-point to connect to.
510 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
512 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
513 boost::system::error_code ec = boost::asio::error::would_block;
514 _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
516 _io_service.run_one();
517 } while (ec == boost::asio::error::would_block);
520 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
523 if (!_socket.is_open ()) {
524 throw NetworkError (_("connect timed out"));
529 Socket::accept (int port)
531 _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
533 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
534 boost::system::error_code ec = boost::asio::error::would_block;
535 _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
537 _io_service.run_one ();
538 } while (ec == boost::asio::error::would_block);
544 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
549 * @param data Buffer to write.
550 * @param size Number of bytes to write.
553 Socket::write (uint8_t const * data, int size)
555 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
556 boost::system::error_code ec = boost::asio::error::would_block;
558 boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
561 _io_service.run_one ();
562 } while (ec == boost::asio::error::would_block);
565 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
570 Socket::write (uint32_t v)
573 write (reinterpret_cast<uint8_t*> (&v), 4);
577 * @param data Buffer to read to.
578 * @param size Number of bytes to read.
581 Socket::read (uint8_t* data, int size)
583 _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
584 boost::system::error_code ec = boost::asio::error::would_block;
586 boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
589 _io_service.run_one ();
590 } while (ec == boost::asio::error::would_block);
593 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
598 Socket::read_uint32 ()
601 read (reinterpret_cast<uint8_t *> (&v), 4);
605 /** Round a number up to the nearest multiple of another number.
607 * @param s Array of numbers to round, indexed by c.
608 * @param t Multiple to round to.
609 * @return Rounded number.
612 stride_round_up (int c, int const * stride, int t)
614 int const a = stride[c] + (t - 1);
618 /** @param n A number.
619 * @param r Rounding `boundary' (must be a power of 2)
620 * @return n rounded to the nearest r
623 round_to (float n, int r)
625 DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
626 return int (n + float(r) / 2) &~ (r - 1);
629 /** Trip an assert if the caller is not in the UI thread */
633 DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
637 audio_channel_name (int c)
639 DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
641 /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
642 /// enhancement channel (sub-woofer). HI is the hearing-impaired audio track and
643 /// VI is the visually-impaired audio track (audio describe).
644 string const channels[] = {
651 _("Hearing impaired"),
652 _("Visually impaired"),
655 _("Left rear surround"),
656 _("Right rear surround"),
663 valid_image_file (boost::filesystem::path f)
665 string ext = f.extension().string();
666 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
668 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
669 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
670 ext == ".j2c" || ext == ".j2k"
675 valid_j2k_file (boost::filesystem::path f)
677 string ext = f.extension().string();
678 transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
679 return (ext == ".j2k" || ext == ".j2c");
683 tidy_for_filename (string f)
686 for (size_t i = 0; i < f.length(); ++i) {
687 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
698 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
700 if (ratio < full_frame.ratio ()) {
701 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
704 return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
708 wrapped_av_malloc (size_t s)
710 void* p = av_malloc (s);
717 /** Return a user-readable string summarising the versions of our dependencies */
719 dependency_version_summary ()
722 s << N_("libopenjpeg ") << opj_version () << N_(", ")
723 << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
724 << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
725 << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
726 << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
727 << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
728 << MagickVersion << N_(", ")
729 << N_("libssh ") << ssh_version (0) << N_(", ")
730 << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
736 subtitle_period (AVSubtitle const & sub)
738 ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
740 ContentTimePeriod period (
741 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
742 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)