[AndroidWebViewShell] Replace rebaseline script with a new version using test_runner.py
[chromium-blink-merge.git] / media / filters / source_buffer_stream.h
blobb4063602c8745da415735db688457f1a9c6b20a7
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_
13 #include <deque>
14 #include <list>
15 #include <string>
16 #include <utility>
17 #include <vector>
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"
28 namespace media {
30 class SourceBufferRange;
32 // See file-level comment for complete description.
33 class MEDIA_EXPORT SourceBufferStream {
34 public:
35 typedef StreamParser::BufferQueue BufferQueue;
36 typedef std::list<SourceBufferRange*> RangeList;
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 Status {
44 kSuccess,
45 kNeedBuffer,
46 kConfigChange,
47 kEndOfStream
50 enum Type {
51 kAudio,
52 kVideo,
53 kText
56 SourceBufferStream(const AudioDecoderConfig& audio_config,
57 const scoped_refptr<MediaLog>& media_log,
58 bool splice_frames_enabled);
59 SourceBufferStream(const VideoDecoderConfig& video_config,
60 const scoped_refptr<MediaLog>& media_log,
61 bool splice_frames_enabled);
62 SourceBufferStream(const TextTrackConfig& text_config,
63 const scoped_refptr<MediaLog>& media_log,
64 bool splice_frames_enabled);
66 ~SourceBufferStream();
68 // Signals that the next buffers appended are part of a new media segment
69 // starting at |media_segment_start_time|.
70 // TODO(acolwell/wolenetz): This should be changed to a presentation
71 // timestamp. See http://crbug.com/402502
72 void OnNewMediaSegment(DecodeTimestamp media_segment_start_time);
74 // Add the |buffers| to the SourceBufferStream. Buffers within the queue are
75 // expected to be in order, but multiple calls to Append() may add buffers out
76 // of order or overlapping. Assumes all buffers within |buffers| are in
77 // presentation order and are non-overlapping.
78 // Returns true if Append() was successful, false if |buffers| are not added.
79 // TODO(vrk): Implement garbage collection. (crbug.com/125070)
80 bool Append(const BufferQueue& buffers);
82 // Removes buffers between |start| and |end| according to the steps
83 // in the "Coded Frame Removal Algorithm" in the Media Source
84 // Extensions Spec.
85 // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-coded-frame-removal
87 // |duration| is the current duration of the presentation. It is
88 // required by the computation outlined in the spec.
89 void Remove(base::TimeDelta start, base::TimeDelta end,
90 base::TimeDelta duration);
92 // Changes the SourceBufferStream's state so that it will start returning
93 // buffers starting from the closest keyframe before |timestamp|.
94 void Seek(base::TimeDelta timestamp);
96 // Returns true if the SourceBufferStream has seeked to a time without
97 // buffered data and is waiting for more data to be appended.
98 bool IsSeekPending() const;
100 // Notifies the SourceBufferStream that the media duration has been changed to
101 // |duration| so it should drop any data past that point.
102 void OnSetDuration(base::TimeDelta duration);
104 // Fills |out_buffer| with a new buffer. Buffers are presented in order from
105 // the last call to Seek(), or starting with the first buffer appended if
106 // Seek() has not been called yet.
107 // |out_buffer|'s timestamp may be earlier than the |timestamp| passed to
108 // the last Seek() call.
109 // Returns kSuccess if |out_buffer| is filled with a valid buffer, kNeedBuffer
110 // if there is not enough data buffered to fulfill the request, and
111 // kConfigChange if the next buffer requires a config change.
112 Status GetNextBuffer(scoped_refptr<StreamParserBuffer>* out_buffer);
114 // Returns a list of the buffered time ranges.
115 Ranges<base::TimeDelta> GetBufferedTime() const;
117 // Returns the duration of the buffered ranges, which is equivalent
118 // to the end timestamp of the last buffered range. If no data is buffered
119 // then base::TimeDelta() is returned.
120 base::TimeDelta GetBufferedDuration() const;
122 // Notifies this object that end of stream has been signalled.
123 void MarkEndOfStream();
125 // Clear the end of stream state set by MarkEndOfStream().
126 void UnmarkEndOfStream();
128 const AudioDecoderConfig& GetCurrentAudioDecoderConfig();
129 const VideoDecoderConfig& GetCurrentVideoDecoderConfig();
130 const TextTrackConfig& GetCurrentTextTrackConfig();
132 // Notifies this object that the audio config has changed and buffers in
133 // future Append() calls should be associated with this new config.
134 bool UpdateAudioConfig(const AudioDecoderConfig& config);
136 // Notifies this object that the video config has changed and buffers in
137 // future Append() calls should be associated with this new config.
138 bool UpdateVideoConfig(const VideoDecoderConfig& config);
140 // Returns the largest distance between two adjacent buffers in this stream,
141 // or an estimate if no two adjacent buffers have been appended to the stream
142 // yet.
143 base::TimeDelta GetMaxInterbufferDistance() const;
145 void set_memory_limit(int memory_limit) {
146 memory_limit_ = memory_limit;
149 private:
150 friend class SourceBufferStreamTest;
152 // Frees up space if the SourceBufferStream is taking up too much memory.
153 void GarbageCollectIfNeeded();
155 // Attempts to delete approximately |total_bytes_to_free| amount of data
156 // |ranges_|, starting at the front of |ranges_| and moving linearly forward
157 // through the buffers. Deletes starting from the back if |reverse_direction|
158 // is true. Returns the number of bytes freed.
159 int FreeBuffers(int total_bytes_to_free, bool reverse_direction);
161 // Attempts to delete approximately |total_bytes_to_free| amount of data from
162 // |ranges_|, starting after the last appended buffer before the current
163 // playback position.
164 int FreeBuffersAfterLastAppended(int total_bytes_to_free);
166 // Gets the removal range to secure |byte_to_free| from
167 // [|start_timestamp|, |end_timestamp|).
168 // Returns the size of buffers to secure if future
169 // Remove(|start_timestamp|, |removal_end_timestamp|, duration) is called.
170 // Will not update |removal_end_timestamp| if the returned size is 0.
171 int GetRemovalRange(DecodeTimestamp start_timestamp,
172 DecodeTimestamp end_timestamp, int byte_to_free,
173 DecodeTimestamp* removal_end_timestamp);
175 // Prepares |range_for_next_append_| so |new_buffers| can be appended.
176 // This involves removing buffers between the end of the previous append
177 // and any buffers covered by the time range in |new_buffers|.
178 // |deleted_buffers| is an output parameter containing candidates for
179 // |track_buffer_| if this method ends up removing the current playback
180 // position from the range.
181 void PrepareRangesForNextAppend(const BufferQueue& new_buffers,
182 BufferQueue* deleted_buffers);
184 // Removes buffers, from the |track_buffer_|, that come after |timestamp|.
185 void PruneTrackBuffer(const DecodeTimestamp timestamp);
187 // Checks to see if |range_with_new_buffers_itr| can be merged with the range
188 // next to it, and merges them if so.
189 void MergeWithAdjacentRangeIfNecessary(
190 const RangeList::iterator& range_with_new_buffers_itr);
192 // Returns true if |second_timestamp| is the timestamp of the next buffer in
193 // sequence after |first_timestamp|, false otherwise.
194 bool AreAdjacentInSequence(
195 DecodeTimestamp first_timestamp, DecodeTimestamp second_timestamp) const;
197 // Helper method that returns the timestamp for the next buffer that
198 // |selected_range_| will return from GetNextBuffer() call, or kNoTimestamp()
199 // if in between seeking (i.e. |selected_range_| is null).
200 DecodeTimestamp GetNextBufferTimestamp();
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(DecodeTimestamp 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
220 // |range|.
221 void SeekAndSetSelectedRange(SourceBufferRange* range,
222 DecodeTimestamp 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(DecodeTimestamp 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
253 // kSuccess.
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_|
259 // is empty.
260 void SetSelectedRangeIfNeeded(const DecodeTimestamp 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
265 // found.
266 DecodeTimestamp FindNewSelectedRangeSeekTimestamp(
267 const DecodeTimestamp 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 DecodeTimestamp FindKeyframeAfterTimestamp(const DecodeTimestamp 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 end of stream has been reached, i.e. the
279 // following conditions are met:
280 // 1. end of stream is marked and there is nothing in the track_buffer.
281 // 2. We don't have any ranges, or the last or no range is selected,
282 // or there is a pending seek beyond any existing ranges.
283 bool IsEndOfStreamReached() const;
285 // Deletes the range pointed to by |*itr| and removes it from |ranges_|.
286 // If |*itr| points to |selected_range_|, then |selected_range_| is set to
287 // NULL. After the range is removed, |*itr| is to the range after the one that
288 // was removed or to |ranges_.end()| if the last range was removed.
289 void DeleteAndRemoveRange(RangeList::iterator* itr);
291 // Helper function used by Remove() and PrepareRangesForNextAppend() to
292 // remove buffers and ranges between |start| and |end|.
293 // |exclude_start| - If set to true, buffers with timestamps that
294 // match |start| are not removed. If set to false, buffers with
295 // timestamps that match |start| will be removed.
296 // |*deleted_buffers| - Filled with buffers for the current playback position
297 // if the removal range included the current playback position. These buffers
298 // can be used as candidates for placing in the |track_buffer_|.
299 void RemoveInternal(DecodeTimestamp start,
300 DecodeTimestamp end,
301 bool exclude_start,
302 BufferQueue* deleted_buffers);
304 Type GetType() const;
306 // See GetNextBuffer() for additional details. This method handles splice
307 // frame processing.
308 Status HandleNextBufferWithSplice(
309 scoped_refptr<StreamParserBuffer>* out_buffer);
311 // See GetNextBuffer() for additional details. This method handles preroll
312 // frame processing.
313 Status HandleNextBufferWithPreroll(
314 scoped_refptr<StreamParserBuffer>* out_buffer);
316 // See GetNextBuffer() for additional details. The internal method hands out
317 // single buffers from the |track_buffer_| and |selected_range_| without
318 // additional processing for splice frame or preroll buffers.
319 Status GetNextBufferInternal(scoped_refptr<StreamParserBuffer>* out_buffer);
321 // Called by PrepareRangesForNextAppend() before pruning overlapped buffers to
322 // generate a splice frame with a small portion of the overlapped buffers. If
323 // a splice frame is generated, the first buffer in |new_buffers| will have
324 // its timestamps, duration, and fade out preroll updated.
325 void GenerateSpliceFrame(const BufferQueue& new_buffers);
327 // If |out_buffer| has splice buffers or preroll, sets |pending_buffer_|
328 // appropriately and returns true. Otherwise returns false.
329 bool SetPendingBuffer(scoped_refptr<StreamParserBuffer>* out_buffer);
331 // Used to report log messages that can help the web developer figure out what
332 // is wrong with the content.
333 scoped_refptr<MediaLog> media_log_;
335 // List of disjoint buffered ranges, ordered by start time.
336 RangeList ranges_;
338 // Indicates which decoder config is being used by the decoder.
339 // GetNextBuffer() is only allows to return buffers that have a
340 // config ID that matches this index. If there is a mismatch then
341 // it must signal that a config change is needed.
342 int current_config_index_;
344 // Indicates which decoder config to associate with new buffers
345 // being appended. Each new buffer appended has its config ID set
346 // to the value of this field.
347 int append_config_index_;
349 // Holds the audio/video configs for this stream. |current_config_index_|
350 // and |append_config_index_| represent indexes into one of these vectors.
351 std::vector<AudioDecoderConfig> audio_configs_;
352 std::vector<VideoDecoderConfig> video_configs_;
354 // Holds the text config for this stream.
355 TextTrackConfig text_track_config_;
357 // True if more data needs to be appended before the Seek() can complete,
358 // false if no Seek() has been requested or the Seek() is completed.
359 bool seek_pending_;
361 // True if the end of the stream has been signalled.
362 bool end_of_stream_;
364 // Timestamp of the last request to Seek().
365 base::TimeDelta seek_buffer_timestamp_;
367 // Pointer to the seeked-to Range. This is the range from which
368 // GetNextBuffer() calls are fulfilled after the |track_buffer_| has been
369 // emptied.
370 SourceBufferRange* selected_range_;
372 // Queue of the next buffers to be returned from calls to GetNextBuffer(). If
373 // |track_buffer_| is empty, return buffers from |selected_range_|.
374 BufferQueue track_buffer_;
376 // The start time of the current media segment being appended.
377 DecodeTimestamp media_segment_start_time_;
379 // Points to the range containing the current media segment being appended.
380 RangeList::iterator range_for_next_append_;
382 // True when the next call to Append() begins a new media segment.
383 bool new_media_segment_;
385 // The timestamp of the last buffer appended to the media segment, set to
386 // kNoDecodeTimestamp() if the beginning of the segment.
387 DecodeTimestamp last_appended_buffer_timestamp_;
388 bool last_appended_buffer_is_keyframe_;
390 // The decode timestamp on the last buffer returned by the most recent
391 // GetNextBuffer() call. Set to kNoDecodeTimestamp() if GetNextBuffer() hasn't
392 // been called yet or a seek has happened since the last GetNextBuffer() call.
393 DecodeTimestamp last_output_buffer_timestamp_;
395 // Stores the largest distance between two adjacent buffers in this stream.
396 base::TimeDelta max_interbuffer_distance_;
398 // The maximum amount of data in bytes the stream will keep in memory.
399 int memory_limit_;
401 // Indicates that a kConfigChanged status has been reported by GetNextBuffer()
402 // and GetCurrentXXXDecoderConfig() must be called to update the current
403 // config. GetNextBuffer() must not be called again until
404 // GetCurrentXXXDecoderConfig() has been called.
405 bool config_change_pending_;
407 // Used by HandleNextBufferWithSplice() or HandleNextBufferWithPreroll() when
408 // a splice frame buffer or buffer with preroll is returned from
409 // GetNextBufferInternal().
410 scoped_refptr<StreamParserBuffer> pending_buffer_;
412 // Indicates which of the splice buffers in |splice_buffer_| should be
413 // handled out next.
414 size_t splice_buffers_index_;
416 // Indicates that all buffers before |pending_buffer_| have been handed out.
417 bool pending_buffers_complete_;
419 // Indicates that splice frame generation is enabled.
420 const bool splice_frames_enabled_;
422 DISALLOW_COPY_AND_ASSIGN(SourceBufferStream);
425 } // namespace media
427 #endif // MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_