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