Fix the build for older macOS.
[dcpomatic.git] / src / lib / dcp_decoder.cc
1 /*
2     Copyright (C) 2014-2020 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 "atmos_decoder.h"
22 #include "dcp_decoder.h"
23 #include "dcp_content.h"
24 #include "audio_content.h"
25 #include "video_decoder.h"
26 #include "audio_decoder.h"
27 #include "j2k_image_proxy.h"
28 #include "text_decoder.h"
29 #include "ffmpeg_image_proxy.h"
30 #include "image.h"
31 #include "config.h"
32 #include "digester.h"
33 #include "frame_interval_checker.h"
34 #include <dcp/dcp.h>
35 #include <dcp/cpl.h>
36 #include <dcp/reel.h>
37 #include <dcp/mono_picture_asset.h>
38 #include <dcp/mono_picture_asset_reader.h>
39 #include <dcp/stereo_picture_asset.h>
40 #include <dcp/stereo_picture_asset_reader.h>
41 #include <dcp/reel_picture_asset.h>
42 #include <dcp/reel_sound_asset.h>
43 #include <dcp/reel_subtitle_asset.h>
44 #include <dcp/reel_closed_caption_asset.h>
45 #include <dcp/mono_picture_frame.h>
46 #include <dcp/stereo_picture_frame.h>
47 #include <dcp/sound_frame.h>
48 #include <dcp/sound_asset_reader.h>
49 #include <dcp/subtitle_image.h>
50 #include <dcp/decrypted_kdm.h>
51 #include <dcp/reel_atmos_asset.h>
52 #include <iostream>
53
54 #include "i18n.h"
55
56 using std::list;
57 using std::cout;
58 using std::map;
59 using std::string;
60 using std::vector;
61 using std::shared_ptr;
62 using std::dynamic_pointer_cast;
63 using std::make_shared;
64 using boost::optional;
65 using namespace dcpomatic;
66
67 DCPDecoder::DCPDecoder (shared_ptr<const Film> film, shared_ptr<const DCPContent> c, bool fast, bool tolerant, shared_ptr<DCPDecoder> old)
68         : DCP (c, tolerant)
69         , Decoder (film)
70 {
71         if (c->can_be_played()) {
72                 if (c->video) {
73                         video = make_shared<VideoDecoder>(this, c);
74                 }
75                 if (c->audio) {
76                         audio = make_shared<AudioDecoder>(this, c->audio, fast);
77                 }
78                 for (auto i: c->text) {
79                         /* XXX: this time here should be the time of the first subtitle, not 0 */
80                         text.push_back (make_shared<TextDecoder>(this, i, ContentTime()));
81                 }
82                 if (c->atmos) {
83                         atmos = make_shared<AtmosDecoder>(this, c);
84                 }
85         }
86
87         /* We try to avoid re-scanning the DCP's files every time we make a new DCPDecoder; we do this
88            by re-using the _reels list.  Before we do this we need to check that nothing too serious
89            has changed in the DCPContent.
90
91            We do this by storing a digest of the important bits of the DCPContent and then checking that's
92            the same before we re-use _reels.
93         */
94
95         _lazy_digest = calculate_lazy_digest (c);
96
97         if (old && old->lazy_digest() == _lazy_digest) {
98                 _reels = old->_reels;
99         } else {
100
101                 auto cpl_list = cpls ();
102
103                 if (cpl_list.empty()) {
104                         throw DCPError (_("No CPLs found in DCP."));
105                 }
106
107                 shared_ptr<dcp::CPL> cpl;
108                 for (auto i: cpl_list) {
109                         if (_dcp_content->cpl() && i->id() == _dcp_content->cpl().get()) {
110                                 cpl = i;
111                         }
112                 }
113
114                 if (!cpl) {
115                         /* No CPL found; probably an old file that doesn't specify it;
116                            just use the first one.
117                         */
118                         cpl = cpls().front ();
119                 }
120
121                 _reels = cpl->reels ();
122         }
123
124         set_decode_referenced (false);
125
126         _reel = _reels.begin ();
127         get_readers ();
128 }
129
130
131 bool
132 DCPDecoder::pass ()
133 {
134         if (!_dcp_content->can_be_played()) {
135                 return true;
136         }
137
138         if (_reel == _reels.end()) {
139                 if (audio) {
140                         audio->flush ();
141                 }
142                 return true;
143         }
144
145         double const vfr = _dcp_content->active_video_frame_rate (film());
146
147         /* Frame within the (played part of the) reel that is coming up next */
148         int64_t const frame = _next.frames_round (vfr);
149
150         shared_ptr<dcp::PictureAsset> picture_asset = (*_reel)->main_picture()->asset();
151         DCPOMATIC_ASSERT (picture_asset);
152
153         /* We must emit texts first as when we emit the video for this frame
154            it will expect already to have the texts.
155         */
156         pass_texts (_next, picture_asset->size());
157
158         if ((_mono_reader || _stereo_reader) && (_decode_referenced || !_dcp_content->reference_video())) {
159                 int64_t const entry_point = (*_reel)->main_picture()->entry_point().get_value_or(0);
160                 if (_mono_reader) {
161                         video->emit (
162                                 film(),
163                                 std::make_shared<J2KImageProxy>(
164                                         _mono_reader->get_frame (entry_point + frame),
165                                         picture_asset->size(),
166                                         AV_PIX_FMT_XYZ12LE,
167                                         _forced_reduction
168                                         ),
169                                 _offset + frame
170                                 );
171                 } else {
172                         video->emit (
173                                 film(),
174                                 std::make_shared<J2KImageProxy>(
175                                         _stereo_reader->get_frame (entry_point + frame),
176                                         picture_asset->size(),
177                                         dcp::Eye::LEFT,
178                                         AV_PIX_FMT_XYZ12LE,
179                                         _forced_reduction
180                                         ),
181                                 _offset + frame
182                                 );
183
184                         video->emit (
185                                 film(),
186                                 std::make_shared<J2KImageProxy>(
187                                         _stereo_reader->get_frame (entry_point + frame),
188                                         picture_asset->size(),
189                                         dcp::Eye::RIGHT,
190                                         AV_PIX_FMT_XYZ12LE,
191                                         _forced_reduction
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         if (_atmos_reader) {
218                 DCPOMATIC_ASSERT (_atmos_metadata);
219                 int64_t const entry_point = (*_reel)->atmos()->entry_point().get_value_or(0);
220                 atmos->emit (film(), _atmos_reader->get_frame(entry_point + frame), _offset + frame, *_atmos_metadata);
221         }
222
223         _next += ContentTime::from_frames (1, vfr);
224
225         if ((*_reel)->main_picture ()) {
226                 if (_next.frames_round (vfr) >= (*_reel)->main_picture()->duration()) {
227                         next_reel ();
228                         _next = ContentTime ();
229                 }
230         }
231
232         return false;
233 }
234
235 void
236 DCPDecoder::pass_texts (ContentTime next, dcp::Size size)
237 {
238         auto decoder = text.begin ();
239         if (decoder == text.end()) {
240                 /* It's possible that there is now a main subtitle but no TextDecoders, for example if
241                    the CPL has just changed but the TextContent's texts have not been recreated yet.
242                 */
243                 return;
244         }
245
246         if ((*_reel)->main_subtitle()) {
247                 pass_texts (
248                         next,
249                         (*_reel)->main_subtitle()->asset(),
250                         _dcp_content->reference_text(TextType::OPEN_SUBTITLE),
251                         (*_reel)->main_subtitle()->entry_point().get_value_or(0),
252                         *decoder,
253                         size
254                         );
255                 ++decoder;
256         }
257
258         for (auto i: (*_reel)->closed_captions()) {
259                 pass_texts (
260                         next, i->asset(), _dcp_content->reference_text(TextType::CLOSED_CAPTION), i->entry_point().get_value_or(0), *decoder, size
261                         );
262                 ++decoder;
263         }
264 }
265
266 void
267 DCPDecoder::pass_texts (
268         ContentTime next, shared_ptr<dcp::SubtitleAsset> asset, bool reference, int64_t entry_point, shared_ptr<TextDecoder> decoder, dcp::Size size
269         )
270 {
271         double const vfr = _dcp_content->active_video_frame_rate (film());
272         /* Frame within the (played part of the) reel that is coming up next */
273         int64_t const frame = next.frames_round (vfr);
274
275         if (_decode_referenced || !reference) {
276                 auto subs = asset->subtitles_during (
277                         dcp::Time (entry_point + frame, vfr, vfr),
278                         dcp::Time (entry_point + frame + 1, vfr, vfr),
279                         true
280                         );
281
282                 list<dcp::SubtitleString> strings;
283
284                 for (auto i: subs) {
285                         auto is = dynamic_pointer_cast<const dcp::SubtitleString>(i);
286                         if (is) {
287                                 if (!strings.empty() && (strings.back().in() != is->in() || strings.back().out() != is->out())) {
288                                         auto b = strings.back();
289                                         decoder->emit_plain (
290                                                 ContentTimePeriod (
291                                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.in().as_seconds()),
292                                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.out().as_seconds())
293                                                         ),
294                                                 strings
295                                                 );
296                                         strings.clear ();
297                                 }
298
299                                 strings.push_back (*is);
300                         }
301
302                         /* XXX: perhaps these image subs should also be collected together like the string ones are;
303                            this would need to be done both here and in DCPSubtitleDecoder.
304                         */
305
306                         auto ii = dynamic_pointer_cast<const dcp::SubtitleImage>(i);
307                         if (ii) {
308                                 emit_subtitle_image (
309                                         ContentTimePeriod (
310                                                 ContentTime::from_frames (_offset - entry_point, vfr) + ContentTime::from_seconds (i->in().as_seconds ()),
311                                                 ContentTime::from_frames (_offset - entry_point, vfr) + ContentTime::from_seconds (i->out().as_seconds ())
312                                                 ),
313                                         *ii,
314                                         size,
315                                         decoder
316                                         );
317                         }
318                 }
319
320                 if (!strings.empty()) {
321                         auto b = strings.back();
322                         decoder->emit_plain (
323                                 ContentTimePeriod (
324                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.in().as_seconds()),
325                                         ContentTime::from_frames(_offset - entry_point, vfr) + ContentTime::from_seconds(b.out().as_seconds())
326                                         ),
327                                 strings
328                                 );
329                         strings.clear ();
330                 }
331         }
332 }
333
334 void
335 DCPDecoder::next_reel ()
336 {
337         _offset += (*_reel)->main_picture()->actual_duration();
338         ++_reel;
339         get_readers ();
340 }
341
342 void
343 DCPDecoder::get_readers ()
344 {
345         if (_reel == _reels.end() || !_dcp_content->can_be_played ()) {
346                 _mono_reader.reset ();
347                 _stereo_reader.reset ();
348                 _sound_reader.reset ();
349                 _atmos_reader.reset ();
350                 return;
351         }
352
353         if ((*_reel)->main_picture()) {
354                 shared_ptr<dcp::PictureAsset> asset = (*_reel)->main_picture()->asset ();
355                 shared_ptr<dcp::MonoPictureAsset> mono = dynamic_pointer_cast<dcp::MonoPictureAsset> (asset);
356                 shared_ptr<dcp::StereoPictureAsset> stereo = dynamic_pointer_cast<dcp::StereoPictureAsset> (asset);
357                 DCPOMATIC_ASSERT (mono || stereo);
358                 if (mono) {
359                         _mono_reader = mono->start_read ();
360                         _mono_reader->set_check_hmac (false);
361                         _stereo_reader.reset ();
362                 } else {
363                         _stereo_reader = stereo->start_read ();
364                         _stereo_reader->set_check_hmac (false);
365                         _mono_reader.reset ();
366                 }
367         } else {
368                 _mono_reader.reset ();
369                 _stereo_reader.reset ();
370         }
371
372         if ((*_reel)->main_sound()) {
373                 _sound_reader = (*_reel)->main_sound()->asset()->start_read ();
374                 _sound_reader->set_check_hmac (false);
375         } else {
376                 _sound_reader.reset ();
377         }
378
379         if ((*_reel)->atmos()) {
380                 shared_ptr<dcp::AtmosAsset> asset = (*_reel)->atmos()->asset();
381                 _atmos_reader = asset->start_read();
382                 _atmos_reader->set_check_hmac (false);
383                 _atmos_metadata = AtmosMetadata (asset);
384         } else {
385                 _atmos_reader.reset ();
386                 _atmos_metadata = boost::none;
387         }
388 }
389
390 void
391 DCPDecoder::seek (ContentTime t, bool accurate)
392 {
393         if (!_dcp_content->can_be_played ()) {
394                 return;
395         }
396
397         Decoder::seek (t, accurate);
398
399         _reel = _reels.begin ();
400         _offset = 0;
401         get_readers ();
402
403         int const pre_roll_seconds = 2;
404
405         /* Pre-roll for subs */
406
407         ContentTime pre = t - ContentTime::from_seconds (pre_roll_seconds);
408         if (pre < ContentTime()) {
409                 pre = ContentTime ();
410         }
411
412         /* Seek to pre-roll position */
413
414         while (
415                 _reel != _reels.end() &&
416                 pre >= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()))
417                 ) {
418
419                 ContentTime rd = ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()));
420                 pre -= rd;
421                 t -= rd;
422                 next_reel ();
423         }
424
425         /* Pass texts in the pre-roll */
426
427         double const vfr = _dcp_content->active_video_frame_rate (film());
428         for (int i = 0; i < pre_roll_seconds * vfr; ++i) {
429                 pass_texts (pre, (*_reel)->main_picture()->asset()->size());
430                 pre += ContentTime::from_frames (1, vfr);
431         }
432
433         /* Seek to correct position */
434
435         while (
436                 _reel != _reels.end() &&
437                 t >= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()))
438                 ) {
439
440                 t -= ContentTime::from_frames ((*_reel)->main_picture()->actual_duration(), _dcp_content->active_video_frame_rate(film()));
441                 next_reel ();
442         }
443
444         _next = t;
445 }
446
447 void
448 DCPDecoder::set_decode_referenced (bool r)
449 {
450         _decode_referenced = r;
451
452         if (video) {
453                 video->set_ignore (_dcp_content->reference_video() && !_decode_referenced);
454         }
455         if (audio) {
456                 audio->set_ignore (_dcp_content->reference_audio() && !_decode_referenced);
457         }
458 }
459
460 void
461 DCPDecoder::set_forced_reduction (optional<int> reduction)
462 {
463         _forced_reduction = reduction;
464 }
465
466 string
467 DCPDecoder::calculate_lazy_digest (shared_ptr<const DCPContent> c) const
468 {
469         Digester d;
470         for (auto i: c->paths()) {
471                 d.add (i.string());
472         }
473         if (_dcp_content->kdm()) {
474                 d.add(_dcp_content->kdm()->id());
475         }
476         d.add (static_cast<bool>(c->cpl()));
477         if (c->cpl()) {
478                 d.add (c->cpl().get());
479         }
480         return d.get ();
481 }
482
483 ContentTime
484 DCPDecoder::position () const
485 {
486         return ContentTime::from_frames(_offset, _dcp_content->active_video_frame_rate(film())) + _next;
487 }
488
489
490 vector<FontData>
491 DCPDecoder::fonts () const
492 {
493         vector<FontData> data;
494         for (auto i: _reels) {
495                 if (i->main_subtitle() && i->main_subtitle()->asset()) {
496                         map<string, dcp::ArrayData> fm = i->main_subtitle()->asset()->font_data();
497                         for (map<string, dcp::ArrayData>::const_iterator j = fm.begin(); j != fm.end(); ++j) {
498                                 data.push_back (FontData(j->first, j->second));
499                         }
500                 }
501         }
502         return data;
503 }
504