1 // Copyright (c) 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.
5 #ifndef MEDIA_BASE_ANDROID_MEDIA_SOURCE_PLAYER_H_
6 #define MEDIA_BASE_ANDROID_MEDIA_SOURCE_PLAYER_H_
13 #include "base/android/scoped_java_ref.h"
14 #include "base/callback.h"
15 #include "base/cancelable_callback.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/memory/weak_ptr.h"
18 #include "base/threading/thread.h"
19 #include "base/time/default_tick_clock.h"
20 #include "base/time/time.h"
21 #include "media/base/android/demuxer_android.h"
22 #include "media/base/android/media_codec_bridge.h"
23 #include "media/base/android/media_decoder_job.h"
24 #include "media/base/android/media_drm_bridge.h"
25 #include "media/base/android/media_player_android.h"
26 #include "media/base/media_export.h"
27 #include "media/base/time_delta_interpolator.h"
31 class AudioDecoderJob
;
32 class VideoDecoderJob
;
34 // This class handles media source extensions on Android. It uses Android
35 // MediaCodec to decode audio and video streams in two separate threads.
36 class MEDIA_EXPORT MediaSourcePlayer
: public MediaPlayerAndroid
,
37 public DemuxerAndroidClient
{
39 // Constructs a player with the given ID and demuxer. |manager| must outlive
40 // the lifetime of this object.
41 MediaSourcePlayer(int player_id
,
42 MediaPlayerManager
* manager
,
43 const RequestMediaResourcesCB
& request_media_resources_cb
,
44 scoped_ptr
<DemuxerAndroid
> demuxer
,
45 const GURL
& frame_url
);
46 virtual ~MediaSourcePlayer();
48 // MediaPlayerAndroid implementation.
49 virtual void SetVideoSurface(gfx::ScopedJavaSurface surface
) override
;
50 virtual void Start() override
;
51 virtual void Pause(bool is_media_related_action
) override
;
52 virtual void SeekTo(base::TimeDelta timestamp
) override
;
53 virtual void Release() override
;
54 virtual void SetVolume(double volume
) override
;
55 virtual int GetVideoWidth() override
;
56 virtual int GetVideoHeight() override
;
57 virtual base::TimeDelta
GetCurrentTime() override
;
58 virtual base::TimeDelta
GetDuration() override
;
59 virtual bool IsPlaying() override
;
60 virtual bool CanPause() override
;
61 virtual bool CanSeekForward() override
;
62 virtual bool CanSeekBackward() override
;
63 virtual bool IsPlayerReady() override
;
64 virtual void SetCdm(BrowserCdm
* cdm
) override
;
66 // DemuxerAndroidClient implementation.
67 virtual void OnDemuxerConfigsAvailable(const DemuxerConfigs
& params
) override
;
68 virtual void OnDemuxerDataAvailable(const DemuxerData
& params
) override
;
69 virtual void OnDemuxerSeekDone(
70 base::TimeDelta actual_browser_seek_time
) override
;
71 virtual void OnDemuxerDurationChanged(base::TimeDelta duration
) override
;
74 friend class MediaSourcePlayerTest
;
76 // Update the current timestamp.
77 void UpdateTimestamps(base::TimeDelta current_presentation_timestamp
,
78 base::TimeDelta max_presentation_timestamp
);
80 // Helper function for starting media playback.
83 // Playback is completed for one channel.
84 void PlaybackCompleted(bool is_audio
);
86 // Called when the decoder finishes its task.
87 void MediaDecoderCallback(
88 bool is_audio
, MediaCodecStatus status
,
89 base::TimeDelta current_presentation_timestamp
,
90 base::TimeDelta max_presentation_timestamp
);
92 bool IsPrerollFinished(bool is_audio
) const;
94 // Gets MediaCrypto object from |drm_bridge_|.
95 base::android::ScopedJavaLocalRef
<jobject
> GetMediaCrypto();
97 // Callback to notify that MediaCrypto is ready in |drm_bridge_|.
98 void OnMediaCryptoReady();
100 // Handle pending events if all the decoder jobs are not currently decoding.
101 void ProcessPendingEvents();
103 // Flush the decoders and clean up all the data needs to be decoded.
104 void ClearDecodingData();
106 // Called to decode more data.
107 void DecodeMoreAudio();
108 void DecodeMoreVideo();
110 // Functions check whether audio/video is present.
111 bool HasVideo() const;
112 bool HasAudio() const;
114 // Functions that check whether audio/video stream has reached end of output
115 // or are not present in player configuration.
116 bool AudioFinished();
117 bool VideoFinished();
119 // Determine seekability based on duration.
122 // Called when the |decoder_starvation_callback_| times out.
123 void OnDecoderStarved();
125 // Starts the |decoder_starvation_callback_| task with the timeout value.
126 // |current_presentation_timestamp| - The presentation timestamp used for
127 // starvation timeout computations. It represents the current timestamp of
129 // |max_presentation_timestamp| - The presentation timestamp if all the
130 // decoded data are rendered.
131 void StartStarvationCallback(
132 base::TimeDelta current_presentation_timestamp
,
133 base::TimeDelta max_presentation_timestamp
);
135 // Schedules a seek event in |pending_events_| and calls StopDecode() on all
136 // the MediaDecoderJobs. Sets clock to |seek_time|, and resets
137 // |pending_seek_|. There must not already be a seek event in
138 // |pending_events_|.
139 void ScheduleSeekEventAndStopDecoding(base::TimeDelta seek_time
);
141 // Schedules a browser seek event. We must not currently be processing any
142 // seek. Note that there is possibility that browser seek of renderer demuxer
143 // may unexpectedly stall due to lack of buffered data at or after the browser
145 // TODO(wolenetz): Instead of doing hack browser seek, replay cached data
146 // since last keyframe. See http://crbug.com/304234.
147 void BrowserSeekToCurrentTime();
149 // Helper function to determine whether a protected surface is needed for
151 bool IsProtectedSurfaceRequired();
153 // Called when a MediaDecoderJob finishes prefetching data. Once all
154 // MediaDecoderJobs have prefetched data, then this method updates
155 // |start_time_ticks_| and |start_presentation_timestamp_| so that video can
156 // resync with audio and starts decoding.
157 void OnPrefetchDone();
159 // Called when the demuxer config changes.
160 void OnDemuxerConfigsChanged();
162 // Called when new decryption key becomes available.
165 // Called to resume playback after NO_KEY is received, but a new key is
167 void ResumePlaybackAfterKeyAdded();
169 // Called when the CDM is detached.
172 // Test-only method to setup hook for the completion of the next decode cycle.
173 // This callback state is cleared when it is next run.
174 // Prevent usage creep by only calling this from the
175 // ReleaseWithOnPrefetchDoneAlreadyPosted MediaSourcePlayerTest.
176 void set_decode_callback_for_testing(const base::Closure
& test_decode_cb
) {
177 decode_callback_for_testing_
= test_decode_cb
;
180 // Please keep this in sync with |kPendingEventNames| in GetEventName().
181 enum PendingEventFlags
{
182 NO_EVENT_PENDING
= 0,
183 PREFETCH_DONE_EVENT_PENDING
= 1 << 0,
184 SEEK_EVENT_PENDING
= 1 << 1,
185 DECODER_CREATION_EVENT_PENDING
= 1 << 2,
186 PREFETCH_REQUEST_EVENT_PENDING
= 1 << 3,
189 static const char* GetEventName(PendingEventFlags event
);
190 bool IsEventPending(PendingEventFlags event
) const;
191 void SetPendingEvent(PendingEventFlags event
);
192 void ClearPendingEvent(PendingEventFlags event
);
194 // If the player is previously waiting for audio or video decoder job, retry
195 // creating the decoders identified by |audio| and |video|.
196 void RetryDecoderCreation(bool audio
, bool video
);
198 scoped_ptr
<DemuxerAndroid
> demuxer_
;
200 // Pending event that the player needs to do.
201 unsigned pending_event_
;
203 // Stats about the media.
204 base::TimeDelta duration_
;
207 // base::TickClock used by |interpolator_|.
208 base::DefaultTickClock default_tick_clock_
;
210 // Tracks the most recent media time update and provides interpolated values
211 // as playback progresses.
212 TimeDeltaInterpolator interpolator_
;
214 // Timestamps for providing simple A/V sync. When start decoding an audio
215 // chunk, we record its presentation timestamp and the current system time.
216 // Then we use this information to estimate when the next audio/video frame
217 // should be rendered.
218 // TODO(qinmin): Need to fix the problem if audio/video lagged too far behind
219 // due to network or decoding problem.
220 base::TimeTicks start_time_ticks_
;
221 base::TimeDelta start_presentation_timestamp_
;
223 // Flag that is true if doing a hack browser seek or false if doing a
224 // regular seek. Only valid when |SEEK_EVENT_PENDING| is pending.
225 // TODO(wolenetz): Instead of doing hack browser seek, replay cached data
226 // since last keyframe. See http://crbug.com/304234.
227 bool doing_browser_seek_
;
229 // If already doing a browser seek when a regular seek request arrives,
230 // these fields remember the regular seek so OnDemuxerSeekDone() can trigger
231 // it when the browser seek is done. These are only valid when
232 // |SEEK_EVENT_PENDING| is pending.
234 base::TimeDelta pending_seek_time_
;
237 scoped_ptr
<AudioDecoderJob
, MediaDecoderJob::Deleter
> audio_decoder_job_
;
238 scoped_ptr
<VideoDecoderJob
, MediaDecoderJob::Deleter
> video_decoder_job_
;
240 // Track the most recent preroll target. Decoder re-creation needs this to
241 // resume any in-progress preroll.
242 base::TimeDelta preroll_timestamp_
;
244 // A cancelable task that is posted when the audio decoder starts requesting
245 // new data. This callback runs if no data arrives before the timeout period
247 base::CancelableClosure decoder_starvation_callback_
;
249 MediaDrmBridge
* drm_bridge_
;
250 int cdm_registration_id_
;
252 // No decryption key available to decrypt the encrypted buffer. In this case,
253 // the player should pause. When a new key is added (OnKeyAdded()), we should
254 // try to start playback again.
255 bool is_waiting_for_key_
;
257 // Indicates the situation where new key is added during pending decode
258 // (this variable can only be set when *_decoder_job_->is_decoding()). If this
259 // variable is true and MEDIA_CODEC_NO_KEY is returned then we need to try
260 // decoding again in case the newly added key is the correct decryption key.
261 bool key_added_while_decode_pending_
;
263 // Indicates whether the player is waiting for audio or video decoder to be
264 // created. This could happen if video surface is not available or key is
266 bool is_waiting_for_audio_decoder_
;
267 bool is_waiting_for_video_decoder_
;
269 // Test-only callback for hooking the completion of the next decode cycle.
270 base::Closure decode_callback_for_testing_
;
272 // Whether audio or video decoder is in the process of prerolling.
275 // Weak pointer passed to media decoder jobs for callbacks.
276 // NOTE: Weak pointers must be invalidated before all other member variables.
277 base::WeakPtrFactory
<MediaSourcePlayer
> weak_factory_
;
278 base::WeakPtr
<MediaSourcePlayer
> weak_this_
;
280 DISALLOW_COPY_AND_ASSIGN(MediaSourcePlayer
);
285 #endif // MEDIA_BASE_ANDROID_MEDIA_SOURCE_PLAYER_H_