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