chunk_demuxer.h revision 0529e5d033099cbfc42635f6f6183833b09dff6e
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#ifndef MEDIA_FILTERS_CHUNK_DEMUXER_H_
6#define MEDIA_FILTERS_CHUNK_DEMUXER_H_
7
8#include <deque>
9#include <map>
10#include <string>
11#include <utility>
12#include <vector>
13
14#include "base/synchronization/lock.h"
15#include "media/base/byte_queue.h"
16#include "media/base/demuxer.h"
17#include "media/base/ranges.h"
18#include "media/base/stream_parser.h"
19#include "media/filters/source_buffer_stream.h"
20
21namespace media {
22
23class FFmpegURLProtocol;
24class SourceState;
25
26class ChunkDemuxerStream : public DemuxerStream {
27 public:
28  typedef std::deque<scoped_refptr<StreamParserBuffer> > BufferQueue;
29
30  explicit ChunkDemuxerStream(Type type, bool splice_frames_enabled);
31  virtual ~ChunkDemuxerStream();
32
33  // ChunkDemuxerStream control methods.
34  void StartReturningData();
35  void AbortReads();
36  void CompletePendingReadIfPossible();
37  void Shutdown();
38
39  // SourceBufferStream manipulation methods.
40  void Seek(base::TimeDelta time);
41  bool IsSeekWaitingForData() const;
42
43  // Add buffers to this stream.  Buffers are stored in SourceBufferStreams,
44  // which handle ordering and overlap resolution.
45  // Returns true if buffers were successfully added.
46  bool Append(const StreamParser::BufferQueue& buffers);
47
48  // Removes buffers between |start| and |end| according to the steps
49  // in the "Coded Frame Removal Algorithm" in the Media Source
50  // Extensions Spec.
51  // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-coded-frame-removal
52  //
53  // |duration| is the current duration of the presentation. It is
54  // required by the computation outlined in the spec.
55  void Remove(base::TimeDelta start, base::TimeDelta end,
56              base::TimeDelta duration);
57
58  // Signal to the stream that duration has changed to |duration|.
59  void OnSetDuration(base::TimeDelta duration);
60
61  // Returns the range of buffered data in this stream, capped at |duration|.
62  Ranges<base::TimeDelta> GetBufferedRanges(base::TimeDelta duration) const;
63
64  // Returns the duration of the buffered data.
65  // Returns base::TimeDelta() if the stream has no buffered data.
66  base::TimeDelta GetBufferedDuration() const;
67
68  // Signal to the stream that buffers handed in through subsequent calls to
69  // Append() belong to a media segment that starts at |start_timestamp|.
70  void OnNewMediaSegment(base::TimeDelta start_timestamp);
71
72  // Called when midstream config updates occur.
73  // Returns true if the new config is accepted.
74  // Returns false if the new config should trigger an error.
75  bool UpdateAudioConfig(const AudioDecoderConfig& config, const LogCB& log_cb);
76  bool UpdateVideoConfig(const VideoDecoderConfig& config, const LogCB& log_cb);
77  void UpdateTextConfig(const TextTrackConfig& config, const LogCB& log_cb);
78
79  void MarkEndOfStream();
80  void UnmarkEndOfStream();
81
82  // DemuxerStream methods.
83  virtual void Read(const ReadCB& read_cb) OVERRIDE;
84  virtual Type type() OVERRIDE;
85  virtual void EnableBitstreamConverter() OVERRIDE;
86  virtual AudioDecoderConfig audio_decoder_config() OVERRIDE;
87  virtual VideoDecoderConfig video_decoder_config() OVERRIDE;
88  virtual bool SupportsConfigChanges() OVERRIDE;
89
90  // Returns the text track configuration.  It is an error to call this method
91  // if type() != TEXT.
92  TextTrackConfig text_track_config();
93
94  // Sets the memory limit, in bytes, on the SourceBufferStream.
95  void set_memory_limit_for_testing(int memory_limit) {
96    stream_->set_memory_limit_for_testing(memory_limit);
97  }
98
99 private:
100  enum State {
101    UNINITIALIZED,
102    RETURNING_DATA_FOR_READS,
103    RETURNING_ABORT_FOR_READS,
104    SHUTDOWN,
105  };
106
107  // Assigns |state_| to |state|
108  void ChangeState_Locked(State state);
109
110  void CompletePendingReadIfPossible_Locked();
111
112  // Specifies the type of the stream.
113  Type type_;
114
115  scoped_ptr<SourceBufferStream> stream_;
116
117  mutable base::Lock lock_;
118  State state_;
119  ReadCB read_cb_;
120  const bool splice_frames_enabled_;
121
122  DISALLOW_IMPLICIT_CONSTRUCTORS(ChunkDemuxerStream);
123};
124
125// Demuxer implementation that allows chunks of media data to be passed
126// from JavaScript to the media stack.
127class MEDIA_EXPORT ChunkDemuxer : public Demuxer {
128 public:
129  enum Status {
130    kOk,              // ID added w/o error.
131    kNotSupported,    // Type specified is not supported.
132    kReachedIdLimit,  // Reached ID limit. We can't handle any more IDs.
133  };
134
135  // |open_cb| Run when Initialize() is called to signal that the demuxer
136  //   is ready to receive media data via AppenData().
137  // |need_key_cb| Run when the demuxer determines that an encryption key is
138  //   needed to decrypt the content.
139  // |enable_text| Process inband text tracks in the normal way when true,
140  //   otherwise ignore them.
141  // |log_cb| Run when parsing error messages need to be logged to the error
142  //   console.
143  // |splice_frames_enabled| Indicates that it's okay to generate splice frames
144  //   per the MSE specification.  Renderers must understand DecoderBuffer's
145  //   splice_timestamp() field.
146  ChunkDemuxer(const base::Closure& open_cb,
147               const NeedKeyCB& need_key_cb,
148               const LogCB& log_cb,
149               bool splice_frames_enabled);
150  virtual ~ChunkDemuxer();
151
152  // Demuxer implementation.
153  virtual void Initialize(DemuxerHost* host,
154                          const PipelineStatusCB& cb,
155                          bool enable_text_tracks) OVERRIDE;
156  virtual void Stop(const base::Closure& callback) OVERRIDE;
157  virtual void Seek(base::TimeDelta time, const PipelineStatusCB&  cb) OVERRIDE;
158  virtual void OnAudioRendererDisabled() OVERRIDE;
159  virtual DemuxerStream* GetStream(DemuxerStream::Type type) OVERRIDE;
160  virtual base::TimeDelta GetStartTime() const OVERRIDE;
161  virtual base::Time GetTimelineOffset() const OVERRIDE;
162
163  // Methods used by an external object to control this demuxer.
164  //
165  // Indicates that a new Seek() call is on its way. Any pending Reads on the
166  // DemuxerStream objects should be aborted immediately inside this call and
167  // future Read calls should return kAborted until the Seek() call occurs.
168  // This method MUST ALWAYS be called before Seek() is called to signal that
169  // the next Seek() call represents the seek point we actually want to return
170  // data for.
171  // |seek_time| - The presentation timestamp for the seek that triggered this
172  // call. It represents the most recent position the caller is trying to seek
173  // to.
174  void StartWaitingForSeek(base::TimeDelta seek_time);
175
176  // Indicates that a Seek() call is on its way, but another seek has been
177  // requested that will override the impending Seek() call. Any pending Reads
178  // on the DemuxerStream objects should be aborted immediately inside this call
179  // and future Read calls should return kAborted until the next
180  // StartWaitingForSeek() call. This method also arranges for the next Seek()
181  // call received before a StartWaitingForSeek() call to immediately call its
182  // callback without waiting for any data.
183  // |seek_time| - The presentation timestamp for the seek request that
184  // triggered this call. It represents the most recent position the caller is
185  // trying to seek to.
186  void CancelPendingSeek(base::TimeDelta seek_time);
187
188  // Registers a new |id| to use for AppendData() calls. |type| indicates
189  // the MIME type for the data that we intend to append for this ID.
190  // |use_legacy_frame_processor| determines which of LegacyFrameProcessor or
191  // a (not yet implemented) more compliant frame processor to use to process
192  // parsed frames from AppendData() calls.
193  // TODO(wolenetz): Enable usage of new frame processor based on this flag.
194  // See http://crbug.com/249422.
195  // kOk is returned if the demuxer has enough resources to support another ID
196  //    and supports the format indicated by |type|.
197  // kNotSupported is returned if |type| is not a supported format.
198  // kReachedIdLimit is returned if the demuxer cannot handle another ID right
199  //    now.
200  Status AddId(const std::string& id, const std::string& type,
201               std::vector<std::string>& codecs,
202               const bool use_legacy_frame_processor);
203
204  // Removed an ID & associated resources that were previously added with
205  // AddId().
206  void RemoveId(const std::string& id);
207
208  // Gets the currently buffered ranges for the specified ID.
209  Ranges<base::TimeDelta> GetBufferedRanges(const std::string& id) const;
210
211  // Appends media data to the source buffer associated with |id|, applying
212  // and possibly updating |*timestamp_offset| during coded frame processing.
213  // |append_window_start| and |append_window_end| correspond to the MSE spec's
214  // similarly named source buffer attributes that are used in coded frame
215  // processing.
216  void AppendData(const std::string& id, const uint8* data, size_t length,
217                  base::TimeDelta append_window_start,
218                  base::TimeDelta append_window_end,
219                  base::TimeDelta* timestamp_offset);
220
221  // Aborts parsing the current segment and reset the parser to a state where
222  // it can accept a new segment.
223  void Abort(const std::string& id);
224
225  // Remove buffers between |start| and |end| for the source buffer
226  // associated with |id|.
227  void Remove(const std::string& id, base::TimeDelta start,
228              base::TimeDelta end);
229
230  // Returns the current presentation duration.
231  double GetDuration();
232  double GetDuration_Locked();
233
234  // Notifies the demuxer that the duration of the media has changed to
235  // |duration|.
236  void SetDuration(double duration);
237
238  // Returns true if the source buffer associated with |id| is currently parsing
239  // a media segment, or false otherwise.
240  bool IsParsingMediaSegment(const std::string& id);
241
242  // Set the append mode to be applied to subsequent buffers appended to the
243  // source buffer associated with |id|. If |sequence_mode| is true, caller
244  // is requesting "sequence" mode. Otherwise, caller is requesting "segments"
245  // mode.
246  void SetSequenceMode(const std::string& id, bool sequence_mode);
247
248  // Called to signal changes in the "end of stream"
249  // state. UnmarkEndOfStream() must not be called if a matching
250  // MarkEndOfStream() has not come before it.
251  void MarkEndOfStream(PipelineStatus status);
252  void UnmarkEndOfStream();
253
254  void Shutdown();
255
256  // Sets the memory limit on each stream. |memory_limit| is the
257  // maximum number of bytes each stream is allowed to hold in its buffer.
258  void SetMemoryLimitsForTesting(int memory_limit);
259
260  // Returns the ranges representing the buffered data in the demuxer.
261  // TODO(wolenetz): Remove this method once MediaSourceDelegate no longer
262  // requires it for doing hack browser seeks to I-frame on Android. See
263  // http://crbug.com/304234.
264  Ranges<base::TimeDelta> GetBufferedRanges() const;
265
266 private:
267  enum State {
268    WAITING_FOR_INIT,
269    INITIALIZING,
270    INITIALIZED,
271    ENDED,
272    PARSE_ERROR,
273    SHUTDOWN,
274  };
275
276  void ChangeState_Locked(State new_state);
277
278  // Reports an error and puts the demuxer in a state where it won't accept more
279  // data.
280  void ReportError_Locked(PipelineStatus error);
281
282  // Returns true if any stream has seeked to a time without buffered data.
283  bool IsSeekWaitingForData_Locked() const;
284
285  // Returns true if all streams can successfully call EndOfStream,
286  // false if any can not.
287  bool CanEndOfStream_Locked() const;
288
289  // SourceState callbacks.
290  void OnSourceInitDone(bool success, base::TimeDelta duration,
291                        base::Time timeline_offset);
292
293  // Creates a DemuxerStream for the specified |type|.
294  // Returns a new ChunkDemuxerStream instance if a stream of this type
295  // has not been created before. Returns NULL otherwise.
296  ChunkDemuxerStream* CreateDemuxerStream(DemuxerStream::Type type);
297
298  void OnNewTextTrack(ChunkDemuxerStream* text_stream,
299                      const TextTrackConfig& config);
300
301  // Returns true if |source_id| is valid, false otherwise.
302  bool IsValidId(const std::string& source_id) const;
303
304  // Increases |duration_| to |new_duration|, if |new_duration| is higher.
305  void IncreaseDurationIfNecessary(base::TimeDelta new_duration);
306
307  // Decreases |duration_| if the buffered region is less than |duration_| when
308  // EndOfStream() is called.
309  void DecreaseDurationIfNecessary();
310
311  // Sets |duration_| to |new_duration|, sets |user_specified_duration_| to -1
312  // and notifies |host_|.
313  void UpdateDuration(base::TimeDelta new_duration);
314
315  // Returns the ranges representing the buffered data in the demuxer.
316  Ranges<base::TimeDelta> GetBufferedRanges_Locked() const;
317
318  // Start returning data on all DemuxerStreams.
319  void StartReturningData();
320
321  // Aborts pending reads on all DemuxerStreams.
322  void AbortPendingReads();
323
324  // Completes any pending reads if it is possible to do so.
325  void CompletePendingReadsIfPossible();
326
327  // Seeks all SourceBufferStreams to |seek_time|.
328  void SeekAllSources(base::TimeDelta seek_time);
329
330  // Shuts down all DemuxerStreams by calling Shutdown() on
331  // all objects in |source_state_map_|.
332  void ShutdownAllStreams();
333
334  mutable base::Lock lock_;
335  State state_;
336  bool cancel_next_seek_;
337
338  DemuxerHost* host_;
339  base::Closure open_cb_;
340  NeedKeyCB need_key_cb_;
341  bool enable_text_;
342  // Callback used to report error strings that can help the web developer
343  // figure out what is wrong with the content.
344  LogCB log_cb_;
345
346  PipelineStatusCB init_cb_;
347  // Callback to execute upon seek completion.
348  // TODO(wolenetz/acolwell): Protect against possible double-locking by first
349  // releasing |lock_| before executing this callback. See
350  // http://crbug.com/308226
351  PipelineStatusCB seek_cb_;
352
353  scoped_ptr<ChunkDemuxerStream> audio_;
354  scoped_ptr<ChunkDemuxerStream> video_;
355
356  // Keeps |audio_| alive when audio has been disabled.
357  scoped_ptr<ChunkDemuxerStream> disabled_audio_;
358
359  base::TimeDelta duration_;
360
361  // The duration passed to the last SetDuration(). If
362  // SetDuration() is never called or an AppendData() call or
363  // a EndOfStream() call changes |duration_|, then this
364  // variable is set to < 0 to indicate that the |duration_| represents
365  // the actual duration instead of a user specified value.
366  double user_specified_duration_;
367
368  base::Time timeline_offset_;
369
370  typedef std::map<std::string, SourceState*> SourceStateMap;
371  SourceStateMap source_state_map_;
372
373  // Used to ensure that (1) config data matches the type and codec provided in
374  // AddId(), (2) only 1 audio and 1 video sources are added, and (3) ids may be
375  // removed with RemoveID() but can not be re-added (yet).
376  std::string source_id_audio_;
377  std::string source_id_video_;
378
379  // Indicates that splice frame generation is enabled.
380  const bool splice_frames_enabled_;
381
382  DISALLOW_COPY_AND_ASSIGN(ChunkDemuxer);
383};
384
385}  // namespace media
386
387#endif  // MEDIA_FILTERS_CHUNK_DEMUXER_H_
388