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