Various OSX warnings fixes.
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012-2020 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 "crypto.h"
39 #include "compose.hpp"
40 #include "audio_buffers.h"
41 #include "string_text.h"
42 #include "font.h"
43 #include "render_text.h"
44 #include "ffmpeg_image_proxy.h"
45 #include "image.h"
46 #include "text_decoder.h"
47 #include "job_manager.h"
48 #include "warnings.h"
49 #include <dcp/decrypted_kdm.h>
50 #include <dcp/locale_convert.h>
51 #include <dcp/util.h>
52 #include <dcp/raw_convert.h>
53 #include <dcp/picture_asset.h>
54 #include <dcp/sound_asset.h>
55 #include <dcp/subtitle_asset.h>
56 #include <dcp/atmos_asset.h>
57 extern "C" {
58 #include <libavfilter/avfilter.h>
59 #include <libavformat/avformat.h>
60 #include <libavcodec/avcodec.h>
61 }
62 #include <curl/curl.h>
63 #include <glib.h>
64 #include <pangomm/init.h>
65 #include <boost/algorithm/string.hpp>
66 #include <boost/range/algorithm/replace_if.hpp>
67 #include <boost/thread.hpp>
68 #include <boost/filesystem.hpp>
69 DCPOMATIC_DISABLE_WARNINGS
70 #include <boost/locale.hpp>
71 DCPOMATIC_ENABLE_WARNINGS
72 #ifdef DCPOMATIC_WINDOWS
73 #include <boost/locale.hpp>
74 #include <dbghelp.h>
75 #endif
76 #include <signal.h>
77 #include <iomanip>
78 #include <iostream>
79 #include <fstream>
80 #include <climits>
81 #include <stdexcept>
82 #ifdef DCPOMATIC_POSIX
83 #include <execinfo.h>
84 #include <cxxabi.h>
85 #endif
86
87 #include "i18n.h"
88
89 using std::string;
90 using std::wstring;
91 using std::setfill;
92 using std::ostream;
93 using std::endl;
94 using std::vector;
95 using std::min;
96 using std::max;
97 using std::map;
98 using std::list;
99 using std::multimap;
100 using std::istream;
101 using std::pair;
102 using std::cout;
103 using std::bad_alloc;
104 using std::set_terminate;
105 using std::make_pair;
106 using boost::shared_ptr;
107 using boost::thread;
108 using boost::optional;
109 using boost::lexical_cast;
110 using boost::bad_lexical_cast;
111 using boost::scoped_array;
112 using dcp::Size;
113 using dcp::raw_convert;
114 using dcp::locale_convert;
115 using namespace dcpomatic;
116
117 /** Path to our executable, required by the stacktrace stuff and filled
118  *  in during App::onInit().
119  */
120 string program_name;
121 bool is_batch_converter = false;
122 static boost::thread::id ui_thread;
123 static boost::filesystem::path backtrace_file;
124
125 /** Convert some number of seconds to a string representation
126  *  in hours, minutes and seconds.
127  *
128  *  @param s Seconds.
129  *  @return String of the form H:M:S (where H is hours, M
130  *  is minutes and S is seconds).
131  */
132 string
133 seconds_to_hms (int s)
134 {
135         int m = s / 60;
136         s -= (m * 60);
137         int h = m / 60;
138         m -= (h * 60);
139
140         char buffer[64];
141         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d", h, m, s);
142         return buffer;
143 }
144
145 string
146 time_to_hmsf (DCPTime time, Frame rate)
147 {
148         Frame f = time.frames_round (rate);
149         int s = f / rate;
150         f -= (s * rate);
151         int m = s / 60;
152         s -= m * 60;
153         int h = m / 60;
154         m -= h * 60;
155
156         char buffer[64];
157         snprintf (buffer, sizeof(buffer), "%d:%02d:%02d.%d", h, m, s, static_cast<int>(f));
158         return buffer;
159 }
160
161 /** @param s Number of seconds.
162  *  @return String containing an approximate description of s (e.g. "about 2 hours")
163  */
164 string
165 seconds_to_approximate_hms (int s)
166 {
167         int m = s / 60;
168         s -= (m * 60);
169         int h = m / 60;
170         m -= (h * 60);
171
172         string ap;
173
174         bool hours = h > 0;
175         bool minutes = h < 6 && m > 0;
176         bool seconds = h == 0 && m < 10 && s > 0;
177
178         if (m > 30 && !minutes) {
179                 /* round up the hours */
180                 ++h;
181         }
182         if (s > 30 && !seconds) {
183                 /* round up the minutes */
184                 ++m;
185                 if (m == 60) {
186                         m = 0;
187                         minutes = false;
188                         ++h;
189                 }
190         }
191
192         if (hours) {
193                 /// TRANSLATORS: h here is an abbreviation for hours
194                 ap += locale_convert<string>(h) + _("h");
195
196                 if (minutes || seconds) {
197                         ap += N_(" ");
198                 }
199         }
200
201         if (minutes) {
202                 /// TRANSLATORS: m here is an abbreviation for minutes
203                 ap += locale_convert<string>(m) + _("m");
204
205                 if (seconds) {
206                         ap += N_(" ");
207                 }
208         }
209
210         if (seconds) {
211                 /* Seconds */
212                 /// TRANSLATORS: s here is an abbreviation for seconds
213                 ap += locale_convert<string>(s) + _("s");
214         }
215
216         return ap;
217 }
218
219 double
220 seconds (struct timeval t)
221 {
222         return t.tv_sec + (double (t.tv_usec) / 1e6);
223 }
224
225 #ifdef DCPOMATIC_WINDOWS
226
227 /** Resolve symbol name and source location given the path to the executable */
228 int
229 addr2line (void const * const addr)
230 {
231         char addr2line_cmd[512] = { 0 };
232         sprintf (addr2line_cmd, "addr2line -f -p -e %.256s %p > %s", program_name.c_str(), addr, backtrace_file.string().c_str());
233         return system(addr2line_cmd);
234 }
235
236 /** This is called when C signals occur on Windows (e.g. SIGSEGV)
237  *  (NOT C++ exceptions!).  We write a backtrace to backtrace_file by dark means.
238  *  Adapted from code here: http://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c/
239  */
240 LONG WINAPI
241 exception_handler(struct _EXCEPTION_POINTERS * info)
242 {
243         FILE* f = fopen_boost (backtrace_file, "w");
244         fprintf (f, "C-style exception %d\n", info->ExceptionRecord->ExceptionCode);
245         fclose(f);
246
247         if (info->ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW) {
248                 CONTEXT* context = info->ContextRecord;
249                 SymInitialize (GetCurrentProcess (), 0, true);
250
251                 STACKFRAME frame = { 0 };
252
253                 /* setup initial stack frame */
254 #if _WIN64
255                 frame.AddrPC.Offset    = context->Rip;
256                 frame.AddrStack.Offset = context->Rsp;
257                 frame.AddrFrame.Offset = context->Rbp;
258 #else
259                 frame.AddrPC.Offset    = context->Eip;
260                 frame.AddrStack.Offset = context->Esp;
261                 frame.AddrFrame.Offset = context->Ebp;
262 #endif
263                 frame.AddrPC.Mode      = AddrModeFlat;
264                 frame.AddrStack.Mode   = AddrModeFlat;
265                 frame.AddrFrame.Mode   = AddrModeFlat;
266
267                 while (
268                         StackWalk (
269                                 IMAGE_FILE_MACHINE_I386,
270                                 GetCurrentProcess (),
271                                 GetCurrentThread (),
272                                 &frame,
273                                 context,
274                                 0,
275                                 SymFunctionTableAccess,
276                                 SymGetModuleBase,
277                                 0
278                                 )
279                         ) {
280                         addr2line((void *) frame.AddrPC.Offset);
281                 }
282         } else {
283 #ifdef _WIN64
284                 addr2line ((void *) info->ContextRecord->Rip);
285 #else
286                 addr2line ((void *) info->ContextRecord->Eip);
287 #endif
288         }
289
290         return EXCEPTION_CONTINUE_SEARCH;
291 }
292 #endif
293
294 void
295 set_backtrace_file (boost::filesystem::path p)
296 {
297         backtrace_file = p;
298 }
299
300 /** This is called when there is an unhandled exception.  Any
301  *  backtrace in this function is useless on Windows as the stack has
302  *  already been unwound from the throw; we have the gdb wrap hack to
303  *  cope with that.
304  */
305 void
306 terminate ()
307 {
308         try {
309                 static bool tried_throw = false;
310                 // try once to re-throw currently active exception
311                 if (!tried_throw) {
312                         tried_throw = true;
313                         throw;
314                 }
315         }
316         catch (const std::exception &e) {
317                 std::cerr << __FUNCTION__ << " caught unhandled exception. what(): "
318                           << e.what() << std::endl;
319         }
320         catch (...) {
321                 std::cerr << __FUNCTION__ << " caught unknown/unhandled exception."
322                           << std::endl;
323         }
324
325         abort();
326 }
327
328 void
329 dcpomatic_setup_path_encoding ()
330 {
331 #ifdef DCPOMATIC_WINDOWS
332         /* Dark voodoo which, I think, gets boost::filesystem::path to
333            correctly convert UTF-8 strings to paths, and also paths
334            back to UTF-8 strings (on path::string()).
335
336            After this, constructing boost::filesystem::paths from strings
337            converts from UTF-8 to UTF-16 inside the path.  Then
338            path::string().c_str() gives UTF-8 and
339            path::c_str()          gives UTF-16.
340
341            This is all Windows-only.  AFAICT Linux/OS X use UTF-8 everywhere,
342            so things are much simpler.
343         */
344         std::locale::global (boost::locale::generator().generate (""));
345         boost::filesystem::path::imbue (std::locale ());
346 #endif
347 }
348
349 /** Call the required functions to set up DCP-o-matic's static arrays, etc.
350  *  Must be called from the UI thread, if there is one.
351  */
352 void
353 dcpomatic_setup ()
354 {
355 #ifdef DCPOMATIC_WINDOWS
356         boost::filesystem::path p = g_get_user_config_dir ();
357         p /= "backtrace.txt";
358         set_backtrace_file (p);
359         SetUnhandledExceptionFilter(exception_handler);
360 #endif
361
362 DCPOMATIC_DISABLE_WARNINGS
363         av_register_all ();
364         avfilter_register_all ();
365 DCPOMATIC_ENABLE_WARNINGS
366
367 #ifdef DCPOMATIC_OSX
368         /* Add our library directory to the libltdl search path so that
369            xmlsec can find xmlsec1-openssl.
370         */
371         boost::filesystem::path lib = directory_containing_executable().parent_path();
372         lib /= "Frameworks";
373         setenv ("LTDL_LIBRARY_PATH", lib.c_str (), 1);
374 #endif
375
376         set_terminate (terminate);
377
378 #ifdef DCPOMATIC_WINDOWS
379         putenv ("PANGOCAIRO_BACKEND=fontconfig");
380         putenv (String::compose("FONTCONFIG_PATH=%1", shared_path().string()).c_str());
381 #endif
382
383 #ifdef DCPOMATIC_OSX
384         setenv ("PANGOCAIRO_BACKEND", "fontconfig", 1);
385         setenv ("FONTCONFIG_PATH", shared_path().string().c_str(), 1);
386 #endif
387
388         Pango::init ();
389         dcp::init ();
390
391 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
392         /* Render something to fontconfig to create its cache */
393         list<StringText> subs;
394         dcp::SubtitleString ss(
395                 optional<string>(), false, false, false, dcp::Colour(), 42, 1, dcp::Time(), dcp::Time(), 0, dcp::HALIGN_CENTER, 0, dcp::VALIGN_CENTER, dcp::DIRECTION_LTR,
396                 "Hello dolly", dcp::NONE, dcp::Colour(), dcp::Time(), dcp::Time()
397                 );
398         subs.push_back (StringText(ss, 0));
399         render_text (subs, list<shared_ptr<Font> >(), dcp::Size(640, 480), DCPTime(), 24);
400 #endif
401
402         Ratio::setup_ratios ();
403         PresetColourConversion::setup_colour_conversion_presets ();
404         DCPContentType::setup_dcp_content_types ();
405         Filter::setup_filters ();
406         CinemaSoundProcessor::setup_cinema_sound_processors ();
407         AudioProcessor::setup_audio_processors ();
408
409         curl_global_init (CURL_GLOBAL_ALL);
410
411         ui_thread = boost::this_thread::get_id ();
412 }
413
414 #ifdef DCPOMATIC_WINDOWS
415 boost::filesystem::path
416 mo_path ()
417 {
418         wchar_t buffer[512];
419         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
420         boost::filesystem::path p (buffer);
421         p = p.parent_path ();
422         p = p.parent_path ();
423         p /= "locale";
424         return p;
425 }
426 #endif
427
428 #ifdef DCPOMATIC_OSX
429 boost::filesystem::path
430 mo_path ()
431 {
432         return "DCP-o-matic 2.app/Contents/Resources";
433 }
434 #endif
435
436 void
437 dcpomatic_setup_gettext_i18n (string lang)
438 {
439 #ifdef DCPOMATIC_LINUX
440         lang += ".UTF8";
441 #endif
442
443         if (!lang.empty ()) {
444                 /* Override our environment language.  Note that the caller must not
445                    free the string passed into putenv().
446                 */
447                 string s = String::compose ("LANGUAGE=%1", lang);
448                 putenv (strdup (s.c_str ()));
449                 s = String::compose ("LANG=%1", lang);
450                 putenv (strdup (s.c_str ()));
451                 s = String::compose ("LC_ALL=%1", lang);
452                 putenv (strdup (s.c_str ()));
453         }
454
455         setlocale (LC_ALL, "");
456         textdomain ("libdcpomatic2");
457
458 #if defined(DCPOMATIC_WINDOWS) || defined(DCPOMATIC_OSX)
459         bindtextdomain ("libdcpomatic2", mo_path().string().c_str());
460         bind_textdomain_codeset ("libdcpomatic2", "UTF8");
461 #endif
462
463 #ifdef DCPOMATIC_LINUX
464         bindtextdomain ("libdcpomatic2", LINUX_LOCALE_PREFIX);
465 #endif
466 }
467
468 /** Compute a digest of the first and last `size' bytes of a set of files. */
469 string
470 digest_head_tail (vector<boost::filesystem::path> files, boost::uintmax_t size)
471 {
472         boost::scoped_array<char> buffer (new char[size]);
473         Digester digester;
474
475         /* Head */
476         boost::uintmax_t to_do = size;
477         char* p = buffer.get ();
478         int i = 0;
479         while (i < int64_t (files.size()) && to_do > 0) {
480                 FILE* f = fopen_boost (files[i], "rb");
481                 if (!f) {
482                         throw OpenFileError (files[i].string(), errno, OpenFileError::READ);
483                 }
484
485                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
486                 checked_fread (p, this_time, f, files[i]);
487                 p += this_time;
488                 to_do -= this_time;
489                 fclose (f);
490
491                 ++i;
492         }
493         digester.add (buffer.get(), size - to_do);
494
495         /* Tail */
496         to_do = size;
497         p = buffer.get ();
498         i = files.size() - 1;
499         while (i >= 0 && to_do > 0) {
500                 FILE* f = fopen_boost (files[i], "rb");
501                 if (!f) {
502                         throw OpenFileError (files[i].string(), errno, OpenFileError::READ);
503                 }
504
505                 boost::uintmax_t this_time = min (to_do, boost::filesystem::file_size (files[i]));
506                 dcpomatic_fseek (f, -this_time, SEEK_END);
507                 checked_fread (p, this_time, f, files[i]);
508                 p += this_time;
509                 to_do -= this_time;
510                 fclose (f);
511
512                 --i;
513         }
514         digester.add (buffer.get(), size - to_do);
515
516         return digester.get ();
517 }
518
519 /** Round a number up to the nearest multiple of another number.
520  *  @param c Index.
521  *  @param stride Array of numbers to round, indexed by c.
522  *  @param t Multiple to round to.
523  *  @return Rounded number.
524  */
525 int
526 stride_round_up (int c, int const * stride, int t)
527 {
528         int const a = stride[c] + (t - 1);
529         return a - (a % t);
530 }
531
532 /** Trip an assert if the caller is not in the UI thread */
533 void
534 ensure_ui_thread ()
535 {
536         DCPOMATIC_ASSERT (boost::this_thread::get_id() == ui_thread);
537 }
538
539 string
540 audio_channel_name (int c)
541 {
542         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
543
544         /// TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
545         /// enhancement channel (sub-woofer).
546         string const channels[] = {
547                 _("Left"),
548                 _("Right"),
549                 _("Centre"),
550                 _("Lfe (sub)"),
551                 _("Left surround"),
552                 _("Right surround"),
553                 _("Hearing impaired"),
554                 _("Visually impaired"),
555                 _("Left centre"),
556                 _("Right centre"),
557                 _("Left rear surround"),
558                 _("Right rear surround"),
559                 _("D-BOX primary"),
560                 _("D-BOX secondary"),
561                 _("Unused"),
562                 _("Unused")
563         };
564
565         return channels[c];
566 }
567
568 string
569 short_audio_channel_name (int c)
570 {
571         DCPOMATIC_ASSERT (MAX_DCP_AUDIO_CHANNELS == 16);
572
573         /// TRANSLATORS: these are short names of audio channels; Lfe is the low-frequency
574         /// enhancement channel (sub-woofer).  HI is the hearing-impaired audio track and
575         /// VI is the visually-impaired audio track (audio describe).  DBP is the D-BOX
576         /// primary channel and DBS is the D-BOX secondary channel.
577         string const channels[] = {
578                 _("L"),
579                 _("R"),
580                 _("C"),
581                 _("Lfe"),
582                 _("Ls"),
583                 _("Rs"),
584                 _("HI"),
585                 _("VI"),
586                 _("Lc"),
587                 _("Rc"),
588                 _("BsL"),
589                 _("BsR"),
590                 _("DBP"),
591                 _("DBS"),
592                 "",
593                 ""
594         };
595
596         return channels[c];
597 }
598
599
600 bool
601 valid_image_file (boost::filesystem::path f)
602 {
603         if (boost::starts_with (f.leaf().string(), "._")) {
604                 return false;
605         }
606
607         string ext = f.extension().string();
608         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
609         return (
610                 ext == ".tif" || ext == ".tiff" || ext == ".jpg" || ext == ".jpeg" ||
611                 ext == ".png" || ext == ".bmp" || ext == ".tga" || ext == ".dpx" ||
612                 ext == ".j2c" || ext == ".j2k" || ext == ".jp2" || ext == ".exr" ||
613                 ext == ".jpf"
614                 );
615 }
616
617 bool
618 valid_sound_file (boost::filesystem::path f)
619 {
620         if (boost::starts_with (f.leaf().string(), "._")) {
621                 return false;
622         }
623
624         string ext = f.extension().string();
625         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
626         return (ext == ".wav" || ext == ".mp3" || ext == ".aif" || ext == ".aiff");
627 }
628
629 bool
630 valid_j2k_file (boost::filesystem::path f)
631 {
632         string ext = f.extension().string();
633         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
634         return (ext == ".j2k" || ext == ".j2c" || ext == ".jp2");
635 }
636
637 string
638 tidy_for_filename (string f)
639 {
640         boost::replace_if (f, boost::is_any_of ("\\/:"), '_');
641         return f;
642 }
643
644 dcp::Size
645 fit_ratio_within (float ratio, dcp::Size full_frame)
646 {
647         if (ratio < full_frame.ratio ()) {
648                 return dcp::Size (lrintf (full_frame.height * ratio), full_frame.height);
649         }
650
651         return dcp::Size (full_frame.width, lrintf (full_frame.width / ratio));
652 }
653
654 void *
655 wrapped_av_malloc (size_t s)
656 {
657         void* p = av_malloc (s);
658         if (!p) {
659                 throw bad_alloc ();
660         }
661         return p;
662 }
663
664 map<string, string>
665 split_get_request (string url)
666 {
667         enum {
668                 AWAITING_QUESTION_MARK,
669                 KEY,
670                 VALUE
671         } state = AWAITING_QUESTION_MARK;
672
673         map<string, string> r;
674         string k;
675         string v;
676         for (size_t i = 0; i < url.length(); ++i) {
677                 switch (state) {
678                 case AWAITING_QUESTION_MARK:
679                         if (url[i] == '?') {
680                                 state = KEY;
681                         }
682                         break;
683                 case KEY:
684                         if (url[i] == '=') {
685                                 v.clear ();
686                                 state = VALUE;
687                         } else {
688                                 k += url[i];
689                         }
690                         break;
691                 case VALUE:
692                         if (url[i] == '&') {
693                                 r.insert (make_pair (k, v));
694                                 k.clear ();
695                                 state = KEY;
696                         } else {
697                                 v += url[i];
698                         }
699                         break;
700                 }
701         }
702
703         if (state == VALUE) {
704                 r.insert (make_pair (k, v));
705         }
706
707         return r;
708 }
709
710 string
711 video_asset_filename (shared_ptr<dcp::PictureAsset> asset, int reel_index, int reel_count, optional<string> summary)
712 {
713         dcp::NameFormat::Map values;
714         values['t'] = "j2c";
715         values['r'] = raw_convert<string> (reel_index + 1);
716         values['n'] = raw_convert<string> (reel_count);
717         if (summary) {
718                 values['c'] = careful_string_filter (summary.get());
719         }
720         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
721 }
722
723 string
724 audio_asset_filename (shared_ptr<dcp::SoundAsset> asset, int reel_index, int reel_count, optional<string> summary)
725 {
726         dcp::NameFormat::Map values;
727         values['t'] = "pcm";
728         values['r'] = raw_convert<string> (reel_index + 1);
729         values['n'] = raw_convert<string> (reel_count);
730         if (summary) {
731                 values['c'] = careful_string_filter (summary.get());
732         }
733         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
734 }
735
736
737 string
738 atmos_asset_filename (shared_ptr<dcp::AtmosAsset> asset, int reel_index, int reel_count, optional<string> summary)
739 {
740         dcp::NameFormat::Map values;
741         values['t'] = "atmos";
742         values['r'] = raw_convert<string> (reel_index + 1);
743         values['n'] = raw_convert<string> (reel_count);
744         if (summary) {
745                 values['c'] = careful_string_filter (summary.get());
746         }
747         return Config::instance()->dcp_asset_filename_format().get(values, "_" + asset->id() + ".mxf");
748 }
749
750
751 float
752 relaxed_string_to_float (string s)
753 {
754         try {
755                 boost::algorithm::replace_all (s, ",", ".");
756                 return lexical_cast<float> (s);
757         } catch (bad_lexical_cast &) {
758                 boost::algorithm::replace_all (s, ".", ",");
759                 return lexical_cast<float> (s);
760         }
761 }
762
763 string
764 careful_string_filter (string s)
765 {
766         /* Filter out `bad' characters which `may' cause problems with some systems (either for DCP name or filename).
767            There's no apparent list of what really is allowed, so this is a guess.
768            Safety first and all that.
769         */
770
771         wstring ws = boost::locale::conv::utf_to_utf<wchar_t>(s);
772
773         string out;
774         string const allowed = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_%.+";
775         for (size_t i = 0; i < ws.size(); ++i) {
776
777                 wchar_t c = ws[i];
778
779                 /* Remove some accents */
780                 if (wstring(L"áàâ").find(c) != string::npos) {
781                         c = 'a';
782                 }
783                 if (wstring(L"éèêë").find(c) != string::npos) {
784                         c = 'e';
785                 }
786                 if (wstring(L"ö").find(c) != string::npos) {
787                         c = 'o';
788                 }
789                 if (wstring(L"ü").find(c) != string::npos) {
790                         c = 'u';
791                 }
792
793                 if (allowed.find(c) != string::npos) {
794                         out += c;
795                 }
796         }
797
798         return boost::locale::conv::utf_to_utf<char>(out);
799 }
800
801 /** @param mapped List of mapped audio channels from a Film.
802  *  @param channels Total number of channels in the Film.
803  *  @return First: number of non-LFE soundtrack channels (L/R/C/Ls/Rs/Lc/Rc/Bsl/Bsr), second: number of LFE channels.
804  */
805 pair<int, int>
806 audio_channel_types (list<int> mapped, int channels)
807 {
808         int non_lfe = 0;
809         int lfe = 0;
810
811         BOOST_FOREACH (int i, mapped) {
812                 if (i >= channels) {
813                         /* This channel is mapped but is not included in the DCP */
814                         continue;
815                 }
816
817                 switch (static_cast<dcp::Channel>(i)) {
818                 case dcp::LFE:
819                         ++lfe;
820                         break;
821                 case dcp::LEFT:
822                 case dcp::RIGHT:
823                 case dcp::CENTRE:
824                 case dcp::LS:
825                 case dcp::RS:
826                 case dcp::LC:
827                 case dcp::RC:
828                 case dcp::BSL:
829                 case dcp::BSR:
830                         ++non_lfe;
831                         break;
832                 case dcp::HI:
833                 case dcp::VI:
834                         break;
835                 }
836         }
837
838         return make_pair (non_lfe, lfe);
839 }
840
841 shared_ptr<AudioBuffers>
842 remap (shared_ptr<const AudioBuffers> input, int output_channels, AudioMapping map)
843 {
844         shared_ptr<AudioBuffers> mapped (new AudioBuffers (output_channels, input->frames()));
845         mapped->make_silent ();
846
847         int to_do = min (map.input_channels(), input->channels());
848
849         for (int i = 0; i < to_do; ++i) {
850                 for (int j = 0; j < mapped->channels(); ++j) {
851                         if (map.get (i, static_cast<dcp::Channel> (j)) > 0) {
852                                 mapped->accumulate_channel (
853                                         input.get(),
854                                         i,
855                                         static_cast<dcp::Channel> (j),
856                                         map.get (i, static_cast<dcp::Channel> (j))
857                                         );
858                         }
859                 }
860         }
861
862         return mapped;
863 }
864
865 Eyes
866 increment_eyes (Eyes e)
867 {
868         if (e == EYES_LEFT) {
869                 return EYES_RIGHT;
870         }
871
872         return EYES_LEFT;
873 }
874
875 void
876 checked_fwrite (void const * ptr, size_t size, FILE* stream, boost::filesystem::path path)
877 {
878         size_t N = fwrite (ptr, 1, size, stream);
879         if (N != size) {
880                 if (ferror(stream)) {
881                         fclose (stream);
882                         throw FileError (String::compose("fwrite error %1", errno), path);
883                 } else {
884                         fclose (stream);
885                         throw FileError ("Unexpected short write", path);
886                 }
887         }
888 }
889
890 void
891 checked_fread (void* ptr, size_t size, FILE* stream, boost::filesystem::path path)
892 {
893         size_t N = fread (ptr, 1, size, stream);
894         if (N != size) {
895                 if (ferror(stream)) {
896                         fclose (stream);
897                         throw FileError (String::compose("fread error %1", errno), path);
898                 } else {
899                         fclose (stream);
900                         throw FileError ("Unexpected short read", path);
901                 }
902         }
903 }
904
905 size_t
906 utf8_strlen (string s)
907 {
908         size_t const len = s.length ();
909         int N = 0;
910         for (size_t i = 0; i < len; ++i) {
911                 unsigned char c = s[i];
912                 if ((c & 0xe0) == 0xc0) {
913                         ++i;
914                 } else if ((c & 0xf0) == 0xe0) {
915                         i += 2;
916                 } else if ((c & 0xf8) == 0xf0) {
917                         i += 3;
918                 }
919                 ++N;
920         }
921         return N;
922 }
923
924 string
925 day_of_week_to_string (boost::gregorian::greg_weekday d)
926 {
927         switch (d.as_enum()) {
928         case boost::date_time::Sunday:
929                 return _("Sunday");
930         case boost::date_time::Monday:
931                 return _("Monday");
932         case boost::date_time::Tuesday:
933                 return _("Tuesday");
934         case boost::date_time::Wednesday:
935                 return _("Wednesday");
936         case boost::date_time::Thursday:
937                 return _("Thursday");
938         case boost::date_time::Friday:
939                 return _("Friday");
940         case boost::date_time::Saturday:
941                 return _("Saturday");
942         }
943
944         return d.as_long_string ();
945 }
946
947 /** @param size Size of picture that the subtitle will be overlaid onto */
948 void
949 emit_subtitle_image (ContentTimePeriod period, dcp::SubtitleImage sub, dcp::Size size, shared_ptr<TextDecoder> decoder)
950 {
951         /* XXX: this is rather inefficient; decoding the image just to get its size */
952         FFmpegImageProxy proxy (sub.png_image());
953         shared_ptr<Image> image = proxy.image().image;
954         /* set up rect with height and width */
955         dcpomatic::Rect<double> rect(0, 0, image->size().width / double(size.width), image->size().height / double(size.height));
956
957         /* add in position */
958
959         switch (sub.h_align()) {
960         case dcp::HALIGN_LEFT:
961                 rect.x += sub.h_position();
962                 break;
963         case dcp::HALIGN_CENTER:
964                 rect.x += 0.5 + sub.h_position() - rect.width / 2;
965                 break;
966         case dcp::HALIGN_RIGHT:
967                 rect.x += 1 - sub.h_position() - rect.width;
968                 break;
969         }
970
971         switch (sub.v_align()) {
972         case dcp::VALIGN_TOP:
973                 rect.y += sub.v_position();
974                 break;
975         case dcp::VALIGN_CENTER:
976                 rect.y += 0.5 + sub.v_position() - rect.height / 2;
977                 break;
978         case dcp::VALIGN_BOTTOM:
979                 rect.y += 1 - sub.v_position() - rect.height;
980                 break;
981         }
982
983         decoder->emit_bitmap (period, image, rect);
984 }
985
986 bool
987 show_jobs_on_console (bool progress)
988 {
989         bool first = true;
990         bool error = false;
991         while (true) {
992
993                 dcpomatic_sleep_seconds (5);
994
995                 list<shared_ptr<Job> > jobs = JobManager::instance()->get();
996
997                 if (!first && progress) {
998                         for (size_t i = 0; i < jobs.size(); ++i) {
999                                 cout << "\033[1A\033[2K";
1000                         }
1001                         cout.flush ();
1002                 }
1003
1004                 first = false;
1005
1006                 BOOST_FOREACH (shared_ptr<Job> i, jobs) {
1007                         if (progress) {
1008                                 cout << i->name();
1009                                 if (!i->sub_name().empty()) {
1010                                         cout << "; " << i->sub_name();
1011                                 }
1012                                 cout << ": ";
1013
1014                                 if (i->progress ()) {
1015                                         cout << i->status() << "                            \n";
1016                                 } else {
1017                                         cout << ": Running           \n";
1018                                 }
1019                         }
1020
1021                         if (!progress && i->finished_in_error()) {
1022                                 /* We won't see this error if we haven't been showing progress,
1023                                    so show it now.
1024                                 */
1025                                 cout << i->status() << "\n";
1026                         }
1027
1028                         if (i->finished_in_error()) {
1029                                 error = true;
1030                         }
1031                 }
1032
1033                 if (!JobManager::instance()->work_to_do()) {
1034                         break;
1035                 }
1036         }
1037
1038         return error;
1039 }
1040
1041 /** XXX: could use mmap? */
1042 void
1043 copy_in_bits (boost::filesystem::path from, boost::filesystem::path to, boost::function<void (float)> progress)
1044 {
1045         FILE* f = fopen_boost (from, "rb");
1046         if (!f) {
1047                 throw OpenFileError (from, errno, OpenFileError::READ);
1048         }
1049         FILE* t = fopen_boost (to, "wb");
1050         if (!t) {
1051                 fclose (f);
1052                 throw OpenFileError (to, errno, OpenFileError::WRITE);
1053         }
1054
1055         /* on the order of a second's worth of copying */
1056         boost::uintmax_t const chunk = 20 * 1024 * 1024;
1057
1058         uint8_t* buffer = static_cast<uint8_t*> (malloc(chunk));
1059         if (!buffer) {
1060                 throw std::bad_alloc ();
1061         }
1062
1063         boost::uintmax_t const total = boost::filesystem::file_size (from);
1064         boost::uintmax_t remaining = total;
1065
1066         while (remaining) {
1067                 boost::uintmax_t this_time = min (chunk, remaining);
1068                 size_t N = fread (buffer, 1, chunk, f);
1069                 if (N < this_time) {
1070                         fclose (f);
1071                         fclose (t);
1072                         free (buffer);
1073                         throw ReadFileError (from, errno);
1074                 }
1075
1076                 N = fwrite (buffer, 1, this_time, t);
1077                 if (N < this_time) {
1078                         fclose (f);
1079                         fclose (t);
1080                         free (buffer);
1081                         throw WriteFileError (to, errno);
1082                 }
1083
1084                 progress (1 - float(remaining) / total);
1085                 remaining -= this_time;
1086         }
1087
1088         fclose (f);
1089         fclose (t);
1090         free (buffer);
1091 }
1092
1093 #ifdef DCPOMATIC_VARIANT_SWAROOP
1094
1095 /* Make up a key from the machine UUID */
1096 dcp::Data
1097 key_from_uuid ()
1098 {
1099         dcp::Data key (dcpomatic::crypto_key_length());
1100         memset (key.data().get(), 0, key.size());
1101         string const magic = command_and_read ("dcpomatic2_uuid");
1102         strncpy ((char *) key.data().get(), magic.c_str(), dcpomatic::crypto_key_length());
1103         return key;
1104 }
1105
1106 /* swaroop chain file format:
1107  *
1108  *  0 [int16_t] IV length
1109  *  2 [int16_t] cert #1 length, or 0 for none
1110  *  4 [int16_t] cert #2 length, or 0 for none
1111  *  6 [int16_t] cert #3 length, or 0 for none
1112  *  8 [int16_t] cert #4 length, or 0 for none
1113  * 10 [int16_t] cert #5 length, or 0 for none
1114  * 12 [int16_t] cert #6 length, or 0 for none
1115  * 14 [int16_t] cert #7 length, or 0 for none
1116  * 16 [int16_t] cert #8 length, or 0 for none
1117  * 16 [int16_t] private key length
1118  * 20 IV
1119  *    cert #1
1120  *    cert #2
1121  *    cert #3
1122  *    cert #4
1123  *    cert #5
1124  *    cert #6
1125  *    cert #7
1126  *    cert #8
1127  *    private key
1128  */
1129
1130 struct __attribute__ ((packed)) Header_ {
1131         int16_t iv_length;
1132         int16_t cert_length[8];
1133         int16_t private_key_length;
1134 };
1135
1136 typedef struct Header_ Header;
1137
1138 shared_ptr<dcp::CertificateChain>
1139 read_swaroop_chain (boost::filesystem::path path)
1140 {
1141         dcp::Data data (path);
1142         Header* header = (Header *) data.data().get();
1143         uint8_t* p = data.data().get() + sizeof(Header);
1144
1145         dcp::Data iv (p, header->iv_length);
1146         p += iv.size();
1147
1148         shared_ptr<dcp::CertificateChain> cc (new dcp::CertificateChain());
1149         for (int i = 0; i < 8; ++i) {
1150                 if (header->cert_length[i] == 0) {
1151                         break;
1152                 }
1153                 dcp::Data c(p, header->cert_length[i]);
1154                 p += c.size();
1155                 cc->add (dcp::Certificate(dcpomatic::decrypt(c, key_from_uuid(), iv)));
1156         }
1157
1158         dcp::Data k (p, header->private_key_length);
1159         cc->set_key (dcpomatic::decrypt(k, key_from_uuid(), iv));
1160         return cc;
1161 }
1162
1163 void
1164 write_swaroop_chain (shared_ptr<const dcp::CertificateChain> chain, boost::filesystem::path output)
1165 {
1166         scoped_array<uint8_t> buffer (new uint8_t[65536]);
1167         Header* header = (Header *) buffer.get();
1168         memset (header, 0, sizeof(Header));
1169         uint8_t* p = buffer.get() + sizeof(Header);
1170
1171         dcp::Data iv = dcpomatic::random_iv ();
1172         header->iv_length = iv.size ();
1173         memcpy (p, iv.data().get(), iv.size());
1174         p += iv.size();
1175
1176         int N = 0;
1177         BOOST_FOREACH (dcp::Certificate i, chain->root_to_leaf()) {
1178                 dcp::Data e = dcpomatic::encrypt (i.certificate(true), key_from_uuid(), iv);
1179                 memcpy (p, e.data().get(), e.size());
1180                 p += e.size();
1181                 DCPOMATIC_ASSERT (N < 8);
1182                 header->cert_length[N] = e.size ();
1183                 ++N;
1184         }
1185
1186         dcp::Data k = dcpomatic::encrypt (chain->key().get(), key_from_uuid(), iv);
1187         memcpy (p, k.data().get(), k.size());
1188         p += k.size();
1189         header->private_key_length = k.size ();
1190
1191         FILE* f = fopen_boost (output, "wb");
1192         checked_fwrite (buffer.get(), p - buffer.get(), f, output);
1193         fclose (f);
1194 }
1195
1196 #endif
1197
1198 double
1199 db_to_linear (double db)
1200 {
1201         return pow(10, db / 20);
1202 }
1203
1204 double
1205 linear_to_db (double linear)
1206 {
1207         return 20 * log10(linear);
1208 }
1209
1210
1211 dcp::Size
1212 scale_for_display (dcp::Size s, dcp::Size display_container, dcp::Size film_container)
1213 {
1214         /* Now scale it down if the display container is smaller than the film container */
1215         if (display_container != film_container) {
1216                 float const scale = min (
1217                         float (display_container.width) / film_container.width,
1218                         float (display_container.height) / film_container.height
1219                         );
1220
1221                 s.width = lrintf (s.width * scale);
1222                 s.height = lrintf (s.height * scale);
1223         }
1224
1225         return s;
1226 }
1227
1228
1229 dcp::DecryptedKDM
1230 decrypt_kdm_with_helpful_error (dcp::EncryptedKDM kdm)
1231 {
1232         try {
1233                 return dcp::DecryptedKDM (kdm, Config::instance()->decryption_chain()->key().get());
1234         } catch (dcp::KDMDecryptionError& e) {
1235                 /* Try to flesh out the error a bit */
1236                 string const kdm_subject_name = kdm.recipient_x509_subject_name();
1237                 bool on_chain = false;
1238                 shared_ptr<const dcp::CertificateChain> dc = Config::instance()->decryption_chain();
1239                 BOOST_FOREACH (dcp::Certificate i, dc->root_to_leaf()) {
1240                         if (i.subject() == kdm_subject_name) {
1241                                 on_chain = true;
1242                         }
1243                 }
1244                 if (!on_chain) {
1245                         throw KDMError (_("This KDM was not made for DCP-o-matic's decryption certificate."), e.what());
1246                 } else if (on_chain && kdm_subject_name != dc->leaf().subject()) {
1247                         throw KDMError (_("This KDM was made for DCP-o-matic but not for its leaf certificate."), e.what());
1248                 } else {
1249                         throw;
1250                 }
1251         }
1252 }
1253