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