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/buffersink.h>
29 #include <libavfilter/avcodec.h>
34 #include "film_state.h"
36 #include "exceptions.h"
42 #include "delay_line.h"
45 using namespace boost;
47 /** @param s FilmState of the Film.
49 * @param j Job that we are running within, or 0
50 * @param l Log to use.
51 * @param minimal true to do the bare minimum of work; just run through the content. Useful for acquiring
52 * accurate frame counts as quickly as possible. This generates no video or audio output.
53 * @param ignore_length Ignore the content's claimed length when computing progress.
55 Decoder::Decoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
61 , _ignore_length (ignore_length)
63 , _buffer_src_context (0)
64 , _buffer_sink_context (0)
65 , _have_setup_video_filters (false)
69 if (_opt->decode_video_frequency != 0 && _fs->length == 0) {
70 throw DecodeError ("cannot do a partial decode if length == 0");
80 Decoder::process_begin ()
82 /* This assumes 2 bytes per sample */
83 _delay_in_bytes = _fs->audio_delay * _fs->audio_sample_rate * _fs->audio_channels * 2 / 1000;
85 _delay_line = new DelayLine (_delay_in_bytes);
89 Decoder::process_end ()
91 if (_delay_in_bytes < 0) {
92 uint8_t remainder[-_delay_in_bytes];
93 _delay_line->get_remaining (remainder);
94 Audio (remainder, _delay_in_bytes);
104 if (_job && _ignore_length) {
105 _job->set_progress_unknown ();
108 while (pass () == false) {
109 if (_job && !_ignore_length) {
110 _job->set_progress (float (_video_frame) / decoding_frames ());
117 /** @return Number of frames that we will be decoding */
119 Decoder::decoding_frames () const
121 if (_opt->num_frames > 0) {
122 return _opt->num_frames;
128 /** Run one pass. This may or may not generate any actual video / audio data;
129 * some decoders may require several passes to generate a single frame.
130 * @return true if we have finished processing all data; otherwise false.
135 if (!_have_setup_video_filters) {
136 setup_video_filters ();
137 _have_setup_video_filters = true;
140 if (_opt->num_frames != 0 && _video_frame >= _opt->num_frames) {
147 /** Called by subclasses to tell the world that some audio data is ready */
149 Decoder::process_audio (uint8_t* data, int channels, int size)
151 if (_fs->audio_gain != 0) {
152 float const linear_gain = pow (10, _fs->audio_gain / 20);
154 int const samples = size / 2;
155 switch (_fs->audio_sample_format) {
156 case AV_SAMPLE_FMT_S16:
157 for (int i = 0; i < samples; ++i) {
158 /* XXX: assumes little-endian; also we should probably be dithering here */
159 int const ou = p[0] | (p[1] << 8);
160 int const os = ou >= 0x8000 ? (- 0x10000 + ou) : ou;
161 int const gs = int (os * linear_gain);
162 int const gu = gs > 0 ? gs : (0x10000 + gs);
164 p[1] = (gu & 0xff00) >> 8;
173 int available = _delay_line->feed (data, size);
174 Audio (data, available);
177 /** Called by subclasses to tell the world that some video data is ready.
178 * We do some post-processing / filtering then emit it for listeners.
179 * @param frame to decode; caller manages memory.
182 Decoder::process_video (AVFrame* frame)
189 /* Use FilmState::length here as our one may be wrong */
192 if (_opt->decode_video_frequency != 0) {
193 gap = _fs->length / _opt->decode_video_frequency;
196 if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
201 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0) < 0) {
202 throw DecodeError ("could not push buffer into filter chain.");
205 while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
206 AVFilterBufferRef* filter_buffer;
207 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) >= 0) {
209 /* This takes ownership of filter_buffer */
210 shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
212 if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
213 image->make_black ();
216 Video (image, _video_frame);
223 Decoder::setup_video_filters ()
226 Size size_after_crop;
228 if (_opt->apply_crop) {
229 size_after_crop = _fs->cropped_size (native_size ());
230 fs << crop_string (Position (_fs->left_crop, _fs->top_crop), size_after_crop);
232 size_after_crop = native_size ();
233 fs << crop_string (Position (0, 0), size_after_crop);
236 string filters = Filter::ffmpeg_strings (_fs->filters).first;
237 if (!filters.empty ()) {
241 filters += fs.str ();
243 avfilter_register_all ();
245 AVFilterGraph* graph = avfilter_graph_alloc();
247 throw DecodeError ("Could not create filter graph.");
250 AVFilter* buffer_src = avfilter_get_by_name("buffer");
251 if (buffer_src == 0) {
252 throw DecodeError ("Could not create buffer src filter");
255 AVFilter* buffer_sink = avfilter_get_by_name("buffersink");
256 if (buffer_sink == 0) {
257 throw DecodeError ("Could not create buffer sink filter");
261 a << native_size().width << ":"
262 << native_size().height << ":"
263 << pixel_format() << ":"
264 << time_base_numerator() << ":"
265 << time_base_denominator() << ":"
266 << sample_aspect_ratio_numerator() << ":"
267 << sample_aspect_ratio_denominator();
270 if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
271 throw DecodeError ("could not create buffer source");
274 enum PixelFormat pixel_formats[] = { pixel_format(), PIX_FMT_NONE };
275 if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, pixel_formats, graph) < 0) {
276 throw DecodeError ("could not create buffer sink.");
279 AVFilterInOut* outputs = avfilter_inout_alloc ();
280 outputs->name = av_strdup("in");
281 outputs->filter_ctx = _buffer_src_context;
282 outputs->pad_idx = 0;
285 AVFilterInOut* inputs = avfilter_inout_alloc ();
286 inputs->name = av_strdup("out");
287 inputs->filter_ctx = _buffer_sink_context;
291 _log->log ("Using filter chain `" + filters + "'");
292 if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
293 throw DecodeError ("could not set up filter graph.");
296 if (avfilter_graph_config (graph, 0) < 0) {
297 throw DecodeError ("could not configure filter graph.");