[Cronet] Delay StartNetLog and StopNetLog until native request context is initialized
[chromium-blink-merge.git] / media / filters / chunk_demuxer.cc
blob40e7ed29d068eb3253697109a16385d829862be7
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/message_loop/message_loop_proxy.h"
15 #include "base/stl_util.h"
16 #include "media/base/audio_decoder_config.h"
17 #include "media/base/bind_to_current_loop.h"
18 #include "media/base/stream_parser_buffer.h"
19 #include "media/base/video_decoder_config.h"
20 #include "media/filters/frame_processor.h"
21 #include "media/filters/stream_parser_factory.h"
23 using base::TimeDelta;
25 namespace media {
27 static TimeDelta EndTimestamp(const StreamParser::BufferQueue& queue) {
28 return queue.back()->timestamp() + queue.back()->duration();
31 // List of time ranges for each SourceBuffer.
32 typedef std::list<Ranges<TimeDelta> > RangesList;
33 static Ranges<TimeDelta> ComputeIntersection(const RangesList& activeRanges,
34 bool ended) {
35 // Implementation of HTMLMediaElement.buffered algorithm in MSE spec.
36 // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#dom-htmlmediaelement.buffered
38 // Step 1: If activeSourceBuffers.length equals 0 then return an empty
39 // TimeRanges object and abort these steps.
40 if (activeRanges.empty())
41 return Ranges<TimeDelta>();
43 // Step 2: Let active ranges be the ranges returned by buffered for each
44 // SourceBuffer object in activeSourceBuffers.
45 // Step 3: Let highest end time be the largest range end time in the active
46 // ranges.
47 TimeDelta highest_end_time;
48 for (RangesList::const_iterator itr = activeRanges.begin();
49 itr != activeRanges.end(); ++itr) {
50 if (!itr->size())
51 continue;
53 highest_end_time = std::max(highest_end_time, itr->end(itr->size() - 1));
56 // Step 4: Let intersection ranges equal a TimeRange object containing a
57 // single range from 0 to highest end time.
58 Ranges<TimeDelta> intersection_ranges;
59 intersection_ranges.Add(TimeDelta(), highest_end_time);
61 // Step 5: For each SourceBuffer object in activeSourceBuffers run the
62 // following steps:
63 for (RangesList::const_iterator itr = activeRanges.begin();
64 itr != activeRanges.end(); ++itr) {
65 // Step 5.1: Let source ranges equal the ranges returned by the buffered
66 // attribute on the current SourceBuffer.
67 Ranges<TimeDelta> source_ranges = *itr;
69 // Step 5.2: If readyState is "ended", then set the end time on the last
70 // range in source ranges to highest end time.
71 if (ended && source_ranges.size() > 0u) {
72 source_ranges.Add(source_ranges.start(source_ranges.size() - 1),
73 highest_end_time);
76 // Step 5.3: Let new intersection ranges equal the intersection between
77 // the intersection ranges and the source ranges.
78 // Step 5.4: Replace the ranges in intersection ranges with the new
79 // intersection ranges.
80 intersection_ranges = intersection_ranges.IntersectionWith(source_ranges);
83 return intersection_ranges;
86 // Contains state belonging to a source id.
87 class SourceState {
88 public:
89 // Callback signature used to create ChunkDemuxerStreams.
90 typedef base::Callback<ChunkDemuxerStream*(
91 DemuxerStream::Type)> CreateDemuxerStreamCB;
93 typedef ChunkDemuxer::InitSegmentReceivedCB InitSegmentReceivedCB;
95 typedef base::Callback<void(
96 ChunkDemuxerStream*, const TextTrackConfig&)> NewTextTrackCB;
98 SourceState(
99 scoped_ptr<StreamParser> stream_parser,
100 scoped_ptr<FrameProcessor> frame_processor, const LogCB& log_cb,
101 const CreateDemuxerStreamCB& create_demuxer_stream_cb,
102 const scoped_refptr<MediaLog>& media_log);
104 ~SourceState();
106 void Init(const StreamParser::InitCB& init_cb,
107 bool allow_audio,
108 bool allow_video,
109 const StreamParser::EncryptedMediaInitDataCB&
110 encrypted_media_init_data_cb,
111 const NewTextTrackCB& new_text_track_cb);
113 // Appends new data to the StreamParser.
114 // Returns true if the data was successfully appended. Returns false if an
115 // error occurred. |*timestamp_offset| is used and possibly updated by the
116 // append. |append_window_start| and |append_window_end| correspond to the MSE
117 // spec's similarly named source buffer attributes that are used in coded
118 // frame processing. |init_segment_received_cb| is run for each new fully
119 // parsed initialization segment.
120 bool Append(const uint8* data,
121 size_t length,
122 TimeDelta append_window_start,
123 TimeDelta append_window_end,
124 TimeDelta* timestamp_offset,
125 const InitSegmentReceivedCB& init_segment_received_cb);
127 // Aborts the current append sequence and resets the parser.
128 void Abort(TimeDelta append_window_start,
129 TimeDelta append_window_end,
130 TimeDelta* timestamp_offset);
132 // Calls Remove(|start|, |end|, |duration|) on all
133 // ChunkDemuxerStreams managed by this object.
134 void Remove(TimeDelta start, TimeDelta end, TimeDelta duration);
136 // Returns true if currently parsing a media segment, or false otherwise.
137 bool parsing_media_segment() const { return parsing_media_segment_; }
139 // Sets |frame_processor_|'s sequence mode to |sequence_mode|.
140 void SetSequenceMode(bool sequence_mode);
142 // Signals the coded frame processor to update its group start timestamp to be
143 // |timestamp_offset| if it is in sequence append mode.
144 void SetGroupStartTimestampIfInSequenceMode(base::TimeDelta timestamp_offset);
146 // Returns the range of buffered data in this source, capped at |duration|.
147 // |ended| - Set to true if end of stream has been signaled and the special
148 // end of stream range logic needs to be executed.
149 Ranges<TimeDelta> GetBufferedRanges(TimeDelta duration, bool ended) const;
151 // Returns the highest buffered duration across all streams managed
152 // by this object.
153 // Returns TimeDelta() if none of the streams contain buffered data.
154 TimeDelta GetMaxBufferedDuration() const;
156 // Helper methods that call methods with similar names on all the
157 // ChunkDemuxerStreams managed by this object.
158 void StartReturningData();
159 void AbortReads();
160 void Seek(TimeDelta seek_time);
161 void CompletePendingReadIfPossible();
162 void OnSetDuration(TimeDelta duration);
163 void MarkEndOfStream();
164 void UnmarkEndOfStream();
165 void Shutdown();
166 // Sets the memory limit on each stream of a specific type.
167 // |memory_limit| is the maximum number of bytes each stream of type |type|
168 // is allowed to hold in its buffer.
169 void SetMemoryLimits(DemuxerStream::Type type, int memory_limit);
170 bool IsSeekWaitingForData() const;
172 private:
173 // Called by the |stream_parser_| when a new initialization segment is
174 // encountered.
175 // Returns true on a successful call. Returns false if an error occurred while
176 // processing decoder configurations.
177 bool OnNewConfigs(bool allow_audio, bool allow_video,
178 const AudioDecoderConfig& audio_config,
179 const VideoDecoderConfig& video_config,
180 const StreamParser::TextTrackConfigMap& text_configs);
182 // Called by the |stream_parser_| at the beginning of a new media segment.
183 void OnNewMediaSegment();
185 // Called by the |stream_parser_| at the end of a media segment.
186 void OnEndOfMediaSegment();
188 // Called by the |stream_parser_| when new buffers have been parsed.
189 // It processes the new buffers using |frame_processor_|, which includes
190 // appending the processed frames to associated demuxer streams for each
191 // frame's track.
192 // Returns true on a successful call. Returns false if an error occurred while
193 // processing the buffers.
194 bool OnNewBuffers(const StreamParser::BufferQueue& audio_buffers,
195 const StreamParser::BufferQueue& video_buffers,
196 const StreamParser::TextBufferQueueMap& text_map);
198 void OnSourceInitDone(const StreamParser::InitParameters& params);
200 CreateDemuxerStreamCB create_demuxer_stream_cb_;
201 NewTextTrackCB new_text_track_cb_;
203 // During Append(), if OnNewBuffers() coded frame processing updates the
204 // timestamp offset then |*timestamp_offset_during_append_| is also updated
205 // so Append()'s caller can know the new offset. This pointer is only non-NULL
206 // during the lifetime of an Append() call.
207 TimeDelta* timestamp_offset_during_append_;
209 // During Append(), coded frame processing triggered by OnNewBuffers()
210 // requires these two attributes. These are only valid during the lifetime of
211 // an Append() call.
212 TimeDelta append_window_start_during_append_;
213 TimeDelta append_window_end_during_append_;
215 // Set to true if the next buffers appended within the append window
216 // represent the start of a new media segment. This flag being set
217 // triggers a call to |new_segment_cb_| when the new buffers are
218 // appended. The flag is set on actual media segment boundaries and
219 // when the "append window" filtering causes discontinuities in the
220 // appended data.
221 // TODO(wolenetz/acolwell): Investigate if we need this, or if coded frame
222 // processing's discontinuity logic is enough. See http://crbug.com/351489.
223 bool new_media_segment_;
225 // Keeps track of whether a media segment is being parsed.
226 bool parsing_media_segment_;
228 // The object used to parse appended data.
229 scoped_ptr<StreamParser> stream_parser_;
231 ChunkDemuxerStream* audio_; // Not owned by |this|.
232 ChunkDemuxerStream* video_; // Not owned by |this|.
234 typedef std::map<StreamParser::TrackId, ChunkDemuxerStream*> TextStreamMap;
235 TextStreamMap text_stream_map_; // |this| owns the map's stream pointers.
237 scoped_ptr<FrameProcessor> frame_processor_;
238 LogCB log_cb_;
239 scoped_refptr<MediaLog> media_log_;
240 StreamParser::InitCB init_cb_;
242 // During Append(), OnNewConfigs() will trigger the initialization segment
243 // received algorithm. This callback is only non-NULL during the lifetime of
244 // an Append() call. Note, the MSE spec explicitly disallows this algorithm
245 // during an Abort(), since Abort() is allowed only to emit coded frames, and
246 // only if the parser is PARSING_MEDIA_SEGMENT (not an INIT segment).
247 InitSegmentReceivedCB init_segment_received_cb_;
249 // Indicates that timestampOffset should be updated automatically during
250 // OnNewBuffers() based on the earliest end timestamp of the buffers provided.
251 // TODO(wolenetz): Refactor this function while integrating April 29, 2014
252 // changes to MSE spec. See http://crbug.com/371499.
253 bool auto_update_timestamp_offset_;
255 DISALLOW_COPY_AND_ASSIGN(SourceState);
258 SourceState::SourceState(scoped_ptr<StreamParser> stream_parser,
259 scoped_ptr<FrameProcessor> frame_processor,
260 const LogCB& log_cb,
261 const CreateDemuxerStreamCB& create_demuxer_stream_cb,
262 const scoped_refptr<MediaLog>& media_log)
263 : create_demuxer_stream_cb_(create_demuxer_stream_cb),
264 timestamp_offset_during_append_(NULL),
265 new_media_segment_(false),
266 parsing_media_segment_(false),
267 stream_parser_(stream_parser.release()),
268 audio_(NULL),
269 video_(NULL),
270 frame_processor_(frame_processor.release()),
271 log_cb_(log_cb),
272 media_log_(media_log),
273 auto_update_timestamp_offset_(false) {
274 DCHECK(!create_demuxer_stream_cb_.is_null());
275 DCHECK(frame_processor_);
278 SourceState::~SourceState() {
279 Shutdown();
281 STLDeleteValues(&text_stream_map_);
284 void SourceState::Init(
285 const StreamParser::InitCB& init_cb,
286 bool allow_audio,
287 bool allow_video,
288 const StreamParser::EncryptedMediaInitDataCB& encrypted_media_init_data_cb,
289 const NewTextTrackCB& new_text_track_cb) {
290 new_text_track_cb_ = new_text_track_cb;
291 init_cb_ = init_cb;
293 stream_parser_->Init(
294 base::Bind(&SourceState::OnSourceInitDone, base::Unretained(this)),
295 base::Bind(&SourceState::OnNewConfigs, base::Unretained(this),
296 allow_audio, allow_video),
297 base::Bind(&SourceState::OnNewBuffers, base::Unretained(this)),
298 new_text_track_cb_.is_null(), encrypted_media_init_data_cb,
299 base::Bind(&SourceState::OnNewMediaSegment, base::Unretained(this)),
300 base::Bind(&SourceState::OnEndOfMediaSegment, base::Unretained(this)),
301 log_cb_);
304 void SourceState::SetSequenceMode(bool sequence_mode) {
305 DCHECK(!parsing_media_segment_);
307 frame_processor_->SetSequenceMode(sequence_mode);
310 void SourceState::SetGroupStartTimestampIfInSequenceMode(
311 base::TimeDelta timestamp_offset) {
312 DCHECK(!parsing_media_segment_);
314 frame_processor_->SetGroupStartTimestampIfInSequenceMode(timestamp_offset);
317 bool SourceState::Append(
318 const uint8* data,
319 size_t length,
320 TimeDelta append_window_start,
321 TimeDelta append_window_end,
322 TimeDelta* timestamp_offset,
323 const InitSegmentReceivedCB& init_segment_received_cb) {
324 DCHECK(timestamp_offset);
325 DCHECK(!timestamp_offset_during_append_);
326 DCHECK(!init_segment_received_cb.is_null());
327 DCHECK(init_segment_received_cb_.is_null());
328 append_window_start_during_append_ = append_window_start;
329 append_window_end_during_append_ = append_window_end;
330 timestamp_offset_during_append_ = timestamp_offset;
331 init_segment_received_cb_= init_segment_received_cb;
333 // TODO(wolenetz/acolwell): Curry and pass a NewBuffersCB here bound with
334 // append window and timestamp offset pointer. See http://crbug.com/351454.
335 bool result = stream_parser_->Parse(data, length);
336 if (!result) {
337 MEDIA_LOG(log_cb_)
338 << __FUNCTION__ << ": stream parsing failed."
339 << " Data size=" << length
340 << " append_window_start=" << append_window_start.InSecondsF()
341 << " append_window_end=" << append_window_end.InSecondsF();
343 timestamp_offset_during_append_ = NULL;
344 init_segment_received_cb_.Reset();
345 return result;
348 void SourceState::Abort(TimeDelta append_window_start,
349 TimeDelta append_window_end,
350 base::TimeDelta* timestamp_offset) {
351 DCHECK(timestamp_offset);
352 DCHECK(!timestamp_offset_during_append_);
353 timestamp_offset_during_append_ = timestamp_offset;
354 append_window_start_during_append_ = append_window_start;
355 append_window_end_during_append_ = append_window_end;
357 stream_parser_->Flush();
358 timestamp_offset_during_append_ = NULL;
360 frame_processor_->Reset();
361 parsing_media_segment_ = false;
364 void SourceState::Remove(TimeDelta start, TimeDelta end, TimeDelta duration) {
365 if (audio_)
366 audio_->Remove(start, end, duration);
368 if (video_)
369 video_->Remove(start, end, duration);
371 for (TextStreamMap::iterator itr = text_stream_map_.begin();
372 itr != text_stream_map_.end(); ++itr) {
373 itr->second->Remove(start, end, duration);
377 Ranges<TimeDelta> SourceState::GetBufferedRanges(TimeDelta duration,
378 bool ended) const {
379 // TODO(acolwell): When we start allowing disabled tracks we'll need to update
380 // this code to only add ranges from active tracks.
381 RangesList ranges_list;
382 if (audio_)
383 ranges_list.push_back(audio_->GetBufferedRanges(duration));
385 if (video_)
386 ranges_list.push_back(video_->GetBufferedRanges(duration));
388 for (TextStreamMap::const_iterator itr = text_stream_map_.begin();
389 itr != text_stream_map_.end(); ++itr) {
390 ranges_list.push_back(itr->second->GetBufferedRanges(duration));
393 return ComputeIntersection(ranges_list, ended);
396 TimeDelta SourceState::GetMaxBufferedDuration() const {
397 TimeDelta max_duration;
399 if (audio_)
400 max_duration = std::max(max_duration, audio_->GetBufferedDuration());
402 if (video_)
403 max_duration = std::max(max_duration, video_->GetBufferedDuration());
405 for (TextStreamMap::const_iterator itr = text_stream_map_.begin();
406 itr != text_stream_map_.end(); ++itr) {
407 max_duration = std::max(max_duration, itr->second->GetBufferedDuration());
410 return max_duration;
413 void SourceState::StartReturningData() {
414 if (audio_)
415 audio_->StartReturningData();
417 if (video_)
418 video_->StartReturningData();
420 for (TextStreamMap::iterator itr = text_stream_map_.begin();
421 itr != text_stream_map_.end(); ++itr) {
422 itr->second->StartReturningData();
426 void SourceState::AbortReads() {
427 if (audio_)
428 audio_->AbortReads();
430 if (video_)
431 video_->AbortReads();
433 for (TextStreamMap::iterator itr = text_stream_map_.begin();
434 itr != text_stream_map_.end(); ++itr) {
435 itr->second->AbortReads();
439 void SourceState::Seek(TimeDelta seek_time) {
440 if (audio_)
441 audio_->Seek(seek_time);
443 if (video_)
444 video_->Seek(seek_time);
446 for (TextStreamMap::iterator itr = text_stream_map_.begin();
447 itr != text_stream_map_.end(); ++itr) {
448 itr->second->Seek(seek_time);
452 void SourceState::CompletePendingReadIfPossible() {
453 if (audio_)
454 audio_->CompletePendingReadIfPossible();
456 if (video_)
457 video_->CompletePendingReadIfPossible();
459 for (TextStreamMap::iterator itr = text_stream_map_.begin();
460 itr != text_stream_map_.end(); ++itr) {
461 itr->second->CompletePendingReadIfPossible();
465 void SourceState::OnSetDuration(TimeDelta duration) {
466 if (audio_)
467 audio_->OnSetDuration(duration);
469 if (video_)
470 video_->OnSetDuration(duration);
472 for (TextStreamMap::iterator itr = text_stream_map_.begin();
473 itr != text_stream_map_.end(); ++itr) {
474 itr->second->OnSetDuration(duration);
478 void SourceState::MarkEndOfStream() {
479 if (audio_)
480 audio_->MarkEndOfStream();
482 if (video_)
483 video_->MarkEndOfStream();
485 for (TextStreamMap::iterator itr = text_stream_map_.begin();
486 itr != text_stream_map_.end(); ++itr) {
487 itr->second->MarkEndOfStream();
491 void SourceState::UnmarkEndOfStream() {
492 if (audio_)
493 audio_->UnmarkEndOfStream();
495 if (video_)
496 video_->UnmarkEndOfStream();
498 for (TextStreamMap::iterator itr = text_stream_map_.begin();
499 itr != text_stream_map_.end(); ++itr) {
500 itr->second->UnmarkEndOfStream();
504 void SourceState::Shutdown() {
505 if (audio_)
506 audio_->Shutdown();
508 if (video_)
509 video_->Shutdown();
511 for (TextStreamMap::iterator itr = text_stream_map_.begin();
512 itr != text_stream_map_.end(); ++itr) {
513 itr->second->Shutdown();
517 void SourceState::SetMemoryLimits(DemuxerStream::Type type, int memory_limit) {
518 switch (type) {
519 case DemuxerStream::AUDIO:
520 if (audio_)
521 audio_->set_memory_limit(memory_limit);
522 break;
523 case DemuxerStream::VIDEO:
524 if (video_)
525 video_->set_memory_limit(memory_limit);
526 break;
527 case DemuxerStream::TEXT:
528 for (TextStreamMap::iterator itr = text_stream_map_.begin();
529 itr != text_stream_map_.end(); ++itr) {
530 itr->second->set_memory_limit(memory_limit);
532 break;
533 case DemuxerStream::UNKNOWN:
534 case DemuxerStream::NUM_TYPES:
535 NOTREACHED();
536 break;
540 bool SourceState::IsSeekWaitingForData() const {
541 if (audio_ && audio_->IsSeekWaitingForData())
542 return true;
544 if (video_ && video_->IsSeekWaitingForData())
545 return true;
547 // NOTE: We are intentionally not checking the text tracks
548 // because text tracks are discontinuous and may not have data
549 // for the seek position. This is ok and playback should not be
550 // stalled because we don't have cues. If cues, with timestamps after
551 // the seek time, eventually arrive they will be delivered properly
552 // in response to ChunkDemuxerStream::Read() calls.
554 return false;
557 bool SourceState::OnNewConfigs(
558 bool allow_audio, bool allow_video,
559 const AudioDecoderConfig& audio_config,
560 const VideoDecoderConfig& video_config,
561 const StreamParser::TextTrackConfigMap& text_configs) {
562 DVLOG(1) << "OnNewConfigs(" << allow_audio << ", " << allow_video
563 << ", " << audio_config.IsValidConfig()
564 << ", " << video_config.IsValidConfig() << ")";
565 DCHECK(!init_segment_received_cb_.is_null());
567 if (!audio_config.IsValidConfig() && !video_config.IsValidConfig()) {
568 DVLOG(1) << "OnNewConfigs() : Audio & video config are not valid!";
569 return false;
572 // Signal an error if we get configuration info for stream types that weren't
573 // specified in AddId() or more configs after a stream is initialized.
574 if (allow_audio != audio_config.IsValidConfig()) {
575 MEDIA_LOG(log_cb_)
576 << "Initialization segment"
577 << (audio_config.IsValidConfig() ? " has" : " does not have")
578 << " an audio track, but the mimetype"
579 << (allow_audio ? " specifies" : " does not specify")
580 << " an audio codec.";
581 return false;
584 if (allow_video != video_config.IsValidConfig()) {
585 MEDIA_LOG(log_cb_)
586 << "Initialization segment"
587 << (video_config.IsValidConfig() ? " has" : " does not have")
588 << " a video track, but the mimetype"
589 << (allow_video ? " specifies" : " does not specify")
590 << " a video codec.";
591 return false;
594 bool success = true;
595 if (audio_config.IsValidConfig()) {
596 if (!audio_) {
597 media_log_->SetBooleanProperty("found_audio_stream", true);
599 if (!audio_ ||
600 audio_->audio_decoder_config().codec() != audio_config.codec()) {
601 media_log_->SetStringProperty("audio_codec_name",
602 audio_config.GetHumanReadableCodecName());
605 if (!audio_) {
606 audio_ = create_demuxer_stream_cb_.Run(DemuxerStream::AUDIO);
608 if (!audio_) {
609 DVLOG(1) << "Failed to create an audio stream.";
610 return false;
613 if (!frame_processor_->AddTrack(FrameProcessor::kAudioTrackId, audio_)) {
614 DVLOG(1) << "Failed to add audio track to frame processor.";
615 return false;
619 frame_processor_->OnPossibleAudioConfigUpdate(audio_config);
620 success &= audio_->UpdateAudioConfig(audio_config, log_cb_);
623 if (video_config.IsValidConfig()) {
624 if (!video_) {
625 media_log_->SetBooleanProperty("found_video_stream", true);
627 if (!video_ ||
628 video_->video_decoder_config().codec() != video_config.codec()) {
629 media_log_->SetStringProperty("video_codec_name",
630 video_config.GetHumanReadableCodecName());
633 if (!video_) {
634 video_ = create_demuxer_stream_cb_.Run(DemuxerStream::VIDEO);
636 if (!video_) {
637 DVLOG(1) << "Failed to create a video stream.";
638 return false;
641 if (!frame_processor_->AddTrack(FrameProcessor::kVideoTrackId, video_)) {
642 DVLOG(1) << "Failed to add video track to frame processor.";
643 return false;
647 success &= video_->UpdateVideoConfig(video_config, log_cb_);
650 typedef StreamParser::TextTrackConfigMap::const_iterator TextConfigItr;
651 if (text_stream_map_.empty()) {
652 for (TextConfigItr itr = text_configs.begin();
653 itr != text_configs.end(); ++itr) {
654 ChunkDemuxerStream* const text_stream =
655 create_demuxer_stream_cb_.Run(DemuxerStream::TEXT);
656 if (!frame_processor_->AddTrack(itr->first, text_stream)) {
657 success &= false;
658 MEDIA_LOG(log_cb_) << "Failed to add text track ID " << itr->first
659 << " to frame processor.";
660 break;
662 text_stream->UpdateTextConfig(itr->second, log_cb_);
663 text_stream_map_[itr->first] = text_stream;
664 new_text_track_cb_.Run(text_stream, itr->second);
666 } else {
667 const size_t text_count = text_stream_map_.size();
668 if (text_configs.size() != text_count) {
669 success &= false;
670 MEDIA_LOG(log_cb_) << "The number of text track configs changed.";
671 } else if (text_count == 1) {
672 TextConfigItr config_itr = text_configs.begin();
673 TextStreamMap::iterator stream_itr = text_stream_map_.begin();
674 ChunkDemuxerStream* text_stream = stream_itr->second;
675 TextTrackConfig old_config = text_stream->text_track_config();
676 TextTrackConfig new_config(config_itr->second.kind(),
677 config_itr->second.label(),
678 config_itr->second.language(),
679 old_config.id());
680 if (!new_config.Matches(old_config)) {
681 success &= false;
682 MEDIA_LOG(log_cb_) << "New text track config does not match old one.";
683 } else {
684 StreamParser::TrackId old_id = stream_itr->first;
685 StreamParser::TrackId new_id = config_itr->first;
686 if (new_id != old_id) {
687 if (frame_processor_->UpdateTrack(old_id, new_id)) {
688 text_stream_map_.clear();
689 text_stream_map_[config_itr->first] = text_stream;
690 } else {
691 success &= false;
692 MEDIA_LOG(log_cb_) << "Error remapping single text track number";
696 } else {
697 for (TextConfigItr config_itr = text_configs.begin();
698 config_itr != text_configs.end(); ++config_itr) {
699 TextStreamMap::iterator stream_itr =
700 text_stream_map_.find(config_itr->first);
701 if (stream_itr == text_stream_map_.end()) {
702 success &= false;
703 MEDIA_LOG(log_cb_) << "Unexpected text track configuration "
704 "for track ID "
705 << config_itr->first;
706 break;
709 const TextTrackConfig& new_config = config_itr->second;
710 ChunkDemuxerStream* stream = stream_itr->second;
711 TextTrackConfig old_config = stream->text_track_config();
712 if (!new_config.Matches(old_config)) {
713 success &= false;
714 MEDIA_LOG(log_cb_) << "New text track config for track ID "
715 << config_itr->first
716 << " does not match old one.";
717 break;
723 frame_processor_->SetAllTrackBuffersNeedRandomAccessPoint();
725 DVLOG(1) << "OnNewConfigs() : " << (success ? "success" : "failed");
726 if (success)
727 init_segment_received_cb_.Run();
729 return success;
732 void SourceState::OnNewMediaSegment() {
733 DVLOG(2) << "OnNewMediaSegment()";
734 parsing_media_segment_ = true;
735 new_media_segment_ = true;
738 void SourceState::OnEndOfMediaSegment() {
739 DVLOG(2) << "OnEndOfMediaSegment()";
740 parsing_media_segment_ = false;
741 new_media_segment_ = false;
744 bool SourceState::OnNewBuffers(
745 const StreamParser::BufferQueue& audio_buffers,
746 const StreamParser::BufferQueue& video_buffers,
747 const StreamParser::TextBufferQueueMap& text_map) {
748 DVLOG(2) << "OnNewBuffers()";
749 DCHECK(timestamp_offset_during_append_);
750 DCHECK(parsing_media_segment_);
752 const TimeDelta timestamp_offset_before_processing =
753 *timestamp_offset_during_append_;
755 // Calculate the new timestamp offset for audio/video tracks if the stream
756 // parser has requested automatic updates.
757 TimeDelta new_timestamp_offset = timestamp_offset_before_processing;
758 if (auto_update_timestamp_offset_) {
759 const bool have_audio_buffers = !audio_buffers.empty();
760 const bool have_video_buffers = !video_buffers.empty();
761 if (have_audio_buffers && have_video_buffers) {
762 new_timestamp_offset +=
763 std::min(EndTimestamp(audio_buffers), EndTimestamp(video_buffers));
764 } else if (have_audio_buffers) {
765 new_timestamp_offset += EndTimestamp(audio_buffers);
766 } else if (have_video_buffers) {
767 new_timestamp_offset += EndTimestamp(video_buffers);
771 if (!frame_processor_->ProcessFrames(audio_buffers,
772 video_buffers,
773 text_map,
774 append_window_start_during_append_,
775 append_window_end_during_append_,
776 &new_media_segment_,
777 timestamp_offset_during_append_)) {
778 return false;
781 // Only update the timestamp offset if the frame processor hasn't already.
782 if (auto_update_timestamp_offset_ &&
783 timestamp_offset_before_processing == *timestamp_offset_during_append_) {
784 *timestamp_offset_during_append_ = new_timestamp_offset;
787 return true;
790 void SourceState::OnSourceInitDone(const StreamParser::InitParameters& params) {
791 auto_update_timestamp_offset_ = params.auto_update_timestamp_offset;
792 base::ResetAndReturn(&init_cb_).Run(params);
795 ChunkDemuxerStream::ChunkDemuxerStream(Type type,
796 Liveness liveness,
797 bool splice_frames_enabled)
798 : type_(type),
799 liveness_(liveness),
800 state_(UNINITIALIZED),
801 splice_frames_enabled_(splice_frames_enabled),
802 partial_append_window_trimming_enabled_(false) {
805 void ChunkDemuxerStream::StartReturningData() {
806 DVLOG(1) << "ChunkDemuxerStream::StartReturningData()";
807 base::AutoLock auto_lock(lock_);
808 DCHECK(read_cb_.is_null());
809 ChangeState_Locked(RETURNING_DATA_FOR_READS);
812 void ChunkDemuxerStream::AbortReads() {
813 DVLOG(1) << "ChunkDemuxerStream::AbortReads()";
814 base::AutoLock auto_lock(lock_);
815 ChangeState_Locked(RETURNING_ABORT_FOR_READS);
816 if (!read_cb_.is_null())
817 base::ResetAndReturn(&read_cb_).Run(kAborted, NULL);
820 void ChunkDemuxerStream::CompletePendingReadIfPossible() {
821 base::AutoLock auto_lock(lock_);
822 if (read_cb_.is_null())
823 return;
825 CompletePendingReadIfPossible_Locked();
828 void ChunkDemuxerStream::Shutdown() {
829 DVLOG(1) << "ChunkDemuxerStream::Shutdown()";
830 base::AutoLock auto_lock(lock_);
831 ChangeState_Locked(SHUTDOWN);
833 // Pass an end of stream buffer to the pending callback to signal that no more
834 // data will be sent.
835 if (!read_cb_.is_null()) {
836 base::ResetAndReturn(&read_cb_).Run(DemuxerStream::kOk,
837 StreamParserBuffer::CreateEOSBuffer());
841 bool ChunkDemuxerStream::IsSeekWaitingForData() const {
842 base::AutoLock auto_lock(lock_);
844 // This method should not be called for text tracks. See the note in
845 // SourceState::IsSeekWaitingForData().
846 DCHECK_NE(type_, DemuxerStream::TEXT);
848 return stream_->IsSeekPending();
851 void ChunkDemuxerStream::Seek(TimeDelta time) {
852 DVLOG(1) << "ChunkDemuxerStream::Seek(" << time.InSecondsF() << ")";
853 base::AutoLock auto_lock(lock_);
854 DCHECK(read_cb_.is_null());
855 DCHECK(state_ == UNINITIALIZED || state_ == RETURNING_ABORT_FOR_READS)
856 << state_;
858 stream_->Seek(time);
861 bool ChunkDemuxerStream::Append(const StreamParser::BufferQueue& buffers) {
862 if (buffers.empty())
863 return false;
865 base::AutoLock auto_lock(lock_);
866 DCHECK_NE(state_, SHUTDOWN);
867 if (!stream_->Append(buffers)) {
868 DVLOG(1) << "ChunkDemuxerStream::Append() : stream append failed";
869 return false;
872 if (!read_cb_.is_null())
873 CompletePendingReadIfPossible_Locked();
875 return true;
878 void ChunkDemuxerStream::Remove(TimeDelta start, TimeDelta end,
879 TimeDelta duration) {
880 base::AutoLock auto_lock(lock_);
881 stream_->Remove(start, end, duration);
884 void ChunkDemuxerStream::OnSetDuration(TimeDelta duration) {
885 base::AutoLock auto_lock(lock_);
886 stream_->OnSetDuration(duration);
889 Ranges<TimeDelta> ChunkDemuxerStream::GetBufferedRanges(
890 TimeDelta duration) const {
891 base::AutoLock auto_lock(lock_);
893 if (type_ == TEXT) {
894 // Since text tracks are discontinuous and the lack of cues should not block
895 // playback, report the buffered range for text tracks as [0, |duration|) so
896 // that intesections with audio & video tracks are computed correctly when
897 // no cues are present.
898 Ranges<TimeDelta> text_range;
899 text_range.Add(TimeDelta(), duration);
900 return text_range;
903 Ranges<TimeDelta> range = stream_->GetBufferedTime();
905 if (range.size() == 0u)
906 return range;
908 // Clamp the end of the stream's buffered ranges to fit within the duration.
909 // This can be done by intersecting the stream's range with the valid time
910 // range.
911 Ranges<TimeDelta> valid_time_range;
912 valid_time_range.Add(range.start(0), duration);
913 return range.IntersectionWith(valid_time_range);
916 TimeDelta ChunkDemuxerStream::GetBufferedDuration() const {
917 return stream_->GetBufferedDuration();
920 void ChunkDemuxerStream::OnNewMediaSegment(DecodeTimestamp start_timestamp) {
921 DVLOG(2) << "ChunkDemuxerStream::OnNewMediaSegment("
922 << start_timestamp.InSecondsF() << ")";
923 base::AutoLock auto_lock(lock_);
924 stream_->OnNewMediaSegment(start_timestamp);
927 bool ChunkDemuxerStream::UpdateAudioConfig(const AudioDecoderConfig& config,
928 const LogCB& log_cb) {
929 DCHECK(config.IsValidConfig());
930 DCHECK_EQ(type_, AUDIO);
931 base::AutoLock auto_lock(lock_);
932 if (!stream_) {
933 DCHECK_EQ(state_, UNINITIALIZED);
935 // On platforms which support splice frames, enable splice frames and
936 // partial append window support for most codecs (notably: not opus).
937 const bool codec_supported = config.codec() == kCodecMP3 ||
938 config.codec() == kCodecAAC ||
939 config.codec() == kCodecVorbis;
940 splice_frames_enabled_ = splice_frames_enabled_ && codec_supported;
941 partial_append_window_trimming_enabled_ =
942 splice_frames_enabled_ && codec_supported;
944 stream_.reset(
945 new SourceBufferStream(config, log_cb, splice_frames_enabled_));
946 return true;
949 return stream_->UpdateAudioConfig(config);
952 bool ChunkDemuxerStream::UpdateVideoConfig(const VideoDecoderConfig& config,
953 const LogCB& log_cb) {
954 DCHECK(config.IsValidConfig());
955 DCHECK_EQ(type_, VIDEO);
956 base::AutoLock auto_lock(lock_);
958 if (!stream_) {
959 DCHECK_EQ(state_, UNINITIALIZED);
960 stream_.reset(
961 new SourceBufferStream(config, log_cb, splice_frames_enabled_));
962 return true;
965 return stream_->UpdateVideoConfig(config);
968 void ChunkDemuxerStream::UpdateTextConfig(const TextTrackConfig& config,
969 const LogCB& log_cb) {
970 DCHECK_EQ(type_, TEXT);
971 base::AutoLock auto_lock(lock_);
972 DCHECK(!stream_);
973 DCHECK_EQ(state_, UNINITIALIZED);
974 stream_.reset(new SourceBufferStream(config, log_cb, splice_frames_enabled_));
977 void ChunkDemuxerStream::MarkEndOfStream() {
978 base::AutoLock auto_lock(lock_);
979 stream_->MarkEndOfStream();
982 void ChunkDemuxerStream::UnmarkEndOfStream() {
983 base::AutoLock auto_lock(lock_);
984 stream_->UnmarkEndOfStream();
987 // DemuxerStream methods.
988 void ChunkDemuxerStream::Read(const ReadCB& read_cb) {
989 base::AutoLock auto_lock(lock_);
990 DCHECK_NE(state_, UNINITIALIZED);
991 DCHECK(read_cb_.is_null());
993 read_cb_ = BindToCurrentLoop(read_cb);
994 CompletePendingReadIfPossible_Locked();
997 DemuxerStream::Type ChunkDemuxerStream::type() const { return type_; }
999 DemuxerStream::Liveness ChunkDemuxerStream::liveness() const {
1000 base::AutoLock auto_lock(lock_);
1001 return liveness_;
1004 AudioDecoderConfig ChunkDemuxerStream::audio_decoder_config() {
1005 CHECK_EQ(type_, AUDIO);
1006 base::AutoLock auto_lock(lock_);
1007 return stream_->GetCurrentAudioDecoderConfig();
1010 VideoDecoderConfig ChunkDemuxerStream::video_decoder_config() {
1011 CHECK_EQ(type_, VIDEO);
1012 base::AutoLock auto_lock(lock_);
1013 return stream_->GetCurrentVideoDecoderConfig();
1016 bool ChunkDemuxerStream::SupportsConfigChanges() { return true; }
1018 VideoRotation ChunkDemuxerStream::video_rotation() {
1019 return VIDEO_ROTATION_0;
1022 TextTrackConfig ChunkDemuxerStream::text_track_config() {
1023 CHECK_EQ(type_, TEXT);
1024 base::AutoLock auto_lock(lock_);
1025 return stream_->GetCurrentTextTrackConfig();
1028 void ChunkDemuxerStream::SetLiveness(Liveness liveness) {
1029 base::AutoLock auto_lock(lock_);
1030 liveness_ = liveness;
1033 void ChunkDemuxerStream::ChangeState_Locked(State state) {
1034 lock_.AssertAcquired();
1035 DVLOG(1) << "ChunkDemuxerStream::ChangeState_Locked() : "
1036 << "type " << type_
1037 << " - " << state_ << " -> " << state;
1038 state_ = state;
1041 ChunkDemuxerStream::~ChunkDemuxerStream() {}
1043 void ChunkDemuxerStream::CompletePendingReadIfPossible_Locked() {
1044 lock_.AssertAcquired();
1045 DCHECK(!read_cb_.is_null());
1047 DemuxerStream::Status status;
1048 scoped_refptr<StreamParserBuffer> buffer;
1050 switch (state_) {
1051 case UNINITIALIZED:
1052 NOTREACHED();
1053 return;
1054 case RETURNING_DATA_FOR_READS:
1055 switch (stream_->GetNextBuffer(&buffer)) {
1056 case SourceBufferStream::kSuccess:
1057 status = DemuxerStream::kOk;
1058 DVLOG(2) << __FUNCTION__ << ": returning kOk, type " << type_
1059 << ", dts " << buffer->GetDecodeTimestamp().InSecondsF()
1060 << ", pts " << buffer->timestamp().InSecondsF()
1061 << ", dur " << buffer->duration().InSecondsF()
1062 << ", key " << buffer->is_key_frame();
1063 break;
1064 case SourceBufferStream::kNeedBuffer:
1065 // Return early without calling |read_cb_| since we don't have
1066 // any data to return yet.
1067 DVLOG(2) << __FUNCTION__ << ": returning kNeedBuffer, type "
1068 << type_;
1069 return;
1070 case SourceBufferStream::kEndOfStream:
1071 status = DemuxerStream::kOk;
1072 buffer = StreamParserBuffer::CreateEOSBuffer();
1073 DVLOG(2) << __FUNCTION__ << ": returning kOk with EOS buffer, type "
1074 << type_;
1075 break;
1076 case SourceBufferStream::kConfigChange:
1077 status = kConfigChanged;
1078 buffer = NULL;
1079 DVLOG(2) << __FUNCTION__ << ": returning kConfigChange, type "
1080 << type_;
1081 break;
1083 break;
1084 case RETURNING_ABORT_FOR_READS:
1085 // Null buffers should be returned in this state since we are waiting
1086 // for a seek. Any buffers in the SourceBuffer should NOT be returned
1087 // because they are associated with the seek.
1088 status = DemuxerStream::kAborted;
1089 buffer = NULL;
1090 DVLOG(2) << __FUNCTION__ << ": returning kAborted, type " << type_;
1091 break;
1092 case SHUTDOWN:
1093 status = DemuxerStream::kOk;
1094 buffer = StreamParserBuffer::CreateEOSBuffer();
1095 DVLOG(2) << __FUNCTION__ << ": returning kOk with EOS buffer, type "
1096 << type_;
1097 break;
1100 base::ResetAndReturn(&read_cb_).Run(status, buffer);
1103 ChunkDemuxer::ChunkDemuxer(
1104 const base::Closure& open_cb,
1105 const EncryptedMediaInitDataCB& encrypted_media_init_data_cb,
1106 const LogCB& log_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 log_cb_(log_cb),
1116 media_log_(media_log),
1117 duration_(kNoTimestamp()),
1118 user_specified_duration_(-1),
1119 liveness_(DemuxerStream::LIVENESS_UNKNOWN),
1120 splice_frames_enabled_(splice_frames_enabled) {
1121 DCHECK(!open_cb_.is_null());
1122 DCHECK(!encrypted_media_init_data_cb_.is_null());
1125 void ChunkDemuxer::Initialize(
1126 DemuxerHost* host,
1127 const PipelineStatusCB& cb,
1128 bool enable_text_tracks) {
1129 DVLOG(1) << "Init()";
1131 base::AutoLock auto_lock(lock_);
1133 // The |init_cb_| must only be run after this method returns, so always post.
1134 init_cb_ = BindToCurrentLoop(cb);
1135 if (state_ == SHUTDOWN) {
1136 base::ResetAndReturn(&init_cb_).Run(DEMUXER_ERROR_COULD_NOT_OPEN);
1137 return;
1139 DCHECK_EQ(state_, WAITING_FOR_INIT);
1140 host_ = host;
1141 enable_text_ = enable_text_tracks;
1143 ChangeState_Locked(INITIALIZING);
1145 base::ResetAndReturn(&open_cb_).Run();
1148 void ChunkDemuxer::Stop() {
1149 DVLOG(1) << "Stop()";
1150 Shutdown();
1153 void ChunkDemuxer::Seek(TimeDelta time, const PipelineStatusCB& cb) {
1154 DVLOG(1) << "Seek(" << time.InSecondsF() << ")";
1155 DCHECK(time >= TimeDelta());
1157 base::AutoLock auto_lock(lock_);
1158 DCHECK(seek_cb_.is_null());
1160 seek_cb_ = BindToCurrentLoop(cb);
1161 if (state_ != INITIALIZED && state_ != ENDED) {
1162 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_ERROR_INVALID_STATE);
1163 return;
1166 if (cancel_next_seek_) {
1167 cancel_next_seek_ = false;
1168 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1169 return;
1172 SeekAllSources(time);
1173 StartReturningData();
1175 if (IsSeekWaitingForData_Locked()) {
1176 DVLOG(1) << "Seek() : waiting for more data to arrive.";
1177 return;
1180 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1183 // Demuxer implementation.
1184 base::Time ChunkDemuxer::GetTimelineOffset() const {
1185 return timeline_offset_;
1188 DemuxerStream* ChunkDemuxer::GetStream(DemuxerStream::Type type) {
1189 DCHECK_NE(type, DemuxerStream::TEXT);
1190 base::AutoLock auto_lock(lock_);
1191 if (type == DemuxerStream::VIDEO)
1192 return video_.get();
1194 if (type == DemuxerStream::AUDIO)
1195 return audio_.get();
1197 return NULL;
1200 TimeDelta ChunkDemuxer::GetStartTime() const {
1201 return TimeDelta();
1204 void ChunkDemuxer::StartWaitingForSeek(TimeDelta seek_time) {
1205 DVLOG(1) << "StartWaitingForSeek()";
1206 base::AutoLock auto_lock(lock_);
1207 DCHECK(state_ == INITIALIZED || state_ == ENDED || state_ == SHUTDOWN ||
1208 state_ == PARSE_ERROR) << state_;
1209 DCHECK(seek_cb_.is_null());
1211 if (state_ == SHUTDOWN || state_ == PARSE_ERROR)
1212 return;
1214 AbortPendingReads();
1215 SeekAllSources(seek_time);
1217 // Cancel state set in CancelPendingSeek() since we want to
1218 // accept the next Seek().
1219 cancel_next_seek_ = false;
1222 void ChunkDemuxer::CancelPendingSeek(TimeDelta seek_time) {
1223 base::AutoLock auto_lock(lock_);
1224 DCHECK_NE(state_, INITIALIZING);
1225 DCHECK(seek_cb_.is_null() || IsSeekWaitingForData_Locked());
1227 if (cancel_next_seek_)
1228 return;
1230 AbortPendingReads();
1231 SeekAllSources(seek_time);
1233 if (seek_cb_.is_null()) {
1234 cancel_next_seek_ = true;
1235 return;
1238 base::ResetAndReturn(&seek_cb_).Run(PIPELINE_OK);
1241 ChunkDemuxer::Status ChunkDemuxer::AddId(const std::string& id,
1242 const std::string& type,
1243 std::vector<std::string>& codecs) {
1244 base::AutoLock auto_lock(lock_);
1246 if ((state_ != WAITING_FOR_INIT && state_ != INITIALIZING) || IsValidId(id))
1247 return kReachedIdLimit;
1249 bool has_audio = false;
1250 bool has_video = false;
1251 scoped_ptr<media::StreamParser> stream_parser(
1252 StreamParserFactory::Create(type, codecs, log_cb_,
1253 &has_audio, &has_video));
1255 if (!stream_parser)
1256 return ChunkDemuxer::kNotSupported;
1258 if ((has_audio && !source_id_audio_.empty()) ||
1259 (has_video && !source_id_video_.empty()))
1260 return kReachedIdLimit;
1262 if (has_audio)
1263 source_id_audio_ = id;
1265 if (has_video)
1266 source_id_video_ = id;
1268 scoped_ptr<FrameProcessor> frame_processor(
1269 new FrameProcessor(base::Bind(&ChunkDemuxer::IncreaseDurationIfNecessary,
1270 base::Unretained(this))));
1272 scoped_ptr<SourceState> source_state(
1273 new SourceState(stream_parser.Pass(),
1274 frame_processor.Pass(), log_cb_,
1275 base::Bind(&ChunkDemuxer::CreateDemuxerStream,
1276 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(log_cb_)
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 (liveness_ != DemuxerStream::LIVENESS_UNKNOWN &&
1671 params.liveness != liveness_) {
1672 MEDIA_LOG(log_cb_)
1673 << "Liveness is not the same across all SourceBuffers.";
1674 ReportError_Locked(DEMUXER_ERROR_COULD_NOT_OPEN);
1675 return;
1678 if (liveness_ != params.liveness) {
1679 liveness_ = params.liveness;
1680 if (audio_)
1681 audio_->SetLiveness(liveness_);
1682 if (video_)
1683 video_->SetLiveness(liveness_);
1687 // Wait until all streams have initialized.
1688 if ((!source_id_audio_.empty() && !audio_) ||
1689 (!source_id_video_.empty() && !video_)) {
1690 return;
1693 SeekAllSources(GetStartTime());
1694 StartReturningData();
1696 if (duration_ == kNoTimestamp())
1697 duration_ = kInfiniteDuration();
1699 // The demuxer is now initialized after the |start_timestamp_| was set.
1700 ChangeState_Locked(INITIALIZED);
1701 base::ResetAndReturn(&init_cb_).Run(PIPELINE_OK);
1704 ChunkDemuxerStream*
1705 ChunkDemuxer::CreateDemuxerStream(DemuxerStream::Type type) {
1706 switch (type) {
1707 case DemuxerStream::AUDIO:
1708 if (audio_)
1709 return NULL;
1710 audio_.reset(new ChunkDemuxerStream(DemuxerStream::AUDIO, liveness_,
1711 splice_frames_enabled_));
1712 return audio_.get();
1713 break;
1714 case DemuxerStream::VIDEO:
1715 if (video_)
1716 return NULL;
1717 video_.reset(new ChunkDemuxerStream(DemuxerStream::VIDEO, liveness_,
1718 splice_frames_enabled_));
1719 return video_.get();
1720 break;
1721 case DemuxerStream::TEXT: {
1722 return new ChunkDemuxerStream(DemuxerStream::TEXT, liveness_,
1723 splice_frames_enabled_);
1724 break;
1726 case DemuxerStream::UNKNOWN:
1727 case DemuxerStream::NUM_TYPES:
1728 NOTREACHED();
1729 return NULL;
1731 NOTREACHED();
1732 return NULL;
1735 void ChunkDemuxer::OnNewTextTrack(ChunkDemuxerStream* text_stream,
1736 const TextTrackConfig& config) {
1737 lock_.AssertAcquired();
1738 DCHECK_NE(state_, SHUTDOWN);
1739 host_->AddTextStream(text_stream, config);
1742 bool ChunkDemuxer::IsValidId(const std::string& source_id) const {
1743 lock_.AssertAcquired();
1744 return source_state_map_.count(source_id) > 0u;
1747 void ChunkDemuxer::UpdateDuration(TimeDelta new_duration) {
1748 DCHECK(duration_ != new_duration);
1749 user_specified_duration_ = -1;
1750 duration_ = new_duration;
1751 host_->SetDuration(new_duration);
1754 void ChunkDemuxer::IncreaseDurationIfNecessary(TimeDelta new_duration) {
1755 DCHECK(new_duration != kNoTimestamp());
1756 DCHECK(new_duration != kInfiniteDuration());
1758 // Per April 1, 2014 MSE spec editor's draft:
1759 // https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/
1760 // media-source.html#sourcebuffer-coded-frame-processing
1761 // 5. If the media segment contains data beyond the current duration, then run
1762 // the duration change algorithm with new duration set to the maximum of
1763 // the current duration and the group end timestamp.
1765 if (new_duration <= duration_)
1766 return;
1768 DVLOG(2) << __FUNCTION__ << ": Increasing duration: "
1769 << duration_.InSecondsF() << " -> " << new_duration.InSecondsF();
1771 UpdateDuration(new_duration);
1774 void ChunkDemuxer::DecreaseDurationIfNecessary() {
1775 lock_.AssertAcquired();
1777 TimeDelta max_duration;
1779 for (SourceStateMap::const_iterator itr = source_state_map_.begin();
1780 itr != source_state_map_.end(); ++itr) {
1781 max_duration = std::max(max_duration,
1782 itr->second->GetMaxBufferedDuration());
1785 if (max_duration == TimeDelta())
1786 return;
1788 if (max_duration < duration_)
1789 UpdateDuration(max_duration);
1792 Ranges<TimeDelta> ChunkDemuxer::GetBufferedRanges() const {
1793 base::AutoLock auto_lock(lock_);
1794 return GetBufferedRanges_Locked();
1797 Ranges<TimeDelta> ChunkDemuxer::GetBufferedRanges_Locked() const {
1798 lock_.AssertAcquired();
1800 bool ended = state_ == ENDED;
1801 // TODO(acolwell): When we start allowing SourceBuffers that are not active,
1802 // we'll need to update this loop to only add ranges from active sources.
1803 RangesList ranges_list;
1804 for (SourceStateMap::const_iterator itr = source_state_map_.begin();
1805 itr != source_state_map_.end(); ++itr) {
1806 ranges_list.push_back(itr->second->GetBufferedRanges(duration_, ended));
1809 return ComputeIntersection(ranges_list, ended);
1812 void ChunkDemuxer::StartReturningData() {
1813 for (SourceStateMap::iterator itr = source_state_map_.begin();
1814 itr != source_state_map_.end(); ++itr) {
1815 itr->second->StartReturningData();
1819 void ChunkDemuxer::AbortPendingReads() {
1820 for (SourceStateMap::iterator itr = source_state_map_.begin();
1821 itr != source_state_map_.end(); ++itr) {
1822 itr->second->AbortReads();
1826 void ChunkDemuxer::SeekAllSources(TimeDelta seek_time) {
1827 for (SourceStateMap::iterator itr = source_state_map_.begin();
1828 itr != source_state_map_.end(); ++itr) {
1829 itr->second->Seek(seek_time);
1833 void ChunkDemuxer::CompletePendingReadsIfPossible() {
1834 for (SourceStateMap::iterator itr = source_state_map_.begin();
1835 itr != source_state_map_.end(); ++itr) {
1836 itr->second->CompletePendingReadIfPossible();
1840 void ChunkDemuxer::ShutdownAllStreams() {
1841 for (SourceStateMap::iterator itr = source_state_map_.begin();
1842 itr != source_state_map_.end(); ++itr) {
1843 itr->second->Shutdown();
1847 } // namespace media