Small fixes and tidy-ups spotted by cppcheck.
[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         try {
291                 static bool tried_throw = false;
292                 // try once to re-throw currently active exception
293                 if (!tried_throw) {
294                         tried_throw = true;
295                         throw;
296                 }
297         }
298         catch (const std::exception &e) {
299                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
300                           << e.what() << std::endl;
301         }
302         catch (...) {
303                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception." 
304                           << std::endl;
305         }
306
307         abort();
308 }
309
310 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
311  *  Must be called from the UI thread, if there is one.
312  */
313 void
314 dcpomatic_setup ()
315 {
316 #ifdef DCPOMATIC_WINDOWS
317         boost::filesystem::path p = g_get_user_config_dir ();
318         p /= "backtrace.txt";
319         set_backtrace_file (p);
320         SetUnhandledExceptionFilter(exception_handler);
321
322         /* Dark voodoo which, I think, gets boost::filesystem::path to
323            correctly convert UTF-8 strings to paths, and also paths
324            back to UTF-8 strings (on path::string()).
325
326            After this, constructing boost::filesystem::paths from strings
327            converts from UTF-8 to UTF-16 inside the path.  Then
328            path::string().c_str() gives UTF-8 and
329            path::c_str()          gives UTF-16.
330
331            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
332            so things are much simpler.
333         */
334         std::locale::global (boost::locale::generator().generate (""));
335         boost::filesystem::path::imbue (std::locale ());
336 #endif  
337         
338         avfilter_register_all ();
339
340 #ifdef DCPOMATIC_OSX
341         /* Add our lib directory to the libltdl search path so that
342            xmlsec can find xmlsec1-openssl.
343         */
344         boost::filesystem::path lib = app_contents ();
345         lib /= "lib";
346         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
347 #endif
348
349         set_terminate (terminate);
350
351         Pango::init ();
352         dcp::init ();
353         
354         Ratio::setup_ratios ();
355         VideoContentScale::setup_scales ();
356         DCPContentType::setup_dcp_content_types ();
357         Scaler::setup_scalers ();
358         Filter::setup_filters ();
359         CinemaSoundProcessor::setup_cinema_sound_processors ();
360         AudioProcessor::setup_audio_processors ();
361
362         ui_thread = boost::this_thread::get_id ();
363 }
364
365 #ifdef DCPOMATIC_WINDOWS
366 boost::filesystem::path
367 mo_path ()
368 {
369         wchar_t buffer[512];
370         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
371         boost::filesystem::path p (buffer);
372         p = p.parent_path ();
373         p = p.parent_path ();
374         p /= "locale";
375         return p;
376 }
377 #endif
378
379 #ifdef DCPOMATIC_OSX
380 boost::filesystem::path
381 mo_path ()
382 {
383         return "DCP-o-matic 2.app/Contents/Resources";
384 }
385 #endif
386
387 void
388 dcpomatic_setup_gettext_i18n (string lang)
389 {
390 #ifdef DCPOMATIC_LINUX
391         lang += ".UTF8";
392 #endif
393
394         if (!lang.empty ()) {
395                 /* Override our environment language.  Note that the caller must not
396                    free the string passed into putenv().
397                 */
398                 string s = String::compose ("LANGUAGE=%1", lang);
399                 putenv (strdup (s.c_str ()));
400                 s = String::compose ("LANG=%1", lang);
401                 putenv (strdup (s.c_str ()));
402                 s = String::compose ("LC_ALL=%1", lang);
403                 putenv (strdup (s.c_str ()));
404         }
405
406         setlocale (LC_ALL, "");
407         textdomain ("libdcpomatic");
408
409 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
410         bindtextdomain ("libdcpomatic", mo_path().string().c_str());
411         bind_textdomain_codeset ("libdcpomatic", "UTF8");
412 #endif  
413
414 #ifdef DCPOMATIC_LINUX
415         bindtextdomain ("libdcpomatic", POSIX_LOCALE_PREFIX);
416 #endif
417 }
418
419 /** Compute a digest of the first and last `size' bytes of a set of files. */
420 string
421 md5_digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
422 {
423         boost::scoped_array<char> buffer (new char[size]);
424         MD5Digester digester;
425
426         /* Head */
427         boost::uintmax_t to_do = size;
428         char* p = buffer.get ();
429         int i = 0;
430         while (i < int64_t (files.size()) && to_do > 0) {
431                 FILE* f = fopen_boost (files[i], "rb");
432                 if (!f) {
433                         throw OpenFileError (files[i].string());
434                 }
435
436                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
437                 fread (p, 1, this_time, f);
438                 p += this_time;
439                 to_do -= this_time;
440                 fclose (f);
441
442                 ++i;
443         }
444         digester.add (buffer.get(), size - to_do);
445
446         /* Tail */
447         to_do = size;
448         p = buffer.get ();
449         i = files.size() - 1;
450         while (i >= 0 && to_do > 0) {
451                 FILE* f = fopen_boost (files[i], "rb");
452                 if (!f) {
453                         throw OpenFileError (files[i].string());
454                 }
455
456                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
457                 fseek (f, -this_time, SEEK_END);
458                 fread (p, 1, this_time, f);
459                 p += this_time;
460                 to_do -= this_time;
461                 fclose (f);
462
463                 --i;
464         }               
465         digester.add (buffer.get(), size - to_do);
466
467         return digester.get ();
468 }
469
470 /** @param An arbitrary audio frame rate.
471  *  @return The appropriate DCP-approved frame rate (48kHz or 96kHz).
472  */
473 int
474 dcp_audio_frame_rate (int fs)
475 {
476         if (fs <= 48000) {
477                 return 48000;
478         }
479
480         return 96000;
481 }
482
483 Socket::Socket (int timeout)
484         : _deadline (_io_service)
485         , _socket (_io_service)
486         , _acceptor (0)
487         , _timeout (timeout)
488 {
489         _deadline.expires_at (boost::posix_time::pos_infin);
490         check ();
491 }
492
493 Socket::~Socket ()
494 {
495         delete _acceptor;
496 }
497
498 void
499 Socket::check ()
500 {
501         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
502                 if (_acceptor) {
503                         _acceptor->cancel ();
504                 } else {
505                         _socket.close ();
506                 }
507                 _deadline.expires_at (boost::posix_time::pos_infin);
508         }
509
510         _deadline.async_wait (boost::bind (&Socket::check, this));
511 }
512
513 /** Blocking connect.
514  *  @param endpoint End-point to connect to.
515  */
516 void
517 Socket::connect (boost::asio::ip::tcp::endpoint endpoint)
518 {
519         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
520         boost::system::error_code ec = boost::asio::error::would_block;
521         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
522         do {
523                 _io_service.run_one();
524         } while (ec == boost::asio::error::would_block);
525
526         if (ec) {
527                 throw NetworkError (String::compose (_("error during async_connect (%1)"), ec.value ()));
528         }
529
530         if (!_socket.is_open ()) {
531                 throw NetworkError (_("connect timed out"));
532         }
533 }
534
535 void
536 Socket::accept (int port)
537 {
538         _acceptor = new boost::asio::ip::tcp::acceptor (_io_service, boost::asio::ip::tcp::endpoint (boost::asio::ip::tcp::v4(), port));
539         
540         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
541         boost::system::error_code ec = boost::asio::error::would_block;
542         _acceptor->async_accept (_socket, boost::lambda::var(ec) = boost::lambda::_1);
543         do {
544                 _io_service.run_one ();
545         } while (ec == boost::asio::error::would_block);
546
547         delete _acceptor;
548         _acceptor = 0;
549         
550         if (ec) {
551                 throw NetworkError (String::compose (_("error during async_accept (%1)"), ec.value ()));
552         }
553 }
554
555 /** Blocking write.
556  *  @param data Buffer to write.
557  *  @param size Number of bytes to write.
558  */
559 void
560 Socket::write (uint8_t const * data, int size)
561 {
562         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
563         boost::system::error_code ec = boost::asio::error::would_block;
564
565         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
566         
567         do {
568                 _io_service.run_one ();
569         } while (ec == boost::asio::error::would_block);
570
571         if (ec) {
572                 throw NetworkError (String::compose (_("error during async_write (%1)"), ec.value ()));
573         }
574 }
575
576 void
577 Socket::write (uint32_t v)
578 {
579         v = htonl (v);
580         write (reinterpret_cast<uint8_t*> (&v), 4);
581 }
582
583 /** Blocking read.
584  *  @param data Buffer to read to.
585  *  @param size Number of bytes to read.
586  */
587 void
588 Socket::read (uint8_t* data, int size)
589 {
590         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
591         boost::system::error_code ec = boost::asio::error::would_block;
592
593         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
594
595         do {
596                 _io_service.run_one ();
597         } while (ec == boost::asio::error::would_block);
598         
599         if (ec) {
600                 throw NetworkError (String::compose (_("error during async_read (%1)"), ec.value ()));
601         }
602 }
603
604 uint32_t
605 Socket::read_uint32 ()
606 {
607         uint32_t v;
608         read (reinterpret_cast<uint8_t *> (&v), 4);
609         return ntohl (v);
610 }
611
612 /** Round a number up to the nearest multiple of another number.
613  *  @param c Index.
614  *  @param s Array of numbers to round, indexed by c.
615  *  @param t Multiple to round to.
616  *  @return Rounded number.
617  */
618 int
619 stride_round_up (int c, int const * stride, int t)
620 {
621         int const a = stride[c] + (t - 1);
622         return a - (a % t);
623 }
624
625 /** @param n A number.
626  *  @param r Rounding `boundary' (must be a power of 2)
627  *  @return n rounded to the nearest r
628  */
629 int
630 round_to (float n, int r)
631 {
632         DCPOMATIC_ASSERT (r == 1 || r == 2 || r == 4);
633         return int (n + float(r) / 2) &~ (r - 1);
634 }
635
636 /** Trip an assert if the caller is not in the UI thread */
637 void
638 ensure_ui_thread ()
639 {
640         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
641 }
642
643 string
644 audio_channel_name (int c)
645 {
646         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 12);
647
648         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
649         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
650         /// VI is the visually-impaired audio track (audio describe).
651         string const channels[] = {
652                 _("Left"),
653                 _("Right"),
654                 _("Centre"),
655                 _("Lfe (sub)"),
656                 _("Left surround"),
657                 _("Right surround"),
658                 _("Hearing impaired"),
659                 _("Visually impaired"),
660                 _("Left centre"),
661                 _("Right centre"),
662                 _("Left rear surround"),
663                 _("Right rear surround"),
664         };
665
666         return channels[c];
667 }
668
669 bool
670 valid_image_file (boost::filesystem::path f)
671 {
672         string ext = f.extension().string();
673         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
674         return (
675                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
676                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
677                 ext == ".j2c" || ext == ".j2k"
678                 );
679 }
680
681 bool
682 valid_j2k_file (boost::filesystem::path f)
683 {
684         string ext = f.extension().string();
685         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
686         return (ext == ".j2k" || ext == ".j2c");
687 }
688
689 string
690 tidy_for_filename (string f)
691 {
692         string t;
693         for (size_t i = 0; i < f.length(); ++i) {
694                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
695                         t += f[i];
696                 } else {
697                         t += '_';
698                 }
699         }
700
701         return t;
702 }
703
704 dcp::Size
705 fit_ratio_within (float ratio, dcp::Size full_frame, int round)
706 {
707         if (ratio < full_frame.ratio ()) {
708                 return dcp::Size (round_to (full_frame.height * ratio, round), full_frame.height);
709         }
710         
711         return dcp::Size (full_frame.width, round_to (full_frame.width / ratio, round));
712 }
713
714 void *
715 wrapped_av_malloc (size_t s)
716 {
717         void* p = av_malloc (s);
718         if (!p) {
719                 throw bad_alloc ();
720         }
721         return p;
722 }
723                 
724 /** Return a user-readable string summarising the versions of our dependencies */
725 string
726 dependency_version_summary ()
727 {
728         SafeStringStream s;
729         s << N_("libopenjpeg ") << opj_version () << N_(", ")
730           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
731           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
732           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
733           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
734           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
735           << MagickVersion << N_(", ")
736           << N_("libssh ") << ssh_version (0) << N_(", ")
737           << N_("libdcp ") << dcp::version << N_(" git ") << dcp::git_commit;
738
739         return s.str ();
740 }
741
742 ContentTimePeriod
743 subtitle_period (AVSubtitle const & sub)
744 {
745         ContentTime const packet_time = ContentTime::from_seconds (static_cast<double> (sub.pts) / AV_TIME_BASE);
746
747         ContentTimePeriod period (
748                 packet_time + ContentTime::from_seconds (sub.start_display_time / 1e3),
749                 packet_time + ContentTime::from_seconds (sub.end_display_time / 1e3)
750                 );
751
752         return period;
753 }