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