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