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