b5bb855c1fa12d442d499b452d470506fb2979a5
[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 StreamParser::BufferQueue 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                      bool splice_frames_enabled);
58   SourceBufferStream(const VideoDecoderConfig& video_config,
59                      const LogCB& log_cb,
60                      bool splice_frames_enabled);
61   SourceBufferStream(const TextTrackConfig& text_config,
62                      const LogCB& log_cb,
63                      bool splice_frames_enabled);
64
65   ~SourceBufferStream();
66
67   // Signals that the next buffers appended are part of a new media segment
68   // starting at |media_segment_start_time|.
69   // TODO(acolwell/wolenetz): This should be changed to a presentation
70   // timestamp. See http://crbug.com/402502
71   void OnNewMediaSegment(DecodeTimestamp media_segment_start_time);
72
73   // Add the |buffers| to the SourceBufferStream. Buffers within the queue are
74   // expected to be in order, but multiple calls to Append() may add buffers out
75   // of order or overlapping. Assumes all buffers within |buffers| are in
76   // presentation order and are non-overlapping.
77   // Returns true if Append() was successful, false if |buffers| are not added.
78   // TODO(vrk): Implement garbage collection. (crbug.com/125070)
79   bool Append(const BufferQueue& buffers);
80
81   // Removes buffers between |start| and |end| according to the steps
82   // in the "Coded Frame Removal Algorithm" in the Media Source
83   // Extensions Spec.
84   // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-coded-frame-removal
85   //
86   // |duration| is the current duration of the presentation. It is
87   // required by the computation outlined in the spec.
88   void Remove(base::TimeDelta start, base::TimeDelta end,
89               base::TimeDelta duration);
90
91   // Changes the SourceBufferStream's state so that it will start returning
92   // buffers starting from the closest keyframe before |timestamp|.
93   void Seek(base::TimeDelta timestamp);
94
95   // Returns true if the SourceBufferStream has seeked to a time without
96   // buffered data and is waiting for more data to be appended.
97   bool IsSeekPending() const;
98
99   // Notifies the SourceBufferStream that the media duration has been changed to
100   // |duration| so it should drop any data past that point.
101   void OnSetDuration(base::TimeDelta duration);
102
103   // Fills |out_buffer| with a new buffer. Buffers are presented in order from
104   // the last call to Seek(), or starting with the first buffer appended if
105   // Seek() has not been called yet.
106   // |out_buffer|'s timestamp may be earlier than the |timestamp| passed to
107   // the last Seek() call.
108   // Returns kSuccess if |out_buffer| is filled with a valid buffer, kNeedBuffer
109   // if there is not enough data buffered to fulfill the request, and
110   // kConfigChange if the next buffer requires a config change.
111   Status GetNextBuffer(scoped_refptr<StreamParserBuffer>* out_buffer);
112
113   // Returns a list of the buffered time ranges.
114   Ranges<base::TimeDelta> GetBufferedTime() const;
115
116   // Returns the duration of the buffered ranges, which is equivalent
117   // to the end timestamp of the last buffered range. If no data is buffered
118   // then base::TimeDelta() is returned.
119   base::TimeDelta GetBufferedDuration() const;
120
121   // Notifies this object that end of stream has been signalled.
122   void MarkEndOfStream();
123
124   // Clear the end of stream state set by MarkEndOfStream().
125   void UnmarkEndOfStream();
126
127   const AudioDecoderConfig& GetCurrentAudioDecoderConfig();
128   const VideoDecoderConfig& GetCurrentVideoDecoderConfig();
129   const TextTrackConfig& GetCurrentTextTrackConfig();
130
131   // Notifies this object that the audio config has changed and buffers in
132   // future Append() calls should be associated with this new config.
133   bool UpdateAudioConfig(const AudioDecoderConfig& config);
134
135   // Notifies this object that the video config has changed and buffers in
136   // future Append() calls should be associated with this new config.
137   bool UpdateVideoConfig(const VideoDecoderConfig& config);
138
139   // Returns the largest distance between two adjacent buffers in this stream,
140   // or an estimate if no two adjacent buffers have been appended to the stream
141   // yet.
142   base::TimeDelta GetMaxInterbufferDistance() const;
143
144   void set_memory_limit(int memory_limit) {
145     memory_limit_ = memory_limit;
146   }
147
148  private:
149   friend class SourceBufferStreamTest;
150
151   typedef std::list<SourceBufferRange*> RangeList;
152
153   // Frees up space if the SourceBufferStream is taking up too much memory.
154   void GarbageCollectIfNeeded();
155
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   int FreeBuffers(int total_bytes_to_free, bool reverse_direction);
161
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   int FreeBuffersAfterLastAppended(int total_bytes_to_free);
166
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   int GetRemovalRange(DecodeTimestamp start_timestamp,
173       DecodeTimestamp end_timestamp, int byte_to_free,
174       DecodeTimestamp* removal_end_timestamp);
175
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);
184
185   // Removes buffers, from the |track_buffer_|, that come after |timestamp|.
186   void PruneTrackBuffer(const DecodeTimestamp timestamp);
187
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);
192
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;
197
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();
202
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);
207
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);
211
212   // Returns an iterator that points to the place in |ranges_| where
213   // |selected_range_| lives.
214   RangeList::iterator GetSelectedRangeItr();
215
216   // Sets the |selected_range_| to |range| and resets the next buffer position
217   // for the previous |selected_range_|.
218   void SetSelectedRange(SourceBufferRange* range);
219
220   // Seeks |range| to |seek_timestamp| and then calls SetSelectedRange() with
221   // |range|.
222   void SeekAndSetSelectedRange(SourceBufferRange* range,
223                                DecodeTimestamp seek_timestamp);
224
225   // Resets this stream back to an unseeked state.
226   void ResetSeekState();
227
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;
231
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;
235
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;
240
241   // Returns true if |selected_range_| is the only range in |ranges_| that
242   // HasNextBufferPosition().
243   bool OnlySelectedRangeIsSeeked() const;
244
245   // Measures the distances between buffer timestamps and tracks the max.
246   void UpdateMaxInterbufferDistance(const BufferQueue& buffers);
247
248   // Sets the config ID for each buffer to |append_config_index_|.
249   void SetConfigIds(const BufferQueue& buffers);
250
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();
256
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);
262
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);
269
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);
274
275   // Returns "VIDEO" for a video SourceBufferStream, "AUDIO" for an audio
276   // stream, and "TEXT" for a text stream.
277   std::string GetStreamTypeName() const;
278
279   // Returns true if we don't have any ranges or the last range is selected
280   // or there is a pending seek beyond any existing ranges.
281   bool IsEndSelected() const;
282
283   // Deletes the range pointed to by |*itr| and removes it from |ranges_|.
284   // If |*itr| points to |selected_range_|, then |selected_range_| is set to
285   // NULL. After the range is removed, |*itr| is to the range after the one that
286   // was removed or to |ranges_.end()| if the last range was removed.
287   void DeleteAndRemoveRange(RangeList::iterator* itr);
288
289   // Helper function used by Remove() and PrepareRangesForNextAppend() to
290   // remove buffers and ranges between |start| and |end|.
291   // |is_exclusive| - If set to true, buffers with timestamps that
292   // match |start| are not removed. If set to false, buffers with
293   // timestamps that match |start| will be removed.
294   // |*deleted_buffers| - Filled with buffers for the current playback position
295   // if the removal range included the current playback position. These buffers
296   // can be used as candidates for placing in the |track_buffer_|.
297   void RemoveInternal(
298       DecodeTimestamp start, DecodeTimestamp end, bool is_exclusive,
299       BufferQueue* deleted_buffers);
300
301   Type GetType() const;
302
303   // See GetNextBuffer() for additional details.  This method handles splice
304   // frame processing.
305   Status HandleNextBufferWithSplice(
306       scoped_refptr<StreamParserBuffer>* out_buffer);
307
308   // See GetNextBuffer() for additional details.  This method handles preroll
309   // frame processing.
310   Status HandleNextBufferWithPreroll(
311       scoped_refptr<StreamParserBuffer>* out_buffer);
312
313   // See GetNextBuffer() for additional details.  The internal method hands out
314   // single buffers from the |track_buffer_| and |selected_range_| without
315   // additional processing for splice frame or preroll buffers.
316   Status GetNextBufferInternal(scoped_refptr<StreamParserBuffer>* out_buffer);
317
318   // Called by PrepareRangesForNextAppend() before pruning overlapped buffers to
319   // generate a splice frame with a small portion of the overlapped buffers.  If
320   // a splice frame is generated, the first buffer in |new_buffers| will have
321   // its timestamps, duration, and fade out preroll updated.
322   void GenerateSpliceFrame(const BufferQueue& new_buffers);
323
324   // If |out_buffer| has splice buffers or preroll, sets |pending_buffer_|
325   // appropriately and returns true.  Otherwise returns false.
326   bool SetPendingBuffer(scoped_refptr<StreamParserBuffer>* out_buffer);
327
328   // Callback used to report error strings that can help the web developer
329   // figure out what is wrong with the content.
330   LogCB log_cb_;
331
332   // List of disjoint buffered ranges, ordered by start time.
333   RangeList ranges_;
334
335   // Indicates which decoder config is being used by the decoder.
336   // GetNextBuffer() is only allows to return buffers that have a
337   // config ID that matches this index. If there is a mismatch then
338   // it must signal that a config change is needed.
339   int current_config_index_;
340
341   // Indicates which decoder config to associate with new buffers
342   // being appended. Each new buffer appended has its config ID set
343   // to the value of this field.
344   int append_config_index_;
345
346   // Holds the audio/video configs for this stream. |current_config_index_|
347   // and |append_config_index_| represent indexes into one of these vectors.
348   std::vector<AudioDecoderConfig> audio_configs_;
349   std::vector<VideoDecoderConfig> video_configs_;
350
351   // Holds the text config for this stream.
352   TextTrackConfig text_track_config_;
353
354   // True if more data needs to be appended before the Seek() can complete,
355   // false if no Seek() has been requested or the Seek() is completed.
356   bool seek_pending_;
357
358   // True if the end of the stream has been signalled.
359   bool end_of_stream_;
360
361   // Timestamp of the last request to Seek().
362   base::TimeDelta seek_buffer_timestamp_;
363
364   // Pointer to the seeked-to Range. This is the range from which
365   // GetNextBuffer() calls are fulfilled after the |track_buffer_| has been
366   // emptied.
367   SourceBufferRange* selected_range_;
368
369   // Queue of the next buffers to be returned from calls to GetNextBuffer(). If
370   // |track_buffer_| is empty, return buffers from |selected_range_|.
371   BufferQueue track_buffer_;
372
373   // The start time of the current media segment being appended.
374   DecodeTimestamp media_segment_start_time_;
375
376   // Points to the range containing the current media segment being appended.
377   RangeList::iterator range_for_next_append_;
378
379   // True when the next call to Append() begins a new media segment.
380   bool new_media_segment_;
381
382   // The timestamp of the last buffer appended to the media segment, set to
383   // kNoDecodeTimestamp() if the beginning of the segment.
384   DecodeTimestamp last_appended_buffer_timestamp_;
385   bool last_appended_buffer_is_keyframe_;
386
387   // The decode timestamp on the last buffer returned by the most recent
388   // GetNextBuffer() call. Set to kNoTimestamp() if GetNextBuffer() hasn't been
389   // called yet or a seek has happened since the last GetNextBuffer() call.
390   DecodeTimestamp last_output_buffer_timestamp_;
391
392   // Stores the largest distance between two adjacent buffers in this stream.
393   base::TimeDelta max_interbuffer_distance_;
394
395   // The maximum amount of data in bytes the stream will keep in memory.
396   int memory_limit_;
397
398   // Indicates that a kConfigChanged status has been reported by GetNextBuffer()
399   // and GetCurrentXXXDecoderConfig() must be called to update the current
400   // config. GetNextBuffer() must not be called again until
401   // GetCurrentXXXDecoderConfig() has been called.
402   bool config_change_pending_;
403
404   // Used by HandleNextBufferWithSplice() or HandleNextBufferWithPreroll() when
405   // a splice frame buffer or buffer with preroll is returned from
406   // GetNextBufferInternal().
407   scoped_refptr<StreamParserBuffer> pending_buffer_;
408
409   // Indicates which of the splice buffers in |splice_buffer_| should be
410   // handled out next.
411   size_t splice_buffers_index_;
412
413   // Indicates that all buffers before |pending_buffer_| have been handed out.
414   bool pending_buffers_complete_;
415
416   // Indicates that splice frame generation is enabled.
417   const bool splice_frames_enabled_;
418
419   DISALLOW_COPY_AND_ASSIGN(SourceBufferStream);
420 };
421
422 }  // namespace media
423
424 #endif  // MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_