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