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>
42 #include "exceptions.h"
48 #include "delay_line.h"
49 #include "ffmpeg_compatibility.h"
53 using namespace boost;
57 * @param j Job that we are running within, or 0
58 * @param minimal true to do the bare minimum of work; just run through the content. Useful for acquiring
59 * accurate frame counts as quickly as possible. This generates no video or audio output.
60 * @param ignore_length Ignore the content's claimed length when computing progress.
62 Decoder::Decoder (boost::shared_ptr<Film> f, boost::shared_ptr<const Options> o, Job* j, bool minimal, bool ignore_length)
67 , _ignore_length (ignore_length)
69 , _buffer_src_context (0)
70 , _buffer_sink_context (0)
71 , _have_setup_video_filters (false)
74 , _audio_frames_processed (0)
76 if (_opt->decode_video_frequency != 0 && _film->length() == 0) {
77 throw DecodeError ("cannot do a partial decode if length == 0");
86 /** Start off a decode processing run */
88 Decoder::process_begin ()
90 _delay_in_bytes = _film->audio_delay() * _film->audio_sample_rate() * _film->audio_channels() * bytes_per_audio_sample() / 1000;
92 _delay_line = new DelayLine (_delay_in_bytes);
94 _audio_frames_processed = 0;
97 /** Finish off a decode processing run */
99 Decoder::process_end ()
101 if (_delay_in_bytes < 0) {
102 uint8_t remainder[-_delay_in_bytes];
103 _delay_line->get_remaining (remainder);
104 _audio_frames_processed += _delay_in_bytes / (_film->audio_channels() * bytes_per_audio_sample());
105 emit_audio (remainder, -_delay_in_bytes);
108 /* If we cut the decode off, the audio may be short; push some silence
109 in to get it to the right length.
112 int64_t const video_length_in_audio_frames = ((int64_t) _film->dcp_length() * _film->audio_sample_rate() / _film->frames_per_second());
113 int64_t const audio_short_by_frames = video_length_in_audio_frames - _audio_frames_processed;
116 String::compose ("DCP length is %1 (%2 audio frames); %3 frames of audio processed.",
118 video_length_in_audio_frames,
119 _audio_frames_processed)
122 if (audio_short_by_frames >= 0 && _opt->decode_audio) {
124 _log->log (String::compose ("DCP length is %1; %2 frames of audio processed.", _film->dcp_length(), _audio_frames_processed));
125 _log->log (String::compose ("Adding %1 frames of silence to the end.", audio_short_by_frames));
127 /* XXX: this is slightly questionable; does memset () give silence with all
131 int64_t bytes = audio_short_by_frames * _film->audio_channels() * bytes_per_audio_sample();
133 int64_t const silence_size = 16 * 1024 * _film->audio_channels() * bytes_per_audio_sample();
134 uint8_t silence[silence_size];
135 memset (silence, 0, silence_size);
138 int64_t const t = min (bytes, silence_size);
139 emit_audio (silence, t);
145 /** Start decoding */
151 if (_job && _ignore_length) {
152 _job->set_progress_unknown ();
155 while (pass () == false) {
156 if (_job && !_ignore_length) {
157 _job->set_progress (float (_video_frame) / _film->dcp_length());
164 /** Run one pass. This may or may not generate any actual video / audio data;
165 * some decoders may require several passes to generate a single frame.
166 * @return true if we have finished processing all data; otherwise false.
171 if (!_have_setup_video_filters) {
172 setup_video_filters ();
173 _have_setup_video_filters = true;
176 if (!_ignore_length && _video_frame >= _film->dcp_length()) {
183 /** Called by subclasses to tell the world that some audio data is ready
184 * @param data Audio data, in Film::audio_sample_format.
185 * @param size Number of bytes of data.
188 Decoder::process_audio (uint8_t* data, int size)
190 /* Push into the delay line */
191 size = _delay_line->feed (data, size);
193 emit_audio (data, size);
197 Decoder::emit_audio (uint8_t* data, int size)
199 /* Deinterleave and convert to float */
201 assert ((size % (bytes_per_audio_sample() * _film->audio_channels())) == 0);
203 int const total_samples = size / bytes_per_audio_sample();
204 int const frames = total_samples / _film->audio_channels();
205 shared_ptr<AudioBuffers> audio (new AudioBuffers (_film->audio_channels(), frames));
207 switch (audio_sample_format()) {
208 case AV_SAMPLE_FMT_S16:
210 int16_t* p = (int16_t *) data;
213 for (int i = 0; i < total_samples; ++i) {
214 audio->data(channel)[sample] = float(*p++) / (1 << 15);
217 if (channel == _film->audio_channels()) {
225 case AV_SAMPLE_FMT_S32:
227 int32_t* p = (int32_t *) data;
230 for (int i = 0; i < total_samples; ++i) {
231 audio->data(channel)[sample] = float(*p++) / (1 << 31);
234 if (channel == _film->audio_channels()) {
241 case AV_SAMPLE_FMT_FLTP:
243 float* p = reinterpret_cast<float*> (data);
244 for (int i = 0; i < _film->audio_channels(); ++i) {
245 memcpy (audio->data(i), p, frames * sizeof(float));
255 /* Maybe apply gain */
256 if (_film->audio_gain() != 0) {
257 float const linear_gain = pow (10, _film->audio_gain() / 20);
258 for (int i = 0; i < _film->audio_channels(); ++i) {
259 for (int j = 0; j < frames; ++j) {
260 audio->data(i)[j] *= linear_gain;
265 /* Update the number of audio frames we've pushed to the encoder */
266 _audio_frames_processed += audio->frames ();
271 /** Called by subclasses to tell the world that some video data is ready.
272 * We do some post-processing / filtering then emit it for listeners.
273 * @param frame to decode; caller manages memory.
276 Decoder::process_video (AVFrame* frame)
283 /* Use Film::length here as our one may be wrong */
286 if (_opt->decode_video_frequency != 0) {
287 gap = _film->length() / _opt->decode_video_frequency;
290 if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
295 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 61
297 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0) < 0) {
298 throw DecodeError ("could not push buffer into filter chain.");
301 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
304 par.num = sample_aspect_ratio_numerator ();
305 par.den = sample_aspect_ratio_denominator ();
307 if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
308 throw DecodeError ("could not push buffer into filter chain.");
313 if (av_buffersrc_write_frame (_buffer_src_context, frame) < 0) {
314 throw DecodeError ("could not push buffer into filter chain.");
319 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15 && LIBAVFILTER_VERSION_MINOR <= 61
320 while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
322 while (av_buffersink_read (_buffer_sink_context, 0)) {
325 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15
327 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
329 throw DecodeError ("could not request filtered frame");
332 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
336 AVFilterBufferRef* filter_buffer;
337 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
344 /* This takes ownership of filter_buffer */
345 shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
347 if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
348 image->make_black ();
351 shared_ptr<Subtitle> sub;
352 if (_timed_subtitle && _timed_subtitle->displayed_at (double (last_video_frame()) / _film->frames_per_second())) {
353 sub = _timed_subtitle->subtitle ();
356 TIMING ("Decoder emits %1", _video_frame);
357 Video (image, _video_frame, sub);
364 /** Set up a video filtering chain to include cropping and any filters that are specified
368 Decoder::setup_video_filters ()
371 Size size_after_crop;
373 if (_opt->apply_crop) {
374 size_after_crop = _film->cropped_size (native_size ());
375 fs << crop_string (Position (_film->crop().left, _film->crop().top), size_after_crop);
377 size_after_crop = native_size ();
378 fs << crop_string (Position (0, 0), size_after_crop);
381 string filters = Filter::ffmpeg_strings (_film->filters()).first;
382 if (!filters.empty ()) {
386 filters += fs.str ();
388 avfilter_register_all ();
390 AVFilterGraph* graph = avfilter_graph_alloc();
392 throw DecodeError ("Could not create filter graph.");
395 AVFilter* buffer_src = avfilter_get_by_name("buffer");
396 if (buffer_src == 0) {
397 throw DecodeError ("Could not find buffer src filter");
400 AVFilter* buffer_sink = get_sink ();
403 a << native_size().width << ":"
404 << native_size().height << ":"
405 << pixel_format() << ":"
406 << time_base_numerator() << ":"
407 << time_base_denominator() << ":"
408 << sample_aspect_ratio_numerator() << ":"
409 << sample_aspect_ratio_denominator();
413 if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
414 throw DecodeError ("could not create buffer source");
417 AVBufferSinkParams* sink_params = av_buffersink_params_alloc ();
418 PixelFormat* pixel_fmts = new PixelFormat[2];
419 pixel_fmts[0] = pixel_format ();
420 pixel_fmts[1] = PIX_FMT_NONE;
421 sink_params->pixel_fmts = pixel_fmts;
423 if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, sink_params, graph) < 0) {
424 throw DecodeError ("could not create buffer sink.");
427 AVFilterInOut* outputs = avfilter_inout_alloc ();
428 outputs->name = av_strdup("in");
429 outputs->filter_ctx = _buffer_src_context;
430 outputs->pad_idx = 0;
433 AVFilterInOut* inputs = avfilter_inout_alloc ();
434 inputs->name = av_strdup("out");
435 inputs->filter_ctx = _buffer_sink_context;
439 _log->log ("Using filter chain `" + filters + "'");
441 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
442 if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
443 throw DecodeError ("could not set up filter graph.");
446 if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
447 throw DecodeError ("could not set up filter graph.");
451 if (avfilter_graph_config (graph, 0) < 0) {
452 throw DecodeError ("could not configure filter graph.");
455 /* XXX: leaking `inputs' / `outputs' ? */
459 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
463 if (_timed_subtitle && _opt->apply_crop) {
464 Position const p = _timed_subtitle->subtitle()->position ();
465 _timed_subtitle->subtitle()->set_position (Position (p.x - _film->crop().left, p.y - _film->crop().top));
471 Decoder::bytes_per_audio_sample () const
473 return av_get_bytes_per_sample (audio_sample_format ());