Try to make audio discard work properly.
[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 extern "C" {
28 #include <libavfilter/avfiltergraph.h>
29 #include <libavfilter/buffersrc.h>
30 #if (LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 77) || LIBAVFILTER_VERSION_MAJOR == 3
31 #include <libavfilter/avcodec.h>
32 #include <libavfilter/buffersink.h>
33 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
34 #include <libavfilter/vsrc_buffer.h>
35 #endif
36 #include <libavformat/avio.h>
37 }
38 #include "film.h"
39 #include "format.h"
40 #include "job.h"
41 #include "film_state.h"
42 #include "options.h"
43 #include "exceptions.h"
44 #include "image.h"
45 #include "util.h"
46 #include "log.h"
47 #include "decoder.h"
48 #include "filter.h"
49 #include "delay_line.h"
50 #include "ffmpeg_compatibility.h"
51 #include "subtitle.h"
52
53 using namespace std;
54 using namespace boost;
55
56 /** @param s FilmState of the Film.
57  *  @param o Options.
58  *  @param j Job that we are running within, or 0
59  *  @param l Log to use.
60  *  @param minimal true to do the bare minimum of work; just run through the content.  Useful for acquiring
61  *  accurate frame counts as quickly as possible.  This generates no video or audio output.
62  *  @param ignore_length Ignore the content's claimed length when computing progress.
63  */
64 Decoder::Decoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
65         : _fs (s)
66         , _opt (o)
67         , _job (j)
68         , _log (l)
69         , _minimal (minimal)
70         , _ignore_length (ignore_length)
71         , _video_frame (0)
72         , _buffer_src_context (0)
73         , _buffer_sink_context (0)
74         , _have_setup_video_filters (false)
75         , _delay_line (0)
76         , _delay_in_bytes (0)
77         , _audio_frames_processed (0)
78 {
79         if (_opt->decode_video_frequency != 0 && _fs->length() == 0) {
80                 throw DecodeError ("cannot do a partial decode if length == 0");
81         }
82 }
83
84 Decoder::~Decoder ()
85 {
86         delete _delay_line;
87 }
88
89 /** Start off a decode processing run */
90 void
91 Decoder::process_begin ()
92 {
93         _delay_in_bytes = _fs->total_audio_delay() * _fs->audio_sample_rate() * _fs->audio_channels() * bytes_per_audio_sample() / 1000;
94         delete _delay_line;
95         _delay_line = new DelayLine (_delay_in_bytes);
96
97         _log->log (String::compose ("Decoding audio with total delay of %1", _fs->total_audio_delay()));
98
99         _audio_frames_processed = 0;
100 }
101
102 /** Finish off a decode processing run */
103 void
104 Decoder::process_end ()
105 {
106         if (_delay_in_bytes < 0) {
107                 uint8_t remainder[-_delay_in_bytes];
108                 _delay_line->get_remaining (remainder);
109                 _audio_frames_processed += _delay_in_bytes / (_fs->audio_channels() * bytes_per_audio_sample());
110                 emit_audio (remainder, -_delay_in_bytes);
111         }
112
113         /* If we cut the decode off, the audio may be short; push some silence
114            in to get it to the right length.
115         */
116
117         int64_t const video_length_in_audio_frames = ((int64_t) _fs->dcp_length() * _fs->target_sample_rate() / _fs->frames_per_second());
118         int64_t const audio_short_by_frames = video_length_in_audio_frames - _audio_frames_processed;
119
120         _log->log (
121                 String::compose ("DCP length is %1 (%2 audio frames); %3 frames of audio processed.",
122                                  _fs->dcp_length(),
123                                  video_length_in_audio_frames,
124                                  _audio_frames_processed)
125                 );
126         
127         if (audio_short_by_frames >= 0 && _opt->decode_audio) {
128
129                 _log->log (String::compose ("DCP length is %1; %2 frames of audio processed.", _fs->dcp_length(), _audio_frames_processed));
130                 _log->log (String::compose ("Adding %1 frames of silence to the end.", audio_short_by_frames));
131
132                 int64_t bytes = audio_short_by_frames * _fs->audio_channels() * bytes_per_audio_sample();
133                 
134                 int64_t const silence_size = 16 * 1024 * _fs->audio_channels() * bytes_per_audio_sample();
135                 uint8_t silence[silence_size];
136                 memset (silence, 0, silence_size);
137                 
138                 while (bytes) {
139                         int64_t const t = min (bytes, silence_size);
140                         emit_audio (silence, t);
141                         bytes -= t;
142                 }
143         }
144 }
145
146 /** Start decoding */
147 void
148 Decoder::go ()
149 {
150         process_begin ();
151
152         if (_job && _ignore_length) {
153                 _job->set_progress_unknown ();
154         }
155
156         while (pass () == false) {
157                 if (_job && !_ignore_length) {
158                         _job->set_progress (float (_video_frame) / _fs->dcp_length());
159                 }
160         }
161
162         process_end ();
163 }
164
165 /** Run one pass.  This may or may not generate any actual video / audio data;
166  *  some decoders may require several passes to generate a single frame.
167  *  @return true if we have finished processing all data; otherwise false.
168  */
169 bool
170 Decoder::pass ()
171 {
172         if (!_have_setup_video_filters) {
173                 setup_video_filters ();
174                 _have_setup_video_filters = true;
175         }
176         
177         if (!_ignore_length && _video_frame >= _fs->dcp_length()) {
178                 return true;
179         }
180
181         return do_pass ();
182 }
183
184 /** Called by subclasses to tell the world that some audio data is ready
185  *  @param data Audio data, in FilmState::audio_sample_format.
186  *  @param size Number of bytes of data.
187  */
188 void
189 Decoder::process_audio (uint8_t* data, int size)
190 {
191         /* Push into the delay line */
192         size = _delay_line->feed (data, size);
193
194         emit_audio (data, size);
195 }
196
197 void
198 Decoder::emit_audio (uint8_t* data, int size)
199 {
200         /* Deinterleave and convert to float */
201
202         assert ((size % (bytes_per_audio_sample() * _fs->audio_channels())) == 0);
203
204         int const total_samples = size / bytes_per_audio_sample();
205         int const frames = total_samples / _fs->audio_channels();
206         shared_ptr<AudioBuffers> audio (new AudioBuffers (_fs->audio_channels(), frames));
207
208         switch (audio_sample_format()) {
209         case AV_SAMPLE_FMT_S16:
210         {
211                 int16_t* p = (int16_t *) data;
212                 int sample = 0;
213                 int channel = 0;
214                 for (int i = 0; i < total_samples; ++i) {
215                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
216
217                         ++channel;
218                         if (channel == _fs->audio_channels()) {
219                                 channel = 0;
220                                 ++sample;
221                         }
222                 }
223         }
224         break;
225
226         case AV_SAMPLE_FMT_S32:
227         {
228                 int32_t* p = (int32_t *) data;
229                 int sample = 0;
230                 int channel = 0;
231                 for (int i = 0; i < total_samples; ++i) {
232                         audio->data(channel)[sample] = float(*p++) / (1 << 31);
233
234                         ++channel;
235                         if (channel == _fs->audio_channels()) {
236                                 channel = 0;
237                                 ++sample;
238                         }
239                 }
240         }
241
242         case AV_SAMPLE_FMT_FLTP:
243         {
244                 float* p = reinterpret_cast<float*> (data);
245                 for (int i = 0; i < _fs->audio_channels(); ++i) {
246                         memcpy (audio->data(i), p, frames * sizeof(float));
247                         p += frames;
248                 }
249         }
250         break;
251
252         default:
253                 assert (false);
254         }
255
256         /* Maybe apply gain */
257         if (_fs->audio_gain() != 0) {
258                 float const linear_gain = pow (10, _fs->audio_gain() / 20);
259                 for (int i = 0; i < _fs->audio_channels(); ++i) {
260                         for (int j = 0; j < frames; ++j) {
261                                 audio->data(i)[j] *= linear_gain;
262                         }
263                 }
264         }
265
266         /* Update the number of audio frames we've pushed to the encoder */
267         _audio_frames_processed += frames;
268
269         Audio (audio);
270 }
271
272 /** Called by subclasses to tell the world that some video data is ready.
273  *  We do some post-processing / filtering then emit it for listeners.
274  *  @param frame to decode; caller manages memory.
275  */
276 void
277 Decoder::process_video (AVFrame* frame)
278 {
279         if (_minimal) {
280                 ++_video_frame;
281                 return;
282         }
283
284         /* Use FilmState::length here as our one may be wrong */
285
286         int gap = 0;
287         if (_opt->decode_video_frequency != 0) {
288                 gap = _fs->length() / _opt->decode_video_frequency;
289         }
290
291         if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
292                 ++_video_frame;
293                 return;
294         }
295
296 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 61
297
298         if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0) < 0) {
299                 throw DecodeError ("could not push buffer into filter chain.");
300         }
301
302 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
303
304         AVRational par;
305         par.num = sample_aspect_ratio_numerator ();
306         par.den = sample_aspect_ratio_denominator ();
307
308         if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
309                 throw DecodeError ("could not push buffer into filter chain.");
310         }
311
312 #else
313
314         if (av_buffersrc_write_frame (_buffer_src_context, frame) < 0) {
315                 throw DecodeError ("could not push buffer into filter chain.");
316         }
317
318 #endif  
319         
320 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15 && LIBAVFILTER_VERSION_MINOR <= 61        
321         while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
322 #else
323         while (av_buffersink_read (_buffer_sink_context, 0)) {
324 #endif          
325
326 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15
327                 
328                 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
329                 if (r < 0) {
330                         throw DecodeError ("could not request filtered frame");
331                 }
332                 
333                 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
334                 
335 #else
336
337                 AVFilterBufferRef* filter_buffer;
338                 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
339                         filter_buffer = 0;
340                 }
341
342 #endif          
343                 
344                 if (filter_buffer) {
345                         /* This takes ownership of filter_buffer */
346                         shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
347
348                         if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
349                                 image->make_black ();
350                         }
351
352                         shared_ptr<Subtitle> sub;
353                         if (_timed_subtitle && _timed_subtitle->displayed_at (double (last_video_frame()) / rint (_fs->frames_per_second()))) {
354                                 sub = _timed_subtitle->subtitle ();
355                         }
356
357                         TIMING ("Decoder emits %1", _video_frame);
358                         Video (image, _video_frame, sub);
359                         ++_video_frame;
360                 }
361         }
362 }
363
364
365 /** Set up a video filtering chain to include cropping and any filters that are specified
366  *  by the Film.
367  */
368 void
369 Decoder::setup_video_filters ()
370 {
371         stringstream fs;
372         Size size_after_crop;
373         
374         if (_opt->apply_crop) {
375                 size_after_crop = _fs->cropped_size (native_size ());
376                 fs << crop_string (Position (_fs->crop().left, _fs->crop().top), size_after_crop);
377         } else {
378                 size_after_crop = native_size ();
379                 fs << crop_string (Position (0, 0), size_after_crop);
380         }
381
382         string filters = Filter::ffmpeg_strings (_fs->filters()).first;
383         if (!filters.empty ()) {
384                 filters += ",";
385         }
386
387         filters += fs.str ();
388
389         avfilter_register_all ();
390         
391         AVFilterGraph* graph = avfilter_graph_alloc();
392         if (graph == 0) {
393                 throw DecodeError ("Could not create filter graph.");
394         }
395
396         AVFilter* buffer_src = avfilter_get_by_name("buffer");
397         if (buffer_src == 0) {
398                 throw DecodeError ("Could not find buffer src filter");
399         }
400
401         AVFilter* buffer_sink = get_sink ();
402
403         stringstream a;
404         a << native_size().width << ":"
405           << native_size().height << ":"
406           << pixel_format() << ":"
407           << time_base_numerator() << ":"
408           << time_base_denominator() << ":"
409           << sample_aspect_ratio_numerator() << ":"
410           << sample_aspect_ratio_denominator();
411
412         int r;
413
414         if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
415                 throw DecodeError ("could not create buffer source");
416         }
417
418         AVBufferSinkParams* sink_params = av_buffersink_params_alloc ();
419         PixelFormat* pixel_fmts = new PixelFormat[2];
420         pixel_fmts[0] = pixel_format ();
421         pixel_fmts[1] = PIX_FMT_NONE;
422         sink_params->pixel_fmts = pixel_fmts;
423         
424         if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, sink_params, graph) < 0) {
425                 throw DecodeError ("could not create buffer sink.");
426         }
427
428         AVFilterInOut* outputs = avfilter_inout_alloc ();
429         outputs->name = av_strdup("in");
430         outputs->filter_ctx = _buffer_src_context;
431         outputs->pad_idx = 0;
432         outputs->next = 0;
433
434         AVFilterInOut* inputs = avfilter_inout_alloc ();
435         inputs->name = av_strdup("out");
436         inputs->filter_ctx = _buffer_sink_context;
437         inputs->pad_idx = 0;
438         inputs->next = 0;
439
440         _log->log ("Using filter chain `" + filters + "'");
441
442 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
443         if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
444                 throw DecodeError ("could not set up filter graph.");
445         }
446 #else   
447         if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
448                 throw DecodeError ("could not set up filter graph.");
449         }
450 #endif  
451         
452         if (avfilter_graph_config (graph, 0) < 0) {
453                 throw DecodeError ("could not configure filter graph.");
454         }
455
456         /* XXX: leaking `inputs' / `outputs' ? */
457 }
458
459 void
460 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
461 {
462         _timed_subtitle = s;
463         
464         if (_opt->apply_crop) {
465                 Position const p = _timed_subtitle->subtitle()->position ();
466                 _timed_subtitle->subtitle()->set_position (Position (p.x - _fs->crop().left, p.y - _fs->crop().top));
467         }
468 }
469
470
471 int
472 Decoder::bytes_per_audio_sample () const
473 {
474         return av_get_bytes_per_sample (audio_sample_format ());
475 }