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