Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / content / common / gpu / media / exynos_video_encode_accelerator.cc
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.
4
5 #include "content/common/gpu/media/exynos_video_encode_accelerator.h"
6
7 #include <fcntl.h>
8 #include <linux/videodev2.h>
9 #include <poll.h>
10 #include <sys/eventfd.h>
11 #include <sys/ioctl.h>
12 #include <sys/mman.h>
13
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"
21
22 #define NOTIFY_ERROR(x)                                            \
23   do {                                                             \
24     SetEncoderState(kError);                                       \
25     DLOG(ERROR) << "calling NotifyError(): " << x;                 \
26     NotifyError(x);                                                \
27   } while (0)
28
29 #define IOCTL_OR_ERROR_RETURN(fd, type, arg)                       \
30   do {                                                             \
31     if (HANDLE_EINTR(ioctl(fd, type, arg) != 0)) {                 \
32       DPLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
33       NOTIFY_ERROR(kPlatformFailureError);                         \
34       return;                                                      \
35     }                                                              \
36   } while (0)
37
38 #define IOCTL_OR_ERROR_RETURN_FALSE(fd, type, arg)                 \
39   do {                                                             \
40     if (HANDLE_EINTR(ioctl(fd, type, arg) != 0)) {                 \
41       DPLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
42       NOTIFY_ERROR(kPlatformFailureError);                         \
43       return false;                                                \
44     }                                                              \
45   } while (0)
46
47 namespace content {
48
49 namespace {
50
51 const char kExynosGscDevice[] = "/dev/gsc1";
52 const char kExynosMfcDevice[] = "/dev/mfc-enc";
53
54 // File descriptors we need to poll, one-bit flag for each.
55 enum PollFds {
56   kPollGsc = (1 << 0),
57   kPollMfc = (1 << 1),
58 };
59
60 }  // anonymous namespace
61
62 struct ExynosVideoEncodeAccelerator::BitstreamBufferRef {
63   BitstreamBufferRef(int32 id, scoped_ptr<base::SharedMemory> shm, size_t size)
64       : id(id), shm(shm.Pass()), size(size) {}
65   const int32 id;
66   const scoped_ptr<base::SharedMemory> shm;
67   const size_t size;
68 };
69
70
71 ExynosVideoEncodeAccelerator::GscInputRecord::GscInputRecord()
72     : at_device(false) {}
73
74 ExynosVideoEncodeAccelerator::GscOutputRecord::GscOutputRecord()
75     : at_device(false), mfc_input(-1) {}
76
77 ExynosVideoEncodeAccelerator::MfcInputRecord::MfcInputRecord()
78     : at_device(false) {
79   fd[0] = fd[1] = -1;
80 }
81
82 ExynosVideoEncodeAccelerator::MfcOutputRecord::MfcOutputRecord()
83     : at_device(false), address(NULL), length(0) {}
84
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),
98       gsc_fd_(-1),
99       gsc_input_streamon_(false),
100       gsc_input_buffer_queued_count_(0),
101       gsc_output_streamon_(false),
102       gsc_output_buffer_queued_count_(0),
103       mfc_fd_(-1),
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) {
110   DCHECK(client_);
111 }
112
113 ExynosVideoEncodeAccelerator::~ExynosVideoEncodeAccelerator() {
114   DCHECK(!encoder_thread_.IsRunning());
115   DCHECK(!device_poll_thread_.IsRunning());
116
117   if (device_poll_interrupt_fd_ != -1) {
118     close(device_poll_interrupt_fd_);
119     device_poll_interrupt_fd_ = -1;
120   }
121   if (gsc_fd_ != -1) {
122     DestroyGscInputBuffers();
123     DestroyGscOutputBuffers();
124     close(gsc_fd_);
125     gsc_fd_ = -1;
126   }
127   if (mfc_fd_ != -1) {
128     DestroyMfcInputBuffers();
129     DestroyMfcOutputBuffers();
130     close(mfc_fd_);
131     mfc_fd_ = -1;
132   }
133 }
134
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;
144
145   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
146   DCHECK_EQ(encoder_state_, kUninitialized);
147
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_;
157
158   switch (input_format) {
159     case media::VideoFrame::I420:
160       input_format_fourcc_ = V4L2_PIX_FMT_YUV420M;
161       break;
162     default:
163       NOTIFY_ERROR(kInvalidArgumentError);
164       return;
165   }
166
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;
173   } else {
174     NOTIFY_ERROR(kInvalidArgumentError);
175     return;
176   }
177
178   // Open the color conversion device.
179   DVLOG(2) << "Initialize(): opening GSC device: " << kExynosGscDevice;
180   gsc_fd_ =
181       HANDLE_EINTR(open(kExynosGscDevice, O_RDWR | O_NONBLOCK | O_CLOEXEC));
182   if (gsc_fd_ == -1) {
183     DPLOG(ERROR) << "Initialize(): could not open GSC device: "
184                  << kExynosGscDevice;
185     NOTIFY_ERROR(kPlatformFailureError);
186     return;
187   }
188
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);
199     return;
200   }
201
202   // Open the video encoder device.
203   DVLOG(2) << "Initialize(): opening MFC device: " << kExynosMfcDevice;
204   mfc_fd_ =
205       HANDLE_EINTR(open(kExynosMfcDevice, O_RDWR | O_NONBLOCK | O_CLOEXEC));
206   if (mfc_fd_ == -1) {
207     DPLOG(ERROR) << "Initialize(): could not open MFC device: "
208                  << kExynosMfcDevice;
209     NOTIFY_ERROR(kPlatformFailureError);
210     return;
211   }
212
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);
219     return;
220   }
221
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);
228     return;
229   }
230
231   DVLOG(3)
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();
237
238   if (!CreateGscInputBuffers() || !CreateGscOutputBuffers())
239     return;
240
241   // MFC setup for encoding is rather particular in ordering:
242   //
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
246   //    queue.
247   //
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.
253
254   if (!SetMfcFormats())
255     return;
256
257   if (!InitMfcControls())
258     return;
259
260   // VIDIOC_REQBUFS on CAPTURE queue.
261   if (!CreateMfcOutputBuffers())
262     return;
263
264
265   if (!encoder_thread_.Start()) {
266     DLOG(ERROR) << "Initialize(): encoder thread failed to start";
267     NOTIFY_ERROR(kPlatformFailureError);
268     return;
269   }
270
271   RequestEncodingParametersChange(initial_bitrate, kInitialFramerate);
272
273   SetEncoderState(kInitialized);
274
275   child_message_loop_proxy_->PostTask(
276       FROM_HERE, base::Bind(&Client::NotifyInitializeDone, client_));
277
278   child_message_loop_proxy_->PostTask(
279       FROM_HERE,
280       base::Bind(&Client::RequireBitstreamBuffers,
281                  client_,
282                  gsc_input_buffer_map_.size(),
283                  input_allocated_size_,
284                  output_buffer_byte_size_));
285 }
286
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());
292
293   encoder_thread_.message_loop()->PostTask(
294       FROM_HERE,
295       base::Bind(&ExynosVideoEncodeAccelerator::EncodeTask,
296                  base::Unretained(this),
297                  frame,
298                  force_keyframe));
299 }
300
301 void ExynosVideoEncodeAccelerator::UseOutputBitstreamBuffer(
302     const media::BitstreamBuffer& buffer) {
303   DVLOG(3) << "UseOutputBitstreamBuffer(): id=" << buffer.id();
304   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
305
306   if (buffer.size() < output_buffer_byte_size_) {
307     NOTIFY_ERROR(kInvalidArgumentError);
308     return;
309   }
310
311   scoped_ptr<base::SharedMemory> shm(
312       new base::SharedMemory(buffer.handle(), false));
313   if (!shm->Map(buffer.size())) {
314     NOTIFY_ERROR(kPlatformFailureError);
315     return;
316   }
317
318   scoped_ptr<BitstreamBufferRef> buffer_ref(
319       new BitstreamBufferRef(buffer.id(), shm.Pass(), buffer.size()));
320   encoder_thread_.message_loop()->PostTask(
321       FROM_HERE,
322       base::Bind(&ExynosVideoEncodeAccelerator::UseOutputBitstreamBufferTask,
323                  base::Unretained(this),
324                  base::Passed(&buffer_ref)));
325 }
326
327 void ExynosVideoEncodeAccelerator::RequestEncodingParametersChange(
328     uint32 bitrate,
329     uint32 framerate) {
330   DVLOG(3) << "RequestEncodingParametersChange(): bitrate=" << bitrate
331            << ", framerate=" << framerate;
332   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
333
334   encoder_thread_.message_loop()->PostTask(
335       FROM_HERE,
336       base::Bind(
337           &ExynosVideoEncodeAccelerator::RequestEncodingParametersChangeTask,
338           base::Unretained(this),
339           bitrate,
340           framerate));
341 }
342
343 void ExynosVideoEncodeAccelerator::Destroy() {
344   DVLOG(3) << "Destroy()";
345   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
346
347   // We're destroying; cancel all callbacks.
348   client_ptr_factory_.InvalidateWeakPtrs();
349
350   // If the encoder thread is running, destroy using posted task.
351   if (encoder_thread_.IsRunning()) {
352     encoder_thread_.message_loop()->PostTask(
353         FROM_HERE,
354         base::Bind(&ExynosVideoEncodeAccelerator::DestroyTask,
355                    base::Unretained(this)));
356     // DestroyTask() will put the encoder into kError state and cause all tasks
357     // to no-op.
358     encoder_thread_.Stop();
359   } else {
360     // Otherwise, call the destroy task directly.
361     DestroyTask();
362   }
363
364   // Set to kError state just in case.
365   SetEncoderState(kError);
366
367   delete this;
368 }
369
370 // static
371 std::vector<media::VideoEncodeAccelerator::SupportedProfile>
372 ExynosVideoEncodeAccelerator::GetSupportedProfiles() {
373   std::vector<SupportedProfile> profiles;
374
375   SupportedProfile profile;
376
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);
384   } else {
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);
390   }
391
392   return profiles;
393 }
394
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);
400
401   if (encoder_state_ == kError) {
402     DVLOG(2) << "EncodeTask(): early out: kError state";
403     return;
404   }
405
406   encoder_input_queue_.push_back(frame);
407   EnqueueGsc();
408
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;
421     control.count = 1;
422     control.controls = ctrls;
423     IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_S_EXT_CTRLS, &control);
424   }
425 }
426
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());
431
432   encoder_output_queue_.push_back(
433       linked_ptr<BitstreamBufferRef>(buffer_ref.release()));
434   EnqueueMfc();
435
436   if (encoder_state_ == kInitialized) {
437     // Finish setting up our MFC OUTPUT queue.  See: Initialize().
438     // VIDIOC_REQBUFS on OUTPUT queue.
439     if (!CreateMfcInputBuffers())
440       return;
441     if (!StartDevicePoll())
442       return;
443     encoder_state_ = kEncoding;
444   }
445 }
446
447 void ExynosVideoEncodeAccelerator::DestroyTask() {
448   DVLOG(3) << "DestroyTask()";
449
450   // DestroyTask() should run regardless of encoder_state_.
451
452   // Stop streaming and the device_poll_thread_.
453   StopDevicePoll();
454
455   // Set our state to kError, and early-out all tasks.
456   encoder_state_ = kError;
457 }
458
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);
464
465   if (encoder_state_ == kError) {
466     DVLOG(2) << "ServiceDeviceTask(): early out: kError state";
467     return;
468   }
469
470   DequeueGsc();
471   DequeueMfc();
472   EnqueueGsc();
473   EnqueueMfc();
474
475   // Clear the interrupt fd.
476   if (!ClearDevicePollInterrupt())
477     return;
478
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;
488
489   // ServiceDeviceTask() should only ever be scheduled from DevicePollTask(),
490   // so either:
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
494   //   already.
495   DCHECK(device_poll_thread_.message_loop());
496   // Queue the DevicePollTask() now.
497   device_poll_thread_.message_loop()->PostTask(
498       FROM_HERE,
499       base::Bind(&ExynosVideoEncodeAccelerator::DevicePollTask,
500                  base::Unretained(this),
501                  poll_fds));
502
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() << "]";
519 }
520
521 void ExynosVideoEncodeAccelerator::EnqueueGsc() {
522   DVLOG(3) << "EnqueueGsc()";
523   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
524
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())
528       return;
529   }
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())
534       return;
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;
540     }
541   }
542
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
545   // buffers as well.
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())
553       return;
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())
558         return;
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;
564       }
565     }
566   }
567   DCHECK_LE(gsc_output_buffer_queued_count_, 1);
568 }
569
570 void ExynosVideoEncodeAccelerator::DequeueGsc() {
571   DVLOG(3) << "DequeueGsc()";
572   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
573
574   // Dequeue completed GSC input (VIDEO_OUTPUT) buffers, and recycle to the free
575   // list.
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.
589         break;
590       }
591       DPLOG(ERROR) << "DequeueGsc(): ioctl() failed: VIDIOC_DQBUF";
592       NOTIFY_ERROR(kPlatformFailureError);
593       return;
594     }
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_--;
602   }
603
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
606   // queue.
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;
614     dqbuf.length   = 2;
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.
618         break;
619       }
620       DPLOG(ERROR) << "DequeueGsc(): ioctl() failed: VIDIOC_DQBUF";
621       NOTIFY_ERROR(kPlatformFailureError);
622       return;
623     }
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_--;
632   }
633 }
634 void ExynosVideoEncodeAccelerator::EnqueueMfc() {
635   DVLOG(3) << "EnqueueMfc()";
636   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
637
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())
642       return;
643   }
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())
648       return;
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;
654     }
655   }
656
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())
661       return;
662   }
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())
667       return;
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;
673     }
674   }
675 }
676
677 void ExynosVideoEncodeAccelerator::DequeueMfc() {
678   DVLOG(3) << "DequeueMfc()";
679   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
680
681   // Dequeue completed MFC input (VIDEO_OUTPUT) buffers, and recycle to the free
682   // list.
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;
692     dqbuf.length   = 2;
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.
696         break;
697       }
698       DPLOG(ERROR) << "DequeueMfc(): ioctl() failed: VIDIOC_DQBUF";
699       NOTIFY_ERROR(kPlatformFailureError);
700       return;
701     }
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_--;
707   }
708
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;
718     dqbuf.length   = 1;
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.
722         break;
723       }
724       DPLOG(ERROR) << "DequeueMfc(): ioctl() failed: VIDIOC_DQBUF";
725       NOTIFY_ERROR(kPlatformFailureError);
726       return;
727     }
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());
732
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_;
740     uint8* target_data =
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_);
748       }
749       if (key_frame &&
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_;
755       } else {
756         memcpy(target_data, output_data, output_size);
757       }
758     } else {
759       memcpy(target_data, output_data, output_size);
760     }
761
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(
766         FROM_HERE,
767         base::Bind(&Client::BitstreamBufferReady,
768                    client_,
769                    output_record.buffer_ref->id,
770                    output_size,
771                    key_frame));
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_--;
776   }
777 }
778
779 bool ExynosVideoEncodeAccelerator::EnqueueGscInputRecord() {
780   DVLOG(3) << "EnqueueGscInputRecord()";
781   DCHECK(!encoder_input_queue_.empty());
782   DCHECK(!gsc_free_input_buffers_.empty());
783
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));
812       qbuf.length = 3;
813       break;
814     }
815     default:
816       NOTREACHED();
817       NOTIFY_ERROR(kIllegalStateError);
818       return false;
819   }
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_++;
826   return true;
827 }
828
829 bool ExynosVideoEncodeAccelerator::EnqueueGscOutputRecord() {
830   DVLOG(3) << "EnqueueGscOutputRecord()";
831   DCHECK(!gsc_free_output_buffers_.empty());
832   DCHECK(!mfc_free_input_buffers_.empty());
833
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];
852   qbuf.length           = 2;
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_++;
859   return true;
860 }
861
862 bool ExynosVideoEncodeAccelerator::EnqueueMfcInputRecord() {
863   DVLOG(3) << "EnqueueMfcInputRecord()";
864   DCHECK(!mfc_ready_input_buffers_.empty());
865
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;
878   qbuf.length    = 2;
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_++;
883   return true;
884 }
885
886 bool ExynosVideoEncodeAccelerator::EnqueueMfcOutputRecord() {
887   DVLOG(3) << "EnqueueMfcOutputRecord()";
888   DCHECK(!mfc_free_output_buffers_.empty());
889   DCHECK(!encoder_output_queue_.empty());
890
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;
905   qbuf.length                = 1;
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_++;
912   return true;
913 }
914
915 bool ExynosVideoEncodeAccelerator::StartDevicePoll() {
916   DVLOG(3) << "StartDevicePoll()";
917   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
918   DCHECK(!device_poll_thread_.IsRunning());
919
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);
924     return false;
925   }
926   // Enqueue a poll task with no devices to poll on -- it will wait only on the
927   // interrupt fd.
928   device_poll_thread_.message_loop()->PostTask(
929       FROM_HERE,
930       base::Bind(&ExynosVideoEncodeAccelerator::DevicePollTask,
931                  base::Unretained(this),
932                  0));
933
934   return true;
935 }
936
937 bool ExynosVideoEncodeAccelerator::StopDevicePoll() {
938   DVLOG(3) << "StopDevicePoll()";
939
940   // Signal the DevicePollTask() to stop, and stop the device poll thread.
941   if (!SetDevicePollInterrupt())
942     return false;
943   device_poll_thread_.Stop();
944   // Clear the interrupt now, to be sure.
945   if (!ClearDevicePollInterrupt())
946     return false;
947
948   // Stop streaming.
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);
952   }
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);
957   }
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);
962   }
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);
967   }
968   mfc_output_streamon_ = false;
969
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);
978   }
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);
986   }
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);
994   }
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);
1002   }
1003   mfc_output_buffer_queued_count_ = 0;
1004   encoder_output_queue_.clear();
1005
1006   DVLOG(3) << "StopDevicePoll(): device poll stopped";
1007   return true;
1008 }
1009
1010 bool ExynosVideoEncodeAccelerator::SetDevicePollInterrupt() {
1011   DVLOG(3) << "SetDevicePollInterrupt()";
1012
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)
1016     return true;
1017
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);
1023     return false;
1024   }
1025   return true;
1026 }
1027
1028 bool ExynosVideoEncodeAccelerator::ClearDevicePollInterrupt() {
1029   DVLOG(3) << "ClearDevicePollInterrupt()";
1030
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)
1034     return true;
1035
1036   uint64 buf;
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.
1041       return true;
1042     } else {
1043       DPLOG(ERROR) << "ClearDevicePollInterrupt(): read() failed";
1044       NOTIFY_ERROR(kPlatformFailureError);
1045       return false;
1046     }
1047   }
1048   return true;
1049 }
1050
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);
1055
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];
1061   nfds_t nfds;
1062
1063   // Add device_poll_interrupt_fd_;
1064   pollfds[0].fd = device_poll_interrupt_fd_;
1065   pollfds[0].events = POLLIN | POLLERR;
1066   nfds = 1;
1067
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;
1074     nfds++;
1075   }
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;
1080     nfds++;
1081   }
1082
1083   // Poll it!
1084   if (HANDLE_EINTR(poll(pollfds, nfds, -1)) == -1) {
1085     DPLOG(ERROR) << "DevicePollTask(): poll() failed";
1086     NOTIFY_ERROR(kPlatformFailureError);
1087     return;
1088   }
1089
1090   // All processing should happen on ServiceDeviceTask(), since we shouldn't
1091   // touch encoder state from this thread.
1092   encoder_thread_.message_loop()->PostTask(
1093       FROM_HERE,
1094       base::Bind(&ExynosVideoEncodeAccelerator::ServiceDeviceTask,
1095                  base::Unretained(this)));
1096 }
1097
1098 void ExynosVideoEncodeAccelerator::NotifyError(Error error) {
1099   DVLOG(1) << "NotifyError(): error=" << error;
1100
1101   if (!child_message_loop_proxy_->BelongsToCurrentThread()) {
1102     child_message_loop_proxy_->PostTask(
1103         FROM_HERE,
1104         base::Bind(
1105             &ExynosVideoEncodeAccelerator::NotifyError, weak_this_, error));
1106     return;
1107   }
1108
1109   if (client_) {
1110     client_->NotifyError(error);
1111     client_ptr_factory_.InvalidateWeakPtrs();
1112   }
1113 }
1114
1115 void ExynosVideoEncodeAccelerator::SetEncoderState(State state) {
1116   DVLOG(3) << "SetEncoderState(): state=" << state;
1117
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(
1123         FROM_HERE,
1124         base::Bind(&ExynosVideoEncodeAccelerator::SetEncoderState,
1125                    base::Unretained(this),
1126                    state));
1127   } else {
1128     encoder_state_ = state;
1129   }
1130 }
1131
1132 void ExynosVideoEncodeAccelerator::RequestEncodingParametersChangeTask(
1133     uint32 bitrate,
1134     uint32 framerate) {
1135   DVLOG(3) << "RequestEncodingParametersChangeTask(): bitrate=" << bitrate
1136            << ", framerate=" << framerate;
1137   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
1138
1139   if (bitrate < 1)
1140     bitrate = 1;
1141   if (framerate < 1)
1142     framerate = 1;
1143
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);
1154
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);
1163 }
1164
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_);
1170
1171   struct v4l2_control control;
1172   memset(&control, 0, sizeof(control));
1173   control.id    = V4L2_CID_ROTATE;
1174   control.value = 0;
1175   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1176
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;
1180   control.value = 0;
1181   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1182
1183   memset(&control, 0, sizeof(control));
1184   control.id    = V4L2_CID_VFLIP;
1185   control.value = 0;
1186   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1187
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);
1192
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;
1206       break;
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;
1221       break;
1222     default:
1223       NOTREACHED();
1224       NOTIFY_ERROR(kIllegalStateError);
1225       return false;
1226   }
1227   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_FMT, &format);
1228
1229   struct v4l2_crop crop;
1230   memset(&crop, 0, sizeof(crop));
1231   crop.type     = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1232   crop.c.left   = 0;
1233   crop.c.top    = 0;
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);
1237
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);
1244
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);
1249
1250   return true;
1251 }
1252
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_);
1258
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);
1275
1276   struct v4l2_crop crop;
1277   memset(&crop, 0, sizeof(crop));
1278   crop.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1279   crop.c.left   = 0;
1280   crop.c.top    = 0;
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);
1284
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);
1291
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);
1296   return true;
1297 }
1298
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_);
1304
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
1315   // size/stride.
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()));
1324
1325   struct v4l2_crop crop;
1326   memset(&crop, 0, sizeof(crop));
1327   crop.type     = V4L2_BUF_TYPE_VIDEO_OUTPUT;
1328   crop.c.left   = 0;
1329   crop.c.top    = 0;
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);
1333
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);
1344
1345   return true;
1346 }
1347
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;
1355   ctrls[0].value = 0;
1356   // Enable frame-level bitrate control.
1357   ctrls[1].id    = V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE;
1358   ctrls[1].value = 1;
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;
1362   ctrls[2].value = 1;
1363   // Force bitrate control to average over a GOP (for tight bitrate
1364   // tolerance).
1365   ctrls[3].id    = V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT;
1366   ctrls[3].value = 1;
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;
1375   ctrls[6].value = 1;
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;
1381   ctrls[8].value = 0;
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);
1386
1387   return true;
1388 }
1389
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_);
1396
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);
1403
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;
1413       expbuf.index = i;
1414       expbuf.plane = j;
1415       expbuf.flags = O_CLOEXEC;
1416       IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_EXPBUF, &expbuf);
1417       input_record.fd[j] = expbuf.fd;
1418     }
1419     mfc_free_input_buffers_.push_back(i);
1420   }
1421
1422   return true;
1423 }
1424
1425 bool ExynosVideoEncodeAccelerator::CreateMfcOutputBuffers() {
1426   DVLOG(3) << "CreateMfcOutputBuffers()";
1427   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1428   DCHECK(!mfc_output_streamon_);
1429
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);
1436
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));
1444     buffer.index    = i;
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";
1455       return false;
1456     }
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);
1460   }
1461
1462   return true;
1463 }
1464
1465 void ExynosVideoEncodeAccelerator::DestroyGscInputBuffers() {
1466   DVLOG(3) << "DestroyGscInputBuffers()";
1467   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1468   DCHECK(!gsc_input_streamon_);
1469
1470   struct v4l2_requestbuffers reqbufs;
1471   memset(&reqbufs, 0, sizeof(reqbufs));
1472   reqbufs.count = 0;
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";
1477
1478   gsc_input_buffer_map_.clear();
1479   gsc_free_input_buffers_.clear();
1480 }
1481
1482 void ExynosVideoEncodeAccelerator::DestroyGscOutputBuffers() {
1483   DVLOG(3) << "DestroyGscOutputBuffers()";
1484   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1485   DCHECK(!gsc_output_streamon_);
1486
1487   struct v4l2_requestbuffers reqbufs;
1488   memset(&reqbufs, 0, sizeof(reqbufs));
1489   reqbufs.count = 0;
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";
1494
1495   gsc_output_buffer_map_.clear();
1496   gsc_free_output_buffers_.clear();
1497 }
1498
1499 void ExynosVideoEncodeAccelerator::DestroyMfcInputBuffers() {
1500   DVLOG(3) << "DestroyMfcInputBuffers()";
1501   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1502   DCHECK(!mfc_input_streamon_);
1503
1504   for (size_t buf = 0; buf < mfc_input_buffer_map_.size(); ++buf) {
1505     MfcInputRecord& input_record = mfc_input_buffer_map_[buf];
1506
1507     for (size_t plane = 0; plane < arraysize(input_record.fd); ++plane)
1508       close(mfc_input_buffer_map_[buf].fd[plane]);
1509   }
1510
1511   struct v4l2_requestbuffers reqbufs;
1512   memset(&reqbufs, 0, sizeof(reqbufs));
1513   reqbufs.count = 0;
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";
1518
1519   mfc_input_buffer_map_.clear();
1520   mfc_free_input_buffers_.clear();
1521 }
1522
1523 void ExynosVideoEncodeAccelerator::DestroyMfcOutputBuffers() {
1524   DVLOG(3) << "DestroyMfcOutputBuffers()";
1525   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1526   DCHECK(!mfc_output_streamon_);
1527
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);
1532     }
1533   }
1534
1535   struct v4l2_requestbuffers reqbufs;
1536   memset(&reqbufs, 0, sizeof(reqbufs));
1537   reqbufs.count = 0;
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";
1542
1543   mfc_output_buffer_map_.clear();
1544   mfc_free_output_buffers_.clear();
1545 }
1546
1547 }  // namespace content