604c195da34ad43a48d8da8642102d317472c027
[platform/framework/web/crosswalk.git] / src / media / base / android / media_source_player_unittest.cc
1 // Copyright 2013 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 <string>
6
7 #include "base/basictypes.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/strings/stringprintf.h"
11 #include "media/base/android/audio_decoder_job.h"
12 #include "media/base/android/media_codec_bridge.h"
13 #include "media/base/android/media_drm_bridge.h"
14 #include "media/base/android/media_player_manager.h"
15 #include "media/base/android/media_source_player.h"
16 #include "media/base/android/video_decoder_job.h"
17 #include "media/base/bind_to_current_loop.h"
18 #include "media/base/decoder_buffer.h"
19 #include "media/base/test_data_util.h"
20 #include "testing/gmock/include/gmock/gmock.h"
21 #include "ui/gl/android/surface_texture.h"
22
23 namespace media {
24
25 // Helper macro to skip the test if MediaCodecBridge isn't available.
26 #define SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE()        \
27   do {                                                            \
28     if (!MediaCodecBridge::IsAvailable()) {                       \
29       VLOG(0) << "Could not run test - not supported on device."; \
30       return;                                                     \
31     }                                                             \
32   } while (0)
33
34 const base::TimeDelta kDefaultDuration =
35     base::TimeDelta::FromMilliseconds(10000);
36
37 // TODO(wolenetz/qinmin): Simplify tests with more effective mock usage, and
38 // fix flaky pointer-based MDJ inequality testing. See http://crbug.com/327839.
39
40 // Mock of MediaPlayerManager for testing purpose.
41 class MockMediaPlayerManager : public MediaPlayerManager {
42  public:
43   explicit MockMediaPlayerManager(base::MessageLoop* message_loop)
44       : message_loop_(message_loop),
45         playback_completed_(false),
46         num_resources_requested_(0),
47         num_resources_released_(0),
48         timestamp_updated_(false) {}
49   virtual ~MockMediaPlayerManager() {}
50
51   // MediaPlayerManager implementation.
52   virtual MediaResourceGetter* GetMediaResourceGetter() OVERRIDE {
53     return NULL;
54   }
55   virtual void OnTimeUpdate(int player_id,
56                             base::TimeDelta current_time) OVERRIDE {
57     timestamp_updated_ = true;
58   }
59   virtual void OnMediaMetadataChanged(
60       int player_id, base::TimeDelta duration, int width, int height,
61       bool success) OVERRIDE {}
62   virtual void OnPlaybackComplete(int player_id) OVERRIDE {
63     playback_completed_ = true;
64     if (message_loop_->is_running())
65       message_loop_->Quit();
66   }
67   virtual void OnMediaInterrupted(int player_id) OVERRIDE {}
68   virtual void OnBufferingUpdate(int player_id, int percentage) OVERRIDE {}
69   virtual void OnSeekComplete(int player_id,
70                               const base::TimeDelta& current_time) OVERRIDE {}
71   virtual void OnError(int player_id, int error) OVERRIDE {}
72   virtual void OnVideoSizeChanged(int player_id, int width,
73                                   int height) OVERRIDE {}
74   virtual MediaPlayerAndroid* GetFullscreenPlayer() OVERRIDE { return NULL; }
75   virtual MediaPlayerAndroid* GetPlayer(int player_id) OVERRIDE { return NULL; }
76   virtual void RequestFullScreen(int player_id) OVERRIDE {}
77 #if defined(VIDEO_HOLE)
78   virtual bool ShouldUseVideoOverlayForEmbeddedEncryptedVideo() OVERRIDE {
79     return false;
80   }
81 #endif  // defined(VIDEO_HOLE)
82
83   bool playback_completed() const {
84     return playback_completed_;
85   }
86
87   int num_resources_requested() const {
88     return num_resources_requested_;
89   }
90
91   int num_resources_released() const {
92     return num_resources_released_;
93   }
94
95   void OnMediaResourcesRequested(int player_id) {
96     num_resources_requested_++;
97   }
98
99   void OnMediaResourcesReleased(int player_id) {
100     num_resources_released_++;
101   }
102
103   bool timestamp_updated() const {
104     return timestamp_updated_;
105   }
106
107   void ResetTimestampUpdated() {
108     timestamp_updated_ = false;
109   }
110
111  private:
112   base::MessageLoop* message_loop_;
113   bool playback_completed_;
114   // The number of resource requests this object has seen.
115   int num_resources_requested_;
116   // The number of released resources.
117   int num_resources_released_;
118   // Playback timestamp was updated.
119   bool timestamp_updated_;
120
121   DISALLOW_COPY_AND_ASSIGN(MockMediaPlayerManager);
122 };
123
124 class MockDemuxerAndroid : public DemuxerAndroid {
125  public:
126   explicit MockDemuxerAndroid(base::MessageLoop* message_loop)
127       : message_loop_(message_loop),
128         num_data_requests_(0),
129         num_seek_requests_(0),
130         num_browser_seek_requests_(0) {}
131   virtual ~MockDemuxerAndroid() {}
132
133   virtual void Initialize(DemuxerAndroidClient* client) OVERRIDE {}
134   virtual void RequestDemuxerData(DemuxerStream::Type type) OVERRIDE {
135     num_data_requests_++;
136     if (message_loop_->is_running())
137       message_loop_->Quit();
138   }
139   virtual void RequestDemuxerSeek(const base::TimeDelta& time_to_seek,
140                                   bool is_browser_seek) OVERRIDE {
141     num_seek_requests_++;
142     if (is_browser_seek)
143       num_browser_seek_requests_++;
144   }
145
146   int num_data_requests() const { return num_data_requests_; }
147   int num_seek_requests() const { return num_seek_requests_; }
148   int num_browser_seek_requests() const { return num_browser_seek_requests_; }
149
150  private:
151   base::MessageLoop* message_loop_;
152
153   // The number of encoded data requests this object has seen.
154   int num_data_requests_;
155
156   // The number of regular and browser seek requests this object has seen.
157   int num_seek_requests_;
158
159   // The number of browser seek requests this object has seen.
160   int num_browser_seek_requests_;
161
162   DISALLOW_COPY_AND_ASSIGN(MockDemuxerAndroid);
163 };
164
165 class MediaSourcePlayerTest : public testing::Test {
166  public:
167   MediaSourcePlayerTest()
168       : manager_(&message_loop_),
169         demuxer_(new MockDemuxerAndroid(&message_loop_)),
170         player_(0, &manager_,
171                 base::Bind(&MockMediaPlayerManager::OnMediaResourcesRequested,
172                            base::Unretained(&manager_)),
173                 base::Bind(&MockMediaPlayerManager::OnMediaResourcesReleased,
174                            base::Unretained(&manager_)),
175                 scoped_ptr<DemuxerAndroid>(demuxer_),
176                 GURL()),
177         decoder_callback_hook_executed_(false),
178         surface_texture_a_is_next_(true) {}
179   virtual ~MediaSourcePlayerTest() {}
180
181  protected:
182   // Get the decoder job from the MediaSourcePlayer. The return value must not
183   // be NULL.
184   MediaDecoderJob* GetMediaDecoderJob(bool is_audio) {
185     if (is_audio) {
186       return reinterpret_cast<MediaDecoderJob*>(
187           player_.audio_decoder_job_.get());
188     }
189     return reinterpret_cast<MediaDecoderJob*>(
190         player_.video_decoder_job_.get());
191   }
192
193   // Get the MediaCodecBridge from the decoder job. The return value could be
194   // NULL if the decoder is not yet created.
195   MediaCodecBridge* GetMediaCodecBridge(bool is_audio) {
196     if (is_audio)
197       return player_.audio_decoder_job_->media_codec_bridge_.get();
198     return player_.video_decoder_job_->media_codec_bridge_.get();
199   }
200
201   // Get the per-job prerolling status from the MediaSourcePlayer's job matching
202   // |is_audio|. Caller must guard against NPE if the player's job is NULL.
203   bool IsPrerolling(bool is_audio) {
204     return GetMediaDecoderJob(is_audio)->prerolling_;
205   }
206
207   // Get the preroll timestamp from the MediaSourcePlayer.
208   base::TimeDelta GetPrerollTimestamp() {
209     return player_.preroll_timestamp_;
210   }
211
212   // Simulate player has reached starvation timeout.
213   void TriggerPlayerStarvation() {
214     player_.decoder_starvation_callback_.Cancel();
215     player_.OnDecoderStarved();
216   }
217
218   // Release() the player.
219   void ReleasePlayer() {
220     EXPECT_TRUE(player_.IsPlaying());
221     player_.Release();
222     EXPECT_FALSE(player_.IsPlaying());
223   }
224
225   // Upon the next successful decode callback, post a task to call Release()
226   // on the |player_|. TEST_F's do not have access to the private player
227   // members, hence this helper method.
228   // Prevent usage creep of MSP::set_decode_callback_for_testing() by
229   // only using it for the ReleaseWithOnPrefetchDoneAlreadyPosted test.
230   void OnNextTestDecodeCallbackPostTaskToReleasePlayer() {
231     DCHECK_EQ(&message_loop_, base::MessageLoop::current());
232     player_.set_decode_callback_for_testing(media::BindToCurrentLoop(
233       base::Bind(
234           &MediaSourcePlayerTest::ReleaseWithPendingPrefetchDoneVerification,
235           base::Unretained(this))));
236   }
237
238   // Asynch test callback posted upon decode completion to verify that a pending
239   // prefetch done event is not cleared across |player_|'s Release(). This helps
240   // ensure the ReleaseWithOnPrefetchDoneAlreadyPosted test scenario is met.
241   void ReleaseWithPendingPrefetchDoneVerification() {
242     EXPECT_TRUE(player_.IsEventPending(player_.PREFETCH_DONE_EVENT_PENDING));
243     ReleasePlayer();
244     EXPECT_TRUE(player_.IsEventPending(player_.PREFETCH_DONE_EVENT_PENDING));
245     EXPECT_FALSE(decoder_callback_hook_executed_);
246     EXPECT_FALSE(GetMediaCodecBridge(true));
247     decoder_callback_hook_executed_ = true;
248   }
249
250   DemuxerConfigs CreateAudioDemuxerConfigs(AudioCodec audio_codec,
251                                            bool use_low_sample_rate) {
252     DemuxerConfigs configs;
253     configs.audio_codec = audio_codec;
254     configs.audio_channels = 2;
255     configs.is_audio_encrypted = false;
256     configs.duration = kDefaultDuration;
257
258     if (audio_codec == kCodecVorbis) {
259       configs.audio_sampling_rate = use_low_sample_rate ? 11025 : 44100;
260       scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile(
261           "vorbis-extradata");
262       configs.audio_extra_data = std::vector<uint8>(
263           buffer->data(),
264           buffer->data() + buffer->data_size());
265       return configs;
266     }
267
268     // Other codecs are not yet supported by this helper.
269     EXPECT_EQ(audio_codec, kCodecAAC);
270
271     configs.audio_sampling_rate = 48000;
272     uint8 aac_extra_data[] = { 0x13, 0x10 };
273     configs.audio_extra_data = std::vector<uint8>(
274         aac_extra_data,
275         aac_extra_data + 2);
276     return configs;
277   }
278
279   DemuxerConfigs CreateVideoDemuxerConfigs(bool use_larger_size) {
280     DemuxerConfigs configs;
281     configs.video_codec = kCodecVP8;
282     configs.video_size =
283         use_larger_size ? gfx::Size(640, 480) : gfx::Size(320, 240);
284     configs.is_video_encrypted = false;
285     configs.duration = kDefaultDuration;
286     return configs;
287   }
288
289   DemuxerConfigs CreateAudioVideoDemuxerConfigs() {
290     DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, false);
291     configs.video_codec = kCodecVP8;
292     configs.video_size = gfx::Size(320, 240);
293     configs.is_video_encrypted = false;
294     return configs;
295   }
296
297   DemuxerConfigs CreateDemuxerConfigs(bool have_audio, bool have_video) {
298     DCHECK(have_audio || have_video);
299
300     if (have_audio && !have_video)
301       return CreateAudioDemuxerConfigs(kCodecVorbis, false);
302
303     if (have_video && !have_audio)
304       return CreateVideoDemuxerConfigs(false);
305
306     return CreateAudioVideoDemuxerConfigs();
307   }
308
309   // Starts an audio decoder job.
310   void StartAudioDecoderJob() {
311     Start(CreateAudioDemuxerConfigs(kCodecVorbis, false));
312   }
313
314   // Starts a video decoder job.
315   void StartVideoDecoderJob() {
316     Start(CreateVideoDemuxerConfigs(false));
317   }
318
319   // Starts decoding the data.
320   void Start(const DemuxerConfigs& configs) {
321     EXPECT_EQ(demuxer_->num_data_requests(), 0);
322     player_.OnDemuxerConfigsAvailable(configs);
323     player_.Start();
324
325     EXPECT_TRUE(player_.IsPlaying());
326     int expected_num_requests = (player_.HasAudio() ? 1 : 0) +
327         (player_.HasVideo() ? 1 : 0);
328     EXPECT_EQ(expected_num_requests, demuxer_->num_data_requests());
329   }
330
331   // Resumes decoding the data. Verifies player behavior relative to
332   // |expect_player_requests_audio_data| and
333   // |expect_player_requests_video_data|.
334   void Resume(bool expect_player_requests_audio_data,
335               bool expect_player_requests_video_data) {
336     EXPECT_FALSE(player_.IsPlaying());
337     EXPECT_TRUE(player_.HasVideo() || player_.HasAudio());
338     int original_num_data_requests = demuxer_->num_data_requests();
339     int expected_request_delta =
340         (expect_player_requests_audio_data ? 1 : 0) +
341         (expect_player_requests_video_data ? 1 : 0);
342
343     player_.Start();
344
345     EXPECT_TRUE(player_.IsPlaying());
346     EXPECT_EQ(original_num_data_requests + expected_request_delta,
347               demuxer_->num_data_requests());
348   }
349
350   // Keeps decoding audio data until the decoder starts to output samples.
351   // Gives up if no audio output after decoding 10 frames.
352   void DecodeAudioDataUntilOutputBecomesAvailable() {
353     EXPECT_TRUE(player_.IsPlaying());
354     base::TimeDelta current_time = player_.GetCurrentTime();
355     base::TimeDelta start_timestamp = current_time;
356     for (int i = 0; i < 10; ++i) {
357       manager_.ResetTimestampUpdated();
358       player_.OnDemuxerDataAvailable(
359           CreateReadFromDemuxerAckForAudio(i > 3 ? 3 : i));
360       WaitForAudioDecodeDone();
361       base::TimeDelta new_current_time = player_.GetCurrentTime();
362       EXPECT_LE(current_time.InMilliseconds(),
363                 new_current_time.InMilliseconds());
364       current_time = new_current_time;
365       if (manager_.timestamp_updated()) {
366         EXPECT_LT(start_timestamp.InMillisecondsF(),
367                   new_current_time.InMillisecondsF());
368         return;
369       }
370     }
371     EXPECT_TRUE(false);
372   }
373
374   AccessUnit CreateAccessUnitWithData(bool is_audio, int audio_packet_id) {
375     AccessUnit unit;
376
377     unit.status = DemuxerStream::kOk;
378     scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile(
379         is_audio ? base::StringPrintf("vorbis-packet-%d", audio_packet_id)
380             : "vp8-I-frame-320x240");
381     unit.data = std::vector<uint8>(
382         buffer->data(), buffer->data() + buffer->data_size());
383
384     if (is_audio) {
385       // Vorbis needs 4 extra bytes padding on Android to decode properly. Check
386       // NuMediaExtractor.cpp in Android source code.
387       uint8 padding[4] = { 0xff , 0xff , 0xff , 0xff };
388       unit.data.insert(unit.data.end(), padding, padding + 4);
389     }
390
391     return unit;
392   }
393
394   DemuxerData CreateReadFromDemuxerAckForAudio(int packet_id) {
395     DemuxerData data;
396     data.type = DemuxerStream::AUDIO;
397     data.access_units.resize(1);
398     data.access_units[0] = CreateAccessUnitWithData(true, packet_id);
399     return data;
400   }
401
402   DemuxerData CreateReadFromDemuxerAckForVideo() {
403     DemuxerData data;
404     data.type = DemuxerStream::VIDEO;
405     data.access_units.resize(1);
406     data.access_units[0] = CreateAccessUnitWithData(false, 0);
407     return data;
408   }
409
410   DemuxerData CreateEOSAck(bool is_audio) {
411     DemuxerData data;
412     data.type = is_audio ? DemuxerStream::AUDIO : DemuxerStream::VIDEO;
413     data.access_units.resize(1);
414     data.access_units[0].status = DemuxerStream::kOk;
415     data.access_units[0].end_of_stream = true;
416     return data;
417   }
418
419   DemuxerData CreateAbortedAck(bool is_audio) {
420     DemuxerData data;
421     data.type = is_audio ? DemuxerStream::AUDIO : DemuxerStream::VIDEO;
422     data.access_units.resize(1);
423     data.access_units[0].status = DemuxerStream::kAborted;
424     return data;
425   }
426
427   // Helper method for use at test start. It starts an audio decoder job and
428   // immediately feeds it some data to decode. Then, without letting the decoder
429   // job complete a decode cycle, it also starts player SeekTo(). Upon return,
430   // the player should not yet have sent the DemuxerSeek IPC request, though
431   // seek event should be pending. The audio decoder job will also still be
432   // decoding.
433   void StartAudioDecoderJobAndSeekToWhileDecoding(
434       const base::TimeDelta& seek_time) {
435     EXPECT_FALSE(GetMediaCodecBridge(true));
436     EXPECT_FALSE(player_.IsPlaying());
437     EXPECT_EQ(0, demuxer_->num_data_requests());
438     EXPECT_EQ(0.0, GetPrerollTimestamp().InMillisecondsF());
439     EXPECT_EQ(player_.GetCurrentTime(), GetPrerollTimestamp());
440     StartAudioDecoderJob();
441     EXPECT_FALSE(GetMediaDecoderJob(true)->is_decoding());
442     player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
443     EXPECT_EQ(2, demuxer_->num_data_requests());
444     EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
445     player_.SeekTo(seek_time);
446     EXPECT_EQ(0.0, GetPrerollTimestamp().InMillisecondsF());
447     EXPECT_EQ(0, demuxer_->num_seek_requests());
448     player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
449   }
450
451   // Seek, including simulated receipt of |kAborted| read between SeekTo() and
452   // OnDemuxerSeekDone(). Use this helper method only when the player already
453   // has created the media codec bridge. Exactly one request for more data is
454   // expected following the seek, so use this helper for players with only audio
455   // or only video.
456   void SeekPlayerWithAbort(bool is_audio, const base::TimeDelta& seek_time) {
457     int original_num_seeks = demuxer_->num_seek_requests();
458     int original_num_data_requests = demuxer_->num_data_requests();
459
460     // Initiate a seek. Skip the round-trip of requesting seek from renderer.
461     // Instead behave as if the renderer has asked us to seek.
462     player_.SeekTo(seek_time);
463
464     // Verify that the seek does not occur until previously outstanding data
465     // request is satisfied.
466     EXPECT_EQ(original_num_seeks, demuxer_->num_seek_requests());
467
468     // Simulate seeking causes the demuxer to abort the outstanding read
469     // caused by the seek.
470     player_.OnDemuxerDataAvailable(CreateAbortedAck(is_audio));
471
472     // Wait for the decode job to finish so we can process the seek request.
473     WaitForDecodeDone(is_audio, !is_audio);
474
475     // Verify that the seek is requested.
476     EXPECT_EQ(original_num_seeks + 1, demuxer_->num_seek_requests());
477
478     // Send back the seek done notification. This should trigger the player to
479     // call OnReadFromDemuxer() again.
480     EXPECT_EQ(original_num_data_requests, demuxer_->num_data_requests());
481     player_.OnDemuxerSeekDone(kNoTimestamp());
482     EXPECT_EQ(original_num_data_requests + 1, demuxer_->num_data_requests());
483
484     // No other seek should have been requested.
485     EXPECT_EQ(original_num_seeks + 1, demuxer_->num_seek_requests());
486   }
487
488   // Preroll the decoder job to |target_timestamp|. The first access unit
489   // to decode will have a timestamp equal to |start_timestamp|.
490   // TODO(qinmin): Add additional test cases for out-of-order decodes.
491   // See http://crbug.com/331421.
492   void PrerollDecoderToTime(bool is_audio,
493                             const base::TimeDelta& start_timestamp,
494                             const base::TimeDelta& target_timestamp) {
495     EXPECT_EQ(target_timestamp, player_.GetCurrentTime());
496     // |start_timestamp| must be smaller than |target_timestamp|.
497     EXPECT_LE(start_timestamp, target_timestamp);
498     DemuxerData data = is_audio ? CreateReadFromDemuxerAckForAudio(1) :
499         CreateReadFromDemuxerAckForVideo();
500     int current_timestamp = start_timestamp.InMilliseconds();
501
502     // Send some data with access unit timestamps before the |target_timestamp|,
503     // and continue sending the data until preroll finishes.
504     // This simulates the common condition that AUs received after browser
505     // seek begin with timestamps before the seek target, and don't
506     // immediately complete preroll.
507     while (IsPrerolling(is_audio)) {
508       data.access_units[0].timestamp =
509           base::TimeDelta::FromMilliseconds(current_timestamp);
510       player_.OnDemuxerDataAvailable(data);
511       EXPECT_TRUE(GetMediaDecoderJob(is_audio)->is_decoding());
512       EXPECT_TRUE(GetMediaCodecBridge(is_audio));
513       EXPECT_EQ(target_timestamp, player_.GetCurrentTime());
514       current_timestamp += 30;
515       WaitForDecodeDone(is_audio, !is_audio);
516     }
517     EXPECT_LE(target_timestamp, player_.GetCurrentTime());
518   }
519
520   DemuxerData CreateReadFromDemuxerAckWithConfigChanged(
521       bool is_audio,
522       int config_unit_index,
523       const DemuxerConfigs& configs) {
524     DemuxerData data;
525     data.type = is_audio ? DemuxerStream::AUDIO : DemuxerStream::VIDEO;
526     data.access_units.resize(config_unit_index + 1);
527
528     for (int i = 0; i < config_unit_index; ++i)
529       data.access_units[i] = CreateAccessUnitWithData(is_audio, i);
530
531     data.access_units[config_unit_index].status = DemuxerStream::kConfigChanged;
532     data.demuxer_configs.resize(1);
533     data.demuxer_configs[0] = configs;
534     return data;
535   }
536
537   // Valid only for video-only player tests. If |trigger_with_release_start| is
538   // true, triggers the browser seek with a Release() + video data received +
539   // Start() with a new surface. If false, triggers the browser seek by
540   // setting a new video surface after beginning decode of received video data.
541   // Such data receipt causes possibility that an I-frame is not next, and
542   // browser seek results once decode completes and surface change processing
543   // begins.
544   void BrowserSeekPlayer(bool trigger_with_release_start) {
545     int expected_num_data_requests = demuxer_->num_data_requests() + 2;
546     int expected_num_seek_requests = demuxer_->num_seek_requests();
547     int expected_num_browser_seek_requests =
548         demuxer_->num_browser_seek_requests();
549
550     CreateNextTextureAndSetVideoSurface();
551     StartVideoDecoderJob();
552     if (trigger_with_release_start) {
553       // Consume the first frame, so that the next VideoDecoderJob will not
554       // inherit the I-frame from the previous decoder.
555       player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
556       ReleasePlayer();
557       WaitForVideoDecodeDone();
558
559       // Simulate demuxer's response to the video data request. The data will be
560       // passed to the next MediaCodecBridge.
561       player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
562       EXPECT_FALSE(GetMediaCodecBridge(false));
563       EXPECT_FALSE(player_.IsPlaying());
564       EXPECT_EQ(expected_num_seek_requests, demuxer_->num_seek_requests());
565
566       CreateNextTextureAndSetVideoSurface();
567       Resume(false, false);
568       EXPECT_FALSE(GetMediaCodecBridge(false));
569
570       // Run the message loop so that prefetch will complete.
571       while (expected_num_seek_requests == demuxer_->num_seek_requests())
572         message_loop_.RunUntilIdle();
573     } else {
574       // Simulate demuxer's response to the video data request.
575       player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
576
577       // While the decoder is decoding, trigger a browser seek by changing
578       // surface. Demuxer does not know of browser seek in advance, so no
579       // |kAborted| data is required (though |kAborted| can certainly occur for
580       // any pending read in reality due to renderer preparing for a regular
581       // seek).
582       CreateNextTextureAndSetVideoSurface();
583
584       // Browser seek should not begin until decoding has completed.
585       EXPECT_TRUE(GetMediaCodecBridge(false));
586       EXPECT_EQ(expected_num_seek_requests, demuxer_->num_seek_requests());
587
588       // Wait for the media codec bridge to finish decoding and be reset pending
589       // the browser seek.
590       WaitForVideoDecodeDone();
591       player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
592     }
593
594     // Only one browser seek should have been initiated, and no further data
595     // should have been requested.
596     expected_num_seek_requests++;
597     expected_num_browser_seek_requests++;
598     EXPECT_EQ(expected_num_seek_requests, demuxer_->num_seek_requests());
599     EXPECT_EQ(expected_num_browser_seek_requests,
600               demuxer_->num_browser_seek_requests());
601     EXPECT_EQ(expected_num_data_requests, demuxer_->num_data_requests());
602   }
603
604   // Creates a new media codec bridge and feeds it data ending with a
605   // |kConfigChanged| access unit. If |config_unit_in_prefetch| is true, sends
606   // feeds the config change AU in response to the job's first read request
607   // (prefetch). If false, regular data is fed and decoded prior to feeding the
608   // config change AU in response to the second data request (after prefetch
609   // completed). |config_unit_index| controls which access unit is
610   // |kConfigChanged|. If |enable_adaptive_playback| is true, config change will
611   // not cause the decoder to recreate the media codec bridge. Otherwise, the
612   // decoder has to drain all its data before recreating the new codec.
613   void SendConfigChangeToDecoder(bool is_audio,
614                                  bool config_unit_in_prefetch,
615                                  int config_unit_index,
616                                  bool enable_adaptive_playback) {
617     EXPECT_FALSE(GetMediaCodecBridge(is_audio));
618     if (is_audio) {
619       StartAudioDecoderJob();
620     } else {
621       CreateNextTextureAndSetVideoSurface();
622       StartVideoDecoderJob();
623     }
624
625     int expected_num_data_requests = demuxer_->num_data_requests();
626     // Feed and decode a standalone access unit so the player exits prefetch.
627     if (!config_unit_in_prefetch) {
628       if (is_audio) {
629         player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
630       } else {
631         player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
632         EnableAdaptiveVideoPlayback(enable_adaptive_playback);
633       }
634
635       WaitForDecodeDone(is_audio, !is_audio);
636
637       // We should have completed the prefetch phase at this point.
638       expected_num_data_requests++;
639       EXPECT_EQ(expected_num_data_requests, demuxer_->num_data_requests());
640     }
641
642     DemuxerConfigs configs = is_audio ?
643         CreateAudioDemuxerConfigs(kCodecAAC, false) :
644         CreateVideoDemuxerConfigs(true);
645     // Feed and decode access units with data for any units prior to
646     // |config_unit_index|, and a |kConfigChanged| unit at that index.
647     // Player should prepare to reconfigure the decoder job, and should request
648     // new demuxer configs.
649     player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckWithConfigChanged(
650         is_audio, config_unit_index, configs));
651
652     expected_num_data_requests++;
653     EXPECT_EQ(expected_num_data_requests, demuxer_->num_data_requests());
654     if (is_audio)
655       player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
656     else
657       player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
658
659     // If the adaptive playback setting was not passed to the MediaCodecBridge
660     // earlier, do it here.
661     if (config_unit_in_prefetch && !is_audio)
662       EnableAdaptiveVideoPlayback(enable_adaptive_playback);
663   }
664
665   // Send a config change to the decoder job and drain the decoder so that the
666   // config change is processed.
667   void StartConfigChange(bool is_audio,
668                          bool config_unit_in_prefetch,
669                          int config_unit_index,
670                          bool enable_adaptive_playback) {
671     SendConfigChangeToDecoder(is_audio, config_unit_in_prefetch,
672                               config_unit_index, enable_adaptive_playback);
673
674     EXPECT_EQ(!config_unit_in_prefetch && !enable_adaptive_playback &&
675               config_unit_index == 0, IsDrainingDecoder(is_audio));
676     int expected_num_data_requests = demuxer_->num_data_requests();
677     // Run until decoder starts to request new data.
678     while (demuxer_->num_data_requests() == expected_num_data_requests)
679       message_loop_.RunUntilIdle();
680     EXPECT_FALSE(IsDrainingDecoder(is_audio));
681   }
682
683   void EnableAdaptiveVideoPlayback(bool enable) {
684     EXPECT_TRUE(GetMediaCodecBridge(false));
685     static_cast<VideoCodecBridge*>(GetMediaCodecBridge(false))->
686         set_adaptive_playback_supported_for_testing(
687             enable ? 1 : 0);
688   }
689
690   void CreateNextTextureAndSetVideoSurface() {
691     gfx::SurfaceTexture* surface_texture;
692     if (surface_texture_a_is_next_) {
693       surface_texture_a_ = gfx::SurfaceTexture::Create(next_texture_id_++);
694       surface_texture = surface_texture_a_.get();
695     } else {
696       surface_texture_b_ = gfx::SurfaceTexture::Create(next_texture_id_++);
697       surface_texture = surface_texture_b_.get();
698     }
699
700     surface_texture_a_is_next_ = !surface_texture_a_is_next_;
701     gfx::ScopedJavaSurface surface = gfx::ScopedJavaSurface(surface_texture);
702     player_.SetVideoSurface(surface.Pass());
703   }
704
705   // Wait for one or both of the jobs to complete decoding. Media codec bridges
706   // are assumed to exist for any stream whose decode completion is awaited.
707   void WaitForDecodeDone(bool wait_for_audio, bool wait_for_video) {
708     DCHECK(wait_for_audio || wait_for_video);
709     while ((wait_for_audio && GetMediaCodecBridge(true) &&
710                GetMediaDecoderJob(true)->HasData() &&
711                GetMediaDecoderJob(true)->is_decoding()) ||
712            (wait_for_video && GetMediaCodecBridge(false) &&
713                GetMediaDecoderJob(false)->HasData() &&
714                GetMediaDecoderJob(false)->is_decoding())) {
715       message_loop_.RunUntilIdle();
716     }
717   }
718
719   void WaitForAudioDecodeDone() {
720     WaitForDecodeDone(true, false);
721   }
722
723   void WaitForVideoDecodeDone() {
724     WaitForDecodeDone(false, true);
725   }
726
727   void WaitForAudioVideoDecodeDone() {
728     WaitForDecodeDone(true, true);
729   }
730
731   // If |send_eos| is true, generates EOS for the stream corresponding to
732   // |eos_for_audio|. Verifies that playback completes and no further data
733   // is requested.
734   // If |send_eos| is false, then it is assumed that caller previously arranged
735   // for player to receive EOS for each stream, but the player has not yet
736   // decoded all of them. In this case, |eos_for_audio| is ignored.
737   void VerifyPlaybackCompletesOnEOSDecode(bool send_eos, bool eos_for_audio) {
738     int original_num_data_requests = demuxer_->num_data_requests();
739     if (send_eos)
740       player_.OnDemuxerDataAvailable(CreateEOSAck(eos_for_audio));
741     EXPECT_FALSE(manager_.playback_completed());
742     message_loop_.Run();
743     EXPECT_TRUE(manager_.playback_completed());
744     EXPECT_EQ(original_num_data_requests, demuxer_->num_data_requests());
745   }
746
747   void VerifyCompletedPlaybackResumesOnSeekPlusStart(bool have_audio,
748                                                      bool have_video) {
749     DCHECK(have_audio || have_video);
750
751     EXPECT_TRUE(manager_.playback_completed());
752
753     player_.SeekTo(base::TimeDelta());
754     player_.OnDemuxerSeekDone(kNoTimestamp());
755     Resume(have_audio, have_video);
756   }
757
758   // Starts the appropriate decoder jobs according to |have_audio| and
759   // |have_video|. Then starts seek during decode of EOS or non-EOS according to
760   // |eos_audio| and |eos_video|. Simulates seek completion and verifies that
761   // playback never completed. |eos_{audio,video}| is ignored if the
762   // corresponding |have_{audio,video}| is false.
763   void VerifySeekDuringEOSDecodePreventsPlaybackCompletion(bool have_audio,
764                                                            bool have_video,
765                                                            bool eos_audio,
766                                                            bool eos_video) {
767     DCHECK(have_audio || have_video);
768
769     if (have_video)
770       CreateNextTextureAndSetVideoSurface();
771
772     Start(CreateDemuxerConfigs(have_audio, have_video));
773
774     if (have_audio)
775       player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
776
777     if (have_video)
778       player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
779
780     // Run until more data is requested a number of times equal to the number of
781     // media types configured. Since prefetching may be in progress, we cannot
782     // reliably expect Run() to complete until we have sent demuxer data for all
783     // configured media types, above.
784     WaitForDecodeDone(have_audio, have_video);
785
786     // Simulate seek while decoding EOS or non-EOS for the appropriate
787     // stream(s).
788     if (have_audio) {
789       if (eos_audio)
790         player_.OnDemuxerDataAvailable(CreateEOSAck(true));
791       else
792         player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(1));
793     }
794
795     if (have_video) {
796       if (eos_video)
797         player_.OnDemuxerDataAvailable(CreateEOSAck(false));
798       else
799         player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
800     }
801
802     player_.SeekTo(base::TimeDelta());
803     EXPECT_EQ(0, demuxer_->num_seek_requests());
804     WaitForDecodeDone(have_audio, have_video);
805     EXPECT_EQ(1, demuxer_->num_seek_requests());
806
807     player_.OnDemuxerSeekDone(kNoTimestamp());
808     EXPECT_FALSE(manager_.playback_completed());
809   }
810
811   base::TimeTicks StartTimeTicks() {
812     return player_.start_time_ticks_;
813   }
814
815   bool IsRequestingDemuxerData(bool is_audio) {
816     return GetMediaDecoderJob(is_audio)->is_requesting_demuxer_data_;
817   }
818
819   bool IsDrainingDecoder(bool is_audio) {
820     return GetMediaDecoderJob(is_audio)->drain_decoder_;
821   }
822
823   base::MessageLoop message_loop_;
824   MockMediaPlayerManager manager_;
825   MockDemuxerAndroid* demuxer_;  // Owned by |player_|.
826   MediaSourcePlayer player_;
827
828   // Track whether a possibly async decoder callback test hook has run.
829   bool decoder_callback_hook_executed_;
830
831   // We need to keep the surface texture while the decoder is actively decoding.
832   // Otherwise, it may trigger unexpected crashes on some devices. To switch
833   // surfaces, tests need to create a new surface texture without releasing
834   // their previous one. In CreateNextTextureAndSetVideoSurface(), we toggle
835   // between two surface textures, only replacing the N-2 texture. Assumption is
836   // that no more than N-1 texture is in use by decoder when
837   // CreateNextTextureAndSetVideoSurface() is called.
838   scoped_refptr<gfx::SurfaceTexture> surface_texture_a_;
839   scoped_refptr<gfx::SurfaceTexture> surface_texture_b_;
840   bool surface_texture_a_is_next_;
841   int next_texture_id_;
842
843   DISALLOW_COPY_AND_ASSIGN(MediaSourcePlayerTest);
844 };
845
846 TEST_F(MediaSourcePlayerTest, StartAudioDecoderWithValidConfig) {
847   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
848
849   // Test audio codec will be created when valid configs and data are passed to
850   // the audio decoder job.
851   StartAudioDecoderJob();
852   EXPECT_EQ(0, demuxer_->num_seek_requests());
853   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
854   EXPECT_TRUE(GetMediaCodecBridge(true));
855 }
856
857 TEST_F(MediaSourcePlayerTest, StartAudioDecoderWithInvalidConfig) {
858   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
859
860   // Test audio decoder job will not be created when failed to start the codec.
861   DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, false);
862   // Replace with invalid |audio_extra_data|
863   configs.audio_extra_data.clear();
864   uint8 invalid_codec_data[] = { 0x00, 0xff, 0xff, 0xff, 0xff };
865   configs.audio_extra_data.insert(configs.audio_extra_data.begin(),
866                                  invalid_codec_data, invalid_codec_data + 4);
867   Start(configs);
868
869   // Decoder is not created after data is received.
870   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
871   EXPECT_FALSE(GetMediaCodecBridge(true));
872 }
873
874 TEST_F(MediaSourcePlayerTest, StartVideoCodecWithValidSurface) {
875   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
876
877   // Test video codec will not be created until data is received.
878   StartVideoDecoderJob();
879
880   // Set both an initial and a later video surface without receiving any
881   // demuxed data yet.
882   CreateNextTextureAndSetVideoSurface();
883   EXPECT_FALSE(GetMediaCodecBridge(false));
884   CreateNextTextureAndSetVideoSurface();
885   EXPECT_FALSE(GetMediaCodecBridge(false));
886
887   // No seeks, even on setting surface, should have occurred. (Browser seeks can
888   // occur on setting surface, but only after previously receiving video data.)
889   EXPECT_EQ(0, demuxer_->num_seek_requests());
890
891   // Send the first input chunk and verify that decoder will be created.
892   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
893   EXPECT_TRUE(GetMediaCodecBridge(false));
894 }
895
896 TEST_F(MediaSourcePlayerTest, StartVideoCodecWithInvalidSurface) {
897   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
898
899   // Test video codec will not be created when surface is invalid.
900   scoped_refptr<gfx::SurfaceTexture> surface_texture(
901       gfx::SurfaceTexture::Create(0));
902   gfx::ScopedJavaSurface surface(surface_texture.get());
903   StartVideoDecoderJob();
904
905   // Release the surface texture.
906   surface_texture = NULL;
907   player_.SetVideoSurface(surface.Pass());
908
909   // Player should not seek the demuxer on setting initial surface.
910   EXPECT_EQ(0, demuxer_->num_seek_requests());
911   EXPECT_EQ(1, demuxer_->num_data_requests());
912
913   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
914   EXPECT_FALSE(GetMediaCodecBridge(false));
915 }
916
917 TEST_F(MediaSourcePlayerTest, ReadFromDemuxerAfterSeek) {
918   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
919
920   // Test decoder job will resend a ReadFromDemuxer request after seek.
921   StartAudioDecoderJob();
922   SeekPlayerWithAbort(true, base::TimeDelta());
923 }
924
925 TEST_F(MediaSourcePlayerTest, SetSurfaceWhileSeeking) {
926   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
927
928   // Test SetVideoSurface() will not cause an extra seek while the player is
929   // waiting for demuxer to indicate seek is done.
930   player_.OnDemuxerConfigsAvailable(
931       CreateVideoDemuxerConfigs(false));
932
933   // Initiate a seek. Skip requesting element seek of renderer.
934   // Instead behave as if the renderer has asked us to seek.
935   player_.SeekTo(base::TimeDelta());
936   EXPECT_EQ(1, demuxer_->num_seek_requests());
937
938   CreateNextTextureAndSetVideoSurface();
939   EXPECT_EQ(1, demuxer_->num_seek_requests());
940   player_.Start();
941
942   // Send the seek done notification. The player should start requesting data.
943   player_.OnDemuxerSeekDone(kNoTimestamp());
944   EXPECT_FALSE(GetMediaCodecBridge(false));
945   EXPECT_EQ(1, demuxer_->num_data_requests());
946   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
947   EXPECT_TRUE(GetMediaCodecBridge(false));
948
949   // Reconfirm exactly 1 seek request has been made of demuxer, and that it
950   // was not a browser seek request.
951   EXPECT_EQ(1, demuxer_->num_seek_requests());
952   EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
953 }
954
955 TEST_F(MediaSourcePlayerTest, ChangeMultipleSurfaceWhileDecoding) {
956   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
957
958   // Test MediaSourcePlayer can switch multiple surfaces during decoding.
959   CreateNextTextureAndSetVideoSurface();
960   StartVideoDecoderJob();
961   EXPECT_EQ(0, demuxer_->num_seek_requests());
962
963   // Send the first input chunk.
964   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
965
966   // While the decoder is decoding, change multiple surfaces. Pass an empty
967   // surface first.
968   gfx::ScopedJavaSurface empty_surface;
969   player_.SetVideoSurface(empty_surface.Pass());
970   // Next, pass a new non-empty surface.
971   CreateNextTextureAndSetVideoSurface();
972
973   // Wait for the media codec bridge to finish decoding and be reset pending a
974   // browser seek.
975   WaitForVideoDecodeDone();
976   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
977
978   // Only one browser seek should have been initiated. No further data request
979   // should have been processed on |message_loop_| before surface change event
980   // became pending, above.
981   EXPECT_EQ(1, demuxer_->num_browser_seek_requests());
982   EXPECT_EQ(2, demuxer_->num_data_requests());
983
984   // Simulate browser seek is done and confirm player requests more data for new
985   // video codec.
986   player_.OnDemuxerSeekDone(player_.GetCurrentTime());
987   EXPECT_FALSE(GetMediaCodecBridge(false));
988   EXPECT_EQ(3, demuxer_->num_data_requests());
989   EXPECT_EQ(1, demuxer_->num_seek_requests());
990
991   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
992   EXPECT_TRUE(GetMediaCodecBridge(false));
993 }
994
995 TEST_F(MediaSourcePlayerTest, SetEmptySurfaceAndStarveWhileDecoding) {
996   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
997
998   // Test player pauses if an empty surface is passed.
999   CreateNextTextureAndSetVideoSurface();
1000   StartVideoDecoderJob();
1001   EXPECT_EQ(1, demuxer_->num_data_requests());
1002
1003   // Send the first input chunk.
1004   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1005
1006   // While the decoder is decoding, pass an empty surface.
1007   gfx::ScopedJavaSurface empty_surface;
1008   player_.SetVideoSurface(empty_surface.Pass());
1009   // Let the player starve. However, it should not issue any new data request in
1010   // this case.
1011   TriggerPlayerStarvation();
1012   // Wait for the media codec bridge to finish decoding and be reset.
1013   while (GetMediaDecoderJob(false)->is_decoding())
1014     message_loop_.RunUntilIdle();
1015
1016   // No further seek or data requests should have been received since the
1017   // surface is empty.
1018   EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
1019   EXPECT_EQ(2, demuxer_->num_data_requests());
1020   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1021
1022   // Playback resumes once a non-empty surface is passed.
1023   CreateNextTextureAndSetVideoSurface();
1024   EXPECT_EQ(1, demuxer_->num_browser_seek_requests());
1025 }
1026
1027 TEST_F(MediaSourcePlayerTest, ReleaseVideoDecoderResourcesWhileDecoding) {
1028   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1029
1030   // Test that if video decoder is released while decoding, the resources will
1031   // not be immediately released.
1032   CreateNextTextureAndSetVideoSurface();
1033   StartVideoDecoderJob();
1034   // No resource is requested since there is no data to decode.
1035   EXPECT_EQ(0, manager_.num_resources_requested());
1036   ReleasePlayer();
1037   EXPECT_EQ(0, manager_.num_resources_released());
1038   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1039
1040   // Recreate the video decoder.
1041   CreateNextTextureAndSetVideoSurface();
1042   player_.Start();
1043   while (!GetMediaDecoderJob(false)->is_decoding())
1044     message_loop_.RunUntilIdle();
1045   EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
1046   EXPECT_EQ(1, manager_.num_resources_requested());
1047   ReleasePlayer();
1048   // The resource is still held by the video decoder until it finishes decoding.
1049   EXPECT_EQ(0, manager_.num_resources_released());
1050   // Wait for the media codec bridge to finish decoding and be reset.
1051   while (manager_.num_resources_released() != 1)
1052     message_loop_.RunUntilIdle();
1053 }
1054
1055 TEST_F(MediaSourcePlayerTest, AudioOnlyStartAfterSeekFinish) {
1056   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1057
1058   // Test audio decoder job will not start until pending seek event is handled.
1059   DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, false);
1060   player_.OnDemuxerConfigsAvailable(configs);
1061
1062   // Initiate a seek. Skip requesting element seek of renderer.
1063   // Instead behave as if the renderer has asked us to seek.
1064   player_.SeekTo(base::TimeDelta());
1065   EXPECT_EQ(1, demuxer_->num_seek_requests());
1066
1067   player_.Start();
1068   EXPECT_EQ(0, demuxer_->num_data_requests());
1069
1070   // Sending back the seek done notification.
1071   player_.OnDemuxerSeekDone(kNoTimestamp());
1072   EXPECT_FALSE(GetMediaCodecBridge(true));
1073   EXPECT_EQ(1, demuxer_->num_data_requests());
1074
1075   // Reconfirm exactly 1 seek request has been made of demuxer.
1076   EXPECT_EQ(1, demuxer_->num_seek_requests());
1077
1078   // Decoder is created after data is received.
1079   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1080   EXPECT_TRUE(GetMediaCodecBridge(true));
1081 }
1082
1083 TEST_F(MediaSourcePlayerTest, VideoOnlyStartAfterSeekFinish) {
1084   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1085
1086   // Test video decoder job will not start until pending seek event is handled.
1087   CreateNextTextureAndSetVideoSurface();
1088   DemuxerConfigs configs = CreateVideoDemuxerConfigs(false);
1089   player_.OnDemuxerConfigsAvailable(configs);
1090
1091   // Initiate a seek. Skip requesting element seek of renderer.
1092   // Instead behave as if the renderer has asked us to seek.
1093   player_.SeekTo(base::TimeDelta());
1094   EXPECT_EQ(1, demuxer_->num_seek_requests());
1095
1096   player_.Start();
1097   EXPECT_EQ(0, demuxer_->num_data_requests());
1098
1099   // Sending back the seek done notification.
1100   player_.OnDemuxerSeekDone(kNoTimestamp());
1101   EXPECT_FALSE(GetMediaCodecBridge(false));
1102   EXPECT_EQ(1, demuxer_->num_data_requests());
1103
1104   // Reconfirm exactly 1 seek request has been made of demuxer.
1105   EXPECT_EQ(1, demuxer_->num_seek_requests());
1106
1107   // Decoder is created after data is received.
1108   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1109   EXPECT_TRUE(GetMediaCodecBridge(false));
1110 }
1111
1112 TEST_F(MediaSourcePlayerTest, StartImmediatelyAfterPause) {
1113   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1114
1115   // Test that if the decoding job is not fully stopped after Pause(),
1116   // calling Start() will be a noop.
1117   StartAudioDecoderJob();
1118
1119   MediaDecoderJob* decoder_job = GetMediaDecoderJob(true);
1120   EXPECT_FALSE(GetMediaDecoderJob(true)->is_decoding());
1121
1122   // Sending data to player.
1123   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1124   EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
1125   EXPECT_EQ(2, demuxer_->num_data_requests());
1126
1127   // Decoder job will not immediately stop after Pause() since it is
1128   // running on another thread.
1129   player_.Pause(true);
1130   EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
1131
1132   // Nothing happens when calling Start() again.
1133   player_.Start();
1134   // Verify that Start() will not destroy and recreate the media codec bridge.
1135   EXPECT_EQ(decoder_job, GetMediaDecoderJob(true));
1136
1137   while (GetMediaDecoderJob(true)->is_decoding())
1138     message_loop_.RunUntilIdle();
1139   // The decoder job should finish and wait for data.
1140   EXPECT_EQ(2, demuxer_->num_data_requests());
1141   EXPECT_TRUE(IsRequestingDemuxerData(true));
1142 }
1143
1144 TEST_F(MediaSourcePlayerTest, DecoderJobsCannotStartWithoutAudio) {
1145   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1146
1147   // Test that when Start() is called, video decoder job will wait for audio
1148   // decoder job before start decoding the data.
1149   CreateNextTextureAndSetVideoSurface();
1150   Start(CreateAudioVideoDemuxerConfigs());
1151   MediaDecoderJob* audio_decoder_job = GetMediaDecoderJob(true);
1152   MediaDecoderJob* video_decoder_job = GetMediaDecoderJob(false);
1153
1154   EXPECT_FALSE(audio_decoder_job->is_decoding());
1155   EXPECT_FALSE(video_decoder_job->is_decoding());
1156
1157   // Sending video data to player, video decoder should not start.
1158   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1159   EXPECT_FALSE(video_decoder_job->is_decoding());
1160
1161   // Sending audio data to player, both decoders should start now.
1162   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1163   EXPECT_TRUE(audio_decoder_job->is_decoding());
1164   EXPECT_TRUE(video_decoder_job->is_decoding());
1165
1166   // No seeks should have occurred.
1167   EXPECT_EQ(0, demuxer_->num_seek_requests());
1168 }
1169
1170 TEST_F(MediaSourcePlayerTest, StartTimeTicksResetAfterDecoderUnderruns) {
1171   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1172
1173   // Test start time ticks will reset after decoder job underruns.
1174   StartAudioDecoderJob();
1175
1176   DecodeAudioDataUntilOutputBecomesAvailable();
1177
1178   // The decoder job should finish and a new request will be sent.
1179   base::TimeTicks previous = StartTimeTicks();
1180   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(3));
1181
1182   // Let the decoder starve.
1183   TriggerPlayerStarvation();
1184   WaitForAudioDecodeDone();
1185   EXPECT_TRUE(StartTimeTicks() == previous);
1186
1187   // Send new data to the decoder so it can finish prefetching. This should
1188   // reset the start time ticks.
1189   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(3));
1190   EXPECT_TRUE(StartTimeTicks() != previous);
1191
1192   base::TimeTicks current = StartTimeTicks();
1193   EXPECT_LE(0, (current - previous).InMillisecondsF());
1194 }
1195
1196 TEST_F(MediaSourcePlayerTest, V_SecondAccessUnitIsEOSAndResumePlayAfterSeek) {
1197   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1198
1199   // Test MediaSourcePlayer can replay video after input EOS is reached.
1200   CreateNextTextureAndSetVideoSurface();
1201   StartVideoDecoderJob();
1202
1203   // Send the first input chunk.
1204   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1205   WaitForVideoDecodeDone();
1206
1207   VerifyPlaybackCompletesOnEOSDecode(true, false);
1208   VerifyCompletedPlaybackResumesOnSeekPlusStart(false, true);
1209 }
1210
1211 TEST_F(MediaSourcePlayerTest, A_FirstAccessUnitIsEOSAndResumePlayAfterSeek) {
1212   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1213
1214   // Test decode of audio EOS buffer without any prior decode. See also
1215   // http://b/11696552.
1216   // Also tests that seeking+Start() after completing audio playback resumes
1217   // playback.
1218   Start(CreateAudioDemuxerConfigs(kCodecAAC, false));
1219   VerifyPlaybackCompletesOnEOSDecode(true, true);
1220   VerifyCompletedPlaybackResumesOnSeekPlusStart(true, false);
1221 }
1222
1223 TEST_F(MediaSourcePlayerTest, V_FirstAccessUnitAfterSeekIsEOS) {
1224   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1225
1226   // Test decode of video EOS buffer, just after seeking, without any prior
1227   // decode (other than the simulated |kAborted| resulting from the seek
1228   // process.)
1229   CreateNextTextureAndSetVideoSurface();
1230   StartVideoDecoderJob();
1231   SeekPlayerWithAbort(false, base::TimeDelta());
1232   VerifyPlaybackCompletesOnEOSDecode(true, false);
1233 }
1234
1235 TEST_F(MediaSourcePlayerTest, A_FirstAccessUnitAfterSeekIsEOS) {
1236   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1237
1238   // Test decode of audio EOS buffer, just after seeking, without any prior
1239   // decode (other than the simulated |kAborted| resulting from the seek
1240   // process.) See also http://b/11696552.
1241   Start(CreateAudioDemuxerConfigs(kCodecAAC, false));
1242   SeekPlayerWithAbort(true, base::TimeDelta());
1243   VerifyPlaybackCompletesOnEOSDecode(true, true);
1244 }
1245
1246 TEST_F(MediaSourcePlayerTest, AV_PlaybackCompletionAcrossConfigChange) {
1247   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1248
1249   // Test that if one stream (audio) has completed decode of EOS and the other
1250   // stream (video) processes config change, that subsequent video EOS completes
1251   // A/V playback.
1252   // Also tests that seeking+Start() after completing playback resumes playback.
1253   CreateNextTextureAndSetVideoSurface();
1254   Start(CreateAudioVideoDemuxerConfigs());
1255
1256   player_.OnDemuxerDataAvailable(CreateEOSAck(true));  // Audio EOS
1257   DemuxerConfigs configs = CreateVideoDemuxerConfigs(true);
1258   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckWithConfigChanged(
1259       false, 0, configs));  // Video |kConfigChanged| as first unit.
1260
1261   WaitForAudioVideoDecodeDone();
1262
1263   EXPECT_EQ(3, demuxer_->num_data_requests());
1264
1265   // At no time after completing audio EOS decode, above, should the
1266   // audio decoder job resume decoding. Send and decode video EOS.
1267   VerifyPlaybackCompletesOnEOSDecode(true, false);
1268   VerifyCompletedPlaybackResumesOnSeekPlusStart(true, true);
1269 }
1270
1271 TEST_F(MediaSourcePlayerTest, VA_PlaybackCompletionAcrossConfigChange) {
1272   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1273
1274   // Test that if one stream (video) has completed decode of EOS and the other
1275   // stream (audio) processes config change, that subsequent audio EOS completes
1276   // A/V playback.
1277   // Also tests that seeking+Start() after completing playback resumes playback.
1278   CreateNextTextureAndSetVideoSurface();
1279   Start(CreateAudioVideoDemuxerConfigs());
1280
1281   player_.OnDemuxerDataAvailable(CreateEOSAck(false));  // Video EOS
1282   // Audio |kConfigChanged| as first unit.
1283   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckWithConfigChanged(
1284       true, 0, CreateAudioDemuxerConfigs(kCodecVorbis, false)));
1285
1286   WaitForAudioVideoDecodeDone();
1287
1288   EXPECT_EQ(3, demuxer_->num_data_requests());
1289
1290   // At no time after completing video EOS decode, above, should the
1291   // video decoder job resume decoding. Send and decode audio EOS.
1292   VerifyPlaybackCompletesOnEOSDecode(true, true);
1293   VerifyCompletedPlaybackResumesOnSeekPlusStart(true, true);
1294 }
1295
1296 TEST_F(MediaSourcePlayerTest, AV_NoPrefetchForFinishedVideoOnAudioStarvation) {
1297   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1298
1299   // Test that if one stream (video) has completed decode of EOS, prefetch
1300   // resulting from player starvation occurs only for the other stream (audio),
1301   // and responding to that prefetch with EOS completes A/V playback, even if
1302   // another starvation occurs during the latter EOS's decode.
1303   CreateNextTextureAndSetVideoSurface();
1304   Start(CreateAudioVideoDemuxerConfigs());
1305
1306   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1307   player_.OnDemuxerDataAvailable(CreateEOSAck(false));  // Video EOS
1308
1309   // Wait until video EOS is processed and more data (assumed to be audio) is
1310   // requested.
1311   WaitForAudioVideoDecodeDone();
1312   EXPECT_EQ(3, demuxer_->num_data_requests());
1313
1314   // Simulate decoder underrun to trigger prefetch while still decoding audio.
1315   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(1));
1316   EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding() &&
1317               !GetMediaDecoderJob(false)->is_decoding());
1318   TriggerPlayerStarvation();
1319
1320   // Complete the audio decode that was in progress when simulated player
1321   // starvation was triggered.
1322   WaitForAudioDecodeDone();
1323   EXPECT_EQ(4, demuxer_->num_data_requests());
1324   player_.OnDemuxerDataAvailable(CreateEOSAck(true));  // Audio EOS
1325   EXPECT_FALSE(GetMediaDecoderJob(false)->is_decoding());
1326   EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
1327
1328   // Simulate another decoder underrun to trigger prefetch while decoding EOS.
1329   TriggerPlayerStarvation();
1330   VerifyPlaybackCompletesOnEOSDecode(false, true /* ignored */);
1331 }
1332
1333 TEST_F(MediaSourcePlayerTest, V_StarvationDuringEOSDecode) {
1334   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1335
1336   // Test that video-only playback completes without further data requested when
1337   // starvation occurs during EOS decode.
1338   CreateNextTextureAndSetVideoSurface();
1339   StartVideoDecoderJob();
1340   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1341   WaitForVideoDecodeDone();
1342
1343   // Simulate decoder underrun to trigger prefetch while decoding EOS.
1344   player_.OnDemuxerDataAvailable(CreateEOSAck(false));  // Video EOS
1345   EXPECT_TRUE(GetMediaDecoderJob(false)->is_decoding());
1346   TriggerPlayerStarvation();
1347   VerifyPlaybackCompletesOnEOSDecode(false, false /* ignored */);
1348 }
1349
1350 TEST_F(MediaSourcePlayerTest, A_StarvationDuringEOSDecode) {
1351   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1352
1353   // Test that audio-only playback completes without further data requested when
1354   // starvation occurs during EOS decode.
1355   StartAudioDecoderJob();
1356   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1357   WaitForAudioDecodeDone();
1358
1359   // Simulate decoder underrun to trigger prefetch while decoding EOS.
1360   player_.OnDemuxerDataAvailable(CreateEOSAck(true));  // Audio EOS
1361   EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
1362   TriggerPlayerStarvation();
1363   VerifyPlaybackCompletesOnEOSDecode(false, true /* ignored */);
1364 }
1365
1366 TEST_F(MediaSourcePlayerTest, AV_SeekDuringEOSDecodePreventsCompletion) {
1367   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1368
1369   // Test that seek supercedes audio+video playback completion on simultaneous
1370   // audio and video EOS decode, if SeekTo() occurs during these EOS decodes.
1371   VerifySeekDuringEOSDecodePreventsPlaybackCompletion(true, true, true, true);
1372 }
1373
1374 TEST_F(MediaSourcePlayerTest, AV_SeekDuringAudioEOSDecodePreventsCompletion) {
1375   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1376
1377   // Test that seek supercedes audio+video playback completion on simultaneous
1378   // audio EOS and video non-EOS decode, if SeekTo() occurs during these
1379   // decodes.
1380   VerifySeekDuringEOSDecodePreventsPlaybackCompletion(true, true, true, false);
1381 }
1382
1383 TEST_F(MediaSourcePlayerTest, AV_SeekDuringVideoEOSDecodePreventsCompletion) {
1384   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1385
1386   // Test that seek supercedes audio+video playback completion on simultaneous
1387   // audio non-EOS and video EOS decode, if SeekTo() occurs during these
1388   // decodes.
1389   VerifySeekDuringEOSDecodePreventsPlaybackCompletion(true, true, false, true);
1390 }
1391
1392 TEST_F(MediaSourcePlayerTest, V_SeekDuringEOSDecodePreventsCompletion) {
1393   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1394
1395   // Test that seek supercedes video-only playback completion on EOS decode, if
1396   // SeekTo() occurs during EOS decode.
1397   VerifySeekDuringEOSDecodePreventsPlaybackCompletion(false, true, false, true);
1398 }
1399
1400 TEST_F(MediaSourcePlayerTest, A_SeekDuringEOSDecodePreventsCompletion) {
1401   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1402
1403   // Test that seek supercedes audio-only playback completion on EOS decode, if
1404   // SeekTo() occurs during EOS decode.
1405   VerifySeekDuringEOSDecodePreventsPlaybackCompletion(true, false, true, false);
1406 }
1407
1408 TEST_F(MediaSourcePlayerTest, NoRequestForDataAfterAbort) {
1409   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1410
1411   // Test that the decoder will not request new data after receiving an aborted
1412   // access unit.
1413   StartAudioDecoderJob();
1414
1415   // Send an aborted access unit.
1416   player_.OnDemuxerDataAvailable(CreateAbortedAck(true));
1417   EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
1418   WaitForAudioDecodeDone();
1419
1420   // No request will be sent for new data.
1421   EXPECT_EQ(1, demuxer_->num_data_requests());
1422
1423   // No seek requests should have occurred.
1424   EXPECT_EQ(0, demuxer_->num_seek_requests());
1425 }
1426
1427 TEST_F(MediaSourcePlayerTest, DemuxerDataArrivesAfterRelease) {
1428   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1429
1430   // Test that the decoder should not crash if demuxer data arrives after
1431   // Release().
1432   StartAudioDecoderJob();
1433
1434   ReleasePlayer();
1435   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1436
1437   // The media codec bridge should have been released.
1438   EXPECT_FALSE(player_.IsPlaying());
1439
1440   // No further data should have been requested.
1441   EXPECT_EQ(1, demuxer_->num_data_requests());
1442
1443   // No seek requests should have occurred.
1444   EXPECT_EQ(0, demuxer_->num_seek_requests());
1445 }
1446
1447 TEST_F(MediaSourcePlayerTest, BrowserSeek_RegularSeekPendsBrowserSeekDone) {
1448   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1449
1450   // Test that a browser seek, once started, delays a newly arrived regular
1451   // SeekTo() request's demuxer seek until the browser seek is done.
1452   BrowserSeekPlayer(false);
1453
1454   // Simulate renderer requesting a regular seek while browser seek in progress.
1455   player_.SeekTo(base::TimeDelta());
1456
1457   // Simulate browser seek is done. Confirm player requests the regular seek,
1458   // still has no video codec configured, and has not requested any
1459   // further data since the surface change event became pending in
1460   // BrowserSeekPlayer().
1461   EXPECT_EQ(1, demuxer_->num_seek_requests());
1462   player_.OnDemuxerSeekDone(base::TimeDelta());
1463   EXPECT_EQ(2, demuxer_->num_seek_requests());
1464   EXPECT_EQ(1, demuxer_->num_browser_seek_requests());
1465
1466   // Simulate regular seek is done and confirm player requests more data for
1467   // new video codec.
1468   player_.OnDemuxerSeekDone(kNoTimestamp());
1469   EXPECT_FALSE(GetMediaCodecBridge(false));
1470   EXPECT_EQ(3, demuxer_->num_data_requests());
1471   EXPECT_EQ(2, demuxer_->num_seek_requests());
1472   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1473   EXPECT_TRUE(GetMediaCodecBridge(false));
1474 }
1475
1476 TEST_F(MediaSourcePlayerTest, BrowserSeek_InitialReleaseAndStart) {
1477   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1478
1479   // Test that no browser seek is requested if player Release() + Start() occurs
1480   // prior to receiving any data.
1481   CreateNextTextureAndSetVideoSurface();
1482   StartVideoDecoderJob();
1483   ReleasePlayer();
1484
1485   // Pass a new non-empty surface.
1486   CreateNextTextureAndSetVideoSurface();
1487
1488   player_.Start();
1489
1490   // No data request is issued since there is still one pending.
1491   EXPECT_EQ(1, demuxer_->num_data_requests());
1492   EXPECT_FALSE(GetMediaCodecBridge(false));
1493
1494   // No browser seek is needed.
1495   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1496   EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
1497   EXPECT_EQ(2, demuxer_->num_data_requests());
1498 }
1499
1500 TEST_F(MediaSourcePlayerTest, BrowserSeek_MidStreamReleaseAndStart) {
1501   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1502
1503   // Test that one browser seek is requested if player Release() + Start(), with
1504   // video data received between Release() and Start().
1505   BrowserSeekPlayer(true);
1506
1507   // Simulate browser seek is done and confirm player requests more data.
1508   player_.OnDemuxerSeekDone(base::TimeDelta());
1509   EXPECT_EQ(3, demuxer_->num_data_requests());
1510   EXPECT_EQ(1, demuxer_->num_seek_requests());
1511 }
1512
1513 TEST_F(MediaSourcePlayerTest, PrerollAudioAfterSeek) {
1514   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1515
1516   // Test decoder job will preroll the media to the seek position.
1517   StartAudioDecoderJob();
1518
1519   SeekPlayerWithAbort(true, base::TimeDelta::FromMilliseconds(100));
1520   EXPECT_TRUE(IsPrerolling(true));
1521   PrerollDecoderToTime(
1522       true, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100));
1523 }
1524
1525 TEST_F(MediaSourcePlayerTest, PrerollVideoAfterSeek) {
1526   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1527
1528   // Test decoder job will preroll the media to the seek position.
1529   CreateNextTextureAndSetVideoSurface();
1530   StartVideoDecoderJob();
1531
1532   SeekPlayerWithAbort(false, base::TimeDelta::FromMilliseconds(100));
1533   EXPECT_TRUE(IsPrerolling(false));
1534   PrerollDecoderToTime(
1535       false, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100));
1536 }
1537
1538 TEST_F(MediaSourcePlayerTest, SeekingAfterCompletingPrerollRestartsPreroll) {
1539   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1540
1541   // Test decoder job will begin prerolling upon seek, when it was not
1542   // prerolling prior to the seek.
1543   StartAudioDecoderJob();
1544   MediaDecoderJob* decoder_job = GetMediaDecoderJob(true);
1545   EXPECT_TRUE(IsPrerolling(true));
1546
1547   // Complete the initial preroll by feeding data to the decoder.
1548   DecodeAudioDataUntilOutputBecomesAvailable();
1549   EXPECT_FALSE(IsPrerolling(true));
1550
1551   SeekPlayerWithAbort(true, base::TimeDelta::FromMilliseconds(500));
1552
1553   // Prerolling should have begun again.
1554   EXPECT_TRUE(IsPrerolling(true));
1555   EXPECT_EQ(500.0, GetPrerollTimestamp().InMillisecondsF());
1556
1557   // Send data at and after the seek position. Prerolling should complete.
1558   for (int i = 0; i < 4; ++i) {
1559     DemuxerData data = CreateReadFromDemuxerAckForAudio(i);
1560     data.access_units[0].timestamp = base::TimeDelta::FromMilliseconds(
1561         500 + 30 * (i - 1));
1562     player_.OnDemuxerDataAvailable(data);
1563     EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
1564     WaitForAudioDecodeDone();
1565   }
1566   EXPECT_LT(500.0, player_.GetCurrentTime().InMillisecondsF());
1567   EXPECT_FALSE(IsPrerolling(true));
1568
1569   // Throughout this test, we should have not re-created the media codec bridge,
1570   // so IsPrerolling() transition from false to true was not due to constructor
1571   // initialization. It was due to BeginPrerolling().
1572   EXPECT_EQ(decoder_job, GetMediaDecoderJob(true));
1573 }
1574
1575 TEST_F(MediaSourcePlayerTest, PrerollContinuesAcrossReleaseAndStart) {
1576   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1577
1578   // Test decoder job will resume media prerolling if interrupted by Release()
1579   // and Start().
1580   StartAudioDecoderJob();
1581
1582   base::TimeDelta target_timestamp = base::TimeDelta::FromMilliseconds(100);
1583   SeekPlayerWithAbort(true, target_timestamp);
1584   EXPECT_TRUE(IsPrerolling(true));
1585   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
1586
1587   // Send some data before the seek position.
1588   // Test uses 'large' number of iterations because decoder job may not get
1589   // MEDIA_CODEC_OK output status until after a few dequeue output attempts.
1590   // This allows decoder status to stabilize prior to AU timestamp reaching
1591   // the preroll target.
1592   DemuxerData data;
1593   for (int i = 0; i < 10; ++i) {
1594     data = CreateReadFromDemuxerAckForAudio(3);
1595     data.access_units[0].timestamp = base::TimeDelta::FromMilliseconds(i * 10);
1596     if (i == 1) {
1597       // While still prerolling, Release() and Start() the player.
1598       ReleasePlayer();
1599       // The decoder is still decoding and will not be immediately released.
1600       EXPECT_TRUE(GetMediaCodecBridge(true));
1601       Resume(false, false);
1602     } else {
1603       player_.OnDemuxerDataAvailable(data);
1604       EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
1605       WaitForAudioDecodeDone();
1606     }
1607     EXPECT_TRUE(IsPrerolling(true));
1608   }
1609   EXPECT_EQ(100.0, player_.GetCurrentTime().InMillisecondsF());
1610   EXPECT_TRUE(IsPrerolling(true));
1611
1612   // Send data after the seek position.
1613   PrerollDecoderToTime(true, target_timestamp, target_timestamp);
1614 }
1615
1616 TEST_F(MediaSourcePlayerTest, PrerollContinuesAcrossConfigChange) {
1617   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1618
1619   // Test decoder job will resume media prerolling if interrupted by
1620   // |kConfigChanged| and OnDemuxerConfigsAvailable().
1621   StartAudioDecoderJob();
1622
1623   SeekPlayerWithAbort(true, base::TimeDelta::FromMilliseconds(100));
1624   EXPECT_TRUE(IsPrerolling(true));
1625   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
1626
1627   DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, true);
1628
1629   // In response to data request, simulate that demuxer signals config change by
1630   // sending an AU with |kConfigChanged|.
1631   DemuxerData data = CreateReadFromDemuxerAckWithConfigChanged(
1632       true, 0, configs);
1633   player_.OnDemuxerDataAvailable(data);
1634   PrerollDecoderToTime(
1635       true, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100));
1636 }
1637
1638 TEST_F(MediaSourcePlayerTest, PrerollContinuesAfterUnchangedConfigs) {
1639   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1640
1641   // Test decoder job will resume media prerolling if interrupted by a config
1642   // change access unit with unchanged configs.
1643   StartAudioDecoderJob();
1644
1645   SeekPlayerWithAbort(true, base::TimeDelta::FromMilliseconds(100));
1646   EXPECT_TRUE(IsPrerolling(true));
1647   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
1648
1649   DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, false);
1650
1651   // In response to data request, simulate that demuxer signals config change by
1652   // sending an AU with |kConfigChanged|.
1653   DemuxerData data = CreateReadFromDemuxerAckWithConfigChanged(
1654       true, 0, configs);
1655   player_.OnDemuxerDataAvailable(data);
1656   PrerollDecoderToTime(
1657       true, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100));
1658 }
1659
1660 TEST_F(MediaSourcePlayerTest, SimultaneousAudioVideoConfigChange) {
1661   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1662
1663   // Test that the player allows simultaneous audio and video config change,
1664   // such as might occur during OnPrefetchDone() if next access unit for both
1665   // audio and video jobs is |kConfigChanged|.
1666   CreateNextTextureAndSetVideoSurface();
1667   Start(CreateAudioVideoDemuxerConfigs());
1668   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1669   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1670   EXPECT_TRUE(GetMediaCodecBridge(true));
1671   EXPECT_TRUE(GetMediaCodecBridge(false));
1672   EnableAdaptiveVideoPlayback(false);
1673   WaitForAudioVideoDecodeDone();
1674
1675   // Simulate audio |kConfigChanged| prefetched as standalone access unit.
1676   DemuxerConfigs audio_configs = CreateAudioDemuxerConfigs(kCodecVorbis, true);
1677   player_.OnDemuxerDataAvailable(
1678       CreateReadFromDemuxerAckWithConfigChanged(true, 0, audio_configs));
1679
1680   // Simulate video |kConfigChanged| prefetched as standalone access unit.
1681   player_.OnDemuxerDataAvailable(
1682       CreateReadFromDemuxerAckWithConfigChanged(
1683           false, 0, CreateVideoDemuxerConfigs(true)));
1684   EXPECT_EQ(6, demuxer_->num_data_requests());
1685   EXPECT_TRUE(IsDrainingDecoder(true));
1686   EXPECT_TRUE(IsDrainingDecoder(false));
1687
1688   // Waiting for decoder to finish draining.
1689   while (IsDrainingDecoder(true) || IsDrainingDecoder(false))
1690     message_loop_.RunUntilIdle();
1691 }
1692
1693 TEST_F(MediaSourcePlayerTest,
1694        SimultaneousAudioVideoConfigChangeWithAdaptivePlayback) {
1695   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1696
1697   // Test that the player allows simultaneous audio and video config change with
1698   // adaptive video playback enabled.
1699   CreateNextTextureAndSetVideoSurface();
1700   Start(CreateAudioVideoDemuxerConfigs());
1701   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1702   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
1703   EXPECT_TRUE(GetMediaCodecBridge(true));
1704   EXPECT_TRUE(GetMediaCodecBridge(false));
1705   EnableAdaptiveVideoPlayback(true);
1706   WaitForAudioVideoDecodeDone();
1707
1708   // Simulate audio |kConfigChanged| prefetched as standalone access unit.
1709   DemuxerConfigs audio_configs = CreateAudioDemuxerConfigs(kCodecVorbis, true);
1710   player_.OnDemuxerDataAvailable(
1711       CreateReadFromDemuxerAckWithConfigChanged(true, 0, audio_configs));
1712
1713   // Simulate video |kConfigChanged| prefetched as standalone access unit.
1714   player_.OnDemuxerDataAvailable(
1715       CreateReadFromDemuxerAckWithConfigChanged(
1716           false, 0, CreateVideoDemuxerConfigs(true)));
1717   EXPECT_EQ(6, demuxer_->num_data_requests());
1718   EXPECT_TRUE(IsDrainingDecoder(true));
1719   EXPECT_FALSE(IsDrainingDecoder(false));
1720
1721   // Waiting for audio decoder to finish draining.
1722   while (IsDrainingDecoder(true))
1723     message_loop_.RunUntilIdle();
1724 }
1725
1726 TEST_F(MediaSourcePlayerTest, DemuxerConfigRequestedIfInPrefetchUnit0) {
1727   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1728
1729   // Test that the player detects need for and requests demuxer configs if
1730   // the |kConfigChanged| unit is the very first unit in the set of units
1731   // received in OnDemuxerDataAvailable() ostensibly while
1732   // |PREFETCH_DONE_EVENT_PENDING|.
1733   StartConfigChange(true, true, 0, false);
1734 }
1735
1736 TEST_F(MediaSourcePlayerTest, DemuxerConfigRequestedIfInPrefetchUnit1) {
1737   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1738
1739   // Test that the player detects need for and requests demuxer configs if
1740   // the |kConfigChanged| unit is not the first unit in the set of units
1741   // received in OnDemuxerDataAvailable() ostensibly while
1742   // |PREFETCH_DONE_EVENT_PENDING|.
1743   StartConfigChange(true, true, 1, false);
1744 }
1745
1746 TEST_F(MediaSourcePlayerTest, DemuxerConfigRequestedIfInUnit0AfterPrefetch) {
1747   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1748
1749   // Test that the player detects need for and requests demuxer configs if
1750   // the |kConfigChanged| unit is the very first unit in the set of units
1751   // received in OnDemuxerDataAvailable() from data requested ostensibly while
1752   // not prefetching.
1753   StartConfigChange(true, false, 0, false);
1754 }
1755
1756 TEST_F(MediaSourcePlayerTest, DemuxerConfigRequestedIfInUnit1AfterPrefetch) {
1757   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1758
1759   // Test that the player detects need for and requests demuxer configs if
1760   // the |kConfigChanged| unit is not the first unit in the set of units
1761   // received in OnDemuxerDataAvailable() from data requested ostensibly while
1762   // not prefetching.
1763   StartConfigChange(true, false, 1, false);
1764 }
1765
1766 TEST_F(MediaSourcePlayerTest, BrowserSeek_PrerollAfterBrowserSeek) {
1767   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1768
1769   // Test decoder job will preroll the media to the actual seek position
1770   // resulting from a browser seek.
1771   BrowserSeekPlayer(false);
1772
1773   // Simulate browser seek is done, but to a later time than was requested.
1774   EXPECT_LT(player_.GetCurrentTime().InMillisecondsF(), 100);
1775   player_.OnDemuxerSeekDone(base::TimeDelta::FromMilliseconds(100));
1776   // Because next AU is not I-frame, MediaCodecBridge will not be recreated.
1777   EXPECT_FALSE(GetMediaCodecBridge(false));
1778   EXPECT_EQ(100.0, player_.GetCurrentTime().InMillisecondsF());
1779   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
1780   EXPECT_EQ(3, demuxer_->num_data_requests());
1781
1782   PrerollDecoderToTime(
1783       false, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100));
1784 }
1785
1786 TEST_F(MediaSourcePlayerTest, VideoDemuxerConfigChange) {
1787   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1788
1789   // Test that video config change notification results in creating a new
1790   // video codec without any browser seek.
1791   StartConfigChange(false, true, 1, false);
1792
1793   // New video codec should have been created and configured, without any
1794   // browser seek.
1795   EXPECT_TRUE(GetMediaCodecBridge(false));
1796   EXPECT_EQ(3, demuxer_->num_data_requests());
1797   EXPECT_EQ(0, demuxer_->num_seek_requests());
1798
1799   // 2 codecs should have been created, one before the config change, and one
1800   // after it.
1801   EXPECT_EQ(2, manager_.num_resources_requested());
1802   EXPECT_EQ(1, manager_.num_resources_released());
1803 }
1804
1805 TEST_F(MediaSourcePlayerTest, VideoDemuxerConfigChangeWithAdaptivePlayback) {
1806   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1807
1808   // Test that if codec supports adaptive playback, no new codec should be
1809   // created beyond the one used to decode the prefetch media data prior to
1810   // the kConfigChanged.
1811   StartConfigChange(false, true, 1, true);
1812
1813   // No browser seek should be needed.
1814   EXPECT_TRUE(GetMediaCodecBridge(false));
1815   EXPECT_EQ(3, demuxer_->num_data_requests());
1816   EXPECT_EQ(0, demuxer_->num_seek_requests());
1817
1818   // Only 1 codec should have been created so far.
1819   EXPECT_EQ(1, manager_.num_resources_requested());
1820 }
1821
1822 TEST_F(MediaSourcePlayerTest, DecoderDrainInterruptedBySeek) {
1823   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1824
1825   // Test if a decoder is being drained while receiving a seek request, draining
1826   // is canceled.
1827   SendConfigChangeToDecoder(true, false, 0, false);
1828   EXPECT_TRUE(IsDrainingDecoder(true));
1829
1830   player_.SeekTo(base::TimeDelta::FromMilliseconds(100));
1831   WaitForAudioDecodeDone();
1832   EXPECT_FALSE(IsDrainingDecoder(true));
1833   player_.OnDemuxerSeekDone(kNoTimestamp());
1834
1835   EXPECT_EQ(1, demuxer_->num_seek_requests());
1836   EXPECT_EQ(4, demuxer_->num_data_requests());
1837 }
1838
1839 TEST_F(MediaSourcePlayerTest, DecoderDrainInterruptedByRelease) {
1840   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1841
1842   // Test if a decoder is being drained while receiving a release request,
1843   // draining is canceled.
1844   SendConfigChangeToDecoder(true, false, 0, false);
1845   EXPECT_TRUE(IsDrainingDecoder(true));
1846
1847   ReleasePlayer();
1848   WaitForAudioDecodeDone();
1849   EXPECT_EQ(3, demuxer_->num_data_requests());
1850   EXPECT_FALSE(IsDrainingDecoder(true));
1851
1852   EXPECT_FALSE(GetMediaCodecBridge(true));
1853   EXPECT_FALSE(player_.IsPlaying());
1854
1855   player_.Start();
1856   EXPECT_TRUE(player_.IsPlaying());
1857   EXPECT_EQ(3, demuxer_->num_data_requests());
1858 }
1859
1860 TEST_F(MediaSourcePlayerTest, DecoderDrainInterruptedBySurfaceChange) {
1861   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1862
1863   // Test if a video decoder is being drained while surface changes, draining
1864   // is canceled.
1865   SendConfigChangeToDecoder(false, false, 0, false);
1866   EXPECT_TRUE(IsDrainingDecoder(false));
1867
1868   CreateNextTextureAndSetVideoSurface();
1869   WaitForVideoDecodeDone();
1870
1871   EXPECT_FALSE(IsDrainingDecoder(false));
1872   EXPECT_FALSE(GetMediaCodecBridge(false));
1873   EXPECT_TRUE(player_.IsPlaying());
1874   EXPECT_EQ(3, demuxer_->num_data_requests());
1875
1876   // Finish the browser seek introduced by surface change.
1877   player_.OnDemuxerSeekDone(base::TimeDelta());
1878   EXPECT_EQ(4, demuxer_->num_data_requests());
1879 }
1880
1881 TEST_F(MediaSourcePlayerTest,
1882        BrowserSeek_DecoderStarvationWhilePendingSurfaceChange) {
1883   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1884
1885   // Test video decoder starvation while handling a pending surface change
1886   // should not cause any crashes.
1887   CreateNextTextureAndSetVideoSurface();
1888   StartVideoDecoderJob();
1889   DemuxerData data = CreateReadFromDemuxerAckForVideo();
1890   player_.OnDemuxerDataAvailable(data);
1891
1892   // Trigger a surface change and decoder starvation.
1893   CreateNextTextureAndSetVideoSurface();
1894   TriggerPlayerStarvation();
1895   WaitForVideoDecodeDone();
1896   EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
1897
1898   // Surface change should trigger a seek.
1899   player_.OnDemuxerDataAvailable(data);
1900   EXPECT_EQ(1, demuxer_->num_browser_seek_requests());
1901   player_.OnDemuxerSeekDone(base::TimeDelta());
1902   // After seek is done, prefetch is handled first. MediaCodecBridge is not
1903   // created at this moment.
1904   EXPECT_FALSE(GetMediaCodecBridge(false));
1905
1906   // A new data request should be sent.
1907   EXPECT_EQ(3, demuxer_->num_data_requests());
1908 }
1909
1910 TEST_F(MediaSourcePlayerTest, ReleaseWithOnPrefetchDoneAlreadyPosted) {
1911   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1912
1913   // Test if OnPrefetchDone() had already been posted before and is executed
1914   // after Release(), then player does not DCHECK. This test is fragile to
1915   // change to MediaDecoderJob::Prefetch() implementation; it assumes task
1916   // is posted to run |prefetch_cb| if the job already HasData().
1917   // TODO(wolenetz): Remove MSP::set_decode_callback_for_testing() if this test
1918   // becomes obsolete. See http://crbug.com/304234.
1919   StartAudioDecoderJob();
1920
1921   // Escape the original prefetch by decoding a single access unit.
1922   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
1923   WaitForAudioDecodeDone();
1924
1925   // Prime the job with a few more access units, so that a later prefetch,
1926   // triggered by starvation to simulate decoder underrun, can trivially
1927   // post task to run OnPrefetchDone().
1928   player_.OnDemuxerDataAvailable(
1929       CreateReadFromDemuxerAckWithConfigChanged(
1930           true, 4, CreateAudioDemuxerConfigs(kCodecVorbis, false)));
1931   EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
1932
1933   // Simulate decoder underrun, so trivial prefetch starts while still decoding.
1934   // The prefetch and posting of OnPrefetchDone() will not occur until next
1935   // MediaDecoderCallBack() occurs.
1936   TriggerPlayerStarvation();
1937
1938   // Upon the next successful decode callback, post a task to call Release() on
1939   // the |player_|, such that the trivial OnPrefetchDone() task posting also
1940   // occurs and should execute after the Release().
1941   OnNextTestDecodeCallbackPostTaskToReleasePlayer();
1942
1943   WaitForAudioDecodeDone();
1944   EXPECT_TRUE(decoder_callback_hook_executed_);
1945
1946   EXPECT_EQ(3, demuxer_->num_data_requests());
1947
1948   // Player should not request any new data since the access units haven't
1949   // been fully decoded yet.
1950   Resume(false, false);
1951 }
1952
1953 TEST_F(MediaSourcePlayerTest, SeekToThenReleaseThenDemuxerSeekAndDone) {
1954   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1955
1956   // Test if Release() occurs after SeekTo(), but the DemuxerSeek IPC request
1957   // has not yet been sent, then the seek request is sent after Release(). Also,
1958   // test if OnDemuxerSeekDone() occurs prior to next Start(), then the player
1959   // will resume correct post-seek preroll upon Start().
1960   StartAudioDecoderJobAndSeekToWhileDecoding(
1961       base::TimeDelta::FromMilliseconds(100));
1962   ReleasePlayer();
1963   EXPECT_EQ(0, demuxer_->num_seek_requests());
1964   WaitForAudioDecodeDone();
1965   EXPECT_EQ(1, demuxer_->num_seek_requests());
1966
1967   player_.OnDemuxerSeekDone(kNoTimestamp());
1968   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
1969   EXPECT_FALSE(GetMediaCodecBridge(true));
1970   EXPECT_FALSE(player_.IsPlaying());
1971
1972   // Player should begin prefetch and resume preroll upon Start().
1973   EXPECT_EQ(2, demuxer_->num_data_requests());
1974   Resume(true, false);
1975   EXPECT_TRUE(IsPrerolling(true));
1976   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
1977
1978   // No further seek should have been requested since Release(), above.
1979   EXPECT_EQ(1, demuxer_->num_seek_requests());
1980 }
1981
1982 TEST_F(MediaSourcePlayerTest, SeekToThenReleaseThenDemuxerSeekThenStart) {
1983   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
1984
1985   // Test if Release() occurs after SeekTo(), but the DemuxerSeek IPC request
1986   // has not yet been sent, then the seek request is sent after Release(). Also,
1987   // test if OnDemuxerSeekDone() does not occur until after the next Start(),
1988   // then the player remains pending seek done until (and resumes correct
1989   // post-seek preroll after) OnDemuxerSeekDone().
1990   StartAudioDecoderJobAndSeekToWhileDecoding(
1991       base::TimeDelta::FromMilliseconds(100));
1992   ReleasePlayer();
1993   EXPECT_EQ(0, demuxer_->num_seek_requests());
1994
1995   // Player should not prefetch upon Start() nor create the media codec bridge,
1996   // due to awaiting DemuxerSeekDone.
1997   EXPECT_EQ(2, demuxer_->num_data_requests());
1998   Resume(false, false);
1999
2000   WaitForAudioDecodeDone();
2001   EXPECT_EQ(1, demuxer_->num_seek_requests());
2002   player_.OnDemuxerSeekDone(kNoTimestamp());
2003   EXPECT_TRUE(GetMediaDecoderJob(true));
2004   EXPECT_TRUE(IsPrerolling(true));
2005   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
2006   EXPECT_EQ(3, demuxer_->num_data_requests());
2007
2008   // No further seek should have been requested since Release(), above.
2009   EXPECT_EQ(1, demuxer_->num_seek_requests());
2010 }
2011
2012 TEST_F(MediaSourcePlayerTest, SeekToThenDemuxerSeekThenReleaseThenSeekDone) {
2013   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
2014
2015   // Test if Release() occurs after a SeekTo()'s subsequent DemuxerSeek IPC
2016   // request and OnDemuxerSeekDone() arrives prior to the next Start(), then the
2017   // player will resume correct post-seek preroll upon Start().
2018   StartAudioDecoderJobAndSeekToWhileDecoding(
2019       base::TimeDelta::FromMilliseconds(100));
2020   WaitForAudioDecodeDone();
2021   EXPECT_EQ(1, demuxer_->num_seek_requests());
2022
2023   ReleasePlayer();
2024   player_.OnDemuxerSeekDone(kNoTimestamp());
2025   EXPECT_FALSE(player_.IsPlaying());
2026   EXPECT_FALSE(GetMediaCodecBridge(true));
2027   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
2028
2029   // Player should begin prefetch and resume preroll upon Start().
2030   EXPECT_EQ(2, demuxer_->num_data_requests());
2031   Resume(true, false);
2032   EXPECT_TRUE(IsPrerolling(true));
2033   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
2034
2035   // No further seek should have been requested since before Release(), above.
2036   EXPECT_EQ(1, demuxer_->num_seek_requests());
2037 }
2038
2039 TEST_F(MediaSourcePlayerTest, SeekToThenReleaseThenStart) {
2040   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
2041
2042   // Test if Release() occurs after a SeekTo()'s subsequent DemuxerSeeK IPC
2043   // request and OnDemuxerSeekDone() does not occur until after the next
2044   // Start(), then the player remains pending seek done until (and resumes
2045   // correct post-seek preroll after) OnDemuxerSeekDone().
2046   StartAudioDecoderJobAndSeekToWhileDecoding(
2047       base::TimeDelta::FromMilliseconds(100));
2048   WaitForAudioDecodeDone();
2049   EXPECT_EQ(1, demuxer_->num_seek_requests());
2050
2051   ReleasePlayer();
2052   EXPECT_EQ(2, demuxer_->num_data_requests());
2053   Resume(false, false);
2054
2055   player_.OnDemuxerSeekDone(kNoTimestamp());
2056   EXPECT_FALSE(GetMediaCodecBridge(true));
2057   EXPECT_TRUE(IsPrerolling(true));
2058   EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
2059   EXPECT_EQ(3, demuxer_->num_data_requests());
2060
2061   // No further seek should have been requested since before Release(), above.
2062   EXPECT_EQ(1, demuxer_->num_seek_requests());
2063 }
2064
2065 TEST_F(MediaSourcePlayerTest, ConfigChangedThenReleaseThenStart) {
2066   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
2067
2068   // Test if Release() occurs after |kConfigChanged| is processed, new data
2069   // requested of demuxer, and the requested data arrive before the next
2070   // Start(), then the player starts to decode the new data without any seek.
2071   StartConfigChange(true, true, 0, false);
2072   ReleasePlayer();
2073
2074   EXPECT_TRUE(GetMediaCodecBridge(true));
2075   EXPECT_FALSE(player_.IsPlaying());
2076   EXPECT_EQ(3, demuxer_->num_data_requests());
2077   player_.OnDemuxerDataAvailable(
2078         CreateReadFromDemuxerAckWithConfigChanged(
2079             true, 4, CreateAudioDemuxerConfigs(kCodecVorbis, false)));
2080   WaitForAudioDecodeDone();
2081   EXPECT_FALSE(GetMediaCodecBridge(true));
2082
2083   // Player should resume upon Start(), even without further configs supplied.
2084   player_.Start();
2085   EXPECT_TRUE(player_.IsPlaying());
2086   EXPECT_EQ(3, demuxer_->num_data_requests());
2087   EXPECT_EQ(0, demuxer_->num_seek_requests());
2088 }
2089
2090 TEST_F(MediaSourcePlayerTest, BrowserSeek_ThenReleaseThenDemuxerSeekDone) {
2091   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
2092
2093   // Test that Release() after a browser seek's DemuxerSeek IPC request has been
2094   // sent behaves similar to a regular seek: if OnDemuxerSeekDone() occurs
2095   // before the next Start()+SetVideoSurface(), then the player will resume
2096   // correct post-seek preroll upon Start()+SetVideoSurface().
2097   BrowserSeekPlayer(false);
2098   base::TimeDelta expected_preroll_timestamp = player_.GetCurrentTime();
2099   ReleasePlayer();
2100
2101   player_.OnDemuxerSeekDone(expected_preroll_timestamp);
2102   EXPECT_FALSE(player_.IsPlaying());
2103   EXPECT_FALSE(GetMediaCodecBridge(false));
2104   EXPECT_EQ(expected_preroll_timestamp, GetPrerollTimestamp());
2105
2106   // Player should begin prefetch and resume preroll upon Start().
2107   EXPECT_EQ(2, demuxer_->num_data_requests());
2108   CreateNextTextureAndSetVideoSurface();
2109   Resume(false, true);
2110   EXPECT_TRUE(IsPrerolling(false));
2111   EXPECT_EQ(expected_preroll_timestamp, GetPrerollTimestamp());
2112   EXPECT_EQ(expected_preroll_timestamp, player_.GetCurrentTime());
2113
2114   // No further seek should have been requested since BrowserSeekPlayer().
2115   EXPECT_EQ(1, demuxer_->num_seek_requests());
2116 }
2117
2118 TEST_F(MediaSourcePlayerTest, BrowserSeek_ThenReleaseThenStart) {
2119   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
2120
2121   // Test that Release() after a browser seek's DemuxerSeek IPC request has been
2122   // sent behaves similar to a regular seek: if OnDemuxerSeekDone() does not
2123   // occur until after the next Start()+SetVideoSurface(), then the player
2124   // remains pending seek done until (and resumes correct post-seek preroll
2125   // after) OnDemuxerSeekDone().
2126   BrowserSeekPlayer(false);
2127   base::TimeDelta expected_preroll_timestamp = player_.GetCurrentTime();
2128   ReleasePlayer();
2129
2130   EXPECT_EQ(2, demuxer_->num_data_requests());
2131   CreateNextTextureAndSetVideoSurface();
2132   Resume(false, false);
2133
2134   player_.OnDemuxerSeekDone(expected_preroll_timestamp);
2135   // Prefetch takes place first, and the decoder is not created yet.
2136   EXPECT_FALSE(GetMediaCodecBridge(false));
2137   EXPECT_TRUE(IsPrerolling(false));
2138   EXPECT_EQ(expected_preroll_timestamp, GetPrerollTimestamp());
2139   EXPECT_EQ(expected_preroll_timestamp, player_.GetCurrentTime());
2140   EXPECT_EQ(3, demuxer_->num_data_requests());
2141
2142   // No further seek should have been requested since BrowserSeekPlayer().
2143   EXPECT_EQ(1, demuxer_->num_seek_requests());
2144
2145   // Decoder will be created once data is received.
2146   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo());
2147   while (!GetMediaCodecBridge(false))
2148     message_loop_.RunUntilIdle();
2149 }
2150
2151 // TODO(xhwang): Once we add tests to cover DrmBridge, update this test to
2152 // also verify that the job is successfully created if SetDrmBridge(), Start()
2153 // and eventually OnMediaCrypto() occur. This would increase test coverage of
2154 // http://crbug.com/313470 and allow us to remove inspection of internal player
2155 // pending event state. See http://crbug.com/313860.
2156 TEST_F(MediaSourcePlayerTest, SurfaceChangeClearedEvenIfMediaCryptoAbsent) {
2157   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
2158
2159   // Test that |SURFACE_CHANGE_EVENT_PENDING| is not pending after
2160   // SetVideoSurface() for a player configured for encrypted video, when the
2161   // player has not yet received media crypto.
2162   DemuxerConfigs configs = CreateVideoDemuxerConfigs(false);
2163   configs.is_video_encrypted = true;
2164
2165   player_.OnDemuxerConfigsAvailable(configs);
2166   CreateNextTextureAndSetVideoSurface();
2167   EXPECT_FALSE(GetMediaCodecBridge(false));
2168 }
2169
2170 TEST_F(MediaSourcePlayerTest, CurrentTimeUpdatedWhileDecoderStarved) {
2171   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
2172
2173   // Test that current time is updated while decoder is starved.
2174   StartAudioDecoderJob();
2175   DecodeAudioDataUntilOutputBecomesAvailable();
2176
2177   // Trigger starvation while the decoder is decoding.
2178   player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(3));
2179   manager_.ResetTimestampUpdated();
2180   TriggerPlayerStarvation();
2181   WaitForAudioDecodeDone();
2182
2183   // Current time should be updated.
2184   EXPECT_TRUE(manager_.timestamp_updated());
2185 }
2186
2187 TEST_F(MediaSourcePlayerTest, CurrentTimeKeepsIncreasingAfterConfigChange) {
2188   SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();
2189
2190   // Test current time keep on increasing after audio config change.
2191   // Test that current time is updated while decoder is starved.
2192   StartAudioDecoderJob();
2193
2194   DecodeAudioDataUntilOutputBecomesAvailable();
2195
2196   DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, true);
2197   DemuxerData data = CreateReadFromDemuxerAckWithConfigChanged(
2198       true, 0, configs);
2199   player_.OnDemuxerDataAvailable(data);
2200   WaitForAudioDecodeDone();
2201   DecodeAudioDataUntilOutputBecomesAvailable();
2202 }
2203
2204 }  // namespace media