2 Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
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.
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.
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.
20 /** @file src/decoder.cc
21 * @brief Parent class for decoders of content.
27 #include <libavfilter/avfiltergraph.h>
28 #include <libavfilter/buffersrc.h>
29 #if (LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 77) || LIBAVFILTER_VERSION_MAJOR == 3
30 #include <libavfilter/avcodec.h>
31 #include <libavfilter/buffersink.h>
32 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
33 #include <libavfilter/vsrc_buffer.h>
35 #include <libavformat/avio.h>
40 #include "film_state.h"
42 #include "exceptions.h"
48 #include "delay_line.h"
49 #include "ffmpeg_compatibility.h"
52 using namespace boost;
54 /** @param s FilmState of the Film.
56 * @param j Job that we are running within, or 0
57 * @param l Log to use.
58 * @param minimal true to do the bare minimum of work; just run through the content. Useful for acquiring
59 * accurate frame counts as quickly as possible. This generates no video or audio output.
60 * @param ignore_length Ignore the content's claimed length when computing progress.
62 Decoder::Decoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
68 , _ignore_length (ignore_length)
70 , _buffer_src_context (0)
71 , _buffer_sink_context (0)
75 , _have_setup_video_filters (false)
78 , _audio_frames_processed (0)
80 if (_opt->decode_video_frequency != 0 && _fs->length == 0) {
81 throw DecodeError ("cannot do a partial decode if length == 0");
91 Decoder::process_begin ()
93 if (_fs->audio_sample_rate != dcp_audio_sample_rate (_fs->audio_sample_rate)) {
95 _swr_context = swr_alloc_set_opts (
97 audio_channel_layout(),
98 audio_sample_format(),
99 dcp_audio_sample_rate (_fs->audio_sample_rate),
100 audio_channel_layout(),
101 audio_sample_format(),
102 _fs->audio_sample_rate,
106 swr_init (_swr_context);
108 throw DecodeError ("Cannot resample audio as libswresample is not present");
116 _delay_in_bytes = _fs->audio_delay * _fs->audio_sample_rate * _fs->audio_channels * _fs->bytes_per_sample() / 1000;
118 _delay_line = new DelayLine (_delay_in_bytes);
120 _audio_frames_processed = 0;
124 Decoder::process_end ()
131 uint8_t buffer[256 * _fs->bytes_per_sample() * _fs->audio_channels];
136 int const frames = swr_convert (_swr_context, out, 256, 0, 0);
139 throw DecodeError ("could not run sample-rate converter");
147 int available = _delay_line->feed (buffer, frames * _fs->audio_channels * _fs->bytes_per_sample());
148 Audio (buffer, available);
151 swr_free (&_swr_context);
155 if (_delay_in_bytes < 0) {
156 uint8_t remainder[-_delay_in_bytes];
157 _delay_line->get_remaining (remainder);
158 _audio_frames_processed += _delay_in_bytes / (_fs->audio_channels * _fs->bytes_per_sample());
159 Audio (remainder, _delay_in_bytes);
162 /* If we cut the decode off, the audio may be short; push some silence
163 in to get it to the right length.
166 int const audio_short_by_frames =
167 (decoding_frames() * dcp_audio_sample_rate (_fs->audio_sample_rate) / _fs->frames_per_second)
168 - _audio_frames_processed;
170 int bytes = audio_short_by_frames * _fs->audio_channels * _fs->bytes_per_sample();
172 int const silence_size = 64 * 1024;
173 uint8_t silence[silence_size];
174 memset (silence, 0, silence_size);
177 int const t = min (bytes, silence_size);
183 /** Start decoding */
189 if (_job && _ignore_length) {
190 _job->set_progress_unknown ();
193 while (pass () == false) {
194 if (_job && !_ignore_length) {
195 _job->set_progress (float (_video_frame) / decoding_frames ());
202 /** @return Number of frames that we will be decoding */
204 Decoder::decoding_frames () const
206 if (_opt->num_frames > 0) {
207 return _opt->num_frames;
213 /** Run one pass. This may or may not generate any actual video / audio data;
214 * some decoders may require several passes to generate a single frame.
215 * @return true if we have finished processing all data; otherwise false.
220 if (!_have_setup_video_filters) {
221 setup_video_filters ();
222 _have_setup_video_filters = true;
225 if (_opt->num_frames != 0 && _video_frame >= _opt->num_frames) {
232 /** Called by subclasses to tell the world that some audio data is ready
233 * @param data Interleaved audio data, in FilmState::audio_sample_format.
234 * @param size Number of bytes of data.
237 Decoder::process_audio (uint8_t* data, int size)
239 /* Here's samples per channel */
240 int const samples = size / _fs->bytes_per_sample();
243 /* And here's frames (where 1 frame is a collection of samples, 1 for each channel,
244 so for 5.1 a frame would be 6 samples)
246 int const frames = samples / _fs->audio_channels;
249 /* Maybe apply gain */
250 if (_fs->audio_gain != 0) {
251 float const linear_gain = pow (10, _fs->audio_gain / 20);
253 switch (_fs->audio_sample_format) {
254 case AV_SAMPLE_FMT_S16:
255 for (int i = 0; i < samples; ++i) {
256 /* XXX: assumes little-endian; also we should probably be dithering here */
258 /* unsigned sample */
259 int const ou = p[0] | (p[1] << 8);
262 int const os = ou >= 0x8000 ? (- 0x10000 + ou) : ou;
264 /* signed sample with altered gain */
265 int const gs = int (os * linear_gain);
267 /* unsigned sample with altered gain */
268 int const gu = gs > 0 ? gs : (0x10000 + gs);
272 p[1] = (gu & 0xff00) >> 8;
281 /* This is a buffer we might use if we are sample-rate converting;
282 it will need freeing if so.
284 uint8_t* out_buffer = 0;
286 /* Maybe sample-rate convert */
290 uint8_t const * in[2] = {
295 /* Compute the resampled frame count and add 32 for luck */
296 int const out_buffer_size_frames = ceil (frames * float (dcp_audio_sample_rate (_fs->audio_sample_rate)) / _fs->audio_sample_rate) + 32;
297 int const out_buffer_size_bytes = out_buffer_size_frames * _fs->audio_channels * _fs->bytes_per_sample();
298 out_buffer = new uint8_t[out_buffer_size_bytes];
306 int out_frames = swr_convert (_swr_context, out, out_buffer_size_frames, in, frames);
307 if (out_frames < 0) {
308 throw DecodeError ("could not run sample-rate converter");
311 /* And point our variables at the resampled audio */
313 size = out_frames * _fs->audio_channels * _fs->bytes_per_sample();
317 /* Update the number of audio frames we've pushed to the encoder */
318 _audio_frames_processed += size / (_fs->audio_channels * _fs->bytes_per_sample ());
320 /* Push into the delay line and then tell the world what we've got */
321 int available = _delay_line->feed (data, size);
322 Audio (data, available);
324 /* Delete the sample-rate conversion buffer, if it exists */
328 /** Called by subclasses to tell the world that some video data is ready.
329 * We do some post-processing / filtering then emit it for listeners.
330 * @param frame to decode; caller manages memory.
333 Decoder::process_video (AVFrame* frame)
340 /* Use FilmState::length here as our one may be wrong */
343 if (_opt->decode_video_frequency != 0) {
344 gap = _fs->length / _opt->decode_video_frequency;
347 if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
352 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 61
354 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0) < 0) {
355 throw DecodeError ("could not push buffer into filter chain.");
358 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
361 par.num = sample_aspect_ratio_numerator ();
362 par.den = sample_aspect_ratio_denominator ();
364 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
365 throw DecodeError ("could not push buffer into filter chain.");
370 if (av_buffersrc_write_frame (_buffer_src_context, frame) < 0) {
371 throw DecodeError ("could not push buffer into filter chain.");
376 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15 && LIBAVFILTER_VERSION_MINOR <= 61
377 while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
379 while (av_buffersink_read (_buffer_sink_context, 0)) {
382 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15
384 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
386 throw DecodeError ("could not request filtered frame");
389 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
393 AVFilterBufferRef* filter_buffer;
394 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
401 /* This takes ownership of filter_buffer */
402 shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
404 if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
405 image->make_black ();
408 Video (image, _video_frame);
415 /** Set up a video filtering chain to include cropping and any filters that are specified
419 Decoder::setup_video_filters ()
422 Size size_after_crop;
424 if (_opt->apply_crop) {
425 size_after_crop = _fs->cropped_size (native_size ());
426 fs << crop_string (Position (_fs->crop.left, _fs->crop.top), size_after_crop);
428 size_after_crop = native_size ();
429 fs << crop_string (Position (0, 0), size_after_crop);
432 string filters = Filter::ffmpeg_strings (_fs->filters).first;
433 if (!filters.empty ()) {
437 filters += fs.str ();
439 avfilter_register_all ();
441 AVFilterGraph* graph = avfilter_graph_alloc();
443 throw DecodeError ("Could not create filter graph.");
446 AVFilter* buffer_src = avfilter_get_by_name("buffer");
447 if (buffer_src == 0) {
448 throw DecodeError ("Could not find buffer src filter");
451 AVFilter* buffer_sink = get_sink ();
454 a << native_size().width << ":"
455 << native_size().height << ":"
456 << pixel_format() << ":"
457 << time_base_numerator() << ":"
458 << time_base_denominator() << ":"
459 << sample_aspect_ratio_numerator() << ":"
460 << sample_aspect_ratio_denominator();
463 if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
464 throw DecodeError ("could not create buffer source");
467 enum PixelFormat pixel_formats[] = { pixel_format(), PIX_FMT_NONE };
468 if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, pixel_formats, graph) < 0) {
469 throw DecodeError ("could not create buffer sink.");
472 AVFilterInOut* outputs = avfilter_inout_alloc ();
473 outputs->name = av_strdup("in");
474 outputs->filter_ctx = _buffer_src_context;
475 outputs->pad_idx = 0;
478 AVFilterInOut* inputs = avfilter_inout_alloc ();
479 inputs->name = av_strdup("out");
480 inputs->filter_ctx = _buffer_sink_context;
484 _log->log ("Using filter chain `" + filters + "'");
486 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
487 if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
488 throw DecodeError ("could not set up filter graph.");
491 if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
492 throw DecodeError ("could not set up filter graph.");
496 if (avfilter_graph_config (graph, 0) < 0) {
497 throw DecodeError ("could not configure filter graph.");
500 /* XXX: leaking `inputs' / `outputs' ? */