Fix typos on hand-applying patch.
[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 addr)
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
283 exception_handler(struct _EXCEPTION_POINTERS * info)
284 {
285         FILE* f = fopen_boost (backtrace_file, "w");
286         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
287         fclose(f);
288         
289         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
290                 CONTEXT* context = info->ContextRecord;
291                 SymInitialize (GetCurrentProcess (), 0, true);
292                 
293                 STACKFRAME frame = { 0 };
294                 
295                 /* setup initial stack frame */
296 #if _WIN64
297                 frame.AddrPC.Offset    = context->Rip;
298                 frame.AddrStack.Offset = context->Rsp;
299                 frame.AddrFrame.Offset = context->Rbp;
300 #else  
301                 frame.AddrPC.Offset    = context->Eip;
302                 frame.AddrStack.Offset = context->Esp;
303                 frame.AddrFrame.Offset = context->Ebp;
304 #endif
305                 frame.AddrPC.Mode      = AddrModeFlat;
306                 frame.AddrStack.Mode   = AddrModeFlat;
307                 frame.AddrFrame.Mode   = AddrModeFlat;
308                 
309                 while (
310                         StackWalk (
311                                 IMAGE_FILE_MACHINE_I386,
312                                 GetCurrentProcess (),
313                                 GetCurrentThread (),
314                                 &frame,
315                                 context,
316                                 0,
317                                 SymFunctionTableAccess,
318                                 SymGetModuleBase,
319                                 0
320                                 )
321                         ) {
322                         addr2line((void *) frame.AddrPC.Offset);
323                 }
324         } else {
325 #ifdef _WIN64          
326                 addr2line ((void *) info->ContextRecord->Rip);
327 #else          
328                 addr2line ((void *) info->ContextRecord->Eip);
329 #endif         
330         }
331         
332         return EXCEPTION_CONTINUE_SEARCH;
333 }
334 #endif
335
336 void
337 set_backtrace_file (boost::filesystem::path p)
338 {
339         backtrace_file = p;
340 }
341
342 /** This is called when there is an unhandled exception.  Any
343  *  backtrace in this function is useless on Windows as the stack has
344  *  already been unwound from the throw; we have the gdb wrap hack to
345  *  cope with that.
346  */
347 void
348 terminate ()
349 {
350         static bool tried_throw = false;
351
352         try {
353                 // try once to re-throw currently active exception
354                 if (!tried_throw) {
355                         tried_throw = true;
356                         throw;
357                 }
358         }
359         catch (const std::exception &e) {
360                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
361                           << e.what() << std::endl;
362         }
363         catch (...) {
364                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception." 
365                           << std::endl;
366         }
367
368 #ifdef DCPOMATIC_POSIX
369         stacktrace (cout, 50);
370 #endif
371         abort();
372 }
373
374 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
375  *  Must be called from the UI thread, if there is one.
376  */
377 void
378 dcpomatic_setup ()
379 {
380 #ifdef DCPOMATIC_WINDOWS
381         boost::filesystem::path p = g_get_user_config_dir ();
382         p /= "backtrace.txt";
383         set_backtrace_file (p);
384         SetUnhandledExceptionFilter(exception_handler);
385
386         /* Dark voodoo which, I think, gets boost::filesystem::path to
387            correctly convert UTF-8 strings to paths, and also paths
388            back to UTF-8 strings (on path::string()).
389
390            After this, constructing boost::filesystem::paths from strings
391            converts from UTF-8 to UTF-16 inside the path.  Then
392            path::string().c_str() gives UTF-8 and
393            path::c_str()          gives UTF-16.
394
395            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
396            so things are much simpler.
397         */
398         std::locale::global (boost::locale::generator().generate (""));
399         boost::filesystem::path::imbue (std::locale ());
400 #endif  
401         
402         avfilter_register_all ();
403
404 #ifdef DCPOMATIC_OSX
405         /* Add our lib directory to the libltdl search path so that
406            xmlsec can find xmlsec1-openssl.
407         */
408         boost::filesystem::path lib = app_contents ();
409         lib /= "lib";
410         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
411 #endif
412
413         set_terminate (terminate);
414
415         Pango::init ();
416         dcp::init ();
417         
418         Ratio::setup_ratios ();
419         VideoContentScale::setup_scales ();
420         DCPContentType::setup_dcp_content_types ();
421         Scaler::setup_scalers ();
422         Filter::setup_filters ();
423         CinemaSoundProcessor::setup_cinema_sound_processors ();
424         AudioProcessor::setup_audio_processors ();
425
426         ui_thread = boost::this_thread::get_id ();
427 }
428
429 #ifdef DCPOMATIC_WINDOWS
430 boost::filesystem::path
431 mo_path ()
432 {
433         wchar_t buffer[512];
434         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
435         boost::filesystem::path p (buffer);
436         p = p.parent_path ();
437         p = p.parent_path ();
438         p /= "locale";
439         return p;
440 }
441 #endif
442
443 #ifdef DCPOMATIC_OSX
444 boost::filesystem::path
445 mo_path ()
446 {
447         return "DCP-o-matic 2.app/Contents/Resources";
448 }
449 #endif
450
451 void
452 dcpomatic_setup_gettext_i18n (string lang)
453 {
454 #ifdef DCPOMATIC_LINUX
455         lang += ".UTF8";
456 #endif
457
458         if (!lang.empty ()) {
459                 /* Override our environment language.  Note that the caller must not
460                    free the string passed into putenv().
461                 */
462                 string s = String::compose ("LANGUAGE=%1", lang);
463                 putenv (strdup (s.c_str ()));
464                 s = String::compose ("LANG=%1", lang);
465                 putenv (strdup (s.c_str ()));
466                 s = String::compose ("LC_ALL=%1", lang);
467                 putenv (strdup (s.c_str ()));
468         }
469
470         setlocale (LC_ALL, "");
471         textdomain ("libdcpomatic");
472
473 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
474         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
475         bind_textdomain_codeset ("libdcpomatic", "UTF8");
476 #endif  
477
478 #ifdef DCPOMATIC_LINUX
479         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
480 #endif
481 }
482
483 /** @param s A string.
484  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
485  */
486 vector<string>
487 split_at_spaces_considering_quotes (string s)
488 {
489         vector<string> out;
490         bool in_quotes = false;
491         string c;
492         for (string::size_type i = 0; i < s.length(); ++i) {
493                 if (s[i] == ' ' && !in_quotes) {
494                         out.push_back (c);
495                         c = N_("");
496                 } else if (s[i] == '"') {
497                         in_quotes = !in_quotes;
498                 } else {
499                         c += s[i];
500                 }
501         }
502
503         out.push_back (c);
504         return out;
505 }
506
507 /** @param job Optional job for which to report progress */
508 string
509 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
510 {
511         boost::uintmax_t const buffer_size = 64 * 1024;
512         char buffer[buffer_size];
513
514         MD5Digester digester;
515
516         vector<int64_t> sizes;
517         for (size_t i = 0; i < files.size(); ++i) {
518                 sizes.push_back (boost::filesystem::file_size (files[i]));
519         }
520
521         for (size_t i = 0; i < files.size(); ++i) {
522                 FILE* f = fopen_boost (files[i], "rb");
523                 if (!f) {
524                         throw OpenFileError (files[i].string());
525                 }
526
527                 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
528                 boost::uintmax_t remaining = bytes;
529
530                 while (remaining > 0) {
531                         int const t = min (remaining, buffer_size);
532                         int const r = fread (buffer, 1, t, f);
533                         if (r != t) {
534                                 throw ReadFileError (files[i], errno);
535                         }
536                         digester.add (buffer, t);
537                         remaining -= t;
538
539                         if (job) {
540                                 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
541                         }
542                 }
543
544                 fclose (f);
545         }
546
547         return digester.get ();
548 }
549
550 /** @param An arbitrary audio frame rate.
551  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
552  */
553 int
554 dcp_audio_frame_rate (int fs)
555 {
556         if (fs <= 48000) {
557                 return 48000;
558         }
559
560         return 96000;
561 }
562
563 Socket::Socket (int timeout)
564         : _deadline (_io_service)
565         , _socket (_io_service)
566         , _acceptor (0)
567         , _timeout (timeout)
568 {
569         _deadline.expires_at (boost::posix_time::pos_infin);
570         check ();
571 }
572
573 Socket::~Socket ()
574 {
575         delete _acceptor;
576 }
577
578 void
579 Socket::check ()
580 {
581         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
582                 if (_acceptor) {
583                         _acceptor->cancel ();
584                 } else {
585                         _socket.close ();
586                 }
587                 _deadline.expires_at (boost::posix_time::pos_infin);
588         }
589
590         _deadline.async_wait (boost::bind (&Socket::check, this));
591 }
592
593 /** Blocking connect.
594  *  @param endpoint End-point to connect to.
595  */
596 void
597 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
598 {
599         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
600         boost::system::error_code ec = boost::asio::error::would_block;
601         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
602         do {
603                 _io_service.run_one();
604         } while (ec == boost::asio::error::would_block);
605
606         if (ec) {
607                 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
608         }
609
610         if (!_socket.is_open ()) {
611                 throw NetworkError (_("connect timed out"));
612         }
613 }
614
615 void
616 Socket::accept (int port)
617 {
618         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
619         
620         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
621         boost::system::error_code ec = boost::asio::error::would_block;
622         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
623         do {
624                 _io_service.run_one ();
625         } while (ec == boost::asio::error::would_block);
626
627         delete _acceptor;
628         _acceptor = 0;
629         
630         if (ec) {
631                 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
632         }
633 }
634
635 /** Blocking write.
636  *  @param data Buffer to write.
637  *  @param size Number of bytes to write.
638  */
639 void
640 Socket::write (uint8_t const * data, int size)
641 {
642         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
643         boost::system::error_code ec = boost::asio::error::would_block;
644
645         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
646         
647         do {
648                 _io_service.run_one ();
649         } while (ec == boost::asio::error::would_block);
650
651         if (ec) {
652                 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
653         }
654 }
655
656 void
657 Socket::write (uint32_t v)
658 {
659         v = htonl (v);
660         write (reinterpret_cast<uint8_t*> (&v), 4);
661 }
662
663 /** Blocking read.
664  *  @param data Buffer to read to.
665  *  @param size Number of bytes to read.
666  */
667 void
668 Socket::read (uint8_t* data, int size)
669 {
670         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
671         boost::system::error_code ec = boost::asio::error::would_block;
672
673         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
674
675         do {
676                 _io_service.run_one ();
677         } while (ec == boost::asio::error::would_block);
678         
679         if (ec) {
680                 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
681         }
682 }
683
684 uint32_t
685 Socket::read_uint32 ()
686 {
687         uint32_t v;
688         read (reinterpret_cast<uint8_t *> (&v), 4);
689         return ntohl (v);
690 }
691
692 /** Round a number up to the nearest multiple of another number.
693  *  @param c Index.
694  *  @param s Array of numbers to round, indexed by c.
695  *  @param t Multiple to round to.
696  *  @return Rounded number.
697  */
698 int
699 stride_round_up (int c, int const * stride, int t)
700 {
701         int const a = stride[c] + (t - 1);
702         return a - (a % t);
703 }
704
705 /** @param n A number.
706  *  @param r Rounding `boundary' (must be a power of 2)
707  *  @return n rounded to the nearest r
708  */
709 int
710 round_to (float n, int r)
711 {
712         DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
713         return int (n + float(r) / 2) &~ (r - 1);
714 }
715
716 /** Read a sequence of key / value pairs from a text stream;
717  *  the keys are the first words on the line, and the values are
718  *  the remainder of the line following the key.  Lines beginning
719  *  with # are ignored.
720  *  @param s Stream to read.
721  *  @return key/value pairs.
722  */
723 multimap<string, string>
724 read_key_value (istream &s) 
725 {
726         multimap<string, string> kv;
727         
728         string line;
729         while (getline (s, line)) {
730                 if (line.empty ()) {
731                         continue;
732                 }
733
734                 if (line[0] == '#') {
735                         continue;
736                 }
737
738                 if (line[line.size() - 1] == '\r') {
739                         line = line.substr (0, line.size() - 1);
740                 }
741
742                 size_t const s = line.find (' ');
743                 if (s == string::npos) {
744                         continue;
745                 }
746
747                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
748         }
749
750         return kv;
751 }
752
753 string
754 get_required_string (multimap<string, string> const & kv, string k)
755 {
756         if (kv.count (k) > 1) {
757                 throw StringError (N_("unexpected multiple keys in key-value set"));
758         }
759
760         multimap<string, string>::const_iterator i = kv.find (k);
761         
762         if (i == kv.end ()) {
763                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
764         }
765
766         return i->second;
767 }
768
769 int
770 get_required_int (multimap<string, string> const & kv, string k)
771 {
772         string const v = get_required_string (kv, k);
773         return raw_convert<int> (v);
774 }
775
776 float
777 get_required_float (multimap<string, string> const & kv, string k)
778 {
779         string const v = get_required_string (kv, k);
780         return raw_convert<float> (v);
781 }
782
783 string
784 get_optional_string (multimap<string, string> const & kv, string k)
785 {
786         if (kv.count (k) > 1) {
787                 throw StringError (N_("unexpected multiple keys in key-value set"));
788         }
789
790         multimap<string, string>::const_iterator i = kv.find (k);
791         if (i == kv.end ()) {
792                 return N_("");
793         }
794
795         return i->second;
796 }
797
798 int
799 get_optional_int (multimap<string, string> const & kv, string k)
800 {
801         if (kv.count (k) > 1) {
802                 throw StringError (N_("unexpected multiple keys in key-value set"));
803         }
804
805         multimap<string, string>::const_iterator i = kv.find (k);
806         if (i == kv.end ()) {
807                 return 0;
808         }
809
810         return raw_convert<int> (i->second);
811 }
812
813 /** Trip an assert if the caller is not in the UI thread */
814 void
815 ensure_ui_thread ()
816 {
817         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
818 }
819
820 string
821 audio_channel_name (int c)
822 {
823         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
824
825         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
826         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
827         /// VI is the visually-impaired audio track (audio describe).
828         string const channels[] = {
829                 _("Left"),
830                 _("Right"),
831                 _("Centre"),
832                 _("Lfe (sub)"),
833                 _("Left surround"),
834                 _("Right surround"),
835                 _("Hearing impaired"),
836                 _("Visually impaired"),
837                 _("Left centre"),
838                 _("Right centre"),
839                 _("Left rear surround"),
840                 _("Right rear surround"),
841         };
842
843         return channels[c];
844 }
845
846 bool
847 valid_image_file (boost::filesystem::path f)
848 {
849         string ext = f.extension().string();
850         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
851         return (
852                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
853                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
854                 ext == ".j2c" || ext == ".j2k"
855                 );
856 }
857
858 bool
859 valid_j2k_file (boost::filesystem::path f)
860 {
861         string ext = f.extension().string();
862         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
863         return (ext == ".j2k" || ext == ".j2c");
864 }
865
866 string
867 tidy_for_filename (string f)
868 {
869         string t;
870         for (size_t i = 0; i < f.length(); ++i) {
871                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
872                         t += f[i];
873                 } else {
874                         t += '_';
875                 }
876         }
877
878         return t;
879 }
880
881 dcp::Size
882 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
883 {
884         if (ratio < full_frame.ratio ()) {
885                 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
886         }
887         
888         return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
889 }
890
891 void *
892 wrapped_av_malloc (size_t s)
893 {
894         void* p = av_malloc (s);
895         if (!p) {
896                 throw bad_alloc ();
897         }
898         return p;
899 }
900                 
901 string
902 entities_to_text (string e)
903 {
904         boost::algorithm::replace_all (e, "%3A", ":");
905         boost::algorithm::replace_all (e, "%2F", "/");
906         return e;
907 }
908
909 int64_t
910 divide_with_round (int64_t a, int64_t b)
911 {
912         if (a % b >= (b / 2)) {
913                 return (a + b - 1) / b;
914         } else {
915                 return a / b;
916         }
917 }
918
919 /** Return a user-readable string summarising the versions of our dependencies */
920 string
921 dependency_version_summary ()
922 {
923         SafeStringStream s;
924         s << N_("libopenjpeg ") << opj_version () << N_(", ")
925           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
926           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
927           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
928           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
929           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
930           << MagickVersion << N_(", ")
931           << N_("libssh ") << ssh_version (0) << N_(", ")
932           << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
933
934         return s.str ();
935 }
936
937 /** Construct a ScopedTemporary.  A temporary filename is decided but the file is not opened
938  *  until ::open() is called.
939  */
940 ScopedTemporary::ScopedTemporary ()
941         : _open (0)
942 {
943         _file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path ();
944 }
945
946 /** Close and delete the temporary file */
947 ScopedTemporary::~ScopedTemporary ()
948 {
949         close ();       
950         boost::system::error_code ec;
951         boost::filesystem::remove (_file, ec);
952 }
953
954 /** @return temporary filename */
955 char const *
956 ScopedTemporary::c_str () const
957 {
958         return _file.string().c_str ();
959 }
960
961 /** Open the temporary file.
962  *  @return File's FILE pointer.
963  */
964 FILE*
965 ScopedTemporary::open (char const * params)
966 {
967         _open = fopen (c_str(), params);
968         return _open;
969 }
970
971 /** Close the file */
972 void
973 ScopedTemporary::close ()
974 {
975         if (_open) {
976                 fclose (_open);
977                 _open = 0;
978         }
979 }
980
981 ContentTimePeriod
982 subtitle_period (AVSubtitle const & sub)
983 {
984         ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
985
986         ContentTimePeriod period (
987                 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
988                 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
989                 );
990
991         return period;
992 }