Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / media / filters / source_buffer_stream_unittest.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "media/filters/source_buffer_stream.h"
6
7 #include <string>
8
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/logging.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "media/base/data_buffer.h"
16 #include "media/base/media_log.h"
17 #include "media/base/test_helpers.h"
18 #include "media/base/text_track_config.h"
19 #include "media/filters/webvtt_util.h"
20 #include "testing/gtest/include/gtest/gtest.h"
21
22 namespace media {
23
24 typedef StreamParser::BufferQueue BufferQueue;
25
26 static const int kDefaultFramesPerSecond = 30;
27 static const int kDefaultKeyframesPerSecond = 6;
28 static const uint8 kDataA = 0x11;
29 static const uint8 kDataB = 0x33;
30 static const int kDataSize = 1;
31
32 class SourceBufferStreamTest : public testing::Test {
33  protected:
34   SourceBufferStreamTest() {
35     video_config_ = TestVideoConfig::Normal();
36     SetStreamInfo(kDefaultFramesPerSecond, kDefaultKeyframesPerSecond);
37     stream_.reset(new SourceBufferStream(video_config_, log_cb(), true));
38   }
39
40   void SetMemoryLimit(int buffers_of_data) {
41     stream_->set_memory_limit(buffers_of_data * kDataSize);
42   }
43
44   void SetStreamInfo(int frames_per_second, int keyframes_per_second) {
45     frames_per_second_ = frames_per_second;
46     keyframes_per_second_ = keyframes_per_second;
47     frame_duration_ = ConvertToFrameDuration(frames_per_second);
48   }
49
50   void SetTextStream() {
51     video_config_ = TestVideoConfig::Invalid();
52     TextTrackConfig config(kTextSubtitles, "", "", "");
53     stream_.reset(new SourceBufferStream(config, LogCB(), true));
54     SetStreamInfo(2, 2);
55   }
56
57   void SetAudioStream() {
58     video_config_ = TestVideoConfig::Invalid();
59     audio_config_.Initialize(kCodecVorbis,
60                              kSampleFormatPlanarF32,
61                              CHANNEL_LAYOUT_STEREO,
62                              1000,
63                              NULL,
64                              0,
65                              false,
66                              false,
67                              base::TimeDelta(),
68                              0);
69     stream_.reset(new SourceBufferStream(audio_config_, LogCB(), true));
70
71     // Equivalent to 2ms per frame.
72     SetStreamInfo(500, 500);
73   }
74
75   void NewSegmentAppend(int starting_position, int number_of_buffers) {
76     AppendBuffers(starting_position, number_of_buffers, true,
77                   base::TimeDelta(), true, &kDataA, kDataSize);
78   }
79
80   void NewSegmentAppend(int starting_position, int number_of_buffers,
81                         const uint8* data) {
82     AppendBuffers(starting_position, number_of_buffers, true,
83                   base::TimeDelta(), true, data, kDataSize);
84   }
85
86   void NewSegmentAppend_OffsetFirstBuffer(
87       int starting_position, int number_of_buffers,
88       base::TimeDelta first_buffer_offset) {
89     AppendBuffers(starting_position, number_of_buffers, true,
90                   first_buffer_offset, true, &kDataA, kDataSize);
91   }
92
93   void NewSegmentAppend_ExpectFailure(
94       int starting_position, int number_of_buffers) {
95     AppendBuffers(starting_position, number_of_buffers, true,
96                   base::TimeDelta(), false, &kDataA, kDataSize);
97   }
98
99   void AppendBuffers(int starting_position, int number_of_buffers) {
100     AppendBuffers(starting_position, number_of_buffers, false,
101                   base::TimeDelta(), true, &kDataA, kDataSize);
102   }
103
104   void AppendBuffers(int starting_position, int number_of_buffers,
105                      const uint8* data) {
106     AppendBuffers(starting_position, number_of_buffers, false,
107                   base::TimeDelta(), true, data, kDataSize);
108   }
109
110   void NewSegmentAppend(const std::string& buffers_to_append) {
111     AppendBuffers(buffers_to_append, true, kNoTimestamp(), false, true);
112   }
113
114   void NewSegmentAppend(base::TimeDelta start_timestamp,
115                         const std::string& buffers_to_append) {
116     AppendBuffers(buffers_to_append, true, start_timestamp, false, true);
117   }
118
119   void AppendBuffers(const std::string& buffers_to_append) {
120     AppendBuffers(buffers_to_append, false, kNoTimestamp(), false, true);
121   }
122
123   void NewSegmentAppendOneByOne(const std::string& buffers_to_append) {
124     AppendBuffers(buffers_to_append, true, kNoTimestamp(), true, true);
125   }
126
127   void AppendBuffersOneByOne(const std::string& buffers_to_append) {
128     AppendBuffers(buffers_to_append, false, kNoTimestamp(), true, true);
129   }
130
131   void NewSegmentAppend_ExpectFailure(const std::string& buffers_to_append) {
132     AppendBuffers(buffers_to_append, true, kNoTimestamp(), false, false);
133   }
134
135   void AppendBuffers_ExpectFailure(const std::string& buffers_to_append) {
136     AppendBuffers(buffers_to_append, false, kNoTimestamp(), false, false);
137   }
138
139   void Seek(int position) {
140     stream_->Seek(position * frame_duration_);
141   }
142
143   void SeekToTimestamp(base::TimeDelta timestamp) {
144     stream_->Seek(timestamp);
145   }
146
147   void RemoveInMs(int start, int end, int duration) {
148     Remove(base::TimeDelta::FromMilliseconds(start),
149            base::TimeDelta::FromMilliseconds(end),
150            base::TimeDelta::FromMilliseconds(duration));
151   }
152
153   void Remove(base::TimeDelta start, base::TimeDelta end,
154               base::TimeDelta duration) {
155     stream_->Remove(start, end, duration);
156   }
157
158   int GetRemovalRangeInMs(int start, int end, int bytes_to_free,
159                           int* removal_end) {
160     DecodeTimestamp removal_end_timestamp =
161         DecodeTimestamp::FromMilliseconds(*removal_end);
162     int bytes_removed = stream_->GetRemovalRange(
163         DecodeTimestamp::FromMilliseconds(start),
164         DecodeTimestamp::FromMilliseconds(end), bytes_to_free,
165         &removal_end_timestamp);
166     *removal_end = removal_end_timestamp.InMilliseconds();
167     return bytes_removed;
168   }
169
170   void CheckExpectedRanges(const std::string& expected) {
171     Ranges<base::TimeDelta> r = stream_->GetBufferedTime();
172
173     std::stringstream ss;
174     ss << "{ ";
175     for (size_t i = 0; i < r.size(); ++i) {
176       int64 start = (r.start(i) / frame_duration_);
177       int64 end = (r.end(i) / frame_duration_) - 1;
178       ss << "[" << start << "," << end << ") ";
179     }
180     ss << "}";
181     EXPECT_EQ(expected, ss.str());
182   }
183
184   void CheckExpectedRangesByTimestamp(const std::string& expected) {
185     Ranges<base::TimeDelta> r = stream_->GetBufferedTime();
186
187     std::stringstream ss;
188     ss << "{ ";
189     for (size_t i = 0; i < r.size(); ++i) {
190       int64 start = r.start(i).InMilliseconds();
191       int64 end = r.end(i).InMilliseconds();
192       ss << "[" << start << "," << end << ") ";
193     }
194     ss << "}";
195     EXPECT_EQ(expected, ss.str());
196   }
197
198   void CheckExpectedBuffers(
199       int starting_position, int ending_position) {
200     CheckExpectedBuffers(starting_position, ending_position, false, NULL, 0);
201   }
202
203   void CheckExpectedBuffers(
204       int starting_position, int ending_position, bool expect_keyframe) {
205     CheckExpectedBuffers(starting_position, ending_position, expect_keyframe,
206                          NULL, 0);
207   }
208
209   void CheckExpectedBuffers(
210       int starting_position, int ending_position, const uint8* data) {
211     CheckExpectedBuffers(starting_position, ending_position, false, data,
212                          kDataSize);
213   }
214
215   void CheckExpectedBuffers(
216       int starting_position, int ending_position, const uint8* data,
217       bool expect_keyframe) {
218     CheckExpectedBuffers(starting_position, ending_position, expect_keyframe,
219                          data, kDataSize);
220   }
221
222   void CheckExpectedBuffers(
223       int starting_position, int ending_position, bool expect_keyframe,
224       const uint8* expected_data, int expected_size) {
225     int current_position = starting_position;
226     for (; current_position <= ending_position; current_position++) {
227       scoped_refptr<StreamParserBuffer> buffer;
228       SourceBufferStream::Status status = stream_->GetNextBuffer(&buffer);
229
230       EXPECT_NE(status, SourceBufferStream::kConfigChange);
231       if (status != SourceBufferStream::kSuccess)
232         break;
233
234       if (expect_keyframe && current_position == starting_position)
235         EXPECT_TRUE(buffer->IsKeyframe());
236
237       if (expected_data) {
238         const uint8* actual_data = buffer->data();
239         const int actual_size = buffer->data_size();
240         EXPECT_EQ(expected_size, actual_size);
241         for (int i = 0; i < std::min(actual_size, expected_size); i++) {
242           EXPECT_EQ(expected_data[i], actual_data[i]);
243         }
244       }
245
246       EXPECT_EQ(buffer->GetDecodeTimestamp() / frame_duration_,
247                 current_position);
248     }
249
250     EXPECT_EQ(ending_position + 1, current_position);
251   }
252
253   void CheckExpectedBuffers(const std::string& expected) {
254     std::vector<std::string> timestamps;
255     base::SplitString(expected, ' ', &timestamps);
256     std::stringstream ss;
257     const SourceBufferStream::Type type = stream_->GetType();
258     base::TimeDelta active_splice_timestamp = kNoTimestamp();
259     for (size_t i = 0; i < timestamps.size(); i++) {
260       scoped_refptr<StreamParserBuffer> buffer;
261       SourceBufferStream::Status status = stream_->GetNextBuffer(&buffer);
262
263       if (i > 0)
264         ss << " ";
265
266       if (status == SourceBufferStream::kConfigChange) {
267         switch (type) {
268           case SourceBufferStream::kVideo:
269             stream_->GetCurrentVideoDecoderConfig();
270             break;
271           case SourceBufferStream::kAudio:
272             stream_->GetCurrentAudioDecoderConfig();
273             break;
274           case SourceBufferStream::kText:
275             stream_->GetCurrentTextTrackConfig();
276             break;
277         }
278
279         EXPECT_EQ("C", timestamps[i]);
280
281         ss << "C";
282         continue;
283       }
284
285       EXPECT_EQ(SourceBufferStream::kSuccess, status);
286       if (status != SourceBufferStream::kSuccess)
287         break;
288
289       ss << buffer->timestamp().InMilliseconds();
290
291       if (buffer->GetDecodeTimestamp() !=
292           DecodeTimestamp::FromPresentationTime(buffer->timestamp())) {
293         ss << "|" << buffer->GetDecodeTimestamp().InMilliseconds();
294       }
295
296       // Handle preroll buffers.
297       if (EndsWith(timestamps[i], "P", true)) {
298         ASSERT_TRUE(buffer->IsKeyframe());
299         scoped_refptr<StreamParserBuffer> preroll_buffer;
300         preroll_buffer.swap(buffer);
301
302         // When a preroll buffer is encountered we should be able to request one
303         // more buffer.  The first buffer should match the timestamp and config
304         // of the second buffer, except that its discard_padding() should be its
305         // duration.
306         ASSERT_EQ(SourceBufferStream::kSuccess,
307                   stream_->GetNextBuffer(&buffer));
308         ASSERT_EQ(buffer->GetConfigId(), preroll_buffer->GetConfigId());
309         ASSERT_EQ(buffer->track_id(), preroll_buffer->track_id());
310         ASSERT_EQ(buffer->timestamp(), preroll_buffer->timestamp());
311         ASSERT_EQ(buffer->GetDecodeTimestamp(),
312                   preroll_buffer->GetDecodeTimestamp());
313         ASSERT_EQ(kInfiniteDuration(), preroll_buffer->discard_padding().first);
314         ASSERT_EQ(base::TimeDelta(), preroll_buffer->discard_padding().second);
315         ASSERT_TRUE(buffer->IsKeyframe());
316
317         ss << "P";
318       } else if (buffer->IsKeyframe()) {
319         ss << "K";
320       }
321
322       // Until the last splice frame is seen, indicated by a matching timestamp,
323       // all buffers must have the same splice_timestamp().
324       if (buffer->timestamp() == active_splice_timestamp) {
325         ASSERT_EQ(buffer->splice_timestamp(), kNoTimestamp());
326       } else {
327         ASSERT_TRUE(active_splice_timestamp == kNoTimestamp() ||
328                     active_splice_timestamp == buffer->splice_timestamp());
329       }
330
331       active_splice_timestamp = buffer->splice_timestamp();
332     }
333     EXPECT_EQ(expected, ss.str());
334   }
335
336   void CheckNoNextBuffer() {
337     scoped_refptr<StreamParserBuffer> buffer;
338     EXPECT_EQ(SourceBufferStream::kNeedBuffer, stream_->GetNextBuffer(&buffer));
339   }
340
341   void CheckVideoConfig(const VideoDecoderConfig& config) {
342     const VideoDecoderConfig& actual = stream_->GetCurrentVideoDecoderConfig();
343     EXPECT_TRUE(actual.Matches(config))
344         << "Expected: " << config.AsHumanReadableString()
345         << "\nActual: " << actual.AsHumanReadableString();
346   }
347
348   void CheckAudioConfig(const AudioDecoderConfig& config) {
349     const AudioDecoderConfig& actual = stream_->GetCurrentAudioDecoderConfig();
350     EXPECT_TRUE(actual.Matches(config))
351         << "Expected: " << config.AsHumanReadableString()
352         << "\nActual: " << actual.AsHumanReadableString();
353   }
354
355   const LogCB log_cb() {
356     return base::Bind(&SourceBufferStreamTest::DebugMediaLog,
357                       base::Unretained(this));
358   }
359
360   base::TimeDelta frame_duration() const { return frame_duration_; }
361
362   scoped_ptr<SourceBufferStream> stream_;
363   VideoDecoderConfig video_config_;
364   AudioDecoderConfig audio_config_;
365
366  private:
367   base::TimeDelta ConvertToFrameDuration(int frames_per_second) {
368     return base::TimeDelta::FromMicroseconds(
369         base::Time::kMicrosecondsPerSecond / frames_per_second);
370   }
371
372   void AppendBuffers(int starting_position,
373                      int number_of_buffers,
374                      bool begin_media_segment,
375                      base::TimeDelta first_buffer_offset,
376                      bool expect_success,
377                      const uint8* data,
378                      int size) {
379     if (begin_media_segment)
380       stream_->OnNewMediaSegment(DecodeTimestamp::FromPresentationTime(
381           starting_position * frame_duration_));
382
383     int keyframe_interval = frames_per_second_ / keyframes_per_second_;
384
385     BufferQueue queue;
386     for (int i = 0; i < number_of_buffers; i++) {
387       int position = starting_position + i;
388       bool is_keyframe = position % keyframe_interval == 0;
389       // Buffer type and track ID are meaningless to these tests.
390       scoped_refptr<StreamParserBuffer> buffer =
391           StreamParserBuffer::CopyFrom(data, size, is_keyframe,
392                                        DemuxerStream::AUDIO, 0);
393       base::TimeDelta timestamp = frame_duration_ * position;
394
395       if (i == 0)
396         timestamp += first_buffer_offset;
397       buffer->SetDecodeTimestamp(
398           DecodeTimestamp::FromPresentationTime(timestamp));
399
400       // Simulate an IBB...BBP pattern in which all B-frames reference both
401       // the I- and P-frames. For a GOP with playback order 12345, this would
402       // result in a decode timestamp order of 15234.
403       base::TimeDelta presentation_timestamp;
404       if (is_keyframe) {
405         presentation_timestamp = timestamp;
406       } else if ((position - 1) % keyframe_interval == 0) {
407         // This is the P-frame (first frame following the I-frame)
408         presentation_timestamp =
409             (timestamp + frame_duration_ * (keyframe_interval - 2));
410       } else {
411         presentation_timestamp = timestamp - frame_duration_;
412       }
413       buffer->set_timestamp(presentation_timestamp);
414       buffer->set_duration(frame_duration_);
415
416       queue.push_back(buffer);
417     }
418     if (!queue.empty())
419       EXPECT_EQ(expect_success, stream_->Append(queue));
420   }
421
422   void UpdateLastBufferDuration(DecodeTimestamp current_dts,
423                                 BufferQueue* buffers) {
424     if (buffers->empty() || buffers->back()->duration() > base::TimeDelta())
425       return;
426
427     DecodeTimestamp last_dts = buffers->back()->GetDecodeTimestamp();
428     DCHECK(current_dts >= last_dts);
429     buffers->back()->set_duration(current_dts - last_dts);
430   }
431
432   // StringToBufferQueue() allows for the generation of StreamParserBuffers from
433   // coded strings of timestamps separated by spaces.  Supported syntax:
434   //
435   // xx:
436   // Generates a StreamParserBuffer with decode and presentation timestamp xx.
437   // E.g., "0 1 2 3".
438   //
439   // pp|dd:
440   // Generates a StreamParserBuffer with presentation timestamp pp and decode
441   // timestamp dd. E.g., "0|0 3|1 1|2 2|3".
442   //
443   // ##Dzz
444   // Specifies the duration for a buffer. ## represents one of the 2 timestamp
445   // formats above. zz specifies the duration of the buffer in milliseconds.
446   // If the duration isn't specified with this syntax then the buffer duration
447   // is determined by the difference between the decode timestamp in ## and
448   // the decode timestamp of the previous buffer in the string. If the string
449   // only contains 1 buffer then the duration must be explicitly specified with
450   // this format.
451   //
452   // ##K:
453   // Indicates the buffer with timestamp ## reflects a keyframe. ##
454   // can be any of the 3 timestamp formats above.
455   // E.g., "0K 1|2K 2|4D2K".
456   //
457   // S(a# ... y# z#)
458   // Indicates a splice frame buffer should be created with timestamp z#.  The
459   // preceding timestamps a# ... y# will be treated as the fade out preroll for
460   // the splice frame.  If a timestamp within the preroll ends with C the config
461   // id to use for that and subsequent preroll appends is incremented by one.
462   // The config id for non-splice frame appends will not be affected.
463   BufferQueue StringToBufferQueue(const std::string& buffers_to_append) {
464     std::vector<std::string> timestamps;
465     base::SplitString(buffers_to_append, ' ', &timestamps);
466
467     CHECK_GT(timestamps.size(), 0u);
468
469     bool splice_frame = false;
470     size_t splice_config_id = stream_->append_config_index_;
471     BufferQueue pre_splice_buffers;
472     BufferQueue buffers;
473     for (size_t i = 0; i < timestamps.size(); i++) {
474       bool is_keyframe = false;
475       bool has_preroll = false;
476       bool last_splice_frame = false;
477       // Handle splice frame starts.
478       if (StartsWithASCII(timestamps[i], "S(", true)) {
479         CHECK(!splice_frame);
480         splice_frame = true;
481         // Remove the "S(" off of the token.
482         timestamps[i] = timestamps[i].substr(2, timestamps[i].length());
483       }
484       if (splice_frame && EndsWith(timestamps[i], ")", true)) {
485         splice_frame = false;
486         last_splice_frame = true;
487         // Remove the ")" off of the token.
488         timestamps[i] = timestamps[i].substr(0, timestamps[i].length() - 1);
489       }
490       // Handle config changes within the splice frame.
491       if (splice_frame && EndsWith(timestamps[i], "C", true)) {
492         splice_config_id++;
493         CHECK(splice_config_id < stream_->audio_configs_.size() ||
494               splice_config_id < stream_->video_configs_.size());
495         // Remove the "C" off of the token.
496         timestamps[i] = timestamps[i].substr(0, timestamps[i].length() - 1);
497       }
498       if (EndsWith(timestamps[i], "K", true)) {
499         is_keyframe = true;
500         // Remove the "K" off of the token.
501         timestamps[i] = timestamps[i].substr(0, timestamps[i].length() - 1);
502       }
503       // Handle preroll buffers.
504       if (EndsWith(timestamps[i], "P", true)) {
505         is_keyframe = true;
506         has_preroll = true;
507         // Remove the "P" off of the token.
508         timestamps[i] = timestamps[i].substr(0, timestamps[i].length() - 1);
509       }
510
511       int duration_in_ms = 0;
512       size_t duration_pos = timestamps[i].find('D');
513       if (duration_pos != std::string::npos) {
514         CHECK(base::StringToInt(timestamps[i].substr(duration_pos + 1),
515                                 &duration_in_ms));
516         timestamps[i] = timestamps[i].substr(0, duration_pos);
517       }
518
519       std::vector<std::string> buffer_timestamps;
520       base::SplitString(timestamps[i], '|', &buffer_timestamps);
521
522       if (buffer_timestamps.size() == 1)
523         buffer_timestamps.push_back(buffer_timestamps[0]);
524
525       CHECK_EQ(2u, buffer_timestamps.size());
526
527       int pts_in_ms = 0;
528       int dts_in_ms = 0;
529       CHECK(base::StringToInt(buffer_timestamps[0], &pts_in_ms));
530       CHECK(base::StringToInt(buffer_timestamps[1], &dts_in_ms));
531
532       // Create buffer. Buffer type and track ID are meaningless to these tests.
533       scoped_refptr<StreamParserBuffer> buffer =
534           StreamParserBuffer::CopyFrom(&kDataA, kDataSize, is_keyframe,
535                                        DemuxerStream::AUDIO, 0);
536       buffer->set_timestamp(base::TimeDelta::FromMilliseconds(pts_in_ms));
537
538       if (dts_in_ms != pts_in_ms) {
539         buffer->SetDecodeTimestamp(
540             DecodeTimestamp::FromMilliseconds(dts_in_ms));
541       }
542
543       if (duration_in_ms)
544         buffer->set_duration(base::TimeDelta::FromMilliseconds(duration_in_ms));
545
546       // Simulate preroll buffers by just generating another buffer and sticking
547       // it as the preroll.
548       if (has_preroll) {
549         scoped_refptr<StreamParserBuffer> preroll_buffer =
550             StreamParserBuffer::CopyFrom(
551                 &kDataA, kDataSize, is_keyframe, DemuxerStream::AUDIO, 0);
552         preroll_buffer->set_duration(frame_duration_);
553         buffer->SetPrerollBuffer(preroll_buffer);
554       }
555
556       if (splice_frame) {
557         // Make sure that splice frames aren't used with content where decode
558         // and presentation timestamps can differ. (i.e., B-frames)
559         CHECK_EQ(buffer->GetDecodeTimestamp().InMicroseconds(),
560                  buffer->timestamp().InMicroseconds());
561         if (!pre_splice_buffers.empty()) {
562           // Enforce strictly monotonically increasing timestamps.
563           CHECK_GT(
564               buffer->timestamp().InMicroseconds(),
565               pre_splice_buffers.back()->timestamp().InMicroseconds());
566           CHECK_GT(
567               buffer->GetDecodeTimestamp().InMicroseconds(),
568               pre_splice_buffers.back()->GetDecodeTimestamp().InMicroseconds());
569         }
570         buffer->SetConfigId(splice_config_id);
571         UpdateLastBufferDuration(buffer->GetDecodeTimestamp(),
572                                  &pre_splice_buffers);
573         pre_splice_buffers.push_back(buffer);
574         continue;
575       }
576
577       if (last_splice_frame) {
578         // Require at least one additional buffer for a splice.
579         CHECK(!pre_splice_buffers.empty());
580         buffer->SetConfigId(splice_config_id);
581         buffer->ConvertToSpliceBuffer(pre_splice_buffers);
582         pre_splice_buffers.clear();
583       }
584
585       UpdateLastBufferDuration(buffer->GetDecodeTimestamp(), &buffers);
586       buffers.push_back(buffer);
587     }
588
589     // If the last buffer doesn't have a duration, assume it is the
590     // same as the second to last buffer.
591     if (buffers.size() >= 2 &&
592         buffers.back()->duration() <= base::TimeDelta()) {
593       buffers.back()->set_duration(
594           buffers[buffers.size() - 2]->duration());
595     }
596
597     return buffers;
598   }
599
600   void AppendBuffers(const std::string& buffers_to_append,
601                      bool start_new_segment,
602                      base::TimeDelta segment_start_timestamp,
603                      bool one_by_one,
604                      bool expect_success) {
605     BufferQueue buffers = StringToBufferQueue(buffers_to_append);
606
607     if (start_new_segment) {
608       base::TimeDelta start_timestamp = segment_start_timestamp;
609       if (start_timestamp == kNoTimestamp())
610         start_timestamp = buffers[0]->timestamp();
611
612       ASSERT_TRUE(start_timestamp <= buffers[0]->timestamp());
613
614       stream_->OnNewMediaSegment(
615           DecodeTimestamp::FromPresentationTime(start_timestamp));
616     }
617
618     if (!one_by_one) {
619       EXPECT_EQ(expect_success, stream_->Append(buffers));
620       return;
621     }
622
623     // Append each buffer one by one.
624     for (size_t i = 0; i < buffers.size(); i++) {
625       BufferQueue wrapper;
626       wrapper.push_back(buffers[i]);
627       EXPECT_TRUE(stream_->Append(wrapper));
628     }
629   }
630
631   void DebugMediaLog(const std::string& log) {
632     DVLOG(1) << log;
633   }
634
635   int frames_per_second_;
636   int keyframes_per_second_;
637   base::TimeDelta frame_duration_;
638   DISALLOW_COPY_AND_ASSIGN(SourceBufferStreamTest);
639 };
640
641 TEST_F(SourceBufferStreamTest, Append_SingleRange) {
642   // Append 15 buffers at positions 0 through 14.
643   NewSegmentAppend(0, 15);
644
645   // Check expected range.
646   CheckExpectedRanges("{ [0,14) }");
647   // Check buffers in range.
648   Seek(0);
649   CheckExpectedBuffers(0, 14);
650 }
651
652 TEST_F(SourceBufferStreamTest, Append_SingleRange_OneBufferAtATime) {
653   // Append 15 buffers starting at position 0, one buffer at a time.
654   NewSegmentAppend(0, 1);
655   for (int i = 1; i < 15; i++)
656     AppendBuffers(i, 1);
657
658   // Check expected range.
659   CheckExpectedRanges("{ [0,14) }");
660   // Check buffers in range.
661   Seek(0);
662   CheckExpectedBuffers(0, 14);
663 }
664
665 TEST_F(SourceBufferStreamTest, Append_DisjointRanges) {
666   // Append 5 buffers at positions 0 through 4.
667   NewSegmentAppend(0, 5);
668
669   // Append 10 buffers at positions 15 through 24.
670   NewSegmentAppend(15, 10);
671
672   // Check expected ranges.
673   CheckExpectedRanges("{ [0,4) [15,24) }");
674   // Check buffers in ranges.
675   Seek(0);
676   CheckExpectedBuffers(0, 4);
677   Seek(15);
678   CheckExpectedBuffers(15, 24);
679 }
680
681 TEST_F(SourceBufferStreamTest, Append_AdjacentRanges) {
682   // Append 10 buffers at positions 0 through 9.
683   NewSegmentAppend(0, 10);
684
685   // Append 11 buffers at positions 15 through 25.
686   NewSegmentAppend(15, 11);
687
688   // Append 5 buffers at positions 10 through 14 to bridge the gap.
689   NewSegmentAppend(10, 5);
690
691   // Check expected range.
692   CheckExpectedRanges("{ [0,25) }");
693   // Check buffers in range.
694   Seek(0);
695   CheckExpectedBuffers(0, 25);
696 }
697
698 TEST_F(SourceBufferStreamTest, Append_DoesNotBeginWithKeyframe) {
699   // Append fails because the range doesn't begin with a keyframe.
700   NewSegmentAppend_ExpectFailure(3, 2);
701
702   // Append 10 buffers at positions 5 through 14.
703   NewSegmentAppend(5, 10);
704
705   // Check expected range.
706   CheckExpectedRanges("{ [5,14) }");
707   // Check buffers in range.
708   Seek(5);
709   CheckExpectedBuffers(5, 14);
710
711   // Append fails because the range doesn't begin with a keyframe.
712   NewSegmentAppend_ExpectFailure(17, 3);
713
714   CheckExpectedRanges("{ [5,14) }");
715   Seek(5);
716   CheckExpectedBuffers(5, 14);
717 }
718
719 TEST_F(SourceBufferStreamTest, Append_DoesNotBeginWithKeyframe_Adjacent) {
720   // Append 8 buffers at positions 0 through 7.
721   NewSegmentAppend(0, 8);
722
723   // Now start a new media segment at position 8. Append should fail because
724   // the media segment does not begin with a keyframe.
725   NewSegmentAppend_ExpectFailure(8, 2);
726
727   // Check expected range.
728   CheckExpectedRanges("{ [0,7) }");
729   // Check buffers in range.
730   Seek(0);
731   CheckExpectedBuffers(0, 7);
732 }
733
734 TEST_F(SourceBufferStreamTest, Complete_Overlap) {
735   // Append 5 buffers at positions 5 through 9.
736   NewSegmentAppend(5, 5);
737
738   // Append 15 buffers at positions 0 through 14.
739   NewSegmentAppend(0, 15);
740
741   // Check expected range.
742   CheckExpectedRanges("{ [0,14) }");
743   // Check buffers in range.
744   Seek(0);
745   CheckExpectedBuffers(0, 14);
746 }
747
748 TEST_F(SourceBufferStreamTest,
749        Complete_Overlap_AfterSegmentTimestampAndBeforeFirstBufferTimestamp) {
750   // Append a segment with a start timestamp of 0, but the first
751   // buffer starts at 30ms. This can happen in muxed content where the
752   // audio starts before the first frame.
753   NewSegmentAppend(base::TimeDelta::FromMilliseconds(0), "30K 60K 90K 120K");
754
755   CheckExpectedRangesByTimestamp("{ [0,150) }");
756
757   // Completely overlap the old buffers, with a segment that starts
758   // after the old segment start timestamp, but before the timestamp
759   // of the first buffer in the segment.
760   NewSegmentAppend("20K 50K 80K 110D10K");
761
762   // Verify that the buffered ranges are updated properly and we don't crash.
763   CheckExpectedRangesByTimestamp("{ [20,150) }");
764
765   SeekToTimestamp(base::TimeDelta::FromMilliseconds(20));
766   CheckExpectedBuffers("20K 50K 80K 110K 120K");
767 }
768
769 TEST_F(SourceBufferStreamTest, Complete_Overlap_EdgeCase) {
770   // Make each frame a keyframe so that it's okay to overlap frames at any point
771   // (instead of needing to respect keyframe boundaries).
772   SetStreamInfo(30, 30);
773
774   // Append 6 buffers at positions 6 through 11.
775   NewSegmentAppend(6, 6);
776
777   // Append 8 buffers at positions 5 through 12.
778   NewSegmentAppend(5, 8);
779
780   // Check expected range.
781   CheckExpectedRanges("{ [5,12) }");
782   // Check buffers in range.
783   Seek(5);
784   CheckExpectedBuffers(5, 12);
785 }
786
787 TEST_F(SourceBufferStreamTest, Start_Overlap) {
788   // Append 10 buffers at positions 5 through 14.
789   NewSegmentAppend(5, 5);
790
791   // Append 6 buffers at positions 10 through 15.
792   NewSegmentAppend(10, 6);
793
794   // Check expected range.
795   CheckExpectedRanges("{ [5,15) }");
796   // Check buffers in range.
797   Seek(5);
798   CheckExpectedBuffers(5, 15);
799 }
800
801 TEST_F(SourceBufferStreamTest, End_Overlap) {
802   // Append 10 buffers at positions 10 through 19.
803   NewSegmentAppend(10, 10);
804
805   // Append 10 buffers at positions 5 through 14.
806   NewSegmentAppend(5, 10);
807
808   // Check expected range.
809   CheckExpectedRanges("{ [5,19) }");
810   // Check buffers in range.
811   Seek(5);
812   CheckExpectedBuffers(5, 19);
813 }
814
815 TEST_F(SourceBufferStreamTest, End_Overlap_Several) {
816   // Append 10 buffers at positions 10 through 19.
817   NewSegmentAppend(10, 10);
818
819   // Append 8 buffers at positions 5 through 12.
820   NewSegmentAppend(5, 8);
821
822   // Check expected ranges: stream should not have kept buffers 13 and 14
823   // because the keyframe on which they depended was overwritten.
824   CheckExpectedRanges("{ [5,12) [15,19) }");
825
826   // Check buffers in range.
827   Seek(5);
828   CheckExpectedBuffers(5, 12);
829   CheckNoNextBuffer();
830
831   Seek(19);
832   CheckExpectedBuffers(15, 19);
833 }
834
835 // Test an end overlap edge case where a single buffer overlaps the
836 // beginning of a range.
837 // old  : *0K*   30   60   90   120K  150
838 // new  : *0K*
839 // after: *0K*                 *120K* 150K
840 // track:
841 TEST_F(SourceBufferStreamTest, End_Overlap_SingleBuffer) {
842   // Seek to start of stream.
843   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
844
845   NewSegmentAppend("0K 30 60 90 120K 150");
846   CheckExpectedRangesByTimestamp("{ [0,180) }");
847
848   NewSegmentAppend("0D30K");
849   CheckExpectedRangesByTimestamp("{ [0,30) [120,180) }");
850
851   CheckExpectedBuffers("0K");
852   CheckNoNextBuffer();
853 }
854
855 TEST_F(SourceBufferStreamTest, Complete_Overlap_Several) {
856   // Append 2 buffers at positions 5 through 6.
857   NewSegmentAppend(5, 2);
858
859   // Append 2 buffers at positions 10 through 11.
860   NewSegmentAppend(10, 2);
861
862   // Append 2 buffers at positions 15 through 16.
863   NewSegmentAppend(15, 2);
864
865   // Check expected ranges.
866   CheckExpectedRanges("{ [5,6) [10,11) [15,16) }");
867
868   // Append buffers at positions 0 through 19.
869   NewSegmentAppend(0, 20);
870
871   // Check expected range.
872   CheckExpectedRanges("{ [0,19) }");
873   // Check buffers in range.
874   Seek(0);
875   CheckExpectedBuffers(0, 19);
876 }
877
878 TEST_F(SourceBufferStreamTest, Complete_Overlap_Several_Then_Merge) {
879   // Append 2 buffers at positions 5 through 6.
880   NewSegmentAppend(5, 2);
881
882   // Append 2 buffers at positions 10 through 11.
883   NewSegmentAppend(10, 2);
884
885   // Append 2 buffers at positions 15 through 16.
886   NewSegmentAppend(15, 2);
887
888   // Append 2 buffers at positions 20 through 21.
889   NewSegmentAppend(20, 2);
890
891   // Append buffers at positions 0 through 19.
892   NewSegmentAppend(0, 20);
893
894   // Check expected ranges.
895   CheckExpectedRanges("{ [0,21) }");
896   // Check buffers in range.
897   Seek(0);
898   CheckExpectedBuffers(0, 21);
899 }
900
901 TEST_F(SourceBufferStreamTest, Complete_Overlap_Selected) {
902   // Append 10 buffers at positions 5 through 14.
903   NewSegmentAppend(5, 10, &kDataA);
904
905   // Seek to buffer at position 5.
906   Seek(5);
907
908   // Replace old data with new data.
909   NewSegmentAppend(5, 10, &kDataB);
910
911   // Check ranges are correct.
912   CheckExpectedRanges("{ [5,14) }");
913
914   // Check that data has been replaced with new data.
915   CheckExpectedBuffers(5, 14, &kDataB);
916 }
917
918 // This test is testing that a client can append data to SourceBufferStream that
919 // overlaps the range from which the client is currently grabbing buffers. We
920 // would expect that the SourceBufferStream would return old data until it hits
921 // the keyframe of the new data, after which it will return the new data.
922 TEST_F(SourceBufferStreamTest, Complete_Overlap_Selected_TrackBuffer) {
923   // Append 10 buffers at positions 5 through 14.
924   NewSegmentAppend(5, 10, &kDataA);
925
926   // Seek to buffer at position 5 and get next buffer.
927   Seek(5);
928   CheckExpectedBuffers(5, 5, &kDataA);
929
930   // Do a complete overlap by appending 20 buffers at positions 0 through 19.
931   NewSegmentAppend(0, 20, &kDataB);
932
933   // Check range is correct.
934   CheckExpectedRanges("{ [0,19) }");
935
936   // Expect old data up until next keyframe in new data.
937   CheckExpectedBuffers(6, 9, &kDataA);
938   CheckExpectedBuffers(10, 10, &kDataB, true);
939
940   // Expect rest of data to be new.
941   CheckExpectedBuffers(11, 19, &kDataB);
942
943   // Seek back to beginning; all data should be new.
944   Seek(0);
945   CheckExpectedBuffers(0, 19, &kDataB);
946
947   // Check range continues to be correct.
948   CheckExpectedRanges("{ [0,19) }");
949 }
950
951 TEST_F(SourceBufferStreamTest, Complete_Overlap_Selected_EdgeCase) {
952   // Append 10 buffers at positions 5 through 14.
953   NewSegmentAppend(5, 10, &kDataA);
954
955   // Seek to buffer at position 5 and get next buffer.
956   Seek(5);
957   CheckExpectedBuffers(5, 5, &kDataA);
958
959   // Replace existing data with new data.
960   NewSegmentAppend(5, 10, &kDataB);
961
962   // Check ranges are correct.
963   CheckExpectedRanges("{ [5,14) }");
964
965   // Expect old data up until next keyframe in new data.
966   CheckExpectedBuffers(6, 9, &kDataA);
967   CheckExpectedBuffers(10, 10, &kDataB, true);
968
969   // Expect rest of data to be new.
970   CheckExpectedBuffers(11, 14, &kDataB);
971
972   // Seek back to beginning; all data should be new.
973   Seek(5);
974   CheckExpectedBuffers(5, 14, &kDataB);
975
976   // Check range continues to be correct.
977   CheckExpectedRanges("{ [5,14) }");
978 }
979
980 TEST_F(SourceBufferStreamTest, Complete_Overlap_Selected_Multiple) {
981   static const uint8 kDataC = 0x55;
982   static const uint8 kDataD = 0x77;
983
984   // Append 5 buffers at positions 5 through 9.
985   NewSegmentAppend(5, 5, &kDataA);
986
987   // Seek to buffer at position 5 and get next buffer.
988   Seek(5);
989   CheckExpectedBuffers(5, 5, &kDataA);
990
991   // Replace existing data with new data.
992   NewSegmentAppend(5, 5, &kDataB);
993
994   // Then replace it again with different data.
995   NewSegmentAppend(5, 5, &kDataC);
996
997   // Now append 5 new buffers at positions 10 through 14.
998   NewSegmentAppend(10, 5, &kDataC);
999
1000   // Now replace all the data entirely.
1001   NewSegmentAppend(5, 10, &kDataD);
1002
1003   // Expect buffers 6 through 9 to be DataA, and the remaining
1004   // buffers to be kDataD.
1005   CheckExpectedBuffers(6, 9, &kDataA);
1006   CheckExpectedBuffers(10, 14, &kDataD);
1007
1008   // At this point we cannot fulfill request.
1009   CheckNoNextBuffer();
1010
1011   // Seek back to beginning; all data should be new.
1012   Seek(5);
1013   CheckExpectedBuffers(5, 14, &kDataD);
1014 }
1015
1016 TEST_F(SourceBufferStreamTest, Start_Overlap_Selected) {
1017   // Append 10 buffers at positions 0 through 9.
1018   NewSegmentAppend(0, 10, &kDataA);
1019
1020   // Seek to position 5, then add buffers to overlap data at that position.
1021   Seek(5);
1022   NewSegmentAppend(5, 10, &kDataB);
1023
1024   // Check expected range.
1025   CheckExpectedRanges("{ [0,14) }");
1026
1027   // Because we seeked to a keyframe, the next buffers should all be new data.
1028   CheckExpectedBuffers(5, 14, &kDataB);
1029
1030   // Make sure all data is correct.
1031   Seek(0);
1032   CheckExpectedBuffers(0, 4, &kDataA);
1033   CheckExpectedBuffers(5, 14, &kDataB);
1034 }
1035
1036 TEST_F(SourceBufferStreamTest, Start_Overlap_Selected_TrackBuffer) {
1037   // Append 15 buffers at positions 0 through 14.
1038   NewSegmentAppend(0, 15, &kDataA);
1039
1040   // Seek to 10 and get buffer.
1041   Seek(10);
1042   CheckExpectedBuffers(10, 10, &kDataA);
1043
1044   // Now append 10 buffers of new data at positions 10 through 19.
1045   NewSegmentAppend(10, 10, &kDataB);
1046
1047   // Check expected range.
1048   CheckExpectedRanges("{ [0,19) }");
1049
1050   // The next 4 buffers should be a from the old buffer, followed by a keyframe
1051   // from the new data.
1052   CheckExpectedBuffers(11, 14, &kDataA);
1053   CheckExpectedBuffers(15, 15, &kDataB, true);
1054
1055   // The rest of the buffers should be new data.
1056   CheckExpectedBuffers(16, 19, &kDataB);
1057
1058   // Now seek to the beginning; positions 0 through 9 should be the original
1059   // data, positions 10 through 19 should be the new data.
1060   Seek(0);
1061   CheckExpectedBuffers(0, 9, &kDataA);
1062   CheckExpectedBuffers(10, 19, &kDataB);
1063
1064   // Make sure range is still correct.
1065   CheckExpectedRanges("{ [0,19) }");
1066 }
1067
1068 TEST_F(SourceBufferStreamTest, Start_Overlap_Selected_EdgeCase) {
1069   // Append 10 buffers at positions 5 through 14.
1070   NewSegmentAppend(5, 10, &kDataA);
1071
1072   Seek(10);
1073   CheckExpectedBuffers(10, 10, &kDataA);
1074
1075   // Now replace the last 5 buffers with new data.
1076   NewSegmentAppend(10, 5, &kDataB);
1077
1078   // The next 4 buffers should be the origial data, held in the track buffer.
1079   CheckExpectedBuffers(11, 14, &kDataA);
1080
1081   // The next buffer is at position 15, so we should fail to fulfill the
1082   // request.
1083   CheckNoNextBuffer();
1084
1085   // Now append data at 15 through 19 and check to make sure it's correct.
1086   NewSegmentAppend(15, 5, &kDataB);
1087   CheckExpectedBuffers(15, 19, &kDataB);
1088
1089   // Seek to beginning of buffered range and check buffers.
1090   Seek(5);
1091   CheckExpectedBuffers(5, 9, &kDataA);
1092   CheckExpectedBuffers(10, 19, &kDataB);
1093
1094   // Check expected range.
1095   CheckExpectedRanges("{ [5,19) }");
1096 }
1097
1098 // This test covers the case where new buffers end-overlap an existing, selected
1099 // range, and the next buffer is a keyframe that's being overlapped by new
1100 // buffers.
1101 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1102 // old Â :           *A*a a a a A a a a a
1103 // new Â :  B b b b b B b b b b
1104 // after:  B b b b b*B*b b b b A a a a a
1105 TEST_F(SourceBufferStreamTest, End_Overlap_Selected) {
1106   // Append 10 buffers at positions 5 through 14.
1107   NewSegmentAppend(5, 10, &kDataA);
1108
1109   // Seek to position 5.
1110   Seek(5);
1111
1112   // Now append 10 buffers at positions 0 through 9.
1113   NewSegmentAppend(0, 10, &kDataB);
1114
1115   // Check expected range.
1116   CheckExpectedRanges("{ [0,14) }");
1117
1118   // Because we seeked to a keyframe, the next buffers should be new.
1119   CheckExpectedBuffers(5, 9, &kDataB);
1120
1121   // Make sure all data is correct.
1122   Seek(0);
1123   CheckExpectedBuffers(0, 9, &kDataB);
1124   CheckExpectedBuffers(10, 14, &kDataA);
1125 }
1126
1127 // This test covers the case where new buffers end-overlap an existing, selected
1128 // range, and the next buffer in the range is after the newly appended buffers.
1129 // In this particular case, the end overlap does not require a split.
1130 //
1131 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1132 // old Â :           |A a a a a A a a*a*a|
1133 // new Â :  B b b b b B b b b b
1134 // after: |B b b b b B b b b b A a a*a*a|
1135 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_AfterEndOfNew_1) {
1136   // Append 10 buffers at positions 5 through 14.
1137   NewSegmentAppend(5, 10, &kDataA);
1138
1139   // Seek to position 10, then move to position 13.
1140   Seek(10);
1141   CheckExpectedBuffers(10, 12, &kDataA);
1142
1143   // Now append 10 buffers at positions 0 through 9.
1144   NewSegmentAppend(0, 10, &kDataB);
1145
1146   // Check expected range.
1147   CheckExpectedRanges("{ [0,14) }");
1148
1149   // Make sure rest of data is as expected.
1150   CheckExpectedBuffers(13, 14, &kDataA);
1151
1152   // Make sure all data is correct.
1153   Seek(0);
1154   CheckExpectedBuffers(0, 9, &kDataB);
1155   CheckExpectedBuffers(10, 14, &kDataA);
1156 }
1157
1158 // This test covers the case where new buffers end-overlap an existing, selected
1159 // range, and the next buffer in the range is after the newly appended buffers.
1160 // In this particular case, the end overlap requires a split, and the next
1161 // buffer is in the split range.
1162 //
1163 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1164 // old Â :           |A a a a a A a a*a*a|
1165 // new Â :  B b b b b B b b
1166 // after: |B b b b b B b b|   |A a a*a*a|
1167 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_AfterEndOfNew_2) {
1168   // Append 10 buffers at positions 5 through 14.
1169   NewSegmentAppend(5, 10, &kDataA);
1170
1171   // Seek to position 10, then move to position 13.
1172   Seek(10);
1173   CheckExpectedBuffers(10, 12, &kDataA);
1174
1175   // Now append 8 buffers at positions 0 through 7.
1176   NewSegmentAppend(0, 8, &kDataB);
1177
1178   // Check expected ranges.
1179   CheckExpectedRanges("{ [0,7) [10,14) }");
1180
1181   // Make sure rest of data is as expected.
1182   CheckExpectedBuffers(13, 14, &kDataA);
1183
1184   // Make sure all data is correct.
1185   Seek(0);
1186   CheckExpectedBuffers(0, 7, &kDataB);
1187   CheckNoNextBuffer();
1188
1189   Seek(10);
1190   CheckExpectedBuffers(10, 14, &kDataA);
1191 }
1192
1193 // This test covers the case where new buffers end-overlap an existing, selected
1194 // range, and the next buffer in the range is after the newly appended buffers.
1195 // In this particular case, the end overlap requires a split, and the next
1196 // buffer was in between the end of the new data and the split range.
1197 //
1198 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1199 // old Â :           |A a a*a*a A a a a a|
1200 // new Â :  B b b b b B b b
1201 // after: |B b b b b B b b|   |A a a a a|
1202 // track:                 |a a|
1203 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_AfterEndOfNew_3) {
1204   // Append 10 buffers at positions 5 through 14.
1205   NewSegmentAppend(5, 10, &kDataA);
1206
1207   // Seek to position 5, then move to position 8.
1208   Seek(5);
1209   CheckExpectedBuffers(5, 7, &kDataA);
1210
1211   // Now append 8 buffers at positions 0 through 7.
1212   NewSegmentAppend(0, 8, &kDataB);
1213
1214   // Check expected ranges.
1215   CheckExpectedRanges("{ [0,7) [10,14) }");
1216
1217   // Check for data in the track buffer.
1218   CheckExpectedBuffers(8, 9, &kDataA);
1219   // The buffer immediately after the track buffer should be a keyframe.
1220   CheckExpectedBuffers(10, 10, &kDataA, true);
1221
1222   // Make sure all data is correct.
1223   Seek(0);
1224   CheckExpectedBuffers(0, 7, &kDataB);
1225   Seek(10);
1226   CheckExpectedBuffers(10, 14, &kDataA);
1227 }
1228
1229 // This test covers the case where new buffers end-overlap an existing, selected
1230 // range, and the next buffer in the range is overlapped by the new buffers.
1231 // In this particular case, the end overlap does not require a split.
1232 //
1233 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1234 // old Â :           |A a a*a*a A a a a a|
1235 // new Â :  B b b b b B b b b b
1236 // after: |B b b b b B b b b b A a a a a|
1237 // track:                 |a a|
1238 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_OverlappedByNew_1) {
1239   // Append 10 buffers at positions 5 through 14.
1240   NewSegmentAppend(5, 10, &kDataA);
1241
1242   // Seek to position 5, then move to position 8.
1243   Seek(5);
1244   CheckExpectedBuffers(5, 7, &kDataA);
1245
1246   // Now append 10 buffers at positions 0 through 9.
1247   NewSegmentAppend(0, 10, &kDataB);
1248
1249   // Check expected range.
1250   CheckExpectedRanges("{ [0,14) }");
1251
1252   // Check for data in the track buffer.
1253   CheckExpectedBuffers(8, 9, &kDataA);
1254   // The buffer immediately after the track buffer should be a keyframe.
1255   CheckExpectedBuffers(10, 10, &kDataA, true);
1256
1257   // Make sure all data is correct.
1258   Seek(0);
1259   CheckExpectedBuffers(0, 9, &kDataB);
1260   CheckExpectedBuffers(10, 14, &kDataA);
1261 }
1262
1263 // This test covers the case where new buffers end-overlap an existing, selected
1264 // range, and the next buffer in the range is overlapped by the new buffers.
1265 // In this particular case, the end overlap requires a split, and the next
1266 // keyframe after the track buffer is in the split range.
1267 //
1268 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1269 // old Â :           |A*a*a a a A a a a a|
1270 // new Â :  B b b b b B b
1271 // after: |B b b b b B b|     |A a a a a|
1272 // track:             |a a a a|
1273 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_OverlappedByNew_2) {
1274   // Append 10 buffers at positions 5 through 14.
1275   NewSegmentAppend(5, 10, &kDataA);
1276
1277   // Seek to position 5, then move to position 6.
1278   Seek(5);
1279   CheckExpectedBuffers(5, 5, &kDataA);
1280
1281   // Now append 7 buffers at positions 0 through 6.
1282   NewSegmentAppend(0, 7, &kDataB);
1283
1284   // Check expected ranges.
1285   CheckExpectedRanges("{ [0,6) [10,14) }");
1286
1287   // Check for data in the track buffer.
1288   CheckExpectedBuffers(6, 9, &kDataA);
1289   // The buffer immediately after the track buffer should be a keyframe.
1290   CheckExpectedBuffers(10, 10, &kDataA, true);
1291
1292   // Make sure all data is correct.
1293   Seek(0);
1294   CheckExpectedBuffers(0, 6, &kDataB);
1295   CheckNoNextBuffer();
1296
1297   Seek(10);
1298   CheckExpectedBuffers(10, 14, &kDataA);
1299 }
1300
1301 // This test covers the case where new buffers end-overlap an existing, selected
1302 // range, and the next buffer in the range is overlapped by the new buffers.
1303 // In this particular case, the end overlap requires a split, and the next
1304 // keyframe after the track buffer is in the range with the new buffers.
1305 //
1306 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1307 // old Â :           |A*a*a a a A a a a a A a a a a|
1308 // new Â :  B b b b b B b b b b B b b
1309 // after: |B b b b b B b b b b B b b|   |A a a a a|
1310 // track:             |a a a a|
1311 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_OverlappedByNew_3) {
1312   // Append 15 buffers at positions 5 through 19.
1313   NewSegmentAppend(5, 15, &kDataA);
1314
1315   // Seek to position 5, then move to position 6.
1316   Seek(5);
1317   CheckExpectedBuffers(5, 5, &kDataA);
1318
1319   // Now append 13 buffers at positions 0 through 12.
1320   NewSegmentAppend(0, 13, &kDataB);
1321
1322   // Check expected ranges.
1323   CheckExpectedRanges("{ [0,12) [15,19) }");
1324
1325   // Check for data in the track buffer.
1326   CheckExpectedBuffers(6, 9, &kDataA);
1327   // The buffer immediately after the track buffer should be a keyframe
1328   // from the new data.
1329   CheckExpectedBuffers(10, 10, &kDataB, true);
1330
1331   // Make sure all data is correct.
1332   Seek(0);
1333   CheckExpectedBuffers(0, 12, &kDataB);
1334   CheckNoNextBuffer();
1335
1336   Seek(15);
1337   CheckExpectedBuffers(15, 19, &kDataA);
1338 }
1339
1340 // This test covers the case where new buffers end-overlap an existing, selected
1341 // range, and there is no keyframe after the end of the new buffers.
1342 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1343 // old Â :           |A*a*a a a|
1344 // new Â :  B b b b b B
1345 // after: |B b b b b B|
1346 // track:             |a a a a|
1347 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_NoKeyframeAfterNew) {
1348   // Append 5 buffers at positions 5 through 9.
1349   NewSegmentAppend(5, 5, &kDataA);
1350
1351   // Seek to position 5, then move to position 6.
1352   Seek(5);
1353   CheckExpectedBuffers(5, 5, &kDataA);
1354
1355   // Now append 6 buffers at positions 0 through 5.
1356   NewSegmentAppend(0, 6, &kDataB);
1357
1358   // Check expected range.
1359   CheckExpectedRanges("{ [0,5) }");
1360
1361   // Check for data in the track buffer.
1362   CheckExpectedBuffers(6, 9, &kDataA);
1363
1364   // Now there's no data to fulfill the request.
1365   CheckNoNextBuffer();
1366
1367   // Let's fill in the gap, buffers 6 through 10.
1368   AppendBuffers(6, 5, &kDataB);
1369
1370   // We should be able to get the next buffer.
1371   CheckExpectedBuffers(10, 10, &kDataB);
1372 }
1373
1374 // This test covers the case where new buffers end-overlap an existing, selected
1375 // range, and there is no keyframe after the end of the new buffers, then the
1376 // range gets split.
1377 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1378 // old Â :                     |A a a a a A*a*|
1379 // new Â :            B b b b b B b b b b B
1380 // after:           |B b b b b B b b b b B|
1381 // new Â :  A a a a a A
1382 // after: |A a a a a A|       |B b b b b B|
1383 // track:                                 |a|
1384 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_NoKeyframeAfterNew2) {
1385   // Append 7 buffers at positions 10 through 16.
1386   NewSegmentAppend(10, 7, &kDataA);
1387
1388   // Seek to position 15, then move to position 16.
1389   Seek(15);
1390   CheckExpectedBuffers(15, 15, &kDataA);
1391
1392   // Now append 11 buffers at positions 5 through 15.
1393   NewSegmentAppend(5, 11, &kDataB);
1394   CheckExpectedRanges("{ [5,15) }");
1395
1396   // Now do another end-overlap to split the range into two parts, where the
1397   // 2nd range should have the next buffer position.
1398   NewSegmentAppend(0, 6, &kDataA);
1399   CheckExpectedRanges("{ [0,5) [10,15) }");
1400
1401   // Check for data in the track buffer.
1402   CheckExpectedBuffers(16, 16, &kDataA);
1403
1404   // Now there's no data to fulfill the request.
1405   CheckNoNextBuffer();
1406
1407   // Add data to the 2nd range, should not be able to fulfill the next read
1408   // until we've added a keyframe.
1409   NewSegmentAppend(15, 1, &kDataB);
1410   CheckNoNextBuffer();
1411   for (int i = 16; i <= 19; i++) {
1412     AppendBuffers(i, 1, &kDataB);
1413     CheckNoNextBuffer();
1414   }
1415
1416   // Now append a keyframe.
1417   AppendBuffers(20, 1, &kDataB);
1418
1419   // We should be able to get the next buffer.
1420   CheckExpectedBuffers(20, 20, &kDataB, true);
1421 }
1422
1423 // This test covers the case where new buffers end-overlap an existing, selected
1424 // range, and the next keyframe in a separate range.
1425 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1426 // old Â :           |A*a*a a a|          |A a a a a|
1427 // new Â :  B b b b b B
1428 // after: |B b b b b B|                  |A a a a a|
1429 // track:             |a a a a|
1430 TEST_F(SourceBufferStreamTest, End_Overlap_Selected_NoKeyframeAfterNew3) {
1431   // Append 5 buffers at positions 5 through 9.
1432   NewSegmentAppend(5, 5, &kDataA);
1433
1434   // Append 5 buffers at positions 15 through 19.
1435   NewSegmentAppend(15, 5, &kDataA);
1436
1437   // Check expected range.
1438   CheckExpectedRanges("{ [5,9) [15,19) }");
1439
1440   // Seek to position 5, then move to position 6.
1441   Seek(5);
1442   CheckExpectedBuffers(5, 5, &kDataA);
1443
1444   // Now append 6 buffers at positions 0 through 5.
1445   NewSegmentAppend(0, 6, &kDataB);
1446
1447   // Check expected range.
1448   CheckExpectedRanges("{ [0,5) [15,19) }");
1449
1450   // Check for data in the track buffer.
1451   CheckExpectedBuffers(6, 9, &kDataA);
1452
1453   // Now there's no data to fulfill the request.
1454   CheckNoNextBuffer();
1455
1456   // Let's fill in the gap, buffers 6 through 14.
1457   AppendBuffers(6, 9, &kDataB);
1458
1459   // Check expected range.
1460   CheckExpectedRanges("{ [0,19) }");
1461
1462   // We should be able to get the next buffer.
1463   CheckExpectedBuffers(10, 14, &kDataB);
1464
1465   // We should be able to get the next buffer.
1466   CheckExpectedBuffers(15, 19, &kDataA);
1467 }
1468
1469 // This test covers the case when new buffers overlap the middle of a selected
1470 // range. This tests the case when there is no split and the next buffer is a
1471 // keyframe.
1472 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1473 // old Â :  A a a a a*A*a a a a A a a a a
1474 // new Â :            B b b b b
1475 // after:  A a a a a*B*b b b b A a a a a
1476 TEST_F(SourceBufferStreamTest, Middle_Overlap_Selected_1) {
1477   // Append 15 buffers at positions 0 through 14.
1478   NewSegmentAppend(0, 15, &kDataA);
1479
1480   // Seek to position 5.
1481   Seek(5);
1482
1483   // Now append 5 buffers at positions 5 through 9.
1484   NewSegmentAppend(5, 5, &kDataB);
1485
1486   // Check expected range.
1487   CheckExpectedRanges("{ [0,14) }");
1488
1489   // Check for next data; should be new data.
1490   CheckExpectedBuffers(5, 9, &kDataB);
1491
1492   // Make sure all data is correct.
1493   Seek(0);
1494   CheckExpectedBuffers(0, 4, &kDataA);
1495   CheckExpectedBuffers(5, 9, &kDataB);
1496   CheckExpectedBuffers(10, 14, &kDataA);
1497 }
1498
1499 // This test covers the case when new buffers overlap the middle of a selected
1500 // range. This tests the case when there is no split and the next buffer is
1501 // after the new buffers.
1502 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1503 // old Â :  A a a a a A a a a a A*a*a a a
1504 // new Â :            B b b b b
1505 // after:  A a a a a B b b b b A*a*a a a
1506 TEST_F(SourceBufferStreamTest, Middle_Overlap_Selected_2) {
1507   // Append 15 buffers at positions 0 through 14.
1508   NewSegmentAppend(0, 15, &kDataA);
1509
1510   // Seek to 10 then move to position 11.
1511   Seek(10);
1512   CheckExpectedBuffers(10, 10, &kDataA);
1513
1514   // Now append 5 buffers at positions 5 through 9.
1515   NewSegmentAppend(5, 5, &kDataB);
1516
1517   // Check expected range.
1518   CheckExpectedRanges("{ [0,14) }");
1519
1520   // Make sure data is correct.
1521   CheckExpectedBuffers(11, 14, &kDataA);
1522   Seek(0);
1523   CheckExpectedBuffers(0, 4, &kDataA);
1524   CheckExpectedBuffers(5, 9, &kDataB);
1525   CheckExpectedBuffers(10, 14, &kDataA);
1526 }
1527
1528 // This test covers the case when new buffers overlap the middle of a selected
1529 // range. This tests the case when there is a split and the next buffer is
1530 // before the new buffers.
1531 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1532 // old Â :  A a*a*a a A a a a a A a a a a
1533 // new Â :            B b b
1534 // after:  A a*a*a a B b b|   |A a a a a
1535 TEST_F(SourceBufferStreamTest, Middle_Overlap_Selected_3) {
1536   // Append 15 buffers at positions 0 through 14.
1537   NewSegmentAppend(0, 15, &kDataA);
1538
1539   // Seek to beginning then move to position 2.
1540   Seek(0);
1541   CheckExpectedBuffers(0, 1, &kDataA);
1542
1543   // Now append 3 buffers at positions 5 through 7.
1544   NewSegmentAppend(5, 3, &kDataB);
1545
1546   // Check expected range.
1547   CheckExpectedRanges("{ [0,7) [10,14) }");
1548
1549   // Make sure data is correct.
1550   CheckExpectedBuffers(2, 4, &kDataA);
1551   CheckExpectedBuffers(5, 7, &kDataB);
1552   Seek(10);
1553   CheckExpectedBuffers(10, 14, &kDataA);
1554 }
1555
1556 // This test covers the case when new buffers overlap the middle of a selected
1557 // range. This tests the case when there is a split and the next buffer is after
1558 // the new buffers but before the split range.
1559 // index:  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
1560 // old Â :  A a a a a A a a*a*a A a a a a
1561 // new Â :            B b b
1562 // after: |A a a a a B b b|   |A a a a a|
1563 // track:                 |a a|
1564 TEST_F(SourceBufferStreamTest, Middle_Overlap_Selected_4) {
1565   // Append 15 buffers at positions 0 through 14.
1566   NewSegmentAppend(0, 15, &kDataA);
1567
1568   // Seek to 5 then move to position 8.
1569   Seek(5);
1570   CheckExpectedBuffers(5, 7, &kDataA);
1571
1572   // Now append 3 buffers at positions 5 through 7.
1573   NewSegmentAppend(5, 3, &kDataB);
1574
1575   // Check expected range.
1576   CheckExpectedRanges("{ [0,7) [10,14) }");
1577
1578   // Buffers 8 and 9 should be in the track buffer.
1579   CheckExpectedBuffers(8, 9, &kDataA);
1580   // The buffer immediately after the track buffer should be a keyframe.
1581   CheckExpectedBuffers(10, 10, &kDataA, true);
1582
1583   // Make sure all data is correct.
1584   Seek(0);
1585   CheckExpectedBuffers(0, 4, &kDataA);
1586   CheckExpectedBuffers(5, 7, &kDataB);
1587   Seek(10);
1588   CheckExpectedBuffers(10, 14, &kDataA);
1589 }
1590
1591 TEST_F(SourceBufferStreamTest, Overlap_OneByOne) {
1592   // Append 5 buffers starting at 10ms, 30ms apart.
1593   NewSegmentAppendOneByOne("10K 40 70 100 130");
1594
1595   // The range ends at 160, accounting for the last buffer's duration.
1596   CheckExpectedRangesByTimestamp("{ [10,160) }");
1597
1598   // Overlap with 10 buffers starting at the beginning, appended one at a
1599   // time.
1600   NewSegmentAppend(0, 1, &kDataB);
1601   for (int i = 1; i < 10; i++)
1602     AppendBuffers(i, 1, &kDataB);
1603
1604   // All data should be replaced.
1605   Seek(0);
1606   CheckExpectedRanges("{ [0,9) }");
1607   CheckExpectedBuffers(0, 9, &kDataB);
1608 }
1609
1610 TEST_F(SourceBufferStreamTest, Overlap_OneByOne_DeleteGroup) {
1611   NewSegmentAppendOneByOne("10K 40 70 100 130K");
1612   CheckExpectedRangesByTimestamp("{ [10,160) }");
1613
1614   // Seek to 130ms.
1615   SeekToTimestamp(base::TimeDelta::FromMilliseconds(130));
1616
1617   // Overlap with a new segment from 0 to 130ms.
1618   NewSegmentAppendOneByOne("0K 120D10");
1619
1620   // Next buffer should still be 130ms.
1621   CheckExpectedBuffers("130K");
1622
1623   // Check the final buffers is correct.
1624   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
1625   CheckExpectedBuffers("0K 120 130K");
1626 }
1627
1628 TEST_F(SourceBufferStreamTest, Overlap_OneByOne_BetweenMediaSegments) {
1629   // Append 5 buffers starting at 110ms, 30ms apart.
1630   NewSegmentAppendOneByOne("110K 140 170 200 230");
1631   CheckExpectedRangesByTimestamp("{ [110,260) }");
1632
1633   // Now append 2 media segments from 0ms to 210ms, 30ms apart. Note that the
1634   // old keyframe 110ms falls in between these two segments.
1635   NewSegmentAppendOneByOne("0K 30 60 90");
1636   NewSegmentAppendOneByOne("120K 150 180 210");
1637   CheckExpectedRangesByTimestamp("{ [0,240) }");
1638
1639   // Check the final buffers is correct; the keyframe at 110ms should be
1640   // deleted.
1641   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
1642   CheckExpectedBuffers("0K 30 60 90 120K 150 180 210");
1643 }
1644
1645 // old  :   10K  40  *70*  100K  125  130K
1646 // new  : 0K   30   60   90   120K
1647 // after: 0K   30   60   90  *120K*   130K
1648 TEST_F(SourceBufferStreamTest, Overlap_OneByOne_TrackBuffer) {
1649   NewSegmentAppendOneByOne("10K 40 70 100K 125 130D30K");
1650   CheckExpectedRangesByTimestamp("{ [10,160) }");
1651
1652   // Seek to 70ms.
1653   SeekToTimestamp(base::TimeDelta::FromMilliseconds(70));
1654   CheckExpectedBuffers("10K 40");
1655
1656   // Overlap with a new segment from 0 to 130ms.
1657   NewSegmentAppendOneByOne("0K 30 60 90 120D10K");
1658   CheckExpectedRangesByTimestamp("{ [0,160) }");
1659
1660   // Should return frame 70ms from the track buffer, then switch
1661   // to the new data at 120K, then switch back to the old data at 130K. The
1662   // frame at 125ms that depended on keyframe 100ms should have been deleted.
1663   CheckExpectedBuffers("70 120K 130K");
1664
1665   // Check the final result: should not include data from the track buffer.
1666   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
1667   CheckExpectedBuffers("0K 30 60 90 120K 130K");
1668 }
1669
1670 // Overlap the next keyframe after the end of the track buffer with a new
1671 // keyframe.
1672 // old  :   10K  40  *70*  100K  125  130K
1673 // new  : 0K   30   60   90   120K
1674 // after: 0K   30   60   90  *120K*   130K
1675 // track:             70
1676 // new  :                     110K    130
1677 // after: 0K   30   60   90  *110K*   130
1678 TEST_F(SourceBufferStreamTest, Overlap_OneByOne_TrackBuffer2) {
1679   NewSegmentAppendOneByOne("10K 40 70 100K 125 130D30K");
1680   CheckExpectedRangesByTimestamp("{ [10,160) }");
1681
1682   // Seek to 70ms.
1683   SeekToTimestamp(base::TimeDelta::FromMilliseconds(70));
1684   CheckExpectedBuffers("10K 40");
1685
1686   // Overlap with a new segment from 0 to 120ms; 70ms and 100ms go in track
1687   // buffer.
1688   NewSegmentAppendOneByOne("0K 30 60 90 120D10K");
1689   CheckExpectedRangesByTimestamp("{ [0,160) }");
1690
1691   // Now overlap the keyframe at 120ms.
1692   NewSegmentAppendOneByOne("110K 130");
1693
1694   // Should return frame 70ms from the track buffer. Then it should
1695   // return the keyframe after the track buffer, which is at 110ms.
1696   CheckExpectedBuffers("70 110K 130");
1697 }
1698
1699 // Overlap the next keyframe after the end of the track buffer without a
1700 // new keyframe.
1701 // old  :   10K  40  *70*  100K  125  130K
1702 // new  : 0K   30   60   90   120K
1703 // after: 0K   30   60   90  *120K*   130K
1704 // track:             70
1705 // new  :        50K   80   110          140
1706 // after: 0K   30   50K   80   110   140 * (waiting for keyframe)
1707 // track:             70
1708 TEST_F(SourceBufferStreamTest, Overlap_OneByOne_TrackBuffer3) {
1709   NewSegmentAppendOneByOne("10K 40 70 100K 125 130D30K");
1710   CheckExpectedRangesByTimestamp("{ [10,160) }");
1711
1712   // Seek to 70ms.
1713   SeekToTimestamp(base::TimeDelta::FromMilliseconds(70));
1714   CheckExpectedBuffers("10K 40");
1715
1716   // Overlap with a new segment from 0 to 120ms; 70ms goes in track buffer.
1717   NewSegmentAppendOneByOne("0K 30 60 90 120D10K");
1718   CheckExpectedRangesByTimestamp("{ [0,160) }");
1719
1720   // Now overlap the keyframe at 120ms and 130ms.
1721   NewSegmentAppendOneByOne("50K 80 110 140");
1722   CheckExpectedRangesByTimestamp("{ [0,170) }");
1723
1724   // Should have all the buffers from the track buffer, then stall.
1725   CheckExpectedBuffers("70");
1726   CheckNoNextBuffer();
1727
1728   // Appending a keyframe should fulfill the read.
1729   AppendBuffersOneByOne("150D30K");
1730   CheckExpectedBuffers("150K");
1731   CheckNoNextBuffer();
1732 }
1733
1734 // Overlap the next keyframe after the end of the track buffer with a keyframe
1735 // that comes before the end of the track buffer.
1736 // old  :   10K  40  *70*  100K  125  130K
1737 // new  : 0K   30   60   90   120K
1738 // after: 0K   30   60   90  *120K*   130K
1739 // track:             70
1740 // new  :              80K  110          140
1741 // after: 0K   30   60   *80K*  110   140
1742 // track:               70
1743 TEST_F(SourceBufferStreamTest, Overlap_OneByOne_TrackBuffer4) {
1744   NewSegmentAppendOneByOne("10K 40 70 100K 125 130D30K");
1745   CheckExpectedRangesByTimestamp("{ [10,160) }");
1746
1747   // Seek to 70ms.
1748   SeekToTimestamp(base::TimeDelta::FromMilliseconds(70));
1749   CheckExpectedBuffers("10K 40");
1750
1751   // Overlap with a new segment from 0 to 120ms; 70ms and 100ms go in track
1752   // buffer.
1753   NewSegmentAppendOneByOne("0K 30 60 90 120D10K");
1754   CheckExpectedRangesByTimestamp("{ [0,160) }");
1755
1756   // Now append a keyframe at 80ms.
1757   NewSegmentAppendOneByOne("80K 110 140");
1758
1759   CheckExpectedBuffers("70 80K 110 140");
1760   CheckNoNextBuffer();
1761 }
1762
1763 // Overlap the next keyframe after the end of the track buffer with a keyframe
1764 // that comes before the end of the track buffer, when the selected stream was
1765 // waiting for the next keyframe.
1766 // old  :   10K  40  *70*  100K
1767 // new  : 0K   30   60   90   120
1768 // after: 0K   30   60   90   120 * (waiting for keyframe)
1769 // track:             70
1770 // new  :              80K  110          140
1771 // after: 0K   30   60   *80K*  110   140
1772 // track:               70
1773 TEST_F(SourceBufferStreamTest, Overlap_OneByOne_TrackBuffer5) {
1774   NewSegmentAppendOneByOne("10K 40 70 100K");
1775   CheckExpectedRangesByTimestamp("{ [10,130) }");
1776
1777   // Seek to 70ms.
1778   SeekToTimestamp(base::TimeDelta::FromMilliseconds(70));
1779   CheckExpectedBuffers("10K 40");
1780
1781   // Overlap with a new segment from 0 to 120ms; 70ms goes in track
1782   // buffer.
1783   NewSegmentAppendOneByOne("0K 30 60 90 120");
1784   CheckExpectedRangesByTimestamp("{ [0,150) }");
1785
1786   // Now append a keyframe at 80ms.
1787   NewSegmentAppendOneByOne("80K 110 140");
1788
1789   CheckExpectedBuffers("70 80K 110 140");
1790   CheckNoNextBuffer();
1791 }
1792
1793 // Test that appending to a different range while there is data in
1794 // the track buffer doesn't affect the selected range or track buffer state.
1795 // old  :   10K  40  *70*  100K  125  130K ... 200K 230
1796 // new  : 0K   30   60   90   120K
1797 // after: 0K   30   60   90  *120K*   130K ... 200K 230
1798 // track:             70
1799 // old  : 0K   30   60   90  *120K*   130K ... 200K 230
1800 // new  :                                               260K 290
1801 // after: 0K   30   60   90  *120K*   130K ... 200K 230 260K 290
1802 // track:             70
1803 TEST_F(SourceBufferStreamTest, Overlap_OneByOne_TrackBuffer6) {
1804   NewSegmentAppendOneByOne("10K 40 70 100K 125 130D30K");
1805   NewSegmentAppendOneByOne("200K 230");
1806   CheckExpectedRangesByTimestamp("{ [10,160) [200,260) }");
1807
1808   // Seek to 70ms.
1809   SeekToTimestamp(base::TimeDelta::FromMilliseconds(70));
1810   CheckExpectedBuffers("10K 40");
1811
1812   // Overlap with a new segment from 0 to 120ms.
1813   NewSegmentAppendOneByOne("0K 30 60 90 120D10K");
1814   CheckExpectedRangesByTimestamp("{ [0,160) [200,260) }");
1815
1816   // Verify that 70 gets read out of the track buffer.
1817   CheckExpectedBuffers("70");
1818
1819   // Append more data to the unselected range.
1820   NewSegmentAppendOneByOne("260K 290");
1821   CheckExpectedRangesByTimestamp("{ [0,160) [200,320) }");
1822
1823   CheckExpectedBuffers("120K 130K");
1824   CheckNoNextBuffer();
1825
1826   // Check the final result: should not include data from the track buffer.
1827   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
1828   CheckExpectedBuffers("0K 30 60 90 120K 130K");
1829   CheckNoNextBuffer();
1830 }
1831
1832 TEST_F(SourceBufferStreamTest, Seek_Keyframe) {
1833   // Append 6 buffers at positions 0 through 5.
1834   NewSegmentAppend(0, 6);
1835
1836   // Seek to beginning.
1837   Seek(0);
1838   CheckExpectedBuffers(0, 5, true);
1839 }
1840
1841 TEST_F(SourceBufferStreamTest, Seek_NonKeyframe) {
1842   // Append 15 buffers at positions 0 through 14.
1843   NewSegmentAppend(0, 15);
1844
1845   // Seek to buffer at position 13.
1846   Seek(13);
1847
1848   // Expect seeking back to the nearest keyframe.
1849   CheckExpectedBuffers(10, 14, true);
1850
1851   // Seek to buffer at position 3.
1852   Seek(3);
1853
1854   // Expect seeking back to the nearest keyframe.
1855   CheckExpectedBuffers(0, 3, true);
1856 }
1857
1858 TEST_F(SourceBufferStreamTest, Seek_NotBuffered) {
1859   // Seek to beginning.
1860   Seek(0);
1861
1862   // Try to get buffer; nothing's appended.
1863   CheckNoNextBuffer();
1864
1865   // Append 2 buffers at positions 0.
1866   NewSegmentAppend(0, 2);
1867   Seek(0);
1868   CheckExpectedBuffers(0, 1);
1869
1870   // Try to get buffer out of range.
1871   Seek(2);
1872   CheckNoNextBuffer();
1873 }
1874
1875 TEST_F(SourceBufferStreamTest, Seek_InBetweenTimestamps) {
1876   // Append 10 buffers at positions 0 through 9.
1877   NewSegmentAppend(0, 10);
1878
1879   base::TimeDelta bump = frame_duration() / 4;
1880   CHECK(bump > base::TimeDelta());
1881
1882   // Seek to buffer a little after position 5.
1883   stream_->Seek(5 * frame_duration() + bump);
1884   CheckExpectedBuffers(5, 5, true);
1885
1886   // Seek to buffer a little before position 5.
1887   stream_->Seek(5 * frame_duration() - bump);
1888   CheckExpectedBuffers(0, 0, true);
1889 }
1890
1891 // This test will do a complete overlap of an existing range in order to add
1892 // buffers to the track buffers. Then the test does a seek to another part of
1893 // the stream. The SourceBufferStream should clear its internal track buffer in
1894 // response to the Seek().
1895 TEST_F(SourceBufferStreamTest, Seek_After_TrackBuffer_Filled) {
1896   // Append 10 buffers at positions 5 through 14.
1897   NewSegmentAppend(5, 10, &kDataA);
1898
1899   // Seek to buffer at position 5 and get next buffer.
1900   Seek(5);
1901   CheckExpectedBuffers(5, 5, &kDataA);
1902
1903   // Do a complete overlap by appending 20 buffers at positions 0 through 19.
1904   NewSegmentAppend(0, 20, &kDataB);
1905
1906   // Check range is correct.
1907   CheckExpectedRanges("{ [0,19) }");
1908
1909   // Seek to beginning; all data should be new.
1910   Seek(0);
1911   CheckExpectedBuffers(0, 19, &kDataB);
1912
1913   // Check range continues to be correct.
1914   CheckExpectedRanges("{ [0,19) }");
1915 }
1916
1917 TEST_F(SourceBufferStreamTest, Seek_StartOfSegment) {
1918   base::TimeDelta bump = frame_duration() / 4;
1919   CHECK(bump > base::TimeDelta());
1920
1921   // Append 5 buffers at position (5 + |bump|) through 9, where the media
1922   // segment begins at position 5.
1923   Seek(5);
1924   NewSegmentAppend_OffsetFirstBuffer(5, 5, bump);
1925   scoped_refptr<StreamParserBuffer> buffer;
1926
1927   // GetNextBuffer() should return the next buffer at position (5 + |bump|).
1928   EXPECT_EQ(stream_->GetNextBuffer(&buffer), SourceBufferStream::kSuccess);
1929   EXPECT_EQ(buffer->GetDecodeTimestamp(),
1930             DecodeTimestamp::FromPresentationTime(5 * frame_duration() + bump));
1931
1932   // Check rest of buffers.
1933   CheckExpectedBuffers(6, 9);
1934
1935   // Seek to position 15.
1936   Seek(15);
1937
1938   // Append 5 buffers at positions (15 + |bump|) through 19, where the media
1939   // segment begins at 15.
1940   NewSegmentAppend_OffsetFirstBuffer(15, 5, bump);
1941
1942   // GetNextBuffer() should return the next buffer at position (15 + |bump|).
1943   EXPECT_EQ(stream_->GetNextBuffer(&buffer), SourceBufferStream::kSuccess);
1944   EXPECT_EQ(buffer->GetDecodeTimestamp(), DecodeTimestamp::FromPresentationTime(
1945       15 * frame_duration() + bump));
1946
1947   // Check rest of buffers.
1948   CheckExpectedBuffers(16, 19);
1949 }
1950
1951 TEST_F(SourceBufferStreamTest, Seek_BeforeStartOfSegment) {
1952   // Append 10 buffers at positions 5 through 14.
1953   NewSegmentAppend(5, 10);
1954
1955   // Seek to a time before the first buffer in the range.
1956   Seek(0);
1957
1958   // Should return buffers from the beginning of the range.
1959   CheckExpectedBuffers(5, 14);
1960 }
1961
1962 TEST_F(SourceBufferStreamTest, OldSeekPoint_CompleteOverlap) {
1963   // Append 5 buffers at positions 0 through 4.
1964   NewSegmentAppend(0, 4);
1965
1966   // Append 5 buffers at positions 10 through 14, and seek to the beginning of
1967   // this range.
1968   NewSegmentAppend(10, 5);
1969   Seek(10);
1970
1971   // Now seek to the beginning of the first range.
1972   Seek(0);
1973
1974   // Completely overlap the old seek point.
1975   NewSegmentAppend(5, 15);
1976
1977   // The GetNextBuffer() call should respect the 2nd seek point.
1978   CheckExpectedBuffers(0, 0);
1979 }
1980
1981 TEST_F(SourceBufferStreamTest, OldSeekPoint_CompleteOverlap_Pending) {
1982   // Append 2 buffers at positions 0 through 1.
1983   NewSegmentAppend(0, 2);
1984
1985   // Append 5 buffers at positions 15 through 19 and seek to beginning of the
1986   // range.
1987   NewSegmentAppend(15, 5);
1988   Seek(15);
1989
1990   // Now seek position 5.
1991   Seek(5);
1992
1993   // Completely overlap the old seek point.
1994   NewSegmentAppend(10, 15);
1995
1996   // The seek at position 5 should still be pending.
1997   CheckNoNextBuffer();
1998 }
1999
2000 TEST_F(SourceBufferStreamTest, OldSeekPoint_MiddleOverlap) {
2001   // Append 2 buffers at positions 0 through 1.
2002   NewSegmentAppend(0, 2);
2003
2004   // Append 15 buffers at positions 5 through 19 and seek to position 15.
2005   NewSegmentAppend(5, 15);
2006   Seek(15);
2007
2008   // Now seek to the beginning of the stream.
2009   Seek(0);
2010
2011   // Overlap the middle of the range such that there are now three ranges.
2012   NewSegmentAppend(10, 3);
2013   CheckExpectedRanges("{ [0,1) [5,12) [15,19) }");
2014
2015   // The GetNextBuffer() call should respect the 2nd seek point.
2016   CheckExpectedBuffers(0, 0);
2017 }
2018
2019 TEST_F(SourceBufferStreamTest, OldSeekPoint_MiddleOverlap_Pending) {
2020   // Append 2 buffers at positions 0 through 1.
2021   NewSegmentAppend(0, 2);
2022
2023   // Append 15 buffers at positions 10 through 24 and seek to position 20.
2024   NewSegmentAppend(10, 15);
2025   Seek(20);
2026
2027   // Now seek to position 5.
2028   Seek(5);
2029
2030   // Overlap the middle of the range such that it is now split into two ranges.
2031   NewSegmentAppend(15, 3);
2032   CheckExpectedRanges("{ [0,1) [10,17) [20,24) }");
2033
2034   // The seek at position 5 should still be pending.
2035   CheckNoNextBuffer();
2036 }
2037
2038 TEST_F(SourceBufferStreamTest, OldSeekPoint_StartOverlap) {
2039   // Append 2 buffers at positions 0 through 1.
2040   NewSegmentAppend(0, 2);
2041
2042   // Append 15 buffers at positions 5 through 19 and seek to position 15.
2043   NewSegmentAppend(5, 15);
2044   Seek(15);
2045
2046   // Now seek to the beginning of the stream.
2047   Seek(0);
2048
2049   // Start overlap the old seek point.
2050   NewSegmentAppend(10, 10);
2051
2052   // The GetNextBuffer() call should respect the 2nd seek point.
2053   CheckExpectedBuffers(0, 0);
2054 }
2055
2056 TEST_F(SourceBufferStreamTest, OldSeekPoint_StartOverlap_Pending) {
2057   // Append 2 buffers at positions 0 through 1.
2058   NewSegmentAppend(0, 2);
2059
2060   // Append 15 buffers at positions 10 through 24 and seek to position 20.
2061   NewSegmentAppend(10, 15);
2062   Seek(20);
2063
2064   // Now seek to position 5.
2065   Seek(5);
2066
2067   // Start overlap the old seek point.
2068   NewSegmentAppend(15, 10);
2069
2070   // The seek at time 0 should still be pending.
2071   CheckNoNextBuffer();
2072 }
2073
2074 TEST_F(SourceBufferStreamTest, OldSeekPoint_EndOverlap) {
2075   // Append 5 buffers at positions 0 through 4.
2076   NewSegmentAppend(0, 4);
2077
2078   // Append 15 buffers at positions 10 through 24 and seek to start of range.
2079   NewSegmentAppend(10, 15);
2080   Seek(10);
2081
2082   // Now seek to the beginning of the stream.
2083   Seek(0);
2084
2085   // End overlap the old seek point.
2086   NewSegmentAppend(5, 10);
2087
2088   // The GetNextBuffer() call should respect the 2nd seek point.
2089   CheckExpectedBuffers(0, 0);
2090 }
2091
2092 TEST_F(SourceBufferStreamTest, OldSeekPoint_EndOverlap_Pending) {
2093   // Append 2 buffers at positions 0 through 1.
2094   NewSegmentAppend(0, 2);
2095
2096   // Append 15 buffers at positions 15 through 29 and seek to start of range.
2097   NewSegmentAppend(15, 15);
2098   Seek(15);
2099
2100   // Now seek to position 5
2101   Seek(5);
2102
2103   // End overlap the old seek point.
2104   NewSegmentAppend(10, 10);
2105
2106   // The seek at time 0 should still be pending.
2107   CheckNoNextBuffer();
2108 }
2109
2110 TEST_F(SourceBufferStreamTest, GetNextBuffer_AfterMerges) {
2111   // Append 5 buffers at positions 10 through 14.
2112   NewSegmentAppend(10, 5);
2113
2114   // Seek to buffer at position 12.
2115   Seek(12);
2116
2117   // Append 5 buffers at positions 5 through 9.
2118   NewSegmentAppend(5, 5);
2119
2120   // Make sure ranges are merged.
2121   CheckExpectedRanges("{ [5,14) }");
2122
2123   // Make sure the next buffer is correct.
2124   CheckExpectedBuffers(10, 10);
2125
2126   // Append 5 buffers at positions 15 through 19.
2127   NewSegmentAppend(15, 5);
2128   CheckExpectedRanges("{ [5,19) }");
2129
2130   // Make sure the remaining next buffers are correct.
2131   CheckExpectedBuffers(11, 14);
2132 }
2133
2134 TEST_F(SourceBufferStreamTest, GetNextBuffer_ExhaustThenAppend) {
2135   // Append 4 buffers at positions 0 through 3.
2136   NewSegmentAppend(0, 4);
2137
2138   // Seek to buffer at position 0 and get all buffers.
2139   Seek(0);
2140   CheckExpectedBuffers(0, 3);
2141
2142   // Next buffer is at position 4, so should not be able to fulfill request.
2143   CheckNoNextBuffer();
2144
2145   // Append 2 buffers at positions 4 through 5.
2146   AppendBuffers(4, 2);
2147   CheckExpectedBuffers(4, 5);
2148 }
2149
2150 // This test covers the case where new buffers start-overlap a range whose next
2151 // buffer is not buffered.
2152 TEST_F(SourceBufferStreamTest, GetNextBuffer_ExhaustThenStartOverlap) {
2153   // Append 10 buffers at positions 0 through 9 and exhaust the buffers.
2154   NewSegmentAppend(0, 10, &kDataA);
2155   Seek(0);
2156   CheckExpectedBuffers(0, 9, &kDataA);
2157
2158   // Next buffer is at position 10, so should not be able to fulfill request.
2159   CheckNoNextBuffer();
2160
2161   // Append 6 buffers at positons 5 through 10. This is to test that doing a
2162   // start-overlap successfully fulfills the read at position 10, even though
2163   // position 10 was unbuffered.
2164   NewSegmentAppend(5, 6, &kDataB);
2165   CheckExpectedBuffers(10, 10, &kDataB);
2166
2167   // Then add 5 buffers from positions 11 though 15.
2168   AppendBuffers(11, 5, &kDataB);
2169
2170   // Check the next 4 buffers are correct, which also effectively seeks to
2171   // position 15.
2172   CheckExpectedBuffers(11, 14, &kDataB);
2173
2174   // Replace the next buffer at position 15 with another start overlap.
2175   NewSegmentAppend(15, 2, &kDataA);
2176   CheckExpectedBuffers(15, 16, &kDataA);
2177 }
2178
2179 // Tests a start overlap that occurs right at the timestamp of the last output
2180 // buffer that was returned by GetNextBuffer(). This test verifies that
2181 // GetNextBuffer() skips to second GOP in the newly appended data instead
2182 // of returning two buffers with the same timestamp.
2183 TEST_F(SourceBufferStreamTest, GetNextBuffer_ExhaustThenStartOverlap2) {
2184   NewSegmentAppend("0K 30 60 90 120");
2185
2186   Seek(0);
2187   CheckExpectedBuffers("0K 30 60 90 120");
2188   CheckNoNextBuffer();
2189
2190   // Append a keyframe with the same timestamp as the last buffer output.
2191   NewSegmentAppend("120D30K");
2192   CheckNoNextBuffer();
2193
2194   // Append the rest of the segment and make sure that buffers are returned
2195   // from the first GOP after 120.
2196   AppendBuffers("150 180 210K 240");
2197   CheckExpectedBuffers("210K 240");
2198
2199   // Seek to the beginning and verify the contents of the source buffer.
2200   Seek(0);
2201   CheckExpectedBuffers("0K 30 60 90 120K 150 180 210K 240");
2202   CheckNoNextBuffer();
2203 }
2204
2205 // This test covers the case where new buffers completely overlap a range
2206 // whose next buffer is not buffered.
2207 TEST_F(SourceBufferStreamTest, GetNextBuffer_ExhaustThenCompleteOverlap) {
2208   // Append 5 buffers at positions 10 through 14 and exhaust the buffers.
2209   NewSegmentAppend(10, 5, &kDataA);
2210   Seek(10);
2211   CheckExpectedBuffers(10, 14, &kDataA);
2212
2213   // Next buffer is at position 15, so should not be able to fulfill request.
2214   CheckNoNextBuffer();
2215
2216   // Do a complete overlap and test that this successfully fulfills the read
2217   // at position 15.
2218   NewSegmentAppend(5, 11, &kDataB);
2219   CheckExpectedBuffers(15, 15, &kDataB);
2220
2221   // Then add 5 buffers from positions 16 though 20.
2222   AppendBuffers(16, 5, &kDataB);
2223
2224   // Check the next 4 buffers are correct, which also effectively seeks to
2225   // position 20.
2226   CheckExpectedBuffers(16, 19, &kDataB);
2227
2228   // Do a complete overlap and replace the buffer at position 20.
2229   NewSegmentAppend(0, 21, &kDataA);
2230   CheckExpectedBuffers(20, 20, &kDataA);
2231 }
2232
2233 // This test covers the case where a range is stalled waiting for its next
2234 // buffer, then an end-overlap causes the end of the range to be deleted.
2235 TEST_F(SourceBufferStreamTest, GetNextBuffer_ExhaustThenEndOverlap) {
2236   // Append 5 buffers at positions 10 through 14 and exhaust the buffers.
2237   NewSegmentAppend(10, 5, &kDataA);
2238   Seek(10);
2239   CheckExpectedBuffers(10, 14, &kDataA);
2240   CheckExpectedRanges("{ [10,14) }");
2241
2242   // Next buffer is at position 15, so should not be able to fulfill request.
2243   CheckNoNextBuffer();
2244
2245   // Do an end overlap that causes the latter half of the range to be deleted.
2246   NewSegmentAppend(5, 6, &kDataB);
2247   CheckNoNextBuffer();
2248   CheckExpectedRanges("{ [5,10) }");
2249
2250   // Fill in the gap. Getting the next buffer should still stall at position 15.
2251   for (int i = 11; i <= 14; i++) {
2252     AppendBuffers(i, 1, &kDataB);
2253     CheckNoNextBuffer();
2254   }
2255
2256   // Append the buffer at position 15 and check to make sure all is correct.
2257   AppendBuffers(15, 1);
2258   CheckExpectedBuffers(15, 15);
2259   CheckExpectedRanges("{ [5,15) }");
2260 }
2261
2262 // This test is testing the "next buffer" logic after a complete overlap. In
2263 // this scenario, when the track buffer is exhausted, there is no buffered data
2264 // to fulfill the request. The SourceBufferStream should be able to fulfill the
2265 // request when the data is later appended, and should not lose track of the
2266 // "next buffer" position.
2267 TEST_F(SourceBufferStreamTest, GetNextBuffer_Overlap_Selected_Complete) {
2268   // Append 5 buffers at positions 5 through 9.
2269   NewSegmentAppend(5, 5, &kDataA);
2270
2271   // Seek to buffer at position 5 and get next buffer.
2272   Seek(5);
2273   CheckExpectedBuffers(5, 5, &kDataA);
2274
2275   // Replace existing data with new data.
2276   NewSegmentAppend(5, 5, &kDataB);
2277
2278   // Expect old data up until next keyframe in new data.
2279   CheckExpectedBuffers(6, 9, &kDataA);
2280
2281   // Next buffer is at position 10, so should not be able to fulfill the
2282   // request.
2283   CheckNoNextBuffer();
2284
2285   // Now add 5 new buffers at positions 10 through 14.
2286   AppendBuffers(10, 5, &kDataB);
2287   CheckExpectedBuffers(10, 14, &kDataB);
2288 }
2289
2290 TEST_F(SourceBufferStreamTest, PresentationTimestampIndependence) {
2291   // Append 20 buffers at position 0.
2292   NewSegmentAppend(0, 20);
2293   Seek(0);
2294
2295   int last_keyframe_idx = -1;
2296   base::TimeDelta last_keyframe_presentation_timestamp;
2297   base::TimeDelta last_p_frame_presentation_timestamp;
2298
2299   // Check for IBB...BBP pattern.
2300   for (int i = 0; i < 20; i++) {
2301     scoped_refptr<StreamParserBuffer> buffer;
2302     ASSERT_EQ(stream_->GetNextBuffer(&buffer), SourceBufferStream::kSuccess);
2303
2304     if (buffer->IsKeyframe()) {
2305       EXPECT_EQ(DecodeTimestamp::FromPresentationTime(buffer->timestamp()),
2306                 buffer->GetDecodeTimestamp());
2307       last_keyframe_idx = i;
2308       last_keyframe_presentation_timestamp = buffer->timestamp();
2309     } else if (i == last_keyframe_idx + 1) {
2310       ASSERT_NE(last_keyframe_idx, -1);
2311       last_p_frame_presentation_timestamp = buffer->timestamp();
2312       EXPECT_LT(last_keyframe_presentation_timestamp,
2313                 last_p_frame_presentation_timestamp);
2314     } else {
2315       EXPECT_GT(buffer->timestamp(), last_keyframe_presentation_timestamp);
2316       EXPECT_LT(buffer->timestamp(), last_p_frame_presentation_timestamp);
2317       EXPECT_LT(DecodeTimestamp::FromPresentationTime(buffer->timestamp()),
2318                 buffer->GetDecodeTimestamp());
2319     }
2320   }
2321 }
2322
2323 TEST_F(SourceBufferStreamTest, GarbageCollection_DeleteFront) {
2324   // Set memory limit to 20 buffers.
2325   SetMemoryLimit(20);
2326
2327   // Append 20 buffers at positions 0 through 19.
2328   NewSegmentAppend(0, 1, &kDataA);
2329   for (int i = 1; i < 20; i++)
2330     AppendBuffers(i, 1, &kDataA);
2331
2332   // None of the buffers should trigger garbage collection, so all data should
2333   // be there as expected.
2334   CheckExpectedRanges("{ [0,19) }");
2335   Seek(0);
2336   CheckExpectedBuffers(0, 19, &kDataA);
2337
2338   // Seek to the middle of the stream.
2339   Seek(10);
2340
2341   // Append 5 buffers to the end of the stream.
2342   AppendBuffers(20, 5, &kDataA);
2343
2344   // GC should have deleted the first 5 buffers.
2345   CheckExpectedRanges("{ [5,24) }");
2346   CheckExpectedBuffers(10, 24, &kDataA);
2347   Seek(5);
2348   CheckExpectedBuffers(5, 9, &kDataA);
2349 }
2350
2351 TEST_F(SourceBufferStreamTest, GarbageCollection_DeleteFrontGOPsAtATime) {
2352   // Set memory limit to 20 buffers.
2353   SetMemoryLimit(20);
2354
2355   // Append 20 buffers at positions 0 through 19.
2356   NewSegmentAppend(0, 20, &kDataA);
2357
2358   // Seek to position 10.
2359   Seek(10);
2360
2361   // Add one buffer to put the memory over the cap.
2362   AppendBuffers(20, 1, &kDataA);
2363
2364   // GC should have deleted the first 5 buffers so that the range still begins
2365   // with a keyframe.
2366   CheckExpectedRanges("{ [5,20) }");
2367   CheckExpectedBuffers(10, 20, &kDataA);
2368   Seek(5);
2369   CheckExpectedBuffers(5, 9, &kDataA);
2370 }
2371
2372 TEST_F(SourceBufferStreamTest, GarbageCollection_DeleteBack) {
2373   // Set memory limit to 5 buffers.
2374   SetMemoryLimit(5);
2375
2376   // Seek to position 0.
2377   Seek(0);
2378
2379   // Append 20 buffers at positions 0 through 19.
2380   NewSegmentAppend(0, 20, &kDataA);
2381
2382   // Should leave the first 5 buffers from 0 to 4 and the last GOP appended.
2383   CheckExpectedRanges("{ [0,4) [15,19) }");
2384   CheckExpectedBuffers(0, 4, &kDataA);
2385 }
2386
2387 TEST_F(SourceBufferStreamTest, GarbageCollection_DeleteFrontAndBack) {
2388   // Set memory limit to 3 buffers.
2389   SetMemoryLimit(3);
2390
2391   // Seek to position 15.
2392   Seek(15);
2393
2394   // Append 40 buffers at positions 0 through 39.
2395   NewSegmentAppend(0, 40, &kDataA);
2396
2397   // Should leave the GOP containing the seek position and the last GOP
2398   // appended.
2399   CheckExpectedRanges("{ [15,19) [35,39) }");
2400   CheckExpectedBuffers(15, 19, &kDataA);
2401   CheckNoNextBuffer();
2402 }
2403
2404 TEST_F(SourceBufferStreamTest, GarbageCollection_DeleteSeveralRanges) {
2405   // Append 5 buffers at positions 0 through 4.
2406   NewSegmentAppend(0, 5);
2407
2408   // Append 5 buffers at positions 10 through 14.
2409   NewSegmentAppend(10, 5);
2410
2411   // Append 5 buffers at positions 20 through 24.
2412   NewSegmentAppend(20, 5);
2413
2414   // Append 5 buffers at positions 30 through 34.
2415   NewSegmentAppend(30, 5);
2416
2417   CheckExpectedRanges("{ [0,4) [10,14) [20,24) [30,34) }");
2418
2419   // Seek to position 21.
2420   Seek(20);
2421   CheckExpectedBuffers(20, 20);
2422
2423   // Set memory limit to 1 buffer.
2424   SetMemoryLimit(1);
2425
2426   // Append 5 buffers at positions 40 through 44. This will trigger GC.
2427   NewSegmentAppend(40, 5);
2428
2429   // Should delete everything except the GOP containing the current buffer and
2430   // the last GOP appended.
2431   CheckExpectedRanges("{ [20,24) [40,44) }");
2432   CheckExpectedBuffers(21, 24);
2433   CheckNoNextBuffer();
2434
2435   // Continue appending into the last range to make sure it didn't break.
2436   AppendBuffers(45, 10);
2437   // Should only save last GOP appended.
2438   CheckExpectedRanges("{ [20,24) [50,54) }");
2439
2440   // Make sure appending before and after the ranges didn't somehow break.
2441   SetMemoryLimit(100);
2442   NewSegmentAppend(0, 10);
2443   CheckExpectedRanges("{ [0,9) [20,24) [50,54) }");
2444   Seek(0);
2445   CheckExpectedBuffers(0, 9);
2446
2447   NewSegmentAppend(90, 10);
2448   CheckExpectedRanges("{ [0,9) [20,24) [50,54) [90,99) }");
2449   Seek(50);
2450   CheckExpectedBuffers(50, 54);
2451   CheckNoNextBuffer();
2452   Seek(90);
2453   CheckExpectedBuffers(90, 99);
2454   CheckNoNextBuffer();
2455 }
2456
2457 TEST_F(SourceBufferStreamTest, GarbageCollection_DeleteAfterLastAppend) {
2458   // Set memory limit to 10 buffers.
2459   SetMemoryLimit(10);
2460
2461   // Append 1 GOP starting at 310ms, 30ms apart.
2462   NewSegmentAppend("310K 340 370");
2463
2464   // Append 2 GOPs starting at 490ms, 30ms apart.
2465   NewSegmentAppend("490K 520 550 580K 610 640");
2466
2467   CheckExpectedRangesByTimestamp("{ [310,400) [490,670) }");
2468
2469   // Seek to the GOP at 580ms.
2470   SeekToTimestamp(base::TimeDelta::FromMilliseconds(580));
2471
2472   // Append 2 GOPs before the existing ranges.
2473   // So the ranges before GC are "{ [100,280) [310,400) [490,670) }".
2474   NewSegmentAppend("100K 130 160 190K 220 250K");
2475
2476   // Should save the newly appended GOPs.
2477   CheckExpectedRangesByTimestamp("{ [100,280) [580,670) }");
2478 }
2479
2480 TEST_F(SourceBufferStreamTest, GarbageCollection_DeleteAfterLastAppendMerged) {
2481   // Set memory limit to 10 buffers.
2482   SetMemoryLimit(10);
2483
2484   // Append 3 GOPs starting at 400ms, 30ms apart.
2485   NewSegmentAppend("400K 430 460 490K 520 550 580K 610 640");
2486
2487   // Seek to the GOP at 580ms.
2488   SeekToTimestamp(base::TimeDelta::FromMilliseconds(580));
2489
2490   // Append 2 GOPs starting at 220ms, and they will be merged with the existing
2491   // range.  So the range before GC is "{ [220,670) }".
2492   NewSegmentAppend("220K 250 280 310K 340 370");
2493
2494   // Should save the newly appended GOPs.
2495   CheckExpectedRangesByTimestamp("{ [220,400) [580,670) }");
2496 }
2497
2498 TEST_F(SourceBufferStreamTest, GarbageCollection_NoSeek) {
2499   // Set memory limit to 20 buffers.
2500   SetMemoryLimit(20);
2501
2502   // Append 25 buffers at positions 0 through 24.
2503   NewSegmentAppend(0, 25, &kDataA);
2504
2505   // GC deletes the first 5 buffers to keep the memory limit within cap.
2506   CheckExpectedRanges("{ [5,24) }");
2507   CheckNoNextBuffer();
2508   Seek(5);
2509   CheckExpectedBuffers(5, 24, &kDataA);
2510 }
2511
2512 TEST_F(SourceBufferStreamTest, GarbageCollection_PendingSeek) {
2513   // Append 10 buffers at positions 0 through 9.
2514   NewSegmentAppend(0, 10, &kDataA);
2515
2516   // Append 5 buffers at positions 25 through 29.
2517   NewSegmentAppend(25, 5, &kDataA);
2518
2519   // Seek to position 15.
2520   Seek(15);
2521   CheckNoNextBuffer();
2522
2523   CheckExpectedRanges("{ [0,9) [25,29) }");
2524
2525   // Set memory limit to 5 buffers.
2526   SetMemoryLimit(5);
2527
2528   // Append 5 buffers as positions 30 to 34 to trigger GC.
2529   AppendBuffers(30, 5, &kDataA);
2530
2531   // The current algorithm will delete from the beginning until the memory is
2532   // under cap.
2533   CheckExpectedRanges("{ [30,34) }");
2534
2535   // Expand memory limit again so that GC won't be triggered.
2536   SetMemoryLimit(100);
2537
2538   // Append data to fulfill seek.
2539   NewSegmentAppend(15, 5, &kDataA);
2540
2541   // Check to make sure all is well.
2542   CheckExpectedRanges("{ [15,19) [30,34) }");
2543   CheckExpectedBuffers(15, 19, &kDataA);
2544   Seek(30);
2545   CheckExpectedBuffers(30, 34, &kDataA);
2546 }
2547
2548 TEST_F(SourceBufferStreamTest, GarbageCollection_NeedsMoreData) {
2549   // Set memory limit to 15 buffers.
2550   SetMemoryLimit(15);
2551
2552   // Append 10 buffers at positions 0 through 9.
2553   NewSegmentAppend(0, 10, &kDataA);
2554
2555   // Advance next buffer position to 10.
2556   Seek(0);
2557   CheckExpectedBuffers(0, 9, &kDataA);
2558   CheckNoNextBuffer();
2559
2560   // Append 20 buffers at positions 15 through 34.
2561   NewSegmentAppend(15, 20, &kDataA);
2562
2563   // GC should have saved the keyframe before the current seek position and the
2564   // data closest to the current seek position. It will also save the last GOP
2565   // appended.
2566   CheckExpectedRanges("{ [5,9) [15,19) [30,34) }");
2567
2568   // Now fulfill the seek at position 10. This will make GC delete the data
2569   // before position 10 to keep it within cap.
2570   NewSegmentAppend(10, 5, &kDataA);
2571   CheckExpectedRanges("{ [10,19) [30,34) }");
2572   CheckExpectedBuffers(10, 19, &kDataA);
2573 }
2574
2575 TEST_F(SourceBufferStreamTest, GarbageCollection_TrackBuffer) {
2576   // Set memory limit to 3 buffers.
2577   SetMemoryLimit(3);
2578
2579   // Seek to position 15.
2580   Seek(15);
2581
2582   // Append 18 buffers at positions 0 through 17.
2583   NewSegmentAppend(0, 18, &kDataA);
2584
2585   // Should leave GOP containing seek position.
2586   CheckExpectedRanges("{ [15,17) }");
2587
2588   // Seek ahead to position 16.
2589   CheckExpectedBuffers(15, 15, &kDataA);
2590
2591   // Completely overlap the existing buffers.
2592   NewSegmentAppend(0, 20, &kDataB);
2593
2594   // Because buffers 16 and 17 are not keyframes, they are moved to the track
2595   // buffer upon overlap. The source buffer (i.e. not the track buffer) is now
2596   // waiting for the next keyframe.
2597   CheckExpectedRanges("{ [15,19) }");
2598   CheckExpectedBuffers(16, 17, &kDataA);
2599   CheckNoNextBuffer();
2600
2601   // Now add a keyframe at position 20.
2602   AppendBuffers(20, 5, &kDataB);
2603
2604   // Should garbage collect such that there are 5 frames remaining, starting at
2605   // the keyframe.
2606   CheckExpectedRanges("{ [20,24) }");
2607   CheckExpectedBuffers(20, 24, &kDataB);
2608   CheckNoNextBuffer();
2609 }
2610
2611 // Test saving the last GOP appended when this GOP is the only GOP in its range.
2612 TEST_F(SourceBufferStreamTest, GarbageCollection_SaveAppendGOP) {
2613   // Set memory limit to 3 and make sure the 4-byte GOP is not garbage
2614   // collected.
2615   SetMemoryLimit(3);
2616   NewSegmentAppend("0K 30 60 90");
2617   CheckExpectedRangesByTimestamp("{ [0,120) }");
2618
2619   // Make sure you can continue appending data to this GOP; again, GC should not
2620   // wipe out anything.
2621   AppendBuffers("120D30");
2622   CheckExpectedRangesByTimestamp("{ [0,150) }");
2623
2624   // Set memory limit to 100 and append a 2nd range after this without
2625   // triggering GC.
2626   SetMemoryLimit(100);
2627   NewSegmentAppend("200K 230 260 290K 320 350");
2628   CheckExpectedRangesByTimestamp("{ [0,150) [200,380) }");
2629
2630   // Seek to 290ms.
2631   SeekToTimestamp(base::TimeDelta::FromMilliseconds(290));
2632
2633   // Now set memory limit to 3 and append a GOP in a separate range after the
2634   // selected range. Because it is after 290ms, this tests that the GOP is saved
2635   // when deleting from the back.
2636   SetMemoryLimit(3);
2637   NewSegmentAppend("500K 530 560 590");
2638
2639   // Should save GOP with 290ms and last GOP appended.
2640   CheckExpectedRangesByTimestamp("{ [290,380) [500,620) }");
2641
2642   // Continue appending to this GOP after GC.
2643   AppendBuffers("620D30");
2644   CheckExpectedRangesByTimestamp("{ [290,380) [500,650) }");
2645 }
2646
2647 // Test saving the last GOP appended when this GOP is in the middle of a
2648 // non-selected range.
2649 TEST_F(SourceBufferStreamTest, GarbageCollection_SaveAppendGOP_Middle) {
2650   // Append 3 GOPs starting at 0ms, 30ms apart.
2651   NewSegmentAppend("0K 30 60 90K 120 150 180K 210 240");
2652   CheckExpectedRangesByTimestamp("{ [0,270) }");
2653
2654   // Now set the memory limit to 1 and overlap the middle of the range with a
2655   // new GOP.
2656   SetMemoryLimit(1);
2657   NewSegmentAppend("80K 110 140");
2658
2659   // This whole GOP should be saved, and should be able to continue appending
2660   // data to it.
2661   CheckExpectedRangesByTimestamp("{ [80,170) }");
2662   AppendBuffers("170D30");
2663   CheckExpectedRangesByTimestamp("{ [80,200) }");
2664
2665   // Set memory limit to 100 and append a 2nd range after this without
2666   // triggering GC.
2667   SetMemoryLimit(100);
2668   NewSegmentAppend("400K 430 460 490K 520 550 580K 610 640");
2669   CheckExpectedRangesByTimestamp("{ [80,200) [400,670) }");
2670
2671   // Seek to 80ms to make the first range the selected range.
2672   SeekToTimestamp(base::TimeDelta::FromMilliseconds(80));
2673
2674   // Now set memory limit to 3 and append a GOP in the middle of the second
2675   // range. Because it is after the selected range, this tests that the GOP is
2676   // saved when deleting from the back.
2677   SetMemoryLimit(3);
2678   NewSegmentAppend("500K 530 560 590");
2679
2680   // Should save the GOP containing the seek point and GOP that was last
2681   // appended.
2682   CheckExpectedRangesByTimestamp("{ [80,200) [500,620) }");
2683
2684   // Continue appending to this GOP after GC.
2685   AppendBuffers("620D30");
2686   CheckExpectedRangesByTimestamp("{ [80,200) [500,650) }");
2687 }
2688
2689 // Test saving the last GOP appended when the GOP containing the next buffer is
2690 // adjacent to the last GOP appended.
2691 TEST_F(SourceBufferStreamTest, GarbageCollection_SaveAppendGOP_Selected1) {
2692   // Append 3 GOPs at 0ms, 90ms, and 180ms.
2693   NewSegmentAppend("0K 30 60 90K 120 150 180K 210 240");
2694   CheckExpectedRangesByTimestamp("{ [0,270) }");
2695
2696   // Seek to the GOP at 90ms.
2697   SeekToTimestamp(base::TimeDelta::FromMilliseconds(90));
2698
2699   // Set the memory limit to 1, then overlap the GOP at 0.
2700   SetMemoryLimit(1);
2701   NewSegmentAppend("0K 30 60");
2702
2703   // Should save the GOP at 0ms and 90ms.
2704   CheckExpectedRangesByTimestamp("{ [0,180) }");
2705
2706   // Seek to 0 and check all buffers.
2707   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
2708   CheckExpectedBuffers("0K 30 60 90K 120 150");
2709   CheckNoNextBuffer();
2710
2711   // Now seek back to 90ms and append a GOP at 180ms.
2712   SeekToTimestamp(base::TimeDelta::FromMilliseconds(90));
2713   NewSegmentAppend("180K 210 240");
2714
2715   // Should save the GOP at 90ms and the GOP at 180ms.
2716   CheckExpectedRangesByTimestamp("{ [90,270) }");
2717   CheckExpectedBuffers("90K 120 150 180K 210 240");
2718   CheckNoNextBuffer();
2719 }
2720
2721 // Test saving the last GOP appended when it is at the beginning or end of the
2722 // selected range. This tests when the last GOP appended is before or after the
2723 // GOP containing the next buffer, but not directly adjacent to this GOP.
2724 TEST_F(SourceBufferStreamTest, GarbageCollection_SaveAppendGOP_Selected2) {
2725   // Append 4 GOPs starting at positions 0ms, 90ms, 180ms, 270ms.
2726   NewSegmentAppend("0K 30 60 90K 120 150 180K 210 240 270K 300 330");
2727   CheckExpectedRangesByTimestamp("{ [0,360) }");
2728
2729   // Seek to the last GOP at 270ms.
2730   SeekToTimestamp(base::TimeDelta::FromMilliseconds(270));
2731
2732   // Set the memory limit to 1, then overlap the GOP at 90ms.
2733   SetMemoryLimit(1);
2734   NewSegmentAppend("90K 120 150");
2735
2736   // Should save the GOP at 90ms and the GOP at 270ms.
2737   CheckExpectedRangesByTimestamp("{ [90,180) [270,360) }");
2738
2739   // Set memory limit to 100 and add 3 GOPs to the end of the selected range
2740   // at 360ms, 450ms, and 540ms.
2741   SetMemoryLimit(100);
2742   NewSegmentAppend("360K 390 420 450K 480 510 540K 570 600");
2743   CheckExpectedRangesByTimestamp("{ [90,180) [270,630) }");
2744
2745   // Constrain the memory limit again and overlap the GOP at 450ms to test
2746   // deleting from the back.
2747   SetMemoryLimit(1);
2748   NewSegmentAppend("450K 480 510");
2749
2750   // Should save GOP at 270ms and the GOP at 450ms.
2751   CheckExpectedRangesByTimestamp("{ [270,360) [450,540) }");
2752 }
2753
2754 // Test saving the last GOP appended when it is the same as the GOP containing
2755 // the next buffer.
2756 TEST_F(SourceBufferStreamTest, GarbageCollection_SaveAppendGOP_Selected3) {
2757   // Seek to start of stream.
2758   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
2759
2760   // Append 3 GOPs starting at 0ms, 90ms, 180ms.
2761   NewSegmentAppend("0K 30 60 90K 120 150 180K 210 240");
2762   CheckExpectedRangesByTimestamp("{ [0,270) }");
2763
2764   // Set the memory limit to 1 then begin appending the start of a GOP starting
2765   // at 0ms.
2766   SetMemoryLimit(1);
2767   NewSegmentAppend("0K 30");
2768
2769   // Should save the newly appended GOP, which is also the next GOP that will be
2770   // returned from the seek request.
2771   CheckExpectedRangesByTimestamp("{ [0,60) }");
2772
2773   // Check the buffers in the range.
2774   CheckExpectedBuffers("0K 30");
2775   CheckNoNextBuffer();
2776
2777   // Continue appending to this buffer.
2778   AppendBuffers("60 90");
2779
2780   // Should still save the rest of this GOP and should be able to fulfill the
2781   // read.
2782   CheckExpectedRangesByTimestamp("{ [0,120) }");
2783   CheckExpectedBuffers("60 90");
2784   CheckNoNextBuffer();
2785 }
2786
2787 // Currently disabled because of bug: crbug.com/140875.
2788 TEST_F(SourceBufferStreamTest, DISABLED_GarbageCollection_WaitingForKeyframe) {
2789   // Set memory limit to 10 buffers.
2790   SetMemoryLimit(10);
2791
2792   // Append 5 buffers at positions 10 through 14 and exhaust the buffers.
2793   NewSegmentAppend(10, 5, &kDataA);
2794   Seek(10);
2795   CheckExpectedBuffers(10, 14, &kDataA);
2796   CheckExpectedRanges("{ [10,14) }");
2797
2798   // We are now stalled at position 15.
2799   CheckNoNextBuffer();
2800
2801   // Do an end overlap that causes the latter half of the range to be deleted.
2802   NewSegmentAppend(5, 6, &kDataA);
2803   CheckNoNextBuffer();
2804   CheckExpectedRanges("{ [5,10) }");
2805
2806   // Append buffers from position 20 to 29. This should trigger GC.
2807   NewSegmentAppend(20, 10, &kDataA);
2808
2809   // GC should keep the keyframe before the seek position 15, and the next 9
2810   // buffers closest to the seek position.
2811   CheckNoNextBuffer();
2812   CheckExpectedRanges("{ [10,10) [20,28) }");
2813
2814   // Fulfill the seek by appending one buffer at 15.
2815   NewSegmentAppend(15, 1, &kDataA);
2816   CheckExpectedBuffers(15, 15, &kDataA);
2817   CheckExpectedRanges("{ [15,15) [20,28) }");
2818 }
2819
2820 // Test the performance of garbage collection.
2821 TEST_F(SourceBufferStreamTest, GarbageCollection_Performance) {
2822   // Force |keyframes_per_second_| to be equal to kDefaultFramesPerSecond.
2823   SetStreamInfo(kDefaultFramesPerSecond, kDefaultFramesPerSecond);
2824
2825   const int kBuffersToKeep = 1000;
2826   SetMemoryLimit(kBuffersToKeep);
2827
2828   int buffers_appended = 0;
2829
2830   NewSegmentAppend(0, kBuffersToKeep);
2831   buffers_appended += kBuffersToKeep;
2832
2833   const int kBuffersToAppend = 1000;
2834   const int kGarbageCollections = 3;
2835   for (int i = 0; i < kGarbageCollections; ++i) {
2836     AppendBuffers(buffers_appended, kBuffersToAppend);
2837     buffers_appended += kBuffersToAppend;
2838   }
2839 }
2840
2841 TEST_F(SourceBufferStreamTest, GetRemovalRange_BytesToFree) {
2842   // Append 2 GOPs starting at 300ms, 30ms apart.
2843   NewSegmentAppend("300K 330 360 390K 420 450");
2844
2845   // Append 2 GOPs starting at 600ms, 30ms apart.
2846   NewSegmentAppend("600K 630 660 690K 720 750");
2847
2848   // Append 2 GOPs starting at 900ms, 30ms apart.
2849   NewSegmentAppend("900K 930 960 990K 1020 1050");
2850
2851   CheckExpectedRangesByTimestamp("{ [300,480) [600,780) [900,1080) }");
2852
2853   int remove_range_end = -1;
2854   int bytes_removed = -1;
2855
2856   // Size 0.
2857   bytes_removed = GetRemovalRangeInMs(300, 1080, 0, &remove_range_end);
2858   EXPECT_EQ(-1, remove_range_end);
2859   EXPECT_EQ(0, bytes_removed);
2860
2861   // Smaller than the size of GOP.
2862   bytes_removed = GetRemovalRangeInMs(300, 1080, 1, &remove_range_end);
2863   EXPECT_EQ(390, remove_range_end);
2864   // Remove as the size of GOP.
2865   EXPECT_EQ(3, bytes_removed);
2866
2867   // The same size with a GOP.
2868   bytes_removed = GetRemovalRangeInMs(300, 1080, 3, &remove_range_end);
2869   EXPECT_EQ(390, remove_range_end);
2870   EXPECT_EQ(3, bytes_removed);
2871
2872   // The same size with a range.
2873   bytes_removed = GetRemovalRangeInMs(300, 1080, 6, &remove_range_end);
2874   EXPECT_EQ(480, remove_range_end);
2875   EXPECT_EQ(6, bytes_removed);
2876
2877   // A frame larger than a range.
2878   bytes_removed = GetRemovalRangeInMs(300, 1080, 7, &remove_range_end);
2879   EXPECT_EQ(690, remove_range_end);
2880   EXPECT_EQ(9, bytes_removed);
2881
2882   // The same size with two ranges.
2883   bytes_removed = GetRemovalRangeInMs(300, 1080, 12, &remove_range_end);
2884   EXPECT_EQ(780, remove_range_end);
2885   EXPECT_EQ(12, bytes_removed);
2886
2887   // Larger than two ranges.
2888   bytes_removed = GetRemovalRangeInMs(300, 1080, 14, &remove_range_end);
2889   EXPECT_EQ(990, remove_range_end);
2890   EXPECT_EQ(15, bytes_removed);
2891
2892   // The same size with the whole ranges.
2893   bytes_removed = GetRemovalRangeInMs(300, 1080, 18, &remove_range_end);
2894   EXPECT_EQ(1080, remove_range_end);
2895   EXPECT_EQ(18, bytes_removed);
2896
2897   // Larger than the whole ranges.
2898   bytes_removed = GetRemovalRangeInMs(300, 1080, 20, &remove_range_end);
2899   EXPECT_EQ(1080, remove_range_end);
2900   EXPECT_EQ(18, bytes_removed);
2901 }
2902
2903 TEST_F(SourceBufferStreamTest, GetRemovalRange_Range) {
2904   // Append 2 GOPs starting at 300ms, 30ms apart.
2905   NewSegmentAppend("300K 330 360 390K 420 450");
2906
2907   // Append 2 GOPs starting at 600ms, 30ms apart.
2908   NewSegmentAppend("600K 630 660 690K 720 750");
2909
2910   // Append 2 GOPs starting at 900ms, 30ms apart.
2911   NewSegmentAppend("900K 930 960 990K 1020 1050");
2912
2913   CheckExpectedRangesByTimestamp("{ [300,480) [600,780) [900,1080) }");
2914
2915   int remove_range_end = -1;
2916   int bytes_removed = -1;
2917
2918   // Within a GOP and no keyframe.
2919   bytes_removed = GetRemovalRangeInMs(630, 660, 20, &remove_range_end);
2920   EXPECT_EQ(-1, remove_range_end);
2921   EXPECT_EQ(0, bytes_removed);
2922
2923   // Across a GOP and no keyframe.
2924   bytes_removed = GetRemovalRangeInMs(630, 750, 20, &remove_range_end);
2925   EXPECT_EQ(-1, remove_range_end);
2926   EXPECT_EQ(0, bytes_removed);
2927
2928   // The same size with a range.
2929   bytes_removed = GetRemovalRangeInMs(600, 780, 20, &remove_range_end);
2930   EXPECT_EQ(780, remove_range_end);
2931   EXPECT_EQ(6, bytes_removed);
2932
2933   // One frame larger than a range.
2934   bytes_removed = GetRemovalRangeInMs(570, 810, 20, &remove_range_end);
2935   EXPECT_EQ(780, remove_range_end);
2936   EXPECT_EQ(6, bytes_removed);
2937
2938   // Facing the other ranges.
2939   bytes_removed = GetRemovalRangeInMs(480, 900, 20, &remove_range_end);
2940   EXPECT_EQ(780, remove_range_end);
2941   EXPECT_EQ(6, bytes_removed);
2942
2943   // In the midle of the other ranges, but not including any GOP.
2944   bytes_removed = GetRemovalRangeInMs(420, 960, 20, &remove_range_end);
2945   EXPECT_EQ(780, remove_range_end);
2946   EXPECT_EQ(6, bytes_removed);
2947
2948   // In the middle of the other ranges.
2949   bytes_removed = GetRemovalRangeInMs(390, 990, 20, &remove_range_end);
2950   EXPECT_EQ(990, remove_range_end);
2951   EXPECT_EQ(12, bytes_removed);
2952
2953   // A frame smaller than the whole ranges.
2954   bytes_removed = GetRemovalRangeInMs(330, 1050, 20, &remove_range_end);
2955   EXPECT_EQ(990, remove_range_end);
2956   EXPECT_EQ(12, bytes_removed);
2957
2958   // The same with the whole ranges.
2959   bytes_removed = GetRemovalRangeInMs(300, 1080, 20, &remove_range_end);
2960   EXPECT_EQ(1080, remove_range_end);
2961   EXPECT_EQ(18, bytes_removed);
2962
2963   // Larger than the whole ranges.
2964   bytes_removed = GetRemovalRangeInMs(270, 1110, 20, &remove_range_end);
2965   EXPECT_EQ(1080, remove_range_end);
2966   EXPECT_EQ(18, bytes_removed);
2967 }
2968
2969 TEST_F(SourceBufferStreamTest, ConfigChange_Basic) {
2970   VideoDecoderConfig new_config = TestVideoConfig::Large();
2971   ASSERT_FALSE(new_config.Matches(video_config_));
2972
2973   Seek(0);
2974   CheckVideoConfig(video_config_);
2975
2976   // Append 5 buffers at positions 0 through 4
2977   NewSegmentAppend(0, 5, &kDataA);
2978
2979   CheckVideoConfig(video_config_);
2980
2981   // Signal a config change.
2982   stream_->UpdateVideoConfig(new_config);
2983
2984   // Make sure updating the config doesn't change anything since new_config
2985   // should not be associated with the buffer GetNextBuffer() will return.
2986   CheckVideoConfig(video_config_);
2987
2988   // Append 5 buffers at positions 5 through 9.
2989   NewSegmentAppend(5, 5, &kDataB);
2990
2991   // Consume the buffers associated with the initial config.
2992   scoped_refptr<StreamParserBuffer> buffer;
2993   for (int i = 0; i < 5; i++) {
2994     EXPECT_EQ(stream_->GetNextBuffer(&buffer), SourceBufferStream::kSuccess);
2995     CheckVideoConfig(video_config_);
2996   }
2997
2998   // Verify the next attempt to get a buffer will signal that a config change
2999   // has happened.
3000   EXPECT_EQ(stream_->GetNextBuffer(&buffer), SourceBufferStream::kConfigChange);
3001
3002   // Verify that the new config is now returned.
3003   CheckVideoConfig(new_config);
3004
3005   // Consume the remaining buffers associated with the new config.
3006   for (int i = 0; i < 5; i++) {
3007     CheckVideoConfig(new_config);
3008     EXPECT_EQ(stream_->GetNextBuffer(&buffer), SourceBufferStream::kSuccess);
3009   }
3010 }
3011
3012 TEST_F(SourceBufferStreamTest, ConfigChange_Seek) {
3013   scoped_refptr<StreamParserBuffer> buffer;
3014   VideoDecoderConfig new_config = TestVideoConfig::Large();
3015
3016   Seek(0);
3017   NewSegmentAppend(0, 5, &kDataA);
3018   stream_->UpdateVideoConfig(new_config);
3019   NewSegmentAppend(5, 5, &kDataB);
3020
3021   // Seek to the start of the buffers with the new config and make sure a
3022   // config change is signalled.
3023   CheckVideoConfig(video_config_);
3024   Seek(5);
3025   CheckVideoConfig(video_config_);
3026   EXPECT_EQ(stream_->GetNextBuffer(&buffer), SourceBufferStream::kConfigChange);
3027   CheckVideoConfig(new_config);
3028   CheckExpectedBuffers(5, 9, &kDataB);
3029
3030
3031   // Seek to the start which has a different config. Don't fetch any buffers and
3032   // seek back to buffers with the current config. Make sure a config change
3033   // isn't signalled in this case.
3034   CheckVideoConfig(new_config);
3035   Seek(0);
3036   Seek(7);
3037   CheckExpectedBuffers(5, 9, &kDataB);
3038
3039
3040   // Seek to the start and make sure a config change is signalled.
3041   CheckVideoConfig(new_config);
3042   Seek(0);
3043   CheckVideoConfig(new_config);
3044   EXPECT_EQ(stream_->GetNextBuffer(&buffer), SourceBufferStream::kConfigChange);
3045   CheckVideoConfig(video_config_);
3046   CheckExpectedBuffers(0, 4, &kDataA);
3047 }
3048
3049 TEST_F(SourceBufferStreamTest, SetExplicitDuration) {
3050   // Append 2 buffers at positions 5 through 6.
3051   NewSegmentAppend(5, 2);
3052
3053   // Append 2 buffers at positions 10 through 11.
3054   NewSegmentAppend(10, 2);
3055
3056   // Append 2 buffers at positions 15 through 16.
3057   NewSegmentAppend(15, 2);
3058
3059   // Check expected ranges.
3060   CheckExpectedRanges("{ [5,6) [10,11) [15,16) }");
3061
3062   // Set duration to be between buffers 6 and 10.
3063   stream_->OnSetDuration(frame_duration() * 8);
3064
3065   // Should truncate the data after 6.
3066   CheckExpectedRanges("{ [5,6) }");
3067
3068   // Adding data past the previous duration should still work.
3069   NewSegmentAppend(0, 20);
3070   CheckExpectedRanges("{ [0,19) }");
3071 }
3072
3073 TEST_F(SourceBufferStreamTest, SetExplicitDuration_EdgeCase) {
3074   // Append 10 buffers at positions 10 through 19.
3075   NewSegmentAppend(10, 10);
3076
3077   // Append 5 buffers at positions 25 through 29.
3078   NewSegmentAppend(25, 5);
3079
3080   // Check expected ranges.
3081   CheckExpectedRanges("{ [10,19) [25,29) }");
3082
3083   // Set duration to be right before buffer 25.
3084   stream_->OnSetDuration(frame_duration() * 25);
3085
3086   // Should truncate the last range.
3087   CheckExpectedRanges("{ [10,19) }");
3088 }
3089
3090 TEST_F(SourceBufferStreamTest, SetExplicitDuration_DeletePartialRange) {
3091   // Append 5 buffers at positions 0 through 4.
3092   NewSegmentAppend(0, 5);
3093
3094   // Append 10 buffers at positions 10 through 19.
3095   NewSegmentAppend(10, 10);
3096
3097   // Append 5 buffers at positions 25 through 29.
3098   NewSegmentAppend(25, 5);
3099
3100   // Check expected ranges.
3101   CheckExpectedRanges("{ [0,4) [10,19) [25,29) }");
3102
3103   // Set duration to be between buffers 13 and 14.
3104   stream_->OnSetDuration(frame_duration() * 14);
3105
3106   // Should truncate the data after 13.
3107   CheckExpectedRanges("{ [0,4) [10,13) }");
3108 }
3109
3110 TEST_F(SourceBufferStreamTest, SetExplicitDuration_DeleteSelectedRange) {
3111   // Append 2 buffers at positions 5 through 6.
3112   NewSegmentAppend(5, 2);
3113
3114   // Append 2 buffers at positions 10 through 11.
3115   NewSegmentAppend(10, 2);
3116
3117   // Append 2 buffers at positions 15 through 16.
3118   NewSegmentAppend(15, 2);
3119
3120   // Check expected ranges.
3121   CheckExpectedRanges("{ [5,6) [10,11) [15,16) }");
3122
3123   // Seek to 10.
3124   Seek(10);
3125
3126   // Set duration to be after position 3.
3127   stream_->OnSetDuration(frame_duration() * 4);
3128
3129   // Expect everything to be deleted, and should not have next buffer anymore.
3130   CheckNoNextBuffer();
3131   CheckExpectedRanges("{ }");
3132
3133   // Appending data at position 10 should not fulfill the seek.
3134   // (If the duration is set to be something smaller than the current seek
3135   // point, then the seek point is reset and the SourceBufferStream waits
3136   // for a new seek request. Therefore even if the data is re-appended, it
3137   // should not fulfill the old seek.)
3138   NewSegmentAppend(0, 15);
3139   CheckNoNextBuffer();
3140   CheckExpectedRanges("{ [0,14) }");
3141 }
3142
3143 TEST_F(SourceBufferStreamTest, SetExplicitDuration_DeletePartialSelectedRange) {
3144   // Append 5 buffers at positions 0 through 4.
3145   NewSegmentAppend(0, 5);
3146
3147   // Append 20 buffers at positions 10 through 29.
3148   NewSegmentAppend(10, 20);
3149
3150   // Check expected ranges.
3151   CheckExpectedRanges("{ [0,4) [10,29) }");
3152
3153   // Seek to position 10.
3154   Seek(10);
3155
3156   // Set duration to be between buffers 24 and 25.
3157   stream_->OnSetDuration(frame_duration() * 25);
3158
3159   // Should truncate the data after 24.
3160   CheckExpectedRanges("{ [0,4) [10,24) }");
3161
3162   // The seek position should not be lost.
3163   CheckExpectedBuffers(10, 10);
3164
3165   // Now set the duration immediately after buffer 10.
3166   stream_->OnSetDuration(frame_duration() * 11);
3167
3168   // Seek position should be reset.
3169   CheckNoNextBuffer();
3170   CheckExpectedRanges("{ [0,4) [10,10) }");
3171 }
3172
3173 // Test the case where duration is set while the stream parser buffers
3174 // already start passing the data to decoding pipeline. Selected range,
3175 // when invalidated by getting truncated, should be updated to NULL
3176 // accordingly so that successive append operations keep working.
3177 TEST_F(SourceBufferStreamTest, SetExplicitDuration_UpdateSelectedRange) {
3178   // Seek to start of stream.
3179   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
3180
3181   NewSegmentAppend("0K 30 60 90");
3182
3183   // Read out the first few buffers.
3184   CheckExpectedBuffers("0K 30");
3185
3186   // Set duration to be right before buffer 1.
3187   stream_->OnSetDuration(base::TimeDelta::FromMilliseconds(60));
3188
3189   // Verify that there is no next buffer.
3190   CheckNoNextBuffer();
3191
3192   // We should be able to append new buffers at this point.
3193   NewSegmentAppend("120K 150");
3194
3195   CheckExpectedRangesByTimestamp("{ [0,60) [120,180) }");
3196 }
3197
3198 TEST_F(SourceBufferStreamTest,
3199        SetExplicitDuration_AfterSegmentTimestampAndBeforeFirstBufferTimestamp) {
3200
3201   NewSegmentAppend("0K 30K 60K");
3202
3203   // Append a segment with a start timestamp of 200, but the first
3204   // buffer starts at 230ms. This can happen in muxed content where the
3205   // audio starts before the first frame.
3206   NewSegmentAppend(base::TimeDelta::FromMilliseconds(200),
3207                    "230K 260K 290K 320K");
3208
3209   NewSegmentAppend("400K 430K 460K");
3210
3211   CheckExpectedRangesByTimestamp("{ [0,90) [200,350) [400,490) }");
3212
3213   stream_->OnSetDuration(base::TimeDelta::FromMilliseconds(120));
3214
3215   // Verify that the buffered ranges are updated properly and we don't crash.
3216   CheckExpectedRangesByTimestamp("{ [0,90) }");
3217 }
3218
3219 // Test the case were the current playback position is at the end of the
3220 // buffered data and several overlaps occur that causes the selected
3221 // range to get split and then merged back into a single range.
3222 TEST_F(SourceBufferStreamTest, OverlapSplitAndMergeWhileWaitingForMoreData) {
3223   // Seek to start of stream.
3224   SeekToTimestamp(base::TimeDelta::FromMilliseconds(0));
3225
3226   NewSegmentAppend("0K 30 60 90 120K 150");
3227   CheckExpectedRangesByTimestamp("{ [0,180) }");
3228
3229   // Read all the buffered data.
3230   CheckExpectedBuffers("0K 30 60 90 120K 150");
3231   CheckNoNextBuffer();
3232
3233   // Append data over the current GOP so that a keyframe is needed before
3234   // playback can continue from the current position.
3235   NewSegmentAppend("120K 150");
3236   CheckExpectedRangesByTimestamp("{ [0,180) }");
3237
3238   // Append buffers that cause the range to get split.
3239   NewSegmentAppend("0K 30");
3240   CheckExpectedRangesByTimestamp("{ [0,60) [120,180) }");
3241
3242   // Append buffers that cause the ranges to get merged.
3243   AppendBuffers("60 90");
3244
3245   CheckExpectedRangesByTimestamp("{ [0,180) }");
3246
3247   // Verify that we still don't have a next buffer.
3248   CheckNoNextBuffer();
3249
3250   // Add more data to the end and verify that this new data is read correctly.
3251   NewSegmentAppend("180K 210");
3252   CheckExpectedRangesByTimestamp("{ [0,240) }");
3253   CheckExpectedBuffers("180K 210");
3254 }
3255
3256 // Verify that non-keyframes with the same timestamp in the same
3257 // append are handled correctly.
3258 TEST_F(SourceBufferStreamTest, SameTimestamp_Video_SingleAppend) {
3259   Seek(0);
3260   NewSegmentAppend("0K 30 30 60 90 120K 150");
3261   CheckExpectedBuffers("0K 30 30 60 90 120K 150");
3262 }
3263
3264 // Verify that non-keyframes with the same timestamp can occur
3265 // in different appends.
3266 TEST_F(SourceBufferStreamTest, SameTimestamp_Video_TwoAppends) {
3267   Seek(0);
3268   NewSegmentAppend("0K 30");
3269   AppendBuffers("30 60 90 120K 150");
3270   CheckExpectedBuffers("0K 30 30 60 90 120K 150");
3271 }
3272
3273 // Verify that a non-keyframe followed by a keyframe with the same timestamp
3274 // is not allowed.
3275 TEST_F(SourceBufferStreamTest, SameTimestamp_Video_Invalid_1) {
3276   Seek(0);
3277   NewSegmentAppend("0K 30");
3278   AppendBuffers_ExpectFailure("30K 60");
3279 }
3280
3281 TEST_F(SourceBufferStreamTest, SameTimestamp_Video_Invalid_2) {
3282   Seek(0);
3283   NewSegmentAppend_ExpectFailure("0K 30 30K 60");
3284 }
3285
3286 // Verify that a keyframe followed by a non-keyframe with the same timestamp
3287 // is allowed.
3288 TEST_F(SourceBufferStreamTest, SameTimestamp_VideoKeyFrame_TwoAppends) {
3289   Seek(0);
3290   NewSegmentAppend("0K 30K");
3291   AppendBuffers("30 60");
3292   CheckExpectedBuffers("0K 30K 30 60");
3293 }
3294
3295 TEST_F(SourceBufferStreamTest, SameTimestamp_VideoKeyFrame_SingleAppend) {
3296   Seek(0);
3297   NewSegmentAppend("0K 30K 30 60");
3298   CheckExpectedBuffers("0K 30K 30 60");
3299 }
3300
3301 TEST_F(SourceBufferStreamTest, SameTimestamp_Video_Overlap_1) {
3302   Seek(0);
3303   NewSegmentAppend("0K 30 60 60 90 120K 150");
3304
3305   NewSegmentAppend("60K 91 121K 151");
3306   CheckExpectedBuffers("0K 30 60K 91 121K 151");
3307 }
3308
3309 TEST_F(SourceBufferStreamTest, SameTimestamp_Video_Overlap_2) {
3310   Seek(0);
3311   NewSegmentAppend("0K 30 60 60 90 120K 150");
3312   NewSegmentAppend("0K 30 61");
3313   CheckExpectedBuffers("0K 30 61 120K 150");
3314 }
3315
3316 TEST_F(SourceBufferStreamTest, SameTimestamp_Video_Overlap_3) {
3317   Seek(0);
3318   NewSegmentAppend("0K 20 40 60 80 100K 101 102 103K");
3319   NewSegmentAppend("0K 20 40 60 80 90");
3320   CheckExpectedBuffers("0K 20 40 60 80 90 100K 101 102 103K");
3321   AppendBuffers("90 110K 150");
3322   Seek(0);
3323   CheckExpectedBuffers("0K 20 40 60 80 90 90 110K 150");
3324   CheckNoNextBuffer();
3325   CheckExpectedRangesByTimestamp("{ [0,190) }");
3326 }
3327
3328 // Test all the valid same timestamp cases for audio.
3329 TEST_F(SourceBufferStreamTest, SameTimestamp_Audio) {
3330   AudioDecoderConfig config(kCodecMP3, kSampleFormatF32, CHANNEL_LAYOUT_STEREO,
3331                             44100, NULL, 0, false);
3332   stream_.reset(new SourceBufferStream(config, log_cb(), true));
3333   Seek(0);
3334   NewSegmentAppend("0K 0K 30K 30 60 60");
3335   CheckExpectedBuffers("0K 0K 30K 30 60 60");
3336 }
3337
3338 TEST_F(SourceBufferStreamTest, SameTimestamp_Audio_Invalid_1) {
3339   AudioDecoderConfig config(kCodecMP3, kSampleFormatF32, CHANNEL_LAYOUT_STEREO,
3340                             44100, NULL, 0, false);
3341   stream_.reset(new SourceBufferStream(config, log_cb(), true));
3342   Seek(0);
3343   NewSegmentAppend_ExpectFailure("0K 30 30K 60");
3344 }
3345
3346 // If seeking past any existing range and the seek is pending
3347 // because no data has been provided for that position,
3348 // the stream position can be considered as the end of stream.
3349 TEST_F(SourceBufferStreamTest, EndSelected_During_PendingSeek) {
3350   // Append 15 buffers at positions 0 through 14.
3351   NewSegmentAppend(0, 15);
3352
3353   Seek(20);
3354   EXPECT_TRUE(stream_->IsSeekPending());
3355   stream_->MarkEndOfStream();
3356   EXPECT_FALSE(stream_->IsSeekPending());
3357 }
3358
3359 // If there is a pending seek between 2 existing ranges,
3360 // the end of the stream has not been reached.
3361 TEST_F(SourceBufferStreamTest, EndNotSelected_During_PendingSeek) {
3362   // Append:
3363   // - 10 buffers at positions 0 through 9.
3364   // - 10 buffers at positions 30 through 39
3365   NewSegmentAppend(0, 10);
3366   NewSegmentAppend(30, 10);
3367
3368   Seek(20);
3369   EXPECT_TRUE(stream_->IsSeekPending());
3370   stream_->MarkEndOfStream();
3371   EXPECT_TRUE(stream_->IsSeekPending());
3372 }
3373
3374
3375 // Removing exact start & end of a range.
3376 TEST_F(SourceBufferStreamTest, Remove_WholeRange1) {
3377   Seek(0);
3378   NewSegmentAppend("10K 40 70K 100 130K");
3379   CheckExpectedRangesByTimestamp("{ [10,160) }");
3380   RemoveInMs(10, 160, 160);
3381   CheckExpectedRangesByTimestamp("{ }");
3382 }
3383
3384 // Removal range starts before range and ends exactly at end.
3385 TEST_F(SourceBufferStreamTest, Remove_WholeRange2) {
3386   Seek(0);
3387   NewSegmentAppend("10K 40 70K 100 130K");
3388   CheckExpectedRangesByTimestamp("{ [10,160) }");
3389   RemoveInMs(0, 160, 160);
3390   CheckExpectedRangesByTimestamp("{ }");
3391 }
3392
3393 // Removal range starts at the start of a range and ends beyond the
3394 // range end.
3395 TEST_F(SourceBufferStreamTest, Remove_WholeRange3) {
3396   Seek(0);
3397   NewSegmentAppend("10K 40 70K 100 130K");
3398   CheckExpectedRangesByTimestamp("{ [10,160) }");
3399   RemoveInMs(10, 200, 200);
3400   CheckExpectedRangesByTimestamp("{ }");
3401 }
3402
3403 // Removal range starts before range start and ends after the range end.
3404 TEST_F(SourceBufferStreamTest, Remove_WholeRange4) {
3405   Seek(0);
3406   NewSegmentAppend("10K 40 70K 100 130K");
3407   CheckExpectedRangesByTimestamp("{ [10,160) }");
3408   RemoveInMs(0, 200, 200);
3409   CheckExpectedRangesByTimestamp("{ }");
3410 }
3411
3412 // Removes multiple ranges.
3413 TEST_F(SourceBufferStreamTest, Remove_WholeRange5) {
3414   Seek(0);
3415   NewSegmentAppend("10K 40 70K 100 130K");
3416   NewSegmentAppend("1000K 1030 1060K 1090 1120K");
3417   NewSegmentAppend("2000K 2030 2060K 2090 2120K");
3418   CheckExpectedRangesByTimestamp("{ [10,160) [1000,1150) [2000,2150) }");
3419   RemoveInMs(10, 3000, 3000);
3420   CheckExpectedRangesByTimestamp("{ }");
3421 }
3422
3423 // Verifies a [0-infinity) range removes everything.
3424 TEST_F(SourceBufferStreamTest, Remove_ZeroToInfinity) {
3425   Seek(0);
3426   NewSegmentAppend("10K 40 70K 100 130K");
3427   NewSegmentAppend("1000K 1030 1060K 1090 1120K");
3428   NewSegmentAppend("2000K 2030 2060K 2090 2120K");
3429   CheckExpectedRangesByTimestamp("{ [10,160) [1000,1150) [2000,2150) }");
3430   Remove(base::TimeDelta(), kInfiniteDuration(), kInfiniteDuration());
3431   CheckExpectedRangesByTimestamp("{ }");
3432 }
3433
3434 // Removal range starts at the beginning of the range and ends in the
3435 // middle of the range. This test verifies that full GOPs are removed.
3436 TEST_F(SourceBufferStreamTest, Remove_Partial1) {
3437   Seek(0);
3438   NewSegmentAppend("10K 40 70K 100 130K");
3439   NewSegmentAppend("1000K 1030 1060K 1090 1120K");
3440   CheckExpectedRangesByTimestamp("{ [10,160) [1000,1150) }");
3441   RemoveInMs(0, 80, 2200);
3442   CheckExpectedRangesByTimestamp("{ [130,160) [1000,1150) }");
3443 }
3444
3445 // Removal range starts in the middle of a range and ends at the exact
3446 // end of the range.
3447 TEST_F(SourceBufferStreamTest, Remove_Partial2) {
3448   Seek(0);
3449   NewSegmentAppend("10K 40 70K 100 130K");
3450   NewSegmentAppend("1000K 1030 1060K 1090 1120K");
3451   CheckExpectedRangesByTimestamp("{ [10,160) [1000,1150) }");
3452   RemoveInMs(40, 160, 2200);
3453   CheckExpectedRangesByTimestamp("{ [10,40) [1000,1150) }");
3454 }
3455
3456 // Removal range starts and ends within a range.
3457 TEST_F(SourceBufferStreamTest, Remove_Partial3) {
3458   Seek(0);
3459   NewSegmentAppend("10K 40 70K 100 130K");
3460   NewSegmentAppend("1000K 1030 1060K 1090 1120K");
3461   CheckExpectedRangesByTimestamp("{ [10,160) [1000,1150) }");
3462   RemoveInMs(40, 120, 2200);
3463   CheckExpectedRangesByTimestamp("{ [10,40) [130,160) [1000,1150) }");
3464 }
3465
3466 // Removal range starts in the middle of one range and ends in the
3467 // middle of another range.
3468 TEST_F(SourceBufferStreamTest, Remove_Partial4) {
3469   Seek(0);
3470   NewSegmentAppend("10K 40 70K 100 130K");
3471   NewSegmentAppend("1000K 1030 1060K 1090 1120K");
3472   NewSegmentAppend("2000K 2030 2060K 2090 2120K");
3473   CheckExpectedRangesByTimestamp("{ [10,160) [1000,1150) [2000,2150) }");
3474   RemoveInMs(40, 2030, 2200);
3475   CheckExpectedRangesByTimestamp("{ [10,40) [2060,2150) }");
3476 }
3477
3478 // Test behavior when the current position is removed and new buffers
3479 // are appended over the removal range.
3480 TEST_F(SourceBufferStreamTest, Remove_CurrentPosition) {
3481   Seek(0);
3482   NewSegmentAppend("0K 30 60 90K 120 150 180K 210 240 270K 300 330");
3483   CheckExpectedRangesByTimestamp("{ [0,360) }");
3484   CheckExpectedBuffers("0K 30 60 90K 120");
3485
3486   // Remove a range that includes the next buffer (i.e., 150).
3487   RemoveInMs(150, 210, 360);
3488   CheckExpectedRangesByTimestamp("{ [0,150) [270,360) }");
3489
3490   // Verify that no next buffer is returned.
3491   CheckNoNextBuffer();
3492
3493   // Append some buffers to fill the gap that was created.
3494   NewSegmentAppend("120K 150 180 210K 240");
3495   CheckExpectedRangesByTimestamp("{ [0,360) }");
3496
3497   // Verify that buffers resume at the next keyframe after the
3498   // current position.
3499   CheckExpectedBuffers("210K 240 270K 300 330");
3500 }
3501
3502 // Test behavior when buffers in the selected range before the current position
3503 // are removed.
3504 TEST_F(SourceBufferStreamTest, Remove_BeforeCurrentPosition) {
3505   Seek(0);
3506   NewSegmentAppend("0K 30 60 90K 120 150 180K 210 240 270K 300 330");
3507   CheckExpectedRangesByTimestamp("{ [0,360) }");
3508   CheckExpectedBuffers("0K 30 60 90K 120");
3509
3510   // Remove a range that is before the current playback position.
3511   RemoveInMs(0, 90, 360);
3512   CheckExpectedRangesByTimestamp("{ [90,360) }");
3513
3514   CheckExpectedBuffers("150 180K 210 240 270K 300 330");
3515 }
3516
3517 // Test removing the entire range for the current media segment
3518 // being appended.
3519 TEST_F(SourceBufferStreamTest, Remove_MidSegment) {
3520   Seek(0);
3521   NewSegmentAppend("0K 30 60 90 120K 150 180 210");
3522   CheckExpectedRangesByTimestamp("{ [0,240) }");
3523
3524   NewSegmentAppend("0K 30");
3525
3526   CheckExpectedBuffers("0K");
3527
3528   CheckExpectedRangesByTimestamp("{ [0,60) [120,240) }");
3529
3530   // Remove the entire range that is being appended to.
3531   RemoveInMs(0, 60, 240);
3532
3533   // Verify that there is no next buffer since it was removed.
3534   CheckNoNextBuffer();
3535
3536   CheckExpectedRangesByTimestamp("{ [120,240) }");
3537
3538   // Continue appending frames for the current GOP.
3539   AppendBuffers("60 90");
3540
3541   // Verify that the non-keyframes are not added.
3542   CheckExpectedRangesByTimestamp("{ [120,240) }");
3543
3544   // Finish the previous GOP and start the next one.
3545   AppendBuffers("120 150K 180");
3546
3547   // Verify that new GOP replaces the existing range.
3548   CheckExpectedRangesByTimestamp("{ [150,210) }");
3549
3550
3551   SeekToTimestamp(base::TimeDelta::FromMilliseconds(150));
3552   CheckExpectedBuffers("150K 180");
3553   CheckNoNextBuffer();
3554 }
3555
3556 // Test removing the current GOP being appended, while not removing
3557 // the entire range the GOP belongs to.
3558 TEST_F(SourceBufferStreamTest, Remove_GOPBeingAppended) {
3559   Seek(0);
3560   NewSegmentAppend("0K 30 60 90 120K 150 180");
3561   CheckExpectedRangesByTimestamp("{ [0,210) }");
3562
3563   // Remove the current GOP being appended.
3564   RemoveInMs(120, 150, 240);
3565   CheckExpectedRangesByTimestamp("{ [0,120) }");
3566
3567   // Continue appending the current GOP and the next one.
3568   AppendBuffers("210 240K 270 300");
3569
3570   // Verify that the non-keyframe in the previous GOP does
3571   // not effect any existing ranges and a new range is started at the
3572   // beginning of the next GOP.
3573   CheckExpectedRangesByTimestamp("{ [0,120) [240,330) }");
3574
3575   // Verify the buffers in the ranges.
3576   CheckExpectedBuffers("0K 30 60 90");
3577   CheckNoNextBuffer();
3578   SeekToTimestamp(base::TimeDelta::FromMilliseconds(240));
3579   CheckExpectedBuffers("240K 270 300");
3580 }
3581
3582 TEST_F(SourceBufferStreamTest, Remove_WholeGOPBeingAppended) {
3583   Seek(0);
3584   NewSegmentAppend("0K 30 60 90");
3585   CheckExpectedRangesByTimestamp("{ [0,120) }");
3586
3587   // Remove the keyframe of the current GOP being appended.
3588   RemoveInMs(0, 30, 120);
3589   CheckExpectedRangesByTimestamp("{ }");
3590
3591   // Continue appending the current GOP.
3592   AppendBuffers("210 240");
3593
3594   CheckExpectedRangesByTimestamp("{ }");
3595
3596   // Append the beginning of the next GOP.
3597   AppendBuffers("270K 300");
3598
3599   // Verify that the new range is started at the
3600   // beginning of the next GOP.
3601   CheckExpectedRangesByTimestamp("{ [270,330) }");
3602
3603   // Verify the buffers in the ranges.
3604   CheckNoNextBuffer();
3605   SeekToTimestamp(base::TimeDelta::FromMilliseconds(270));
3606   CheckExpectedBuffers("270K 300");
3607 }
3608
3609 TEST_F(SourceBufferStreamTest,
3610        Remove_PreviousAppendDestroyedAndOverwriteExistingRange) {
3611   SeekToTimestamp(base::TimeDelta::FromMilliseconds(90));
3612
3613   NewSegmentAppend("90K 120 150");
3614   CheckExpectedRangesByTimestamp("{ [90,180) }");
3615
3616   // Append a segment before the previously appended data.
3617   NewSegmentAppend("0K 30 60");
3618
3619   // Verify that the ranges get merged.
3620   CheckExpectedRangesByTimestamp("{ [0,180) }");
3621
3622   // Remove the data from the last append.
3623   RemoveInMs(0, 90, 360);
3624   CheckExpectedRangesByTimestamp("{ [90,180) }");
3625
3626   // Append a new segment that follows the removed segment and
3627   // starts at the beginning of the range left over from the
3628   // remove.
3629   NewSegmentAppend("90K 121 151");
3630   CheckExpectedBuffers("90K 121 151");
3631 }
3632
3633 TEST_F(SourceBufferStreamTest, Remove_GapAtBeginningOfMediaSegment) {
3634   Seek(0);
3635
3636   // Append a media segment that has a gap at the beginning of it.
3637   NewSegmentAppend(base::TimeDelta::FromMilliseconds(0),
3638                    "30K 60 90 120K 150");
3639   CheckExpectedRangesByTimestamp("{ [0,180) }");
3640
3641   // Remove the gap that doesn't contain any buffers.
3642   RemoveInMs(0, 10, 180);
3643   CheckExpectedRangesByTimestamp("{ [10,180) }");
3644
3645   // Verify we still get the first buffer still since only part of
3646   // the gap was removed.
3647   // TODO(acolwell/wolenetz): Consider not returning a buffer at this
3648   // point since the current seek position has been explicitly
3649   // removed but didn't happen to remove any buffers.
3650   // http://crbug.com/384016
3651   CheckExpectedBuffers("30K");
3652
3653   // Remove a range that includes the first GOP.
3654   RemoveInMs(0, 60, 180);
3655
3656   // Verify that no buffer is returned because the current buffer
3657   // position has been removed.
3658   CheckNoNextBuffer();
3659
3660   CheckExpectedRangesByTimestamp("{ [120,180) }");
3661 }
3662
3663 TEST_F(SourceBufferStreamTest, Text_Append_SingleRange) {
3664   SetTextStream();
3665   NewSegmentAppend("0K 500K 1000K");
3666   CheckExpectedRangesByTimestamp("{ [0,1500) }");
3667
3668   Seek(0);
3669   CheckExpectedBuffers("0K 500K 1000K");
3670 }
3671
3672 TEST_F(SourceBufferStreamTest, Text_Append_DisjointAfter) {
3673   SetTextStream();
3674   NewSegmentAppend("0K 500K 1000K");
3675   CheckExpectedRangesByTimestamp("{ [0,1500) }");
3676   NewSegmentAppend("3000K 3500K 4000K");
3677   CheckExpectedRangesByTimestamp("{ [0,4500) }");
3678
3679   Seek(0);
3680   CheckExpectedBuffers("0K 500K 1000K 3000K 3500K 4000K");
3681 }
3682
3683 TEST_F(SourceBufferStreamTest, Text_Append_DisjointBefore) {
3684   SetTextStream();
3685   NewSegmentAppend("3000K 3500K 4000K");
3686   CheckExpectedRangesByTimestamp("{ [3000,4500) }");
3687   NewSegmentAppend("0K 500K 1000K");
3688   CheckExpectedRangesByTimestamp("{ [0,4500) }");
3689
3690   Seek(0);
3691   CheckExpectedBuffers("0K 500K 1000K 3000K 3500K 4000K");
3692 }
3693
3694 TEST_F(SourceBufferStreamTest, Text_CompleteOverlap) {
3695   SetTextStream();
3696   NewSegmentAppend("3000K 3500K 4000K");
3697   CheckExpectedRangesByTimestamp("{ [3000,4500) }");
3698   NewSegmentAppend("0K 501K 1001K 1501K 2001K 2501K "
3699                    "3001K 3501K 4001K 4501K 5001K");
3700   CheckExpectedRangesByTimestamp("{ [0,5501) }");
3701
3702   Seek(0);
3703   CheckExpectedBuffers("0K 501K 1001K 1501K 2001K 2501K "
3704                        "3001K 3501K 4001K 4501K 5001K");
3705 }
3706
3707 TEST_F(SourceBufferStreamTest, Text_OverlapAfter) {
3708   SetTextStream();
3709   NewSegmentAppend("0K 500K 1000K 1500K 2000K");
3710   CheckExpectedRangesByTimestamp("{ [0,2500) }");
3711   NewSegmentAppend("1499K 2001K 2501K 3001K");
3712   CheckExpectedRangesByTimestamp("{ [0,3501) }");
3713
3714   Seek(0);
3715   CheckExpectedBuffers("0K 500K 1000K 1499K 2001K 2501K 3001K");
3716 }
3717
3718 TEST_F(SourceBufferStreamTest, Text_OverlapBefore) {
3719   SetTextStream();
3720   NewSegmentAppend("1500K 2000K 2500K 3000K 3500K");
3721   CheckExpectedRangesByTimestamp("{ [1500,4000) }");
3722   NewSegmentAppend("0K 501K 1001K 1501K 2001K");
3723   CheckExpectedRangesByTimestamp("{ [0,4000) }");
3724
3725   Seek(0);
3726   CheckExpectedBuffers("0K 501K 1001K 1501K 2001K 3000K 3500K");
3727 }
3728
3729 TEST_F(SourceBufferStreamTest, SpliceFrame_Basic) {
3730   Seek(0);
3731   NewSegmentAppend("0K S(3K 6 9D3 10D5) 15 20 S(25K 30D5 35D5) 40");
3732   CheckExpectedBuffers("0K 3K 6 9 C 10 15 20 25K 30 C 35 40");
3733   CheckNoNextBuffer();
3734 }
3735
3736 TEST_F(SourceBufferStreamTest, SpliceFrame_SeekClearsSplice) {
3737   Seek(0);
3738   NewSegmentAppend("0K S(3K 6 9D3 10D5) 15K 20");
3739   CheckExpectedBuffers("0K 3K 6");
3740
3741   SeekToTimestamp(base::TimeDelta::FromMilliseconds(15));
3742   CheckExpectedBuffers("15K 20");
3743   CheckNoNextBuffer();
3744 }
3745
3746 TEST_F(SourceBufferStreamTest, SpliceFrame_SeekClearsSpliceFromTrackBuffer) {
3747   Seek(0);
3748   NewSegmentAppend("0K 2K S(3K 6 9D3 10D5) 15K 20");
3749   CheckExpectedBuffers("0K 2K");
3750
3751   // Overlap the existing segment.
3752   NewSegmentAppend("5K 15K 20");
3753   CheckExpectedBuffers("3K 6");
3754
3755   SeekToTimestamp(base::TimeDelta::FromMilliseconds(15));
3756   CheckExpectedBuffers("15K 20");
3757   CheckNoNextBuffer();
3758 }
3759
3760 TEST_F(SourceBufferStreamTest, SpliceFrame_ConfigChangeWithinSplice) {
3761   VideoDecoderConfig new_config = TestVideoConfig::Large();
3762   ASSERT_FALSE(new_config.Matches(video_config_));
3763
3764   // Add a new video config, then reset the config index back to the original.
3765   stream_->UpdateVideoConfig(new_config);
3766   stream_->UpdateVideoConfig(video_config_);
3767
3768   Seek(0);
3769   CheckVideoConfig(video_config_);
3770   NewSegmentAppend("0K S(3K 6C 9D3 10D5) 15");
3771
3772   CheckExpectedBuffers("0K 3K C");
3773   CheckVideoConfig(new_config);
3774   CheckExpectedBuffers("6 9 C");
3775   CheckExpectedBuffers("10 C");
3776   CheckVideoConfig(video_config_);
3777   CheckExpectedBuffers("15");
3778   CheckNoNextBuffer();
3779 }
3780
3781 TEST_F(SourceBufferStreamTest, SpliceFrame_BasicFromTrackBuffer) {
3782   Seek(0);
3783   NewSegmentAppend("0K 5K S(8K 9D1 10D10) 20");
3784   CheckExpectedBuffers("0K 5K");
3785
3786   // Overlap the existing segment.
3787   NewSegmentAppend("5K 20");
3788   CheckExpectedBuffers("8K 9 C 10 20");
3789   CheckNoNextBuffer();
3790 }
3791
3792 TEST_F(SourceBufferStreamTest,
3793        SpliceFrame_ConfigChangeWithinSpliceFromTrackBuffer) {
3794   VideoDecoderConfig new_config = TestVideoConfig::Large();
3795   ASSERT_FALSE(new_config.Matches(video_config_));
3796
3797   // Add a new video config, then reset the config index back to the original.
3798   stream_->UpdateVideoConfig(new_config);
3799   stream_->UpdateVideoConfig(video_config_);
3800
3801   Seek(0);
3802   CheckVideoConfig(video_config_);
3803   NewSegmentAppend("0K 5K S(7K 8C 9D1 10D10) 20");
3804   CheckExpectedBuffers("0K 5K");
3805
3806   // Overlap the existing segment.
3807   NewSegmentAppend("5K 20");
3808   CheckExpectedBuffers("7K C");
3809   CheckVideoConfig(new_config);
3810   CheckExpectedBuffers("8 9 C");
3811   CheckExpectedBuffers("10 C");
3812   CheckVideoConfig(video_config_);
3813   CheckExpectedBuffers("20");
3814   CheckNoNextBuffer();
3815 }
3816
3817 TEST_F(SourceBufferStreamTest, Audio_SpliceFrame_Basic) {
3818   SetAudioStream();
3819   Seek(0);
3820   NewSegmentAppend("0K 2K 4K 6K 8K 10K 12K");
3821   NewSegmentAppend("11K 13K 15K 17K");
3822   CheckExpectedBuffers("0K 2K 4K 6K 8K 10K 12K C 11K 13K 15K 17K");
3823   CheckNoNextBuffer();
3824 }
3825
3826 TEST_F(SourceBufferStreamTest, Audio_SpliceFrame_NoExactSplices) {
3827   SetAudioStream();
3828   Seek(0);
3829   NewSegmentAppend("0K 2K 4K 6K 8K 10K 12K");
3830   NewSegmentAppend("10K 14K");
3831   CheckExpectedBuffers("0K 2K 4K 6K 8K 10K 14K");
3832   CheckNoNextBuffer();
3833 }
3834
3835 // Do not allow splices on top of splices.
3836 TEST_F(SourceBufferStreamTest, Audio_SpliceFrame_NoDoubleSplice) {
3837   SetAudioStream();
3838   Seek(0);
3839   NewSegmentAppend("0K 2K 4K 6K 8K 10K 12K");
3840   NewSegmentAppend("11K 13K 15K 17K");
3841
3842   // Verify the splice was created.
3843   CheckExpectedBuffers("0K 2K 4K 6K 8K 10K 12K C 11K 13K 15K 17K");
3844   CheckNoNextBuffer();
3845   Seek(0);
3846
3847   // Create a splice before the first splice which would include it.
3848   NewSegmentAppend("9D2K");
3849
3850   // A splice on top of a splice should result in a discard of the original
3851   // splice and no new splice frame being generated.
3852   CheckExpectedBuffers("0K 2K 4K 6K 8K 9K 13K 15K 17K");
3853   CheckNoNextBuffer();
3854 }
3855
3856 // Test that a splice is not created if an end timestamp and start timestamp
3857 // overlap.
3858 TEST_F(SourceBufferStreamTest, Audio_SpliceFrame_NoSplice) {
3859   SetAudioStream();
3860   Seek(0);
3861   NewSegmentAppend("0K 2K 4K 6K 8K 10K");
3862   NewSegmentAppend("12K 14K 16K 18K");
3863   CheckExpectedBuffers("0K 2K 4K 6K 8K 10K 12K 14K 16K 18K");
3864   CheckNoNextBuffer();
3865 }
3866
3867 TEST_F(SourceBufferStreamTest, Audio_SpliceFrame_CorrectMediaSegmentStartTime) {
3868   SetAudioStream();
3869   Seek(0);
3870   NewSegmentAppend("0K 2K 4K");
3871   CheckExpectedRangesByTimestamp("{ [0,6) }");
3872   NewSegmentAppend("6K 8K 10K");
3873   CheckExpectedRangesByTimestamp("{ [0,12) }");
3874   NewSegmentAppend("1K 4D2K");
3875   CheckExpectedRangesByTimestamp("{ [0,12) }");
3876   CheckExpectedBuffers("0K 2K 4K C 1K 4K 6K 8K 10K");
3877   CheckNoNextBuffer();
3878 }
3879
3880 TEST_F(SourceBufferStreamTest, Audio_SpliceFrame_ConfigChange) {
3881   SetAudioStream();
3882
3883   AudioDecoderConfig new_config(kCodecVorbis,
3884                                 kSampleFormatPlanarF32,
3885                                 CHANNEL_LAYOUT_MONO,
3886                                 1000,
3887                                 NULL,
3888                                 0,
3889                                 false);
3890   ASSERT_NE(new_config.channel_layout(), audio_config_.channel_layout());
3891
3892   Seek(0);
3893   CheckAudioConfig(audio_config_);
3894   NewSegmentAppend("0K 2K 4K 6K");
3895   stream_->UpdateAudioConfig(new_config);
3896   NewSegmentAppend("5K 8K 12K");
3897   CheckExpectedBuffers("0K 2K 4K 6K C 5K 8K 12K");
3898   CheckAudioConfig(new_config);
3899   CheckNoNextBuffer();
3900 }
3901
3902 // Ensure splices are not created if there are not enough frames to crossfade.
3903 TEST_F(SourceBufferStreamTest, Audio_SpliceFrame_NoTinySplices) {
3904   SetAudioStream();
3905   Seek(0);
3906
3907   // Overlap the range [0, 2) with [1, 3).  Since each frame has a duration of
3908   // 2ms this results in an overlap of 1ms between the ranges.  A splice frame
3909   // should not be generated since it requires at least 2 frames, or 2ms in this
3910   // case, of data to crossfade.
3911   NewSegmentAppend("0D2K");
3912   CheckExpectedRangesByTimestamp("{ [0,2) }");
3913   NewSegmentAppend("1D2K");
3914   CheckExpectedRangesByTimestamp("{ [0,3) }");
3915   CheckExpectedBuffers("0K 1K");
3916   CheckNoNextBuffer();
3917 }
3918
3919 TEST_F(SourceBufferStreamTest, Audio_SpliceFrame_Preroll) {
3920   SetAudioStream();
3921   Seek(0);
3922   NewSegmentAppend("0K 2K 4K 6K 8K 10K 12K");
3923   NewSegmentAppend("11P 13K 15K 17K");
3924   CheckExpectedBuffers("0K 2K 4K 6K 8K 10K 12K C 11P 13K 15K 17K");
3925   CheckNoNextBuffer();
3926 }
3927
3928 TEST_F(SourceBufferStreamTest, Audio_PrerollFrame) {
3929   Seek(0);
3930   NewSegmentAppend("0K 3P 6K");
3931   CheckExpectedBuffers("0K 3P 6K");
3932   CheckNoNextBuffer();
3933 }
3934
3935 TEST_F(SourceBufferStreamTest, BFrames) {
3936   Seek(0);
3937   NewSegmentAppend("0K 120|30 30|60 60|90 90|120");
3938   CheckExpectedRangesByTimestamp("{ [0,150) }");
3939
3940   CheckExpectedBuffers("0K 120|30 30|60 60|90 90|120");
3941   CheckNoNextBuffer();
3942 }
3943
3944 // TODO(vrk): Add unit tests where keyframes are unaligned between streams.
3945 // (crbug.com/133557)
3946
3947 // TODO(vrk): Add unit tests with end of stream being called at interesting
3948 // times.
3949
3950 }  // namespace media