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.
26 #include <boost/lexical_cast.hpp>
28 #include <libavfilter/avfiltergraph.h>
29 #include <libavfilter/buffersrc.h>
30 #if (LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 77) || LIBAVFILTER_VERSION_MAJOR == 3
31 #include <libavfilter/avcodec.h>
32 #include <libavfilter/buffersink.h>
33 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
34 #include <libavfilter/vsrc_buffer.h>
36 #include <libavformat/avio.h>
41 #include "film_state.h"
43 #include "exceptions.h"
49 #include "delay_line.h"
50 #include "ffmpeg_compatibility.h"
54 using namespace boost;
56 /** @param s FilmState of the Film.
58 * @param j Job that we are running within, or 0
59 * @param l Log to use.
60 * @param minimal true to do the bare minimum of work; just run through the content. Useful for acquiring
61 * accurate frame counts as quickly as possible. This generates no video or audio output.
62 * @param ignore_length Ignore the content's claimed length when computing progress.
64 Decoder::Decoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
70 , _ignore_length (ignore_length)
72 , _buffer_src_context (0)
73 , _buffer_sink_context (0)
74 , _have_setup_video_filters (false)
77 , _audio_frames_processed (0)
79 if (_opt->decode_video_frequency != 0 && _fs->length() == 0) {
80 throw DecodeError ("cannot do a partial decode if length == 0");
89 /** Start off a decode processing run */
91 Decoder::process_begin ()
93 _delay_in_bytes = _fs->audio_delay() * _fs->audio_sample_rate() * _fs->audio_channels() * bytes_per_audio_sample() / 1000;
95 _delay_line = new DelayLine (_delay_in_bytes);
97 _audio_frames_processed = 0;
100 /** Finish off a decode processing run */
102 Decoder::process_end ()
104 if (_delay_in_bytes < 0) {
105 uint8_t remainder[-_delay_in_bytes];
106 _delay_line->get_remaining (remainder);
107 _audio_frames_processed += _delay_in_bytes / (_fs->audio_channels() * bytes_per_audio_sample());
108 emit_audio (remainder, -_delay_in_bytes);
111 /* If we cut the decode off, the audio may be short; push some silence
112 in to get it to the right length.
115 int64_t const video_length_in_audio_frames = ((int64_t) _fs->dcp_length() * _fs->audio_sample_rate() / _fs->frames_per_second());
116 int64_t const audio_short_by_frames = video_length_in_audio_frames - _audio_frames_processed;
119 String::compose ("DCP length is %1 (%2 audio frames); %3 frames of audio processed.",
121 video_length_in_audio_frames,
122 _audio_frames_processed)
125 if (audio_short_by_frames >= 0 && _opt->decode_audio) {
127 _log->log (String::compose ("DCP length is %1; %2 frames of audio processed.", _fs->dcp_length(), _audio_frames_processed));
128 _log->log (String::compose ("Adding %1 frames of silence to the end.", audio_short_by_frames));
130 /* XXX: this is slightly questionable; does memset () give silence with all
134 int64_t bytes = audio_short_by_frames * _fs->audio_channels() * bytes_per_audio_sample();
136 int64_t const silence_size = 16 * 1024 * _fs->audio_channels() * bytes_per_audio_sample();
137 uint8_t silence[silence_size];
138 memset (silence, 0, silence_size);
141 int64_t const t = min (bytes, silence_size);
142 emit_audio (silence, t);
148 /** Start decoding */
154 if (_job && _ignore_length) {
155 _job->set_progress_unknown ();
158 while (pass () == false) {
159 if (_job && !_ignore_length) {
160 _job->set_progress (float (_video_frame) / _fs->dcp_length());
167 /** Run one pass. This may or may not generate any actual video / audio data;
168 * some decoders may require several passes to generate a single frame.
169 * @return true if we have finished processing all data; otherwise false.
174 if (!_have_setup_video_filters) {
175 setup_video_filters ();
176 _have_setup_video_filters = true;
179 if (!_ignore_length && _video_frame >= _fs->dcp_length()) {
186 /** Called by subclasses to tell the world that some audio data is ready
187 * @param data Audio data, in FilmState::audio_sample_format.
188 * @param size Number of bytes of data.
191 Decoder::process_audio (uint8_t* data, int size)
193 /* Push into the delay line */
194 size = _delay_line->feed (data, size);
196 emit_audio (data, size);
200 Decoder::emit_audio (uint8_t* data, int size)
202 /* Deinterleave and convert to float */
204 assert ((size % (bytes_per_audio_sample() * _fs->audio_channels())) == 0);
206 int const total_samples = size / bytes_per_audio_sample();
207 int const frames = total_samples / _fs->audio_channels();
208 shared_ptr<AudioBuffers> audio (new AudioBuffers (_fs->audio_channels(), frames));
210 switch (audio_sample_format()) {
211 case AV_SAMPLE_FMT_S16:
213 int16_t* p = (int16_t *) data;
216 for (int i = 0; i < total_samples; ++i) {
217 audio->data(channel)[sample] = float(*p++) / (1 << 15);
220 if (channel == _fs->audio_channels()) {
228 case AV_SAMPLE_FMT_S32:
230 int32_t* p = (int32_t *) data;
233 for (int i = 0; i < total_samples; ++i) {
234 audio->data(channel)[sample] = float(*p++) / (1 << 31);
237 if (channel == _fs->audio_channels()) {
244 case AV_SAMPLE_FMT_FLTP:
246 float* p = reinterpret_cast<float*> (data);
247 for (int i = 0; i < _fs->audio_channels(); ++i) {
248 memcpy (audio->data(i), p, frames * sizeof(float));
258 /* Maybe apply gain */
259 if (_fs->audio_gain() != 0) {
260 float const linear_gain = pow (10, _fs->audio_gain() / 20);
261 for (int i = 0; i < _fs->audio_channels(); ++i) {
262 for (int j = 0; j < frames; ++j) {
263 audio->data(i)[j] *= linear_gain;
268 /* Update the number of audio frames we've pushed to the encoder */
269 _audio_frames_processed += audio->frames ();
274 /** Called by subclasses to tell the world that some video data is ready.
275 * We do some post-processing / filtering then emit it for listeners.
276 * @param frame to decode; caller manages memory.
279 Decoder::process_video (AVFrame* frame)
286 /* Use FilmState::length here as our one may be wrong */
289 if (_opt->decode_video_frequency != 0) {
290 gap = _fs->length() / _opt->decode_video_frequency;
293 if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
298 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 61
300 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0) < 0) {
301 throw DecodeError ("could not push buffer into filter chain.");
304 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
307 par.num = sample_aspect_ratio_numerator ();
308 par.den = sample_aspect_ratio_denominator ();
310 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
311 throw DecodeError ("could not push buffer into filter chain.");
316 if (av_buffersrc_write_frame (_buffer_src_context, frame) < 0) {
317 throw DecodeError ("could not push buffer into filter chain.");
322 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15 && LIBAVFILTER_VERSION_MINOR <= 61
323 while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
325 while (av_buffersink_read (_buffer_sink_context, 0)) {
328 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15
330 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
332 throw DecodeError ("could not request filtered frame");
335 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
339 AVFilterBufferRef* filter_buffer;
340 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
347 /* This takes ownership of filter_buffer */
348 shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
350 if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
351 image->make_black ();
354 shared_ptr<Subtitle> sub;
355 if (_timed_subtitle && _timed_subtitle->displayed_at (double (last_video_frame()) / _fs->frames_per_second())) {
356 sub = _timed_subtitle->subtitle ();
359 TIMING ("Decoder emits %1", _video_frame);
360 Video (image, _video_frame, sub);
367 /** Set up a video filtering chain to include cropping and any filters that are specified
371 Decoder::setup_video_filters ()
374 Size size_after_crop;
376 if (_opt->apply_crop) {
377 size_after_crop = _fs->cropped_size (native_size ());
378 fs << crop_string (Position (_fs->crop().left, _fs->crop().top), size_after_crop);
380 size_after_crop = native_size ();
381 fs << crop_string (Position (0, 0), size_after_crop);
384 string filters = Filter::ffmpeg_strings (_fs->filters()).first;
385 if (!filters.empty ()) {
389 filters += fs.str ();
391 avfilter_register_all ();
393 AVFilterGraph* graph = avfilter_graph_alloc();
395 throw DecodeError ("Could not create filter graph.");
398 AVFilter* buffer_src = avfilter_get_by_name("buffer");
399 if (buffer_src == 0) {
400 throw DecodeError ("Could not find buffer src filter");
403 AVFilter* buffer_sink = get_sink ();
406 a << native_size().width << ":"
407 << native_size().height << ":"
408 << pixel_format() << ":"
409 << time_base_numerator() << ":"
410 << time_base_denominator() << ":"
411 << sample_aspect_ratio_numerator() << ":"
412 << sample_aspect_ratio_denominator();
416 if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
417 throw DecodeError ("could not create buffer source");
420 AVBufferSinkParams* sink_params = av_buffersink_params_alloc ();
421 PixelFormat* pixel_fmts = new PixelFormat[2];
422 pixel_fmts[0] = pixel_format ();
423 pixel_fmts[1] = PIX_FMT_NONE;
424 sink_params->pixel_fmts = pixel_fmts;
426 if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, sink_params, graph) < 0) {
427 throw DecodeError ("could not create buffer sink.");
430 AVFilterInOut* outputs = avfilter_inout_alloc ();
431 outputs->name = av_strdup("in");
432 outputs->filter_ctx = _buffer_src_context;
433 outputs->pad_idx = 0;
436 AVFilterInOut* inputs = avfilter_inout_alloc ();
437 inputs->name = av_strdup("out");
438 inputs->filter_ctx = _buffer_sink_context;
442 _log->log ("Using filter chain `" + filters + "'");
444 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
445 if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
446 throw DecodeError ("could not set up filter graph.");
449 if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
450 throw DecodeError ("could not set up filter graph.");
454 if (avfilter_graph_config (graph, 0) < 0) {
455 throw DecodeError ("could not configure filter graph.");
458 /* XXX: leaking `inputs' / `outputs' ? */
462 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
466 if (_opt->apply_crop) {
467 Position const p = _timed_subtitle->subtitle()->position ();
468 _timed_subtitle->subtitle()->set_position (Position (p.x - _fs->crop().left, p.y - _fs->crop().top));
474 Decoder::bytes_per_audio_sample () const
476 return av_get_bytes_per_sample (audio_sample_format ());