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