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