- add sources.
[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     HANDLE_EINTR(close(device_poll_interrupt_fd_));
119     device_poll_interrupt_fd_ = -1;
120   }
121   if (gsc_fd_ != -1) {
122     DestroyGscInputBuffers();
123     DestroyGscOutputBuffers();
124     HANDLE_EINTR(close(gsc_fd_));
125     gsc_fd_ = -1;
126   }
127   if (mfc_fd_ != -1) {
128     DestroyMfcInputBuffers();
129     DestroyMfcOutputBuffers();
130     HANDLE_EINTR(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::RGB32:
160       input_format_fourcc_ = V4L2_PIX_FMT_RGB32;
161       break;
162     case media::VideoFrame::I420:
163       input_format_fourcc_ = V4L2_PIX_FMT_YUV420M;
164       break;
165     default:
166       NOTIFY_ERROR(kInvalidArgumentError);
167       return;
168   }
169
170   if (output_profile >= media::H264PROFILE_MIN &&
171       output_profile <= media::H264PROFILE_MAX) {
172     output_format_fourcc_ = V4L2_PIX_FMT_H264;
173   } else if (output_profile >= media::VP8PROFILE_MIN &&
174              output_profile <= media::VP8PROFILE_MAX) {
175     output_format_fourcc_ = V4L2_PIX_FMT_VP8;
176   } else {
177     NOTIFY_ERROR(kInvalidArgumentError);
178     return;
179   }
180
181   // Open the color conversion device.
182   DVLOG(2) << "Initialize(): opening GSC device: " << kExynosGscDevice;
183   gsc_fd_ =
184       HANDLE_EINTR(open(kExynosGscDevice, O_RDWR | O_NONBLOCK | O_CLOEXEC));
185   if (gsc_fd_ == -1) {
186     DPLOG(ERROR) << "Initialize(): could not open GSC device: "
187                  << kExynosGscDevice;
188     NOTIFY_ERROR(kPlatformFailureError);
189     return;
190   }
191
192   // Capabilities check.
193   struct v4l2_capability caps;
194   memset(&caps, 0, sizeof(caps));
195   const __u32 kCapsRequired = V4L2_CAP_VIDEO_CAPTURE_MPLANE |
196                               V4L2_CAP_VIDEO_OUTPUT_MPLANE | V4L2_CAP_STREAMING;
197   IOCTL_OR_ERROR_RETURN(gsc_fd_, VIDIOC_QUERYCAP, &caps);
198   if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
199     DLOG(ERROR) << "Initialize(): ioctl() failed: VIDIOC_QUERYCAP: "
200                    "caps check failed: 0x" << std::hex << caps.capabilities;
201     NOTIFY_ERROR(kPlatformFailureError);
202     return;
203   }
204
205   // Open the video encoder device.
206   DVLOG(2) << "Initialize(): opening MFC device: " << kExynosMfcDevice;
207   mfc_fd_ =
208       HANDLE_EINTR(open(kExynosMfcDevice, O_RDWR | O_NONBLOCK | O_CLOEXEC));
209   if (mfc_fd_ == -1) {
210     DPLOG(ERROR) << "Initialize(): could not open MFC device: "
211                  << kExynosMfcDevice;
212     NOTIFY_ERROR(kPlatformFailureError);
213     return;
214   }
215
216   memset(&caps, 0, sizeof(caps));
217   IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_QUERYCAP, &caps);
218   if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
219     DLOG(ERROR) << "Initialize(): ioctl() failed: VIDIOC_QUERYCAP: "
220                    "caps check failed: 0x" << std::hex << caps.capabilities;
221     NOTIFY_ERROR(kPlatformFailureError);
222     return;
223   }
224
225   // Create the interrupt fd.
226   DCHECK_EQ(device_poll_interrupt_fd_, -1);
227   device_poll_interrupt_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
228   if (device_poll_interrupt_fd_ == -1) {
229     DPLOG(ERROR) << "Initialize(): eventfd() failed";
230     NOTIFY_ERROR(kPlatformFailureError);
231     return;
232   }
233
234   DVLOG(3)
235       << "Initialize(): input_visible_size_=" << input_visible_size_.ToString()
236       << ", input_allocated_size_=" << input_allocated_size_.ToString()
237       << ", converted_visible_size_=" << converted_visible_size_.ToString()
238       << ", converted_allocated_size_=" << converted_allocated_size_.ToString()
239       << ", output_visible_size_=" << output_visible_size_.ToString();
240
241   if (!CreateGscInputBuffers() || !CreateGscOutputBuffers())
242     return;
243
244   // MFC setup for encoding is rather particular in ordering:
245   //
246   // 1. Format (VIDIOC_S_FMT) set first on OUTPUT and CAPTURE queues.
247   // 2. VIDIOC_REQBUFS, VIDIOC_QBUF, and VIDIOC_STREAMON on CAPTURE queue.
248   // 3. VIDIOC_REQBUFS (and later VIDIOC_QBUF and VIDIOC_STREAMON) on OUTPUT
249   //    queue.
250   //
251   // Unfortunately, we cannot do (3) in Initialize() here since we have no
252   // buffers to QBUF in step (2) until the client has provided output buffers
253   // through UseOutputBitstreamBuffer().  So, we just do (1), and the
254   // VIDIOC_REQBUFS part of (2) here.  The rest is done the first time we get
255   // a UseOutputBitstreamBuffer() callback.
256
257   if (!SetMfcFormats())
258     return;
259
260   if (!InitMfcControls())
261     return;
262
263   // VIDIOC_REQBUFS on CAPTURE queue.
264   if (!CreateMfcOutputBuffers())
265     return;
266
267
268   if (!encoder_thread_.Start()) {
269     DLOG(ERROR) << "Initialize(): encoder thread failed to start";
270     NOTIFY_ERROR(kPlatformFailureError);
271     return;
272   }
273
274   RequestEncodingParametersChange(initial_bitrate, kInitialFramerate);
275
276   SetEncoderState(kInitialized);
277
278   child_message_loop_proxy_->PostTask(
279       FROM_HERE, base::Bind(&Client::NotifyInitializeDone, client_));
280
281   child_message_loop_proxy_->PostTask(
282       FROM_HERE,
283       base::Bind(&Client::RequireBitstreamBuffers,
284                  client_,
285                  gsc_input_buffer_map_.size(),
286                  input_allocated_size_,
287                  output_buffer_byte_size_));
288 }
289
290 void ExynosVideoEncodeAccelerator::Encode(
291     const scoped_refptr<media::VideoFrame>& frame,
292     bool force_keyframe) {
293   DVLOG(3) << "Encode(): force_keyframe=" << force_keyframe;
294   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
295
296   encoder_thread_.message_loop()->PostTask(
297       FROM_HERE,
298       base::Bind(&ExynosVideoEncodeAccelerator::EncodeTask,
299                  base::Unretained(this),
300                  frame,
301                  force_keyframe));
302 }
303
304 void ExynosVideoEncodeAccelerator::UseOutputBitstreamBuffer(
305     const media::BitstreamBuffer& buffer) {
306   DVLOG(3) << "UseOutputBitstreamBuffer(): id=" << buffer.id();
307   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
308
309   if (buffer.size() < output_buffer_byte_size_) {
310     NOTIFY_ERROR(kInvalidArgumentError);
311     return;
312   }
313
314   scoped_ptr<base::SharedMemory> shm(
315       new base::SharedMemory(buffer.handle(), false));
316   if (!shm->Map(buffer.size())) {
317     NOTIFY_ERROR(kPlatformFailureError);
318     return;
319   }
320
321   scoped_ptr<BitstreamBufferRef> buffer_ref(
322       new BitstreamBufferRef(buffer.id(), shm.Pass(), buffer.size()));
323   encoder_thread_.message_loop()->PostTask(
324       FROM_HERE,
325       base::Bind(&ExynosVideoEncodeAccelerator::UseOutputBitstreamBufferTask,
326                  base::Unretained(this),
327                  base::Passed(&buffer_ref)));
328 }
329
330 void ExynosVideoEncodeAccelerator::RequestEncodingParametersChange(
331     uint32 bitrate,
332     uint32 framerate) {
333   DVLOG(3) << "RequestEncodingParametersChange(): bitrate=" << bitrate
334            << ", framerate=" << framerate;
335   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
336
337   encoder_thread_.message_loop()->PostTask(
338       FROM_HERE,
339       base::Bind(
340           &ExynosVideoEncodeAccelerator::RequestEncodingParametersChangeTask,
341           base::Unretained(this),
342           bitrate,
343           framerate));
344 }
345
346 void ExynosVideoEncodeAccelerator::Destroy() {
347   DVLOG(3) << "Destroy()";
348   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
349
350   // We're destroying; cancel all callbacks.
351   client_ptr_factory_.InvalidateWeakPtrs();
352
353   // If the encoder thread is running, destroy using posted task.
354   if (encoder_thread_.IsRunning()) {
355     encoder_thread_.message_loop()->PostTask(
356         FROM_HERE,
357         base::Bind(&ExynosVideoEncodeAccelerator::DestroyTask,
358                    base::Unretained(this)));
359     // DestroyTask() will put the encoder into kError state and cause all tasks
360     // to no-op.
361     encoder_thread_.Stop();
362   } else {
363     // Otherwise, call the destroy task directly.
364     DestroyTask();
365   }
366
367   // Set to kError state just in case.
368   SetEncoderState(kError);
369
370   delete this;
371 }
372
373 // static
374 std::vector<media::VideoEncodeAccelerator::SupportedProfile>
375 ExynosVideoEncodeAccelerator::GetSupportedProfiles() {
376   std::vector<SupportedProfile> profiles;
377
378   SupportedProfile profile;
379
380   const CommandLine* cmd_line = CommandLine::ForCurrentProcess();
381   if (cmd_line->HasSwitch(switches::kEnableWebRtcHWVp8Encoding)) {
382     profile.profile = media::VP8PROFILE_MAIN;
383     profile.max_resolution.SetSize(1920, 1088);
384     profile.max_framerate.numerator = 30;
385     profile.max_framerate.denominator = 1;
386     profiles.push_back(profile);
387   } else {
388     profile.profile = media::H264PROFILE_MAIN;
389     profile.max_resolution.SetSize(1920, 1088);
390     profile.max_framerate.numerator = 30;
391     profile.max_framerate.denominator = 1;
392     profiles.push_back(profile);
393   }
394
395   return profiles;
396 }
397
398 void ExynosVideoEncodeAccelerator::EncodeTask(
399     const scoped_refptr<media::VideoFrame>& frame, bool force_keyframe) {
400   DVLOG(3) << "EncodeTask(): force_keyframe=" << force_keyframe;
401   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
402   DCHECK_NE(encoder_state_, kUninitialized);
403
404   if (encoder_state_ == kError) {
405     DVLOG(2) << "EncodeTask(): early out: kError state";
406     return;
407   }
408
409   encoder_input_queue_.push_back(frame);
410   EnqueueGsc();
411
412   if (force_keyframe) {
413     // TODO(sheu): this presently makes for slightly imprecise encoding
414     // parameters updates.  To precisely align the parameter updates with the
415     // incoming input frame, we should track the parameters through the GSC
416     // pipeline and only apply them when the MFC input is about to be queued.
417     struct v4l2_ext_control ctrls[1];
418     struct v4l2_ext_controls control;
419     memset(&ctrls, 0, sizeof(ctrls));
420     memset(&control, 0, sizeof(control));
421     ctrls[0].id    = V4L2_CID_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE;
422     ctrls[0].value = V4L2_MPEG_MFC51_VIDEO_FORCE_FRAME_TYPE_I_FRAME;
423     control.ctrl_class = V4L2_CTRL_CLASS_MPEG;
424     control.count = 1;
425     control.controls = ctrls;
426     IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_S_EXT_CTRLS, &control);
427   }
428 }
429
430 void ExynosVideoEncodeAccelerator::UseOutputBitstreamBufferTask(
431     scoped_ptr<BitstreamBufferRef> buffer_ref) {
432   DVLOG(3) << "UseOutputBitstreamBufferTask(): id=" << buffer_ref->id;
433   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
434
435   encoder_output_queue_.push_back(
436       linked_ptr<BitstreamBufferRef>(buffer_ref.release()));
437   EnqueueMfc();
438
439   if (encoder_state_ == kInitialized) {
440     // Finish setting up our MFC OUTPUT queue.  See: Initialize().
441     // VIDIOC_REQBUFS on OUTPUT queue.
442     if (!CreateMfcInputBuffers())
443       return;
444     if (!StartDevicePoll())
445       return;
446     encoder_state_ = kEncoding;
447   }
448 }
449
450 void ExynosVideoEncodeAccelerator::DestroyTask() {
451   DVLOG(3) << "DestroyTask()";
452
453   // DestroyTask() should run regardless of encoder_state_.
454
455   // Stop streaming and the device_poll_thread_.
456   StopDevicePoll();
457
458   // Set our state to kError, and early-out all tasks.
459   encoder_state_ = kError;
460 }
461
462 void ExynosVideoEncodeAccelerator::ServiceDeviceTask() {
463   DVLOG(3) << "ServiceDeviceTask()";
464   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
465   DCHECK_NE(encoder_state_, kUninitialized);
466   DCHECK_NE(encoder_state_, kInitialized);
467
468   if (encoder_state_ == kError) {
469     DVLOG(2) << "ServiceDeviceTask(): early out: kError state";
470     return;
471   }
472
473   DequeueGsc();
474   DequeueMfc();
475   EnqueueGsc();
476   EnqueueMfc();
477
478   // Clear the interrupt fd.
479   if (!ClearDevicePollInterrupt())
480     return;
481
482   unsigned int poll_fds = 0;
483   // Add GSC fd, if we should poll on it.
484   // GSC has to wait until both input and output buffers are queued.
485   if (gsc_input_buffer_queued_count_ > 0 && gsc_output_buffer_queued_count_ > 0)
486     poll_fds |= kPollGsc;
487   // Add MFC fd, if we should poll on it.
488   // MFC can be polled as soon as either input or output buffers are queued.
489   if (mfc_input_buffer_queued_count_ + mfc_output_buffer_queued_count_ > 0)
490     poll_fds |= kPollMfc;
491
492   // ServiceDeviceTask() should only ever be scheduled from DevicePollTask(),
493   // so either:
494   // * device_poll_thread_ is running normally
495   // * device_poll_thread_ scheduled us, but then a DestroyTask() shut it down,
496   //   in which case we're in kError state, and we should have early-outed
497   //   already.
498   DCHECK(device_poll_thread_.message_loop());
499   // Queue the DevicePollTask() now.
500   device_poll_thread_.message_loop()->PostTask(
501       FROM_HERE,
502       base::Bind(&ExynosVideoEncodeAccelerator::DevicePollTask,
503                  base::Unretained(this),
504                  poll_fds));
505
506   DVLOG(2) << "ServiceDeviceTask(): buffer counts: ENC["
507            << encoder_input_queue_.size() << "] => GSC["
508            << gsc_free_input_buffers_.size() << "+"
509            << gsc_input_buffer_queued_count_ << "/"
510            << gsc_input_buffer_map_.size() << "->"
511            << gsc_free_output_buffers_.size() << "+"
512            << gsc_output_buffer_queued_count_ << "/"
513            << gsc_output_buffer_map_.size() << "] => "
514            << mfc_ready_input_buffers_.size() << " => MFC["
515            << mfc_free_input_buffers_.size() << "+"
516            << mfc_input_buffer_queued_count_ << "/"
517            << mfc_input_buffer_map_.size() << "->"
518            << mfc_free_output_buffers_.size() << "+"
519            << mfc_output_buffer_queued_count_ << "/"
520            << mfc_output_buffer_map_.size() << "] => OUT["
521            << encoder_output_queue_.size() << "]";
522 }
523
524 void ExynosVideoEncodeAccelerator::EnqueueGsc() {
525   DVLOG(3) << "EnqueueGsc()";
526   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
527
528   const int old_gsc_inputs_queued = gsc_input_buffer_queued_count_;
529   while (!encoder_input_queue_.empty() && !gsc_free_input_buffers_.empty()) {
530     if (!EnqueueGscInputRecord())
531       return;
532   }
533   if (old_gsc_inputs_queued == 0 && gsc_input_buffer_queued_count_ != 0) {
534     // We started up a previously empty queue.
535     // Queue state changed; signal interrupt.
536     if (!SetDevicePollInterrupt())
537       return;
538     // Start VIDIOC_STREAMON if we haven't yet.
539     if (!gsc_input_streamon_) {
540       __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
541       IOCTL_OR_ERROR_RETURN(gsc_fd_, VIDIOC_STREAMON, &type);
542       gsc_input_streamon_ = true;
543     }
544   }
545
546   // Enqueue a GSC output, only if we need one.  GSC output buffers write
547   // directly to MFC input buffers, so we'll have to check for free MFC input
548   // buffers as well.
549   // GSC is liable to race conditions if more than one output buffer is
550   // simultaneously enqueued, so enqueue just one.
551   if (gsc_input_buffer_queued_count_ != 0 &&
552       gsc_output_buffer_queued_count_ == 0 &&
553       !gsc_free_output_buffers_.empty() && !mfc_free_input_buffers_.empty()) {
554     const int old_gsc_outputs_queued = gsc_output_buffer_queued_count_;
555     if (!EnqueueGscOutputRecord())
556       return;
557     if (old_gsc_outputs_queued == 0 && gsc_output_buffer_queued_count_ != 0) {
558       // We just started up a previously empty queue.
559       // Queue state changed; signal interrupt.
560       if (!SetDevicePollInterrupt())
561         return;
562       // Start VIDIOC_STREAMON if we haven't yet.
563       if (!gsc_output_streamon_) {
564         __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
565         IOCTL_OR_ERROR_RETURN(gsc_fd_, VIDIOC_STREAMON, &type);
566         gsc_output_streamon_ = true;
567       }
568     }
569   }
570   DCHECK_LE(gsc_output_buffer_queued_count_, 1);
571 }
572
573 void ExynosVideoEncodeAccelerator::DequeueGsc() {
574   DVLOG(3) << "DequeueGsc()";
575   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
576
577   // Dequeue completed GSC input (VIDEO_OUTPUT) buffers, and recycle to the free
578   // list.
579   struct v4l2_buffer dqbuf;
580   struct v4l2_plane planes[3];
581   while (gsc_input_buffer_queued_count_ > 0) {
582     DCHECK(gsc_input_streamon_);
583     memset(&dqbuf, 0, sizeof(dqbuf));
584     memset(&planes, 0, sizeof(planes));
585     dqbuf.type     = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
586     dqbuf.memory   = V4L2_MEMORY_USERPTR;
587     dqbuf.m.planes = planes;
588     dqbuf.length   = arraysize(planes);
589     if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_DQBUF, &dqbuf)) != 0) {
590       if (errno == EAGAIN) {
591         // EAGAIN if we're just out of buffers to dequeue.
592         break;
593       }
594       DPLOG(ERROR) << "DequeueGsc(): ioctl() failed: VIDIOC_DQBUF";
595       NOTIFY_ERROR(kPlatformFailureError);
596       return;
597     }
598     GscInputRecord& input_record = gsc_input_buffer_map_[dqbuf.index];
599     DCHECK(input_record.at_device);
600     DCHECK(input_record.frame.get());
601     input_record.at_device = false;
602     input_record.frame = NULL;
603     gsc_free_input_buffers_.push_back(dqbuf.index);
604     gsc_input_buffer_queued_count_--;
605   }
606
607   // Dequeue completed GSC output (VIDEO_CAPTURE) buffers, and recycle to the
608   // free list.  Queue the corresponding MFC buffer to the GSC->MFC holding
609   // queue.
610   while (gsc_output_buffer_queued_count_ > 0) {
611     DCHECK(gsc_output_streamon_);
612     memset(&dqbuf, 0, sizeof(dqbuf));
613     memset(&planes, 0, sizeof(planes));
614     dqbuf.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
615     dqbuf.memory   = V4L2_MEMORY_DMABUF;
616     dqbuf.m.planes = planes;
617     dqbuf.length   = 2;
618     if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_DQBUF, &dqbuf)) != 0) {
619       if (errno == EAGAIN) {
620         // EAGAIN if we're just out of buffers to dequeue.
621         break;
622       }
623       DPLOG(ERROR) << "DequeueGsc(): ioctl() failed: VIDIOC_DQBUF";
624       NOTIFY_ERROR(kPlatformFailureError);
625       return;
626     }
627     GscOutputRecord& output_record = gsc_output_buffer_map_[dqbuf.index];
628     DCHECK(output_record.at_device);
629     DCHECK(output_record.mfc_input != -1);
630     mfc_ready_input_buffers_.push_back(output_record.mfc_input);
631     output_record.at_device = false;
632     output_record.mfc_input = -1;
633     gsc_free_output_buffers_.push_back(dqbuf.index);
634     gsc_output_buffer_queued_count_--;
635   }
636 }
637 void ExynosVideoEncodeAccelerator::EnqueueMfc() {
638   DVLOG(3) << "EnqueueMfc()";
639   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
640
641   // Enqueue all the MFC inputs we can.
642   const int old_mfc_inputs_queued = mfc_input_buffer_queued_count_;
643   while (!mfc_ready_input_buffers_.empty()) {
644     if (!EnqueueMfcInputRecord())
645       return;
646   }
647   if (old_mfc_inputs_queued == 0 && mfc_input_buffer_queued_count_ != 0) {
648     // We just started up a previously empty queue.
649     // Queue state changed; signal interrupt.
650     if (!SetDevicePollInterrupt())
651       return;
652     // Start VIDIOC_STREAMON if we haven't yet.
653     if (!mfc_input_streamon_) {
654       __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
655       IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_STREAMON, &type);
656       mfc_input_streamon_ = true;
657     }
658   }
659
660   // Enqueue all the MFC outputs we can.
661   const int old_mfc_outputs_queued = mfc_output_buffer_queued_count_;
662   while (!mfc_free_output_buffers_.empty() && !encoder_output_queue_.empty()) {
663     if (!EnqueueMfcOutputRecord())
664       return;
665   }
666   if (old_mfc_outputs_queued == 0 && mfc_output_buffer_queued_count_ != 0) {
667     // We just started up a previously empty queue.
668     // Queue state changed; signal interrupt.
669     if (!SetDevicePollInterrupt())
670       return;
671     // Start VIDIOC_STREAMON if we haven't yet.
672     if (!mfc_output_streamon_) {
673       __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
674       IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_STREAMON, &type);
675       mfc_output_streamon_ = true;
676     }
677   }
678 }
679
680 void ExynosVideoEncodeAccelerator::DequeueMfc() {
681   DVLOG(3) << "DequeueMfc()";
682   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
683
684   // Dequeue completed MFC input (VIDEO_OUTPUT) buffers, and recycle to the free
685   // list.
686   struct v4l2_buffer dqbuf;
687   struct v4l2_plane planes[2];
688   while (mfc_input_buffer_queued_count_ > 0) {
689     DCHECK(mfc_input_streamon_);
690     memset(&dqbuf, 0, sizeof(dqbuf));
691     memset(&planes, 0, sizeof(planes));
692     dqbuf.type     = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
693     dqbuf.memory   = V4L2_MEMORY_MMAP;
694     dqbuf.m.planes = planes;
695     dqbuf.length   = 2;
696     if (HANDLE_EINTR(ioctl(mfc_fd_, VIDIOC_DQBUF, &dqbuf)) != 0) {
697       if (errno == EAGAIN) {
698         // EAGAIN if we're just out of buffers to dequeue.
699         break;
700       }
701       DPLOG(ERROR) << "DequeueMfc(): ioctl() failed: VIDIOC_DQBUF";
702       NOTIFY_ERROR(kPlatformFailureError);
703       return;
704     }
705     MfcInputRecord& input_record = mfc_input_buffer_map_[dqbuf.index];
706     DCHECK(input_record.at_device);
707     input_record.at_device = false;
708     mfc_free_input_buffers_.push_back(dqbuf.index);
709     mfc_input_buffer_queued_count_--;
710   }
711
712   // Dequeue completed MFC output (VIDEO_CAPTURE) buffers, and recycle to the
713   // free list.  Notify the client that an output buffer is complete.
714   while (mfc_output_buffer_queued_count_ > 0) {
715     DCHECK(mfc_output_streamon_);
716     memset(&dqbuf, 0, sizeof(dqbuf));
717     memset(planes, 0, sizeof(planes));
718     dqbuf.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
719     dqbuf.memory   = V4L2_MEMORY_MMAP;
720     dqbuf.m.planes = planes;
721     dqbuf.length   = 1;
722     if (HANDLE_EINTR(ioctl(mfc_fd_, VIDIOC_DQBUF, &dqbuf)) != 0) {
723       if (errno == EAGAIN) {
724         // EAGAIN if we're just out of buffers to dequeue.
725         break;
726       }
727       DPLOG(ERROR) << "DequeueMfc(): ioctl() failed: VIDIOC_DQBUF";
728       NOTIFY_ERROR(kPlatformFailureError);
729       return;
730     }
731     const bool key_frame = ((dqbuf.flags & V4L2_BUF_FLAG_KEYFRAME) != 0);
732     MfcOutputRecord& output_record = mfc_output_buffer_map_[dqbuf.index];
733     DCHECK(output_record.at_device);
734     DCHECK(output_record.buffer_ref.get());
735
736     void* output_data = output_record.address;
737     size_t output_size = dqbuf.m.planes[0].bytesused;
738     // This shouldn't happen, but just in case. We should be able to recover
739     // after next keyframe after showing some corruption.
740     DCHECK_LE(output_size, output_buffer_byte_size_);
741     if (output_size > output_buffer_byte_size_)
742       output_size = output_buffer_byte_size_;
743     uint8* target_data =
744         reinterpret_cast<uint8*>(output_record.buffer_ref->shm->memory());
745     if (output_format_fourcc_ == V4L2_PIX_FMT_H264) {
746       if (stream_header_size_ == 0) {
747         // Assume that the first buffer dequeued is the stream header.
748         stream_header_size_ = output_size;
749         stream_header_.reset(new uint8[stream_header_size_]);
750         memcpy(stream_header_.get(), output_data, stream_header_size_);
751       }
752       if (key_frame &&
753           output_buffer_byte_size_ - stream_header_size_ >= output_size) {
754         // Insert stream header before every keyframe.
755         memcpy(target_data, stream_header_.get(), stream_header_size_);
756         memcpy(target_data + stream_header_size_, output_data, output_size);
757         output_size += stream_header_size_;
758       } else {
759         memcpy(target_data, output_data, output_size);
760       }
761     } else {
762       memcpy(target_data, output_data, output_size);
763     }
764
765     DVLOG(3) << "DequeueMfc(): returning "
766                 "bitstream_buffer_id=" << output_record.buffer_ref->id
767              << ", key_frame=" << key_frame;
768     child_message_loop_proxy_->PostTask(
769         FROM_HERE,
770         base::Bind(&Client::BitstreamBufferReady,
771                    client_,
772                    output_record.buffer_ref->id,
773                    output_size,
774                    key_frame));
775     output_record.at_device = false;
776     output_record.buffer_ref.reset();
777     mfc_free_output_buffers_.push_back(dqbuf.index);
778     mfc_output_buffer_queued_count_--;
779   }
780 }
781
782 bool ExynosVideoEncodeAccelerator::EnqueueGscInputRecord() {
783   DVLOG(3) << "EnqueueGscInputRecord()";
784   DCHECK(!encoder_input_queue_.empty());
785   DCHECK(!gsc_free_input_buffers_.empty());
786
787   // Enqueue a GSC input (VIDEO_OUTPUT) buffer for an input video frame
788   scoped_refptr<media::VideoFrame> frame = encoder_input_queue_.front();
789   const int gsc_buffer = gsc_free_input_buffers_.back();
790   GscInputRecord& input_record = gsc_input_buffer_map_[gsc_buffer];
791   DCHECK(!input_record.at_device);
792   DCHECK(!input_record.frame.get());
793   struct v4l2_buffer qbuf;
794   struct v4l2_plane qbuf_planes[3];
795   memset(&qbuf, 0, sizeof(qbuf));
796   memset(qbuf_planes, 0, sizeof(qbuf_planes));
797   qbuf.index    = gsc_buffer;
798   qbuf.type     = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
799   qbuf.memory   = V4L2_MEMORY_USERPTR;
800   qbuf.m.planes = qbuf_planes;
801   switch (input_format_fourcc_) {
802     case V4L2_PIX_FMT_RGB32: {
803       qbuf.m.planes[0].bytesused = input_allocated_size_.GetArea() * 4;
804       qbuf.m.planes[0].length    = input_allocated_size_.GetArea() * 4;
805       qbuf.m.planes[0].m.userptr = reinterpret_cast<unsigned long>(
806           frame->data(media::VideoFrame::kRGBPlane));
807       qbuf.length = 1;
808       break;
809     }
810     case V4L2_PIX_FMT_YUV420M: {
811       qbuf.m.planes[0].bytesused = input_allocated_size_.GetArea();
812       qbuf.m.planes[0].length    = input_allocated_size_.GetArea();
813       qbuf.m.planes[0].m.userptr = reinterpret_cast<unsigned long>(
814           frame->data(media::VideoFrame::kYPlane));
815       qbuf.m.planes[1].bytesused = input_allocated_size_.GetArea() / 4;
816       qbuf.m.planes[1].length    = input_allocated_size_.GetArea() / 4;
817       qbuf.m.planes[1].m.userptr = reinterpret_cast<unsigned long>(
818           frame->data(media::VideoFrame::kUPlane));
819       qbuf.m.planes[2].bytesused = input_allocated_size_.GetArea() / 4;
820       qbuf.m.planes[2].length    = input_allocated_size_.GetArea() / 4;
821       qbuf.m.planes[2].m.userptr = reinterpret_cast<unsigned long>(
822           frame->data(media::VideoFrame::kVPlane));
823       qbuf.length = 3;
824       break;
825     }
826     default:
827       NOTREACHED();
828       NOTIFY_ERROR(kIllegalStateError);
829       return false;
830   }
831   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_QBUF, &qbuf);
832   input_record.at_device = true;
833   input_record.frame = frame;
834   encoder_input_queue_.pop_front();
835   gsc_free_input_buffers_.pop_back();
836   gsc_input_buffer_queued_count_++;
837   return true;
838 }
839
840 bool ExynosVideoEncodeAccelerator::EnqueueGscOutputRecord() {
841   DVLOG(3) << "EnqueueGscOutputRecord()";
842   DCHECK(!gsc_free_output_buffers_.empty());
843   DCHECK(!mfc_free_input_buffers_.empty());
844
845   // Enqueue a GSC output (VIDEO_CAPTURE) buffer.
846   const int gsc_buffer = gsc_free_output_buffers_.back();
847   const int mfc_buffer = mfc_free_input_buffers_.back();
848   GscOutputRecord& output_record = gsc_output_buffer_map_[gsc_buffer];
849   MfcInputRecord& input_record = mfc_input_buffer_map_[mfc_buffer];
850   DCHECK(!output_record.at_device);
851   DCHECK_EQ(output_record.mfc_input, -1);
852   DCHECK(!input_record.at_device);
853   struct v4l2_buffer qbuf;
854   struct v4l2_plane qbuf_planes[2];
855   memset(&qbuf, 0, sizeof(qbuf));
856   memset(qbuf_planes, 0, sizeof(qbuf_planes));
857   qbuf.index            = gsc_buffer;
858   qbuf.type             = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
859   qbuf.memory           = V4L2_MEMORY_DMABUF;
860   qbuf.m.planes         = qbuf_planes;
861   qbuf.m.planes[0].m.fd = input_record.fd[0];
862   qbuf.m.planes[1].m.fd = input_record.fd[1];
863   qbuf.length           = 2;
864   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_QBUF, &qbuf);
865   output_record.at_device = true;
866   output_record.mfc_input = mfc_buffer;
867   mfc_free_input_buffers_.pop_back();
868   gsc_free_output_buffers_.pop_back();
869   gsc_output_buffer_queued_count_++;
870   return true;
871 }
872
873 bool ExynosVideoEncodeAccelerator::EnqueueMfcInputRecord() {
874   DVLOG(3) << "EnqueueMfcInputRecord()";
875   DCHECK(!mfc_ready_input_buffers_.empty());
876
877   // Enqueue a MFC input (VIDEO_OUTPUT) buffer.
878   const int mfc_buffer = mfc_ready_input_buffers_.front();
879   MfcInputRecord& input_record = mfc_input_buffer_map_[mfc_buffer];
880   DCHECK(!input_record.at_device);
881   struct v4l2_buffer qbuf;
882   struct v4l2_plane qbuf_planes[2];
883   memset(&qbuf, 0, sizeof(qbuf));
884   memset(qbuf_planes, 0, sizeof(qbuf_planes));
885   qbuf.index     = mfc_buffer;
886   qbuf.type      = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
887   qbuf.memory    = V4L2_MEMORY_MMAP;
888   qbuf.m.planes  = qbuf_planes;
889   qbuf.length    = 2;
890   IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_QBUF, &qbuf);
891   input_record.at_device = true;
892   mfc_ready_input_buffers_.pop_front();
893   mfc_input_buffer_queued_count_++;
894   return true;
895 }
896
897 bool ExynosVideoEncodeAccelerator::EnqueueMfcOutputRecord() {
898   DVLOG(3) << "EnqueueMfcOutputRecord()";
899   DCHECK(!mfc_free_output_buffers_.empty());
900   DCHECK(!encoder_output_queue_.empty());
901
902   // Enqueue a MFC output (VIDEO_CAPTURE) buffer.
903   linked_ptr<BitstreamBufferRef> output_buffer = encoder_output_queue_.back();
904   const int mfc_buffer = mfc_free_output_buffers_.back();
905   MfcOutputRecord& output_record = mfc_output_buffer_map_[mfc_buffer];
906   DCHECK(!output_record.at_device);
907   DCHECK(!output_record.buffer_ref.get());
908   struct v4l2_buffer qbuf;
909   struct v4l2_plane qbuf_planes[1];
910   memset(&qbuf, 0, sizeof(qbuf));
911   memset(qbuf_planes, 0, sizeof(qbuf_planes));
912   qbuf.index                 = mfc_buffer;
913   qbuf.type                  = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
914   qbuf.memory                = V4L2_MEMORY_MMAP;
915   qbuf.m.planes              = qbuf_planes;
916   qbuf.length                = 1;
917   IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_QBUF, &qbuf);
918   output_record.at_device = true;
919   output_record.buffer_ref = output_buffer;
920   encoder_output_queue_.pop_back();
921   mfc_free_output_buffers_.pop_back();
922   mfc_output_buffer_queued_count_++;
923   return true;
924 }
925
926 bool ExynosVideoEncodeAccelerator::StartDevicePoll() {
927   DVLOG(3) << "StartDevicePoll()";
928   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
929   DCHECK(!device_poll_thread_.IsRunning());
930
931   // Start up the device poll thread and schedule its first DevicePollTask().
932   if (!device_poll_thread_.Start()) {
933     DLOG(ERROR) << "StartDevicePoll(): Device thread failed to start";
934     NOTIFY_ERROR(kPlatformFailureError);
935     return false;
936   }
937   // Enqueue a poll task with no devices to poll on -- it will wait only on the
938   // interrupt fd.
939   device_poll_thread_.message_loop()->PostTask(
940       FROM_HERE,
941       base::Bind(&ExynosVideoEncodeAccelerator::DevicePollTask,
942                  base::Unretained(this),
943                  0));
944
945   return true;
946 }
947
948 bool ExynosVideoEncodeAccelerator::StopDevicePoll() {
949   DVLOG(3) << "StopDevicePoll()";
950
951   // Signal the DevicePollTask() to stop, and stop the device poll thread.
952   if (!SetDevicePollInterrupt())
953     return false;
954   device_poll_thread_.Stop();
955   // Clear the interrupt now, to be sure.
956   if (!ClearDevicePollInterrupt())
957     return false;
958
959   // Stop streaming.
960   if (gsc_input_streamon_) {
961     __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
962     IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_STREAMOFF, &type);
963   }
964   gsc_input_streamon_ = false;
965   if (gsc_output_streamon_) {
966     __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
967     IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_STREAMOFF, &type);
968   }
969   gsc_output_streamon_ = false;
970   if (mfc_input_streamon_) {
971     __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
972     IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_STREAMOFF, &type);
973   }
974   mfc_input_streamon_ = false;
975   if (mfc_output_streamon_) {
976     __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
977     IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_STREAMOFF, &type);
978   }
979   mfc_output_streamon_ = false;
980
981   // Reset all our accounting info.
982   encoder_input_queue_.clear();
983   gsc_free_input_buffers_.clear();
984   for (size_t i = 0; i < gsc_input_buffer_map_.size(); ++i) {
985     GscInputRecord& input_record = gsc_input_buffer_map_[i];
986     input_record.at_device = false;
987     input_record.frame = NULL;
988     gsc_free_input_buffers_.push_back(i);
989   }
990   gsc_input_buffer_queued_count_ = 0;
991   gsc_free_output_buffers_.clear();
992   for (size_t i = 0; i < gsc_output_buffer_map_.size(); ++i) {
993     GscOutputRecord& output_record = gsc_output_buffer_map_[i];
994     output_record.at_device = false;
995     output_record.mfc_input = -1;
996     gsc_free_output_buffers_.push_back(i);
997   }
998   gsc_output_buffer_queued_count_ = 0;
999   mfc_ready_input_buffers_.clear();
1000   mfc_free_input_buffers_.clear();
1001   for (size_t i = 0; i < mfc_input_buffer_map_.size(); ++i) {
1002     MfcInputRecord& input_record = mfc_input_buffer_map_[i];
1003     input_record.at_device = false;
1004     mfc_free_input_buffers_.push_back(i);
1005   }
1006   mfc_input_buffer_queued_count_ = 0;
1007   mfc_free_output_buffers_.clear();
1008   for (size_t i = 0; i < mfc_output_buffer_map_.size(); ++i) {
1009     MfcOutputRecord& output_record = mfc_output_buffer_map_[i];
1010     output_record.at_device = false;
1011     output_record.buffer_ref.reset();
1012     mfc_free_output_buffers_.push_back(i);
1013   }
1014   mfc_output_buffer_queued_count_ = 0;
1015   encoder_output_queue_.clear();
1016
1017   DVLOG(3) << "StopDevicePoll(): device poll stopped";
1018   return true;
1019 }
1020
1021 bool ExynosVideoEncodeAccelerator::SetDevicePollInterrupt() {
1022   DVLOG(3) << "SetDevicePollInterrupt()";
1023
1024   // We might get called here if we fail during initialization, in which case we
1025   // don't have a file descriptor.
1026   if (device_poll_interrupt_fd_ == -1)
1027     return true;
1028
1029   const uint64 buf = 1;
1030   if (HANDLE_EINTR((write(device_poll_interrupt_fd_, &buf, sizeof(buf)))) <
1031       static_cast<ssize_t>(sizeof(buf))) {
1032     DPLOG(ERROR) << "SetDevicePollInterrupt(): write() failed";
1033     NOTIFY_ERROR(kPlatformFailureError);
1034     return false;
1035   }
1036   return true;
1037 }
1038
1039 bool ExynosVideoEncodeAccelerator::ClearDevicePollInterrupt() {
1040   DVLOG(3) << "ClearDevicePollInterrupt()";
1041
1042   // We might get called here if we fail during initialization, in which case we
1043   // don't have a file descriptor.
1044   if (device_poll_interrupt_fd_ == -1)
1045     return true;
1046
1047   uint64 buf;
1048   if (HANDLE_EINTR(read(device_poll_interrupt_fd_, &buf, sizeof(buf))) <
1049       static_cast<ssize_t>(sizeof(buf))) {
1050     if (errno == EAGAIN) {
1051       // No interrupt flag set, and we're reading nonblocking.  Not an error.
1052       return true;
1053     } else {
1054       DPLOG(ERROR) << "ClearDevicePollInterrupt(): read() failed";
1055       NOTIFY_ERROR(kPlatformFailureError);
1056       return false;
1057     }
1058   }
1059   return true;
1060 }
1061
1062 void ExynosVideoEncodeAccelerator::DevicePollTask(unsigned int poll_fds) {
1063   DVLOG(3) << "DevicePollTask()";
1064   DCHECK_EQ(device_poll_thread_.message_loop(), base::MessageLoop::current());
1065   DCHECK_NE(device_poll_interrupt_fd_, -1);
1066
1067   // This routine just polls the set of device fds, and schedules a
1068   // ServiceDeviceTask() on encoder_thread_ when processing needs to occur.
1069   // Other threads may notify this task to return early by writing to
1070   // device_poll_interrupt_fd_.
1071   struct pollfd pollfds[3];
1072   nfds_t nfds;
1073
1074   // Add device_poll_interrupt_fd_;
1075   pollfds[0].fd = device_poll_interrupt_fd_;
1076   pollfds[0].events = POLLIN | POLLERR;
1077   nfds = 1;
1078
1079   // Add GSC fd, if we should poll on it.
1080   // GSC has to wait until both input and output buffers are queued.
1081   if (poll_fds & kPollGsc) {
1082     DVLOG(3) << "DevicePollTask(): adding GSC to poll() set";
1083     pollfds[nfds].fd = gsc_fd_;
1084     pollfds[nfds].events = POLLIN | POLLOUT | POLLERR;
1085     nfds++;
1086   }
1087   if (poll_fds & kPollMfc) {
1088     DVLOG(3) << "DevicePollTask(): adding MFC to poll() set";
1089     pollfds[nfds].fd = mfc_fd_;
1090     pollfds[nfds].events = POLLIN | POLLOUT | POLLERR;
1091     nfds++;
1092   }
1093
1094   // Poll it!
1095   if (HANDLE_EINTR(poll(pollfds, nfds, -1)) == -1) {
1096     DPLOG(ERROR) << "DevicePollTask(): poll() failed";
1097     NOTIFY_ERROR(kPlatformFailureError);
1098     return;
1099   }
1100
1101   // All processing should happen on ServiceDeviceTask(), since we shouldn't
1102   // touch encoder state from this thread.
1103   encoder_thread_.message_loop()->PostTask(
1104       FROM_HERE,
1105       base::Bind(&ExynosVideoEncodeAccelerator::ServiceDeviceTask,
1106                  base::Unretained(this)));
1107 }
1108
1109 void ExynosVideoEncodeAccelerator::NotifyError(Error error) {
1110   DVLOG(1) << "NotifyError(): error=" << error;
1111
1112   if (!child_message_loop_proxy_->BelongsToCurrentThread()) {
1113     child_message_loop_proxy_->PostTask(
1114         FROM_HERE,
1115         base::Bind(
1116             &ExynosVideoEncodeAccelerator::NotifyError, weak_this_, error));
1117     return;
1118   }
1119
1120   if (client_) {
1121     client_->NotifyError(error);
1122     client_ptr_factory_.InvalidateWeakPtrs();
1123   }
1124 }
1125
1126 void ExynosVideoEncodeAccelerator::SetEncoderState(State state) {
1127   DVLOG(3) << "SetEncoderState(): state=" << state;
1128
1129   // We can touch encoder_state_ only if this is the encoder thread or the
1130   // encoder thread isn't running.
1131   if (encoder_thread_.message_loop() != NULL &&
1132       encoder_thread_.message_loop() != base::MessageLoop::current()) {
1133     encoder_thread_.message_loop()->PostTask(
1134         FROM_HERE,
1135         base::Bind(&ExynosVideoEncodeAccelerator::SetEncoderState,
1136                    base::Unretained(this),
1137                    state));
1138   } else {
1139     encoder_state_ = state;
1140   }
1141 }
1142
1143 void ExynosVideoEncodeAccelerator::RequestEncodingParametersChangeTask(
1144     uint32 bitrate,
1145     uint32 framerate) {
1146   DVLOG(3) << "RequestEncodingParametersChangeTask(): bitrate=" << bitrate
1147            << ", framerate=" << framerate;
1148   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
1149
1150   if (bitrate < 1)
1151     bitrate = 1;
1152   if (framerate < 1)
1153     framerate = 1;
1154
1155   struct v4l2_ext_control ctrls[1];
1156   struct v4l2_ext_controls control;
1157   memset(&ctrls, 0, sizeof(ctrls));
1158   memset(&control, 0, sizeof(control));
1159   ctrls[0].id    = V4L2_CID_MPEG_VIDEO_BITRATE;
1160   ctrls[0].value = bitrate;
1161   control.ctrl_class = V4L2_CTRL_CLASS_MPEG;
1162   control.count = arraysize(ctrls);
1163   control.controls = ctrls;
1164   IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_S_EXT_CTRLS, &control);
1165
1166   struct v4l2_streamparm parms;
1167   memset(&parms, 0, sizeof(parms));
1168   parms.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1169   // Note that we are provided "frames per second" but V4L2 expects "time per
1170   // frame"; hence we provide the reciprocal of the framerate here.
1171   parms.parm.output.timeperframe.numerator = 1;
1172   parms.parm.output.timeperframe.denominator = framerate;
1173   IOCTL_OR_ERROR_RETURN(mfc_fd_, VIDIOC_S_PARM, &parms);
1174 }
1175
1176 bool ExynosVideoEncodeAccelerator::CreateGscInputBuffers() {
1177   DVLOG(3) << "CreateGscInputBuffers()";
1178   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1179   DCHECK_EQ(encoder_state_, kUninitialized);
1180   DCHECK(!gsc_input_streamon_);
1181
1182   struct v4l2_control control;
1183   memset(&control, 0, sizeof(control));
1184   control.id    = V4L2_CID_ROTATE;
1185   control.value = 0;
1186   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1187
1188   // HFLIP actually seems to control vertical mirroring for GSC, and vice-versa.
1189   memset(&control, 0, sizeof(control));
1190   control.id    = V4L2_CID_HFLIP;
1191   control.value = 0;
1192   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1193
1194   memset(&control, 0, sizeof(control));
1195   control.id    = V4L2_CID_VFLIP;
1196   control.value = 0;
1197   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1198
1199   memset(&control, 0, sizeof(control));
1200   control.id    = V4L2_CID_ALPHA_COMPONENT;
1201   control.value = 255;
1202   if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_S_CTRL, &control)) != 0) {
1203     // TODO(posciak): This is a  temporary hack and should be removed when
1204     // all platforms migrate to kernel >=3.8.
1205     memset(&control, 0, sizeof(control));
1206     control.id    = V4L2_CID_GLOBAL_ALPHA;
1207     control.value = 255;
1208     IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CTRL, &control);
1209   }
1210
1211   struct v4l2_format format;
1212   memset(&format, 0, sizeof(format));
1213   format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1214   format.fmt.pix_mp.width  = input_allocated_size_.width();
1215   format.fmt.pix_mp.height = input_allocated_size_.height();
1216   format.fmt.pix_mp.pixelformat = input_format_fourcc_;
1217   switch (input_format_fourcc_) {
1218     case V4L2_PIX_FMT_RGB32:
1219       format.fmt.pix_mp.plane_fmt[0].sizeimage =
1220           input_allocated_size_.GetArea() * 4;
1221       format.fmt.pix_mp.plane_fmt[0].bytesperline =
1222           input_allocated_size_.width() * 4;
1223       format.fmt.pix_mp.num_planes = 1;
1224       break;
1225     case V4L2_PIX_FMT_YUV420M:
1226       format.fmt.pix_mp.plane_fmt[0].sizeimage =
1227           input_allocated_size_.GetArea();
1228       format.fmt.pix_mp.plane_fmt[0].bytesperline =
1229           input_allocated_size_.width();
1230       format.fmt.pix_mp.plane_fmt[1].sizeimage =
1231           input_allocated_size_.GetArea() / 4;
1232       format.fmt.pix_mp.plane_fmt[1].bytesperline =
1233           input_allocated_size_.width() / 2;
1234       format.fmt.pix_mp.plane_fmt[2].sizeimage =
1235           input_allocated_size_.GetArea() / 4;
1236       format.fmt.pix_mp.plane_fmt[2].bytesperline =
1237           input_allocated_size_.width() / 2;
1238       format.fmt.pix_mp.num_planes = 3;
1239       break;
1240     default:
1241       NOTREACHED();
1242       NOTIFY_ERROR(kIllegalStateError);
1243       return false;
1244   }
1245   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_FMT, &format);
1246
1247   struct v4l2_crop crop;
1248   memset(&crop, 0, sizeof(crop));
1249   crop.type     = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1250   crop.c.left   = 0;
1251   crop.c.top    = 0;
1252   crop.c.width  = input_visible_size_.width();
1253   crop.c.height = input_visible_size_.height();
1254   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CROP, &crop);
1255
1256   struct v4l2_requestbuffers reqbufs;
1257   memset(&reqbufs, 0, sizeof(reqbufs));
1258   reqbufs.count  = kGscInputBufferCount;
1259   reqbufs.type   = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1260   reqbufs.memory = V4L2_MEMORY_USERPTR;
1261   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_REQBUFS, &reqbufs);
1262
1263   DCHECK(gsc_input_buffer_map_.empty());
1264   gsc_input_buffer_map_.resize(reqbufs.count);
1265   for (size_t i = 0; i < gsc_input_buffer_map_.size(); ++i)
1266     gsc_free_input_buffers_.push_back(i);
1267
1268   return true;
1269 }
1270
1271 bool ExynosVideoEncodeAccelerator::CreateGscOutputBuffers() {
1272   DVLOG(3) << "CreateGscOutputBuffers()";
1273   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1274   DCHECK_EQ(encoder_state_, kUninitialized);
1275   DCHECK(!gsc_output_streamon_);
1276
1277   struct v4l2_format format;
1278   memset(&format, 0, sizeof(format));
1279   format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1280   format.fmt.pix_mp.width = converted_allocated_size_.width();
1281   format.fmt.pix_mp.height = converted_allocated_size_.height();
1282   format.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12M;
1283   format.fmt.pix_mp.plane_fmt[0].sizeimage =
1284       converted_allocated_size_.GetArea();
1285   format.fmt.pix_mp.plane_fmt[1].sizeimage =
1286       converted_allocated_size_.GetArea() / 2;
1287   format.fmt.pix_mp.plane_fmt[0].bytesperline =
1288       converted_allocated_size_.width();
1289   format.fmt.pix_mp.plane_fmt[1].bytesperline =
1290       converted_allocated_size_.width();
1291   format.fmt.pix_mp.num_planes = 2;
1292   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_FMT, &format);
1293
1294   struct v4l2_crop crop;
1295   memset(&crop, 0, sizeof(crop));
1296   crop.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1297   crop.c.left   = 0;
1298   crop.c.top    = 0;
1299   crop.c.width  = converted_visible_size_.width();
1300   crop.c.height = converted_visible_size_.height();
1301   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_S_CROP, &crop);
1302
1303   struct v4l2_requestbuffers reqbufs;
1304   memset(&reqbufs, 0, sizeof(reqbufs));
1305   reqbufs.count  = kGscOutputBufferCount;
1306   reqbufs.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1307   reqbufs.memory = V4L2_MEMORY_DMABUF;
1308   IOCTL_OR_ERROR_RETURN_FALSE(gsc_fd_, VIDIOC_REQBUFS, &reqbufs);
1309
1310   DCHECK(gsc_output_buffer_map_.empty());
1311   gsc_output_buffer_map_.resize(reqbufs.count);
1312   for (size_t i = 0; i < gsc_output_buffer_map_.size(); ++i)
1313     gsc_free_output_buffers_.push_back(i);
1314   return true;
1315 }
1316
1317 bool ExynosVideoEncodeAccelerator::SetMfcFormats() {
1318   DVLOG(3) << "SetMfcFormats()";
1319   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1320   DCHECK(!mfc_input_streamon_);
1321   DCHECK(!mfc_output_streamon_);
1322
1323   // VIDIOC_S_FMT on OUTPUT queue.
1324   struct v4l2_format format;
1325   memset(&format, 0, sizeof(format));
1326   format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1327   format.fmt.pix_mp.width = input_allocated_size_.width();
1328   format.fmt.pix_mp.height = input_allocated_size_.height();
1329   format.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12M;
1330   format.fmt.pix_mp.num_planes = 2;
1331   IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_S_FMT, &format);
1332   // We read direct from GSC, so we rely on the HW not changing our set
1333   // size/stride.
1334   DCHECK_EQ(format.fmt.pix_mp.plane_fmt[0].sizeimage,
1335             static_cast<__u32>(input_allocated_size_.GetArea()));
1336   DCHECK_EQ(format.fmt.pix_mp.plane_fmt[0].bytesperline,
1337             static_cast<__u32>(input_allocated_size_.width()));
1338   DCHECK_EQ(format.fmt.pix_mp.plane_fmt[1].sizeimage,
1339             static_cast<__u32>(input_allocated_size_.GetArea() / 2));
1340   DCHECK_EQ(format.fmt.pix_mp.plane_fmt[1].bytesperline,
1341             static_cast<__u32>(input_allocated_size_.width()));
1342
1343   struct v4l2_crop crop;
1344   memset(&crop, 0, sizeof(crop));
1345   crop.type     = V4L2_BUF_TYPE_VIDEO_OUTPUT;
1346   crop.c.left   = 0;
1347   crop.c.top    = 0;
1348   crop.c.width  = input_visible_size_.width();
1349   crop.c.height = input_visible_size_.height();
1350   IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_S_CROP, &crop);
1351
1352   // VIDIOC_S_FMT on CAPTURE queue.
1353   output_buffer_byte_size_ = kMfcOutputBufferSize;
1354   memset(&format, 0, sizeof(format));
1355   format.type                   = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1356   format.fmt.pix_mp.width       = output_visible_size_.width();
1357   format.fmt.pix_mp.height      = output_visible_size_.height();
1358   format.fmt.pix_mp.pixelformat = output_format_fourcc_;
1359   format.fmt.pix_mp.plane_fmt[0].sizeimage = output_buffer_byte_size_;
1360   format.fmt.pix_mp.num_planes  = 1;
1361   IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_S_FMT, &format);
1362
1363   return true;
1364 }
1365
1366 bool ExynosVideoEncodeAccelerator::InitMfcControls() {
1367   struct v4l2_ext_control ctrls[9];
1368   struct v4l2_ext_controls control;
1369   memset(&ctrls, 0, sizeof(ctrls));
1370   memset(&control, 0, sizeof(control));
1371   // No B-frames, for lowest decoding latency.
1372   ctrls[0].id    = V4L2_CID_MPEG_VIDEO_B_FRAMES;
1373   ctrls[0].value = 0;
1374   // Enable frame-level bitrate control.
1375   ctrls[1].id    = V4L2_CID_MPEG_VIDEO_FRAME_RC_ENABLE;
1376   ctrls[1].value = 1;
1377   // Enable "tight" bitrate mode. For this to work properly, frame- and mb-level
1378   // bitrate controls have to be enabled as well.
1379   ctrls[2].id    = V4L2_CID_MPEG_MFC51_VIDEO_RC_REACTION_COEFF;
1380   ctrls[2].value = 1;
1381   // Force bitrate control to average over a GOP (for tight bitrate
1382   // tolerance).
1383   ctrls[3].id    = V4L2_CID_MPEG_MFC51_VIDEO_RC_FIXED_TARGET_BIT;
1384   ctrls[3].value = 1;
1385   // Quantization parameter maximum value (for variable bitrate control).
1386   ctrls[4].id    = V4L2_CID_MPEG_VIDEO_H264_MAX_QP;
1387   ctrls[4].value = 51;
1388   // Separate stream header so we can cache it and insert into the stream.
1389   ctrls[5].id    = V4L2_CID_MPEG_VIDEO_HEADER_MODE;
1390   ctrls[5].value = V4L2_MPEG_VIDEO_HEADER_MODE_SEPARATE;
1391   // Enable macroblock-level bitrate control.
1392   ctrls[6].id    = V4L2_CID_MPEG_VIDEO_MB_RC_ENABLE;
1393   ctrls[6].value = 1;
1394   // Use H.264 level 4.0 to match the supported max resolution.
1395   ctrls[7].id    = V4L2_CID_MPEG_VIDEO_H264_LEVEL;
1396   ctrls[7].value = V4L2_MPEG_VIDEO_H264_LEVEL_4_0;
1397   // Disable periodic key frames.
1398   ctrls[8].id    = V4L2_CID_MPEG_VIDEO_GOP_SIZE;
1399   ctrls[8].value = 0;
1400   control.ctrl_class = V4L2_CTRL_CLASS_MPEG;
1401   control.count = arraysize(ctrls);
1402   control.controls = ctrls;
1403   IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_S_EXT_CTRLS, &control);
1404
1405   return true;
1406 }
1407
1408 bool ExynosVideoEncodeAccelerator::CreateMfcInputBuffers() {
1409   DVLOG(3) << "CreateMfcInputBuffers()";
1410   // This function runs on encoder_thread_ after output buffers have been
1411   // provided by the client.
1412   DCHECK_EQ(encoder_thread_.message_loop(), base::MessageLoop::current());
1413   DCHECK(!mfc_input_streamon_);
1414
1415   struct v4l2_requestbuffers reqbufs;
1416   memset(&reqbufs, 0, sizeof(reqbufs));
1417   reqbufs.count = 1;  // Driver will allocate the appropriate number of buffers.
1418   reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1419   reqbufs.memory = V4L2_MEMORY_MMAP;
1420   IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_REQBUFS, &reqbufs);
1421
1422   DCHECK(mfc_input_buffer_map_.empty());
1423   mfc_input_buffer_map_.resize(reqbufs.count);
1424   for (size_t i = 0; i < mfc_input_buffer_map_.size(); ++i) {
1425     MfcInputRecord& input_record = mfc_input_buffer_map_[i];
1426     for (int j = 0; j < 2; ++j) {
1427       // Export the DMABUF fd so GSC can write to it.
1428       struct v4l2_exportbuffer expbuf;
1429       memset(&expbuf, 0, sizeof(expbuf));
1430       expbuf.type  = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1431       expbuf.index = i;
1432       expbuf.plane = j;
1433       expbuf.flags = O_CLOEXEC;
1434       IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_EXPBUF, &expbuf);
1435       input_record.fd[j] = expbuf.fd;
1436     }
1437     mfc_free_input_buffers_.push_back(i);
1438   }
1439
1440   return true;
1441 }
1442
1443 bool ExynosVideoEncodeAccelerator::CreateMfcOutputBuffers() {
1444   DVLOG(3) << "CreateMfcOutputBuffers()";
1445   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1446   DCHECK(!mfc_output_streamon_);
1447
1448   struct v4l2_requestbuffers reqbufs;
1449   memset(&reqbufs, 0, sizeof(reqbufs));
1450   reqbufs.count = kMfcOutputBufferCount;
1451   reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1452   reqbufs.memory = V4L2_MEMORY_MMAP;
1453   IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_REQBUFS, &reqbufs);
1454
1455   DCHECK(mfc_output_buffer_map_.empty());
1456   mfc_output_buffer_map_.resize(reqbufs.count);
1457   for (size_t i = 0; i < mfc_output_buffer_map_.size(); ++i) {
1458     struct v4l2_plane planes[1];
1459     struct v4l2_buffer buffer;
1460     memset(&buffer, 0, sizeof(buffer));
1461     memset(planes, 0, sizeof(planes));
1462     buffer.index    = i;
1463     buffer.type     = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1464     buffer.memory   = V4L2_MEMORY_MMAP;
1465     buffer.m.planes = planes;
1466     buffer.length   = arraysize(planes);
1467     IOCTL_OR_ERROR_RETURN_FALSE(mfc_fd_, VIDIOC_QUERYBUF, &buffer);
1468     void* address = mmap(NULL, buffer.m.planes[0].length,
1469         PROT_READ | PROT_WRITE, MAP_SHARED, mfc_fd_,
1470         buffer.m.planes[0].m.mem_offset);
1471     if (address == MAP_FAILED) {
1472       DPLOG(ERROR) << "CreateMfcOutputBuffers(): mmap() failed";
1473       return false;
1474     }
1475     mfc_output_buffer_map_[i].address = address;
1476     mfc_output_buffer_map_[i].length = buffer.m.planes[0].length;
1477     mfc_free_output_buffers_.push_back(i);
1478   }
1479
1480   return true;
1481 }
1482
1483 void ExynosVideoEncodeAccelerator::DestroyGscInputBuffers() {
1484   DVLOG(3) << "DestroyGscInputBuffers()";
1485   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1486   DCHECK(!gsc_input_streamon_);
1487
1488   struct v4l2_requestbuffers reqbufs;
1489   memset(&reqbufs, 0, sizeof(reqbufs));
1490   reqbufs.count = 0;
1491   reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1492   reqbufs.memory = V4L2_MEMORY_USERPTR;
1493   if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_REQBUFS, &reqbufs)) != 0)
1494     DPLOG(ERROR) << "DestroyGscInputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1495
1496   gsc_input_buffer_map_.clear();
1497   gsc_free_input_buffers_.clear();
1498 }
1499
1500 void ExynosVideoEncodeAccelerator::DestroyGscOutputBuffers() {
1501   DVLOG(3) << "DestroyGscOutputBuffers()";
1502   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1503   DCHECK(!gsc_output_streamon_);
1504
1505   struct v4l2_requestbuffers reqbufs;
1506   memset(&reqbufs, 0, sizeof(reqbufs));
1507   reqbufs.count = 0;
1508   reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1509   reqbufs.memory = V4L2_MEMORY_DMABUF;
1510   if (HANDLE_EINTR(ioctl(gsc_fd_, VIDIOC_REQBUFS, &reqbufs)) != 0)
1511     DPLOG(ERROR) << "DestroyGscOutputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1512
1513   gsc_output_buffer_map_.clear();
1514   gsc_free_output_buffers_.clear();
1515 }
1516
1517 void ExynosVideoEncodeAccelerator::DestroyMfcInputBuffers() {
1518   DVLOG(3) << "DestroyMfcInputBuffers()";
1519   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1520   DCHECK(!mfc_input_streamon_);
1521
1522   for (size_t buf = 0; buf < mfc_input_buffer_map_.size(); ++buf) {
1523     MfcInputRecord& input_record = mfc_input_buffer_map_[buf];
1524
1525     for (size_t plane = 0; plane < arraysize(input_record.fd); ++plane)
1526       HANDLE_EINTR(close(mfc_input_buffer_map_[buf].fd[plane]));
1527   }
1528
1529   struct v4l2_requestbuffers reqbufs;
1530   memset(&reqbufs, 0, sizeof(reqbufs));
1531   reqbufs.count = 0;
1532   reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
1533   reqbufs.memory = V4L2_MEMORY_MMAP;
1534   if (HANDLE_EINTR(ioctl(mfc_fd_, VIDIOC_REQBUFS, &reqbufs)) != 0)
1535     DPLOG(ERROR) << "DestroyMfcInputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1536
1537   mfc_input_buffer_map_.clear();
1538   mfc_free_input_buffers_.clear();
1539 }
1540
1541 void ExynosVideoEncodeAccelerator::DestroyMfcOutputBuffers() {
1542   DVLOG(3) << "DestroyMfcOutputBuffers()";
1543   DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1544   DCHECK(!mfc_output_streamon_);
1545
1546   for (size_t i = 0; i < mfc_output_buffer_map_.size(); ++i) {
1547     if (mfc_output_buffer_map_[i].address != NULL) {
1548       munmap(mfc_output_buffer_map_[i].address,
1549              mfc_output_buffer_map_[i].length);
1550     }
1551   }
1552
1553   struct v4l2_requestbuffers reqbufs;
1554   memset(&reqbufs, 0, sizeof(reqbufs));
1555   reqbufs.count = 0;
1556   reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1557   reqbufs.memory = V4L2_MEMORY_MMAP;
1558   if (HANDLE_EINTR(ioctl(mfc_fd_, VIDIOC_REQBUFS, &reqbufs)) != 0)
1559     DPLOG(ERROR) << "DestroyMfcOutputBuffers(): ioctl() failed: VIDIOC_REQBUFS";
1560
1561   mfc_output_buffer_map_.clear();
1562   mfc_free_output_buffers_.clear();
1563 }
1564
1565 }  // namespace content