Revert "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  *  @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_frame_index (0)
58         , _delay_line (0)
59         , _delay_in_bytes (0)
60         , _audio_frames_processed (0)
61 {
62         
63 }
64
65 Decoder::~Decoder ()
66 {
67         delete _delay_line;
68 }
69
70 /** Start off a decode processing run */
71 void
72 Decoder::process_begin ()
73 {
74         _delay_in_bytes = _film->audio_delay() * audio_sample_rate() * audio_channels() * bytes_per_audio_sample() / 1000;
75         delete _delay_line;
76         _delay_line = new DelayLine (_delay_in_bytes);
77
78         _audio_frames_processed = 0;
79 }
80
81 /** Finish off a decode processing run */
82 void
83 Decoder::process_end ()
84 {
85         if (_delay_in_bytes < 0) {
86                 uint8_t remainder[-_delay_in_bytes];
87                 _delay_line->get_remaining (remainder);
88                 _audio_frames_processed += _delay_in_bytes / (audio_channels() * bytes_per_audio_sample());
89                 emit_audio (remainder, -_delay_in_bytes);
90         }
91
92         /* If we cut the decode off, the audio may be short; push some silence
93            in to get it to the right length.
94         */
95
96         int64_t const video_length_in_audio_frames = ((int64_t) video_frame_index() * audio_sample_rate() / frames_per_second());
97         int64_t const audio_short_by_frames = video_length_in_audio_frames - _audio_frames_processed;
98
99         _film->log()->log (
100                 String::compose ("Source length is %1 (%2 audio frames); %3 frames of audio processed.",
101                                  video_frame_index(),
102                                  video_length_in_audio_frames,
103                                  _audio_frames_processed)
104                 );
105         
106         if (audio_short_by_frames >= 0 && _opt->decode_audio) {
107
108                 _film->log()->log (String::compose ("Source length is %1; %2 frames of audio processed.", video_frame_index(), _audio_frames_processed));
109                 _film->log()->log (String::compose ("Adding %1 frames of silence to the end.", audio_short_by_frames));
110
111                 /* XXX: this is slightly questionable; does memset () give silence with all
112                    sample formats?
113                 */
114
115                 int64_t bytes = audio_short_by_frames * _film->audio_channels() * bytes_per_audio_sample();
116                 
117                 int64_t const silence_size = 16 * 1024 * _film->audio_channels() * bytes_per_audio_sample();
118                 uint8_t silence[silence_size];
119                 memset (silence, 0, silence_size);
120                 
121                 while (bytes) {
122                         int64_t const t = min (bytes, silence_size);
123                         emit_audio (silence, t);
124                         bytes -= t;
125                 }
126         }
127 }
128
129 /** Start decoding */
130 void
131 Decoder::go ()
132 {
133         process_begin ();
134
135         if (_job && !_film->dcp_length()) {
136                 _job->set_progress_unknown ();
137         }
138
139         while (pass () == false) {
140                 if (_job && _film->dcp_length()) {
141                         SourceFrame const p = _video_frame_index - _film->dcp_trim_start();
142                         _job->set_progress (float (p) / _film->dcp_length().get());
143                 }
144         }
145
146         process_end ();
147 }
148
149 /** Called by subclasses to tell the world that some audio data is ready
150  *  @param data Audio data, in Film::audio_sample_format.
151  *  @param size Number of bytes of data.
152  */
153 void
154 Decoder::process_audio (uint8_t* data, int size)
155 {
156         /* Push into the delay line */
157         size = _delay_line->feed (data, size);
158
159         emit_audio (data, size);
160 }
161
162 void
163 Decoder::emit_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         /* Update the number of audio frames we've pushed to the encoder */
239         _audio_frames_processed += audio->frames ();
240
241         Audio (audio);
242 }
243
244 /** Called by subclasses to tell the world that some video data is ready.
245  *  We do some post-processing / filtering then emit it for listeners.
246  *  @param frame to decode; caller manages memory.
247  */
248 void
249 Decoder::process_video (AVFrame* frame)
250 {
251         assert (_film->length());
252         
253         if (_minimal) {
254                 ++_video_frame_index;
255                 return;
256         }
257
258         /* Use Film::length here as our one may be wrong */
259
260         if (_opt->decode_video_skip != 0 && (_video_frame_index % _opt->decode_video_skip) != 0) {
261                 ++_video_frame_index;
262                 return;
263         }
264
265         if (_film->dcp_trim_start() > _video_frame_index || (_film->length().get() - _film->dcp_trim_end()) < _video_frame_index) {
266                 ++_video_frame_index;
267                 return;
268         }
269
270         shared_ptr<FilterGraph> graph;
271
272         list<shared_ptr<FilterGraph> >::iterator i = _filter_graphs.begin();
273         while (i != _filter_graphs.end() && !(*i)->can_process (Size (frame->width, frame->height), (AVPixelFormat) frame->format)) {
274                 ++i;
275         }
276
277         if (i == _filter_graphs.end ()) {
278                 graph.reset (new FilterGraph (_film, this, _opt->apply_crop, Size (frame->width, frame->height), (AVPixelFormat) frame->format));
279                 _filter_graphs.push_back (graph);
280                 _film->log()->log (String::compose ("New graph for %1x%2, pixel format %3", frame->width, frame->height, frame->format));
281         } else {
282                 graph = *i;
283         }
284
285         list<shared_ptr<Image> > images = graph->process (frame);
286
287         for (list<shared_ptr<Image> >::iterator i = images.begin(); i != images.end(); ++i) {
288                 shared_ptr<Subtitle> sub;
289                 if (_timed_subtitle && _timed_subtitle->displayed_at (double (video_frame_index()) / _film->frames_per_second())) {
290                         sub = _timed_subtitle->subtitle ();
291                 }
292                 
293                 TIMING ("Decoder emits %1", _video_frame_index);
294                 Video (*i, _video_frame_index, sub);
295                 ++_video_frame_index;
296                 _last_image = *i;
297                 _last_subtitle = sub;
298         }
299 }
300
301 void
302 Decoder::repeat_last_video ()
303 {
304         if (!_last_image) {
305                 _last_image.reset (new CompactImage (pixel_format(), native_size()));
306                 _last_image->make_black ();
307         }
308         
309         Video (_last_image, _video_frame_index, _last_subtitle);
310         ++_video_frame_index;
311 }
312
313 void
314 Decoder::process_subtitle (shared_ptr<TimedSubtitle> s)
315 {
316         _timed_subtitle = s;
317         
318         if (_timed_subtitle && _opt->apply_crop) {
319                 Position const p = _timed_subtitle->subtitle()->position ();
320                 _timed_subtitle->subtitle()->set_position (Position (p.x - _film->crop().left, p.y - _film->crop().top));
321         }
322 }
323
324
325 int
326 Decoder::bytes_per_audio_sample () const
327 {
328         return av_get_bytes_per_sample (audio_sample_format ());
329 }