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