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