Small bits of tidying up.
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012 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 <sstream>
26 #include <iomanip>
27 #include <iostream>
28 #include <fstream>
29 #include <climits>
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/lexical_cast.hpp>
40 #include <boost/thread.hpp>
41 #include <boost/filesystem.hpp>
42 #include <glib.h>
43 #include <openjpeg.h>
44 #include <openssl/md5.h>
45 #include <magick/MagickCore.h>
46 #include <magick/version.h>
47 #include <libdcp/version.h>
48 extern "C" {
49 #include <libavcodec/avcodec.h>
50 #include <libavformat/avformat.h>
51 #include <libswscale/swscale.h>
52 #include <libavfilter/avfiltergraph.h>
53 #include <libpostproc/postprocess.h>
54 #include <libavutil/pixfmt.h>
55 }
56 #include "util.h"
57 #include "exceptions.h"
58 #include "scaler.h"
59 #include "dcp_content_type.h"
60 #include "filter.h"
61 #include "sound_processor.h"
62 #include "config.h"
63 #include "ratio.h"
64 #ifdef DCPOMATIC_WINDOWS
65 #include "stack.hpp"
66 #endif
67
68 #include "i18n.h"
69
70 using std::string;
71 using std::stringstream;
72 using std::setfill;
73 using std::ostream;
74 using std::endl;
75 using std::vector;
76 using std::hex;
77 using std::setw;
78 using std::ifstream;
79 using std::ios;
80 using std::min;
81 using std::max;
82 using std::list;
83 using std::multimap;
84 using std::istream;
85 using std::numeric_limits;
86 using std::pair;
87 using std::ofstream;
88 using boost::shared_ptr;
89 using boost::thread;
90 using boost::lexical_cast;
91 using boost::optional;
92 using libdcp::Size;
93
94 static boost::thread::id ui_thread;
95 static boost::filesystem::path backtrace_file;
96
97 /** Convert some number of seconds to a string representation
98  *  in hours, minutes and seconds.
99  *
100  *  @param s Seconds.
101  *  @return String of the form H:M:S (where H is hours, M
102  *  is minutes and S is seconds).
103  */
104 string
105 seconds_to_hms (int s)
106 {
107         int m = s / 60;
108         s -= (m * 60);
109         int h = m / 60;
110         m -= (h * 60);
111
112         stringstream hms;
113         hms << h << N_(":");
114         hms.width (2);
115         hms << std::setfill ('0') << m << N_(":");
116         hms.width (2);
117         hms << std::setfill ('0') << s;
118
119         return hms.str ();
120 }
121
122 /** @param s Number of seconds.
123  *  @return String containing an approximate description of s (e.g. "about 2 hours")
124  */
125 string
126 seconds_to_approximate_hms (int s)
127 {
128         int m = s / 60;
129         s -= (m * 60);
130         int h = m / 60;
131         m -= (h * 60);
132
133         stringstream ap;
134         
135         if (h > 0) {
136                 if (m > 30) {
137                         ap << (h + 1) << N_(" ") << _("hours");
138                 } else {
139                         if (h == 1) {
140                                 ap << N_("1 ") << _("hour");
141                         } else {
142                                 ap << h << N_(" ") << _("hours");
143                         }
144                 }
145         } else if (m > 0) {
146                 if (m == 1) {
147                         ap << N_("1 ") << _("minute");
148                 } else {
149                         ap << m << N_(" ") << _("minutes");
150                 }
151         } else {
152                 ap << s << N_(" ") << _("seconds");
153         }
154
155         return ap.str ();
156 }
157
158 #ifdef DCPOMATIC_POSIX
159 /** @param l Mangled C++ identifier.
160  *  @return Demangled version.
161  */
162 static string
163 demangle (string l)
164 {
165         string::size_type const b = l.find_first_of (N_("("));
166         if (b == string::npos) {
167                 return l;
168         }
169
170         string::size_type const p = l.find_last_of (N_("+"));
171         if (p == string::npos) {
172                 return l;
173         }
174
175         if ((p - b) <= 1) {
176                 return l;
177         }
178         
179         string const fn = l.substr (b + 1, p - b - 1);
180
181         int status;
182         try {
183                 
184                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
185                 string d (realname);
186                 free (realname);
187                 return d;
188                 
189         } catch (std::exception) {
190                 
191         }
192         
193         return l;
194 }
195
196 /** Write a stacktrace to an ostream.
197  *  @param out Stream to write to.
198  *  @param levels Number of levels to go up the call stack.
199  */
200 void
201 stacktrace (ostream& out, int levels)
202 {
203         void *array[200];
204         size_t size = backtrace (array, 200);
205         char** strings = backtrace_symbols (array, size);
206      
207         if (strings) {
208                 for (size_t i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
209                         out << N_("  ") << demangle (strings[i]) << "\n";
210                 }
211                 
212                 free (strings);
213         }
214 }
215 #endif
216
217 /** @param v Version as used by FFmpeg.
218  *  @return A string representation of v.
219  */
220 static string
221 ffmpeg_version_to_string (int v)
222 {
223         stringstream s;
224         s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
225         return s.str ();
226 }
227
228 /** Return a user-readable string summarising the versions of our dependencies */
229 string
230 dependency_version_summary ()
231 {
232         stringstream s;
233         s << N_("libopenjpeg ") << opj_version () << N_(", ")
234           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
235           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
236           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
237           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
238           << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
239           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
240           << MagickVersion << N_(", ")
241           << N_("libssh ") << ssh_version (0) << N_(", ")
242           << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
243
244         return s.str ();
245 }
246
247 double
248 seconds (struct timeval t)
249 {
250         return t.tv_sec + (double (t.tv_usec) / 1e6);
251 }
252
253 #ifdef DCPOMATIC_WINDOWS
254 LONG WINAPI exception_handler(struct _EXCEPTION_POINTERS *)
255 {
256         dbg::stack s;
257         ofstream f (backtrace_file.string().c_str());
258         std::copy(s.begin(), s.end(), std::ostream_iterator<dbg::stack_frame>(f, "\n"));
259         return EXCEPTION_CONTINUE_SEARCH;
260 }
261 #endif
262
263 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
264  *  Must be called from the UI thread, if there is one.
265  */
266 void
267 dcpomatic_setup ()
268 {
269 #ifdef DCPOMATIC_WINDOWS
270         backtrace_file /= g_get_user_config_dir ();
271         backtrace_file /= "backtrace.txt";
272         SetUnhandledExceptionFilter(exception_handler);
273 #endif  
274         
275         avfilter_register_all ();
276         
277         Ratio::setup_ratios ();
278         DCPContentType::setup_dcp_content_types ();
279         Scaler::setup_scalers ();
280         Filter::setup_filters ();
281         SoundProcessor::setup_sound_processors ();
282
283         ui_thread = boost::this_thread::get_id ();
284 }
285
286 #ifdef DCPOMATIC_WINDOWS
287 boost::filesystem::path
288 mo_path ()
289 {
290         wchar_t buffer[512];
291         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
292         boost::filesystem::path p (buffer);
293         p = p.parent_path ();
294         p = p.parent_path ();
295         p /= "locale";
296         return p;
297 }
298 #endif
299
300 void
301 dcpomatic_setup_gettext_i18n (string lang)
302 {
303 #ifdef DCPOMATIC_POSIX
304         lang += ".UTF8";
305 #endif
306
307         if (!lang.empty ()) {
308                 /* Override our environment language; this is essential on
309                    Windows.
310                 */
311                 char cmd[64];
312                 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
313                 putenv (cmd);
314                 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
315                 putenv (cmd);
316         }
317
318         setlocale (LC_ALL, "");
319         textdomain ("libdcpomatic");
320
321 #ifdef DCPOMATIC_WINDOWS
322         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
323         bind_textdomain_codeset ("libdcpomatic", "UTF8");
324 #endif  
325
326 #ifdef DCPOMATIC_POSIX
327         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
328 #endif
329 }
330
331 /** @param s A string.
332  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
333  */
334 vector<string>
335 split_at_spaces_considering_quotes (string s)
336 {
337         vector<string> out;
338         bool in_quotes = false;
339         string c;
340         for (string::size_type i = 0; i < s.length(); ++i) {
341                 if (s[i] == ' ' && !in_quotes) {
342                         out.push_back (c);
343                         c = N_("");
344                 } else if (s[i] == '"') {
345                         in_quotes = !in_quotes;
346                 } else {
347                         c += s[i];
348                 }
349         }
350
351         out.push_back (c);
352         return out;
353 }
354
355 string
356 md5_digest (void const * data, int size)
357 {
358         MD5_CTX md5_context;
359         MD5_Init (&md5_context);
360         MD5_Update (&md5_context, data, size);
361         unsigned char digest[MD5_DIGEST_LENGTH];
362         MD5_Final (digest, &md5_context);
363         
364         stringstream s;
365         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
366                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
367         }
368
369         return s.str ();
370 }
371
372 /** @param file File name.
373  *  @return MD5 digest of file's contents.
374  */
375 string
376 md5_digest (boost::filesystem::path file)
377 {
378         ifstream f (file.string().c_str(), std::ios::binary);
379         if (!f.good ()) {
380                 throw OpenFileError (file.string());
381         }
382         
383         f.seekg (0, std::ios::end);
384         int bytes = f.tellg ();
385         f.seekg (0, std::ios::beg);
386
387         int const buffer_size = 64 * 1024;
388         char buffer[buffer_size];
389
390         MD5_CTX md5_context;
391         MD5_Init (&md5_context);
392         while (bytes > 0) {
393                 int const t = min (bytes, buffer_size);
394                 f.read (buffer, t);
395                 MD5_Update (&md5_context, buffer, t);
396                 bytes -= t;
397         }
398
399         unsigned char digest[MD5_DIGEST_LENGTH];
400         MD5_Final (digest, &md5_context);
401
402         stringstream s;
403         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
404                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
405         }
406
407         return s.str ();
408 }
409
410 static bool
411 about_equal (float a, float b)
412 {
413         /* A film of F seconds at f FPS will be Ff frames;
414            Consider some delta FPS d, so if we run the same
415            film at (f + d) FPS it will last F(f + d) seconds.
416
417            Hence the difference in length over the length of the film will
418            be F(f + d) - Ff frames
419             = Ff + Fd - Ff frames
420             = Fd frames
421             = Fd/f seconds
422  
423            So if we accept a difference of 1 frame, ie 1/f seconds, we can
424            say that
425
426            1/f = Fd/f
427         ie 1 = Fd
428         ie d = 1/F
429  
430            So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
431            FPS error is 1/F ~= 0.0001 ~= 10-e4
432         */
433
434         return (fabs (a - b) < 1e-4);
435 }
436
437 /** @param An arbitrary audio frame rate.
438  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
439  */
440 int
441 dcp_audio_frame_rate (int fs)
442 {
443         if (fs <= 48000) {
444                 return 48000;
445         }
446
447         return 96000;
448 }
449
450 Socket::Socket (int timeout)
451         : _deadline (_io_service)
452         , _socket (_io_service)
453         , _timeout (timeout)
454 {
455         _deadline.expires_at (boost::posix_time::pos_infin);
456         check ();
457 }
458
459 void
460 Socket::check ()
461 {
462         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
463                 _socket.close ();
464                 _deadline.expires_at (boost::posix_time::pos_infin);
465         }
466
467         _deadline.async_wait (boost::bind (&Socket::check, this));
468 }
469
470 /** Blocking connect.
471  *  @param endpoint End-point to connect to.
472  */
473 void
474 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
475 {
476         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
477         boost::system::error_code ec = boost::asio::error::would_block;
478         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
479         do {
480                 _io_service.run_one();
481         } while (ec == boost::asio::error::would_block);
482
483         if (ec || !_socket.is_open ()) {
484                 throw NetworkError (_("connect timed out"));
485         }
486 }
487
488 /** Blocking write.
489  *  @param data Buffer to write.
490  *  @param size Number of bytes to write.
491  */
492 void
493 Socket::write (uint8_t const * data, int size)
494 {
495         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
496         boost::system::error_code ec = boost::asio::error::would_block;
497
498         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
499         
500         do {
501                 _io_service.run_one ();
502         } while (ec == boost::asio::error::would_block);
503
504         if (ec) {
505                 throw NetworkError (ec.message ());
506         }
507 }
508
509 void
510 Socket::write (uint32_t v)
511 {
512         v = htonl (v);
513         write (reinterpret_cast<uint8_t*> (&v), 4);
514 }
515
516 /** Blocking read.
517  *  @param data Buffer to read to.
518  *  @param size Number of bytes to read.
519  */
520 void
521 Socket::read (uint8_t* data, int size)
522 {
523         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
524         boost::system::error_code ec = boost::asio::error::would_block;
525
526         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
527
528         do {
529                 _io_service.run_one ();
530         } while (ec == boost::asio::error::would_block);
531         
532         if (ec) {
533                 throw NetworkError (ec.message ());
534         }
535 }
536
537 uint32_t
538 Socket::read_uint32 ()
539 {
540         uint32_t v;
541         read (reinterpret_cast<uint8_t *> (&v), 4);
542         return ntohl (v);
543 }
544
545 /** Round a number up to the nearest multiple of another number.
546  *  @param c Index.
547  *  @param s Array of numbers to round, indexed by c.
548  *  @param t Multiple to round to.
549  *  @return Rounded number.
550  */
551 int
552 stride_round_up (int c, int const * stride, int t)
553 {
554         int const a = stride[c] + (t - 1);
555         return a - (a % t);
556 }
557
558 /** Read a sequence of key / value pairs from a text stream;
559  *  the keys are the first words on the line, and the values are
560  *  the remainder of the line following the key.  Lines beginning
561  *  with # are ignored.
562  *  @param s Stream to read.
563  *  @return key/value pairs.
564  */
565 multimap<string, string>
566 read_key_value (istream &s) 
567 {
568         multimap<string, string> kv;
569         
570         string line;
571         while (getline (s, line)) {
572                 if (line.empty ()) {
573                         continue;
574                 }
575
576                 if (line[0] == '#') {
577                         continue;
578                 }
579
580                 if (line[line.size() - 1] == '\r') {
581                         line = line.substr (0, line.size() - 1);
582                 }
583
584                 size_t const s = line.find (' ');
585                 if (s == string::npos) {
586                         continue;
587                 }
588
589                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
590         }
591
592         return kv;
593 }
594
595 string
596 get_required_string (multimap<string, string> const & kv, string k)
597 {
598         if (kv.count (k) > 1) {
599                 throw StringError (N_("unexpected multiple keys in key-value set"));
600         }
601
602         multimap<string, string>::const_iterator i = kv.find (k);
603         
604         if (i == kv.end ()) {
605                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
606         }
607
608         return i->second;
609 }
610
611 int
612 get_required_int (multimap<string, string> const & kv, string k)
613 {
614         string const v = get_required_string (kv, k);
615         return lexical_cast<int> (v);
616 }
617
618 float
619 get_required_float (multimap<string, string> const & kv, string k)
620 {
621         string const v = get_required_string (kv, k);
622         return lexical_cast<float> (v);
623 }
624
625 string
626 get_optional_string (multimap<string, string> const & kv, string k)
627 {
628         if (kv.count (k) > 1) {
629                 throw StringError (N_("unexpected multiple keys in key-value set"));
630         }
631
632         multimap<string, string>::const_iterator i = kv.find (k);
633         if (i == kv.end ()) {
634                 return N_("");
635         }
636
637         return i->second;
638 }
639
640 int
641 get_optional_int (multimap<string, string> const & kv, string k)
642 {
643         if (kv.count (k) > 1) {
644                 throw StringError (N_("unexpected multiple keys in key-value set"));
645         }
646
647         multimap<string, string>::const_iterator i = kv.find (k);
648         if (i == kv.end ()) {
649                 return 0;
650         }
651
652         return lexical_cast<int> (i->second);
653 }
654
655 /** Trip an assert if the caller is not in the UI thread */
656 void
657 ensure_ui_thread ()
658 {
659         assert (boost::this_thread::get_id() == ui_thread);
660 }
661
662 /** @param v Content video frame.
663  *  @param audio_sample_rate Source audio sample rate.
664  *  @param frames_per_second Number of video frames per second.
665  *  @return Equivalent number of audio frames for `v'.
666  */
667 int64_t
668 video_frames_to_audio_frames (VideoContent::Frame v, float audio_sample_rate, float frames_per_second)
669 {
670         return ((int64_t) v * audio_sample_rate / frames_per_second);
671 }
672
673 string
674 audio_channel_name (int c)
675 {
676         assert (MAX_AUDIO_CHANNELS == 6);
677
678         /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
679            enhancement channel (sub-woofer)./
680         */
681         string const channels[] = {
682                 _("Left"),
683                 _("Right"),
684                 _("Centre"),
685                 _("Lfe (sub)"),
686                 _("Left surround"),
687                 _("Right surround"),
688         };
689
690         return channels[c];
691 }
692
693 FrameRateConversion::FrameRateConversion (float source, int dcp)
694         : skip (false)
695         , repeat (false)
696         , change_speed (false)
697 {
698         if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
699                 skip = true;
700         } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
701                 repeat = true;
702         }
703
704         change_speed = !about_equal (source * factor(), dcp);
705
706         if (!skip && !repeat && !change_speed) {
707                 description = _("DCP and source have the same rate.\n");
708         } else {
709                 if (skip) {
710                         description = _("DCP will use every other frame of the source.\n");
711                 } else if (repeat) {
712                         description = _("Each source frame will be doubled in the DCP.\n");
713                 }
714
715                 if (change_speed) {
716                         float const pc = dcp * 100 / (source * factor());
717                         description += String::compose (_("DCP will run at %1%% of the source speed.\n"), pc);
718                 }
719         }
720 }
721
722 LocaleGuard::LocaleGuard ()
723         : _old (0)
724 {
725         char const * old = setlocale (LC_NUMERIC, 0);
726
727         if (old) {
728                 _old = strdup (old);
729                 if (strcmp (_old, "C")) {
730                         setlocale (LC_NUMERIC, "C");
731                 }
732         }
733 }
734
735 LocaleGuard::~LocaleGuard ()
736 {
737         setlocale (LC_NUMERIC, _old);
738         free (_old);
739 }