1 // Copyright 2015 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_CODEC_DECODER_H_
6 #define MEDIA_BASE_ANDROID_MEDIA_CODEC_DECODER_H_
8 #include "base/android/scoped_java_ref.h"
9 #include "base/callback.h"
10 #include "base/macros.h"
11 #include "base/memory/ref_counted.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/single_thread_task_runner.h"
14 #include "base/synchronization/lock.h"
15 #include "base/threading/thread.h"
16 #include "base/time/time.h"
17 #include "media/base/android/access_unit_queue.h"
18 #include "media/base/android/demuxer_stream_player_params.h"
22 class MediaCodecBridge
;
24 // The decoder for MediaCodecPlayer.
25 // This class accepts the incoming data into AccessUnitQueue and works with
26 // MediaCodecBridge for decoding and rendering the frames. The MediaCodecPlayer
27 // has two decoder objects: audio and video.
29 // The decoder works on two threads. The data from demuxer comes on Media
30 // thread. The commands from MediaCodecPlayer, such as Prefetch, Start,
31 // RequestToStop also come on the Media thread. The operations with MediaCodec
32 // buffers and rendering happen on a separate thread called Decoder thread.
33 // This class creates, starts and stops it as necessary.
35 // Decoder's internal state machine goes through the following states:
37 // [ Stopped ] <------------------- (any state except Error)
39 // | Prefetch |--- internal ------|
41 // [ Prefetching ] | [ Error ]
43 // | internal transition |
44 // v | Error recovery:
46 // | | (any state including Error)
48 // v | | ReleaseDecoderResources
53 // [ Stopping ] -------------------
56 // [ Stopped ] --------------------
59 // ---------------------------
61 class MediaCodecDecoder
{
63 // The result of MediaCodec configuration, used by MediaCodecPlayer.
67 CONFIG_KEY_FRAME_REQUIRED
,
70 // The decoder reports current playback time to the MediaCodecPlayer.
71 // For audio, the parameters designate the beginning and end of a time
72 // interval. The beginning is the estimated time that is playing right now.
73 // The end is the playback time of the last buffered data. During normal
74 // playback the subsequent intervals overlap.
75 // For video both values are PTS of the corresponding frame, i.e. the interval
77 typedef base::Callback
<void(base::TimeDelta
, base::TimeDelta
)>
80 // MediaCodecDecoder constructor.
83 // A task runner for the controlling thread. All public methods should be
84 // called on this thread, and callbacks are delivered on this thread.
85 // The MediaCodecPlayer uses a dedicated (Media) thread for this.
86 // external_request_data_cb:
87 // Called periodically as the amount of internally stored data decreases.
88 // The receiver should call OnDemuxerDataAvailable() with more data.
90 // Called when starvation is detected. The decoder state does not change.
91 // The player is supposed to stop and then prefetch the decoder.
93 // Called when async stop request is completed.
95 // Called when a MediaCodec error occurred. If this happens, a player has
96 // to either call ReleaseDecoderResources() or destroy the decoder object.
97 // decoder_thread_name:
98 // The thread name to be passed to decoder thread constructor.
100 const scoped_refptr
<base::SingleThreadTaskRunner
>& media_task_runner
,
101 const base::Closure
& external_request_data_cb
,
102 const base::Closure
& starvation_cb
,
103 const base::Closure
& stop_done_cb
,
104 const base::Closure
& error_cb
,
105 const char* decoder_thread_name
);
106 virtual ~MediaCodecDecoder();
108 virtual const char* class_name() const;
110 // MediaCodecDecoder exists through the whole lifetime of the player
111 // to support dynamic addition and removal of the streams.
112 // This method returns true if the current stream (audio or video)
113 // is currently active.
114 virtual bool HasStream() const = 0;
116 // Stores configuration for the use of upcoming Configure()
117 virtual void SetDemuxerConfigs(const DemuxerConfigs
& configs
) = 0;
119 // Stops decoder thread, releases the MediaCodecBridge and other resources.
120 virtual void ReleaseDecoderResources();
122 // Flushes the MediaCodec and resets the AccessUnitQueue.
123 // Decoder thread should not be running.
124 virtual void Flush();
126 // Releases MediaCodecBridge.
127 void ReleaseMediaCodec();
129 // Returns corresponding conditions.
130 bool IsPrefetchingOrPlaying() const;
131 bool IsStopped() const;
132 bool IsCompleted() const;
134 base::android::ScopedJavaLocalRef
<jobject
> GetMediaCrypto();
136 // Starts prefetching: accumulates enough data in AccessUnitQueue.
137 // Decoder thread is not running.
138 void Prefetch(const base::Closure
& prefetch_done_cb
);
140 // Configures MediaCodec.
141 ConfigStatus
Configure();
143 // Starts the decoder thread and resumes the playback.
144 bool Start(base::TimeDelta current_time
);
146 // Stops the playback process synchronously. This method stops the decoder
147 // thread synchronously, and then releases all MediaCodec buffers.
150 // Requests to stop the playback and returns.
151 // Decoder will stop asynchronously after all the dequeued output buffers
153 void RequestToStop();
155 // Notification posted when asynchronous stop is done or playback completed.
156 void OnLastFrameRendered(bool completed
);
158 // Puts the incoming data into AccessUnitQueue.
159 void OnDemuxerDataAvailable(const DemuxerData
& data
);
162 // Returns true if the new DemuxerConfigs requires MediaCodec
164 virtual bool IsCodecReconfigureNeeded(const DemuxerConfigs
& curr
,
165 const DemuxerConfigs
& next
) const = 0;
167 // Does the part of MediaCodecBridge configuration that is specific
168 // to audio or video.
169 virtual ConfigStatus
ConfigureInternal() = 0;
171 // Associates PTS with device time so we can calculate delays.
172 // We use delays for video decoder only.
173 virtual void SynchronizePTSWithTime(base::TimeDelta current_time
) {}
175 // Processes the change of the output format, varies by stream.
176 virtual void OnOutputFormatChanged() = 0;
178 // Renders the decoded frame and releases output buffer, or posts
179 // a delayed task to do it at a later time,
180 virtual void Render(int buffer_index
,
184 bool eos_encountered
) = 0;
186 // Returns the number of delayed task (we might have them for video).
187 virtual int NumDelayedRenderTasks() const;
189 // Releases output buffers that are dequeued and not released yet
190 // because their rendering is delayed (video).
191 virtual void ReleaseDelayedBuffers() {}
195 // Notifies the decoder if the frame is the last one.
196 void CheckLastFrame(bool eos_encountered
, bool has_delayed_tasks
);
200 // Object for posting tasks on Media thread.
201 scoped_refptr
<base::SingleThreadTaskRunner
> media_task_runner_
;
203 // Controls Android MediaCodec
204 scoped_ptr
<MediaCodecBridge
> media_codec_bridge_
;
206 // We call MediaCodecBridge on this thread for both
207 // input and output buffers.
208 base::Thread decoder_thread_
;
210 // The queue of access units.
211 AccessUnitQueue au_queue_
;
223 // Helper method that processes an error from MediaCodec.
226 // Requests data. Ensures there is no more than one request at a time.
229 // Prefetching callback that is posted to Media thread
230 // in the kPrefetching state.
231 void PrefetchNextChunk();
233 // The callback to do actual playback. Posted to Decoder thread
234 // in the kRunning state.
235 void ProcessNextFrame();
237 // Helper method for ProcessNextFrame.
238 // Pushes one input buffer to the MediaCodec if the codec can accept it.
239 // Returns false if there was MediaCodec error.
240 bool EnqueueInputBuffer();
242 // Helper method for ProcessNextFrame.
243 // Pulls all currently available output frames and renders them.
244 // Returns false if there was MediaCodec error.
245 bool DepleteOutputBufferQueue(bool* eos_encountered
);
247 DecoderState
GetState() const;
248 void SetState(DecoderState state
);
249 const char* AsString(DecoderState state
);
253 // External data request callback that is passed to decoder.
254 base::Closure external_request_data_cb_
;
256 // These notifications are called on corresponding conditions.
257 base::Closure prefetch_done_cb_
;
258 base::Closure starvation_cb_
;
259 base::Closure stop_done_cb_
;
260 base::Closure error_cb_
;
262 // Data request callback that is posted by decoder internally.
263 base::Closure request_data_cb_
;
265 // Callback used to post OnCodecError method.
266 base::Closure internal_error_cb_
;
270 mutable base::Lock state_lock_
;
272 // Flag is set when the EOS is enqueued into MediaCodec. Reset by Flush.
275 // Flag is set when the EOS is received in MediaCodec output. Reset by Flush.
278 // Flag to ensure we post last frame notification once.
279 bool last_frame_posted_
;
281 // Indicates whether the data request is in progress.
282 bool is_data_request_in_progress_
;
284 // Indicates whether the incoming data should be ignored.
285 bool is_incoming_data_invalid_
;
287 // NOTE: Weak pointers must be invalidated before all other member variables.
288 base::WeakPtrFactory
<MediaCodecDecoder
> weak_factory_
;
290 DISALLOW_COPY_AND_ASSIGN(MediaCodecDecoder
);
295 #endif // MEDIA_BASE_ANDROID_MEDIA_CODEC_DECODER_H_