android: add gyp rules for platform android_window
[chromium-blink-merge.git] / media / filters / source_buffer_stream.h
blob31b3f33475e208afd25140b8241b5a8078eb8b7e
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/basictypes.h"
20 #include "base/memory/ref_counted.h"
21 #include "media/base/audio_decoder_config.h"
22 #include "media/base/media_export.h"
23 #include "media/base/media_log.h"
24 #include "media/base/ranges.h"
25 #include "media/base/stream_parser_buffer.h"
26 #include "media/base/text_track_config.h"
27 #include "media/base/video_decoder_config.h"
29 namespace media {
31 class SourceBufferRange;
33 // See file-level comment for complete description.
34 class MEDIA_EXPORT SourceBufferStream {
35 public:
36 typedef StreamParser::BufferQueue BufferQueue;
37 typedef std::list<SourceBufferRange*> RangeList;
39 // Status returned by GetNextBuffer().
40 // kSuccess: Indicates that the next buffer was returned.
41 // kNeedBuffer: Indicates that we need more data before a buffer can be
42 // returned.
43 // kConfigChange: Indicates that the next buffer requires a config change.
44 enum Status {
45 kSuccess,
46 kNeedBuffer,
47 kConfigChange,
48 kEndOfStream
51 enum Type {
52 kAudio,
53 kVideo,
54 kText
57 SourceBufferStream(const AudioDecoderConfig& audio_config,
58 const scoped_refptr<MediaLog>& media_log,
59 bool splice_frames_enabled);
60 SourceBufferStream(const VideoDecoderConfig& video_config,
61 const scoped_refptr<MediaLog>& media_log,
62 bool splice_frames_enabled);
63 SourceBufferStream(const TextTrackConfig& text_config,
64 const scoped_refptr<MediaLog>& media_log,
65 bool splice_frames_enabled);
67 ~SourceBufferStream();
69 // Signals that the next buffers appended are part of a new media segment
70 // starting at |media_segment_start_time|.
71 // TODO(acolwell/wolenetz): This should be changed to a presentation
72 // timestamp. See http://crbug.com/402502
73 void OnNewMediaSegment(DecodeTimestamp media_segment_start_time);
75 // Add the |buffers| to the SourceBufferStream. Buffers within the queue are
76 // expected to be in order, but multiple calls to Append() may add buffers out
77 // of order or overlapping. Assumes all buffers within |buffers| are in
78 // presentation order and are non-overlapping.
79 // Returns true if Append() was successful, false if |buffers| are not added.
80 // TODO(vrk): Implement garbage collection. (crbug.com/125070)
81 bool Append(const BufferQueue& buffers);
83 // Removes buffers between |start| and |end| according to the steps
84 // in the "Coded Frame Removal Algorithm" in the Media Source
85 // Extensions Spec.
86 // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-coded-frame-removal
88 // |duration| is the current duration of the presentation. It is
89 // required by the computation outlined in the spec.
90 void Remove(base::TimeDelta start, base::TimeDelta end,
91 base::TimeDelta duration);
93 // Changes the SourceBufferStream's state so that it will start returning
94 // buffers starting from the closest keyframe before |timestamp|.
95 void Seek(base::TimeDelta timestamp);
97 // Returns true if the SourceBufferStream has seeked to a time without
98 // buffered data and is waiting for more data to be appended.
99 bool IsSeekPending() const;
101 // Notifies the SourceBufferStream that the media duration has been changed to
102 // |duration| so it should drop any data past that point.
103 void OnSetDuration(base::TimeDelta duration);
105 // Fills |out_buffer| with a new buffer. Buffers are presented in order from
106 // the last call to Seek(), or starting with the first buffer appended if
107 // Seek() has not been called yet.
108 // |out_buffer|'s timestamp may be earlier than the |timestamp| passed to
109 // the last Seek() call.
110 // Returns kSuccess if |out_buffer| is filled with a valid buffer, kNeedBuffer
111 // if there is not enough data buffered to fulfill the request, and
112 // kConfigChange if the next buffer requires a config change.
113 Status GetNextBuffer(scoped_refptr<StreamParserBuffer>* out_buffer);
115 // Returns a list of the buffered time ranges.
116 Ranges<base::TimeDelta> GetBufferedTime() const;
118 // Returns the duration of the buffered ranges, which is equivalent
119 // to the end timestamp of the last buffered range. If no data is buffered
120 // then base::TimeDelta() is returned.
121 base::TimeDelta GetBufferedDuration() const;
123 // Notifies this object that end of stream has been signalled.
124 void MarkEndOfStream();
126 // Clear the end of stream state set by MarkEndOfStream().
127 void UnmarkEndOfStream();
129 const AudioDecoderConfig& GetCurrentAudioDecoderConfig();
130 const VideoDecoderConfig& GetCurrentVideoDecoderConfig();
131 const TextTrackConfig& GetCurrentTextTrackConfig();
133 // Notifies this object that the audio config has changed and buffers in
134 // future Append() calls should be associated with this new config.
135 bool UpdateAudioConfig(const AudioDecoderConfig& config);
137 // Notifies this object that the video config has changed and buffers in
138 // future Append() calls should be associated with this new config.
139 bool UpdateVideoConfig(const VideoDecoderConfig& config);
141 // Returns the largest distance between two adjacent buffers in this stream,
142 // or an estimate if no two adjacent buffers have been appended to the stream
143 // yet.
144 base::TimeDelta GetMaxInterbufferDistance() const;
146 void set_memory_limit(size_t memory_limit) {
147 memory_limit_ = memory_limit;
150 private:
151 friend class SourceBufferStreamTest;
153 // Frees up space if the SourceBufferStream is taking up too much memory.
154 void GarbageCollectIfNeeded();
156 // Attempts to delete approximately |total_bytes_to_free| amount of data
157 // |ranges_|, starting at the front of |ranges_| and moving linearly forward
158 // through the buffers. Deletes starting from the back if |reverse_direction|
159 // is true. Returns the number of bytes freed.
160 size_t FreeBuffers(size_t total_bytes_to_free, bool reverse_direction);
162 // Attempts to delete approximately |total_bytes_to_free| amount of data from
163 // |ranges_|, starting after the last appended buffer before the current
164 // playback position.
165 size_t FreeBuffersAfterLastAppended(size_t total_bytes_to_free);
167 // Gets the removal range to secure |byte_to_free| from
168 // [|start_timestamp|, |end_timestamp|).
169 // Returns the size of buffers to secure if future
170 // Remove(|start_timestamp|, |removal_end_timestamp|, duration) is called.
171 // Will not update |removal_end_timestamp| if the returned size is 0.
172 size_t GetRemovalRange(DecodeTimestamp start_timestamp,
173 DecodeTimestamp end_timestamp, size_t byte_to_free,
174 DecodeTimestamp* removal_end_timestamp);
176 // Prepares |range_for_next_append_| so |new_buffers| can be appended.
177 // This involves removing buffers between the end of the previous append
178 // and any buffers covered by the time range in |new_buffers|.
179 // |deleted_buffers| is an output parameter containing candidates for
180 // |track_buffer_| if this method ends up removing the current playback
181 // position from the range.
182 void PrepareRangesForNextAppend(const BufferQueue& new_buffers,
183 BufferQueue* deleted_buffers);
185 // Removes buffers, from the |track_buffer_|, that come after |timestamp|.
186 void PruneTrackBuffer(const DecodeTimestamp timestamp);
188 // Checks to see if |range_with_new_buffers_itr| can be merged with the range
189 // next to it, and merges them if so.
190 void MergeWithAdjacentRangeIfNecessary(
191 const RangeList::iterator& range_with_new_buffers_itr);
193 // Returns true if |second_timestamp| is the timestamp of the next buffer in
194 // sequence after |first_timestamp|, false otherwise.
195 bool AreAdjacentInSequence(
196 DecodeTimestamp first_timestamp, DecodeTimestamp second_timestamp) const;
198 // Helper method that returns the timestamp for the next buffer that
199 // |selected_range_| will return from GetNextBuffer() call, or kNoTimestamp()
200 // if in between seeking (i.e. |selected_range_| is null).
201 DecodeTimestamp GetNextBufferTimestamp();
203 // Finds the range that should contain a media segment that begins with
204 // |start_timestamp| and returns the iterator pointing to it. Returns
205 // |ranges_.end()| if there's no such existing range.
206 RangeList::iterator FindExistingRangeFor(DecodeTimestamp start_timestamp);
208 // Inserts |new_range| into |ranges_| preserving sorted order. Returns an
209 // iterator in |ranges_| that points to |new_range|.
210 RangeList::iterator AddToRanges(SourceBufferRange* new_range);
212 // Returns an iterator that points to the place in |ranges_| where
213 // |selected_range_| lives.
214 RangeList::iterator GetSelectedRangeItr();
216 // Sets the |selected_range_| to |range| and resets the next buffer position
217 // for the previous |selected_range_|.
218 void SetSelectedRange(SourceBufferRange* range);
220 // Seeks |range| to |seek_timestamp| and then calls SetSelectedRange() with
221 // |range|.
222 void SeekAndSetSelectedRange(SourceBufferRange* range,
223 DecodeTimestamp seek_timestamp);
225 // Resets this stream back to an unseeked state.
226 void ResetSeekState();
228 // Returns true if |seek_timestamp| refers to the beginning of the first range
229 // in |ranges_|, false otherwise or if |ranges_| is empty.
230 bool ShouldSeekToStartOfBuffered(base::TimeDelta seek_timestamp) const;
232 // Returns true if the timestamps of |buffers| are monotonically increasing
233 // since the previous append to the media segment, false otherwise.
234 bool IsMonotonicallyIncreasing(const BufferQueue& buffers) const;
236 // Returns true if |next_timestamp| and |next_is_keyframe| are valid for
237 // the first buffer after the previous append.
238 bool IsNextTimestampValid(DecodeTimestamp next_timestamp,
239 bool next_is_keyframe) const;
241 // Returns true if |selected_range_| is the only range in |ranges_| that
242 // HasNextBufferPosition().
243 bool OnlySelectedRangeIsSeeked() const;
245 // Measures the distances between buffer timestamps and tracks the max.
246 void UpdateMaxInterbufferDistance(const BufferQueue& buffers);
248 // Sets the config ID for each buffer to |append_config_index_|.
249 void SetConfigIds(const BufferQueue& buffers);
251 // Called to complete a config change. Updates |current_config_index_| to
252 // match the index of the next buffer. Calling this method causes
253 // GetNextBuffer() to stop returning kConfigChange and start returning
254 // kSuccess.
255 void CompleteConfigChange();
257 // Sets |selected_range_| and seeks to the nearest keyframe after
258 // |timestamp| if necessary and possible. This method only attempts to
259 // set |selected_range_| if |seleted_range_| is null and |track_buffer_|
260 // is empty.
261 void SetSelectedRangeIfNeeded(const DecodeTimestamp timestamp);
263 // Find a keyframe timestamp that is >= |start_timestamp| and can be used to
264 // find a new selected range.
265 // Returns kNoTimestamp() if an appropriate keyframe timestamp could not be
266 // found.
267 DecodeTimestamp FindNewSelectedRangeSeekTimestamp(
268 const DecodeTimestamp start_timestamp);
270 // Searches |ranges_| for the first keyframe timestamp that is >= |timestamp|.
271 // If |ranges_| doesn't contain a GOP that covers |timestamp| or doesn't
272 // have a keyframe after |timestamp| then kNoTimestamp() is returned.
273 DecodeTimestamp FindKeyframeAfterTimestamp(const DecodeTimestamp timestamp);
275 // Returns "VIDEO" for a video SourceBufferStream, "AUDIO" for an audio
276 // stream, and "TEXT" for a text stream.
277 std::string GetStreamTypeName() const;
279 // Returns true if end of stream has been reached, i.e. the
280 // following conditions are met:
281 // 1. end of stream is marked and there is nothing in the track_buffer.
282 // 2. We don't have any ranges, or the last or no range is selected,
283 // or there is a pending seek beyond any existing ranges.
284 bool IsEndOfStreamReached() const;
286 // Deletes the range pointed to by |*itr| and removes it from |ranges_|.
287 // If |*itr| points to |selected_range_|, then |selected_range_| is set to
288 // NULL. After the range is removed, |*itr| is to the range after the one that
289 // was removed or to |ranges_.end()| if the last range was removed.
290 void DeleteAndRemoveRange(RangeList::iterator* itr);
292 // Helper function used by Remove() and PrepareRangesForNextAppend() to
293 // remove buffers and ranges between |start| and |end|.
294 // |exclude_start| - If set to true, buffers with timestamps that
295 // match |start| are not removed. If set to false, buffers with
296 // timestamps that match |start| will be removed.
297 // |*deleted_buffers| - Filled with buffers for the current playback position
298 // if the removal range included the current playback position. These buffers
299 // can be used as candidates for placing in the |track_buffer_|.
300 void RemoveInternal(DecodeTimestamp start,
301 DecodeTimestamp end,
302 bool exclude_start,
303 BufferQueue* deleted_buffers);
305 Type GetType() const;
307 // See GetNextBuffer() for additional details. This method handles splice
308 // frame processing.
309 Status HandleNextBufferWithSplice(
310 scoped_refptr<StreamParserBuffer>* out_buffer);
312 // See GetNextBuffer() for additional details. This method handles preroll
313 // frame processing.
314 Status HandleNextBufferWithPreroll(
315 scoped_refptr<StreamParserBuffer>* out_buffer);
317 // See GetNextBuffer() for additional details. The internal method hands out
318 // single buffers from the |track_buffer_| and |selected_range_| without
319 // additional processing for splice frame or preroll buffers.
320 Status GetNextBufferInternal(scoped_refptr<StreamParserBuffer>* out_buffer);
322 // If the next buffer's timestamp is significantly beyond the last output
323 // buffer, and if we just exhausted |track_buffer_| on the previous read, this
324 // method logs a warning to |media_log_| that there could be perceivable
325 // delay. Apps can avoid this behavior by not overlap-appending buffers near
326 // current playback position.
327 void WarnIfTrackBufferExhaustionSkipsForward(
328 const scoped_refptr<StreamParserBuffer>& next_buffer);
330 // Called by PrepareRangesForNextAppend() before pruning overlapped buffers to
331 // generate a splice frame with a small portion of the overlapped buffers. If
332 // a splice frame is generated, the first buffer in |new_buffers| will have
333 // its timestamps, duration, and fade out preroll updated.
334 void GenerateSpliceFrame(const BufferQueue& new_buffers);
336 // If |out_buffer| has splice buffers or preroll, sets |pending_buffer_|
337 // appropriately and returns true. Otherwise returns false.
338 bool SetPendingBuffer(scoped_refptr<StreamParserBuffer>* out_buffer);
340 // Used to report log messages that can help the web developer figure out what
341 // is wrong with the content.
342 scoped_refptr<MediaLog> media_log_;
344 // List of disjoint buffered ranges, ordered by start time.
345 RangeList ranges_;
347 // Indicates which decoder config is being used by the decoder.
348 // GetNextBuffer() is only allows to return buffers that have a
349 // config ID that matches this index. If there is a mismatch then
350 // it must signal that a config change is needed.
351 int current_config_index_ = 0;
353 // Indicates which decoder config to associate with new buffers
354 // being appended. Each new buffer appended has its config ID set
355 // to the value of this field.
356 int append_config_index_ = 0;
358 // Holds the audio/video configs for this stream. |current_config_index_|
359 // and |append_config_index_| represent indexes into one of these vectors.
360 std::vector<AudioDecoderConfig> audio_configs_;
361 std::vector<VideoDecoderConfig> video_configs_;
363 // Holds the text config for this stream.
364 TextTrackConfig text_track_config_;
366 // True if more data needs to be appended before the Seek() can complete,
367 // false if no Seek() has been requested or the Seek() is completed.
368 bool seek_pending_ = false;
370 // True if the end of the stream has been signalled.
371 bool end_of_stream_ = false;
373 // Timestamp of the last request to Seek().
374 base::TimeDelta seek_buffer_timestamp_;
376 // Pointer to the seeked-to Range. This is the range from which
377 // GetNextBuffer() calls are fulfilled after the |track_buffer_| has been
378 // emptied.
379 SourceBufferRange* selected_range_ = nullptr;
381 // Queue of the next buffers to be returned from calls to GetNextBuffer(). If
382 // |track_buffer_| is empty, return buffers from |selected_range_|.
383 BufferQueue track_buffer_;
385 // If there has been no intervening Seek, this will be true if the last
386 // emitted buffer emptied |track_buffer_|.
387 bool just_exhausted_track_buffer_ = false;
389 // The start time of the current media segment being appended.
390 DecodeTimestamp media_segment_start_time_;
392 // Points to the range containing the current media segment being appended.
393 RangeList::iterator range_for_next_append_;
395 // True when the next call to Append() begins a new media segment.
396 bool new_media_segment_ = false;
398 // The timestamp of the last buffer appended to the media segment, set to
399 // kNoDecodeTimestamp() if the beginning of the segment.
400 DecodeTimestamp last_appended_buffer_timestamp_;
401 bool last_appended_buffer_is_keyframe_ = false;
403 // The decode timestamp on the last buffer returned by the most recent
404 // GetNextBuffer() call. Set to kNoDecodeTimestamp() if GetNextBuffer() hasn't
405 // been called yet or a seek has happened since the last GetNextBuffer() call.
406 DecodeTimestamp last_output_buffer_timestamp_;
408 // Stores the largest distance between two adjacent buffers in this stream.
409 base::TimeDelta max_interbuffer_distance_;
411 // The maximum amount of data in bytes the stream will keep in memory.
412 size_t memory_limit_;
414 // Indicates that a kConfigChanged status has been reported by GetNextBuffer()
415 // and GetCurrentXXXDecoderConfig() must be called to update the current
416 // config. GetNextBuffer() must not be called again until
417 // GetCurrentXXXDecoderConfig() has been called.
418 bool config_change_pending_ = false;
420 // Used by HandleNextBufferWithSplice() or HandleNextBufferWithPreroll() when
421 // a splice frame buffer or buffer with preroll is returned from
422 // GetNextBufferInternal().
423 scoped_refptr<StreamParserBuffer> pending_buffer_;
425 // Indicates which of the splice buffers in |splice_buffer_| should be
426 // handled out next.
427 size_t splice_buffers_index_ = 0;
429 // Indicates that all buffers before |pending_buffer_| have been handed out.
430 bool pending_buffers_complete_ = false;
432 // Indicates that splice frame generation is enabled.
433 const bool splice_frames_enabled_;
435 // To prevent log spam, count the number of warnings and successes logged.
436 int num_splice_generation_warning_logs_ = 0;
437 int num_splice_generation_success_logs_ = 0;
438 int num_track_buffer_gap_warning_logs_ = 0;
440 DISALLOW_COPY_AND_ASSIGN(SourceBufferStream);
443 } // namespace media
445 #endif // MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_