Try to clean up source length handling.
[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 "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 #include "subtitle.h"
51
52 using std::string;
53 using std::stringstream;
54 using std::min;
55 using boost::shared_ptr;
56
57 /** @param f Film.
58  *  @param o Options.
59  *  @param j Job that we are running within, or 0
60  *  @param minimal true to do the bare minimum of work; just run through the content.  Useful for acquiring
61  *  accurate frame counts as quickly as possible.  This generates no video or audio output.
62  *  @param ignore_length Ignore the content's claimed length when computing progress.
63  */
64 Decoder::Decoder (boost::shared_ptr<Film> f, boost::shared_ptr<const Options> o, Job* j, bool minimal, bool ignore_length)
65         : _film (f)
66         , _opt (o)
67         , _job (j)
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 && !_film->length()) {
79                 throw DecodeError ("cannot do a partial decode if length is unknown");
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 = _film->audio_delay() * audio_sample_rate() * audio_channels() * bytes_per_audio_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 / (audio_channels() * bytes_per_audio_sample());
107                 emit_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 video_length_in_audio_frames = ((int64_t) last_video_frame() * audio_sample_rate() / frames_per_second());
115         int64_t const audio_short_by_frames = video_length_in_audio_frames - _audio_frames_processed;
116
117         _log->log (
118                 String::compose ("DCP length is %1 (%2 audio frames); %3 frames of audio processed.",
119                                  last_video_frame(),
120                                  video_length_in_audio_frames,
121                                  _audio_frames_processed)
122                 );
123         
124         if (audio_short_by_frames >= 0 && _opt->decode_audio) {
125
126                 _log->log (String::compose ("DCP length is %1; %2 frames of audio processed.", last_video_frame(), _audio_frames_processed));
127                 _log->log (String::compose ("Adding %1 frames of silence to the end.", audio_short_by_frames));
128
129                 /* XXX: this is slightly questionable; does memset () give silence with all
130                    sample formats?
131                 */
132
133                 int64_t bytes = audio_short_by_frames * _film->audio_channels() * bytes_per_audio_sample();
134                 
135                 int64_t const silence_size = 16 * 1024 * _film->audio_channels() * bytes_per_audio_sample();
136                 uint8_t silence[silence_size];
137                 memset (silence, 0, silence_size);
138                 
139                 while (bytes) {
140                         int64_t const t = min (bytes, silence_size);
141                         emit_audio (silence, t);
142                         bytes -= t;
143                 }
144         }
145 }
146
147 /** Start decoding */
148 void
149 Decoder::go ()
150 {
151         process_begin ();
152
153         if (_job && !_film->dcp_length()) {
154                 _job->set_progress_unknown ();
155         }
156
157         while (pass () == false) {
158                 if (_job && _film->dcp_length()) {
159                         _job->set_progress (float (_video_frame) / _film->dcp_length().get());
160                 }
161         }
162
163         process_end ();
164 }
165
166 /** Run one pass.  This may or may not generate any actual video / audio data;
167  *  some decoders may require several passes to generate a single frame.
168  *  @return true if we have finished processing all data; otherwise false.
169  */
170 bool
171 Decoder::pass ()
172 {
173         if (!_have_setup_video_filters) {
174                 setup_video_filters ();
175                 _have_setup_video_filters = true;
176         }
177         
178         if (!_ignore_length && _video_frame >= _film->dcp_length()) {
179                 return true;
180         }
181
182         return do_pass ();
183 }
184
185 /** Called by subclasses to tell the world that some audio data is ready
186  *  @param data Audio data, in Film::audio_sample_format.
187  *  @param size Number of bytes of data.
188  */
189 void
190 Decoder::process_audio (uint8_t* data, int size)
191 {
192         /* Push into the delay line */
193         size = _delay_line->feed (data, size);
194
195         emit_audio (data, size);
196 }
197
198 void
199 Decoder::emit_audio (uint8_t* data, int size)
200 {
201         /* Deinterleave and convert to float */
202
203         assert ((size % (bytes_per_audio_sample() * _film->audio_channels())) == 0);
204
205         int const total_samples = size / bytes_per_audio_sample();
206         int const frames = total_samples / _film->audio_channels();
207         shared_ptr<AudioBuffers> audio (new AudioBuffers (_film->audio_channels(), frames));
208
209         switch (audio_sample_format()) {
210         case AV_SAMPLE_FMT_S16:
211         {
212                 int16_t* p = (int16_t *) data;
213                 int sample = 0;
214                 int channel = 0;
215                 for (int i = 0; i < total_samples; ++i) {
216                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
217
218                         ++channel;
219                         if (channel == _film->audio_channels()) {
220                                 channel = 0;
221                                 ++sample;
222                         }
223                 }
224         }
225         break;
226
227         case AV_SAMPLE_FMT_S32:
228         {
229                 int32_t* p = (int32_t *) data;
230                 int sample = 0;
231                 int channel = 0;
232                 for (int i = 0; i < total_samples; ++i) {
233                         audio->data(channel)[sample] = float(*p++) / (1 << 31);
234
235                         ++channel;
236                         if (channel == _film->audio_channels()) {
237                                 channel = 0;
238                                 ++sample;
239                         }
240                 }
241         }
242
243         case AV_SAMPLE_FMT_FLTP:
244         {
245                 float* p = reinterpret_cast<float*> (data);
246                 for (int i = 0; i < _film->audio_channels(); ++i) {
247                         memcpy (audio->data(i), p, frames * sizeof(float));
248                         p += frames;
249                 }
250         }
251         break;
252
253         default:
254                 assert (false);
255         }
256
257         /* Maybe apply gain */
258         if (_film->audio_gain() != 0) {
259                 float const linear_gain = pow (10, _film->audio_gain() / 20);
260                 for (int i = 0; i < _film->audio_channels(); ++i) {
261                         for (int j = 0; j < frames; ++j) {
262                                 audio->data(i)[j] *= linear_gain;
263                         }
264                 }
265         }
266
267         /* Update the number of audio frames we've pushed to the encoder */
268         _audio_frames_processed += audio->frames ();
269
270         Audio (audio);
271 }
272
273 /** Called by subclasses to tell the world that some video data is ready.
274  *  We do some post-processing / filtering then emit it for listeners.
275  *  @param frame to decode; caller manages memory.
276  */
277 void
278 Decoder::process_video (AVFrame* frame)
279 {
280         if (_minimal) {
281                 ++_video_frame;
282                 return;
283         }
284
285         /* Use Film::length here as our one may be wrong */
286
287         int gap = 0;
288         if (_opt->decode_video_frequency != 0) {
289                 gap = _film->length().get() / _opt->decode_video_frequency;
290         }
291
292         if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
293                 ++_video_frame;
294                 return;
295         }
296
297 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 53 && LIBAVFILTER_VERSION_MINOR <= 61
298
299         if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0) < 0) {
300                 throw DecodeError ("could not push buffer into filter chain.");
301         }
302
303 #elif LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
304
305         AVRational par;
306         par.num = sample_aspect_ratio_numerator ();
307         par.den = sample_aspect_ratio_denominator ();
308
309         if (av_vsrc_buffer_add_frame (_buffer_src_context, frame, 0, par) < 0) {
310                 throw DecodeError ("could not push buffer into filter chain.");
311         }
312
313 #else
314
315         if (av_buffersrc_write_frame (_buffer_src_context, frame) < 0) {
316                 throw DecodeError ("could not push buffer into filter chain.");
317         }
318
319 #endif  
320         
321 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15 && LIBAVFILTER_VERSION_MINOR <= 61        
322         while (avfilter_poll_frame (_buffer_sink_context->inputs[0])) {
323 #else
324         while (av_buffersink_read (_buffer_sink_context, 0)) {
325 #endif          
326
327 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR >= 15
328                 
329                 int r = avfilter_request_frame (_buffer_sink_context->inputs[0]);
330                 if (r < 0) {
331                         throw DecodeError ("could not request filtered frame");
332                 }
333                 
334                 AVFilterBufferRef* filter_buffer = _buffer_sink_context->inputs[0]->cur_buf;
335                 
336 #else
337
338                 AVFilterBufferRef* filter_buffer;
339                 if (av_buffersink_get_buffer_ref (_buffer_sink_context, &filter_buffer, 0) < 0) {
340                         filter_buffer = 0;
341                 }
342
343 #endif          
344                 
345                 if (filter_buffer) {
346                         /* This takes ownership of filter_buffer */
347                         shared_ptr<Image> image (new FilterBufferImage ((PixelFormat) frame->format, filter_buffer));
348
349                         if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
350                                 image->make_black ();
351                         }
352
353                         shared_ptr<Subtitle> sub;
354                         if (_timed_subtitle && _timed_subtitle->displayed_at (double (last_video_frame()) / _film->frames_per_second())) {
355                                 sub = _timed_subtitle->subtitle ();
356                         }
357
358                         TIMING ("Decoder emits %1", _video_frame);
359                         Video (image, _video_frame, sub);
360                         ++_video_frame;
361                 }
362         }
363 }
364
365
366 /** Set up a video filtering chain to include cropping and any filters that are specified
367  *  by the Film.
368  */
369 void
370 Decoder::setup_video_filters ()
371 {
372         stringstream fs;
373         Size size_after_crop;
374         
375         if (_opt->apply_crop) {
376                 size_after_crop = _film->cropped_size (native_size ());
377                 fs << crop_string (Position (_film->crop().left, _film->crop().top), size_after_crop);
378         } else {
379                 size_after_crop = native_size ();
380                 fs << crop_string (Position (0, 0), size_after_crop);
381         }
382
383         string filters = Filter::ffmpeg_strings (_film->filters()).first;
384         if (!filters.empty ()) {
385                 filters += ",";
386         }
387
388         filters += fs.str ();
389
390         avfilter_register_all ();
391         
392         AVFilterGraph* graph = avfilter_graph_alloc();
393         if (graph == 0) {
394                 throw DecodeError ("Could not create filter graph.");
395         }
396
397         AVFilter* buffer_src = avfilter_get_by_name("buffer");
398         if (buffer_src == 0) {
399                 throw DecodeError ("Could not find buffer src filter");
400         }
401
402         AVFilter* buffer_sink = get_sink ();
403
404         stringstream a;
405         a << native_size().width << ":"
406           << native_size().height << ":"
407           << pixel_format() << ":"
408           << time_base_numerator() << ":"
409           << time_base_denominator() << ":"
410           << sample_aspect_ratio_numerator() << ":"
411           << sample_aspect_ratio_denominator();
412
413         int r;
414
415         if ((r = avfilter_graph_create_filter (&_buffer_src_context, buffer_src, "in", a.str().c_str(), 0, graph)) < 0) {
416                 throw DecodeError ("could not create buffer source");
417         }
418
419         AVBufferSinkParams* sink_params = av_buffersink_params_alloc ();
420         PixelFormat* pixel_fmts = new PixelFormat[2];
421         pixel_fmts[0] = pixel_format ();
422         pixel_fmts[1] = PIX_FMT_NONE;
423         sink_params->pixel_fmts = pixel_fmts;
424         
425         if (avfilter_graph_create_filter (&_buffer_sink_context, buffer_sink, "out", 0, sink_params, graph) < 0) {
426                 throw DecodeError ("could not create buffer sink.");
427         }
428
429         AVFilterInOut* outputs = avfilter_inout_alloc ();
430         outputs->name = av_strdup("in");
431         outputs->filter_ctx = _buffer_src_context;
432         outputs->pad_idx = 0;
433         outputs->next = 0;
434
435         AVFilterInOut* inputs = avfilter_inout_alloc ();
436         inputs->name = av_strdup("out");
437         inputs->filter_ctx = _buffer_sink_context;
438         inputs->pad_idx = 0;
439         inputs->next = 0;
440
441         _log->log ("Using filter chain `" + filters + "'");
442
443 #if LIBAVFILTER_VERSION_MAJOR == 2 && LIBAVFILTER_VERSION_MINOR == 15
444         if (avfilter_graph_parse (graph, filters.c_str(), inputs, outputs, 0) < 0) {
445                 throw DecodeError ("could not set up filter graph.");
446         }
447 #else   
448         if (avfilter_graph_parse (graph, filters.c_str(), &inputs, &outputs, 0) < 0) {
449                 throw DecodeError ("could not set up filter graph.");
450         }
451 #endif  
452         
453         if (avfilter_graph_config (graph, 0) < 0) {
454                 throw DecodeError ("could not configure filter graph.");
455         }
456
457         /* XXX: leaking `inputs' / `outputs' ? */
458 }
459
460 void
461 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
462 {
463         _timed_subtitle = s;
464         
465         if (_timed_subtitle && _opt->apply_crop) {
466                 Position const p = _timed_subtitle->subtitle()->position ();
467                 _timed_subtitle->subtitle()->set_position (Position (p.x - _film->crop().left, p.y - _film->crop().top));
468         }
469 }
470
471
472 int
473 Decoder::bytes_per_audio_sample () const
474 {
475         return av_get_bytes_per_sample (audio_sample_format ());
476 }