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