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