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