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