Home | History | Annotate | Download | only in filters
      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   SourceBufferStream(const AudioDecoderConfig& audio_config,
     50                      const LogCB& log_cb);
     51   SourceBufferStream(const VideoDecoderConfig& video_config,
     52                      const LogCB& log_cb);
     53   SourceBufferStream(const TextTrackConfig& text_config,
     54                      const LogCB& log_cb);
     55 
     56   ~SourceBufferStream();
     57 
     58   // Signals that the next buffers appended are part of a new media segment
     59   // starting at |media_segment_start_time|.
     60   void OnNewMediaSegment(base::TimeDelta media_segment_start_time);
     61 
     62   // Add the |buffers| to the SourceBufferStream. Buffers within the queue are
     63   // expected to be in order, but multiple calls to Append() may add buffers out
     64   // of order or overlapping. Assumes all buffers within |buffers| are in
     65   // presentation order and are non-overlapping.
     66   // Returns true if Append() was successful, false if |buffers| are not added.
     67   // TODO(vrk): Implement garbage collection. (crbug.com/125070)
     68   bool Append(const BufferQueue& buffers);
     69 
     70   // Removes buffers between |start| and |end| according to the steps
     71   // in the "Coded Frame Removal Algorithm" in the Media Source
     72   // Extensions Spec.
     73   // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-coded-frame-removal
     74   //
     75   // |duration| is the current duration of the presentation. It is
     76   // required by the computation outlined in the spec.
     77   void Remove(base::TimeDelta start, base::TimeDelta end,
     78               base::TimeDelta duration);
     79 
     80   // Changes the SourceBufferStream's state so that it will start returning
     81   // buffers starting from the closest keyframe before |timestamp|.
     82   void Seek(base::TimeDelta timestamp);
     83 
     84   // Returns true if the SourceBufferStream has seeked to a time without
     85   // buffered data and is waiting for more data to be appended.
     86   bool IsSeekPending() const;
     87 
     88   // Notifies the SourceBufferStream that the media duration has been changed to
     89   // |duration| so it should drop any data past that point.
     90   void OnSetDuration(base::TimeDelta duration);
     91 
     92   // Fills |out_buffer| with a new buffer. Buffers are presented in order from
     93   // the last call to Seek(), or starting with the first buffer appended if
     94   // Seek() has not been called yet.
     95   // |out_buffer|'s timestamp may be earlier than the |timestamp| passed to
     96   // the last Seek() call.
     97   // Returns kSuccess if |out_buffer| is filled with a valid buffer, kNeedBuffer
     98   // if there is not enough data buffered to fulfill the request, and
     99   // kConfigChange if the next buffer requires a config change.
    100   Status GetNextBuffer(scoped_refptr<StreamParserBuffer>* out_buffer);
    101 
    102   // Returns a list of the buffered time ranges.
    103   Ranges<base::TimeDelta> GetBufferedTime() const;
    104 
    105   // Notifies this object that end of stream has been signalled.
    106   void MarkEndOfStream();
    107 
    108   // Clear the end of stream state set by MarkEndOfStream().
    109   void UnmarkEndOfStream();
    110 
    111   const AudioDecoderConfig& GetCurrentAudioDecoderConfig();
    112   const VideoDecoderConfig& GetCurrentVideoDecoderConfig();
    113   const TextTrackConfig& GetCurrentTextTrackConfig();
    114 
    115   // Notifies this object that the audio config has changed and buffers in
    116   // future Append() calls should be associated with this new config.
    117   bool UpdateAudioConfig(const AudioDecoderConfig& config);
    118 
    119   // Notifies this object that the video config has changed and buffers in
    120   // future Append() calls should be associated with this new config.
    121   bool UpdateVideoConfig(const VideoDecoderConfig& config);
    122 
    123   // Returns the largest distance between two adjacent buffers in this stream,
    124   // or an estimate if no two adjacent buffers have been appended to the stream
    125   // yet.
    126   base::TimeDelta GetMaxInterbufferDistance() const;
    127 
    128   void set_memory_limit_for_testing(int memory_limit) {
    129     memory_limit_ = memory_limit;
    130   }
    131 
    132  private:
    133   friend class SourceBufferStreamTest;
    134 
    135   typedef std::list<SourceBufferRange*> RangeList;
    136 
    137   // Frees up space if the SourceBufferStream is taking up too much memory.
    138   void GarbageCollectIfNeeded();
    139 
    140   // Attempts to delete approximately |total_bytes_to_free| amount of data
    141   // |ranges_|, starting at the front of |ranges_| and moving linearly forward
    142   // through the buffers. Deletes starting from the back if |reverse_direction|
    143   // is true. Returns the number of bytes freed.
    144   int FreeBuffers(int total_bytes_to_free, bool reverse_direction);
    145 
    146   // Attempts to delete approximately |total_bytes_to_free| amount of data from
    147   // |ranges_|, starting after the last appended buffer before the current
    148   // playback position.
    149   int FreeBuffersAfterLastAppended(int total_bytes_to_free);
    150 
    151   // Gets the removal range to secure |byte_to_free| from
    152   // [|start_timestamp|, |end_timestamp|).
    153   // Returns the size of buffers to secure if future
    154   // Remove(|start_timestamp|, |removal_end_timestamp|, duration) is called.
    155   // Will not update |removal_end_timestamp| if the returned size is 0.
    156   int GetRemovalRange(base::TimeDelta start_timestamp,
    157       base::TimeDelta end_timestamp, int byte_to_free,
    158       base::TimeDelta* removal_end_timestamp);
    159 
    160   // Prepares |range_for_next_append_| so |new_buffers| can be appended.
    161   // This involves removing buffers between the end of the previous append
    162   // and any buffers covered by the time range in |new_buffers|.
    163   // |deleted_buffers| is an output parameter containing candidates for
    164   // |track_buffer_| if this method ends up removing the current playback
    165   // position from the range.
    166   void PrepareRangesForNextAppend(const BufferQueue& new_buffers,
    167                                   BufferQueue* deleted_buffers);
    168 
    169   // Removes buffers, from the |track_buffer_|, that come after |timestamp|.
    170   void PruneTrackBuffer(const base::TimeDelta timestamp);
    171 
    172   // Checks to see if |range_with_new_buffers_itr| can be merged with the range
    173   // next to it, and merges them if so.
    174   void MergeWithAdjacentRangeIfNecessary(
    175       const RangeList::iterator& range_with_new_buffers_itr);
    176 
    177   // Returns true if |second_timestamp| is the timestamp of the next buffer in
    178   // sequence after |first_timestamp|, false otherwise.
    179   bool AreAdjacentInSequence(
    180       base::TimeDelta first_timestamp, base::TimeDelta second_timestamp) const;
    181 
    182   // Helper method that returns the timestamp for the next buffer that
    183   // |selected_range_| will return from GetNextBuffer() call, or kNoTimestamp()
    184   // if in between seeking (i.e. |selected_range_| is null).
    185   base::TimeDelta GetNextBufferTimestamp();
    186 
    187   // Returns the timestamp of the last buffer in the |selected_range_| or
    188   // kNoTimestamp() if |selected_range_| is null.
    189   base::TimeDelta GetEndBufferTimestamp();
    190 
    191   // Finds the range that should contain a media segment that begins with
    192   // |start_timestamp| and returns the iterator pointing to it. Returns
    193   // |ranges_.end()| if there's no such existing range.
    194   RangeList::iterator FindExistingRangeFor(base::TimeDelta start_timestamp);
    195 
    196   // Inserts |new_range| into |ranges_| preserving sorted order. Returns an
    197   // iterator in |ranges_| that points to |new_range|.
    198   RangeList::iterator AddToRanges(SourceBufferRange* new_range);
    199 
    200   // Returns an iterator that points to the place in |ranges_| where
    201   // |selected_range_| lives.
    202   RangeList::iterator GetSelectedRangeItr();
    203 
    204   // Sets the |selected_range_| to |range| and resets the next buffer position
    205   // for the previous |selected_range_|.
    206   void SetSelectedRange(SourceBufferRange* range);
    207 
    208   // Seeks |range| to |seek_timestamp| and then calls SetSelectedRange() with
    209   // |range|.
    210   void SeekAndSetSelectedRange(SourceBufferRange* range,
    211                                base::TimeDelta seek_timestamp);
    212 
    213   // Resets this stream back to an unseeked state.
    214   void ResetSeekState();
    215 
    216   // Returns true if |seek_timestamp| refers to the beginning of the first range
    217   // in |ranges_|, false otherwise or if |ranges_| is empty.
    218   bool ShouldSeekToStartOfBuffered(base::TimeDelta seek_timestamp) const;
    219 
    220   // Returns true if the timestamps of |buffers| are monotonically increasing
    221   // since the previous append to the media segment, false otherwise.
    222   bool IsMonotonicallyIncreasing(const BufferQueue& buffers) const;
    223 
    224   // Returns true if |next_timestamp| and |next_is_keyframe| are valid for
    225   // the first buffer after the previous append.
    226   bool IsNextTimestampValid(base::TimeDelta next_timestamp,
    227                             bool next_is_keyframe) const;
    228 
    229   // Returns true if |selected_range_| is the only range in |ranges_| that
    230   // HasNextBufferPosition().
    231   bool OnlySelectedRangeIsSeeked() const;
    232 
    233   // Measures the distances between buffer timestamps and tracks the max.
    234   void UpdateMaxInterbufferDistance(const BufferQueue& buffers);
    235 
    236   // Sets the config ID for each buffer to |append_config_index_|.
    237   void SetConfigIds(const BufferQueue& buffers);
    238 
    239   // Called to complete a config change. Updates |current_config_index_| to
    240   // match the index of the next buffer. Calling this method causes
    241   // GetNextBuffer() to stop returning kConfigChange and start returning
    242   // kSuccess.
    243   void CompleteConfigChange();
    244 
    245   // Sets |selected_range_| and seeks to the nearest keyframe after
    246   // |timestamp| if necessary and possible. This method only attempts to
    247   // set |selected_range_| if |seleted_range_| is null and |track_buffer_|
    248   // is empty.
    249   void SetSelectedRangeIfNeeded(const base::TimeDelta timestamp);
    250 
    251   // Find a keyframe timestamp that is >= |start_timestamp| and can be used to
    252   // find a new selected range.
    253   // Returns kNoTimestamp() if an appropriate keyframe timestamp could not be
    254   // found.
    255   base::TimeDelta FindNewSelectedRangeSeekTimestamp(
    256       const base::TimeDelta start_timestamp);
    257 
    258   // Searches |ranges_| for the first keyframe timestamp that is >= |timestamp|.
    259   // If |ranges_| doesn't contain a GOP that covers |timestamp| or doesn't
    260   // have a keyframe after |timestamp| then kNoTimestamp() is returned.
    261   base::TimeDelta FindKeyframeAfterTimestamp(const base::TimeDelta timestamp);
    262 
    263   // Returns "VIDEO" for a video SourceBufferStream and "AUDIO" for an audio
    264   // one.
    265   std::string GetStreamTypeName() const;
    266 
    267   // Returns true if we don't have any ranges or the last range is selected
    268   // or there is a pending seek beyond any existing ranges.
    269   bool IsEndSelected() const;
    270 
    271   // Deletes the range pointed to by |*itr| and removes it from |ranges_|.
    272   // If |*itr| points to |selected_range_|, then |selected_range_| is set to
    273   // NULL. After the range is removed, |*itr| is to the range after the one that
    274   // was removed or to |ranges_.end()| if the last range was removed.
    275   void DeleteAndRemoveRange(RangeList::iterator* itr);
    276 
    277   // Helper function used by Remove() and PrepareRangesForNextAppend() to
    278   // remove buffers and ranges between |start| and |end|.
    279   // |is_exclusive| - If set to true, buffers with timestamps that
    280   // match |start| are not removed. If set to false, buffers with
    281   // timestamps that match |start| will be removed.
    282   // |*deleted_buffers| - Filled with buffers for the current playback position
    283   // if the removal range included the current playback position. These buffers
    284   // can be used as candidates for placing in the |track_buffer_|.
    285   void RemoveInternal(
    286       base::TimeDelta start, base::TimeDelta end, bool is_exclusive,
    287       BufferQueue* deleted_buffers);
    288 
    289   bool is_video() const { return video_configs_.size() > 0; }
    290 
    291   // Callback used to report error strings that can help the web developer
    292   // figure out what is wrong with the content.
    293   LogCB log_cb_;
    294 
    295   // List of disjoint buffered ranges, ordered by start time.
    296   RangeList ranges_;
    297 
    298   // Indicates which decoder config is being used by the decoder.
    299   // GetNextBuffer() is only allows to return buffers that have a
    300   // config ID that matches this index. If there is a mismatch then
    301   // it must signal that a config change is needed.
    302   int current_config_index_;
    303 
    304   // Indicates which decoder config to associate with new buffers
    305   // being appended. Each new buffer appended has its config ID set
    306   // to the value of this field.
    307   int append_config_index_;
    308 
    309   // Holds the audio/video configs for this stream. |current_config_index_|
    310   // and |append_config_index_| represent indexes into one of these vectors.
    311   std::vector<AudioDecoderConfig> audio_configs_;
    312   std::vector<VideoDecoderConfig> video_configs_;
    313 
    314   // Holds the text config for this stream.
    315   TextTrackConfig text_track_config_;
    316 
    317   // True if more data needs to be appended before the Seek() can complete,
    318   // false if no Seek() has been requested or the Seek() is completed.
    319   bool seek_pending_;
    320 
    321   // True if the end of the stream has been signalled.
    322   bool end_of_stream_;
    323 
    324   // Timestamp of the last request to Seek().
    325   base::TimeDelta seek_buffer_timestamp_;
    326 
    327   // Pointer to the seeked-to Range. This is the range from which
    328   // GetNextBuffer() calls are fulfilled after the |track_buffer_| has been
    329   // emptied.
    330   SourceBufferRange* selected_range_;
    331 
    332   // Queue of the next buffers to be returned from calls to GetNextBuffer(). If
    333   // |track_buffer_| is empty, return buffers from |selected_range_|.
    334   BufferQueue track_buffer_;
    335 
    336   // The start time of the current media segment being appended.
    337   base::TimeDelta media_segment_start_time_;
    338 
    339   // Points to the range containing the current media segment being appended.
    340   RangeList::iterator range_for_next_append_;
    341 
    342   // True when the next call to Append() begins a new media segment.
    343   bool new_media_segment_;
    344 
    345   // The timestamp of the last buffer appended to the media segment, set to
    346   // kNoTimestamp() if the beginning of the segment.
    347   base::TimeDelta last_appended_buffer_timestamp_;
    348   bool last_appended_buffer_is_keyframe_;
    349 
    350   // The decode timestamp on the last buffer returned by the most recent
    351   // GetNextBuffer() call. Set to kNoTimestamp() if GetNextBuffer() hasn't been
    352   // called yet or a seek has happened since the last GetNextBuffer() call.
    353   base::TimeDelta last_output_buffer_timestamp_;
    354 
    355   // Stores the largest distance between two adjacent buffers in this stream.
    356   base::TimeDelta max_interbuffer_distance_;
    357 
    358   // The maximum amount of data in bytes the stream will keep in memory.
    359   int memory_limit_;
    360 
    361   // Indicates that a kConfigChanged status has been reported by GetNextBuffer()
    362   // and GetCurrentXXXDecoderConfig() must be called to update the current
    363   // config. GetNextBuffer() must not be called again until
    364   // GetCurrentXXXDecoderConfig() has been called.
    365   bool config_change_pending_;
    366 
    367   DISALLOW_COPY_AND_ASSIGN(SourceBufferStream);
    368 };
    369 
    370 }  // namespace media
    371 
    372 #endif  // MEDIA_FILTERS_SOURCE_BUFFER_STREAM_H_
    373