Partial small cleanup.
[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  */
52 Decoder::Decoder (boost::shared_ptr<Film> f, boost::shared_ptr<const Options> o, Job* j, bool minimal)
53         : _film (f)
54         , _opt (o)
55         , _job (j)
56         , _minimal (minimal)
57         , _video_frames_in (0)
58         , _video_frames_out (0)
59         , _audio_frames_in (0)
60         , _audio_frames_out (0)
61         , _delay_line (0)
62         , _delay_in_bytes (0)
63 {
64         
65 }
66
67 Decoder::~Decoder ()
68 {
69         delete _delay_line;
70 }
71
72 /** Start off a decode processing run.  This should only be called once on
73  *  a given Decoder object.
74  */
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         _delay_line = new DelayLine (_delay_in_bytes);
80 }
81
82 /** Finish off a decode processing run */
83 void
84 Decoder::process_end ()
85 {
86         if (_delay_in_bytes < 0) {
87                 /* Empty the delay line */
88                 uint8_t remainder[-_delay_in_bytes];
89                 _delay_line->get_remaining (remainder);
90                 emit_audio (remainder, -_delay_in_bytes);
91         }
92
93         if (_opt->decode_audio) {
94
95                 /* Ensure that our video and audio emissions are the same length */
96
97                 int64_t video_frames_out_in_audio_frames = ((int64_t) _video_frames_out * audio_sample_rate() / frames_per_second());
98                 int64_t audio_short_by_frames = video_frames_out_in_audio_frames - _audio_frames_out;
99
100                 _film->log()->log (
101                         String::compose ("Decoder has emitted %1 video frames (which equals %2 audio frames) and %3 audio frames",
102                                          _video_frames_out,
103                                          video_frames_out_in_audio_frames,
104                                          _audio_frames_out)
105                         );
106
107                 if (audio_short_by_frames < 0) {
108
109                         _film->log()->log (String::compose ("Emitted %1 too many audio frames", -audio_short_by_frames));
110                         
111                         /* We have emitted more audio than video.  Emit enough black video frames so that we reverse this */
112                         int const black_video_frames = ceil (-audio_short_by_frames * frames_per_second() / audio_sample_rate());
113
114                         _film->log()->log (String::compose ("Emitting %1 frames of black video", black_video_frames));
115
116                         shared_ptr<Image> black (new CompactImage (pixel_format(), native_size()));
117                         black->make_black ();
118                         for (int i = 0; i < black_video_frames; ++i) {
119                                 emit_video (black, shared_ptr<Subtitle> ());
120                         }
121
122                         /* Now recompute our check values */
123                         video_frames_out_in_audio_frames = ((int64_t) _video_frames_out * audio_sample_rate() / frames_per_second());
124                         audio_short_by_frames = video_frames_out_in_audio_frames - _audio_frames_out;
125                 }
126         
127                 if (audio_short_by_frames > 0) {
128
129                         _film->log()->log (String::compose ("Emitted %1 too few audio frames", audio_short_by_frames));
130
131                         /* XXX: this is slightly questionable; does memset () give silence with all
132                            sample formats?
133                         */
134                         
135                         int64_t bytes = audio_short_by_frames * _film->audio_channels() * bytes_per_audio_sample();
136                         
137                         int64_t const silence_size = 16 * 1024 * _film->audio_channels() * bytes_per_audio_sample();
138                         uint8_t silence[silence_size];
139                         memset (silence, 0, silence_size);
140                         
141                         while (bytes) {
142                                 int64_t const t = min (bytes, silence_size);
143                                 emit_audio (silence, t);
144                                 bytes -= t;
145                         }
146                 }
147         }
148 }
149
150 /** Start decoding */
151 void
152 Decoder::go ()
153 {
154         process_begin ();
155
156         if (_job && !_film->dcp_length()) {
157                 _job->set_progress_unknown ();
158         }
159
160         while (pass () == false) {
161                 if (_job && _film->dcp_length()) {
162                         _job->set_progress (float (_video_frames_out) / _film->dcp_length().get());
163                 }
164         }
165
166         process_end ();
167 }
168
169 /** Called by subclasses to tell the world that some audio data is ready
170  *  @param data Audio data, in Film::audio_sample_format.
171  *  @param size Number of bytes of data.
172  */
173 void
174 Decoder::process_audio (uint8_t* data, int size)
175 {
176         int const audio_frames_in_in_video_frames = _audio_frames_in * frames_per_second() / audio_sample_rate();
177         if (!within_range (audio_frames_in_in_video_frames)) {
178                 return;
179         }
180         
181         /* Push into the delay line */
182         size = _delay_line->feed (data, size);
183
184         emit_audio (data, size);
185 }
186
187 void
188 Decoder::emit_audio (uint8_t* data, int size)
189 {
190         if (size == 0) {
191                 return;
192         }
193         
194         assert (_film->audio_channels());
195         assert (bytes_per_audio_sample());
196         
197         /* Deinterleave and convert to float */
198
199         assert ((size % (bytes_per_audio_sample() * audio_channels())) == 0);
200
201         int const total_samples = size / bytes_per_audio_sample();
202         int const frames = total_samples / _film->audio_channels();
203         shared_ptr<AudioBuffers> audio (new AudioBuffers (audio_channels(), frames));
204
205         switch (audio_sample_format()) {
206         case AV_SAMPLE_FMT_S16:
207         {
208                 int16_t* p = (int16_t *) data;
209                 int sample = 0;
210                 int channel = 0;
211                 for (int i = 0; i < total_samples; ++i) {
212                         audio->data(channel)[sample] = float(*p++) / (1 << 15);
213
214                         ++channel;
215                         if (channel == _film->audio_channels()) {
216                                 channel = 0;
217                                 ++sample;
218                         }
219                 }
220         }
221         break;
222
223         case AV_SAMPLE_FMT_S32:
224         {
225                 int32_t* p = (int32_t *) data;
226                 int sample = 0;
227                 int channel = 0;
228                 for (int i = 0; i < total_samples; ++i) {
229                         audio->data(channel)[sample] = float(*p++) / (1 << 31);
230
231                         ++channel;
232                         if (channel == _film->audio_channels()) {
233                                 channel = 0;
234                                 ++sample;
235                         }
236                 }
237         }
238
239         case AV_SAMPLE_FMT_FLTP:
240         {
241                 float* p = reinterpret_cast<float*> (data);
242                 for (int i = 0; i < _film->audio_channels(); ++i) {
243                         memcpy (audio->data(i), p, frames * sizeof(float));
244                         p += frames;
245                 }
246         }
247         break;
248
249         default:
250                 assert (false);
251         }
252
253         /* Maybe apply gain */
254         if (_film->audio_gain() != 0) {
255                 float const linear_gain = pow (10, _film->audio_gain() / 20);
256                 for (int i = 0; i < _film->audio_channels(); ++i) {
257                         for (int j = 0; j < frames; ++j) {
258                                 audio->data(i)[j] *= linear_gain;
259                         }
260                 }
261         }
262
263         /* Update the number of audio frames we've pushed to the encoder */
264         _audio_frames_out += audio->frames ();
265
266         Audio (audio);
267 }
268
269 /** Called by subclasses to tell the world that some video data is ready.
270  *  We do some post-processing / filtering then emit it for listeners.
271  *  @param frame to decode; caller manages memory.
272  */
273 void
274 Decoder::process_video (AVFrame* frame)
275 {
276         assert (_film->length());
277
278         if (_minimal) {
279                 ++_video_frames_in;
280                 return;
281         }
282
283         /* Use Film::length here as our one may be wrong */
284
285         if (_opt->decode_video_skip != 0 && (_video_frames_in % _opt->decode_video_skip) != 0) {
286                 ++_video_frames_in;
287                 return;
288         }
289
290         if (!within_range (_video_frames_in)) {
291                 ++_video_frames_in;
292                 return;
293         }
294
295         shared_ptr<FilterGraph> graph;
296
297         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
298         while (i != _filter_graphs.end() && !(*i)->can_process (Size (frame->width, frame->height), (AVPixelFormat) frame->format)) {
299                 ++i;
300         }
301
302         if (i == _filter_graphs.end ()) {
303                 graph.reset (new FilterGraph (_film, this, _opt->apply_crop, Size (frame->width, frame->height), (AVPixelFormat) frame->format));
304                 _filter_graphs.push_back (graph);
305                 _film->log()->log (String::compose ("New graph for %1x%2, pixel format %3", frame->width, frame->height, frame->format));
306         } else {
307                 graph = *i;
308         }
309
310         list<shared_ptr<Image> > images = graph->process (frame);
311
312         for (list<shared_ptr<Image> >::iterator i = images.begin(); i != images.end(); ++i) {
313                 shared_ptr<Subtitle> sub;
314                 if (_timed_subtitle && _timed_subtitle->displayed_at (double (video_frames_in()) / _film->frames_per_second())) {
315                         sub = _timed_subtitle->subtitle ();
316                 }
317
318                 emit_video (*i, sub);
319         }
320 }
321
322 void
323 Decoder::repeat_last_video ()
324 {
325         if (!_last_image) {
326                 _last_image.reset (new CompactImage (pixel_format(), native_size()));
327                 _last_image->make_black ();
328         }
329
330         emit_video (_last_image, _last_subtitle);
331 }
332
333 void
334 Decoder::emit_video (shared_ptr<Image> image, shared_ptr<Subtitle> sub)
335 {
336         TIMING ("Decoder emits %1", _video_frames_out);
337         Video (image, _video_frames_out, sub);
338         ++_video_frames_out;
339         _last_image = image;
340         _last_subtitle = sub;
341 }
342
343 void
344 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
345 {
346         _timed_subtitle = s;
347         
348         if (_timed_subtitle && _opt->apply_crop) {
349                 Position const p = _timed_subtitle->subtitle()->position ();
350                 _timed_subtitle->subtitle()->set_position (Position (p.x - _film->crop().left, p.y - _film->crop().top));
351         }
352 }
353
354
355 int
356 Decoder::bytes_per_audio_sample () const
357 {
358         return av_get_bytes_per_sample (audio_sample_format ());
359 }
360
361 /** @param s A video frame index within the source */
362 bool
363 Decoder::within_range (SourceFrames s) const
364 {
365         return (s >= _film->dcp_trim_start() && s < (_film->length().get() + _film->dcp_trim_start()));
366 }