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