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