Hand-apply d849d411cff28ef5453085791d0b4d7cd73bd070 from master; replace all assert...
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3     Copyright (C) 2000-2007 Paul Davis
4
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.
9
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.
14
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.
18
19 */
20
21 /** @file src/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include "util.h"
26 #include "exceptions.h"
27 #include "scaler.h"
28 #include "dcp_content_type.h"
29 #include "filter.h"
30 #include "cinema_sound_processor.h"
31 #include "config.h"
32 #include "ratio.h"
33 #include "job.h"
34 #include "cross.h"
35 #include "video_content.h"
36 #include "rect.h"
37 #include "md5_digester.h"
38 #include "audio_processor.h"
39 #include "safe_stringstream.h"
40 #include <dcp/version.h>
41 #include <dcp/util.h>
42 #include <dcp/signer.h>
43 #include <dcp/raw_convert.h>
44 extern "C" {
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>
50 }
51 #include <glib.h>
52 #include <openjpeg.h>
53 #include <pangomm/init.h>
54 #ifdef DCPOMATIC_IMAGE_MAGICK
55 #include <magick/MagickCore.h>
56 #else
57 #include <magick/common.h>
58 #include <magick/magick_config.h>
59 #endif
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>
69 #include <dbghelp.h>
70 #endif
71 #include <signal.h>
72 #include <iomanip>
73 #include <iostream>
74 #include <fstream>
75 #include <climits>
76 #include <stdexcept>
77 #ifdef DCPOMATIC_POSIX
78 #include <execinfo.h>
79 #include <cxxabi.h>
80 #endif
81
82 #include "i18n.h"
83
84 using std::string;
85 using std::setfill;
86 using std::ostream;
87 using std::endl;
88 using std::vector;
89 using std::min;
90 using std::max;
91 using std::list;
92 using std::multimap;
93 using std::istream;
94 using std::pair;
95 using std::cout;
96 using std::bad_alloc;
97 using std::set_terminate;
98 using boost::shared_ptr;
99 using boost::thread;
100 using boost::optional;
101 using dcp::Size;
102 using dcp::raw_convert;
103
104 /** Path to our executable, required by the stacktrace stuff and filled
105  *  in during App::onInit().
106  */
107 string program_name;
108 static boost::thread::id ui_thread;
109 static boost::filesystem::path backtrace_file;
110
111 /** Convert some number of seconds to a string representation
112  *  in hours, minutes and seconds.
113  *
114  *  @param s Seconds.
115  *  @return String of the form H:M:S (where H is hours, M
116  *  is minutes and S is seconds).
117  */
118 string
119 seconds_to_hms (int s)
120 {
121         int m = s / 60;
122         s -= (m * 60);
123         int h = m / 60;
124         m -= (h * 60);
125
126         SafeStringStream hms;
127         hms << h << N_(":");
128         hms.width (2);
129         hms << setfill ('0') << m << N_(":");
130         hms.width (2);
131         hms << setfill ('0') << s;
132
133         return hms.str ();
134 }
135
136 /** @param s Number of seconds.
137  *  @return String containing an approximate description of s (e.g. "about 2 hours")
138  */
139 string
140 seconds_to_approximate_hms (int s)
141 {
142         int m = s / 60;
143         s -= (m * 60);
144         int h = m / 60;
145         m -= (h * 60);
146
147         SafeStringStream ap;
148
149         bool const hours = h > 0;
150         bool const minutes = h < 10 && m > 0;
151         bool const seconds = m < 10 && s > 0;
152
153         if (hours) {
154                 if (m > 30 && !minutes) {
155                         /// TRANSLATORS: h here is an abbreviation for hours
156                         ap << (h + 1) << _("h");
157                 } else {
158                         /// TRANSLATORS: h here is an abbreviation for hours
159                         ap << h << _("h");
160                 }
161
162                 if (minutes | seconds) {
163                         ap << N_(" ");
164                 }
165         }
166
167         if (minutes) {
168                 /* Minutes */
169                 if (s > 30 && !seconds) {
170                         /// TRANSLATORS: m here is an abbreviation for minutes
171                         ap << (m + 1) << _("m");
172                 } else {
173                         /// TRANSLATORS: m here is an abbreviation for minutes
174                         ap << m << _("m");
175                 }
176
177                 if (seconds) {
178                         ap << N_(" ");
179                 }
180         }
181
182         if (seconds) {
183                 /* Seconds */
184                 /// TRANSLATORS: s here is an abbreviation for seconds
185                 ap << s << _("s");
186         }
187
188         return ap.str ();
189 }
190
191 #ifdef DCPOMATIC_POSIX
192 /** @param l Mangled C++ identifier.
193  *  @return Demangled version.
194  */
195 static string
196 demangle (string l)
197 {
198         string::size_type const b = l.find_first_of (N_("("));
199         if (b == string::npos) {
200                 return l;
201         }
202
203         string::size_type const p = l.find_last_of (N_("+"));
204         if (p == string::npos) {
205                 return l;
206         }
207
208         if ((p - b) <= 1) {
209                 return l;
210         }
211         
212         string const fn = l.substr (b + 1, p - b - 1);
213
214         int status;
215         try {
216                 
217                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
218                 string d (realname);
219                 free (realname);
220                 return d;
221                 
222         } catch (std::exception) {
223                 
224         }
225         
226         return l;
227 }
228
229 /** Write a stacktrace to an ostream.
230  *  @param out Stream to write to.
231  *  @param levels Number of levels to go up the call stack.
232  */
233 void
234 stacktrace (ostream& out, int levels)
235 {
236         void *array[200];
237         size_t size = backtrace (array, 200);
238         char** strings = backtrace_symbols (array, size);
239      
240         if (strings) {
241                 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
242                         out << N_("  ") << demangle (strings[i]) << "\n";
243                 }
244                 
245                 free (strings);
246         }
247 }
248 #endif
249
250 /** @param v Version as used by FFmpeg.
251  *  @return A string representation of v.
252  */
253 static string
254 ffmpeg_version_to_string (int v)
255 {
256         SafeStringStream s;
257         s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
258         return s.str ();
259 }
260
261 double
262 seconds (struct timeval t)
263 {
264         return t.tv_sec + (double (t.tv_usec) / 1e6);
265 }
266
267 #ifdef DCPOMATIC_WINDOWS
268
269 /** Resolve symbol name and source location given the path to the executable */
270 int
271 addr2line (void const * const adr)
272 {
273         char addr2line_cmd[512] = { 0 };
274         sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str()); 
275         return system(addr2line_cmd);
276 }
277
278 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
279  *  (NOT C++ exceptions!).  We write a backtrace to backtrace_file by dark means.
280  *  Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
281  */
282 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
283 {
284         FILE* f = fopen_boost (backtrace_file, "w");
285         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
286         fclose(f);
287         
288         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
289                 CONTEXT* context = info->ContextRecord;
290                 SymInitialize (GetCurrentProcess (), 0, true);
291                 
292                 STACKFRAME frame = { 0 };
293                 
294                 /* setup initial stack frame */
295 #if _WIN64
296                 frame.AddrPC.Offset    = context->Rip;
297                 frame.AddrStack.Offset = context->Rsp;
298                 frame.AddrFrame.Offset = context->Rbp;
299 #else  
300                 frame.AddrPC.Offset    = context->Eip;
301                 frame.AddrStack.Offset = context->Esp;
302                 frame.AddrFrame.Offset = context->Ebp;
303 #endif
304                 frame.AddrPC.Mode      = AddrModeFlat;
305                 frame.AddrStack.Mode   = AddrModeFlat;
306                 frame.AddrFrame.Mode   = AddrModeFlat;
307                 
308                 while (
309                         StackWalk (
310                                 IMAGE_FILE_MACHINE_I386,
311                                 GetCurrentProcess (),
312                                 GetCurrentThread (),
313                                 &frame,
314                                 context,
315                                 0,
316                                 SymFunctionTableAccess,
317                                 SymGetModuleBase,
318                                 0
319                                 )
320                         ) {
321                         addr2line((void *) frame.AddrPC.Offset);
322                 }
323         } else {
324 #ifdef _WIN64          
325                 addr2line ((void *) info->ContextRecord->Rip);
326 #else          
327                 addr2line ((void *) info->ContextRecord->Eip);
328 #endif         
329         }
330         
331         return EXCEPTION_CONTINUE_SEARCH;
332 }
333 #endif
334
335 void
336 set_backtrace_file (boost::filesystem::path p)
337 {
338         backtrace_file = p;
339 }
340
341 /** This is called when there is an unhandled exception.  Any
342  *  backtrace in this function is useless on Windows as the stack has
343  *  already been unwound from the throw; we have the gdb wrap hack to
344  *  cope with that.
345  */
346 void
347 terminate ()
348 {
349         static bool tried_throw = false;
350
351         try {
352                 // try once to re-throw currently active exception
353                 if (!tried_throw) {
354                         tried_throw = true;
355                         throw;
356                 }
357         }
358         catch (const std::exception &e) {
359                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
360                           << e.what() << std::endl;
361         }
362         catch (...) {
363                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception." 
364                           << std::endl;
365         }
366
367 #ifdef DCPOMATIC_POSIX
368         stacktrace (cout, 50);
369 #endif
370         abort();
371 }
372
373 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
374  *  Must be called from the UI thread, if there is one.
375  */
376 void
377 dcpomatic_setup ()
378 {
379 #ifdef DCPOMATIC_WINDOWS
380         boost::filesystem::path p = g_get_user_config_dir ();
381         p /= "backtrace.txt";
382         set_backtrace_file (p);
383         SetUnhandledExceptionFilter(exception_handler);
384
385         /* Dark voodoo which, I think, gets boost::filesystem::path to
386            correctly convert UTF-8 strings to paths, and also paths
387            back to UTF-8 strings (on path::string()).
388
389            After this, constructing boost::filesystem::paths from strings
390            converts from UTF-8 to UTF-16 inside the path.  Then
391            path::string().c_str() gives UTF-8 and
392            path::c_str()          gives UTF-16.
393
394            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
395            so things are much simpler.
396         */
397         std::locale::global (boost::locale::generator().generate (""));
398         boost::filesystem::path::imbue (std::locale ());
399 #endif  
400         
401         avfilter_register_all ();
402
403 #ifdef DCPOMATIC_OSX
404         /* Add our lib directory to the libltdl search path so that
405            xmlsec can find xmlsec1-openssl.
406         */
407         boost::filesystem::path lib = app_contents ();
408         lib /= "lib";
409         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
410 #endif
411
412         set_terminate (terminate);
413
414         Pango::init ();
415         dcp::init ();
416         
417         Ratio::setup_ratios ();
418         VideoContentScale::setup_scales ();
419         DCPContentType::setup_dcp_content_types ();
420         Scaler::setup_scalers ();
421         Filter::setup_filters ();
422         CinemaSoundProcessor::setup_cinema_sound_processors ();
423         AudioProcessor::setup_audio_processors ();
424
425         ui_thread = boost::this_thread::get_id ();
426 }
427
428 #ifdef DCPOMATIC_WINDOWS
429 boost::filesystem::path
430 mo_path ()
431 {
432         wchar_t buffer[512];
433         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
434         boost::filesystem::path p (buffer);
435         p = p.parent_path ();
436         p = p.parent_path ();
437         p /= "locale";
438         return p;
439 }
440 #endif
441
442 #ifdef DCPOMATIC_OSX
443 boost::filesystem::path
444 mo_path ()
445 {
446         return "DCP-o-matic 2.app/Contents/Resources";
447 }
448 #endif
449
450 void
451 dcpomatic_setup_gettext_i18n (string lang)
452 {
453 #ifdef DCPOMATIC_LINUX
454         lang += ".UTF8";
455 #endif
456
457         if (!lang.empty ()) {
458                 /* Override our environment language.  Note that the caller must not
459                    free the string passed into putenv().
460                 */
461                 string s = String::compose ("LANGUAGE=%1", lang);
462                 putenv (strdup (s.c_str ()));
463                 s = String::compose ("LANG=%1", lang);
464                 putenv (strdup (s.c_str ()));
465                 s = String::compose ("LC_ALL=%1", lang);
466                 putenv (strdup (s.c_str ()));
467         }
468
469         setlocale (LC_ALL, "");
470         textdomain ("libdcpomatic");
471
472 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
473         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
474         bind_textdomain_codeset ("libdcpomatic", "UTF8");
475 #endif  
476
477 #ifdef DCPOMATIC_LINUX
478         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
479 #endif
480 }
481
482 /** @param s A string.
483  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
484  */
485 vector<string>
486 split_at_spaces_considering_quotes (string s)
487 {
488         vector<string> out;
489         bool in_quotes = false;
490         string c;
491         for (string::size_type i = 0; i < s.length(); ++i) {
492                 if (s[i] == ' ' && !in_quotes) {
493                         out.push_back (c);
494                         c = N_("");
495                 } else if (s[i] == '"') {
496                         in_quotes = !in_quotes;
497                 } else {
498                         c += s[i];
499                 }
500         }
501
502         out.push_back (c);
503         return out;
504 }
505
506 /** @param job Optional job for which to report progress */
507 string
508 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
509 {
510         boost::uintmax_t const buffer_size = 64 * 1024;
511         char buffer[buffer_size];
512
513         MD5Digester digester;
514
515         vector<int64_t> sizes;
516         for (size_t i = 0; i < files.size(); ++i) {
517                 sizes.push_back (boost::filesystem::file_size (files[i]));
518         }
519
520         for (size_t i = 0; i < files.size(); ++i) {
521                 FILE* f = fopen_boost (files[i], "rb");
522                 if (!f) {
523                         throw OpenFileError (files[i].string());
524                 }
525
526                 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
527                 boost::uintmax_t remaining = bytes;
528
529                 while (remaining > 0) {
530                         int const t = min (remaining, buffer_size);
531                         int const r = fread (buffer, 1, t, f);
532                         if (r != t) {
533                                 throw ReadFileError (files[i], errno);
534                         }
535                         digester.add (buffer, t);
536                         remaining -= t;
537
538                         if (job) {
539                                 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
540                         }
541                 }
542
543                 fclose (f);
544         }
545
546         return digester.get ();
547 }
548
549 /** @param An arbitrary audio frame rate.
550  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
551  */
552 int
553 dcp_audio_frame_rate (int fs)
554 {
555         if (fs <= 48000) {
556                 return 48000;
557         }
558
559         return 96000;
560 }
561
562 Socket::Socket (int timeout)
563         : _deadline (_io_service)
564         , _socket (_io_service)
565         , _acceptor (0)
566         , _timeout (timeout)
567 {
568         _deadline.expires_at (boost::posix_time::pos_infin);
569         check ();
570 }
571
572 Socket::~Socket ()
573 {
574         delete _acceptor;
575 }
576
577 void
578 Socket::check ()
579 {
580         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
581                 if (_acceptor) {
582                         _acceptor->cancel ();
583                 } else {
584                         _socket.close ();
585                 }
586                 _deadline.expires_at (boost::posix_time::pos_infin);
587         }
588
589         _deadline.async_wait (boost::bind (&Socket::check, this));
590 }
591
592 /** Blocking connect.
593  *  @param endpoint End-point to connect to.
594  */
595 void
596 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
597 {
598         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
599         boost::system::error_code ec = boost::asio::error::would_block;
600         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
601         do {
602                 _io_service.run_one();
603         } while (ec == boost::asio::error::would_block);
604
605         if (ec) {
606                 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
607         }
608
609         if (!_socket.is_open ()) {
610                 throw NetworkError (_("connect timed out"));
611         }
612 }
613
614 void
615 Socket::accept (int port)
616 {
617         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
618         
619         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
620         boost::system::error_code ec = boost::asio::error::would_block;
621         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
622         do {
623                 _io_service.run_one ();
624         } while (ec == boost::asio::error::would_block);
625
626         delete _acceptor;
627         _acceptor = 0;
628         
629         if (ec) {
630                 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
631         }
632 }
633
634 /** Blocking write.
635  *  @param data Buffer to write.
636  *  @param size Number of bytes to write.
637  */
638 void
639 Socket::write (uint8_t const * data, int size)
640 {
641         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
642         boost::system::error_code ec = boost::asio::error::would_block;
643
644         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
645         
646         do {
647                 _io_service.run_one ();
648         } while (ec == boost::asio::error::would_block);
649
650         if (ec) {
651                 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
652         }
653 }
654
655 void
656 Socket::write (uint32_t v)
657 {
658         v = htonl (v);
659         write (reinterpret_cast<uint8_t*> (&v), 4);
660 }
661
662 /** Blocking read.
663  *  @param data Buffer to read to.
664  *  @param size Number of bytes to read.
665  */
666 void
667 Socket::read (uint8_t* data, int size)
668 {
669         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
670         boost::system::error_code ec = boost::asio::error::would_block;
671
672         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
673
674         do {
675                 _io_service.run_one ();
676         } while (ec == boost::asio::error::would_block);
677         
678         if (ec) {
679                 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
680         }
681 }
682
683 uint32_t
684 Socket::read_uint32 ()
685 {
686         uint32_t v;
687         read (reinterpret_cast<uint8_t *> (&v), 4);
688         return ntohl (v);
689 }
690
691 /** Round a number up to the nearest multiple of another number.
692  *  @param c Index.
693  *  @param s Array of numbers to round, indexed by c.
694  *  @param t Multiple to round to.
695  *  @return Rounded number.
696  */
697 int
698 stride_round_up (int c, int const * stride, int t)
699 {
700         int const a = stride[c] + (t - 1);
701         return a - (a % t);
702 }
703
704 /** @param n A number.
705  *  @param r Rounding `boundary' (must be a power of 2)
706  *  @return n rounded to the nearest r
707  */
708 int
709 round_to (float n, int r)
710 {
711         DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
712         return int (n + float(r) / 2) &~ (r - 1);
713 }
714
715 /** Read a sequence of key / value pairs from a text stream;
716  *  the keys are the first words on the line, and the values are
717  *  the remainder of the line following the key.  Lines beginning
718  *  with # are ignored.
719  *  @param s Stream to read.
720  *  @return key/value pairs.
721  */
722 multimap<string, string>
723 read_key_value (istream &s) 
724 {
725         multimap<string, string> kv;
726         
727         string line;
728         while (getline (s, line)) {
729                 if (line.empty ()) {
730                         continue;
731                 }
732
733                 if (line[0] == '#') {
734                         continue;
735                 }
736
737                 if (line[line.size() - 1] == '\r') {
738                         line = line.substr (0, line.size() - 1);
739                 }
740
741                 size_t const s = line.find (' ');
742                 if (s == string::npos) {
743                         continue;
744                 }
745
746                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
747         }
748
749         return kv;
750 }
751
752 string
753 get_required_string (multimap<string, string> const & kv, string k)
754 {
755         if (kv.count (k) > 1) {
756                 throw StringError (N_("unexpected multiple keys in key-value set"));
757         }
758
759         multimap<string, string>::const_iterator i = kv.find (k);
760         
761         if (i == kv.end ()) {
762                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
763         }
764
765         return i->second;
766 }
767
768 int
769 get_required_int (multimap<string, string> const & kv, string k)
770 {
771         string const v = get_required_string (kv, k);
772         return raw_convert<int> (v);
773 }
774
775 float
776 get_required_float (multimap<string, string> const & kv, string k)
777 {
778         string const v = get_required_string (kv, k);
779         return raw_convert<float> (v);
780 }
781
782 string
783 get_optional_string (multimap<string, string> const & kv, string k)
784 {
785         if (kv.count (k) > 1) {
786                 throw StringError (N_("unexpected multiple keys in key-value set"));
787         }
788
789         multimap<string, string>::const_iterator i = kv.find (k);
790         if (i == kv.end ()) {
791                 return N_("");
792         }
793
794         return i->second;
795 }
796
797 int
798 get_optional_int (multimap<string, string> const & kv, string k)
799 {
800         if (kv.count (k) > 1) {
801                 throw StringError (N_("unexpected multiple keys in key-value set"));
802         }
803
804         multimap<string, string>::const_iterator i = kv.find (k);
805         if (i == kv.end ()) {
806                 return 0;
807         }
808
809         return raw_convert<int> (i->second);
810 }
811
812 /** Trip an assert if the caller is not in the UI thread */
813 void
814 ensure_ui_thread ()
815 {
816         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
817 }
818
819 string
820 audio_channel_name (int c)
821 {
822         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
823
824         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
825         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
826         /// VI is the visually-impaired audio track (audio describe).
827         string const channels[] = {
828                 _("Left"),
829                 _("Right"),
830                 _("Centre"),
831                 _("Lfe (sub)"),
832                 _("Left surround"),
833                 _("Right surround"),
834                 _("Hearing impaired"),
835                 _("Visually impaired"),
836                 _("Left centre"),
837                 _("Right centre"),
838                 _("Left rear surround"),
839                 _("Right rear surround"),
840         };
841
842         return channels[c];
843 }
844
845 bool
846 valid_image_file (boost::filesystem::path f)
847 {
848         string ext = f.extension().string();
849         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
850         return (
851                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
852                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
853                 ext == ".j2c" || ext == ".j2k"
854                 );
855 }
856
857 bool
858 valid_j2k_file (boost::filesystem::path f)
859 {
860         string ext = f.extension().string();
861         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
862         return (ext == ".j2k" || ext == ".j2c");
863 }
864
865 string
866 tidy_for_filename (string f)
867 {
868         string t;
869         for (size_t i = 0; i < f.length(); ++i) {
870                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
871                         t += f[i];
872                 } else {
873                         t += '_';
874                 }
875         }
876
877         return t;
878 }
879
880 dcp::Size
881 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
882 {
883         if (ratio < full_frame.ratio ()) {
884                 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
885         }
886         
887         return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
888 }
889
890 void *
891 wrapped_av_malloc (size_t s)
892 {
893         void* p = av_malloc (s);
894         if (!p) {
895                 throw bad_alloc ();
896         }
897         return p;
898 }
899                 
900 string
901 entities_to_text (string e)
902 {
903         boost::algorithm::replace_all (e, "%3A", ":");
904         boost::algorithm::replace_all (e, "%2F", "/");
905         return e;
906 }
907
908 int64_t
909 divide_with_round (int64_t a, int64_t b)
910 {
911         if (a % b >= (b / 2)) {
912                 return (a + b - 1) / b;
913         } else {
914                 return a / b;
915         }
916 }
917
918 /** Return a user-readable string summarising the versions of our dependencies */
919 string
920 dependency_version_summary ()
921 {
922         SafeStringStream s;
923         s << N_("libopenjpeg ") << opj_version () << N_(", ")
924           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
925           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
926           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
927           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
928           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
929           << MagickVersion << N_(", ")
930           << N_("libssh ") << ssh_version (0) << N_(", ")
931           << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
932
933         return s.str ();
934 }
935
936 /** Construct a ScopedTemporary.  A temporary filename is decided but the file is not opened
937  *  until ::open() is called.
938  */
939 ScopedTemporary::ScopedTemporary ()
940         : _open (0)
941 {
942         _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
943 }
944
945 /** Close and delete the temporary file */
946 ScopedTemporary::~ScopedTemporary ()
947 {
948         close ();       
949         boost::system::error_code ec;
950         boost::filesystem::remove (_file, ec);
951 }
952
953 /** @return temporary filename */
954 char const *
955 ScopedTemporary::c_str () const
956 {
957         return _file.string().c_str ();
958 }
959
960 /** Open the temporary file.
961  *  @return File's FILE pointer.
962  */
963 FILE*
964 ScopedTemporary::open (char const * params)
965 {
966         _open = fopen (c_str(), params);
967         return _open;
968 }
969
970 /** Close the file */
971 void
972 ScopedTemporary::close ()
973 {
974         if (_open) {
975                 fclose (_open);
976                 _open = 0;
977         }
978 }
979
980 ContentTimePeriod
981 subtitle_period (AVSubtitle const & sub)
982 {
983         ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
984
985         ContentTimePeriod period (
986                 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
987                 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
988                 );
989
990         return period;
991 }