Flush audio decoder when a DCPDecoder finishes so that
[dcpomatic.git] / src / lib / dcp_decoder.cc
1 /*
2     Copyright (C) 2014-2019 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "dcp_decoder.h"
22 #include "dcp_content.h"
23 #include "audio_content.h"
24 #include "video_decoder.h"
25 #include "audio_decoder.h"
26 #include "j2k_image_proxy.h"
27 #include "text_decoder.h"
28 #include "ffmpeg_image_proxy.h"
29 #include "image.h"
30 #include "config.h"
31 #include "digester.h"
32 #include <dcp/dcp.h>
33 #include <dcp/cpl.h>
34 #include <dcp/reel.h>
35 #include <dcp/mono_picture_asset.h>
36 #include <dcp/mono_picture_asset_reader.h>
37 #include <dcp/stereo_picture_asset.h>
38 #include <dcp/stereo_picture_asset_reader.h>
39 #include <dcp/reel_picture_asset.h>
40 #include <dcp/reel_sound_asset.h>
41 #include <dcp/reel_subtitle_asset.h>
42 #include <dcp/reel_closed_caption_asset.h>
43 #include <dcp/mono_picture_frame.h>
44 #include <dcp/stereo_picture_frame.h>
45 #include <dcp/sound_frame.h>
46 #include <dcp/sound_asset_reader.h>
47 #include <dcp/subtitle_image.h>
48 #include <dcp/decrypted_kdm.h>
49 #include <boost/foreach.hpp>
50 #include <iostream>
51
52 #include "i18n.h"
53
54 using std::list;
55 using std::cout;
56 using std::string;
57 using boost::shared_ptr;
58 using boost::dynamic_pointer_cast;
59 using boost::optional;
60 using namespace dcpomatic;
61
62 DCPDecoder::DCPDecoder (shared_ptr<const Film> film, shared_ptr<const DCPContent> c, bool fast, bool tolerant, shared_ptr<DCPDecoder> old)
63         : DCP (c, tolerant)
64         , Decoder (film)
65         , _decode_referenced (false)
66 {
67         if (c->can_be_played()) {
68                 if (c->video) {
69                         video.reset (new VideoDecoder (this, c));
70                 }
71                 if (c->audio) {
72                         audio.reset (new AudioDecoder (this, c->audio, fast));
73                 }
74                 BOOST_FOREACH (shared_ptr<TextContent> i, c->text) {
75                         /* XXX: this time here should be the time of the first subtitle, not 0 */
76                         text.push_back (shared_ptr<TextDecoder> (new TextDecoder (this, i, ContentTime())));
77                 }
78         }
79
80         /* We try to avoid re-scanning the DCP's files every time we make a new DCPDecoder; we do this
81            by re-using the _reels list.  Before we do this we need to check that nothing too serious
82            has changed in the DCPContent.
83
84            We do this by storing a digest of the important bits of the DCPContent and then checking that's
85            the same before we re-use _reels.
86         */
87
88         _lazy_digest = calculate_lazy_digest (c);
89
90         if (old && old->lazy_digest() == _lazy_digest) {
91                 _reels = old->_reels;
92         } else {
93
94                 list<shared_ptr<dcp::CPL> > cpl_list = cpls ();
95
96                 if (cpl_list.empty()) {
97                         throw DCPError (_("No CPLs found in DCP."));
98                 }
99
100                 shared_ptr<dcp::CPL> cpl;
101                 BOOST_FOREACH (shared_ptr<dcp::CPL> i, cpl_list) {
102                         if (_dcp_content->cpl() && i->id() == _dcp_content->cpl().get()) {
103                                 cpl = i;
104                         }
105                 }
106
107                 if (!cpl) {
108                         /* No CPL found; probably an old file that doesn't specify it;
109                            just use the first one.
110                         */
111                         cpl = cpls().front ();
112                 }
113
114                 _reels = cpl->reels ();
115         }
116
117         set_decode_referenced (false);
118
119         _reel = _reels.begin ();
120         _offset = 0;
121         get_readers ();
122 }
123
124
125 bool
126 DCPDecoder::pass ()
127 {
128         if (!_dcp_content->can_be_played()) {
129                 return true;
130         }
131
132         if (_reel == _reels.end()) {
133                 if (audio) {
134                         audio->flush ();
135                 }
136                 return true;
137         }
138
139         double const vfr = _dcp_content->active_video_frame_rate (film());
140
141         /* Frame within the (played part of the) reel that is coming up next */
142         int64_t const frame = _next.frames_round (vfr);
143
144         shared_ptr<dcp::PictureAsset> picture_asset = (*_reel)->main_picture()->asset();
145         DCPOMATIC_ASSERT (picture_asset);
146
147         /* We must emit texts first as when we emit the video for this frame
148            it will expect already to have the texts.
149         */
150         pass_texts (_next, picture_asset->size());
151
152         if ((_mono_reader || _stereo_reader) && (_decode_referenced || !_dcp_content->reference_video())) {
153                 int64_t const entry_point = (*_reel)->main_picture()->entry_point().get_value_or(0);
154                 if (_mono_reader) {
155                         video->emit (
156                                 film(),
157                                 shared_ptr<ImageProxy> (
158                                         new J2KImageProxy (
159                                                 _mono_reader->get_frame (entry_point + frame),
160                                                 picture_asset->size(),
161                                                 AV_PIX_FMT_XYZ12LE,
162                                                 _forced_reduction
163                                                 )
164                                         ),
165                                 _offset + frame
166                                 );
167                 } else {
168                         video->emit (
169                                 film(),
170                                 shared_ptr<ImageProxy> (
171                                         new J2KImageProxy (
172                                                 _stereo_reader->get_frame (entry_point + frame),
173                                                 picture_asset->size(),
174                                                 dcp::EYE_LEFT,
175                                                 AV_PIX_FMT_XYZ12LE,
176                                                 _forced_reduction
177                                                 )
178                                         ),
179                                 _offset + frame
180                                 );
181
182                         video->emit (
183                                 film(),
184                                 shared_ptr<ImageProxy> (
185                                         new J2KImageProxy (
186                                                 _stereo_reader->get_frame (entry_point + frame),
187                                                 picture_asset->size(),
188                                                 dcp::EYE_RIGHT,
189                                                 AV_PIX_FMT_XYZ12LE,
190                                                 _forced_reduction
191                                                 )
192                                         ),
193                                 _offset + frame
194                                 );
195                 }
196         }
197
198         if (_sound_reader && (_decode_referenced || !_dcp_content->reference_audio())) {
199                 int64_t const entry_point = (*_reel)->main_sound()->entry_point().get_value_or(0);
200                 shared_ptr<const dcp::SoundFrame> sf = _sound_reader->get_frame (entry_point + frame);
201                 uint8_t const * from = sf->data ();
202
203                 int const channels = _dcp_content->audio->stream()->channels ();
204                 int const frames = sf->size() / (3 * channels);
205                 shared_ptr<AudioBuffers> data (new AudioBuffers (channels, frames));
206                 float** data_data = data->data();
207                 for (int i = 0; i < frames; ++i) {
208                         for (int j = 0; j < channels; ++j) {
209                                 data_data[j][i] = static_cast<int> ((from[0] << 8) | (from[1] << 16) | (from[2] << 24)) / static_cast<float> (INT_MAX - 256);
210                                 from += 3;
211                         }
212                 }
213
214                 audio->emit (film(), _dcp_content->audio->stream(), data, ContentTime::from_frames (_offset, vfr) + _next);
215         }
216
217         _next += ContentTime::from_frames (1, vfr);
218
219         if ((*_reel)->main_picture ()) {
220                 if (_next.frames_round (vfr) >= (*_reel)->main_picture()->duration()) {
221                         next_reel ();
222                         _next = ContentTime ();
223                 }
224         }
225
226         return false;
227 }
228
229 void
230 DCPDecoder::pass_texts (ContentTime next, dcp::Size size)
231 {
232         list<shared_ptr<TextDecoder> >::const_iterator decoder = text.begin ();
233         if (decoder == text.end()) {
234                 /* It's possible that there is now a main subtitle but no TextDecoders, for example if
235                    the CPL has just changed but the TextContent's texts have not been recreated yet.
236                 */
237                 return;
238         }
239
240         if ((*_reel)->main_subtitle()) {
241                 pass_texts (
242                         next,
243                         (*_reel)->main_subtitle()->asset(),
244                         _dcp_content->reference_text(TEXT_OPEN_SUBTITLE),
245                         (*_reel)->main_subtitle()->entry_point().get_value_or(0),
246                         *decoder,
247                         size
248                         );
249                 ++decoder;
250         }
251
252         BOOST_FOREACH (shared_ptr<dcp::ReelClosedCaptionAsset> i, (*_reel)->closed_captions()) {
253                 pass_texts (
254                         next, i->asset(), _dcp_content->reference_text(TEXT_CLOSED_CAPTION), i->entry_point().get_value_or(0), *decoder, size
255                         );
256                 ++decoder;
257         }
258 }
259
260 void
261 DCPDecoder::pass_texts (
262         ContentTime next, shared_ptr<dcp::SubtitleAsset> asset, bool reference, int64_t entry_point, shared_ptr<TextDecoder> decoder, dcp::Size size
263         )
264 {
265         double const vfr = _dcp_content->active_video_frame_rate (film());
266         /* Frame within the (played part of the) reel that is coming up next */
267         int64_t const frame = next.frames_round (vfr);
268
269         if (_decode_referenced || !reference) {
270                 list<shared_ptr<dcp::Subtitle> > subs = asset->subtitles_during (
271                         dcp::Time (entry_point + frame, vfr, vfr),
272                         dcp::Time (entry_point + frame + 1, vfr, vfr),
273                         true
274                         );
275
276                 list<dcp::SubtitleString> strings;
277
278                 BOOST_FOREACH (shared_ptr<dcp::Subtitle> i, subs) {
279                         shared_ptr<dcp::SubtitleString> is = dynamic_pointer_cast<dcp::SubtitleString> (i);
280                         if (is) {
281                                 if (!strings.empty() && (strings.back().in() != is->in() || strings.back().out() != is->out())) {
282                                         dcp::SubtitleString b = strings.back();
283                                         decoder->emit_plain (
284                                                 ContentTimePeriod (
285                                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.in().as_seconds()),
286                                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.out().as_seconds())
287                                                         ),
288                                                 strings
289                                                 );
290                                         strings.clear ();
291                                 }
292
293                                 strings.push_back (*is);
294                         }
295
296                         /* XXX: perhaps these image subs should also be collected together like the string ones are;
297                            this would need to be done both here and in DCPSubtitleDecoder.
298                         */
299
300                         shared_ptr<dcp::SubtitleImage> ii = dynamic_pointer_cast<dcp::SubtitleImage> (i);
301                         if (ii) {
302                                 emit_subtitle_image (
303                                         ContentTimePeriod (
304                                                 ContentTime::from_frames (_offset - entry_point, vfr) + ContentTime::from_seconds (i->in().as_seconds ()),
305                                                 ContentTime::from_frames (_offset - entry_point, vfr) + ContentTime::from_seconds (i->out().as_seconds ())
306                                                 ),
307                                         *ii,
308                                         size,
309                                         decoder
310                                         );
311                         }
312                 }
313
314                 if (!strings.empty()) {
315                         dcp::SubtitleString b = strings.back();
316                         decoder->emit_plain (
317                                 ContentTimePeriod (
318                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.in().as_seconds()),
319                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.out().as_seconds())
320                                         ),
321                                 strings
322                                 );
323                         strings.clear ();
324                 }
325         }
326 }
327
328 void
329 DCPDecoder::next_reel ()
330 {
331         _offset += (*_reel)->main_picture()->actual_duration();
332         ++_reel;
333         get_readers ();
334 }
335
336 void
337 DCPDecoder::get_readers ()
338 {
339         if (_reel == _reels.end() || !_dcp_content->can_be_played ()) {
340                 _mono_reader.reset ();
341                 _stereo_reader.reset ();
342                 _sound_reader.reset ();
343                 return;
344         }
345
346         if ((*_reel)->main_picture()) {
347                 shared_ptr<dcp::PictureAsset> asset = (*_reel)->main_picture()->asset ();
348                 shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (asset);
349                 shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (asset);
350                 DCPOMATIC_ASSERT (mono || stereo);
351                 if (mono) {
352                         _mono_reader = mono->start_read ();
353                         _stereo_reader.reset ();
354                 } else {
355                         _stereo_reader = stereo->start_read ();
356                         _mono_reader.reset ();
357                 }
358         } else {
359                 _mono_reader.reset ();
360                 _stereo_reader.reset ();
361         }
362
363         if ((*_reel)->main_sound()) {
364                 _sound_reader = (*_reel)->main_sound()->asset()->start_read ();
365         } else {
366                 _sound_reader.reset ();
367         }
368 }
369
370 void
371 DCPDecoder::seek (ContentTime t, bool accurate)
372 {
373         if (!_dcp_content->can_be_played ()) {
374                 return;
375         }
376
377         Decoder::seek (t, accurate);
378
379         _reel = _reels.begin ();
380         _offset = 0;
381         get_readers ();
382
383         int const pre_roll_seconds = 2;
384
385         /* Pre-roll for subs */
386
387         ContentTime pre = t - ContentTime::from_seconds (pre_roll_seconds);
388         if (pre < ContentTime()) {
389                 pre = ContentTime ();
390         }
391
392         /* Seek to pre-roll position */
393
394         while (
395                 _reel != _reels.end() &&
396                 pre >= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()))
397                 ) {
398
399                 ContentTime rd = ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()));
400                 pre -= rd;
401                 t -= rd;
402                 next_reel ();
403         }
404
405         /* Pass texts in the pre-roll */
406
407         double const vfr = _dcp_content->active_video_frame_rate (film());
408         for (int i = 0; i < pre_roll_seconds * vfr; ++i) {
409                 pass_texts (pre, (*_reel)->main_picture()->asset()->size());
410                 pre += ContentTime::from_frames (1, vfr);
411         }
412
413         /* Seek to correct position */
414
415         while (
416                 _reel != _reels.end() &&
417                 t >= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()))
418                 ) {
419
420                 t -= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()));
421                 next_reel ();
422         }
423
424         _next = t;
425 }
426
427 void
428 DCPDecoder::set_decode_referenced (bool r)
429 {
430         _decode_referenced = r;
431
432         if (video) {
433                 video->set_ignore (_dcp_content->reference_video() && !_decode_referenced);
434         }
435         if (audio) {
436                 audio->set_ignore (_dcp_content->reference_audio() && !_decode_referenced);
437         }
438 }
439
440 void
441 DCPDecoder::set_forced_reduction (optional<int> reduction)
442 {
443         _forced_reduction = reduction;
444 }
445
446 string
447 DCPDecoder::calculate_lazy_digest (shared_ptr<const DCPContent> c) const
448 {
449         Digester d;
450         BOOST_FOREACH (boost::filesystem::path i, c->paths()) {
451                 d.add (i.string());
452         }
453         d.add (static_cast<bool>(_dcp_content->kdm()));
454         d.add (static_cast<bool>(c->cpl()));
455         if (c->cpl()) {
456                 d.add (c->cpl().get());
457         }
458         return d.get ();
459 }