Fix dying butler on changing CPL from one without to one with
[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 (_reel == _reels.end () || !_dcp_content->can_be_played ()) {
129                 return true;
130         }
131
132         double const vfr = _dcp_content->active_video_frame_rate (film());
133
134         /* Frame within the (played part of the) reel that is coming up next */
135         int64_t const frame = _next.frames_round (vfr);
136
137         shared_ptr<dcp::PictureAsset> picture_asset = (*_reel)->main_picture()->asset();
138         DCPOMATIC_ASSERT (picture_asset);
139
140         /* We must emit texts first as when we emit the video for this frame
141            it will expect already to have the texts.
142         */
143         pass_texts (_next, picture_asset->size());
144
145         if ((_mono_reader || _stereo_reader) && (_decode_referenced || !_dcp_content->reference_video())) {
146                 int64_t const entry_point = (*_reel)->main_picture()->entry_point().get_value_or(0);
147                 if (_mono_reader) {
148                         video->emit (
149                                 film(),
150                                 shared_ptr<ImageProxy> (
151                                         new J2KImageProxy (
152                                                 _mono_reader->get_frame (entry_point + frame),
153                                                 picture_asset->size(),
154                                                 AV_PIX_FMT_XYZ12LE,
155                                                 _forced_reduction
156                                                 )
157                                         ),
158                                 _offset + frame
159                                 );
160                 } else {
161                         video->emit (
162                                 film(),
163                                 shared_ptr<ImageProxy> (
164                                         new J2KImageProxy (
165                                                 _stereo_reader->get_frame (entry_point + frame),
166                                                 picture_asset->size(),
167                                                 dcp::EYE_LEFT,
168                                                 AV_PIX_FMT_XYZ12LE,
169                                                 _forced_reduction
170                                                 )
171                                         ),
172                                 _offset + frame
173                                 );
174
175                         video->emit (
176                                 film(),
177                                 shared_ptr<ImageProxy> (
178                                         new J2KImageProxy (
179                                                 _stereo_reader->get_frame (entry_point + frame),
180                                                 picture_asset->size(),
181                                                 dcp::EYE_RIGHT,
182                                                 AV_PIX_FMT_XYZ12LE,
183                                                 _forced_reduction
184                                                 )
185                                         ),
186                                 _offset + frame
187                                 );
188                 }
189         }
190
191         if (_sound_reader && (_decode_referenced || !_dcp_content->reference_audio())) {
192                 int64_t const entry_point = (*_reel)->main_sound()->entry_point().get_value_or(0);
193                 shared_ptr<const dcp::SoundFrame> sf = _sound_reader->get_frame (entry_point + frame);
194                 uint8_t const * from = sf->data ();
195
196                 int const channels = _dcp_content->audio->stream()->channels ();
197                 int const frames = sf->size() / (3 * channels);
198                 shared_ptr<AudioBuffers> data (new AudioBuffers (channels, frames));
199                 float** data_data = data->data();
200                 for (int i = 0; i < frames; ++i) {
201                         for (int j = 0; j < channels; ++j) {
202                                 data_data[j][i] = static_cast<int> ((from[0] << 8) | (from[1] << 16) | (from[2] << 24)) / static_cast<float> (INT_MAX - 256);
203                                 from += 3;
204                         }
205                 }
206
207                 audio->emit (film(), _dcp_content->audio->stream(), data, ContentTime::from_frames (_offset, vfr) + _next);
208         }
209
210         _next += ContentTime::from_frames (1, vfr);
211
212         if ((*_reel)->main_picture ()) {
213                 if (_next.frames_round (vfr) >= (*_reel)->main_picture()->duration()) {
214                         next_reel ();
215                         _next = ContentTime ();
216                 }
217         }
218
219         return false;
220 }
221
222 void
223 DCPDecoder::pass_texts (ContentTime next, dcp::Size size)
224 {
225         list<shared_ptr<TextDecoder> >::const_iterator decoder = text.begin ();
226         if (decoder == text.end()) {
227                 /* It's possible that there is now a main subtitle but no TextDecoders, for example if
228                    the CPL has just changed but the TextContent's texts have not been recreated yet.
229                 */
230                 return;
231         }
232
233         if ((*_reel)->main_subtitle()) {
234                 pass_texts (
235                         next,
236                         (*_reel)->main_subtitle()->asset(),
237                         _dcp_content->reference_text(TEXT_OPEN_SUBTITLE),
238                         (*_reel)->main_subtitle()->entry_point().get_value_or(0),
239                         *decoder,
240                         size
241                         );
242                 ++decoder;
243         }
244
245         BOOST_FOREACH (shared_ptr<dcp::ReelClosedCaptionAsset> i, (*_reel)->closed_captions()) {
246                 pass_texts (
247                         next, i->asset(), _dcp_content->reference_text(TEXT_CLOSED_CAPTION), i->entry_point().get_value_or(0), *decoder, size
248                         );
249                 ++decoder;
250         }
251 }
252
253 void
254 DCPDecoder::pass_texts (
255         ContentTime next, shared_ptr<dcp::SubtitleAsset> asset, bool reference, int64_t entry_point, shared_ptr<TextDecoder> decoder, dcp::Size size
256         )
257 {
258         double const vfr = _dcp_content->active_video_frame_rate (film());
259         /* Frame within the (played part of the) reel that is coming up next */
260         int64_t const frame = next.frames_round (vfr);
261
262         if (_decode_referenced || !reference) {
263                 list<shared_ptr<dcp::Subtitle> > subs = asset->subtitles_during (
264                         dcp::Time (entry_point + frame, vfr, vfr),
265                         dcp::Time (entry_point + frame + 1, vfr, vfr),
266                         true
267                         );
268
269                 list<dcp::SubtitleString> strings;
270
271                 BOOST_FOREACH (shared_ptr<dcp::Subtitle> i, subs) {
272                         shared_ptr<dcp::SubtitleString> is = dynamic_pointer_cast<dcp::SubtitleString> (i);
273                         if (is) {
274                                 if (!strings.empty() && (strings.back().in() != is->in() || strings.back().out() != is->out())) {
275                                         dcp::SubtitleString b = strings.back();
276                                         decoder->emit_plain (
277                                                 ContentTimePeriod (
278                                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.in().as_seconds()),
279                                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.out().as_seconds())
280                                                         ),
281                                                 strings
282                                                 );
283                                         strings.clear ();
284                                 }
285
286                                 strings.push_back (*is);
287                         }
288
289                         /* XXX: perhaps these image subs should also be collected together like the string ones are;
290                            this would need to be done both here and in DCPSubtitleDecoder.
291                         */
292
293                         shared_ptr<dcp::SubtitleImage> ii = dynamic_pointer_cast<dcp::SubtitleImage> (i);
294                         if (ii) {
295                                 emit_subtitle_image (
296                                         ContentTimePeriod (
297                                                 ContentTime::from_frames (_offset - entry_point, vfr) + ContentTime::from_seconds (i->in().as_seconds ()),
298                                                 ContentTime::from_frames (_offset - entry_point, vfr) + ContentTime::from_seconds (i->out().as_seconds ())
299                                                 ),
300                                         *ii,
301                                         size,
302                                         decoder
303                                         );
304                         }
305                 }
306
307                 if (!strings.empty()) {
308                         dcp::SubtitleString b = strings.back();
309                         decoder->emit_plain (
310                                 ContentTimePeriod (
311                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.in().as_seconds()),
312                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.out().as_seconds())
313                                         ),
314                                 strings
315                                 );
316                         strings.clear ();
317                 }
318         }
319 }
320
321 void
322 DCPDecoder::next_reel ()
323 {
324         _offset += (*_reel)->main_picture()->actual_duration();
325         ++_reel;
326         get_readers ();
327 }
328
329 void
330 DCPDecoder::get_readers ()
331 {
332         if (_reel == _reels.end() || !_dcp_content->can_be_played ()) {
333                 _mono_reader.reset ();
334                 _stereo_reader.reset ();
335                 _sound_reader.reset ();
336                 return;
337         }
338
339         if ((*_reel)->main_picture()) {
340                 shared_ptr<dcp::PictureAsset> asset = (*_reel)->main_picture()->asset ();
341                 shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (asset);
342                 shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (asset);
343                 DCPOMATIC_ASSERT (mono || stereo);
344                 if (mono) {
345                         _mono_reader = mono->start_read ();
346                         _stereo_reader.reset ();
347                 } else {
348                         _stereo_reader = stereo->start_read ();
349                         _mono_reader.reset ();
350                 }
351         } else {
352                 _mono_reader.reset ();
353                 _stereo_reader.reset ();
354         }
355
356         if ((*_reel)->main_sound()) {
357                 _sound_reader = (*_reel)->main_sound()->asset()->start_read ();
358         } else {
359                 _sound_reader.reset ();
360         }
361 }
362
363 void
364 DCPDecoder::seek (ContentTime t, bool accurate)
365 {
366         if (!_dcp_content->can_be_played ()) {
367                 return;
368         }
369
370         Decoder::seek (t, accurate);
371
372         _reel = _reels.begin ();
373         _offset = 0;
374         get_readers ();
375
376         int const pre_roll_seconds = 2;
377
378         /* Pre-roll for subs */
379
380         ContentTime pre = t - ContentTime::from_seconds (pre_roll_seconds);
381         if (pre < ContentTime()) {
382                 pre = ContentTime ();
383         }
384
385         /* Seek to pre-roll position */
386
387         while (
388                 _reel != _reels.end() &&
389                 pre >= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()))
390                 ) {
391
392                 ContentTime rd = ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()));
393                 pre -= rd;
394                 t -= rd;
395                 next_reel ();
396         }
397
398         /* Pass texts in the pre-roll */
399
400         double const vfr = _dcp_content->active_video_frame_rate (film());
401         for (int i = 0; i < pre_roll_seconds * vfr; ++i) {
402                 pass_texts (pre, (*_reel)->main_picture()->asset()->size());
403                 pre += ContentTime::from_frames (1, vfr);
404         }
405
406         /* Seek to correct position */
407
408         while (
409                 _reel != _reels.end() &&
410                 t >= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()))
411                 ) {
412
413                 t -= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()));
414                 next_reel ();
415         }
416
417         _next = t;
418 }
419
420 void
421 DCPDecoder::set_decode_referenced (bool r)
422 {
423         _decode_referenced = r;
424
425         if (video) {
426                 video->set_ignore (_dcp_content->reference_video() && !_decode_referenced);
427         }
428         if (audio) {
429                 audio->set_ignore (_dcp_content->reference_audio() && !_decode_referenced);
430         }
431 }
432
433 void
434 DCPDecoder::set_forced_reduction (optional<int> reduction)
435 {
436         _forced_reduction = reduction;
437 }
438
439 string
440 DCPDecoder::calculate_lazy_digest (shared_ptr<const DCPContent> c) const
441 {
442         Digester d;
443         BOOST_FOREACH (boost::filesystem::path i, c->paths()) {
444                 d.add (i.string());
445         }
446         d.add (static_cast<bool>(_dcp_content->kdm()));
447         d.add (static_cast<bool>(c->cpl()));
448         if (c->cpl()) {
449                 d.add (c->cpl().get());
450         }
451         return d.get ();
452 }