Replace incorrect uses of raw_convert with a new locale_convert.
[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 "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
98 /** Path to our executable, required by the stacktrace stuff and filled
99  *  in during App::onInit().
100  */
101 string program_name;
102 static boost::thread::id ui_thread;
103 static boost::filesystem::path backtrace_file;
104
105 /** Convert some number of seconds to a string representation
106  *  in hours, minutes and seconds.
107  *
108  *  @param s Seconds.
109  *  @return String of the form H:M:S (where H is hours, M
110  *  is minutes and S is seconds).
111  */
112 string
113 seconds_to_hms (int s)
114 {
115         int m = s / 60;
116         s -= (m * 60);
117         int h = m / 60;
118         m -= (h * 60);
119
120         char buffer[64];
121         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
122         return buffer;
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         string ap;
137
138         bool const hours = h > 0;
139         bool const minutes = h < 6 && m > 0;
140         bool const seconds = h == 0 && m < 10 && s > 0;
141
142         if (hours) {
143                 if (m > 30 && !minutes) {
144                         /// TRANSLATORS: h here is an abbreviation for hours
145                         ap += locale_convert<string>(h + 1) + _("h");
146                 } else {
147                         /// TRANSLATORS: h here is an abbreviation for hours
148                         ap += locale_convert<string>(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 += locale_convert<string>(m + 1) + _("m");
161                 } else {
162                         /// TRANSLATORS: m here is an abbreviation for minutes
163                         ap += locale_convert<string>(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 += locale_convert<string>(s) + _("s");
175         }
176
177         return ap;
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 #ifdef DCPOMATIC_GRAPHICS_MAGICK
350         Magick::InitializeMagick (0);
351 #endif
352
353         ui_thread = boost::this_thread::get_id ();
354 }
355
356 #ifdef DCPOMATIC_WINDOWS
357 boost::filesystem::path
358 mo_path ()
359 {
360         wchar_t buffer[512];
361         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
362         boost::filesystem::path p (buffer);
363         p = p.parent_path ();
364         p = p.parent_path ();
365         p /= "locale";
366         return p;
367 }
368 #endif
369
370 #ifdef DCPOMATIC_OSX
371 boost::filesystem::path
372 mo_path ()
373 {
374         return "DCP-o-matic 2.app/Contents/Resources";
375 }
376 #endif
377
378 void
379 dcpomatic_setup_gettext_i18n (string lang)
380 {
381 #ifdef DCPOMATIC_LINUX
382         lang += ".UTF8";
383 #endif
384
385         if (!lang.empty ()) {
386                 /* Override our environment language.  Note that the caller must not
387                    free the string passed into putenv().
388                 */
389                 string s = String::compose ("LANGUAGE=%1", lang);
390                 putenv (strdup (s.c_str ()));
391                 s = String::compose ("LANG=%1", lang);
392                 putenv (strdup (s.c_str ()));
393                 s = String::compose ("LC_ALL=%1", lang);
394                 putenv (strdup (s.c_str ()));
395         }
396
397         setlocale (LC_ALL, "");
398         textdomain ("libdcpomatic2");
399
400 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
401         bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
402         bind_textdomain_codeset ("libdcpomatic2", "UTF8");
403 #endif
404
405 #ifdef DCPOMATIC_LINUX
406         bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
407 #endif
408 }
409
410 /** Compute a digest of the first and last `size' bytes of a set of files. */
411 string
412 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
413 {
414         boost::scoped_array<char> buffer (new char[size]);
415         Digester digester;
416
417         /* Head */
418         boost::uintmax_t to_do = size;
419         char* p = buffer.get ();
420         int i = 0;
421         while (i < int64_t (files.size()) && to_do > 0) {
422                 FILE* f = fopen_boost (files[i], "rb");
423                 if (!f) {
424                         throw OpenFileError (files[i].string());
425                 }
426
427                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
428                 fread (p, 1, this_time, f);
429                 p += this_time;
430                 to_do -= this_time;
431                 fclose (f);
432
433                 ++i;
434         }
435         digester.add (buffer.get(), size - to_do);
436
437         /* Tail */
438         to_do = size;
439         p = buffer.get ();
440         i = files.size() - 1;
441         while (i >= 0 && to_do > 0) {
442                 FILE* f = fopen_boost (files[i], "rb");
443                 if (!f) {
444                         throw OpenFileError (files[i].string());
445                 }
446
447                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
448                 dcpomatic_fseek (f, -this_time, SEEK_END);
449                 fread (p, 1, this_time, f);
450                 p += this_time;
451                 to_do -= this_time;
452                 fclose (f);
453
454                 --i;
455         }
456         digester.add (buffer.get(), size - to_do);
457
458         return digester.get ();
459 }
460
461 /** Round a number up to the nearest multiple of another number.
462  *  @param c Index.
463  *  @param s Array of numbers to round, indexed by c.
464  *  @param t Multiple to round to.
465  *  @return Rounded number.
466  */
467 int
468 stride_round_up (int c, int const * stride, int t)
469 {
470         int const a = stride[c] + (t - 1);
471         return a - (a % t);
472 }
473
474 /** Trip an assert if the caller is not in the UI thread */
475 void
476 ensure_ui_thread ()
477 {
478         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
479 }
480
481 string
482 audio_channel_name (int c)
483 {
484         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
485
486         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
487         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
488         /// VI is the visually-impaired audio track (audio describe).
489         string const channels[] = {
490                 _("Left"),
491                 _("Right"),
492                 _("Centre"),
493                 _("Lfe (sub)"),
494                 _("Left surround"),
495                 _("Right surround"),
496                 _("Hearing impaired"),
497                 _("Visually impaired"),
498                 _("Left centre"),
499                 _("Right centre"),
500                 _("Left rear surround"),
501                 _("Right rear surround"),
502                 _("D-BOX primary"),
503                 _("D-BOX secondary"),
504                 _("Unused"),
505                 _("Unused")
506         };
507
508         return channels[c];
509 }
510
511 bool
512 valid_image_file (boost::filesystem::path f)
513 {
514         if (boost::starts_with (f.leaf().string(), "._")) {
515                 return false;
516         }
517
518         string ext = f.extension().string();
519         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
520         return (
521                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
522                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
523                 ext == ".j2c" || ext == ".j2k" || ext == ".jp2"
524                 );
525 }
526
527 bool
528 valid_j2k_file (boost::filesystem::path f)
529 {
530         string ext = f.extension().string();
531         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
532         return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
533 }
534
535 string
536 tidy_for_filename (string f)
537 {
538         string t;
539         for (size_t i = 0; i < f.length(); ++i) {
540                 if (isalnum (f[i]) || f[i] == '_' || f[i] == '-') {
541                         t += f[i];
542                 } else {
543                         t += '_';
544                 }
545         }
546
547         return t;
548 }
549
550 dcp::Size
551 fit_ratio_within (float ratio, dcp::Size full_frame)
552 {
553         if (ratio < full_frame.ratio ()) {
554                 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
555         }
556
557         return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
558 }
559
560 void *
561 wrapped_av_malloc (size_t s)
562 {
563         void* p = av_malloc (s);
564         if (!p) {
565                 throw bad_alloc ();
566         }
567         return p;
568 }
569
570 map<string, string>
571 split_get_request (string url)
572 {
573         enum {
574                 AWAITING_QUESTION_MARK,
575                 KEY,
576                 VALUE
577         } state = AWAITING_QUESTION_MARK;
578
579         map<string, string> r;
580         string k;
581         string v;
582         for (size_t i = 0; i < url.length(); ++i) {
583                 switch (state) {
584                 case AWAITING_QUESTION_MARK:
585                         if (url[i] == '?') {
586                                 state = KEY;
587                         }
588                         break;
589                 case KEY:
590                         if (url[i] == '=') {
591                                 v.clear ();
592                                 state = VALUE;
593                         } else {
594                                 k += url[i];
595                         }
596                         break;
597                 case VALUE:
598                         if (url[i] == '&') {
599                                 r.insert (make_pair (k, v));
600                                 k.clear ();
601                                 state = KEY;
602                         } else {
603                                 v += url[i];
604                         }
605                         break;
606                 }
607         }
608
609         if (state == VALUE) {
610                 r.insert (make_pair (k, v));
611         }
612
613         return r;
614 }
615
616 string
617 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
618 {
619         dcp::NameFormat::Map values;
620         values['t'] = "j2c";
621         values['i'] = asset->id();
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) + ".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['i'] = asset->id();
636         values['r'] = raw_convert<string> (reel_index + 1);
637         values['n'] = raw_convert<string> (reel_count);
638         if (summary) {
639                 values['c'] = summary.get();
640         }
641         return Config::instance()->dcp_asset_filename_format().get(values) + ".mxf";
642 }
643
644 float
645 relaxed_string_to_float (string s)
646 {
647         try {
648                 boost::algorithm::replace_all (s, ",", ".");
649                 return lexical_cast<float> (s);
650         } catch (bad_lexical_cast) {
651                 boost::algorithm::replace_all (s, ".", ",");
652                 return lexical_cast<float> (s);
653         }
654 }
655
656 bool
657 string_not_empty (string s)
658 {
659         return !s.empty ();
660 }