1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/common/gpu/media/exynos_video_encode_accelerator.h"
8 #include <linux/videodev2.h>
10 #include <sys/eventfd.h>
11 #include <sys/ioctl.h>
14 #include "base/callback.h"
15 #include "base/command_line.h"
16 #include "base/debug/trace_event.h"
17 #include "base/message_loop/message_loop_proxy.h"
18 #include "base/posix/eintr_wrapper.h"
19 #include "content/public/common/content_switches.h"
20 #include "media/base/bitstream_buffer.h"
22 #define NOTIFY_ERROR(x) \
24 SetEncoderState(kError); \
25 DLOG(ERROR) << "calling NotifyError(): " << x; \
29 #define IOCTL_OR_ERROR_RETURN(fd, type, arg) \
31 if (HANDLE_EINTR(ioctl(fd, type, arg) != 0)) { \
32 DPLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
33 NOTIFY_ERROR(kPlatformFailureError); \
38 #define IOCTL_OR_ERROR_RETURN_FALSE(fd, type, arg) \
40 if (HANDLE_EINTR(ioctl(fd, type, arg) != 0)) { \
41 DPLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
42 NOTIFY_ERROR(kPlatformFailureError); \
51 const char kExynosGscDevice[] = "/dev/gsc1";
52 const char kExynosMfcDevice[] = "/dev/mfc-enc";
54 // File descriptors we need to poll, one-bit flag for each.
60 } // anonymous namespace
62 struct ExynosVideoEncodeAccelerator::BitstreamBufferRef {
63 BitstreamBufferRef(int32 id, scoped_ptr<base::SharedMemory> shm, size_t size)
64 : id(id), shm(shm.Pass()), size(size) {}
66 const scoped_ptr<base::SharedMemory> shm;
71 ExynosVideoEncodeAccelerator::GscInputRecord::GscInputRecord()
74 ExynosVideoEncodeAccelerator::GscOutputRecord::GscOutputRecord()
75 : at_device(false), mfc_input(-1) {}
77 ExynosVideoEncodeAccelerator::MfcInputRecord::MfcInputRecord()
82 ExynosVideoEncodeAccelerator::MfcOutputRecord::MfcOutputRecord()
83 : at_device(false), address(NULL), length(0) {}
85 ExynosVideoEncodeAccelerator::ExynosVideoEncodeAccelerator(
86 media::VideoEncodeAccelerator::Client* client)
87 : child_message_loop_proxy_(base::MessageLoopProxy::current()),
88 weak_this_ptr_factory_(this),
89 weak_this_(weak_this_ptr_factory_.GetWeakPtr()),
90 client_ptr_factory_(client),
91 client_(client_ptr_factory_.GetWeakPtr()),
92 encoder_thread_("ExynosEncoderThread"),
93 encoder_state_(kUninitialized),
94 output_buffer_byte_size_(0),
95 stream_header_size_(0),
96 input_format_fourcc_(0),
97 output_format_fourcc_(0),
99 gsc_input_streamon_(false),
100 gsc_input_buffer_queued_count_(0),
101 gsc_output_streamon_(false),
102 gsc_output_buffer_queued_count_(0),
104 mfc_input_streamon_(false),
105 mfc_input_buffer_queued_count_(0),
106 mfc_output_streamon_(false),
107 mfc_output_buffer_queued_count_(0),
108 device_poll_thread_("ExynosEncoderDevicePollThread"),
109 device_poll_interrupt_fd_(-1) {
113 ExynosVideoEncodeAccelerator::~ExynosVideoEncodeAccelerator() {
114 DCHECK(!encoder_thread_.IsRunning());
115 DCHECK(!device_poll_thread_.IsRunning());
117 if (device_poll_interrupt_fd_ != -1) {
118 close(device_poll_interrupt_fd_);
119 device_poll_interrupt_fd_ = -1;
122 DestroyGscInputBuffers();
123 DestroyGscOutputBuffers();
128 DestroyMfcInputBuffers();
129 DestroyMfcOutputBuffers();
135 void ExynosVideoEncodeAccelerator::Initialize(
136 media::VideoFrame::Format input_format,
137 const gfx::Size& input_visible_size,
138 media::VideoCodecProfile output_profile,
139 uint32 initial_bitrate) {
140 DVLOG(3) << "Initialize(): input_format=" << input_format
141 << ", input_visible_size=" << input_visible_size.ToString()
142 << ", output_profile=" << output_profile
143 << ", initial_bitrate=" << initial_bitrate;
145 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
146 DCHECK_EQ(encoder_state_, kUninitialized);
148 input_visible_size_ = input_visible_size;
149 input_allocated_size_.SetSize((input_visible_size_.width() + 0xF) & ~0xF,
150 (input_visible_size_.height() + 0xF) & ~0xF);
151 converted_visible_size_.SetSize((input_visible_size_.width() + 0x1) & ~0x1,
152 (input_visible_size_.height() + 0x1) & ~0x1);
153 converted_allocated_size_.SetSize(
154 (converted_visible_size_.width() + 0xF) & ~0xF,
155 (converted_visible_size_.height() + 0xF) & ~0xF);
156 output_visible_size_ = converted_visible_size_;
158 switch (input_format) {
159 case media::VideoFrame::I420:
160 input_format_fourcc_ = V4L2_PIX_FMT_YUV420M;
163 NOTIFY_ERROR(kInvalidArgumentError);
167 if (output_profile >= media::H264PROFILE_MIN &&
168 output_profile <= media::H264PROFILE_MAX) {
169 output_format_fourcc_ = V4L2_PIX_FMT_H264;
170 } else if (output_profile >= media::VP8PROFILE_MIN &&
171 output_profile <= media::VP8PROFILE_MAX) {
172 output_format_fourcc_ = V4L2_PIX_FMT_VP8;
174 NOTIFY_ERROR(kInvalidArgumentError);
178 // Open the color conversion device.
179 DVLOG(2) << "Initialize(): opening GSC device: " << kExynosGscDevice;
181 HANDLE_EINTR(open(kExynosGscDevice, O_RDWR | O_NONBLOCK | O_CLOEXEC));
183 DPLOG(ERROR) << "Initialize(): could not open GSC device: "
185 NOTIFY_ERROR(kPlatformFailureError);
189 // Capabilities check.
190 struct v4l2_capability caps;
191 memset(&caps, 0, sizeof(caps));
192 const __u32 kCapsRequired = V4L2_CAP_VIDEO_CAPTURE_MPLANE |
193 V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_STREAMING;
194 IOCTL_OR_ERROR_RETURN(gsc_fd_, VIDIOC_QUERYCAP, &caps);
195 if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
196 DLOG(ERROR) << "Initialize(): ioctl() failed: VIDIOC_QUERYCAP: "
197 "caps check failed: 0x" << std::hex << caps.capabilities;
198 NOTIFY_ERROR(kPlatformFailureError);
202 // Open the video encoder device.
203 DVLOG(2) << "Initialize(): opening MFC device: " << kExynosMfcDevice;
205 HANDLE_EINTR(open(kExynosMfcDevice, O_RDWR | O_NONBLOCK | O_CLOEXEC));
207 DPLOG(ERROR) << "Initialize(): could not open MFC device: "
209 NOTIFY_ERROR(kPlatformFailureError);
213 memset(&caps, 0, sizeof(caps));
214 IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_QUERYCAP, &caps);
215 if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
216 DLOG(ERROR) << "Initialize(): ioctl() failed: VIDIOC_QUERYCAP: "
217 "caps check failed: 0x" << std::hex << caps.capabilities;
218 NOTIFY_ERROR(kPlatformFailureError);
222 // Create the interrupt fd.
223 DCHECK_EQ(device_poll_interrupt_fd_, -1);
224 device_poll_interrupt_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
225 if (device_poll_interrupt_fd_ == -1) {
226 DPLOG(ERROR) << "Initialize(): eventfd() failed";
227 NOTIFY_ERROR(kPlatformFailureError);
232 << "Initialize(): input_visible_size_=" << input_visible_size_.ToString()
233 << ", input_allocated_size_=" << input_allocated_size_.ToString()
234 << ", converted_visible_size_=" << converted_visible_size_.ToString()
235 << ", converted_allocated_size_=" << converted_allocated_size_.ToString()
236 << ", output_visible_size_=" << output_visible_size_.ToString();
238 if (!CreateGscInputBuffers() || !CreateGscOutputBuffers())
241 // MFC setup for encoding is rather particular in ordering:
243 // 1. Format (VIDIOC_S_FMT) set first on OUTPUT and CAPTURE queues.
244 // 2. VIDIOC_REQBUFS, VIDIOC_QBUF, and VIDIOC_STREAMON on CAPTURE queue.
245 // 3. VIDIOC_REQBUFS (and later VIDIOC_QBUF and VIDIOC_STREAMON) on OUTPUT
248 // Unfortunately, we cannot do (3) in Initialize() here since we have no
249 // buffers to QBUF in step (2) until the client has provided output buffers
250 // through UseOutputBitstreamBuffer(). So, we just do (1), and the
251 // VIDIOC_REQBUFS part of (2) here. The rest is done the first time we get
252 // a UseOutputBitstreamBuffer() callback.
254 if (!SetMfcFormats())
257 if (!InitMfcControls())
260 // VIDIOC_REQBUFS on CAPTURE queue.
261 if (!CreateMfcOutputBuffers())
265 if (!encoder_thread_.Start()) {
266 DLOG(ERROR) << "Initialize(): encoder thread failed to start";
267 NOTIFY_ERROR(kPlatformFailureError);
271 RequestEncodingParametersChange(initial_bitrate, kInitialFramerate);
273 SetEncoderState(kInitialized);
275 child_message_loop_proxy_->PostTask(
276 FROM_HERE, base::Bind(&Client::NotifyInitializeDone, client_));
278 child_message_loop_proxy_->PostTask(
280 base::Bind(&Client::RequireBitstreamBuffers,
282 gsc_input_buffer_map_.size(),
283 input_allocated_size_,
284 output_buffer_byte_size_));
287 void ExynosVideoEncodeAccelerator::Encode(
288 const scoped_refptr<media::VideoFrame>& frame,
289 bool force_keyframe) {
290 DVLOG(3) << "Encode(): force_keyframe=" << force_keyframe;
291 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
293 encoder_thread_.message_loop()->PostTask(
295 base::Bind(&ExynosVideoEncodeAccelerator::EncodeTask,
296 base::Unretained(this),
301 void ExynosVideoEncodeAccelerator::UseOutputBitstreamBuffer(
302 const media::BitstreamBuffer& buffer) {
303 DVLOG(3) << "UseOutputBitstreamBuffer(): id=" << buffer.id();
304 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
306 if (buffer.size() < output_buffer_byte_size_) {
307 NOTIFY_ERROR(kInvalidArgumentError);
311 scoped_ptr<base::SharedMemory> shm(
312 new base::SharedMemory(buffer.handle(), false));
313 if (!shm->Map(buffer.size())) {
314 NOTIFY_ERROR(kPlatformFailureError);
318 scoped_ptr<BitstreamBufferRef> buffer_ref(
319 new BitstreamBufferRef(buffer.id(), shm.Pass(), buffer.size()));
320 encoder_thread_.message_loop()->PostTask(
322 base::Bind(&ExynosVideoEncodeAccelerator::UseOutputBitstreamBufferTask,
323 base::Unretained(this),
324 base::Passed(&buffer_ref)));
327 void ExynosVideoEncodeAccelerator::RequestEncodingParametersChange(
330 DVLOG(3) << "RequestEncodingParametersChange(): bitrate=" << bitrate
331 << ", framerate=" << framerate;
332 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
334 encoder_thread_.message_loop()->PostTask(
337 &ExynosVideoEncodeAccelerator::RequestEncodingParametersChangeTask,
338 base::Unretained(this),
343 void ExynosVideoEncodeAccelerator::Destroy() {
344 DVLOG(3) << "Destroy()";
345 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
347 // We're destroying; cancel all callbacks.
348 client_ptr_factory_.InvalidateWeakPtrs();
350 // If the encoder thread is running, destroy using posted task.
351 if (encoder_thread_.IsRunning()) {
352 encoder_thread_.message_loop()->PostTask(
354 base::Bind(&ExynosVideoEncodeAccelerator::DestroyTask,
355 base::Unretained(this)));
356 // DestroyTask() will put the encoder into kError state and cause all tasks
358 encoder_thread_.Stop();
360 // Otherwise, call the destroy task directly.
364 // Set to kError state just in case.
365 SetEncoderState(kError);
371 std::vector<media::VideoEncodeAccelerator::SupportedProfile>
372 ExynosVideoEncodeAccelerator::GetSupportedProfiles() {
373 std::vector<SupportedProfile> profiles;
375 SupportedProfile profile;
377 const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
378 if (cmd_line->HasSwitch(switches::kEnableWebRtcHWVp8Encoding)) {
379 profile.profile = media::VP8PROFILE_MAIN;
380 profile.max_resolution.SetSize(1920, 1088);
381 profile.max_framerate.numerator = 30;
382 profile.max_framerate.denominator = 1;
383 profiles.push_back(profile);
385 profile.profile = media::H264PROFILE_MAIN;
386 profile.max_resolution.SetSize(1920, 1088);
387 profile.max_framerate.numerator = 30;
388 profile.max_framerate.denominator = 1;
389 profiles.push_back(profile);
395 void ExynosVideoEncodeAccelerator::EncodeTask(
396 const scoped_refptr<media::VideoFrame>& frame, bool force_keyframe) {
397 DVLOG(3) << "EncodeTask(): force_keyframe=" << force_keyframe;
398 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
399 DCHECK_NE(encoder_state_, kUninitialized);
401 if (encoder_state_ == kError) {
402 DVLOG(2) << "EncodeTask(): early out: kError state";
406 encoder_input_queue_.push_back(frame);
409 if (force_keyframe) {
410 // TODO(sheu): this presently makes for slightly imprecise encoding
411 // parameters updates. To precisely align the parameter updates with the
412 // incoming input frame, we should track the parameters through the GSC
413 // pipeline and only apply them when the MFC input is about to be queued.
414 struct v4l2_ext_control ctrls[1];
415 struct v4l2_ext_controls control;
416 memset(&ctrls, 0, sizeof(ctrls));
417 memset(&control, 0, sizeof(control));
418 ctrls[0].id = V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE;
419 ctrls[0].value = V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME;
420 control.ctrl_class = V4L2_CTRL_CLASS_MPEG;
422 control.controls = ctrls;
423 IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_S_EXT_CTRLS, &control);
427 void ExynosVideoEncodeAccelerator::UseOutputBitstreamBufferTask(
428 scoped_ptr<BitstreamBufferRef> buffer_ref) {
429 DVLOG(3) << "UseOutputBitstreamBufferTask(): id=" << buffer_ref->id;
430 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
432 encoder_output_queue_.push_back(
433 linked_ptr<BitstreamBufferRef>(buffer_ref.release()));
436 if (encoder_state_ == kInitialized) {
437 // Finish setting up our MFC OUTPUT queue. See: Initialize().
438 // VIDIOC_REQBUFS on OUTPUT queue.
439 if (!CreateMfcInputBuffers())
441 if (!StartDevicePoll())
443 encoder_state_ = kEncoding;
447 void ExynosVideoEncodeAccelerator::DestroyTask() {
448 DVLOG(3) << "DestroyTask()";
450 // DestroyTask() should run regardless of encoder_state_.
452 // Stop streaming and the device_poll_thread_.
455 // Set our state to kError, and early-out all tasks.
456 encoder_state_ = kError;
459 void ExynosVideoEncodeAccelerator::ServiceDeviceTask() {
460 DVLOG(3) << "ServiceDeviceTask()";
461 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
462 DCHECK_NE(encoder_state_, kUninitialized);
463 DCHECK_NE(encoder_state_, kInitialized);
465 if (encoder_state_ == kError) {
466 DVLOG(2) << "ServiceDeviceTask(): early out: kError state";
475 // Clear the interrupt fd.
476 if (!ClearDevicePollInterrupt())
479 unsigned int poll_fds = 0;
480 // Add GSC fd, if we should poll on it.
481 // GSC has to wait until both input and output buffers are queued.
482 if (gsc_input_buffer_queued_count_ > 0 && gsc_output_buffer_queued_count_ > 0)
483 poll_fds |= kPollGsc;
484 // Add MFC fd, if we should poll on it.
485 // MFC can be polled as soon as either input or output buffers are queued.
486 if (mfc_input_buffer_queued_count_ + mfc_output_buffer_queued_count_ > 0)
487 poll_fds |= kPollMfc;
489 // ServiceDeviceTask() should only ever be scheduled from DevicePollTask(),
491 // * device_poll_thread_ is running normally
492 // * device_poll_thread_ scheduled us, but then a DestroyTask() shut it down,
493 // in which case we're in kError state, and we should have early-outed
495 DCHECK(device_poll_thread_.message_loop());
496 // Queue the DevicePollTask() now.
497 device_poll_thread_.message_loop()->PostTask(
499 base::Bind(&ExynosVideoEncodeAccelerator::DevicePollTask,
500 base::Unretained(this),
503 DVLOG(2) << "ServiceDeviceTask(): buffer counts: ENC["
504 << encoder_input_queue_.size() << "] => GSC["
505 << gsc_free_input_buffers_.size() << "+"
506 << gsc_input_buffer_queued_count_ << "/"
507 << gsc_input_buffer_map_.size() << "->"
508 << gsc_free_output_buffers_.size() << "+"
509 << gsc_output_buffer_queued_count_ << "/"
510 << gsc_output_buffer_map_.size() << "] => "
511 << mfc_ready_input_buffers_.size() << " => MFC["
512 << mfc_free_input_buffers_.size() << "+"
513 << mfc_input_buffer_queued_count_ << "/"
514 << mfc_input_buffer_map_.size() << "->"
515 << mfc_free_output_buffers_.size() << "+"
516 << mfc_output_buffer_queued_count_ << "/"
517 << mfc_output_buffer_map_.size() << "] => OUT["
518 << encoder_output_queue_.size() << "]";
521 void ExynosVideoEncodeAccelerator::EnqueueGsc() {
522 DVLOG(3) << "EnqueueGsc()";
523 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
525 const int old_gsc_inputs_queued = gsc_input_buffer_queued_count_;
526 while (!encoder_input_queue_.empty() && !gsc_free_input_buffers_.empty()) {
527 if (!EnqueueGscInputRecord())
530 if (old_gsc_inputs_queued == 0 && gsc_input_buffer_queued_count_ != 0) {
531 // We started up a previously empty queue.
532 // Queue state changed; signal interrupt.
533 if (!SetDevicePollInterrupt())
535 // Start VIDIOC_STREAMON if we haven't yet.
536 if (!gsc_input_streamon_) {
537 __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
538 IOCTL_OR_ERROR_RETURN(gsc_fd_, VIDIOC_STREAMON, &type);
539 gsc_input_streamon_ = true;
543 // Enqueue a GSC output, only if we need one. GSC output buffers write
544 // directly to MFC input buffers, so we'll have to check for free MFC input
546 // GSC is liable to race conditions if more than one output buffer is
547 // simultaneously enqueued, so enqueue just one.
548 if (gsc_input_buffer_queued_count_ != 0 &&
549 gsc_output_buffer_queued_count_ == 0 &&
550 !gsc_free_output_buffers_.empty() && !mfc_free_input_buffers_.empty()) {
551 const int old_gsc_outputs_queued = gsc_output_buffer_queued_count_;
552 if (!EnqueueGscOutputRecord())
554 if (old_gsc_outputs_queued == 0 && gsc_output_buffer_queued_count_ != 0) {
555 // We just started up a previously empty queue.
556 // Queue state changed; signal interrupt.
557 if (!SetDevicePollInterrupt())
559 // Start VIDIOC_STREAMON if we haven't yet.
560 if (!gsc_output_streamon_) {
561 __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
562 IOCTL_OR_ERROR_RETURN(gsc_fd_, VIDIOC_STREAMON, &type);
563 gsc_output_streamon_ = true;
567 DCHECK_LE(gsc_output_buffer_queued_count_, 1);
570 void ExynosVideoEncodeAccelerator::DequeueGsc() {
571 DVLOG(3) << "DequeueGsc()";
572 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
574 // Dequeue completed GSC input (VIDEO_OUTPUT) buffers, and recycle to the free
576 struct v4l2_buffer dqbuf;
577 struct v4l2_plane planes[3];
578 while (gsc_input_buffer_queued_count_ > 0) {
579 DCHECK(gsc_input_streamon_);
580 memset(&dqbuf, 0, sizeof(dqbuf));
581 memset(&planes, 0, sizeof(planes));
582 dqbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
583 dqbuf.memory = V4L2_MEMORY_USERPTR;
584 dqbuf.m.planes = planes;
585 dqbuf.length = arraysize(planes);
586 if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_DQBUF, &dqbuf)) != 0) {
587 if (errno == EAGAIN) {
588 // EAGAIN if we're just out of buffers to dequeue.
591 DPLOG(ERROR) << "DequeueGsc(): ioctl() failed: VIDIOC_DQBUF";
592 NOTIFY_ERROR(kPlatformFailureError);
595 GscInputRecord& input_record = gsc_input_buffer_map_[dqbuf.index];
596 DCHECK(input_record.at_device);
597 DCHECK(input_record.frame.get());
598 input_record.at_device = false;
599 input_record.frame = NULL;
600 gsc_free_input_buffers_.push_back(dqbuf.index);
601 gsc_input_buffer_queued_count_--;
604 // Dequeue completed GSC output (VIDEO_CAPTURE) buffers, and recycle to the
605 // free list. Queue the corresponding MFC buffer to the GSC->MFC holding
607 while (gsc_output_buffer_queued_count_ > 0) {
608 DCHECK(gsc_output_streamon_);
609 memset(&dqbuf, 0, sizeof(dqbuf));
610 memset(&planes, 0, sizeof(planes));
611 dqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
612 dqbuf.memory = V4L2_MEMORY_DMABUF;
613 dqbuf.m.planes = planes;
615 if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_DQBUF, &dqbuf)) != 0) {
616 if (errno == EAGAIN) {
617 // EAGAIN if we're just out of buffers to dequeue.
620 DPLOG(ERROR) << "DequeueGsc(): ioctl() failed: VIDIOC_DQBUF";
621 NOTIFY_ERROR(kPlatformFailureError);
624 GscOutputRecord& output_record = gsc_output_buffer_map_[dqbuf.index];
625 DCHECK(output_record.at_device);
626 DCHECK(output_record.mfc_input != -1);
627 mfc_ready_input_buffers_.push_back(output_record.mfc_input);
628 output_record.at_device = false;
629 output_record.mfc_input = -1;
630 gsc_free_output_buffers_.push_back(dqbuf.index);
631 gsc_output_buffer_queued_count_--;
634 void ExynosVideoEncodeAccelerator::EnqueueMfc() {
635 DVLOG(3) << "EnqueueMfc()";
636 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
638 // Enqueue all the MFC inputs we can.
639 const int old_mfc_inputs_queued = mfc_input_buffer_queued_count_;
640 while (!mfc_ready_input_buffers_.empty()) {
641 if (!EnqueueMfcInputRecord())
644 if (old_mfc_inputs_queued == 0 && mfc_input_buffer_queued_count_ != 0) {
645 // We just started up a previously empty queue.
646 // Queue state changed; signal interrupt.
647 if (!SetDevicePollInterrupt())
649 // Start VIDIOC_STREAMON if we haven't yet.
650 if (!mfc_input_streamon_) {
651 __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
652 IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_STREAMON, &type);
653 mfc_input_streamon_ = true;
657 // Enqueue all the MFC outputs we can.
658 const int old_mfc_outputs_queued = mfc_output_buffer_queued_count_;
659 while (!mfc_free_output_buffers_.empty() && !encoder_output_queue_.empty()) {
660 if (!EnqueueMfcOutputRecord())
663 if (old_mfc_outputs_queued == 0 && mfc_output_buffer_queued_count_ != 0) {
664 // We just started up a previously empty queue.
665 // Queue state changed; signal interrupt.
666 if (!SetDevicePollInterrupt())
668 // Start VIDIOC_STREAMON if we haven't yet.
669 if (!mfc_output_streamon_) {
670 __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
671 IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_STREAMON, &type);
672 mfc_output_streamon_ = true;
677 void ExynosVideoEncodeAccelerator::DequeueMfc() {
678 DVLOG(3) << "DequeueMfc()";
679 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
681 // Dequeue completed MFC input (VIDEO_OUTPUT) buffers, and recycle to the free
683 struct v4l2_buffer dqbuf;
684 struct v4l2_plane planes[2];
685 while (mfc_input_buffer_queued_count_ > 0) {
686 DCHECK(mfc_input_streamon_);
687 memset(&dqbuf, 0, sizeof(dqbuf));
688 memset(&planes, 0, sizeof(planes));
689 dqbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
690 dqbuf.memory = V4L2_MEMORY_MMAP;
691 dqbuf.m.planes = planes;
693 if (HANDLE_EINTR(ioctl(mfc_fd_, VIDIOC_DQBUF, &dqbuf)) != 0) {
694 if (errno == EAGAIN) {
695 // EAGAIN if we're just out of buffers to dequeue.
698 DPLOG(ERROR) << "DequeueMfc(): ioctl() failed: VIDIOC_DQBUF";
699 NOTIFY_ERROR(kPlatformFailureError);
702 MfcInputRecord& input_record = mfc_input_buffer_map_[dqbuf.index];
703 DCHECK(input_record.at_device);
704 input_record.at_device = false;
705 mfc_free_input_buffers_.push_back(dqbuf.index);
706 mfc_input_buffer_queued_count_--;
709 // Dequeue completed MFC output (VIDEO_CAPTURE) buffers, and recycle to the
710 // free list. Notify the client that an output buffer is complete.
711 while (mfc_output_buffer_queued_count_ > 0) {
712 DCHECK(mfc_output_streamon_);
713 memset(&dqbuf, 0, sizeof(dqbuf));
714 memset(planes, 0, sizeof(planes));
715 dqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
716 dqbuf.memory = V4L2_MEMORY_MMAP;
717 dqbuf.m.planes = planes;
719 if (HANDLE_EINTR(ioctl(mfc_fd_, VIDIOC_DQBUF, &dqbuf)) != 0) {
720 if (errno == EAGAIN) {
721 // EAGAIN if we're just out of buffers to dequeue.
724 DPLOG(ERROR) << "DequeueMfc(): ioctl() failed: VIDIOC_DQBUF";
725 NOTIFY_ERROR(kPlatformFailureError);
728 const bool key_frame = ((dqbuf.flags & V4L2_BUF_FLAG_KEYFRAME) != 0);
729 MfcOutputRecord& output_record = mfc_output_buffer_map_[dqbuf.index];
730 DCHECK(output_record.at_device);
731 DCHECK(output_record.buffer_ref.get());
733 void* output_data = output_record.address;
734 size_t output_size = dqbuf.m.planes[0].bytesused;
735 // This shouldn't happen, but just in case. We should be able to recover
736 // after next keyframe after showing some corruption.
737 DCHECK_LE(output_size, output_buffer_byte_size_);
738 if (output_size > output_buffer_byte_size_)
739 output_size = output_buffer_byte_size_;
741 reinterpret_cast<uint8*>(output_record.buffer_ref->shm->memory());
742 if (output_format_fourcc_ == V4L2_PIX_FMT_H264) {
743 if (stream_header_size_ == 0) {
744 // Assume that the first buffer dequeued is the stream header.
745 stream_header_size_ = output_size;
746 stream_header_.reset(new uint8[stream_header_size_]);
747 memcpy(stream_header_.get(), output_data, stream_header_size_);
750 output_buffer_byte_size_ - stream_header_size_ >= output_size) {
751 // Insert stream header before every keyframe.
752 memcpy(target_data, stream_header_.get(), stream_header_size_);
753 memcpy(target_data + stream_header_size_, output_data, output_size);
754 output_size += stream_header_size_;
756 memcpy(target_data, output_data, output_size);
759 memcpy(target_data, output_data, output_size);
762 DVLOG(3) << "DequeueMfc(): returning "
763 "bitstream_buffer_id=" << output_record.buffer_ref->id
764 << ", key_frame=" << key_frame;
765 child_message_loop_proxy_->PostTask(
767 base::Bind(&Client::BitstreamBufferReady,
769 output_record.buffer_ref->id,
772 output_record.at_device = false;
773 output_record.buffer_ref.reset();
774 mfc_free_output_buffers_.push_back(dqbuf.index);
775 mfc_output_buffer_queued_count_--;
779 bool ExynosVideoEncodeAccelerator::EnqueueGscInputRecord() {
780 DVLOG(3) << "EnqueueGscInputRecord()";
781 DCHECK(!encoder_input_queue_.empty());
782 DCHECK(!gsc_free_input_buffers_.empty());
784 // Enqueue a GSC input (VIDEO_OUTPUT) buffer for an input video frame
785 scoped_refptr<media::VideoFrame> frame = encoder_input_queue_.front();
786 const int gsc_buffer = gsc_free_input_buffers_.back();
787 GscInputRecord& input_record = gsc_input_buffer_map_[gsc_buffer];
788 DCHECK(!input_record.at_device);
789 DCHECK(!input_record.frame.get());
790 struct v4l2_buffer qbuf;
791 struct v4l2_plane qbuf_planes[3];
792 memset(&qbuf, 0, sizeof(qbuf));
793 memset(qbuf_planes, 0, sizeof(qbuf_planes));
794 qbuf.index = gsc_buffer;
795 qbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
796 qbuf.memory = V4L2_MEMORY_USERPTR;
797 qbuf.m.planes = qbuf_planes;
798 switch (input_format_fourcc_) {
799 case V4L2_PIX_FMT_YUV420M: {
800 qbuf.m.planes[0].bytesused = input_allocated_size_.GetArea();
801 qbuf.m.planes[0].length = input_allocated_size_.GetArea();
802 qbuf.m.planes[0].m.userptr = reinterpret_cast<unsigned long>(
803 frame->data(media::VideoFrame::kYPlane));
804 qbuf.m.planes[1].bytesused = input_allocated_size_.GetArea() / 4;
805 qbuf.m.planes[1].length = input_allocated_size_.GetArea() / 4;
806 qbuf.m.planes[1].m.userptr = reinterpret_cast<unsigned long>(
807 frame->data(media::VideoFrame::kUPlane));
808 qbuf.m.planes[2].bytesused = input_allocated_size_.GetArea() / 4;
809 qbuf.m.planes[2].length = input_allocated_size_.GetArea() / 4;
810 qbuf.m.planes[2].m.userptr = reinterpret_cast<unsigned long>(
811 frame->data(media::VideoFrame::kVPlane));
817 NOTIFY_ERROR(kIllegalStateError);
820 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_QBUF, &qbuf);
821 input_record.at_device = true;
822 input_record.frame = frame;
823 encoder_input_queue_.pop_front();
824 gsc_free_input_buffers_.pop_back();
825 gsc_input_buffer_queued_count_++;
829 bool ExynosVideoEncodeAccelerator::EnqueueGscOutputRecord() {
830 DVLOG(3) << "EnqueueGscOutputRecord()";
831 DCHECK(!gsc_free_output_buffers_.empty());
832 DCHECK(!mfc_free_input_buffers_.empty());
834 // Enqueue a GSC output (VIDEO_CAPTURE) buffer.
835 const int gsc_buffer = gsc_free_output_buffers_.back();
836 const int mfc_buffer = mfc_free_input_buffers_.back();
837 GscOutputRecord& output_record = gsc_output_buffer_map_[gsc_buffer];
838 MfcInputRecord& input_record = mfc_input_buffer_map_[mfc_buffer];
839 DCHECK(!output_record.at_device);
840 DCHECK_EQ(output_record.mfc_input, -1);
841 DCHECK(!input_record.at_device);
842 struct v4l2_buffer qbuf;
843 struct v4l2_plane qbuf_planes[2];
844 memset(&qbuf, 0, sizeof(qbuf));
845 memset(qbuf_planes, 0, sizeof(qbuf_planes));
846 qbuf.index = gsc_buffer;
847 qbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
848 qbuf.memory = V4L2_MEMORY_DMABUF;
849 qbuf.m.planes = qbuf_planes;
850 qbuf.m.planes[0].m.fd = input_record.fd[0];
851 qbuf.m.planes[1].m.fd = input_record.fd[1];
853 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_QBUF, &qbuf);
854 output_record.at_device = true;
855 output_record.mfc_input = mfc_buffer;
856 mfc_free_input_buffers_.pop_back();
857 gsc_free_output_buffers_.pop_back();
858 gsc_output_buffer_queued_count_++;
862 bool ExynosVideoEncodeAccelerator::EnqueueMfcInputRecord() {
863 DVLOG(3) << "EnqueueMfcInputRecord()";
864 DCHECK(!mfc_ready_input_buffers_.empty());
866 // Enqueue a MFC input (VIDEO_OUTPUT) buffer.
867 const int mfc_buffer = mfc_ready_input_buffers_.front();
868 MfcInputRecord& input_record = mfc_input_buffer_map_[mfc_buffer];
869 DCHECK(!input_record.at_device);
870 struct v4l2_buffer qbuf;
871 struct v4l2_plane qbuf_planes[2];
872 memset(&qbuf, 0, sizeof(qbuf));
873 memset(qbuf_planes, 0, sizeof(qbuf_planes));
874 qbuf.index = mfc_buffer;
875 qbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
876 qbuf.memory = V4L2_MEMORY_MMAP;
877 qbuf.m.planes = qbuf_planes;
879 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_QBUF, &qbuf);
880 input_record.at_device = true;
881 mfc_ready_input_buffers_.pop_front();
882 mfc_input_buffer_queued_count_++;
886 bool ExynosVideoEncodeAccelerator::EnqueueMfcOutputRecord() {
887 DVLOG(3) << "EnqueueMfcOutputRecord()";
888 DCHECK(!mfc_free_output_buffers_.empty());
889 DCHECK(!encoder_output_queue_.empty());
891 // Enqueue a MFC output (VIDEO_CAPTURE) buffer.
892 linked_ptr<BitstreamBufferRef> output_buffer = encoder_output_queue_.back();
893 const int mfc_buffer = mfc_free_output_buffers_.back();
894 MfcOutputRecord& output_record = mfc_output_buffer_map_[mfc_buffer];
895 DCHECK(!output_record.at_device);
896 DCHECK(!output_record.buffer_ref.get());
897 struct v4l2_buffer qbuf;
898 struct v4l2_plane qbuf_planes[1];
899 memset(&qbuf, 0, sizeof(qbuf));
900 memset(qbuf_planes, 0, sizeof(qbuf_planes));
901 qbuf.index = mfc_buffer;
902 qbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
903 qbuf.memory = V4L2_MEMORY_MMAP;
904 qbuf.m.planes = qbuf_planes;
906 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_QBUF, &qbuf);
907 output_record.at_device = true;
908 output_record.buffer_ref = output_buffer;
909 encoder_output_queue_.pop_back();
910 mfc_free_output_buffers_.pop_back();
911 mfc_output_buffer_queued_count_++;
915 bool ExynosVideoEncodeAccelerator::StartDevicePoll() {
916 DVLOG(3) << "StartDevicePoll()";
917 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
918 DCHECK(!device_poll_thread_.IsRunning());
920 // Start up the device poll thread and schedule its first DevicePollTask().
921 if (!device_poll_thread_.Start()) {
922 DLOG(ERROR) << "StartDevicePoll(): Device thread failed to start";
923 NOTIFY_ERROR(kPlatformFailureError);
926 // Enqueue a poll task with no devices to poll on -- it will wait only on the
928 device_poll_thread_.message_loop()->PostTask(
930 base::Bind(&ExynosVideoEncodeAccelerator::DevicePollTask,
931 base::Unretained(this),
937 bool ExynosVideoEncodeAccelerator::StopDevicePoll() {
938 DVLOG(3) << "StopDevicePoll()";
940 // Signal the DevicePollTask() to stop, and stop the device poll thread.
941 if (!SetDevicePollInterrupt())
943 device_poll_thread_.Stop();
944 // Clear the interrupt now, to be sure.
945 if (!ClearDevicePollInterrupt())
949 if (gsc_input_streamon_) {
950 __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
951 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_STREAMOFF, &type);
953 gsc_input_streamon_ = false;
954 if (gsc_output_streamon_) {
955 __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
956 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_STREAMOFF, &type);
958 gsc_output_streamon_ = false;
959 if (mfc_input_streamon_) {
960 __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
961 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_STREAMOFF, &type);
963 mfc_input_streamon_ = false;
964 if (mfc_output_streamon_) {
965 __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
966 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_STREAMOFF, &type);
968 mfc_output_streamon_ = false;
970 // Reset all our accounting info.
971 encoder_input_queue_.clear();
972 gsc_free_input_buffers_.clear();
973 for (size_t i = 0; i < gsc_input_buffer_map_.size(); ++i) {
974 GscInputRecord& input_record = gsc_input_buffer_map_[i];
975 input_record.at_device = false;
976 input_record.frame = NULL;
977 gsc_free_input_buffers_.push_back(i);
979 gsc_input_buffer_queued_count_ = 0;
980 gsc_free_output_buffers_.clear();
981 for (size_t i = 0; i < gsc_output_buffer_map_.size(); ++i) {
982 GscOutputRecord& output_record = gsc_output_buffer_map_[i];
983 output_record.at_device = false;
984 output_record.mfc_input = -1;
985 gsc_free_output_buffers_.push_back(i);
987 gsc_output_buffer_queued_count_ = 0;
988 mfc_ready_input_buffers_.clear();
989 mfc_free_input_buffers_.clear();
990 for (size_t i = 0; i < mfc_input_buffer_map_.size(); ++i) {
991 MfcInputRecord& input_record = mfc_input_buffer_map_[i];
992 input_record.at_device = false;
993 mfc_free_input_buffers_.push_back(i);
995 mfc_input_buffer_queued_count_ = 0;
996 mfc_free_output_buffers_.clear();
997 for (size_t i = 0; i < mfc_output_buffer_map_.size(); ++i) {
998 MfcOutputRecord& output_record = mfc_output_buffer_map_[i];
999 output_record.at_device = false;
1000 output_record.buffer_ref.reset();
1001 mfc_free_output_buffers_.push_back(i);
1003 mfc_output_buffer_queued_count_ = 0;
1004 encoder_output_queue_.clear();
1006 DVLOG(3) << "StopDevicePoll(): device poll stopped";
1010 bool ExynosVideoEncodeAccelerator::SetDevicePollInterrupt() {
1011 DVLOG(3) << "SetDevicePollInterrupt()";
1013 // We might get called here if we fail during initialization, in which case we
1014 // don't have a file descriptor.
1015 if (device_poll_interrupt_fd_ == -1)
1018 const uint64 buf = 1;
1019 if (HANDLE_EINTR((write(device_poll_interrupt_fd_, &buf, sizeof(buf)))) <
1020 static_cast<ssize_t>(sizeof(buf))) {
1021 DPLOG(ERROR) << "SetDevicePollInterrupt(): write() failed";
1022 NOTIFY_ERROR(kPlatformFailureError);
1028 bool ExynosVideoEncodeAccelerator::ClearDevicePollInterrupt() {
1029 DVLOG(3) << "ClearDevicePollInterrupt()";
1031 // We might get called here if we fail during initialization, in which case we
1032 // don't have a file descriptor.
1033 if (device_poll_interrupt_fd_ == -1)
1037 if (HANDLE_EINTR(read(device_poll_interrupt_fd_, &buf, sizeof(buf))) <
1038 static_cast<ssize_t>(sizeof(buf))) {
1039 if (errno == EAGAIN) {
1040 // No interrupt flag set, and we're reading nonblocking. Not an error.
1043 DPLOG(ERROR) << "ClearDevicePollInterrupt(): read() failed";
1044 NOTIFY_ERROR(kPlatformFailureError);
1051 void ExynosVideoEncodeAccelerator::DevicePollTask(unsigned int poll_fds) {
1052 DVLOG(3) << "DevicePollTask()";
1053 DCHECK_EQ(device_poll_thread_.message_loop(), base::MessageLoop::current());
1054 DCHECK_NE(device_poll_interrupt_fd_, -1);
1056 // This routine just polls the set of device fds, and schedules a
1057 // ServiceDeviceTask() on encoder_thread_ when processing needs to occur.
1058 // Other threads may notify this task to return early by writing to
1059 // device_poll_interrupt_fd_.
1060 struct pollfd pollfds[3];
1063 // Add device_poll_interrupt_fd_;
1064 pollfds[0].fd = device_poll_interrupt_fd_;
1065 pollfds[0].events = POLLIN | POLLERR;
1068 // Add GSC fd, if we should poll on it.
1069 // GSC has to wait until both input and output buffers are queued.
1070 if (poll_fds & kPollGsc) {
1071 DVLOG(3) << "DevicePollTask(): adding GSC to poll() set";
1072 pollfds[nfds].fd = gsc_fd_;
1073 pollfds[nfds].events = POLLIN | POLLOUT | POLLERR;
1076 if (poll_fds & kPollMfc) {
1077 DVLOG(3) << "DevicePollTask(): adding MFC to poll() set";
1078 pollfds[nfds].fd = mfc_fd_;
1079 pollfds[nfds].events = POLLIN | POLLOUT | POLLERR;
1084 if (HANDLE_EINTR(poll(pollfds, nfds, -1)) == -1) {
1085 DPLOG(ERROR) << "DevicePollTask(): poll() failed";
1086 NOTIFY_ERROR(kPlatformFailureError);
1090 // All processing should happen on ServiceDeviceTask(), since we shouldn't
1091 // touch encoder state from this thread.
1092 encoder_thread_.message_loop()->PostTask(
1094 base::Bind(&ExynosVideoEncodeAccelerator::ServiceDeviceTask,
1095 base::Unretained(this)));
1098 void ExynosVideoEncodeAccelerator::NotifyError(Error error) {
1099 DVLOG(1) << "NotifyError(): error=" << error;
1101 if (!child_message_loop_proxy_->BelongsToCurrentThread()) {
1102 child_message_loop_proxy_->PostTask(
1105 &ExynosVideoEncodeAccelerator::NotifyError, weak_this_, error));
1110 client_->NotifyError(error);
1111 client_ptr_factory_.InvalidateWeakPtrs();
1115 void ExynosVideoEncodeAccelerator::SetEncoderState(State state) {
1116 DVLOG(3) << "SetEncoderState(): state=" << state;
1118 // We can touch encoder_state_ only if this is the encoder thread or the
1119 // encoder thread isn't running.
1120 if (encoder_thread_.message_loop() != NULL &&
1121 encoder_thread_.message_loop() != base::MessageLoop::current()) {
1122 encoder_thread_.message_loop()->PostTask(
1124 base::Bind(&ExynosVideoEncodeAccelerator::SetEncoderState,
1125 base::Unretained(this),
1128 encoder_state_ = state;
1132 void ExynosVideoEncodeAccelerator::RequestEncodingParametersChangeTask(
1135 DVLOG(3) << "RequestEncodingParametersChangeTask(): bitrate=" << bitrate
1136 << ", framerate=" << framerate;
1137 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
1144 struct v4l2_ext_control ctrls[1];
1145 struct v4l2_ext_controls control;
1146 memset(&ctrls, 0, sizeof(ctrls));
1147 memset(&control, 0, sizeof(control));
1148 ctrls[0].id = V4L2_CID_MPEG_VIDEO_BITRATE;
1149 ctrls[0].value = bitrate;
1150 control.ctrl_class = V4L2_CTRL_CLASS_MPEG;
1151 control.count = arraysize(ctrls);
1152 control.controls = ctrls;
1153 IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_S_EXT_CTRLS, &control);
1155 struct v4l2_streamparm parms;
1156 memset(&parms, 0, sizeof(parms));
1157 parms.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1158 // Note that we are provided "frames per second" but V4L2 expects "time per
1159 // frame"; hence we provide the reciprocal of the framerate here.
1160 parms.parm.output.timeperframe.numerator = 1;
1161 parms.parm.output.timeperframe.denominator = framerate;
1162 IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_S_PARM, &parms);
1165 bool ExynosVideoEncodeAccelerator::CreateGscInputBuffers() {
1166 DVLOG(3) << "CreateGscInputBuffers()";
1167 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1168 DCHECK_EQ(encoder_state_, kUninitialized);
1169 DCHECK(!gsc_input_streamon_);
1171 struct v4l2_control control;
1172 memset(&control, 0, sizeof(control));
1173 control.id = V4L2_CID_ROTATE;
1175 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1177 // HFLIP actually seems to control vertical mirroring for GSC, and vice-versa.
1178 memset(&control, 0, sizeof(control));
1179 control.id = V4L2_CID_HFLIP;
1181 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1183 memset(&control, 0, sizeof(control));
1184 control.id = V4L2_CID_VFLIP;
1186 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1188 memset(&control, 0, sizeof(control));
1189 control.id = V4L2_CID_ALPHA_COMPONENT;
1190 control.value = 255;
1191 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1193 struct v4l2_format format;
1194 memset(&format, 0, sizeof(format));
1195 format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1196 format.fmt.pix_mp.width = input_allocated_size_.width();
1197 format.fmt.pix_mp.height = input_allocated_size_.height();
1198 format.fmt.pix_mp.pixelformat = input_format_fourcc_;
1199 switch (input_format_fourcc_) {
1200 case V4L2_PIX_FMT_RGB32:
1201 format.fmt.pix_mp.plane_fmt[0].sizeimage =
1202 input_allocated_size_.GetArea() * 4;
1203 format.fmt.pix_mp.plane_fmt[0].bytesperline =
1204 input_allocated_size_.width() * 4;
1205 format.fmt.pix_mp.num_planes = 1;
1207 case V4L2_PIX_FMT_YUV420M:
1208 format.fmt.pix_mp.plane_fmt[0].sizeimage =
1209 input_allocated_size_.GetArea();
1210 format.fmt.pix_mp.plane_fmt[0].bytesperline =
1211 input_allocated_size_.width();
1212 format.fmt.pix_mp.plane_fmt[1].sizeimage =
1213 input_allocated_size_.GetArea() / 4;
1214 format.fmt.pix_mp.plane_fmt[1].bytesperline =
1215 input_allocated_size_.width() / 2;
1216 format.fmt.pix_mp.plane_fmt[2].sizeimage =
1217 input_allocated_size_.GetArea() / 4;
1218 format.fmt.pix_mp.plane_fmt[2].bytesperline =
1219 input_allocated_size_.width() / 2;
1220 format.fmt.pix_mp.num_planes = 3;
1224 NOTIFY_ERROR(kIllegalStateError);
1227 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_FMT, &format);
1229 struct v4l2_crop crop;
1230 memset(&crop, 0, sizeof(crop));
1231 crop.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1234 crop.c.width = input_visible_size_.width();
1235 crop.c.height = input_visible_size_.height();
1236 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CROP, &crop);
1238 struct v4l2_requestbuffers reqbufs;
1239 memset(&reqbufs, 0, sizeof(reqbufs));
1240 reqbufs.count = kGscInputBufferCount;
1241 reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1242 reqbufs.memory = V4L2_MEMORY_USERPTR;
1243 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_REQBUFS, &reqbufs);
1245 DCHECK(gsc_input_buffer_map_.empty());
1246 gsc_input_buffer_map_.resize(reqbufs.count);
1247 for (size_t i = 0; i < gsc_input_buffer_map_.size(); ++i)
1248 gsc_free_input_buffers_.push_back(i);
1253 bool ExynosVideoEncodeAccelerator::CreateGscOutputBuffers() {
1254 DVLOG(3) << "CreateGscOutputBuffers()";
1255 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1256 DCHECK_EQ(encoder_state_, kUninitialized);
1257 DCHECK(!gsc_output_streamon_);
1259 struct v4l2_format format;
1260 memset(&format, 0, sizeof(format));
1261 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1262 format.fmt.pix_mp.width = converted_allocated_size_.width();
1263 format.fmt.pix_mp.height = converted_allocated_size_.height();
1264 format.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12M;
1265 format.fmt.pix_mp.plane_fmt[0].sizeimage =
1266 converted_allocated_size_.GetArea();
1267 format.fmt.pix_mp.plane_fmt[1].sizeimage =
1268 converted_allocated_size_.GetArea() / 2;
1269 format.fmt.pix_mp.plane_fmt[0].bytesperline =
1270 converted_allocated_size_.width();
1271 format.fmt.pix_mp.plane_fmt[1].bytesperline =
1272 converted_allocated_size_.width();
1273 format.fmt.pix_mp.num_planes = 2;
1274 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_FMT, &format);
1276 struct v4l2_crop crop;
1277 memset(&crop, 0, sizeof(crop));
1278 crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1281 crop.c.width = converted_visible_size_.width();
1282 crop.c.height = converted_visible_size_.height();
1283 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CROP, &crop);
1285 struct v4l2_requestbuffers reqbufs;
1286 memset(&reqbufs, 0, sizeof(reqbufs));
1287 reqbufs.count = kGscOutputBufferCount;
1288 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1289 reqbufs.memory = V4L2_MEMORY_DMABUF;
1290 IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_REQBUFS, &reqbufs);
1292 DCHECK(gsc_output_buffer_map_.empty());
1293 gsc_output_buffer_map_.resize(reqbufs.count);
1294 for (size_t i = 0; i < gsc_output_buffer_map_.size(); ++i)
1295 gsc_free_output_buffers_.push_back(i);
1299 bool ExynosVideoEncodeAccelerator::SetMfcFormats() {
1300 DVLOG(3) << "SetMfcFormats()";
1301 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1302 DCHECK(!mfc_input_streamon_);
1303 DCHECK(!mfc_output_streamon_);
1305 // VIDIOC_S_FMT on OUTPUT queue.
1306 struct v4l2_format format;
1307 memset(&format, 0, sizeof(format));
1308 format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1309 format.fmt.pix_mp.width = input_allocated_size_.width();
1310 format.fmt.pix_mp.height = input_allocated_size_.height();
1311 format.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12M;
1312 format.fmt.pix_mp.num_planes = 2;
1313 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_S_FMT, &format);
1314 // We read direct from GSC, so we rely on the HW not changing our set
1316 DCHECK_EQ(format.fmt.pix_mp.plane_fmt[0].sizeimage,
1317 static_cast<__u32>(input_allocated_size_.GetArea()));
1318 DCHECK_EQ(format.fmt.pix_mp.plane_fmt[0].bytesperline,
1319 static_cast<__u32>(input_allocated_size_.width()));
1320 DCHECK_EQ(format.fmt.pix_mp.plane_fmt[1].sizeimage,
1321 static_cast<__u32>(input_allocated_size_.GetArea() / 2));
1322 DCHECK_EQ(format.fmt.pix_mp.plane_fmt[1].bytesperline,
1323 static_cast<__u32>(input_allocated_size_.width()));
1325 struct v4l2_crop crop;
1326 memset(&crop, 0, sizeof(crop));
1327 crop.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
1330 crop.c.width = input_visible_size_.width();
1331 crop.c.height = input_visible_size_.height();
1332 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_S_CROP, &crop);
1334 // VIDIOC_S_FMT on CAPTURE queue.
1335 output_buffer_byte_size_ = kMfcOutputBufferSize;
1336 memset(&format, 0, sizeof(format));
1337 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1338 format.fmt.pix_mp.width = output_visible_size_.width();
1339 format.fmt.pix_mp.height = output_visible_size_.height();
1340 format.fmt.pix_mp.pixelformat = output_format_fourcc_;
1341 format.fmt.pix_mp.plane_fmt[0].sizeimage = output_buffer_byte_size_;
1342 format.fmt.pix_mp.num_planes = 1;
1343 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_S_FMT, &format);
1348 bool ExynosVideoEncodeAccelerator::InitMfcControls() {
1349 struct v4l2_ext_control ctrls[9];
1350 struct v4l2_ext_controls control;
1351 memset(&ctrls, 0, sizeof(ctrls));
1352 memset(&control, 0, sizeof(control));
1353 // No B-frames, for lowest decoding latency.
1354 ctrls[0].id = V4L2_CID_MPEG_VIDEO_B_FRAMES;
1356 // Enable frame-level bitrate control.
1357 ctrls[1].id = V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE;
1359 // Enable "tight" bitrate mode. For this to work properly, frame- and mb-level
1360 // bitrate controls have to be enabled as well.
1361 ctrls[2].id = V4L2_CID_MPEG_MFC51_VIDEO_RC_REACTION_COEFF;
1363 // Force bitrate control to average over a GOP (for tight bitrate
1365 ctrls[3].id = V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT;
1367 // Quantization parameter maximum value (for variable bitrate control).
1368 ctrls[4].id = V4L2_CID_MPEG_VIDEO_H264_MAX_QP;
1369 ctrls[4].value = 51;
1370 // Separate stream header so we can cache it and insert into the stream.
1371 ctrls[5].id = V4L2_CID_MPEG_VIDEO_HEADER_MODE;
1372 ctrls[5].value = V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE;
1373 // Enable macroblock-level bitrate control.
1374 ctrls[6].id = V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE;
1376 // Use H.264 level 4.0 to match the supported max resolution.
1377 ctrls[7].id = V4L2_CID_MPEG_VIDEO_H264_LEVEL;
1378 ctrls[7].value = V4L2_MPEG_VIDEO_H264_LEVEL_4_0;
1379 // Disable periodic key frames.
1380 ctrls[8].id = V4L2_CID_MPEG_VIDEO_GOP_SIZE;
1382 control.ctrl_class = V4L2_CTRL_CLASS_MPEG;
1383 control.count = arraysize(ctrls);
1384 control.controls = ctrls;
1385 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_S_EXT_CTRLS, &control);
1390 bool ExynosVideoEncodeAccelerator::CreateMfcInputBuffers() {
1391 DVLOG(3) << "CreateMfcInputBuffers()";
1392 // This function runs on encoder_thread_ after output buffers have been
1393 // provided by the client.
1394 DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
1395 DCHECK(!mfc_input_streamon_);
1397 struct v4l2_requestbuffers reqbufs;
1398 memset(&reqbufs, 0, sizeof(reqbufs));
1399 reqbufs.count = 1; // Driver will allocate the appropriate number of buffers.
1400 reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1401 reqbufs.memory = V4L2_MEMORY_MMAP;
1402 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_REQBUFS, &reqbufs);
1404 DCHECK(mfc_input_buffer_map_.empty());
1405 mfc_input_buffer_map_.resize(reqbufs.count);
1406 for (size_t i = 0; i < mfc_input_buffer_map_.size(); ++i) {
1407 MfcInputRecord& input_record = mfc_input_buffer_map_[i];
1408 for (int j = 0; j < 2; ++j) {
1409 // Export the DMABUF fd so GSC can write to it.
1410 struct v4l2_exportbuffer expbuf;
1411 memset(&expbuf, 0, sizeof(expbuf));
1412 expbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1415 expbuf.flags = O_CLOEXEC;
1416 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_EXPBUF, &expbuf);
1417 input_record.fd[j] = expbuf.fd;
1419 mfc_free_input_buffers_.push_back(i);
1425 bool ExynosVideoEncodeAccelerator::CreateMfcOutputBuffers() {
1426 DVLOG(3) << "CreateMfcOutputBuffers()";
1427 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1428 DCHECK(!mfc_output_streamon_);
1430 struct v4l2_requestbuffers reqbufs;
1431 memset(&reqbufs, 0, sizeof(reqbufs));
1432 reqbufs.count = kMfcOutputBufferCount;
1433 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1434 reqbufs.memory = V4L2_MEMORY_MMAP;
1435 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_REQBUFS, &reqbufs);
1437 DCHECK(mfc_output_buffer_map_.empty());
1438 mfc_output_buffer_map_.resize(reqbufs.count);
1439 for (size_t i = 0; i < mfc_output_buffer_map_.size(); ++i) {
1440 struct v4l2_plane planes[1];
1441 struct v4l2_buffer buffer;
1442 memset(&buffer, 0, sizeof(buffer));
1443 memset(planes, 0, sizeof(planes));
1445 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1446 buffer.memory = V4L2_MEMORY_MMAP;
1447 buffer.m.planes = planes;
1448 buffer.length = arraysize(planes);
1449 IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_QUERYBUF, &buffer);
1450 void* address = mmap(NULL, buffer.m.planes[0].length,
1451 PROT_READ | PROT_WRITE, MAP_SHARED, mfc_fd_,
1452 buffer.m.planes[0].m.mem_offset);
1453 if (address == MAP_FAILED) {
1454 DPLOG(ERROR) << "CreateMfcOutputBuffers(): mmap() failed";
1457 mfc_output_buffer_map_[i].address = address;
1458 mfc_output_buffer_map_[i].length = buffer.m.planes[0].length;
1459 mfc_free_output_buffers_.push_back(i);
1465 void ExynosVideoEncodeAccelerator::DestroyGscInputBuffers() {
1466 DVLOG(3) << "DestroyGscInputBuffers()";
1467 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1468 DCHECK(!gsc_input_streamon_);
1470 struct v4l2_requestbuffers reqbufs;
1471 memset(&reqbufs, 0, sizeof(reqbufs));
1473 reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1474 reqbufs.memory = V4L2_MEMORY_USERPTR;
1475 if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_REQBUFS, &reqbufs)) != 0)
1476 DPLOG(ERROR) << "DestroyGscInputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1478 gsc_input_buffer_map_.clear();
1479 gsc_free_input_buffers_.clear();
1482 void ExynosVideoEncodeAccelerator::DestroyGscOutputBuffers() {
1483 DVLOG(3) << "DestroyGscOutputBuffers()";
1484 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1485 DCHECK(!gsc_output_streamon_);
1487 struct v4l2_requestbuffers reqbufs;
1488 memset(&reqbufs, 0, sizeof(reqbufs));
1490 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1491 reqbufs.memory = V4L2_MEMORY_DMABUF;
1492 if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_REQBUFS, &reqbufs)) != 0)
1493 DPLOG(ERROR) << "DestroyGscOutputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1495 gsc_output_buffer_map_.clear();
1496 gsc_free_output_buffers_.clear();
1499 void ExynosVideoEncodeAccelerator::DestroyMfcInputBuffers() {
1500 DVLOG(3) << "DestroyMfcInputBuffers()";
1501 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1502 DCHECK(!mfc_input_streamon_);
1504 for (size_t buf = 0; buf < mfc_input_buffer_map_.size(); ++buf) {
1505 MfcInputRecord& input_record = mfc_input_buffer_map_[buf];
1507 for (size_t plane = 0; plane < arraysize(input_record.fd); ++plane)
1508 close(mfc_input_buffer_map_[buf].fd[plane]);
1511 struct v4l2_requestbuffers reqbufs;
1512 memset(&reqbufs, 0, sizeof(reqbufs));
1514 reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1515 reqbufs.memory = V4L2_MEMORY_MMAP;
1516 if (HANDLE_EINTR(ioctl(mfc_fd_, VIDIOC_REQBUFS, &reqbufs)) != 0)
1517 DPLOG(ERROR) << "DestroyMfcInputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1519 mfc_input_buffer_map_.clear();
1520 mfc_free_input_buffers_.clear();
1523 void ExynosVideoEncodeAccelerator::DestroyMfcOutputBuffers() {
1524 DVLOG(3) << "DestroyMfcOutputBuffers()";
1525 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1526 DCHECK(!mfc_output_streamon_);
1528 for (size_t i = 0; i < mfc_output_buffer_map_.size(); ++i) {
1529 if (mfc_output_buffer_map_[i].address != NULL) {
1530 munmap(mfc_output_buffer_map_[i].address,
1531 mfc_output_buffer_map_[i].length);
1535 struct v4l2_requestbuffers reqbufs;
1536 memset(&reqbufs, 0, sizeof(reqbufs));
1538 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1539 reqbufs.memory = V4L2_MEMORY_MMAP;
1540 if (HANDLE_EINTR(ioctl(mfc_fd_, VIDIOC_REQBUFS, &reqbufs)) != 0)
1541 DPLOG(ERROR) << "DestroyMfcOutputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1543 mfc_output_buffer_map_.clear();
1544 mfc_free_output_buffers_.clear();
1547 } // namespace content