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