Revert "[M120 Migration]Fix for crash during chrome exit"
[platform/framework/web/chromium-efl.git] / media / filters / source_buffer_stream.h
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 // SourceBufferStream is a data structure that stores media Buffers in ranges.
6 // Buffers can be appended out of presentation order. Buffers are retrieved by
7 // seeking to the desired start point and calling GetNextBuffer(). Buffers are
8 // returned in sequential order to feed decoder, generally near presentation
9 // order though not necessarily the same as presentation order within GOPs of
10 // out-of-order codecs.
11
12 #ifndef MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_
13 #define MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_
14
15 #include <stddef.h>
16
17 #include <list>
18 #include <memory>
19 #include <string>
20 #include <type_traits>
21 #include <utility>
22 #include <vector>
23
24 #include "base/memory/memory_pressure_listener.h"
25 #include "base/memory/raw_ptr.h"
26 #include "base/memory/scoped_refptr.h"
27 #include "base/time/time.h"
28 #include "media/base/audio_decoder_config.h"
29 #include "media/base/media_export.h"
30 #include "media/base/media_log.h"
31 #include "media/base/ranges.h"
32 #include "media/base/stream_parser_buffer.h"
33 #include "media/base/video_decoder_config.h"
34 #include "media/filters/source_buffer_range.h"
35
36 namespace media {
37
38 // Status returned by GetNextBuffer().
39 // kSuccess: Indicates that the next buffer was returned.
40 // kNeedBuffer: Indicates that we need more data before a buffer can be
41 //              returned.
42 // kConfigChange: Indicates that the next buffer requires a config change.
43 enum class SourceBufferStreamStatus {
44   kSuccess,
45   kNeedBuffer,
46   kConfigChange,
47   kEndOfStream
48 };
49
50 enum class SourceBufferStreamType { kAudio, kVideo };
51
52 // See file-level comment for complete description.
53 class MEDIA_EXPORT SourceBufferStream {
54  public:
55   using BufferQueue = StreamParser::BufferQueue;
56   using RangeList = std::list<std::unique_ptr<SourceBufferRange>>;
57
58   // Helper for PrepareRangesForNextAppend and BufferQueueToLogString that
59   // populates |start| and |end| with the presentation interval of |buffers|.
60   static void GetTimestampInterval(const BufferQueue& buffers,
61                                    base::TimeDelta* start,
62                                    base::TimeDelta* end);
63
64   SourceBufferStream(const AudioDecoderConfig& audio_config,
65                      MediaLog* media_log);
66   SourceBufferStream(const VideoDecoderConfig& video_config,
67                      MediaLog* media_log);
68
69   SourceBufferStream(const SourceBufferStream&) = delete;
70   SourceBufferStream& operator=(const SourceBufferStream&) = delete;
71
72   ~SourceBufferStream();
73
74   // Signals that the next buffers appended are part of a new coded frame group
75   // starting at |coded_frame_group_start_pts|.
76   void OnStartOfCodedFrameGroup(base::TimeDelta coded_frame_group_start_pts);
77
78   // Add the |buffers| to the SourceBufferStream. Buffers within the queue are
79   // expected to be in order, but multiple calls to Append() may add buffers out
80   // of order or overlapping. Assumes all buffers within |buffers| are in
81   // presentation order and are non-overlapping.
82   void Append(const BufferQueue& buffers);
83
84   // Removes buffers between |start| and |end| according to the steps
85   // in the "Coded Frame Removal Algorithm" in the Media Source
86   // Extensions Spec.
87   // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-coded-frame-removal
88   //
89   // |duration| is the current duration of the presentation. It is
90   // required by the computation outlined in the spec.
91   void Remove(base::TimeDelta start, base::TimeDelta end,
92               base::TimeDelta duration);
93
94   // Frees up space if the SourceBufferStream is taking up too much memory.
95   // |media_time| is current playback position.
96   bool GarbageCollectIfNeeded(base::TimeDelta media_time, size_t newDataSize);
97
98   // Gets invoked when the system is experiencing memory pressure, i.e. there's
99   // not enough free memory. The |media_time| is the media playback position at
100   // the time of memory pressure notification (needed for accurate GC). The
101   // |memory_pressure_level| indicates memory pressure severity. The
102   // |force_instant_gc| is used to force the MSE garbage collection algorithm to
103   // be run right away, without waiting for the next append.
104   void OnMemoryPressure(
105       base::TimeDelta media_time,
106       base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level,
107       bool force_instant_gc);
108
109   // Changes the SourceBufferStream's state so that it will start returning
110   // buffers starting from the closest keyframe before |timestamp|.
111   void Seek(base::TimeDelta timestamp);
112
113   // Returns true if the SourceBufferStream has seeked to a time without
114   // buffered data and is waiting for more data to be appended.
115   bool IsSeekPending() const;
116
117   // Notifies the SourceBufferStream that the media duration has been changed to
118   // |duration| so it should drop any data past that point.
119   void OnSetDuration(base::TimeDelta duration);
120
121   // Fills |out_buffer| with a new buffer. Buffers are presented in order from
122   // the last call to Seek(), or starting with the first buffer appended if
123   // Seek() has not been called yet.
124   // |out_buffer|'s timestamp may be earlier than the |timestamp| passed to
125   // the last Seek() call.
126   // Returns kSuccess if |out_buffer| is filled with a valid buffer, kNeedBuffer
127   // if there is not enough data buffered to fulfill the request, and
128   // kConfigChange if the next buffer requires a config change.
129   SourceBufferStreamStatus GetNextBuffer(
130       scoped_refptr<StreamParserBuffer>* out_buffer);
131
132   // Returns a list of the buffered time ranges.
133   Ranges<base::TimeDelta> GetBufferedTime() const;
134
135   // Returns the lowest buffered PTS or base::TimeDelta() if nothing is
136   // buffered.
137   base::TimeDelta GetLowestPresentationTimestamp() const;
138
139   // Returns the highest buffered PTS or base::TimeDelta() if nothing is
140   // buffered.
141   base::TimeDelta GetHighestPresentationTimestamp() const;
142
143   // Returns the duration of the buffered ranges, which is equivalent
144   // to the end timestamp of the last buffered range. If no data is buffered
145   // then base::TimeDelta() is returned.
146   base::TimeDelta GetBufferedDuration() const;
147
148   // Returns the size of the buffered data in bytes.
149   size_t GetBufferedSize() const;
150
151   // Notifies this object that end of stream has been signalled.
152   void MarkEndOfStream();
153
154   // Clear the end of stream state set by MarkEndOfStream().
155   void UnmarkEndOfStream();
156
157   const AudioDecoderConfig& GetCurrentAudioDecoderConfig();
158   const VideoDecoderConfig& GetCurrentVideoDecoderConfig();
159
160 #if BUILDFLAG(IS_TIZEN_TV)
161   void updateFramerate(const StreamFramerate::Framerate& framerate);
162 #endif
163
164   // Notifies this object that the audio config has changed and buffers in
165   // future Append() calls should be associated with this new config.
166   // If the codec is allowed to change, the caller should set
167   // |allow_codec_change| to true.
168   bool UpdateAudioConfig(const AudioDecoderConfig& config,
169                          bool allow_codec_change);
170
171   // Notifies this object that the video config has changed and buffers in
172   // future Append() calls should be associated with this new config.
173   // If the codec is allowed to change, the caller should set
174   // |allow_codec_change| to true.
175   bool UpdateVideoConfig(const VideoDecoderConfig& config,
176                          bool allow_codec_change);
177
178   // Returns the largest distance between two adjacent buffers in this stream,
179   // or an estimate if no two adjacent buffers have been appended to the stream
180   // yet.
181   base::TimeDelta GetMaxInterbufferDistance() const;
182
183   void set_memory_limit(size_t memory_limit) {
184     memory_limit_ = memory_limit;
185   }
186
187   // A helper function for detecting video/audio config change, so that we
188   // can "peek" the next buffer instead of dequeuing it directly from the source
189   // stream buffer queue.
190   bool IsNextBufferConfigChanged();
191
192  private:
193   friend class SourceBufferStreamTest;
194
195   // Attempts to delete approximately |total_bytes_to_free| amount of data
196   // |ranges_|, starting at the front of |ranges_| and moving linearly forward
197   // through the buffers. Deletes starting from the back if |reverse_direction|
198   // is true. |media_time| is current playback position.
199   // Returns the number of bytes freed.
200   size_t FreeBuffers(size_t total_bytes_to_free,
201                      base::TimeDelta media_time,
202                      bool reverse_direction);
203
204   // Attempts to delete approximately |total_bytes_to_free| amount of data from
205   // |ranges_|, starting after the last appended media
206   // (|highest_buffered_end_time_in_append_sequence_|) but before the current
207   // playback position |media_time|.
208   size_t FreeBuffersAfterLastAppended(size_t total_bytes_to_free,
209                                       base::TimeDelta media_time);
210
211   // Gets the removal range to secure |total_bytes_to_free| from
212   // [|start_timestamp|, |end_timestamp|).
213   // Returns the size of buffers to secure if future
214   // Remove(|start_timestamp|, |removal_end_timestamp|, duration) is called.
215   // Will not update |removal_end_timestamp| if the returned size is 0.
216   size_t GetRemovalRange(base::TimeDelta start_timestamp,
217                          base::TimeDelta end_timestamp,
218                          size_t total_bytes_to_free,
219                          base::TimeDelta* removal_end_timestamp);
220
221   // Prepares |range_for_next_append_| so |new_buffers| can be appended.
222   // This involves removing buffers between the end of the previous append
223   // and any buffers covered by the time range in |new_buffers|.
224   // |deleted_buffers| is an output parameter containing candidates for
225   // |track_buffer_| if this method ends up removing the current playback
226   // position from the range.
227   void PrepareRangesForNextAppend(const BufferQueue& new_buffers,
228                                   BufferQueue* deleted_buffers);
229
230   // Removes buffers, from the |track_buffer_|, that come after |timestamp|.
231   // Due to out-of-order decode versus presentation times for some kinds of
232   // media, |timestamp| should be the time of a keyframe known by the caller.
233   // |timestamp| must not be kNoTimestamp.
234   void PruneTrackBuffer(const base::TimeDelta timestamp);
235
236   // Checks to see if |range_with_new_buffers_itr| can be merged with the range
237   // next to it, and merges them if so while preserving correctness of
238   // |range_for_next_append_| and |selected_range_|.
239   void MergeWithNextRangeIfNecessary(
240       const RangeList::iterator& range_with_new_buffers_itr);
241
242   // Merges any adjacent ranges while preserving correctness of
243   // |range_for_next_append_| and |selected_range_|.
244   void MergeAllAdjacentRanges();
245
246   // Returns true if |next_gop_timestamp| follows
247   // |highest_timestamp_in_append_sequence_| within fudge room.
248   bool IsNextGopAdjacentToEndOfCurrentAppendSequence(
249       base::TimeDelta next_gop_timestamp) const;
250
251   // Helper method that returns the timestamp for the next buffer that
252   // |selected_range_| will return from GetNextBuffer() call, or kNoTimestamp
253   // if in between seeking (i.e. |selected_range_| is null).
254   base::TimeDelta GetNextBufferTimestamp();
255
256   // Finds the range that should contain a coded frame group that begins with
257   // |start_timestamp| (presentation time) and returns the iterator pointing to
258   // it. Returns |ranges_.end()| if there's no such existing range.
259   RangeList::iterator FindExistingRangeFor(base::TimeDelta start_timestamp);
260
261   // Inserts |new_range| into |ranges_| preserving sorted order. Returns an
262   // iterator in |ranges_| that points to |new_range|. |new_range| becomes owned
263   // by |ranges_|.
264   RangeList::iterator AddToRanges(std::unique_ptr<SourceBufferRange> new_range);
265
266   // Sets the |selected_range_| to |range| and resets the next buffer position
267   // for the previous |selected_range_|.
268   void SetSelectedRange(SourceBufferRange* range);
269
270   // Seeks |range| to |seek_timestamp| and then calls SetSelectedRange() with
271   // |range|.
272   void SeekAndSetSelectedRange(SourceBufferRange* range,
273                                base::TimeDelta seek_timestamp);
274
275   // Resets this stream back to an unseeked state.
276   void ResetSeekState();
277
278   // Reset state tracking various metadata about the last appended buffer.
279   void ResetLastAppendedState();
280
281   // Returns true if |seek_timestamp| refers to the beginning of the first range
282   // in |ranges_|, false otherwise or if |ranges_| is empty.
283   bool ShouldSeekToStartOfBuffered(base::TimeDelta seek_timestamp) const;
284
285   // Returns true if the decode timestamps of |buffers| are monotonically
286   // increasing (within each GOP) since the previous append to the coded frame
287   // group, false otherwise.
288   bool IsDtsMonotonicallyIncreasing(const BufferQueue& buffers);
289
290   // Returns true if |selected_range_| is the only range in |ranges_| that
291   // HasNextBufferPosition().
292   bool OnlySelectedRangeIsSeeked() const;
293
294   // Measures the distances between buffer decode timestamps and tracks the max.
295   // This enables a reasonable approximation of adjacency fudge room, even for
296   // out-of-order PTS vs DTS sequences. Returns true if
297   // |max_interbuffer_distance_| was changed.
298   bool UpdateMaxInterbufferDtsDistance(const BufferQueue& buffers);
299
300   // Sets the config ID for each buffer to |append_config_index_|.
301   void SetConfigIds(const BufferQueue& buffers);
302
303   // Called to complete a config change. Updates |current_config_index_| to
304   // match the index of the next buffer. Calling this method causes
305   // GetNextBuffer() to stop returning kConfigChange and start returning
306   // kSuccess.
307   void CompleteConfigChange();
308
309   // Sets |selected_range_| and seeks to the nearest keyframe after
310   // |timestamp| if necessary and possible. This method only attempts to
311   // set |selected_range_| if |seleted_range_| is null and |track_buffer_|
312   // is empty.
313   void SetSelectedRangeIfNeeded(const base::TimeDelta timestamp);
314
315   // Find a keyframe timestamp that is >= |start_timestamp| and can be used to
316   // find a new selected range.
317   // Returns kNoTimestamp if an appropriate keyframe timestamp could not be
318   // found.
319   base::TimeDelta FindNewSelectedRangeSeekTimestamp(
320       const base::TimeDelta start_timestamp);
321
322   // Searches |ranges_| for the first keyframe timestamp that is >= |timestamp|.
323   // If |ranges_| doesn't contain a GOP that covers |timestamp| or doesn't
324   // have a keyframe after |timestamp| then kNoTimestamp is returned.
325   base::TimeDelta FindKeyframeAfterTimestamp(const base::TimeDelta timestamp);
326
327   // Returns "VIDEO" for a video SourceBufferStream and "AUDIO" for an audio
328   // stream.
329   std::string GetStreamTypeName() const;
330
331   // (Audio only) If |new_buffers| overlap existing buffers, trims end of
332   // existing buffers to remove overlap. |new_buffers| are not modified.
333   void TrimSpliceOverlap(const BufferQueue& new_buffers);
334
335   // Returns true if end of stream has been reached, i.e. the
336   // following conditions are met:
337   // 1. end of stream is marked and there is nothing in the track_buffer.
338   // 2. We don't have any ranges, or the last or no range is selected,
339   //    or there is a pending seek beyond any existing ranges.
340   bool IsEndOfStreamReached() const;
341
342   // Deletes the range pointed to by |*itr| and removes it from |ranges_|.
343   // If |*itr| points to |selected_range_|, then |selected_range_| is set to
344   // NULL. After the range is removed, |*itr| is to the range after the one that
345   // was removed or to |ranges_.end()| if the last range was removed.
346   void DeleteAndRemoveRange(RangeList::iterator* itr);
347
348   // Helper function used when updating |range_for_next_append_|. Returns a
349   // guess of what the next append timestamp will be based on
350   // |last_appended_buffer_timestamp_|, |new_coded_frame_group_| and
351   // |coded_frame_group_start_pts_|. Returns kNoTimestamp if unable to guess,
352   // which can occur prior to first OnStartOfCodedFrameGroup(), or when the most
353   // recent GOP appended to since the last OnStartOfCodedFrameGroup() is
354   // removed.
355   base::TimeDelta PotentialNextAppendTimestamp() const;
356
357   // Helper function used by Remove() and PrepareRangesForNextAppend() to
358   // remove buffers and ranges between |start| and |end|.
359   // |exclude_start| - If set to true, buffers with timestamps that
360   // match |start| are not removed. If set to false, buffers with
361   // timestamps that match |start| will be removed.
362   // |*deleted_buffers| - Filled with buffers for the current playback position
363   // if the removal range included the current playback position. These buffers
364   // can be used as candidates for placing in the |track_buffer_|.
365   void RemoveInternal(base::TimeDelta start,
366                       base::TimeDelta end,
367                       bool exclude_start,
368                       BufferQueue* deleted_buffers);
369
370   // Helper function used by RemoveInternal() to evaluate whether remove will
371   // disrupt the last appended GOP. If disruption is expected, reset state
372   // tracking the last append. This will trigger frame filtering in Append()
373   // until a new key frame is provided.
374   void UpdateLastAppendStateForRemove(base::TimeDelta remove_start,
375                                       base::TimeDelta remove_end,
376                                       bool exclude_start);
377
378   SourceBufferStreamType GetType() const;
379
380   // See GetNextBuffer() for additional details.  This method handles preroll
381   // frame processing.
382   SourceBufferStreamStatus HandleNextBufferWithPreroll(
383       scoped_refptr<StreamParserBuffer>* out_buffer);
384
385   // See GetNextBuffer() for additional details.  The internal method hands out
386   // single buffers from the |track_buffer_| and |selected_range_| without
387   // additional processing for preroll buffers.
388   SourceBufferStreamStatus GetNextBufferInternal(
389       scoped_refptr<StreamParserBuffer>* out_buffer);
390
391   // If the next buffer's timestamp is significantly beyond the last output
392   // buffer, and if we just exhausted |track_buffer_| on the previous read, this
393   // method logs a warning to |media_log_| that there could be perceivable
394   // delay. Apps can avoid this behavior by not overlap-appending buffers near
395   // current playback position.
396   void WarnIfTrackBufferExhaustionSkipsForward(
397       scoped_refptr<StreamParserBuffer> next_buffer);
398
399   // If |out_buffer| has preroll, sets |pending_buffer_| to feed out preroll and
400   // returns true.  Otherwise returns false.
401   bool SetPendingBuffer(scoped_refptr<StreamParserBuffer>* out_buffer);
402
403   // Used to report log messages that can help the web developer figure out what
404   // is wrong with the content.
405   raw_ptr<MediaLog> media_log_;
406
407   // List of disjoint buffered ranges, ordered by start time.
408   RangeList ranges_;
409
410   // Indicates which decoder config is being used by the decoder.
411   // GetNextBuffer() is only allows to return buffers that have a
412   // config ID that matches this index. If there is a mismatch then
413   // it must signal that a config change is needed.
414   int current_config_index_ = 0;
415
416   // Indicates which decoder config to associate with new buffers
417   // being appended. Each new buffer appended has its config ID set
418   // to the value of this field.
419   int append_config_index_ = 0;
420
421   // Holds the audio/video configs for this stream. |current_config_index_|
422   // and |append_config_index_| represent indexes into one of these vectors.
423   std::vector<AudioDecoderConfig> audio_configs_;
424   std::vector<VideoDecoderConfig> video_configs_;
425
426   // True if more data needs to be appended before the Seek() can complete,
427   // false if no Seek() has been requested or the Seek() is completed.
428   bool seek_pending_ = false;
429
430   // True if the end of the stream has been signalled.
431   bool end_of_stream_ = false;
432
433   // Timestamp of the last request to Seek().
434   base::TimeDelta seek_buffer_timestamp_;
435
436   // Pointer to the seeked-to Range. This is the range from which
437   // GetNextBuffer() calls are fulfilled after the |track_buffer_| has been
438   // emptied.
439   raw_ptr<SourceBufferRange> selected_range_ = nullptr;
440
441   // Queue of the next buffers to be returned from calls to GetNextBuffer(). If
442   // |track_buffer_| is empty, return buffers from |selected_range_|.
443   BufferQueue track_buffer_;
444
445   // If there has been no intervening Seek, this will be true if the last
446   // emitted buffer emptied |track_buffer_|.
447   bool just_exhausted_track_buffer_ = false;
448
449   // The start presentation time of the current coded frame group being
450   // appended.
451   base::TimeDelta coded_frame_group_start_pts_;
452
453   // Points to the range containing the current coded frame group being
454   // appended.
455   RangeList::iterator range_for_next_append_;
456
457   // True when the next call to Append() begins a new coded frame group.
458   // TODO(wolenetz): Simplify by passing this flag into Append().
459   bool new_coded_frame_group_ = false;
460
461   // The timestamp of the last buffer appended to the coded frame group, set to
462   // kNoTimestamp if the beginning of the group.
463   base::TimeDelta last_appended_buffer_timestamp_ = kNoTimestamp;
464   base::TimeDelta last_appended_buffer_duration_ = kNoTimestamp;
465   bool last_appended_buffer_is_keyframe_ = false;
466
467   // When buffering GOPs by keyframe PTS and intra-gop by nonkeyframe DTS, to
468   // verify monotonically increasing intra-GOP DTS sequence and to update max
469   // interbuffer distance also by DTS deltas within a coded frame group, the
470   // following is needed.
471   DecodeTimestamp last_appended_buffer_decode_timestamp_ = kNoDecodeTimestamp;
472
473   // The following is the highest presentation timestamp appended so far in this
474   // coded frame group. Due to potentially out-of-order decode versus
475   // presentation time sequence, this isn't necessarily the most recently
476   // appended frame. This is used as the lower bound of removing previously
477   // buffered media when processing new appends.
478   base::TimeDelta highest_timestamp_in_append_sequence_ = kNoTimestamp;
479
480   // The following is used in determining if FreeBuffersAfterLastAppended() is
481   // allowed during garbage collection. Due to out-of-order decode versus
482   // presentation sequence, this isn't necessarily the end time of the most
483   // recently appended frame.
484   base::TimeDelta highest_buffered_end_time_in_append_sequence_ = kNoTimestamp;
485
486   // The highest presentation timestamp for buffers returned by recent
487   // GetNextBuffer() calls. Set to kNoTimestamp if GetNextBuffer() hasn't been
488   // called yet or a seek has happened since the last GetNextBuffer() call.
489   base::TimeDelta highest_output_buffer_timestamp_;
490
491   // Stores the largest distance between two adjacent buffers in this stream.
492   base::TimeDelta max_interbuffer_distance_;
493
494   base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level_ =
495       base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE;
496
497   // The maximum amount of data in bytes the stream will keep in memory.
498   // |memory_limit_| is initialized based on the audio/video configuration in
499   // the constructor, but either user-setting of |memory_limit_| or
500   // memory-pressure-based adjustment to determine effective limit in the
501   // eviction heuristic can cause the result to vary from the value set in
502   // constructor.
503   size_t memory_limit_;
504
505   // Indicates that a kConfigChanged status has been reported by GetNextBuffer()
506   // and GetCurrentXXXDecoderConfig() must be called to update the current
507   // config. GetNextBuffer() must not be called again until
508   // GetCurrentXXXDecoderConfig() has been called.
509   bool config_change_pending_ = false;
510
511   // Used by HandleNextBufferWithPreroll() when a buffer with preroll is
512   // returned from GetNextBufferInternal().
513   scoped_refptr<StreamParserBuffer> pending_buffer_;
514
515   // Indicates that all buffers before |pending_buffer_| have been handed out.
516   bool pending_buffers_complete_ = false;
517
518   // To prevent log spam, count the number of logs for different log scenarios.
519   int num_splice_logs_ = 0;
520   int num_track_buffer_gap_warning_logs_ = 0;
521   int num_garbage_collect_algorithm_logs_ = 0;
522 };
523
524 }  // namespace media
525
526 #endif  // MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_