Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(154)

Side by Side Diff: content/common/gpu/media/android_video_decode_accelerator.cc

Issue 11973010: AndroidVDA by using Android's MediaCodec API. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: using CopyTextureCHROMIUMResourceManager Created 7 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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.
4
5 #include "content/common/gpu/media/android_video_decode_accelerator.h"
6
7 #include <jni.h>
8
9 #include "base/android/jni_android.h"
10 #include "base/android/scoped_java_ref.h"
11 #include "base/bind.h"
12 #include "base/logging.h"
13 #include "base/message_loop.h"
14 #include "content/common/android/surface_callback.h"
15 #include "content/common/gpu/gpu_channel.h"
16 #include "content/common/gpu/media/gles2_external_texture_copier.h"
17 #include "media/base/bitstream_buffer.h"
18 #include "media/base/limits.h"
19 #include "media/video/picture.h"
20 #include "ui/gl/gl_bindings.h"
21
22 using base::android::MethodID;
23 using base::android::ScopedJavaLocalRef;
24
25 namespace content {
26
27 // XXX: drop the below before submitting.
28 #define LOG_LINE() LOG(INFO) << __FUNCTION__
29
30 // Helper macros for dealing with failure. If |result| evaluates false, emit
31 // |log| to ERROR, register |error| with the decoder, and return.
32 #define RETURN_ON_FAILURE(result, log, error) \
33 do { \
34 if (!(result)) { \
35 DLOG(ERROR) << log; \
36 MessageLoop::current()->PostTask(FROM_HERE, base::Bind( \
37 &AndroidVideoDecodeAccelerator::NotifyError, \
38 base::AsWeakPtr(this), error)); \
39 state_ = ERROR; \
40 return; \
41 } \
42 } while (0)
43
44 // TODO(dwkang): We only need kMaxVideoFrames to pass media stack's prerolling
45 // phase, but 1 is added due to crbug.com/176036. This should be tuned when we
46 // have actual use case.
47 enum { kNumPictureBuffers = media::limits::kMaxVideoFrames + 1 };
48
49 // Max number of bitstreams notified to the client with
50 // NotifyEndOfBitstreamBuffer() before getting output from the bitstream.
51 enum { kMaxBitstreamsNotifiedInAdvance = 32 };
52
53 // static
54 const base::TimeDelta AndroidVideoDecodeAccelerator::kDecodePollDelay =
55 base::TimeDelta::FromMilliseconds(10);
56
57 AndroidVideoDecodeAccelerator::AndroidVideoDecodeAccelerator(
58 media::VideoDecodeAccelerator::Client* client,
59 const base::Callback<bool(void)>& make_context_current)
60 : client_(client),
61 make_context_current_(make_context_current),
62 codec_(media::MediaCodecBridge::VIDEO_H264),
63 state_(NO_ERROR),
64 surface_texture_id_(-1),
65 picturebuffers_requested_(false),
66 io_task_is_posted_(false),
67 decoder_met_eos_(false),
68 num_bytes_used_in_the_pending_buffer_(0) {
69 LOG_LINE();
70 }
71
72 AndroidVideoDecodeAccelerator::~AndroidVideoDecodeAccelerator() {
73 LOG_LINE();
74 DCHECK(thread_checker_.CalledOnValidThread());
75 }
76
77 bool AndroidVideoDecodeAccelerator::Initialize(
78 media::VideoCodecProfile profile) {
79 LOG_LINE();
80 DCHECK(!media_codec_);
81 DCHECK(thread_checker_.CalledOnValidThread());
82
83 if (profile == media::VP8PROFILE_MAIN) {
84 codec_ = media::MediaCodecBridge::VIDEO_VP8;
85 } else if (profile >= media::H264PROFILE_MIN &&
86 profile <= media::H264PROFILE_MAX) {
87 codec_ = media::MediaCodecBridge::VIDEO_H264;
88 } else {
89 LOG(ERROR) << "Unsupported profile: " << profile;
90 return false;
91 }
92
93 if (!make_context_current_.Run()) {
94 LOG(ERROR) << "Failed to make this decoder's GL context current.";
95 return false;
96 }
97
98 glGenTextures(1, &surface_texture_id_);
99 glActiveTexture(GL_TEXTURE0);
100 glBindTexture(GL_TEXTURE_EXTERNAL_OES, surface_texture_id_);
101
102 glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
103 glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
104 glTexParameteri(GL_TEXTURE_EXTERNAL_OES,
105 GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
106 glTexParameteri(GL_TEXTURE_EXTERNAL_OES,
107 GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
108
109 surface_texture_ = new SurfaceTextureBridge(surface_texture_id_);
110
111 ConfigureMediaCodec();
112
113 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
114 &AndroidVideoDecodeAccelerator::NotifyInitializeDone,
115 base::AsWeakPtr(this)));
116 return true;
117 }
118
119 void AndroidVideoDecodeAccelerator::DoIOTask() {
120 io_task_is_posted_ = false;
121 if (state_ == ERROR) {
122 return;
123 }
124
125 DequeueOutput();
126 QueueInput();
127
128 if (!pending_bitstream_buffers_.empty() ||
129 !free_picture_ids_.empty()) {
130 io_task_is_posted_ = true;
131 MessageLoop::current()->PostDelayedTask(
132 FROM_HERE,
133 base::Bind(
134 &AndroidVideoDecodeAccelerator::DoIOTask, base::AsWeakPtr(this)),
135 kDecodePollDelay);
136 }
137 }
138
139 void AndroidVideoDecodeAccelerator::QueueInput() {
140 if (bitstreams_notified_in_advance_.size() > kMaxBitstreamsNotifiedInAdvance)
141 return;
142 if (pending_bitstream_buffers_.empty())
143 return;
144
145 int input_buf_index = media_codec_->DequeueInputBuffer(
146 media::MediaCodecBridge::kTimeOutNoWait);
147 if (input_buf_index < 0) {
148 DCHECK_EQ(input_buf_index, media::MediaCodecBridge::INFO_TRY_AGAIN_LATER);
149 return;
150 }
151 media::BitstreamBuffer& bitstream_buffer =
152 pending_bitstream_buffers_.front();
153
154 if (bitstream_buffer.id() == -1) {
155 media_codec_->QueueEOS(input_buf_index);
156 pending_bitstream_buffers_.pop();
157 return;
158 }
159 // Abuse the presentation time argument to propagate the bitstream
160 // buffer ID to the output, so we can report it back to the client in
161 // PictureReady().
162 base::TimeDelta timestamp =
163 base::TimeDelta::FromMicroseconds(bitstream_buffer.id());
164
165 int bytes_written = 0;
166 scoped_ptr<base::SharedMemory> shm(
167 new base::SharedMemory(bitstream_buffer.handle(), true));
168
169 RETURN_ON_FAILURE(shm->Map(bitstream_buffer.size()),
170 "Failed to SharedMemory::Map()",
171 UNREADABLE_INPUT);
172
173 const size_t offset = num_bytes_used_in_the_pending_buffer_;
174 bytes_written = media_codec_->QueueInputBuffer(
175 input_buf_index,
176 static_cast<const uint8*>(shm->memory()) + offset,
177 bitstream_buffer.size() - offset, timestamp);
178 num_bytes_used_in_the_pending_buffer_ += bytes_written;
179 CHECK_LE(num_bytes_used_in_the_pending_buffer_, bitstream_buffer.size());
180
181 if (num_bytes_used_in_the_pending_buffer_ == bitstream_buffer.size()) {
182 num_bytes_used_in_the_pending_buffer_ = 0;
183 pending_bitstream_buffers_.pop();
184
185 // We should call NotifyEndOfBitstreamBuffer(), when no more decoded output
186 // will be returned from the bitstream buffer. However, MediaCodec API is
187 // not enough to guarantee it.
188 // So, here, we calls NotifyEndOfBitstreamBuffer() in advance in order to
189 // keep getting more bitstreams from the client, and throttle them by using
190 // |bitstreams_notified_in_advance_|.
191 // TODO(dwkang): check if there is a way to remove this workaround.
192 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
193 &AndroidVideoDecodeAccelerator::NotifyEndOfBitstreamBuffer,
194 base::AsWeakPtr(this), bitstream_buffer.id()));
195 bitstreams_notified_in_advance_.push_back(bitstream_buffer.id());
196 }
197 }
198
199 void AndroidVideoDecodeAccelerator::DequeueOutput() {
200 if (picturebuffers_requested_ && output_picture_buffers_.empty())
201 return;
202
203 if (!output_picture_buffers_.empty() && free_picture_ids_.empty()) {
204 // Don't have any picture buffer to send. Need to wait more.
205 return;
206 }
207
208 bool eos = false;
209 base::TimeDelta timestamp;
210 int32 buf_index = 0;
211 do {
212 int32 offset = 0;
213 int32 size = 0;
214 buf_index = media_codec_->DequeueOutputBuffer(
215 media::MediaCodecBridge::kTimeOutNoWait,
216 &offset, &size, &timestamp, &eos);
217 switch (buf_index) {
218 case media::MediaCodecBridge::INFO_TRY_AGAIN_LATER:
219 return;
220
221 case media::MediaCodecBridge::INFO_OUTPUT_FORMAT_CHANGED: {
222 int32 width, height;
223 media_codec_->GetOutputFormat(&width, &height);
224
225 if (!picturebuffers_requested_) {
226 picturebuffers_requested_ = true;
227 size_ = gfx::Size(width, height);
228 texture_copier_.reset(new Gles2ExternalTextureCopier(width, height));
229 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
230 &AndroidVideoDecodeAccelerator::RequestPictureBuffers,
231 base::AsWeakPtr(this)));
232 } else {
233 // TODO(dwkang): support the dynamic resolution change.
234 // Currently, we assume that there is no resolution change in the
235 // input stream. So, INFO_OUTPUT_FORMAT_CHANGED should not happen
236 // more than once. However, we allows it if resolution is the same
237 // as the previous one because |media_codec_| can be reset in Reset().
238 RETURN_ON_FAILURE(size_ == gfx::Size(width, height),
239 "Dynamic resolution change is not supported.",
240 PLATFORM_FAILURE);
241 }
242 return;
243 }
244
245 case media::MediaCodecBridge::INFO_OUTPUT_BUFFERS_CHANGED:
246 media_codec_->GetOutputBuffers();
247 break;
248 }
249 } while (buf_index < 0);
250
251 media_codec_->ReleaseOutputBuffer(buf_index, true);
252
253 if (eos) {
254 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
255 &AndroidVideoDecodeAccelerator::NotifyFlushDone,
256 base::AsWeakPtr(this)));
257 decoder_met_eos_ = true;
258 } else {
259 int64 bitstream_buffer_id = timestamp.InMicroseconds();
260 SendCurrentSurfaceToClient(static_cast<int32>(bitstream_buffer_id));
261
262 // Removes ids former or equal than the id from decoder. Note that
263 // |bitstreams_notified_in_advance_| does not mean bitstream ids in decoder
264 // because of frame reordering issue. We just maintain this roughly and use
265 // for the throttling purpose.
266 std::list<int32>::iterator it;
267 for (it = bitstreams_notified_in_advance_.begin();
268 it != bitstreams_notified_in_advance_.end();
269 ++it) {
270 if (*it == bitstream_buffer_id) {
271 bitstreams_notified_in_advance_.erase(
272 bitstreams_notified_in_advance_.begin(), ++it);
273 break;
274 }
275 }
276 }
277 }
278
279 void AndroidVideoDecodeAccelerator::SendCurrentSurfaceToClient(
280 int32 bitstream_id) {
281 LOG_LINE();
282 DCHECK(thread_checker_.CalledOnValidThread());
283 DCHECK_NE(bitstream_id, -1);
284 DCHECK(!free_picture_ids_.empty());
285
286 RETURN_ON_FAILURE(make_context_current_.Run(),
287 "Failed to make this decoder's GL context current.",
288 PLATFORM_FAILURE);
289
290 int32 picture_buffer_id = free_picture_ids_.front();
291 free_picture_ids_.pop();
292
293 float transfrom_matrix[16];
294 surface_texture_->UpdateTexImage();
295 surface_texture_->GetTransformMatrix(transfrom_matrix);
296
297 OutputBufferMap::const_iterator i =
298 output_picture_buffers_.find(picture_buffer_id);
299 RETURN_ON_FAILURE(i != output_picture_buffers_.end(),
300 "Can't find a PictureBuffer for " << picture_buffer_id,
301 PLATFORM_FAILURE);
302 uint32 picture_buffer_texture_id = i->second.texture_id();
303
304 // Here, we copy |surface_texture_id_| to the picture buffer instead of
305 // setting new texture to |surface_texture_| by calling attachToGLContext()
306 // because:
307 // 1. Once we call detachFrameGLContext(), it deletes the texture previous
308 // attached.
309 // 2. SurfaceTexture requires us to apply a transform matrix when we show
310 // the texture.
311 texture_copier_->Copy(
312 surface_texture_id_, picture_buffer_texture_id);
313
314 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
315 &AndroidVideoDecodeAccelerator::NotifyPictureReady,
316 base::AsWeakPtr(this), media::Picture(picture_buffer_id, bitstream_id)));
317 }
318
319 void AndroidVideoDecodeAccelerator::Decode(
320 const media::BitstreamBuffer& bitstream_buffer) {
321 LOG_LINE();
322 DCHECK(thread_checker_.CalledOnValidThread());
323 if (bitstream_buffer.id() != -1 && bitstream_buffer.size() == 0) {
324 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
325 &AndroidVideoDecodeAccelerator::NotifyEndOfBitstreamBuffer,
326 base::AsWeakPtr(this), bitstream_buffer.id()));
327 return;
328 }
329
330 pending_bitstream_buffers_.push(bitstream_buffer);
331
332 if (!io_task_is_posted_)
333 DoIOTask();
334 }
335
336 void AndroidVideoDecodeAccelerator::AssignPictureBuffers(
337 const std::vector<media::PictureBuffer>& buffers) {
338 LOG_LINE();
339 DCHECK(thread_checker_.CalledOnValidThread());
340 DCHECK(output_picture_buffers_.empty());
341
342 for (size_t i = 0; i < buffers.size(); ++i) {
343 output_picture_buffers_.insert(std::make_pair(buffers[i].id(), buffers[i]));
344 free_picture_ids_.push(buffers[i].id());
345 }
346
347 RETURN_ON_FAILURE(output_picture_buffers_.size() == kNumPictureBuffers,
348 "Invalid picture buffers were passed.",
349 INVALID_ARGUMENT);
350
351 if (!io_task_is_posted_)
352 DoIOTask();
353 }
354
355 void AndroidVideoDecodeAccelerator::ReusePictureBuffer(
356 int32 picture_buffer_id) {
357 DCHECK(thread_checker_.CalledOnValidThread());
358 free_picture_ids_.push(picture_buffer_id);
359
360 if (!io_task_is_posted_)
361 DoIOTask();
362 }
363
364 void AndroidVideoDecodeAccelerator::Flush() {
365 LOG_LINE();
366 DCHECK(thread_checker_.CalledOnValidThread());
367
368 Decode(media::BitstreamBuffer(-1, base::SharedMemoryHandle(), 0));
369 }
370
371 void AndroidVideoDecodeAccelerator::ConfigureMediaCodec() {
372 DCHECK(surface_texture_.get());
373
374 media_codec_.reset(new media::MediaCodecBridge(codec_));
375
376 JNIEnv* env = base::android::AttachCurrentThread();
377 CHECK(env);
378 ScopedJavaLocalRef<jclass> cls(
379 base::android::GetClass(env, "android/view/Surface"));
380 jmethodID constructor = MethodID::Get<MethodID::TYPE_INSTANCE>(
381 env, cls.obj(), "<init>", "(Landroid/graphics/SurfaceTexture;)V");
382 ScopedJavaLocalRef<jobject> j_surface(
383 env, env->NewObject(
384 cls.obj(), constructor,
385 surface_texture_->j_surface_texture().obj()));
386
387 // VDA does not pass the container indicated resolution in the initialization
388 // phase. Here, we set 720p by default.
389 // TODO(dwkang): find out a way to remove the following hard-coded value.
390 media_codec_->StartVideo(codec_, gfx::Size(1280, 720), j_surface.obj());
391 content::ReleaseSurface(j_surface.obj());
392 media_codec_->GetOutputBuffers();
393 }
394
395 void AndroidVideoDecodeAccelerator::Reset() {
396 LOG_LINE();
397 DCHECK(thread_checker_.CalledOnValidThread());
398
399 while(!pending_bitstream_buffers_.empty()) {
400 media::BitstreamBuffer& bitstream_buffer =
401 pending_bitstream_buffers_.front();
402 pending_bitstream_buffers_.pop();
403
404 if (bitstream_buffer.id() != -1) {
405 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
406 &AndroidVideoDecodeAccelerator::NotifyEndOfBitstreamBuffer,
407 base::AsWeakPtr(this), bitstream_buffer.id()));
408 }
409 }
410 bitstreams_notified_in_advance_.clear();
411
412 if (!decoder_met_eos_) {
413 media_codec_->Reset();
414 } else {
415 // MediaCodec should be usable after meeting EOS, but it is not on some
416 // devices. b/8125974 To avoid the case, we recreate a new one.
417 media_codec_->Stop();
418 ConfigureMediaCodec();
419 }
420 decoder_met_eos_ = false;
421 num_bytes_used_in_the_pending_buffer_ = 0;
422 state_ = NO_ERROR;
423
424 MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
425 &AndroidVideoDecodeAccelerator::NotifyResetDone, base::AsWeakPtr(this)));
426 }
427
428 void AndroidVideoDecodeAccelerator::Destroy() {
429 LOG_LINE();
430 DCHECK(thread_checker_.CalledOnValidThread());
431
432 if (media_codec_) media_codec_->Stop();
433 delete this;
434 }
435
436 void AndroidVideoDecodeAccelerator::NotifyInitializeDone() {
437 client_->NotifyInitializeDone();
438 }
439
440 void AndroidVideoDecodeAccelerator::RequestPictureBuffers() {
441 client_->ProvidePictureBuffers(kNumPictureBuffers, size_, GL_TEXTURE_2D);
442 }
443
444 void AndroidVideoDecodeAccelerator::NotifyPictureReady(
445 const media::Picture& picture) {
446 client_->PictureReady(picture);
447 }
448
449 void AndroidVideoDecodeAccelerator::NotifyEndOfBitstreamBuffer(
450 int input_buffer_id) {
451 client_->NotifyEndOfBitstreamBuffer(input_buffer_id);
452 }
453
454 void AndroidVideoDecodeAccelerator::NotifyFlushDone() {
455 client_->NotifyFlushDone();
456 }
457
458 void AndroidVideoDecodeAccelerator::NotifyResetDone() {
459 client_->NotifyResetDone();
460 }
461
462 void AndroidVideoDecodeAccelerator::NotifyError(
463 media::VideoDecodeAccelerator::Error error) {
464 client_->NotifyError(error);
465 }
466
467 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698