Abort MSP::OnPrefetchDone() if just after MSP::Release(). Let seek and config change...
[chromium-blink-merge.git] / media / base / android / media_source_player.h
blobc718464408fd749e81e45752a30fdd044e496849
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_
8 #include <jni.h>
9 #include <map>
10 #include <string>
11 #include <vector>
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_player_android.h"
25 #include "media/base/clock.h"
26 #include "media/base/media_export.h"
28 namespace media {
30 class AudioDecoderJob;
31 class AudioTimestampHelper;
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 {
38 public:
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 scoped_ptr<DemuxerAndroid> demuxer);
44 virtual ~MediaSourcePlayer();
46 static bool IsTypeSupported(const std::vector<uint8>& scheme_uuid,
47 const std::string& security_level,
48 const std::string& container,
49 const std::vector<std::string>& codecs);
51 // MediaPlayerAndroid implementation.
52 virtual void SetVideoSurface(gfx::ScopedJavaSurface surface) OVERRIDE;
53 virtual void Start() OVERRIDE;
54 virtual void Pause(bool is_media_related_action ALLOW_UNUSED) OVERRIDE;
55 virtual void SeekTo(const base::TimeDelta& timestamp) OVERRIDE;
56 virtual void Release() OVERRIDE;
57 virtual void SetVolume(double volume) OVERRIDE;
58 virtual int GetVideoWidth() OVERRIDE;
59 virtual int GetVideoHeight() OVERRIDE;
60 virtual base::TimeDelta GetCurrentTime() OVERRIDE;
61 virtual base::TimeDelta GetDuration() OVERRIDE;
62 virtual bool IsPlaying() OVERRIDE;
63 virtual bool CanPause() OVERRIDE;
64 virtual bool CanSeekForward() OVERRIDE;
65 virtual bool CanSeekBackward() OVERRIDE;
66 virtual bool IsPlayerReady() OVERRIDE;
67 virtual void SetDrmBridge(MediaDrmBridge* drm_bridge) OVERRIDE;
68 virtual void OnKeyAdded() OVERRIDE;
70 // DemuxerAndroidClient implementation.
71 virtual void OnDemuxerConfigsAvailable(const DemuxerConfigs& params) OVERRIDE;
72 virtual void OnDemuxerDataAvailable(const DemuxerData& params) OVERRIDE;
73 virtual void OnDemuxerSeekDone(
74 const base::TimeDelta& actual_browser_seek_time) OVERRIDE;
75 virtual void OnDemuxerDurationChanged(base::TimeDelta duration) OVERRIDE;
77 private:
78 // Update the current timestamp.
79 void UpdateTimestamps(const base::TimeDelta& presentation_timestamp,
80 size_t audio_output_bytes);
82 // Helper function for starting media playback.
83 void StartInternal();
85 // Playback is completed for one channel.
86 void PlaybackCompleted(bool is_audio);
88 // Called when the decoder finishes its task.
89 void MediaDecoderCallback(
90 bool is_audio, MediaCodecStatus status,
91 const base::TimeDelta& presentation_timestamp,
92 size_t audio_output_bytes);
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 when all the decoder jobs finished.
101 void ProcessPendingEvents();
103 // Helper method to configure the decoder jobs.
104 void ConfigureVideoDecoderJob();
105 void ConfigureAudioDecoderJob();
107 // Flush the decoders and clean up all the data needs to be decoded.
108 void ClearDecodingData();
110 // Called to decoder more data.
111 void DecodeMoreAudio();
112 void DecodeMoreVideo();
114 // Functions check whether audio/video is present.
115 bool HasVideo();
116 bool HasAudio();
118 // Determine seekability based on duration.
119 bool Seekable();
121 // Called when the |decoder_starvation_callback_| times out.
122 void OnDecoderStarved();
124 // Starts the |decoder_starvation_callback_| task with the timeout value.
125 // |presentation_timestamp| - The presentation timestamp used for starvation
126 // timeout computations. It represents the timestamp of the last piece of
127 // decoded data.
128 void StartStarvationCallback(const base::TimeDelta& presentation_timestamp);
130 // Schedules a seek event in |pending_events_| and calls StopDecode() on all
131 // the MediaDecoderJobs. Sets clock to |seek_time|, and resets
132 // |pending_seek_|. There must not already be a seek event in
133 // |pending_events_|.
134 void ScheduleSeekEventAndStopDecoding(const base::TimeDelta& seek_time);
136 // Schedules a browser seek event. We must not currently be processing any
137 // seek. Note that there is possibility that browser seek of renderer demuxer
138 // may unexpectedly stall due to lack of buffered data at or after the browser
139 // seek time.
140 // TODO(wolenetz): Instead of doing hack browser seek, replay cached data
141 // since last keyframe. See http://crbug.com/304234.
142 void BrowserSeekToCurrentTime();
144 // Helper function to set the volume.
145 void SetVolumeInternal();
147 // Helper function to determine whether a protected surface is needed for
148 // video playback.
149 bool IsProtectedSurfaceRequired();
151 // Called when a MediaDecoderJob finishes prefetching data. Once all
152 // MediaDecoderJobs have prefetched data, then this method updates
153 // |start_time_ticks_| and |start_presentation_timestamp_| so that video can
154 // resync with audio and starts decoding.
155 void OnPrefetchDone();
157 // Test-only method to setup hook for the completion of the next decode cycle.
158 // This callback state is cleared when it is next run.
159 // Prevent usage creep by only calling this from the
160 // ReleaseWithOnPrefetchDoneAlreadyPosted MediaSourcePlayerTest.
161 void set_decode_callback_for_testing(const base::Closure& test_decode_cb) {
162 decode_callback_for_testing_ = test_decode_cb;
165 // TODO(qinmin/wolenetz): Reorder these based on their priority from
166 // ProcessPendingEvents(). Release() and other routines are dependent upon
167 // priority consistency.
168 enum PendingEventFlags {
169 NO_EVENT_PENDING = 0,
170 SEEK_EVENT_PENDING = 1 << 0,
171 SURFACE_CHANGE_EVENT_PENDING = 1 << 1,
172 CONFIG_CHANGE_EVENT_PENDING = 1 << 2,
173 PREFETCH_REQUEST_EVENT_PENDING = 1 << 3,
174 PREFETCH_DONE_EVENT_PENDING = 1 << 4,
177 static const char* GetEventName(PendingEventFlags event);
178 bool IsEventPending(PendingEventFlags event) const;
179 void SetPendingEvent(PendingEventFlags event);
180 void ClearPendingEvent(PendingEventFlags event);
182 scoped_ptr<DemuxerAndroid> demuxer_;
184 // Pending event that the player needs to do.
185 unsigned pending_event_;
187 // Stats about the media.
188 base::TimeDelta duration_;
189 int width_;
190 int height_;
191 AudioCodec audio_codec_;
192 VideoCodec video_codec_;
193 int num_channels_;
194 int sampling_rate_;
195 // TODO(xhwang/qinmin): Add |video_extra_data_|.
196 std::vector<uint8> audio_extra_data_;
197 bool audio_finished_;
198 bool video_finished_;
199 bool playing_;
200 bool is_audio_encrypted_;
201 bool is_video_encrypted_;
202 double volume_;
204 // base::TickClock used by |clock_|.
205 base::DefaultTickClock default_tick_clock_;
207 // Reference clock. Keeps track of current playback time.
208 Clock clock_;
210 // Timestamps for providing simple A/V sync. When start decoding an audio
211 // chunk, we record its presentation timestamp and the current system time.
212 // Then we use this information to estimate when the next audio/video frame
213 // should be rendered.
214 // TODO(qinmin): Need to fix the problem if audio/video lagged too far behind
215 // due to network or decoding problem.
216 base::TimeTicks start_time_ticks_;
217 base::TimeDelta start_presentation_timestamp_;
219 // The surface object currently owned by the player.
220 gfx::ScopedJavaSurface surface_;
222 // Track whether or not the player has received any video data since the most
223 // recent of player construction, end of last seek, or receiving and
224 // detecting a |kConfigChanged| access unit from the demuxer.
225 // If no such video data has been received, the next video data begins with
226 // an I-frame. Otherwise, we have no such guarantee.
227 bool next_video_data_is_iframe_;
229 // Flag that is true if doing a hack browser seek or false if doing a
230 // regular seek. Only valid when |SEEK_EVENT_PENDING| is pending.
231 // TODO(wolenetz): Instead of doing hack browser seek, replay cached data
232 // since last keyframe. See http://crbug.com/304234.
233 bool doing_browser_seek_;
235 // If already doing a browser seek when a regular seek request arrives,
236 // these fields remember the regular seek so OnDemuxerSeekDone() can trigger
237 // it when the browser seek is done. These are only valid when
238 // |SEEK_EVENT_PENDING| is pending.
239 bool pending_seek_;
240 base::TimeDelta pending_seek_time_;
242 // Decoder jobs.
243 scoped_ptr<AudioDecoderJob, MediaDecoderJob::Deleter> audio_decoder_job_;
244 scoped_ptr<VideoDecoderJob, MediaDecoderJob::Deleter> video_decoder_job_;
246 bool reconfig_audio_decoder_;
247 bool reconfig_video_decoder_;
249 // Track the most recent preroll target. Decoder re-creation needs this to
250 // resume any in-progress preroll.
251 base::TimeDelta preroll_timestamp_;
253 // A cancelable task that is posted when the audio decoder starts requesting
254 // new data. This callback runs if no data arrives before the timeout period
255 // elapses.
256 base::CancelableClosure decoder_starvation_callback_;
258 // Object to calculate the current audio timestamp for A/V sync.
259 scoped_ptr<AudioTimestampHelper> audio_timestamp_helper_;
261 // Weak pointer passed to media decoder jobs for callbacks.
262 base::WeakPtrFactory<MediaSourcePlayer> weak_this_;
264 MediaDrmBridge* drm_bridge_;
266 // No decryption key available to decrypt the encrypted buffer. In this case,
267 // the player should pause. When a new key is added (OnKeyAdded()), we should
268 // try to start playback again.
269 bool is_waiting_for_key_;
271 // Test-only callback for hooking the completion of the next decode cycle.
272 base::Closure decode_callback_for_testing_;
274 friend class MediaSourcePlayerTest;
275 DISALLOW_COPY_AND_ASSIGN(MediaSourcePlayer);
278 } // namespace media
280 #endif // MEDIA_BASE_ANDROID_MEDIA_SOURCE_PLAYER_H_