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