Merge branch 'resample-drop-frame'
[dcpomatic.git] / src / lib / decoder.cc
1 /*
2     Copyright (C) 2012 Carl Hetherington <cth@carlh.net>
3
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.
8
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.
13
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.
17
18 */
19
20 /** @file  src/decoder.cc
21  *  @brief Parent class for decoders of content.
22  */
23
24 #include <iostream>
25 #include <stdint.h>
26 #include <boost/lexical_cast.hpp>
27 extern "C" {
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>
35 #endif
36 #include <libavformat/avio.h>
37 }
38 #include "film.h"
39 #include "format.h"
40 #include "job.h"
41 #include "film_state.h"
42 #include "options.h"
43 #include "exceptions.h"
44 #include "image.h"
45 #include "util.h"
46 #include "log.h"
47 #include "decoder.h"
48 #include "filter.h"
49 #include "delay_line.h"
50 #include "ffmpeg_compatibility.h"
51
52 using namespace std;
53 using namespace boost;
54
55 /** @param s FilmState of the Film.
56  *  @param o Options.
57  *  @param j Job that we are running within, or 0
58  *  @param l Log to use.
59  *  @param minimal true to do the bare minimum of work; just run through the content.  Useful for acquiring
60  *  accurate frame counts as quickly as possible.  This generates no video or audio output.
61  *  @param ignore_length Ignore the content's claimed length when computing progress.
62  */
63 Decoder::Decoder (boost::shared_ptr<const FilmState> s, boost::shared_ptr<const Options> o, Job* j, Log* l, bool minimal, bool ignore_length)
64         : _fs (s)
65         , _opt (o)
66         , _job (j)
67         , _log (l)
68         , _minimal (minimal)
69         , _ignore_length (ignore_length)
70         , _video_frame (0)
71         , _buffer_src_context (0)
72         , _buffer_sink_context (0)
73         , _have_setup_video_filters (false)
74         , _delay_line (0)
75         , _delay_in_bytes (0)
76         , _audio_frames_processed (0)
77 {
78         if (_opt->decode_video_frequency != 0 && _fs->length == 0) {
79                 throw DecodeError ("cannot do a partial decode if length == 0");
80         }
81 }
82
83 Decoder::~Decoder ()
84 {
85         delete _delay_line;
86 }
87
88 /** Start off a decode processing run */
89 void
90 Decoder::process_begin ()
91 {
92         _delay_in_bytes = _fs->audio_delay * _fs->audio_sample_rate * _fs->audio_channels * _fs->bytes_per_sample() / 1000;
93         delete _delay_line;
94         _delay_line = new DelayLine (_delay_in_bytes);
95
96         _audio_frames_processed = 0;
97 }
98
99 /** Finish off a decode processing run */
100 void
101 Decoder::process_end ()
102 {
103         if (_delay_in_bytes < 0) {
104                 uint8_t remainder[-_delay_in_bytes];
105                 _delay_line->get_remaining (remainder);
106                 _audio_frames_processed += _delay_in_bytes / (_fs->audio_channels * _fs->bytes_per_sample());
107                 Audio (remainder, _delay_in_bytes);
108         }
109
110         /* If we cut the decode off, the audio may be short; push some silence
111            in to get it to the right length.
112         */
113
114         int64_t const audio_short_by_frames =
115                 ((int64_t) decoding_frames() * _fs->target_sample_rate() / _fs->frames_per_second)
116                 - _audio_frames_processed;
117
118         if (audio_short_by_frames >= 0) {
119
120                 stringstream s;
121                 s << "Adding " << audio_short_by_frames << " frames of silence to the end.";
122                 _log->log (s.str ());
123
124                 int64_t bytes = audio_short_by_frames * _fs->audio_channels * _fs->bytes_per_sample();
125                 
126                 int64_t const silence_size = 64 * 1024;
127                 uint8_t silence[silence_size];
128                 memset (silence, 0, silence_size);
129                 
130                 while (bytes) {
131                         int64_t const t = min (bytes, silence_size);
132                         Audio (silence, t);
133                         bytes -= t;
134                 }
135         }
136 }
137
138 /** Start decoding */
139 void
140 Decoder::go ()
141 {
142         process_begin ();
143
144         if (_job && _ignore_length) {
145                 _job->set_progress_unknown ();
146         }
147
148         while (pass () == false) {
149                 if (_job && !_ignore_length) {
150                         _job->set_progress (float (_video_frame) / decoding_frames ());
151                 }
152         }
153
154         process_end ();
155 }
156
157 /** @return Number of frames that we will be decoding */
158 int
159 Decoder::decoding_frames () const
160 {
161         if (_opt->num_frames > 0) {
162                 return _opt->num_frames;
163         }
164         
165         return _fs->length;
166 }
167
168 /** Run one pass.  This may or may not generate any actual video / audio data;
169  *  some decoders may require several passes to generate a single frame.
170  *  @return true if we have finished processing all data; otherwise false.
171  */
172 bool
173 Decoder::pass ()
174 {
175         if (!_have_setup_video_filters) {
176                 setup_video_filters ();
177                 _have_setup_video_filters = true;
178         }
179         
180         if (_opt->num_frames != 0 && _video_frame >= _opt->num_frames) {
181                 return true;
182         }
183
184         return do_pass ();
185 }
186
187 /** Called by subclasses to tell the world that some audio data is ready
188  *  @param data Interleaved audio data, in FilmState::audio_sample_format.
189  *  @param size Number of bytes of data.
190  */
191 void
192 Decoder::process_audio (uint8_t* data, int size)
193 {
194         /* Samples per channel */
195         int const samples = size / _fs->bytes_per_sample();
196
197         /* Maybe apply gain */
198         if (_fs->audio_gain != 0) {
199                 float const linear_gain = pow (10, _fs->audio_gain / 20);
200                 uint8_t* p = data;
201                 switch (_fs->audio_sample_format) {
202                 case AV_SAMPLE_FMT_S16:
203                         for (int i = 0; i < samples; ++i) {
204                                 /* XXX: assumes little-endian; also we should probably be dithering here */
205
206                                 /* unsigned sample */
207                                 int const ou = p[0] | (p[1] << 8);
208
209                                 /* signed sample */
210                                 int const os = ou >= 0x8000 ? (- 0x10000 + ou) : ou;
211
212                                 /* signed sample with altered gain */
213                                 int const gs = int (os * linear_gain);
214
215                                 /* unsigned sample with altered gain */
216                                 int const gu = gs > 0 ? gs : (0x10000 + gs);
217
218                                 /* write it back */
219                                 p[0] = gu & 0xff;
220                                 p[1] = (gu & 0xff00) >> 8;
221                                 p += 2;
222                         }
223                         break;
224                 default:
225                         assert (false);
226                 }
227         }
228
229         /* Update the number of audio frames we've pushed to the encoder */
230         _audio_frames_processed += size / (_fs->audio_channels * _fs->bytes_per_sample ());
231
232         /* Push into the delay line and then tell the world what we've got */
233         int available = _delay_line->feed (data, size);
234         Audio (data, available);
235 }
236
237 /** Called by subclasses to tell the world that some video data is ready.
238  *  We do some post-processing / filtering then emit it for listeners.
239  *  @param frame to decode; caller manages memory.
240  */
241 void
242 Decoder::process_video (AVFrame* frame)
243 {
244         if (_minimal) {
245                 ++_video_frame;
246                 return;
247         }
248
249         /* Use FilmState::length here as our one may be wrong */
250
251         int gap = 0;
252         if (_opt->decode_video_frequency != 0) {
253                 gap = _fs->length / _opt->decode_video_frequency;
254         }
255
256         if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
257                 ++_video_frame;
258                 return;
259         }
260
261 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 61
262
263         if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0) < 0) {
264                 throw DecodeError ("could not push buffer into filter chain.");
265         }
266
267 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
268
269         AVRational par;
270         par.num = sample_aspect_ratio_numerator ();
271         par.den = sample_aspect_ratio_denominator ();
272
273         if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
274                 throw DecodeError ("could not push buffer into filter chain.");
275         }
276
277 #else
278
279         if (av_buffersrc_write_frame (_buffer_src_context, frame) < 0) {
280                 throw DecodeError ("could not push buffer into filter chain.");
281         }
282
283 #endif  
284         
285 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15 && LIBAVFILTER_VERSION_MINOR <= 61        
286         while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
287 #else
288         while (av_buffersink_read (_buffer_sink_context, 0)) {
289 #endif          
290
291 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15
292                 
293                 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
294                 if (r < 0) {
295                         throw DecodeError ("could not request filtered frame");
296                 }
297                 
298                 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
299                 
300 #else
301
302                 AVFilterBufferRef* filter_buffer;
303                 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
304                         filter_buffer = 0;
305                 }
306
307 #endif          
308                 
309                 if (filter_buffer) {
310                         /* This takes ownership of filter_buffer */
311                         shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
312
313                         if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
314                                 image->make_black ();
315                         }
316
317                         TIMING ("Decoder emits %1", _video_frame);
318                         Video (image, _video_frame);
319                         ++_video_frame;
320                 }
321         }
322 }
323
324
325 /** Set up a video filtering chain to include cropping and any filters that are specified
326  *  by the Film.
327  */
328 void
329 Decoder::setup_video_filters ()
330 {
331         stringstream fs;
332         Size size_after_crop;
333         
334         if (_opt->apply_crop) {
335                 size_after_crop = _fs->cropped_size (native_size ());
336                 fs << crop_string (Position (_fs->crop.left, _fs->crop.top), size_after_crop);
337         } else {
338                 size_after_crop = native_size ();
339                 fs << crop_string (Position (0, 0), size_after_crop);
340         }
341
342         string filters = Filter::ffmpeg_strings (_fs->filters).first;
343         if (!filters.empty ()) {
344                 filters += ",";
345         }
346
347         filters += fs.str ();
348
349         avfilter_register_all ();
350         
351         AVFilterGraph* graph = avfilter_graph_alloc();
352         if (graph == 0) {
353                 throw DecodeError ("Could not create filter graph.");
354         }
355
356         AVFilter* buffer_src = avfilter_get_by_name("buffer");
357         if (buffer_src == 0) {
358                 throw DecodeError ("Could not find buffer src filter");
359         }
360
361         AVFilter* buffer_sink = get_sink ();
362
363         stringstream a;
364         a << native_size().width << ":"
365           << native_size().height << ":"
366           << pixel_format() << ":"
367           << time_base_numerator() << ":"
368           << time_base_denominator() << ":"
369           << sample_aspect_ratio_numerator() << ":"
370           << sample_aspect_ratio_denominator();
371
372         int r;
373
374         if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
375                 throw DecodeError ("could not create buffer source");
376         }
377
378         AVBufferSinkParams* sink_params = av_buffersink_params_alloc ();
379         PixelFormat* pixel_fmts = new PixelFormat[2];
380         pixel_fmts[0] = pixel_format ();
381         pixel_fmts[1] = PIX_FMT_NONE;
382         sink_params->pixel_fmts = pixel_fmts;
383         
384         if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, sink_params, graph) < 0) {
385                 throw DecodeError ("could not create buffer sink.");
386         }
387
388         AVFilterInOut* outputs = avfilter_inout_alloc ();
389         outputs->name = av_strdup("in");
390         outputs->filter_ctx = _buffer_src_context;
391         outputs->pad_idx = 0;
392         outputs->next = 0;
393
394         AVFilterInOut* inputs = avfilter_inout_alloc ();
395         inputs->name = av_strdup("out");
396         inputs->filter_ctx = _buffer_sink_context;
397         inputs->pad_idx = 0;
398         inputs->next = 0;
399
400         _log->log ("Using filter chain `" + filters + "'");
401
402 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
403         if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
404                 throw DecodeError ("could not set up filter graph.");
405         }
406 #else   
407         if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
408                 throw DecodeError ("could not set up filter graph.");
409         }
410 #endif  
411         
412         if (avfilter_graph_config (graph, 0) < 0) {
413                 throw DecodeError ("could not configure filter graph.");
414         }
415
416         /* XXX: leaking `inputs' / `outputs' ? */
417 }
418