ef67b94f17e606144230d35a417911fdacee87b1
[dcpomatic.git] / src / lib / audio_decoder_stream.cc
1 /*
2     Copyright (C) 2012-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "audio_decoder_stream.h"
22 #include "audio_buffers.h"
23 #include "audio_processor.h"
24 #include "audio_decoder.h"
25 #include "resampler.h"
26 #include "util.h"
27 #include "film.h"
28 #include "log.h"
29 #include "audio_content.h"
30 #include "compose.hpp"
31 #include <iostream>
32
33 #include "i18n.h"
34
35 using std::list;
36 using std::pair;
37 using std::cout;
38 using std::min;
39 using std::max;
40 using boost::optional;
41 using boost::shared_ptr;
42
43 AudioDecoderStream::AudioDecoderStream (
44         shared_ptr<const AudioContent> content, AudioStreamPtr stream, Decoder* decoder, AudioDecoder* audio_decoder, shared_ptr<Log> log
45         )
46         : _content (content)
47         , _stream (stream)
48         , _decoder (decoder)
49         , _audio_decoder (audio_decoder)
50         , _log (log)
51           /* We effectively start having done a seek to zero; this allows silence-padding of the first
52              data that comes out of our decoder.
53           */
54         , _seek_reference (ContentTime ())
55 {
56         if (content->resampled_frame_rate() != _stream->frame_rate() && _stream->channels() > 0) {
57                 _resampler.reset (new Resampler (_stream->frame_rate(), content->resampled_frame_rate(), _stream->channels ()));
58         }
59
60         reset_decoded ();
61 }
62
63 void
64 AudioDecoderStream::reset_decoded ()
65 {
66         _decoded = ContentAudio (shared_ptr<AudioBuffers> (new AudioBuffers (_stream->channels(), 0)), 0);
67 }
68
69 ContentAudio
70 AudioDecoderStream::get (Frame frame, Frame length, bool accurate)
71 {
72         shared_ptr<ContentAudio> dec;
73
74         _log->log (String::compose ("ADS has request for %1 %2", frame, length), LogEntry::TYPE_DEBUG_DECODE);
75
76         Frame const from = frame;
77         Frame const to = from + length;
78         Frame const have_from = _decoded.frame;
79         Frame const have_to = _decoded.frame + _decoded.audio->frames();
80
81         optional<Frame> missing;
82         if (have_from > from || have_to < to) {
83                 /* We need something */
84                 if (have_from < from && from < have_to) {
85                         missing = have_to;
86                 } else {
87                         missing = from;
88                 }
89         }
90
91         if (missing) {
92                 _log->log (String::compose ("ADS suggests seek to %1", *missing), LogEntry::TYPE_DEBUG_DECODE);
93                 _audio_decoder->maybe_seek (ContentTime::from_frames (*missing, _content->resampled_frame_rate()), accurate);
94         }
95
96         /* Offset of the data that we want from the start of _decoded.audio
97            (to be set up shortly)
98         */
99         Frame decoded_offset = 0;
100
101         /* Now enough pass() calls will either:
102          *  (a) give us what we want, or
103          *  (b) hit the end of the decoder.
104          *
105          * If we are being accurate, we want the right frames,
106          * otherwise any frames will do.
107          */
108         if (accurate) {
109                 /* Keep stuffing data into _decoded until we have enough data, or the subclass does not want to give us any more */
110                 while (
111                         (_decoded.frame > frame || (_decoded.frame + _decoded.audio->frames()) <= to) &&
112                         !_decoder->pass (Decoder::PASS_REASON_AUDIO, accurate)
113                         )
114                 {}
115
116                 decoded_offset = frame - _decoded.frame;
117
118                 _log->log (
119                         String::compose ("Accurate ADS::get has offset %1 from request %2 and available %3", decoded_offset, frame, have_from),
120                         LogEntry::TYPE_DEBUG_DECODE
121                         );
122         } else {
123                 while (
124                         _decoded.audio->frames() < length &&
125                         !_decoder->pass (Decoder::PASS_REASON_AUDIO, accurate)
126                         )
127                 {}
128
129                 /* Use decoded_offset of 0, as we don't really care what frames we return */
130         }
131
132         /* The amount of data available in _decoded.audio starting from `frame'.  This could be -ve
133            if pass() returned true before we got enough data.
134         */
135         Frame const available = _decoded.audio->frames() - decoded_offset;
136
137         /* We will return either that, or the requested amount, whichever is smaller */
138         Frame const to_return = max ((Frame) 0, min (available, length));
139
140         /* Copy our data to the output */
141         shared_ptr<AudioBuffers> out (new AudioBuffers (_decoded.audio->channels(), to_return));
142         out->copy_from (_decoded.audio.get(), to_return, decoded_offset, 0);
143
144         Frame const remaining = max ((Frame) 0, available - to_return);
145
146         /* Clean up decoded; first, move the data after what we just returned to the start of the buffer */
147         _decoded.audio->move (decoded_offset + to_return, 0, remaining);
148         /* And set up the number of frames we have left */
149         _decoded.audio->set_frames (remaining);
150         /* Also bump where those frames are in terms of the content */
151         _decoded.frame += decoded_offset + to_return;
152
153         return ContentAudio (out, frame);
154 }
155
156 /** Audio timestamping is made hard by many factors, but perhaps the most entertaining is resampling.
157  *  We have to assume that we are feeding continuous data into the resampler, and so we get continuous
158  *  data out.  Hence we do the timestamping here, post-resampler, just by counting samples.
159  *
160  *  The time is passed in here so that after a seek we can set up our _position.  The
161  *  time is ignored once this has been done.
162  */
163 void
164 AudioDecoderStream::audio (shared_ptr<const AudioBuffers> data, ContentTime time)
165 {
166         _log->log (String::compose ("ADS receives %1 %2", to_string(time), data->frames ()), LogEntry::TYPE_DEBUG_DECODE);
167
168         if (_resampler) {
169                 data = _resampler->run (data);
170         }
171
172         Frame const frame_rate = _content->resampled_frame_rate ();
173
174         if (_seek_reference) {
175                 /* We've had an accurate seek and now we're seeing some data */
176                 ContentTime const delta = time - _seek_reference.get ();
177                 Frame const delta_frames = delta.frames_round (frame_rate);
178                 if (delta_frames > 0) {
179                         /* This data comes after the seek time.  Pad the data with some silence. */
180                         shared_ptr<AudioBuffers> padded (new AudioBuffers (data->channels(), data->frames() + delta_frames));
181                         padded->make_silent ();
182                         padded->copy_from (data.get(), data->frames(), 0, delta_frames);
183                         data = padded;
184                         time -= delta;
185                 }
186                 _seek_reference = optional<ContentTime> ();
187         }
188
189         if (!_position) {
190                 _position = time.frames_round (frame_rate);
191         }
192
193         DCPOMATIC_ASSERT (_position.get() >= (_decoded.frame + _decoded.audio->frames()));
194
195         add (data);
196 }
197
198 void
199 AudioDecoderStream::add (shared_ptr<const AudioBuffers> data)
200 {
201         if (!_position) {
202                 /* This should only happen when there is a seek followed by a flush, but
203                    we need to cope with it.
204                 */
205                 return;
206         }
207
208         /* Resize _decoded to fit the new data */
209         int new_size = 0;
210         if (_decoded.audio->frames() == 0) {
211                 /* There's nothing in there, so just store the new data */
212                 new_size = data->frames ();
213                 _decoded.frame = _position.get ();
214         } else {
215                 /* Otherwise we need to extend _decoded to include the new stuff */
216                 new_size = _position.get() + data->frames() - _decoded.frame;
217         }
218
219         _decoded.audio->ensure_size (new_size);
220         _decoded.audio->set_frames (new_size);
221
222         /* Copy new data in */
223         _decoded.audio->copy_from (data.get(), data->frames(), 0, _position.get() - _decoded.frame);
224         _position = _position.get() + data->frames ();
225
226         /* Limit the amount of data we keep in case nobody is asking for it */
227         int const max_frames = _content->resampled_frame_rate () * 10;
228         if (_decoded.audio->frames() > max_frames) {
229                 int const to_remove = _decoded.audio->frames() - max_frames;
230                 _decoded.frame += to_remove;
231                 _decoded.audio->move (to_remove, 0, max_frames);
232                 _decoded.audio->set_frames (max_frames);
233         }
234 }
235
236 void
237 AudioDecoderStream::flush ()
238 {
239         if (!_resampler) {
240                 return;
241         }
242
243         shared_ptr<const AudioBuffers> b = _resampler->flush ();
244         if (b) {
245                 add (b);
246         }
247 }
248
249 void
250 AudioDecoderStream::seek (ContentTime t, bool accurate)
251 {
252         _position.reset ();
253         reset_decoded ();
254         if (accurate) {
255                 _seek_reference = t;
256         }
257 }
258
259 void
260 AudioDecoderStream::set_fast ()
261 {
262         if (_resampler) {
263                 _resampler->set_fast ();
264         }
265 }