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