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

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

Issue 833063003: Add accelerated video decoder interface, VP8 and H.264 implementations and hook up to V4L2SVDA. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2015 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 <fcntl.h>
6 #include <linux/videodev2.h>
7 #include <poll.h>
8 #include <sys/eventfd.h>
9 #include <sys/ioctl.h>
10 #include <sys/mman.h>
11
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/callback_helpers.h"
16 #include "base/command_line.h"
17 #include "base/message_loop/message_loop_proxy.h"
18 #include "base/numerics/safe_conversions.h"
19 #include "base/strings/stringprintf.h"
20 #include "content/common/gpu/media/v4l2_slice_video_decode_accelerator.h"
21 #include "media/base/bind_to_current_loop.h"
22 #include "media/base/media_switches.h"
23 #include "ui/gl/scoped_binders.h"
24
25 #define LOGF(level) LOG(level) << __FUNCTION__ << "(): "
26 #define DVLOGF(level) LOG(ERROR) << __FUNCTION__ << "(): "
kcwu 2015/01/12 07:31:46 level is ignored?
Pawel Osciak 2015/01/13 11:33:33 Just for debugging, sorry.
27
28 #define NOTIFY_ERROR(x) \
29 do { \
30 LOG(ERROR) << "Setting error state:" << x; \
31 SetErrorState(x); \
32 } while (0)
33
34 #define IOCTL_OR_ERROR_RETURN_VALUE(type, arg, value) \
35 do { \
36 if (device_->Ioctl(type, arg) != 0) { \
37 PLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
38 return value; \
39 } \
40 } while (0)
41
42 #define IOCTL_OR_ERROR_RETURN(type, arg) \
43 IOCTL_OR_ERROR_RETURN_VALUE(type, arg, ((void)0))
44
45 #define IOCTL_OR_ERROR_RETURN_FALSE(type, arg) \
46 IOCTL_OR_ERROR_RETURN_VALUE(type, arg, false)
47
48 #define IOCTL_OR_LOG_ERROR(type, arg) \
49 do { \
50 if (device_->Ioctl(type, arg) != 0) \
51 PLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
52 } while (0)
53
54 namespace content {
55
56 V4L2SliceVideoDecodeAccelerator::V4L2DecodeSurface::V4L2DecodeSurface(
57 int32 bitstream_id,
58 int input_record,
59 int output_record,
60 const ReleaseCB& release_cb)
61 : bitstream_id_(bitstream_id),
62 input_record_(input_record),
63 output_record_(output_record),
64 config_store_(input_record + 1),
65 decoded_(false),
66 release_cb_(release_cb) {
67 }
68
69 V4L2SliceVideoDecodeAccelerator::V4L2DecodeSurface::~V4L2DecodeSurface() {
70 DVLOGF(5) << "Releasing output record id=" << output_record_;
71 release_cb_.Run(output_record_);
72 }
73
74 void V4L2SliceVideoDecodeAccelerator::V4L2DecodeSurface::SetReferenceSurfaces(
75 const std::vector<scoped_refptr<V4L2DecodeSurface>>& ref_surfaces) {
76 DCHECK(reference_surfaces_.empty());
77 reference_surfaces_ = ref_surfaces;
78 }
79
80 void V4L2SliceVideoDecodeAccelerator::V4L2DecodeSurface::SetDecoded() {
81 DCHECK(!decoded_);
82 decoded_ = true;
83
84 // We can now drop references to all reference surfaces for this surface
85 // as we are done with decoding.
86 reference_surfaces_.clear();
87 }
88
89 std::string V4L2SliceVideoDecodeAccelerator::V4L2DecodeSurface::ToString()
90 const {
91 std::string out;
92 base::StringAppendF(&out, "Buffer %d -> %d. ", input_record_, output_record_);
93 base::StringAppendF(&out, "Reference surfaces:");
94 for (const auto& ref : reference_surfaces_) {
95 DCHECK_NE(ref->output_record(), output_record_);
96 base::StringAppendF(&out, " %d", ref->output_record());
97 }
98 return out;
99 }
100
101 V4L2SliceVideoDecodeAccelerator::InputRecord::InputRecord()
102 : input_id(-1),
103 address(nullptr),
104 length(0),
105 bytes_used(0),
106 at_device(false) {
107 }
108
109 V4L2SliceVideoDecodeAccelerator::OutputRecord::OutputRecord()
110 : at_device(false),
111 at_client(false),
112 picture_id(-1),
113 egl_image(EGL_NO_IMAGE_KHR),
114 egl_sync(EGL_NO_SYNC_KHR),
115 cleared(false) {
116 }
117
118 struct V4L2SliceVideoDecodeAccelerator::BitstreamBufferRef {
119 BitstreamBufferRef(
120 base::WeakPtr<VideoDecodeAccelerator::Client>& client,
121 const scoped_refptr<base::MessageLoopProxy>& client_message_loop_proxy,
122 base::SharedMemory* shm,
123 size_t size,
124 int32 input_id);
125 ~BitstreamBufferRef();
126 const base::WeakPtr<VideoDecodeAccelerator::Client> client;
127 const scoped_refptr<base::MessageLoopProxy> client_message_loop_proxy;
128 const scoped_ptr<base::SharedMemory> shm;
129 const size_t size;
130 off_t bytes_used;
131 const int32 input_id;
132 };
133
134 V4L2SliceVideoDecodeAccelerator::BitstreamBufferRef::BitstreamBufferRef(
135 base::WeakPtr<VideoDecodeAccelerator::Client>& client,
136 const scoped_refptr<base::MessageLoopProxy>& client_message_loop_proxy,
137 base::SharedMemory* shm,
138 size_t size,
139 int32 input_id)
140 : client(client),
141 client_message_loop_proxy(client_message_loop_proxy),
142 shm(shm),
143 size(size),
144 bytes_used(0),
145 input_id(input_id) {
146 }
147
148 V4L2SliceVideoDecodeAccelerator::BitstreamBufferRef::~BitstreamBufferRef() {
149 if (input_id >= 0) {
150 DVLOGF(5) << "returning input_id: " << input_id;
151 client_message_loop_proxy->PostTask(
152 FROM_HERE,
153 base::Bind(&VideoDecodeAccelerator::Client::NotifyEndOfBitstreamBuffer,
154 client, input_id));
155 }
156 }
157
158 struct V4L2SliceVideoDecodeAccelerator::EGLSyncKHRRef {
159 EGLSyncKHRRef(EGLDisplay egl_display, EGLSyncKHR egl_sync);
160 ~EGLSyncKHRRef();
161 EGLDisplay const egl_display;
162 EGLSyncKHR egl_sync;
163 };
164
165 V4L2SliceVideoDecodeAccelerator::EGLSyncKHRRef::EGLSyncKHRRef(
166 EGLDisplay egl_display,
167 EGLSyncKHR egl_sync)
168 : egl_display(egl_display), egl_sync(egl_sync) {
169 }
170
171 V4L2SliceVideoDecodeAccelerator::EGLSyncKHRRef::~EGLSyncKHRRef() {
172 // We don't check for eglDestroySyncKHR failures, because if we get here
173 // with a valid sync object, something went wrong and we are getting
174 // destroyed anyway.
175 if (egl_sync != EGL_NO_SYNC_KHR)
176 eglDestroySyncKHR(egl_display, egl_sync);
177 }
178
179 struct V4L2SliceVideoDecodeAccelerator::PictureRecord {
180 PictureRecord(bool cleared, const media::Picture& picture);
181 ~PictureRecord();
182 bool cleared; // Whether the texture is cleared and safe to render from.
183 media::Picture picture; // The decoded picture.
184 };
185
186 V4L2SliceVideoDecodeAccelerator::PictureRecord::PictureRecord(
187 bool cleared,
188 const media::Picture& picture)
189 : cleared(cleared), picture(picture) {
190 }
191
192 V4L2SliceVideoDecodeAccelerator::PictureRecord::~PictureRecord() {
193 }
194
195 V4L2SliceVideoDecodeAccelerator::V4L2SliceVideoDecodeAccelerator(
196 const scoped_refptr<V4L2Device>& device,
197 EGLDisplay egl_display,
198 EGLContext egl_context,
199 const base::WeakPtr<Client>& io_client,
200 const base::Callback<bool(void)>& make_context_current,
201 const scoped_refptr<base::MessageLoopProxy>& io_message_loop_proxy)
202 : input_planes_count_(0),
203 output_planes_count_(0),
204 child_message_loop_proxy_(base::MessageLoopProxy::current()),
205 io_message_loop_proxy_(io_message_loop_proxy),
206 io_client_(io_client),
207 device_(device),
208 decoder_thread_("V4L2SliceVideoDecodeAcceleratorThread"),
209 device_poll_thread_("V4L2SliceVideoDecodeAcceleratorDevicePollThread"),
210 input_streamon_(false),
211 input_buffer_queued_count_(0),
212 output_streamon_(false),
213 output_buffer_queued_count_(0),
214 video_profile_(media::VIDEO_CODEC_PROFILE_UNKNOWN),
215 output_format_fourcc_(0),
216 output_dpb_size_(0),
217 state_(kUninitialized),
218 decoder_flushing_(false),
219 decoder_resetting_(false),
220 surface_set_change_pending_(false),
221 picture_clearing_count_(0),
222 pictures_assigned_(false, false),
223 make_context_current_(make_context_current),
224 egl_display_(egl_display),
225 egl_context_(egl_context),
226 weak_this_factory_(this) {
227 weak_this_ = weak_this_factory_.GetWeakPtr();
228 }
229
230 V4L2SliceVideoDecodeAccelerator::~V4L2SliceVideoDecodeAccelerator() {
231 DVLOGF(2);
232
233 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
234 DCHECK(!decoder_thread_.IsRunning());
235 DCHECK(!device_poll_thread_.IsRunning());
236
237 DCHECK(input_buffer_map_.empty());
238 DCHECK(output_buffer_map_.empty());
239 }
240
241 void V4L2SliceVideoDecodeAccelerator::NotifyError(Error error) {
242 if (!child_message_loop_proxy_->BelongsToCurrentThread()) {
243 child_message_loop_proxy_->PostTask(
244 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::NotifyError,
245 weak_this_, error));
246 return;
247 }
248
249 if (client_) {
250 client_->NotifyError(error);
251 client_ptr_factory_.reset();
252 }
253 }
254
255 bool V4L2SliceVideoDecodeAccelerator::Initialize(
256 media::VideoCodecProfile profile,
257 VideoDecodeAccelerator::Client* client) {
258 DVLOGF(3);
259 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
260 DCHECK_EQ(state_, kUninitialized);
261
262 client_ptr_factory_.reset(
263 new base::WeakPtrFactory<VideoDecodeAccelerator::Client>(client));
264 client_ = client_ptr_factory_->GetWeakPtr();
265
266 video_profile_ = profile;
267
268 if (video_profile_ >= media::H264PROFILE_MIN &&
269 video_profile_ <= media::H264PROFILE_MAX) {
270 h264_accelerator_.reset(new V4L2H264Accelerator(this));
271 decoder_.reset(new H264Decoder(h264_accelerator_.get()));
272 } else if (video_profile_ >= media::VP8PROFILE_MIN &&
273 video_profile_ <= media::VP8PROFILE_MAX) {
274 vp8_accelerator_.reset(new V4L2VP8Accelerator(this));
275 decoder_.reset(new VP8Decoder(vp8_accelerator_.get()));
276 } else {
277 DLOG(ERROR) << "Unsupported profile " << video_profile_;
278 return false;
279 }
280
281 // TODO(posciak): This needs to be queried once supported.
282 input_planes_count_ = 1;
283 output_planes_count_ = 1;
284
285 if (egl_display_ == EGL_NO_DISPLAY) {
286 LOG(ERROR) << "Initialize(): could not get EGLDisplay";
287 return false;
288 }
289
290 // We need the context to be initialized to query extensions.
291 if (!make_context_current_.Run()) {
292 LOG(ERROR) << "Initialize(): could not make context current";
293 return false;
294 }
295
296 if (!gfx::g_driver_egl.ext.b_EGL_KHR_fence_sync) {
297 LOG(ERROR) << "Initialize(): context does not have EGL_KHR_fence_sync";
298 return false;
299 }
300
301 // Capabilities check.
302 struct v4l2_capability caps;
303 const __u32 kCapsRequired =
304 V4L2_CAP_VIDEO_CAPTURE_MPLANE |
305 V4L2_CAP_VIDEO_OUTPUT_MPLANE |
306 V4L2_CAP_STREAMING;
307 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYCAP, &caps);
308 if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
309 DLOG(ERROR) << "Initialize(): ioctl() failed: VIDIOC_QUERYCAP"
310 ", caps check failed: 0x" << std::hex << caps.capabilities;
311 return false;
312 }
313
314 if (!SetupFormats())
315 return false;
316
317 if (!decoder_thread_.Start()) {
318 DLOG(ERROR) << "Initialize(): device thread failed to start";
319 return false;
320 }
321 decoder_thread_proxy_ = decoder_thread_.message_loop_proxy();
322
323 state_ = kInitialized;
324
325 // InitializeTask will NOTIFY_ERROR on failure.
326 decoder_thread_proxy_->PostTask(
327 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::InitializeTask,
328 base::Unretained(this)));
329
330 DVLOGF(1) << "V4L2SliceVideoDecodeAccelerator initialized";
331 return true;
332 }
333
334 void V4L2SliceVideoDecodeAccelerator::InitializeTask() {
335 DVLOGF(3);
336 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
337 DCHECK_EQ(state_, kInitialized);
338
339 if (!CreateInputBuffers())
340 NOTIFY_ERROR(PLATFORM_FAILURE);
341
342 // Output buffers will be created once decoder gives us information
343 // about their size and required count.
344 state_ = kDecoding;
345 }
346
347 void V4L2SliceVideoDecodeAccelerator::Destroy() {
348 DVLOGF(3);
349 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
350
351 if (decoder_thread_.IsRunning()) {
352 decoder_thread_proxy_->PostTask(
353 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::DestroyTask,
354 base::Unretained(this)));
355
356 // Wait for tasks to finish/early-exit.
357 decoder_thread_.Stop();
358 }
359
360 delete this;
361 DVLOGF(3) << "Destroyed";
362 }
363
364 void V4L2SliceVideoDecodeAccelerator::DestroyTask() {
365 DVLOGF(3);
366 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
367
368 state_ = kError;
369
370 decoder_->Reset();
371
372 decoder_current_bitstream_buffer_.reset();
373 while (!decoder_input_queue_.empty())
374 decoder_input_queue_.pop();
375
376 // Stop streaming and the device_poll_thread_.
377 StopDevicePoll(false);
378
379 DestroyInputBuffers();
380 DestroyOutputs(false);
381
382 DCHECK(surfaces_at_device_.empty());
383 DCHECK(surfaces_at_display_.empty());
384 DCHECK(decoder_display_queue_.empty());
385 }
386
387 bool V4L2SliceVideoDecodeAccelerator::SetupFormats() {
388 DCHECK_EQ(state_, kUninitialized);
389
390 __u32 input_format_fourcc =
391 V4L2Device::VideoCodecProfileToV4L2PixFmt(video_profile_, true);
392 if (!input_format_fourcc) {
393 NOTREACHED();
394 return false;
395 }
396
397 size_t input_size;
398 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
399 switches::kIgnoreResolutionLimitsForAcceleratedVideoDecode))
400 input_size = kInputBufferMaxSizeFor4k;
401 else
402 input_size = kInputBufferMaxSizeFor1080p;
403
404 struct v4l2_format format;
405 memset(&format, 0, sizeof(format));
406 format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
407 format.fmt.pix_mp.pixelformat = input_format_fourcc;
408 format.fmt.pix_mp.plane_fmt[0].sizeimage = input_size;
409 format.fmt.pix_mp.num_planes = input_planes_count_;
410 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format);
411
412 // We have to set up the format for output, because the driver may not allow
413 // changing it once we start streaming; whether it can support our chosen
414 // output format or not may depend on the input format.
415 struct v4l2_fmtdesc fmtdesc;
416 memset(&fmtdesc, 0, sizeof(fmtdesc));
417 fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
418 while (device_->Ioctl(VIDIOC_ENUM_FMT, &fmtdesc) == 0) {
419 if (device_->CanCreateEGLImageFrom(fmtdesc.pixelformat)) {
420 output_format_fourcc_ = fmtdesc.pixelformat;
421 break;
422 }
423 ++fmtdesc.index;
424 }
425
426 if (output_format_fourcc_ == 0) {
427 LOG(ERROR) << "Could not find a usable output format";
428 return false;
429 }
430
431 // Only set fourcc for output; resolution, etc., will come from the
432 // driver once it extracts it from the stream.
433 memset(&format, 0, sizeof(format));
434 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
435 format.fmt.pix_mp.pixelformat = output_format_fourcc_;
436 format.fmt.pix_mp.num_planes = output_planes_count_;
437 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format);
438
439 return true;
440 }
441
442 bool V4L2SliceVideoDecodeAccelerator::CreateInputBuffers() {
443 DVLOGF(3);
444 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
445 DCHECK(!input_streamon_);
446 DCHECK(input_buffer_map_.empty());
447
448 struct v4l2_requestbuffers reqbufs;
449 memset(&reqbufs, 0, sizeof(reqbufs));
450 reqbufs.count = kNumInputBuffers;
451 reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
452 reqbufs.memory = V4L2_MEMORY_MMAP;
453 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);
454 if (reqbufs.count < kNumInputBuffers) {
455 PLOG(ERROR) << "Could not allocate enough output buffers";
456 return false;
457 }
458 input_buffer_map_.resize(reqbufs.count);
459 for (size_t i = 0; i < input_buffer_map_.size(); ++i) {
460 free_input_buffers_.push_back(i);
461
462 // Query for the MEMORY_MMAP pointer.
463 struct v4l2_plane planes[VIDEO_MAX_PLANES];
464 struct v4l2_buffer buffer;
465 memset(&buffer, 0, sizeof(buffer));
466 memset(planes, 0, sizeof(planes));
467 buffer.index = i;
468 buffer.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
469 buffer.memory = V4L2_MEMORY_MMAP;
470 buffer.m.planes = planes;
471 buffer.length = input_planes_count_;
kcwu 2015/01/12 07:31:46 I think we usually don't align assignment?
Pawel Osciak 2015/01/13 11:33:34 Yup, sorry.
472 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYBUF, &buffer);
473 void* address = device_->Mmap(nullptr,
474 buffer.m.planes[0].length,
475 PROT_READ | PROT_WRITE,
476 MAP_SHARED,
477 buffer.m.planes[0].m.mem_offset);
478 if (address == MAP_FAILED) {
479 PLOG(ERROR) << "CreateInputBuffers(): mmap() failed";
480 return false;
481 }
482 input_buffer_map_[i].address = address;
483 input_buffer_map_[i].length = buffer.m.planes[0].length;
484 }
485
486 return true;
487 }
488
489 bool V4L2SliceVideoDecodeAccelerator::CreateOutputBuffers() {
490 DVLOGF(3);
491 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
492 DCHECK(!output_streamon_);
493 DCHECK(output_buffer_map_.empty());
494 DCHECK(surfaces_at_display_.empty());
495 DCHECK(surfaces_at_device_.empty());
496
497 frame_buffer_size_ = decoder_->GetPicSize();
498 output_dpb_size_ = decoder_->GetRequiredNumOfPictures();
499
500 DCHECK_GT(output_dpb_size_, 0u);
501 DCHECK(!frame_buffer_size_.IsEmpty());
502
503 struct v4l2_format format;
504 memset(&format, 0, sizeof(format));
505 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
506 format.fmt.pix_mp.pixelformat = output_format_fourcc_;
507 format.fmt.pix_mp.width = frame_buffer_size_.width();
508 format.fmt.pix_mp.height = frame_buffer_size_.height();
509 format.fmt.pix_mp.num_planes = input_planes_count_;
510
511 if (device_->Ioctl(VIDIOC_S_FMT, &format) != 0) {
512 PLOG(ERROR) << "Failed setting format to: " << output_format_fourcc_;
513 NOTIFY_ERROR(PLATFORM_FAILURE);
514 return false;
515 }
516
517 struct v4l2_requestbuffers reqbufs;
518 memset(&reqbufs, 0, sizeof(reqbufs));
519 reqbufs.count = output_dpb_size_;
520 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
521 reqbufs.memory = V4L2_MEMORY_MMAP;
522 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);
523
524 if (reqbufs.count < output_dpb_size_) {
525 PLOG(ERROR) << "Could not allocate enough output buffers";
526 return false;
527 }
528
529 output_buffer_map_.resize(reqbufs.count);
kcwu 2015/01/12 07:31:46 according to http://linuxtv.org/downloads/v4l-dvb-
Pawel Osciak 2015/01/13 11:33:33 In l.524 we check that we got not less than output
530
531 DVLOGF(3) << "buffer_count=" << output_buffer_map_.size()
532 << ", width=" << frame_buffer_size_.width()
533 << ", height=" << frame_buffer_size_.height();
534
535 child_message_loop_proxy_->PostTask(
536 FROM_HERE,
537 base::Bind(&VideoDecodeAccelerator::Client::ProvidePictureBuffers,
538 client_, output_buffer_map_.size(), frame_buffer_size_,
539 device_->GetTextureTarget()));
540
541 // Wait for the client to call AssignPictureBuffers() on the Child thread.
542 // We do this, because if we continue decoding without finishing buffer
543 // allocation, we may end up Resetting before AssignPictureBuffers arrives,
544 // resulting in unnecessary complications and subtle bugs.
545 pictures_assigned_.Wait();
546
547 return true;
548 }
549
550 void V4L2SliceVideoDecodeAccelerator::DestroyInputBuffers() {
551 DVLOGF(3);
552 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread() ||
553 !decoder_thread_.IsRunning());
554 DCHECK(!input_streamon_);
555
556 for (auto& input_record : input_buffer_map_) {
557 if (input_record.address != nullptr)
558 device_->Munmap(input_record.address, input_record.length);
559 }
560
561 struct v4l2_requestbuffers reqbufs;
562 memset(&reqbufs, 0, sizeof(reqbufs));
563 reqbufs.count = 0;
564 reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
565 reqbufs.memory = V4L2_MEMORY_MMAP;
566 IOCTL_OR_LOG_ERROR(VIDIOC_REQBUFS, &reqbufs);
567
568 input_buffer_map_.clear();
569 free_input_buffers_.clear();
570 }
571
572 void V4L2SliceVideoDecodeAccelerator::DismissPictures(
573 std::vector<int32> picture_buffer_ids,
574 base::WaitableEvent* done) {
575 DVLOGF(3);
576 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
577
578 for (auto picture_buffer_id : picture_buffer_ids) {
579 DVLOGF(1) << "dismissing PictureBuffer id=" << picture_buffer_id;
580 client_->DismissPictureBuffer(picture_buffer_id);
581 }
582
583 done->Signal();
584 }
585
586 void V4L2SliceVideoDecodeAccelerator::DevicePollTask(bool poll_device) {
587 DVLOGF(4);
588 DCHECK_EQ(device_poll_thread_.message_loop(), base::MessageLoop::current());
589
590 bool event_pending;
591 if (!device_->Poll(poll_device, &event_pending)) {
592 NOTIFY_ERROR(PLATFORM_FAILURE);
593 return;
594 }
595
596 // All processing should happen on ServiceDeviceTask(), since we shouldn't
597 // touch encoder state from this thread.
598 decoder_thread_proxy_->PostTask(
599 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::ServiceDeviceTask,
600 base::Unretained(this)));
601 }
602
603 void V4L2SliceVideoDecodeAccelerator::ServiceDeviceTask() {
604 DVLOGF(4);
605 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
606
607 // ServiceDeviceTask() should only ever be scheduled from DevicePollTask().
608
609 Dequeue();
610 SchedulePollIfNeeded();
611 }
612
613 void V4L2SliceVideoDecodeAccelerator::SchedulePollIfNeeded() {
614 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
615
616 if (!device_poll_thread_.IsRunning()) {
617 DVLOGF(2) << "Device poll thread stopped, will not schedule poll";
618 return;
619 }
620
621 DCHECK(input_streamon_ || output_streamon_);
622
623 if (input_buffer_queued_count_ + output_buffer_queued_count_ == 0) {
624 DVLOGF(4) << "No buffers queued, will not schedule poll";
625 return;
626 }
627
628 DVLOGF(4) << "Scheduling device poll task";
629
630 device_poll_thread_.message_loop()->PostTask(
631 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::DevicePollTask,
632 base::Unretained(this), true));
633
634 DVLOGF(2) << "buffer counts: "
635 << "INPUT[" << decoder_input_queue_.size() << "]"
636 << " => DEVICE["
637 << free_input_buffers_.size() << "+"
638 << input_buffer_queued_count_ << "/"
639 << input_buffer_map_.size() << "]->["
640 << free_output_buffers_.size() << "+"
641 << output_buffer_queued_count_ << "/"
642 << output_buffer_map_.size() << "]"
643 << " => DISPLAYQ[" << decoder_display_queue_.size() << "]"
644 << " => CLIENT[" << surfaces_at_display_.size() << "]";
645 }
646
647 void V4L2SliceVideoDecodeAccelerator::Enqueue(
648 const scoped_refptr<V4L2DecodeSurface>& dec_surface) {
649 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
650
651 const int old_inputs_queued = input_buffer_queued_count_;
652 const int old_outputs_queued = output_buffer_queued_count_;
653
654 if (!EnqueueInputRecord(dec_surface->input_record(),
655 dec_surface->config_store())) {
656 DVLOGF(1) << "Failed queueing an input buffer";
657 NOTIFY_ERROR(PLATFORM_FAILURE);
658 return;
659 }
660
661 if (!EnqueueOutputRecord(dec_surface->output_record())) {
662 DVLOGF(1) << "Failed queueing an output buffer";
663 NOTIFY_ERROR(PLATFORM_FAILURE);
664 return;
665 }
666
667 bool inserted =
668 surfaces_at_device_.insert(std::make_pair(dec_surface->output_record(),
669 dec_surface)).second;
670 DCHECK(inserted);
671
672 if (old_inputs_queued == 0 && old_outputs_queued == 0)
673 SchedulePollIfNeeded();
674 }
675
676 void V4L2SliceVideoDecodeAccelerator::Dequeue() {
677 DVLOGF(3);
678 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
679
680 struct v4l2_buffer dqbuf;
681 struct v4l2_plane planes[VIDEO_MAX_PLANES];
682 while (input_buffer_queued_count_ > 0) {
683 DCHECK(input_streamon_);
684 memset(&dqbuf, 0, sizeof(dqbuf));
685 memset(&planes, 0, sizeof(planes));
686 dqbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
687 dqbuf.memory = V4L2_MEMORY_USERPTR;
688 dqbuf.m.planes = planes;
689 dqbuf.length = input_planes_count_;
690 if (device_->Ioctl(VIDIOC_DQBUF, &dqbuf) != 0) {
691 if (errno == EAGAIN) {
692 // EAGAIN if we're just out of buffers to dequeue.
693 break;
694 }
695 PLOG(ERROR) << "ioctl() failed: VIDIOC_DQBUF";
696 NOTIFY_ERROR(PLATFORM_FAILURE);
697 return;
698 }
699 InputRecord& input_record = input_buffer_map_[dqbuf.index];
700 DCHECK(input_record.at_device);
701 input_record.at_device = false;
702 input_record.input_id = -1;
703 input_record.bytes_used = 0;
704 free_input_buffers_.push_back(dqbuf.index);
705 input_buffer_queued_count_--;
706 DVLOGF(4) << "Dequeued input=" << dqbuf.index
707 << " count: " << input_buffer_queued_count_;
708 }
709
710 while (output_buffer_queued_count_ > 0) {
711 DCHECK(output_streamon_);
712 memset(&dqbuf, 0, sizeof(dqbuf));
713 memset(&planes, 0, sizeof(planes));
714 dqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
715 dqbuf.memory = V4L2_MEMORY_MMAP;
716 dqbuf.m.planes = planes;
717 dqbuf.length = output_planes_count_;
718 if (device_->Ioctl(VIDIOC_DQBUF, &dqbuf) != 0) {
719 if (errno == EAGAIN) {
720 // EAGAIN if we're just out of buffers to dequeue.
721 break;
722 }
723 PLOG(ERROR) << "ioctl() failed: VIDIOC_DQBUF";
724 NOTIFY_ERROR(PLATFORM_FAILURE);
725 return;
726 }
727 OutputRecord& output_record = output_buffer_map_[dqbuf.index];
728 DCHECK(output_record.at_device);
729 output_record.at_device = false;
730 DCHECK_NE(output_record.picture_id, -1);
731 output_buffer_queued_count_--;
732 DVLOGF(3) << "Dequeued output=" << dqbuf.index
733 << " count " << output_buffer_queued_count_;
734
735 V4L2DecodeSurfaceByOutputId::iterator it =
736 surfaces_at_device_.find(dqbuf.index);
737 if (it == surfaces_at_device_.end()) {
738 DLOG(ERROR) << "Got invalid surface from device.";
739 NOTIFY_ERROR(PLATFORM_FAILURE);
740 }
741
742 it->second->SetDecoded();
743 surfaces_at_device_.erase(it);
744 }
745
746 // A frame was decoded, see if we can output it.
747 TryOutputSurfaces();
748
749 ProcessPendingEventsIfNeeded();
750 }
751
752 void V4L2SliceVideoDecodeAccelerator::ProcessPendingEventsIfNeeded() {
753 // Process pending events, if any, in the correct order.
754 // We always first process the surface set change, as it is an internal
755 // event from the decoder and interleaving it with external requests would
756 // put the decoder in an undefined state.
757 FinishSurfaceSetChangeIfNeeded();
758
759 // Process external (client) requests.
760 FinishFlushIfNeeded();
761 FinishResetIfNeeded();
762 }
763
764 void V4L2SliceVideoDecodeAccelerator::ReuseOutputBuffer(int index) {
765 DCHECK_LT(index, static_cast<int>(output_buffer_map_.size()));
766 DVLOGF(4) << "Reusing output buffer, index=" << index;
767 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
768
769 OutputRecord& output_record = output_buffer_map_[index];
770 DCHECK(!output_record.at_device);
771 output_record.at_client = false;
772
773 free_output_buffers_.push_back(index);
774
775 ScheduleDecodeBufferTaskIfNeeded();
776 }
777
778 bool V4L2SliceVideoDecodeAccelerator::EnqueueInputRecord(
779 int index,
780 uint32_t config_store) {
781 DVLOGF(3);
782 DCHECK_LT(index, static_cast<int>(input_buffer_map_.size()));
783 DCHECK_GT(config_store, 0u);
784
785 // Enqueue an input (VIDEO_OUTPUT) buffer for an input video frame.
786 InputRecord& input_record = input_buffer_map_[index];
787 DCHECK(!input_record.at_device);
788 struct v4l2_buffer qbuf;
789 struct v4l2_plane qbuf_planes[VIDEO_MAX_PLANES];
790 memset(&qbuf, 0, sizeof(qbuf));
791 memset(qbuf_planes, 0, sizeof(qbuf_planes));
792 qbuf.index = index;
793 qbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
794 qbuf.memory = V4L2_MEMORY_MMAP;
795 qbuf.m.planes = qbuf_planes;
796 qbuf.m.planes[0].bytesused = input_record.bytes_used;
797 qbuf.length = input_planes_count_;
798 qbuf.config_store = config_store;
799 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QBUF, &qbuf);
800 input_record.at_device = true;
801 input_buffer_queued_count_++;
802 DVLOGF(4) << "Enqueued input=" << qbuf.index
803 << " count: " << input_buffer_queued_count_;
804
805 return true;
806 }
807
808 bool V4L2SliceVideoDecodeAccelerator::EnqueueOutputRecord(int index) {
809 DVLOGF(3);
810 DCHECK_LT(index, static_cast<int>(output_buffer_map_.size()));
811
812 // Enqueue an output (VIDEO_CAPTURE) buffer.
813 OutputRecord& output_record = output_buffer_map_[index];
814 DCHECK(!output_record.at_device);
815 DCHECK(!output_record.at_client);
816 DCHECK_NE(output_record.egl_image, EGL_NO_IMAGE_KHR);
817 DCHECK_NE(output_record.picture_id, -1);
818 if (output_record.egl_sync != EGL_NO_SYNC_KHR) {
819 // If we have to wait for completion, wait. Note that
820 // free_output_buffers_ is a FIFO queue, so we always wait on the
821 // buffer that has been in the queue the longest.
822 if (eglClientWaitSyncKHR(egl_display_, output_record.egl_sync, 0,
823 EGL_FOREVER_KHR) == EGL_FALSE) {
824 // This will cause tearing, but is safe otherwise.
825 DVLOGF(1) << "eglClientWaitSyncKHR failed!";
826 }
827 if (eglDestroySyncKHR(egl_display_, output_record.egl_sync) != EGL_TRUE) {
828 LOGF(ERROR) << "eglDestroySyncKHR failed!";
829 NOTIFY_ERROR(PLATFORM_FAILURE);
830 return false;
831 }
832 output_record.egl_sync = EGL_NO_SYNC_KHR;
833 }
834
835 struct v4l2_buffer qbuf;
836 struct v4l2_plane qbuf_planes[VIDEO_MAX_PLANES];
837 memset(&qbuf, 0, sizeof(qbuf));
838 memset(qbuf_planes, 0, sizeof(qbuf_planes));
839 qbuf.index = index;
840 qbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
841 qbuf.memory = V4L2_MEMORY_MMAP;
842 qbuf.m.planes = qbuf_planes;
843 qbuf.length = output_planes_count_;
844 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QBUF, &qbuf);
845 output_record.at_device = true;
846 output_buffer_queued_count_++;
847 DVLOGF(4) << "Enqueued output=" << qbuf.index
848 << " count: " << output_buffer_queued_count_;
849
850 return true;
851 }
852
853 bool V4L2SliceVideoDecodeAccelerator::StartDevicePoll() {
854 DVLOGF(3) << "Starting device poll";
855 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
856 DCHECK(!device_poll_thread_.IsRunning());
857
858 // Start up the device poll thread and schedule its first DevicePollTask().
859 if (!device_poll_thread_.Start()) {
860 DLOG(ERROR) << "StartDevicePoll(): Device thread failed to start";
861 NOTIFY_ERROR(PLATFORM_FAILURE);
862 return false;
863 }
864 if (!input_streamon_) {
865 __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
866 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_STREAMON, &type);
867 input_streamon_ = true;
868 }
869
870 if (!output_streamon_) {
871 __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
872 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_STREAMON, &type);
873 output_streamon_ = true;
874 }
875
876 device_poll_thread_.message_loop()->PostTask(
877 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::DevicePollTask,
878 base::Unretained(this), true));
879
880 return true;
881 }
882
883 bool V4L2SliceVideoDecodeAccelerator::StopDevicePoll(bool keep_input_state) {
884 DVLOGF(3) << "Stopping device poll";
885 if (decoder_thread_.IsRunning())
886 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
887
888 // Signal the DevicePollTask() to stop, and stop the device poll thread.
889 if (!device_->SetDevicePollInterrupt()) {
890 PLOG(ERROR) << "SetDevicePollInterrupt(): failed";
891 NOTIFY_ERROR(PLATFORM_FAILURE);
892 return false;
893 }
894 device_poll_thread_.Stop();
895 DVLOGF(3) << "Device poll thread stopped";
896
897 // Clear the interrupt now, to be sure.
898 if (!device_->ClearDevicePollInterrupt()) {
899 NOTIFY_ERROR(PLATFORM_FAILURE);
900 return false;
901 }
902
903 if (!keep_input_state) {
904 if (input_streamon_) {
905 __u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
906 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_STREAMOFF, &type);
907 }
908 input_streamon_ = false;
909 }
910
911 if (output_streamon_) {
912 __u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
913 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_STREAMOFF, &type);
914 }
915 output_streamon_ = false;
916
917 if (!keep_input_state) {
918 free_input_buffers_.clear();
919 for (size_t i = 0; i < input_buffer_map_.size(); ++i) {
920 InputRecord& input_record = input_buffer_map_[i];
921 input_record.at_device = false;
922 input_record.bytes_used = 0;
923 input_record.input_id = -1;
924 free_input_buffers_.push_back(i);
925 }
926 input_buffer_queued_count_ = 0;
927 }
928
929 surfaces_at_device_.clear();
930
931 free_output_buffers_.clear();
932 for (size_t i = 0; i < output_buffer_map_.size(); ++i) {
933 OutputRecord& output_record = output_buffer_map_[i];
934 DCHECK(!(output_record.at_client && output_record.at_device));
935 output_record.at_device = false;
936 if (!output_record.at_client)
937 free_output_buffers_.push_back(i);
938 }
939 output_buffer_queued_count_ = 0;
940
941 DVLOGF(3) << "Device poll stopped";
942 return true;
943 }
944
945 void V4L2SliceVideoDecodeAccelerator::Decode(
946 const media::BitstreamBuffer& bitstream_buffer) {
947 DVLOGF(3) << "input_id=" << bitstream_buffer.id()
948 << ", size=" << bitstream_buffer.size();
949 DCHECK(io_message_loop_proxy_->BelongsToCurrentThread());
950
951 decoder_thread_proxy_->PostTask(
952 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::DecodeTask,
953 base::Unretained(this), bitstream_buffer));
954 }
955
956 void V4L2SliceVideoDecodeAccelerator::DecodeTask(
957 const media::BitstreamBuffer& bitstream_buffer) {
958 DVLOGF(3) << "input_id=" << bitstream_buffer.id()
959 << " size=" << bitstream_buffer.size();
960 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
961
962 scoped_ptr<BitstreamBufferRef> bitstream_record(new BitstreamBufferRef(
963 io_client_, io_message_loop_proxy_,
964 new base::SharedMemory(bitstream_buffer.handle(), true),
965 bitstream_buffer.size(), bitstream_buffer.id()));
966 if (!bitstream_record->shm->Map(bitstream_buffer.size())) {
967 LOGF(ERROR) << "Could not map bitstream_buffer";
968 NOTIFY_ERROR(UNREADABLE_INPUT);
969 return;
970 }
971 DVLOGF(3) << "mapped at=" << bitstream_record->shm->memory();
972
973 decoder_input_queue_.push(
974 linked_ptr<BitstreamBufferRef>(bitstream_record.release()));
975
976 ScheduleDecodeBufferTaskIfNeeded();
977 }
978
979 bool V4L2SliceVideoDecodeAccelerator::TrySetNewBistreamBuffer() {
980 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
981 DCHECK(!decoder_current_bitstream_buffer_);
982
983 if (decoder_input_queue_.empty())
984 return false;
985
986 decoder_current_bitstream_buffer_.reset(
987 decoder_input_queue_.front().release());
988 decoder_input_queue_.pop();
989
990 if (decoder_current_bitstream_buffer_->input_id == kFlushBufferId) {
991 // This is a buffer we queued for ourselves to trigger flush at this time.
992 InitiateFlush();
993 return false;
994 }
995
996 const uint8* const data = reinterpret_cast<const uint8*>(
997 decoder_current_bitstream_buffer_->shm->memory());
998 const size_t data_size = decoder_current_bitstream_buffer_->size;
999 decoder_->SetStream(data, data_size);
1000
1001 return true;
1002 }
1003
1004 void V4L2SliceVideoDecodeAccelerator::ScheduleDecodeBufferTaskIfNeeded() {
1005 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1006 if (state_ == kDecoding) {
1007 decoder_thread_proxy_->PostTask(
1008 FROM_HERE,
1009 base::Bind(&V4L2SliceVideoDecodeAccelerator::DecodeBufferTask,
1010 base::Unretained(this)));
1011 }
1012 }
1013
1014 void V4L2SliceVideoDecodeAccelerator::DecodeBufferTask() {
1015 DVLOGF(3);
1016 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1017
1018 if (state_ != kDecoding) {
1019 DVLOGF(3) << "Early exit, not in kDecoding";
1020 return;
1021 }
1022
1023 while (true) {
1024 AcceleratedVideoDecoder::DecResult res;
1025 res = decoder_->Decode();
1026 switch (res) {
1027 case AcceleratedVideoDecoder::kAllocateNewSurfaces:
1028 DVLOGF(2) << "Decoder requesting a new set of surfaces";
1029 InitiateSurfaceSetChange();
1030 return;
1031
1032 case AcceleratedVideoDecoder::kRanOutOfStreamData:
1033 decoder_current_bitstream_buffer_.reset();
1034 if (!TrySetNewBistreamBuffer())
1035 return;
1036
1037 break;
1038
1039 case AcceleratedVideoDecoder::kRanOutOfSurfaces:
1040 // No more surfaces for the decoder, we'll come back once we have more.
1041 DVLOGF(4) << "Ran out of surfaces";
1042 return;
1043
1044 case AcceleratedVideoDecoder::kDecodeError:
1045 DVLOGF(1) << "Error decoding stream";
1046 NOTIFY_ERROR(PLATFORM_FAILURE);
1047 return;
1048 }
1049 }
1050 }
1051
1052 void V4L2SliceVideoDecodeAccelerator::InitiateSurfaceSetChange() {
1053 DVLOGF(2);
1054 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1055 DCHECK_EQ(state_, kDecoding);
1056
1057 DCHECK_EQ(state_, kDecoding);
kcwu 2015/01/12 07:31:46 code duped
Pawel Osciak 2015/01/13 11:33:33 Done.
1058 state_ = kIdle;
1059
1060 DCHECK(!surface_set_change_pending_);
1061 surface_set_change_pending_ = true;
1062
1063 FinishSurfaceSetChangeIfNeeded();
1064 }
1065
1066 void V4L2SliceVideoDecodeAccelerator::FinishSurfaceSetChangeIfNeeded() {
1067 DVLOGF(2);
1068 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1069
1070 if (!surface_set_change_pending_ || !surfaces_at_device_.empty())
1071 return;
1072
1073 DCHECK_EQ(state_, kIdle);
1074 DCHECK(decoder_display_queue_.empty());
1075
1076 // Keep input queue running while we switch outputs.
1077 if (!StopDevicePoll(true)) {
1078 NOTIFY_ERROR(PLATFORM_FAILURE);
1079 return;
1080 }
1081
1082 // This will return only once all buffers are dismissed and destroyed.
1083 // This does not wait until they are displayed however, as display retains
1084 // references to the buffers bound to textures and will release them
1085 // after displaying.
1086 if (!DestroyOutputs(true)) {
1087 NOTIFY_ERROR(PLATFORM_FAILURE);
1088 return;
1089 }
1090
1091 if (!CreateOutputBuffers()) {
1092 NOTIFY_ERROR(PLATFORM_FAILURE);
1093 return;
1094 }
1095
1096 if (!StartDevicePoll()) {
1097 NOTIFY_ERROR(PLATFORM_FAILURE);
1098 return;
1099 }
1100
1101 DVLOGF(3) << "Surface set change finished";
1102
1103 surface_set_change_pending_ = false;
1104 state_ = kDecoding;
1105 ScheduleDecodeBufferTaskIfNeeded();
1106 }
1107
1108 bool V4L2SliceVideoDecodeAccelerator::DestroyOutputs(bool dismiss) {
1109 DVLOGF(3);
1110 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1111 std::vector<EGLImageKHR> egl_images_to_destroy;
1112 std::vector<int32> picture_buffers_to_dismiss;
1113
1114 if (output_buffer_map_.empty())
1115 return true;
1116
1117 for (auto output_record : output_buffer_map_) {
1118 DCHECK(!output_record.at_device);
1119 output_record.at_client = false;
1120
1121 if (output_record.egl_sync != EGL_NO_SYNC_KHR) {
1122 if (eglDestroySyncKHR(egl_display_, output_record.egl_sync) != EGL_TRUE)
1123 DVLOGF(1) << "eglDestroySyncKHR failed.";
1124 }
1125
1126 if (output_record.egl_image != EGL_NO_IMAGE_KHR) {
1127 child_message_loop_proxy_->PostTask(
1128 FROM_HERE,
1129 base::Bind(base::IgnoreResult(&V4L2Device::DestroyEGLImage), device_,
1130 egl_display_, output_record.egl_image));
1131 }
1132
1133 picture_buffers_to_dismiss.push_back(output_record.picture_id);
1134 }
1135
1136 if (dismiss) {
1137 DVLOGF(2) << "Scheduling picture dismissal";
1138 base::WaitableEvent done(false, false);
1139 child_message_loop_proxy_->PostTask(
1140 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::DismissPictures,
1141 weak_this_, picture_buffers_to_dismiss, &done));
1142 done.Wait();
1143 }
1144
1145 // At this point client can't call ReusePictureBuffer on any of the pictures
1146 // anymore, so it's safe to destroy.
1147 return DestroyOutputBuffers();
1148 }
1149
1150 bool V4L2SliceVideoDecodeAccelerator::DestroyOutputBuffers() {
1151 DVLOGF(3);
1152 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread() ||
1153 !decoder_thread_.IsRunning());
1154 DCHECK(!output_streamon_);
1155 DCHECK(surfaces_at_device_.empty());
1156 DCHECK(decoder_display_queue_.empty());
1157 DCHECK(surfaces_at_display_.size() + free_output_buffers_.size() ==
1158 output_buffer_map_.size());
1159
1160 if (output_buffer_map_.empty())
1161 return true;
1162
1163 // It's ok to do this, client will retain references to textures, but we are
1164 // not interested in reusing the surfaces anymore.
1165 // This will prevent us from reusing old surfaces in case we have some
1166 // ReusePictureBuffer() pending on ChildThread already. It's ok to ignore
1167 // them, because we have already dismissed them (in DestroyOutputs()).
1168 surfaces_at_display_.clear();
1169 DCHECK_EQ(free_output_buffers_.size(), output_buffer_map_.size());
1170
1171 free_output_buffers_.clear();
1172 output_buffer_map_.clear();
1173
1174 struct v4l2_requestbuffers reqbufs;
1175 memset(&reqbufs, 0, sizeof(reqbufs));
1176 reqbufs.count = 0;
1177 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
1178 reqbufs.memory = V4L2_MEMORY_MMAP;
1179 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);
1180
1181 return true;
1182 }
1183
1184 void V4L2SliceVideoDecodeAccelerator::AssignPictureBuffers(
1185 const std::vector<media::PictureBuffer>& buffers) {
1186 DVLOGF(3);
1187 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1188
1189 if (buffers.size() != output_buffer_map_.size()) {
1190 DLOG(ERROR) << "Failed to provide requested picture buffers. "
1191 << "(Got " << buffers.size()
1192 << ", requested " << output_buffer_map_.size() << ")";
1193 NOTIFY_ERROR(INVALID_ARGUMENT);
1194 return;
1195 }
1196
1197 if (!make_context_current_.Run()) {
1198 DLOG(ERROR) << "could not make context current";
1199 NOTIFY_ERROR(PLATFORM_FAILURE);
1200 return;
1201 }
1202
1203 gfx::ScopedTextureBinder bind_restore(GL_TEXTURE_EXTERNAL_OES, 0);
1204
1205 // It's safe to manipulate all the buffer state here, because the decoder
1206 // thread is waiting on pictures_assigned_.
1207 DCHECK(free_output_buffers_.empty());
1208 for (size_t i = 0; i < output_buffer_map_.size(); ++i) {
1209 DCHECK(buffers[i].size() == frame_buffer_size_);
1210
1211 OutputRecord& output_record = output_buffer_map_[i];
1212 DCHECK(!output_record.at_device);
1213 DCHECK(!output_record.at_client);
1214 DCHECK_EQ(output_record.egl_image, EGL_NO_IMAGE_KHR);
1215 DCHECK_EQ(output_record.egl_sync, EGL_NO_SYNC_KHR);
1216 DCHECK_EQ(output_record.picture_id, -1);
1217 DCHECK_EQ(output_record.cleared, false);
1218
1219 EGLImageKHR egl_image = device_->CreateEGLImage(egl_display_,
1220 egl_context_,
1221 buffers[i].texture_id(),
1222 frame_buffer_size_,
1223 i,
1224 output_format_fourcc_,
1225 output_planes_count_);
1226 if (egl_image == EGL_NO_IMAGE_KHR) {
1227 LOGF(ERROR) << "Could not create EGLImageKHR";
1228 // Ownership of EGLImages allocated in previous iterations of this loop
1229 // has been transferred to output_buffer_map_. After we error-out here
1230 // the destructor will handle their cleanup.
1231 NOTIFY_ERROR(PLATFORM_FAILURE);
1232 return;
1233 }
1234
1235 output_record.egl_image = egl_image;
1236 output_record.picture_id = buffers[i].id();
1237 free_output_buffers_.push_back(i);
1238 DVLOGF(3) << "buffer[" << i << "]: picture_id=" << output_record.picture_id;
1239 }
1240
1241 pictures_assigned_.Signal();
1242 }
1243
1244 void V4L2SliceVideoDecodeAccelerator::ReusePictureBuffer(
1245 int32 picture_buffer_id) {
1246 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1247 DVLOGF(4) << "picture_buffer_id=" << picture_buffer_id;
1248
1249 if (!make_context_current_.Run()) {
1250 LOGF(ERROR) << "could not make context current";
1251 NOTIFY_ERROR(PLATFORM_FAILURE);
1252 return;
1253 }
1254
1255 EGLSyncKHR egl_sync =
1256 eglCreateSyncKHR(egl_display_, EGL_SYNC_FENCE_KHR, NULL);
1257 if (egl_sync == EGL_NO_SYNC_KHR) {
1258 LOGF(ERROR) << "eglCreateSyncKHR() failed";
1259 NOTIFY_ERROR(PLATFORM_FAILURE);
1260 return;
1261 }
1262
1263 scoped_ptr<EGLSyncKHRRef> egl_sync_ref(
1264 new EGLSyncKHRRef(egl_display_, egl_sync));
1265 decoder_thread_proxy_->PostTask(
1266 FROM_HERE,
1267 base::Bind(&V4L2SliceVideoDecodeAccelerator::ReusePictureBufferTask,
1268 base::Unretained(this), picture_buffer_id,
1269 base::Passed(&egl_sync_ref)));
1270 }
1271
1272 void V4L2SliceVideoDecodeAccelerator::ReusePictureBufferTask(
1273 int32 picture_buffer_id,
1274 scoped_ptr<EGLSyncKHRRef> egl_sync_ref) {
1275 DVLOGF(3) << "picture_buffer_id=" << picture_buffer_id;
1276 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1277
1278 V4L2DecodeSurfaceByPictureBufferId::iterator it =
1279 surfaces_at_display_.find(picture_buffer_id);
1280 if (it == surfaces_at_display_.end()) {
1281 // It's possible that we've already posted a DismissPictureBuffer for this
1282 // picture, but it has not yet executed when this ReusePictureBuffer was
1283 // posted to us by the client. In that case just ignore this (we've already
1284 // dismissed it and accounted for that) and let the sync object get
1285 // destroyed.
1286 DVLOGF(3) << "got picture id= " << picture_buffer_id
1287 << " not in use (anymore?).";
1288 return;
1289 }
1290
1291 OutputRecord& output_record = output_buffer_map_[it->second->output_record()];
1292 if (output_record.at_device || !output_record.at_client) {
1293 DVLOGF(1) << "picture_buffer_id not reusable";
1294 NOTIFY_ERROR(INVALID_ARGUMENT);
1295 return;
1296 }
1297
1298 DCHECK_EQ(output_record.egl_sync, EGL_NO_SYNC_KHR);
1299 DCHECK(!output_record.at_device);
1300 output_record.at_client = false;
1301 output_record.egl_sync = egl_sync_ref->egl_sync;
1302 // Take ownership of the EGLSync.
1303 egl_sync_ref->egl_sync = EGL_NO_SYNC_KHR;
1304 surfaces_at_display_.erase(it);
1305 }
1306
1307 void V4L2SliceVideoDecodeAccelerator::Flush() {
1308 DVLOGF(3);
1309 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1310
1311 decoder_thread_proxy_->PostTask(
1312 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::FlushTask,
1313 base::Unretained(this)));
1314 }
1315
1316 void V4L2SliceVideoDecodeAccelerator::FlushTask() {
1317 DVLOGF(3);
1318 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1319
1320 if (!decoder_input_queue_.empty()) {
1321 // We are not done with pending inputs, so queue an empty buffer,
1322 // which - when reached - will trigger flush sequence.
1323 decoder_input_queue_.push(
1324 linked_ptr<BitstreamBufferRef>(new BitstreamBufferRef(
1325 io_client_, io_message_loop_proxy_, nullptr, 0, kFlushBufferId)));
1326 return;
1327 }
1328
1329 // No more inputs pending, so just finish flushing here.
1330 InitiateFlush();
1331 }
1332
1333 void V4L2SliceVideoDecodeAccelerator::InitiateFlush() {
1334 DVLOGF(3);
1335 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1336
1337 DCHECK(!decoder_flushing_);
1338 DCHECK_EQ(state_, kDecoding);
1339 state_ = kIdle;
1340
1341 // This will trigger output for all remaining surfaces in the decoder.
1342 // However, not all of them may be decoded yet (they would be queued
1343 // in hardware then).
1344 if (!decoder_->Flush()) {
1345 DVLOGF(1) << "Failed flushing the decoder.";
1346 NOTIFY_ERROR(PLATFORM_FAILURE);
1347 return;
1348 }
1349
1350 // Put the decoder in an idle state, ready to resume.
1351 decoder_->Reset();
1352
1353 decoder_flushing_ = true;
1354
1355 decoder_thread_proxy_->PostTask(
1356 FROM_HERE,
1357 base::Bind(&V4L2SliceVideoDecodeAccelerator::FinishFlushIfNeeded,
1358 base::Unretained(this)));
1359 }
1360
1361 void V4L2SliceVideoDecodeAccelerator::FinishFlushIfNeeded() {
1362 DVLOGF(3);
1363 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1364
1365 if (!decoder_flushing_ || !surfaces_at_device_.empty())
1366 return;
1367
1368 DCHECK_EQ(state_, kIdle);
1369
1370 // At this point, all remaining surfaces are decoded and dequeued, and since
1371 // we have already scheduled output for them in InitiateFlush(), their
1372 // respective PictureReady calls have been posted (or they have been queued on
1373 // pending_picture_ready_). So at this time, once we SendPictureReady(),
1374 // we will have all remaining PictureReady() posted to the client and we
1375 // can post NotifyFlushDone().
1376 DCHECK(decoder_display_queue_.empty());
1377 SendPictureReady();
1378
1379 child_message_loop_proxy_->PostTask(
1380 FROM_HERE, base::Bind(&Client::NotifyFlushDone, client_));
1381
1382 decoder_flushing_ = false;
1383
1384 DVLOGF(3) << "Flush finished";
1385 state_ = kDecoding;
1386 ScheduleDecodeBufferTaskIfNeeded();
1387 }
1388
1389 void V4L2SliceVideoDecodeAccelerator::Reset() {
1390 DVLOGF(3);
1391 DCHECK(child_message_loop_proxy_->BelongsToCurrentThread());
1392
1393 decoder_thread_proxy_->PostTask(
1394 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::ResetTask,
1395 base::Unretained(this)));
1396 }
1397
1398 void V4L2SliceVideoDecodeAccelerator::ResetTask() {
1399 DVLOGF(3);
1400 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1401
1402 if (decoder_resetting_) {
1403 // This is a bug in the client, multiple Reset()s before NotifyResetDone()
1404 // are not allowed.
1405 NOTREACHED() << "Client should not be requesting multiple Reset()s";
1406 return;
1407 }
1408
1409 DCHECK_EQ(state_, kDecoding);
1410 state_ = kIdle;
1411
1412 // Put the decoder in an idle state, ready to resume.
1413 decoder_->Reset();
1414
1415 decoder_resetting_ = true;
1416
1417 // Drop all remaining inputs.
1418 decoder_current_bitstream_buffer_.reset();
1419 while (!decoder_input_queue_.empty())
1420 decoder_input_queue_.pop();
1421
1422 FinishResetIfNeeded();
1423 }
1424
1425 void V4L2SliceVideoDecodeAccelerator::FinishResetIfNeeded() {
1426 DVLOGF(3);
1427 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1428
1429 if (!decoder_resetting_ || !surfaces_at_device_.empty())
1430 return;
1431
1432 DCHECK_EQ(state_, kIdle);
1433 DCHECK(!decoder_flushing_);
1434
1435 // Drop any pending outputs.
1436 while (!decoder_display_queue_.empty())
1437 decoder_display_queue_.pop();
1438
1439 SendPictureReady();
1440 decoder_resetting_ = false;
1441
1442 child_message_loop_proxy_->PostTask(
1443 FROM_HERE, base::Bind(&Client::NotifyResetDone, client_));
1444
1445 DVLOGF(3) << "Reset finished";
1446
1447 state_ = kDecoding;
1448 ScheduleDecodeBufferTaskIfNeeded();
1449 }
1450
1451 void V4L2SliceVideoDecodeAccelerator::SetErrorState(Error error) {
1452 // We can touch decoder_state_ only if this is the decoder thread or the
1453 // decoder thread isn't running.
1454 if (decoder_thread_.IsRunning() &&
1455 !decoder_thread_proxy_->BelongsToCurrentThread()) {
1456 decoder_thread_proxy_->PostTask(
1457 FROM_HERE, base::Bind(&V4L2SliceVideoDecodeAccelerator::SetErrorState,
1458 base::Unretained(this), error));
1459 return;
1460 }
1461
1462 // Post NotifyError only if we are already initialized, as the API does
1463 // not allow doing so before that.
1464 if (state_ != kError && state_ != kUninitialized)
1465 NotifyError(error);
1466
1467 state_ = kError;
1468 }
1469
1470 V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::V4L2H264Accelerator(
1471 V4L2SliceVideoDecodeAccelerator* v4l2_dec)
1472 : num_slices_(0), v4l2_dec_(v4l2_dec) {
1473 DCHECK(v4l2_dec_);
1474 }
1475
1476 scoped_refptr<H264Picture>
1477 V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::CreateH264Picture() {
1478 scoped_refptr<V4L2DecodeSurface> dec_surface = v4l2_dec_->CreateSurface();
1479 if (!dec_surface)
1480 return nullptr;
1481
1482 return new V4L2H264Picture(dec_surface);
1483 }
1484
1485 void V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::
1486 H264PictureListToDPBIndicesList(const H264Picture::Vector& src_pic_list,
1487 uint8_t dst_list[32]) {
1488 size_t i = 0;
1489 for (auto& pic : src_pic_list)
1490 dst_list[i++] = pic ? pic->dpb_position : VIDEO_MAX_FRAME;
1491
1492 while (i < 32)
1493 dst_list[i++] = VIDEO_MAX_FRAME;
1494 }
1495
1496 void V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::H264DPBToV4L2DPB(
1497 const H264DPB& dpb,
1498 std::vector<scoped_refptr<V4L2DecodeSurface>>* ref_surfaces) {
1499 memset(v4l2_decode_param_.dpb, 0, sizeof(v4l2_decode_param_.dpb));
1500 size_t i = 0;
1501 for (const auto& pic : dpb) {
1502 struct v4l2_h264_dpb_entry& entry = v4l2_decode_param_.dpb[i++];
1503 scoped_refptr<V4L2DecodeSurface> dec_surface =
1504 H264PictureToV4L2DecodeSurface(pic);
1505 entry.buf_index = dec_surface->output_record();
1506 entry.frame_num = pic->frame_num;
1507 entry.pic_num = pic->pic_num;
1508 entry.top_field_order_cnt = pic->top_field_order_cnt;
1509 entry.bottom_field_order_cnt = pic->bottom_field_order_cnt;
1510 entry.flags = (pic->ref ? V4L2_H264_DPB_ENTRY_FLAG_ACTIVE : 0) |
1511 (pic->long_term ? V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM : 0);
1512
1513 ref_surfaces->push_back(dec_surface);
1514 }
1515 }
1516
1517 bool V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::SubmitFrameMetadata(
1518 const media::H264SPS* sps,
1519 const media::H264PPS* pps,
1520 const H264DPB& dpb,
1521 const H264Picture::Vector& ref_pic_listp0,
1522 const H264Picture::Vector& ref_pic_listb0,
1523 const H264Picture::Vector& ref_pic_listb1,
1524 const scoped_refptr<H264Picture>& pic) {
1525 struct v4l2_ext_control ctrl;
1526 std::vector<struct v4l2_ext_control> ctrls;
1527
1528 struct v4l2_ctrl_h264_sps v4l2_sps;
1529 memset(&v4l2_sps, 0, sizeof(v4l2_sps));
1530 v4l2_sps.constraint_set_flags =
1531 sps->constraint_set0_flag ? V4L2_H264_SPS_CONSTRAINT_SET0_FLAG : 0 |
1532 sps->constraint_set1_flag ? V4L2_H264_SPS_CONSTRAINT_SET1_FLAG : 0 |
1533 sps->constraint_set2_flag ? V4L2_H264_SPS_CONSTRAINT_SET2_FLAG : 0 |
1534 sps->constraint_set3_flag ? V4L2_H264_SPS_CONSTRAINT_SET3_FLAG : 0 |
1535 sps->constraint_set4_flag ? V4L2_H264_SPS_CONSTRAINT_SET4_FLAG : 0 |
1536 sps->constraint_set5_flag ? V4L2_H264_SPS_CONSTRAINT_SET5_FLAG : 0;
1537 #define SPS_TO_V4L2SPS(a) v4l2_sps.a = sps->a
1538 SPS_TO_V4L2SPS(profile_idc);
1539 SPS_TO_V4L2SPS(level_idc);
1540 SPS_TO_V4L2SPS(seq_parameter_set_id);
1541 SPS_TO_V4L2SPS(chroma_format_idc);
1542 SPS_TO_V4L2SPS(bit_depth_luma_minus8);
1543 SPS_TO_V4L2SPS(bit_depth_chroma_minus8);
1544 SPS_TO_V4L2SPS(log2_max_frame_num_minus4);
1545 SPS_TO_V4L2SPS(pic_order_cnt_type);
1546 SPS_TO_V4L2SPS(log2_max_pic_order_cnt_lsb_minus4);
1547 SPS_TO_V4L2SPS(offset_for_non_ref_pic);
1548 SPS_TO_V4L2SPS(offset_for_top_to_bottom_field);
1549 SPS_TO_V4L2SPS(num_ref_frames_in_pic_order_cnt_cycle);
1550
1551 COMPILE_ASSERT(arraysize(v4l2_sps.offset_for_ref_frame) ==
1552 arraysize(sps->offset_for_ref_frame),
1553 offset_for_ref_frame_arrays_must_be_same_size);
1554 for (size_t i = 0; i < arraysize(v4l2_sps.offset_for_ref_frame); ++i)
1555 v4l2_sps.offset_for_ref_frame[i] = sps->offset_for_ref_frame[i];
1556 SPS_TO_V4L2SPS(max_num_ref_frames);
1557 SPS_TO_V4L2SPS(pic_width_in_mbs_minus1);
1558 SPS_TO_V4L2SPS(pic_height_in_map_units_minus1);
1559 #undef SPS_TO_V4L2SPS
1560
1561 #define SET_V4L2_SPS_FLAG_IF(cond, flag) \
1562 v4l2_sps.flags |= ((sps->cond) ? (flag) : 0)
1563 SET_V4L2_SPS_FLAG_IF(separate_colour_plane_flag,
1564 V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE);
1565 SET_V4L2_SPS_FLAG_IF(qpprime_y_zero_transform_bypass_flag,
1566 V4L2_H264_SPS_FLAG_QPPRIME_Y_ZERO_TRANSFORM_BYPASS);
1567 SET_V4L2_SPS_FLAG_IF(delta_pic_order_always_zero_flag,
1568 V4L2_H264_SPS_FLAG_DELTA_PIC_ORDER_ALWAYS_ZERO);
1569 SET_V4L2_SPS_FLAG_IF(gaps_in_frame_num_value_allowed_flag,
1570 V4L2_H264_SPS_FLAG_GAPS_IN_FRAME_NUM_VALUE_ALLOWED);
1571 SET_V4L2_SPS_FLAG_IF(frame_mbs_only_flag, V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY);
1572 SET_V4L2_SPS_FLAG_IF(mb_adaptive_frame_field_flag,
1573 V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD);
1574 SET_V4L2_SPS_FLAG_IF(direct_8x8_inference_flag,
1575 V4L2_H264_SPS_FLAG_DIRECT_8X8_INFERENCE);
1576 #undef SET_FLAG
1577 memset(&ctrl, 0, sizeof(ctrl));
1578 ctrl.id = V4L2_CID_MPEG_VIDEO_H264_SPS;
1579 ctrl.size = sizeof(v4l2_sps);
1580 ctrl.p_h264_sps = &v4l2_sps;
1581 ctrls.push_back(ctrl);
1582
1583 struct v4l2_ctrl_h264_pps v4l2_pps;
1584 memset(&v4l2_pps, 0, sizeof(v4l2_pps));
1585 #define PPS_TO_V4L2PPS(a) v4l2_pps.a = pps->a
1586 PPS_TO_V4L2PPS(pic_parameter_set_id);
1587 PPS_TO_V4L2PPS(seq_parameter_set_id);
1588 PPS_TO_V4L2PPS(num_slice_groups_minus1);
1589 PPS_TO_V4L2PPS(num_ref_idx_l0_default_active_minus1);
1590 PPS_TO_V4L2PPS(num_ref_idx_l1_default_active_minus1);
1591 PPS_TO_V4L2PPS(weighted_bipred_idc);
1592 PPS_TO_V4L2PPS(pic_init_qp_minus26);
1593 PPS_TO_V4L2PPS(pic_init_qs_minus26);
1594 PPS_TO_V4L2PPS(chroma_qp_index_offset);
1595 PPS_TO_V4L2PPS(second_chroma_qp_index_offset);
1596 #undef PPS_TO_V4L2PPS
1597
1598 #define SET_V4L2_PPS_FLAG_IF(cond, flag) \
1599 v4l2_pps.flags |= ((pps->cond) ? (flag) : 0)
1600 SET_V4L2_PPS_FLAG_IF(entropy_coding_mode_flag,
1601 V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE);
1602 SET_V4L2_PPS_FLAG_IF(
1603 bottom_field_pic_order_in_frame_present_flag,
1604 V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT);
1605 SET_V4L2_PPS_FLAG_IF(weighted_pred_flag, V4L2_H264_PPS_FLAG_WEIGHTED_PRED);
1606 SET_V4L2_PPS_FLAG_IF(deblocking_filter_control_present_flag,
1607 V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT);
1608 SET_V4L2_PPS_FLAG_IF(constrained_intra_pred_flag,
1609 V4L2_H264_PPS_FLAG_CONSTRAINED_INTRA_PRED);
1610 SET_V4L2_PPS_FLAG_IF(redundant_pic_cnt_present_flag,
1611 V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT);
1612 SET_V4L2_PPS_FLAG_IF(transform_8x8_mode_flag,
1613 V4L2_H264_PPS_FLAG_TRANSFORM_8X8_MODE);
1614 SET_V4L2_PPS_FLAG_IF(pic_scaling_matrix_present_flag,
1615 V4L2_H264_PPS_FLAG_PIC_SCALING_MATRIX_PRESENT);
1616 #undef SET_V4L2_PPS_FLAG_IF
1617 memset(&ctrl, 0, sizeof(ctrl));
1618 ctrl.id = V4L2_CID_MPEG_VIDEO_H264_PPS;
1619 ctrl.size = sizeof(v4l2_pps);
1620 ctrl.p_h264_pps = &v4l2_pps;
1621 ctrls.push_back(ctrl);
1622
1623 struct v4l2_ctrl_h264_scaling_matrix v4l2_scaling_matrix;
1624 memset(&v4l2_scaling_matrix, 0, sizeof(v4l2_scaling_matrix));
1625 COMPILE_ASSERT(arraysize(v4l2_scaling_matrix.scaling_list_4x4) <=
1626 arraysize(pps->scaling_list4x4) &&
1627 arraysize(v4l2_scaling_matrix.scaling_list_4x4[0]) <=
1628 arraysize(pps->scaling_list4x4[0]) &&
1629 arraysize(v4l2_scaling_matrix.scaling_list_8x8) <=
1630 arraysize(pps->scaling_list8x8) &&
1631 arraysize(v4l2_scaling_matrix.scaling_list_8x8[0]) <=
1632 arraysize(pps->scaling_list8x8[0]),
1633 scaling_lists_invalid_size);
1634 for (size_t i = 0; i < arraysize(v4l2_scaling_matrix.scaling_list_4x4); ++i) {
1635 for (size_t j = 0; j < arraysize(v4l2_scaling_matrix.scaling_list_4x4[i]);
1636 ++j) {
1637 v4l2_scaling_matrix.scaling_list_4x4[i][j] = pps->scaling_list4x4[i][j];
1638 }
1639 }
1640 for (size_t i = 0; i < arraysize(v4l2_scaling_matrix.scaling_list_8x8); ++i) {
1641 for (size_t j = 0; j < arraysize(v4l2_scaling_matrix.scaling_list_8x8[i]);
1642 ++j) {
1643 v4l2_scaling_matrix.scaling_list_8x8[i][j] = pps->scaling_list8x8[i][j];
1644 }
1645 }
1646 memset(&ctrl, 0, sizeof(ctrl));
1647 ctrl.id = V4L2_CID_MPEG_VIDEO_H264_SCALING_MATRIX;
1648 ctrl.size = sizeof(v4l2_scaling_matrix);
1649 ctrl.p_h264_scal_mtrx = &v4l2_scaling_matrix;
1650 ctrls.push_back(ctrl);
1651
1652 scoped_refptr<V4L2DecodeSurface> dec_surface =
1653 H264PictureToV4L2DecodeSurface(pic);
1654
1655 struct v4l2_ext_controls ext_ctrls;
1656 memset(&ext_ctrls, 0, sizeof(ext_ctrls));
1657 ext_ctrls.count = ctrls.size();
1658 ext_ctrls.controls = &ctrls[0];
1659 ext_ctrls.config_store = dec_surface->config_store();
1660 v4l2_dec_->SubmitExtControls(&ext_ctrls);
1661
1662 H264PictureListToDPBIndicesList(ref_pic_listp0,
1663 v4l2_decode_param_.ref_pic_list_p0);
1664 H264PictureListToDPBIndicesList(ref_pic_listb0,
1665 v4l2_decode_param_.ref_pic_list_b0);
1666 H264PictureListToDPBIndicesList(ref_pic_listb1,
1667 v4l2_decode_param_.ref_pic_list_b1);
1668
1669 std::vector<scoped_refptr<V4L2DecodeSurface>> ref_surfaces;
1670 H264DPBToV4L2DPB(dpb, &ref_surfaces);
1671 dec_surface->SetReferenceSurfaces(ref_surfaces);
1672
1673 return true;
1674 }
1675
1676 bool V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::SubmitSlice(
1677 const media::H264PPS* pps,
1678 const media::H264SliceHeader* slice_hdr,
1679 const H264Picture::Vector& ref_pic_list0,
1680 const H264Picture::Vector& ref_pic_list1,
1681 const scoped_refptr<H264Picture>& pic,
1682 const uint8_t* data,
1683 size_t size) {
1684 if (num_slices_ == kMaxSlices) {
1685 LOGF(ERROR) << "Over limit of supported slices per frame";
1686 return false;
1687 }
1688
1689 struct v4l2_ctrl_h264_slice_param& v4l2_slice_param =
1690 v4l2_slice_params_[num_slices_++];
1691 memset(&v4l2_slice_param, 0, sizeof(v4l2_slice_param));
1692
1693 v4l2_slice_param.size = size;
1694 #define SHDR_TO_V4L2SPARM(a) v4l2_slice_param.a = slice_hdr->a
1695 SHDR_TO_V4L2SPARM(header_bit_size);
1696 SHDR_TO_V4L2SPARM(first_mb_in_slice);
1697 SHDR_TO_V4L2SPARM(slice_type);
1698 SHDR_TO_V4L2SPARM(pic_parameter_set_id);
1699 SHDR_TO_V4L2SPARM(colour_plane_id);
1700 SHDR_TO_V4L2SPARM(frame_num);
1701 SHDR_TO_V4L2SPARM(idr_pic_id);
1702 SHDR_TO_V4L2SPARM(pic_order_cnt_lsb);
1703 SHDR_TO_V4L2SPARM(delta_pic_order_cnt_bottom);
1704 SHDR_TO_V4L2SPARM(delta_pic_order_cnt0);
1705 SHDR_TO_V4L2SPARM(delta_pic_order_cnt1);
1706 SHDR_TO_V4L2SPARM(redundant_pic_cnt);
1707 SHDR_TO_V4L2SPARM(dec_ref_pic_marking_bit_size);
1708 SHDR_TO_V4L2SPARM(cabac_init_idc);
1709 SHDR_TO_V4L2SPARM(slice_qp_delta);
1710 SHDR_TO_V4L2SPARM(slice_qs_delta);
1711 SHDR_TO_V4L2SPARM(disable_deblocking_filter_idc);
1712 SHDR_TO_V4L2SPARM(slice_alpha_c0_offset_div2);
1713 SHDR_TO_V4L2SPARM(slice_beta_offset_div2);
1714 SHDR_TO_V4L2SPARM(num_ref_idx_l0_active_minus1);
1715 SHDR_TO_V4L2SPARM(num_ref_idx_l1_active_minus1);
1716 SHDR_TO_V4L2SPARM(pic_order_cnt_bit_size);
1717 #undef SHDR_TO_V4L2SPARM
1718
1719 #define SET_V4L2_SPARM_FLAG_IF(cond, flag) \
1720 v4l2_slice_param.flags |= ((slice_hdr->cond) ? (flag) : 0)
1721 SET_V4L2_SPARM_FLAG_IF(field_pic_flag, V4L2_SLICE_FLAG_FIELD_PIC);
1722 SET_V4L2_SPARM_FLAG_IF(bottom_field_flag, V4L2_SLICE_FLAG_BOTTOM_FIELD);
1723 SET_V4L2_SPARM_FLAG_IF(direct_spatial_mv_pred_flag,
1724 V4L2_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED);
1725 SET_V4L2_SPARM_FLAG_IF(sp_for_switch_flag, V4L2_SLICE_FLAG_SP_FOR_SWITCH);
1726 #undef SET_V4L2_SPARM_FLAG_IF
1727
1728 struct v4l2_h264_pred_weight_table* pred_weight_table =
1729 &v4l2_slice_param.pred_weight_table;
1730
1731 if (((slice_hdr->IsPSlice() || slice_hdr->IsSPSlice()) &&
1732 pps->weighted_pred_flag) ||
1733 (slice_hdr->IsBSlice() && pps->weighted_bipred_idc == 1)) {
1734 pred_weight_table->luma_log2_weight_denom =
1735 slice_hdr->luma_log2_weight_denom;
1736 pred_weight_table->chroma_log2_weight_denom =
1737 slice_hdr->chroma_log2_weight_denom;
1738
1739 struct v4l2_h264_weight_factors* factorsl0 =
1740 &pred_weight_table->weight_factors[0];
1741
1742 for (int i = 0; i < 32; ++i) {
1743 factorsl0->luma_weight[i] =
1744 slice_hdr->pred_weight_table_l0.luma_weight[i];
1745 factorsl0->luma_offset[i] =
1746 slice_hdr->pred_weight_table_l0.luma_offset[i];
1747
1748 for (int j = 0; j < 2; ++j) {
1749 factorsl0->chroma_weight[i][j] =
1750 slice_hdr->pred_weight_table_l0.chroma_weight[i][j];
1751 factorsl0->chroma_offset[i][j] =
1752 slice_hdr->pred_weight_table_l0.chroma_offset[i][j];
1753 }
1754 }
1755
1756 if (slice_hdr->IsBSlice()) {
1757 struct v4l2_h264_weight_factors* factorsl1 =
1758 &pred_weight_table->weight_factors[1];
1759
1760 for (int i = 0; i < 32; ++i) {
1761 factorsl1->luma_weight[i] =
1762 slice_hdr->pred_weight_table_l1.luma_weight[i];
1763 factorsl1->luma_offset[i] =
1764 slice_hdr->pred_weight_table_l1.luma_offset[i];
1765
1766 for (int j = 0; j < 2; ++j) {
1767 factorsl1->chroma_weight[i][j] =
1768 slice_hdr->pred_weight_table_l1.chroma_weight[i][j];
1769 factorsl1->chroma_offset[i][j] =
1770 slice_hdr->pred_weight_table_l1.chroma_offset[i][j];
1771 }
1772 }
1773 }
1774 }
1775
1776 H264PictureListToDPBIndicesList(ref_pic_list0,
1777 v4l2_slice_param.ref_pic_list0);
1778 H264PictureListToDPBIndicesList(ref_pic_list1,
1779 v4l2_slice_param.ref_pic_list1);
1780
1781 scoped_refptr<V4L2DecodeSurface> dec_surface =
1782 H264PictureToV4L2DecodeSurface(pic);
1783
1784 v4l2_decode_param_.nal_ref_idc = slice_hdr->nal_ref_idc;
1785
1786 // TODO(posciak): Don't add start code back here, but have it passed from
1787 // the parser.
1788 size_t data_copy_size = size + 3;
1789 scoped_ptr<uint8_t[]> data_copy(new uint8_t[data_copy_size]);
1790 memset(data_copy.get(), 0, data_copy_size);
1791 data_copy[2] = 0x01;
1792 memcpy(data_copy.get() + 3, data, size);
1793 return v4l2_dec_->SubmitSlice(dec_surface->input_record(), data_copy.get(),
1794 data_copy_size);
1795 }
1796
1797 bool V4L2SliceVideoDecodeAccelerator::SubmitSlice(int index,
1798 const uint8_t* data,
1799 size_t size) {
1800 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
1801
1802 InputRecord& input_record = input_buffer_map_[index];
1803
1804 if (input_record.bytes_used + size > input_record.length) {
1805 DVLOGF(1) << "Input buffer too small";
1806 return false;
1807 }
1808
1809 memcpy(static_cast<uint8*>(input_record.address) + input_record.bytes_used,
1810 data, size);
1811 input_record.bytes_used += size;
1812
1813 return true;
1814 }
1815
1816 bool V4L2SliceVideoDecodeAccelerator::SubmitExtControls(
1817 struct v4l2_ext_controls* ext_ctrls) {
1818 DCHECK_GT(ext_ctrls->config_store, 0u);
1819 IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_EXT_CTRLS, ext_ctrls);
1820 return true;
1821 }
1822
1823 bool V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::SubmitDecode(
1824 const scoped_refptr<H264Picture>& pic) {
1825 scoped_refptr<V4L2DecodeSurface> dec_surface =
1826 H264PictureToV4L2DecodeSurface(pic);
1827
1828 v4l2_decode_param_.num_slices = num_slices_;
1829 v4l2_decode_param_.idr_pic_flag = pic->idr;
1830 v4l2_decode_param_.top_field_order_cnt = pic->top_field_order_cnt;
1831 v4l2_decode_param_.bottom_field_order_cnt = pic->bottom_field_order_cnt;
1832
1833 struct v4l2_ext_control ctrl;
1834 std::vector<struct v4l2_ext_control> ctrls;
1835
1836 memset(&ctrl, 0, sizeof(ctrl));
1837 ctrl.id = V4L2_CID_MPEG_VIDEO_H264_SLICE_PARAM;
1838 ctrl.size = sizeof(v4l2_slice_params_);
1839 ctrl.p_h264_slice_param = v4l2_slice_params_;
1840 ctrls.push_back(ctrl);
1841
1842 memset(&ctrl, 0, sizeof(ctrl));
1843 ctrl.id = V4L2_CID_MPEG_VIDEO_H264_DECODE_PARAM;
1844 ctrl.size = sizeof(v4l2_decode_param_);
1845 ctrl.p_h264_decode_param = &v4l2_decode_param_;
1846 ctrls.push_back(ctrl);
1847
1848 struct v4l2_ext_controls ext_ctrls;
1849 memset(&ext_ctrls, 0, sizeof(ext_ctrls));
1850 ext_ctrls.count = ctrls.size();
1851 ext_ctrls.controls = &ctrls[0];
1852 ext_ctrls.config_store = dec_surface->config_store();
1853 v4l2_dec_->SubmitExtControls(&ext_ctrls);
1854
1855 num_slices_ = 0;
1856 memset(&v4l2_decode_param_, 0, sizeof(v4l2_decode_param_));
1857 memset(&v4l2_slice_params_, 0, sizeof(v4l2_slice_params_));
1858
1859 v4l2_dec_->DecodeSurface(dec_surface);
1860 return true;
1861 }
1862
1863 bool V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::OutputPicture(
1864 const scoped_refptr<H264Picture>& pic) {
1865 scoped_refptr<V4L2DecodeSurface> dec_surface =
1866 H264PictureToV4L2DecodeSurface(pic);
1867 v4l2_dec_->SurfaceReady(dec_surface);
1868 return true;
1869 }
1870
1871 scoped_refptr<V4L2SliceVideoDecodeAccelerator::V4L2DecodeSurface>
1872 V4L2SliceVideoDecodeAccelerator::V4L2H264Accelerator::
1873 H264PictureToV4L2DecodeSurface(const scoped_refptr<H264Picture>& pic) {
1874 V4L2H264Picture* v4l2_pic = pic->AsV4L2H264Picture();
1875 CHECK(v4l2_pic);
1876 return v4l2_pic->dec_surface();
1877 }
1878
1879 V4L2SliceVideoDecodeAccelerator::V4L2VP8Accelerator::V4L2VP8Accelerator(
1880 V4L2SliceVideoDecodeAccelerator* v4l2_dec)
1881 : v4l2_dec_(v4l2_dec) {
1882 DCHECK(v4l2_dec_);
1883 }
1884
1885 scoped_refptr<VP8Picture>
1886 V4L2SliceVideoDecodeAccelerator::V4L2VP8Accelerator::CreateVP8Picture() {
1887 scoped_refptr<V4L2DecodeSurface> dec_surface = v4l2_dec_->CreateSurface();
1888 if (!dec_surface)
1889 return nullptr;
1890
1891 return new V4L2VP8Picture(dec_surface);
1892 }
1893
1894 #define ARRAY_MEMCPY_CHECKED(to, from) \
1895 do { \
1896 static_assert(sizeof(to) == sizeof(from), \
1897 #from " and " #to " arrays must be of same size"); \
1898 memcpy(to, from, sizeof(to)); \
1899 } while (0)
1900
1901 static void FillV4L2SegmentationHeader(
1902 const media::Vp8SegmentationHeader& vp8_sgmnt_hdr,
1903 struct v4l2_vp8_sgmnt_hdr* v4l2_sgmnt_hdr) {
1904 #define SET_V4L2_SGMNT_HDR_FLAG_IF(cond, flag) \
1905 v4l2_sgmnt_hdr->flags |= ((vp8_sgmnt_hdr.cond) ? (flag) : 0)
1906 SET_V4L2_SGMNT_HDR_FLAG_IF(segmentation_enabled,
1907 V4L2_VP8_SEGMNT_HDR_FLAG_ENABLED);
1908 SET_V4L2_SGMNT_HDR_FLAG_IF(update_mb_segmentation_map,
1909 V4L2_VP8_SEGMNT_HDR_FLAG_UPDATE_MAP);
1910 SET_V4L2_SGMNT_HDR_FLAG_IF(update_segment_feature_data,
1911 V4L2_VP8_SEGMNT_HDR_FLAG_UPDATE_FEATURE_DATA);
1912 #undef SET_V4L2_SPARM_FLAG_IF
1913 v4l2_sgmnt_hdr->segment_feature_mode = vp8_sgmnt_hdr.segment_feature_mode;
1914
1915 ARRAY_MEMCPY_CHECKED(v4l2_sgmnt_hdr->quant_update,
1916 vp8_sgmnt_hdr.quantizer_update_value);
1917 ARRAY_MEMCPY_CHECKED(v4l2_sgmnt_hdr->lf_update,
1918 vp8_sgmnt_hdr.lf_update_value);
1919 ARRAY_MEMCPY_CHECKED(v4l2_sgmnt_hdr->segment_probs,
1920 vp8_sgmnt_hdr.segment_prob);
1921 }
1922
1923 static void FillV4L2LoopfilterHeader(
1924 const media::Vp8LoopFilterHeader& vp8_loopfilter_hdr,
1925 struct v4l2_vp8_loopfilter_hdr* v4l2_lf_hdr) {
1926 #define SET_V4L2_LF_HDR_FLAG_IF(cond, flag) \
1927 v4l2_lf_hdr->flags |= ((vp8_loopfilter_hdr.cond) ? (flag) : 0)
1928 SET_V4L2_LF_HDR_FLAG_IF(loop_filter_adj_enable, V4L2_VP8_LF_HDR_ADJ_ENABLE);
1929 SET_V4L2_LF_HDR_FLAG_IF(mode_ref_lf_delta_update,
1930 V4L2_VP8_LF_HDR_DELTA_UPDATE);
1931 #undef SET_V4L2_SGMNT_HDR_FLAG_IF
1932
1933 #define LF_HDR_TO_V4L2_LF_HDR(a) v4l2_lf_hdr->a = vp8_loopfilter_hdr.a;
1934 LF_HDR_TO_V4L2_LF_HDR(type);
1935 LF_HDR_TO_V4L2_LF_HDR(level);
1936 LF_HDR_TO_V4L2_LF_HDR(sharpness_level);
1937 #undef LF_HDR_TO_V4L2_LF_HDR
1938
1939 ARRAY_MEMCPY_CHECKED(v4l2_lf_hdr->ref_frm_delta_magnitude,
1940 vp8_loopfilter_hdr.ref_frame_delta);
1941 ARRAY_MEMCPY_CHECKED(v4l2_lf_hdr->mb_mode_delta_magnitude,
1942 vp8_loopfilter_hdr.mb_mode_delta);
1943 }
1944
1945 static void FillV4L2QuantizationHeader(
1946 const media::Vp8QuantizationHeader& vp8_quant_hdr,
1947 struct v4l2_vp8_quantization_hdr* v4l2_quant_hdr) {
1948 v4l2_quant_hdr->y_ac_qi = vp8_quant_hdr.y_ac_qi;
1949 v4l2_quant_hdr->y_dc_delta = vp8_quant_hdr.y_dc_delta;
1950 v4l2_quant_hdr->y2_dc_delta = vp8_quant_hdr.y2_dc_delta;
1951 v4l2_quant_hdr->y2_ac_delta = vp8_quant_hdr.y2_ac_delta;
1952 v4l2_quant_hdr->uv_dc_delta = vp8_quant_hdr.uv_dc_delta;
1953 v4l2_quant_hdr->uv_ac_delta = vp8_quant_hdr.uv_ac_delta;
1954 }
1955
1956 static void FillV4L2EntropyHeader(
1957 const media::Vp8EntropyHeader& vp8_entropy_hdr,
1958 struct v4l2_vp8_entropy_hdr* v4l2_entropy_hdr) {
1959 ARRAY_MEMCPY_CHECKED(v4l2_entropy_hdr->coeff_probs,
1960 vp8_entropy_hdr.coeff_probs);
1961 ARRAY_MEMCPY_CHECKED(v4l2_entropy_hdr->y_mode_probs,
1962 vp8_entropy_hdr.y_mode_probs);
1963 ARRAY_MEMCPY_CHECKED(v4l2_entropy_hdr->uv_mode_probs,
1964 vp8_entropy_hdr.uv_mode_probs);
1965 ARRAY_MEMCPY_CHECKED(v4l2_entropy_hdr->mv_probs,
1966 vp8_entropy_hdr.mv_probs);
1967 }
1968
1969 bool V4L2SliceVideoDecodeAccelerator::V4L2VP8Accelerator::SubmitDecode(
1970 const scoped_refptr<VP8Picture>& pic,
1971 const media::Vp8FrameHeader* frame_hdr,
1972 const scoped_refptr<VP8Picture>& last_frame,
1973 const scoped_refptr<VP8Picture>& golden_frame,
1974 const scoped_refptr<VP8Picture>& alt_frame) {
1975 struct v4l2_ctrl_vp8_frame_hdr v4l2_frame_hdr;
1976 memset(&v4l2_frame_hdr, 0, sizeof(v4l2_frame_hdr));
1977
1978 #define FHDR_TO_V4L2_FHDR(a) v4l2_frame_hdr.a = frame_hdr->a
1979 FHDR_TO_V4L2_FHDR(key_frame);
1980 FHDR_TO_V4L2_FHDR(version);
1981 FHDR_TO_V4L2_FHDR(width);
1982 FHDR_TO_V4L2_FHDR(horizontal_scale);
1983 FHDR_TO_V4L2_FHDR(height);
1984 FHDR_TO_V4L2_FHDR(vertical_scale);
1985 FHDR_TO_V4L2_FHDR(sign_bias_golden);
1986 FHDR_TO_V4L2_FHDR(sign_bias_alternate);
1987 FHDR_TO_V4L2_FHDR(prob_skip_false);
1988 FHDR_TO_V4L2_FHDR(prob_intra);
1989 FHDR_TO_V4L2_FHDR(prob_last);
1990 FHDR_TO_V4L2_FHDR(prob_gf);
1991 FHDR_TO_V4L2_FHDR(bool_dec_range);
1992 FHDR_TO_V4L2_FHDR(bool_dec_value);
1993 FHDR_TO_V4L2_FHDR(bool_dec_count);
1994 #undef FHDR_TO_V4L2_FHDR
1995
1996 #define SET_V4L2_FRM_HDR_FLAG_IF(cond, flag) \
1997 v4l2_frame_hdr.flags |= ((frame_hdr->cond) ? (flag) : 0)
1998 SET_V4L2_FRM_HDR_FLAG_IF(is_experimental,
1999 V4L2_VP8_FRAME_HDR_FLAG_EXPERIMENTAL);
2000 SET_V4L2_FRM_HDR_FLAG_IF(show_frame, V4L2_VP8_FRAME_HDR_FLAG_SHOW_FRAME);
2001 SET_V4L2_FRM_HDR_FLAG_IF(mb_no_skip_coeff,
2002 V4L2_VP8_FRAME_HDR_FLAG_MB_NO_SKIP_COEFF);
2003 #undef SET_V4L2_FRM_HDR_FLAG_IF
2004
2005 FillV4L2SegmentationHeader(frame_hdr->segmentation_hdr,
2006 &v4l2_frame_hdr.sgmnt_hdr);
2007
2008 FillV4L2LoopfilterHeader(frame_hdr->loopfilter_hdr, &v4l2_frame_hdr.lf_hdr);
2009
2010 FillV4L2QuantizationHeader(frame_hdr->quantization_hdr,
2011 &v4l2_frame_hdr.quant_hdr);
2012
2013 FillV4L2EntropyHeader(frame_hdr->entropy_hdr, &v4l2_frame_hdr.entropy_hdr);
2014
2015 v4l2_frame_hdr.first_part_size =
2016 base::checked_cast<__u32>(frame_hdr->first_part_size);
2017 v4l2_frame_hdr.first_part_offset =
2018 base::checked_cast<__u32>(frame_hdr->first_part_offset);
2019 v4l2_frame_hdr.macroblock_bit_offset =
2020 base::checked_cast<__u32>(frame_hdr->macroblock_bit_offset);
2021 v4l2_frame_hdr.num_dct_parts = frame_hdr->num_of_dct_partitions;
2022
2023 static_assert(arraysize(v4l2_frame_hdr.dct_part_sizes) ==
2024 arraysize(frame_hdr->dct_partition_sizes),
2025 "DCT partition size arrays must have equal number of elements");
2026 for (size_t i = 0; i < frame_hdr->num_of_dct_partitions &&
2027 i < arraysize(v4l2_frame_hdr.dct_part_sizes); ++i)
2028 v4l2_frame_hdr.dct_part_sizes[i] = frame_hdr->dct_partition_sizes[i];
2029
2030 scoped_refptr<V4L2DecodeSurface> dec_surface =
2031 VP8PictureToV4L2DecodeSurface(pic);
2032 std::vector<scoped_refptr<V4L2DecodeSurface>> ref_surfaces;
2033
2034 if (last_frame) {
2035 scoped_refptr<V4L2DecodeSurface> last_frame_surface =
2036 VP8PictureToV4L2DecodeSurface(last_frame);
2037 v4l2_frame_hdr.last_frame = last_frame_surface->output_record();
2038 ref_surfaces.push_back(last_frame_surface);
2039 } else {
2040 v4l2_frame_hdr.last_frame = VIDEO_MAX_FRAME;
2041 }
2042
2043 if (golden_frame) {
2044 scoped_refptr<V4L2DecodeSurface> golden_frame_surface =
2045 VP8PictureToV4L2DecodeSurface(golden_frame);
2046 v4l2_frame_hdr.golden_frame = golden_frame_surface->output_record();
2047 ref_surfaces.push_back(golden_frame_surface);
2048 } else {
2049 v4l2_frame_hdr.golden_frame = VIDEO_MAX_FRAME;
2050 }
2051
2052 if (alt_frame) {
2053 scoped_refptr<V4L2DecodeSurface> alt_frame_surface =
2054 VP8PictureToV4L2DecodeSurface(alt_frame);
2055 v4l2_frame_hdr.alt_frame = alt_frame_surface->output_record();
2056 ref_surfaces.push_back(alt_frame_surface);
2057 } else {
2058 v4l2_frame_hdr.alt_frame = VIDEO_MAX_FRAME;
2059 }
2060
2061 struct v4l2_ext_control ctrl;
2062 memset(&ctrl, 0, sizeof(ctrl));
2063 ctrl.id = V4L2_CID_MPEG_VIDEO_VP8_FRAME_HDR;
2064 ctrl.size = sizeof(v4l2_frame_hdr);
2065 ctrl.p_vp8_frame_hdr = &v4l2_frame_hdr;
2066
2067 struct v4l2_ext_controls ext_ctrls;
2068 memset(&ext_ctrls, 0, sizeof(ext_ctrls));
2069 ext_ctrls.count = 1;
2070 ext_ctrls.controls = &ctrl;
2071 ext_ctrls.config_store = dec_surface->config_store();
2072
2073 if (!v4l2_dec_->SubmitExtControls(&ext_ctrls))
2074 return false;
2075
2076 dec_surface->SetReferenceSurfaces(ref_surfaces);
2077
2078 if (!v4l2_dec_->SubmitSlice(dec_surface->input_record(), frame_hdr->data,
2079 frame_hdr->frame_size))
2080 return false;
2081
2082 v4l2_dec_->DecodeSurface(dec_surface);
2083 return true;
2084 }
2085
2086 bool V4L2SliceVideoDecodeAccelerator::V4L2VP8Accelerator::OutputPicture(
2087 const scoped_refptr<VP8Picture>& pic) {
2088 scoped_refptr<V4L2DecodeSurface> dec_surface =
2089 VP8PictureToV4L2DecodeSurface(pic);
2090
2091 v4l2_dec_->SurfaceReady(dec_surface);
2092 return true;
2093 }
2094
2095 scoped_refptr<V4L2SliceVideoDecodeAccelerator::V4L2DecodeSurface>
2096 V4L2SliceVideoDecodeAccelerator::V4L2VP8Accelerator::
2097 VP8PictureToV4L2DecodeSurface(const scoped_refptr<VP8Picture>& pic) {
2098 V4L2VP8Picture* v4l2_pic = pic->AsV4L2VP8Picture();
2099 CHECK(v4l2_pic);
2100 return v4l2_pic->dec_surface();
2101 }
2102
2103 void V4L2SliceVideoDecodeAccelerator::DecodeSurface(
2104 const scoped_refptr<V4L2DecodeSurface>& dec_surface) {
2105 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
2106
2107 DVLOGF(3) << "Submitting decode for surface: " << dec_surface->ToString();
2108 Enqueue(dec_surface);
2109 }
2110
2111 void V4L2SliceVideoDecodeAccelerator::SurfaceReady(
2112 const scoped_refptr<V4L2DecodeSurface>& dec_surface) {
2113 DVLOGF(3);
2114 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
2115
2116 decoder_display_queue_.push(dec_surface);
2117 TryOutputSurfaces();
2118 }
2119
2120 void V4L2SliceVideoDecodeAccelerator::TryOutputSurfaces() {
2121 while (!decoder_display_queue_.empty()) {
2122 scoped_refptr<V4L2DecodeSurface> dec_surface =
2123 decoder_display_queue_.front();
2124
2125 if (!dec_surface->decoded())
2126 break;
2127
2128 decoder_display_queue_.pop();
2129 OutputSurface(dec_surface);
2130 }
2131 }
2132
2133 void V4L2SliceVideoDecodeAccelerator::OutputSurface(
2134 const scoped_refptr<V4L2DecodeSurface>& dec_surface) {
2135 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
2136
2137 OutputRecord& output_record =
2138 output_buffer_map_[dec_surface->output_record()];
2139
2140 bool inserted =
2141 surfaces_at_display_.insert(std::make_pair(output_record.picture_id,
2142 dec_surface)).second;
2143 DCHECK(inserted);
2144
2145 DCHECK(!output_record.at_client);
2146 DCHECK(!output_record.at_device);
2147 DCHECK_NE(output_record.egl_image, EGL_NO_IMAGE_KHR);
2148 DCHECK_NE(output_record.picture_id, -1);
2149 output_record.at_client = true;
2150
2151 media::Picture picture(output_record.picture_id, dec_surface->bitstream_id(),
2152 gfx::Rect(frame_buffer_size_));
2153 DVLOGF(3) << dec_surface->ToString()
2154 << " picture_id: " << picture.picture_buffer_id();
2155 pending_picture_ready_.push(PictureRecord(output_record.cleared, picture));
2156 SendPictureReady();
2157 output_record.cleared = true;
2158 }
2159
2160 scoped_refptr<V4L2SliceVideoDecodeAccelerator::V4L2DecodeSurface>
2161 V4L2SliceVideoDecodeAccelerator::CreateSurface() {
2162 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
2163
2164 if (free_input_buffers_.empty() || free_output_buffers_.empty())
2165 return nullptr;
2166
2167 int input = free_input_buffers_.front();
2168 free_input_buffers_.pop_front();
2169 int output = free_output_buffers_.front();
2170 free_output_buffers_.pop_front();
2171
2172 InputRecord& input_record = input_buffer_map_[input];
2173 DCHECK_EQ(input_record.bytes_used, 0u);
2174 DCHECK_EQ(input_record.input_id, -1);
2175 DCHECK(decoder_current_bitstream_buffer_ != nullptr);
2176 input_record.input_id = decoder_current_bitstream_buffer_->input_id;
2177
2178 scoped_refptr<V4L2DecodeSurface> dec_surface = new V4L2DecodeSurface(
2179 decoder_current_bitstream_buffer_->input_id, input, output,
2180 base::Bind(&V4L2SliceVideoDecodeAccelerator::ReuseOutputBuffer,
2181 base::Unretained(this)));
2182
2183 DVLOGF(4) << "Created surface " << input << " -> " << output;
2184 return dec_surface;
2185 }
2186
2187 void V4L2SliceVideoDecodeAccelerator::SendPictureReady() {
2188 DVLOGF(3);
2189 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
2190 bool resetting_or_flushing = (decoder_resetting_ || decoder_flushing_);
2191 while (pending_picture_ready_.size() > 0) {
2192 bool cleared = pending_picture_ready_.front().cleared;
2193 const media::Picture& picture = pending_picture_ready_.front().picture;
2194 if (cleared && picture_clearing_count_ == 0) {
2195 DVLOGF(4) << "Posting picture ready to IO for: "
2196 << picture.picture_buffer_id();
2197 // This picture is cleared. Post it to IO thread to reduce latency. This
2198 // should be the case after all pictures are cleared at the beginning.
2199 io_message_loop_proxy_->PostTask(
2200 FROM_HERE, base::Bind(&Client::PictureReady, io_client_, picture));
2201 pending_picture_ready_.pop();
2202 } else if (!cleared || resetting_or_flushing) {
2203 DVLOGF(3) << ". cleared=" << pending_picture_ready_.front().cleared
2204 << ", decoder_resetting_=" << decoder_resetting_
2205 << ", decoder_flushing_=" << decoder_flushing_
2206 << ", picture_clearing_count_=" << picture_clearing_count_;
2207 DVLOGF(4) << "Posting picture ready to GPU for: "
2208 << picture.picture_buffer_id();
2209 // If the picture is not cleared, post it to the child thread because it
2210 // has to be cleared in the child thread. A picture only needs to be
2211 // cleared once. If the decoder is resetting or flushing, send all
2212 // pictures to ensure PictureReady arrive before reset or flush done.
2213 child_message_loop_proxy_->PostTaskAndReply(
2214 FROM_HERE, base::Bind(&Client::PictureReady, client_, picture),
2215 // Unretained is safe. If Client::PictureReady gets to run, |this| is
2216 // alive. Destroy() will wait the decode thread to finish.
2217 base::Bind(&V4L2SliceVideoDecodeAccelerator::PictureCleared,
2218 base::Unretained(this)));
2219 picture_clearing_count_++;
2220 pending_picture_ready_.pop();
2221 } else {
2222 // This picture is cleared. But some pictures are about to be cleared on
2223 // the child thread. To preserve the order, do not send this until those
2224 // pictures are cleared.
2225 break;
2226 }
2227 }
2228 }
2229
2230 void V4L2SliceVideoDecodeAccelerator::PictureCleared() {
2231 DVLOGF(3) << "clearing count=" << picture_clearing_count_;
2232 DCHECK(decoder_thread_proxy_->BelongsToCurrentThread());
2233 DCHECK_GT(picture_clearing_count_, 0);
2234 picture_clearing_count_--;
2235 SendPictureReady();
2236 }
2237
2238 bool V4L2SliceVideoDecodeAccelerator::CanDecodeOnIOThread() {
2239 return true;
2240 }
2241
2242 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698