1 // Copyright 2014 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.
8 #include <libdrm/drm_fourcc.h>
9 #include <linux/videodev2.h>
11 #include <sys/eventfd.h>
12 #include <sys/ioctl.h>
15 #include "base/bind.h"
16 #include "base/debug/trace_event.h"
17 #include "base/memory/shared_memory.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/message_loop/message_loop_proxy.h"
20 #include "base/posix/eintr_wrapper.h"
21 #include "content/common/gpu/media/v4l2_video_decode_accelerator.h"
22 #include "media/filters/h264_parser.h"
23 #include "ui/gl/scoped_binders.h"
27 #define NOTIFY_ERROR(x) \
29 SetDecoderState(kError); \
30 DLOG(ERROR) << "calling NotifyError(): " << x; \
34 #define IOCTL_OR_ERROR_RETURN(type, arg) \
36 if (HANDLE_EINTR(device_->Ioctl(type, arg) != 0)) { \
37 DPLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
38 NOTIFY_ERROR(PLATFORM_FAILURE); \
43 #define IOCTL_OR_ERROR_RETURN_FALSE(type, arg) \
45 if (HANDLE_EINTR(device_->Ioctl(type, arg) != 0)) { \
46 DPLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
47 NOTIFY_ERROR(PLATFORM_FAILURE); \
54 // TODO(posciak): remove once we update linux-headers.
55 #ifndef V4L2_EVENT_RESOLUTION_CHANGE
56 #define V4L2_EVENT_RESOLUTION_CHANGE 5
59 } // anonymous namespace
61 struct V4L2VideoDecodeAccelerator::BitstreamBufferRef {
63 base::WeakPtr<Client>& client,
64 scoped_refptr<base::MessageLoopProxy>& client_message_loop_proxy,
65 base::SharedMemory* shm,
68 ~BitstreamBufferRef();
69 const base::WeakPtr<Client> client;
70 const scoped_refptr<base::MessageLoopProxy> client_message_loop_proxy;
71 const scoped_ptr<base::SharedMemory> shm;
77 struct V4L2VideoDecodeAccelerator::EGLSyncKHRRef {
78 EGLSyncKHRRef(EGLDisplay egl_display, EGLSyncKHR egl_sync);
80 EGLDisplay const egl_display;
84 struct V4L2VideoDecodeAccelerator::PictureRecord {
85 PictureRecord(bool cleared, const media::Picture& picture);
87 bool cleared; // Whether the texture is cleared and safe to render from.
88 media::Picture picture; // The decoded picture.
91 V4L2VideoDecodeAccelerator::BitstreamBufferRef::BitstreamBufferRef(
92 base::WeakPtr<Client>& client,
93 scoped_refptr<base::MessageLoopProxy>& client_message_loop_proxy,
94 base::SharedMemory* shm, size_t size, int32 input_id)
96 client_message_loop_proxy(client_message_loop_proxy),
103 V4L2VideoDecodeAccelerator::BitstreamBufferRef::~BitstreamBufferRef() {
105 client_message_loop_proxy->PostTask(FROM_HERE, base::Bind(
106 &Client::NotifyEndOfBitstreamBuffer, client, input_id));
110 V4L2VideoDecodeAccelerator::EGLSyncKHRRef::EGLSyncKHRRef(
111 EGLDisplay egl_display, EGLSyncKHR egl_sync)
112 : egl_display(egl_display),
116 V4L2VideoDecodeAccelerator::EGLSyncKHRRef::~EGLSyncKHRRef() {
117 // We don't check for eglDestroySyncKHR failures, because if we get here
118 // with a valid sync object, something went wrong and we are getting
120 if (egl_sync != EGL_NO_SYNC_KHR)
121 eglDestroySyncKHR(egl_display, egl_sync);
124 V4L2VideoDecodeAccelerator::InputRecord::InputRecord()
132 V4L2VideoDecodeAccelerator::InputRecord::~InputRecord() {
135 V4L2VideoDecodeAccelerator::OutputRecord::OutputRecord()
138 egl_image(EGL_NO_IMAGE_KHR),
139 egl_sync(EGL_NO_SYNC_KHR),
142 for (size_t i = 0; i < arraysize(fds); ++i)
146 V4L2VideoDecodeAccelerator::OutputRecord::~OutputRecord() {}
148 V4L2VideoDecodeAccelerator::PictureRecord::PictureRecord(
150 const media::Picture& picture)
151 : cleared(cleared), picture(picture) {}
153 V4L2VideoDecodeAccelerator::PictureRecord::~PictureRecord() {}
155 V4L2VideoDecodeAccelerator::V4L2VideoDecodeAccelerator(
156 EGLDisplay egl_display,
158 const base::WeakPtr<Client>& io_client,
159 const base::Callback<bool(void)>& make_context_current,
160 scoped_ptr<V4L2Device> device,
161 const scoped_refptr<base::MessageLoopProxy>& io_message_loop_proxy)
162 : child_message_loop_proxy_(base::MessageLoopProxy::current()),
163 io_message_loop_proxy_(io_message_loop_proxy),
164 weak_this_(base::AsWeakPtr(this)),
165 client_ptr_factory_(client),
166 client_(client_ptr_factory_.GetWeakPtr()),
167 io_client_(io_client),
168 decoder_thread_("V4L2DecoderThread"),
169 decoder_state_(kUninitialized),
170 device_(device.Pass()),
171 decoder_delay_bitstream_buffer_id_(-1),
172 decoder_current_input_buffer_(-1),
173 decoder_decode_buffer_tasks_scheduled_(0),
174 decoder_frames_at_client_(0),
175 decoder_flushing_(false),
176 resolution_change_pending_(false),
177 resolution_change_reset_pending_(false),
178 decoder_partial_frame_pending_(false),
179 input_streamon_(false),
180 input_buffer_queued_count_(0),
181 output_streamon_(false),
182 output_buffer_queued_count_(0),
183 output_buffer_pixelformat_(0),
185 picture_clearing_count_(0),
186 pictures_assigned_(false, false),
187 device_poll_thread_("V4L2DevicePollThread"),
188 make_context_current_(make_context_current),
189 egl_display_(egl_display),
190 video_profile_(media::VIDEO_CODEC_PROFILE_UNKNOWN) {}
192 V4L2VideoDecodeAccelerator::~V4L2VideoDecodeAccelerator() {
193 DCHECK(!decoder_thread_.IsRunning());
194 DCHECK(!device_poll_thread_.IsRunning());
196 DestroyInputBuffers();
197 DestroyOutputBuffers();
199 // These maps have members that should be manually destroyed, e.g. file
200 // descriptors, mmap() segments, etc.
201 DCHECK(input_buffer_map_.empty());
202 DCHECK(output_buffer_map_.empty());
205 bool V4L2VideoDecodeAccelerator::Initialize(
206 media::VideoCodecProfile profile) {
207 DVLOG(3) << "Initialize()";
208 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
209 DCHECK_EQ(decoder_state_, kUninitialized);
212 case media::H264PROFILE_BASELINE:
213 DVLOG(2) << "Initialize(): profile H264PROFILE_BASELINE";
215 case media::H264PROFILE_MAIN:
216 DVLOG(2) << "Initialize(): profile H264PROFILE_MAIN";
218 case media::H264PROFILE_HIGH:
219 DVLOG(2) << "Initialize(): profile H264PROFILE_HIGH";
221 case media::VP8PROFILE_MAIN:
222 DVLOG(2) << "Initialize(): profile VP8PROFILE_MAIN";
225 DLOG(ERROR) << "Initialize(): unsupported profile=" << profile;
228 video_profile_ = profile;
230 if (egl_display_ == EGL_NO_DISPLAY) {
231 DLOG(ERROR) << "Initialize(): could not get EGLDisplay";
232 NOTIFY_ERROR(PLATFORM_FAILURE);
236 // We need the context to be initialized to query extensions.
237 if (!make_context_current_.Run()) {
238 DLOG(ERROR) << "Initialize(): could not make context current";
239 NOTIFY_ERROR(PLATFORM_FAILURE);
243 if (!gfx::g_driver_egl.ext.b_EGL_KHR_fence_sync) {
244 DLOG(ERROR) << "Initialize(): context does not have EGL_KHR_fence_sync";
245 NOTIFY_ERROR(PLATFORM_FAILURE);
249 // Capabilities check.
250 struct v4l2_capability caps;
251 const __u32 kCapsRequired =
252 V4L2_CAP_VIDEO_CAPTURE_MPLANE |
253 V4L2_CAP_VIDEO_OUTPUT_MPLANE |
255 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYCAP, &caps);
256 if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
257 DLOG(ERROR) << "Initialize(): ioctl() failed: VIDIOC_QUERYCAP"
258 ", caps check failed: 0x" << std::hex << caps.capabilities;
259 NOTIFY_ERROR(PLATFORM_FAILURE);
263 if (!CreateInputBuffers())
266 // Output format has to be setup before streaming starts.
267 struct v4l2_format format;
268 memset(&format, 0, sizeof(format));
269 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
270 format.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12M;
271 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format);
273 // Subscribe to the resolution change event.
274 struct v4l2_event_subscription sub;
275 memset(&sub, 0, sizeof(sub));
276 sub.type = V4L2_EVENT_RESOLUTION_CHANGE;
277 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_SUBSCRIBE_EVENT, &sub);
279 // Initialize format-specific bits.
280 if (video_profile_ >= media::H264PROFILE_MIN &&
281 video_profile_ <= media::H264PROFILE_MAX) {
282 decoder_h264_parser_.reset(new media::H264Parser());
285 if (!decoder_thread_.Start()) {
286 DLOG(ERROR) << "Initialize(): decoder thread failed to start";
287 NOTIFY_ERROR(PLATFORM_FAILURE);
291 SetDecoderState(kInitialized);
293 child_message_loop_proxy_->PostTask(FROM_HERE, base::Bind(
294 &Client::NotifyInitializeDone, client_));
298 void V4L2VideoDecodeAccelerator::Decode(
299 const media::BitstreamBuffer& bitstream_buffer) {
300 DVLOG(1) << "Decode(): input_id=" << bitstream_buffer.id()
301 << ", size=" << bitstream_buffer.size();
302 DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());
304 // DecodeTask() will take care of running a DecodeBufferTask().
305 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
306 &V4L2VideoDecodeAccelerator::DecodeTask, base::Unretained(this),
310 void V4L2VideoDecodeAccelerator::AssignPictureBuffers(
311 const std::vector<media::PictureBuffer>& buffers) {
312 DVLOG(3) << "AssignPictureBuffers(): buffer_count=" << buffers.size();
313 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
315 if (buffers.size() != output_buffer_map_.size()) {
316 DLOG(ERROR) << "AssignPictureBuffers(): Failed to provide requested picture"
317 " buffers. (Got " << buffers.size()
318 << ", requested " << output_buffer_map_.size() << ")";
319 NOTIFY_ERROR(INVALID_ARGUMENT);
323 if (!make_context_current_.Run()) {
324 DLOG(ERROR) << "AssignPictureBuffers(): could not make context current";
325 NOTIFY_ERROR(PLATFORM_FAILURE);
329 gfx::ScopedTextureBinder bind_restore(GL_TEXTURE_EXTERNAL_OES, 0);
331 EGL_WIDTH, 0, EGL_HEIGHT, 0,
332 EGL_LINUX_DRM_FOURCC_EXT, 0, EGL_DMA_BUF_PLANE0_FD_EXT, 0,
333 EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, EGL_DMA_BUF_PLANE0_PITCH_EXT, 0,
334 EGL_DMA_BUF_PLANE1_FD_EXT, 0, EGL_DMA_BUF_PLANE1_OFFSET_EXT, 0,
335 EGL_DMA_BUF_PLANE1_PITCH_EXT, 0, EGL_NONE, };
336 attrs[1] = frame_buffer_size_.width();
337 attrs[3] = frame_buffer_size_.height();
338 attrs[5] = DRM_FORMAT_NV12;
340 // It's safe to manipulate all the buffer state here, because the decoder
341 // thread is waiting on pictures_assigned_.
342 DCHECK(free_output_buffers_.empty());
343 for (size_t i = 0; i < output_buffer_map_.size(); ++i) {
344 DCHECK(buffers[i].size() == frame_buffer_size_);
346 OutputRecord& output_record = output_buffer_map_[i];
347 DCHECK(!output_record.at_device);
348 DCHECK(!output_record.at_client);
349 DCHECK_EQ(output_record.egl_image, EGL_NO_IMAGE_KHR);
350 DCHECK_EQ(output_record.egl_sync, EGL_NO_SYNC_KHR);
351 DCHECK_EQ(output_record.picture_id, -1);
352 DCHECK_EQ(output_record.cleared, false);
354 attrs[7] = output_record.fds[0];
356 attrs[11] = frame_buffer_size_.width();
357 attrs[13] = output_record.fds[1];
359 attrs[17] = frame_buffer_size_.width();
361 EGLImageKHR egl_image = eglCreateImageKHR(
362 egl_display_, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attrs);
363 if (egl_image == EGL_NO_IMAGE_KHR) {
364 DLOG(ERROR) << "AssignPictureBuffers(): could not create EGLImageKHR";
365 // Ownership of EGLImages allocated in previous iterations of this loop
366 // has been transferred to output_buffer_map_. After we error-out here
367 // the destructor will handle their cleanup.
368 NOTIFY_ERROR(PLATFORM_FAILURE);
372 glBindTexture(GL_TEXTURE_EXTERNAL_OES, buffers[i].texture_id());
373 glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, egl_image);
375 output_record.egl_image = egl_image;
376 output_record.picture_id = buffers[i].id();
377 free_output_buffers_.push(i);
378 DVLOG(3) << "AssignPictureBuffers(): buffer[" << i
379 << "]: picture_id=" << output_record.picture_id;
382 pictures_assigned_.Signal();
385 void V4L2VideoDecodeAccelerator::ReusePictureBuffer(int32 picture_buffer_id) {
386 DVLOG(3) << "ReusePictureBuffer(): picture_buffer_id=" << picture_buffer_id;
387 // Must be run on child thread, as we'll insert a sync in the EGL context.
388 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
390 if (!make_context_current_.Run()) {
391 DLOG(ERROR) << "ReusePictureBuffer(): could not make context current";
392 NOTIFY_ERROR(PLATFORM_FAILURE);
396 EGLSyncKHR egl_sync =
397 eglCreateSyncKHR(egl_display_, EGL_SYNC_FENCE_KHR, NULL);
398 if (egl_sync == EGL_NO_SYNC_KHR) {
399 DLOG(ERROR) << "ReusePictureBuffer(): eglCreateSyncKHR() failed";
400 NOTIFY_ERROR(PLATFORM_FAILURE);
404 scoped_ptr<EGLSyncKHRRef> egl_sync_ref(new EGLSyncKHRRef(
405 egl_display_, egl_sync));
406 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
407 &V4L2VideoDecodeAccelerator::ReusePictureBufferTask,
408 base::Unretained(this), picture_buffer_id, base::Passed(&egl_sync_ref)));
411 void V4L2VideoDecodeAccelerator::Flush() {
412 DVLOG(3) << "Flush()";
413 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
414 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
415 &V4L2VideoDecodeAccelerator::FlushTask, base::Unretained(this)));
418 void V4L2VideoDecodeAccelerator::Reset() {
419 DVLOG(3) << "Reset()";
420 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
421 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
422 &V4L2VideoDecodeAccelerator::ResetTask, base::Unretained(this)));
425 void V4L2VideoDecodeAccelerator::Destroy() {
426 DVLOG(3) << "Destroy()";
427 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
429 // We're destroying; cancel all callbacks.
430 client_ptr_factory_.InvalidateWeakPtrs();
432 // If the decoder thread is running, destroy using posted task.
433 if (decoder_thread_.IsRunning()) {
434 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
435 &V4L2VideoDecodeAccelerator::DestroyTask, base::Unretained(this)));
436 pictures_assigned_.Signal();
437 // DestroyTask() will cause the decoder_thread_ to flush all tasks.
438 decoder_thread_.Stop();
440 // Otherwise, call the destroy task directly.
444 // Set to kError state just in case.
445 SetDecoderState(kError);
450 bool V4L2VideoDecodeAccelerator::CanDecodeOnIOThread() { return true; }
452 void V4L2VideoDecodeAccelerator::DecodeTask(
453 const media::BitstreamBuffer& bitstream_buffer) {
454 DVLOG(3) << "DecodeTask(): input_id=" << bitstream_buffer.id();
455 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
456 DCHECK_NE(decoder_state_, kUninitialized);
457 TRACE_EVENT1("Video Decoder", "V4L2VDA::DecodeTask", "input_id",
458 bitstream_buffer.id());
460 scoped_ptr<BitstreamBufferRef> bitstream_record(new BitstreamBufferRef(
461 io_client_, io_message_loop_proxy_,
462 new base::SharedMemory(bitstream_buffer.handle(), true),
463 bitstream_buffer.size(), bitstream_buffer.id()));
464 if (!bitstream_record->shm->Map(bitstream_buffer.size())) {
465 DLOG(ERROR) << "Decode(): could not map bitstream_buffer";
466 NOTIFY_ERROR(UNREADABLE_INPUT);
469 DVLOG(3) << "DecodeTask(): mapped at=" << bitstream_record->shm->memory();
471 if (decoder_state_ == kResetting || decoder_flushing_) {
472 // In the case that we're resetting or flushing, we need to delay decoding
473 // the BitstreamBuffers that come after the Reset() or Flush() call. When
474 // we're here, we know that this DecodeTask() was scheduled by a Decode()
475 // call that came after (in the client thread) the Reset() or Flush() call;
476 // thus set up the delay if necessary.
477 if (decoder_delay_bitstream_buffer_id_ == -1)
478 decoder_delay_bitstream_buffer_id_ = bitstream_record->input_id;
479 } else if (decoder_state_ == kError) {
480 DVLOG(2) << "DecodeTask(): early out: kError state";
484 decoder_input_queue_.push(
485 linked_ptr<BitstreamBufferRef>(bitstream_record.release()));
486 decoder_decode_buffer_tasks_scheduled_++;
490 void V4L2VideoDecodeAccelerator::DecodeBufferTask() {
491 DVLOG(3) << "DecodeBufferTask()";
492 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
493 DCHECK_NE(decoder_state_, kUninitialized);
494 TRACE_EVENT0("Video Decoder", "V4L2VDA::DecodeBufferTask");
496 decoder_decode_buffer_tasks_scheduled_--;
498 if (decoder_state_ == kResetting) {
499 DVLOG(2) << "DecodeBufferTask(): early out: kResetting state";
501 } else if (decoder_state_ == kError) {
502 DVLOG(2) << "DecodeBufferTask(): early out: kError state";
504 } else if (decoder_state_ == kChangingResolution) {
505 DVLOG(2) << "DecodeBufferTask(): early out: resolution change pending";
509 if (decoder_current_bitstream_buffer_ == NULL) {
510 if (decoder_input_queue_.empty()) {
511 // We're waiting for a new buffer -- exit without scheduling a new task.
514 linked_ptr<BitstreamBufferRef>& buffer_ref = decoder_input_queue_.front();
515 if (decoder_delay_bitstream_buffer_id_ == buffer_ref->input_id) {
516 // We're asked to delay decoding on this and subsequent buffers.
520 // Setup to use the next buffer.
521 decoder_current_bitstream_buffer_.reset(buffer_ref.release());
522 decoder_input_queue_.pop();
523 DVLOG(3) << "DecodeBufferTask(): reading input_id="
524 << decoder_current_bitstream_buffer_->input_id
525 << ", addr=" << (decoder_current_bitstream_buffer_->shm ?
526 decoder_current_bitstream_buffer_->shm->memory() :
528 << ", size=" << decoder_current_bitstream_buffer_->size;
530 bool schedule_task = false;
531 const size_t size = decoder_current_bitstream_buffer_->size;
532 size_t decoded_size = 0;
534 const int32 input_id = decoder_current_bitstream_buffer_->input_id;
536 // This is a buffer queued from the client that has zero size. Skip.
537 schedule_task = true;
539 // This is a buffer of zero size, queued to flush the pipe. Flush.
540 DCHECK_EQ(decoder_current_bitstream_buffer_->shm.get(),
541 static_cast<base::SharedMemory*>(NULL));
542 // Enqueue a buffer guaranteed to be empty. To do that, we flush the
543 // current input, enqueue no data to the next frame, then flush that down.
544 schedule_task = true;
545 if (decoder_current_input_buffer_ != -1 &&
546 input_buffer_map_[decoder_current_input_buffer_].input_id !=
548 schedule_task = FlushInputFrame();
550 if (schedule_task && AppendToInputFrame(NULL, 0) && FlushInputFrame()) {
551 DVLOG(2) << "DecodeBufferTask(): enqueued flush buffer";
552 decoder_partial_frame_pending_ = false;
553 schedule_task = true;
555 // If we failed to enqueue the empty buffer (due to pipeline
556 // backpressure), don't advance the bitstream buffer queue, and don't
557 // schedule the next task. This bitstream buffer queue entry will get
558 // reprocessed when the pipeline frees up.
559 schedule_task = false;
563 // This is a buffer queued from the client, with actual contents. Decode.
564 const uint8* const data =
565 reinterpret_cast<const uint8*>(
566 decoder_current_bitstream_buffer_->shm->memory()) +
567 decoder_current_bitstream_buffer_->bytes_used;
568 const size_t data_size =
569 decoder_current_bitstream_buffer_->size -
570 decoder_current_bitstream_buffer_->bytes_used;
571 if (!AdvanceFrameFragment(data, data_size, &decoded_size)) {
572 NOTIFY_ERROR(UNREADABLE_INPUT);
575 // AdvanceFrameFragment should not return a size larger than the buffer
576 // size, even on invalid data.
577 CHECK_LE(decoded_size, data_size);
579 switch (decoder_state_) {
582 schedule_task = DecodeBufferInitial(data, decoded_size, &decoded_size);
585 schedule_task = DecodeBufferContinue(data, decoded_size);
588 NOTIFY_ERROR(ILLEGAL_STATE);
592 if (decoder_state_ == kError) {
593 // Failed during decode.
598 decoder_current_bitstream_buffer_->bytes_used += decoded_size;
599 if (decoder_current_bitstream_buffer_->bytes_used ==
600 decoder_current_bitstream_buffer_->size) {
601 // Our current bitstream buffer is done; return it.
602 int32 input_id = decoder_current_bitstream_buffer_->input_id;
603 DVLOG(3) << "DecodeBufferTask(): finished input_id=" << input_id;
604 // BitstreamBufferRef destructor calls NotifyEndOfBitstreamBuffer().
605 decoder_current_bitstream_buffer_.reset();
607 ScheduleDecodeBufferTaskIfNeeded();
611 bool V4L2VideoDecodeAccelerator::AdvanceFrameFragment(
615 if (video_profile_ >= media::H264PROFILE_MIN &&
616 video_profile_ <= media::H264PROFILE_MAX) {
617 // For H264, we need to feed HW one frame at a time. This is going to take
618 // some parsing of our input stream.
619 decoder_h264_parser_->SetStream(data, size);
620 media::H264NALU nalu;
621 media::H264Parser::Result result;
624 // Keep on peeking the next NALs while they don't indicate a frame
627 bool end_of_frame = false;
628 result = decoder_h264_parser_->AdvanceToNextNALU(&nalu);
629 if (result == media::H264Parser::kInvalidStream ||
630 result == media::H264Parser::kUnsupportedStream)
632 if (result == media::H264Parser::kEOStream) {
633 // We've reached the end of the buffer before finding a frame boundary.
634 decoder_partial_frame_pending_ = true;
637 switch (nalu.nal_unit_type) {
638 case media::H264NALU::kNonIDRSlice:
639 case media::H264NALU::kIDRSlice:
642 // For these two, if the "first_mb_in_slice" field is zero, start a
643 // new frame and return. This field is Exp-Golomb coded starting on
644 // the eighth data bit of the NAL; a zero value is encoded with a
645 // leading '1' bit in the byte, which we can detect as the byte being
646 // (unsigned) greater than or equal to 0x80.
647 if (nalu.data[1] >= 0x80) {
652 case media::H264NALU::kSPS:
653 case media::H264NALU::kPPS:
654 case media::H264NALU::kEOSeq:
655 case media::H264NALU::kEOStream:
656 // These unconditionally signal a frame boundary.
660 // For all others, keep going.
664 if (!decoder_partial_frame_pending_ && *endpos == 0) {
665 // The frame was previously restarted, and we haven't filled the
666 // current frame with any contents yet. Start the new frame here and
667 // continue parsing NALs.
669 // The frame wasn't previously restarted and/or we have contents for
670 // the current frame; signal the start of a new frame here: we don't
671 // have a partial frame anymore.
672 decoder_partial_frame_pending_ = false;
676 *endpos = (nalu.data + nalu.size) - data;
681 DCHECK_GE(video_profile_, media::VP8PROFILE_MIN);
682 DCHECK_LE(video_profile_, media::VP8PROFILE_MAX);
683 // For VP8, we can just dump the entire buffer. No fragmentation needed,
684 // and we never return a partial frame.
686 decoder_partial_frame_pending_ = false;
691 void V4L2VideoDecodeAccelerator::ScheduleDecodeBufferTaskIfNeeded() {
692 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
694 // If we're behind on tasks, schedule another one.
695 int buffers_to_decode = decoder_input_queue_.size();
696 if (decoder_current_bitstream_buffer_ != NULL)
698 if (decoder_decode_buffer_tasks_scheduled_ < buffers_to_decode) {
699 decoder_decode_buffer_tasks_scheduled_++;
700 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
701 &V4L2VideoDecodeAccelerator::DecodeBufferTask,
702 base::Unretained(this)));
706 bool V4L2VideoDecodeAccelerator::DecodeBufferInitial(
707 const void* data, size_t size, size_t* endpos) {
708 DVLOG(3) << "DecodeBufferInitial(): data=" << data << ", size=" << size;
709 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
710 DCHECK_NE(decoder_state_, kUninitialized);
711 DCHECK_NE(decoder_state_, kDecoding);
712 DCHECK(!device_poll_thread_.IsRunning());
713 // Initial decode. We haven't been able to get output stream format info yet.
714 // Get it, and start decoding.
716 // Copy in and send to HW.
717 if (!AppendToInputFrame(data, size))
720 // If we only have a partial frame, don't flush and process yet.
721 if (decoder_partial_frame_pending_)
724 if (!FlushInputFrame())
730 // Check and see if we have format info yet.
731 struct v4l2_format format;
733 if (!GetFormatInfo(&format, &again))
737 // Need more stream to decode format, return true and schedule next buffer.
742 // Run this initialization only on first startup.
743 if (decoder_state_ == kInitialized) {
744 DVLOG(3) << "DecodeBufferInitial(): running initialization";
745 // Success! Setup our parameters.
746 if (!CreateBuffersForFormat(format))
749 // We expect to process the initial buffer once during stream init to
750 // configure stream parameters, but will not consume the steam data on that
751 // iteration. Subsequent iterations (including after reset) do not require
752 // the stream init step.
758 // StartDevicePoll will raise the error if there is one.
759 if (!StartDevicePoll())
762 decoder_state_ = kDecoding;
763 ScheduleDecodeBufferTaskIfNeeded();
767 bool V4L2VideoDecodeAccelerator::DecodeBufferContinue(
768 const void* data, size_t size) {
769 DVLOG(3) << "DecodeBufferContinue(): data=" << data << ", size=" << size;
770 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
771 DCHECK_EQ(decoder_state_, kDecoding);
773 // Both of these calls will set kError state if they fail.
774 // Only flush the frame if it's complete.
775 return (AppendToInputFrame(data, size) &&
776 (decoder_partial_frame_pending_ || FlushInputFrame()));
779 bool V4L2VideoDecodeAccelerator::AppendToInputFrame(
780 const void* data, size_t size) {
781 DVLOG(3) << "AppendToInputFrame()";
782 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
783 DCHECK_NE(decoder_state_, kUninitialized);
784 DCHECK_NE(decoder_state_, kResetting);
785 DCHECK_NE(decoder_state_, kError);
786 // This routine can handle data == NULL and size == 0, which occurs when
787 // we queue an empty buffer for the purposes of flushing the pipe.
789 // Flush if we're too big
790 if (decoder_current_input_buffer_ != -1) {
791 InputRecord& input_record =
792 input_buffer_map_[decoder_current_input_buffer_];
793 if (input_record.bytes_used + size > input_record.length) {
794 if (!FlushInputFrame())
796 decoder_current_input_buffer_ = -1;
800 // Try to get an available input buffer
801 if (decoder_current_input_buffer_ == -1) {
802 if (free_input_buffers_.empty()) {
803 // See if we can get more free buffers from HW
805 if (free_input_buffers_.empty()) {
807 DVLOG(2) << "AppendToInputFrame(): stalled for input buffers";
811 decoder_current_input_buffer_ = free_input_buffers_.back();
812 free_input_buffers_.pop_back();
813 InputRecord& input_record =
814 input_buffer_map_[decoder_current_input_buffer_];
815 DCHECK_EQ(input_record.bytes_used, 0);
816 DCHECK_EQ(input_record.input_id, -1);
817 DCHECK(decoder_current_bitstream_buffer_ != NULL);
818 input_record.input_id = decoder_current_bitstream_buffer_->input_id;
821 DCHECK(data != NULL || size == 0);
823 // If we asked for an empty buffer, return now. We return only after
824 // getting the next input buffer, since we might actually want an empty
825 // input buffer for flushing purposes.
829 // Copy in to the buffer.
830 InputRecord& input_record =
831 input_buffer_map_[decoder_current_input_buffer_];
832 if (size > input_record.length - input_record.bytes_used) {
833 LOG(ERROR) << "AppendToInputFrame(): over-size frame, erroring";
834 NOTIFY_ERROR(UNREADABLE_INPUT);
838 reinterpret_cast<uint8*>(input_record.address) + input_record.bytes_used,
841 input_record.bytes_used += size;
846 bool V4L2VideoDecodeAccelerator::FlushInputFrame() {
847 DVLOG(3) << "FlushInputFrame()";
848 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
849 DCHECK_NE(decoder_state_, kUninitialized);
850 DCHECK_NE(decoder_state_, kResetting);
851 DCHECK_NE(decoder_state_, kError);
853 if (decoder_current_input_buffer_ == -1)
856 InputRecord& input_record =
857 input_buffer_map_[decoder_current_input_buffer_];
858 DCHECK_NE(input_record.input_id, -1);
859 DCHECK(input_record.input_id != kFlushBufferId ||
860 input_record.bytes_used == 0);
861 // * if input_id >= 0, this input buffer was prompted by a bitstream buffer we
862 // got from the client. We can skip it if it is empty.
863 // * if input_id < 0 (should be kFlushBufferId in this case), this input
864 // buffer was prompted by a flush buffer, and should be queued even when
866 if (input_record.input_id >= 0 && input_record.bytes_used == 0) {
867 input_record.input_id = -1;
868 free_input_buffers_.push_back(decoder_current_input_buffer_);
869 decoder_current_input_buffer_ = -1;
874 input_ready_queue_.push(decoder_current_input_buffer_);
875 decoder_current_input_buffer_ = -1;
876 DVLOG(3) << "FlushInputFrame(): submitting input_id="
877 << input_record.input_id;
878 // Enqueue once since there's new available input for it.
881 return (decoder_state_ != kError);
884 void V4L2VideoDecodeAccelerator::ServiceDeviceTask(bool event_pending) {
885 DVLOG(3) << "ServiceDeviceTask()";
886 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
887 DCHECK_NE(decoder_state_, kUninitialized);
888 DCHECK_NE(decoder_state_, kInitialized);
889 DCHECK_NE(decoder_state_, kAfterReset);
890 TRACE_EVENT0("Video Decoder", "V4L2VDA::ServiceDeviceTask");
892 if (decoder_state_ == kResetting) {
893 DVLOG(2) << "ServiceDeviceTask(): early out: kResetting state";
895 } else if (decoder_state_ == kError) {
896 DVLOG(2) << "ServiceDeviceTask(): early out: kError state";
898 } else if (decoder_state_ == kChangingResolution) {
899 DVLOG(2) << "ServiceDeviceTask(): early out: kChangingResolution state";
908 // Clear the interrupt fd.
909 if (!device_->ClearDevicePollInterrupt()) {
910 NOTIFY_ERROR(PLATFORM_FAILURE);
914 bool poll_device = false;
915 // Add fd, if we should poll on it.
916 // Can be polled as soon as either input or output buffers are queued.
917 if (input_buffer_queued_count_ + output_buffer_queued_count_ > 0)
920 // ServiceDeviceTask() should only ever be scheduled from DevicePollTask(),
922 // * device_poll_thread_ is running normally
923 // * device_poll_thread_ scheduled us, but then a ResetTask() or DestroyTask()
924 // shut it down, in which case we're either in kResetting or kError states
925 // respectively, and we should have early-outed already.
926 DCHECK(device_poll_thread_.message_loop());
927 // Queue the DevicePollTask() now.
928 device_poll_thread_.message_loop()->PostTask(
930 base::Bind(&V4L2VideoDecodeAccelerator::DevicePollTask,
931 base::Unretained(this),
934 DVLOG(1) << "ServiceDeviceTask(): buffer counts: DEC["
935 << decoder_input_queue_.size() << "->"
936 << input_ready_queue_.size() << "] => DEVICE["
937 << free_input_buffers_.size() << "+"
938 << input_buffer_queued_count_ << "/"
939 << input_buffer_map_.size() << "->"
940 << free_output_buffers_.size() << "+"
941 << output_buffer_queued_count_ << "/"
942 << output_buffer_map_.size() << "] => VDA["
943 << decoder_frames_at_client_ << "]";
945 ScheduleDecodeBufferTaskIfNeeded();
946 StartResolutionChangeIfNeeded();
949 void V4L2VideoDecodeAccelerator::Enqueue() {
950 DVLOG(3) << "Enqueue()";
951 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
952 DCHECK_NE(decoder_state_, kUninitialized);
953 TRACE_EVENT0("Video Decoder", "V4L2VDA::Enqueue");
955 // Drain the pipe of completed decode buffers.
956 const int old_inputs_queued = input_buffer_queued_count_;
957 while (!input_ready_queue_.empty()) {
958 if (!EnqueueInputRecord())
961 if (old_inputs_queued == 0 && input_buffer_queued_count_ != 0) {
962 // We just started up a previously empty queue.
963 // Queue state changed; signal interrupt.
964 if (!device_->SetDevicePollInterrupt()) {
965 DPLOG(ERROR) << "SetDevicePollInterrupt(): failed";
966 NOTIFY_ERROR(PLATFORM_FAILURE);
969 // Start VIDIOC_STREAMON if we haven't yet.
970 if (!input_streamon_) {
971 __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
972 IOCTL_OR_ERROR_RETURN(VIDIOC_STREAMON, &type);
973 input_streamon_ = true;
977 // Enqueue all the outputs we can.
978 const int old_outputs_queued = output_buffer_queued_count_;
979 while (!free_output_buffers_.empty()) {
980 if (!EnqueueOutputRecord())
983 if (old_outputs_queued == 0 && output_buffer_queued_count_ != 0) {
984 // We just started up a previously empty queue.
985 // Queue state changed; signal interrupt.
986 if (!device_->SetDevicePollInterrupt()) {
987 DPLOG(ERROR) << "SetDevicePollInterrupt(): failed";
988 NOTIFY_ERROR(PLATFORM_FAILURE);
991 // Start VIDIOC_STREAMON if we haven't yet.
992 if (!output_streamon_) {
993 __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
994 IOCTL_OR_ERROR_RETURN(VIDIOC_STREAMON, &type);
995 output_streamon_ = true;
1000 void V4L2VideoDecodeAccelerator::DequeueEvents() {
1001 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1002 DCHECK_NE(decoder_state_, kUninitialized);
1003 DVLOG(3) << "DequeueEvents()";
1005 struct v4l2_event ev;
1006 memset(&ev, 0, sizeof(ev));
1008 while (device_->Ioctl(VIDIOC_DQEVENT, &ev) == 0) {
1009 if (ev.type == V4L2_EVENT_RESOLUTION_CHANGE) {
1010 DVLOG(3) << "DequeueEvents(): got resolution change event.";
1011 DCHECK(!resolution_change_pending_);
1012 resolution_change_pending_ = true;
1014 DLOG(FATAL) << "DequeueEvents(): got an event (" << ev.type
1015 << ") we haven't subscribed to.";
1020 void V4L2VideoDecodeAccelerator::Dequeue() {
1021 DVLOG(3) << "Dequeue()";
1022 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1023 DCHECK_NE(decoder_state_, kUninitialized);
1024 TRACE_EVENT0("Video Decoder", "V4L2VDA::Dequeue");
1026 // Dequeue completed input (VIDEO_OUTPUT) buffers, and recycle to the free
1028 struct v4l2_buffer dqbuf;
1029 struct v4l2_plane planes[2];
1030 while (input_buffer_queued_count_ > 0) {
1031 DCHECK(input_streamon_);
1032 memset(&dqbuf, 0, sizeof(dqbuf));
1033 memset(planes, 0, sizeof(planes));
1034 dqbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1035 dqbuf.memory = V4L2_MEMORY_MMAP;
1036 dqbuf.m.planes = planes;
1038 if (device_->Ioctl(VIDIOC_DQBUF, &dqbuf) != 0) {
1039 if (errno == EAGAIN) {
1040 // EAGAIN if we're just out of buffers to dequeue.
1043 DPLOG(ERROR) << "Dequeue(): ioctl() failed: VIDIOC_DQBUF";
1044 NOTIFY_ERROR(PLATFORM_FAILURE);
1047 InputRecord& input_record = input_buffer_map_[dqbuf.index];
1048 DCHECK(input_record.at_device);
1049 free_input_buffers_.push_back(dqbuf.index);
1050 input_record.at_device = false;
1051 input_record.bytes_used = 0;
1052 input_record.input_id = -1;
1053 input_buffer_queued_count_--;
1056 // Dequeue completed output (VIDEO_CAPTURE) buffers, and queue to the
1058 while (output_buffer_queued_count_ > 0) {
1059 DCHECK(output_streamon_);
1060 memset(&dqbuf, 0, sizeof(dqbuf));
1061 memset(planes, 0, sizeof(planes));
1062 dqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1063 dqbuf.memory = V4L2_MEMORY_MMAP;
1064 dqbuf.m.planes = planes;
1066 if (device_->Ioctl(VIDIOC_DQBUF, &dqbuf) != 0) {
1067 if (errno == EAGAIN) {
1068 // EAGAIN if we're just out of buffers to dequeue.
1071 DPLOG(ERROR) << "Dequeue(): ioctl() failed: VIDIOC_DQBUF";
1072 NOTIFY_ERROR(PLATFORM_FAILURE);
1075 OutputRecord& output_record = output_buffer_map_[dqbuf.index];
1076 DCHECK(output_record.at_device);
1077 DCHECK(!output_record.at_client);
1078 DCHECK_NE(output_record.egl_image, EGL_NO_IMAGE_KHR);
1079 DCHECK_NE(output_record.picture_id, -1);
1080 output_record.at_device = false;
1081 if (dqbuf.m.planes[0].bytesused + dqbuf.m.planes[1].bytesused == 0) {
1082 // This is an empty output buffer returned as part of a flush.
1083 free_output_buffers_.push(dqbuf.index);
1085 DCHECK_GE(dqbuf.timestamp.tv_sec, 0);
1086 output_record.at_client = true;
1087 DVLOG(3) << "Dequeue(): returning input_id=" << dqbuf.timestamp.tv_sec
1088 << " as picture_id=" << output_record.picture_id;
1089 const media::Picture& picture =
1090 media::Picture(output_record.picture_id, dqbuf.timestamp.tv_sec);
1091 pending_picture_ready_.push(
1092 PictureRecord(output_record.cleared, picture));
1094 output_record.cleared = true;
1095 decoder_frames_at_client_++;
1097 output_buffer_queued_count_--;
1100 NotifyFlushDoneIfNeeded();
1103 bool V4L2VideoDecodeAccelerator::EnqueueInputRecord() {
1104 DVLOG(3) << "EnqueueInputRecord()";
1105 DCHECK(!input_ready_queue_.empty());
1107 // Enqueue an input (VIDEO_OUTPUT) buffer.
1108 const int buffer = input_ready_queue_.front();
1109 InputRecord& input_record = input_buffer_map_[buffer];
1110 DCHECK(!input_record.at_device);
1111 struct v4l2_buffer qbuf;
1112 struct v4l2_plane qbuf_plane;
1113 memset(&qbuf, 0, sizeof(qbuf));
1114 memset(&qbuf_plane, 0, sizeof(qbuf_plane));
1115 qbuf.index = buffer;
1116 qbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1117 qbuf.timestamp.tv_sec = input_record.input_id;
1118 qbuf.memory = V4L2_MEMORY_MMAP;
1119 qbuf.m.planes = &qbuf_plane;
1120 qbuf.m.planes[0].bytesused = input_record.bytes_used;
1122 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QBUF, &qbuf);
1123 input_ready_queue_.pop();
1124 input_record.at_device = true;
1125 input_buffer_queued_count_++;
1126 DVLOG(3) << "EnqueueInputRecord(): enqueued input_id="
1127 << input_record.input_id << " size=" << input_record.bytes_used;
1131 bool V4L2VideoDecodeAccelerator::EnqueueOutputRecord() {
1132 DVLOG(3) << "EnqueueOutputRecord()";
1133 DCHECK(!free_output_buffers_.empty());
1135 // Enqueue an output (VIDEO_CAPTURE) buffer.
1136 const int buffer = free_output_buffers_.front();
1137 OutputRecord& output_record = output_buffer_map_[buffer];
1138 DCHECK(!output_record.at_device);
1139 DCHECK(!output_record.at_client);
1140 DCHECK_NE(output_record.egl_image, EGL_NO_IMAGE_KHR);
1141 DCHECK_NE(output_record.picture_id, -1);
1142 if (output_record.egl_sync != EGL_NO_SYNC_KHR) {
1143 TRACE_EVENT0("Video Decoder",
1144 "V4L2VDA::EnqueueOutputRecord: eglClientWaitSyncKHR");
1145 // If we have to wait for completion, wait. Note that
1146 // free_output_buffers_ is a FIFO queue, so we always wait on the
1147 // buffer that has been in the queue the longest.
1148 if (eglClientWaitSyncKHR(egl_display_, output_record.egl_sync, 0,
1149 EGL_FOREVER_KHR) == EGL_FALSE) {
1150 // This will cause tearing, but is safe otherwise.
1151 DVLOG(1) << __func__ << " eglClientWaitSyncKHR failed!";
1153 if (eglDestroySyncKHR(egl_display_, output_record.egl_sync) != EGL_TRUE) {
1154 DLOG(FATAL) << __func__ << " eglDestroySyncKHR failed!";
1155 NOTIFY_ERROR(PLATFORM_FAILURE);
1158 output_record.egl_sync = EGL_NO_SYNC_KHR;
1160 struct v4l2_buffer qbuf;
1161 struct v4l2_plane qbuf_planes[arraysize(output_record.fds)];
1162 memset(&qbuf, 0, sizeof(qbuf));
1163 memset(qbuf_planes, 0, sizeof(qbuf_planes));
1164 qbuf.index = buffer;
1165 qbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1166 qbuf.memory = V4L2_MEMORY_MMAP;
1167 qbuf.m.planes = qbuf_planes;
1168 qbuf.length = arraysize(output_record.fds);
1169 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QBUF, &qbuf);
1170 free_output_buffers_.pop();
1171 output_record.at_device = true;
1172 output_buffer_queued_count_++;
1176 void V4L2VideoDecodeAccelerator::ReusePictureBufferTask(
1177 int32 picture_buffer_id, scoped_ptr<EGLSyncKHRRef> egl_sync_ref) {
1178 DVLOG(3) << "ReusePictureBufferTask(): picture_buffer_id="
1179 << picture_buffer_id;
1180 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1181 TRACE_EVENT0("Video Decoder", "V4L2VDA::ReusePictureBufferTask");
1183 // We run ReusePictureBufferTask even if we're in kResetting.
1184 if (decoder_state_ == kError) {
1185 DVLOG(2) << "ReusePictureBufferTask(): early out: kError state";
1189 if (decoder_state_ == kChangingResolution) {
1190 DVLOG(2) << "ReusePictureBufferTask(): early out: kChangingResolution";
1195 for (index = 0; index < output_buffer_map_.size(); ++index)
1196 if (output_buffer_map_[index].picture_id == picture_buffer_id)
1199 if (index >= output_buffer_map_.size()) {
1200 // It's possible that we've already posted a DismissPictureBuffer for this
1201 // picture, but it has not yet executed when this ReusePictureBuffer was
1202 // posted to us by the client. In that case just ignore this (we've already
1203 // dismissed it and accounted for that) and let the sync object get
1205 DVLOG(4) << "ReusePictureBufferTask(): got picture id= "
1206 << picture_buffer_id << " not in use (anymore?).";
1210 OutputRecord& output_record = output_buffer_map_[index];
1211 if (output_record.at_device || !output_record.at_client) {
1212 DLOG(ERROR) << "ReusePictureBufferTask(): picture_buffer_id not reusable";
1213 NOTIFY_ERROR(INVALID_ARGUMENT);
1217 DCHECK_EQ(output_record.egl_sync, EGL_NO_SYNC_KHR);
1218 DCHECK(!output_record.at_device);
1219 output_record.at_client = false;
1220 output_record.egl_sync = egl_sync_ref->egl_sync;
1221 free_output_buffers_.push(index);
1222 decoder_frames_at_client_--;
1223 // Take ownership of the EGLSync.
1224 egl_sync_ref->egl_sync = EGL_NO_SYNC_KHR;
1225 // We got a buffer back, so enqueue it back.
1229 void V4L2VideoDecodeAccelerator::FlushTask() {
1230 DVLOG(3) << "FlushTask()";
1231 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1232 TRACE_EVENT0("Video Decoder", "V4L2VDA::FlushTask");
1234 // Flush outstanding buffers.
1235 if (decoder_state_ == kInitialized || decoder_state_ == kAfterReset) {
1236 // There's nothing in the pipe, so return done immediately.
1237 DVLOG(3) << "FlushTask(): returning flush";
1238 child_message_loop_proxy_->PostTask(
1239 FROM_HERE, base::Bind(&Client::NotifyFlushDone, client_));
1241 } else if (decoder_state_ == kError) {
1242 DVLOG(2) << "FlushTask(): early out: kError state";
1246 // We don't support stacked flushing.
1247 DCHECK(!decoder_flushing_);
1249 // Queue up an empty buffer -- this triggers the flush.
1250 decoder_input_queue_.push(
1251 linked_ptr<BitstreamBufferRef>(new BitstreamBufferRef(
1252 io_client_, io_message_loop_proxy_, NULL, 0, kFlushBufferId)));
1253 decoder_flushing_ = true;
1254 SendPictureReady(); // Send all pending PictureReady.
1256 ScheduleDecodeBufferTaskIfNeeded();
1259 void V4L2VideoDecodeAccelerator::NotifyFlushDoneIfNeeded() {
1260 if (!decoder_flushing_)
1263 // Pipeline is empty when:
1264 // * Decoder input queue is empty of non-delayed buffers.
1265 // * There is no currently filling input buffer.
1266 // * Input holding queue is empty.
1267 // * All input (VIDEO_OUTPUT) buffers are returned.
1268 if (!decoder_input_queue_.empty()) {
1269 if (decoder_input_queue_.front()->input_id !=
1270 decoder_delay_bitstream_buffer_id_)
1273 if (decoder_current_input_buffer_ != -1)
1275 if ((input_ready_queue_.size() + input_buffer_queued_count_) != 0)
1278 // TODO(posciak): crbug.com/270039. Exynos requires a streamoff-streamon
1279 // sequence after flush to continue, even if we are not resetting. This would
1280 // make sense, because we don't really want to resume from a non-resume point
1281 // (e.g. not from an IDR) if we are flushed.
1282 // MSE player however triggers a Flush() on chunk end, but never Reset(). One
1283 // could argue either way, or even say that Flush() is not needed/harmful when
1284 // transitioning to next chunk.
1285 // For now, do the streamoff-streamon cycle to satisfy Exynos and not freeze
1286 // when doing MSE. This should be harmless otherwise.
1287 if (!StopDevicePoll(false))
1290 if (!StartDevicePoll())
1293 decoder_delay_bitstream_buffer_id_ = -1;
1294 decoder_flushing_ = false;
1295 DVLOG(3) << "NotifyFlushDoneIfNeeded(): returning flush";
1296 child_message_loop_proxy_->PostTask(
1297 FROM_HERE, base::Bind(&Client::NotifyFlushDone, client_));
1299 // While we were flushing, we early-outed DecodeBufferTask()s.
1300 ScheduleDecodeBufferTaskIfNeeded();
1303 void V4L2VideoDecodeAccelerator::ResetTask() {
1304 DVLOG(3) << "ResetTask()";
1305 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1306 TRACE_EVENT0("Video Decoder", "V4L2VDA::ResetTask");
1308 if (decoder_state_ == kError) {
1309 DVLOG(2) << "ResetTask(): early out: kError state";
1313 // If we are in the middle of switching resolutions, postpone reset until
1314 // it's done. We don't have to worry about timing of this wrt to decoding,
1315 // because input pipe is already stopped if we are changing resolution.
1316 // We will come back here after we are done with the resolution change.
1317 DCHECK(!resolution_change_reset_pending_);
1318 if (resolution_change_pending_ || decoder_state_ == kChangingResolution) {
1319 resolution_change_reset_pending_ = true;
1323 // We stop streaming and clear buffer tracking info (not preserving inputs).
1324 // StopDevicePoll() unconditionally does _not_ destroy buffers, however.
1325 if (!StopDevicePoll(false))
1328 decoder_current_bitstream_buffer_.reset();
1329 while (!decoder_input_queue_.empty())
1330 decoder_input_queue_.pop();
1332 decoder_current_input_buffer_ = -1;
1334 // If we were flushing, we'll never return any more BitstreamBuffers or
1335 // PictureBuffers; they have all been dropped and returned by now.
1336 NotifyFlushDoneIfNeeded();
1338 // Mark that we're resetting, then enqueue a ResetDoneTask(). All intervening
1339 // jobs will early-out in the kResetting state.
1340 decoder_state_ = kResetting;
1341 SendPictureReady(); // Send all pending PictureReady.
1342 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
1343 &V4L2VideoDecodeAccelerator::ResetDoneTask, base::Unretained(this)));
1346 void V4L2VideoDecodeAccelerator::ResetDoneTask() {
1347 DVLOG(3) << "ResetDoneTask()";
1348 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1349 TRACE_EVENT0("Video Decoder", "V4L2VDA::ResetDoneTask");
1351 if (decoder_state_ == kError) {
1352 DVLOG(2) << "ResetDoneTask(): early out: kError state";
1356 // We might have received a resolution change event while we were waiting
1357 // for the reset to finish. The codec will not post another event if the
1358 // resolution after reset remains the same as the one to which were just
1359 // about to switch, so preserve the event across reset so we can address
1360 // it after resuming.
1362 // Reset format-specific bits.
1363 if (video_profile_ >= media::H264PROFILE_MIN &&
1364 video_profile_ <= media::H264PROFILE_MAX) {
1365 decoder_h264_parser_.reset(new media::H264Parser());
1368 // Jobs drained, we're finished resetting.
1369 DCHECK_EQ(decoder_state_, kResetting);
1370 if (output_buffer_map_.empty()) {
1371 // We must have gotten Reset() before we had a chance to request buffers
1373 decoder_state_ = kInitialized;
1375 decoder_state_ = kAfterReset;
1378 decoder_partial_frame_pending_ = false;
1379 decoder_delay_bitstream_buffer_id_ = -1;
1380 child_message_loop_proxy_->PostTask(FROM_HERE, base::Bind(
1381 &Client::NotifyResetDone, client_));
1383 // While we were resetting, we early-outed DecodeBufferTask()s.
1384 ScheduleDecodeBufferTaskIfNeeded();
1387 void V4L2VideoDecodeAccelerator::DestroyTask() {
1388 DVLOG(3) << "DestroyTask()";
1389 TRACE_EVENT0("Video Decoder", "V4L2VDA::DestroyTask");
1391 // DestroyTask() should run regardless of decoder_state_.
1393 // Stop streaming and the device_poll_thread_.
1394 StopDevicePoll(false);
1396 decoder_current_bitstream_buffer_.reset();
1397 decoder_current_input_buffer_ = -1;
1398 decoder_decode_buffer_tasks_scheduled_ = 0;
1399 decoder_frames_at_client_ = 0;
1400 while (!decoder_input_queue_.empty())
1401 decoder_input_queue_.pop();
1402 decoder_flushing_ = false;
1404 // Set our state to kError. Just in case.
1405 decoder_state_ = kError;
1408 bool V4L2VideoDecodeAccelerator::StartDevicePoll() {
1409 DVLOG(3) << "StartDevicePoll()";
1410 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1411 DCHECK(!device_poll_thread_.IsRunning());
1413 // Start up the device poll thread and schedule its first DevicePollTask().
1414 if (!device_poll_thread_.Start()) {
1415 DLOG(ERROR) << "StartDevicePoll(): Device thread failed to start";
1416 NOTIFY_ERROR(PLATFORM_FAILURE);
1419 device_poll_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
1420 &V4L2VideoDecodeAccelerator::DevicePollTask,
1421 base::Unretained(this),
1427 bool V4L2VideoDecodeAccelerator::StopDevicePoll(bool keep_input_state) {
1428 DVLOG(3) << "StopDevicePoll()";
1429 if (decoder_thread_.IsRunning())
1430 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1432 // Signal the DevicePollTask() to stop, and stop the device poll thread.
1433 if (!device_->SetDevicePollInterrupt()) {
1434 DPLOG(ERROR) << "SetDevicePollInterrupt(): failed";
1435 NOTIFY_ERROR(PLATFORM_FAILURE);
1438 device_poll_thread_.Stop();
1439 // Clear the interrupt now, to be sure.
1440 if (!device_->ClearDevicePollInterrupt()) {
1441 NOTIFY_ERROR(PLATFORM_FAILURE);
1446 if (!keep_input_state) {
1447 if (input_streamon_) {
1448 __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1449 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_STREAMOFF, &type);
1451 input_streamon_ = false;
1453 if (output_streamon_) {
1454 __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1455 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_STREAMOFF, &type);
1457 output_streamon_ = false;
1459 // Reset all our accounting info.
1460 if (!keep_input_state) {
1461 while (!input_ready_queue_.empty())
1462 input_ready_queue_.pop();
1463 free_input_buffers_.clear();
1464 for (size_t i = 0; i < input_buffer_map_.size(); ++i) {
1465 free_input_buffers_.push_back(i);
1466 input_buffer_map_[i].at_device = false;
1467 input_buffer_map_[i].bytes_used = 0;
1468 input_buffer_map_[i].input_id = -1;
1470 input_buffer_queued_count_ = 0;
1473 while (!free_output_buffers_.empty())
1474 free_output_buffers_.pop();
1476 for (size_t i = 0; i < output_buffer_map_.size(); ++i) {
1477 OutputRecord& output_record = output_buffer_map_[i];
1478 DCHECK(!(output_record.at_client && output_record.at_device));
1480 // After streamoff, the device drops ownership of all buffers, even if
1481 // we don't dequeue them explicitly.
1482 output_buffer_map_[i].at_device = false;
1483 // Some of them may still be owned by the client however.
1484 // Reuse only those that aren't.
1485 if (!output_record.at_client) {
1486 DCHECK_EQ(output_record.egl_sync, EGL_NO_SYNC_KHR);
1487 free_output_buffers_.push(i);
1490 output_buffer_queued_count_ = 0;
1492 DVLOG(3) << "StopDevicePoll(): device poll stopped";
1496 void V4L2VideoDecodeAccelerator::StartResolutionChangeIfNeeded() {
1497 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1498 DCHECK_EQ(decoder_state_, kDecoding);
1500 if (!resolution_change_pending_)
1503 DVLOG(3) << "No more work, initiate resolution change";
1505 // Keep input queue.
1506 if (!StopDevicePoll(true))
1509 decoder_state_ = kChangingResolution;
1510 DCHECK(resolution_change_pending_);
1511 resolution_change_pending_ = false;
1513 // Post a task to clean up buffers on child thread. This will also ensure
1514 // that we won't accept ReusePictureBuffer() anymore after that.
1515 child_message_loop_proxy_->PostTask(FROM_HERE, base::Bind(
1516 &V4L2VideoDecodeAccelerator::ResolutionChangeDestroyBuffers,
1520 void V4L2VideoDecodeAccelerator::FinishResolutionChange() {
1521 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1522 DCHECK_EQ(decoder_state_, kChangingResolution);
1523 DVLOG(3) << "FinishResolutionChange()";
1525 if (decoder_state_ == kError) {
1526 DVLOG(2) << "FinishResolutionChange(): early out: kError state";
1530 struct v4l2_format format;
1532 bool ret = GetFormatInfo(&format, &again);
1533 if (!ret || again) {
1534 DVLOG(3) << "Couldn't get format information after resolution change";
1535 NOTIFY_ERROR(PLATFORM_FAILURE);
1539 if (!CreateBuffersForFormat(format)) {
1540 DVLOG(3) << "Couldn't reallocate buffers after resolution change";
1541 NOTIFY_ERROR(PLATFORM_FAILURE);
1545 decoder_state_ = kDecoding;
1547 if (resolution_change_reset_pending_) {
1548 resolution_change_reset_pending_ = false;
1553 if (!StartDevicePoll())
1557 ScheduleDecodeBufferTaskIfNeeded();
1560 void V4L2VideoDecodeAccelerator::DevicePollTask(bool poll_device) {
1561 DVLOG(3) << "DevicePollTask()";
1562 DCHECK_EQ(device_poll_thread_.message_loop(), base::MessageLoop::current());
1563 TRACE_EVENT0("Video Decoder", "V4L2VDA::DevicePollTask");
1565 bool event_pending = false;
1567 if (!device_->Poll(poll_device, &event_pending)) {
1568 NOTIFY_ERROR(PLATFORM_FAILURE);
1572 // All processing should happen on ServiceDeviceTask(), since we shouldn't
1573 // touch decoder state from this thread.
1574 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
1575 &V4L2VideoDecodeAccelerator::ServiceDeviceTask,
1576 base::Unretained(this), event_pending));
1579 void V4L2VideoDecodeAccelerator::NotifyError(Error error) {
1580 DVLOG(2) << "NotifyError()";
1582 if (!child_message_loop_proxy_->BelongsToCurrentThread()) {
1583 child_message_loop_proxy_->PostTask(FROM_HERE, base::Bind(
1584 &V4L2VideoDecodeAccelerator::NotifyError, weak_this_, error));
1589 client_->NotifyError(error);
1590 client_ptr_factory_.InvalidateWeakPtrs();
1594 void V4L2VideoDecodeAccelerator::SetDecoderState(State state) {
1595 DVLOG(3) << "SetDecoderState(): state=" << state;
1597 // We can touch decoder_state_ only if this is the decoder thread or the
1598 // decoder thread isn't running.
1599 if (decoder_thread_.message_loop() != NULL &&
1600 decoder_thread_.message_loop() != base::MessageLoop::current()) {
1601 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
1602 &V4L2VideoDecodeAccelerator::SetDecoderState,
1603 base::Unretained(this), state));
1605 decoder_state_ = state;
1609 bool V4L2VideoDecodeAccelerator::GetFormatInfo(struct v4l2_format* format,
1611 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1614 memset(format, 0, sizeof(*format));
1615 format->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1616 if (HANDLE_EINTR(device_->Ioctl(VIDIOC_G_FMT, format)) != 0) {
1617 if (errno == EINVAL) {
1618 // EINVAL means we haven't seen sufficient stream to decode the format.
1622 DPLOG(ERROR) << __func__ << "(): ioctl() failed: VIDIOC_G_FMT";
1623 NOTIFY_ERROR(PLATFORM_FAILURE);
1631 bool V4L2VideoDecodeAccelerator::CreateBuffersForFormat(
1632 const struct v4l2_format& format) {
1633 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1634 CHECK_EQ(format.fmt.pix_mp.num_planes, 2);
1635 frame_buffer_size_.SetSize(
1636 format.fmt.pix_mp.width, format.fmt.pix_mp.height);
1637 output_buffer_pixelformat_ = format.fmt.pix_mp.pixelformat;
1638 DCHECK_EQ(output_buffer_pixelformat_, V4L2_PIX_FMT_NV12M);
1639 DVLOG(3) << "CreateBuffersForFormat(): new resolution: "
1640 << frame_buffer_size_.ToString();
1642 if (!CreateOutputBuffers())
1648 bool V4L2VideoDecodeAccelerator::CreateInputBuffers() {
1649 DVLOG(3) << "CreateInputBuffers()";
1650 // We always run this as we prepare to initialize.
1651 DCHECK_EQ(decoder_state_, kUninitialized);
1652 DCHECK(!input_streamon_);
1653 DCHECK(input_buffer_map_.empty());
1655 __u32 pixelformat = 0;
1656 if (video_profile_ >= media::H264PROFILE_MIN &&
1657 video_profile_ <= media::H264PROFILE_MAX) {
1658 pixelformat = V4L2_PIX_FMT_H264;
1659 } else if (video_profile_ >= media::VP8PROFILE_MIN &&
1660 video_profile_ <= media::VP8PROFILE_MAX) {
1661 pixelformat = V4L2_PIX_FMT_VP8;
1666 struct v4l2_format format;
1667 memset(&format, 0, sizeof(format));
1668 format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1669 format.fmt.pix_mp.pixelformat = pixelformat;
1670 format.fmt.pix_mp.plane_fmt[0].sizeimage = kInputBufferMaxSize;
1671 format.fmt.pix_mp.num_planes = 1;
1672 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format);
1674 struct v4l2_requestbuffers reqbufs;
1675 memset(&reqbufs, 0, sizeof(reqbufs));
1676 reqbufs.count = kInputBufferCount;
1677 reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1678 reqbufs.memory = V4L2_MEMORY_MMAP;
1679 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);
1680 input_buffer_map_.resize(reqbufs.count);
1681 for (size_t i = 0; i < input_buffer_map_.size(); ++i) {
1682 free_input_buffers_.push_back(i);
1684 // Query for the MEMORY_MMAP pointer.
1685 struct v4l2_plane planes[1];
1686 struct v4l2_buffer buffer;
1687 memset(&buffer, 0, sizeof(buffer));
1688 memset(planes, 0, sizeof(planes));
1690 buffer.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1691 buffer.memory = V4L2_MEMORY_MMAP;
1692 buffer.m.planes = planes;
1694 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYBUF, &buffer);
1695 void* address = device_->Mmap(NULL,
1696 buffer.m.planes[0].length,
1697 PROT_READ | PROT_WRITE,
1699 buffer.m.planes[0].m.mem_offset);
1700 if (address == MAP_FAILED) {
1701 DPLOG(ERROR) << "CreateInputBuffers(): mmap() failed";
1704 input_buffer_map_[i].address = address;
1705 input_buffer_map_[i].length = buffer.m.planes[0].length;
1711 bool V4L2VideoDecodeAccelerator::CreateOutputBuffers() {
1712 DVLOG(3) << "CreateOutputBuffers()";
1713 DCHECK(decoder_state_ == kInitialized ||
1714 decoder_state_ == kChangingResolution);
1715 DCHECK(!output_streamon_);
1716 DCHECK(output_buffer_map_.empty());
1718 // Number of output buffers we need.
1719 struct v4l2_control ctrl;
1720 memset(&ctrl, 0, sizeof(ctrl));
1721 ctrl.id = V4L2_CID_MIN_BUFFERS_FOR_CAPTURE;
1722 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_G_CTRL, &ctrl);
1723 output_dpb_size_ = ctrl.value;
1725 // Output format setup in Initialize().
1727 // Allocate the output buffers.
1728 struct v4l2_requestbuffers reqbufs;
1729 memset(&reqbufs, 0, sizeof(reqbufs));
1730 reqbufs.count = output_dpb_size_ + kDpbOutputBufferExtraCount;
1731 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1732 reqbufs.memory = V4L2_MEMORY_MMAP;
1733 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);
1735 // Create DMABUFs from output buffers.
1736 output_buffer_map_.resize(reqbufs.count);
1737 for (size_t i = 0; i < output_buffer_map_.size(); ++i) {
1738 OutputRecord& output_record = output_buffer_map_[i];
1739 for (size_t j = 0; j < arraysize(output_record.fds); ++j) {
1740 // Export the DMABUF fd so we can export it as a texture.
1741 struct v4l2_exportbuffer expbuf;
1742 memset(&expbuf, 0, sizeof(expbuf));
1743 expbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1746 expbuf.flags = O_CLOEXEC;
1747 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_EXPBUF, &expbuf);
1748 output_record.fds[j] = expbuf.fd;
1752 DVLOG(3) << "CreateOutputBuffers(): ProvidePictureBuffers(): "
1753 << "buffer_count=" << output_buffer_map_.size()
1754 << ", width=" << frame_buffer_size_.width()
1755 << ", height=" << frame_buffer_size_.height();
1756 child_message_loop_proxy_->PostTask(FROM_HERE,
1757 base::Bind(&Client::ProvidePictureBuffers,
1759 output_buffer_map_.size(),
1761 GL_TEXTURE_EXTERNAL_OES));
1763 // Wait for the client to call AssignPictureBuffers() on the Child thread.
1764 // We do this, because if we continue decoding without finishing buffer
1765 // allocation, we may end up Resetting before AssignPictureBuffers arrives,
1766 // resulting in unnecessary complications and subtle bugs.
1767 // For example, if the client calls Decode(Input1), Reset(), Decode(Input2)
1768 // in a sequence, and Decode(Input1) results in us getting here and exiting
1769 // without waiting, we might end up running Reset{,Done}Task() before
1770 // AssignPictureBuffers is scheduled, thus cleaning up and pushing buffers
1771 // to the free_output_buffers_ map twice. If we somehow marked buffers as
1772 // not ready, we'd need special handling for restarting the second Decode
1773 // task and delaying it anyway.
1774 // Waiting here is not very costly and makes reasoning about different
1775 // situations much simpler.
1776 pictures_assigned_.Wait();
1782 void V4L2VideoDecodeAccelerator::DestroyInputBuffers() {
1783 DVLOG(3) << "DestroyInputBuffers()";
1784 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1785 DCHECK(!input_streamon_);
1787 for (size_t i = 0; i < input_buffer_map_.size(); ++i) {
1788 if (input_buffer_map_[i].address != NULL) {
1789 device_->Munmap(input_buffer_map_[i].address,
1790 input_buffer_map_[i].length);
1794 struct v4l2_requestbuffers reqbufs;
1795 memset(&reqbufs, 0, sizeof(reqbufs));
1797 reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1798 reqbufs.memory = V4L2_MEMORY_MMAP;
1799 if (device_->Ioctl(VIDIOC_REQBUFS, &reqbufs) != 0)
1800 DPLOG(ERROR) << "DestroyInputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1802 input_buffer_map_.clear();
1803 free_input_buffers_.clear();
1806 bool V4L2VideoDecodeAccelerator::DestroyOutputBuffers() {
1807 DVLOG(3) << "DestroyOutputBuffers()";
1808 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1809 DCHECK(!output_streamon_);
1810 bool success = true;
1812 for (size_t i = 0; i < output_buffer_map_.size(); ++i) {
1813 OutputRecord& output_record = output_buffer_map_[i];
1814 for (size_t j = 0; j < arraysize(output_record.fds); ++j) {
1815 if (output_record.fds[j] != -1) {
1816 if (close(output_record.fds[j])) {
1817 DVPLOG(1) << __func__ << " close() on a dmabuf fd failed.";
1822 if (output_record.egl_image != EGL_NO_IMAGE_KHR) {
1823 if (eglDestroyImageKHR(egl_display_, output_record.egl_image) !=
1825 DVLOG(1) << __func__ << " eglDestroyImageKHR failed.";
1830 if (output_record.egl_sync != EGL_NO_SYNC_KHR) {
1831 if (eglDestroySyncKHR(egl_display_, output_record.egl_sync) != EGL_TRUE) {
1832 DVLOG(1) << __func__ << " eglDestroySyncKHR failed.";
1837 DVLOG(1) << "DestroyOutputBuffers(): dismissing PictureBuffer id="
1838 << output_record.picture_id;
1839 child_message_loop_proxy_->PostTask(
1842 &Client::DismissPictureBuffer, client_, output_record.picture_id));
1845 struct v4l2_requestbuffers reqbufs;
1846 memset(&reqbufs, 0, sizeof(reqbufs));
1848 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1849 reqbufs.memory = V4L2_MEMORY_MMAP;
1850 if (device_->Ioctl(VIDIOC_REQBUFS, &reqbufs) != 0) {
1851 DPLOG(ERROR) << "DestroyOutputBuffers() ioctl() failed: VIDIOC_REQBUFS";
1855 output_buffer_map_.clear();
1856 while (!free_output_buffers_.empty())
1857 free_output_buffers_.pop();
1862 void V4L2VideoDecodeAccelerator::ResolutionChangeDestroyBuffers() {
1863 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1864 DVLOG(3) << "ResolutionChangeDestroyBuffers()";
1866 if (!DestroyOutputBuffers()) {
1867 DLOG(FATAL) << __func__ << " Failed destroying output buffers.";
1868 NOTIFY_ERROR(PLATFORM_FAILURE);
1872 // Finish resolution change on decoder thread.
1873 decoder_thread_.message_loop()->PostTask(FROM_HERE, base::Bind(
1874 &V4L2VideoDecodeAccelerator::FinishResolutionChange,
1875 base::Unretained(this)));
1878 void V4L2VideoDecodeAccelerator::SendPictureReady() {
1879 DVLOG(3) << "SendPictureReady()";
1880 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1881 bool resetting_or_flushing =
1882 (decoder_state_ == kResetting || decoder_flushing_);
1883 while (pending_picture_ready_.size() > 0) {
1884 bool cleared = pending_picture_ready_.front().cleared;
1885 const media::Picture& picture = pending_picture_ready_.front().picture;
1886 if (cleared && picture_clearing_count_ == 0) {
1887 // This picture is cleared. Post it to IO thread to reduce latency. This
1888 // should be the case after all pictures are cleared at the beginning.
1889 io_message_loop_proxy_->PostTask(
1890 FROM_HERE, base::Bind(&Client::PictureReady, io_client_, picture));
1891 pending_picture_ready_.pop();
1892 } else if (!cleared || resetting_or_flushing) {
1893 DVLOG(3) << "SendPictureReady()"
1894 << ". cleared=" << pending_picture_ready_.front().cleared
1895 << ", decoder_state_=" << decoder_state_
1896 << ", decoder_flushing_=" << decoder_flushing_
1897 << ", picture_clearing_count_=" << picture_clearing_count_;
1898 // If the picture is not cleared, post it to the child thread because it
1899 // has to be cleared in the child thread. A picture only needs to be
1900 // cleared once. If the decoder is resetting or flushing, send all
1901 // pictures to ensure PictureReady arrive before reset or flush done.
1902 child_message_loop_proxy_->PostTaskAndReply(
1904 base::Bind(&Client::PictureReady, client_, picture),
1905 // Unretained is safe. If Client::PictureReady gets to run, |this| is
1906 // alive. Destroy() will wait the decode thread to finish.
1907 base::Bind(&V4L2VideoDecodeAccelerator::PictureCleared,
1908 base::Unretained(this)));
1909 picture_clearing_count_++;
1910 pending_picture_ready_.pop();
1912 // This picture is cleared. But some pictures are about to be cleared on
1913 // the child thread. To preserve the order, do not send this until those
1914 // pictures are cleared.
1920 void V4L2VideoDecodeAccelerator::PictureCleared() {
1921 DVLOG(3) << "PictureCleared(). clearing count=" << picture_clearing_count_;
1922 DCHECK_EQ(decoder_thread_.message_loop(), base::MessageLoop::current());
1923 DCHECK_GT(picture_clearing_count_, 0);
1924 picture_clearing_count_--;
1928 } // namespace content