Bump version
[dcpomatic.git] / src / lib / util.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3     Copyright (C) 2000-2007 Paul Davis
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 /** @file src/lib/util.cc
22  *  @brief Some utility functions and classes.
23  */
24
25 #include <sstream>
26 #include <iomanip>
27 #include <iostream>
28 #include <fstream>
29 #include <climits>
30 #ifdef DVDOMATIC_POSIX
31 #include <execinfo.h>
32 #include <cxxabi.h>
33 #endif
34 #include <libssh/libssh.h>
35 #include <signal.h>
36 #include <boost/algorithm/string.hpp>
37 #include <boost/bind.hpp>
38 #include <boost/lambda/lambda.hpp>
39 #include <boost/lexical_cast.hpp>
40 #include <boost/thread.hpp>
41 #include <boost/filesystem.hpp>
42 #include <openjpeg.h>
43 #include <openssl/md5.h>
44 #include <magick/MagickCore.h>
45 #include <magick/version.h>
46 #include <libdcp/version.h>
47 extern "C" {
48 #include <libavcodec/avcodec.h>
49 #include <libavformat/avformat.h>
50 #include <libswscale/swscale.h>
51 #include <libavfilter/avfiltergraph.h>
52 #include <libpostproc/postprocess.h>
53 #include <libavutil/pixfmt.h>
54 }
55 #include "util.h"
56 #include "exceptions.h"
57 #include "scaler.h"
58 #include "format.h"
59 #include "dcp_content_type.h"
60 #include "filter.h"
61 #include "sound_processor.h"
62 #include "config.h"
63
64 #include "i18n.h"
65
66 using std::cout;
67 using std::string;
68 using std::stringstream;
69 using std::list;
70 using std::ostream;
71 using std::vector;
72 using std::ifstream;
73 using std::istream;
74 using std::min;
75 using std::max;
76 using std::multimap;
77 using std::pair;
78 using boost::shared_ptr;
79 using boost::lexical_cast;
80 using boost::optional;
81 using libdcp::Size;
82
83 boost::thread::id ui_thread;
84
85 /** Convert some number of seconds to a string representation
86  *  in hours, minutes and seconds.
87  *
88  *  @param s Seconds.
89  *  @return String of the form H:M:S (where H is hours, M
90  *  is minutes and S is seconds).
91  */
92 string
93 seconds_to_hms (int s)
94 {
95         int m = s / 60;
96         s -= (m * 60);
97         int h = m / 60;
98         m -= (h * 60);
99
100         stringstream hms;
101         hms << h << N_(":");
102         hms.width (2);
103         hms << std::setfill ('0') << m << N_(":");
104         hms.width (2);
105         hms << std::setfill ('0') << s;
106
107         return hms.str ();
108 }
109
110 /** @param s Number of seconds.
111  *  @return String containing an approximate description of s (e.g. "about 2 hours")
112  */
113 string
114 seconds_to_approximate_hms (int s)
115 {
116         int m = s / 60;
117         s -= (m * 60);
118         int h = m / 60;
119         m -= (h * 60);
120
121         stringstream ap;
122         
123         if (h > 0) {
124                 if (m > 30) {
125                         ap << (h + 1) << N_(" ") << _("hours");
126                 } else {
127                         if (h == 1) {
128                                 ap << N_("1 ") << _("hour");
129                         } else {
130                                 ap << h << N_(" ") << _("hours");
131                         }
132                 }
133         } else if (m > 0) {
134                 if (m == 1) {
135                         ap << N_("1 ") << _("minute");
136                 } else {
137                         ap << m << N_(" ") << _("minutes");
138                 }
139         } else {
140                 ap << s << N_(" ") << _("seconds");
141         }
142
143         return ap.str ();
144 }
145
146 #ifdef DVDOMATIC_POSIX
147 /** @param l Mangled C++ identifier.
148  *  @return Demangled version.
149  */
150 static string
151 demangle (string l)
152 {
153         string::size_type const b = l.find_first_of (N_("("));
154         if (b == string::npos) {
155                 return l;
156         }
157
158         string::size_type const p = l.find_last_of (N_("+"));
159         if (p == string::npos) {
160                 return l;
161         }
162
163         if ((p - b) <= 1) {
164                 return l;
165         }
166         
167         string const fn = l.substr (b + 1, p - b - 1);
168
169         int status;
170         try {
171                 
172                 char* realname = abi::__cxa_demangle (fn.c_str(), 0, 0, &status);
173                 string d (realname);
174                 free (realname);
175                 return d;
176                 
177         } catch (std::exception) {
178                 
179         }
180         
181         return l;
182 }
183
184 /** Write a stacktrace to an ostream.
185  *  @param out Stream to write to.
186  *  @param levels Number of levels to go up the call stack.
187  */
188 void
189 stacktrace (ostream& out, int levels)
190 {
191         void *array[200];
192         size_t size;
193         char **strings;
194         size_t i;
195      
196         size = backtrace (array, 200);
197         strings = backtrace_symbols (array, size);
198      
199         if (strings) {
200                 for (i = 0; i < size && (levels == 0 || i < size_t(levels)); i++) {
201                         out << N_("  ") << demangle (strings[i]) << "\n";
202                 }
203                 
204                 free (strings);
205         }
206 }
207 #endif
208
209 /** @param v Version as used by FFmpeg.
210  *  @return A string representation of v.
211  */
212 static string
213 ffmpeg_version_to_string (int v)
214 {
215         stringstream s;
216         s << ((v & 0xff0000) >> 16) << N_(".") << ((v & 0xff00) >> 8) << N_(".") << (v & 0xff);
217         return s.str ();
218 }
219
220 /** Return a user-readable string summarising the versions of our dependencies */
221 string
222 dependency_version_summary ()
223 {
224         stringstream s;
225         s << N_("libopenjpeg ") << opj_version () << N_(", ")
226           << N_("libavcodec ") << ffmpeg_version_to_string (avcodec_version()) << N_(", ")
227           << N_("libavfilter ") << ffmpeg_version_to_string (avfilter_version()) << N_(", ")
228           << N_("libavformat ") << ffmpeg_version_to_string (avformat_version()) << N_(", ")
229           << N_("libavutil ") << ffmpeg_version_to_string (avutil_version()) << N_(", ")
230           << N_("libpostproc ") << ffmpeg_version_to_string (postproc_version()) << N_(", ")
231           << N_("libswscale ") << ffmpeg_version_to_string (swscale_version()) << N_(", ")
232           << MagickVersion << N_(", ")
233           << N_("libssh ") << ssh_version (0) << N_(", ")
234           << N_("libdcp ") << libdcp::version << N_(" git ") << libdcp::git_commit;
235
236         return s.str ();
237 }
238
239 double
240 seconds (struct timeval t)
241 {
242         return t.tv_sec + (double (t.tv_usec) / 1e6);
243 }
244
245 /** Call the required functions to set up DVD-o-matic's static arrays, etc.
246  *  Must be called from the UI thread, if there is one.
247  */
248 void
249 dvdomatic_setup ()
250 {
251         avfilter_register_all ();
252         
253         Format::setup_formats ();
254         DCPContentType::setup_dcp_content_types ();
255         Scaler::setup_scalers ();
256         Filter::setup_filters ();
257         SoundProcessor::setup_sound_processors ();
258
259         ui_thread = boost::this_thread::get_id ();
260 }
261
262 #ifdef DVDOMATIC_WINDOWS
263 boost::filesystem::path
264 mo_path ()
265 {
266         wchar_t buffer[512];
267         GetModuleFileName (0, buffer, 512 * sizeof(wchar_t));
268         boost::filesystem::path p (buffer);
269         p = p.parent_path ();
270         p = p.parent_path ();
271         p /= "locale";
272         return p;
273 }
274 #endif
275
276 void
277 dvdomatic_setup_i18n (string lang)
278 {
279 #ifdef DVDOMATIC_POSIX
280         lang += ".UTF8";
281 #endif
282
283         if (!lang.empty ()) {
284                 /* Override our environment language; this is essential on
285                    Windows.
286                 */
287                 char cmd[64];
288                 snprintf (cmd, sizeof(cmd), "LANGUAGE=%s", lang.c_str ());
289                 putenv (cmd);
290                 snprintf (cmd, sizeof(cmd), "LANG=%s", lang.c_str ());
291                 putenv (cmd);
292         }
293
294         setlocale (LC_ALL, "");
295         textdomain ("libdvdomatic");
296
297 #ifdef DVDOMATIC_WINDOWS
298         bindtextdomain ("libdvdomatic", mo_path().string().c_str());
299         bind_textdomain_codeset ("libdvdomatic", "UTF8");
300 #endif  
301
302 #ifdef DVDOMATIC_POSIX
303         bindtextdomain ("libdvdomatic", POSIX_LOCALE_PREFIX);
304 #endif
305 }
306
307 /** @param start Start position for the crop within the image.
308  *  @param size Size of the cropped area.
309  *  @return FFmpeg crop filter string.
310  */
311 string
312 crop_string (Position start, libdcp::Size size)
313 {
314         stringstream s;
315         s << N_("crop=") << size.width << N_(":") << size.height << N_(":") << start.x << N_(":") << start.y;
316         return s.str ();
317 }
318
319 /** @param s A string.
320  *  @return Parts of the string split at spaces, except when a space is within quotation marks.
321  */
322 vector<string>
323 split_at_spaces_considering_quotes (string s)
324 {
325         vector<string> out;
326         bool in_quotes = false;
327         string c;
328         for (string::size_type i = 0; i < s.length(); ++i) {
329                 if (s[i] == ' ' && !in_quotes) {
330                         out.push_back (c);
331                         c = N_("");
332                 } else if (s[i] == '"') {
333                         in_quotes = !in_quotes;
334                 } else {
335                         c += s[i];
336                 }
337         }
338
339         out.push_back (c);
340         return out;
341 }
342
343 string
344 md5_digest (void const * data, int size)
345 {
346         MD5_CTX md5_context;
347         MD5_Init (&md5_context);
348         MD5_Update (&md5_context, data, size);
349         unsigned char digest[MD5_DIGEST_LENGTH];
350         MD5_Final (digest, &md5_context);
351         
352         stringstream s;
353         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
354                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
355         }
356
357         return s.str ();
358 }
359
360 /** @param file File name.
361  *  @return MD5 digest of file's contents.
362  */
363 string
364 md5_digest (string file)
365 {
366         ifstream f (file.c_str(), std::ios::binary);
367         if (!f.good ()) {
368                 throw OpenFileError (file);
369         }
370         
371         f.seekg (0, std::ios::end);
372         int bytes = f.tellg ();
373         f.seekg (0, std::ios::beg);
374
375         int const buffer_size = 64 * 1024;
376         char buffer[buffer_size];
377
378         MD5_CTX md5_context;
379         MD5_Init (&md5_context);
380         while (bytes > 0) {
381                 int const t = min (bytes, buffer_size);
382                 f.read (buffer, t);
383                 MD5_Update (&md5_context, buffer, t);
384                 bytes -= t;
385         }
386
387         unsigned char digest[MD5_DIGEST_LENGTH];
388         MD5_Final (digest, &md5_context);
389
390         stringstream s;
391         for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
392                 s << std::hex << std::setfill('0') << std::setw(2) << ((int) digest[i]);
393         }
394
395         return s.str ();
396 }
397
398 static bool
399 about_equal (float a, float b)
400 {
401         /* A film of F seconds at f FPS will be Ff frames;
402            Consider some delta FPS d, so if we run the same
403            film at (f + d) FPS it will last F(f + d) seconds.
404
405            Hence the difference in length over the length of the film will
406            be F(f + d) - Ff frames
407             = Ff + Fd - Ff frames
408             = Fd frames
409             = Fd/f seconds
410  
411            So if we accept a difference of 1 frame, ie 1/f seconds, we can
412            say that
413
414            1/f = Fd/f
415         ie 1 = Fd
416         ie d = 1/F
417  
418            So for a 3hr film, ie F = 3 * 60 * 60 = 10800, the acceptable
419            FPS error is 1/F ~= 0.0001 ~= 10-e4
420         */
421
422         return (fabs (a - b) < 1e-4);
423 }
424
425 class FrameRateCandidate
426 {
427 public:
428         FrameRateCandidate (float source_, int dcp_)
429                 : source (source_)
430                 , dcp (dcp_)
431         {}
432
433         float source;
434         int dcp;
435 };
436
437 int
438 best_dcp_frame_rate (float source_fps)
439 {
440         list<int> const allowed_dcp_frame_rates = Config::instance()->allowed_dcp_frame_rates ();
441
442         /* Work out what rates we could manage, including those achieved by using skip / repeat. */
443         list<FrameRateCandidate> candidates;
444
445         /* Start with the ones without skip / repeat so they will get matched in preference to skipped/repeated ones */
446         for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
447                 candidates.push_back (FrameRateCandidate (*i, *i));
448         }
449
450         /* Then the skip/repeat ones */
451         for (list<int>::const_iterator i = allowed_dcp_frame_rates.begin(); i != allowed_dcp_frame_rates.end(); ++i) {
452                 candidates.push_back (FrameRateCandidate (float (*i) / 2, *i));
453                 candidates.push_back (FrameRateCandidate (float (*i) * 2, *i));
454         }
455
456         /* Pick the best one, bailing early if we hit an exact match */
457         float error = std::numeric_limits<float>::max ();
458         optional<FrameRateCandidate> best;
459         list<FrameRateCandidate>::iterator i = candidates.begin();
460         while (i != candidates.end()) {
461                 
462                 if (about_equal (i->source, source_fps)) {
463                         best = *i;
464                         break;
465                 }
466
467                 float const e = fabs (i->source - source_fps);
468                 if (e < error) {
469                         error = e;
470                         best = *i;
471                 }
472
473                 ++i;
474         }
475
476         assert (best);
477         return best->dcp;
478 }
479
480 /** @param An arbitrary sampling rate.
481  *  @return The appropriate DCP-approved sampling rate (48kHz or 96kHz).
482  */
483 int
484 dcp_audio_sample_rate (int fs)
485 {
486         if (fs <= 48000) {
487                 return 48000;
488         }
489
490         return 96000;
491 }
492
493 bool operator== (Crop const & a, Crop const & b)
494 {
495         return (a.left == b.left && a.right == b.right && a.top == b.top && a.bottom == b.bottom);
496 }
497
498 bool operator!= (Crop const & a, Crop const & b)
499 {
500         return !(a == b);
501 }
502
503 /** @param index Colour LUT index.
504  *  @return Human-readable name.
505  */
506 string
507 colour_lut_index_to_name (int index)
508 {
509         switch (index) {
510         case 0:
511                 return _("sRGB");
512         case 1:
513                 return _("Rec 709");
514         }
515
516         assert (false);
517         return N_("");
518 }
519
520 Socket::Socket (int timeout)
521         : _deadline (_io_service)
522         , _socket (_io_service)
523         , _timeout (timeout)
524 {
525         _deadline.expires_at (boost::posix_time::pos_infin);
526         check ();
527 }
528
529 void
530 Socket::check ()
531 {
532         if (_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now ()) {
533                 _socket.close ();
534                 _deadline.expires_at (boost::posix_time::pos_infin);
535         }
536
537         _deadline.async_wait (boost::bind (&Socket::check, this));
538 }
539
540 /** Blocking connect.
541  *  @param endpoint End-point to connect to.
542  */
543 void
544 Socket::connect (boost::asio::ip::basic_resolver_entry<boost::asio::ip::tcp> const & endpoint)
545 {
546         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
547         boost::system::error_code ec = boost::asio::error::would_block;
548         _socket.async_connect (endpoint, boost::lambda::var(ec) = boost::lambda::_1);
549         do {
550                 _io_service.run_one();
551         } while (ec == boost::asio::error::would_block);
552
553         if (ec || !_socket.is_open ()) {
554                 throw NetworkError (_("connect timed out"));
555         }
556 }
557
558 /** Blocking write.
559  *  @param data Buffer to write.
560  *  @param size Number of bytes to write.
561  */
562 void
563 Socket::write (uint8_t const * data, int size)
564 {
565         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
566         boost::system::error_code ec = boost::asio::error::would_block;
567
568         boost::asio::async_write (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
569         
570         do {
571                 _io_service.run_one ();
572         } while (ec == boost::asio::error::would_block);
573
574         if (ec) {
575                 throw NetworkError (ec.message ());
576         }
577 }
578
579 void
580 Socket::write (uint32_t v)
581 {
582         v = htonl (v);
583         write (reinterpret_cast<uint8_t*> (&v), 4);
584 }
585
586 /** Blocking read.
587  *  @param data Buffer to read to.
588  *  @param size Number of bytes to read.
589  */
590 void
591 Socket::read (uint8_t* data, int size)
592 {
593         _deadline.expires_from_now (boost::posix_time::seconds (_timeout));
594         boost::system::error_code ec = boost::asio::error::would_block;
595
596         boost::asio::async_read (_socket, boost::asio::buffer (data, size), boost::lambda::var(ec) = boost::lambda::_1);
597
598         do {
599                 _io_service.run_one ();
600         } while (ec == boost::asio::error::would_block);
601         
602         if (ec) {
603                 throw NetworkError (ec.message ());
604         }
605 }
606
607 uint32_t
608 Socket::read_uint32 ()
609 {
610         uint32_t v;
611         read (reinterpret_cast<uint8_t *> (&v), 4);
612         return ntohl (v);
613 }
614
615 /** @param other A Rect.
616  *  @return The intersection of this with `other'.
617  */
618 Rect
619 Rect::intersection (Rect const & other) const
620 {
621         int const tx = max (x, other.x);
622         int const ty = max (y, other.y);
623         
624         return Rect (
625                 tx, ty,
626                 min (x + width, other.x + other.width) - tx,
627                 min (y + height, other.y + other.height) - ty
628                 );
629 }
630
631 /** Round a number up to the nearest multiple of another number.
632  *  @param c Index.
633  *  @param s Array of numbers to round, indexed by c.
634  *  @param t Multiple to round to.
635  *  @return Rounded number.
636  */
637 int
638 stride_round_up (int c, int const * stride, int t)
639 {
640         int const a = stride[c] + (t - 1);
641         return a - (a % t);
642 }
643
644 int
645 stride_lookup (int c, int const * stride)
646 {
647         return stride[c];
648 }
649
650 /** Read a sequence of key / value pairs from a text stream;
651  *  the keys are the first words on the line, and the values are
652  *  the remainder of the line following the key.  Lines beginning
653  *  with # are ignored.
654  *  @param s Stream to read.
655  *  @return key/value pairs.
656  */
657 multimap<string, string>
658 read_key_value (istream &s) 
659 {
660         multimap<string, string> kv;
661         
662         string line;
663         while (getline (s, line)) {
664                 if (line.empty ()) {
665                         continue;
666                 }
667
668                 if (line[0] == '#') {
669                         continue;
670                 }
671
672                 if (line[line.size() - 1] == '\r') {
673                         line = line.substr (0, line.size() - 1);
674                 }
675
676                 size_t const s = line.find (' ');
677                 if (s == string::npos) {
678                         continue;
679                 }
680
681                 kv.insert (make_pair (line.substr (0, s), line.substr (s + 1)));
682         }
683
684         return kv;
685 }
686
687 string
688 get_required_string (multimap<string, string> const & kv, string k)
689 {
690         if (kv.count (k) > 1) {
691                 throw StringError (N_("unexpected multiple keys in key-value set"));
692         }
693
694         multimap<string, string>::const_iterator i = kv.find (k);
695         
696         if (i == kv.end ()) {
697                 throw StringError (String::compose (_("missing key %1 in key-value set"), k));
698         }
699
700         return i->second;
701 }
702
703 int
704 get_required_int (multimap<string, string> const & kv, string k)
705 {
706         string const v = get_required_string (kv, k);
707         return lexical_cast<int> (v);
708 }
709
710 float
711 get_required_float (multimap<string, string> const & kv, string k)
712 {
713         string const v = get_required_string (kv, k);
714         return lexical_cast<float> (v);
715 }
716
717 string
718 get_optional_string (multimap<string, string> const & kv, string k)
719 {
720         if (kv.count (k) > 1) {
721                 throw StringError (N_("unexpected multiple keys in key-value set"));
722         }
723
724         multimap<string, string>::const_iterator i = kv.find (k);
725         if (i == kv.end ()) {
726                 return N_("");
727         }
728
729         return i->second;
730 }
731
732 int
733 get_optional_int (multimap<string, string> const & kv, string k)
734 {
735         if (kv.count (k) > 1) {
736                 throw StringError (N_("unexpected multiple keys in key-value set"));
737         }
738
739         multimap<string, string>::const_iterator i = kv.find (k);
740         if (i == kv.end ()) {
741                 return 0;
742         }
743
744         return lexical_cast<int> (i->second);
745 }
746
747 /** Construct an AudioBuffers.  Audio data is undefined after this constructor.
748  *  @param channels Number of channels.
749  *  @param frames Number of frames to reserve space for.
750  */
751 AudioBuffers::AudioBuffers (int channels, int frames)
752         : _channels (channels)
753         , _frames (frames)
754         , _allocated_frames (frames)
755 {
756         _data = new float*[_channels];
757         for (int i = 0; i < _channels; ++i) {
758                 _data[i] = new float[frames];
759         }
760 }
761
762 /** Copy constructor.
763  *  @param other Other AudioBuffers; data is copied.
764  */
765 AudioBuffers::AudioBuffers (AudioBuffers const & other)
766         : _channels (other._channels)
767         , _frames (other._frames)
768         , _allocated_frames (other._frames)
769 {
770         _data = new float*[_channels];
771         for (int i = 0; i < _channels; ++i) {
772                 _data[i] = new float[_frames];
773                 memcpy (_data[i], other._data[i], _frames * sizeof (float));
774         }
775 }
776
777 /* XXX: it's a shame that this is a copy-and-paste of the above;
778    probably fixable with c++0x.
779 */
780 AudioBuffers::AudioBuffers (boost::shared_ptr<const AudioBuffers> other)
781         : _channels (other->_channels)
782         , _frames (other->_frames)
783         , _allocated_frames (other->_frames)
784 {
785         _data = new float*[_channels];
786         for (int i = 0; i < _channels; ++i) {
787                 _data[i] = new float[_frames];
788                 memcpy (_data[i], other->_data[i], _frames * sizeof (float));
789         }
790 }
791
792 /** AudioBuffers destructor */
793 AudioBuffers::~AudioBuffers ()
794 {
795         for (int i = 0; i < _channels; ++i) {
796                 delete[] _data[i];
797         }
798
799         delete[] _data;
800 }
801
802 /** @param c Channel index.
803  *  @return Buffer for this channel.
804  */
805 float*
806 AudioBuffers::data (int c) const
807 {
808         assert (c >= 0 && c < _channels);
809         return _data[c];
810 }
811
812 /** Set the number of frames that these AudioBuffers will report themselves
813  *  as having.
814  *  @param f Frames; must be less than or equal to the number of allocated frames.
815  */
816 void
817 AudioBuffers::set_frames (int f)
818 {
819         assert (f <= _allocated_frames);
820         _frames = f;
821 }
822
823 /** Make all samples on all channels silent */
824 void
825 AudioBuffers::make_silent ()
826 {
827         for (int i = 0; i < _channels; ++i) {
828                 make_silent (i);
829         }
830 }
831
832 /** Make all samples on a given channel silent.
833  *  @param c Channel.
834  */
835 void
836 AudioBuffers::make_silent (int c)
837 {
838         assert (c >= 0 && c < _channels);
839         
840         for (int i = 0; i < _frames; ++i) {
841                 _data[c][i] = 0;
842         }
843 }
844
845 /** Copy data from another AudioBuffers to this one.  All channels are copied.
846  *  @param from AudioBuffers to copy from; must have the same number of channels as this.
847  *  @param frames_to_copy Number of frames to copy.
848  *  @param read_offset Offset to read from in `from'.
849  *  @param write_offset Offset to write to in `to'.
850  */
851 void
852 AudioBuffers::copy_from (AudioBuffers* from, int frames_to_copy, int read_offset, int write_offset)
853 {
854         assert (from->channels() == channels());
855
856         assert (from);
857         assert (read_offset >= 0 && (read_offset + frames_to_copy) <= from->_allocated_frames);
858         assert (write_offset >= 0 && (write_offset + frames_to_copy) <= _allocated_frames);
859
860         for (int i = 0; i < _channels; ++i) {
861                 memcpy (_data[i] + write_offset, from->_data[i] + read_offset, frames_to_copy * sizeof(float));
862         }
863 }
864
865 /** Move audio data around.
866  *  @param from Offset to move from.
867  *  @param to Offset to move to.
868  *  @param frames Number of frames to move.
869  */
870     
871 void
872 AudioBuffers::move (int from, int to, int frames)
873 {
874         if (frames == 0) {
875                 return;
876         }
877         
878         assert (from >= 0);
879         assert (from < _frames);
880         assert (to >= 0);
881         assert (to < _frames);
882         assert (frames > 0);
883         assert (frames <= _frames);
884         assert ((from + frames) <= _frames);
885         assert ((to + frames) <= _frames);
886         
887         for (int i = 0; i < _channels; ++i) {
888                 memmove (_data[i] + to, _data[i] + from, frames * sizeof(float));
889         }
890 }
891
892 /** Trip an assert if the caller is not in the UI thread */
893 void
894 ensure_ui_thread ()
895 {
896         assert (boost::this_thread::get_id() == ui_thread);
897 }
898
899 /** @param v Source video frame.
900  *  @param audio_sample_rate Source audio sample rate.
901  *  @param frames_per_second Number of video frames per second.
902  *  @return Equivalent number of audio frames for `v'.
903  */
904 int64_t
905 video_frames_to_audio_frames (SourceFrame v, float audio_sample_rate, float frames_per_second)
906 {
907         return ((int64_t) v * audio_sample_rate / frames_per_second);
908 }
909
910 /** @param f Filename.
911  *  @return true if this file is a still image, false if it is something else.
912  */
913 bool
914 still_image_file (string f)
915 {
916         string ext = boost::filesystem::path(f).extension().string();
917
918         transform (ext.begin(), ext.end(), ext.begin(), ::tolower);
919         
920         return (ext == N_(".tif") || ext == N_(".tiff") || ext == N_(".jpg") || ext == N_(".jpeg") || ext == N_(".png") || ext == N_(".bmp"));
921 }
922
923 /** @return A pair containing CPU model name and the number of processors */
924 pair<string, int>
925 cpu_info ()
926 {
927         pair<string, int> info;
928         info.second = 0;
929         
930 #ifdef DVDOMATIC_POSIX
931         ifstream f (N_("/proc/cpuinfo"));
932         while (f.good ()) {
933                 string l;
934                 getline (f, l);
935                 if (boost::algorithm::starts_with (l, N_("model name"))) {
936                         string::size_type const c = l.find (':');
937                         if (c != string::npos) {
938                                 info.first = l.substr (c + 2);
939                         }
940                 } else if (boost::algorithm::starts_with (l, N_("processor"))) {
941                         ++info.second;
942                 }
943         }
944 #endif  
945
946         return info;
947 }
948
949 string
950 audio_channel_name (int c)
951 {
952         assert (MAX_AUDIO_CHANNELS == 6);
953
954         /* TRANSLATORS: these are the names of audio channels; Lfe (sub) is the low-frequency
955            enhancement channel (sub-woofer)./
956         */
957         string const channels[] = {
958                 _("Left"),
959                 _("Right"),
960                 _("Centre"),
961                 _("Lfe (sub)"),
962                 _("Left surround"),
963                 _("Right surround"),
964         };
965
966         return channels[c];
967 }
968
969 AudioMapping::AudioMapping (int c)
970         : _source_channels (c)
971 {
972
973 }
974
975 optional<libdcp::Channel>
976 AudioMapping::source_to_dcp (int c) const
977 {
978         if (c >= _source_channels) {
979                 return optional<libdcp::Channel> ();
980         }
981
982         if (_source_channels == 1) {
983                 /* mono sources to centre */
984                 return libdcp::CENTRE;
985         }
986         
987         return static_cast<libdcp::Channel> (c);
988 }
989
990 optional<int>
991 AudioMapping::dcp_to_source (libdcp::Channel c) const
992 {
993         if (_source_channels == 1) {
994                 if (c == libdcp::CENTRE) {
995                         return 0;
996                 } else {
997                         return optional<int> ();
998                 }
999         }
1000
1001         if (static_cast<int> (c) >= _source_channels) {
1002                 return optional<int> ();
1003         }
1004         
1005         return static_cast<int> (c);
1006 }
1007
1008 int
1009 AudioMapping::dcp_channels () const
1010 {
1011         if (_source_channels == 1) {
1012                 /* The source is mono, so to put the mono channel into
1013                    the centre we need to generate a 5.1 soundtrack.
1014                 */
1015                 return 6;
1016         }
1017
1018         return _source_channels;
1019 }
1020
1021 FrameRateConversion::FrameRateConversion (float source, int dcp)
1022         : skip (false)
1023         , repeat (false)
1024         , change_speed (false)
1025 {
1026         if (fabs (source / 2.0 - dcp) < (fabs (source - dcp))) {
1027                 skip = true;
1028         } else if (fabs (source * 2 - dcp) < fabs (source - dcp)) {
1029                 repeat = true;
1030         }
1031
1032         change_speed = !about_equal (source * factor(), dcp);
1033
1034         if (!skip && !repeat && !change_speed) {
1035                 description = _("DCP and source have the same rate.\n");
1036         } else {
1037                 if (skip) {
1038                         description = _("DCP will use every other frame of the source.\n");
1039                 } else if (repeat) {
1040                         description = _("Each source frame will be doubled in the DCP.\n");
1041                 }
1042
1043                 if (change_speed) {
1044                         float const pc = dcp * 100 / (source * factor());
1045                         description += String::compose (_("DCP will run at %1%% of the source speed.\n"), pc);
1046                 }
1047         }
1048 }
1049
1050 LocaleGuard::LocaleGuard ()
1051         : _old (0)
1052 {
1053         char const * old = setlocale (LC_NUMERIC, 0);
1054
1055         if (old) {
1056                 _old = strdup (old);
1057                 if (strcmp (_old, "POSIX")) {
1058                         setlocale (LC_NUMERIC, "POSIX");
1059                 }
1060         }
1061 }
1062
1063 LocaleGuard::~LocaleGuard ()
1064 {
1065         setlocale (LC_NUMERIC, _old);
1066         free (_old);
1067 }