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