Various work on range setting.
[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_index (0)
60         , _delay_line (0)
61         , _delay_in_bytes (0)
62         , _audio_frames_processed (0)
63 {
64         
65 }
66
67 Decoder::~Decoder ()
68 {
69         delete _delay_line;
70 }
71
72 /** Start off a decode processing run */
73 void
74 Decoder::process_begin ()
75 {
76         _delay_in_bytes = _film->audio_delay() * audio_sample_rate() * audio_channels() * bytes_per_audio_sample() / 1000;
77         delete _delay_line;
78         _delay_line = new DelayLine (_delay_in_bytes);
79
80         _audio_frames_processed = 0;
81 }
82
83 /** Finish off a decode processing run */
84 void
85 Decoder::process_end ()
86 {
87         if (_delay_in_bytes < 0) {
88                 uint8_t remainder[-_delay_in_bytes];
89                 _delay_line->get_remaining (remainder);
90                 _audio_frames_processed += _delay_in_bytes / (audio_channels() * bytes_per_audio_sample());
91                 emit_audio (remainder, -_delay_in_bytes);
92         }
93
94         /* If we cut the decode off, the audio may be short; push some silence
95            in to get it to the right length.
96         */
97
98         int64_t const video_length_in_audio_frames = ((int64_t) video_frame_index() * audio_sample_rate() / frames_per_second());
99         int64_t const audio_short_by_frames = video_length_in_audio_frames - _audio_frames_processed;
100
101         _film->log()->log (
102                 String::compose ("Source length is %1 (%2 audio frames); %3 frames of audio processed.",
103                                  video_frame_index(),
104                                  video_length_in_audio_frames,
105                                  _audio_frames_processed)
106                 );
107         
108         if (audio_short_by_frames >= 0 && _opt->decode_audio) {
109
110                 _film->log()->log (String::compose ("Source length is %1; %2 frames of audio processed.", video_frame_index(), _audio_frames_processed));
111                 _film->log()->log (String::compose ("Adding %1 frames of silence to the end.", audio_short_by_frames));
112
113                 /* XXX: this is slightly questionable; does memset () give silence with all
114                    sample formats?
115                 */
116
117                 int64_t bytes = audio_short_by_frames * _film->audio_channels() * bytes_per_audio_sample();
118                 
119                 int64_t const silence_size = 16 * 1024 * _film->audio_channels() * bytes_per_audio_sample();
120                 uint8_t silence[silence_size];
121                 memset (silence, 0, silence_size);
122                 
123                 while (bytes) {
124                         int64_t const t = min (bytes, silence_size);
125                         emit_audio (silence, t);
126                         bytes -= t;
127                 }
128         }
129 }
130
131 /** Start decoding */
132 void
133 Decoder::go ()
134 {
135         process_begin ();
136
137         if (_job && !_film->dcp_length()) {
138                 _job->set_progress_unknown ();
139         }
140
141         while (pass () == false) {
142                 if (_job && _film->dcp_length()) {
143                         SourceFrame const p = _video_frame_index - _film->dcp_trim_start();
144                         _job->set_progress (float (p) / _film->dcp_length().get());
145                 }
146         }
147
148         process_end ();
149 }
150
151 /** Called by subclasses to tell the world that some audio data is ready
152  *  @param data Audio data, in Film::audio_sample_format.
153  *  @param size Number of bytes of data.
154  */
155 void
156 Decoder::process_audio (uint8_t* data, int size)
157 {
158         /* Push into the delay line */
159         size = _delay_line->feed (data, size);
160
161         emit_audio (data, size);
162 }
163
164 void
165 Decoder::emit_audio (uint8_t* data, int size)
166 {
167         if (size == 0) {
168                 return;
169         }
170         
171         assert (_film->audio_channels());
172         assert (bytes_per_audio_sample());
173         
174         /* Deinterleave and convert to float */
175
176         assert ((size % (bytes_per_audio_sample() * audio_channels())) == 0);
177
178         int const total_samples = size / bytes_per_audio_sample();
179         int const frames = total_samples / _film->audio_channels();
180         shared_ptr<AudioBuffers> audio (new AudioBuffers (audio_channels(), frames));
181
182         switch (audio_sample_format()) {
183         case AV_SAMPLE_FMT_S16:
184         {
185                 int16_t* p = (int16_t *) data;
186                 int sample = 0;
187                 int channel = 0;
188                 for (int i = 0; i < total_samples; ++i) {
189                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
190
191                         ++channel;
192                         if (channel == _film->audio_channels()) {
193                                 channel = 0;
194                                 ++sample;
195                         }
196                 }
197         }
198         break;
199
200         case AV_SAMPLE_FMT_S32:
201         {
202                 int32_t* p = (int32_t *) data;
203                 int sample = 0;
204                 int channel = 0;
205                 for (int i = 0; i < total_samples; ++i) {
206                         audio->data(channel)[sample] = float(*p++) / (1 << 31);
207
208                         ++channel;
209                         if (channel == _film->audio_channels()) {
210                                 channel = 0;
211                                 ++sample;
212                         }
213                 }
214         }
215
216         case AV_SAMPLE_FMT_FLTP:
217         {
218                 float* p = reinterpret_cast<float*> (data);
219                 for (int i = 0; i < _film->audio_channels(); ++i) {
220                         memcpy (audio->data(i), p, frames * sizeof(float));
221                         p += frames;
222                 }
223         }
224         break;
225
226         default:
227                 assert (false);
228         }
229
230         /* Maybe apply gain */
231         if (_film->audio_gain() != 0) {
232                 float const linear_gain = pow (10, _film->audio_gain() / 20);
233                 for (int i = 0; i < _film->audio_channels(); ++i) {
234                         for (int j = 0; j < frames; ++j) {
235                                 audio->data(i)[j] *= linear_gain;
236                         }
237                 }
238         }
239
240         /* Update the number of audio frames we've pushed to the encoder */
241         _audio_frames_processed += audio->frames ();
242
243         Audio (audio);
244 }
245
246 /** Called by subclasses to tell the world that some video data is ready.
247  *  We do some post-processing / filtering then emit it for listeners.
248  *  @param frame to decode; caller manages memory.
249  */
250 void
251 Decoder::process_video (AVFrame* frame)
252 {
253         assert (_ignore_length || _film->length());
254         
255         if (_minimal) {
256                 ++_video_frame_index;
257                 return;
258         }
259
260         /* Use Film::length here as our one may be wrong */
261
262         if (_opt->decode_video_skip != 0 && (_video_frame_index % _opt->decode_video_skip) != 0) {
263                 ++_video_frame_index;
264                 return;
265         }
266
267         if (_film->dcp_trim_start() > _video_frame_index || (_film->length().get() - _film->dcp_trim_end()) < _video_frame_index) {
268                 ++_video_frame_index;
269                 return;
270         }
271
272         shared_ptr<FilterGraph> graph;
273
274         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
275         while (i != _filter_graphs.end() && !(*i)->can_process (Size (frame->width, frame->height), (AVPixelFormat) frame->format)) {
276                 ++i;
277         }
278
279         if (i == _filter_graphs.end ()) {
280                 graph.reset (new FilterGraph (_film, this, _opt->apply_crop, Size (frame->width, frame->height), (AVPixelFormat) frame->format));
281                 _filter_graphs.push_back (graph);
282                 _film->log()->log (String::compose ("New graph for %1x%2, pixel format %3", frame->width, frame->height, frame->format));
283         } else {
284                 graph = *i;
285         }
286
287         list<shared_ptr<Image> > images = graph->process (frame);
288
289         for (list<shared_ptr<Image> >::iterator i = images.begin(); i != images.end(); ++i) {
290                 shared_ptr<Subtitle> sub;
291                 if (_timed_subtitle && _timed_subtitle->displayed_at (double (video_frame_index()) / _film->frames_per_second())) {
292                         sub = _timed_subtitle->subtitle ();
293                 }
294                 
295                 TIMING ("Decoder emits %1", _video_frame_index);
296                 Video (*i, _video_frame_index, sub);
297                 ++_video_frame_index;
298                 _last_image = *i;
299                 _last_subtitle = sub;
300         }
301 }
302
303 void
304 Decoder::repeat_last_video ()
305 {
306         if (!_last_image) {
307                 _last_image.reset (new CompactImage (pixel_format(), native_size()));
308                 _last_image->make_black ();
309         }
310         
311         Video (_last_image, _video_frame_index, _last_subtitle);
312         ++_video_frame_index;
313 }
314
315 void
316 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
317 {
318         _timed_subtitle = s;
319         
320         if (_timed_subtitle && _opt->apply_crop) {
321                 Position const p = _timed_subtitle->subtitle()->position ();
322                 _timed_subtitle->subtitle()->set_position (Position (p.x - _film->crop().left, p.y - _film->crop().top));
323         }
324 }
325
326
327 int
328 Decoder::bytes_per_audio_sample () const
329 {
330         return av_get_bytes_per_sample (audio_sample_format ());
331 }