1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
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 presentation order.
10 #ifndef MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_
11 #define MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_
19 #include "base/memory/ref_counted.h"
20 #include "media/base/audio_decoder_config.h"
21 #include "media/base/media_export.h"
22 #include "media/base/media_log.h"
23 #include "media/base/ranges.h"
24 #include "media/base/stream_parser_buffer.h"
25 #include "media/base/text_track_config.h"
26 #include "media/base/video_decoder_config.h"
30 class SourceBufferRange
;
32 // See file-level comment for complete description.
33 class MEDIA_EXPORT SourceBufferStream
{
35 typedef std::deque
<scoped_refptr
<StreamParserBuffer
> > BufferQueue
;
37 // Status returned by GetNextBuffer().
38 // kSuccess: Indicates that the next buffer was returned.
39 // kNeedBuffer: Indicates that we need more data before a buffer can be
41 // kConfigChange: Indicates that the next buffer requires a config change.
55 SourceBufferStream(const AudioDecoderConfig
& audio_config
,
57 SourceBufferStream(const VideoDecoderConfig
& video_config
,
59 SourceBufferStream(const TextTrackConfig
& text_config
,
62 ~SourceBufferStream();
64 // Signals that the next buffers appended are part of a new media segment
65 // starting at |media_segment_start_time|.
66 void OnNewMediaSegment(base::TimeDelta media_segment_start_time
);
68 // Add the |buffers| to the SourceBufferStream. Buffers within the queue are
69 // expected to be in order, but multiple calls to Append() may add buffers out
70 // of order or overlapping. Assumes all buffers within |buffers| are in
71 // presentation order and are non-overlapping.
72 // Returns true if Append() was successful, false if |buffers| are not added.
73 // TODO(vrk): Implement garbage collection. (crbug.com/125070)
74 bool Append(const BufferQueue
& buffers
);
76 // Removes buffers between |start| and |end| according to the steps
77 // in the "Coded Frame Removal Algorithm" in the Media Source
79 // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-coded-frame-removal
81 // |duration| is the current duration of the presentation. It is
82 // required by the computation outlined in the spec.
83 void Remove(base::TimeDelta start
, base::TimeDelta end
,
84 base::TimeDelta duration
);
86 // Changes the SourceBufferStream's state so that it will start returning
87 // buffers starting from the closest keyframe before |timestamp|.
88 void Seek(base::TimeDelta timestamp
);
90 // Returns true if the SourceBufferStream has seeked to a time without
91 // buffered data and is waiting for more data to be appended.
92 bool IsSeekPending() const;
94 // Notifies the SourceBufferStream that the media duration has been changed to
95 // |duration| so it should drop any data past that point.
96 void OnSetDuration(base::TimeDelta duration
);
98 // Fills |out_buffer| with a new buffer. Buffers are presented in order from
99 // the last call to Seek(), or starting with the first buffer appended if
100 // Seek() has not been called yet.
101 // |out_buffer|'s timestamp may be earlier than the |timestamp| passed to
102 // the last Seek() call.
103 // Returns kSuccess if |out_buffer| is filled with a valid buffer, kNeedBuffer
104 // if there is not enough data buffered to fulfill the request, and
105 // kConfigChange if the next buffer requires a config change.
106 Status
GetNextBuffer(scoped_refptr
<StreamParserBuffer
>* out_buffer
);
108 // Returns a list of the buffered time ranges.
109 Ranges
<base::TimeDelta
> GetBufferedTime() const;
111 // Returns the duration of the buffered ranges, which is equivalent
112 // to the end timestamp of the last buffered range. If no data is buffered
113 // then base::TimeDelta() is returned.
114 base::TimeDelta
GetBufferedDuration() const;
116 // Notifies this object that end of stream has been signalled.
117 void MarkEndOfStream();
119 // Clear the end of stream state set by MarkEndOfStream().
120 void UnmarkEndOfStream();
122 const AudioDecoderConfig
& GetCurrentAudioDecoderConfig();
123 const VideoDecoderConfig
& GetCurrentVideoDecoderConfig();
124 const TextTrackConfig
& GetCurrentTextTrackConfig();
126 // Notifies this object that the audio config has changed and buffers in
127 // future Append() calls should be associated with this new config.
128 bool UpdateAudioConfig(const AudioDecoderConfig
& config
);
130 // Notifies this object that the video config has changed and buffers in
131 // future Append() calls should be associated with this new config.
132 bool UpdateVideoConfig(const VideoDecoderConfig
& config
);
134 // Returns the largest distance between two adjacent buffers in this stream,
135 // or an estimate if no two adjacent buffers have been appended to the stream
137 base::TimeDelta
GetMaxInterbufferDistance() const;
139 void set_memory_limit_for_testing(int memory_limit
) {
140 memory_limit_
= memory_limit
;
144 friend class SourceBufferStreamTest
;
146 typedef std::list
<SourceBufferRange
*> RangeList
;
148 // Frees up space if the SourceBufferStream is taking up too much memory.
149 void GarbageCollectIfNeeded();
151 // Attempts to delete approximately |total_bytes_to_free| amount of data
152 // |ranges_|, starting at the front of |ranges_| and moving linearly forward
153 // through the buffers. Deletes starting from the back if |reverse_direction|
154 // is true. Returns the number of bytes freed.
155 int FreeBuffers(int total_bytes_to_free
, bool reverse_direction
);
157 // Attempts to delete approximately |total_bytes_to_free| amount of data from
158 // |ranges_|, starting after the last appended buffer before the current
159 // playback position.
160 int FreeBuffersAfterLastAppended(int total_bytes_to_free
);
162 // Gets the removal range to secure |byte_to_free| from
163 // [|start_timestamp|, |end_timestamp|).
164 // Returns the size of buffers to secure if future
165 // Remove(|start_timestamp|, |removal_end_timestamp|, duration) is called.
166 // Will not update |removal_end_timestamp| if the returned size is 0.
167 int GetRemovalRange(base::TimeDelta start_timestamp
,
168 base::TimeDelta end_timestamp
, int byte_to_free
,
169 base::TimeDelta
* removal_end_timestamp
);
171 // Prepares |range_for_next_append_| so |new_buffers| can be appended.
172 // This involves removing buffers between the end of the previous append
173 // and any buffers covered by the time range in |new_buffers|.
174 // |deleted_buffers| is an output parameter containing candidates for
175 // |track_buffer_| if this method ends up removing the current playback
176 // position from the range.
177 void PrepareRangesForNextAppend(const BufferQueue
& new_buffers
,
178 BufferQueue
* deleted_buffers
);
180 // Removes buffers, from the |track_buffer_|, that come after |timestamp|.
181 void PruneTrackBuffer(const base::TimeDelta timestamp
);
183 // Checks to see if |range_with_new_buffers_itr| can be merged with the range
184 // next to it, and merges them if so.
185 void MergeWithAdjacentRangeIfNecessary(
186 const RangeList::iterator
& range_with_new_buffers_itr
);
188 // Returns true if |second_timestamp| is the timestamp of the next buffer in
189 // sequence after |first_timestamp|, false otherwise.
190 bool AreAdjacentInSequence(
191 base::TimeDelta first_timestamp
, base::TimeDelta second_timestamp
) const;
193 // Helper method that returns the timestamp for the next buffer that
194 // |selected_range_| will return from GetNextBuffer() call, or kNoTimestamp()
195 // if in between seeking (i.e. |selected_range_| is null).
196 base::TimeDelta
GetNextBufferTimestamp();
198 // Returns the timestamp of the last buffer in the |selected_range_| or
199 // kNoTimestamp() if |selected_range_| is null.
200 base::TimeDelta
GetEndBufferTimestamp();
202 // Finds the range that should contain a media segment that begins with
203 // |start_timestamp| and returns the iterator pointing to it. Returns
204 // |ranges_.end()| if there's no such existing range.
205 RangeList::iterator
FindExistingRangeFor(base::TimeDelta start_timestamp
);
207 // Inserts |new_range| into |ranges_| preserving sorted order. Returns an
208 // iterator in |ranges_| that points to |new_range|.
209 RangeList::iterator
AddToRanges(SourceBufferRange
* new_range
);
211 // Returns an iterator that points to the place in |ranges_| where
212 // |selected_range_| lives.
213 RangeList::iterator
GetSelectedRangeItr();
215 // Sets the |selected_range_| to |range| and resets the next buffer position
216 // for the previous |selected_range_|.
217 void SetSelectedRange(SourceBufferRange
* range
);
219 // Seeks |range| to |seek_timestamp| and then calls SetSelectedRange() with
221 void SeekAndSetSelectedRange(SourceBufferRange
* range
,
222 base::TimeDelta seek_timestamp
);
224 // Resets this stream back to an unseeked state.
225 void ResetSeekState();
227 // Returns true if |seek_timestamp| refers to the beginning of the first range
228 // in |ranges_|, false otherwise or if |ranges_| is empty.
229 bool ShouldSeekToStartOfBuffered(base::TimeDelta seek_timestamp
) const;
231 // Returns true if the timestamps of |buffers| are monotonically increasing
232 // since the previous append to the media segment, false otherwise.
233 bool IsMonotonicallyIncreasing(const BufferQueue
& buffers
) const;
235 // Returns true if |next_timestamp| and |next_is_keyframe| are valid for
236 // the first buffer after the previous append.
237 bool IsNextTimestampValid(base::TimeDelta next_timestamp
,
238 bool next_is_keyframe
) const;
240 // Returns true if |selected_range_| is the only range in |ranges_| that
241 // HasNextBufferPosition().
242 bool OnlySelectedRangeIsSeeked() const;
244 // Measures the distances between buffer timestamps and tracks the max.
245 void UpdateMaxInterbufferDistance(const BufferQueue
& buffers
);
247 // Sets the config ID for each buffer to |append_config_index_|.
248 void SetConfigIds(const BufferQueue
& buffers
);
250 // Called to complete a config change. Updates |current_config_index_| to
251 // match the index of the next buffer. Calling this method causes
252 // GetNextBuffer() to stop returning kConfigChange and start returning
254 void CompleteConfigChange();
256 // Sets |selected_range_| and seeks to the nearest keyframe after
257 // |timestamp| if necessary and possible. This method only attempts to
258 // set |selected_range_| if |seleted_range_| is null and |track_buffer_|
260 void SetSelectedRangeIfNeeded(const base::TimeDelta timestamp
);
262 // Find a keyframe timestamp that is >= |start_timestamp| and can be used to
263 // find a new selected range.
264 // Returns kNoTimestamp() if an appropriate keyframe timestamp could not be
266 base::TimeDelta
FindNewSelectedRangeSeekTimestamp(
267 const base::TimeDelta start_timestamp
);
269 // Searches |ranges_| for the first keyframe timestamp that is >= |timestamp|.
270 // If |ranges_| doesn't contain a GOP that covers |timestamp| or doesn't
271 // have a keyframe after |timestamp| then kNoTimestamp() is returned.
272 base::TimeDelta
FindKeyframeAfterTimestamp(const base::TimeDelta timestamp
);
274 // Returns "VIDEO" for a video SourceBufferStream, "AUDIO" for an audio
275 // stream, and "TEXT" for a text stream.
276 std::string
GetStreamTypeName() const;
278 // Returns true if we don't have any ranges or the last range is selected
279 // or there is a pending seek beyond any existing ranges.
280 bool IsEndSelected() const;
282 // Deletes the range pointed to by |*itr| and removes it from |ranges_|.
283 // If |*itr| points to |selected_range_|, then |selected_range_| is set to
284 // NULL. After the range is removed, |*itr| is to the range after the one that
285 // was removed or to |ranges_.end()| if the last range was removed.
286 void DeleteAndRemoveRange(RangeList::iterator
* itr
);
288 // Helper function used by Remove() and PrepareRangesForNextAppend() to
289 // remove buffers and ranges between |start| and |end|.
290 // |is_exclusive| - If set to true, buffers with timestamps that
291 // match |start| are not removed. If set to false, buffers with
292 // timestamps that match |start| will be removed.
293 // |*deleted_buffers| - Filled with buffers for the current playback position
294 // if the removal range included the current playback position. These buffers
295 // can be used as candidates for placing in the |track_buffer_|.
297 base::TimeDelta start
, base::TimeDelta end
, bool is_exclusive
,
298 BufferQueue
* deleted_buffers
);
300 Type
GetType() const;
302 // See GetNextBuffer() for additional details. The internal method hands out
303 // buffers from the |track_buffer_| and |selected_range_| without additional
304 // processing for splice frame buffers; which is handled by GetNextBuffer().
305 Status
GetNextBufferInternal(scoped_refptr
<StreamParserBuffer
>* out_buffer
);
307 // Callback used to report error strings that can help the web developer
308 // figure out what is wrong with the content.
311 // List of disjoint buffered ranges, ordered by start time.
314 // Indicates which decoder config is being used by the decoder.
315 // GetNextBuffer() is only allows to return buffers that have a
316 // config ID that matches this index. If there is a mismatch then
317 // it must signal that a config change is needed.
318 int current_config_index_
;
320 // Indicates which decoder config to associate with new buffers
321 // being appended. Each new buffer appended has its config ID set
322 // to the value of this field.
323 int append_config_index_
;
325 // Holds the audio/video configs for this stream. |current_config_index_|
326 // and |append_config_index_| represent indexes into one of these vectors.
327 std::vector
<AudioDecoderConfig
> audio_configs_
;
328 std::vector
<VideoDecoderConfig
> video_configs_
;
330 // Holds the text config for this stream.
331 TextTrackConfig text_track_config_
;
333 // True if more data needs to be appended before the Seek() can complete,
334 // false if no Seek() has been requested or the Seek() is completed.
337 // True if the end of the stream has been signalled.
340 // Timestamp of the last request to Seek().
341 base::TimeDelta seek_buffer_timestamp_
;
343 // Pointer to the seeked-to Range. This is the range from which
344 // GetNextBuffer() calls are fulfilled after the |track_buffer_| has been
346 SourceBufferRange
* selected_range_
;
348 // Queue of the next buffers to be returned from calls to GetNextBuffer(). If
349 // |track_buffer_| is empty, return buffers from |selected_range_|.
350 BufferQueue track_buffer_
;
352 // The start time of the current media segment being appended.
353 base::TimeDelta media_segment_start_time_
;
355 // Points to the range containing the current media segment being appended.
356 RangeList::iterator range_for_next_append_
;
358 // True when the next call to Append() begins a new media segment.
359 bool new_media_segment_
;
361 // The timestamp of the last buffer appended to the media segment, set to
362 // kNoTimestamp() if the beginning of the segment.
363 base::TimeDelta last_appended_buffer_timestamp_
;
364 bool last_appended_buffer_is_keyframe_
;
366 // The decode timestamp on the last buffer returned by the most recent
367 // GetNextBuffer() call. Set to kNoTimestamp() if GetNextBuffer() hasn't been
368 // called yet or a seek has happened since the last GetNextBuffer() call.
369 base::TimeDelta last_output_buffer_timestamp_
;
371 // Stores the largest distance between two adjacent buffers in this stream.
372 base::TimeDelta max_interbuffer_distance_
;
374 // The maximum amount of data in bytes the stream will keep in memory.
377 // Indicates that a kConfigChanged status has been reported by GetNextBuffer()
378 // and GetCurrentXXXDecoderConfig() must be called to update the current
379 // config. GetNextBuffer() must not be called again until
380 // GetCurrentXXXDecoderConfig() has been called.
381 bool config_change_pending_
;
383 // Used by GetNextBuffer() when a buffer with fade out is returned from
384 // GetNextBufferInternal(). Will be set to the returned buffer and will be
385 // consumed after the fade out section has been exhausted.
386 scoped_refptr
<StreamParserBuffer
> fade_in_buffer_
;
388 // Indicates which of the fade out preroll buffers in |fade_in_buffer_| should
389 // be handled out next.
390 size_t fade_out_preroll_index_
;
392 DISALLOW_COPY_AND_ASSIGN(SourceBufferStream
);
397 #endif // MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_