0a6f381db8adf23cd7c8028e3dd2cc624f49d575
[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 /** Compute a digest of the first and last `size' bytes of a set of files. */
421 string
422 md5_digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
423 {
424         boost::scoped_array<char> buffer (new char[size]);
425         MD5Digester digester;
426
427         /* Head */
428         boost::uintmax_t to_do = size;
429         char* p = buffer.get ();
430         int i = 0;
431         while (i < int64_t (files.size()) && to_do > 0) {
432                 FILE* f = fopen_boost (files[i], "rb");
433                 if (!f) {
434                         throw OpenFileError (files[i].string());
435                 }
436
437                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
438                 fread (p, 1, this_time, f);
439                 p += this_time;
440                 to_do -= this_time;
441                 fclose (f);
442
443                 ++i;
444         }
445         digester.add (buffer.get(), size - to_do);
446
447         /* Tail */
448         to_do = size;
449         p = buffer.get ();
450         i = files.size() - 1;
451         while (i >= 0 && to_do > 0) {
452                 FILE* f = fopen_boost (files[i], "rb");
453                 if (!f) {
454                         throw OpenFileError (files[i].string());
455                 }
456
457                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
458                 fseek (f, -this_time, SEEK_END);
459                 fread (p, 1, this_time, f);
460                 p += this_time;
461                 to_do -= this_time;
462                 fclose (f);
463
464                 --i;
465         }               
466         digester.add (buffer.get(), size - to_do);
467
468         return digester.get ();
469 }
470
471 /** @param An arbitrary audio frame rate.
472  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
473  */
474 int
475 dcp_audio_frame_rate (int fs)
476 {
477         if (fs <= 48000) {
478                 return 48000;
479         }
480
481         return 96000;
482 }
483
484 Socket::Socket (int timeout)
485         : _deadline (_io_service)
486         , _socket (_io_service)
487         , _acceptor (0)
488         , _timeout (timeout)
489 {
490         _deadline.expires_at (boost::posix_time::pos_infin);
491         check ();
492 }
493
494 Socket::~Socket ()
495 {
496         delete _acceptor;
497 }
498
499 void
500 Socket::check ()
501 {
502         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
503                 if (_acceptor) {
504                         _acceptor->cancel ();
505                 } else {
506                         _socket.close ();
507                 }
508                 _deadline.expires_at (boost::posix_time::pos_infin);
509         }
510
511         _deadline.async_wait (boost::bind (&Socket::check, this));
512 }
513
514 /** Blocking connect.
515  *  @param endpoint End-point to connect to.
516  */
517 void
518 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
519 {
520         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
521         boost::system::error_code ec = boost::asio::error::would_block;
522         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
523         do {
524                 _io_service.run_one();
525         } while (ec == boost::asio::error::would_block);
526
527         if (ec) {
528                 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
529         }
530
531         if (!_socket.is_open ()) {
532                 throw NetworkError (_("connect timed out"));
533         }
534 }
535
536 void
537 Socket::accept (int port)
538 {
539         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
540         
541         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
542         boost::system::error_code ec = boost::asio::error::would_block;
543         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
544         do {
545                 _io_service.run_one ();
546         } while (ec == boost::asio::error::would_block);
547
548         delete _acceptor;
549         _acceptor = 0;
550         
551         if (ec) {
552                 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
553         }
554 }
555
556 /** Blocking write.
557  *  @param data Buffer to write.
558  *  @param size Number of bytes to write.
559  */
560 void
561 Socket::write (uint8_t const * data, int size)
562 {
563         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
564         boost::system::error_code ec = boost::asio::error::would_block;
565
566         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
567         
568         do {
569                 _io_service.run_one ();
570         } while (ec == boost::asio::error::would_block);
571
572         if (ec) {
573                 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
574         }
575 }
576
577 void
578 Socket::write (uint32_t v)
579 {
580         v = htonl (v);
581         write (reinterpret_cast<uint8_t*> (&v), 4);
582 }
583
584 /** Blocking read.
585  *  @param data Buffer to read to.
586  *  @param size Number of bytes to read.
587  */
588 void
589 Socket::read (uint8_t* data, int size)
590 {
591         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
592         boost::system::error_code ec = boost::asio::error::would_block;
593
594         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
595
596         do {
597                 _io_service.run_one ();
598         } while (ec == boost::asio::error::would_block);
599         
600         if (ec) {
601                 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
602         }
603 }
604
605 uint32_t
606 Socket::read_uint32 ()
607 {
608         uint32_t v;
609         read (reinterpret_cast<uint8_t *> (&v), 4);
610         return ntohl (v);
611 }
612
613 /** Round a number up to the nearest multiple of another number.
614  *  @param c Index.
615  *  @param s Array of numbers to round, indexed by c.
616  *  @param t Multiple to round to.
617  *  @return Rounded number.
618  */
619 int
620 stride_round_up (int c, int const * stride, int t)
621 {
622         int const a = stride[c] + (t - 1);
623         return a - (a % t);
624 }
625
626 /** @param n A number.
627  *  @param r Rounding `boundary' (must be a power of 2)
628  *  @return n rounded to the nearest r
629  */
630 int
631 round_to (float n, int r)
632 {
633         DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
634         return int (n + float(r) / 2) &~ (r - 1);
635 }
636
637 /** Trip an assert if the caller is not in the UI thread */
638 void
639 ensure_ui_thread ()
640 {
641         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
642 }
643
644 string
645 audio_channel_name (int c)
646 {
647         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
648
649         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
650         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
651         /// VI is the visually-impaired audio track (audio describe).
652         string const channels[] = {
653                 _("Left"),
654                 _("Right"),
655                 _("Centre"),
656                 _("Lfe (sub)"),
657                 _("Left surround"),
658                 _("Right surround"),
659                 _("Hearing impaired"),
660                 _("Visually impaired"),
661                 _("Left centre"),
662                 _("Right centre"),
663                 _("Left rear surround"),
664                 _("Right rear surround"),
665         };
666
667         return channels[c];
668 }
669
670 bool
671 valid_image_file (boost::filesystem::path f)
672 {
673         string ext = f.extension().string();
674         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
675         return (
676                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
677                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
678                 ext == ".j2c" || ext == ".j2k"
679                 );
680 }
681
682 bool
683 valid_j2k_file (boost::filesystem::path f)
684 {
685         string ext = f.extension().string();
686         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
687         return (ext == ".j2k" || ext == ".j2c");
688 }
689
690 string
691 tidy_for_filename (string f)
692 {
693         string t;
694         for (size_t i = 0; i < f.length(); ++i) {
695                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
696                         t += f[i];
697                 } else {
698                         t += '_';
699                 }
700         }
701
702         return t;
703 }
704
705 dcp::Size
706 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
707 {
708         if (ratio < full_frame.ratio ()) {
709                 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
710         }
711         
712         return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
713 }
714
715 void *
716 wrapped_av_malloc (size_t s)
717 {
718         void* p = av_malloc (s);
719         if (!p) {
720                 throw bad_alloc ();
721         }
722         return p;
723 }
724                 
725 /** Return a user-readable string summarising the versions of our dependencies */
726 string
727 dependency_version_summary ()
728 {
729         SafeStringStream s;
730         s << N_("libopenjpeg ") << opj_version () << N_(", ")
731           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
732           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
733           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
734           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
735           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
736           << MagickVersion << N_(", ")
737           << N_("libssh ") << ssh_version (0) << N_(", ")
738           << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
739
740         return s.str ();
741 }
742
743 ContentTimePeriod
744 subtitle_period (AVSubtitle const & sub)
745 {
746         ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
747
748         ContentTimePeriod period (
749                 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
750                 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
751                 );
752
753         return period;
754 }