Be more checky about inputs.
[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 #include "film.h"
28 #include "format.h"
29 #include "job.h"
30 #include "options.h"
31 #include "exceptions.h"
32 #include "image.h"
33 #include "util.h"
34 #include "log.h"
35 #include "decoder.h"
36 #include "delay_line.h"
37 #include "subtitle.h"
38 #include "filter_graph.h"
39
40 using std::string;
41 using std::stringstream;
42 using std::min;
43 using std::list;
44 using boost::shared_ptr;
45
46 /** @param f Film.
47  *  @param o Options.
48  *  @param j Job that we are running within, or 0
49  *  @param minimal true to do the bare minimum of work; just run through the content.  Useful for acquiring
50  *  accurate frame counts as quickly as possible.  This generates no video or audio output.
51  *  @param ignore_length Ignore the content's claimed length when computing progress.
52  */
53 Decoder::Decoder (boost::shared_ptr<Film> f, boost::shared_ptr<const Options> o, Job* j, bool minimal, bool ignore_length)
54         : _film (f)
55         , _opt (o)
56         , _job (j)
57         , _minimal (minimal)
58         , _ignore_length (ignore_length)
59         , _video_frame (0)
60         , _delay_line (0)
61         , _delay_in_bytes (0)
62         , _audio_frames_processed (0)
63 {
64         if (_opt->decode_video_frequency != 0 && !_film->length()) {
65                 throw DecodeError ("cannot do a partial decode if length is unknown");
66         }
67 }
68
69 Decoder::~Decoder ()
70 {
71         delete _delay_line;
72 }
73
74 /** Start off a decode processing run */
75 void
76 Decoder::process_begin ()
77 {
78         _delay_in_bytes = _film->audio_delay() * audio_sample_rate() * audio_channels() * bytes_per_audio_sample() / 1000;
79         delete _delay_line;
80         _delay_line = new DelayLine (_delay_in_bytes);
81
82         _audio_frames_processed = 0;
83 }
84
85 /** Finish off a decode processing run */
86 void
87 Decoder::process_end ()
88 {
89         if (_delay_in_bytes < 0) {
90                 uint8_t remainder[-_delay_in_bytes];
91                 _delay_line->get_remaining (remainder);
92                 _audio_frames_processed += _delay_in_bytes / (audio_channels() * bytes_per_audio_sample());
93                 emit_audio (remainder, -_delay_in_bytes);
94         }
95
96         /* If we cut the decode off, the audio may be short; push some silence
97            in to get it to the right length.
98         */
99
100         int64_t const video_length_in_audio_frames = ((int64_t) video_frame() * audio_sample_rate() / frames_per_second());
101         int64_t const audio_short_by_frames = video_length_in_audio_frames - _audio_frames_processed;
102
103         _film->log()->log (
104                 String::compose ("DCP length is %1 (%2 audio frames); %3 frames of audio processed.",
105                                  video_frame(),
106                                  video_length_in_audio_frames,
107                                  _audio_frames_processed)
108                 );
109         
110         if (audio_short_by_frames >= 0 && _opt->decode_audio) {
111
112                 _film->log()->log (String::compose ("DCP length is %1; %2 frames of audio processed.", video_frame(), _audio_frames_processed));
113                 _film->log()->log (String::compose ("Adding %1 frames of silence to the end.", audio_short_by_frames));
114
115                 /* XXX: this is slightly questionable; does memset () give silence with all
116                    sample formats?
117                 */
118
119                 int64_t bytes = audio_short_by_frames * _film->audio_channels() * bytes_per_audio_sample();
120                 
121                 int64_t const silence_size = 16 * 1024 * _film->audio_channels() * bytes_per_audio_sample();
122                 uint8_t silence[silence_size];
123                 memset (silence, 0, silence_size);
124                 
125                 while (bytes) {
126                         int64_t const t = min (bytes, silence_size);
127                         emit_audio (silence, t);
128                         bytes -= t;
129                 }
130         }
131 }
132
133 /** Start decoding */
134 void
135 Decoder::go ()
136 {
137         process_begin ();
138
139         if (_job && !_film->dcp_length()) {
140                 _job->set_progress_unknown ();
141         }
142
143         while (pass () == false) {
144                 if (_job && _film->dcp_length()) {
145                         _job->set_progress (float (_video_frame) / _film->dcp_length().get());
146                 }
147         }
148
149         process_end ();
150 }
151
152 /** Run one pass.  This may or may not generate any actual video / audio data;
153  *  some decoders may require several passes to generate a single frame.
154  *  @return true if we have finished processing all data; otherwise false.
155  */
156 bool
157 Decoder::pass ()
158 {
159         if (!_ignore_length && _video_frame >= _film->dcp_length()) {
160                 return true;
161         }
162
163         return do_pass ();
164 }
165
166 /** Called by subclasses to tell the world that some audio data is ready
167  *  @param data Audio data, in Film::audio_sample_format.
168  *  @param size Number of bytes of data.
169  */
170 void
171 Decoder::process_audio (uint8_t* data, int size)
172 {
173         /* Push into the delay line */
174         size = _delay_line->feed (data, size);
175
176         emit_audio (data, size);
177 }
178
179 void
180 Decoder::emit_audio (uint8_t* data, int size)
181 {
182         if (size == 0) {
183                 return;
184         }
185         
186         assert (_film->audio_channels());
187         assert (bytes_per_audio_sample());
188         
189         /* Deinterleave and convert to float */
190
191         assert ((size % (bytes_per_audio_sample() * audio_channels())) == 0);
192
193         int const total_samples = size / bytes_per_audio_sample();
194         int const frames = total_samples / _film->audio_channels();
195         shared_ptr<AudioBuffers> audio (new AudioBuffers (audio_channels(), frames));
196
197         switch (audio_sample_format()) {
198         case AV_SAMPLE_FMT_S16:
199         {
200                 int16_t* p = (int16_t *) data;
201                 int sample = 0;
202                 int channel = 0;
203                 for (int i = 0; i < total_samples; ++i) {
204                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
205
206                         ++channel;
207                         if (channel == _film->audio_channels()) {
208                                 channel = 0;
209                                 ++sample;
210                         }
211                 }
212         }
213         break;
214
215         case AV_SAMPLE_FMT_S32:
216         {
217                 int32_t* p = (int32_t *) data;
218                 int sample = 0;
219                 int channel = 0;
220                 for (int i = 0; i < total_samples; ++i) {
221                         audio->data(channel)[sample] = float(*p++) / (1 << 31);
222
223                         ++channel;
224                         if (channel == _film->audio_channels()) {
225                                 channel = 0;
226                                 ++sample;
227                         }
228                 }
229         }
230
231         case AV_SAMPLE_FMT_FLTP:
232         {
233                 float* p = reinterpret_cast<float*> (data);
234                 for (int i = 0; i < _film->audio_channels(); ++i) {
235                         memcpy (audio->data(i), p, frames * sizeof(float));
236                         p += frames;
237                 }
238         }
239         break;
240
241         default:
242                 assert (false);
243         }
244
245         /* Maybe apply gain */
246         if (_film->audio_gain() != 0) {
247                 float const linear_gain = pow (10, _film->audio_gain() / 20);
248                 for (int i = 0; i < _film->audio_channels(); ++i) {
249                         for (int j = 0; j < frames; ++j) {
250                                 audio->data(i)[j] *= linear_gain;
251                         }
252                 }
253         }
254
255         /* Update the number of audio frames we've pushed to the encoder */
256         _audio_frames_processed += audio->frames ();
257
258         Audio (audio);
259 }
260
261 /** Called by subclasses to tell the world that some video data is ready.
262  *  We do some post-processing / filtering then emit it for listeners.
263  *  @param frame to decode; caller manages memory.
264  */
265 void
266 Decoder::process_video (AVFrame* frame)
267 {
268         if (_minimal) {
269                 ++_video_frame;
270                 return;
271         }
272
273         /* Use Film::length here as our one may be wrong */
274
275         int gap = 0;
276         if (_opt->decode_video_frequency != 0) {
277                 gap = _film->length().get() / _opt->decode_video_frequency;
278         }
279
280         if (_opt->decode_video_frequency != 0 && gap != 0 && (_video_frame % gap) != 0) {
281                 ++_video_frame;
282                 return;
283         }
284
285         shared_ptr<FilterGraph> graph;
286
287         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
288         while (i != _filter_graphs.end() && !(*i)->can_process (Size (frame->width, frame->height), (AVPixelFormat) frame->format)) {
289                 ++i;
290         }
291
292         if (i == _filter_graphs.end ()) {
293                 graph.reset (new FilterGraph (_film, this, _opt->apply_crop, Size (frame->width, frame->height), (AVPixelFormat) frame->format));
294                 _filter_graphs.push_back (graph);
295                 _film->log()->log (String::compose ("New graph for %1x%2, pixel format %3", frame->width, frame->height, frame->format));
296         } else {
297                 graph = *i;
298         }
299
300         list<shared_ptr<Image> > images = graph->process (frame);
301
302         for (list<shared_ptr<Image> >::iterator i = images.begin(); i != images.end(); ++i) {
303                 if (_opt->black_after > 0 && _video_frame > _opt->black_after) {
304                         (*i)->make_black ();
305                 }
306                 
307                 shared_ptr<Subtitle> sub;
308                 if (_timed_subtitle && _timed_subtitle->displayed_at (double (video_frame()) / _film->frames_per_second())) {
309                         sub = _timed_subtitle->subtitle ();
310                 }
311                 
312                 TIMING ("Decoder emits %1", _video_frame);
313                 Video ((*i), _video_frame, sub);
314                 ++_video_frame;
315         }
316 }
317
318 void
319 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
320 {
321         _timed_subtitle = s;
322         
323         if (_timed_subtitle && _opt->apply_crop) {
324                 Position const p = _timed_subtitle->subtitle()->position ();
325                 _timed_subtitle->subtitle()->set_position (Position (p.x - _film->crop().left, p.y - _film->crop().top));
326         }
327 }
328
329
330 int
331 Decoder::bytes_per_audio_sample () const
332 {
333         return av_get_bytes_per_sample (audio_sample_format ());
334 }