BookmarkManager: Fix 'new folder text field size changes on clicking it' issue.
[chromium-blink-merge.git] / media / base / android / media_codec_decoder.h
blobd22744fabc8dbae19e2fe0b767054ddcf3d0aa54
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"
20 namespace media {
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)
38 // | | |
39 // | Prefetch |--- internal ------|
40 // v | transition v
41 // [ Prefetching ] | [ Error ]
42 // | |
43 // | internal transition |
44 // v | Error recovery:
45 // [ Prefetched ] |
46 // | | (any state including Error)
47 // | Configure and Start | |
48 // v | | ReleaseDecoderResources
49 // [ Running ] | v
50 // | | [ InEmergencyStop ]
51 // | RequestToStop | |
52 // v | |(decoder thread stopped)
53 // [ Stopping ] ------------------- v
54 // [ Stopped ]
56 // [ Stopped ] --------------------
57 // ^ |
58 // | Flush |
59 // ---------------------------
61 // (any state except Error)
62 // |
63 // | SyncStop
64 // v
65 // [ InEmergencyStop ]
66 // |
67 // |(decoder thread stopped)
68 // v
69 // [ Stopped ]
71 // Here is the workflow that is expected to be maintained by a caller, which is
72 // MediaCodecPlayer currently.
74 // [ Stopped ]
75 // |
76 // | Prefetch
77 // v
78 // [ Prefetching ]
79 // |
80 // | (Enough data received)
81 // v
82 // [ Prefetched ]
83 // |
84 // | <---------- SetDemuxerConfigs (*)
85 // |
86 // | <---------- SetVideoSurface (**)
87 // |
88 // | Configure --------------------------------------------+
89 // | |
90 // v v
91 // ( Config Succeeded ) ( Key frame required )
92 // | |
93 // | Start |
94 // v |
95 // [ Running ] ------------------------------+ |
96 // | | |
97 // | | |
98 // | RequestToStop | SyncStop | SyncStop
99 // | | |
100 // [ Stopping ] | |
101 // | | |
102 // | ( Last frame rendered ) | |
103 // | | |
104 // | | |
105 // v | |
106 // [ Stopped ] <-----------------------------+-----------------+
109 // (*) Demuxer configs is a precondition to Configure(), but MediaCodecPlayer
110 // has stricter requirements and they are set before Prefetch().
112 // (**) VideoSurface is a precondition to video decoder Configure(), can be set
113 // any time before Configure().
115 class MediaCodecDecoder {
116 public:
117 // The result of MediaCodec configuration, used by MediaCodecPlayer.
118 enum ConfigStatus {
119 kConfigFailure = 0,
120 kConfigOk,
121 kConfigKeyFrameRequired,
124 // The decoder reports current playback time to the MediaCodecPlayer.
125 // For audio, the parameters designate the beginning and end of a time
126 // interval. The beginning is the estimated time that is playing right now.
127 // The end is the playback time of the last buffered data. During normal
128 // playback the subsequent intervals overlap.
129 // For video both values are PTS of the corresponding frame, i.e. the interval
130 // has zero width.
131 // The third parameter means "postpone", it is set to true if the actual
132 // rendering will start in a later point in time. This only happens with
133 // audio after preroll. The MediaCodecPlayer might decide to update the
134 // current time but not pass it to the upper layer.
135 typedef base::Callback<void(base::TimeDelta, base::TimeDelta, bool)>
136 SetTimeCallback;
138 // MediaCodecDecoder constructor.
139 // Parameters:
140 // media_task_runner:
141 // A task runner for the controlling thread. All public methods should be
142 // called on this thread, and callbacks are delivered on this thread.
143 // The MediaCodecPlayer uses a dedicated (Media) thread for this.
144 // external_request_data_cb:
145 // Called periodically as the amount of internally stored data decreases.
146 // The receiver should call OnDemuxerDataAvailable() with more data.
147 // starvation_cb:
148 // Called when starvation is detected. The decoder state does not change.
149 // The player is supposed to stop and then prefetch the decoder.
150 // stop_done_cb:
151 // Called when async stop request is completed.
152 // decoder_drained_cb:
153 // Called when decoder is drained for reconfiguration.
154 // error_cb:
155 // Called when a MediaCodec error occurred. If this happens, a player has
156 // to either call ReleaseDecoderResources() or destroy the decoder object.
157 // decoder_thread_name:
158 // The thread name to be passed to decoder thread constructor.
159 MediaCodecDecoder(
160 const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
161 const base::Closure& external_request_data_cb,
162 const base::Closure& starvation_cb,
163 const base::Closure& decoder_drained_cb,
164 const base::Closure& stop_done_cb,
165 const base::Closure& error_cb,
166 const char* decoder_thread_name);
167 virtual ~MediaCodecDecoder();
169 virtual const char* class_name() const;
171 // MediaCodecDecoder exists through the whole lifetime of the player
172 // to support dynamic addition and removal of the streams.
173 // This method returns true if the current stream (audio or video)
174 // is currently active.
175 virtual bool HasStream() const = 0;
177 // Stores configuration for the use of upcoming Configure()
178 virtual void SetDemuxerConfigs(const DemuxerConfigs& configs) = 0;
180 // Stops decoder thread, releases the MediaCodecBridge and other resources.
181 virtual void ReleaseDecoderResources() = 0;
183 // Flushes the MediaCodec, after that resets the AccessUnitQueue and blocks
184 // the input. Decoder thread should not be running.
185 virtual void Flush();
187 // Releases MediaCodecBridge and any related buffers or references.
188 virtual void ReleaseMediaCodec();
190 // Returns corresponding conditions.
191 bool IsPrefetchingOrPlaying() const;
192 bool IsStopped() const;
193 bool IsCompleted() const;
194 bool NotCompletedAndNeedsPreroll() const;
196 // Sets preroll timestamp and requests preroll.
197 void SetPrerollTimestamp(base::TimeDelta preroll_ts);
199 base::android::ScopedJavaLocalRef<jobject> GetMediaCrypto();
201 // Starts prefetching: accumulates enough data in AccessUnitQueue.
202 // Decoder thread is not running.
203 void Prefetch(const base::Closure& prefetch_done_cb);
205 // Configures MediaCodec.
206 ConfigStatus Configure();
208 // Starts the decoder for prerolling. This method starts the decoder thread.
209 bool Preroll(const base::Closure& preroll_done_cb);
211 // Starts the decoder after preroll is not needed, starting decoder thread
212 // if it has not started yet.
213 bool Start(base::TimeDelta start_timestamp);
215 // Stops the playback process synchronously. This method stops the decoder
216 // thread synchronously, and then releases all MediaCodec buffers.
217 void SyncStop();
219 // Requests to stop the playback and returns.
220 // Decoder will stop asynchronously after all the dequeued output buffers
221 // are rendered.
222 void RequestToStop();
224 // Notification posted when asynchronous stop is done or playback completed.
225 void OnLastFrameRendered(bool eos_encountered);
227 // Notification posted when last prerolled frame has been returned to codec.
228 void OnPrerollDone();
230 // Puts the incoming data into AccessUnitQueue.
231 void OnDemuxerDataAvailable(const DemuxerData& data);
233 // For testing only.
235 // Returns true if the decoder is in kPrerolling state.
236 bool IsPrerollingForTests() const;
238 // Drains decoder and reconfigures for each |kConfigChanged|.
239 void SetAlwaysReconfigureForTests();
241 // Sets the notification to be called when MediaCodec is created.
242 void SetCodecCreatedCallbackForTests(base::Closure cb);
244 protected:
245 enum RenderMode {
246 kRenderSkip = 0,
247 kRenderAfterPreroll,
248 kRenderNow,
251 // Returns true if the new DemuxerConfigs requires MediaCodec
252 // reconfiguration.
253 virtual bool IsCodecReconfigureNeeded(const DemuxerConfigs& next) const = 0;
255 // Does the part of MediaCodecBridge configuration that is specific
256 // to audio or video.
257 virtual ConfigStatus ConfigureInternal() = 0;
259 // Associates PTS with device time so we can calculate delays.
260 // We use delays for video decoder only.
261 virtual void AssociateCurrentTimeWithPTS(base::TimeDelta current_time) {}
263 // Invalidate delay calculation. We use delays for video decoder only.
264 virtual void DissociatePTSFromTime() {}
266 // Processes the change of the output format, varies by stream.
267 virtual void OnOutputFormatChanged() = 0;
269 // Renders the decoded frame and releases output buffer, or posts
270 // a delayed task to do it at a later time,
271 virtual void Render(int buffer_index,
272 size_t offset,
273 size_t size,
274 RenderMode render_mode,
275 base::TimeDelta pts,
276 bool eos_encountered) = 0;
278 // Returns the number of delayed task (we might have them for video).
279 virtual int NumDelayedRenderTasks() const;
281 // Releases output buffers that are dequeued and not released yet (video).
282 virtual void ReleaseDelayedBuffers() {}
284 #ifndef NDEBUG
285 // For video, checks that access unit is the key frame or stand-alone EOS.
286 virtual void VerifyUnitIsKeyFrame(const AccessUnit* unit) const {}
287 #endif
289 // Helper methods.
291 // Synchroniously stop decoder thread.
292 void DoEmergencyStop();
294 // Returns true if we are in the process of sync stop.
295 bool InEmergencyStop() const { return GetState() == kInEmergencyStop; }
297 // Notifies the decoder if the frame is the last one.
298 void CheckLastFrame(bool eos_encountered, bool has_delayed_tasks);
300 const char* AsString(RenderMode render_mode);
302 // Protected data.
304 // Object for posting tasks on Media thread.
305 scoped_refptr<base::SingleThreadTaskRunner> media_task_runner_;
307 // Controls Android MediaCodec
308 scoped_ptr<MediaCodecBridge> media_codec_bridge_;
310 // We call MediaCodecBridge on this thread for both
311 // input and output buffers.
312 base::Thread decoder_thread_;
314 // The queue of access units.
315 AccessUnitQueue au_queue_;
317 // Flag forces reconfiguration even if |media_codec_bridge_| exists. Currently
318 // is set by video decoder when the video surface changes.
319 bool needs_reconfigure_;
321 // Flag forces to drain decoder in the process of dynamic reconfiguration.
322 bool drain_decoder_;
324 // For tests only. Forces to always reconfigure for |kConfigChanged| unit.
325 bool always_reconfigure_for_tests_;
327 // For tests only. Callback to be callned when MediaCodec is created.
328 base::Closure codec_created_for_tests_cb_;
330 private:
331 enum DecoderState {
332 kStopped = 0,
333 kPrefetching,
334 kPrefetched,
335 kPrerolling,
336 kPrerolled,
337 kRunning,
338 kStopping,
339 kInEmergencyStop,
340 kError,
343 // Helper method that processes an error from MediaCodec.
344 void OnCodecError();
346 // Requests data. Ensures there is no more than one request at a time.
347 void RequestData();
349 // Prefetching callback that is posted to Media thread
350 // in the kPrefetching state.
351 void PrefetchNextChunk();
353 // The callback to do actual playback. Posted to Decoder thread
354 // in the kRunning state.
355 void ProcessNextFrame();
357 // Helper method for ProcessNextFrame.
358 // Pushes one input buffer to the MediaCodec if the codec can accept it.
359 // Returns false if there was MediaCodec error.
360 bool EnqueueInputBuffer();
362 // Helper method for EnqueueInputBuffer.
363 // Gets the next data frame from the queue, requesting more data and saving
364 // configuration changes on the way. Sets |drain_decoder| to true of any of
365 // the configuration changes requires draining the decoder. Returns the Info
366 // pointing to the current data unit ot empty Info if it got past the end of
367 // the queue.
368 AccessUnitQueue::Info AdvanceAccessUnitQueue(bool* drain_decoder);
370 // Helper method for ProcessNextFrame.
371 // Pulls all currently available output frames and renders them.
372 // Returns true if we need to continue decoding process, i.e post next
373 // ProcessNextFrame method, and false if we need to stop decoding.
374 bool DepleteOutputBufferQueue();
376 DecoderState GetState() const;
377 void SetState(DecoderState state);
378 const char* AsString(DecoderState state);
380 // Private Data.
382 // External data request callback that is passed to decoder.
383 base::Closure external_request_data_cb_;
385 // These notifications are called on corresponding conditions.
386 base::Closure prefetch_done_cb_;
387 base::Closure starvation_cb_;
388 base::Closure preroll_done_cb_;
389 base::Closure decoder_drained_cb_;
390 base::Closure stop_done_cb_;
391 base::Closure error_cb_;
393 // Data request callback that is posted by decoder internally.
394 base::Closure request_data_cb_;
396 // Callback used to post OnCodecError method.
397 base::Closure internal_error_cb_;
399 // Callback for posting OnPrerollDone method.
400 base::Closure internal_preroll_done_cb_;
402 // Internal state.
403 DecoderState state_;
404 mutable base::Lock state_lock_;
406 // Preroll timestamp is set if we need preroll and cleared after we done it.
407 base::TimeDelta preroll_timestamp_;
409 // Set to true when MediaCodec internal buffers are filled up.
410 bool is_prepared_;
412 // Flag is set when the EOS is enqueued into MediaCodec. Reset by Flush.
413 bool eos_enqueued_;
415 // Flag is set when the EOS is received in MediaCodec output. Reset by Flush.
416 bool completed_;
418 // Flag to ensure we post last frame notification once.
419 bool last_frame_posted_;
421 // Indicates whether the data request is in progress.
422 bool is_data_request_in_progress_;
424 // Indicates whether the incoming data should be ignored.
425 bool is_incoming_data_invalid_;
427 #ifndef NDEBUG
428 // When set, we check that the following video frame is the key frame.
429 bool verify_next_frame_is_key_;
430 #endif
432 // NOTE: Weak pointers must be invalidated before all other member variables.
433 base::WeakPtrFactory<MediaCodecDecoder> weak_factory_;
435 DISALLOW_COPY_AND_ASSIGN(MediaCodecDecoder);
438 } // namespace media
440 #endif // MEDIA_BASE_ANDROID_MEDIA_CODEC_DECODER_H_