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 #ifndef DVDOMATIC_FFMPEG_0_8_3
30 #include <libavfilter/avcodec.h>
31 #include <libavfilter/buffersink.h>
33 #include <libavformat/avio.h>
35 #include <samplerate.h>
39 #include "film_state.h"
41 #include "exceptions.h"
47 #include "delay_line.h"
48 #include "ffmpeg_compatibility.h"
51 using namespace boost;
53 /** @param s FilmState of the Film.
55 * @param j Job that we are running within, or 0
56 * @param l Log to use.
57 * @param minimal true to do the bare minimum of work; just run through the content. Useful for acquiring
58 * accurate frame counts as quickly as possible. This generates no video or audio output.
59 * @param ignore_length Ignore the content's claimed length when computing progress.
61 Decoder::Decoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
67 , _ignore_length (ignore_length)
69 , _buffer_src_context (0)
70 , _buffer_sink_context (0)
72 , _have_setup_video_filters (false)
75 , _audio_frames_processed (0)
77 if (_opt->decode_video_frequency != 0 && _fs->length == 0) {
78 throw DecodeError ("cannot do a partial decode if length == 0");
88 Decoder::process_begin ()
90 if (_fs->audio_sample_rate != dcp_audio_sample_rate (_fs->audio_sample_rate)) {
91 _swr_context = swr_alloc_set_opts (
93 audio_channel_layout(),
94 audio_sample_format(),
95 dcp_audio_sample_rate (_fs->audio_sample_rate),
96 audio_channel_layout(),
97 audio_sample_format(),
98 _fs->audio_sample_rate,
102 swr_init (_swr_context);
107 _delay_in_bytes = _fs->audio_delay * _fs->audio_sample_rate * _fs->audio_channels * _fs->bytes_per_sample() / 1000;
109 _delay_line = new DelayLine (_delay_in_bytes);
111 _audio_frames_processed = 0;
115 Decoder::process_end ()
121 uint8_t buffer[256 * _fs->bytes_per_sample() * _fs->audio_channels];
126 int const frames = swr_convert (_swr_context, out, 256, 0, 0);
129 throw DecodeError ("could not run sample-rate converter");
137 int available = _delay_line->feed (buffer, frames * _fs->audio_channels * _fs->bytes_per_sample());
138 Audio (buffer, available);
141 cout << "mopped up " << mop << "\n";
143 swr_free (&_swr_context);
146 if (_delay_in_bytes < 0) {
147 uint8_t remainder[-_delay_in_bytes];
148 _delay_line->get_remaining (remainder);
149 _audio_frames_processed += _delay_in_bytes / (audio_channels() * _fs->bytes_per_sample());
150 Audio (remainder, _delay_in_bytes);
153 /* If we cut the decode off, the audio may be short; push some silence
154 in to get it to the right length.
157 int const audio_short_by_frames = (decoding_frames() * dcp_audio_sample_rate (_fs->audio_sample_rate) / _fs->frames_per_second) - _audio_frames_processed;
159 int bytes = audio_short_by_frames * audio_channels() * _fs->bytes_per_sample();
161 int const silence_size = 64 * 1024;
162 uint8_t silence[silence_size];
163 memset (silence, 0, silence_size);
166 int const t = min (bytes, silence_size);
172 /** Start decoding */
178 if (_job && _ignore_length) {
179 _job->set_progress_unknown ();
182 while (pass () == false) {
183 if (_job && !_ignore_length) {
184 _job->set_progress (float (_video_frame) / decoding_frames ());
191 /** @return Number of frames that we will be decoding */
193 Decoder::decoding_frames () const
195 if (_opt->num_frames > 0) {
196 return _opt->num_frames;
202 /** Run one pass. This may or may not generate any actual video / audio data;
203 * some decoders may require several passes to generate a single frame.
204 * @return true if we have finished processing all data; otherwise false.
209 if (!_have_setup_video_filters) {
210 setup_video_filters ();
211 _have_setup_video_filters = true;
214 if (_opt->num_frames != 0 && _video_frame >= _opt->num_frames) {
221 /** Called by subclasses to tell the world that some audio data is ready */
223 Decoder::process_audio (uint8_t* data, int size)
225 int const samples = size / _fs->bytes_per_sample();
226 int const frames = samples / _fs->audio_channels;
228 if (_fs->audio_gain != 0) {
229 float const linear_gain = pow (10, _fs->audio_gain / 20);
231 switch (_fs->audio_sample_format) {
232 case AV_SAMPLE_FMT_S16:
233 for (int i = 0; i < samples; ++i) {
234 /* XXX: assumes little-endian; also we should probably be dithering here */
235 int const ou = p[0] | (p[1] << 8);
236 int const os = ou >= 0x8000 ? (- 0x10000 + ou) : ou;
237 int const gs = int (os * linear_gain);
238 int const gu = gs > 0 ? gs : (0x10000 + gs);
240 p[1] = (gu & 0xff00) >> 8;
249 uint8_t* out_buffer = 0;
253 uint8_t const * in[2] = {
258 int const out_buffer_size_frames = ceil (frames * float (dcp_audio_sample_rate (_fs->audio_sample_rate)) / _fs->audio_sample_rate) + 32;
259 int const out_buffer_size_bytes = out_buffer_size_frames * _fs->audio_channels * _fs->bytes_per_sample();
260 out_buffer = new uint8_t[out_buffer_size_bytes];
267 int out_frames = swr_convert (_swr_context, out, out_buffer_size_frames, in, frames);
268 if (out_frames < 0) {
269 throw DecodeError ("could not run sample-rate converter");
273 size = out_frames * _fs->audio_channels * _fs->bytes_per_sample();
276 /* Update the number of audio frames we've pushed to the encoder */
277 _audio_frames_processed += size / (_fs->audio_channels * _fs->bytes_per_sample ());
279 int available = _delay_line->feed (data, size);
280 Audio (data, available);
285 /** Called by subclasses to tell the world that some video data is ready.
286 * We do some post-processing / filtering then emit it for listeners.
287 * @param frame to decode; caller manages memory.
290 Decoder::process_video (AVFrame* frame)
297 /* Use FilmState::length here as our one may be wrong */
300 if (_opt->decode_video_frequency != 0) {
301 gap = _fs->length / _opt->decode_video_frequency;
304 if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
309 #ifdef DVDOMATIC_FFMPEG_0_8_3
312 par.num = sample_aspect_ratio_numerator ();
313 par.den = sample_aspect_ratio_denominator ();
315 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
316 throw DecodeError ("could not push buffer into filter chain.");
321 if (av_buffersrc_write_frame (_buffer_src_context, frame) < 0) {
322 throw DecodeError ("could not push buffer into filter chain.");
327 #ifdef DVDOMATIC_FFMPEG_0_8_3
328 while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
330 while (av_buffersink_read (_buffer_sink_context, 0)) {
333 #ifdef DVDOMATIC_FFMPEG_0_8_3
335 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
337 throw DecodeError ("could not request filtered frame");
340 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
344 AVFilterBufferRef* filter_buffer;
345 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
352 /* This takes ownership of filter_buffer */
353 shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
355 if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
356 image->make_black ();
359 Video (image, _video_frame);
366 Decoder::setup_video_filters ()
369 Size size_after_crop;
371 if (_opt->apply_crop) {
372 size_after_crop = _fs->cropped_size (native_size ());
373 fs << crop_string (Position (_fs->left_crop, _fs->top_crop), size_after_crop);
375 size_after_crop = native_size ();
376 fs << crop_string (Position (0, 0), size_after_crop);
379 string filters = Filter::ffmpeg_strings (_fs->filters).first;
380 if (!filters.empty ()) {
384 filters += fs.str ();
386 avfilter_register_all ();
388 AVFilterGraph* graph = avfilter_graph_alloc();
390 throw DecodeError ("Could not create filter graph.");
393 AVFilter* buffer_src = avfilter_get_by_name("buffer");
394 if (buffer_src == 0) {
395 throw DecodeError ("Could not find buffer src filter");
398 AVFilter* buffer_sink = get_sink ();
401 a << native_size().width << ":"
402 << native_size().height << ":"
403 << pixel_format() << ":"
404 << time_base_numerator() << ":"
405 << time_base_denominator() << ":"
406 << sample_aspect_ratio_numerator() << ":"
407 << sample_aspect_ratio_denominator();
410 if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
411 throw DecodeError ("could not create buffer source");
414 enum PixelFormat pixel_formats[] = { pixel_format(), PIX_FMT_NONE };
415 if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, pixel_formats, graph) < 0) {
416 throw DecodeError ("could not create buffer sink.");
419 AVFilterInOut* outputs = avfilter_inout_alloc ();
420 outputs->name = av_strdup("in");
421 outputs->filter_ctx = _buffer_src_context;
422 outputs->pad_idx = 0;
425 AVFilterInOut* inputs = avfilter_inout_alloc ();
426 inputs->name = av_strdup("out");
427 inputs->filter_ctx = _buffer_sink_context;
431 _log->log ("Using filter chain `" + filters + "'");
432 #ifdef DVDOMATIC_FFMPEG_0_8_3
433 if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
435 if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
438 throw DecodeError ("could not set up filter graph.");
441 if (avfilter_graph_config (graph, 0) < 0) {
442 throw DecodeError ("could not configure filter graph.");
445 /* XXX: leaking `inputs' / `outputs' ? */