Put av_register_all() in the right place.
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 /** @file src/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include "util.h"
26 #include "exceptions.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 "digester.h"
37 #include "audio_processor.h"
38 #include "compose.hpp"
39 #include <dcp/locale_convert.h>
40 #include <dcp/util.h>
41 #include <dcp/raw_convert.h>
42 #include <dcp/picture_asset.h>
43 #include <dcp/sound_asset.h>
44 #include <dcp/subtitle_asset.h>
45 extern "C" {
46 #include <libavfilter/avfilter.h>
47 #include <libavformat/avformat.h>
48 #include <libavcodec/avcodec.h>
49 }
50 #include <curl/curl.h>
51 #ifdef DCPOMATIC_GRAPHICS_MAGICK
52 #include <Magick++.h>
53 #endif
54 #include <glib.h>
55 #include <pangomm/init.h>
56 #include <boost/algorithm/string.hpp>
57 #include <boost/range/algorithm/replace_if.hpp>
58 #include <boost/thread.hpp>
59 #include <boost/filesystem.hpp>
60 #ifdef DCPOMATIC_WINDOWS
61 #include <boost/locale.hpp>
62 #include <dbghelp.h>
63 #endif
64 #include <signal.h>
65 #include <iomanip>
66 #include <iostream>
67 #include <fstream>
68 #include <climits>
69 #include <stdexcept>
70 #ifdef DCPOMATIC_POSIX
71 #include <execinfo.h>
72 #include <cxxabi.h>
73 #endif
74
75 #include "i18n.h"
76
77 using std::string;
78 using std::setfill;
79 using std::ostream;
80 using std::endl;
81 using std::vector;
82 using std::min;
83 using std::max;
84 using std::map;
85 using std::list;
86 using std::multimap;
87 using std::istream;
88 using std::pair;
89 using std::cout;
90 using std::bad_alloc;
91 using std::set_terminate;
92 using std::make_pair;
93 using boost::shared_ptr;
94 using boost::thread;
95 using boost::optional;
96 using boost::lexical_cast;
97 using boost::bad_lexical_cast;
98 using dcp::Size;
99 using dcp::raw_convert;
100 using dcp::locale_convert;
101
102 /** Path to our executable, required by the stacktrace stuff and filled
103  *  in during App::onInit().
104  */
105 string program_name;
106 static boost::thread::id ui_thread;
107 static boost::filesystem::path backtrace_file;
108
109 /** Convert some number of seconds to a string representation
110  *  in hours, minutes and seconds.
111  *
112  *  @param s Seconds.
113  *  @return String of the form H:M:S (where H is hours, M
114  *  is minutes and S is seconds).
115  */
116 string
117 seconds_to_hms (int s)
118 {
119         int m = s / 60;
120         s -= (m * 60);
121         int h = m / 60;
122         m -= (h * 60);
123
124         char buffer[64];
125         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
126         return buffer;
127 }
128
129 /** @param s Number of seconds.
130  *  @return String containing an approximate description of s (e.g. "about 2 hours")
131  */
132 string
133 seconds_to_approximate_hms (int s)
134 {
135         int m = s / 60;
136         s -= (m * 60);
137         int h = m / 60;
138         m -= (h * 60);
139
140         string ap;
141
142         bool const hours = h > 0;
143         bool const minutes = h < 6 && m > 0;
144         bool const seconds = h == 0 && m < 10 && s > 0;
145
146         if (hours) {
147                 if (m > 30 && !minutes) {
148                         /// TRANSLATORS: h here is an abbreviation for hours
149                         ap += locale_convert<string>(h + 1) + _("h");
150                 } else {
151                         /// TRANSLATORS: h here is an abbreviation for hours
152                         ap += locale_convert<string>(h) + _("h");
153                 }
154
155                 if (minutes || seconds) {
156                         ap += N_(" ");
157                 }
158         }
159
160         if (minutes) {
161                 /* Minutes */
162                 if (s > 30 && !seconds) {
163                         /// TRANSLATORS: m here is an abbreviation for minutes
164                         ap += locale_convert<string>(m + 1) + _("m");
165                 } else {
166                         /// TRANSLATORS: m here is an abbreviation for minutes
167                         ap += locale_convert<string>(m) + _("m");
168                 }
169
170                 if (seconds) {
171                         ap += N_(" ");
172                 }
173         }
174
175         if (seconds) {
176                 /* Seconds */
177                 /// TRANSLATORS: s here is an abbreviation for seconds
178                 ap += locale_convert<string>(s) + _("s");
179         }
180
181         return ap;
182 }
183
184 double
185 seconds (struct timeval t)
186 {
187         return t.tv_sec + (double (t.tv_usec) / 1e6);
188 }
189
190 #ifdef DCPOMATIC_WINDOWS
191
192 /** Resolve symbol name and source location given the path to the executable */
193 int
194 addr2line (void const * const addr)
195 {
196         char addr2line_cmd[512] = { 0 };
197         sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
198         return system(addr2line_cmd);
199 }
200
201 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
202  *  (NOT C++ exceptions!).  We write a backtrace to backtrace_file by dark means.
203  *  Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
204  */
205 LONG WINAPI
206 exception_handler(struct _EXCEPTION_POINTERS * info)
207 {
208         FILE* f = fopen_boost (backtrace_file, "w");
209         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
210         fclose(f);
211
212         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
213                 CONTEXT* context = info->ContextRecord;
214                 SymInitialize (GetCurrentProcess (), 0, true);
215
216                 STACKFRAME frame = { 0 };
217
218                 /* setup initial stack frame */
219 #if _WIN64
220                 frame.AddrPC.Offset    = context->Rip;
221                 frame.AddrStack.Offset = context->Rsp;
222                 frame.AddrFrame.Offset = context->Rbp;
223 #else
224                 frame.AddrPC.Offset    = context->Eip;
225                 frame.AddrStack.Offset = context->Esp;
226                 frame.AddrFrame.Offset = context->Ebp;
227 #endif
228                 frame.AddrPC.Mode      = AddrModeFlat;
229                 frame.AddrStack.Mode   = AddrModeFlat;
230                 frame.AddrFrame.Mode   = AddrModeFlat;
231
232                 while (
233                         StackWalk (
234                                 IMAGE_FILE_MACHINE_I386,
235                                 GetCurrentProcess (),
236                                 GetCurrentThread (),
237                                 &frame,
238                                 context,
239                                 0,
240                                 SymFunctionTableAccess,
241                                 SymGetModuleBase,
242                                 0
243                                 )
244                         ) {
245                         addr2line((void *) frame.AddrPC.Offset);
246                 }
247         } else {
248 #ifdef _WIN64
249                 addr2line ((void *) info->ContextRecord->Rip);
250 #else
251                 addr2line ((void *) info->ContextRecord->Eip);
252 #endif
253         }
254
255         return EXCEPTION_CONTINUE_SEARCH;
256 }
257 #endif
258
259 void
260 set_backtrace_file (boost::filesystem::path p)
261 {
262         backtrace_file = p;
263 }
264
265 /** This is called when there is an unhandled exception.  Any
266  *  backtrace in this function is useless on Windows as the stack has
267  *  already been unwound from the throw; we have the gdb wrap hack to
268  *  cope with that.
269  */
270 void
271 terminate ()
272 {
273         try {
274                 static bool tried_throw = false;
275                 // try once to re-throw currently active exception
276                 if (!tried_throw) {
277                         tried_throw = true;
278                         throw;
279                 }
280         }
281         catch (const std::exception &e) {
282                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
283                           << e.what() << std::endl;
284         }
285         catch (...) {
286                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
287                           << std::endl;
288         }
289
290         abort();
291 }
292
293 void
294 dcpomatic_setup_path_encoding ()
295 {
296 #ifdef DCPOMATIC_WINDOWS
297         /* Dark voodoo which, I think, gets boost::filesystem::path to
298            correctly convert UTF-8 strings to paths, and also paths
299            back to UTF-8 strings (on path::string()).
300
301            After this, constructing boost::filesystem::paths from strings
302            converts from UTF-8 to UTF-16 inside the path.  Then
303            path::string().c_str() gives UTF-8 and
304            path::c_str()          gives UTF-16.
305
306            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
307            so things are much simpler.
308         */
309         std::locale::global (boost::locale::generator().generate (""));
310         boost::filesystem::path::imbue (std::locale ());
311 #endif
312 }
313
314 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
315  *  Must be called from the UI thread, if there is one.
316  */
317 void
318 dcpomatic_setup ()
319 {
320 #ifdef DCPOMATIC_WINDOWS
321         boost::filesystem::path p = g_get_user_config_dir ();
322         p /= "backtrace.txt";
323         set_backtrace_file (p);
324         SetUnhandledExceptionFilter(exception_handler);
325 #endif
326
327         av_register_all ();
328         avfilter_register_all ();
329
330 #ifdef DCPOMATIC_OSX
331         /* Add our lib directory to the libltdl search path so that
332            xmlsec can find xmlsec1-openssl.
333         */
334         boost::filesystem::path lib = app_contents ();
335         lib /= "lib";
336         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
337 #endif
338
339         set_terminate (terminate);
340
341         Pango::init ();
342         dcp::init ();
343
344         Ratio::setup_ratios ();
345         PresetColourConversion::setup_colour_conversion_presets ();
346         VideoContentScale::setup_scales ();
347         DCPContentType::setup_dcp_content_types ();
348         Filter::setup_filters ();
349         CinemaSoundProcessor::setup_cinema_sound_processors ();
350         AudioProcessor::setup_audio_processors ();
351
352         curl_global_init (CURL_GLOBAL_ALL);
353
354 #ifdef DCPOMATIC_GRAPHICS_MAGICK
355         Magick::InitializeMagick (0);
356 #endif
357
358         ui_thread = boost::this_thread::get_id ();
359 }
360
361 #ifdef DCPOMATIC_WINDOWS
362 boost::filesystem::path
363 mo_path ()
364 {
365         wchar_t buffer[512];
366         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
367         boost::filesystem::path p (buffer);
368         p = p.parent_path ();
369         p = p.parent_path ();
370         p /= "locale";
371         return p;
372 }
373 #endif
374
375 #ifdef DCPOMATIC_OSX
376 boost::filesystem::path
377 mo_path ()
378 {
379         return "DCP-o-matic 2.app/Contents/Resources";
380 }
381 #endif
382
383 void
384 dcpomatic_setup_gettext_i18n (string lang)
385 {
386 #ifdef DCPOMATIC_LINUX
387         lang += ".UTF8";
388 #endif
389
390         if (!lang.empty ()) {
391                 /* Override our environment language.  Note that the caller must not
392                    free the string passed into putenv().
393                 */
394                 string s = String::compose ("LANGUAGE=%1", lang);
395                 putenv (strdup (s.c_str ()));
396                 s = String::compose ("LANG=%1", lang);
397                 putenv (strdup (s.c_str ()));
398                 s = String::compose ("LC_ALL=%1", lang);
399                 putenv (strdup (s.c_str ()));
400         }
401
402         setlocale (LC_ALL, "");
403         textdomain ("libdcpomatic2");
404
405 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
406         bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
407         bind_textdomain_codeset ("libdcpomatic2", "UTF8");
408 #endif
409
410 #ifdef DCPOMATIC_LINUX
411         bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
412 #endif
413 }
414
415 /** Compute a digest of the first and last `size' bytes of a set of files. */
416 string
417 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
418 {
419         boost::scoped_array<char> buffer (new char[size]);
420         Digester digester;
421
422         /* Head */
423         boost::uintmax_t to_do = size;
424         char* p = buffer.get ();
425         int i = 0;
426         while (i < int64_t (files.size()) && to_do > 0) {
427                 FILE* f = fopen_boost (files[i], "rb");
428                 if (!f) {
429                         throw OpenFileError (files[i].string(), errno, true);
430                 }
431
432                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
433                 fread (p, 1, this_time, f);
434                 p += this_time;
435                 to_do -= this_time;
436                 fclose (f);
437
438                 ++i;
439         }
440         digester.add (buffer.get(), size - to_do);
441
442         /* Tail */
443         to_do = size;
444         p = buffer.get ();
445         i = files.size() - 1;
446         while (i >= 0 && to_do > 0) {
447                 FILE* f = fopen_boost (files[i], "rb");
448                 if (!f) {
449                         throw OpenFileError (files[i].string(), errno, true);
450                 }
451
452                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
453                 dcpomatic_fseek (f, -this_time, SEEK_END);
454                 fread (p, 1, this_time, f);
455                 p += this_time;
456                 to_do -= this_time;
457                 fclose (f);
458
459                 --i;
460         }
461         digester.add (buffer.get(), size - to_do);
462
463         return digester.get ();
464 }
465
466 /** Round a number up to the nearest multiple of another number.
467  *  @param c Index.
468  *  @param stride Array of numbers to round, indexed by c.
469  *  @param t Multiple to round to.
470  *  @return Rounded number.
471  */
472 int
473 stride_round_up (int c, int const * stride, int t)
474 {
475         int const a = stride[c] + (t - 1);
476         return a - (a % t);
477 }
478
479 /** Trip an assert if the caller is not in the UI thread */
480 void
481 ensure_ui_thread ()
482 {
483         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
484 }
485
486 string
487 audio_channel_name (int c)
488 {
489         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
490
491         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
492         /// enhancement channel (sub-woofer).
493         string const channels[] = {
494                 _("Left"),
495                 _("Right"),
496                 _("Centre"),
497                 _("Lfe (sub)"),
498                 _("Left surround"),
499                 _("Right surround"),
500                 _("Hearing impaired"),
501                 _("Visually impaired"),
502                 _("Left centre"),
503                 _("Right centre"),
504                 _("Left rear surround"),
505                 _("Right rear surround"),
506                 _("D-BOX primary"),
507                 _("D-BOX secondary"),
508                 _("Unused"),
509                 _("Unused")
510         };
511
512         return channels[c];
513 }
514
515 string
516 short_audio_channel_name (int c)
517 {
518         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
519
520         /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
521         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
522         /// VI is the visually-impaired audio track (audio describe).  DBP is the D-BOX
523         /// primary channel and DBS is the D-BOX secondary channel.
524         string const channels[] = {
525                 _("L"),
526                 _("R"),
527                 _("C"),
528                 _("Lfe"),
529                 _("Ls"),
530                 _("Rs"),
531                 _("HI"),
532                 _("VI"),
533                 _("Lc"),
534                 _("Rc"),
535                 _("BsL"),
536                 _("BsR"),
537                 _("DBP"),
538                 _("DBS"),
539                 "",
540                 ""
541         };
542
543         return channels[c];
544 }
545
546
547 bool
548 valid_image_file (boost::filesystem::path f)
549 {
550         if (boost::starts_with (f.leaf().string(), "._")) {
551                 return false;
552         }
553
554         string ext = f.extension().string();
555         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
556         return (
557                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
558                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
559                 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
560                 );
561 }
562
563 bool
564 valid_sound_file (boost::filesystem::path f)
565 {
566         if (boost::starts_with (f.leaf().string(), "._")) {
567                 return false;
568         }
569
570         string ext = f.extension().string();
571         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
572         return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
573 }
574
575 bool
576 valid_j2k_file (boost::filesystem::path f)
577 {
578         string ext = f.extension().string();
579         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
580         return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
581 }
582
583 string
584 tidy_for_filename (string f)
585 {
586         boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
587         return f;
588 }
589
590 dcp::Size
591 fit_ratio_within (float ratio, dcp::Size full_frame)
592 {
593         if (ratio < full_frame.ratio ()) {
594                 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
595         }
596
597         return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
598 }
599
600 void *
601 wrapped_av_malloc (size_t s)
602 {
603         void* p = av_malloc (s);
604         if (!p) {
605                 throw bad_alloc ();
606         }
607         return p;
608 }
609
610 map<string, string>
611 split_get_request (string url)
612 {
613         enum {
614                 AWAITING_QUESTION_MARK,
615                 KEY,
616                 VALUE
617         } state = AWAITING_QUESTION_MARK;
618
619         map<string, string> r;
620         string k;
621         string v;
622         for (size_t i = 0; i < url.length(); ++i) {
623                 switch (state) {
624                 case AWAITING_QUESTION_MARK:
625                         if (url[i] == '?') {
626                                 state = KEY;
627                         }
628                         break;
629                 case KEY:
630                         if (url[i] == '=') {
631                                 v.clear ();
632                                 state = VALUE;
633                         } else {
634                                 k += url[i];
635                         }
636                         break;
637                 case VALUE:
638                         if (url[i] == '&') {
639                                 r.insert (make_pair (k, v));
640                                 k.clear ();
641                                 state = KEY;
642                         } else {
643                                 v += url[i];
644                         }
645                         break;
646                 }
647         }
648
649         if (state == VALUE) {
650                 r.insert (make_pair (k, v));
651         }
652
653         return r;
654 }
655
656 string
657 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
658 {
659         dcp::NameFormat::Map values;
660         values['t'] = "j2c";
661         values['r'] = raw_convert<string> (reel_index + 1);
662         values['n'] = raw_convert<string> (reel_count);
663         if (summary) {
664                 values['c'] = careful_string_filter (summary.get());
665         }
666         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
667 }
668
669 string
670 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
671 {
672         dcp::NameFormat::Map values;
673         values['t'] = "pcm";
674         values['r'] = raw_convert<string> (reel_index + 1);
675         values['n'] = raw_convert<string> (reel_count);
676         if (summary) {
677                 values['c'] = careful_string_filter (summary.get());
678         }
679         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
680 }
681
682 float
683 relaxed_string_to_float (string s)
684 {
685         try {
686                 boost::algorithm::replace_all (s, ",", ".");
687                 return lexical_cast<float> (s);
688         } catch (bad_lexical_cast) {
689                 boost::algorithm::replace_all (s, ".", ",");
690                 return lexical_cast<float> (s);
691         }
692 }
693
694 string
695 careful_string_filter (string s)
696 {
697         /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
698            There's no apparent list of what really is allowed, so this is a guess.
699            Safety first and all that.
700         */
701
702         string out;
703         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.";
704         for (size_t i = 0; i < s.size(); ++i) {
705                 if (allowed.find (s[i]) != string::npos) {
706                         out += s[i];
707                 }
708         }
709
710         return out;
711 }
712
713 /** @param mapped List of mapped audio channels from a Film.
714  *  @param channels Total number of channels in the Film.
715  *  @return First: number of non-LFE channels, second: number of LFE channels.
716  */
717 pair<int, int>
718 audio_channel_types (list<int> mapped, int channels)
719 {
720         int non_lfe = 0;
721         int lfe = 0;
722
723         BOOST_FOREACH (int i, mapped) {
724                 if (i >= channels) {
725                         /* This channel is mapped but is not included in the DCP */
726                         continue;
727                 }
728
729                 if (static_cast<dcp::Channel> (i) == dcp::LFE) {
730                         ++lfe;
731                 } else {
732                         ++non_lfe;
733                 }
734         }
735
736         return make_pair (non_lfe, lfe);
737 }