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/vsrc_buffer.h>
29 #include <libavformat/avio.h>
34 #include "film_state.h"
36 #include "exceptions.h"
42 #include "delay_line.h"
43 #include "ffmpeg_compatibility.h"
46 using namespace boost;
48 /** @param s FilmState of the Film.
50 * @param j Job that we are running within, or 0
51 * @param l Log to use.
52 * @param minimal true to do the bare minimum of work; just run through the content. Useful for acquiring
53 * accurate frame counts as quickly as possible. This generates no video or audio output.
54 * @param ignore_length Ignore the content's claimed length when computing progress.
56 Decoder::Decoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
62 , _ignore_length (ignore_length)
64 , _buffer_src_context (0)
65 , _buffer_sink_context (0)
66 , _have_setup_video_filters (false)
70 if (_opt->decode_video_frequency != 0 && _fs->length == 0) {
71 throw DecodeError ("cannot do a partial decode if length == 0");
81 Decoder::process_begin ()
83 /* This assumes 2 bytes per sample */
84 _delay_in_bytes = _fs->audio_delay * _fs->audio_sample_rate * _fs->audio_channels * 2 / 1000;
86 _delay_line = new DelayLine (_delay_in_bytes);
90 Decoder::process_end ()
92 if (_delay_in_bytes < 0) {
93 uint8_t remainder[-_delay_in_bytes];
94 _delay_line->get_remaining (remainder);
95 Audio (remainder, _delay_in_bytes);
105 if (_job && _ignore_length) {
106 _job->set_progress_unknown ();
109 while (pass () == false) {
110 if (_job && !_ignore_length) {
111 _job->set_progress (float (_video_frame) / decoding_frames ());
118 /** @return Number of frames that we will be decoding */
120 Decoder::decoding_frames () const
122 if (_opt->num_frames > 0) {
123 return _opt->num_frames;
129 /** Run one pass. This may or may not generate any actual video / audio data;
130 * some decoders may require several passes to generate a single frame.
131 * @return true if we have finished processing all data; otherwise false.
136 if (!_have_setup_video_filters) {
137 setup_video_filters ();
138 _have_setup_video_filters = true;
141 if (_opt->num_frames != 0 && _video_frame >= _opt->num_frames) {
148 /** Called by subclasses to tell the world that some audio data is ready */
150 Decoder::process_audio (uint8_t* data, int channels, int size)
152 if (_fs->audio_gain != 0) {
153 float const linear_gain = pow (10, _fs->audio_gain / 20);
155 int const samples = size / 2;
156 switch (_fs->audio_sample_format) {
157 case AV_SAMPLE_FMT_S16:
158 for (int i = 0; i < samples; ++i) {
159 /* XXX: assumes little-endian; also we should probably be dithering here */
160 int const ou = p[0] | (p[1] << 8);
161 int const os = ou >= 0x8000 ? (- 0x10000 + ou) : ou;
162 int const gs = int (os * linear_gain);
163 int const gu = gs > 0 ? gs : (0x10000 + gs);
165 p[1] = (gu & 0xff00) >> 8;
174 int available = _delay_line->feed (data, size);
175 Audio (data, available);
178 /** Called by subclasses to tell the world that some video data is ready.
179 * We do some post-processing / filtering then emit it for listeners.
180 * @param frame to decode; caller manages memory.
183 Decoder::process_video (AVFrame* frame)
190 /* Use FilmState::length here as our one may be wrong */
193 if (_opt->decode_video_frequency != 0) {
194 gap = _fs->length / _opt->decode_video_frequency;
197 if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
202 #ifdef DVDOMATIC_FFMPEG_0_8_3
205 par.num = sample_aspect_ratio_numerator ();
206 par.den = sample_aspect_ratio_denominator ();
208 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
209 throw DecodeError ("could not push buffer into filter chain.");
214 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0) < 0) {
215 throw DecodeError ("could not push buffer into filter chain.");
220 while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
222 #ifdef DVDOMATIC_FFMPEG_0_8_3
224 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
226 throw DecodeError ("could not request filtered frame");
229 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
233 AVFilterBufferRef* filter_buffer;
234 if (avbuffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
241 /* This takes ownership of filter_buffer */
242 shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
244 if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
245 image->make_black ();
248 Video (image, _video_frame);
255 Decoder::setup_video_filters ()
258 Size size_after_crop;
260 if (_opt->apply_crop) {
261 size_after_crop = _fs->cropped_size (native_size ());
262 fs << crop_string (Position (_fs->left_crop, _fs->top_crop), size_after_crop);
264 size_after_crop = native_size ();
265 fs << crop_string (Position (0, 0), size_after_crop);
268 string filters = Filter::ffmpeg_strings (_fs->filters).first;
269 if (!filters.empty ()) {
273 filters += fs.str ();
275 avfilter_register_all ();
277 AVFilterGraph* graph = avfilter_graph_alloc();
279 throw DecodeError ("Could not create filter graph.");
282 AVFilter* buffer_src = avfilter_get_by_name("buffer");
283 if (buffer_src == 0) {
284 throw DecodeError ("Could not find buffer src filter");
287 AVFilter* buffer_sink = get_sink ();
290 a << native_size().width << ":"
291 << native_size().height << ":"
292 << pixel_format() << ":"
293 << time_base_numerator() << ":"
294 << time_base_denominator() << ":"
295 << sample_aspect_ratio_numerator() << ":"
296 << sample_aspect_ratio_denominator();
299 if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
300 throw DecodeError ("could not create buffer source");
303 enum PixelFormat pixel_formats[] = { pixel_format(), PIX_FMT_NONE };
304 if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, pixel_formats, graph) < 0) {
305 throw DecodeError ("could not create buffer sink.");
308 AVFilterInOut* outputs = avfilter_inout_alloc ();
309 outputs->name = av_strdup("in");
310 outputs->filter_ctx = _buffer_src_context;
311 outputs->pad_idx = 0;
314 AVFilterInOut* inputs = avfilter_inout_alloc ();
315 inputs->name = av_strdup("out");
316 inputs->filter_ctx = _buffer_sink_context;
320 _log->log ("Using filter chain `" + filters + "'");
321 #ifdef DVDOMATIC_FFMPEG_0_8_3
322 if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
324 if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
327 throw DecodeError ("could not set up filter graph.");
330 if (avfilter_graph_config (graph, 0) < 0) {
331 throw DecodeError ("could not configure filter graph.");
334 /* XXX: leaking `inputs' / `outputs' ? */