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