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