c0e32b778669ce3b9f810d5d46ac4c188a3e067d
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 /** @file src/lib/util.cc
21  *  @brief Some utility functions and classes.
22  */
23
24 #include "util.h"
25 #include "exceptions.h"
26 #include "scaler.h"
27 #include "dcp_content_type.h"
28 #include "filter.h"
29 #include "cinema_sound_processor.h"
30 #include "config.h"
31 #include "ratio.h"
32 #include "job.h"
33 #include "cross.h"
34 #include "video_content.h"
35 #include "rect.h"
36 #include "md5_digester.h"
37 #include "audio_processor.h"
38 #include "safe_stringstream.h"
39 #include <dcp/version.h>
40 #include <dcp/util.h>
41 #include <dcp/signer.h>
42 #include <dcp/raw_convert.h>
43 extern "C" {
44 #include <libavcodec/avcodec.h>
45 #include <libavformat/avformat.h>
46 #include <libswscale/swscale.h>
47 #include <libavfilter/avfiltergraph.h>
48 #include <libavutil/pixfmt.h>
49 }
50 #include <glib.h>
51 #include <openjpeg.h>
52 #include <pangomm/init.h>
53 #ifdef DCPOMATIC_IMAGE_MAGICK
54 #include <magick/MagickCore.h>
55 #else
56 #include <magick/common.h>
57 #include <magick/magick_config.h>
58 #endif
59 #include <magick/version.h>
60 #include <libssh/libssh.h>
61 #include <boost/algorithm/string.hpp>
62 #include <boost/bind.hpp>
63 #include <boost/lambda/lambda.hpp>
64 #include <boost/thread.hpp>
65 #include <boost/filesystem.hpp>
66 #ifdef DCPOMATIC_WINDOWS
67 #include <boost/locale.hpp>
68 #include <dbghelp.h>
69 #endif
70 #include <signal.h>
71 #include <iomanip>
72 #include <iostream>
73 #include <fstream>
74 #include <climits>
75 #include <stdexcept>
76 #ifdef DCPOMATIC_POSIX
77 #include <execinfo.h>
78 #include <cxxabi.h>
79 #endif
80
81 #include "i18n.h"
82
83 using std::string;
84 using std::setfill;
85 using std::ostream;
86 using std::endl;
87 using std::vector;
88 using std::min;
89 using std::max;
90 using std::list;
91 using std::multimap;
92 using std::istream;
93 using std::pair;
94 using std::cout;
95 using std::bad_alloc;
96 using std::set_terminate;
97 using boost::shared_ptr;
98 using boost::thread;
99 using boost::optional;
100 using dcp::Size;
101 using dcp::raw_convert;
102
103 /** Path to our executable, required by the stacktrace stuff and filled
104  *  in during App::onInit().
105  */
106 string program_name;
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 << setfill ('0') << m << N_(":");
129         hms.width (2);
130         hms << 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                         /// TRANSLATORS: h here is an abbreviation for hours
155                         ap << (h + 1) << _("h");
156                 } else {
157                         /// TRANSLATORS: h here is an abbreviation for hours
158                         ap << h << _("h");
159                 }
160
161                 if (minutes | seconds) {
162                         ap << N_(" ");
163                 }
164         }
165
166         if (minutes) {
167                 /* Minutes */
168                 if (s > 30 && !seconds) {
169                         /// TRANSLATORS: m here is an abbreviation for minutes
170                         ap << (m + 1) << _("m");
171                 } else {
172                         /// TRANSLATORS: m here is an abbreviation for minutes
173                         ap << m << _("m");
174                 }
175
176                 if (seconds) {
177                         ap << N_(" ");
178                 }
179         }
180
181         if (seconds) {
182                 /* Seconds */
183                 /// TRANSLATORS: s here is an abbreviation for seconds
184                 ap << s << _("s");
185         }
186
187         return ap.str ();
188 }
189
190 /** @param v Version as used by FFmpeg.
191  *  @return A string representation of v.
192  */
193 static string
194 ffmpeg_version_to_string (int v)
195 {
196         SafeStringStream s;
197         s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
198         return s.str ();
199 }
200
201 double
202 seconds (struct timeval t)
203 {
204         return t.tv_sec + (double (t.tv_usec) / 1e6);
205 }
206
207 #ifdef DCPOMATIC_WINDOWS
208
209 /** Resolve symbol name and source location given the path to the executable */
210 int
211 addr2line (void const * const addr)
212 {
213         char addr2line_cmd[512] = { 0 };
214         sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str()); 
215         return system(addr2line_cmd);
216 }
217
218 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
219  *  (NOT C++ exceptions!).  We write a backtrace to backtrace_file by dark means.
220  *  Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
221  */
222 LONG WINAPI
223 exception_handler(struct _EXCEPTION_POINTERS * info)
224 {
225         FILE* f = fopen_boost (backtrace_file, "w");
226         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
227         fclose(f);
228         
229         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
230                 CONTEXT* context = info->ContextRecord;
231                 SymInitialize (GetCurrentProcess (), 0, true);
232                 
233                 STACKFRAME frame = { 0 };
234                 
235                 /* setup initial stack frame */
236 #if _WIN64
237                 frame.AddrPC.Offset    = context->Rip;
238                 frame.AddrStack.Offset = context->Rsp;
239                 frame.AddrFrame.Offset = context->Rbp;
240 #else  
241                 frame.AddrPC.Offset    = context->Eip;
242                 frame.AddrStack.Offset = context->Esp;
243                 frame.AddrFrame.Offset = context->Ebp;
244 #endif
245                 frame.AddrPC.Mode      = AddrModeFlat;
246                 frame.AddrStack.Mode   = AddrModeFlat;
247                 frame.AddrFrame.Mode   = AddrModeFlat;
248                 
249                 while (
250                         StackWalk (
251                                 IMAGE_FILE_MACHINE_I386,
252                                 GetCurrentProcess (),
253                                 GetCurrentThread (),
254                                 &frame,
255                                 context,
256                                 0,
257                                 SymFunctionTableAccess,
258                                 SymGetModuleBase,
259                                 0
260                                 )
261                         ) {
262                         addr2line((void *) frame.AddrPC.Offset);
263                 }
264         } else {
265 #ifdef _WIN64          
266                 addr2line ((void *) info->ContextRecord->Rip);
267 #else          
268                 addr2line ((void *) info->ContextRecord->Eip);
269 #endif         
270         }
271         
272         return EXCEPTION_CONTINUE_SEARCH;
273 }
274 #endif
275
276 void
277 set_backtrace_file (boost::filesystem::path p)
278 {
279         backtrace_file = p;
280 }
281
282 /** This is called when there is an unhandled exception.  Any
283  *  backtrace in this function is useless on Windows as the stack has
284  *  already been unwound from the throw; we have the gdb wrap hack to
285  *  cope with that.
286  */
287 void
288 terminate ()
289 {
290         static bool tried_throw = false;
291
292         try {
293                 // try once to re-throw currently active exception
294                 if (!tried_throw) {
295                         tried_throw = true;
296                         throw;
297                 }
298         }
299         catch (const std::exception &e) {
300                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
301                           << e.what() << std::endl;
302         }
303         catch (...) {
304                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception." 
305                           << std::endl;
306         }
307
308         abort();
309 }
310
311 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
312  *  Must be called from the UI thread, if there is one.
313  */
314 void
315 dcpomatic_setup ()
316 {
317 #ifdef DCPOMATIC_WINDOWS
318         boost::filesystem::path p = g_get_user_config_dir ();
319         p /= "backtrace.txt";
320         set_backtrace_file (p);
321         SetUnhandledExceptionFilter(exception_handler);
322
323         /* Dark voodoo which, I think, gets boost::filesystem::path to
324            correctly convert UTF-8 strings to paths, and also paths
325            back to UTF-8 strings (on path::string()).
326
327            After this, constructing boost::filesystem::paths from strings
328            converts from UTF-8 to UTF-16 inside the path.  Then
329            path::string().c_str() gives UTF-8 and
330            path::c_str()          gives UTF-16.
331
332            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
333            so things are much simpler.
334         */
335         std::locale::global (boost::locale::generator().generate (""));
336         boost::filesystem::path::imbue (std::locale ());
337 #endif  
338         
339         avfilter_register_all ();
340
341 #ifdef DCPOMATIC_OSX
342         /* Add our lib directory to the libltdl search path so that
343            xmlsec can find xmlsec1-openssl.
344         */
345         boost::filesystem::path lib = app_contents ();
346         lib /= "lib";
347         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
348 #endif
349
350         set_terminate (terminate);
351
352         Pango::init ();
353         dcp::init ();
354         
355         Ratio::setup_ratios ();
356         VideoContentScale::setup_scales ();
357         DCPContentType::setup_dcp_content_types ();
358         Scaler::setup_scalers ();
359         Filter::setup_filters ();
360         CinemaSoundProcessor::setup_cinema_sound_processors ();
361         AudioProcessor::setup_audio_processors ();
362
363         ui_thread = boost::this_thread::get_id ();
364 }
365
366 #ifdef DCPOMATIC_WINDOWS
367 boost::filesystem::path
368 mo_path ()
369 {
370         wchar_t buffer[512];
371         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
372         boost::filesystem::path p (buffer);
373         p = p.parent_path ();
374         p = p.parent_path ();
375         p /= "locale";
376         return p;
377 }
378 #endif
379
380 #ifdef DCPOMATIC_OSX
381 boost::filesystem::path
382 mo_path ()
383 {
384         return "DCP-o-matic 2.app/Contents/Resources";
385 }
386 #endif
387
388 void
389 dcpomatic_setup_gettext_i18n (string lang)
390 {
391 #ifdef DCPOMATIC_LINUX
392         lang += ".UTF8";
393 #endif
394
395         if (!lang.empty ()) {
396                 /* Override our environment language.  Note that the caller must not
397                    free the string passed into putenv().
398                 */
399                 string s = String::compose ("LANGUAGE=%1", lang);
400                 putenv (strdup (s.c_str ()));
401                 s = String::compose ("LANG=%1", lang);
402                 putenv (strdup (s.c_str ()));
403                 s = String::compose ("LC_ALL=%1", lang);
404                 putenv (strdup (s.c_str ()));
405         }
406
407         setlocale (LC_ALL, "");
408         textdomain ("libdcpomatic");
409
410 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
411         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
412         bind_textdomain_codeset ("libdcpomatic", "UTF8");
413 #endif  
414
415 #ifdef DCPOMATIC_LINUX
416         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
417 #endif
418 }
419
420 /** @param job Optional job for which to report progress */
421 string
422 md5_digest (vector<boost::filesystem::path> files, shared_ptr<Job> job)
423 {
424         boost::uintmax_t const buffer_size = 64 * 1024;
425         char buffer[buffer_size];
426
427         MD5Digester digester;
428
429         vector<int64_t> sizes;
430         for (size_t i = 0; i < files.size(); ++i) {
431                 sizes.push_back (boost::filesystem::file_size (files[i]));
432         }
433
434         for (size_t i = 0; i < files.size(); ++i) {
435                 FILE* f = fopen_boost (files[i], "rb");
436                 if (!f) {
437                         throw OpenFileError (files[i].string());
438                 }
439
440                 boost::uintmax_t const bytes = boost::filesystem::file_size (files[i]);
441                 boost::uintmax_t remaining = bytes;
442
443                 while (remaining > 0) {
444                         int const t = min (remaining, buffer_size);
445                         int const r = fread (buffer, 1, t, f);
446                         if (r != t) {
447                                 throw ReadFileError (files[i], errno);
448                         }
449                         digester.add (buffer, t);
450                         remaining -= t;
451
452                         if (job) {
453                                 job->set_progress ((float (i) + 1 - float(remaining) / bytes) / files.size ());
454                         }
455                 }
456
457                 fclose (f);
458         }
459
460         return digester.get ();
461 }
462
463 /** @param An arbitrary audio frame rate.
464  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
465  */
466 int
467 dcp_audio_frame_rate (int fs)
468 {
469         if (fs <= 48000) {
470                 return 48000;
471         }
472
473         return 96000;
474 }
475
476 Socket::Socket (int timeout)
477         : _deadline (_io_service)
478         , _socket (_io_service)
479         , _acceptor (0)
480         , _timeout (timeout)
481 {
482         _deadline.expires_at (boost::posix_time::pos_infin);
483         check ();
484 }
485
486 Socket::~Socket ()
487 {
488         delete _acceptor;
489 }
490
491 void
492 Socket::check ()
493 {
494         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
495                 if (_acceptor) {
496                         _acceptor->cancel ();
497                 } else {
498                         _socket.close ();
499                 }
500                 _deadline.expires_at (boost::posix_time::pos_infin);
501         }
502
503         _deadline.async_wait (boost::bind (&Socket::check, this));
504 }
505
506 /** Blocking connect.
507  *  @param endpoint End-point to connect to.
508  */
509 void
510 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
511 {
512         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
513         boost::system::error_code ec = boost::asio::error::would_block;
514         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
515         do {
516                 _io_service.run_one();
517         } while (ec == boost::asio::error::would_block);
518
519         if (ec) {
520                 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
521         }
522
523         if (!_socket.is_open ()) {
524                 throw NetworkError (_("connect timed out"));
525         }
526 }
527
528 void
529 Socket::accept (int port)
530 {
531         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
532         
533         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
534         boost::system::error_code ec = boost::asio::error::would_block;
535         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
536         do {
537                 _io_service.run_one ();
538         } while (ec == boost::asio::error::would_block);
539
540         delete _acceptor;
541         _acceptor = 0;
542         
543         if (ec) {
544                 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
545         }
546 }
547
548 /** Blocking write.
549  *  @param data Buffer to write.
550  *  @param size Number of bytes to write.
551  */
552 void
553 Socket::write (uint8_t const * data, int size)
554 {
555         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
556         boost::system::error_code ec = boost::asio::error::would_block;
557
558         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
559         
560         do {
561                 _io_service.run_one ();
562         } while (ec == boost::asio::error::would_block);
563
564         if (ec) {
565                 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
566         }
567 }
568
569 void
570 Socket::write (uint32_t v)
571 {
572         v = htonl (v);
573         write (reinterpret_cast<uint8_t*> (&v), 4);
574 }
575
576 /** Blocking read.
577  *  @param data Buffer to read to.
578  *  @param size Number of bytes to read.
579  */
580 void
581 Socket::read (uint8_t* data, int size)
582 {
583         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
584         boost::system::error_code ec = boost::asio::error::would_block;
585
586         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
587
588         do {
589                 _io_service.run_one ();
590         } while (ec == boost::asio::error::would_block);
591         
592         if (ec) {
593                 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
594         }
595 }
596
597 uint32_t
598 Socket::read_uint32 ()
599 {
600         uint32_t v;
601         read (reinterpret_cast<uint8_t *> (&v), 4);
602         return ntohl (v);
603 }
604
605 /** Round a number up to the nearest multiple of another number.
606  *  @param c Index.
607  *  @param s Array of numbers to round, indexed by c.
608  *  @param t Multiple to round to.
609  *  @return Rounded number.
610  */
611 int
612 stride_round_up (int c, int const * stride, int t)
613 {
614         int const a = stride[c] + (t - 1);
615         return a - (a % t);
616 }
617
618 /** @param n A number.
619  *  @param r Rounding `boundary' (must be a power of 2)
620  *  @return n rounded to the nearest r
621  */
622 int
623 round_to (float n, int r)
624 {
625         DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
626         return int (n + float(r) / 2) &~ (r - 1);
627 }
628
629 /** Trip an assert if the caller is not in the UI thread */
630 void
631 ensure_ui_thread ()
632 {
633         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
634 }
635
636 string
637 audio_channel_name (int c)
638 {
639         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
640
641         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
642         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
643         /// VI is the visually-impaired audio track (audio describe).
644         string const channels[] = {
645                 _("Left"),
646                 _("Right"),
647                 _("Centre"),
648                 _("Lfe (sub)"),
649                 _("Left surround"),
650                 _("Right surround"),
651                 _("Hearing impaired"),
652                 _("Visually impaired"),
653                 _("Left centre"),
654                 _("Right centre"),
655                 _("Left rear surround"),
656                 _("Right rear surround"),
657         };
658
659         return channels[c];
660 }
661
662 bool
663 valid_image_file (boost::filesystem::path f)
664 {
665         string ext = f.extension().string();
666         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
667         return (
668                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
669                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
670                 ext == ".j2c" || ext == ".j2k"
671                 );
672 }
673
674 bool
675 valid_j2k_file (boost::filesystem::path f)
676 {
677         string ext = f.extension().string();
678         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
679         return (ext == ".j2k" || ext == ".j2c");
680 }
681
682 string
683 tidy_for_filename (string f)
684 {
685         string t;
686         for (size_t i = 0; i < f.length(); ++i) {
687                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
688                         t += f[i];
689                 } else {
690                         t += '_';
691                 }
692         }
693
694         return t;
695 }
696
697 dcp::Size
698 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
699 {
700         if (ratio < full_frame.ratio ()) {
701                 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
702         }
703         
704         return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
705 }
706
707 void *
708 wrapped_av_malloc (size_t s)
709 {
710         void* p = av_malloc (s);
711         if (!p) {
712                 throw bad_alloc ();
713         }
714         return p;
715 }
716                 
717 /** Return a user-readable string summarising the versions of our dependencies */
718 string
719 dependency_version_summary ()
720 {
721         SafeStringStream s;
722         s << N_("libopenjpeg ") << opj_version () << N_(", ")
723           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
724           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
725           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
726           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
727           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
728           << MagickVersion << N_(", ")
729           << N_("libssh ") << ssh_version (0) << N_(", ")
730           << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
731
732         return s.str ();
733 }
734
735 ContentTimePeriod
736 subtitle_period (AVSubtitle const & sub)
737 {
738         ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
739
740         ContentTimePeriod period (
741                 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
742                 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
743                 );
744
745         return period;
746 }