Fix excessive memory usage on long plays without audio.
[dcpomatic.git] / src / lib / audio_decoder.cc
1 /*
2     Copyright (C) 2012-2014 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 "audio_decoder.h"
21 #include "audio_buffers.h"
22 #include "audio_processor.h"
23 #include "resampler.h"
24 #include "util.h"
25
26 #include "i18n.h"
27
28 using std::stringstream;
29 using std::list;
30 using std::pair;
31 using std::cout;
32 using std::min;
33 using std::max;
34 using boost::optional;
35 using boost::shared_ptr;
36
37 AudioDecoder::AudioDecoder (shared_ptr<const AudioContent> content)
38         : _audio_content (content)
39 {
40         if (content->resampled_audio_frame_rate() != content->audio_frame_rate() && content->audio_channels ()) {
41                 _resampler.reset (new Resampler (content->audio_frame_rate(), content->resampled_audio_frame_rate(), content->audio_channels ()));
42         }
43
44         if (content->audio_processor ()) {
45                 _processor = content->audio_processor()->clone (content->resampled_audio_frame_rate ());
46         }
47
48         reset_decoded_audio ();
49 }
50
51 void
52 AudioDecoder::reset_decoded_audio ()
53 {
54         _decoded_audio = ContentAudio (shared_ptr<AudioBuffers> (new AudioBuffers (_audio_content->processed_audio_channels(), 0)), 0);
55 }
56
57 shared_ptr<ContentAudio>
58 AudioDecoder::get_audio (AudioFrame frame, AudioFrame length, bool accurate)
59 {
60         shared_ptr<ContentAudio> dec;
61
62         AudioFrame const end = frame + length - 1;
63                 
64         if (frame < _decoded_audio.frame || end > (_decoded_audio.frame + length * 4)) {
65                 /* Either we have no decoded data, or what we do have is a long way from what we want: seek */
66                 seek (ContentTime::from_frames (frame, _audio_content->audio_frame_rate()), accurate);
67         }
68
69         /* Offset of the data that we want from the start of _decoded_audio.audio
70            (to be set up shortly)
71         */
72         AudioFrame decoded_offset = 0;
73         
74         /* Now enough pass() calls will either:
75          *  (a) give us what we want, or
76          *  (b) hit the end of the decoder.
77          *
78          * If we are being accurate, we want the right frames,
79          * otherwise any frames will do.
80          */
81         if (accurate) {
82                 /* Keep stuffing data into _decoded_audio until we have enough data, or the subclass does not want to give us any more */
83                 while (!pass() && (_decoded_audio.frame > frame || (_decoded_audio.frame + _decoded_audio.audio->frames()) < end)) {}
84                 decoded_offset = frame - _decoded_audio.frame;
85         } else {
86                 while (!pass() && _decoded_audio.audio->frames() < length) {}
87                 /* Use decoded_offset of 0, as we don't really care what frames we return */
88         }
89
90         /* The amount of data available in _decoded_audio.audio starting from `frame'.  This could be -ve
91            if pass() returned true before we got enough data.
92         */
93         AudioFrame const available = _decoded_audio.audio->frames() - decoded_offset;
94
95         /* We will return either that, or the requested amount, whichever is smaller */
96         AudioFrame const to_return = max ((AudioFrame) 0, min (available, length));
97
98         /* Copy our data to the output */
99         shared_ptr<AudioBuffers> out (new AudioBuffers (_decoded_audio.audio->channels(), to_return));
100         out->copy_from (_decoded_audio.audio.get(), to_return, decoded_offset, 0);
101
102         AudioFrame const remaining = max ((AudioFrame) 0, available - to_return);
103
104         /* Clean up decoded; first, move the data after what we just returned to the start of the buffer */
105         _decoded_audio.audio->move (decoded_offset + to_return, 0, remaining);
106         /* And set up the number of frames we have left */
107         _decoded_audio.audio->set_frames (remaining);
108         /* Also bump where those frames are in terms of the content */
109         _decoded_audio.frame += decoded_offset + to_return;
110
111         return shared_ptr<ContentAudio> (new ContentAudio (out, frame));
112 }
113
114 /** Called by subclasses when audio data is ready.
115  *
116  *  Audio timestamping is made hard by many factors, but perhaps the most entertaining is resampling.
117  *  We have to assume that we are feeding continuous data into the resampler, and so we get continuous
118  *  data out.  Hence we do the timestamping here, post-resampler, just by counting samples.
119  *
120  *  The time is passed in here so that after a seek we can set up our _audio_position.  The
121  *  time is ignored once this has been done.
122  */
123 void
124 AudioDecoder::audio (shared_ptr<const AudioBuffers> data, ContentTime time)
125 {
126         if (_resampler) {
127                 data = _resampler->run (data);
128         }
129
130         if (_processor) {
131                 data = _processor->run (data);
132         }
133
134         AudioFrame const frame_rate = _audio_content->resampled_audio_frame_rate ();
135
136         if (_seek_reference) {
137                 /* We've had an accurate seek and now we're seeing some data */
138                 ContentTime const delta = time - _seek_reference.get ();
139                 AudioFrame const delta_frames = delta.frames (frame_rate);
140                 if (delta_frames > 0) {
141                         /* This data comes after the seek time.  Pad the data with some silence. */
142                         shared_ptr<AudioBuffers> padded (new AudioBuffers (data->channels(), data->frames() + delta_frames));
143                         padded->make_silent ();
144                         padded->copy_from (data.get(), data->frames(), 0, delta_frames);
145                         data = padded;
146                         time -= delta;
147                 } else if (delta_frames < 0) {
148                         /* This data comes before the seek time.  Throw some data away */
149                         AudioFrame const to_discard = min (-delta_frames, static_cast<AudioFrame> (data->frames()));
150                         AudioFrame const to_keep = data->frames() - to_discard;
151                         if (to_keep == 0) {
152                                 /* We have to throw all this data away, so keep _seek_reference and
153                                    try again next time some data arrives.
154                                 */
155                                 return;
156                         }
157                         shared_ptr<AudioBuffers> trimmed (new AudioBuffers (data->channels(), to_keep));
158                         trimmed->copy_from (data.get(), to_keep, to_discard, 0);
159                         data = trimmed;
160                         time += ContentTime::from_frames (to_discard, frame_rate);
161                 }
162                 _seek_reference = optional<ContentTime> ();
163         }
164
165         if (!_audio_position) {
166                 _audio_position = time.frames (frame_rate);
167         }
168
169         assert (_audio_position.get() >= (_decoded_audio.frame + _decoded_audio.audio->frames()));
170
171         /* Resize _decoded_audio to fit the new data */
172         int new_size = 0;
173         if (_decoded_audio.audio->frames() == 0) {
174                 /* There's nothing in there, so just store the new data */
175                 new_size = data->frames ();
176                 _decoded_audio.frame = _audio_position.get ();
177         } else {
178                 /* Otherwise we need to extend _decoded_audio to include the new stuff */
179                 new_size = _audio_position.get() + data->frames() - _decoded_audio.frame;
180         }
181         
182         _decoded_audio.audio->ensure_size (new_size);
183         _decoded_audio.audio->set_frames (new_size);
184
185         /* Copy new data in */
186         _decoded_audio.audio->copy_from (data.get(), data->frames(), 0, _audio_position.get() - _decoded_audio.frame);
187         _audio_position = _audio_position.get() + data->frames ();
188
189         /* Limit the amount of data we keep in case nobody is asking for it */
190         int const max_frames = _audio_content->resampled_audio_frame_rate () * 10;
191         if (_decoded_audio.audio->frames() > max_frames) {
192                 int const to_remove = _decoded_audio.audio->frames() - max_frames;
193                 _decoded_audio.frame += to_remove;
194                 _decoded_audio.audio->move (to_remove, 0, max_frames);
195                 _decoded_audio.audio->set_frames (max_frames);
196         }
197 }
198
199 /* XXX: called? */
200 void
201 AudioDecoder::flush ()
202 {
203         if (!_resampler) {
204                 return;
205         }
206
207         /*
208         shared_ptr<const AudioBuffers> b = _resampler->flush ();
209         if (b) {
210                 _pending.push_back (shared_ptr<DecodedAudio> (new DecodedAudio (b, _audio_position.get ())));
211                 _audio_position = _audio_position.get() + b->frames ();
212         }
213         */
214 }
215
216 void
217 AudioDecoder::seek (ContentTime t, bool accurate)
218 {
219         _audio_position.reset ();
220         reset_decoded_audio ();
221         if (accurate) {
222                 _seek_reference = t;
223         }
224         if (_processor) {
225                 _processor->flush ();
226         }
227 }