Upload upstream chromium 114.0.5735.31
[platform/framework/web/chromium-efl.git] / media / filters / decrypting_video_decoder.cc
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "media/filters/decrypting_video_decoder.h"
6
7 #include "base/functional/bind.h"
8 #include "base/functional/callback_helpers.h"
9 #include "base/location.h"
10 #include "base/logging.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/task/bind_post_task.h"
13 #include "base/task/sequenced_task_runner.h"
14 #include "base/trace_event/trace_event.h"
15 #include "media/base/cdm_context.h"
16 #include "media/base/decoder_buffer.h"
17 #include "media/base/media_log.h"
18 #include "media/base/video_frame.h"
19
20 namespace media {
21
22 const char DecryptingVideoDecoder::kDecoderName[] = "DecryptingVideoDecoder";
23
24 DecryptingVideoDecoder::DecryptingVideoDecoder(
25     const scoped_refptr<base::SequencedTaskRunner>& task_runner,
26     MediaLog* media_log)
27     : task_runner_(task_runner), media_log_(media_log) {
28   DETACH_FROM_SEQUENCE(sequence_checker_);
29 }
30
31 VideoDecoderType DecryptingVideoDecoder::GetDecoderType() const {
32   return VideoDecoderType::kDecrypting;
33 }
34
35 void DecryptingVideoDecoder::Initialize(const VideoDecoderConfig& config,
36                                         bool /* low_delay */,
37                                         CdmContext* cdm_context,
38                                         InitCB init_cb,
39                                         const OutputCB& output_cb,
40                                         const WaitingCB& waiting_cb) {
41   DVLOG(2) << __func__ << ": " << config.AsHumanReadableString();
42
43   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
44   DCHECK(state_ == kUninitialized || state_ == kIdle ||
45          state_ == kDecodeFinished)
46       << state_;
47   DCHECK(!decode_cb_);
48   DCHECK(!reset_cb_);
49   DCHECK(config.IsValidConfig());
50
51   init_cb_ = base::BindPostTaskToCurrentDefault(std::move(init_cb));
52
53   if (!cdm_context) {
54     // Once we have a CDM context, one should always be present.
55     DCHECK(!support_clear_content_);
56     std::move(init_cb_).Run(DecoderStatus::Codes::kUnsupportedEncryptionMode);
57     return;
58   }
59
60   if (!config.is_encrypted() && !support_clear_content_) {
61     std::move(init_cb_).Run(DecoderStatus::Codes::kUnsupportedEncryptionMode);
62     return;
63   }
64
65   // Once initialized with encryption support, the value is sticky, so we'll use
66   // the decryptor for clear content as well.
67   support_clear_content_ = true;
68
69   output_cb_ = base::BindPostTaskToCurrentDefault(output_cb);
70   config_ = config;
71
72   DCHECK(waiting_cb);
73   waiting_cb_ = waiting_cb;
74
75   if (state_ == kUninitialized) {
76     if (!cdm_context->GetDecryptor()) {
77       DVLOG(1) << __func__ << ": no decryptor";
78       std::move(init_cb_).Run(DecoderStatus::Codes::kUnsupportedEncryptionMode);
79       return;
80     }
81
82     decryptor_ = cdm_context->GetDecryptor();
83     event_cb_registration_ = cdm_context->RegisterEventCB(
84         base::BindRepeating(&DecryptingVideoDecoder::OnCdmContextEvent,
85                             weak_factory_.GetWeakPtr()));
86   } else {
87     // Reinitialization (i.e. upon a config change). The new config can be
88     // encrypted or clear.
89     decryptor_->DeinitializeDecoder(Decryptor::kVideo);
90   }
91
92   state_ = kPendingDecoderInit;
93   decryptor_->InitializeVideoDecoder(
94       config_, base::BindPostTaskToCurrentDefault(
95                    base::BindOnce(&DecryptingVideoDecoder::FinishInitialization,
96                                   weak_factory_.GetWeakPtr())));
97 }
98
99 bool DecryptingVideoDecoder::SupportsDecryption() const {
100   return true;
101 }
102
103 void DecryptingVideoDecoder::Decode(scoped_refptr<DecoderBuffer> buffer,
104                                     DecodeCB decode_cb) {
105   DVLOG(3) << "Decode()";
106   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
107   DCHECK(state_ == kIdle || state_ == kDecodeFinished || state_ == kError)
108       << state_;
109   DCHECK(decode_cb);
110   CHECK(!decode_cb_) << "Overlapping decodes are not supported.";
111
112   decode_cb_ = base::BindPostTaskToCurrentDefault(std::move(decode_cb));
113
114   if (state_ == kError) {
115     std::move(decode_cb_).Run(DecoderStatus::Codes::kPlatformDecodeFailure);
116     return;
117   }
118
119   // Return empty frames if decoding has finished.
120   if (state_ == kDecodeFinished) {
121     std::move(decode_cb_).Run(DecoderStatus::Codes::kOk);
122     return;
123   }
124
125   pending_buffer_to_decode_ = std::move(buffer);
126   state_ = kPendingDecode;
127   DecodePendingBuffer();
128 }
129
130 void DecryptingVideoDecoder::Reset(base::OnceClosure closure) {
131   DVLOG(2) << "Reset() - state: " << state_;
132   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
133   DCHECK(state_ == kIdle || state_ == kPendingDecode ||
134          state_ == kWaitingForKey || state_ == kDecodeFinished ||
135          state_ == kError)
136       << state_;
137   DCHECK(!init_cb_);  // No Reset() during pending initialization.
138   DCHECK(!reset_cb_);
139
140   reset_cb_ = base::BindPostTaskToCurrentDefault(std::move(closure));
141
142   decryptor_->ResetDecoder(Decryptor::kVideo);
143
144   // Reset() cannot complete if the decode callback is still pending.
145   // Defer the resetting process in this case. The |reset_cb_| will be fired
146   // after the decode callback is fired - see DecryptAndDecodeBuffer() and
147   // DeliverFrame().
148   if (state_ == kPendingDecode) {
149     DCHECK(decode_cb_);
150     return;
151   }
152
153   if (state_ == kWaitingForKey) {
154     CompleteWaitingForDecryptionKey();
155     DCHECK(decode_cb_);
156     pending_buffer_to_decode_.reset();
157     std::move(decode_cb_).Run(DecoderStatus::Codes::kAborted);
158   }
159
160   DCHECK(!decode_cb_);
161   DoReset();
162 }
163
164 DecryptingVideoDecoder::~DecryptingVideoDecoder() {
165   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
166
167   if (state_ == kUninitialized)
168     return;
169
170   if (state_ == kWaitingForKey)
171     CompleteWaitingForDecryptionKey();
172   if (state_ == kPendingDecode)
173     CompletePendingDecode(Decryptor::kError);
174
175   if (decryptor_) {
176     decryptor_->DeinitializeDecoder(Decryptor::kVideo);
177     decryptor_ = nullptr;
178   }
179   pending_buffer_to_decode_.reset();
180   if (init_cb_)
181     std::move(init_cb_).Run(DecoderStatus::Codes::kInterrupted);
182   if (decode_cb_)
183     std::move(decode_cb_).Run(DecoderStatus::Codes::kAborted);
184   if (reset_cb_)
185     std::move(reset_cb_).Run();
186 }
187
188 void DecryptingVideoDecoder::FinishInitialization(bool success) {
189   DVLOG(2) << "FinishInitialization()";
190   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
191   DCHECK_EQ(state_, kPendingDecoderInit) << state_;
192   DCHECK(init_cb_);
193   DCHECK(!reset_cb_);   // No Reset() before initialization finished.
194   DCHECK(!decode_cb_);  // No Decode() before initialization finished.
195
196   if (!success) {
197     DVLOG(1) << __func__ << ": failed to init video decoder on decryptor";
198     // TODO(*) Is there a better reason? Should this method itself take a
199     // status?
200     std::move(init_cb_).Run(DecoderStatus::Codes::kFailed);
201     decryptor_ = nullptr;
202     event_cb_registration_.reset();
203     state_ = kError;
204     return;
205   }
206
207   // Success!
208   state_ = kIdle;
209   std::move(init_cb_).Run(DecoderStatus::Codes::kOk);
210 }
211
212 void DecryptingVideoDecoder::DecodePendingBuffer() {
213   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
214   DCHECK_EQ(state_, kPendingDecode) << state_;
215
216   // Note: Traces require a unique ID per decode, if we ever support multiple
217   // in flight decodes, the trace begin+end macros need the same unique id.
218   DCHECK_EQ(GetMaxDecodeRequests(), 1);
219   TRACE_EVENT_ASYNC_BEGIN1(
220       "media", "DecryptingVideoDecoder::DecodePendingBuffer", this,
221       "timestamp_us",
222       pending_buffer_to_decode_->end_of_stream()
223           ? 0
224           : pending_buffer_to_decode_->timestamp().InMicroseconds());
225
226   if (!DecoderBuffer::DoSubsamplesMatch(*pending_buffer_to_decode_)) {
227     MEDIA_LOG(ERROR, media_log_)
228         << "DecryptingVideoDecoder: Subsamples for Buffer do not match";
229     state_ = kError;
230     std::move(decode_cb_).Run(DecoderStatus::Codes::kPlatformDecodeFailure);
231     return;
232   }
233
234   decryptor_->DecryptAndDecodeVideo(
235       pending_buffer_to_decode_,
236       base::BindPostTaskToCurrentDefault(base::BindRepeating(
237           &DecryptingVideoDecoder::DeliverFrame, weak_factory_.GetWeakPtr())));
238 }
239
240 void DecryptingVideoDecoder::DeliverFrame(Decryptor::Status status,
241                                           scoped_refptr<VideoFrame> frame) {
242   DVLOG(3) << "DeliverFrame() - status: " << status;
243   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
244   DCHECK_EQ(state_, kPendingDecode) << state_;
245   DCHECK(decode_cb_);
246   DCHECK(pending_buffer_to_decode_.get());
247   CompletePendingDecode(status);
248
249   bool need_to_try_again_if_nokey_is_returned = key_added_while_decode_pending_;
250   key_added_while_decode_pending_ = false;
251
252   scoped_refptr<DecoderBuffer> scoped_pending_buffer_to_decode =
253       std::move(pending_buffer_to_decode_);
254
255   if (reset_cb_) {
256     std::move(decode_cb_).Run(DecoderStatus::Codes::kAborted);
257     DoReset();
258     return;
259   }
260
261   DCHECK_EQ(status == Decryptor::kSuccess, frame.get() != nullptr);
262
263   if (status == Decryptor::kError) {
264     DVLOG(2) << "DeliverFrame() - kError";
265     MEDIA_LOG(ERROR, media_log_) << GetDecoderType() << ": decode error";
266     state_ = kError;
267     std::move(decode_cb_).Run(DecoderStatus::Codes::kPlatformDecodeFailure);
268     return;
269   }
270
271   if (status == Decryptor::kNoKey) {
272     std::string key_id =
273         scoped_pending_buffer_to_decode->decrypt_config()->key_id();
274     std::string log_message =
275         "no key for key ID " + base::HexEncode(key_id.data(), key_id.size()) +
276         "; will resume decoding after new usable key is available";
277     DVLOG(1) << __func__ << ": " << log_message;
278     MEDIA_LOG(INFO, media_log_) << GetDecoderType() << ": " << log_message;
279
280     // Set |pending_buffer_to_decode_| back as we need to try decoding the
281     // pending buffer again when new key is added to the decryptor.
282     pending_buffer_to_decode_ = std::move(scoped_pending_buffer_to_decode);
283
284     if (need_to_try_again_if_nokey_is_returned) {
285       // The |state_| is still kPendingDecode.
286       MEDIA_LOG(INFO, media_log_)
287           << GetDecoderType() << ": key was added, resuming decode";
288       DecodePendingBuffer();
289       return;
290     }
291
292     TRACE_EVENT_ASYNC_BEGIN0(
293         "media", "DecryptingVideoDecoder::WaitingForDecryptionKey", this);
294     state_ = kWaitingForKey;
295     waiting_cb_.Run(WaitingReason::kNoDecryptionKey);
296     return;
297   }
298
299   if (status == Decryptor::kNeedMoreData) {
300     DVLOG(2) << "DeliverFrame() - kNeedMoreData";
301     state_ = scoped_pending_buffer_to_decode->end_of_stream() ? kDecodeFinished
302                                                               : kIdle;
303     std::move(decode_cb_).Run(DecoderStatus::Codes::kOk);
304     return;
305   }
306
307   DCHECK_EQ(status, Decryptor::kSuccess);
308   CHECK(frame);
309
310   // Frame returned with kSuccess should not be an end-of-stream frame.
311   DCHECK(!frame->metadata().end_of_stream);
312
313   // If color space is not set, use the color space in the |config_|.
314   if (!frame->ColorSpace().IsValid()) {
315     DVLOG(3) << "Setting color space using information in the config.";
316     if (config_.color_space_info().IsSpecified())
317       frame->set_color_space(config_.color_space_info().ToGfxColorSpace());
318   }
319
320   output_cb_.Run(std::move(frame));
321
322   if (scoped_pending_buffer_to_decode->end_of_stream()) {
323     // Set |pending_buffer_to_decode_| back as we need to keep flushing the
324     // decryptor.
325     pending_buffer_to_decode_ = std::move(scoped_pending_buffer_to_decode);
326     DecodePendingBuffer();
327     return;
328   }
329
330   state_ = kIdle;
331   std::move(decode_cb_).Run(DecoderStatus::Codes::kOk);
332 }
333
334 void DecryptingVideoDecoder::OnCdmContextEvent(CdmContext::Event event) {
335   DVLOG(2) << __func__;
336   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
337
338   if (event != CdmContext::Event::kHasAdditionalUsableKey)
339     return;
340
341   if (state_ == kPendingDecode) {
342     key_added_while_decode_pending_ = true;
343     return;
344   }
345
346   if (state_ == kWaitingForKey) {
347     CompleteWaitingForDecryptionKey();
348     MEDIA_LOG(INFO, media_log_)
349         << GetDecoderType() << ": key added, resuming decode";
350     state_ = kPendingDecode;
351     DecodePendingBuffer();
352   }
353 }
354
355 void DecryptingVideoDecoder::DoReset() {
356   DCHECK(!init_cb_);
357   DCHECK(!decode_cb_);
358   state_ = kIdle;
359   std::move(reset_cb_).Run();
360 }
361
362 void DecryptingVideoDecoder::CompletePendingDecode(Decryptor::Status status) {
363   DCHECK_EQ(state_, kPendingDecode);
364   TRACE_EVENT_ASYNC_END1("media", "DecryptingVideoDecoder::DecodePendingBuffer",
365                          this, "status", Decryptor::GetStatusName(status));
366 }
367
368 void DecryptingVideoDecoder::CompleteWaitingForDecryptionKey() {
369   DCHECK_EQ(state_, kWaitingForKey);
370   TRACE_EVENT_ASYNC_END0(
371       "media", "DecryptingVideoDecoder::WaitingForDecryptionKey", this);
372 }
373
374 }  // namespace media