Upload upstream chromium 108.0.5359.1
[platform/framework/web/chromium-efl.git] / media / filters / decoder_stream.h
1 // Copyright 2014 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 #ifndef MEDIA_FILTERS_DECODER_STREAM_H_
6 #define MEDIA_FILTERS_DECODER_STREAM_H_
7
8 #include <memory>
9 #include <vector>
10
11 #include "base/callback.h"
12 #include "base/compiler_specific.h"
13 #include "base/containers/circular_deque.h"
14 #include "base/memory/raw_ptr.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/time/time.h"
18 #include "base/types/pass_key.h"
19 #include "media/base/audio_decoder.h"
20 #include "media/base/audio_timestamp_helper.h"
21 #include "media/base/decoder_status.h"
22 #include "media/base/demuxer_stream.h"
23 #include "media/base/media_export.h"
24 #include "media/base/media_log.h"
25 #include "media/base/moving_average.h"
26 #include "media/base/pipeline_status.h"
27 #include "media/base/timestamp_constants.h"
28 #include "media/base/waiting.h"
29 #include "media/filters/decoder_selector.h"
30 #include "media/filters/decoder_stream_traits.h"
31
32 namespace base {
33 class SequencedTaskRunner;
34 }
35
36 namespace media {
37
38 class CdmContext;
39 class DecryptingDemuxerStream;
40
41 // Wraps a DemuxerStream and a list of Decoders and provides decoded
42 // output to its client (e.g. Audio/VideoRendererImpl).
43 template <DemuxerStream::Type StreamType>
44 class MEDIA_EXPORT DecoderStream {
45  public:
46   using StreamTraits = DecoderStreamTraits<StreamType>;
47   using Decoder = typename StreamTraits::DecoderType;
48   using Output = typename StreamTraits::OutputType;
49   using DecoderConfig = typename StreamTraits::DecoderConfigType;
50
51   // Callback to create a list of decoders.
52   using CreateDecodersCB =
53       base::RepeatingCallback<std::vector<std::unique_ptr<Decoder>>()>;
54
55   // Indicates completion of a DecoderStream initialization.
56   using InitCB = base::OnceCallback<void(bool success)>;
57
58   // Indicates completion of a DecoderStream read.
59   using ReadResult = DecoderStatus::Or<scoped_refptr<Output>>;
60   using ReadCB = base::OnceCallback<void(ReadResult)>;
61
62   DecoderStream(std::unique_ptr<DecoderStreamTraits<StreamType>> traits,
63                 scoped_refptr<base::SequencedTaskRunner> task_runner,
64                 CreateDecodersCB create_decoders_cb,
65                 MediaLog* media_log);
66   virtual ~DecoderStream();
67
68   // Initializes the DecoderStream and returns the initialization result
69   // through |init_cb|. Note that |init_cb| is always called asynchronously.
70   // |cdm_context| can be used to handle encrypted stream. Can be null if the
71   // stream is not encrypted.
72   void Initialize(DemuxerStream* stream,
73                   InitCB init_cb,
74                   CdmContext* cdm_context,
75                   StatisticsCB statistics_cb,
76                   WaitingCB waiting_cb);
77
78   // Reads a decoded Output and returns it via the |read_cb|. Note that
79   // |read_cb| is always called asynchronously. This method should only be
80   // called after initialization has succeeded and must not be called during
81   // pending Reset().
82   void Read(ReadCB read_cb);
83
84   // Resets the decoder, flushes all decoded outputs and/or internal buffers,
85   // fires any existing pending read callback and calls |closure| on completion.
86   // Note that |closure| is always called asynchronously. This method should
87   // only be called after initialization has succeeded and must not be called
88   // during pending Reset().
89   // N.B: If the decoder stream has run into an error, calling this method does
90   // not 'reset' it to a normal state.
91   void Reset(base::OnceClosure closure);
92
93   // Returns true if the decoder currently has the ability to decode and return
94   // an Output.
95   bool CanReadWithoutStalling() const;
96
97   base::TimeDelta AverageDuration() const;
98
99   // Indicates that outputs need preparation (e.g., copying into GPU buffers)
100   // before being marked as ready. When an output is given by the decoder it
101   // will be added to |unprepared_outputs_| if a PrepareCB has been specified.
102   // If the size of |ready_outputs_| is less than
103   // Decoder::GetMaxDecodeRequests(), the provided PrepareCB will be called for
104   // the output. Once an output has been prepared by the PrepareCB it must call
105   // the given OutputReadyCB with the prepared output.
106   //
107   // This process is structured such that only a fixed number of outputs are
108   // prepared at any one time; this alleviates resource usage issues incurred by
109   // the preparation process when a decoder has a burst of outputs after on
110   // Decode(). For more context on why, see https://crbug.com/820167.
111   using OutputReadyCB = base::OnceCallback<void(scoped_refptr<Output>)>;
112   using PrepareCB =
113       base::RepeatingCallback<void(scoped_refptr<Output>, OutputReadyCB)>;
114   void SetPrepareCB(PrepareCB prepare_cb);
115
116   // Indicates that we won't need to prepare outputs before |start_timestamp|,
117   // so that the preparation step (which is generally expensive) can be skipped.
118   void SkipPrepareUntil(base::TimeDelta start_timestamp);
119
120   // Allows callers to register for notification of config changes; this is
121   // called immediately after receiving the 'kConfigChanged' status from the
122   // DemuxerStream, before any action is taken to handle the config change.
123   using ConfigChangeObserverCB =
124       base::RepeatingCallback<void(const DecoderConfig&)>;
125   void set_config_change_observer(
126       ConfigChangeObserverCB config_change_observer) {
127     config_change_observer_cb_ = config_change_observer;
128   }
129
130   // Allow interested folks to keep track the currently selected decoder.  The
131   // provided decoder is valid only during the scope of the callback.
132   using DecoderChangeObserverCB = base::RepeatingCallback<void(Decoder*)>;
133   void set_decoder_change_observer(
134       DecoderChangeObserverCB decoder_change_observer_cb) {
135     decoder_change_observer_cb_ = std::move(decoder_change_observer_cb);
136   }
137
138   void set_fallback_observer(PipelineStatusCB fallback_cb) {
139     fallback_cb_ = std::move(fallback_cb);
140   }
141
142   int get_pending_buffers_size_for_testing() const {
143     return pending_buffers_.size();
144   }
145
146   int get_fallback_buffers_size_for_testing() const {
147     return fallback_buffers_.size();
148   }
149
150   bool is_demuxer_read_pending() const { return pending_demuxer_read_; }
151
152   DecoderSelector<StreamType>& GetDecoderSelectorForTesting(
153       base::PassKey<class VideoDecoderStreamTest>) {
154     return decoder_selector_;
155   }
156
157  private:
158   enum State {
159     STATE_UNINITIALIZED,
160     STATE_INITIALIZING,
161     STATE_NORMAL,  // Includes idle, pending decoder decode/reset.
162     STATE_FLUSHING_DECODER,
163     STATE_REINITIALIZING_DECODER,
164     STATE_END_OF_STREAM,  // End of stream reached; returns EOS on all reads.
165     STATE_ERROR,
166   };
167
168   // Returns the string representation of the StreamType for logging purpose.
169   std::string GetStreamTypeString();
170
171   // Returns maximum concurrent decode requests for the current |decoder_|.
172   int GetMaxDecodeRequests() const;
173
174   // Returns the maximum number of outputs we should keep ready at any one time.
175   int GetMaxReadyOutputs() const;
176
177   // Returns true if one more decode request can be submitted to the decoder.
178   bool CanDecodeMore() const;
179
180   void BeginDecoderSelection();
181   void ResumeDecoderSelection(DecoderStatus&& reinit_cause);
182
183   // Called when |decoder_selector| selected the |selected_decoder|.
184   // |decrypting_demuxer_stream| was also populated if a DecryptingDemuxerStream
185   // is created to help decrypt the encrypted stream.
186   void OnDecoderSelected(
187       DecoderStatus::Or<std::unique_ptr<Decoder>> decoder_or_error,
188       std::unique_ptr<DecryptingDemuxerStream> decrypting_demuxer_stream);
189
190   // Satisfy pending |read_cb_| with |result|.
191   void SatisfyRead(ReadResult result);
192
193   // Decodes |buffer| and returns the result via OnDecodeOutputReady().
194   // Saves |buffer| into |pending_buffers_| if appropriate.
195   void Decode(scoped_refptr<DecoderBuffer> buffer);
196
197   // Performs the heavy lifting of the decode call.
198   void DecodeInternal(scoped_refptr<DecoderBuffer> buffer);
199
200   // Flushes the decoder with an EOS buffer to retrieve internally buffered
201   // decoder output.
202   void FlushDecoder();
203
204   // Callback for Decoder::Decode().
205   void OnDecodeDone(int buffer_size,
206                     bool end_of_stream,
207                     std::unique_ptr<ScopedDecodeTrace> trace_event,
208                     DecoderStatus status);
209
210   // Output callback passed to Decoder::Initialize().
211   void OnDecodeOutputReady(scoped_refptr<Output> output);
212
213   // Reads a buffer from |stream_| and returns the result via OnBufferReady().
214   void ReadFromDemuxerStream();
215
216   // Callback for DemuxerStream::Read().
217   void OnBufferReady(DemuxerStream::Status status,
218                      scoped_refptr<DecoderBuffer> buffer);
219
220   void ReinitializeDecoder();
221
222   void CompleteDecoderReinitialization(DecoderStatus status);
223
224   void ResetDecoder();
225   void OnDecoderReset();
226
227   void ClearOutputs();
228   void MaybePrepareAnotherOutput();
229   void OnPreparedOutputReady(scoped_refptr<Output> frame);
230   void CompletePrepare(const Output* output);
231
232   void ReportEncryptionType(const scoped_refptr<DecoderBuffer>& buffer);
233
234   std::unique_ptr<DecoderStreamTraits<StreamType>> traits_;
235
236   scoped_refptr<base::SequencedTaskRunner> task_runner_;
237   raw_ptr<MediaLog> media_log_;
238
239   State state_;
240
241   StatisticsCB statistics_cb_;
242   InitCB init_cb_;
243   WaitingCB waiting_cb_;
244   PipelineStatusCB fallback_cb_;
245
246   ReadCB read_cb_;
247   base::OnceClosure reset_cb_;
248
249   raw_ptr<DemuxerStream> stream_;
250
251   raw_ptr<CdmContext> cdm_context_;
252
253   std::unique_ptr<Decoder> decoder_;
254
255   // Whether |decoder_| has produced a frame yet. Reset on fallback.
256   bool decoder_produced_a_frame_;
257
258   std::unique_ptr<DecryptingDemuxerStream> decrypting_demuxer_stream_;
259
260   // Note: Holds pointers to |traits_|, |stream_|, |decrypting_demuxer_stream_|,
261   // and |cdm_context_|.
262   DecoderSelector<StreamType> decoder_selector_;
263
264   ConfigChangeObserverCB config_change_observer_cb_;
265   DecoderChangeObserverCB decoder_change_observer_cb_;
266
267   // An end-of-stream buffer has been sent for decoding, no more buffers should
268   // be sent for decoding until it completes.
269   // TODO(sandersd): Turn this into a State. http://crbug.com/408316
270   bool decoding_eos_;
271
272   PrepareCB prepare_cb_;
273   bool preparing_output_;
274
275   // Decoded buffers that haven't been read yet. If |prepare_cb_| has been set
276   // |unprepared_outputs_| will contain buffers which haven't been prepared yet.
277   // Once prepared or if preparation is not required, outputs will be put into
278   // |ready_outputs_|.
279   base::circular_deque<scoped_refptr<Output>> unprepared_outputs_;
280   base::circular_deque<scoped_refptr<Output>> ready_outputs_;
281
282   // Number of outstanding decode requests sent to the |decoder_|.
283   int pending_decode_requests_;
284
285   // Tracks the duration of incoming packets over time.
286   MovingAverage duration_tracker_;
287
288   // Stores buffers that might be reused if the decoder fails right after
289   // Initialize().
290   base::circular_deque<scoped_refptr<DecoderBuffer>> pending_buffers_;
291
292   // Stores buffers that are guaranteed to be fed to the decoder before fetching
293   // more from the demuxer stream. All buffers in this queue first were in
294   // |pending_buffers_|.
295   base::circular_deque<scoped_refptr<DecoderBuffer>> fallback_buffers_;
296
297   // TODO(tguilbert): support config changes during decoder fallback, see
298   // crbug.com/603713
299   bool received_config_change_during_reinit_;
300
301   // Used to track read requests; not rolled into |state_| since that is
302   // overwritten in many cases.
303   bool pending_demuxer_read_;
304
305   // Timestamp after which all outputs need to be prepared.
306   base::TimeDelta skip_prepare_until_timestamp_;
307
308   bool encryption_type_reported_ = false;
309
310   int fallback_buffers_being_decoded_ = 0;
311
312   // NOTE: Weak pointers must be invalidated before all other member variables.
313   base::WeakPtrFactory<DecoderStream<StreamType>> weak_factory_{this};
314
315   // Used to invalidate pending decode requests and output callbacks.
316   base::WeakPtrFactory<DecoderStream<StreamType>> fallback_weak_factory_{this};
317
318   // Used to invalidate outputs awaiting preparation. This can't use either of
319   // the above factories since they are used to bind one time callbacks given
320   // to decoders that may not be reinitialized after Reset().
321   base::WeakPtrFactory<DecoderStream<StreamType>> prepare_weak_factory_{this};
322 };
323
324 template <>
325 bool DecoderStream<DemuxerStream::AUDIO>::CanReadWithoutStalling() const;
326
327 template <>
328 int DecoderStream<DemuxerStream::AUDIO>::GetMaxDecodeRequests() const;
329
330 using VideoDecoderStream = DecoderStream<DemuxerStream::VIDEO>;
331 using AudioDecoderStream = DecoderStream<DemuxerStream::AUDIO>;
332
333 }  // namespace media
334
335 #endif  // MEDIA_FILTERS_DECODER_STREAM_H_