Extension syncing: Introduce a NeedsSync pref
[chromium-blink-merge.git] / media / filters / chunk_demuxer.cc
blob6ba9a1387a862e3d3516e28cb19d5818c3a540ac
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 #include "media/filters/chunk_demuxer.h"
7 #include <algorithm>
8 #include <limits>
9 #include <list>
11 #include "base/bind.h"
12 #include "base/callback_helpers.h"
13 #include "base/location.h"
14 #include "base/stl_util.h"
15 #include "media/base/audio_decoder_config.h"
16 #include "media/base/bind_to_current_loop.h"
17 #include "media/base/stream_parser_buffer.h"
18 #include "media/base/video_decoder_config.h"
19 #include "media/filters/frame_processor.h"
20 #include "media/filters/stream_parser_factory.h"
22 using base::TimeDelta;
24 namespace media {
26 static TimeDelta EndTimestamp(const StreamParser::BufferQueue& queue) {
27 return queue.back()->timestamp() + queue.back()->duration();
30 // List of time ranges for each SourceBuffer.
31 typedef std::list<Ranges<TimeDelta> > RangesList;
32 static Ranges<TimeDelta> ComputeIntersection(const RangesList& activeRanges,
33 bool ended) {
34 // Implementation of HTMLMediaElement.buffered algorithm in MSE spec.
35 // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#dom-htmlmediaelement.buffered
37 // Step 1: If activeSourceBuffers.length equals 0 then return an empty
38 // TimeRanges object and abort these steps.
39 if (activeRanges.empty())
40 return Ranges<TimeDelta>();
42 // Step 2: Let active ranges be the ranges returned by buffered for each
43 // SourceBuffer object in activeSourceBuffers.
44 // Step 3: Let highest end time be the largest range end time in the active
45 // ranges.
46 TimeDelta highest_end_time;
47 for (RangesList::const_iterator itr = activeRanges.begin();
48 itr != activeRanges.end(); ++itr) {
49 if (!itr->size())
50 continue;
52 highest_end_time = std::max(highest_end_time, itr->end(itr->size() - 1));
55 // Step 4: Let intersection ranges equal a TimeRange object containing a
56 // single range from 0 to highest end time.
57 Ranges<TimeDelta> intersection_ranges;
58 intersection_ranges.Add(TimeDelta(), highest_end_time);
60 // Step 5: For each SourceBuffer object in activeSourceBuffers run the
61 // following steps:
62 for (RangesList::const_iterator itr = activeRanges.begin();
63 itr != activeRanges.end(); ++itr) {
64 // Step 5.1: Let source ranges equal the ranges returned by the buffered
65 // attribute on the current SourceBuffer.
66 Ranges<TimeDelta> source_ranges = *itr;
68 // Step 5.2: If readyState is "ended", then set the end time on the last
69 // range in source ranges to highest end time.
70 if (ended && source_ranges.size() > 0u) {
71 source_ranges.Add(source_ranges.start(source_ranges.size() - 1),
72 highest_end_time);
75 // Step 5.3: Let new intersection ranges equal the intersection between
76 // the intersection ranges and the source ranges.
77 // Step 5.4: Replace the ranges in intersection ranges with the new
78 // intersection ranges.
79 intersection_ranges = intersection_ranges.IntersectionWith(source_ranges);
82 return intersection_ranges;
85 // Contains state belonging to a source id.
86 class SourceState {
87 public:
88 // Callback signature used to create ChunkDemuxerStreams.
89 typedef base::Callback<ChunkDemuxerStream*(
90 DemuxerStream::Type)> CreateDemuxerStreamCB;
92 typedef ChunkDemuxer::InitSegmentReceivedCB InitSegmentReceivedCB;
94 typedef base::Callback<void(
95 ChunkDemuxerStream*, const TextTrackConfig&)> NewTextTrackCB;
97 SourceState(scoped_ptr<StreamParser> stream_parser,
98 scoped_ptr<FrameProcessor> frame_processor,
99 const CreateDemuxerStreamCB& create_demuxer_stream_cb,
100 const scoped_refptr<MediaLog>& media_log);
102 ~SourceState();
104 void Init(const StreamParser::InitCB& init_cb,
105 bool allow_audio,
106 bool allow_video,
107 const StreamParser::EncryptedMediaInitDataCB&
108 encrypted_media_init_data_cb,
109 const NewTextTrackCB& new_text_track_cb);
111 // Appends new data to the StreamParser.
112 // Returns true if the data was successfully appended. Returns false if an
113 // error occurred. |*timestamp_offset| is used and possibly updated by the
114 // append. |append_window_start| and |append_window_end| correspond to the MSE
115 // spec's similarly named source buffer attributes that are used in coded
116 // frame processing. |init_segment_received_cb| is run for each new fully
117 // parsed initialization segment.
118 bool Append(const uint8* data,
119 size_t length,
120 TimeDelta append_window_start,
121 TimeDelta append_window_end,
122 TimeDelta* timestamp_offset,
123 const InitSegmentReceivedCB& init_segment_received_cb);
125 // Aborts the current append sequence and resets the parser.
126 void Abort(TimeDelta append_window_start,
127 TimeDelta append_window_end,
128 TimeDelta* timestamp_offset);
130 // Calls Remove(|start|, |end|, |duration|) on all
131 // ChunkDemuxerStreams managed by this object.
132 void Remove(TimeDelta start, TimeDelta end, TimeDelta duration);
134 // Returns true if currently parsing a media segment, or false otherwise.
135 bool parsing_media_segment() const { return parsing_media_segment_; }
137 // Sets |frame_processor_|'s sequence mode to |sequence_mode|.
138 void SetSequenceMode(bool sequence_mode);
140 // Signals the coded frame processor to update its group start timestamp to be
141 // |timestamp_offset| if it is in sequence append mode.
142 void SetGroupStartTimestampIfInSequenceMode(base::TimeDelta timestamp_offset);
144 // Returns the range of buffered data in this source, capped at |duration|.
145 // |ended| - Set to true if end of stream has been signaled and the special
146 // end of stream range logic needs to be executed.
147 Ranges<TimeDelta> GetBufferedRanges(TimeDelta duration, bool ended) const;
149 // Returns the highest buffered duration across all streams managed
150 // by this object.
151 // Returns TimeDelta() if none of the streams contain buffered data.
152 TimeDelta GetMaxBufferedDuration() const;
154 // Helper methods that call methods with similar names on all the
155 // ChunkDemuxerStreams managed by this object.
156 void StartReturningData();
157 void AbortReads();
158 void Seek(TimeDelta seek_time);
159 void CompletePendingReadIfPossible();
160 void OnSetDuration(TimeDelta duration);
161 void MarkEndOfStream();
162 void UnmarkEndOfStream();
163 void Shutdown();
164 // Sets the memory limit on each stream of a specific type.
165 // |memory_limit| is the maximum number of bytes each stream of type |type|
166 // is allowed to hold in its buffer.
167 void SetMemoryLimits(DemuxerStream::Type type, int memory_limit);
168 bool IsSeekWaitingForData() const;
170 private:
171 // Called by the |stream_parser_| when a new initialization segment is
172 // encountered.
173 // Returns true on a successful call. Returns false if an error occurred while
174 // processing decoder configurations.
175 bool OnNewConfigs(bool allow_audio, bool allow_video,
176 const AudioDecoderConfig& audio_config,
177 const VideoDecoderConfig& video_config,
178 const StreamParser::TextTrackConfigMap& text_configs);
180 // Called by the |stream_parser_| at the beginning of a new media segment.
181 void OnNewMediaSegment();
183 // Called by the |stream_parser_| at the end of a media segment.
184 void OnEndOfMediaSegment();
186 // Called by the |stream_parser_| when new buffers have been parsed.
187 // It processes the new buffers using |frame_processor_|, which includes
188 // appending the processed frames to associated demuxer streams for each
189 // frame's track.
190 // Returns true on a successful call. Returns false if an error occurred while
191 // processing the buffers.
192 bool OnNewBuffers(const StreamParser::BufferQueue& audio_buffers,
193 const StreamParser::BufferQueue& video_buffers,
194 const StreamParser::TextBufferQueueMap& text_map);
196 void OnSourceInitDone(const StreamParser::InitParameters& params);
198 CreateDemuxerStreamCB create_demuxer_stream_cb_;
199 NewTextTrackCB new_text_track_cb_;
201 // During Append(), if OnNewBuffers() coded frame processing updates the
202 // timestamp offset then |*timestamp_offset_during_append_| is also updated
203 // so Append()'s caller can know the new offset. This pointer is only non-NULL
204 // during the lifetime of an Append() call.
205 TimeDelta* timestamp_offset_during_append_;
207 // During Append(), coded frame processing triggered by OnNewBuffers()
208 // requires these two attributes. These are only valid during the lifetime of
209 // an Append() call.
210 TimeDelta append_window_start_during_append_;
211 TimeDelta append_window_end_during_append_;
213 // Set to true if the next buffers appended within the append window
214 // represent the start of a new media segment. This flag being set
215 // triggers a call to |new_segment_cb_| when the new buffers are
216 // appended. The flag is set on actual media segment boundaries and
217 // when the "append window" filtering causes discontinuities in the
218 // appended data.
219 // TODO(wolenetz/acolwell): Investigate if we need this, or if coded frame
220 // processing's discontinuity logic is enough. See http://crbug.com/351489.
221 bool new_media_segment_;
223 // Keeps track of whether a media segment is being parsed.
224 bool parsing_media_segment_;
226 // The object used to parse appended data.
227 scoped_ptr<StreamParser> stream_parser_;
229 ChunkDemuxerStream* audio_; // Not owned by |this|.
230 ChunkDemuxerStream* video_; // Not owned by |this|.
232 typedef std::map<StreamParser::TrackId, ChunkDemuxerStream*> TextStreamMap;
233 TextStreamMap text_stream_map_; // |this| owns the map's stream pointers.
235 scoped_ptr<FrameProcessor> frame_processor_;
236 scoped_refptr<MediaLog> media_log_;
237 StreamParser::InitCB init_cb_;
239 // During Append(), OnNewConfigs() will trigger the initialization segment
240 // received algorithm. This callback is only non-NULL during the lifetime of
241 // an Append() call. Note, the MSE spec explicitly disallows this algorithm
242 // during an Abort(), since Abort() is allowed only to emit coded frames, and
243 // only if the parser is PARSING_MEDIA_SEGMENT (not an INIT segment).
244 InitSegmentReceivedCB init_segment_received_cb_;
246 // Indicates that timestampOffset should be updated automatically during
247 // OnNewBuffers() based on the earliest end timestamp of the buffers provided.
248 // TODO(wolenetz): Refactor this function while integrating April 29, 2014
249 // changes to MSE spec. See http://crbug.com/371499.
250 bool auto_update_timestamp_offset_;
252 DISALLOW_COPY_AND_ASSIGN(SourceState);
255 SourceState::SourceState(scoped_ptr<StreamParser> stream_parser,
256 scoped_ptr<FrameProcessor> frame_processor,
257 const CreateDemuxerStreamCB& create_demuxer_stream_cb,
258 const scoped_refptr<MediaLog>& media_log)
259 : create_demuxer_stream_cb_(create_demuxer_stream_cb),
260 timestamp_offset_during_append_(NULL),
261 new_media_segment_(false),
262 parsing_media_segment_(false),
263 stream_parser_(stream_parser.release()),
264 audio_(NULL),
265 video_(NULL),
266 frame_processor_(frame_processor.release()),
267 media_log_(media_log),
268 auto_update_timestamp_offset_(false) {
269 DCHECK(!create_demuxer_stream_cb_.is_null());
270 DCHECK(frame_processor_);
273 SourceState::~SourceState() {
274 Shutdown();
276 STLDeleteValues(&text_stream_map_);
279 void SourceState::Init(
280 const StreamParser::InitCB& init_cb,
281 bool allow_audio,
282 bool allow_video,
283 const StreamParser::EncryptedMediaInitDataCB& encrypted_media_init_data_cb,
284 const NewTextTrackCB& new_text_track_cb) {
285 new_text_track_cb_ = new_text_track_cb;
286 init_cb_ = init_cb;
288 stream_parser_->Init(
289 base::Bind(&SourceState::OnSourceInitDone, base::Unretained(this)),
290 base::Bind(&SourceState::OnNewConfigs, base::Unretained(this),
291 allow_audio, allow_video),
292 base::Bind(&SourceState::OnNewBuffers, base::Unretained(this)),
293 new_text_track_cb_.is_null(), encrypted_media_init_data_cb,
294 base::Bind(&SourceState::OnNewMediaSegment, base::Unretained(this)),
295 base::Bind(&SourceState::OnEndOfMediaSegment, base::Unretained(this)),
296 media_log_);
299 void SourceState::SetSequenceMode(bool sequence_mode) {
300 DCHECK(!parsing_media_segment_);
302 frame_processor_->SetSequenceMode(sequence_mode);
305 void SourceState::SetGroupStartTimestampIfInSequenceMode(
306 base::TimeDelta timestamp_offset) {
307 DCHECK(!parsing_media_segment_);
309 frame_processor_->SetGroupStartTimestampIfInSequenceMode(timestamp_offset);
312 bool SourceState::Append(
313 const uint8* data,
314 size_t length,
315 TimeDelta append_window_start,
316 TimeDelta append_window_end,
317 TimeDelta* timestamp_offset,
318 const InitSegmentReceivedCB& init_segment_received_cb) {
319 DCHECK(timestamp_offset);
320 DCHECK(!timestamp_offset_during_append_);
321 DCHECK(!init_segment_received_cb.is_null());
322 DCHECK(init_segment_received_cb_.is_null());
323 append_window_start_during_append_ = append_window_start;
324 append_window_end_during_append_ = append_window_end;
325 timestamp_offset_during_append_ = timestamp_offset;
326 init_segment_received_cb_= init_segment_received_cb;
328 // TODO(wolenetz/acolwell): Curry and pass a NewBuffersCB here bound with
329 // append window and timestamp offset pointer. See http://crbug.com/351454.
330 bool result = stream_parser_->Parse(data, length);
331 if (!result) {
332 MEDIA_LOG(ERROR, media_log_)
333 << __FUNCTION__ << ": stream parsing failed."
334 << " Data size=" << length
335 << " append_window_start=" << append_window_start.InSecondsF()
336 << " append_window_end=" << append_window_end.InSecondsF();
338 timestamp_offset_during_append_ = NULL;
339 init_segment_received_cb_.Reset();
340 return result;
343 void SourceState::Abort(TimeDelta append_window_start,
344 TimeDelta append_window_end,
345 base::TimeDelta* timestamp_offset) {
346 DCHECK(timestamp_offset);
347 DCHECK(!timestamp_offset_during_append_);
348 timestamp_offset_during_append_ = timestamp_offset;
349 append_window_start_during_append_ = append_window_start;
350 append_window_end_during_append_ = append_window_end;
352 stream_parser_->Flush();
353 timestamp_offset_during_append_ = NULL;
355 frame_processor_->Reset();
356 parsing_media_segment_ = false;
359 void SourceState::Remove(TimeDelta start, TimeDelta end, TimeDelta duration) {
360 if (audio_)
361 audio_->Remove(start, end, duration);
363 if (video_)
364 video_->Remove(start, end, duration);
366 for (TextStreamMap::iterator itr = text_stream_map_.begin();
367 itr != text_stream_map_.end(); ++itr) {
368 itr->second->Remove(start, end, duration);
372 Ranges<TimeDelta> SourceState::GetBufferedRanges(TimeDelta duration,
373 bool ended) const {
374 // TODO(acolwell): When we start allowing disabled tracks we'll need to update
375 // this code to only add ranges from active tracks.
376 RangesList ranges_list;
377 if (audio_)
378 ranges_list.push_back(audio_->GetBufferedRanges(duration));
380 if (video_)
381 ranges_list.push_back(video_->GetBufferedRanges(duration));
383 for (TextStreamMap::const_iterator itr = text_stream_map_.begin();
384 itr != text_stream_map_.end(); ++itr) {
385 ranges_list.push_back(itr->second->GetBufferedRanges(duration));
388 return ComputeIntersection(ranges_list, ended);
391 TimeDelta SourceState::GetMaxBufferedDuration() const {
392 TimeDelta max_duration;
394 if (audio_)
395 max_duration = std::max(max_duration, audio_->GetBufferedDuration());
397 if (video_)
398 max_duration = std::max(max_duration, video_->GetBufferedDuration());
400 for (TextStreamMap::const_iterator itr = text_stream_map_.begin();
401 itr != text_stream_map_.end(); ++itr) {
402 max_duration = std::max(max_duration, itr->second->GetBufferedDuration());
405 return max_duration;
408 void SourceState::StartReturningData() {
409 if (audio_)
410 audio_->StartReturningData();
412 if (video_)
413 video_->StartReturningData();
415 for (TextStreamMap::iterator itr = text_stream_map_.begin();
416 itr != text_stream_map_.end(); ++itr) {
417 itr->second->StartReturningData();
421 void SourceState::AbortReads() {
422 if (audio_)
423 audio_->AbortReads();
425 if (video_)
426 video_->AbortReads();
428 for (TextStreamMap::iterator itr = text_stream_map_.begin();
429 itr != text_stream_map_.end(); ++itr) {
430 itr->second->AbortReads();
434 void SourceState::Seek(TimeDelta seek_time) {
435 if (audio_)
436 audio_->Seek(seek_time);
438 if (video_)
439 video_->Seek(seek_time);
441 for (TextStreamMap::iterator itr = text_stream_map_.begin();
442 itr != text_stream_map_.end(); ++itr) {
443 itr->second->Seek(seek_time);
447 void SourceState::CompletePendingReadIfPossible() {
448 if (audio_)
449 audio_->CompletePendingReadIfPossible();
451 if (video_)
452 video_->CompletePendingReadIfPossible();
454 for (TextStreamMap::iterator itr = text_stream_map_.begin();
455 itr != text_stream_map_.end(); ++itr) {
456 itr->second->CompletePendingReadIfPossible();
460 void SourceState::OnSetDuration(TimeDelta duration) {
461 if (audio_)
462 audio_->OnSetDuration(duration);
464 if (video_)
465 video_->OnSetDuration(duration);
467 for (TextStreamMap::iterator itr = text_stream_map_.begin();
468 itr != text_stream_map_.end(); ++itr) {
469 itr->second->OnSetDuration(duration);
473 void SourceState::MarkEndOfStream() {
474 if (audio_)
475 audio_->MarkEndOfStream();
477 if (video_)
478 video_->MarkEndOfStream();
480 for (TextStreamMap::iterator itr = text_stream_map_.begin();
481 itr != text_stream_map_.end(); ++itr) {
482 itr->second->MarkEndOfStream();
486 void SourceState::UnmarkEndOfStream() {
487 if (audio_)
488 audio_->UnmarkEndOfStream();
490 if (video_)
491 video_->UnmarkEndOfStream();
493 for (TextStreamMap::iterator itr = text_stream_map_.begin();
494 itr != text_stream_map_.end(); ++itr) {
495 itr->second->UnmarkEndOfStream();
499 void SourceState::Shutdown() {
500 if (audio_)
501 audio_->Shutdown();
503 if (video_)
504 video_->Shutdown();
506 for (TextStreamMap::iterator itr = text_stream_map_.begin();
507 itr != text_stream_map_.end(); ++itr) {
508 itr->second->Shutdown();
512 void SourceState::SetMemoryLimits(DemuxerStream::Type type, int memory_limit) {
513 switch (type) {
514 case DemuxerStream::AUDIO:
515 if (audio_)
516 audio_->set_memory_limit(memory_limit);
517 break;
518 case DemuxerStream::VIDEO:
519 if (video_)
520 video_->set_memory_limit(memory_limit);
521 break;
522 case DemuxerStream::TEXT:
523 for (TextStreamMap::iterator itr = text_stream_map_.begin();
524 itr != text_stream_map_.end(); ++itr) {
525 itr->second->set_memory_limit(memory_limit);
527 break;
528 case DemuxerStream::UNKNOWN:
529 case DemuxerStream::NUM_TYPES:
530 NOTREACHED();
531 break;
535 bool SourceState::IsSeekWaitingForData() const {
536 if (audio_ && audio_->IsSeekWaitingForData())
537 return true;
539 if (video_ && video_->IsSeekWaitingForData())
540 return true;
542 // NOTE: We are intentionally not checking the text tracks
543 // because text tracks are discontinuous and may not have data
544 // for the seek position. This is ok and playback should not be
545 // stalled because we don't have cues. If cues, with timestamps after
546 // the seek time, eventually arrive they will be delivered properly
547 // in response to ChunkDemuxerStream::Read() calls.
549 return false;
552 bool SourceState::OnNewConfigs(
553 bool allow_audio, bool allow_video,
554 const AudioDecoderConfig& audio_config,
555 const VideoDecoderConfig& video_config,
556 const StreamParser::TextTrackConfigMap& text_configs) {
557 DVLOG(1) << "OnNewConfigs(" << allow_audio << ", " << allow_video
558 << ", " << audio_config.IsValidConfig()
559 << ", " << video_config.IsValidConfig() << ")";
560 DCHECK(!init_segment_received_cb_.is_null());
562 if (!audio_config.IsValidConfig() && !video_config.IsValidConfig()) {
563 DVLOG(1) << "OnNewConfigs() : Audio & video config are not valid!";
564 return false;
567 // Signal an error if we get configuration info for stream types that weren't
568 // specified in AddId() or more configs after a stream is initialized.
569 if (allow_audio != audio_config.IsValidConfig()) {
570 MEDIA_LOG(ERROR, media_log_)
571 << "Initialization segment"
572 << (audio_config.IsValidConfig() ? " has" : " does not have")
573 << " an audio track, but the mimetype"
574 << (allow_audio ? " specifies" : " does not specify")
575 << " an audio codec.";
576 return false;
579 if (allow_video != video_config.IsValidConfig()) {
580 MEDIA_LOG(ERROR, media_log_)
581 << "Initialization segment"
582 << (video_config.IsValidConfig() ? " has" : " does not have")
583 << " a video track, but the mimetype"
584 << (allow_video ? " specifies" : " does not specify")
585 << " a video codec.";
586 return false;
589 bool success = true;
590 if (audio_config.IsValidConfig()) {
591 if (!audio_) {
592 media_log_->SetBooleanProperty("found_audio_stream", true);
594 if (!audio_ ||
595 audio_->audio_decoder_config().codec() != audio_config.codec()) {
596 media_log_->SetStringProperty("audio_codec_name",
597 audio_config.GetHumanReadableCodecName());
600 if (!audio_) {
601 audio_ = create_demuxer_stream_cb_.Run(DemuxerStream::AUDIO);
603 if (!audio_) {
604 DVLOG(1) << "Failed to create an audio stream.";
605 return false;
608 if (!frame_processor_->AddTrack(FrameProcessor::kAudioTrackId, audio_)) {
609 DVLOG(1) << "Failed to add audio track to frame processor.";
610 return false;
614 frame_processor_->OnPossibleAudioConfigUpdate(audio_config);
615 success &= audio_->UpdateAudioConfig(audio_config, media_log_);
618 if (video_config.IsValidConfig()) {
619 if (!video_) {
620 media_log_->SetBooleanProperty("found_video_stream", true);
622 if (!video_ ||
623 video_->video_decoder_config().codec() != video_config.codec()) {
624 media_log_->SetStringProperty("video_codec_name",
625 video_config.GetHumanReadableCodecName());
628 if (!video_) {
629 video_ = create_demuxer_stream_cb_.Run(DemuxerStream::VIDEO);
631 if (!video_) {
632 DVLOG(1) << "Failed to create a video stream.";
633 return false;
636 if (!frame_processor_->AddTrack(FrameProcessor::kVideoTrackId, video_)) {
637 DVLOG(1) << "Failed to add video track to frame processor.";
638 return false;
642 success &= video_->UpdateVideoConfig(video_config, media_log_);
645 typedef StreamParser::TextTrackConfigMap::const_iterator TextConfigItr;
646 if (text_stream_map_.empty()) {
647 for (TextConfigItr itr = text_configs.begin();
648 itr != text_configs.end(); ++itr) {
649 ChunkDemuxerStream* const text_stream =
650 create_demuxer_stream_cb_.Run(DemuxerStream::TEXT);
651 if (!frame_processor_->AddTrack(itr->first, text_stream)) {
652 success &= false;
653 MEDIA_LOG(ERROR, media_log_) << "Failed to add text track ID "
654 << itr->first << " to frame processor.";
655 break;
657 text_stream->UpdateTextConfig(itr->second, media_log_);
658 text_stream_map_[itr->first] = text_stream;
659 new_text_track_cb_.Run(text_stream, itr->second);
661 } else {
662 const size_t text_count = text_stream_map_.size();
663 if (text_configs.size() != text_count) {
664 success &= false;
665 MEDIA_LOG(ERROR, media_log_)
666 << "The number of text track configs changed.";
667 } else if (text_count == 1) {
668 TextConfigItr config_itr = text_configs.begin();
669 TextStreamMap::iterator stream_itr = text_stream_map_.begin();
670 ChunkDemuxerStream* text_stream = stream_itr->second;
671 TextTrackConfig old_config = text_stream->text_track_config();
672 TextTrackConfig new_config(config_itr->second.kind(),
673 config_itr->second.label(),
674 config_itr->second.language(),
675 old_config.id());
676 if (!new_config.Matches(old_config)) {
677 success &= false;
678 MEDIA_LOG(ERROR, media_log_)
679 << "New text track config does not match old one.";
680 } else {
681 StreamParser::TrackId old_id = stream_itr->first;
682 StreamParser::TrackId new_id = config_itr->first;
683 if (new_id != old_id) {
684 if (frame_processor_->UpdateTrack(old_id, new_id)) {
685 text_stream_map_.clear();
686 text_stream_map_[config_itr->first] = text_stream;
687 } else {
688 success &= false;
689 MEDIA_LOG(ERROR, media_log_)
690 << "Error remapping single text track number";
694 } else {
695 for (TextConfigItr config_itr = text_configs.begin();
696 config_itr != text_configs.end(); ++config_itr) {
697 TextStreamMap::iterator stream_itr =
698 text_stream_map_.find(config_itr->first);
699 if (stream_itr == text_stream_map_.end()) {
700 success &= false;
701 MEDIA_LOG(ERROR, media_log_)
702 << "Unexpected text track configuration for track ID "
703 << config_itr->first;
704 break;
707 const TextTrackConfig& new_config = config_itr->second;
708 ChunkDemuxerStream* stream = stream_itr->second;
709 TextTrackConfig old_config = stream->text_track_config();
710 if (!new_config.Matches(old_config)) {
711 success &= false;
712 MEDIA_LOG(ERROR, media_log_) << "New text track config for track ID "
713 << config_itr->first
714 << " does not match old one.";
715 break;
721 frame_processor_->SetAllTrackBuffersNeedRandomAccessPoint();
723 DVLOG(1) << "OnNewConfigs() : " << (success ? "success" : "failed");
724 if (success)
725 init_segment_received_cb_.Run();
727 return success;
730 void SourceState::OnNewMediaSegment() {
731 DVLOG(2) << "OnNewMediaSegment()";
732 parsing_media_segment_ = true;
733 new_media_segment_ = true;
736 void SourceState::OnEndOfMediaSegment() {
737 DVLOG(2) << "OnEndOfMediaSegment()";
738 parsing_media_segment_ = false;
739 new_media_segment_ = false;
742 bool SourceState::OnNewBuffers(
743 const StreamParser::BufferQueue& audio_buffers,
744 const StreamParser::BufferQueue& video_buffers,
745 const StreamParser::TextBufferQueueMap& text_map) {
746 DVLOG(2) << "OnNewBuffers()";
747 DCHECK(timestamp_offset_during_append_);
748 DCHECK(parsing_media_segment_);
750 const TimeDelta timestamp_offset_before_processing =
751 *timestamp_offset_during_append_;
753 // Calculate the new timestamp offset for audio/video tracks if the stream
754 // parser has requested automatic updates.
755 TimeDelta new_timestamp_offset = timestamp_offset_before_processing;
756 if (auto_update_timestamp_offset_) {
757 const bool have_audio_buffers = !audio_buffers.empty();
758 const bool have_video_buffers = !video_buffers.empty();
759 if (have_audio_buffers && have_video_buffers) {
760 new_timestamp_offset +=
761 std::min(EndTimestamp(audio_buffers), EndTimestamp(video_buffers));
762 } else if (have_audio_buffers) {
763 new_timestamp_offset += EndTimestamp(audio_buffers);
764 } else if (have_video_buffers) {
765 new_timestamp_offset += EndTimestamp(video_buffers);
769 if (!frame_processor_->ProcessFrames(audio_buffers,
770 video_buffers,
771 text_map,
772 append_window_start_during_append_,
773 append_window_end_during_append_,
774 &new_media_segment_,
775 timestamp_offset_during_append_)) {
776 return false;
779 // Only update the timestamp offset if the frame processor hasn't already.
780 if (auto_update_timestamp_offset_ &&
781 timestamp_offset_before_processing == *timestamp_offset_during_append_) {
782 *timestamp_offset_during_append_ = new_timestamp_offset;
785 return true;
788 void SourceState::OnSourceInitDone(const StreamParser::InitParameters& params) {
789 auto_update_timestamp_offset_ = params.auto_update_timestamp_offset;
790 base::ResetAndReturn(&init_cb_).Run(params);
793 ChunkDemuxerStream::ChunkDemuxerStream(Type type,
794 bool splice_frames_enabled)
795 : type_(type),
796 liveness_(DemuxerStream::LIVENESS_UNKNOWN),
797 state_(UNINITIALIZED),
798 splice_frames_enabled_(splice_frames_enabled),
799 partial_append_window_trimming_enabled_(false) {
802 void ChunkDemuxerStream::StartReturningData() {
803 DVLOG(1) << "ChunkDemuxerStream::StartReturningData()";
804 base::AutoLock auto_lock(lock_);
805 DCHECK(read_cb_.is_null());
806 ChangeState_Locked(RETURNING_DATA_FOR_READS);
809 void ChunkDemuxerStream::AbortReads() {
810 DVLOG(1) << "ChunkDemuxerStream::AbortReads()";
811 base::AutoLock auto_lock(lock_);
812 ChangeState_Locked(RETURNING_ABORT_FOR_READS);
813 if (!read_cb_.is_null())
814 base::ResetAndReturn(&read_cb_).Run(kAborted, NULL);
817 void ChunkDemuxerStream::CompletePendingReadIfPossible() {
818 base::AutoLock auto_lock(lock_);
819 if (read_cb_.is_null())
820 return;
822 CompletePendingReadIfPossible_Locked();
825 void ChunkDemuxerStream::Shutdown() {
826 DVLOG(1) << "ChunkDemuxerStream::Shutdown()";
827 base::AutoLock auto_lock(lock_);
828 ChangeState_Locked(SHUTDOWN);
830 // Pass an end of stream buffer to the pending callback to signal that no more
831 // data will be sent.
832 if (!read_cb_.is_null()) {
833 base::ResetAndReturn(&read_cb_).Run(DemuxerStream::kOk,
834 StreamParserBuffer::CreateEOSBuffer());
838 bool ChunkDemuxerStream::IsSeekWaitingForData() const {
839 base::AutoLock auto_lock(lock_);
841 // This method should not be called for text tracks. See the note in
842 // SourceState::IsSeekWaitingForData().
843 DCHECK_NE(type_, DemuxerStream::TEXT);
845 return stream_->IsSeekPending();
848 void ChunkDemuxerStream::Seek(TimeDelta time) {
849 DVLOG(1) << "ChunkDemuxerStream::Seek(" << time.InSecondsF() << ")";
850 base::AutoLock auto_lock(lock_);
851 DCHECK(read_cb_.is_null());
852 DCHECK(state_ == UNINITIALIZED || state_ == RETURNING_ABORT_FOR_READS)
853 << state_;
855 stream_->Seek(time);
858 bool ChunkDemuxerStream::Append(const StreamParser::BufferQueue& buffers) {
859 if (buffers.empty())
860 return false;
862 base::AutoLock auto_lock(lock_);
863 DCHECK_NE(state_, SHUTDOWN);
864 if (!stream_->Append(buffers)) {
865 DVLOG(1) << "ChunkDemuxerStream::Append() : stream append failed";
866 return false;
869 if (!read_cb_.is_null())
870 CompletePendingReadIfPossible_Locked();
872 return true;
875 void ChunkDemuxerStream::Remove(TimeDelta start, TimeDelta end,
876 TimeDelta duration) {
877 base::AutoLock auto_lock(lock_);
878 stream_->Remove(start, end, duration);
881 void ChunkDemuxerStream::OnSetDuration(TimeDelta duration) {
882 base::AutoLock auto_lock(lock_);
883 stream_->OnSetDuration(duration);
886 Ranges<TimeDelta> ChunkDemuxerStream::GetBufferedRanges(
887 TimeDelta duration) const {
888 base::AutoLock auto_lock(lock_);
890 if (type_ == TEXT) {
891 // Since text tracks are discontinuous and the lack of cues should not block
892 // playback, report the buffered range for text tracks as [0, |duration|) so
893 // that intesections with audio & video tracks are computed correctly when
894 // no cues are present.
895 Ranges<TimeDelta> text_range;
896 text_range.Add(TimeDelta(), duration);
897 return text_range;
900 Ranges<TimeDelta> range = stream_->GetBufferedTime();
902 if (range.size() == 0u)
903 return range;
905 // Clamp the end of the stream's buffered ranges to fit within the duration.
906 // This can be done by intersecting the stream's range with the valid time
907 // range.
908 Ranges<TimeDelta> valid_time_range;
909 valid_time_range.Add(range.start(0), duration);
910 return range.IntersectionWith(valid_time_range);
913 TimeDelta ChunkDemuxerStream::GetBufferedDuration() const {
914 return stream_->GetBufferedDuration();
917 void ChunkDemuxerStream::OnNewMediaSegment(DecodeTimestamp start_timestamp) {
918 DVLOG(2) << "ChunkDemuxerStream::OnNewMediaSegment("
919 << start_timestamp.InSecondsF() << ")";
920 base::AutoLock auto_lock(lock_);
921 stream_->OnNewMediaSegment(start_timestamp);
924 bool ChunkDemuxerStream::UpdateAudioConfig(
925 const AudioDecoderConfig& config,
926 const scoped_refptr<MediaLog>& media_log) {
927 DCHECK(config.IsValidConfig());
928 DCHECK_EQ(type_, AUDIO);
929 base::AutoLock auto_lock(lock_);
930 if (!stream_) {
931 DCHECK_EQ(state_, UNINITIALIZED);
933 // On platforms which support splice frames, enable splice frames and
934 // partial append window support for most codecs (notably: not opus).
935 const bool codec_supported = config.codec() == kCodecMP3 ||
936 config.codec() == kCodecAAC ||
937 config.codec() == kCodecVorbis;
938 splice_frames_enabled_ = splice_frames_enabled_ && codec_supported;
939 partial_append_window_trimming_enabled_ =
940 splice_frames_enabled_ && codec_supported;
942 stream_.reset(
943 new SourceBufferStream(config, media_log, splice_frames_enabled_));
944 return true;
947 return stream_->UpdateAudioConfig(config);
950 bool ChunkDemuxerStream::UpdateVideoConfig(
951 const VideoDecoderConfig& config,
952 const scoped_refptr<MediaLog>& media_log) {
953 DCHECK(config.IsValidConfig());
954 DCHECK_EQ(type_, VIDEO);
955 base::AutoLock auto_lock(lock_);
957 if (!stream_) {
958 DCHECK_EQ(state_, UNINITIALIZED);
959 stream_.reset(
960 new SourceBufferStream(config, media_log, splice_frames_enabled_));
961 return true;
964 return stream_->UpdateVideoConfig(config);
967 void ChunkDemuxerStream::UpdateTextConfig(
968 const TextTrackConfig& config,
969 const scoped_refptr<MediaLog>& media_log) {
970 DCHECK_EQ(type_, TEXT);
971 base::AutoLock auto_lock(lock_);
972 DCHECK(!stream_);
973 DCHECK_EQ(state_, UNINITIALIZED);
974 stream_.reset(
975 new SourceBufferStream(config, media_log, splice_frames_enabled_));
978 void ChunkDemuxerStream::MarkEndOfStream() {
979 base::AutoLock auto_lock(lock_);
980 stream_->MarkEndOfStream();
983 void ChunkDemuxerStream::UnmarkEndOfStream() {
984 base::AutoLock auto_lock(lock_);
985 stream_->UnmarkEndOfStream();
988 // DemuxerStream methods.
989 void ChunkDemuxerStream::Read(const ReadCB& read_cb) {
990 base::AutoLock auto_lock(lock_);
991 DCHECK_NE(state_, UNINITIALIZED);
992 DCHECK(read_cb_.is_null());
994 read_cb_ = BindToCurrentLoop(read_cb);
995 CompletePendingReadIfPossible_Locked();
998 DemuxerStream::Type ChunkDemuxerStream::type() const { return type_; }
1000 DemuxerStream::Liveness ChunkDemuxerStream::liveness() const {
1001 base::AutoLock auto_lock(lock_);
1002 return liveness_;
1005 AudioDecoderConfig ChunkDemuxerStream::audio_decoder_config() {
1006 CHECK_EQ(type_, AUDIO);
1007 base::AutoLock auto_lock(lock_);
1008 return stream_->GetCurrentAudioDecoderConfig();
1011 VideoDecoderConfig ChunkDemuxerStream::video_decoder_config() {
1012 CHECK_EQ(type_, VIDEO);
1013 base::AutoLock auto_lock(lock_);
1014 return stream_->GetCurrentVideoDecoderConfig();
1017 bool ChunkDemuxerStream::SupportsConfigChanges() { return true; }
1019 VideoRotation ChunkDemuxerStream::video_rotation() {
1020 return VIDEO_ROTATION_0;
1023 TextTrackConfig ChunkDemuxerStream::text_track_config() {
1024 CHECK_EQ(type_, TEXT);
1025 base::AutoLock auto_lock(lock_);
1026 return stream_->GetCurrentTextTrackConfig();
1029 void ChunkDemuxerStream::SetLiveness(Liveness liveness) {
1030 base::AutoLock auto_lock(lock_);
1031 liveness_ = liveness;
1034 void ChunkDemuxerStream::ChangeState_Locked(State state) {
1035 lock_.AssertAcquired();
1036 DVLOG(1) << "ChunkDemuxerStream::ChangeState_Locked() : "
1037 << "type " << type_
1038 << " - " << state_ << " -> " << state;
1039 state_ = state;
1042 ChunkDemuxerStream::~ChunkDemuxerStream() {}
1044 void ChunkDemuxerStream::CompletePendingReadIfPossible_Locked() {
1045 lock_.AssertAcquired();
1046 DCHECK(!read_cb_.is_null());
1048 DemuxerStream::Status status;
1049 scoped_refptr<StreamParserBuffer> buffer;
1051 switch (state_) {
1052 case UNINITIALIZED:
1053 NOTREACHED();
1054 return;
1055 case RETURNING_DATA_FOR_READS:
1056 switch (stream_->GetNextBuffer(&buffer)) {
1057 case SourceBufferStream::kSuccess:
1058 status = DemuxerStream::kOk;
1059 DVLOG(2) << __FUNCTION__ << ": returning kOk, type " << type_
1060 << ", dts " << buffer->GetDecodeTimestamp().InSecondsF()
1061 << ", pts " << buffer->timestamp().InSecondsF()
1062 << ", dur " << buffer->duration().InSecondsF()
1063 << ", key " << buffer->is_key_frame();
1064 break;
1065 case SourceBufferStream::kNeedBuffer:
1066 // Return early without calling |read_cb_| since we don't have
1067 // any data to return yet.
1068 DVLOG(2) << __FUNCTION__ << ": returning kNeedBuffer, type "
1069 << type_;
1070 return;
1071 case SourceBufferStream::kEndOfStream:
1072 status = DemuxerStream::kOk;
1073 buffer = StreamParserBuffer::CreateEOSBuffer();
1074 DVLOG(2) << __FUNCTION__ << ": returning kOk with EOS buffer, type "
1075 << type_;
1076 break;
1077 case SourceBufferStream::kConfigChange:
1078 status = kConfigChanged;
1079 buffer = NULL;
1080 DVLOG(2) << __FUNCTION__ << ": returning kConfigChange, type "
1081 << type_;
1082 break;
1084 break;
1085 case RETURNING_ABORT_FOR_READS:
1086 // Null buffers should be returned in this state since we are waiting
1087 // for a seek. Any buffers in the SourceBuffer should NOT be returned
1088 // because they are associated with the seek.
1089 status = DemuxerStream::kAborted;
1090 buffer = NULL;
1091 DVLOG(2) << __FUNCTION__ << ": returning kAborted, type " << type_;
1092 break;
1093 case SHUTDOWN:
1094 status = DemuxerStream::kOk;
1095 buffer = StreamParserBuffer::CreateEOSBuffer();
1096 DVLOG(2) << __FUNCTION__ << ": returning kOk with EOS buffer, type "
1097 << type_;
1098 break;
1101 base::ResetAndReturn(&read_cb_).Run(status, buffer);
1104 ChunkDemuxer::ChunkDemuxer(
1105 const base::Closure& open_cb,
1106 const EncryptedMediaInitDataCB& encrypted_media_init_data_cb,
1107 const scoped_refptr<MediaLog>& media_log,
1108 bool splice_frames_enabled)
1109 : state_(WAITING_FOR_INIT),
1110 cancel_next_seek_(false),
1111 host_(NULL),
1112 open_cb_(open_cb),
1113 encrypted_media_init_data_cb_(encrypted_media_init_data_cb),
1114 enable_text_(false),
1115 media_log_(media_log),
1116 duration_(kNoTimestamp()),
1117 user_specified_duration_(-1),
1118 liveness_(DemuxerStream::LIVENESS_UNKNOWN),
1119 splice_frames_enabled_(splice_frames_enabled) {
1120 DCHECK(!open_cb_.is_null());
1121 DCHECK(!encrypted_media_init_data_cb_.is_null());
1124 std::string ChunkDemuxer::GetDisplayName() const {
1125 return "ChunkDemuxer";
1128 void ChunkDemuxer::Initialize(
1129 DemuxerHost* host,
1130 const PipelineStatusCB& cb,
1131 bool enable_text_tracks) {
1132 DVLOG(1) << "Init()";
1134 base::AutoLock auto_lock(lock_);
1136 // The |init_cb_| must only be run after this method returns, so always post.
1137 init_cb_ = BindToCurrentLoop(cb);
1138 if (state_ == SHUTDOWN) {
1139 base::ResetAndReturn(&init_cb_).Run(DEMUXER_ERROR_COULD_NOT_OPEN);
1140 return;
1142 DCHECK_EQ(state_, WAITING_FOR_INIT);
1143 host_ = host;
1144 enable_text_ = enable_text_tracks;
1146 ChangeState_Locked(INITIALIZING);
1148 base::ResetAndReturn(&open_cb_).Run();
1151 void ChunkDemuxer::Stop() {
1152 DVLOG(1) << "Stop()";
1153 Shutdown();
1156 void ChunkDemuxer::Seek(TimeDelta time, const PipelineStatusCB& cb) {
1157 DVLOG(1) << "Seek(" << time.InSecondsF() << ")";
1158 DCHECK(time >= TimeDelta());
1160 base::AutoLock auto_lock(lock_);
1161 DCHECK(seek_cb_.is_null());
1163 seek_cb_ = BindToCurrentLoop(cb);
1164 if (state_ != INITIALIZED && state_ != ENDED) {
1165 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_ERROR_INVALID_STATE);
1166 return;
1169 if (cancel_next_seek_) {
1170 cancel_next_seek_ = false;
1171 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1172 return;
1175 SeekAllSources(time);
1176 StartReturningData();
1178 if (IsSeekWaitingForData_Locked()) {
1179 DVLOG(1) << "Seek() : waiting for more data to arrive.";
1180 return;
1183 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1186 // Demuxer implementation.
1187 base::Time ChunkDemuxer::GetTimelineOffset() const {
1188 return timeline_offset_;
1191 DemuxerStream* ChunkDemuxer::GetStream(DemuxerStream::Type type) {
1192 DCHECK_NE(type, DemuxerStream::TEXT);
1193 base::AutoLock auto_lock(lock_);
1194 if (type == DemuxerStream::VIDEO)
1195 return video_.get();
1197 if (type == DemuxerStream::AUDIO)
1198 return audio_.get();
1200 return NULL;
1203 TimeDelta ChunkDemuxer::GetStartTime() const {
1204 return TimeDelta();
1207 void ChunkDemuxer::StartWaitingForSeek(TimeDelta seek_time) {
1208 DVLOG(1) << "StartWaitingForSeek()";
1209 base::AutoLock auto_lock(lock_);
1210 DCHECK(state_ == INITIALIZED || state_ == ENDED || state_ == SHUTDOWN ||
1211 state_ == PARSE_ERROR) << state_;
1212 DCHECK(seek_cb_.is_null());
1214 if (state_ == SHUTDOWN || state_ == PARSE_ERROR)
1215 return;
1217 AbortPendingReads();
1218 SeekAllSources(seek_time);
1220 // Cancel state set in CancelPendingSeek() since we want to
1221 // accept the next Seek().
1222 cancel_next_seek_ = false;
1225 void ChunkDemuxer::CancelPendingSeek(TimeDelta seek_time) {
1226 base::AutoLock auto_lock(lock_);
1227 DCHECK_NE(state_, INITIALIZING);
1228 DCHECK(seek_cb_.is_null() || IsSeekWaitingForData_Locked());
1230 if (cancel_next_seek_)
1231 return;
1233 AbortPendingReads();
1234 SeekAllSources(seek_time);
1236 if (seek_cb_.is_null()) {
1237 cancel_next_seek_ = true;
1238 return;
1241 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1244 ChunkDemuxer::Status ChunkDemuxer::AddId(const std::string& id,
1245 const std::string& type,
1246 std::vector<std::string>& codecs) {
1247 base::AutoLock auto_lock(lock_);
1249 if ((state_ != WAITING_FOR_INIT && state_ != INITIALIZING) || IsValidId(id))
1250 return kReachedIdLimit;
1252 bool has_audio = false;
1253 bool has_video = false;
1254 scoped_ptr<media::StreamParser> stream_parser(StreamParserFactory::Create(
1255 type, codecs, media_log_, &has_audio, &has_video));
1257 if (!stream_parser)
1258 return ChunkDemuxer::kNotSupported;
1260 if ((has_audio && !source_id_audio_.empty()) ||
1261 (has_video && !source_id_video_.empty()))
1262 return kReachedIdLimit;
1264 if (has_audio)
1265 source_id_audio_ = id;
1267 if (has_video)
1268 source_id_video_ = id;
1270 scoped_ptr<FrameProcessor> frame_processor(
1271 new FrameProcessor(base::Bind(&ChunkDemuxer::IncreaseDurationIfNecessary,
1272 base::Unretained(this))));
1274 scoped_ptr<SourceState> source_state(new SourceState(
1275 stream_parser.Pass(), frame_processor.Pass(),
1276 base::Bind(&ChunkDemuxer::CreateDemuxerStream, base::Unretained(this)),
1277 media_log_));
1279 SourceState::NewTextTrackCB new_text_track_cb;
1281 if (enable_text_) {
1282 new_text_track_cb = base::Bind(&ChunkDemuxer::OnNewTextTrack,
1283 base::Unretained(this));
1286 source_state->Init(
1287 base::Bind(&ChunkDemuxer::OnSourceInitDone, base::Unretained(this)),
1288 has_audio, has_video, encrypted_media_init_data_cb_, new_text_track_cb);
1290 source_state_map_[id] = source_state.release();
1291 return kOk;
1294 void ChunkDemuxer::RemoveId(const std::string& id) {
1295 base::AutoLock auto_lock(lock_);
1296 CHECK(IsValidId(id));
1298 delete source_state_map_[id];
1299 source_state_map_.erase(id);
1301 if (source_id_audio_ == id)
1302 source_id_audio_.clear();
1304 if (source_id_video_ == id)
1305 source_id_video_.clear();
1308 Ranges<TimeDelta> ChunkDemuxer::GetBufferedRanges(const std::string& id) const {
1309 base::AutoLock auto_lock(lock_);
1310 DCHECK(!id.empty());
1312 SourceStateMap::const_iterator itr = source_state_map_.find(id);
1314 DCHECK(itr != source_state_map_.end());
1315 return itr->second->GetBufferedRanges(duration_, state_ == ENDED);
1318 void ChunkDemuxer::AppendData(
1319 const std::string& id,
1320 const uint8* data,
1321 size_t length,
1322 TimeDelta append_window_start,
1323 TimeDelta append_window_end,
1324 TimeDelta* timestamp_offset,
1325 const InitSegmentReceivedCB& init_segment_received_cb) {
1326 DVLOG(1) << "AppendData(" << id << ", " << length << ")";
1328 DCHECK(!id.empty());
1329 DCHECK(timestamp_offset);
1330 DCHECK(!init_segment_received_cb.is_null());
1332 Ranges<TimeDelta> ranges;
1335 base::AutoLock auto_lock(lock_);
1336 DCHECK_NE(state_, ENDED);
1338 // Capture if any of the SourceBuffers are waiting for data before we start
1339 // parsing.
1340 bool old_waiting_for_data = IsSeekWaitingForData_Locked();
1342 if (length == 0u)
1343 return;
1345 DCHECK(data);
1347 switch (state_) {
1348 case INITIALIZING:
1349 case INITIALIZED:
1350 DCHECK(IsValidId(id));
1351 if (!source_state_map_[id]->Append(data, length,
1352 append_window_start,
1353 append_window_end,
1354 timestamp_offset,
1355 init_segment_received_cb)) {
1356 ReportError_Locked(PIPELINE_ERROR_DECODE);
1357 return;
1359 break;
1361 case PARSE_ERROR:
1362 DVLOG(1) << "AppendData(): Ignoring data after a parse error.";
1363 return;
1365 case WAITING_FOR_INIT:
1366 case ENDED:
1367 case SHUTDOWN:
1368 DVLOG(1) << "AppendData(): called in unexpected state " << state_;
1369 return;
1372 // Check to see if data was appended at the pending seek point. This
1373 // indicates we have parsed enough data to complete the seek.
1374 if (old_waiting_for_data && !IsSeekWaitingForData_Locked() &&
1375 !seek_cb_.is_null()) {
1376 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1379 ranges = GetBufferedRanges_Locked();
1382 for (size_t i = 0; i < ranges.size(); ++i)
1383 host_->AddBufferedTimeRange(ranges.start(i), ranges.end(i));
1386 void ChunkDemuxer::Abort(const std::string& id,
1387 TimeDelta append_window_start,
1388 TimeDelta append_window_end,
1389 TimeDelta* timestamp_offset) {
1390 DVLOG(1) << "Abort(" << id << ")";
1391 base::AutoLock auto_lock(lock_);
1392 DCHECK(!id.empty());
1393 CHECK(IsValidId(id));
1394 bool old_waiting_for_data = IsSeekWaitingForData_Locked();
1395 source_state_map_[id]->Abort(append_window_start,
1396 append_window_end,
1397 timestamp_offset);
1398 // Abort can possibly emit some buffers.
1399 // Need to check whether seeking can be completed.
1400 if (old_waiting_for_data && !IsSeekWaitingForData_Locked() &&
1401 !seek_cb_.is_null()) {
1402 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1406 void ChunkDemuxer::Remove(const std::string& id, TimeDelta start,
1407 TimeDelta end) {
1408 DVLOG(1) << "Remove(" << id << ", " << start.InSecondsF()
1409 << ", " << end.InSecondsF() << ")";
1410 base::AutoLock auto_lock(lock_);
1412 DCHECK(!id.empty());
1413 CHECK(IsValidId(id));
1414 DCHECK(start >= base::TimeDelta()) << start.InSecondsF();
1415 DCHECK(start < end) << "start " << start.InSecondsF()
1416 << " end " << end.InSecondsF();
1417 DCHECK(duration_ != kNoTimestamp());
1418 DCHECK(start <= duration_) << "start " << start.InSecondsF()
1419 << " duration " << duration_.InSecondsF();
1421 if (start == duration_)
1422 return;
1424 source_state_map_[id]->Remove(start, end, duration_);
1427 double ChunkDemuxer::GetDuration() {
1428 base::AutoLock auto_lock(lock_);
1429 return GetDuration_Locked();
1432 double ChunkDemuxer::GetDuration_Locked() {
1433 lock_.AssertAcquired();
1434 if (duration_ == kNoTimestamp())
1435 return std::numeric_limits<double>::quiet_NaN();
1437 // Return positive infinity if the resource is unbounded.
1438 // http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#dom-media-duration
1439 if (duration_ == kInfiniteDuration())
1440 return std::numeric_limits<double>::infinity();
1442 if (user_specified_duration_ >= 0)
1443 return user_specified_duration_;
1445 return duration_.InSecondsF();
1448 void ChunkDemuxer::SetDuration(double duration) {
1449 base::AutoLock auto_lock(lock_);
1450 DVLOG(1) << "SetDuration(" << duration << ")";
1451 DCHECK_GE(duration, 0);
1453 if (duration == GetDuration_Locked())
1454 return;
1456 // Compute & bounds check the TimeDelta representation of duration.
1457 // This can be different if the value of |duration| doesn't fit the range or
1458 // precision of TimeDelta.
1459 TimeDelta min_duration = TimeDelta::FromInternalValue(1);
1460 // Don't use TimeDelta::Max() here, as we want the largest finite time delta.
1461 TimeDelta max_duration = TimeDelta::FromInternalValue(kint64max - 1);
1462 double min_duration_in_seconds = min_duration.InSecondsF();
1463 double max_duration_in_seconds = max_duration.InSecondsF();
1465 TimeDelta duration_td;
1466 if (duration == std::numeric_limits<double>::infinity()) {
1467 duration_td = media::kInfiniteDuration();
1468 } else if (duration < min_duration_in_seconds) {
1469 duration_td = min_duration;
1470 } else if (duration > max_duration_in_seconds) {
1471 duration_td = max_duration;
1472 } else {
1473 duration_td = TimeDelta::FromMicroseconds(
1474 duration * base::Time::kMicrosecondsPerSecond);
1477 DCHECK(duration_td > TimeDelta());
1479 user_specified_duration_ = duration;
1480 duration_ = duration_td;
1481 host_->SetDuration(duration_);
1483 for (SourceStateMap::iterator itr = source_state_map_.begin();
1484 itr != source_state_map_.end(); ++itr) {
1485 itr->second->OnSetDuration(duration_);
1489 bool ChunkDemuxer::IsParsingMediaSegment(const std::string& id) {
1490 base::AutoLock auto_lock(lock_);
1491 DVLOG(1) << "IsParsingMediaSegment(" << id << ")";
1492 CHECK(IsValidId(id));
1494 return source_state_map_[id]->parsing_media_segment();
1497 void ChunkDemuxer::SetSequenceMode(const std::string& id,
1498 bool sequence_mode) {
1499 base::AutoLock auto_lock(lock_);
1500 DVLOG(1) << "SetSequenceMode(" << id << ", " << sequence_mode << ")";
1501 CHECK(IsValidId(id));
1502 DCHECK_NE(state_, ENDED);
1504 source_state_map_[id]->SetSequenceMode(sequence_mode);
1507 void ChunkDemuxer::SetGroupStartTimestampIfInSequenceMode(
1508 const std::string& id,
1509 base::TimeDelta timestamp_offset) {
1510 base::AutoLock auto_lock(lock_);
1511 DVLOG(1) << "SetGroupStartTimestampIfInSequenceMode(" << id << ", "
1512 << timestamp_offset.InSecondsF() << ")";
1513 CHECK(IsValidId(id));
1514 DCHECK_NE(state_, ENDED);
1516 source_state_map_[id]->SetGroupStartTimestampIfInSequenceMode(
1517 timestamp_offset);
1521 void ChunkDemuxer::MarkEndOfStream(PipelineStatus status) {
1522 DVLOG(1) << "MarkEndOfStream(" << status << ")";
1523 base::AutoLock auto_lock(lock_);
1524 DCHECK_NE(state_, WAITING_FOR_INIT);
1525 DCHECK_NE(state_, ENDED);
1527 if (state_ == SHUTDOWN || state_ == PARSE_ERROR)
1528 return;
1530 if (state_ == INITIALIZING) {
1531 ReportError_Locked(DEMUXER_ERROR_COULD_NOT_OPEN);
1532 return;
1535 bool old_waiting_for_data = IsSeekWaitingForData_Locked();
1536 for (SourceStateMap::iterator itr = source_state_map_.begin();
1537 itr != source_state_map_.end(); ++itr) {
1538 itr->second->MarkEndOfStream();
1541 CompletePendingReadsIfPossible();
1543 // Give a chance to resume the pending seek process.
1544 if (status != PIPELINE_OK) {
1545 ReportError_Locked(status);
1546 return;
1549 ChangeState_Locked(ENDED);
1550 DecreaseDurationIfNecessary();
1552 if (old_waiting_for_data && !IsSeekWaitingForData_Locked() &&
1553 !seek_cb_.is_null()) {
1554 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1558 void ChunkDemuxer::UnmarkEndOfStream() {
1559 DVLOG(1) << "UnmarkEndOfStream()";
1560 base::AutoLock auto_lock(lock_);
1561 DCHECK_EQ(state_, ENDED);
1563 ChangeState_Locked(INITIALIZED);
1565 for (SourceStateMap::iterator itr = source_state_map_.begin();
1566 itr != source_state_map_.end(); ++itr) {
1567 itr->second->UnmarkEndOfStream();
1571 void ChunkDemuxer::Shutdown() {
1572 DVLOG(1) << "Shutdown()";
1573 base::AutoLock auto_lock(lock_);
1575 if (state_ == SHUTDOWN)
1576 return;
1578 ShutdownAllStreams();
1580 ChangeState_Locked(SHUTDOWN);
1582 if(!seek_cb_.is_null())
1583 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_ERROR_ABORT);
1586 void ChunkDemuxer::SetMemoryLimits(DemuxerStream::Type type, int memory_limit) {
1587 for (SourceStateMap::iterator itr = source_state_map_.begin();
1588 itr != source_state_map_.end(); ++itr) {
1589 itr->second->SetMemoryLimits(type, memory_limit);
1593 void ChunkDemuxer::ChangeState_Locked(State new_state) {
1594 lock_.AssertAcquired();
1595 DVLOG(1) << "ChunkDemuxer::ChangeState_Locked() : "
1596 << state_ << " -> " << new_state;
1597 state_ = new_state;
1600 ChunkDemuxer::~ChunkDemuxer() {
1601 DCHECK_NE(state_, INITIALIZED);
1603 STLDeleteValues(&source_state_map_);
1606 void ChunkDemuxer::ReportError_Locked(PipelineStatus error) {
1607 DVLOG(1) << "ReportError_Locked(" << error << ")";
1608 lock_.AssertAcquired();
1609 DCHECK_NE(error, PIPELINE_OK);
1611 ChangeState_Locked(PARSE_ERROR);
1613 PipelineStatusCB cb;
1615 if (!init_cb_.is_null()) {
1616 std::swap(cb, init_cb_);
1617 } else {
1618 if (!seek_cb_.is_null())
1619 std::swap(cb, seek_cb_);
1621 ShutdownAllStreams();
1624 if (!cb.is_null()) {
1625 cb.Run(error);
1626 return;
1629 base::AutoUnlock auto_unlock(lock_);
1630 host_->OnDemuxerError(error);
1633 bool ChunkDemuxer::IsSeekWaitingForData_Locked() const {
1634 lock_.AssertAcquired();
1635 for (SourceStateMap::const_iterator itr = source_state_map_.begin();
1636 itr != source_state_map_.end(); ++itr) {
1637 if (itr->second->IsSeekWaitingForData())
1638 return true;
1641 return false;
1644 void ChunkDemuxer::OnSourceInitDone(
1645 const StreamParser::InitParameters& params) {
1646 DVLOG(1) << "OnSourceInitDone(" << params.duration.InSecondsF() << ")";
1647 lock_.AssertAcquired();
1648 DCHECK_EQ(state_, INITIALIZING);
1649 if (!audio_ && !video_) {
1650 ReportError_Locked(DEMUXER_ERROR_COULD_NOT_OPEN);
1651 return;
1654 if (params.duration != TimeDelta() && duration_ == kNoTimestamp())
1655 UpdateDuration(params.duration);
1657 if (!params.timeline_offset.is_null()) {
1658 if (!timeline_offset_.is_null() &&
1659 params.timeline_offset != timeline_offset_) {
1660 MEDIA_LOG(ERROR, media_log_)
1661 << "Timeline offset is not the same across all SourceBuffers.";
1662 ReportError_Locked(DEMUXER_ERROR_COULD_NOT_OPEN);
1663 return;
1666 timeline_offset_ = params.timeline_offset;
1669 if (params.liveness != DemuxerStream::LIVENESS_UNKNOWN) {
1670 if (audio_)
1671 audio_->SetLiveness(params.liveness);
1672 if (video_)
1673 video_->SetLiveness(params.liveness);
1676 // Wait until all streams have initialized.
1677 if ((!source_id_audio_.empty() && !audio_) ||
1678 (!source_id_video_.empty() && !video_)) {
1679 return;
1682 SeekAllSources(GetStartTime());
1683 StartReturningData();
1685 if (duration_ == kNoTimestamp())
1686 duration_ = kInfiniteDuration();
1688 // The demuxer is now initialized after the |start_timestamp_| was set.
1689 ChangeState_Locked(INITIALIZED);
1690 base::ResetAndReturn(&init_cb_).Run(PIPELINE_OK);
1693 ChunkDemuxerStream*
1694 ChunkDemuxer::CreateDemuxerStream(DemuxerStream::Type type) {
1695 switch (type) {
1696 case DemuxerStream::AUDIO:
1697 if (audio_)
1698 return NULL;
1699 audio_.reset(
1700 new ChunkDemuxerStream(DemuxerStream::AUDIO, splice_frames_enabled_));
1701 return audio_.get();
1702 break;
1703 case DemuxerStream::VIDEO:
1704 if (video_)
1705 return NULL;
1706 video_.reset(
1707 new ChunkDemuxerStream(DemuxerStream::VIDEO, splice_frames_enabled_));
1708 return video_.get();
1709 break;
1710 case DemuxerStream::TEXT: {
1711 return new ChunkDemuxerStream(DemuxerStream::TEXT,
1712 splice_frames_enabled_);
1713 break;
1715 case DemuxerStream::UNKNOWN:
1716 case DemuxerStream::NUM_TYPES:
1717 NOTREACHED();
1718 return NULL;
1720 NOTREACHED();
1721 return NULL;
1724 void ChunkDemuxer::OnNewTextTrack(ChunkDemuxerStream* text_stream,
1725 const TextTrackConfig& config) {
1726 lock_.AssertAcquired();
1727 DCHECK_NE(state_, SHUTDOWN);
1728 host_->AddTextStream(text_stream, config);
1731 bool ChunkDemuxer::IsValidId(const std::string& source_id) const {
1732 lock_.AssertAcquired();
1733 return source_state_map_.count(source_id) > 0u;
1736 void ChunkDemuxer::UpdateDuration(TimeDelta new_duration) {
1737 DCHECK(duration_ != new_duration);
1738 user_specified_duration_ = -1;
1739 duration_ = new_duration;
1740 host_->SetDuration(new_duration);
1743 void ChunkDemuxer::IncreaseDurationIfNecessary(TimeDelta new_duration) {
1744 DCHECK(new_duration != kNoTimestamp());
1745 DCHECK(new_duration != kInfiniteDuration());
1747 // Per April 1, 2014 MSE spec editor's draft:
1748 // https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/
1749 // media-source.html#sourcebuffer-coded-frame-processing
1750 // 5. If the media segment contains data beyond the current duration, then run
1751 // the duration change algorithm with new duration set to the maximum of
1752 // the current duration and the group end timestamp.
1754 if (new_duration <= duration_)
1755 return;
1757 DVLOG(2) << __FUNCTION__ << ": Increasing duration: "
1758 << duration_.InSecondsF() << " -> " << new_duration.InSecondsF();
1760 UpdateDuration(new_duration);
1763 void ChunkDemuxer::DecreaseDurationIfNecessary() {
1764 lock_.AssertAcquired();
1766 TimeDelta max_duration;
1768 for (SourceStateMap::const_iterator itr = source_state_map_.begin();
1769 itr != source_state_map_.end(); ++itr) {
1770 max_duration = std::max(max_duration,
1771 itr->second->GetMaxBufferedDuration());
1774 if (max_duration == TimeDelta())
1775 return;
1777 if (max_duration < duration_)
1778 UpdateDuration(max_duration);
1781 Ranges<TimeDelta> ChunkDemuxer::GetBufferedRanges() const {
1782 base::AutoLock auto_lock(lock_);
1783 return GetBufferedRanges_Locked();
1786 Ranges<TimeDelta> ChunkDemuxer::GetBufferedRanges_Locked() const {
1787 lock_.AssertAcquired();
1789 bool ended = state_ == ENDED;
1790 // TODO(acolwell): When we start allowing SourceBuffers that are not active,
1791 // we'll need to update this loop to only add ranges from active sources.
1792 RangesList ranges_list;
1793 for (SourceStateMap::const_iterator itr = source_state_map_.begin();
1794 itr != source_state_map_.end(); ++itr) {
1795 ranges_list.push_back(itr->second->GetBufferedRanges(duration_, ended));
1798 return ComputeIntersection(ranges_list, ended);
1801 void ChunkDemuxer::StartReturningData() {
1802 for (SourceStateMap::iterator itr = source_state_map_.begin();
1803 itr != source_state_map_.end(); ++itr) {
1804 itr->second->StartReturningData();
1808 void ChunkDemuxer::AbortPendingReads() {
1809 for (SourceStateMap::iterator itr = source_state_map_.begin();
1810 itr != source_state_map_.end(); ++itr) {
1811 itr->second->AbortReads();
1815 void ChunkDemuxer::SeekAllSources(TimeDelta seek_time) {
1816 for (SourceStateMap::iterator itr = source_state_map_.begin();
1817 itr != source_state_map_.end(); ++itr) {
1818 itr->second->Seek(seek_time);
1822 void ChunkDemuxer::CompletePendingReadsIfPossible() {
1823 for (SourceStateMap::iterator itr = source_state_map_.begin();
1824 itr != source_state_map_.end(); ++itr) {
1825 itr->second->CompletePendingReadIfPossible();
1829 void ChunkDemuxer::ShutdownAllStreams() {
1830 for (SourceStateMap::iterator itr = source_state_map_.begin();
1831 itr != source_state_map_.end(); ++itr) {
1832 itr->second->Shutdown();
1836 } // namespace media