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/source_buffer_stream.h"
11 #include "base/bind.h"
12 #include "base/logging.h"
13 #include "base/trace_event/trace_event.h"
14 #include "media/base/audio_splicer.h"
15 #include "media/filters/source_buffer_platform.h"
16 #include "media/filters/source_buffer_range.h"
20 // Helper method that returns true if |ranges| is sorted in increasing order,
22 static bool IsRangeListSorted(
23 const std::list
<media::SourceBufferRange
*>& ranges
) {
24 DecodeTimestamp prev
= kNoDecodeTimestamp();
25 for (std::list
<SourceBufferRange
*>::const_iterator itr
=
26 ranges
.begin(); itr
!= ranges
.end(); ++itr
) {
27 if (prev
!= kNoDecodeTimestamp() && prev
>= (*itr
)->GetStartTimestamp())
29 prev
= (*itr
)->GetEndTimestamp();
34 // Returns an estimate of how far from the beginning or end of a range a buffer
35 // can be to still be considered in the range, given the |approximate_duration|
36 // of a buffer in the stream.
37 // TODO(wolenetz): Once all stream parsers emit accurate frame durations, use
38 // logic like FrameProcessor (2*last_frame_duration + last_decode_timestamp)
39 // instead of an overall maximum interbuffer delta for range discontinuity
40 // detection, and adjust similarly for splice frame discontinuity detection.
41 // See http://crbug.com/351489 and http://crbug.com/351166.
42 static base::TimeDelta
ComputeFudgeRoom(base::TimeDelta approximate_duration
) {
43 // Because we do not know exactly when is the next timestamp, any buffer
44 // that starts within 2x the approximate duration of a buffer is considered
46 return 2 * approximate_duration
;
49 // An arbitrarily-chosen number to estimate the duration of a buffer if none
50 // is set and there's not enough information to get a better estimate.
51 static int kDefaultBufferDurationInMs
= 125;
53 // The amount of time the beginning of the buffered data can differ from the
54 // start time in order to still be considered the start of stream.
55 static base::TimeDelta
kSeekToStartFudgeRoom() {
56 return base::TimeDelta::FromMilliseconds(1000);
59 // Helper method for logging, converts a range into a readable string.
60 static std::string
RangeToString(const SourceBufferRange
& range
) {
62 ss
<< "[" << range
.GetStartTimestamp().InSecondsF()
63 << ";" << range
.GetEndTimestamp().InSecondsF()
64 << "(" << range
.GetBufferedEndTimestamp().InSecondsF() << ")]";
68 // Helper method for logging, converts a set of ranges into a readable string.
69 static std::string
RangesToString(const SourceBufferStream::RangeList
& ranges
) {
74 for (const auto* range_ptr
: ranges
) {
75 if (range_ptr
!= ranges
.front())
77 ss
<< RangeToString(*range_ptr
);
82 static SourceBufferRange::GapPolicy
TypeToGapPolicy(
83 SourceBufferStream::Type type
) {
85 case SourceBufferStream::kAudio
:
86 case SourceBufferStream::kVideo
:
87 return SourceBufferRange::NO_GAPS_ALLOWED
;
88 case SourceBufferStream::kText
:
89 return SourceBufferRange::ALLOW_GAPS
;
93 return SourceBufferRange::NO_GAPS_ALLOWED
;
96 SourceBufferStream::SourceBufferStream(const AudioDecoderConfig
& audio_config
,
98 bool splice_frames_enabled
)
100 current_config_index_(0),
101 append_config_index_(0),
102 seek_pending_(false),
103 end_of_stream_(false),
104 seek_buffer_timestamp_(kNoTimestamp()),
105 selected_range_(NULL
),
106 media_segment_start_time_(kNoDecodeTimestamp()),
107 range_for_next_append_(ranges_
.end()),
108 new_media_segment_(false),
109 last_appended_buffer_timestamp_(kNoDecodeTimestamp()),
110 last_appended_buffer_is_keyframe_(false),
111 last_output_buffer_timestamp_(kNoDecodeTimestamp()),
112 max_interbuffer_distance_(kNoTimestamp()),
113 memory_limit_(kSourceBufferAudioMemoryLimit
),
114 config_change_pending_(false),
115 splice_buffers_index_(0),
116 pending_buffers_complete_(false),
117 splice_frames_enabled_(splice_frames_enabled
) {
118 DCHECK(audio_config
.IsValidConfig());
119 audio_configs_
.push_back(audio_config
);
122 SourceBufferStream::SourceBufferStream(const VideoDecoderConfig
& video_config
,
124 bool splice_frames_enabled
)
126 current_config_index_(0),
127 append_config_index_(0),
128 seek_pending_(false),
129 end_of_stream_(false),
130 seek_buffer_timestamp_(kNoTimestamp()),
131 selected_range_(NULL
),
132 media_segment_start_time_(kNoDecodeTimestamp()),
133 range_for_next_append_(ranges_
.end()),
134 new_media_segment_(false),
135 last_appended_buffer_timestamp_(kNoDecodeTimestamp()),
136 last_appended_buffer_is_keyframe_(false),
137 last_output_buffer_timestamp_(kNoDecodeTimestamp()),
138 max_interbuffer_distance_(kNoTimestamp()),
139 memory_limit_(kSourceBufferVideoMemoryLimit
),
140 config_change_pending_(false),
141 splice_buffers_index_(0),
142 pending_buffers_complete_(false),
143 splice_frames_enabled_(splice_frames_enabled
) {
144 DCHECK(video_config
.IsValidConfig());
145 video_configs_
.push_back(video_config
);
148 SourceBufferStream::SourceBufferStream(const TextTrackConfig
& text_config
,
150 bool splice_frames_enabled
)
152 current_config_index_(0),
153 append_config_index_(0),
154 text_track_config_(text_config
),
155 seek_pending_(false),
156 end_of_stream_(false),
157 seek_buffer_timestamp_(kNoTimestamp()),
158 selected_range_(NULL
),
159 media_segment_start_time_(kNoDecodeTimestamp()),
160 range_for_next_append_(ranges_
.end()),
161 new_media_segment_(false),
162 last_appended_buffer_timestamp_(kNoDecodeTimestamp()),
163 last_appended_buffer_is_keyframe_(false),
164 last_output_buffer_timestamp_(kNoDecodeTimestamp()),
165 max_interbuffer_distance_(kNoTimestamp()),
166 memory_limit_(kSourceBufferAudioMemoryLimit
),
167 config_change_pending_(false),
168 splice_buffers_index_(0),
169 pending_buffers_complete_(false),
170 splice_frames_enabled_(splice_frames_enabled
) {}
172 SourceBufferStream::~SourceBufferStream() {
173 while (!ranges_
.empty()) {
174 delete ranges_
.front();
179 void SourceBufferStream::OnNewMediaSegment(
180 DecodeTimestamp media_segment_start_time
) {
181 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
182 << " (" << media_segment_start_time
.InSecondsF() << ")";
183 DCHECK(!end_of_stream_
);
184 media_segment_start_time_
= media_segment_start_time
;
185 new_media_segment_
= true;
187 RangeList::iterator last_range
= range_for_next_append_
;
188 range_for_next_append_
= FindExistingRangeFor(media_segment_start_time
);
190 // Only reset |last_appended_buffer_timestamp_| if this new media segment is
191 // not adjacent to the previous media segment appended to the stream.
192 if (range_for_next_append_
== ranges_
.end() ||
193 !AreAdjacentInSequence(last_appended_buffer_timestamp_
,
194 media_segment_start_time
)) {
195 last_appended_buffer_timestamp_
= kNoDecodeTimestamp();
196 last_appended_buffer_is_keyframe_
= false;
197 DVLOG(3) << __FUNCTION__
<< " next appended buffers will be in a new range";
198 } else if (last_range
!= ranges_
.end()) {
199 DCHECK(last_range
== range_for_next_append_
);
200 DVLOG(3) << __FUNCTION__
<< " next appended buffers will continue range "
201 << "unless intervening remove makes discontinuity";
205 bool SourceBufferStream::Append(const BufferQueue
& buffers
) {
206 TRACE_EVENT2("media", "SourceBufferStream::Append",
207 "stream type", GetStreamTypeName(),
208 "buffers to append", buffers
.size());
210 DCHECK(!buffers
.empty());
211 DCHECK(media_segment_start_time_
!= kNoDecodeTimestamp());
212 DCHECK(media_segment_start_time_
<= buffers
.front()->GetDecodeTimestamp());
213 DCHECK(!end_of_stream_
);
215 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName() << ": buffers dts=["
216 << buffers
.front()->GetDecodeTimestamp().InSecondsF() << ";"
217 << buffers
.back()->GetDecodeTimestamp().InSecondsF() << "] pts=["
218 << buffers
.front()->timestamp().InSecondsF() << ";"
219 << buffers
.back()->timestamp().InSecondsF() << "(last frame dur="
220 << buffers
.back()->duration().InSecondsF() << ")]";
222 // New media segments must begin with a keyframe.
223 if (new_media_segment_
&& !buffers
.front()->is_key_frame()) {
224 MEDIA_LOG(log_cb_
) << "Media segment did not begin with key frame.";
228 // Buffers within a media segment should be monotonically increasing.
229 if (!IsMonotonicallyIncreasing(buffers
))
232 if (media_segment_start_time_
< DecodeTimestamp() ||
233 buffers
.front()->GetDecodeTimestamp() < DecodeTimestamp()) {
235 << "Cannot append a media segment with negative timestamps.";
239 if (!IsNextTimestampValid(buffers
.front()->GetDecodeTimestamp(),
240 buffers
.front()->is_key_frame())) {
241 MEDIA_LOG(log_cb_
) << "Invalid same timestamp construct detected at time "
242 << buffers
.front()->GetDecodeTimestamp().InSecondsF();
247 UpdateMaxInterbufferDistance(buffers
);
248 SetConfigIds(buffers
);
250 // Save a snapshot of stream state before range modifications are made.
251 DecodeTimestamp next_buffer_timestamp
= GetNextBufferTimestamp();
252 BufferQueue deleted_buffers
;
254 PrepareRangesForNextAppend(buffers
, &deleted_buffers
);
256 // If there's a range for |buffers|, insert |buffers| accordingly. Otherwise,
257 // create a new range with |buffers|.
258 if (range_for_next_append_
!= ranges_
.end()) {
259 (*range_for_next_append_
)->AppendBuffersToEnd(buffers
);
260 last_appended_buffer_timestamp_
= buffers
.back()->GetDecodeTimestamp();
261 last_appended_buffer_is_keyframe_
= buffers
.back()->is_key_frame();
263 DecodeTimestamp new_range_start_time
= std::min(
264 media_segment_start_time_
, buffers
.front()->GetDecodeTimestamp());
265 const BufferQueue
* buffers_for_new_range
= &buffers
;
266 BufferQueue trimmed_buffers
;
268 // If the new range is not being created because of a new media
269 // segment, then we must make sure that we start with a key frame.
270 // This can happen if the GOP in the previous append gets destroyed
271 // by a Remove() call.
272 if (!new_media_segment_
) {
273 BufferQueue::const_iterator itr
= buffers
.begin();
275 // Scan past all the non-key-frames.
276 while (itr
!= buffers
.end() && !(*itr
)->is_key_frame()) {
280 // If we didn't find a key frame, then update the last appended
281 // buffer state and return.
282 if (itr
== buffers
.end()) {
283 last_appended_buffer_timestamp_
= buffers
.back()->GetDecodeTimestamp();
284 last_appended_buffer_is_keyframe_
= buffers
.back()->is_key_frame();
285 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
286 << ": new buffers in the middle of media segment depend on"
287 "keyframe that has been removed, and contain no keyframes."
288 "Skipping further processing.";
289 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
290 << ": done. ranges_=" << RangesToString(ranges_
);
292 } else if (itr
!= buffers
.begin()) {
293 // Copy the first key frame and everything after it into
294 // |trimmed_buffers|.
295 trimmed_buffers
.assign(itr
, buffers
.end());
296 buffers_for_new_range
= &trimmed_buffers
;
299 new_range_start_time
=
300 buffers_for_new_range
->front()->GetDecodeTimestamp();
303 range_for_next_append_
=
304 AddToRanges(new SourceBufferRange(
305 TypeToGapPolicy(GetType()),
306 *buffers_for_new_range
, new_range_start_time
,
307 base::Bind(&SourceBufferStream::GetMaxInterbufferDistance
,
308 base::Unretained(this))));
309 last_appended_buffer_timestamp_
=
310 buffers_for_new_range
->back()->GetDecodeTimestamp();
311 last_appended_buffer_is_keyframe_
=
312 buffers_for_new_range
->back()->is_key_frame();
315 new_media_segment_
= false;
317 MergeWithAdjacentRangeIfNecessary(range_for_next_append_
);
319 // Seek to try to fulfill a previous call to Seek().
321 DCHECK(!selected_range_
);
322 DCHECK(deleted_buffers
.empty());
323 Seek(seek_buffer_timestamp_
);
326 if (!deleted_buffers
.empty()) {
327 DecodeTimestamp start_of_deleted
=
328 deleted_buffers
.front()->GetDecodeTimestamp();
330 DCHECK(track_buffer_
.empty() ||
331 track_buffer_
.back()->GetDecodeTimestamp() < start_of_deleted
)
332 << "decode timestamp "
333 << track_buffer_
.back()->GetDecodeTimestamp().InSecondsF() << " sec"
334 << ", start_of_deleted " << start_of_deleted
.InSecondsF()<< " sec";
336 track_buffer_
.insert(track_buffer_
.end(), deleted_buffers
.begin(),
337 deleted_buffers
.end());
340 // Prune any extra buffers in |track_buffer_| if new keyframes
341 // are appended to the range covered by |track_buffer_|.
342 if (!track_buffer_
.empty()) {
343 DecodeTimestamp keyframe_timestamp
=
344 FindKeyframeAfterTimestamp(track_buffer_
.front()->GetDecodeTimestamp());
345 if (keyframe_timestamp
!= kNoDecodeTimestamp())
346 PruneTrackBuffer(keyframe_timestamp
);
349 SetSelectedRangeIfNeeded(next_buffer_timestamp
);
351 GarbageCollectIfNeeded();
353 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
354 << ": done. ranges_=" << RangesToString(ranges_
);
355 DCHECK(IsRangeListSorted(ranges_
));
356 DCHECK(OnlySelectedRangeIsSeeked());
360 void SourceBufferStream::Remove(base::TimeDelta start
, base::TimeDelta end
,
361 base::TimeDelta duration
) {
362 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
363 << " (" << start
.InSecondsF() << ", " << end
.InSecondsF()
364 << ", " << duration
.InSecondsF() << ")";
365 DCHECK(start
>= base::TimeDelta()) << start
.InSecondsF();
366 DCHECK(start
< end
) << "start " << start
.InSecondsF()
367 << " end " << end
.InSecondsF();
368 DCHECK(duration
!= kNoTimestamp());
370 DecodeTimestamp start_dts
= DecodeTimestamp::FromPresentationTime(start
);
371 DecodeTimestamp end_dts
= DecodeTimestamp::FromPresentationTime(end
);
372 DecodeTimestamp remove_end_timestamp
=
373 DecodeTimestamp::FromPresentationTime(duration
);
374 DecodeTimestamp keyframe_timestamp
= FindKeyframeAfterTimestamp(end_dts
);
375 if (keyframe_timestamp
!= kNoDecodeTimestamp()) {
376 remove_end_timestamp
= keyframe_timestamp
;
377 } else if (end_dts
< remove_end_timestamp
) {
378 remove_end_timestamp
= end_dts
;
381 BufferQueue deleted_buffers
;
382 RemoveInternal(start_dts
, remove_end_timestamp
, false, &deleted_buffers
);
384 if (!deleted_buffers
.empty())
385 SetSelectedRangeIfNeeded(deleted_buffers
.front()->GetDecodeTimestamp());
388 void SourceBufferStream::RemoveInternal(
389 DecodeTimestamp start
, DecodeTimestamp end
, bool is_exclusive
,
390 BufferQueue
* deleted_buffers
) {
391 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
392 << " (" << start
.InSecondsF() << ", " << end
.InSecondsF()
393 << ", " << is_exclusive
<< ")";
394 DVLOG(3) << __FUNCTION__
<< " " << GetStreamTypeName()
395 << ": before remove ranges_=" << RangesToString(ranges_
);
397 DCHECK(start
>= DecodeTimestamp());
398 DCHECK(start
< end
) << "start " << start
.InSecondsF()
399 << " end " << end
.InSecondsF();
400 DCHECK(deleted_buffers
);
402 RangeList::iterator itr
= ranges_
.begin();
404 while (itr
!= ranges_
.end()) {
405 SourceBufferRange
* range
= *itr
;
406 if (range
->GetStartTimestamp() >= end
)
409 // Split off any remaining end piece and add it to |ranges_|.
410 SourceBufferRange
* new_range
= range
->SplitRange(end
, is_exclusive
);
412 itr
= ranges_
.insert(++itr
, new_range
);
415 // Update the selected range if the next buffer position was transferred
417 if (new_range
->HasNextBufferPosition())
418 SetSelectedRange(new_range
);
421 // Truncate the current range so that it only contains data before
422 // the removal range.
423 BufferQueue saved_buffers
;
424 bool delete_range
= range
->TruncateAt(start
, &saved_buffers
, is_exclusive
);
426 // Check to see if the current playback position was removed and
427 // update the selected range appropriately.
428 if (!saved_buffers
.empty()) {
429 DCHECK(!range
->HasNextBufferPosition());
430 DCHECK(deleted_buffers
->empty());
432 *deleted_buffers
= saved_buffers
;
435 if (range
== selected_range_
&& !range
->HasNextBufferPosition())
436 SetSelectedRange(NULL
);
438 // If the current range now is completely covered by the removal
439 // range then delete it and move on.
441 DeleteAndRemoveRange(&itr
);
445 // Clear |range_for_next_append_| if we determine that the removal
446 // operation makes it impossible for the next append to be added
447 // to the current range.
448 if (range_for_next_append_
!= ranges_
.end() &&
449 *range_for_next_append_
== range
&&
450 last_appended_buffer_timestamp_
!= kNoDecodeTimestamp()) {
451 DecodeTimestamp potential_next_append_timestamp
=
452 last_appended_buffer_timestamp_
+
453 base::TimeDelta::FromInternalValue(1);
455 if (!range
->BelongsToRange(potential_next_append_timestamp
)) {
456 DVLOG(1) << "Resetting range_for_next_append_ since the next append"
457 << " can't add to the current range.";
458 range_for_next_append_
=
459 FindExistingRangeFor(potential_next_append_timestamp
);
463 // Move on to the next range.
467 DVLOG(3) << __FUNCTION__
<< " " << GetStreamTypeName()
468 << ": after remove ranges_=" << RangesToString(ranges_
);
470 DCHECK(IsRangeListSorted(ranges_
));
471 DCHECK(OnlySelectedRangeIsSeeked());
474 void SourceBufferStream::ResetSeekState() {
475 SetSelectedRange(NULL
);
476 track_buffer_
.clear();
477 config_change_pending_
= false;
478 last_output_buffer_timestamp_
= kNoDecodeTimestamp();
479 splice_buffers_index_
= 0;
480 pending_buffer_
= NULL
;
481 pending_buffers_complete_
= false;
484 bool SourceBufferStream::ShouldSeekToStartOfBuffered(
485 base::TimeDelta seek_timestamp
) const {
488 base::TimeDelta beginning_of_buffered
=
489 ranges_
.front()->GetStartTimestamp().ToPresentationTime();
490 return (seek_timestamp
<= beginning_of_buffered
&&
491 beginning_of_buffered
< kSeekToStartFudgeRoom());
494 bool SourceBufferStream::IsMonotonicallyIncreasing(
495 const BufferQueue
& buffers
) const {
496 DCHECK(!buffers
.empty());
497 DecodeTimestamp prev_timestamp
= last_appended_buffer_timestamp_
;
498 bool prev_is_keyframe
= last_appended_buffer_is_keyframe_
;
499 for (BufferQueue::const_iterator itr
= buffers
.begin();
500 itr
!= buffers
.end(); ++itr
) {
501 DecodeTimestamp current_timestamp
= (*itr
)->GetDecodeTimestamp();
502 bool current_is_keyframe
= (*itr
)->is_key_frame();
503 DCHECK(current_timestamp
!= kNoDecodeTimestamp());
504 DCHECK((*itr
)->duration() >= base::TimeDelta())
505 << "Packet with invalid duration."
506 << " pts " << (*itr
)->timestamp().InSecondsF()
507 << " dts " << (*itr
)->GetDecodeTimestamp().InSecondsF()
508 << " dur " << (*itr
)->duration().InSecondsF();
510 if (prev_timestamp
!= kNoDecodeTimestamp()) {
511 if (current_timestamp
< prev_timestamp
) {
512 MEDIA_LOG(log_cb_
) << "Buffers were not monotonically increasing.";
516 if (current_timestamp
== prev_timestamp
&&
517 !SourceBufferRange::AllowSameTimestamp(prev_is_keyframe
,
518 current_is_keyframe
)) {
519 MEDIA_LOG(log_cb_
) << "Unexpected combination of buffers with the"
520 << " same timestamp detected at "
521 << current_timestamp
.InSecondsF();
526 prev_timestamp
= current_timestamp
;
527 prev_is_keyframe
= current_is_keyframe
;
532 bool SourceBufferStream::IsNextTimestampValid(
533 DecodeTimestamp next_timestamp
, bool next_is_keyframe
) const {
534 return (last_appended_buffer_timestamp_
!= next_timestamp
) ||
535 new_media_segment_
||
536 SourceBufferRange::AllowSameTimestamp(last_appended_buffer_is_keyframe_
,
541 bool SourceBufferStream::OnlySelectedRangeIsSeeked() const {
542 for (RangeList::const_iterator itr
= ranges_
.begin();
543 itr
!= ranges_
.end(); ++itr
) {
544 if ((*itr
)->HasNextBufferPosition() && (*itr
) != selected_range_
)
547 return !selected_range_
|| selected_range_
->HasNextBufferPosition();
550 void SourceBufferStream::UpdateMaxInterbufferDistance(
551 const BufferQueue
& buffers
) {
552 DCHECK(!buffers
.empty());
553 DecodeTimestamp prev_timestamp
= last_appended_buffer_timestamp_
;
554 for (BufferQueue::const_iterator itr
= buffers
.begin();
555 itr
!= buffers
.end(); ++itr
) {
556 DecodeTimestamp current_timestamp
= (*itr
)->GetDecodeTimestamp();
557 DCHECK(current_timestamp
!= kNoDecodeTimestamp());
559 base::TimeDelta interbuffer_distance
= (*itr
)->duration();
560 DCHECK(interbuffer_distance
>= base::TimeDelta());
562 if (prev_timestamp
!= kNoDecodeTimestamp()) {
563 interbuffer_distance
=
564 std::max(current_timestamp
- prev_timestamp
, interbuffer_distance
);
567 if (interbuffer_distance
> base::TimeDelta()) {
568 if (max_interbuffer_distance_
== kNoTimestamp()) {
569 max_interbuffer_distance_
= interbuffer_distance
;
571 max_interbuffer_distance_
=
572 std::max(max_interbuffer_distance_
, interbuffer_distance
);
575 prev_timestamp
= current_timestamp
;
579 void SourceBufferStream::SetConfigIds(const BufferQueue
& buffers
) {
580 for (BufferQueue::const_iterator itr
= buffers
.begin();
581 itr
!= buffers
.end(); ++itr
) {
582 (*itr
)->SetConfigId(append_config_index_
);
586 void SourceBufferStream::GarbageCollectIfNeeded() {
587 // Compute size of |ranges_|.
589 for (RangeList::iterator itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
)
590 ranges_size
+= (*itr
)->size_in_bytes();
592 // Return if we're under or at the memory limit.
593 if (ranges_size
<= memory_limit_
)
596 int bytes_to_free
= ranges_size
- memory_limit_
;
598 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName() << ": Before GC"
599 << " ranges_size=" << ranges_size
600 << " ranges_=" << RangesToString(ranges_
)
601 << " memory_limit_=" << memory_limit_
;
603 // Begin deleting after the last appended buffer.
604 int bytes_freed
= FreeBuffersAfterLastAppended(bytes_to_free
);
606 // Begin deleting from the front.
607 if (bytes_to_free
- bytes_freed
> 0)
608 bytes_freed
+= FreeBuffers(bytes_to_free
- bytes_freed
, false);
610 // Begin deleting from the back.
611 if (bytes_to_free
- bytes_freed
> 0)
612 bytes_freed
+= FreeBuffers(bytes_to_free
- bytes_freed
, true);
614 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName() << ": After GC"
615 << " bytes_freed=" << bytes_freed
616 << " ranges_=" << RangesToString(ranges_
);
619 int SourceBufferStream::FreeBuffersAfterLastAppended(int total_bytes_to_free
) {
620 DecodeTimestamp next_buffer_timestamp
= GetNextBufferTimestamp();
621 if (last_appended_buffer_timestamp_
== kNoDecodeTimestamp() ||
622 next_buffer_timestamp
== kNoDecodeTimestamp() ||
623 last_appended_buffer_timestamp_
>= next_buffer_timestamp
) {
627 DecodeTimestamp remove_range_start
= last_appended_buffer_timestamp_
;
628 if (last_appended_buffer_is_keyframe_
)
629 remove_range_start
+= GetMaxInterbufferDistance();
631 DecodeTimestamp remove_range_start_keyframe
= FindKeyframeAfterTimestamp(
633 if (remove_range_start_keyframe
!= kNoDecodeTimestamp())
634 remove_range_start
= remove_range_start_keyframe
;
635 if (remove_range_start
>= next_buffer_timestamp
)
638 DecodeTimestamp remove_range_end
;
639 int bytes_freed
= GetRemovalRange(
640 remove_range_start
, next_buffer_timestamp
, total_bytes_to_free
,
642 if (bytes_freed
> 0) {
643 Remove(remove_range_start
.ToPresentationTime(),
644 remove_range_end
.ToPresentationTime(),
645 next_buffer_timestamp
.ToPresentationTime());
651 int SourceBufferStream::GetRemovalRange(
652 DecodeTimestamp start_timestamp
, DecodeTimestamp end_timestamp
,
653 int total_bytes_to_free
, DecodeTimestamp
* removal_end_timestamp
) {
654 DCHECK(start_timestamp
>= DecodeTimestamp()) << start_timestamp
.InSecondsF();
655 DCHECK(start_timestamp
< end_timestamp
)
656 << "start " << start_timestamp
.InSecondsF()
657 << ", end " << end_timestamp
.InSecondsF();
659 int bytes_to_free
= total_bytes_to_free
;
662 for (RangeList::iterator itr
= ranges_
.begin();
663 itr
!= ranges_
.end() && bytes_to_free
> 0; ++itr
) {
664 SourceBufferRange
* range
= *itr
;
665 if (range
->GetStartTimestamp() >= end_timestamp
)
667 if (range
->GetEndTimestamp() < start_timestamp
)
670 int bytes_removed
= range
->GetRemovalGOP(
671 start_timestamp
, end_timestamp
, bytes_to_free
, removal_end_timestamp
);
672 bytes_to_free
-= bytes_removed
;
673 bytes_freed
+= bytes_removed
;
678 int SourceBufferStream::FreeBuffers(int total_bytes_to_free
,
679 bool reverse_direction
) {
680 TRACE_EVENT2("media", "SourceBufferStream::FreeBuffers",
681 "total bytes to free", total_bytes_to_free
,
682 "reverse direction", reverse_direction
);
684 DCHECK_GT(total_bytes_to_free
, 0);
685 int bytes_to_free
= total_bytes_to_free
;
688 // This range will save the last GOP appended to |range_for_next_append_|
689 // if the buffers surrounding it get deleted during garbage collection.
690 SourceBufferRange
* new_range_for_append
= NULL
;
692 while (!ranges_
.empty() && bytes_to_free
> 0) {
693 SourceBufferRange
* current_range
= NULL
;
695 int bytes_deleted
= 0;
697 if (reverse_direction
) {
698 current_range
= ranges_
.back();
699 if (current_range
->LastGOPContainsNextBufferPosition()) {
700 DCHECK_EQ(current_range
, selected_range_
);
703 bytes_deleted
= current_range
->DeleteGOPFromBack(&buffers
);
705 current_range
= ranges_
.front();
706 if (current_range
->FirstGOPContainsNextBufferPosition()) {
707 DCHECK_EQ(current_range
, selected_range_
);
710 bytes_deleted
= current_range
->DeleteGOPFromFront(&buffers
);
713 // Check to see if we've just deleted the GOP that was last appended.
714 DecodeTimestamp end_timestamp
= buffers
.back()->GetDecodeTimestamp();
715 if (end_timestamp
== last_appended_buffer_timestamp_
) {
716 DCHECK(last_appended_buffer_timestamp_
!= kNoDecodeTimestamp());
717 DCHECK(!new_range_for_append
);
718 // Create a new range containing these buffers.
719 new_range_for_append
= new SourceBufferRange(
720 TypeToGapPolicy(GetType()),
721 buffers
, kNoDecodeTimestamp(),
722 base::Bind(&SourceBufferStream::GetMaxInterbufferDistance
,
723 base::Unretained(this)));
724 range_for_next_append_
= ranges_
.end();
726 bytes_to_free
-= bytes_deleted
;
727 bytes_freed
+= bytes_deleted
;
730 if (current_range
->size_in_bytes() == 0) {
731 DCHECK_NE(current_range
, selected_range_
);
732 DCHECK(range_for_next_append_
== ranges_
.end() ||
733 *range_for_next_append_
!= current_range
);
734 delete current_range
;
735 reverse_direction
? ranges_
.pop_back() : ranges_
.pop_front();
739 // Insert |new_range_for_append| into |ranges_|, if applicable.
740 if (new_range_for_append
) {
741 range_for_next_append_
= AddToRanges(new_range_for_append
);
742 DCHECK(range_for_next_append_
!= ranges_
.end());
744 // Check to see if we need to merge |new_range_for_append| with the range
745 // before or after it. |new_range_for_append| is created whenever the last
746 // GOP appended is encountered, regardless of whether any buffers after it
747 // are ultimately deleted. Merging is necessary if there were no buffers
748 // (or very few buffers) deleted after creating |new_range_for_append|.
749 if (range_for_next_append_
!= ranges_
.begin()) {
750 RangeList::iterator range_before_next
= range_for_next_append_
;
752 MergeWithAdjacentRangeIfNecessary(range_before_next
);
754 MergeWithAdjacentRangeIfNecessary(range_for_next_append_
);
759 void SourceBufferStream::PrepareRangesForNextAppend(
760 const BufferQueue
& new_buffers
, BufferQueue
* deleted_buffers
) {
761 DCHECK(deleted_buffers
);
763 bool temporarily_select_range
= false;
764 if (!track_buffer_
.empty()) {
765 DecodeTimestamp tb_timestamp
= track_buffer_
.back()->GetDecodeTimestamp();
766 DecodeTimestamp seek_timestamp
= FindKeyframeAfterTimestamp(tb_timestamp
);
767 if (seek_timestamp
!= kNoDecodeTimestamp() &&
768 seek_timestamp
< new_buffers
.front()->GetDecodeTimestamp() &&
769 range_for_next_append_
!= ranges_
.end() &&
770 (*range_for_next_append_
)->BelongsToRange(seek_timestamp
)) {
771 DCHECK(tb_timestamp
< seek_timestamp
);
772 DCHECK(!selected_range_
);
773 DCHECK(!(*range_for_next_append_
)->HasNextBufferPosition());
775 // If there are GOPs between the end of the track buffer and the
776 // beginning of the new buffers, then temporarily seek the range
777 // so that the buffers between these two times will be deposited in
778 // |deleted_buffers| as if they were part of the current playback
780 // TODO(acolwell): Figure out a more elegant way to do this.
781 SeekAndSetSelectedRange(*range_for_next_append_
, seek_timestamp
);
782 temporarily_select_range
= true;
786 // Handle splices between the existing buffers and the new buffers. If a
787 // splice is generated the timestamp and duration of the first buffer in
788 // |new_buffers| will be modified.
789 if (splice_frames_enabled_
)
790 GenerateSpliceFrame(new_buffers
);
792 DecodeTimestamp prev_timestamp
= last_appended_buffer_timestamp_
;
793 bool prev_is_keyframe
= last_appended_buffer_is_keyframe_
;
794 DecodeTimestamp next_timestamp
= new_buffers
.front()->GetDecodeTimestamp();
795 bool next_is_keyframe
= new_buffers
.front()->is_key_frame();
797 if (prev_timestamp
!= kNoDecodeTimestamp() &&
798 prev_timestamp
!= next_timestamp
) {
799 // Clean up the old buffers between the last appended buffer and the
800 // beginning of |new_buffers|.
801 RemoveInternal(prev_timestamp
, next_timestamp
, true, deleted_buffers
);
804 // Make the delete range exclusive if we are dealing with an allowed same
805 // timestamp situation. This prevents the first buffer in the current append
806 // from deleting the last buffer in the previous append if both buffers
807 // have the same timestamp.
809 // The delete range should never be exclusive if a splice frame was generated
810 // because we don't generate splice frames for same timestamp situations.
811 DCHECK(new_buffers
.front()->splice_timestamp() !=
812 new_buffers
.front()->timestamp());
813 const bool is_exclusive
=
814 new_buffers
.front()->splice_buffers().empty() &&
815 prev_timestamp
== next_timestamp
&&
816 SourceBufferRange::AllowSameTimestamp(prev_is_keyframe
, next_is_keyframe
);
818 // Delete the buffers that |new_buffers| overlaps.
819 DecodeTimestamp start
= new_buffers
.front()->GetDecodeTimestamp();
820 DecodeTimestamp end
= new_buffers
.back()->GetDecodeTimestamp();
821 base::TimeDelta duration
= new_buffers
.back()->duration();
823 if (duration
!= kNoTimestamp() && duration
> base::TimeDelta()) {
826 // TODO(acolwell): Ensure all buffers actually have proper
827 // duration info so that this hack isn't needed.
828 // http://crbug.com/312836
829 end
+= base::TimeDelta::FromInternalValue(1);
832 RemoveInternal(start
, end
, is_exclusive
, deleted_buffers
);
834 // Restore the range seek state if necessary.
835 if (temporarily_select_range
)
836 SetSelectedRange(NULL
);
839 bool SourceBufferStream::AreAdjacentInSequence(
840 DecodeTimestamp first_timestamp
, DecodeTimestamp second_timestamp
) const {
841 return first_timestamp
< second_timestamp
&&
843 first_timestamp
+ ComputeFudgeRoom(GetMaxInterbufferDistance());
846 void SourceBufferStream::PruneTrackBuffer(const DecodeTimestamp timestamp
) {
847 // If we don't have the next timestamp, we don't have anything to delete.
848 if (timestamp
== kNoDecodeTimestamp())
851 while (!track_buffer_
.empty() &&
852 track_buffer_
.back()->GetDecodeTimestamp() >= timestamp
) {
853 track_buffer_
.pop_back();
857 void SourceBufferStream::MergeWithAdjacentRangeIfNecessary(
858 const RangeList::iterator
& range_with_new_buffers_itr
) {
859 DCHECK(range_with_new_buffers_itr
!= ranges_
.end());
861 SourceBufferRange
* range_with_new_buffers
= *range_with_new_buffers_itr
;
862 RangeList::iterator next_range_itr
= range_with_new_buffers_itr
;
865 if (next_range_itr
== ranges_
.end() ||
866 !range_with_new_buffers
->CanAppendRangeToEnd(**next_range_itr
)) {
870 bool transfer_current_position
= selected_range_
== *next_range_itr
;
871 DVLOG(3) << __FUNCTION__
<< " " << GetStreamTypeName()
872 << " merging " << RangeToString(*range_with_new_buffers
)
873 << " into " << RangeToString(**next_range_itr
);
874 range_with_new_buffers
->AppendRangeToEnd(**next_range_itr
,
875 transfer_current_position
);
876 // Update |selected_range_| pointer if |range| has become selected after
878 if (transfer_current_position
)
879 SetSelectedRange(range_with_new_buffers
);
881 if (next_range_itr
== range_for_next_append_
)
882 range_for_next_append_
= range_with_new_buffers_itr
;
884 DeleteAndRemoveRange(&next_range_itr
);
887 void SourceBufferStream::Seek(base::TimeDelta timestamp
) {
888 DCHECK(timestamp
>= base::TimeDelta());
889 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
890 << " (" << timestamp
.InSecondsF() << ")";
893 if (ShouldSeekToStartOfBuffered(timestamp
)) {
894 ranges_
.front()->SeekToStart();
895 SetSelectedRange(ranges_
.front());
896 seek_pending_
= false;
900 seek_buffer_timestamp_
= timestamp
;
901 seek_pending_
= true;
903 DecodeTimestamp seek_dts
= DecodeTimestamp::FromPresentationTime(timestamp
);
905 RangeList::iterator itr
= ranges_
.end();
906 for (itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
) {
907 if ((*itr
)->CanSeekTo(seek_dts
))
911 if (itr
== ranges_
.end())
914 SeekAndSetSelectedRange(*itr
, seek_dts
);
915 seek_pending_
= false;
918 bool SourceBufferStream::IsSeekPending() const {
919 return !(end_of_stream_
&& IsEndSelected()) && seek_pending_
;
922 void SourceBufferStream::OnSetDuration(base::TimeDelta duration
) {
923 DecodeTimestamp duration_dts
=
924 DecodeTimestamp::FromPresentationTime(duration
);
925 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
926 << " (" << duration
.InSecondsF() << ")";
928 RangeList::iterator itr
= ranges_
.end();
929 for (itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
) {
930 if ((*itr
)->GetEndTimestamp() > duration_dts
)
933 if (itr
== ranges_
.end())
936 // Need to partially truncate this range.
937 if ((*itr
)->GetStartTimestamp() < duration_dts
) {
938 bool delete_range
= (*itr
)->TruncateAt(duration_dts
, NULL
, false);
939 if ((*itr
== selected_range_
) && !selected_range_
->HasNextBufferPosition())
940 SetSelectedRange(NULL
);
943 DeleteAndRemoveRange(&itr
);
949 // Delete all ranges that begin after |duration_dts|.
950 while (itr
!= ranges_
.end()) {
951 // If we're about to delete the selected range, also reset the seek state.
952 DCHECK((*itr
)->GetStartTimestamp() >= duration_dts
);
953 if (*itr
== selected_range_
)
955 DeleteAndRemoveRange(&itr
);
959 SourceBufferStream::Status
SourceBufferStream::GetNextBuffer(
960 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
961 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName();
962 if (!pending_buffer_
.get()) {
963 const SourceBufferStream::Status status
= GetNextBufferInternal(out_buffer
);
964 if (status
!= SourceBufferStream::kSuccess
||
965 !SetPendingBuffer(out_buffer
)) {
966 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
967 << ": no pending buffer, returning status " << status
;
972 if (!pending_buffer_
->splice_buffers().empty()) {
973 const SourceBufferStream::Status status
=
974 HandleNextBufferWithSplice(out_buffer
);
975 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
976 << ": handled next buffer with splice, returning status "
981 DCHECK(pending_buffer_
->preroll_buffer().get());
983 const SourceBufferStream::Status status
=
984 HandleNextBufferWithPreroll(out_buffer
);
985 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
986 << ": handled next buffer with preroll, returning status "
991 SourceBufferStream::Status
SourceBufferStream::HandleNextBufferWithSplice(
992 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
993 const BufferQueue
& splice_buffers
= pending_buffer_
->splice_buffers();
994 const size_t last_splice_buffer_index
= splice_buffers
.size() - 1;
996 // Are there any splice buffers left to hand out? The last buffer should be
997 // handed out separately since it represents the first post-splice buffer.
998 if (splice_buffers_index_
< last_splice_buffer_index
) {
999 // Account for config changes which occur between fade out buffers.
1000 if (current_config_index_
!=
1001 splice_buffers
[splice_buffers_index_
]->GetConfigId()) {
1002 config_change_pending_
= true;
1003 DVLOG(1) << "Config change (splice buffer config ID does not match).";
1004 return SourceBufferStream::kConfigChange
;
1007 // Every pre splice buffer must have the same splice_timestamp().
1008 DCHECK(pending_buffer_
->splice_timestamp() ==
1009 splice_buffers
[splice_buffers_index_
]->splice_timestamp());
1011 // No pre splice buffers should have preroll.
1012 DCHECK(!splice_buffers
[splice_buffers_index_
]->preroll_buffer().get());
1014 *out_buffer
= splice_buffers
[splice_buffers_index_
++];
1015 return SourceBufferStream::kSuccess
;
1018 // Did we hand out the last pre-splice buffer on the previous call?
1019 if (!pending_buffers_complete_
) {
1020 DCHECK_EQ(splice_buffers_index_
, last_splice_buffer_index
);
1021 pending_buffers_complete_
= true;
1022 config_change_pending_
= true;
1023 DVLOG(1) << "Config change (forced for fade in of splice frame).";
1024 return SourceBufferStream::kConfigChange
;
1027 // All pre-splice buffers have been handed out and a config change completed,
1028 // so hand out the final buffer for fade in. Because a config change is
1029 // always issued prior to handing out this buffer, any changes in config id
1030 // have been inherently handled.
1031 DCHECK(pending_buffers_complete_
);
1032 DCHECK_EQ(splice_buffers_index_
, splice_buffers
.size() - 1);
1033 DCHECK(splice_buffers
.back()->splice_timestamp() == kNoTimestamp());
1034 *out_buffer
= splice_buffers
.back();
1035 pending_buffer_
= NULL
;
1037 // If the last splice buffer has preroll, hand off to the preroll handler.
1038 return SetPendingBuffer(out_buffer
) ? HandleNextBufferWithPreroll(out_buffer
)
1039 : SourceBufferStream::kSuccess
;
1042 SourceBufferStream::Status
SourceBufferStream::HandleNextBufferWithPreroll(
1043 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
1044 // Any config change should have already been handled.
1045 DCHECK_EQ(current_config_index_
, pending_buffer_
->GetConfigId());
1047 // Check if the preroll buffer has already been handed out.
1048 if (!pending_buffers_complete_
) {
1049 pending_buffers_complete_
= true;
1050 *out_buffer
= pending_buffer_
->preroll_buffer();
1051 return SourceBufferStream::kSuccess
;
1054 // Preroll complete, hand out the final buffer.
1055 *out_buffer
= pending_buffer_
;
1056 pending_buffer_
= NULL
;
1057 return SourceBufferStream::kSuccess
;
1060 SourceBufferStream::Status
SourceBufferStream::GetNextBufferInternal(
1061 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
1062 CHECK(!config_change_pending_
);
1064 if (!track_buffer_
.empty()) {
1065 DCHECK(!selected_range_
);
1066 scoped_refptr
<StreamParserBuffer
>& next_buffer
= track_buffer_
.front();
1068 // If the next buffer is an audio splice frame, the next effective config id
1069 // comes from the first splice buffer.
1070 if (next_buffer
->GetSpliceBufferConfigId(0) != current_config_index_
) {
1071 config_change_pending_
= true;
1072 DVLOG(1) << "Config change (track buffer config ID does not match).";
1073 return kConfigChange
;
1076 *out_buffer
= next_buffer
;
1077 track_buffer_
.pop_front();
1078 last_output_buffer_timestamp_
= (*out_buffer
)->GetDecodeTimestamp();
1080 // If the track buffer becomes empty, then try to set the selected range
1081 // based on the timestamp of this buffer being returned.
1082 if (track_buffer_
.empty())
1083 SetSelectedRangeIfNeeded(last_output_buffer_timestamp_
);
1088 if (!selected_range_
|| !selected_range_
->HasNextBuffer()) {
1089 if (end_of_stream_
&& IsEndSelected())
1090 return kEndOfStream
;
1091 DVLOG(3) << __FUNCTION__
<< " " << GetStreamTypeName()
1092 << ": returning kNeedBuffer "
1093 << (selected_range_
? "(selected range has no next buffer)"
1094 : "(no selected range)");
1098 if (selected_range_
->GetNextConfigId() != current_config_index_
) {
1099 config_change_pending_
= true;
1100 DVLOG(1) << "Config change (selected range config ID does not match).";
1101 return kConfigChange
;
1104 CHECK(selected_range_
->GetNextBuffer(out_buffer
));
1105 last_output_buffer_timestamp_
= (*out_buffer
)->GetDecodeTimestamp();
1109 DecodeTimestamp
SourceBufferStream::GetNextBufferTimestamp() {
1110 if (!track_buffer_
.empty())
1111 return track_buffer_
.front()->GetDecodeTimestamp();
1113 if (!selected_range_
)
1114 return kNoDecodeTimestamp();
1116 DCHECK(selected_range_
->HasNextBufferPosition());
1117 return selected_range_
->GetNextTimestamp();
1120 SourceBufferStream::RangeList::iterator
1121 SourceBufferStream::FindExistingRangeFor(DecodeTimestamp start_timestamp
) {
1122 for (RangeList::iterator itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
) {
1123 if ((*itr
)->BelongsToRange(start_timestamp
))
1126 return ranges_
.end();
1129 SourceBufferStream::RangeList::iterator
1130 SourceBufferStream::AddToRanges(SourceBufferRange
* new_range
) {
1131 DecodeTimestamp start_timestamp
= new_range
->GetStartTimestamp();
1132 RangeList::iterator itr
= ranges_
.end();
1133 for (itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
) {
1134 if ((*itr
)->GetStartTimestamp() > start_timestamp
)
1137 return ranges_
.insert(itr
, new_range
);
1140 SourceBufferStream::RangeList::iterator
1141 SourceBufferStream::GetSelectedRangeItr() {
1142 DCHECK(selected_range_
);
1143 RangeList::iterator itr
= ranges_
.end();
1144 for (itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
) {
1145 if (*itr
== selected_range_
)
1148 DCHECK(itr
!= ranges_
.end());
1152 void SourceBufferStream::SeekAndSetSelectedRange(
1153 SourceBufferRange
* range
, DecodeTimestamp seek_timestamp
) {
1155 range
->Seek(seek_timestamp
);
1156 SetSelectedRange(range
);
1159 void SourceBufferStream::SetSelectedRange(SourceBufferRange
* range
) {
1160 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
1161 << ": " << selected_range_
<< " -> " << range
;
1162 if (selected_range_
)
1163 selected_range_
->ResetNextBufferPosition();
1164 DCHECK(!range
|| range
->HasNextBufferPosition());
1165 selected_range_
= range
;
1168 Ranges
<base::TimeDelta
> SourceBufferStream::GetBufferedTime() const {
1169 Ranges
<base::TimeDelta
> ranges
;
1170 for (RangeList::const_iterator itr
= ranges_
.begin();
1171 itr
!= ranges_
.end(); ++itr
) {
1172 ranges
.Add((*itr
)->GetStartTimestamp().ToPresentationTime(),
1173 (*itr
)->GetBufferedEndTimestamp().ToPresentationTime());
1178 base::TimeDelta
SourceBufferStream::GetBufferedDuration() const {
1179 if (ranges_
.empty())
1180 return base::TimeDelta();
1182 return ranges_
.back()->GetBufferedEndTimestamp().ToPresentationTime();
1185 void SourceBufferStream::MarkEndOfStream() {
1186 DCHECK(!end_of_stream_
);
1187 end_of_stream_
= true;
1190 void SourceBufferStream::UnmarkEndOfStream() {
1191 DCHECK(end_of_stream_
);
1192 end_of_stream_
= false;
1195 bool SourceBufferStream::IsEndSelected() const {
1196 if (ranges_
.empty())
1199 if (seek_pending_
) {
1200 base::TimeDelta last_range_end_time
=
1201 ranges_
.back()->GetBufferedEndTimestamp().ToPresentationTime();
1202 return seek_buffer_timestamp_
>= last_range_end_time
;
1205 return selected_range_
== ranges_
.back();
1208 const AudioDecoderConfig
& SourceBufferStream::GetCurrentAudioDecoderConfig() {
1209 if (config_change_pending_
)
1210 CompleteConfigChange();
1211 return audio_configs_
[current_config_index_
];
1214 const VideoDecoderConfig
& SourceBufferStream::GetCurrentVideoDecoderConfig() {
1215 if (config_change_pending_
)
1216 CompleteConfigChange();
1217 return video_configs_
[current_config_index_
];
1220 const TextTrackConfig
& SourceBufferStream::GetCurrentTextTrackConfig() {
1221 return text_track_config_
;
1224 base::TimeDelta
SourceBufferStream::GetMaxInterbufferDistance() const {
1225 if (max_interbuffer_distance_
== kNoTimestamp())
1226 return base::TimeDelta::FromMilliseconds(kDefaultBufferDurationInMs
);
1227 return max_interbuffer_distance_
;
1230 bool SourceBufferStream::UpdateAudioConfig(const AudioDecoderConfig
& config
) {
1231 DCHECK(!audio_configs_
.empty());
1232 DCHECK(video_configs_
.empty());
1233 DVLOG(3) << "UpdateAudioConfig.";
1235 if (audio_configs_
[0].codec() != config
.codec()) {
1236 MEDIA_LOG(log_cb_
) << "Audio codec changes not allowed.";
1240 if (audio_configs_
[0].is_encrypted() != config
.is_encrypted()) {
1241 MEDIA_LOG(log_cb_
) << "Audio encryption changes not allowed.";
1245 // Check to see if the new config matches an existing one.
1246 for (size_t i
= 0; i
< audio_configs_
.size(); ++i
) {
1247 if (config
.Matches(audio_configs_
[i
])) {
1248 append_config_index_
= i
;
1253 // No matches found so let's add this one to the list.
1254 append_config_index_
= audio_configs_
.size();
1255 DVLOG(2) << "New audio config - index: " << append_config_index_
;
1256 audio_configs_
.resize(audio_configs_
.size() + 1);
1257 audio_configs_
[append_config_index_
] = config
;
1261 bool SourceBufferStream::UpdateVideoConfig(const VideoDecoderConfig
& config
) {
1262 DCHECK(!video_configs_
.empty());
1263 DCHECK(audio_configs_
.empty());
1264 DVLOG(3) << "UpdateVideoConfig.";
1266 if (video_configs_
[0].codec() != config
.codec()) {
1267 MEDIA_LOG(log_cb_
) << "Video codec changes not allowed.";
1271 if (video_configs_
[0].is_encrypted() != config
.is_encrypted()) {
1272 MEDIA_LOG(log_cb_
) << "Video encryption changes not allowed.";
1276 // Check to see if the new config matches an existing one.
1277 for (size_t i
= 0; i
< video_configs_
.size(); ++i
) {
1278 if (config
.Matches(video_configs_
[i
])) {
1279 append_config_index_
= i
;
1284 // No matches found so let's add this one to the list.
1285 append_config_index_
= video_configs_
.size();
1286 DVLOG(2) << "New video config - index: " << append_config_index_
;
1287 video_configs_
.resize(video_configs_
.size() + 1);
1288 video_configs_
[append_config_index_
] = config
;
1292 void SourceBufferStream::CompleteConfigChange() {
1293 config_change_pending_
= false;
1295 if (pending_buffer_
.get()) {
1296 current_config_index_
=
1297 pending_buffer_
->GetSpliceBufferConfigId(splice_buffers_index_
);
1301 if (!track_buffer_
.empty()) {
1302 current_config_index_
= track_buffer_
.front()->GetSpliceBufferConfigId(0);
1306 if (selected_range_
&& selected_range_
->HasNextBuffer())
1307 current_config_index_
= selected_range_
->GetNextConfigId();
1310 void SourceBufferStream::SetSelectedRangeIfNeeded(
1311 const DecodeTimestamp timestamp
) {
1312 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
1313 << "(" << timestamp
.InSecondsF() << ")";
1315 if (selected_range_
) {
1316 DCHECK(track_buffer_
.empty());
1320 if (!track_buffer_
.empty()) {
1321 DCHECK(!selected_range_
);
1325 DecodeTimestamp start_timestamp
= timestamp
;
1327 // If the next buffer timestamp is not known then use a timestamp just after
1328 // the timestamp on the last buffer returned by GetNextBuffer().
1329 if (start_timestamp
== kNoDecodeTimestamp()) {
1330 if (last_output_buffer_timestamp_
== kNoDecodeTimestamp()) {
1331 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
1332 << " no previous output timestamp";
1336 start_timestamp
= last_output_buffer_timestamp_
+
1337 base::TimeDelta::FromInternalValue(1);
1340 DecodeTimestamp seek_timestamp
=
1341 FindNewSelectedRangeSeekTimestamp(start_timestamp
);
1343 // If we don't have buffered data to seek to, then return.
1344 if (seek_timestamp
== kNoDecodeTimestamp()) {
1345 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
1346 << " couldn't find new selected range seek timestamp";
1350 DCHECK(track_buffer_
.empty());
1351 SeekAndSetSelectedRange(*FindExistingRangeFor(seek_timestamp
),
1355 DecodeTimestamp
SourceBufferStream::FindNewSelectedRangeSeekTimestamp(
1356 const DecodeTimestamp start_timestamp
) {
1357 DCHECK(start_timestamp
!= kNoDecodeTimestamp());
1358 DCHECK(start_timestamp
>= DecodeTimestamp());
1360 RangeList::iterator itr
= ranges_
.begin();
1362 for (; itr
!= ranges_
.end(); ++itr
) {
1363 if ((*itr
)->GetEndTimestamp() >= start_timestamp
) {
1368 if (itr
== ranges_
.end()) {
1369 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
1370 << " no buffered data for dts=" << start_timestamp
.InSecondsF();
1371 return kNoDecodeTimestamp();
1374 // First check for a keyframe timestamp >= |start_timestamp|
1375 // in the current range.
1376 DecodeTimestamp keyframe_timestamp
=
1377 (*itr
)->NextKeyframeTimestamp(start_timestamp
);
1379 if (keyframe_timestamp
!= kNoDecodeTimestamp())
1380 return keyframe_timestamp
;
1382 // If a keyframe was not found then look for a keyframe that is
1383 // "close enough" in the current or next range.
1384 DecodeTimestamp end_timestamp
=
1385 start_timestamp
+ ComputeFudgeRoom(GetMaxInterbufferDistance());
1386 DCHECK(start_timestamp
< end_timestamp
);
1388 // Make sure the current range doesn't start beyond |end_timestamp|.
1389 if ((*itr
)->GetStartTimestamp() >= end_timestamp
)
1390 return kNoDecodeTimestamp();
1392 keyframe_timestamp
= (*itr
)->KeyframeBeforeTimestamp(end_timestamp
);
1394 // Check to see if the keyframe is within the acceptable range
1395 // (|start_timestamp|, |end_timestamp|].
1396 if (keyframe_timestamp
!= kNoDecodeTimestamp() &&
1397 start_timestamp
< keyframe_timestamp
&&
1398 keyframe_timestamp
<= end_timestamp
) {
1399 return keyframe_timestamp
;
1402 // If |end_timestamp| is within this range, then no other checks are
1404 if (end_timestamp
<= (*itr
)->GetEndTimestamp())
1405 return kNoDecodeTimestamp();
1407 // Move on to the next range.
1410 // Return early if the next range does not contain |end_timestamp|.
1411 if (itr
== ranges_
.end() || (*itr
)->GetStartTimestamp() >= end_timestamp
)
1412 return kNoDecodeTimestamp();
1414 keyframe_timestamp
= (*itr
)->KeyframeBeforeTimestamp(end_timestamp
);
1416 // Check to see if the keyframe is within the acceptable range
1417 // (|start_timestamp|, |end_timestamp|].
1418 if (keyframe_timestamp
!= kNoDecodeTimestamp() &&
1419 start_timestamp
< keyframe_timestamp
&&
1420 keyframe_timestamp
<= end_timestamp
) {
1421 return keyframe_timestamp
;
1424 return kNoDecodeTimestamp();
1427 DecodeTimestamp
SourceBufferStream::FindKeyframeAfterTimestamp(
1428 const DecodeTimestamp timestamp
) {
1429 DCHECK(timestamp
!= kNoDecodeTimestamp());
1431 RangeList::iterator itr
= FindExistingRangeFor(timestamp
);
1433 if (itr
== ranges_
.end())
1434 return kNoDecodeTimestamp();
1436 // First check for a keyframe timestamp >= |timestamp|
1437 // in the current range.
1438 return (*itr
)->NextKeyframeTimestamp(timestamp
);
1441 std::string
SourceBufferStream::GetStreamTypeName() const {
1442 switch (GetType()) {
1454 SourceBufferStream::Type
SourceBufferStream::GetType() const {
1455 if (!audio_configs_
.empty())
1457 if (!video_configs_
.empty())
1459 DCHECK_NE(text_track_config_
.kind(), kTextNone
);
1463 void SourceBufferStream::DeleteAndRemoveRange(RangeList::iterator
* itr
) {
1464 DVLOG(1) << __FUNCTION__
;
1466 DCHECK(*itr
!= ranges_
.end());
1467 if (**itr
== selected_range_
) {
1468 DVLOG(1) << __FUNCTION__
<< " deleting selected range.";
1469 SetSelectedRange(NULL
);
1472 if (*itr
== range_for_next_append_
) {
1473 DVLOG(1) << __FUNCTION__
<< " deleting range_for_next_append_.";
1474 range_for_next_append_
= ranges_
.end();
1475 last_appended_buffer_timestamp_
= kNoDecodeTimestamp();
1476 last_appended_buffer_is_keyframe_
= false;
1480 *itr
= ranges_
.erase(*itr
);
1483 void SourceBufferStream::GenerateSpliceFrame(const BufferQueue
& new_buffers
) {
1484 DCHECK(!new_buffers
.empty());
1486 // Splice frames are only supported for audio.
1487 if (GetType() != kAudio
)
1490 // Find the overlapped range (if any).
1491 const base::TimeDelta splice_timestamp
= new_buffers
.front()->timestamp();
1492 const DecodeTimestamp splice_dts
=
1493 DecodeTimestamp::FromPresentationTime(splice_timestamp
);
1494 RangeList::iterator range_itr
= FindExistingRangeFor(splice_dts
);
1495 if (range_itr
== ranges_
.end())
1498 const DecodeTimestamp max_splice_end_dts
=
1499 splice_dts
+ base::TimeDelta::FromMilliseconds(
1500 AudioSplicer::kCrossfadeDurationInMilliseconds
);
1502 // Find all buffers involved before the splice point.
1503 BufferQueue pre_splice_buffers
;
1504 if (!(*range_itr
)->GetBuffersInRange(
1505 splice_dts
, max_splice_end_dts
, &pre_splice_buffers
)) {
1509 // If there are gaps in the timeline, it's possible that we only find buffers
1510 // after the splice point but within the splice range. For simplicity, we do
1511 // not generate splice frames in this case.
1513 // We also do not want to generate splices if the first new buffer replaces an
1514 // existing buffer exactly.
1515 if (pre_splice_buffers
.front()->timestamp() >= splice_timestamp
)
1518 // If any |pre_splice_buffers| are already splices or preroll, do not generate
1520 for (size_t i
= 0; i
< pre_splice_buffers
.size(); ++i
) {
1521 const BufferQueue
& original_splice_buffers
=
1522 pre_splice_buffers
[i
]->splice_buffers();
1523 if (!original_splice_buffers
.empty()) {
1524 DVLOG(1) << "Can't generate splice: overlapped buffers contain a "
1525 "pre-existing splice.";
1529 if (pre_splice_buffers
[i
]->preroll_buffer().get()) {
1530 DVLOG(1) << "Can't generate splice: overlapped buffers contain preroll.";
1535 // Don't generate splice frames which represent less than two frames, since we
1536 // need at least that much to generate a crossfade. Per the spec, make this
1537 // check using the sample rate of the overlapping buffers.
1538 const base::TimeDelta splice_duration
=
1539 pre_splice_buffers
.back()->timestamp() +
1540 pre_splice_buffers
.back()->duration() - splice_timestamp
;
1541 const base::TimeDelta minimum_splice_duration
= base::TimeDelta::FromSecondsD(
1542 2.0 / audio_configs_
[append_config_index_
].samples_per_second());
1543 if (splice_duration
< minimum_splice_duration
) {
1544 DVLOG(1) << "Can't generate splice: not enough samples for crossfade; have "
1545 << splice_duration
.InMicroseconds() << " us, but need "
1546 << minimum_splice_duration
.InMicroseconds() << " us.";
1550 new_buffers
.front()->ConvertToSpliceBuffer(pre_splice_buffers
);
1553 bool SourceBufferStream::SetPendingBuffer(
1554 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
1555 DCHECK(out_buffer
->get());
1556 DCHECK(!pending_buffer_
.get());
1558 const bool have_splice_buffers
= !(*out_buffer
)->splice_buffers().empty();
1559 const bool have_preroll_buffer
= !!(*out_buffer
)->preroll_buffer().get();
1561 if (!have_splice_buffers
&& !have_preroll_buffer
)
1564 DCHECK_NE(have_splice_buffers
, have_preroll_buffer
);
1565 splice_buffers_index_
= 0;
1566 pending_buffer_
.swap(*out_buffer
);
1567 pending_buffers_complete_
= false;
1571 } // namespace media