daa363c5e8aaef9b8ecfebac5dbe1e1b0e563b53
[dcpomatic.git] / src / lib / sndfile_decoder.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <iostream>
21 #include <sndfile.h>
22 #include "sndfile_content.h"
23 #include "sndfile_decoder.h"
24 #include "film.h"
25 #include "exceptions.h"
26
27 #include "i18n.h"
28
29 using std::vector;
30 using std::string;
31 using std::stringstream;
32 using std::min;
33 using std::cout;
34 using boost::shared_ptr;
35 using boost::optional;
36
37 /* XXX */
38
39 SndfileDecoder::SndfileDecoder (shared_ptr<const Film> f, shared_ptr<SndfileContent> c)
40         : Decoder (f)
41         , AudioDecoder (f, c)
42 {
43         sf_count_t frames;
44         SNDFILE* sf = open_file (frames);
45         sf_close (sf);
46 }
47
48 SNDFILE*
49 SndfileDecoder::open_file (sf_count_t & frames)
50 {
51         frames = 0;
52         
53         SF_INFO info;
54         SNDFILE* s = sf_open (_sndfile_content->file().string().c_str(), SFM_READ, &info);
55         if (!s) {
56                 throw DecodeError (_("could not open external audio file for reading"));
57         }
58
59         frames = info.frames;
60         return s;
61 }
62
63 bool
64 SndfileDecoder::pass ()
65 {
66         sf_count_t frames;
67         SNDFILE* sndfile = open_file (frames);
68
69         /* Do things in half second blocks as I think there may be limits
70            to what FFmpeg (and in particular the resampler) can cope with.
71         */
72         sf_count_t const block = _sndfile_content->audio_frame_rate() / 2;
73
74         shared_ptr<AudioBuffers> audio (new AudioBuffers (_sndfile_content->audio_channels(), block));
75         while (frames > 0) {
76                 sf_count_t const this_time = min (block, frames);
77                 sf_read_float (sndfile, audio->data(0), this_time);
78                 audio->set_frames (this_time);
79                 Audio (audio);
80                 frames -= this_time;
81         }
82
83         sf_close (sndfile);
84
85         return true;
86 }