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