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