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/debug/trace_event.h"
13 #include "base/logging.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 if (!pending_buffer_
.get()) {
962 const SourceBufferStream::Status status
= GetNextBufferInternal(out_buffer
);
963 if (status
!= SourceBufferStream::kSuccess
|| !SetPendingBuffer(out_buffer
))
967 if (!pending_buffer_
->splice_buffers().empty())
968 return HandleNextBufferWithSplice(out_buffer
);
970 DCHECK(pending_buffer_
->preroll_buffer().get());
971 return HandleNextBufferWithPreroll(out_buffer
);
974 SourceBufferStream::Status
SourceBufferStream::HandleNextBufferWithSplice(
975 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
976 const BufferQueue
& splice_buffers
= pending_buffer_
->splice_buffers();
977 const size_t last_splice_buffer_index
= splice_buffers
.size() - 1;
979 // Are there any splice buffers left to hand out? The last buffer should be
980 // handed out separately since it represents the first post-splice buffer.
981 if (splice_buffers_index_
< last_splice_buffer_index
) {
982 // Account for config changes which occur between fade out buffers.
983 if (current_config_index_
!=
984 splice_buffers
[splice_buffers_index_
]->GetConfigId()) {
985 config_change_pending_
= true;
986 DVLOG(1) << "Config change (splice buffer config ID does not match).";
987 return SourceBufferStream::kConfigChange
;
990 // Every pre splice buffer must have the same splice_timestamp().
991 DCHECK(pending_buffer_
->splice_timestamp() ==
992 splice_buffers
[splice_buffers_index_
]->splice_timestamp());
994 // No pre splice buffers should have preroll.
995 DCHECK(!splice_buffers
[splice_buffers_index_
]->preroll_buffer().get());
997 *out_buffer
= splice_buffers
[splice_buffers_index_
++];
998 return SourceBufferStream::kSuccess
;
1001 // Did we hand out the last pre-splice buffer on the previous call?
1002 if (!pending_buffers_complete_
) {
1003 DCHECK_EQ(splice_buffers_index_
, last_splice_buffer_index
);
1004 pending_buffers_complete_
= true;
1005 config_change_pending_
= true;
1006 DVLOG(1) << "Config change (forced for fade in of splice frame).";
1007 return SourceBufferStream::kConfigChange
;
1010 // All pre-splice buffers have been handed out and a config change completed,
1011 // so hand out the final buffer for fade in. Because a config change is
1012 // always issued prior to handing out this buffer, any changes in config id
1013 // have been inherently handled.
1014 DCHECK(pending_buffers_complete_
);
1015 DCHECK_EQ(splice_buffers_index_
, splice_buffers
.size() - 1);
1016 DCHECK(splice_buffers
.back()->splice_timestamp() == kNoTimestamp());
1017 *out_buffer
= splice_buffers
.back();
1018 pending_buffer_
= NULL
;
1020 // If the last splice buffer has preroll, hand off to the preroll handler.
1021 return SetPendingBuffer(out_buffer
) ? HandleNextBufferWithPreroll(out_buffer
)
1022 : SourceBufferStream::kSuccess
;
1025 SourceBufferStream::Status
SourceBufferStream::HandleNextBufferWithPreroll(
1026 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
1027 // Any config change should have already been handled.
1028 DCHECK_EQ(current_config_index_
, pending_buffer_
->GetConfigId());
1030 // Check if the preroll buffer has already been handed out.
1031 if (!pending_buffers_complete_
) {
1032 pending_buffers_complete_
= true;
1033 *out_buffer
= pending_buffer_
->preroll_buffer();
1034 return SourceBufferStream::kSuccess
;
1037 // Preroll complete, hand out the final buffer.
1038 *out_buffer
= pending_buffer_
;
1039 pending_buffer_
= NULL
;
1040 return SourceBufferStream::kSuccess
;
1043 SourceBufferStream::Status
SourceBufferStream::GetNextBufferInternal(
1044 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
1045 CHECK(!config_change_pending_
);
1047 if (!track_buffer_
.empty()) {
1048 DCHECK(!selected_range_
);
1049 scoped_refptr
<StreamParserBuffer
>& next_buffer
= track_buffer_
.front();
1051 // If the next buffer is an audio splice frame, the next effective config id
1052 // comes from the first splice buffer.
1053 if (next_buffer
->GetSpliceBufferConfigId(0) != current_config_index_
) {
1054 config_change_pending_
= true;
1055 DVLOG(1) << "Config change (track buffer config ID does not match).";
1056 return kConfigChange
;
1059 *out_buffer
= next_buffer
;
1060 track_buffer_
.pop_front();
1061 last_output_buffer_timestamp_
= (*out_buffer
)->GetDecodeTimestamp();
1063 // If the track buffer becomes empty, then try to set the selected range
1064 // based on the timestamp of this buffer being returned.
1065 if (track_buffer_
.empty())
1066 SetSelectedRangeIfNeeded(last_output_buffer_timestamp_
);
1071 if (!selected_range_
|| !selected_range_
->HasNextBuffer()) {
1072 if (end_of_stream_
&& IsEndSelected())
1073 return kEndOfStream
;
1074 DVLOG(3) << __FUNCTION__
<< " " << GetStreamTypeName()
1075 << ": returning kNeedBuffer "
1076 << (selected_range_
? "(selected range has no next buffer)"
1077 : "(no selected range)");
1081 if (selected_range_
->GetNextConfigId() != current_config_index_
) {
1082 config_change_pending_
= true;
1083 DVLOG(1) << "Config change (selected range config ID does not match).";
1084 return kConfigChange
;
1087 CHECK(selected_range_
->GetNextBuffer(out_buffer
));
1088 last_output_buffer_timestamp_
= (*out_buffer
)->GetDecodeTimestamp();
1092 DecodeTimestamp
SourceBufferStream::GetNextBufferTimestamp() {
1093 if (!track_buffer_
.empty())
1094 return track_buffer_
.front()->GetDecodeTimestamp();
1096 if (!selected_range_
)
1097 return kNoDecodeTimestamp();
1099 DCHECK(selected_range_
->HasNextBufferPosition());
1100 return selected_range_
->GetNextTimestamp();
1103 SourceBufferStream::RangeList::iterator
1104 SourceBufferStream::FindExistingRangeFor(DecodeTimestamp start_timestamp
) {
1105 for (RangeList::iterator itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
) {
1106 if ((*itr
)->BelongsToRange(start_timestamp
))
1109 return ranges_
.end();
1112 SourceBufferStream::RangeList::iterator
1113 SourceBufferStream::AddToRanges(SourceBufferRange
* new_range
) {
1114 DecodeTimestamp start_timestamp
= new_range
->GetStartTimestamp();
1115 RangeList::iterator itr
= ranges_
.end();
1116 for (itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
) {
1117 if ((*itr
)->GetStartTimestamp() > start_timestamp
)
1120 return ranges_
.insert(itr
, new_range
);
1123 SourceBufferStream::RangeList::iterator
1124 SourceBufferStream::GetSelectedRangeItr() {
1125 DCHECK(selected_range_
);
1126 RangeList::iterator itr
= ranges_
.end();
1127 for (itr
= ranges_
.begin(); itr
!= ranges_
.end(); ++itr
) {
1128 if (*itr
== selected_range_
)
1131 DCHECK(itr
!= ranges_
.end());
1135 void SourceBufferStream::SeekAndSetSelectedRange(
1136 SourceBufferRange
* range
, DecodeTimestamp seek_timestamp
) {
1138 range
->Seek(seek_timestamp
);
1139 SetSelectedRange(range
);
1142 void SourceBufferStream::SetSelectedRange(SourceBufferRange
* range
) {
1143 DVLOG(1) << __FUNCTION__
<< " " << GetStreamTypeName()
1144 << ": " << selected_range_
<< " -> " << range
;
1145 if (selected_range_
)
1146 selected_range_
->ResetNextBufferPosition();
1147 DCHECK(!range
|| range
->HasNextBufferPosition());
1148 selected_range_
= range
;
1151 Ranges
<base::TimeDelta
> SourceBufferStream::GetBufferedTime() const {
1152 Ranges
<base::TimeDelta
> ranges
;
1153 for (RangeList::const_iterator itr
= ranges_
.begin();
1154 itr
!= ranges_
.end(); ++itr
) {
1155 ranges
.Add((*itr
)->GetStartTimestamp().ToPresentationTime(),
1156 (*itr
)->GetBufferedEndTimestamp().ToPresentationTime());
1161 base::TimeDelta
SourceBufferStream::GetBufferedDuration() const {
1162 if (ranges_
.empty())
1163 return base::TimeDelta();
1165 return ranges_
.back()->GetBufferedEndTimestamp().ToPresentationTime();
1168 void SourceBufferStream::MarkEndOfStream() {
1169 DCHECK(!end_of_stream_
);
1170 end_of_stream_
= true;
1173 void SourceBufferStream::UnmarkEndOfStream() {
1174 DCHECK(end_of_stream_
);
1175 end_of_stream_
= false;
1178 bool SourceBufferStream::IsEndSelected() const {
1179 if (ranges_
.empty())
1182 if (seek_pending_
) {
1183 base::TimeDelta last_range_end_time
=
1184 ranges_
.back()->GetBufferedEndTimestamp().ToPresentationTime();
1185 return seek_buffer_timestamp_
>= last_range_end_time
;
1188 return selected_range_
== ranges_
.back();
1191 const AudioDecoderConfig
& SourceBufferStream::GetCurrentAudioDecoderConfig() {
1192 if (config_change_pending_
)
1193 CompleteConfigChange();
1194 return audio_configs_
[current_config_index_
];
1197 const VideoDecoderConfig
& SourceBufferStream::GetCurrentVideoDecoderConfig() {
1198 if (config_change_pending_
)
1199 CompleteConfigChange();
1200 return video_configs_
[current_config_index_
];
1203 const TextTrackConfig
& SourceBufferStream::GetCurrentTextTrackConfig() {
1204 return text_track_config_
;
1207 base::TimeDelta
SourceBufferStream::GetMaxInterbufferDistance() const {
1208 if (max_interbuffer_distance_
== kNoTimestamp())
1209 return base::TimeDelta::FromMilliseconds(kDefaultBufferDurationInMs
);
1210 return max_interbuffer_distance_
;
1213 bool SourceBufferStream::UpdateAudioConfig(const AudioDecoderConfig
& config
) {
1214 DCHECK(!audio_configs_
.empty());
1215 DCHECK(video_configs_
.empty());
1216 DVLOG(3) << "UpdateAudioConfig.";
1218 if (audio_configs_
[0].codec() != config
.codec()) {
1219 MEDIA_LOG(log_cb_
) << "Audio codec changes not allowed.";
1223 if (audio_configs_
[0].is_encrypted() != config
.is_encrypted()) {
1224 MEDIA_LOG(log_cb_
) << "Audio encryption changes not allowed.";
1228 // Check to see if the new config matches an existing one.
1229 for (size_t i
= 0; i
< audio_configs_
.size(); ++i
) {
1230 if (config
.Matches(audio_configs_
[i
])) {
1231 append_config_index_
= i
;
1236 // No matches found so let's add this one to the list.
1237 append_config_index_
= audio_configs_
.size();
1238 DVLOG(2) << "New audio config - index: " << append_config_index_
;
1239 audio_configs_
.resize(audio_configs_
.size() + 1);
1240 audio_configs_
[append_config_index_
] = config
;
1244 bool SourceBufferStream::UpdateVideoConfig(const VideoDecoderConfig
& config
) {
1245 DCHECK(!video_configs_
.empty());
1246 DCHECK(audio_configs_
.empty());
1247 DVLOG(3) << "UpdateVideoConfig.";
1249 if (video_configs_
[0].codec() != config
.codec()) {
1250 MEDIA_LOG(log_cb_
) << "Video codec changes not allowed.";
1254 if (video_configs_
[0].is_encrypted() != config
.is_encrypted()) {
1255 MEDIA_LOG(log_cb_
) << "Video encryption changes not allowed.";
1259 // Check to see if the new config matches an existing one.
1260 for (size_t i
= 0; i
< video_configs_
.size(); ++i
) {
1261 if (config
.Matches(video_configs_
[i
])) {
1262 append_config_index_
= i
;
1267 // No matches found so let's add this one to the list.
1268 append_config_index_
= video_configs_
.size();
1269 DVLOG(2) << "New video config - index: " << append_config_index_
;
1270 video_configs_
.resize(video_configs_
.size() + 1);
1271 video_configs_
[append_config_index_
] = config
;
1275 void SourceBufferStream::CompleteConfigChange() {
1276 config_change_pending_
= false;
1278 if (pending_buffer_
.get()) {
1279 current_config_index_
=
1280 pending_buffer_
->GetSpliceBufferConfigId(splice_buffers_index_
);
1284 if (!track_buffer_
.empty()) {
1285 current_config_index_
= track_buffer_
.front()->GetSpliceBufferConfigId(0);
1289 if (selected_range_
&& selected_range_
->HasNextBuffer())
1290 current_config_index_
= selected_range_
->GetNextConfigId();
1293 void SourceBufferStream::SetSelectedRangeIfNeeded(
1294 const DecodeTimestamp timestamp
) {
1295 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
1296 << "(" << timestamp
.InSecondsF() << ")";
1298 if (selected_range_
) {
1299 DCHECK(track_buffer_
.empty());
1303 if (!track_buffer_
.empty()) {
1304 DCHECK(!selected_range_
);
1308 DecodeTimestamp start_timestamp
= timestamp
;
1310 // If the next buffer timestamp is not known then use a timestamp just after
1311 // the timestamp on the last buffer returned by GetNextBuffer().
1312 if (start_timestamp
== kNoDecodeTimestamp()) {
1313 if (last_output_buffer_timestamp_
== kNoDecodeTimestamp()) {
1314 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
1315 << " no previous output timestamp";
1319 start_timestamp
= last_output_buffer_timestamp_
+
1320 base::TimeDelta::FromInternalValue(1);
1323 DecodeTimestamp seek_timestamp
=
1324 FindNewSelectedRangeSeekTimestamp(start_timestamp
);
1326 // If we don't have buffered data to seek to, then return.
1327 if (seek_timestamp
== kNoDecodeTimestamp()) {
1328 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
1329 << " couldn't find new selected range seek timestamp";
1333 DCHECK(track_buffer_
.empty());
1334 SeekAndSetSelectedRange(*FindExistingRangeFor(seek_timestamp
),
1338 DecodeTimestamp
SourceBufferStream::FindNewSelectedRangeSeekTimestamp(
1339 const DecodeTimestamp start_timestamp
) {
1340 DCHECK(start_timestamp
!= kNoDecodeTimestamp());
1341 DCHECK(start_timestamp
>= DecodeTimestamp());
1343 RangeList::iterator itr
= ranges_
.begin();
1345 for (; itr
!= ranges_
.end(); ++itr
) {
1346 if ((*itr
)->GetEndTimestamp() >= start_timestamp
) {
1351 if (itr
== ranges_
.end()) {
1352 DVLOG(2) << __FUNCTION__
<< " " << GetStreamTypeName()
1353 << " no buffered data for dts=" << start_timestamp
.InSecondsF();
1354 return kNoDecodeTimestamp();
1357 // First check for a keyframe timestamp >= |start_timestamp|
1358 // in the current range.
1359 DecodeTimestamp keyframe_timestamp
=
1360 (*itr
)->NextKeyframeTimestamp(start_timestamp
);
1362 if (keyframe_timestamp
!= kNoDecodeTimestamp())
1363 return keyframe_timestamp
;
1365 // If a keyframe was not found then look for a keyframe that is
1366 // "close enough" in the current or next range.
1367 DecodeTimestamp end_timestamp
=
1368 start_timestamp
+ ComputeFudgeRoom(GetMaxInterbufferDistance());
1369 DCHECK(start_timestamp
< end_timestamp
);
1371 // Make sure the current range doesn't start beyond |end_timestamp|.
1372 if ((*itr
)->GetStartTimestamp() >= end_timestamp
)
1373 return kNoDecodeTimestamp();
1375 keyframe_timestamp
= (*itr
)->KeyframeBeforeTimestamp(end_timestamp
);
1377 // Check to see if the keyframe is within the acceptable range
1378 // (|start_timestamp|, |end_timestamp|].
1379 if (keyframe_timestamp
!= kNoDecodeTimestamp() &&
1380 start_timestamp
< keyframe_timestamp
&&
1381 keyframe_timestamp
<= end_timestamp
) {
1382 return keyframe_timestamp
;
1385 // If |end_timestamp| is within this range, then no other checks are
1387 if (end_timestamp
<= (*itr
)->GetEndTimestamp())
1388 return kNoDecodeTimestamp();
1390 // Move on to the next range.
1393 // Return early if the next range does not contain |end_timestamp|.
1394 if (itr
== ranges_
.end() || (*itr
)->GetStartTimestamp() >= end_timestamp
)
1395 return kNoDecodeTimestamp();
1397 keyframe_timestamp
= (*itr
)->KeyframeBeforeTimestamp(end_timestamp
);
1399 // Check to see if the keyframe is within the acceptable range
1400 // (|start_timestamp|, |end_timestamp|].
1401 if (keyframe_timestamp
!= kNoDecodeTimestamp() &&
1402 start_timestamp
< keyframe_timestamp
&&
1403 keyframe_timestamp
<= end_timestamp
) {
1404 return keyframe_timestamp
;
1407 return kNoDecodeTimestamp();
1410 DecodeTimestamp
SourceBufferStream::FindKeyframeAfterTimestamp(
1411 const DecodeTimestamp timestamp
) {
1412 DCHECK(timestamp
!= kNoDecodeTimestamp());
1414 RangeList::iterator itr
= FindExistingRangeFor(timestamp
);
1416 if (itr
== ranges_
.end())
1417 return kNoDecodeTimestamp();
1419 // First check for a keyframe timestamp >= |timestamp|
1420 // in the current range.
1421 return (*itr
)->NextKeyframeTimestamp(timestamp
);
1424 std::string
SourceBufferStream::GetStreamTypeName() const {
1425 switch (GetType()) {
1437 SourceBufferStream::Type
SourceBufferStream::GetType() const {
1438 if (!audio_configs_
.empty())
1440 if (!video_configs_
.empty())
1442 DCHECK_NE(text_track_config_
.kind(), kTextNone
);
1446 void SourceBufferStream::DeleteAndRemoveRange(RangeList::iterator
* itr
) {
1447 DVLOG(1) << __FUNCTION__
;
1449 DCHECK(*itr
!= ranges_
.end());
1450 if (**itr
== selected_range_
) {
1451 DVLOG(1) << __FUNCTION__
<< " deleting selected range.";
1452 SetSelectedRange(NULL
);
1455 if (*itr
== range_for_next_append_
) {
1456 DVLOG(1) << __FUNCTION__
<< " deleting range_for_next_append_.";
1457 range_for_next_append_
= ranges_
.end();
1458 last_appended_buffer_timestamp_
= kNoDecodeTimestamp();
1459 last_appended_buffer_is_keyframe_
= false;
1463 *itr
= ranges_
.erase(*itr
);
1466 void SourceBufferStream::GenerateSpliceFrame(const BufferQueue
& new_buffers
) {
1467 DCHECK(!new_buffers
.empty());
1469 // Splice frames are only supported for audio.
1470 if (GetType() != kAudio
)
1473 // Find the overlapped range (if any).
1474 const base::TimeDelta splice_timestamp
= new_buffers
.front()->timestamp();
1475 const DecodeTimestamp splice_dts
=
1476 DecodeTimestamp::FromPresentationTime(splice_timestamp
);
1477 RangeList::iterator range_itr
= FindExistingRangeFor(splice_dts
);
1478 if (range_itr
== ranges_
.end())
1481 const DecodeTimestamp max_splice_end_dts
=
1482 splice_dts
+ base::TimeDelta::FromMilliseconds(
1483 AudioSplicer::kCrossfadeDurationInMilliseconds
);
1485 // Find all buffers involved before the splice point.
1486 BufferQueue pre_splice_buffers
;
1487 if (!(*range_itr
)->GetBuffersInRange(
1488 splice_dts
, max_splice_end_dts
, &pre_splice_buffers
)) {
1492 // If there are gaps in the timeline, it's possible that we only find buffers
1493 // after the splice point but within the splice range. For simplicity, we do
1494 // not generate splice frames in this case.
1496 // We also do not want to generate splices if the first new buffer replaces an
1497 // existing buffer exactly.
1498 if (pre_splice_buffers
.front()->timestamp() >= splice_timestamp
)
1501 // If any |pre_splice_buffers| are already splices or preroll, do not generate
1503 for (size_t i
= 0; i
< pre_splice_buffers
.size(); ++i
) {
1504 const BufferQueue
& original_splice_buffers
=
1505 pre_splice_buffers
[i
]->splice_buffers();
1506 if (!original_splice_buffers
.empty()) {
1507 DVLOG(1) << "Can't generate splice: overlapped buffers contain a "
1508 "pre-existing splice.";
1512 if (pre_splice_buffers
[i
]->preroll_buffer().get()) {
1513 DVLOG(1) << "Can't generate splice: overlapped buffers contain preroll.";
1518 // Don't generate splice frames which represent less than two frames, since we
1519 // need at least that much to generate a crossfade. Per the spec, make this
1520 // check using the sample rate of the overlapping buffers.
1521 const base::TimeDelta splice_duration
=
1522 pre_splice_buffers
.back()->timestamp() +
1523 pre_splice_buffers
.back()->duration() - splice_timestamp
;
1524 const base::TimeDelta minimum_splice_duration
= base::TimeDelta::FromSecondsD(
1525 2.0 / audio_configs_
[append_config_index_
].samples_per_second());
1526 if (splice_duration
< minimum_splice_duration
) {
1527 DVLOG(1) << "Can't generate splice: not enough samples for crossfade; have "
1528 << splice_duration
.InMicroseconds() << " us, but need "
1529 << minimum_splice_duration
.InMicroseconds() << " us.";
1533 new_buffers
.front()->ConvertToSpliceBuffer(pre_splice_buffers
);
1536 bool SourceBufferStream::SetPendingBuffer(
1537 scoped_refptr
<StreamParserBuffer
>* out_buffer
) {
1538 DCHECK(out_buffer
->get());
1539 DCHECK(!pending_buffer_
.get());
1541 const bool have_splice_buffers
= !(*out_buffer
)->splice_buffers().empty();
1542 const bool have_preroll_buffer
= !!(*out_buffer
)->preroll_buffer().get();
1544 if (!have_splice_buffers
&& !have_preroll_buffer
)
1547 DCHECK_NE(have_splice_buffers
, have_preroll_buffer
);
1548 splice_buffers_index_
= 0;
1549 pending_buffer_
.swap(*out_buffer
);
1550 pending_buffers_complete_
= false;
1554 } // namespace media