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>
38 #include "film_state.h"
40 #include "exceptions.h"
46 #include "delay_line.h"
47 #include "ffmpeg_compatibility.h"
50 using namespace boost;
52 /** @param s FilmState of the Film.
54 * @param j Job that we are running within, or 0
55 * @param l Log to use.
56 * @param minimal true to do the bare minimum of work; just run through the content. Useful for acquiring
57 * accurate frame counts as quickly as possible. This generates no video or audio output.
58 * @param ignore_length Ignore the content's claimed length when computing progress.
60 Decoder::Decoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
66 , _ignore_length (ignore_length)
68 , _buffer_src_context (0)
69 , _buffer_sink_context (0)
70 , _have_setup_video_filters (false)
73 , _audio_frames_processed (0)
75 if (_opt->decode_video_frequency != 0 && _fs->length == 0) {
76 throw DecodeError ("cannot do a partial decode if length == 0");
86 Decoder::process_begin ()
88 /* This assumes 2 bytes per sample */
89 _delay_in_bytes = _fs->audio_delay * _fs->audio_sample_rate * _fs->audio_channels * 2 / 1000;
91 _delay_line = new DelayLine (_delay_in_bytes);
93 _audio_frames_processed = 0;
97 Decoder::process_end ()
99 if (_delay_in_bytes < 0) {
100 uint8_t remainder[-_delay_in_bytes];
101 _delay_line->get_remaining (remainder);
102 _audio_frames_processed += _delay_in_bytes / (audio_channels() * 2);
103 Audio (remainder, _delay_in_bytes);
106 /* If we cut the decode off, the audio may be short; push some silence
107 in to get it to the right length.
110 int const audio_short_by_frames = (decoding_frames() * _fs->audio_sample_rate / _fs->frames_per_second) - _audio_frames_processed;
112 int bytes = audio_short_by_frames * audio_channels() * 2;
114 int const silence_size = 64 * 1024;
115 uint8_t silence[silence_size];
116 memset (silence, 0, silence_size);
119 int const t = min (bytes, silence_size);
125 /** Start decoding */
131 if (_job && _ignore_length) {
132 _job->set_progress_unknown ();
135 while (pass () == false) {
136 if (_job && !_ignore_length) {
137 _job->set_progress (float (_video_frame) / decoding_frames ());
144 /** @return Number of frames that we will be decoding */
146 Decoder::decoding_frames () const
148 if (_opt->num_frames > 0) {
149 return _opt->num_frames;
155 /** Run one pass. This may or may not generate any actual video / audio data;
156 * some decoders may require several passes to generate a single frame.
157 * @return true if we have finished processing all data; otherwise false.
162 if (!_have_setup_video_filters) {
163 setup_video_filters ();
164 _have_setup_video_filters = true;
167 if (_opt->num_frames != 0 && _video_frame >= _opt->num_frames) {
174 /** Called by subclasses to tell the world that some audio data is ready */
176 Decoder::process_audio (uint8_t* data, int channels, int size)
178 /* Update the number of audio frames we've pushed to the encoder;
179 2 is the hard-coded (!) number of bytes per sample.
181 _audio_frames_processed += size / (channels * 2);
183 if (_fs->audio_gain != 0) {
184 float const linear_gain = pow (10, _fs->audio_gain / 20);
186 int const samples = size / 2;
187 switch (_fs->audio_sample_format) {
188 case AV_SAMPLE_FMT_S16:
189 for (int i = 0; i < samples; ++i) {
190 /* XXX: assumes little-endian; also we should probably be dithering here */
191 int const ou = p[0] | (p[1] << 8);
192 int const os = ou >= 0x8000 ? (- 0x10000 + ou) : ou;
193 int const gs = int (os * linear_gain);
194 int const gu = gs > 0 ? gs : (0x10000 + gs);
196 p[1] = (gu & 0xff00) >> 8;
205 int available = _delay_line->feed (data, size);
206 Audio (data, available);
209 /** Called by subclasses to tell the world that some video data is ready.
210 * We do some post-processing / filtering then emit it for listeners.
211 * @param frame to decode; caller manages memory.
214 Decoder::process_video (AVFrame* frame)
221 /* Use FilmState::length here as our one may be wrong */
224 if (_opt->decode_video_frequency != 0) {
225 gap = _fs->length / _opt->decode_video_frequency;
228 if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
233 #ifdef DVDOMATIC_FFMPEG_0_8_3
236 par.num = sample_aspect_ratio_numerator ();
237 par.den = sample_aspect_ratio_denominator ();
239 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
240 throw DecodeError ("could not push buffer into filter chain.");
245 if (av_buffersrc_write_frame (_buffer_src_context, frame) < 0) {
246 throw DecodeError ("could not push buffer into filter chain.");
251 #ifdef DVDOMATIC_FFMPEG_0_8_3
252 while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
254 while (av_buffersink_read (_buffer_sink_context, 0)) {
257 #ifdef DVDOMATIC_FFMPEG_0_8_3
259 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
261 throw DecodeError ("could not request filtered frame");
264 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
268 AVFilterBufferRef* filter_buffer;
269 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
276 /* This takes ownership of filter_buffer */
277 shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
279 if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
280 image->make_black ();
283 Video (image, _video_frame);
290 Decoder::setup_video_filters ()
293 Size size_after_crop;
295 if (_opt->apply_crop) {
296 size_after_crop = _fs->cropped_size (native_size ());
297 fs << crop_string (Position (_fs->left_crop, _fs->top_crop), size_after_crop);
299 size_after_crop = native_size ();
300 fs << crop_string (Position (0, 0), size_after_crop);
303 string filters = Filter::ffmpeg_strings (_fs->filters).first;
304 if (!filters.empty ()) {
308 filters += fs.str ();
310 avfilter_register_all ();
312 AVFilterGraph* graph = avfilter_graph_alloc();
314 throw DecodeError ("Could not create filter graph.");
317 AVFilter* buffer_src = avfilter_get_by_name("buffer");
318 if (buffer_src == 0) {
319 throw DecodeError ("Could not find buffer src filter");
322 AVFilter* buffer_sink = get_sink ();
325 a << native_size().width << ":"
326 << native_size().height << ":"
327 << pixel_format() << ":"
328 << time_base_numerator() << ":"
329 << time_base_denominator() << ":"
330 << sample_aspect_ratio_numerator() << ":"
331 << sample_aspect_ratio_denominator();
334 if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
335 throw DecodeError ("could not create buffer source");
338 enum PixelFormat pixel_formats[] = { pixel_format(), PIX_FMT_NONE };
339 if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, pixel_formats, graph) < 0) {
340 throw DecodeError ("could not create buffer sink.");
343 AVFilterInOut* outputs = avfilter_inout_alloc ();
344 outputs->name = av_strdup("in");
345 outputs->filter_ctx = _buffer_src_context;
346 outputs->pad_idx = 0;
349 AVFilterInOut* inputs = avfilter_inout_alloc ();
350 inputs->name = av_strdup("out");
351 inputs->filter_ctx = _buffer_sink_context;
355 _log->log ("Using filter chain `" + filters + "'");
356 #ifdef DVDOMATIC_FFMPEG_0_8_3
357 if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
359 if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
362 throw DecodeError ("could not set up filter graph.");
365 if (avfilter_graph_config (graph, 0) < 0) {
366 throw DecodeError ("could not configure filter graph.");
369 /* XXX: leaking `inputs' / `outputs' ? */