Do the delay line in floats with an AudioBuffer.
[dcpomatic.git] / src / lib / 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 /** @file  src/decoder.cc
21  *  @brief Parent class for decoders of content.
22  */
23
24 #include <iostream>
25 #include <stdint.h>
26 #include <boost/lexical_cast.hpp>
27 #include "film.h"
28 #include "format.h"
29 #include "job.h"
30 #include "options.h"
31 #include "exceptions.h"
32 #include "image.h"
33 #include "util.h"
34 #include "log.h"
35 #include "decoder.h"
36 #include "delay_line.h"
37 #include "subtitle.h"
38 #include "filter_graph.h"
39
40 using std::string;
41 using std::stringstream;
42 using std::min;
43 using std::list;
44 using boost::shared_ptr;
45
46 /** @param f Film.
47  *  @param o Options.
48  *  @param j Job that we are running within, or 0
49  *  @param minimal true to do the bare minimum of work; just run through the content.  Useful for acquiring
50  *  accurate frame counts as quickly as possible.  This generates no video or audio output.
51  *  @param ignore_length Ignore the content's claimed length when computing progress.
52  */
53 Decoder::Decoder (boost::shared_ptr<Film> f, boost::shared_ptr<const Options> o, Job* j, bool minimal, bool ignore_length)
54         : _film (f)
55         , _opt (o)
56         , _job (j)
57         , _minimal (minimal)
58         , _ignore_length (ignore_length)
59         , _video_frame_index (0)
60         , _delay_line (0)
61         , _delay_in_frames (0)
62         , _audio_frames_processed (0)
63 {
64         
65 }
66
67 Decoder::~Decoder ()
68 {
69         delete _delay_line;
70 }
71
72 /** Start off a decode processing run */
73 void
74 Decoder::process_begin ()
75 {
76         _delay_in_frames = _film->audio_delay() * audio_sample_rate() / 1000;
77         delete _delay_line;
78         _delay_line = new DelayLine (audio_channels(), _delay_in_frames);
79
80         _audio_frames_processed = 0;
81 }
82
83 /** Finish off a decode processing run */
84 void
85 Decoder::process_end ()
86 {
87         if (_delay_in_frames < 0 && _opt->decode_audio && audio_channels()) {
88                 shared_ptr<AudioBuffers> b (new AudioBuffers (audio_channels(), -_delay_in_frames));
89                 b->make_silent ();
90                 emit_audio (b);
91         }
92
93         /* If we cut the decode off, the audio may be short; push some silence
94            in to get it to the right length.
95         */
96
97         int64_t const video_length_in_audio_frames = ((int64_t) video_frame_index() * audio_sample_rate() / frames_per_second());
98         int64_t const audio_short_by_frames = video_length_in_audio_frames - _audio_frames_processed;
99
100         _film->log()->log (
101                 String::compose ("Source length is %1 (%2 audio frames); %3 frames of audio processed.",
102                                  video_frame_index(),
103                                  video_length_in_audio_frames,
104                                  _audio_frames_processed)
105                 );
106         
107         if (audio_short_by_frames > 0 && _opt->decode_audio && audio_channels()) {
108
109                 _film->log()->log (String::compose ("Source length is %1; %2 frames of audio processed.", video_frame_index(), _audio_frames_processed));
110                 _film->log()->log (String::compose ("Adding %1 frames of silence to the end.", audio_short_by_frames));
111
112                 shared_ptr<AudioBuffers> b (new AudioBuffers (audio_channels(), audio_short_by_frames));
113                 b->make_silent ();
114                 emit_audio (b);
115         }
116 }
117
118 /** Start decoding */
119 void
120 Decoder::go ()
121 {
122         process_begin ();
123
124         if (_job && !_film->dcp_length()) {
125                 _job->set_progress_unknown ();
126         }
127
128         while (pass () == false) {
129                 if (_job && _film->dcp_length()) {
130                         _job->set_progress (float (_video_frame_index) / _film->dcp_length().get());
131                 }
132         }
133
134         process_end ();
135 }
136
137 /** Run one pass.  This may or may not generate any actual video / audio data;
138  *  some decoders may require several passes to generate a single frame.
139  *  @return true if we have finished processing all data; otherwise false.
140  */
141 bool
142 Decoder::pass ()
143 {
144         if (!_ignore_length && _video_frame_index >= _film->dcp_length()) {
145                 return true;
146         }
147
148         return do_pass ();
149 }
150
151 /** Called by subclasses to tell the world that some audio data is ready
152  *  @param data Audio data, in Film::audio_sample_format.
153  *  @param size Number of bytes of data.
154  */
155 void
156 Decoder::process_audio (uint8_t* data, int size)
157 {
158         if (size == 0) {
159                 return;
160         }
161         
162         assert (_film->audio_channels());
163         assert (bytes_per_audio_sample());
164         
165         /* Deinterleave and convert to float */
166
167         assert ((size % (bytes_per_audio_sample() * audio_channels())) == 0);
168
169         int const total_samples = size / bytes_per_audio_sample();
170         int const frames = total_samples / _film->audio_channels();
171         shared_ptr<AudioBuffers> audio (new AudioBuffers (audio_channels(), frames));
172
173         switch (audio_sample_format()) {
174         case AV_SAMPLE_FMT_S16:
175         {
176                 int16_t* p = (int16_t *) data;
177                 int sample = 0;
178                 int channel = 0;
179                 for (int i = 0; i < total_samples; ++i) {
180                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
181
182                         ++channel;
183                         if (channel == _film->audio_channels()) {
184                                 channel = 0;
185                                 ++sample;
186                         }
187                 }
188         }
189         break;
190
191         case AV_SAMPLE_FMT_S32:
192         {
193                 int32_t* p = (int32_t *) data;
194                 int sample = 0;
195                 int channel = 0;
196                 for (int i = 0; i < total_samples; ++i) {
197                         audio->data(channel)[sample] = float(*p++) / (1 << 31);
198
199                         ++channel;
200                         if (channel == _film->audio_channels()) {
201                                 channel = 0;
202                                 ++sample;
203                         }
204                 }
205         }
206
207         case AV_SAMPLE_FMT_FLTP:
208         {
209                 float* p = reinterpret_cast<float*> (data);
210                 for (int i = 0; i < _film->audio_channels(); ++i) {
211                         memcpy (audio->data(i), p, frames * sizeof(float));
212                         p += frames;
213                 }
214         }
215         break;
216
217         default:
218                 assert (false);
219         }
220
221         /* Maybe apply gain */
222         if (_film->audio_gain() != 0) {
223                 float const linear_gain = pow (10, _film->audio_gain() / 20);
224                 for (int i = 0; i < _film->audio_channels(); ++i) {
225                         for (int j = 0; j < frames; ++j) {
226                                 audio->data(i)[j] *= linear_gain;
227                         }
228                 }
229         }
230
231         _delay_line->feed (audio);
232         emit_audio (audio);
233 }
234
235 void
236 Decoder::emit_audio (shared_ptr<AudioBuffers> audio)
237 {
238         Audio (audio);
239         _audio_frames_processed += audio->frames ();
240 }
241
242 /** Called by subclasses to tell the world that some video data is ready.
243  *  We do some post-processing / filtering then emit it for listeners.
244  *  @param frame to decode; caller manages memory.
245  */
246 void
247 Decoder::process_video (AVFrame* frame)
248 {
249         if (_minimal) {
250                 ++_video_frame_index;
251                 return;
252         }
253
254         /* Use Film::length here as our one may be wrong */
255
256         if (_opt->decode_video_skip != 0 && (_video_frame_index % _opt->decode_video_skip) != 0) {
257                 ++_video_frame_index;
258                 return;
259         }
260
261         shared_ptr<FilterGraph> graph;
262
263         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
264         while (i != _filter_graphs.end() && !(*i)->can_process (Size (frame->width, frame->height), (AVPixelFormat) frame->format)) {
265                 ++i;
266         }
267
268         if (i == _filter_graphs.end ()) {
269                 graph.reset (new FilterGraph (_film, this, _opt->apply_crop, Size (frame->width, frame->height), (AVPixelFormat) frame->format));
270                 _filter_graphs.push_back (graph);
271                 _film->log()->log (String::compose ("New graph for %1x%2, pixel format %3", frame->width, frame->height, frame->format));
272         } else {
273                 graph = *i;
274         }
275
276         list<shared_ptr<Image> > images = graph->process (frame);
277
278         for (list<shared_ptr<Image> >::iterator i = images.begin(); i != images.end(); ++i) {
279                 if (_opt->black_after > 0 && _video_frame_index > _opt->black_after) {
280                         (*i)->make_black ();
281                 }
282                 
283                 shared_ptr<Subtitle> sub;
284                 if (_timed_subtitle && _timed_subtitle->displayed_at (double (video_frame_index()) / _film->frames_per_second())) {
285                         sub = _timed_subtitle->subtitle ();
286                 }
287                 
288                 TIMING ("Decoder emits %1", _video_frame_index);
289                 Video (*i, _video_frame_index, sub);
290                 ++_video_frame_index;
291                 _last_image = *i;
292                 _last_subtitle = sub;
293         }
294 }
295
296 void
297 Decoder::repeat_last_video ()
298 {
299         if (!_last_image) {
300                 _last_image.reset (new CompactImage (pixel_format(), native_size()));
301                 _last_image->make_black ();
302         }
303         
304         Video (_last_image, _video_frame_index, _last_subtitle);
305         ++_video_frame_index;
306 }
307
308 void
309 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
310 {
311         _timed_subtitle = s;
312         
313         if (_timed_subtitle && _opt->apply_crop) {
314                 Position const p = _timed_subtitle->subtitle()->position ();
315                 _timed_subtitle->subtitle()->set_position (Position (p.x - _film->crop().left, p.y - _film->crop().top));
316         }
317 }
318
319
320 int
321 Decoder::bytes_per_audio_sample () const
322 {
323         return av_get_bytes_per_sample (audio_sample_format ());
324 }