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