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