Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / media / filters / source_buffer_stream.h
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.
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 presentation order.
9
10 #ifndef MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_
11 #define MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_
12
13 #include <deque>
14 #include <list>
15 #include <string>
16 #include <utility>
17 #include <vector>
18
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"
27
28 namespace media {
29
30 class SourceBufferRange;
31
32 // See file-level comment for complete description.
33 class MEDIA_EXPORT SourceBufferStream {
34  public:
35   typedef std::deque<scoped_refptr<StreamParserBuffer> > BufferQueue;
36
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
40   //              returned.
41   // kConfigChange: Indicates that the next buffer requires a config change.
42   enum Status {
43     kSuccess,
44     kNeedBuffer,
45     kConfigChange,
46     kEndOfStream
47   };
48
49   enum Type {
50     kAudio,
51     kVideo,
52     kText
53   };
54
55   SourceBufferStream(const AudioDecoderConfig& audio_config,
56                      const LogCB& log_cb);
57   SourceBufferStream(const VideoDecoderConfig& video_config,
58                      const LogCB& log_cb);
59   SourceBufferStream(const TextTrackConfig& text_config,
60                      const LogCB& log_cb);
61
62   ~SourceBufferStream();
63
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);
67
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);
75
76   // Removes buffers between |start| and |end| according to the steps
77   // in the "Coded Frame Removal Algorithm" in the Media Source
78   // Extensions Spec.
79   // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-coded-frame-removal
80   //
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);
85
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);
89
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;
93
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);
97
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);
107
108   // Returns a list of the buffered time ranges.
109   Ranges<base::TimeDelta> GetBufferedTime() const;
110
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;
115
116   // Notifies this object that end of stream has been signalled.
117   void MarkEndOfStream();
118
119   // Clear the end of stream state set by MarkEndOfStream().
120   void UnmarkEndOfStream();
121
122   const AudioDecoderConfig& GetCurrentAudioDecoderConfig();
123   const VideoDecoderConfig& GetCurrentVideoDecoderConfig();
124   const TextTrackConfig& GetCurrentTextTrackConfig();
125
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);
129
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);
133
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
136   // yet.
137   base::TimeDelta GetMaxInterbufferDistance() const;
138
139   void set_memory_limit_for_testing(int memory_limit) {
140     memory_limit_ = memory_limit;
141   }
142
143  private:
144   friend class SourceBufferStreamTest;
145
146   typedef std::list<SourceBufferRange*> RangeList;
147
148   // Frees up space if the SourceBufferStream is taking up too much memory.
149   void GarbageCollectIfNeeded();
150
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);
156
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);
161
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);
170
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);
179
180   // Removes buffers, from the |track_buffer_|, that come after |timestamp|.
181   void PruneTrackBuffer(const base::TimeDelta timestamp);
182
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);
187
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;
192
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();
197
198   // Returns the timestamp of the last buffer in the |selected_range_| or
199   // kNoTimestamp() if |selected_range_| is null.
200   base::TimeDelta GetEndBufferTimestamp();
201
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);
206
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);
210
211   // Returns an iterator that points to the place in |ranges_| where
212   // |selected_range_| lives.
213   RangeList::iterator GetSelectedRangeItr();
214
215   // Sets the |selected_range_| to |range| and resets the next buffer position
216   // for the previous |selected_range_|.
217   void SetSelectedRange(SourceBufferRange* range);
218
219   // Seeks |range| to |seek_timestamp| and then calls SetSelectedRange() with
220   // |range|.
221   void SeekAndSetSelectedRange(SourceBufferRange* range,
222                                base::TimeDelta seek_timestamp);
223
224   // Resets this stream back to an unseeked state.
225   void ResetSeekState();
226
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;
230
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;
234
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;
239
240   // Returns true if |selected_range_| is the only range in |ranges_| that
241   // HasNextBufferPosition().
242   bool OnlySelectedRangeIsSeeked() const;
243
244   // Measures the distances between buffer timestamps and tracks the max.
245   void UpdateMaxInterbufferDistance(const BufferQueue& buffers);
246
247   // Sets the config ID for each buffer to |append_config_index_|.
248   void SetConfigIds(const BufferQueue& buffers);
249
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();
255
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 base::TimeDelta timestamp);
261
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   base::TimeDelta FindNewSelectedRangeSeekTimestamp(
267       const base::TimeDelta start_timestamp);
268
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);
273
274   // Returns "VIDEO" for a video SourceBufferStream, "AUDIO" for an audio
275   // stream, and "TEXT" for a text stream.
276   std::string GetStreamTypeName() const;
277
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;
281
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);
287
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_|.
296   void RemoveInternal(
297       base::TimeDelta start, base::TimeDelta end, bool is_exclusive,
298       BufferQueue* deleted_buffers);
299
300   Type GetType() const;
301
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);
306
307   // Callback used to report error strings that can help the web developer
308   // figure out what is wrong with the content.
309   LogCB log_cb_;
310
311   // List of disjoint buffered ranges, ordered by start time.
312   RangeList ranges_;
313
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_;
319
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_;
324
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_;
329
330   // Holds the text config for this stream.
331   TextTrackConfig text_track_config_;
332
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.
335   bool seek_pending_;
336
337   // True if the end of the stream has been signalled.
338   bool end_of_stream_;
339
340   // Timestamp of the last request to Seek().
341   base::TimeDelta seek_buffer_timestamp_;
342
343   // Pointer to the seeked-to Range. This is the range from which
344   // GetNextBuffer() calls are fulfilled after the |track_buffer_| has been
345   // emptied.
346   SourceBufferRange* selected_range_;
347
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_;
351
352   // The start time of the current media segment being appended.
353   base::TimeDelta media_segment_start_time_;
354
355   // Points to the range containing the current media segment being appended.
356   RangeList::iterator range_for_next_append_;
357
358   // True when the next call to Append() begins a new media segment.
359   bool new_media_segment_;
360
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_;
365
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_;
370
371   // Stores the largest distance between two adjacent buffers in this stream.
372   base::TimeDelta max_interbuffer_distance_;
373
374   // The maximum amount of data in bytes the stream will keep in memory.
375   int memory_limit_;
376
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_;
382
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_;
387
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_;
391
392   DISALLOW_COPY_AND_ASSIGN(SourceBufferStream);
393 };
394
395 }  // namespace media
396
397 #endif  // MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_