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