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