]> git.pld-linux.org Git - packages/ffmpeg.git/blob - v4l2-request-hwdec.patch
add hevc support to v4l2 request patch
[packages/ffmpeg.git] / v4l2-request-hwdec.patch
1 From 904af26693095364851bbc6c6557fca9b3437b69 Mon Sep 17 00:00:00 2001
2 From: Jonas Karlman <jonas@kwiboo.se>
3 Date: Mon, 3 Dec 2018 23:48:04 +0100
4 Subject: [PATCH 01/17] avutil: add av_buffer_pool_flush()
5
6 Used by V4L2 request API hwaccel
7
8 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
9 ---
10  libavutil/buffer.c | 13 +++++++++++++
11  libavutil/buffer.h |  5 +++++
12  2 files changed, 18 insertions(+)
13
14 diff --git a/libavutil/buffer.c b/libavutil/buffer.c
15 index 858633e8c73..41555d99825 100644
16 --- a/libavutil/buffer.c
17 +++ b/libavutil/buffer.c
18 @@ -305,6 +305,19 @@ static void buffer_pool_free(AVBufferPool *pool)
19      av_freep(&pool);
20  }
21  
22 +void av_buffer_pool_flush(AVBufferPool *pool)
23 +{
24 +    ff_mutex_lock(&pool->mutex);
25 +    while (pool->pool) {
26 +        BufferPoolEntry *buf = pool->pool;
27 +        pool->pool = buf->next;
28 +
29 +        buf->free(buf->opaque, buf->data);
30 +        av_freep(&buf);
31 +    }
32 +    ff_mutex_unlock(&pool->mutex);
33 +}
34 +
35  void av_buffer_pool_uninit(AVBufferPool **ppool)
36  {
37      AVBufferPool *pool;
38 diff --git a/libavutil/buffer.h b/libavutil/buffer.h
39 index 241a80ed670..f41363faf1d 100644
40 --- a/libavutil/buffer.h
41 +++ b/libavutil/buffer.h
42 @@ -315,6 +315,11 @@ AVBufferPool *av_buffer_pool_init2(size_t size, void *opaque,
43  #endif
44                                     void (*pool_free)(void *opaque));
45  
46 +/**
47 + * Free all available buffers in a buffer pool.
48 + */
49 + void av_buffer_pool_flush(AVBufferPool *pool);
50 +
51  /**
52   * Mark the pool as being available for freeing. It will actually be freed only
53   * once all the allocated buffers associated with the pool are released. Thus it
54
55 From ec84dc22e99f544e4de7c43e7f8ef9ab7ee8e19b Mon Sep 17 00:00:00 2001
56 From: Jonas Karlman <jonas@kwiboo.se>
57 Date: Sat, 15 Dec 2018 22:32:16 +0100
58 Subject: [PATCH 02/17] Add common V4L2 request API code
59
60 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
61 ---
62  configure                 |  12 +
63  libavcodec/Makefile       |   1 +
64  libavcodec/hwconfig.h     |   2 +
65  libavcodec/v4l2_request.c | 984 ++++++++++++++++++++++++++++++++++++++
66  libavcodec/v4l2_request.h |  77 +++
67  5 files changed, 1076 insertions(+)
68  create mode 100644 libavcodec/v4l2_request.c
69  create mode 100644 libavcodec/v4l2_request.h
70
71 diff --git a/configure b/configure
72 index d7a3f507e83..f2e203d1346 100755
73 --- a/configure
74 +++ b/configure
75 @@ -279,6 +279,7 @@ External library support:
76                             if openssl, gnutls or mbedtls is not used [no]
77    --enable-libtwolame      enable MP2 encoding via libtwolame [no]
78    --enable-libuavs3d       enable AVS3 decoding via libuavs3d [no]
79 +  --enable-libudev         enable libudev [no]
80    --enable-libv4l2         enable libv4l2/v4l-utils [no]
81    --enable-libvidstab      enable video stabilization using vid.stab [no]
82    --enable-libvmaf         enable vmaf filter via libvmaf [no]
83 @@ -346,6 +347,7 @@ External library support:
84    --enable-omx-rpi         enable OpenMAX IL code for Raspberry Pi [no]
85    --enable-rkmpp           enable Rockchip Media Process Platform code [no]
86    --disable-v4l2-m2m       disable V4L2 mem2mem code [autodetect]
87 +  --enable-v4l2-request    enable V4L2 request API code [no]
88    --disable-vaapi          disable Video Acceleration API (mainly Unix/Intel) code [autodetect]
89    --disable-vdpau          disable Nvidia Video Decode and Presentation API for Unix code [autodetect]
90    --disable-videotoolbox   disable VideoToolbox code [autodetect]
91 @@ -1814,6 +1816,7 @@ EXTERNAL_LIBRARY_LIST="
92      libtheora
93      libtwolame
94      libuavs3d
95 +    libudev
96      libv4l2
97      libvmaf
98      libvorbis
99 @@ -1868,6 +1871,7 @@ HWACCEL_LIBRARY_LIST="
100      mmal
101      omx
102      opencl
103 +    v4l2_request
104      vulkan
105  "
106  
107 @@ -2919,6 +2923,7 @@ d3d11va_deps="dxva_h ID3D11VideoDecoder ID3D11VideoContext"
108  dxva2_deps="dxva2api_h DXVA2_ConfigPictureDecode ole32 user32"
109  ffnvcodec_deps_any="libdl LoadLibrary"
110  nvdec_deps="ffnvcodec"
111 +v4l2_request_deps="linux_videodev2_h linux_media_h v4l2_timeval_to_ns libdrm libudev"
112  vaapi_x11_deps="xlib"
113  videotoolbox_hwaccel_deps="videotoolbox pthreads"
114  videotoolbox_hwaccel_extralibs="-framework QuartzCore"
115 @@ -6438,6 +6443,7 @@ enabled libtwolame        && require libtwolame twolame.h twolame_init -ltwolame
116                               { check_lib libtwolame twolame.h twolame_encode_buffer_float32_interleaved -ltwolame ||
117                                 die "ERROR: libtwolame must be installed and version must be >= 0.3.10"; }
118  enabled libuavs3d         && require_pkg_config libuavs3d "uavs3d >= 1.1.41" uavs3d.h uavs3d_decode
119 +enabled libudev           && require_pkg_config libudev libudev libudev.h udev_new
120  enabled libv4l2           && require_pkg_config libv4l2 libv4l2 libv4l2.h v4l2_ioctl
121  enabled libvidstab        && require_pkg_config libvidstab "vidstab >= 0.98" vid.stab/libvidstab.h vsMotionDetectInit
122  enabled libvmaf           && require_pkg_config libvmaf "libvmaf >= 1.5.2" libvmaf.h compute_vmaf
123 @@ -6536,6 +6542,10 @@ enabled rkmpp             && { require_pkg_config rkmpp rockchip_mpp  rockchip/r
124                                 { enabled libdrm ||
125                                   die "ERROR: rkmpp requires --enable-libdrm"; }
126                               }
127 +enabled v4l2_request      && { enabled libdrm ||
128 +                               die "ERROR: v4l2-request requires --enable-libdrm"; } &&
129 +                             { enabled libudev ||
130 +                               die "ERROR: v4l2-request requires --enable-libudev"; }
131  enabled vapoursynth       && require_pkg_config vapoursynth "vapoursynth-script >= 42" VSScript.h vsscript_init
132  
133  
134 @@ -6617,6 +6627,8 @@ if enabled v4l2_m2m; then
135      check_cc vp9_v4l2_m2m linux/videodev2.h "int i = V4L2_PIX_FMT_VP9;"
136  fi
137  
138 +check_func_headers "linux/media.h linux/videodev2.h" v4l2_timeval_to_ns
139 +
140  check_headers sys/videoio.h
141  test_code cc sys/videoio.h "struct v4l2_frmsizeenum vfse; vfse.discrete.width = 0;" && enable_sanitized struct_v4l2_frmivalenum_discrete
142  
143 diff --git a/libavcodec/Makefile b/libavcodec/Makefile
144 index 33a280cf695..90dfffcb200 100644
145 --- a/libavcodec/Makefile
146 +++ b/libavcodec/Makefile
147 @@ -155,6 +155,7 @@ OBJS-$(CONFIG_VP3DSP)                  += vp3dsp.o
148  OBJS-$(CONFIG_VP56DSP)                 += vp56dsp.o
149  OBJS-$(CONFIG_VP8DSP)                  += vp8dsp.o
150  OBJS-$(CONFIG_V4L2_M2M)                += v4l2_m2m.o v4l2_context.o v4l2_buffers.o v4l2_fmt.o
151 +OBJS-$(CONFIG_V4L2_REQUEST)            += v4l2_request.o
152  OBJS-$(CONFIG_WMA_FREQS)               += wma_freqs.o
153  OBJS-$(CONFIG_WMV2DSP)                 += wmv2dsp.o
154  
155 diff --git a/libavcodec/hwconfig.h b/libavcodec/hwconfig.h
156 index f421dc909f4..ee78d8ab8e8 100644
157 --- a/libavcodec/hwconfig.h
158 +++ b/libavcodec/hwconfig.h
159 @@ -80,6 +80,8 @@ typedef struct AVCodecHWConfigInternal {
160      HW_CONFIG_HWACCEL(0, 0, 1, D3D11VA_VLD,  NONE,         ff_ ## codec ## _d3d11va_hwaccel)
161  #define HWACCEL_XVMC(codec) \
162      HW_CONFIG_HWACCEL(0, 0, 1, XVMC,         NONE,         ff_ ## codec ## _xvmc_hwaccel)
163 +#define HWACCEL_V4L2REQUEST(codec) \
164 +    HW_CONFIG_HWACCEL(1, 0, 0, DRM_PRIME,    DRM,          ff_ ## codec ## _v4l2request_hwaccel)
165  
166  #define HW_CONFIG_ENCODER(device, frames, ad_hoc, format, device_type_) \
167      &(const AVCodecHWConfigInternal) { \
168 diff --git a/libavcodec/v4l2_request.c b/libavcodec/v4l2_request.c
169 new file mode 100644
170 index 00000000000..5234b5049b0
171 --- /dev/null
172 +++ b/libavcodec/v4l2_request.c
173 @@ -0,0 +1,984 @@
174 +/*
175 + * This file is part of FFmpeg.
176 + *
177 + * FFmpeg is free software; you can redistribute it and/or
178 + * modify it under the terms of the GNU Lesser General Public
179 + * License as published by the Free Software Foundation; either
180 + * version 2.1 of the License, or (at your option) any later version.
181 + *
182 + * FFmpeg is distributed in the hope that it will be useful,
183 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
184 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
185 + * Lesser General Public License for more details.
186 + *
187 + * You should have received a copy of the GNU Lesser General Public
188 + * License along with FFmpeg; if not, write to the Free Software
189 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
190 + */
191 +
192 +#include <drm_fourcc.h>
193 +#include <linux/media.h>
194 +#include <sys/mman.h>
195 +#include <sys/types.h>
196 +#include <sys/stat.h>
197 +#include <fcntl.h>
198 +
199 +#include <sys/sysmacros.h>
200 +#include <libudev.h>
201 +
202 +#include "decode.h"
203 +#include "internal.h"
204 +#include "v4l2_request.h"
205 +
206 +uint64_t ff_v4l2_request_get_capture_timestamp(AVFrame *frame)
207 +{
208 +    V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)frame->data[0];
209 +    return req ? v4l2_timeval_to_ns(&req->capture.buffer.timestamp) : 0;
210 +}
211 +
212 +int ff_v4l2_request_reset_frame(AVCodecContext *avctx, AVFrame *frame)
213 +{
214 +    V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)frame->data[0];
215 +    memset(&req->drm, 0, sizeof(AVDRMFrameDescriptor));
216 +    req->output.used = 0;
217 +    return 0;
218 +}
219 +
220 +int ff_v4l2_request_append_output_buffer(AVCodecContext *avctx, AVFrame *frame, const uint8_t *data, uint32_t size)
221 +{
222 +    V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)frame->data[0];
223 +    if (req->output.used + size + (AV_INPUT_BUFFER_PADDING_SIZE * 4) <= req->output.size) {
224 +        memcpy(req->output.addr + req->output.used, data, size);
225 +        req->output.used += size;
226 +    } else {
227 +        av_log(avctx, AV_LOG_ERROR, "%s: output.used=%u output.size=%u size=%u\n", __func__, req->output.used, req->output.size, size);
228 +    }
229 +    return 0;
230 +}
231 +
232 +static int v4l2_request_controls(V4L2RequestContext *ctx, int request_fd, unsigned long type, struct v4l2_ext_control *control, int count)
233 +{
234 +    struct v4l2_ext_controls controls = {
235 +        .controls = control,
236 +        .count = count,
237 +        .request_fd = request_fd,
238 +        .which = (request_fd >= 0) ? V4L2_CTRL_WHICH_REQUEST_VAL : 0,
239 +    };
240 +
241 +    if (!control || !count)
242 +        return 0;
243 +
244 +    return ioctl(ctx->video_fd, type, &controls);
245 +}
246 +
247 +static int v4l2_request_set_controls(V4L2RequestContext *ctx, int request_fd, struct v4l2_ext_control *control, int count)
248 +{
249 +    return v4l2_request_controls(ctx, request_fd, VIDIOC_S_EXT_CTRLS, control, count);
250 +}
251 +
252 +int ff_v4l2_request_set_controls(AVCodecContext *avctx, struct v4l2_ext_control *control, int count)
253 +{
254 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
255 +    int ret;
256 +
257 +    ret = v4l2_request_controls(ctx, -1, VIDIOC_S_EXT_CTRLS, control, count);
258 +    if (ret < 0) {
259 +        av_log(avctx, AV_LOG_ERROR, "%s: set controls failed, %s (%d)\n", __func__, strerror(errno), errno);
260 +        return AVERROR(EINVAL);
261 +    }
262 +
263 +    return ret;
264 +}
265 +
266 +int ff_v4l2_request_get_controls(AVCodecContext *avctx, struct v4l2_ext_control *control, int count)
267 +{
268 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
269 +    int ret;
270 +
271 +    ret = v4l2_request_controls(ctx, -1, VIDIOC_G_EXT_CTRLS, control, count);
272 +    if (ret < 0) {
273 +        av_log(avctx, AV_LOG_ERROR, "%s: get controls failed, %s (%d)\n", __func__, strerror(errno), errno);
274 +        return AVERROR(EINVAL);
275 +    }
276 +
277 +    return ret;
278 +}
279 +
280 +int ff_v4l2_request_query_control(AVCodecContext *avctx, struct v4l2_query_ext_ctrl *control)
281 +{
282 +    int ret;
283 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
284 +
285 +    ret = ioctl(ctx->video_fd, VIDIOC_QUERY_EXT_CTRL, control);
286 +    if (ret < 0) {
287 +        av_log(avctx, AV_LOG_ERROR, "%s: query control failed, %s (%d)\n", __func__, strerror(errno), errno);
288 +        return AVERROR(EINVAL);
289 +    }
290 +
291 +    return 0;
292 +}
293 +
294 +int ff_v4l2_request_query_control_default_value(AVCodecContext *avctx, uint32_t id)
295 +{
296 +    int ret;
297 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
298 +    struct v4l2_queryctrl control = {
299 +        .id = id,
300 +    };
301 +
302 +    ret = ioctl(ctx->video_fd, VIDIOC_QUERYCTRL, &control);
303 +    if (ret < 0) {
304 +        av_log(avctx, AV_LOG_ERROR, "%s: query control failed, %s (%d)\n", __func__, strerror(errno), errno);
305 +        return AVERROR(EINVAL);
306 +    }
307 +
308 +    return control.default_value;
309 +}
310 +
311 +static int v4l2_request_queue_buffer(V4L2RequestContext *ctx, int request_fd, V4L2RequestBuffer *buf, uint32_t flags)
312 +{
313 +    struct v4l2_plane planes[1] = {};
314 +    struct v4l2_buffer buffer = {
315 +        .type = buf->buffer.type,
316 +        .memory = buf->buffer.memory,
317 +        .index = buf->index,
318 +        .timestamp.tv_usec = ctx->timestamp,
319 +        .bytesused = buf->used,
320 +        .request_fd = request_fd,
321 +        .flags = ((request_fd >= 0) ? V4L2_BUF_FLAG_REQUEST_FD : 0) | flags,
322 +    };
323 +
324 +    buf->buffer.timestamp = buffer.timestamp;
325 +
326 +    if (V4L2_TYPE_IS_MULTIPLANAR(buf->buffer.type)) {
327 +        planes[0].bytesused = buf->used;
328 +        buffer.bytesused = 0;
329 +        buffer.length = 1;
330 +        buffer.m.planes = planes;
331 +    }
332 +
333 +    return ioctl(ctx->video_fd, VIDIOC_QBUF, &buffer);
334 +}
335 +
336 +static int v4l2_request_dequeue_buffer(V4L2RequestContext *ctx, V4L2RequestBuffer *buf)
337 +{
338 +    int ret;
339 +    struct v4l2_plane planes[1] = {};
340 +    struct v4l2_buffer buffer = {
341 +        .type = buf->buffer.type,
342 +        .memory = buf->buffer.memory,
343 +        .index = buf->index,
344 +    };
345 +
346 +    if (V4L2_TYPE_IS_MULTIPLANAR(buf->buffer.type)) {
347 +        buffer.length = 1;
348 +        buffer.m.planes = planes;
349 +    }
350 +
351 +    ret = ioctl(ctx->video_fd, VIDIOC_DQBUF, &buffer);
352 +    if (ret < 0)
353 +        return ret;
354 +
355 +    buf->buffer.timestamp = buffer.timestamp;
356 +    return 0;
357 +}
358 +
359 +const uint32_t v4l2_request_capture_pixelformats[] = {
360 +    V4L2_PIX_FMT_NV12,
361 +#ifdef DRM_FORMAT_MOD_ALLWINNER_TILED
362 +    V4L2_PIX_FMT_SUNXI_TILED_NV12,
363 +#endif
364 +};
365 +
366 +static int v4l2_request_set_drm_descriptor(V4L2RequestDescriptor *req, struct v4l2_format *format)
367 +{
368 +    AVDRMFrameDescriptor *desc = &req->drm;
369 +    AVDRMLayerDescriptor *layer = &desc->layers[0];
370 +    uint32_t pixelformat = V4L2_TYPE_IS_MULTIPLANAR(format->type) ? format->fmt.pix_mp.pixelformat : format->fmt.pix.pixelformat;
371 +
372 +    switch (pixelformat) {
373 +    case V4L2_PIX_FMT_NV12:
374 +        layer->format = DRM_FORMAT_NV12;
375 +        desc->objects[0].format_modifier = DRM_FORMAT_MOD_LINEAR;
376 +        break;
377 +#ifdef DRM_FORMAT_MOD_ALLWINNER_TILED
378 +    case V4L2_PIX_FMT_SUNXI_TILED_NV12:
379 +        layer->format = DRM_FORMAT_NV12;
380 +        desc->objects[0].format_modifier = DRM_FORMAT_MOD_ALLWINNER_TILED;
381 +        break;
382 +#endif
383 +    default:
384 +        return -1;
385 +    }
386 +
387 +    desc->nb_objects = 1;
388 +    desc->objects[0].fd = req->capture.fd;
389 +    desc->objects[0].size = req->capture.size;
390 +
391 +    desc->nb_layers = 1;
392 +    layer->nb_planes = 2;
393 +
394 +    layer->planes[0].object_index = 0;
395 +    layer->planes[0].offset = 0;
396 +    layer->planes[0].pitch = V4L2_TYPE_IS_MULTIPLANAR(format->type) ? format->fmt.pix_mp.plane_fmt[0].bytesperline : format->fmt.pix.bytesperline;
397 +
398 +    layer->planes[1].object_index = 0;
399 +    layer->planes[1].offset = layer->planes[0].pitch * (V4L2_TYPE_IS_MULTIPLANAR(format->type) ? format->fmt.pix_mp.height : format->fmt.pix.height);
400 +    layer->planes[1].pitch = layer->planes[0].pitch;
401 +
402 +    return 0;
403 +}
404 +
405 +static int v4l2_request_queue_decode(AVCodecContext *avctx, AVFrame *frame, struct v4l2_ext_control *control, int count, int first_slice, int last_slice)
406 +{
407 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
408 +    V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)frame->data[0];
409 +    struct timeval tv = { 2, 0 };
410 +    fd_set except_fds;
411 +    int ret;
412 +
413 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p used=%u controls=%d index=%d fd=%d request_fd=%d first_slice=%d last_slice=%d\n", __func__, avctx, req->output.used, count, req->capture.index, req->capture.fd, req->request_fd, first_slice, last_slice);
414 +
415 +    if (first_slice)
416 +        ctx->timestamp++;
417 +
418 +    ret = v4l2_request_set_controls(ctx, req->request_fd, control, count);
419 +    if (ret < 0) {
420 +        av_log(avctx, AV_LOG_ERROR, "%s: set controls failed for request %d, %s (%d)\n", __func__, req->request_fd, strerror(errno), errno);
421 +        return -1;
422 +    }
423 +
424 +    memset(req->output.addr + req->output.used, 0, AV_INPUT_BUFFER_PADDING_SIZE * 4);
425 +
426 +    ret = v4l2_request_queue_buffer(ctx, req->request_fd, &req->output, last_slice ? 0 : V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF);
427 +    if (ret < 0) {
428 +        av_log(avctx, AV_LOG_ERROR, "%s: queue output buffer %d failed for request %d, %s (%d)\n", __func__, req->output.index, req->request_fd, strerror(errno), errno);
429 +        return -1;
430 +    }
431 +
432 +    if (first_slice) {
433 +        ret = v4l2_request_queue_buffer(ctx, -1, &req->capture, 0);
434 +        if (ret < 0) {
435 +            av_log(avctx, AV_LOG_ERROR, "%s: queue capture buffer %d failed for request %d, %s (%d)\n", __func__, req->capture.index, req->request_fd, strerror(errno), errno);
436 +            return -1;
437 +        }
438 +    }
439 +
440 +    // NOTE: do we need to dequeue when request fails/timeout?
441 +
442 +    // 4. queue request and wait
443 +    ret = ioctl(req->request_fd, MEDIA_REQUEST_IOC_QUEUE, NULL);
444 +    if (ret < 0) {
445 +        av_log(avctx, AV_LOG_ERROR, "%s: queue request %d failed, %s (%d)\n", __func__, req->request_fd, strerror(errno), errno);
446 +        goto fail;
447 +    }
448 +
449 +    FD_ZERO(&except_fds);
450 +    FD_SET(req->request_fd, &except_fds);
451 +
452 +    ret = select(req->request_fd + 1, NULL, NULL, &except_fds, &tv);
453 +    if (ret == 0) {
454 +        av_log(avctx, AV_LOG_ERROR, "%s: request %d timeout\n", __func__, req->request_fd);
455 +        goto fail;
456 +    } else if (ret < 0) {
457 +        av_log(avctx, AV_LOG_ERROR, "%s: select request %d failed, %s (%d)\n", __func__, req->request_fd, strerror(errno), errno);
458 +        goto fail;
459 +    }
460 +
461 +    ret = v4l2_request_dequeue_buffer(ctx, &req->output);
462 +    if (ret < 0) {
463 +        av_log(avctx, AV_LOG_ERROR, "%s: dequeue output buffer %d failed for request %d, %s (%d)\n", __func__, req->output.index, req->request_fd, strerror(errno), errno);
464 +        return -1;
465 +    }
466 +
467 +    if (last_slice) {
468 +        ret = v4l2_request_dequeue_buffer(ctx, &req->capture);
469 +        if (ret < 0) {
470 +            av_log(avctx, AV_LOG_ERROR, "%s: dequeue capture buffer %d failed for request %d, %s (%d)\n", __func__, req->capture.index, req->request_fd, strerror(errno), errno);
471 +            return -1;
472 +        }
473 +    }
474 +
475 +    // TODO: check errors
476 +    // buffer.flags & V4L2_BUF_FLAG_ERROR
477 +
478 +    ret = ioctl(req->request_fd, MEDIA_REQUEST_IOC_REINIT, NULL);
479 +    if (ret < 0) {
480 +        av_log(avctx, AV_LOG_ERROR, "%s: reinit request %d failed, %s (%d)\n", __func__, req->request_fd, strerror(errno), errno);
481 +        return -1;
482 +    }
483 +
484 +    if (last_slice)
485 +        return v4l2_request_set_drm_descriptor(req, &ctx->format);
486 +
487 +    return 0;
488 +
489 +fail:
490 +    ret = v4l2_request_dequeue_buffer(ctx, &req->output);
491 +    if (ret < 0)
492 +        av_log(avctx, AV_LOG_ERROR, "%s: dequeue output buffer %d failed for request %d, %s (%d)\n", __func__, req->output.index, req->request_fd, strerror(errno), errno);
493 +
494 +    ret = v4l2_request_dequeue_buffer(ctx, &req->capture);
495 +    if (ret < 0)
496 +        av_log(avctx, AV_LOG_ERROR, "%s: dequeue capture buffer %d failed for request %d, %s (%d)\n", __func__, req->capture.index, req->request_fd, strerror(errno), errno);
497 +
498 +    ret = ioctl(req->request_fd, MEDIA_REQUEST_IOC_REINIT, NULL);
499 +    if (ret < 0)
500 +        av_log(avctx, AV_LOG_ERROR, "%s: reinit request %d failed, %s (%d)\n", __func__, req->request_fd, strerror(errno), errno);
501 +
502 +    return -1;
503 +}
504 +
505 +int ff_v4l2_request_decode_slice(AVCodecContext *avctx, AVFrame *frame, struct v4l2_ext_control *control, int count, int first_slice, int last_slice)
506 +{
507 +    V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)frame->data[0];
508 +
509 +    // fall back to queue each slice as a full frame
510 +    if ((req->output.capabilities & V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF) != V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF)
511 +        return v4l2_request_queue_decode(avctx, frame, control, count, 1, 1);
512 +
513 +    return v4l2_request_queue_decode(avctx, frame, control, count, first_slice, last_slice);
514 +}
515 +
516 +int ff_v4l2_request_decode_frame(AVCodecContext *avctx, AVFrame *frame, struct v4l2_ext_control *control, int count)
517 +{
518 +    return v4l2_request_queue_decode(avctx, frame, control, count, 1, 1);
519 +}
520 +
521 +static int v4l2_request_try_format(AVCodecContext *avctx, enum v4l2_buf_type type, uint32_t pixelformat)
522 +{
523 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
524 +    struct v4l2_fmtdesc fmtdesc = {
525 +        .index = 0,
526 +        .type = type,
527 +    };
528 +
529 +    if (V4L2_TYPE_IS_OUTPUT(type)) {
530 +        struct v4l2_create_buffers buffers = {
531 +            .count = 0,
532 +            .memory = V4L2_MEMORY_MMAP,
533 +            .format.type = type,
534 +        };
535 +
536 +        if (ioctl(ctx->video_fd, VIDIOC_CREATE_BUFS, &buffers) < 0) {
537 +            av_log(avctx, AV_LOG_ERROR, "%s: create buffers failed for type %u, %s (%d)\n", __func__, type, strerror(errno), errno);
538 +            return -1;
539 +        }
540 +
541 +        if ((buffers.capabilities & V4L2_BUF_CAP_SUPPORTS_REQUESTS) != V4L2_BUF_CAP_SUPPORTS_REQUESTS) {
542 +            av_log(avctx, AV_LOG_INFO, "%s: output buffer type do not support requests, capabilities %u\n", __func__, buffers.capabilities);
543 +            return -1;
544 +        }
545 +    }
546 +
547 +    while (ioctl(ctx->video_fd, VIDIOC_ENUM_FMT, &fmtdesc) >= 0) {
548 +        if (fmtdesc.pixelformat == pixelformat)
549 +            return 0;
550 +
551 +        fmtdesc.index++;
552 +    }
553 +
554 +    av_log(avctx, AV_LOG_INFO, "%s: pixelformat %u not supported for type %u\n", __func__, pixelformat, type);
555 +    return -1;
556 +}
557 +
558 +static int v4l2_request_set_format(AVCodecContext *avctx, enum v4l2_buf_type type, uint32_t pixelformat, uint32_t buffersize)
559 +{
560 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
561 +    struct v4l2_format format = {
562 +        .type = type,
563 +    };
564 +
565 +    if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
566 +        format.fmt.pix_mp.width = avctx->coded_width;
567 +        format.fmt.pix_mp.height = avctx->coded_height;
568 +        format.fmt.pix_mp.pixelformat = pixelformat;
569 +        format.fmt.pix_mp.plane_fmt[0].sizeimage = buffersize;
570 +        format.fmt.pix_mp.num_planes = 1;
571 +    } else {
572 +        format.fmt.pix.width = avctx->coded_width;
573 +        format.fmt.pix.height = avctx->coded_height;
574 +        format.fmt.pix.pixelformat = pixelformat;
575 +        format.fmt.pix.sizeimage = buffersize;
576 +    }
577 +
578 +    return ioctl(ctx->video_fd, VIDIOC_S_FMT, &format);
579 +}
580 +
581 +static int v4l2_request_select_capture_format(AVCodecContext *avctx)
582 +{
583 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
584 +    enum v4l2_buf_type type = ctx->format.type;
585 +
586 +#if 0
587 +    struct v4l2_format format = {
588 +        .type = type,
589 +    };
590 +    struct v4l2_fmtdesc fmtdesc = {
591 +        .index = 0,
592 +        .type = type,
593 +    };
594 +    uint32_t pixelformat;
595 +    int i;
596 +
597 +    if (ioctl(ctx->video_fd, VIDIOC_G_FMT, &format) < 0) {
598 +        av_log(avctx, AV_LOG_ERROR, "%s: get capture format failed, %s (%d)\n", __func__, strerror(errno), errno);
599 +        return -1;
600 +    }
601 +
602 +    pixelformat = V4L2_TYPE_IS_MULTIPLANAR(type) ? format.fmt.pix_mp.pixelformat : format.fmt.pix.pixelformat;
603 +
604 +    for (i = 0; i < FF_ARRAY_ELEMS(v4l2_request_capture_pixelformats); i++) {
605 +        if (pixelformat == v4l2_request_capture_pixelformats[i])
606 +            return v4l2_request_set_format(avctx, type, pixelformat, 0);
607 +    }
608 +
609 +    while (ioctl(ctx->video_fd, VIDIOC_ENUM_FMT, &fmtdesc) >= 0) {
610 +        for (i = 0; i < FF_ARRAY_ELEMS(v4l2_request_capture_pixelformats); i++) {
611 +            if (fmtdesc.pixelformat == v4l2_request_capture_pixelformats[i])
612 +                return v4l2_request_set_format(avctx, type, fmtdesc.pixelformat, 0);
613 +        }
614 +
615 +        fmtdesc.index++;
616 +    }
617 +#else
618 +    for (int i = 0; i < FF_ARRAY_ELEMS(v4l2_request_capture_pixelformats); i++) {
619 +        uint32_t pixelformat = v4l2_request_capture_pixelformats[i];
620 +        if (!v4l2_request_try_format(avctx, type, pixelformat))
621 +            return v4l2_request_set_format(avctx, type, pixelformat, 0);
622 +    }
623 +#endif
624 +
625 +    return -1;
626 +}
627 +
628 +static int v4l2_request_probe_video_device(struct udev_device *device, AVCodecContext *avctx, uint32_t pixelformat, uint32_t buffersize, struct v4l2_ext_control *control, int count)
629 +{
630 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
631 +    int ret = AVERROR(EINVAL);
632 +    struct v4l2_capability capability = {0};
633 +    unsigned int capabilities = 0;
634 +
635 +    const char *path = udev_device_get_devnode(device);
636 +    if (!path) {
637 +        av_log(avctx, AV_LOG_ERROR, "%s: get video device devnode failed\n", __func__);
638 +        ret = AVERROR(EINVAL);
639 +        goto fail;
640 +    }
641 +
642 +    ctx->video_fd = open(path, O_RDWR | O_NONBLOCK, 0);
643 +    if (ctx->video_fd < 0) {
644 +        av_log(avctx, AV_LOG_ERROR, "%s: opening %s failed, %s (%d)\n", __func__, path, strerror(errno), errno);
645 +        ret = AVERROR(EINVAL);
646 +        goto fail;
647 +    }
648 +
649 +    ret = ioctl(ctx->video_fd, VIDIOC_QUERYCAP, &capability);
650 +    if (ret < 0) {
651 +        av_log(avctx, AV_LOG_ERROR, "%s: get video capability failed, %s (%d)\n", __func__, strerror(errno), errno);
652 +        ret = AVERROR(EINVAL);
653 +        goto fail;
654 +    }
655 +
656 +    if (capability.capabilities & V4L2_CAP_DEVICE_CAPS)
657 +        capabilities = capability.device_caps;
658 +    else
659 +        capabilities = capability.capabilities;
660 +
661 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p ctx=%p path=%s capabilities=%u\n", __func__, avctx, ctx, path, capabilities);
662 +
663 +    if ((capabilities & V4L2_CAP_STREAMING) != V4L2_CAP_STREAMING) {
664 +        av_log(avctx, AV_LOG_ERROR, "%s: missing required streaming capability\n", __func__);
665 +        ret = AVERROR(EINVAL);
666 +        goto fail;
667 +    }
668 +
669 +    if ((capabilities & V4L2_CAP_VIDEO_M2M_MPLANE) == V4L2_CAP_VIDEO_M2M_MPLANE) {
670 +        ctx->output_type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
671 +        ctx->format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
672 +    } else if ((capabilities & V4L2_CAP_VIDEO_M2M) == V4L2_CAP_VIDEO_M2M) {
673 +        ctx->output_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
674 +        ctx->format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
675 +    } else {
676 +        av_log(avctx, AV_LOG_ERROR, "%s: missing required mem2mem capability\n", __func__);
677 +        ret = AVERROR(EINVAL);
678 +        goto fail;
679 +    }
680 +
681 +    ret = v4l2_request_try_format(avctx, ctx->output_type, pixelformat);
682 +    if (ret < 0) {
683 +        av_log(avctx, AV_LOG_WARNING, "%s: try output format failed\n", __func__);
684 +        ret = AVERROR(EINVAL);
685 +        goto fail;
686 +    }
687 +
688 +    ret = v4l2_request_set_format(avctx, ctx->output_type, pixelformat, buffersize);
689 +    if (ret < 0) {
690 +        av_log(avctx, AV_LOG_ERROR, "%s: set output format failed, %s (%d)\n", __func__, strerror(errno), errno);
691 +        ret = AVERROR(EINVAL);
692 +        goto fail;
693 +    }
694 +
695 +    ret = v4l2_request_set_controls(ctx, -1, control, count);
696 +    if (ret < 0) {
697 +        av_log(avctx, AV_LOG_ERROR, "%s: set controls failed, %s (%d)\n", __func__, strerror(errno), errno);
698 +        ret = AVERROR(EINVAL);
699 +        goto fail;
700 +    }
701 +
702 +    ret = v4l2_request_select_capture_format(avctx);
703 +    if (ret < 0) {
704 +        av_log(avctx, AV_LOG_WARNING, "%s: select capture format failed\n", __func__);
705 +        ret = AVERROR(EINVAL);
706 +        goto fail;
707 +    }
708 +
709 +    return 0;
710 +
711 +fail:
712 +    if (ctx->video_fd >= 0) {
713 +        close(ctx->video_fd);
714 +        ctx->video_fd = -1;
715 +    }
716 +    return ret;
717 +}
718 +
719 +static int v4l2_request_init_context(AVCodecContext *avctx)
720 +{
721 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
722 +    int ret;
723 +
724 +    ret = ioctl(ctx->video_fd, VIDIOC_G_FMT, &ctx->format);
725 +    if (ret < 0) {
726 +        av_log(avctx, AV_LOG_ERROR, "%s: get capture format failed, %s (%d)\n", __func__, strerror(errno), errno);
727 +        ret = AVERROR(EINVAL);
728 +        goto fail;
729 +    }
730 +
731 +    if (V4L2_TYPE_IS_MULTIPLANAR(ctx->format.type)) {
732 +        av_log(avctx, AV_LOG_DEBUG, "%s: pixelformat=%d width=%u height=%u bytesperline=%u sizeimage=%u num_planes=%u\n", __func__, ctx->format.fmt.pix_mp.pixelformat, ctx->format.fmt.pix_mp.width, ctx->format.fmt.pix_mp.height, ctx->format.fmt.pix_mp.plane_fmt[0].bytesperline, ctx->format.fmt.pix_mp.plane_fmt[0].sizeimage, ctx->format.fmt.pix_mp.num_planes);
733 +    } else {
734 +        av_log(avctx, AV_LOG_DEBUG, "%s: pixelformat=%d width=%u height=%u bytesperline=%u sizeimage=%u\n", __func__, ctx->format.fmt.pix.pixelformat, ctx->format.fmt.pix.width, ctx->format.fmt.pix.height, ctx->format.fmt.pix.bytesperline, ctx->format.fmt.pix.sizeimage);
735 +    }
736 +
737 +    ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_DRM);
738 +    if (ret < 0)
739 +        goto fail;
740 +
741 +    ret = ioctl(ctx->video_fd, VIDIOC_STREAMON, &ctx->output_type);
742 +    if (ret < 0) {
743 +        av_log(avctx, AV_LOG_ERROR, "%s: output stream on failed, %s (%d)\n", __func__, strerror(errno), errno);
744 +        ret = AVERROR(EINVAL);
745 +        goto fail;
746 +    }
747 +
748 +    ret = ioctl(ctx->video_fd, VIDIOC_STREAMON, &ctx->format.type);
749 +    if (ret < 0) {
750 +        av_log(avctx, AV_LOG_ERROR, "%s: capture stream on failed, %s (%d)\n", __func__, strerror(errno), errno);
751 +        ret = AVERROR(EINVAL);
752 +        goto fail;
753 +    }
754 +
755 +    return 0;
756 +
757 +fail:
758 +    ff_v4l2_request_uninit(avctx);
759 +    return ret;
760 +}
761 +
762 +static int v4l2_request_probe_media_device(struct udev_device *device, AVCodecContext *avctx, uint32_t pixelformat, uint32_t buffersize, struct v4l2_ext_control *control, int count)
763 +{
764 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
765 +    int ret;
766 +    struct media_device_info device_info = {0};
767 +    struct media_v2_topology topology = {0};
768 +    struct media_v2_interface *interfaces = NULL;
769 +    struct udev *udev = udev_device_get_udev(device);
770 +    struct udev_device *video_device;
771 +    dev_t devnum;
772 +
773 +    const char *path = udev_device_get_devnode(device);
774 +    if (!path) {
775 +        av_log(avctx, AV_LOG_ERROR, "%s: get media device devnode failed\n", __func__);
776 +        ret = AVERROR(EINVAL);
777 +        goto fail;
778 +    }
779 +
780 +    ctx->media_fd = open(path, O_RDWR, 0);
781 +    if (ctx->media_fd < 0) {
782 +        av_log(avctx, AV_LOG_ERROR, "%s: opening %s failed, %s (%d)\n", __func__, path, strerror(errno), errno);
783 +        ret = AVERROR(EINVAL);
784 +        goto fail;
785 +    }
786 +
787 +    ret = ioctl(ctx->media_fd, MEDIA_IOC_DEVICE_INFO, &device_info);
788 +    if (ret < 0) {
789 +        av_log(avctx, AV_LOG_ERROR, "%s: get media device info failed, %s (%d)\n", __func__, strerror(errno), errno);
790 +        ret = AVERROR(EINVAL);
791 +        goto fail;
792 +    }
793 +
794 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p ctx=%p path=%s driver=%s\n", __func__, avctx, ctx, path, device_info.driver);
795 +
796 +    ret = ioctl(ctx->media_fd, MEDIA_IOC_G_TOPOLOGY, &topology);
797 +    if (ret < 0) {
798 +        av_log(avctx, AV_LOG_ERROR, "%s: get media topology failed, %s (%d)\n", __func__, strerror(errno), errno);
799 +        ret = AVERROR(EINVAL);
800 +        goto fail;
801 +    }
802 +
803 +    if (topology.num_interfaces <= 0) {
804 +        av_log(avctx, AV_LOG_ERROR, "%s: media device has no interfaces\n", __func__);
805 +        ret = AVERROR(EINVAL);
806 +        goto fail;
807 +    }
808 +
809 +    interfaces = av_mallocz(topology.num_interfaces * sizeof(struct media_v2_interface));
810 +    if (!interfaces) {
811 +        av_log(avctx, AV_LOG_ERROR, "%s: allocating media interface struct failed\n", __func__);
812 +        ret = AVERROR(ENOMEM);
813 +        goto fail;
814 +    }
815 +
816 +    topology.ptr_interfaces = (__u64)(uintptr_t)interfaces;
817 +    ret = ioctl(ctx->media_fd, MEDIA_IOC_G_TOPOLOGY, &topology);
818 +    if (ret < 0) {
819 +        av_log(avctx, AV_LOG_ERROR, "%s: get media topology failed, %s (%d)\n", __func__, strerror(errno), errno);
820 +        ret = AVERROR(EINVAL);
821 +        goto fail;
822 +    }
823 +
824 +    ret = AVERROR(EINVAL);
825 +    for (int i = 0; i < topology.num_interfaces; i++) {
826 +        if (interfaces[i].intf_type != MEDIA_INTF_T_V4L_VIDEO)
827 +            continue;
828 +
829 +        devnum = makedev(interfaces[i].devnode.major, interfaces[i].devnode.minor);
830 +        video_device = udev_device_new_from_devnum(udev, 'c', devnum);
831 +        if (!video_device) {
832 +            av_log(avctx, AV_LOG_ERROR, "%s: video_device=%p\n", __func__, video_device);
833 +            continue;
834 +        }
835 +
836 +        ret = v4l2_request_probe_video_device(video_device, avctx, pixelformat, buffersize, control, count);
837 +        udev_device_unref(video_device);
838 +
839 +        if (!ret)
840 +            break;
841 +    }
842 +
843 +    av_freep(&interfaces);
844 +    return ret;
845 +
846 +fail:
847 +    av_freep(&interfaces);
848 +    if (ctx->media_fd >= 0) {
849 +        close(ctx->media_fd);
850 +        ctx->media_fd = -1;
851 +    }
852 +    return ret;
853 +}
854 +
855 +int ff_v4l2_request_init(AVCodecContext *avctx, uint32_t pixelformat, uint32_t buffersize, struct v4l2_ext_control *control, int count)
856 +{
857 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
858 +    int ret = AVERROR(EINVAL);
859 +    struct udev *udev;
860 +    struct udev_enumerate *enumerate;
861 +    struct udev_list_entry *devices;
862 +    struct udev_list_entry *entry;
863 +    struct udev_device *device;
864 +
865 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p hw_device_ctx=%p hw_frames_ctx=%p\n", __func__, avctx, avctx->hw_device_ctx, avctx->hw_frames_ctx);
866 +
867 +    ctx->media_fd = -1;
868 +    ctx->video_fd = -1;
869 +    ctx->timestamp = 0;
870 +
871 +    udev = udev_new();
872 +    if (!udev) {
873 +        av_log(avctx, AV_LOG_ERROR, "%s: allocating udev context failed\n", __func__);
874 +        ret = AVERROR(ENOMEM);
875 +        goto fail;
876 +    }
877 +
878 +    enumerate = udev_enumerate_new(udev);
879 +    if (!enumerate) {
880 +        av_log(avctx, AV_LOG_ERROR, "%s: allocating udev enumerator failed\n", __func__);
881 +        ret = AVERROR(ENOMEM);
882 +        goto fail;
883 +    }
884 +
885 +    udev_enumerate_add_match_subsystem(enumerate, "media");
886 +    udev_enumerate_scan_devices(enumerate);
887 +
888 +    devices = udev_enumerate_get_list_entry(enumerate);
889 +    udev_list_entry_foreach(entry, devices) {
890 +        const char *path = udev_list_entry_get_name(entry);
891 +        if (!path)
892 +            continue;
893 +
894 +        device = udev_device_new_from_syspath(udev, path);
895 +        if (!device)
896 +            continue;
897 +
898 +        ret = v4l2_request_probe_media_device(device, avctx, pixelformat, buffersize, control, count);
899 +        udev_device_unref(device);
900 +
901 +        if (!ret)
902 +            break;
903 +    }
904 +
905 +    udev_enumerate_unref(enumerate);
906 +
907 +    if (!ret)
908 +        ret = v4l2_request_init_context(avctx);
909 +
910 +fail:
911 +    udev_unref(udev);
912 +    return ret;
913 +}
914 +
915 +int ff_v4l2_request_uninit(AVCodecContext *avctx)
916 +{
917 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
918 +    int ret;
919 +
920 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p ctx=%p\n", __func__, avctx, ctx);
921 +
922 +    if (ctx->video_fd >= 0) {
923 +        ret = ioctl(ctx->video_fd, VIDIOC_STREAMOFF, &ctx->output_type);
924 +        if (ret < 0)
925 +            av_log(avctx, AV_LOG_ERROR, "%s: output stream off failed, %s (%d)\n", __func__, strerror(errno), errno);
926 +
927 +        ret = ioctl(ctx->video_fd, VIDIOC_STREAMOFF, &ctx->format.type);
928 +        if (ret < 0)
929 +            av_log(avctx, AV_LOG_ERROR, "%s: capture stream off failed, %s (%d)\n", __func__, strerror(errno), errno);
930 +    }
931 +
932 +    if (avctx->hw_frames_ctx) {
933 +        AVHWFramesContext *hwfc = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
934 +        av_buffer_pool_flush(hwfc->pool);
935 +    }
936 +
937 +    if (ctx->video_fd >= 0)
938 +        close(ctx->video_fd);
939 +
940 +    if (ctx->media_fd >= 0)
941 +        close(ctx->media_fd);
942 +
943 +    return 0;
944 +}
945 +
946 +static int v4l2_request_buffer_alloc(AVCodecContext *avctx, V4L2RequestBuffer *buf, enum v4l2_buf_type type)
947 +{
948 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
949 +    int ret;
950 +    struct v4l2_plane planes[1] = {};
951 +    struct v4l2_create_buffers buffers = {
952 +        .count = 1,
953 +        .memory = V4L2_MEMORY_MMAP,
954 +        .format.type = type,
955 +    };
956 +
957 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p buf=%p type=%u\n", __func__, avctx, buf, type);
958 +
959 +    ret = ioctl(ctx->video_fd, VIDIOC_G_FMT, &buffers.format);
960 +    if (ret < 0) {
961 +        av_log(avctx, AV_LOG_ERROR, "%s: get format failed for type %u, %s (%d)\n", __func__, type, strerror(errno), errno);
962 +        return ret;
963 +    }
964 +
965 +    if (V4L2_TYPE_IS_MULTIPLANAR(buffers.format.type)) {
966 +        av_log(avctx, AV_LOG_DEBUG, "%s: pixelformat=%d width=%u height=%u bytesperline=%u sizeimage=%u num_planes=%u\n", __func__, buffers.format.fmt.pix_mp.pixelformat, buffers.format.fmt.pix_mp.width, buffers.format.fmt.pix_mp.height, buffers.format.fmt.pix_mp.plane_fmt[0].bytesperline, buffers.format.fmt.pix_mp.plane_fmt[0].sizeimage, buffers.format.fmt.pix_mp.num_planes);
967 +    } else {
968 +        av_log(avctx, AV_LOG_DEBUG, "%s: pixelformat=%d width=%u height=%u bytesperline=%u sizeimage=%u\n", __func__, buffers.format.fmt.pix.pixelformat, buffers.format.fmt.pix.width, buffers.format.fmt.pix.height, buffers.format.fmt.pix.bytesperline, buffers.format.fmt.pix.sizeimage);
969 +    }
970 +
971 +    ret = ioctl(ctx->video_fd, VIDIOC_CREATE_BUFS, &buffers);
972 +    if (ret < 0) {
973 +        av_log(avctx, AV_LOG_ERROR, "%s: create buffers failed for type %u, %s (%d)\n", __func__, type, strerror(errno), errno);
974 +        return ret;
975 +    }
976 +
977 +    if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
978 +        buf->width = buffers.format.fmt.pix_mp.width;
979 +        buf->height = buffers.format.fmt.pix_mp.height;
980 +        buf->size = buffers.format.fmt.pix_mp.plane_fmt[0].sizeimage;
981 +        buf->buffer.length = 1;
982 +        buf->buffer.m.planes = planes;
983 +    } else {
984 +        buf->width = buffers.format.fmt.pix.width;
985 +        buf->height = buffers.format.fmt.pix.height;
986 +        buf->size = buffers.format.fmt.pix.sizeimage;
987 +    }
988 +
989 +    buf->index = buffers.index;
990 +    buf->capabilities = buffers.capabilities;
991 +    buf->used = 0;
992 +
993 +    buf->buffer.type = type;
994 +    buf->buffer.memory = V4L2_MEMORY_MMAP;
995 +    buf->buffer.index = buf->index;
996 +
997 +    ret = ioctl(ctx->video_fd, VIDIOC_QUERYBUF, &buf->buffer);
998 +    if (ret < 0) {
999 +        av_log(avctx, AV_LOG_ERROR, "%s: query buffer %d failed, %s (%d)\n", __func__, buf->index, strerror(errno), errno);
1000 +        return ret;
1001 +    }
1002 +
1003 +    if (V4L2_TYPE_IS_OUTPUT(type)) {
1004 +        void *addr = mmap(NULL, buf->size, PROT_READ | PROT_WRITE, MAP_SHARED, ctx->video_fd, V4L2_TYPE_IS_MULTIPLANAR(type) ? buf->buffer.m.planes[0].m.mem_offset : buf->buffer.m.offset);
1005 +        if (addr == MAP_FAILED) {
1006 +            av_log(avctx, AV_LOG_ERROR, "%s: mmap failed, %s (%d)\n", __func__, strerror(errno), errno);
1007 +            return -1;
1008 +        }
1009 +
1010 +        buf->addr = (uint8_t*)addr;
1011 +    } else {
1012 +        struct v4l2_exportbuffer exportbuffer = {
1013 +            .type = type,
1014 +            .index = buf->index,
1015 +            .flags = O_RDONLY,
1016 +        };
1017 +
1018 +        ret = ioctl(ctx->video_fd, VIDIOC_EXPBUF, &exportbuffer);
1019 +        if (ret < 0) {
1020 +            av_log(avctx, AV_LOG_ERROR, "%s: export buffer %d failed, %s (%d)\n", __func__, buf->index, strerror(errno), errno);
1021 +            return ret;
1022 +        }
1023 +
1024 +        buf->fd = exportbuffer.fd;
1025 +    }
1026 +
1027 +    av_log(avctx, AV_LOG_DEBUG, "%s: buf=%p index=%d fd=%d addr=%p width=%u height=%u size=%u\n", __func__, buf, buf->index, buf->fd, buf->addr, buf->width, buf->height, buf->size);
1028 +    return 0;
1029 +}
1030 +
1031 +static void v4l2_request_buffer_free(V4L2RequestBuffer *buf)
1032 +{
1033 +    av_log(NULL, AV_LOG_DEBUG, "%s: buf=%p index=%d fd=%d addr=%p width=%u height=%u size=%u\n", __func__, buf, buf->index, buf->fd, buf->addr, buf->width, buf->height, buf->size);
1034 +
1035 +    if (buf->addr)
1036 +        munmap(buf->addr, buf->size);
1037 +
1038 +    if (buf->fd >= 0)
1039 +        close(buf->fd);
1040 +}
1041 +
1042 +static void v4l2_request_frame_free(void *opaque, uint8_t *data)
1043 +{
1044 +    AVCodecContext *avctx = opaque;
1045 +    V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)data;
1046 +
1047 +    av_log(NULL, AV_LOG_DEBUG, "%s: avctx=%p data=%p request_fd=%d\n", __func__, avctx, data, req->request_fd);
1048 +
1049 +    if (req->request_fd >= 0)
1050 +        close(req->request_fd);
1051 +
1052 +    v4l2_request_buffer_free(&req->capture);
1053 +    v4l2_request_buffer_free(&req->output);
1054 +
1055 +    av_free(data);
1056 +}
1057 +
1058 +static AVBufferRef *v4l2_request_frame_alloc(void *opaque, int size)
1059 +{
1060 +    AVCodecContext *avctx = opaque;
1061 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
1062 +    V4L2RequestDescriptor *req;
1063 +    AVBufferRef *ref;
1064 +    uint8_t *data;
1065 +    int ret;
1066 +
1067 +    data = av_mallocz(size);
1068 +    if (!data)
1069 +        return NULL;
1070 +
1071 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p size=%d data=%p\n", __func__, avctx, size, data);
1072 +
1073 +    ref = av_buffer_create(data, size, v4l2_request_frame_free, avctx, 0);
1074 +    if (!ref) {
1075 +        av_freep(&data);
1076 +        return NULL;
1077 +    }
1078 +
1079 +    req = (V4L2RequestDescriptor*)data;
1080 +    req->request_fd = -1;
1081 +    req->output.fd = -1;
1082 +    req->capture.fd = -1;
1083 +
1084 +    ret = v4l2_request_buffer_alloc(avctx, &req->output, ctx->output_type);
1085 +    if (ret < 0) {
1086 +        av_buffer_unref(&ref);
1087 +        return NULL;
1088 +    }
1089 +
1090 +    ret = v4l2_request_buffer_alloc(avctx, &req->capture, ctx->format.type);
1091 +    if (ret < 0) {
1092 +        av_buffer_unref(&ref);
1093 +        return NULL;
1094 +    }
1095 +
1096 +    ret = ioctl(ctx->media_fd, MEDIA_IOC_REQUEST_ALLOC, &req->request_fd);
1097 +    if (ret < 0) {
1098 +        av_log(avctx, AV_LOG_ERROR, "%s: request alloc failed, %s (%d)\n", __func__, strerror(errno), errno);
1099 +        av_buffer_unref(&ref);
1100 +        return NULL;
1101 +    }
1102 +
1103 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p size=%d data=%p request_fd=%d\n", __func__, avctx, size, data, req->request_fd);
1104 +    return ref;
1105 +}
1106 +
1107 +static void v4l2_request_pool_free(void *opaque)
1108 +{
1109 +    av_log(NULL, AV_LOG_DEBUG, "%s: opaque=%p\n", __func__, opaque);
1110 +}
1111 +
1112 +static void v4l2_request_hwframe_ctx_free(AVHWFramesContext *hwfc)
1113 +{
1114 +    av_log(NULL, AV_LOG_DEBUG, "%s: hwfc=%p pool=%p\n", __func__, hwfc, hwfc->pool);
1115 +
1116 +    av_buffer_pool_flush(hwfc->pool);
1117 +    av_buffer_pool_uninit(&hwfc->pool);
1118 +}
1119 +
1120 +int ff_v4l2_request_frame_params(AVCodecContext *avctx, AVBufferRef *hw_frames_ctx)
1121 +{
1122 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
1123 +    AVHWFramesContext *hwfc = (AVHWFramesContext*)hw_frames_ctx->data;
1124 +
1125 +    hwfc->format = AV_PIX_FMT_DRM_PRIME;
1126 +    hwfc->sw_format = AV_PIX_FMT_NV12;
1127 +    if (V4L2_TYPE_IS_MULTIPLANAR(ctx->format.type)) {
1128 +        hwfc->width = ctx->format.fmt.pix_mp.width;
1129 +        hwfc->height = ctx->format.fmt.pix_mp.height;
1130 +    } else {
1131 +        hwfc->width = ctx->format.fmt.pix.width;
1132 +        hwfc->height = ctx->format.fmt.pix.height;
1133 +    }
1134 +
1135 +    hwfc->pool = av_buffer_pool_init2(sizeof(V4L2RequestDescriptor), avctx, v4l2_request_frame_alloc, v4l2_request_pool_free);
1136 +    if (!hwfc->pool)
1137 +        return AVERROR(ENOMEM);
1138 +
1139 +    hwfc->free = v4l2_request_hwframe_ctx_free;
1140 +
1141 +    hwfc->initial_pool_size = 1;
1142 +
1143 +    switch (avctx->codec_id) {
1144 +    case AV_CODEC_ID_VP9:
1145 +        hwfc->initial_pool_size += 8;
1146 +        break;
1147 +    case AV_CODEC_ID_VP8:
1148 +        hwfc->initial_pool_size += 3;
1149 +        break;
1150 +    default:
1151 +        hwfc->initial_pool_size += 2;
1152 +    }
1153 +
1154 +    av_log(avctx, AV_LOG_DEBUG, "%s: avctx=%p ctx=%p hw_frames_ctx=%p hwfc=%p pool=%p width=%d height=%d initial_pool_size=%d\n", __func__, avctx, ctx, hw_frames_ctx, hwfc, hwfc->pool, hwfc->width, hwfc->height, hwfc->initial_pool_size);
1155 +
1156 +    return 0;
1157 +}
1158 diff --git a/libavcodec/v4l2_request.h b/libavcodec/v4l2_request.h
1159 new file mode 100644
1160 index 00000000000..58d2aa70af8
1161 --- /dev/null
1162 +++ b/libavcodec/v4l2_request.h
1163 @@ -0,0 +1,77 @@
1164 +/*
1165 + * This file is part of FFmpeg.
1166 + *
1167 + * FFmpeg is free software; you can redistribute it and/or
1168 + * modify it under the terms of the GNU Lesser General Public
1169 + * License as published by the Free Software Foundation; either
1170 + * version 2.1 of the License, or (at your option) any later version.
1171 + *
1172 + * FFmpeg is distributed in the hope that it will be useful,
1173 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
1174 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1175 + * Lesser General Public License for more details.
1176 + *
1177 + * You should have received a copy of the GNU Lesser General Public
1178 + * License along with FFmpeg; if not, write to the Free Software
1179 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1180 + */
1181 +
1182 +#ifndef AVCODEC_V4L2_REQUEST_H
1183 +#define AVCODEC_V4L2_REQUEST_H
1184 +
1185 +#include <linux/videodev2.h>
1186 +
1187 +#include "libavutil/hwcontext_drm.h"
1188 +
1189 +typedef struct V4L2RequestContext {
1190 +    int video_fd;
1191 +    int media_fd;
1192 +    enum v4l2_buf_type output_type;
1193 +    struct v4l2_format format;
1194 +    int timestamp;
1195 +} V4L2RequestContext;
1196 +
1197 +typedef struct V4L2RequestBuffer {
1198 +    int index;
1199 +    int fd;
1200 +    uint8_t *addr;
1201 +    uint32_t width;
1202 +    uint32_t height;
1203 +    uint32_t size;
1204 +    uint32_t used;
1205 +    uint32_t capabilities;
1206 +    struct v4l2_buffer buffer;
1207 +} V4L2RequestBuffer;
1208 +
1209 +typedef struct V4L2RequestDescriptor {
1210 +    AVDRMFrameDescriptor drm;
1211 +    int request_fd;
1212 +    V4L2RequestBuffer output;
1213 +    V4L2RequestBuffer capture;
1214 +} V4L2RequestDescriptor;
1215 +
1216 +uint64_t ff_v4l2_request_get_capture_timestamp(AVFrame *frame);
1217 +
1218 +int ff_v4l2_request_reset_frame(AVCodecContext *avctx, AVFrame *frame);
1219 +
1220 +int ff_v4l2_request_append_output_buffer(AVCodecContext *avctx, AVFrame *frame, const uint8_t *data, uint32_t size);
1221 +
1222 +int ff_v4l2_request_set_controls(AVCodecContext *avctx, struct v4l2_ext_control *control, int count);
1223 +
1224 +int ff_v4l2_request_get_controls(AVCodecContext *avctx, struct v4l2_ext_control *control, int count);
1225 +
1226 +int ff_v4l2_request_query_control(AVCodecContext *avctx, struct v4l2_query_ext_ctrl *control);
1227 +
1228 +int ff_v4l2_request_query_control_default_value(AVCodecContext *avctx, uint32_t id);
1229 +
1230 +int ff_v4l2_request_decode_slice(AVCodecContext *avctx, AVFrame *frame, struct v4l2_ext_control *control, int count, int first_slice, int last_slice);
1231 +
1232 +int ff_v4l2_request_decode_frame(AVCodecContext *avctx, AVFrame *frame, struct v4l2_ext_control *control, int count);
1233 +
1234 +int ff_v4l2_request_init(AVCodecContext *avctx, uint32_t pixelformat, uint32_t buffersize, struct v4l2_ext_control *control, int count);
1235 +
1236 +int ff_v4l2_request_uninit(AVCodecContext *avctx);
1237 +
1238 +int ff_v4l2_request_frame_params(AVCodecContext *avctx, AVBufferRef *hw_frames_ctx);
1239 +
1240 +#endif /* AVCODEC_V4L2_REQUEST_H */
1241
1242 From e432d3151f4c5507e40fb1fe8b3c3fb7c7a0a08c Mon Sep 17 00:00:00 2001
1243 From: Ezequiel Garcia <ezequiel@collabora.com>
1244 Date: Wed, 20 Feb 2019 11:18:00 -0300
1245 Subject: [PATCH 03/17] h264dec: add idr_pic_id to slice context
1246
1247 Used by V4L2 request API h264 hwaccel
1248
1249 Signed-off-by: Ezequiel Garcia <ezequiel@collabora.com>
1250 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
1251 ---
1252  libavcodec/h264_slice.c | 2 +-
1253  libavcodec/h264dec.h    | 1 +
1254  2 files changed, 2 insertions(+), 1 deletion(-)
1255
1256 diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c
1257 index 2d0605c7f4f..c3a7338a704 100644
1258 --- a/libavcodec/h264_slice.c
1259 +++ b/libavcodec/h264_slice.c
1260 @@ -1830,7 +1830,7 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
1261      }
1262  
1263      if (nal->type == H264_NAL_IDR_SLICE)
1264 -        get_ue_golomb_long(&sl->gb); /* idr_pic_id */
1265 +        sl->idr_pic_id = get_ue_golomb_long(&sl->gb);
1266  
1267      sl->poc_lsb = 0;
1268      sl->delta_poc_bottom = 0;
1269 diff --git a/libavcodec/h264dec.h b/libavcodec/h264dec.h
1270 index b7b19ba4f16..0698ab95ba5 100644
1271 --- a/libavcodec/h264dec.h
1272 +++ b/libavcodec/h264dec.h
1273 @@ -336,6 +336,7 @@ typedef struct H264SliceContext {
1274      int delta_poc[2];
1275      int curr_pic_num;
1276      int max_pic_num;
1277 +    int idr_pic_id;
1278  } H264SliceContext;
1279  
1280  /**
1281
1282 From 84564d13ec0ec40f408622ff6b0d900723bbab5b Mon Sep 17 00:00:00 2001
1283 From: Boris Brezillon <boris.brezillon@collabora.com>
1284 Date: Wed, 22 May 2019 14:44:22 +0200
1285 Subject: [PATCH 04/17] h264dec: add ref_pic_marking and pic_order_cnt bit_size
1286  to slice context
1287
1288 Used by V4L2 request API h264 hwaccel
1289
1290 Signed-off-by: Boris Brezillon <boris.brezillon@collabora.com>
1291 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
1292 ---
1293  libavcodec/h264_slice.c | 6 +++++-
1294  libavcodec/h264dec.h    | 2 ++
1295  2 files changed, 7 insertions(+), 1 deletion(-)
1296
1297 diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c
1298 index c3a7338a704..c28b58cd5d9 100644
1299 --- a/libavcodec/h264_slice.c
1300 +++ b/libavcodec/h264_slice.c
1301 @@ -1748,7 +1748,7 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
1302      unsigned int slice_type, tmp, i;
1303      int field_pic_flag, bottom_field_flag;
1304      int first_slice = sl == h->slice_ctx && !h->current_slice;
1305 -    int picture_structure;
1306 +    int picture_structure, pos;
1307  
1308      if (first_slice)
1309          av_assert0(!h->setup_finished);
1310 @@ -1832,6 +1832,7 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
1311      if (nal->type == H264_NAL_IDR_SLICE)
1312          sl->idr_pic_id = get_ue_golomb_long(&sl->gb);
1313  
1314 +    pos = sl->gb.index;
1315      sl->poc_lsb = 0;
1316      sl->delta_poc_bottom = 0;
1317      if (sps->poc_type == 0) {
1318 @@ -1845,6 +1846,7 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
1319          if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
1320              sl->delta_poc[1] = get_se_golomb(&sl->gb);
1321      }
1322 +    sl->pic_order_cnt_bit_size = sl->gb.index - pos;
1323  
1324      sl->redundant_pic_count = 0;
1325      if (pps->redundant_pic_cnt_present)
1326 @@ -1884,9 +1886,11 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
1327  
1328      sl->explicit_ref_marking = 0;
1329      if (nal->ref_idc) {
1330 +        pos = sl->gb.index;
1331          ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, h->avctx);
1332          if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
1333              return AVERROR_INVALIDDATA;
1334 +        sl->ref_pic_marking_bit_size = sl->gb.index - pos;
1335      }
1336  
1337      if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
1338 diff --git a/libavcodec/h264dec.h b/libavcodec/h264dec.h
1339 index 0698ab95ba5..2b39e82c3b0 100644
1340 --- a/libavcodec/h264dec.h
1341 +++ b/libavcodec/h264dec.h
1342 @@ -329,6 +329,7 @@ typedef struct H264SliceContext {
1343      MMCO mmco[MAX_MMCO_COUNT];
1344      int  nb_mmco;
1345      int explicit_ref_marking;
1346 +    int ref_pic_marking_bit_size;
1347  
1348      int frame_num;
1349      int poc_lsb;
1350 @@ -337,6 +338,7 @@ typedef struct H264SliceContext {
1351      int curr_pic_num;
1352      int max_pic_num;
1353      int idr_pic_id;
1354 +    int pic_order_cnt_bit_size;
1355  } H264SliceContext;
1356  
1357  /**
1358
1359 From 5a8628cf6368fe18457d02bf551d5935609efab5 Mon Sep 17 00:00:00 2001
1360 From: Jernej Skrabec <jernej.skrabec@siol.net>
1361 Date: Sat, 15 Dec 2018 22:32:16 +0100
1362 Subject: [PATCH 05/17] Add V4L2 request API h264 hwaccel
1363
1364 Signed-off-by: Jernej Skrabec <jernej.skrabec@siol.net>
1365 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
1366 ---
1367  configure                      |   3 +
1368  libavcodec/Makefile            |   1 +
1369  libavcodec/h264_slice.c        |   4 +
1370  libavcodec/h264dec.c           |   3 +
1371  libavcodec/hwaccels.h          |   1 +
1372  libavcodec/v4l2_request_h264.c | 456 +++++++++++++++++++++++++++++++++
1373  6 files changed, 468 insertions(+)
1374  create mode 100644 libavcodec/v4l2_request_h264.c
1375
1376 diff --git a/configure b/configure
1377 index f2e203d1346..b17e4108c1b 100755
1378 --- a/configure
1379 +++ b/configure
1380 @@ -2951,6 +2951,8 @@ h264_dxva2_hwaccel_deps="dxva2"
1381  h264_dxva2_hwaccel_select="h264_decoder"
1382  h264_nvdec_hwaccel_deps="nvdec"
1383  h264_nvdec_hwaccel_select="h264_decoder"
1384 +h264_v4l2request_hwaccel_deps="v4l2_request h264_v4l2_request"
1385 +h264_v4l2request_hwaccel_select="h264_decoder"
1386  h264_vaapi_hwaccel_deps="vaapi"
1387  h264_vaapi_hwaccel_select="h264_decoder"
1388  h264_vdpau_hwaccel_deps="vdpau"
1389 @@ -6628,6 +6630,7 @@ if enabled v4l2_m2m; then
1390  fi
1391  
1392  check_func_headers "linux/media.h linux/videodev2.h" v4l2_timeval_to_ns
1393 +check_cc h264_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_H264_SLICE;"
1394  
1395  check_headers sys/videoio.h
1396  test_code cc sys/videoio.h "struct v4l2_frmsizeenum vfse; vfse.discrete.width = 0;" && enable_sanitized struct_v4l2_frmivalenum_discrete
1397 diff --git a/libavcodec/Makefile b/libavcodec/Makefile
1398 index 90dfffcb200..426c7528e90 100644
1399 --- a/libavcodec/Makefile
1400 +++ b/libavcodec/Makefile
1401 @@ -935,6 +935,7 @@ OBJS-$(CONFIG_H264_D3D11VA_HWACCEL)       += dxva2_h264.o
1402  OBJS-$(CONFIG_H264_DXVA2_HWACCEL)         += dxva2_h264.o
1403  OBJS-$(CONFIG_H264_NVDEC_HWACCEL)         += nvdec_h264.o
1404  OBJS-$(CONFIG_H264_QSV_HWACCEL)           += qsvdec.o
1405 +OBJS-$(CONFIG_H264_V4L2REQUEST_HWACCEL)   += v4l2_request_h264.o
1406  OBJS-$(CONFIG_H264_VAAPI_HWACCEL)         += vaapi_h264.o
1407  OBJS-$(CONFIG_H264_VDPAU_HWACCEL)         += vdpau_h264.o
1408  OBJS-$(CONFIG_H264_VIDEOTOOLBOX_HWACCEL)  += videotoolbox.o
1409 diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c
1410 index c28b58cd5d9..0a10d00aad9 100644
1411 --- a/libavcodec/h264_slice.c
1412 +++ b/libavcodec/h264_slice.c
1413 @@ -768,6 +768,7 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
1414  #define HWACCEL_MAX (CONFIG_H264_DXVA2_HWACCEL + \
1415                       (CONFIG_H264_D3D11VA_HWACCEL * 2) + \
1416                       CONFIG_H264_NVDEC_HWACCEL + \
1417 +                     CONFIG_H264_V4L2REQUEST_HWACCEL + \
1418                       CONFIG_H264_VAAPI_HWACCEL + \
1419                       CONFIG_H264_VIDEOTOOLBOX_HWACCEL + \
1420                       CONFIG_H264_VDPAU_HWACCEL)
1421 @@ -852,6 +853,9 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
1422  #endif
1423  #if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
1424              *fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
1425 +#endif
1426 +#if CONFIG_H264_V4L2REQUEST_HWACCEL
1427 +            *fmt++ = AV_PIX_FMT_DRM_PRIME;
1428  #endif
1429              if (h->avctx->codec->pix_fmts)
1430                  choices = h->avctx->codec->pix_fmts;
1431 diff --git a/libavcodec/h264dec.c b/libavcodec/h264dec.c
1432 index 0a999bef43d..d78e3eaee3a 100644
1433 --- a/libavcodec/h264dec.c
1434 +++ b/libavcodec/h264dec.c
1435 @@ -1076,6 +1076,9 @@ AVCodec ff_h264_decoder = {
1436  #endif
1437  #if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
1438                                 HWACCEL_VIDEOTOOLBOX(h264),
1439 +#endif
1440 +#if CONFIG_H264_V4L2REQUEST_HWACCEL
1441 +                               HWACCEL_V4L2REQUEST(h264),
1442  #endif
1443                                 NULL
1444                             },
1445 diff --git a/libavcodec/hwaccels.h b/libavcodec/hwaccels.h
1446 index 8e54cf73f90..969a1da0f4b 100644
1447 --- a/libavcodec/hwaccels.h
1448 +++ b/libavcodec/hwaccels.h
1449 @@ -32,6 +32,7 @@ extern const AVHWAccel ff_h264_d3d11va_hwaccel;
1450  extern const AVHWAccel ff_h264_d3d11va2_hwaccel;
1451  extern const AVHWAccel ff_h264_dxva2_hwaccel;
1452  extern const AVHWAccel ff_h264_nvdec_hwaccel;
1453 +extern const AVHWAccel ff_h264_v4l2request_hwaccel;
1454  extern const AVHWAccel ff_h264_vaapi_hwaccel;
1455  extern const AVHWAccel ff_h264_vdpau_hwaccel;
1456  extern const AVHWAccel ff_h264_videotoolbox_hwaccel;
1457 diff --git a/libavcodec/v4l2_request_h264.c b/libavcodec/v4l2_request_h264.c
1458 new file mode 100644
1459 index 00000000000..88da8f0a2db
1460 --- /dev/null
1461 +++ b/libavcodec/v4l2_request_h264.c
1462 @@ -0,0 +1,456 @@
1463 +/*
1464 + * This file is part of FFmpeg.
1465 + *
1466 + * FFmpeg is free software; you can redistribute it and/or
1467 + * modify it under the terms of the GNU Lesser General Public
1468 + * License as published by the Free Software Foundation; either
1469 + * version 2.1 of the License, or (at your option) any later version.
1470 + *
1471 + * FFmpeg is distributed in the hope that it will be useful,
1472 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
1473 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1474 + * Lesser General Public License for more details.
1475 + *
1476 + * You should have received a copy of the GNU Lesser General Public
1477 + * License along with FFmpeg; if not, write to the Free Software
1478 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1479 + */
1480 +
1481 +#include "h264dec.h"
1482 +#include "hwconfig.h"
1483 +#include "v4l2_request.h"
1484 +
1485 +typedef struct V4L2RequestControlsH264 {
1486 +    struct v4l2_ctrl_h264_sps sps;
1487 +    struct v4l2_ctrl_h264_pps pps;
1488 +    struct v4l2_ctrl_h264_scaling_matrix scaling_matrix;
1489 +    struct v4l2_ctrl_h264_decode_params decode_params;
1490 +    struct v4l2_ctrl_h264_slice_params slice_params;
1491 +    struct v4l2_ctrl_h264_pred_weights pred_weights;
1492 +    int pred_weights_required;
1493 +    int first_slice;
1494 +    int num_slices;
1495 +} V4L2RequestControlsH264;
1496 +
1497 +typedef struct V4L2RequestContextH264 {
1498 +    V4L2RequestContext base;
1499 +    int decode_mode;
1500 +    int start_code;
1501 +} V4L2RequestContextH264;
1502 +
1503 +static uint8_t nalu_slice_start_code[] = { 0x00, 0x00, 0x01 };
1504 +
1505 +static void fill_weight_factors(struct v4l2_h264_weight_factors *factors, int list, const H264SliceContext *sl)
1506 +{
1507 +    for (int i = 0; i < sl->ref_count[list]; i++) {
1508 +        if (sl->pwt.luma_weight_flag[list]) {
1509 +            factors->luma_weight[i] = sl->pwt.luma_weight[i][list][0];
1510 +            factors->luma_offset[i] = sl->pwt.luma_weight[i][list][1];
1511 +        } else {
1512 +            factors->luma_weight[i] = 1 << sl->pwt.luma_log2_weight_denom;
1513 +            factors->luma_offset[i] = 0;
1514 +        }
1515 +        for (int j = 0; j < 2; j++) {
1516 +            if (sl->pwt.chroma_weight_flag[list]) {
1517 +                factors->chroma_weight[i][j] = sl->pwt.chroma_weight[i][list][j][0];
1518 +                factors->chroma_offset[i][j] = sl->pwt.chroma_weight[i][list][j][1];
1519 +            } else {
1520 +                factors->chroma_weight[i][j] = 1 << sl->pwt.chroma_log2_weight_denom;
1521 +                factors->chroma_offset[i][j] = 0;
1522 +            }
1523 +        }
1524 +    }
1525 +}
1526 +
1527 +static void fill_dpb_entry(struct v4l2_h264_dpb_entry *entry, const H264Picture *pic)
1528 +{
1529 +    entry->reference_ts = ff_v4l2_request_get_capture_timestamp(pic->f);
1530 +    entry->pic_num = pic->pic_id;
1531 +    entry->frame_num = pic->frame_num;
1532 +    entry->fields = pic->reference & V4L2_H264_FRAME_REF;
1533 +    entry->flags = V4L2_H264_DPB_ENTRY_FLAG_VALID;
1534 +    if (entry->fields)
1535 +        entry->flags |= V4L2_H264_DPB_ENTRY_FLAG_ACTIVE;
1536 +    if (pic->long_ref)
1537 +        entry->flags |= V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM;
1538 +    if (pic->field_picture)
1539 +        entry->flags |= V4L2_H264_DPB_ENTRY_FLAG_FIELD;
1540 +    if (pic->field_poc[0] != INT_MAX)
1541 +        entry->top_field_order_cnt = pic->field_poc[0];
1542 +    if (pic->field_poc[1] != INT_MAX)
1543 +        entry->bottom_field_order_cnt = pic->field_poc[1];
1544 +}
1545 +
1546 +static void fill_dpb(struct v4l2_ctrl_h264_decode_params *decode, const H264Context *h)
1547 +{
1548 +    int entries = 0;
1549 +
1550 +    for (int i = 0; i < h->short_ref_count; i++) {
1551 +        const H264Picture *pic = h->short_ref[i];
1552 +        if (pic && (pic->field_poc[0] != INT_MAX || pic->field_poc[1] != INT_MAX))
1553 +            fill_dpb_entry(&decode->dpb[entries++], pic);
1554 +    }
1555 +
1556 +    if (!h->long_ref_count)
1557 +        return;
1558 +
1559 +    for (int i = 0; i < FF_ARRAY_ELEMS(h->long_ref); i++) {
1560 +        const H264Picture *pic = h->long_ref[i];
1561 +        if (pic && (pic->field_poc[0] != INT_MAX || pic->field_poc[1] != INT_MAX))
1562 +            fill_dpb_entry(&decode->dpb[entries++], pic);
1563 +    }
1564 +}
1565 +
1566 +static void fill_ref_list(struct v4l2_h264_reference *reference, struct v4l2_ctrl_h264_decode_params *decode, const H264Ref *ref)
1567 +{
1568 +    uint64_t timestamp;
1569 +
1570 +    if (!ref->parent)
1571 +        return;
1572 +
1573 +    timestamp = ff_v4l2_request_get_capture_timestamp(ref->parent->f);
1574 +
1575 +    for (uint8_t i = 0; i < FF_ARRAY_ELEMS(decode->dpb); i++) {
1576 +        struct v4l2_h264_dpb_entry *entry = &decode->dpb[i];
1577 +        if ((entry->flags & V4L2_H264_DPB_ENTRY_FLAG_VALID) &&
1578 +            entry->reference_ts == timestamp) {
1579 +            reference->fields = ref->reference & V4L2_H264_FRAME_REF;
1580 +            reference->index = i;
1581 +            return;
1582 +        }
1583 +    }
1584 +}
1585 +
1586 +static void fill_sps(struct v4l2_ctrl_h264_sps *ctrl, const H264Context *h)
1587 +{
1588 +    const SPS *sps = h->ps.sps;
1589 +
1590 +    *ctrl = (struct v4l2_ctrl_h264_sps) {
1591 +        .profile_idc = sps->profile_idc,
1592 +        .constraint_set_flags = sps->constraint_set_flags,
1593 +        .level_idc = sps->level_idc,
1594 +        .seq_parameter_set_id = sps->sps_id,
1595 +        .chroma_format_idc = sps->chroma_format_idc,
1596 +        .bit_depth_luma_minus8 = sps->bit_depth_luma - 8,
1597 +        .bit_depth_chroma_minus8 = sps->bit_depth_chroma - 8,
1598 +        .log2_max_frame_num_minus4 = sps->log2_max_frame_num - 4,
1599 +        .pic_order_cnt_type = sps->poc_type,
1600 +        .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_poc_lsb - 4,
1601 +        .max_num_ref_frames = sps->ref_frame_count,
1602 +        .num_ref_frames_in_pic_order_cnt_cycle = sps->poc_cycle_length,
1603 +        .offset_for_non_ref_pic = sps->offset_for_non_ref_pic,
1604 +        .offset_for_top_to_bottom_field = sps->offset_for_top_to_bottom_field,
1605 +        .pic_width_in_mbs_minus1 = h->mb_width - 1,
1606 +        .pic_height_in_map_units_minus1 = sps->frame_mbs_only_flag ? h->mb_height - 1 : h->mb_height / 2 - 1,
1607 +    };
1608 +
1609 +    if (sps->poc_cycle_length > 0 && sps->poc_cycle_length <= 255)
1610 +        memcpy(ctrl->offset_for_ref_frame, sps->offset_for_ref_frame, sps->poc_cycle_length * sizeof(ctrl->offset_for_ref_frame[0]));
1611 +
1612 +    if (sps->residual_color_transform_flag)
1613 +        ctrl->flags |= V4L2_H264_SPS_FLAG_SEPARATE_COLOUR_PLANE;
1614 +    if (sps->transform_bypass)
1615 +        ctrl->flags |= V4L2_H264_SPS_FLAG_QPPRIME_Y_ZERO_TRANSFORM_BYPASS;
1616 +    if (sps->delta_pic_order_always_zero_flag)
1617 +        ctrl->flags |= V4L2_H264_SPS_FLAG_DELTA_PIC_ORDER_ALWAYS_ZERO;
1618 +    if (sps->gaps_in_frame_num_allowed_flag)
1619 +        ctrl->flags |= V4L2_H264_SPS_FLAG_GAPS_IN_FRAME_NUM_VALUE_ALLOWED;
1620 +    if (sps->frame_mbs_only_flag)
1621 +        ctrl->flags |= V4L2_H264_SPS_FLAG_FRAME_MBS_ONLY;
1622 +    if (sps->mb_aff)
1623 +        ctrl->flags |= V4L2_H264_SPS_FLAG_MB_ADAPTIVE_FRAME_FIELD;
1624 +    if (sps->direct_8x8_inference_flag)
1625 +        ctrl->flags |= V4L2_H264_SPS_FLAG_DIRECT_8X8_INFERENCE;
1626 +}
1627 +
1628 +static void fill_pps(struct v4l2_ctrl_h264_pps *ctrl, const H264Context *h)
1629 +{
1630 +    const SPS *sps = h->ps.sps;
1631 +    const PPS *pps = h->ps.pps;
1632 +    const H264SliceContext *sl = &h->slice_ctx[0];
1633 +    int qp_bd_offset = 6 * (sps->bit_depth_luma - 8);
1634 +
1635 +    *ctrl = (struct v4l2_ctrl_h264_pps) {
1636 +        .pic_parameter_set_id = sl->pps_id,
1637 +        .seq_parameter_set_id = pps->sps_id,
1638 +        .num_slice_groups_minus1 = pps->slice_group_count - 1,
1639 +        .num_ref_idx_l0_default_active_minus1 = pps->ref_count[0] - 1,
1640 +        .num_ref_idx_l1_default_active_minus1 = pps->ref_count[1] - 1,
1641 +        .weighted_bipred_idc = pps->weighted_bipred_idc,
1642 +        .pic_init_qp_minus26 = pps->init_qp - 26 - qp_bd_offset,
1643 +        .pic_init_qs_minus26 = pps->init_qs - 26 - qp_bd_offset,
1644 +        .chroma_qp_index_offset = pps->chroma_qp_index_offset[0],
1645 +        .second_chroma_qp_index_offset = pps->chroma_qp_index_offset[1],
1646 +    };
1647 +
1648 +    if (pps->cabac)
1649 +        ctrl->flags |= V4L2_H264_PPS_FLAG_ENTROPY_CODING_MODE;
1650 +    if (pps->pic_order_present)
1651 +        ctrl->flags |= V4L2_H264_PPS_FLAG_BOTTOM_FIELD_PIC_ORDER_IN_FRAME_PRESENT;
1652 +    if (pps->weighted_pred)
1653 +        ctrl->flags |= V4L2_H264_PPS_FLAG_WEIGHTED_PRED;
1654 +    if (pps->deblocking_filter_parameters_present)
1655 +        ctrl->flags |= V4L2_H264_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT;
1656 +    if (pps->constrained_intra_pred)
1657 +        ctrl->flags |= V4L2_H264_PPS_FLAG_CONSTRAINED_INTRA_PRED;
1658 +    if (pps->redundant_pic_cnt_present)
1659 +        ctrl->flags |= V4L2_H264_PPS_FLAG_REDUNDANT_PIC_CNT_PRESENT;
1660 +    if (pps->transform_8x8_mode)
1661 +        ctrl->flags |= V4L2_H264_PPS_FLAG_TRANSFORM_8X8_MODE;
1662 +
1663 +    /* FFmpeg always provide a scaling matrix */
1664 +    ctrl->flags |= V4L2_H264_PPS_FLAG_SCALING_MATRIX_PRESENT;
1665 +}
1666 +
1667 +static int v4l2_request_h264_start_frame(AVCodecContext *avctx,
1668 +                                         av_unused const uint8_t *buffer,
1669 +                                         av_unused uint32_t size)
1670 +{
1671 +    const H264Context *h = avctx->priv_data;
1672 +    const PPS *pps = h->ps.pps;
1673 +    const SPS *sps = h->ps.sps;
1674 +    const H264SliceContext *sl = &h->slice_ctx[0];
1675 +    V4L2RequestControlsH264 *controls = h->cur_pic_ptr->hwaccel_picture_private;
1676 +
1677 +    fill_sps(&controls->sps, h);
1678 +    fill_pps(&controls->pps, h);
1679 +
1680 +    memcpy(controls->scaling_matrix.scaling_list_4x4, pps->scaling_matrix4, sizeof(controls->scaling_matrix.scaling_list_4x4));
1681 +    memcpy(controls->scaling_matrix.scaling_list_8x8[0], pps->scaling_matrix8[0], sizeof(controls->scaling_matrix.scaling_list_8x8[0]));
1682 +    memcpy(controls->scaling_matrix.scaling_list_8x8[1], pps->scaling_matrix8[3], sizeof(controls->scaling_matrix.scaling_list_8x8[1]));
1683 +
1684 +    if (sps->chroma_format_idc == 3) {
1685 +        memcpy(controls->scaling_matrix.scaling_list_8x8[2], pps->scaling_matrix8[1], sizeof(controls->scaling_matrix.scaling_list_8x8[2]));
1686 +        memcpy(controls->scaling_matrix.scaling_list_8x8[3], pps->scaling_matrix8[4], sizeof(controls->scaling_matrix.scaling_list_8x8[3]));
1687 +        memcpy(controls->scaling_matrix.scaling_list_8x8[4], pps->scaling_matrix8[2], sizeof(controls->scaling_matrix.scaling_list_8x8[4]));
1688 +        memcpy(controls->scaling_matrix.scaling_list_8x8[5], pps->scaling_matrix8[5], sizeof(controls->scaling_matrix.scaling_list_8x8[5]));
1689 +    }
1690 +
1691 +    controls->decode_params = (struct v4l2_ctrl_h264_decode_params) {
1692 +        .nal_ref_idc = h->nal_ref_idc,
1693 +        .frame_num = h->poc.frame_num,
1694 +        .top_field_order_cnt = h->cur_pic_ptr->field_poc[0] != INT_MAX ? h->cur_pic_ptr->field_poc[0] : 0,
1695 +        .bottom_field_order_cnt = h->cur_pic_ptr->field_poc[1] != INT_MAX ? h->cur_pic_ptr->field_poc[1] : 0,
1696 +        .idr_pic_id = sl->idr_pic_id,
1697 +        .pic_order_cnt_lsb = sl->poc_lsb,
1698 +        .delta_pic_order_cnt_bottom = sl->delta_poc_bottom,
1699 +        .delta_pic_order_cnt0 = sl->delta_poc[0],
1700 +        .delta_pic_order_cnt1 = sl->delta_poc[1],
1701 +        /* Size in bits of dec_ref_pic_marking() syntax element. */
1702 +        .dec_ref_pic_marking_bit_size = sl->ref_pic_marking_bit_size,
1703 +        /* Size in bits of pic order count syntax. */
1704 +        .pic_order_cnt_bit_size = sl->pic_order_cnt_bit_size,
1705 +        .slice_group_change_cycle = 0, /* slice group not supported by FFmpeg */
1706 +    };
1707 +
1708 +    if (h->picture_idr)
1709 +        controls->decode_params.flags |= V4L2_H264_DECODE_PARAM_FLAG_IDR_PIC;
1710 +    if (FIELD_PICTURE(h))
1711 +        controls->decode_params.flags |= V4L2_H264_DECODE_PARAM_FLAG_FIELD_PIC;
1712 +    if (h->picture_structure == PICT_BOTTOM_FIELD)
1713 +        controls->decode_params.flags |= V4L2_H264_DECODE_PARAM_FLAG_BOTTOM_FIELD;
1714 +
1715 +    fill_dpb(&controls->decode_params, h);
1716 +
1717 +    controls->first_slice = !FIELD_PICTURE(h) || h->first_field;
1718 +    controls->num_slices = 0;
1719 +
1720 +    return ff_v4l2_request_reset_frame(avctx, h->cur_pic_ptr->f);
1721 +}
1722 +
1723 +static int v4l2_request_h264_queue_decode(AVCodecContext *avctx, int last_slice)
1724 +{
1725 +    const H264Context *h = avctx->priv_data;
1726 +    V4L2RequestControlsH264 *controls = h->cur_pic_ptr->hwaccel_picture_private;
1727 +    V4L2RequestContextH264 *ctx = avctx->internal->hwaccel_priv_data;
1728 +
1729 +    struct v4l2_ext_control control[] = {
1730 +        {
1731 +            .id = V4L2_CID_STATELESS_H264_SPS,
1732 +            .ptr = &controls->sps,
1733 +            .size = sizeof(controls->sps),
1734 +        },
1735 +        {
1736 +            .id = V4L2_CID_STATELESS_H264_PPS,
1737 +            .ptr = &controls->pps,
1738 +            .size = sizeof(controls->pps),
1739 +        },
1740 +        {
1741 +            .id = V4L2_CID_STATELESS_H264_SCALING_MATRIX,
1742 +            .ptr = &controls->scaling_matrix,
1743 +            .size = sizeof(controls->scaling_matrix),
1744 +        },
1745 +        {
1746 +            .id = V4L2_CID_STATELESS_H264_DECODE_PARAMS,
1747 +            .ptr = &controls->decode_params,
1748 +            .size = sizeof(controls->decode_params),
1749 +        },
1750 +        {
1751 +            .id = V4L2_CID_STATELESS_H264_SLICE_PARAMS,
1752 +            .ptr = &controls->slice_params,
1753 +            .size = sizeof(controls->slice_params),
1754 +        },
1755 +        {
1756 +            .id = V4L2_CID_STATELESS_H264_PRED_WEIGHTS,
1757 +            .ptr = &controls->pred_weights,
1758 +            .size = sizeof(controls->pred_weights),
1759 +        },
1760 +    };
1761 +
1762 +    if (ctx->decode_mode == V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED) {
1763 +        int count = FF_ARRAY_ELEMS(control) - (controls->pred_weights_required ? 0 : 1);
1764 +        return ff_v4l2_request_decode_slice(avctx, h->cur_pic_ptr->f, control, count, controls->first_slice, last_slice);
1765 +    }
1766 +
1767 +    return ff_v4l2_request_decode_frame(avctx, h->cur_pic_ptr->f, control, FF_ARRAY_ELEMS(control) - 2);
1768 +}
1769 +
1770 +static int v4l2_request_h264_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)
1771 +{
1772 +    const H264Context *h = avctx->priv_data;
1773 +    const PPS *pps = h->ps.pps;
1774 +    const H264SliceContext *sl = &h->slice_ctx[0];
1775 +    V4L2RequestControlsH264 *controls = h->cur_pic_ptr->hwaccel_picture_private;
1776 +    V4L2RequestContextH264 *ctx = avctx->internal->hwaccel_priv_data;
1777 +    int i, ret, count;
1778 +
1779 +    if (ctx->decode_mode == V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED && controls->num_slices) {
1780 +        ret = v4l2_request_h264_queue_decode(avctx, 0);
1781 +        if (ret)
1782 +            return ret;
1783 +
1784 +        ff_v4l2_request_reset_frame(avctx, h->cur_pic_ptr->f);
1785 +        controls->first_slice = 0;
1786 +    }
1787 +
1788 +    if (ctx->start_code == V4L2_STATELESS_H264_START_CODE_ANNEX_B) {
1789 +        ret = ff_v4l2_request_append_output_buffer(avctx, h->cur_pic_ptr->f, nalu_slice_start_code, 3);
1790 +        if (ret)
1791 +            return ret;
1792 +    }
1793 +
1794 +    ret = ff_v4l2_request_append_output_buffer(avctx, h->cur_pic_ptr->f, buffer, size);
1795 +    if (ret)
1796 +        return ret;
1797 +
1798 +    if (ctx->decode_mode != V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED)
1799 +        return 0;
1800 +
1801 +    controls->slice_params = (struct v4l2_ctrl_h264_slice_params) {
1802 +        /* Offset in bits to slice_data() from the beginning of this slice. */
1803 +        .header_bit_size = get_bits_count(&sl->gb),
1804 +
1805 +        .first_mb_in_slice = sl->first_mb_addr,
1806 +
1807 +        .slice_type = ff_h264_get_slice_type(sl),
1808 +        .colour_plane_id = 0, /* separate colour plane not supported by FFmpeg */
1809 +        .redundant_pic_cnt = sl->redundant_pic_count,
1810 +        .cabac_init_idc = sl->cabac_init_idc,
1811 +        .slice_qp_delta = sl->qscale - pps->init_qp,
1812 +        .slice_qs_delta = 0, /* not implemented by FFmpeg */
1813 +        .disable_deblocking_filter_idc = sl->deblocking_filter < 2 ? !sl->deblocking_filter : sl->deblocking_filter,
1814 +        .slice_alpha_c0_offset_div2 = sl->slice_alpha_c0_offset / 2,
1815 +        .slice_beta_offset_div2 = sl->slice_beta_offset / 2,
1816 +        .num_ref_idx_l0_active_minus1 = sl->list_count > 0 ? sl->ref_count[0] - 1 : 0,
1817 +        .num_ref_idx_l1_active_minus1 = sl->list_count > 1 ? sl->ref_count[1] - 1 : 0,
1818 +    };
1819 +
1820 +    if (sl->slice_type == AV_PICTURE_TYPE_B && sl->direct_spatial_mv_pred)
1821 +        controls->slice_params.flags |= V4L2_H264_SLICE_FLAG_DIRECT_SPATIAL_MV_PRED;
1822 +    /* V4L2_H264_SLICE_FLAG_SP_FOR_SWITCH: not implemented by FFmpeg */
1823 +
1824 +    controls->pred_weights_required = V4L2_H264_CTRL_PRED_WEIGHTS_REQUIRED(&controls->pps, &controls->slice_params);
1825 +    if (controls->pred_weights_required) {
1826 +        controls->pred_weights.chroma_log2_weight_denom = sl->pwt.chroma_log2_weight_denom;
1827 +        controls->pred_weights.luma_log2_weight_denom = sl->pwt.luma_log2_weight_denom;
1828 +    }
1829 +
1830 +    count = sl->list_count > 0 ? sl->ref_count[0] : 0;
1831 +    for (i = 0; i < count; i++)
1832 +        fill_ref_list(&controls->slice_params.ref_pic_list0[i], &controls->decode_params, &sl->ref_list[0][i]);
1833 +    if (count && controls->pred_weights_required)
1834 +        fill_weight_factors(&controls->pred_weights.weight_factors[0], 0, sl);
1835 +
1836 +    count = sl->list_count > 1 ? sl->ref_count[1] : 0;
1837 +    for (i = 0; i < count; i++)
1838 +        fill_ref_list(&controls->slice_params.ref_pic_list1[i], &controls->decode_params, &sl->ref_list[1][i]);
1839 +    if (count && controls->pred_weights_required)
1840 +        fill_weight_factors(&controls->pred_weights.weight_factors[1], 1, sl);
1841 +
1842 +    controls->num_slices++;
1843 +    return 0;
1844 +}
1845 +
1846 +static int v4l2_request_h264_end_frame(AVCodecContext *avctx)
1847 +{
1848 +    const H264Context *h = avctx->priv_data;
1849 +    return v4l2_request_h264_queue_decode(avctx, !FIELD_PICTURE(h) || !h->first_field);
1850 +}
1851 +
1852 +static int v4l2_request_h264_set_controls(AVCodecContext *avctx)
1853 +{
1854 +    V4L2RequestContextH264 *ctx = avctx->internal->hwaccel_priv_data;
1855 +
1856 +    struct v4l2_ext_control control[] = {
1857 +        { .id = V4L2_CID_STATELESS_H264_DECODE_MODE, },
1858 +        { .id = V4L2_CID_STATELESS_H264_START_CODE, },
1859 +    };
1860 +
1861 +    ctx->decode_mode = ff_v4l2_request_query_control_default_value(avctx, V4L2_CID_STATELESS_H264_DECODE_MODE);
1862 +    if (ctx->decode_mode != V4L2_STATELESS_H264_DECODE_MODE_SLICE_BASED &&
1863 +        ctx->decode_mode != V4L2_STATELESS_H264_DECODE_MODE_FRAME_BASED) {
1864 +        av_log(avctx, AV_LOG_ERROR, "%s: unsupported decode mode, %d\n", __func__, ctx->decode_mode);
1865 +        return AVERROR(EINVAL);
1866 +    }
1867 +
1868 +    ctx->start_code = ff_v4l2_request_query_control_default_value(avctx, V4L2_CID_STATELESS_H264_START_CODE);
1869 +    if (ctx->start_code != V4L2_STATELESS_H264_START_CODE_NONE &&
1870 +        ctx->start_code != V4L2_STATELESS_H264_START_CODE_ANNEX_B) {
1871 +        av_log(avctx, AV_LOG_ERROR, "%s: unsupported start code, %d\n", __func__, ctx->start_code);
1872 +        return AVERROR(EINVAL);
1873 +    }
1874 +
1875 +    control[0].value = ctx->decode_mode;
1876 +    control[1].value = ctx->start_code;
1877 +
1878 +    return ff_v4l2_request_set_controls(avctx, control, FF_ARRAY_ELEMS(control));
1879 +}
1880 +
1881 +static int v4l2_request_h264_init(AVCodecContext *avctx)
1882 +{
1883 +    const H264Context *h = avctx->priv_data;
1884 +    struct v4l2_ctrl_h264_sps sps;
1885 +    int ret;
1886 +
1887 +    struct v4l2_ext_control control[] = {
1888 +        {
1889 +            .id = V4L2_CID_STATELESS_H264_SPS,
1890 +            .ptr = &sps,
1891 +            .size = sizeof(sps),
1892 +        },
1893 +    };
1894 +
1895 +    fill_sps(&sps, h);
1896 +
1897 +    ret = ff_v4l2_request_init(avctx, V4L2_PIX_FMT_H264_SLICE, 4 * 1024 * 1024, control, FF_ARRAY_ELEMS(control));
1898 +    if (ret)
1899 +        return ret;
1900 +
1901 +    return v4l2_request_h264_set_controls(avctx);
1902 +}
1903 +
1904 +const AVHWAccel ff_h264_v4l2request_hwaccel = {
1905 +    .name           = "h264_v4l2request",
1906 +    .type           = AVMEDIA_TYPE_VIDEO,
1907 +    .id             = AV_CODEC_ID_H264,
1908 +    .pix_fmt        = AV_PIX_FMT_DRM_PRIME,
1909 +    .start_frame    = v4l2_request_h264_start_frame,
1910 +    .decode_slice   = v4l2_request_h264_decode_slice,
1911 +    .end_frame      = v4l2_request_h264_end_frame,
1912 +    .frame_priv_data_size = sizeof(V4L2RequestControlsH264),
1913 +    .init           = v4l2_request_h264_init,
1914 +    .uninit         = ff_v4l2_request_uninit,
1915 +    .priv_data_size = sizeof(V4L2RequestContextH264),
1916 +    .frame_params   = ff_v4l2_request_frame_params,
1917 +    .caps_internal  = HWACCEL_CAP_ASYNC_SAFE,
1918 +};
1919
1920 From 02b8fb17c2a019463dcab4baa1cb0bec63353183 Mon Sep 17 00:00:00 2001
1921 From: Jonas Karlman <jonas@kwiboo.se>
1922 Date: Sat, 15 Dec 2018 22:32:16 +0100
1923 Subject: [PATCH 06/17] Add V4L2 request API mpeg2 hwaccel
1924
1925 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
1926 ---
1927  configure                       |   3 +
1928  libavcodec/Makefile             |   1 +
1929  libavcodec/hwaccels.h           |   1 +
1930  libavcodec/mpeg12dec.c          |   6 ++
1931  libavcodec/v4l2_request_mpeg2.c | 159 ++++++++++++++++++++++++++++++++
1932  5 files changed, 170 insertions(+)
1933  create mode 100644 libavcodec/v4l2_request_mpeg2.c
1934
1935 diff --git a/configure b/configure
1936 index b17e4108c1b..ec141fabbdc 100755
1937 --- a/configure
1938 +++ b/configure
1939 @@ -2995,6 +2995,8 @@ mpeg2_dxva2_hwaccel_deps="dxva2"
1940  mpeg2_dxva2_hwaccel_select="mpeg2video_decoder"
1941  mpeg2_nvdec_hwaccel_deps="nvdec"
1942  mpeg2_nvdec_hwaccel_select="mpeg2video_decoder"
1943 +mpeg2_v4l2request_hwaccel_deps="v4l2_request mpeg2_v4l2_request"
1944 +mpeg2_v4l2request_hwaccel_select="mpeg2video_decoder"
1945  mpeg2_vaapi_hwaccel_deps="vaapi"
1946  mpeg2_vaapi_hwaccel_select="mpeg2video_decoder"
1947  mpeg2_vdpau_hwaccel_deps="vdpau"
1948 @@ -6631,6 +6633,7 @@ fi
1949  
1950  check_func_headers "linux/media.h linux/videodev2.h" v4l2_timeval_to_ns
1951  check_cc h264_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_H264_SLICE;"
1952 +check_cc mpeg2_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_MPEG2_SLICE;"
1953  
1954  check_headers sys/videoio.h
1955  test_code cc sys/videoio.h "struct v4l2_frmsizeenum vfse; vfse.discrete.width = 0;" && enable_sanitized struct_v4l2_frmivalenum_discrete
1956 diff --git a/libavcodec/Makefile b/libavcodec/Makefile
1957 index 426c7528e90..02c023a4477 100644
1958 --- a/libavcodec/Makefile
1959 +++ b/libavcodec/Makefile
1960 @@ -955,6 +955,7 @@ OBJS-$(CONFIG_MPEG2_D3D11VA_HWACCEL)      += dxva2_mpeg2.o
1961  OBJS-$(CONFIG_MPEG2_DXVA2_HWACCEL)        += dxva2_mpeg2.o
1962  OBJS-$(CONFIG_MPEG2_NVDEC_HWACCEL)        += nvdec_mpeg12.o
1963  OBJS-$(CONFIG_MPEG2_QSV_HWACCEL)          += qsvdec.o
1964 +OBJS-$(CONFIG_MPEG2_V4L2REQUEST_HWACCEL)  += v4l2_request_mpeg2.o
1965  OBJS-$(CONFIG_MPEG2_VAAPI_HWACCEL)        += vaapi_mpeg2.o
1966  OBJS-$(CONFIG_MPEG2_VDPAU_HWACCEL)        += vdpau_mpeg12.o
1967  OBJS-$(CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o
1968 diff --git a/libavcodec/hwaccels.h b/libavcodec/hwaccels.h
1969 index 969a1da0f4b..a8ae1483d8e 100644
1970 --- a/libavcodec/hwaccels.h
1971 +++ b/libavcodec/hwaccels.h
1972 @@ -53,6 +53,7 @@ extern const AVHWAccel ff_mpeg2_d3d11va_hwaccel;
1973  extern const AVHWAccel ff_mpeg2_d3d11va2_hwaccel;
1974  extern const AVHWAccel ff_mpeg2_nvdec_hwaccel;
1975  extern const AVHWAccel ff_mpeg2_dxva2_hwaccel;
1976 +extern const AVHWAccel ff_mpeg2_v4l2request_hwaccel;
1977  extern const AVHWAccel ff_mpeg2_vaapi_hwaccel;
1978  extern const AVHWAccel ff_mpeg2_vdpau_hwaccel;
1979  extern const AVHWAccel ff_mpeg2_videotoolbox_hwaccel;
1980 diff --git a/libavcodec/mpeg12dec.c b/libavcodec/mpeg12dec.c
1981 index 94221da2c15..4b0176f6cb1 100644
1982 --- a/libavcodec/mpeg12dec.c
1983 +++ b/libavcodec/mpeg12dec.c
1984 @@ -1147,6 +1147,9 @@ static const enum AVPixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
1985  #endif
1986  #if CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL
1987      AV_PIX_FMT_VIDEOTOOLBOX,
1988 +#endif
1989 +#if CONFIG_MPEG2_V4L2REQUEST_HWACCEL
1990 +    AV_PIX_FMT_DRM_PRIME,
1991  #endif
1992      AV_PIX_FMT_YUV420P,
1993      AV_PIX_FMT_NONE
1994 @@ -2961,6 +2964,9 @@ AVCodec ff_mpeg2video_decoder = {
1995  #endif
1996  #if CONFIG_MPEG2_XVMC_HWACCEL
1997                          HWACCEL_XVMC(mpeg2),
1998 +#endif
1999 +#if CONFIG_MPEG2_V4L2REQUEST_HWACCEL
2000 +                        HWACCEL_V4L2REQUEST(mpeg2),
2001  #endif
2002                          NULL
2003                      },
2004 diff --git a/libavcodec/v4l2_request_mpeg2.c b/libavcodec/v4l2_request_mpeg2.c
2005 new file mode 100644
2006 index 00000000000..84d53209c79
2007 --- /dev/null
2008 +++ b/libavcodec/v4l2_request_mpeg2.c
2009 @@ -0,0 +1,159 @@
2010 +/*
2011 + * This file is part of FFmpeg.
2012 + *
2013 + * FFmpeg is free software; you can redistribute it and/or
2014 + * modify it under the terms of the GNU Lesser General Public
2015 + * License as published by the Free Software Foundation; either
2016 + * version 2.1 of the License, or (at your option) any later version.
2017 + *
2018 + * FFmpeg is distributed in the hope that it will be useful,
2019 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
2020 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
2021 + * Lesser General Public License for more details.
2022 + *
2023 + * You should have received a copy of the GNU Lesser General Public
2024 + * License along with FFmpeg; if not, write to the Free Software
2025 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2026 + */
2027 +
2028 +#include "hwconfig.h"
2029 +#include "mpegvideo.h"
2030 +#include "v4l2_request.h"
2031 +
2032 +typedef struct V4L2RequestControlsMPEG2 {
2033 +    struct v4l2_ctrl_mpeg2_sequence sequence;
2034 +    struct v4l2_ctrl_mpeg2_picture picture;
2035 +    struct v4l2_ctrl_mpeg2_quantisation quantisation;
2036 +} V4L2RequestControlsMPEG2;
2037 +
2038 +static int v4l2_request_mpeg2_start_frame(AVCodecContext *avctx,
2039 +                                          av_unused const uint8_t *buffer,
2040 +                                          av_unused uint32_t size)
2041 +{
2042 +    const MpegEncContext *s = avctx->priv_data;
2043 +    V4L2RequestControlsMPEG2 *controls = s->current_picture_ptr->hwaccel_picture_private;
2044 +    V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)s->current_picture_ptr->f->data[0];
2045 +
2046 +    controls->sequence = (struct v4l2_ctrl_mpeg2_sequence) {
2047 +        /* ISO/IEC 13818-2, ITU-T Rec. H.262: Sequence header */
2048 +        .horizontal_size = s->width,
2049 +        .vertical_size = s->height,
2050 +        .vbv_buffer_size = req->output.size,
2051 +
2052 +        /* ISO/IEC 13818-2, ITU-T Rec. H.262: Sequence extension */
2053 +        .profile_and_level_indication = 0,
2054 +        .chroma_format = s->chroma_format,
2055 +    };
2056 +
2057 +    if (s->progressive_sequence)
2058 +        controls->sequence.flags |= V4L2_MPEG2_SEQ_FLAG_PROGRESSIVE;
2059 +
2060 +    controls->picture = (struct v4l2_ctrl_mpeg2_picture) {
2061 +        /* ISO/IEC 13818-2, ITU-T Rec. H.262: Picture header */
2062 +        .picture_coding_type = s->pict_type,
2063 +
2064 +        /* ISO/IEC 13818-2, ITU-T Rec. H.262: Picture coding extension */
2065 +        .f_code[0][0] = s->mpeg_f_code[0][0],
2066 +        .f_code[0][1] = s->mpeg_f_code[0][1],
2067 +        .f_code[1][0] = s->mpeg_f_code[1][0],
2068 +        .f_code[1][1] = s->mpeg_f_code[1][1],
2069 +        .picture_structure = s->picture_structure,
2070 +        .intra_dc_precision = s->intra_dc_precision,
2071 +    };
2072 +
2073 +    if (s->top_field_first)
2074 +        controls->picture.flags |= V4L2_MPEG2_PIC_FLAG_TOP_FIELD_FIRST;
2075 +
2076 +    if (s->frame_pred_frame_dct)
2077 +        controls->picture.flags |= V4L2_MPEG2_PIC_FLAG_FRAME_PRED_DCT;
2078 +
2079 +    if (s->concealment_motion_vectors)
2080 +        controls->picture.flags |= V4L2_MPEG2_PIC_FLAG_CONCEALMENT_MV;
2081 +
2082 +    if (s->intra_vlc_format)
2083 +        controls->picture.flags |= V4L2_MPEG2_PIC_FLAG_INTRA_VLC;
2084 +
2085 +    if (s->q_scale_type)
2086 +        controls->picture.flags |= V4L2_MPEG2_PIC_FLAG_Q_SCALE_TYPE;
2087 +
2088 +    if (s->alternate_scan)
2089 +        controls->picture.flags |= V4L2_MPEG2_PIC_FLAG_ALT_SCAN;
2090 +
2091 +    if (s->repeat_first_field)
2092 +        controls->picture.flags |= V4L2_MPEG2_PIC_FLAG_REPEAT_FIRST;
2093 +
2094 +    if (s->progressive_frame)
2095 +        controls->picture.flags |= V4L2_MPEG2_PIC_FLAG_PROGRESSIVE;
2096 +
2097 +    switch (s->pict_type) {
2098 +    case AV_PICTURE_TYPE_B:
2099 +        controls->picture.backward_ref_ts = ff_v4l2_request_get_capture_timestamp(s->next_picture.f);
2100 +        // fall-through
2101 +    case AV_PICTURE_TYPE_P:
2102 +        controls->picture.forward_ref_ts = ff_v4l2_request_get_capture_timestamp(s->last_picture.f);
2103 +    }
2104 +
2105 +    for (int i = 0; i < 64; i++) {
2106 +        int n = s->idsp.idct_permutation[ff_zigzag_direct[i]];
2107 +        controls->quantisation.intra_quantiser_matrix[i] = s->intra_matrix[n];
2108 +        controls->quantisation.non_intra_quantiser_matrix[i] = s->inter_matrix[n];
2109 +        controls->quantisation.chroma_intra_quantiser_matrix[i] = s->chroma_intra_matrix[n];
2110 +        controls->quantisation.chroma_non_intra_quantiser_matrix[i] = s->chroma_inter_matrix[n];
2111 +    }
2112 +
2113 +    return ff_v4l2_request_reset_frame(avctx, s->current_picture_ptr->f);
2114 +}
2115 +
2116 +static int v4l2_request_mpeg2_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)
2117 +{
2118 +    const MpegEncContext *s = avctx->priv_data;
2119 +
2120 +    return ff_v4l2_request_append_output_buffer(avctx, s->current_picture_ptr->f, buffer, size);
2121 +}
2122 +
2123 +static int v4l2_request_mpeg2_end_frame(AVCodecContext *avctx)
2124 +{
2125 +    const MpegEncContext *s = avctx->priv_data;
2126 +    V4L2RequestControlsMPEG2 *controls = s->current_picture_ptr->hwaccel_picture_private;
2127 +
2128 +    struct v4l2_ext_control control[] = {
2129 +        {
2130 +            .id = V4L2_CID_STATELESS_MPEG2_SEQUENCE,
2131 +            .ptr = &controls->sequence,
2132 +            .size = sizeof(controls->sequence),
2133 +        },
2134 +        {
2135 +            .id = V4L2_CID_STATELESS_MPEG2_PICTURE,
2136 +            .ptr = &controls->picture,
2137 +            .size = sizeof(controls->picture),
2138 +        },
2139 +        {
2140 +            .id = V4L2_CID_STATELESS_MPEG2_QUANTISATION,
2141 +            .ptr = &controls->quantisation,
2142 +            .size = sizeof(controls->quantisation),
2143 +        },
2144 +    };
2145 +
2146 +    return ff_v4l2_request_decode_frame(avctx, s->current_picture_ptr->f, control, FF_ARRAY_ELEMS(control));
2147 +}
2148 +
2149 +static int v4l2_request_mpeg2_init(AVCodecContext *avctx)
2150 +{
2151 +    return ff_v4l2_request_init(avctx, V4L2_PIX_FMT_MPEG2_SLICE, 1024 * 1024, NULL, 0);
2152 +}
2153 +
2154 +const AVHWAccel ff_mpeg2_v4l2request_hwaccel = {
2155 +    .name           = "mpeg2_v4l2request",
2156 +    .type           = AVMEDIA_TYPE_VIDEO,
2157 +    .id             = AV_CODEC_ID_MPEG2VIDEO,
2158 +    .pix_fmt        = AV_PIX_FMT_DRM_PRIME,
2159 +    .start_frame    = v4l2_request_mpeg2_start_frame,
2160 +    .decode_slice   = v4l2_request_mpeg2_decode_slice,
2161 +    .end_frame      = v4l2_request_mpeg2_end_frame,
2162 +    .frame_priv_data_size = sizeof(V4L2RequestControlsMPEG2),
2163 +    .init           = v4l2_request_mpeg2_init,
2164 +    .uninit         = ff_v4l2_request_uninit,
2165 +    .priv_data_size = sizeof(V4L2RequestContext),
2166 +    .frame_params   = ff_v4l2_request_frame_params,
2167 +    .caps_internal  = HWACCEL_CAP_ASYNC_SAFE,
2168 +};
2169
2170 From 1cd61e5730acc12c39c964bcf13c73a54203a390 Mon Sep 17 00:00:00 2001
2171 From: Boris Brezillon <boris.brezillon@collabora.com>
2172 Date: Wed, 22 May 2019 14:46:58 +0200
2173 Subject: [PATCH 07/17] Add V4L2 request API vp8 hwaccel
2174
2175 Signed-off-by: Boris Brezillon <boris.brezillon@collabora.com>
2176 Signed-off-by: Ezequiel Garcia <ezequiel@collabora.com>
2177 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
2178 ---
2179  configure                     |   3 +
2180  libavcodec/Makefile           |   1 +
2181  libavcodec/hwaccels.h         |   1 +
2182  libavcodec/v4l2_request_vp8.c | 180 ++++++++++++++++++++++++++++++++++
2183  libavcodec/vp8.c              |   6 ++
2184  5 files changed, 191 insertions(+)
2185  create mode 100644 libavcodec/v4l2_request_vp8.c
2186
2187 diff --git a/configure b/configure
2188 index ec141fabbdc..f16bed65a3a 100755
2189 --- a/configure
2190 +++ b/configure
2191 @@ -3027,6 +3027,8 @@ vc1_vdpau_hwaccel_deps="vdpau"
2192  vc1_vdpau_hwaccel_select="vc1_decoder"
2193  vp8_nvdec_hwaccel_deps="nvdec"
2194  vp8_nvdec_hwaccel_select="vp8_decoder"
2195 +vp8_v4l2request_hwaccel_deps="v4l2_request vp8_v4l2_request"
2196 +vp8_v4l2request_hwaccel_select="vp8_decoder"
2197  vp8_vaapi_hwaccel_deps="vaapi"
2198  vp8_vaapi_hwaccel_select="vp8_decoder"
2199  vp9_d3d11va_hwaccel_deps="d3d11va DXVA_PicParams_VP9"
2200 @@ -6634,6 +6636,7 @@ fi
2201  check_func_headers "linux/media.h linux/videodev2.h" v4l2_timeval_to_ns
2202  check_cc h264_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_H264_SLICE;"
2203  check_cc mpeg2_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_MPEG2_SLICE;"
2204 +check_cc vp8_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_VP8_FRAME;"
2205  
2206  check_headers sys/videoio.h
2207  test_code cc sys/videoio.h "struct v4l2_frmsizeenum vfse; vfse.discrete.width = 0;" && enable_sanitized struct_v4l2_frmivalenum_discrete
2208 diff --git a/libavcodec/Makefile b/libavcodec/Makefile
2209 index 02c023a4477..c79d678eb3e 100644
2210 --- a/libavcodec/Makefile
2211 +++ b/libavcodec/Makefile
2212 @@ -971,6 +971,7 @@ OBJS-$(CONFIG_VC1_QSV_HWACCEL)            += qsvdec.o
2213  OBJS-$(CONFIG_VC1_VAAPI_HWACCEL)          += vaapi_vc1.o
2214  OBJS-$(CONFIG_VC1_VDPAU_HWACCEL)          += vdpau_vc1.o
2215  OBJS-$(CONFIG_VP8_NVDEC_HWACCEL)          += nvdec_vp8.o
2216 +OBJS-$(CONFIG_VP8_V4L2REQUEST_HWACCEL)    += v4l2_request_vp8.o
2217  OBJS-$(CONFIG_VP8_VAAPI_HWACCEL)          += vaapi_vp8.o
2218  OBJS-$(CONFIG_VP9_D3D11VA_HWACCEL)        += dxva2_vp9.o
2219  OBJS-$(CONFIG_VP9_DXVA2_HWACCEL)          += dxva2_vp9.o
2220 diff --git a/libavcodec/hwaccels.h b/libavcodec/hwaccels.h
2221 index a8ae1483d8e..9f8d41e367e 100644
2222 --- a/libavcodec/hwaccels.h
2223 +++ b/libavcodec/hwaccels.h
2224 @@ -69,6 +69,7 @@ extern const AVHWAccel ff_vc1_nvdec_hwaccel;
2225  extern const AVHWAccel ff_vc1_vaapi_hwaccel;
2226  extern const AVHWAccel ff_vc1_vdpau_hwaccel;
2227  extern const AVHWAccel ff_vp8_nvdec_hwaccel;
2228 +extern const AVHWAccel ff_vp8_v4l2request_hwaccel;
2229  extern const AVHWAccel ff_vp8_vaapi_hwaccel;
2230  extern const AVHWAccel ff_vp9_d3d11va_hwaccel;
2231  extern const AVHWAccel ff_vp9_d3d11va2_hwaccel;
2232 diff --git a/libavcodec/v4l2_request_vp8.c b/libavcodec/v4l2_request_vp8.c
2233 new file mode 100644
2234 index 00000000000..bc0fc400727
2235 --- /dev/null
2236 +++ b/libavcodec/v4l2_request_vp8.c
2237 @@ -0,0 +1,180 @@
2238 +/*
2239 + * This file is part of FFmpeg.
2240 + *
2241 + * FFmpeg is free software; you can redistribute it and/or
2242 + * modify it under the terms of the GNU Lesser General Public
2243 + * License as published by the Free Software Foundation; either
2244 + * version 2.1 of the License, or (at your option) any later version.
2245 + *
2246 + * FFmpeg is distributed in the hope that it will be useful,
2247 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
2248 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
2249 + * Lesser General Public License for more details.
2250 + *
2251 + * You should have received a copy of the GNU Lesser General Public
2252 + * License along with FFmpeg; if not, write to the Free Software
2253 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2254 + */
2255 +
2256 +#include "hwconfig.h"
2257 +#include "v4l2_request.h"
2258 +#include "vp8.h"
2259 +
2260 +typedef struct V4L2RequestControlsVP8 {
2261 +    struct v4l2_ctrl_vp8_frame ctrl;
2262 +} V4L2RequestControlsVP8;
2263 +
2264 +static int v4l2_request_vp8_start_frame(AVCodecContext          *avctx,
2265 +                                        av_unused const uint8_t *buffer,
2266 +                                        av_unused uint32_t       size)
2267 +{
2268 +    const VP8Context *s = avctx->priv_data;
2269 +    V4L2RequestControlsVP8 *controls = s->framep[VP56_FRAME_CURRENT]->hwaccel_picture_private;
2270 +
2271 +    memset(&controls->ctrl, 0, sizeof(controls->ctrl));
2272 +    return ff_v4l2_request_reset_frame(avctx, s->framep[VP56_FRAME_CURRENT]->tf.f);
2273 +}
2274 +
2275 +static int v4l2_request_vp8_end_frame(AVCodecContext *avctx)
2276 +{
2277 +    const VP8Context *s = avctx->priv_data;
2278 +    V4L2RequestControlsVP8 *controls = s->framep[VP56_FRAME_CURRENT]->hwaccel_picture_private;
2279 +    struct v4l2_ext_control control[] = {
2280 +        {
2281 +            .id = V4L2_CID_STATELESS_VP8_FRAME,
2282 +            .ptr = &controls->ctrl,
2283 +            .size = sizeof(controls->ctrl),
2284 +        },
2285 +    };
2286 +
2287 +    return ff_v4l2_request_decode_frame(avctx, s->framep[VP56_FRAME_CURRENT]->tf.f,
2288 +                                        control, FF_ARRAY_ELEMS(control));
2289 +}
2290 +
2291 +static int v4l2_request_vp8_decode_slice(AVCodecContext *avctx,
2292 +                                         const uint8_t *buffer,
2293 +                                         uint32_t size)
2294 +{
2295 +    const VP8Context *s = avctx->priv_data;
2296 +    V4L2RequestControlsVP8 *controls = s->framep[VP56_FRAME_CURRENT]->hwaccel_picture_private;
2297 +    struct v4l2_ctrl_vp8_frame *frame = &controls->ctrl;
2298 +    const uint8_t *data = buffer + 3 + 7 * s->keyframe;
2299 +    unsigned int i, j, k;
2300 +
2301 +    frame->version = s->profile & 0x3;
2302 +    frame->width = avctx->width;
2303 +    frame->height = avctx->height;
2304 +    /* FIXME: set ->xx_scale */
2305 +    frame->prob_skip_false = s->prob->mbskip;
2306 +    frame->prob_intra = s->prob->intra;
2307 +    frame->prob_gf = s->prob->golden;
2308 +    frame->prob_last = s->prob->last;
2309 +    frame->first_part_size = s->header_partition_size;
2310 +    frame->first_part_header_bits = (8 * (s->coder_state_at_header_end.input - data) -
2311 +                                    s->coder_state_at_header_end.bit_count - 8);
2312 +    frame->num_dct_parts = s->num_coeff_partitions;
2313 +    for (i = 0; i < 8; i++)
2314 +        frame->dct_part_sizes[i] = s->coeff_partition_size[i];
2315 +
2316 +    frame->coder_state.range = s->coder_state_at_header_end.range;
2317 +    frame->coder_state.value = s->coder_state_at_header_end.value;
2318 +    frame->coder_state.bit_count = s->coder_state_at_header_end.bit_count;
2319 +    if (s->framep[VP56_FRAME_PREVIOUS])
2320 +        frame->last_frame_ts = ff_v4l2_request_get_capture_timestamp(s->framep[VP56_FRAME_PREVIOUS]->tf.f);
2321 +    if (s->framep[VP56_FRAME_GOLDEN])
2322 +        frame->golden_frame_ts = ff_v4l2_request_get_capture_timestamp(s->framep[VP56_FRAME_GOLDEN]->tf.f);
2323 +    if (s->framep[VP56_FRAME_GOLDEN2])
2324 +        frame->alt_frame_ts = ff_v4l2_request_get_capture_timestamp(s->framep[VP56_FRAME_GOLDEN2]->tf.f);
2325 +    frame->flags |= s->invisible ? 0 : V4L2_VP8_FRAME_FLAG_SHOW_FRAME;
2326 +    frame->flags |= s->mbskip_enabled ? V4L2_VP8_FRAME_FLAG_MB_NO_SKIP_COEFF : 0;
2327 +    frame->flags |= (s->profile & 0x4) ? V4L2_VP8_FRAME_FLAG_EXPERIMENTAL : 0;
2328 +    frame->flags |= s->keyframe ? V4L2_VP8_FRAME_FLAG_KEY_FRAME : 0;
2329 +    frame->flags |= s->sign_bias[VP56_FRAME_GOLDEN] ? V4L2_VP8_FRAME_FLAG_SIGN_BIAS_GOLDEN : 0;
2330 +    frame->flags |= s->sign_bias[VP56_FRAME_GOLDEN2] ? V4L2_VP8_FRAME_FLAG_SIGN_BIAS_ALT : 0;
2331 +    frame->segment.flags |= s->segmentation.enabled ? V4L2_VP8_SEGMENT_FLAG_ENABLED : 0;
2332 +    frame->segment.flags |= s->segmentation.update_map ? V4L2_VP8_SEGMENT_FLAG_UPDATE_MAP : 0;
2333 +    frame->segment.flags |= s->segmentation.update_feature_data ? V4L2_VP8_SEGMENT_FLAG_UPDATE_FEATURE_DATA : 0;
2334 +    frame->segment.flags |= s->segmentation.absolute_vals ? 0 : V4L2_VP8_SEGMENT_FLAG_DELTA_VALUE_MODE;
2335 +    for (i = 0; i < 4; i++) {
2336 +        frame->segment.quant_update[i] = s->segmentation.base_quant[i];
2337 +        frame->segment.lf_update[i] = s->segmentation.filter_level[i];
2338 +    }
2339 +
2340 +    for (i = 0; i < 3; i++)
2341 +        frame->segment.segment_probs[i] = s->prob->segmentid[i];
2342 +
2343 +    frame->lf.level = s->filter.level;
2344 +    frame->lf.sharpness_level = s->filter.sharpness;
2345 +    frame->lf.flags |= s->lf_delta.enabled ? V4L2_VP8_LF_ADJ_ENABLE : 0;
2346 +    frame->lf.flags |= s->lf_delta.update ? V4L2_VP8_LF_DELTA_UPDATE : 0;
2347 +    frame->lf.flags |= s->filter.simple ? V4L2_VP8_LF_FILTER_TYPE_SIMPLE : 0;
2348 +    for (i = 0; i < 4; i++) {
2349 +        frame->lf.ref_frm_delta[i] = s->lf_delta.ref[i];
2350 +        frame->lf.mb_mode_delta[i] = s->lf_delta.mode[i + MODE_I4x4];
2351 +    }
2352 +
2353 +    // Probabilites
2354 +    if (s->keyframe) {
2355 +        static const uint8_t keyframe_y_mode_probs[4] = {
2356 +            145, 156, 163, 128
2357 +        };
2358 +        static const uint8_t keyframe_uv_mode_probs[3] = {
2359 +            142, 114, 183
2360 +        };
2361 +
2362 +        memcpy(frame->entropy.y_mode_probs, keyframe_y_mode_probs,  4);
2363 +        memcpy(frame->entropy.uv_mode_probs, keyframe_uv_mode_probs, 3);
2364 +    } else {
2365 +        for (i = 0; i < 4; i++)
2366 +            frame->entropy.y_mode_probs[i] = s->prob->pred16x16[i];
2367 +        for (i = 0; i < 3; i++)
2368 +            frame->entropy.uv_mode_probs[i] = s->prob->pred8x8c[i];
2369 +    }
2370 +    for (i = 0; i < 2; i++)
2371 +        for (j = 0; j < 19; j++)
2372 +            frame->entropy.mv_probs[i][j] = s->prob->mvc[i][j];
2373 +
2374 +    for (i = 0; i < 4; i++) {
2375 +        for (j = 0; j < 8; j++) {
2376 +            static const int coeff_bands_inverse[8] = {
2377 +                0, 1, 2, 3, 5, 6, 4, 15
2378 +            };
2379 +            int coeff_pos = coeff_bands_inverse[j];
2380 +
2381 +            for (k = 0; k < 3; k++) {
2382 +                memcpy(frame->entropy.coeff_probs[i][j][k],
2383 +                       s->prob->token[i][coeff_pos][k], 11);
2384 +            }
2385 +        }
2386 +    }
2387 +
2388 +    frame->quant.y_ac_qi = s->quant.yac_qi;
2389 +    frame->quant.y_dc_delta = s->quant.ydc_delta;
2390 +    frame->quant.y2_dc_delta = s->quant.y2dc_delta;
2391 +    frame->quant.y2_ac_delta = s->quant.y2ac_delta;
2392 +    frame->quant.uv_dc_delta = s->quant.uvdc_delta;
2393 +    frame->quant.uv_ac_delta = s->quant.uvac_delta;
2394 +
2395 +    return ff_v4l2_request_append_output_buffer(avctx, s->framep[VP56_FRAME_CURRENT]->tf.f, buffer, size);
2396 +}
2397 +
2398 +static int v4l2_request_vp8_init(AVCodecContext *avctx)
2399 +{
2400 +    return ff_v4l2_request_init(avctx, V4L2_PIX_FMT_VP8_FRAME, 2 * 1024 * 1024, NULL, 0);
2401 +}
2402 +
2403 +const AVHWAccel ff_vp8_v4l2request_hwaccel = {
2404 +    .name           = "vp8_v4l2request",
2405 +    .type           = AVMEDIA_TYPE_VIDEO,
2406 +    .id             = AV_CODEC_ID_VP8,
2407 +    .pix_fmt        = AV_PIX_FMT_DRM_PRIME,
2408 +    .start_frame    = v4l2_request_vp8_start_frame,
2409 +    .decode_slice   = v4l2_request_vp8_decode_slice,
2410 +    .end_frame      = v4l2_request_vp8_end_frame,
2411 +    .frame_priv_data_size = sizeof(V4L2RequestControlsVP8),
2412 +    .init           = v4l2_request_vp8_init,
2413 +    .uninit         = ff_v4l2_request_uninit,
2414 +    .priv_data_size = sizeof(V4L2RequestContext),
2415 +    .frame_params   = ff_v4l2_request_frame_params,
2416 +    .caps_internal  = HWACCEL_CAP_ASYNC_SAFE,
2417 +};
2418 diff --git a/libavcodec/vp8.c b/libavcodec/vp8.c
2419 index d16e7b6aa34..8ee768d875a 100644
2420 --- a/libavcodec/vp8.c
2421 +++ b/libavcodec/vp8.c
2422 @@ -176,6 +176,9 @@ static enum AVPixelFormat get_pixel_format(VP8Context *s)
2423  #endif
2424  #if CONFIG_VP8_NVDEC_HWACCEL
2425          AV_PIX_FMT_CUDA,
2426 +#endif
2427 +#if CONFIG_VP8_V4L2REQUEST_HWACCEL
2428 +        AV_PIX_FMT_DRM_PRIME,
2429  #endif
2430          AV_PIX_FMT_YUV420P,
2431          AV_PIX_FMT_NONE,
2432 @@ -2972,6 +2975,9 @@ AVCodec ff_vp8_decoder = {
2433  #endif
2434  #if CONFIG_VP8_NVDEC_HWACCEL
2435                                 HWACCEL_NVDEC(vp8),
2436 +#endif
2437 +#if CONFIG_VP8_V4L2REQUEST_HWACCEL
2438 +                               HWACCEL_V4L2REQUEST(vp8),
2439  #endif
2440                                 NULL
2441                             },
2442
2443 From 3c9c4c99eccdda102064ea67a04c8cbf8083ad1a Mon Sep 17 00:00:00 2001
2444 From: Boris Brezillon <boris.brezillon@collabora.com>
2445 Date: Thu, 12 Dec 2019 16:13:55 +0100
2446 Subject: [PATCH 09/17] Add V4L2 request API VP9 hwaccel
2447
2448 Signed-off-by: Boris Brezillon <boris.brezillon@collabora.com>
2449 Signed-off-by: Jernej Skrabec <jernej.skrabec@gmail.com>
2450 ---
2451  configure                     |   3 +
2452  libavcodec/Makefile           |   1 +
2453  libavcodec/hwaccels.h         |   1 +
2454  libavcodec/v4l2_request_vp9.c | 268 ++++++++++++++++++++++++++++++++++
2455  libavcodec/vp9.c              | 192 +++++++++++++++++-------
2456  libavcodec/vp9dec.h           |   4 +
2457  libavcodec/vp9shared.h        |   1 +
2458  7 files changed, 415 insertions(+), 55 deletions(-)
2459  create mode 100644 libavcodec/v4l2_request_vp9.c
2460
2461 diff --git a/configure b/configure
2462 index 02a80cf27fd..0b238c051df 100755
2463 --- a/configure
2464 +++ b/configure
2465 @@ -3041,6 +3041,8 @@ vp9_dxva2_hwaccel_deps="dxva2 DXVA_PicParams_VP9"
2466  vp9_dxva2_hwaccel_select="vp9_decoder"
2467  vp9_nvdec_hwaccel_deps="nvdec"
2468  vp9_nvdec_hwaccel_select="vp9_decoder"
2469 +vp9_v4l2request_hwaccel_deps="v4l2_request"
2470 +vp9_v4l2request_hwaccel_select="vp9_decoder"
2471  vp9_vaapi_hwaccel_deps="vaapi VADecPictureParameterBufferVP9_bit_depth"
2472  vp9_vaapi_hwaccel_select="vp9_decoder"
2473  vp9_vdpau_hwaccel_deps="vdpau VdpPictureInfoVP9"
2474 @@ -6640,6 +6642,7 @@ check_cc h264_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_H264_SLICE;"
2475  check_cc h264_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_H264_SLICE;"
2476  check_cc mpeg2_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_MPEG2_SLICE;"
2477  check_cc vp8_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_VP8_FRAME;"
2478 +check_cc vp9_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_VP9_FRAME;"
2479  
2480  check_headers sys/videoio.h
2481  test_code cc sys/videoio.h "struct v4l2_frmsizeenum vfse; vfse.discrete.width = 0;" && enable_sanitized struct_v4l2_frmivalenum_discrete
2482 diff --git a/libavcodec/Makefile b/libavcodec/Makefile
2483 index 0059074530c..38edf1cfe5e 100644
2484 --- a/libavcodec/Makefile
2485 +++ b/libavcodec/Makefile
2486 @@ -977,6 +977,7 @@ OBJS-$(CONFIG_VP8_VAAPI_HWACCEL)          += vaapi_vp8.o
2487  OBJS-$(CONFIG_VP9_D3D11VA_HWACCEL)        += dxva2_vp9.o
2488  OBJS-$(CONFIG_VP9_DXVA2_HWACCEL)          += dxva2_vp9.o
2489  OBJS-$(CONFIG_VP9_NVDEC_HWACCEL)          += nvdec_vp9.o
2490 +OBJS-$(CONFIG_VP9_V4L2REQUEST_HWACCEL)    += v4l2_request_vp9.o
2491  OBJS-$(CONFIG_VP9_VAAPI_HWACCEL)          += vaapi_vp9.o
2492  OBJS-$(CONFIG_VP9_VDPAU_HWACCEL)          += vdpau_vp9.o
2493  OBJS-$(CONFIG_VP8_QSV_HWACCEL)            += qsvdec.o
2494 diff --git a/libavcodec/hwaccels.h b/libavcodec/hwaccels.h
2495 index ffb9fa5087d..fc5d0b0479b 100644
2496 --- a/libavcodec/hwaccels.h
2497 +++ b/libavcodec/hwaccels.h
2498 @@ -76,6 +76,7 @@ extern const AVHWAccel ff_vp9_d3d11va_hwaccel;
2499  extern const AVHWAccel ff_vp9_d3d11va2_hwaccel;
2500  extern const AVHWAccel ff_vp9_dxva2_hwaccel;
2501  extern const AVHWAccel ff_vp9_nvdec_hwaccel;
2502 +extern const AVHWAccel ff_vp9_v4l2request_hwaccel;
2503  extern const AVHWAccel ff_vp9_vaapi_hwaccel;
2504  extern const AVHWAccel ff_vp9_vdpau_hwaccel;
2505  extern const AVHWAccel ff_wmv3_d3d11va_hwaccel;
2506 diff --git a/libavcodec/v4l2_request_vp9.c b/libavcodec/v4l2_request_vp9.c
2507 new file mode 100644
2508 index 00000000000..9b95c76cdb8
2509 --- /dev/null
2510 +++ b/libavcodec/v4l2_request_vp9.c
2511 @@ -0,0 +1,268 @@
2512 +/*
2513 + * This file is part of FFmpeg.
2514 + *
2515 + * FFmpeg is free software; you can redistribute it and/or
2516 + * modify it under the terms of the GNU Lesser General Public
2517 + * License as published by the Free Software Foundation; either
2518 + * version 2.1 of the License, or (at your option) any later version.
2519 + *
2520 + * FFmpeg is distributed in the hope that it will be useful,
2521 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
2522 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
2523 + * Lesser General Public License for more details.
2524 + *
2525 + * You should have received a copy of the GNU Lesser General Public
2526 + * License along with FFmpeg; if not, write to the Free Software
2527 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
2528 + */
2529 +
2530 +#include "hwconfig.h"
2531 +#include "v4l2_request.h"
2532 +#include "vp9dec.h"
2533 +
2534 +typedef struct V4L2RequestControlsVP9 {
2535 +    struct v4l2_ctrl_vp9_frame decode_params;
2536 +} V4L2RequestControlsVP9;
2537 +
2538 +static int v4l2_request_vp9_set_frame_ctx(AVCodecContext *avctx)
2539 +{
2540 +    VP9Context *s = avctx->priv_data;
2541 +    struct v4l2_ctrl_vp9_compressed_hdr chp;
2542 +    struct v4l2_ext_control control[] = {
2543 +        {
2544 +            .id = V4L2_CID_STATELESS_VP9_COMPRESSED_HDR,
2545 +            .ptr = &chp,
2546 +            .size = sizeof(chp),
2547 +        },
2548 +    };
2549 +
2550 +    memset(&chp, 0, sizeof(chp));
2551 +
2552 +    chp.tx_mode = s->s.h.txfmmode;
2553 +    memcpy(chp.tx8, s->prob_raw.p.tx8p, sizeof(s->prob_raw.p.tx8p));
2554 +    memcpy(chp.tx16, s->prob_raw.p.tx16p, sizeof(s->prob_raw.p.tx16p));
2555 +    memcpy(chp.tx32, s->prob_raw.p.tx32p, sizeof(s->prob_raw.p.tx32p));
2556 +    for (unsigned i = 0; i < 4; i++) {
2557 +        for (unsigned j = 0; j < 2; j++) {
2558 +            for (unsigned k = 0; k < 2; k++) {
2559 +                for (unsigned l = 0; l < 6; l++) {
2560 +                    for (unsigned m = 0; m < 6; m++) {
2561 +                        memcpy(chp.coef[i][j][k][l][m], s->prob_raw.coef[i][j][k][l][m], sizeof(chp.coef[0][0][0][0][0]));
2562 +                    }
2563 +                }
2564 +            }
2565 +        }
2566 +    }
2567 +    memcpy(chp.skip, s->prob_raw.p.skip, sizeof(s->prob_raw.p.skip));
2568 +    memcpy(chp.inter_mode, s->prob_raw.p.mv_mode, sizeof(s->prob_raw.p.mv_mode));
2569 +    memcpy(chp.interp_filter, s->prob_raw.p.filter, sizeof(s->prob_raw.p.filter));
2570 +    memcpy(chp.is_inter, s->prob_raw.p.intra, sizeof(s->prob_raw.p.intra));
2571 +    memcpy(chp.comp_mode, s->prob_raw.p.comp, sizeof(s->prob_raw.p.comp));
2572 +    memcpy(chp.single_ref, s->prob_raw.p.single_ref, sizeof(s->prob_raw.p.single_ref));
2573 +    memcpy(chp.comp_ref, s->prob_raw.p.comp_ref, sizeof(s->prob_raw.p.comp_ref));
2574 +    memcpy(chp.y_mode, s->prob_raw.p.y_mode, sizeof(s->prob_raw.p.y_mode));
2575 +    for (unsigned i = 0; i < 10; i++)
2576 +        memcpy(chp.uv_mode[i], s->prob.p.uv_mode[i], sizeof(s->prob.p.uv_mode[0]));
2577 +    for (unsigned i = 0; i < 4; i++)
2578 +        memcpy(chp.partition[i * 4], s->prob_raw.p.partition[i], sizeof(s->prob_raw.p.partition[0]));
2579 +    memcpy(chp.mv.joint, s->prob_raw.p.mv_joint, sizeof(s->prob_raw.p.mv_joint));
2580 +    for (unsigned i = 0; i < 2; i++) {
2581 +         chp.mv.sign[i] = s->prob_raw.p.mv_comp[i].sign;
2582 +         memcpy(chp.mv.classes[i], s->prob_raw.p.mv_comp[i].classes, sizeof(s->prob_raw.p.mv_comp[0].classes));
2583 +         chp.mv.class0_bit[i] = s->prob_raw.p.mv_comp[i].class0;
2584 +         memcpy(chp.mv.bits[i], s->prob_raw.p.mv_comp[i].bits, sizeof(s->prob_raw.p.mv_comp[0].bits));
2585 +         memcpy(chp.mv.class0_fr[i], s->prob_raw.p.mv_comp[i].class0_fp, sizeof(s->prob_raw.p.mv_comp[0].class0_fp));
2586 +         memcpy(chp.mv.fr[i], s->prob_raw.p.mv_comp[i].fp, sizeof(s->prob_raw.p.mv_comp[0].fp));
2587 +         chp.mv.class0_hp[i] = s->prob_raw.p.mv_comp[i].class0_hp;
2588 +         chp.mv.hp[i] = s->prob_raw.p.mv_comp[i].hp;
2589 +    }
2590 +
2591 +    return ff_v4l2_request_set_controls(avctx, control, FF_ARRAY_ELEMS(control));
2592 +}
2593 +
2594 +static int v4l2_request_vp9_start_frame(AVCodecContext *avctx,
2595 +                                        av_unused const uint8_t *buffer,
2596 +                                        av_unused uint32_t size)
2597 +{
2598 +    const VP9Context *s = avctx->priv_data;
2599 +    const VP9Frame *f = &s->s.frames[CUR_FRAME];
2600 +    V4L2RequestControlsVP9 *controls = f->hwaccel_picture_private;
2601 +    struct v4l2_ctrl_vp9_frame *dec_params = &controls->decode_params;
2602 +    const ThreadFrame *ref;
2603 +    int ret;
2604 +
2605 +    ret = v4l2_request_vp9_set_frame_ctx(avctx);
2606 +    if (ret)
2607 +       return ret;
2608 +
2609 +    memset(dec_params, 0, sizeof(*dec_params));
2610 +
2611 +    if (s->s.h.keyframe)
2612 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_KEY_FRAME;
2613 +    if (!s->s.h.invisible)
2614 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_SHOW_FRAME;
2615 +    if (s->s.h.errorres)
2616 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_ERROR_RESILIENT;
2617 +    if (s->s.h.intraonly)
2618 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_INTRA_ONLY;
2619 +    if (!s->s.h.keyframe && s->s.h.highprecisionmvs)
2620 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_ALLOW_HIGH_PREC_MV;
2621 +    if (s->s.h.refreshctx)
2622 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_REFRESH_FRAME_CTX;
2623 +    if (s->s.h.parallelmode)
2624 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_PARALLEL_DEC_MODE;
2625 +    if (s->ss_h)
2626 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_X_SUBSAMPLING;
2627 +    if (s->ss_v)
2628 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_Y_SUBSAMPLING;
2629 +    if (avctx->color_range == AVCOL_RANGE_JPEG)
2630 +        dec_params->flags |= V4L2_VP9_FRAME_FLAG_COLOR_RANGE_FULL_SWING;
2631 +
2632 +    dec_params->compressed_header_size = s->s.h.compressed_header_size;
2633 +    dec_params->uncompressed_header_size = s->s.h.uncompressed_header_size;
2634 +    dec_params->profile = s->s.h.profile;
2635 +    dec_params->reset_frame_context = s->s.h.resetctx > 0 ? s->s.h.resetctx - 1 : 0;
2636 +    dec_params->frame_context_idx = s->s.h.framectxid;
2637 +    dec_params->bit_depth = s->s.h.bpp;
2638 +
2639 +    dec_params->interpolation_filter = s->s.h.filtermode ^ (s->s.h.filtermode <= 1);
2640 +    dec_params->tile_cols_log2 = s->s.h.tiling.log2_tile_cols;
2641 +    dec_params->tile_rows_log2 = s->s.h.tiling.log2_tile_rows;
2642 +    dec_params->reference_mode = s->s.h.comppredmode;
2643 +    dec_params->frame_width_minus_1 = s->w - 1;
2644 +    dec_params->frame_height_minus_1 = s->h - 1;
2645 +    //dec_params->render_width_minus_1 = avctx->width - 1;
2646 +    //dec_params->render_height_minus_1 = avctx->height - 1;
2647 +
2648 +    ref = &s->s.refs[s->s.h.refidx[0]];
2649 +    if (ref->f && ref->f->buf[0])
2650 +        dec_params->last_frame_ts = ff_v4l2_request_get_capture_timestamp(ref->f);
2651 +    ref = &s->s.refs[s->s.h.refidx[1]];
2652 +    if (ref->f && ref->f->buf[0])
2653 +        dec_params->golden_frame_ts = ff_v4l2_request_get_capture_timestamp(ref->f);
2654 +    ref = &s->s.refs[s->s.h.refidx[2]];
2655 +    if (ref->f && ref->f->buf[0])
2656 +        dec_params->alt_frame_ts = ff_v4l2_request_get_capture_timestamp(ref->f);
2657 +
2658 +    if (s->s.h.signbias[0])
2659 +        dec_params->ref_frame_sign_bias |= V4L2_VP9_SIGN_BIAS_LAST;
2660 +    if (s->s.h.signbias[1])
2661 +        dec_params->ref_frame_sign_bias |= V4L2_VP9_SIGN_BIAS_GOLDEN;
2662 +    if (s->s.h.signbias[2])
2663 +        dec_params->ref_frame_sign_bias |= V4L2_VP9_SIGN_BIAS_ALT;
2664 +
2665 +    if (s->s.h.lf_delta.enabled)
2666 +        dec_params->lf.flags |= V4L2_VP9_LOOP_FILTER_FLAG_DELTA_ENABLED;
2667 +    if (s->s.h.lf_delta.updated)
2668 +        dec_params->lf.flags |= V4L2_VP9_LOOP_FILTER_FLAG_DELTA_UPDATE;
2669 +
2670 +    dec_params->lf.level = s->s.h.filter.level;
2671 +    dec_params->lf.sharpness = s->s.h.filter.sharpness;
2672 +    for (unsigned i = 0; i < 4; i++)
2673 +        dec_params->lf.ref_deltas[i] = s->s.h.lf_delta.ref[i];
2674 +    for (unsigned i = 0; i < 2; i++)
2675 +        dec_params->lf.mode_deltas[i] = s->s.h.lf_delta.mode[i];
2676 +
2677 +    dec_params->quant.base_q_idx = s->s.h.yac_qi;
2678 +    dec_params->quant.delta_q_y_dc = s->s.h.ydc_qdelta;
2679 +    dec_params->quant.delta_q_uv_dc = s->s.h.uvdc_qdelta;
2680 +    dec_params->quant.delta_q_uv_ac = s->s.h.uvac_qdelta;
2681 +
2682 +    if (s->s.h.segmentation.enabled)
2683 +        dec_params->seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_ENABLED;
2684 +    if (s->s.h.segmentation.update_map)
2685 +        dec_params->seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_UPDATE_MAP;
2686 +    if (s->s.h.segmentation.temporal)
2687 +        dec_params->seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_TEMPORAL_UPDATE;
2688 +    if (s->s.h.segmentation.update_data)
2689 +        dec_params->seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_UPDATE_DATA;
2690 +    if (s->s.h.segmentation.absolute_vals)
2691 +        dec_params->seg.flags |= V4L2_VP9_SEGMENTATION_FLAG_ABS_OR_DELTA_UPDATE;
2692 +
2693 +    for (unsigned i = 0; i < 7; i++)
2694 +        dec_params->seg.tree_probs[i] = s->s.h.segmentation.prob[i];
2695 +
2696 +    if (s->s.h.segmentation.temporal) {
2697 +        for (unsigned i = 0; i < 3; i++)
2698 +            dec_params->seg.pred_probs[i] = s->s.h.segmentation.pred_prob[i];
2699 +    } else {
2700 +        memset(dec_params->seg.pred_probs, 255, sizeof(dec_params->seg.pred_probs));
2701 +    }
2702 +
2703 +    for (unsigned i = 0; i < 8; i++) {
2704 +        if (s->s.h.segmentation.feat[i].q_enabled) {
2705 +            dec_params->seg.feature_enabled[i] |= 1 << V4L2_VP9_SEG_LVL_ALT_Q;
2706 +            dec_params->seg.feature_data[i][V4L2_VP9_SEG_LVL_ALT_Q] = s->s.h.segmentation.feat[i].q_val;
2707 +        }
2708 +
2709 +        if (s->s.h.segmentation.feat[i].lf_enabled) {
2710 +            dec_params->seg.feature_enabled[i] |= 1 << V4L2_VP9_SEG_LVL_ALT_L;
2711 +            dec_params->seg.feature_data[i][V4L2_VP9_SEG_LVL_ALT_L] = s->s.h.segmentation.feat[i].lf_val;
2712 +        }
2713 +
2714 +        if (s->s.h.segmentation.feat[i].ref_enabled) {
2715 +            dec_params->seg.feature_enabled[i] |= 1 << V4L2_VP9_SEG_LVL_REF_FRAME;
2716 +            dec_params->seg.feature_data[i][V4L2_VP9_SEG_LVL_REF_FRAME] = s->s.h.segmentation.feat[i].ref_val;
2717 +        }
2718 +
2719 +        if (s->s.h.segmentation.feat[i].skip_enabled)
2720 +            dec_params->seg.feature_enabled[i] |= 1 << V4L2_VP9_SEG_LVL_SKIP;
2721 +    }
2722 +
2723 +    return ff_v4l2_request_reset_frame(avctx, f->tf.f);
2724 +}
2725 +
2726 +static int v4l2_request_vp9_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)
2727 +{
2728 +    const VP9Context *s = avctx->priv_data;
2729 +    const VP9Frame *f = &s->s.frames[CUR_FRAME];
2730 +
2731 +    return ff_v4l2_request_append_output_buffer(avctx, f->tf.f, buffer, size);
2732 +}
2733 +
2734 +static int v4l2_request_vp9_end_frame(AVCodecContext *avctx)
2735 +{
2736 +    const VP9Context *s = avctx->priv_data;
2737 +    const VP9Frame *f = &s->s.frames[CUR_FRAME];
2738 +    V4L2RequestControlsVP9 *controls = f->hwaccel_picture_private;
2739 +    int ret;
2740 +
2741 +    struct v4l2_ext_control control[] = {
2742 +        {
2743 +            .id = V4L2_CID_STATELESS_VP9_FRAME,
2744 +            .ptr = &controls->decode_params,
2745 +            .size = sizeof(controls->decode_params),
2746 +        },
2747 +    };
2748 +
2749 +    ret = ff_v4l2_request_decode_frame(avctx, f->tf.f, control, FF_ARRAY_ELEMS(control));
2750 +    if (ret)
2751 +        return ret;
2752 +
2753 +    if (!s->s.h.refreshctx)
2754 +        return 0;
2755 +
2756 +    return 0;
2757 +}
2758 +
2759 +static int v4l2_request_vp9_init(AVCodecContext *avctx)
2760 +{
2761 +    // TODO: check V4L2_CID_MPEG_VIDEO_VP9_PROFILE
2762 +    return ff_v4l2_request_init(avctx, V4L2_PIX_FMT_VP9_FRAME, 3 * 1024 * 1024, NULL, 0);
2763 +}
2764 +
2765 +const AVHWAccel ff_vp9_v4l2request_hwaccel = {
2766 +    .name           = "vp9_v4l2request",
2767 +    .type           = AVMEDIA_TYPE_VIDEO,
2768 +    .id             = AV_CODEC_ID_VP9,
2769 +    .pix_fmt        = AV_PIX_FMT_DRM_PRIME,
2770 +    .start_frame    = v4l2_request_vp9_start_frame,
2771 +    .decode_slice   = v4l2_request_vp9_decode_slice,
2772 +    .end_frame      = v4l2_request_vp9_end_frame,
2773 +    .frame_priv_data_size = sizeof(V4L2RequestControlsVP9),
2774 +    .init           = v4l2_request_vp9_init,
2775 +    .uninit         = ff_v4l2_request_uninit,
2776 +    .priv_data_size = sizeof(V4L2RequestContext),
2777 +    .frame_params   = ff_v4l2_request_frame_params,
2778 +    .caps_internal  = HWACCEL_CAP_ASYNC_SAFE,
2779 +};
2780 diff --git a/libavcodec/vp9.c b/libavcodec/vp9.c
2781 index 4659f94ee8b..1b2f1eeaf69 100644
2782 --- a/libavcodec/vp9.c
2783 +++ b/libavcodec/vp9.c
2784 @@ -191,6 +191,7 @@ static int update_size(AVCodecContext *avctx, int w, int h)
2785  #define HWACCEL_MAX (CONFIG_VP9_DXVA2_HWACCEL + \
2786                       CONFIG_VP9_D3D11VA_HWACCEL * 2 + \
2787                       CONFIG_VP9_NVDEC_HWACCEL + \
2788 +                     CONFIG_VP9_V4L2REQUEST_HWACCEL + \
2789                       CONFIG_VP9_VAAPI_HWACCEL + \
2790                       CONFIG_VP9_VDPAU_HWACCEL)
2791      enum AVPixelFormat pix_fmts[HWACCEL_MAX + 2], *fmtp = pix_fmts;
2792 @@ -223,6 +224,9 @@ static int update_size(AVCodecContext *avctx, int w, int h)
2793  #endif
2794  #if CONFIG_VP9_VDPAU_HWACCEL
2795              *fmtp++ = AV_PIX_FMT_VDPAU;
2796 +#endif
2797 +#if CONFIG_VP9_V4L2REQUEST_HWACCEL
2798 +            *fmtp++ = AV_PIX_FMT_DRM_PRIME;
2799  #endif
2800              break;
2801          case AV_PIX_FMT_YUV420P12:
2802 @@ -234,6 +238,9 @@ static int update_size(AVCodecContext *avctx, int w, int h)
2803  #endif
2804  #if CONFIG_VP9_VDPAU_HWACCEL
2805              *fmtp++ = AV_PIX_FMT_VDPAU;
2806 +#endif
2807 +#if CONFIG_VP9_V4L2REQUEST_HWACCEL
2808 +            *fmtp++ = AV_PIX_FMT_DRM_PRIME;
2809  #endif
2810              break;
2811          }
2812 @@ -382,7 +389,7 @@ static av_always_inline int inv_recenter_nonneg(int v, int m)
2813  }
2814  
2815  // differential forward probability updates
2816 -static int update_prob(VP56RangeCoder *c, int p)
2817 +static int read_prob_delta(VP56RangeCoder *c)
2818  {
2819      static const uint8_t inv_map_table[255] = {
2820            7,  20,  33,  46,  59,  72,  85,  98, 111, 124, 137, 150, 163, 176,
2821 @@ -436,8 +443,13 @@ static int update_prob(VP56RangeCoder *c, int p)
2822          av_assert2(d < FF_ARRAY_ELEMS(inv_map_table));
2823      }
2824  
2825 -    return p <= 128 ? 1 + inv_recenter_nonneg(inv_map_table[d], p - 1) :
2826 -                    255 - inv_recenter_nonneg(inv_map_table[d], 255 - p);
2827 +    return inv_map_table[d];
2828 +}
2829 +
2830 +static int update_prob(int p, int d)
2831 +{
2832 +    return p <= 128 ? 1 + inv_recenter_nonneg(d, p - 1) :
2833 +                    255 - inv_recenter_nonneg(d, 255 - p);
2834  }
2835  
2836  static int read_colorspace_details(AVCodecContext *avctx)
2837 @@ -703,7 +715,8 @@ static int decode_frame_header(AVCodecContext *avctx,
2838                                           get_bits(&s->gb, 8) : 255;
2839          }
2840  
2841 -        if (get_bits1(&s->gb)) {
2842 +        s->s.h.segmentation.update_data = get_bits1(&s->gb);
2843 +        if (s->s.h.segmentation.update_data) {
2844              s->s.h.segmentation.absolute_vals = get_bits1(&s->gb);
2845              for (i = 0; i < 8; i++) {
2846                  if ((s->s.h.segmentation.feat[i].q_enabled = get_bits1(&s->gb)))
2847 @@ -904,6 +917,8 @@ static int decode_frame_header(AVCodecContext *avctx,
2848       * as explicit copies if the fw update is missing (and skip the copy upon
2849       * fw update)? */
2850      s->prob.p = s->prob_ctx[c].p;
2851 +    memset(&s->prob_raw.p, 0, sizeof(s->prob_raw.p));
2852 +    memset(&s->prob_raw.coef, 0, sizeof(s->prob_raw.coef));
2853  
2854      // txfm updates
2855      if (s->s.h.lossless) {
2856 @@ -915,18 +930,25 @@ static int decode_frame_header(AVCodecContext *avctx,
2857  
2858          if (s->s.h.txfmmode == TX_SWITCHABLE) {
2859              for (i = 0; i < 2; i++)
2860 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
2861 -                    s->prob.p.tx8p[i] = update_prob(&s->c, s->prob.p.tx8p[i]);
2862 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2863 +                    s->prob_raw.p.tx8p[i] = read_prob_delta(&s->c);
2864 +                    s->prob.p.tx8p[i] = update_prob(s->prob.p.tx8p[i],
2865 +                                                    s->prob_raw.p.tx8p[i]);
2866 +                }
2867              for (i = 0; i < 2; i++)
2868                  for (j = 0; j < 2; j++)
2869 -                    if (vp56_rac_get_prob_branchy(&s->c, 252))
2870 -                        s->prob.p.tx16p[i][j] =
2871 -                            update_prob(&s->c, s->prob.p.tx16p[i][j]);
2872 +                    if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2873 +                        s->prob_raw.p.tx16p[i][j] = read_prob_delta(&s->c);
2874 +                        s->prob.p.tx16p[i][j] = update_prob(s->prob.p.tx16p[i][j],
2875 +                                                            s->prob_raw.p.tx16p[i][j]);
2876 +                    }
2877              for (i = 0; i < 2; i++)
2878                  for (j = 0; j < 3; j++)
2879 -                    if (vp56_rac_get_prob_branchy(&s->c, 252))
2880 -                        s->prob.p.tx32p[i][j] =
2881 -                            update_prob(&s->c, s->prob.p.tx32p[i][j]);
2882 +                    if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2883 +                        s->prob_raw.p.tx32p[i][j] = read_prob_delta(&s->c);
2884 +                        s->prob.p.tx32p[i][j] = update_prob(s->prob.p.tx32p[i][j],
2885 +                                                            s->prob_raw.p.tx32p[i][j]);
2886 +                    }
2887          }
2888      }
2889  
2890 @@ -938,15 +960,18 @@ static int decode_frame_header(AVCodecContext *avctx,
2891                  for (k = 0; k < 2; k++)
2892                      for (l = 0; l < 6; l++)
2893                          for (m = 0; m < 6; m++) {
2894 +                            uint8_t *pd = s->prob_raw.coef[i][j][k][l][m];
2895                              uint8_t *p = s->prob.coef[i][j][k][l][m];
2896                              uint8_t *r = ref[j][k][l][m];
2897                              if (m >= 3 && l == 0) // dc only has 3 pt
2898                                  break;
2899                              for (n = 0; n < 3; n++) {
2900 -                                if (vp56_rac_get_prob_branchy(&s->c, 252))
2901 -                                    p[n] = update_prob(&s->c, r[n]);
2902 -                                else
2903 +                                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2904 +                                    pd[n] = read_prob_delta(&s->c);
2905 +                                    p[n] = update_prob(r[n], pd[n]);
2906 +                                } else {
2907                                      p[n] = r[n];
2908 +                                }
2909                              }
2910                              memcpy(&p[3], ff_vp9_model_pareto8[p[2]], 8);
2911                          }
2912 @@ -961,7 +986,7 @@ static int decode_frame_header(AVCodecContext *avctx,
2913                                  break;
2914                              memcpy(p, r, 3);
2915                              memcpy(&p[3], ff_vp9_model_pareto8[p[2]], 8);
2916 -                        }
2917 +                         }
2918          }
2919          if (s->s.h.txfmmode == i)
2920              break;
2921 @@ -969,25 +994,37 @@ static int decode_frame_header(AVCodecContext *avctx,
2922  
2923      // mode updates
2924      for (i = 0; i < 3; i++)
2925 -        if (vp56_rac_get_prob_branchy(&s->c, 252))
2926 -            s->prob.p.skip[i] = update_prob(&s->c, s->prob.p.skip[i]);
2927 +        if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2928 +            s->prob_raw.p.skip[i] = read_prob_delta(&s->c);
2929 +            s->prob.p.skip[i] = update_prob(s->prob.p.skip[i],
2930 +                                            s->prob_raw.p.skip[i]);
2931 +        }
2932      if (!s->s.h.keyframe && !s->s.h.intraonly) {
2933          for (i = 0; i < 7; i++)
2934              for (j = 0; j < 3; j++)
2935 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
2936 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2937 +                    s->prob_raw.p.mv_mode[i][j] = read_prob_delta(&s->c);
2938                      s->prob.p.mv_mode[i][j] =
2939 -                        update_prob(&s->c, s->prob.p.mv_mode[i][j]);
2940 +                        update_prob(s->prob.p.mv_mode[i][j],
2941 +                                    s->prob_raw.p.mv_mode[i][j]);
2942 +                }
2943  
2944          if (s->s.h.filtermode == FILTER_SWITCHABLE)
2945              for (i = 0; i < 4; i++)
2946                  for (j = 0; j < 2; j++)
2947 -                    if (vp56_rac_get_prob_branchy(&s->c, 252))
2948 +                    if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2949 +                        s->prob_raw.p.filter[i][j] = read_prob_delta(&s->c);
2950                          s->prob.p.filter[i][j] =
2951 -                            update_prob(&s->c, s->prob.p.filter[i][j]);
2952 +                            update_prob(s->prob.p.filter[i][j],
2953 +                                        s->prob_raw.p.filter[i][j]);
2954 +                    }
2955  
2956          for (i = 0; i < 4; i++)
2957 -            if (vp56_rac_get_prob_branchy(&s->c, 252))
2958 -                s->prob.p.intra[i] = update_prob(&s->c, s->prob.p.intra[i]);
2959 +            if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2960 +                s->prob_raw.p.intra[i] = read_prob_delta(&s->c);
2961 +                s->prob.p.intra[i] = update_prob(s->prob.p.intra[i],
2962 +                                                 s->prob_raw.p.intra[i]);
2963 +            }
2964  
2965          if (s->s.h.allowcompinter) {
2966              s->s.h.comppredmode = vp8_rac_get(&s->c);
2967 @@ -995,92 +1032,134 @@ static int decode_frame_header(AVCodecContext *avctx,
2968                  s->s.h.comppredmode += vp8_rac_get(&s->c);
2969              if (s->s.h.comppredmode == PRED_SWITCHABLE)
2970                  for (i = 0; i < 5; i++)
2971 -                    if (vp56_rac_get_prob_branchy(&s->c, 252))
2972 +                    if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2973 +                        s->prob_raw.p.comp[i] = read_prob_delta(&s->c);
2974                          s->prob.p.comp[i] =
2975 -                            update_prob(&s->c, s->prob.p.comp[i]);
2976 +                            update_prob(s->prob.p.comp[i], s->prob_raw.p.comp[i]);
2977 +                    }
2978          } else {
2979              s->s.h.comppredmode = PRED_SINGLEREF;
2980          }
2981  
2982          if (s->s.h.comppredmode != PRED_COMPREF) {
2983              for (i = 0; i < 5; i++) {
2984 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
2985 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2986 +                    s->prob_raw.p.single_ref[i][0] = read_prob_delta(&s->c);
2987                      s->prob.p.single_ref[i][0] =
2988 -                        update_prob(&s->c, s->prob.p.single_ref[i][0]);
2989 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
2990 +                        update_prob(s->prob.p.single_ref[i][0],
2991 +                                    s->prob_raw.p.single_ref[i][0]);
2992 +                }
2993 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
2994 +                    s->prob_raw.p.single_ref[i][1] = read_prob_delta(&s->c);
2995                      s->prob.p.single_ref[i][1] =
2996 -                        update_prob(&s->c, s->prob.p.single_ref[i][1]);
2997 +                        update_prob(s->prob.p.single_ref[i][1],
2998 +                                    s->prob_raw.p.single_ref[i][1]);
2999 +                }
3000              }
3001          }
3002  
3003          if (s->s.h.comppredmode != PRED_SINGLEREF) {
3004              for (i = 0; i < 5; i++)
3005 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
3006 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3007 +                    s->prob_raw.p.comp_ref[i] = read_prob_delta(&s->c);
3008                      s->prob.p.comp_ref[i] =
3009 -                        update_prob(&s->c, s->prob.p.comp_ref[i]);
3010 +                        update_prob(s->prob.p.comp_ref[i],
3011 +                                    s->prob_raw.p.comp_ref[i]);
3012 +                }
3013          }
3014  
3015          for (i = 0; i < 4; i++)
3016              for (j = 0; j < 9; j++)
3017 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
3018 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3019 +                    s->prob_raw.p.y_mode[i][j] = read_prob_delta(&s->c);
3020                      s->prob.p.y_mode[i][j] =
3021 -                        update_prob(&s->c, s->prob.p.y_mode[i][j]);
3022 +                        update_prob(s->prob.p.y_mode[i][j],
3023 +                                    s->prob_raw.p.y_mode[i][j]);
3024 +                }
3025  
3026          for (i = 0; i < 4; i++)
3027              for (j = 0; j < 4; j++)
3028                  for (k = 0; k < 3; k++)
3029 -                    if (vp56_rac_get_prob_branchy(&s->c, 252))
3030 +                    if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3031 +                        s->prob_raw.p.partition[i][j][k] = read_prob_delta(&s->c);
3032                          s->prob.p.partition[3 - i][j][k] =
3033 -                            update_prob(&s->c,
3034 -                                        s->prob.p.partition[3 - i][j][k]);
3035 +                            update_prob(s->prob.p.partition[3 - i][j][k],
3036 +                                        s->prob_raw.p.partition[i][j][k]);
3037 +                    }
3038  
3039          // mv fields don't use the update_prob subexp model for some reason
3040          for (i = 0; i < 3; i++)
3041 -            if (vp56_rac_get_prob_branchy(&s->c, 252))
3042 -                s->prob.p.mv_joint[i] = (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3043 +            if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3044 +                s->prob_raw.p.mv_joint[i] = (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3045 +                s->prob.p.mv_joint[i] = s->prob_raw.p.mv_joint[i];
3046 +            }
3047  
3048          for (i = 0; i < 2; i++) {
3049 -            if (vp56_rac_get_prob_branchy(&s->c, 252))
3050 -                s->prob.p.mv_comp[i].sign =
3051 +            if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3052 +                s->prob_raw.p.mv_comp[i].sign =
3053                      (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3054 +                s->prob.p.mv_comp[i].sign =
3055 +                    s->prob_raw.p.mv_comp[i].sign;
3056 +            }
3057  
3058              for (j = 0; j < 10; j++)
3059 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
3060 -                    s->prob.p.mv_comp[i].classes[j] =
3061 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3062 +                    s->prob_raw.p.mv_comp[i].classes[j] =
3063                          (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3064 +                    s->prob.p.mv_comp[i].classes[j] =
3065 +                        s->prob_raw.p.mv_comp[i].classes[j];
3066 +                }
3067  
3068 -            if (vp56_rac_get_prob_branchy(&s->c, 252))
3069 -                s->prob.p.mv_comp[i].class0 =
3070 +            if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3071 +                s->prob_raw.p.mv_comp[i].class0 =
3072                      (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3073 +                s->prob.p.mv_comp[i].class0 =
3074 +                    s->prob_raw.p.mv_comp[i].class0;
3075 +            }
3076  
3077              for (j = 0; j < 10; j++)
3078 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
3079 -                    s->prob.p.mv_comp[i].bits[j] =
3080 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3081 +                    s->prob_raw.p.mv_comp[i].bits[j] =
3082                          (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3083 +                    s->prob.p.mv_comp[i].bits[j] =
3084 +                        s->prob_raw.p.mv_comp[i].bits[j];
3085 +                }
3086          }
3087  
3088          for (i = 0; i < 2; i++) {
3089              for (j = 0; j < 2; j++)
3090                  for (k = 0; k < 3; k++)
3091 -                    if (vp56_rac_get_prob_branchy(&s->c, 252))
3092 -                        s->prob.p.mv_comp[i].class0_fp[j][k] =
3093 +                    if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3094 +                        s->prob_raw.p.mv_comp[i].class0_fp[j][k] =
3095                              (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3096 +                        s->prob.p.mv_comp[i].class0_fp[j][k] =
3097 +                            s->prob_raw.p.mv_comp[i].class0_fp[j][k];
3098 +                    }
3099  
3100              for (j = 0; j < 3; j++)
3101 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
3102 -                    s->prob.p.mv_comp[i].fp[j] =
3103 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3104 +                    s->prob_raw.p.mv_comp[i].fp[j] =
3105                          (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3106 +                    s->prob.p.mv_comp[i].fp[j] =
3107 +                        s->prob_raw.p.mv_comp[i].fp[j];
3108 +                }
3109          }
3110  
3111          if (s->s.h.highprecisionmvs) {
3112              for (i = 0; i < 2; i++) {
3113 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
3114 -                    s->prob.p.mv_comp[i].class0_hp =
3115 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3116 +                    s->prob_raw.p.mv_comp[i].class0_hp =
3117                          (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3118 +                    s->prob.p.mv_comp[i].class0_hp =
3119 +                        s->prob_raw.p.mv_comp[i].class0_hp;
3120 +                }
3121  
3122 -                if (vp56_rac_get_prob_branchy(&s->c, 252))
3123 -                    s->prob.p.mv_comp[i].hp =
3124 +                if (vp56_rac_get_prob_branchy(&s->c, 252)) {
3125 +                    s->prob_raw.p.mv_comp[i].hp =
3126                          (vp8_rac_get_uint(&s->c, 7) << 1) | 1;
3127 +                    s->prob.p.mv_comp[i].hp =
3128 +                        s->prob_raw.p.mv_comp[i].hp;
3129 +                }
3130              }
3131          }
3132      }
3133 @@ -1912,6 +1991,9 @@ AVCodec ff_vp9_decoder = {
3134  #endif
3135  #if CONFIG_VP9_VDPAU_HWACCEL
3136                                 HWACCEL_VDPAU(vp9),
3137 +#endif
3138 +#if CONFIG_VP9_V4L2REQUEST_HWACCEL
3139 +                               HWACCEL_V4L2REQUEST(vp9),
3140  #endif
3141                                 NULL
3142                             },
3143 diff --git a/libavcodec/vp9dec.h b/libavcodec/vp9dec.h
3144 index d82b258a3d8..8d2c341e0b9 100644
3145 --- a/libavcodec/vp9dec.h
3146 +++ b/libavcodec/vp9dec.h
3147 @@ -131,6 +131,10 @@ typedef struct VP9Context {
3148          ProbContext p;
3149          uint8_t coef[4][2][2][6][6][11];
3150      } prob;
3151 +    struct {
3152 +        ProbContext p;
3153 +        uint8_t coef[4][2][2][6][6][11];
3154 +    } prob_raw;
3155  
3156      // contextual (above) cache
3157      uint8_t *above_partition_ctx;
3158 diff --git a/libavcodec/vp9shared.h b/libavcodec/vp9shared.h
3159 index 54726df742f..fee3568736f 100644
3160 --- a/libavcodec/vp9shared.h
3161 +++ b/libavcodec/vp9shared.h
3162 @@ -131,6 +131,7 @@ typedef struct VP9BitstreamHeader {
3163          uint8_t temporal;
3164          uint8_t absolute_vals;
3165          uint8_t update_map;
3166 +        uint8_t update_data;
3167          uint8_t prob[7];
3168          uint8_t pred_prob[3];
3169          struct {
3170
3171 From bb3cf90c0533a0096dff74b416f55832814293e0 Mon Sep 17 00:00:00 2001
3172 From: Jonas Karlman <jonas@kwiboo.se>
3173 Date: Mon, 29 Apr 2019 22:08:59 +0000
3174 Subject: [PATCH 11/17] HACK: hwcontext_drm: do not require drm device
3175
3176 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
3177 ---
3178  libavutil/hwcontext_drm.c | 5 +++++
3179  1 file changed, 5 insertions(+)
3180
3181 diff --git a/libavutil/hwcontext_drm.c b/libavutil/hwcontext_drm.c
3182 index 7a9fdbd263d..6297d1f9b61 100644
3183 --- a/libavutil/hwcontext_drm.c
3184 +++ b/libavutil/hwcontext_drm.c
3185 @@ -53,6 +53,11 @@ static int drm_device_create(AVHWDeviceContext *hwdev, const char *device,
3186      AVDRMDeviceContext *hwctx = hwdev->hwctx;
3187      drmVersionPtr version;
3188  
3189 +    if (device == NULL) {
3190 +      hwctx->fd = -1;
3191 +      return 0;
3192 +    }
3193 +
3194      hwctx->fd = open(device, O_RDWR);
3195      if (hwctx->fd < 0)
3196          return AVERROR(errno);
3197
3198 From 154405d2d8987c741e722f59430fda9326c8cdef Mon Sep 17 00:00:00 2001
3199 From: Jonas Karlman <jonas@kwiboo.se>
3200 Date: Fri, 15 May 2020 16:54:05 +0000
3201 Subject: [PATCH 13/17] WIP: add NV15 and NV20 support
3202
3203 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
3204 ---
3205  libavcodec/h264_slice.c   | 14 ++++++++++++--
3206  libavcodec/v4l2_request.c | 23 +++++++++++++++++++++++
3207  2 files changed, 35 insertions(+), 2 deletions(-)
3208
3209 diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c
3210 index 0a10d00aad9..45057fd049b 100644
3211 --- a/libavcodec/h264_slice.c
3212 +++ b/libavcodec/h264_slice.c
3213 @@ -794,10 +794,17 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3214                  *fmt++ = AV_PIX_FMT_GBRP10;
3215              } else
3216                  *fmt++ = AV_PIX_FMT_YUV444P10;
3217 -        } else if (CHROMA422(h))
3218 +        } else if (CHROMA422(h)) {
3219 +#if CONFIG_H264_V4L2REQUEST_HWACCEL
3220 +            *fmt++ = AV_PIX_FMT_DRM_PRIME;
3221 +#endif
3222              *fmt++ = AV_PIX_FMT_YUV422P10;
3223 -        else
3224 +        } else {
3225 +#if CONFIG_H264_V4L2REQUEST_HWACCEL
3226 +            *fmt++ = AV_PIX_FMT_DRM_PRIME;
3227 +#endif
3228              *fmt++ = AV_PIX_FMT_YUV420P10;
3229 +        }
3230          break;
3231      case 12:
3232          if (CHROMA444(h)) {
3233 @@ -836,6 +843,9 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
3234              else
3235                  *fmt++ = AV_PIX_FMT_YUV444P;
3236          } else if (CHROMA422(h)) {
3237 +#if CONFIG_H264_V4L2REQUEST_HWACCEL
3238 +                *fmt++ = AV_PIX_FMT_DRM_PRIME;
3239 +#endif
3240              if (h->avctx->color_range == AVCOL_RANGE_JPEG)
3241                  *fmt++ = AV_PIX_FMT_YUVJ422P;
3242              else
3243 diff --git a/libavcodec/v4l2_request.c b/libavcodec/v4l2_request.c
3244 index 5234b5049b0..0b294feff2e 100644
3245 --- a/libavcodec/v4l2_request.c
3246 +++ b/libavcodec/v4l2_request.c
3247 @@ -188,6 +188,13 @@ const uint32_t v4l2_request_capture_pixelformats[] = {
3248  #ifdef DRM_FORMAT_MOD_ALLWINNER_TILED
3249      V4L2_PIX_FMT_SUNXI_TILED_NV12,
3250  #endif
3251 +#if defined(V4L2_PIX_FMT_NV15) && defined(DRM_FORMAT_NV15)
3252 +    V4L2_PIX_FMT_NV15,
3253 +#endif
3254 +    V4L2_PIX_FMT_NV16,
3255 +#if defined(V4L2_PIX_FMT_NV20) && defined(DRM_FORMAT_NV20)
3256 +    V4L2_PIX_FMT_NV20,
3257 +#endif
3258  };
3259  
3260  static int v4l2_request_set_drm_descriptor(V4L2RequestDescriptor *req, struct v4l2_format *format)
3261 @@ -206,6 +213,22 @@ static int v4l2_request_set_drm_descriptor(V4L2RequestDescriptor *req, struct v4
3262          layer->format = DRM_FORMAT_NV12;
3263          desc->objects[0].format_modifier = DRM_FORMAT_MOD_ALLWINNER_TILED;
3264          break;
3265 +#endif
3266 +#if defined(V4L2_PIX_FMT_NV15) && defined(DRM_FORMAT_NV15)
3267 +    case V4L2_PIX_FMT_NV15:
3268 +        layer->format = DRM_FORMAT_NV15;
3269 +        desc->objects[0].format_modifier = DRM_FORMAT_MOD_LINEAR;
3270 +        break;
3271 +#endif
3272 +    case V4L2_PIX_FMT_NV16:
3273 +        layer->format = DRM_FORMAT_NV16;
3274 +        desc->objects[0].format_modifier = DRM_FORMAT_MOD_LINEAR;
3275 +        break;
3276 +#if defined(V4L2_PIX_FMT_NV20) && defined(DRM_FORMAT_NV20)
3277 +    case V4L2_PIX_FMT_NV20:
3278 +        layer->format = DRM_FORMAT_NV20;
3279 +        desc->objects[0].format_modifier = DRM_FORMAT_MOD_LINEAR;
3280 +        break;
3281  #endif
3282      default:
3283          return -1;
3284
3285 From d7933e19a712a59af418f6b029c0984d5b29afe9 Mon Sep 17 00:00:00 2001
3286 From: Jonas Karlman <jonas@kwiboo.se>
3287 Date: Mon, 27 Jul 2020 23:15:45 +0000
3288 Subject: [PATCH 14/17] HACK: define drm NV15 and NV20 format
3289
3290 ---
3291  libavcodec/v4l2_request.c | 8 ++++++++
3292  1 file changed, 8 insertions(+)
3293
3294 diff --git a/libavcodec/v4l2_request.c b/libavcodec/v4l2_request.c
3295 index 0b294feff2e..a8f0ee79eee 100644
3296 --- a/libavcodec/v4l2_request.c
3297 +++ b/libavcodec/v4l2_request.c
3298 @@ -30,6 +30,14 @@
3299  #include "internal.h"
3300  #include "v4l2_request.h"
3301  
3302 +#ifndef DRM_FORMAT_NV15
3303 +#define DRM_FORMAT_NV15 fourcc_code('N', 'V', '1', '5')
3304 +#endif
3305 +
3306 +#ifndef DRM_FORMAT_NV20
3307 +#define DRM_FORMAT_NV20 fourcc_code('N', 'V', '2', '0')
3308 +#endif
3309 +
3310  uint64_t ff_v4l2_request_get_capture_timestamp(AVFrame *frame)
3311  {
3312      V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)frame->data[0];
3313
3314 From c9ae9a29ef84096bb2e4d37fbdea6c3b3d20fff7 Mon Sep 17 00:00:00 2001
3315 From: Alex Bee <knaerzche@gmail.com>
3316 Date: Sun, 19 Sep 2021 13:10:55 +0200
3317 Subject: [PATCH 16/17] v4l2_request: validate supported framesizes
3318
3319 Signed-off-by: Alex Bee <knaerzche@gmail.com>
3320 ---
3321  libavcodec/v4l2_request.c | 38 +++++++++++++++++++++++++++++++++++++-
3322  1 file changed, 37 insertions(+), 1 deletion(-)
3323
3324 diff --git a/libavcodec/v4l2_request.c b/libavcodec/v4l2_request.c
3325 index a8f0ee79eee..2fbe1663416 100644
3326 --- a/libavcodec/v4l2_request.c
3327 +++ b/libavcodec/v4l2_request.c
3328 @@ -376,6 +376,42 @@ int ff_v4l2_request_decode_frame(AVCodecContext *avctx, AVFrame *frame, struct v
3329      return v4l2_request_queue_decode(avctx, frame, control, count, 1, 1);
3330  }
3331  
3332 +static int v4l2_request_try_framesize(AVCodecContext *avctx, uint32_t pixelformat)
3333 +{
3334 +    V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
3335 +    struct v4l2_frmsizeenum frmsize = {
3336 +        .index = 0,
3337 +        .pixel_format = pixelformat,
3338 +    };
3339 +
3340 +    if (ioctl(ctx->video_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize) < 0)
3341 +        return 0;
3342 +
3343 +    /*
3344 +     * We only validate min/max framesize for V4L2_FRMSIZE_TYPE_STEPWISE here, since the alignment
3345 +     * which is eventually needed will be done driver-side later in VIDIOC_S_FMT and there is no need
3346 +     * validate step_width/step_height here
3347 +     */
3348 +
3349 +    do {
3350 +
3351 +        if (frmsize.type == V4L2_FRMSIZE_TYPE_DISCRETE && frmsize.discrete.width == avctx->coded_width &&
3352 +            frmsize.discrete.height == avctx->coded_height)
3353 +            return 0;
3354 +        else if ((frmsize.type == V4L2_FRMSIZE_TYPE_STEPWISE || frmsize.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) &&
3355 +                 avctx->coded_width >= frmsize.stepwise.min_width && avctx->coded_height >= frmsize.stepwise.min_height &&
3356 +                 avctx->coded_width <= frmsize.stepwise.max_width && avctx->coded_height <= frmsize.stepwise.max_height)
3357 +            return 0;
3358 +
3359 +        frmsize.index++;
3360 +
3361 +    } while (ioctl(ctx->video_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize) >= 0);
3362 +
3363 +    av_log(avctx, AV_LOG_INFO, "%s: pixelformat %u not supported for width %u height %u\n", __func__, pixelformat, avctx->coded_width, avctx->coded_height);
3364 +
3365 +    return -1;
3366 +}
3367 +
3368  static int v4l2_request_try_format(AVCodecContext *avctx, enum v4l2_buf_type type, uint32_t pixelformat)
3369  {
3370      V4L2RequestContext *ctx = avctx->internal->hwaccel_priv_data;
3371 @@ -404,7 +440,7 @@ static int v4l2_request_try_format(AVCodecContext *avctx, enum v4l2_buf_type typ
3372  
3373      while (ioctl(ctx->video_fd, VIDIOC_ENUM_FMT, &fmtdesc) >= 0) {
3374          if (fmtdesc.pixelformat == pixelformat)
3375 -            return 0;
3376 +            return v4l2_request_try_framesize(avctx, pixelformat);
3377  
3378          fmtdesc.index++;
3379      }
3380
3381 From c415926540fe04141bb1e8cabd24049b61752d4f Mon Sep 17 00:00:00 2001
3382 From: Jernej Skrabec <jernej.skrabec@gmail.com>
3383 Date: Sun, 27 Feb 2022 18:54:21 +0100
3384 Subject: [PATCH 17/17] Improve VP9 decoding
3385
3386 ---
3387  libavcodec/v4l2_request_vp9.c | 110 +++++++++++++++++++---------------
3388  1 file changed, 62 insertions(+), 48 deletions(-)
3389
3390 diff --git a/libavcodec/v4l2_request_vp9.c b/libavcodec/v4l2_request_vp9.c
3391 index 9b95c76cdb8..ec0300f66db 100644
3392 --- a/libavcodec/v4l2_request_vp9.c
3393 +++ b/libavcodec/v4l2_request_vp9.c
3394 @@ -22,78 +22,62 @@
3395  
3396  typedef struct V4L2RequestControlsVP9 {
3397      struct v4l2_ctrl_vp9_frame decode_params;
3398 +    struct v4l2_ctrl_vp9_compressed_hdr chp;
3399  } V4L2RequestControlsVP9;
3400  
3401 -static int v4l2_request_vp9_set_frame_ctx(AVCodecContext *avctx)
3402 +static void v4l2_request_vp9_set_frame_ctx(AVCodecContext *avctx)
3403  {
3404      VP9Context *s = avctx->priv_data;
3405 -    struct v4l2_ctrl_vp9_compressed_hdr chp;
3406 -    struct v4l2_ext_control control[] = {
3407 -        {
3408 -            .id = V4L2_CID_STATELESS_VP9_COMPRESSED_HDR,
3409 -            .ptr = &chp,
3410 -            .size = sizeof(chp),
3411 -        },
3412 -    };
3413 +    const VP9Frame *f = &s->s.frames[CUR_FRAME];
3414 +    V4L2RequestControlsVP9 *controls = f->hwaccel_picture_private;
3415 +    struct v4l2_ctrl_vp9_compressed_hdr *chp = &controls->chp;
3416  
3417 -    memset(&chp, 0, sizeof(chp));
3418 +    memset(chp, 0, sizeof(&chp));
3419  
3420 -    chp.tx_mode = s->s.h.txfmmode;
3421 -    memcpy(chp.tx8, s->prob_raw.p.tx8p, sizeof(s->prob_raw.p.tx8p));
3422 -    memcpy(chp.tx16, s->prob_raw.p.tx16p, sizeof(s->prob_raw.p.tx16p));
3423 -    memcpy(chp.tx32, s->prob_raw.p.tx32p, sizeof(s->prob_raw.p.tx32p));
3424 +    chp->tx_mode = s->s.h.txfmmode;
3425 +    memcpy(chp->tx8, s->prob_raw.p.tx8p, sizeof(s->prob_raw.p.tx8p));
3426 +    memcpy(chp->tx16, s->prob_raw.p.tx16p, sizeof(s->prob_raw.p.tx16p));
3427 +    memcpy(chp->tx32, s->prob_raw.p.tx32p, sizeof(s->prob_raw.p.tx32p));
3428      for (unsigned i = 0; i < 4; i++) {
3429          for (unsigned j = 0; j < 2; j++) {
3430              for (unsigned k = 0; k < 2; k++) {
3431                  for (unsigned l = 0; l < 6; l++) {
3432                      for (unsigned m = 0; m < 6; m++) {
3433 -                        memcpy(chp.coef[i][j][k][l][m], s->prob_raw.coef[i][j][k][l][m], sizeof(chp.coef[0][0][0][0][0]));
3434 +                        memcpy(chp->coef[i][j][k][l][m], s->prob_raw.coef[i][j][k][l][m], sizeof(chp->coef[0][0][0][0][0]));
3435                      }
3436                  }
3437              }
3438          }
3439      }
3440 -    memcpy(chp.skip, s->prob_raw.p.skip, sizeof(s->prob_raw.p.skip));
3441 -    memcpy(chp.inter_mode, s->prob_raw.p.mv_mode, sizeof(s->prob_raw.p.mv_mode));
3442 -    memcpy(chp.interp_filter, s->prob_raw.p.filter, sizeof(s->prob_raw.p.filter));
3443 -    memcpy(chp.is_inter, s->prob_raw.p.intra, sizeof(s->prob_raw.p.intra));
3444 -    memcpy(chp.comp_mode, s->prob_raw.p.comp, sizeof(s->prob_raw.p.comp));
3445 -    memcpy(chp.single_ref, s->prob_raw.p.single_ref, sizeof(s->prob_raw.p.single_ref));
3446 -    memcpy(chp.comp_ref, s->prob_raw.p.comp_ref, sizeof(s->prob_raw.p.comp_ref));
3447 -    memcpy(chp.y_mode, s->prob_raw.p.y_mode, sizeof(s->prob_raw.p.y_mode));
3448 +    memcpy(chp->skip, s->prob_raw.p.skip, sizeof(s->prob_raw.p.skip));
3449 +    memcpy(chp->inter_mode, s->prob_raw.p.mv_mode, sizeof(s->prob_raw.p.mv_mode));
3450 +    memcpy(chp->interp_filter, s->prob_raw.p.filter, sizeof(s->prob_raw.p.filter));
3451 +    memcpy(chp->is_inter, s->prob_raw.p.intra, sizeof(s->prob_raw.p.intra));
3452 +    memcpy(chp->comp_mode, s->prob_raw.p.comp, sizeof(s->prob_raw.p.comp));
3453 +    memcpy(chp->single_ref, s->prob_raw.p.single_ref, sizeof(s->prob_raw.p.single_ref));
3454 +    memcpy(chp->comp_ref, s->prob_raw.p.comp_ref, sizeof(s->prob_raw.p.comp_ref));
3455 +    memcpy(chp->y_mode, s->prob_raw.p.y_mode, sizeof(s->prob_raw.p.y_mode));
3456      for (unsigned i = 0; i < 10; i++)
3457 -        memcpy(chp.uv_mode[i], s->prob.p.uv_mode[i], sizeof(s->prob.p.uv_mode[0]));
3458 +        memcpy(chp->uv_mode[i], s->prob.p.uv_mode[i], sizeof(s->prob.p.uv_mode[0]));
3459      for (unsigned i = 0; i < 4; i++)
3460 -        memcpy(chp.partition[i * 4], s->prob_raw.p.partition[i], sizeof(s->prob_raw.p.partition[0]));
3461 -    memcpy(chp.mv.joint, s->prob_raw.p.mv_joint, sizeof(s->prob_raw.p.mv_joint));
3462 +        memcpy(chp->partition[i * 4], s->prob_raw.p.partition[i], sizeof(s->prob_raw.p.partition[0]));
3463 +    memcpy(chp->mv.joint, s->prob_raw.p.mv_joint, sizeof(s->prob_raw.p.mv_joint));
3464      for (unsigned i = 0; i < 2; i++) {
3465 -         chp.mv.sign[i] = s->prob_raw.p.mv_comp[i].sign;
3466 -         memcpy(chp.mv.classes[i], s->prob_raw.p.mv_comp[i].classes, sizeof(s->prob_raw.p.mv_comp[0].classes));
3467 -         chp.mv.class0_bit[i] = s->prob_raw.p.mv_comp[i].class0;
3468 -         memcpy(chp.mv.bits[i], s->prob_raw.p.mv_comp[i].bits, sizeof(s->prob_raw.p.mv_comp[0].bits));
3469 -         memcpy(chp.mv.class0_fr[i], s->prob_raw.p.mv_comp[i].class0_fp, sizeof(s->prob_raw.p.mv_comp[0].class0_fp));
3470 -         memcpy(chp.mv.fr[i], s->prob_raw.p.mv_comp[i].fp, sizeof(s->prob_raw.p.mv_comp[0].fp));
3471 -         chp.mv.class0_hp[i] = s->prob_raw.p.mv_comp[i].class0_hp;
3472 -         chp.mv.hp[i] = s->prob_raw.p.mv_comp[i].hp;
3473 +         chp->mv.sign[i] = s->prob_raw.p.mv_comp[i].sign;
3474 +         memcpy(chp->mv.classes[i], s->prob_raw.p.mv_comp[i].classes, sizeof(s->prob_raw.p.mv_comp[0].classes));
3475 +         chp->mv.class0_bit[i] = s->prob_raw.p.mv_comp[i].class0;
3476 +         memcpy(chp->mv.bits[i], s->prob_raw.p.mv_comp[i].bits, sizeof(s->prob_raw.p.mv_comp[0].bits));
3477 +         memcpy(chp->mv.class0_fr[i], s->prob_raw.p.mv_comp[i].class0_fp, sizeof(s->prob_raw.p.mv_comp[0].class0_fp));
3478 +         memcpy(chp->mv.fr[i], s->prob_raw.p.mv_comp[i].fp, sizeof(s->prob_raw.p.mv_comp[0].fp));
3479 +         chp->mv.class0_hp[i] = s->prob_raw.p.mv_comp[i].class0_hp;
3480 +         chp->mv.hp[i] = s->prob_raw.p.mv_comp[i].hp;
3481      }
3482 -
3483 -    return ff_v4l2_request_set_controls(avctx, control, FF_ARRAY_ELEMS(control));
3484  }
3485  
3486 -static int v4l2_request_vp9_start_frame(AVCodecContext *avctx,
3487 -                                        av_unused const uint8_t *buffer,
3488 -                                        av_unused uint32_t size)
3489 +static void fill_frame(struct v4l2_ctrl_vp9_frame *dec_params, AVCodecContext *avctx)
3490  {
3491      const VP9Context *s = avctx->priv_data;
3492 -    const VP9Frame *f = &s->s.frames[CUR_FRAME];
3493 -    V4L2RequestControlsVP9 *controls = f->hwaccel_picture_private;
3494 -    struct v4l2_ctrl_vp9_frame *dec_params = &controls->decode_params;
3495      const ThreadFrame *ref;
3496 -    int ret;
3497 -
3498 -    ret = v4l2_request_vp9_set_frame_ctx(avctx);
3499 -    if (ret)
3500 -       return ret;
3501  
3502      memset(dec_params, 0, sizeof(*dec_params));
3503  
3504 @@ -208,6 +192,19 @@ static int v4l2_request_vp9_start_frame(AVCodecContext *avctx,
3505          if (s->s.h.segmentation.feat[i].skip_enabled)
3506              dec_params->seg.feature_enabled[i] |= 1 << V4L2_VP9_SEG_LVL_SKIP;
3507      }
3508 +}
3509 +
3510 +static int v4l2_request_vp9_start_frame(AVCodecContext *avctx,
3511 +                                        av_unused const uint8_t *buffer,
3512 +                                        av_unused uint32_t size)
3513 +{
3514 +    const VP9Context *s = avctx->priv_data;
3515 +    const VP9Frame *f = &s->s.frames[CUR_FRAME];
3516 +    V4L2RequestControlsVP9 *controls = f->hwaccel_picture_private;
3517 +
3518 +    v4l2_request_vp9_set_frame_ctx(avctx);
3519 +
3520 +    fill_frame(&controls->decode_params, avctx);
3521  
3522      return ff_v4l2_request_reset_frame(avctx, f->tf.f);
3523  }
3524 @@ -233,6 +230,11 @@ static int v4l2_request_vp9_end_frame(AVCodecContext *avctx)
3525              .ptr = &controls->decode_params,
3526              .size = sizeof(controls->decode_params),
3527          },
3528 +        {
3529 +            .id = V4L2_CID_STATELESS_VP9_COMPRESSED_HDR,
3530 +            .ptr = &controls->chp,
3531 +            .size = sizeof(controls->chp),
3532 +        },
3533      };
3534  
3535      ret = ff_v4l2_request_decode_frame(avctx, f->tf.f, control, FF_ARRAY_ELEMS(control));
3536 @@ -247,8 +249,20 @@ static int v4l2_request_vp9_end_frame(AVCodecContext *avctx)
3537  
3538  static int v4l2_request_vp9_init(AVCodecContext *avctx)
3539  {
3540 +    struct v4l2_ctrl_vp9_frame frame;
3541 +
3542 +    struct v4l2_ext_control control[] = {
3543 +        {
3544 +            .id = V4L2_CID_STATELESS_VP9_FRAME,
3545 +            .ptr = &frame,
3546 +            .size = sizeof(frame),
3547 +        },
3548 +    };
3549 +
3550 +    fill_frame(&frame, avctx);
3551 +
3552      // TODO: check V4L2_CID_MPEG_VIDEO_VP9_PROFILE
3553 -    return ff_v4l2_request_init(avctx, V4L2_PIX_FMT_VP9_FRAME, 3 * 1024 * 1024, NULL, 0);
3554 +    return ff_v4l2_request_init(avctx, V4L2_PIX_FMT_VP9_FRAME, 3 * 1024 * 1024, control, FF_ARRAY_ELEMS(control));
3555  }
3556  
3557  const AVHWAccel ff_vp9_v4l2request_hwaccel = {
3558 From e5df38921bf3a7f918c7e05b0207e3fde6c65017 Mon Sep 17 00:00:00 2001
3559 From: Jernej Skrabec <jernej.skrabec@siol.net>
3560 Date: Sat, 15 Dec 2018 22:32:16 +0100
3561 Subject: [PATCH] Add V4L2 request API hevc hwaccel
3562
3563 Signed-off-by: Jernej Skrabec <jernej.skrabec@siol.net>
3564 Signed-off-by: Jonas Karlman <jonas@kwiboo.se>
3565 Signed-off-by: Benjamin Gaignard <benjamin.gaignard@collabora.com>
3566 Signed-off-by: Alex Bee <knaerzche@gmail.com>
3567 ---
3568  configure                      |   3 +
3569  libavcodec/Makefile            |   1 +
3570  libavcodec/hevcdec.c           |  10 +
3571  libavcodec/hwaccels.h          |   1 +
3572  libavcodec/v4l2_request_hevc.c | 679 +++++++++++++++++++++++++++++++++
3573  5 files changed, 694 insertions(+)
3574  create mode 100644 libavcodec/v4l2_request_hevc.c
3575
3576 diff --git a/configure b/configure
3577 index 794bd7f4d612..2565ce8d7c20 100755
3578 --- a/configure
3579 +++ b/configure
3580 @@ -3049,6 +3049,8 @@ hevc_dxva2_hwaccel_deps="dxva2 DXVA_PicParams_HEVC"
3581  hevc_dxva2_hwaccel_select="hevc_decoder"
3582  hevc_nvdec_hwaccel_deps="nvdec"
3583  hevc_nvdec_hwaccel_select="hevc_decoder"
3584 +hevc_v4l2request_hwaccel_deps="v4l2_request hevc_v4l2_request"
3585 +hevc_v4l2request_hwaccel_select="hevc_decoder"
3586  hevc_vaapi_hwaccel_deps="vaapi VAPictureParameterBufferHEVC"
3587  hevc_vaapi_hwaccel_select="hevc_decoder"
3588  hevc_vdpau_hwaccel_deps="vdpau VdpPictureInfoHEVC"
3589 @@ -6894,6 +6896,7 @@ fi
3590  
3591  check_func_headers "linux/media.h linux/videodev2.h" v4l2_timeval_to_ns
3592  check_cc h264_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_H264_SLICE;"
3593 +check_cc hevc_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_HEVC_SLICE;"
3594  check_cc mpeg2_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_MPEG2_SLICE;"
3595  check_cc vp8_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_VP8_FRAME;"
3596  check_cc vp9_v4l2_request linux/videodev2.h "int i = V4L2_PIX_FMT_VP9_FRAME;"
3597 diff --git a/libavcodec/Makefile b/libavcodec/Makefile
3598 index 7da4fd1a8718..cd08740e75f1 100644
3599 --- a/libavcodec/Makefile
3600 +++ b/libavcodec/Makefile
3601 @@ -998,6 +998,7 @@ OBJS-$(CONFIG_HEVC_D3D11VA_HWACCEL)       += dxva2_hevc.o
3602  OBJS-$(CONFIG_HEVC_DXVA2_HWACCEL)         += dxva2_hevc.o
3603  OBJS-$(CONFIG_HEVC_NVDEC_HWACCEL)         += nvdec_hevc.o
3604  OBJS-$(CONFIG_HEVC_QSV_HWACCEL)           += qsvdec.o
3605 +OBJS-$(CONFIG_HEVC_V4L2REQUEST_HWACCEL)   += v4l2_request_hevc.o
3606  OBJS-$(CONFIG_HEVC_VAAPI_HWACCEL)         += vaapi_hevc.o h265_profile_level.o
3607  OBJS-$(CONFIG_HEVC_VDPAU_HWACCEL)         += vdpau_hevc.o h265_profile_level.o
3608  OBJS-$(CONFIG_MJPEG_NVDEC_HWACCEL)        += nvdec_mjpeg.o
3609 diff --git a/libavcodec/hevcdec.c b/libavcodec/hevcdec.c
3610 index 567e8d81d4a6..79b821e7e51e 100644
3611 --- a/libavcodec/hevcdec.c
3612 +++ b/libavcodec/hevcdec.c
3613 @@ -403,6 +403,7 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
3614  #define HWACCEL_MAX (CONFIG_HEVC_DXVA2_HWACCEL + \
3615                       CONFIG_HEVC_D3D11VA_HWACCEL * 2 + \
3616                       CONFIG_HEVC_NVDEC_HWACCEL + \
3617 +                     CONFIG_HEVC_V4L2REQUEST_HWACCEL + \
3618                       CONFIG_HEVC_VAAPI_HWACCEL + \
3619                       CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL + \
3620                       CONFIG_HEVC_VDPAU_HWACCEL)
3621 @@ -429,6 +430,9 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
3622  #endif
3623  #if CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL
3624          *fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
3625 +#endif
3626 +#if CONFIG_HEVC_V4L2REQUEST_HWACCEL
3627 +        *fmt++ = AV_PIX_FMT_DRM_PRIME;
3628  #endif
3629          break;
3630      case AV_PIX_FMT_YUV420P10:
3631 @@ -450,6 +454,9 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
3632  #endif
3633  #if CONFIG_HEVC_NVDEC_HWACCEL
3634          *fmt++ = AV_PIX_FMT_CUDA;
3635 +#endif
3636 +#if CONFIG_HEVC_V4L2REQUEST_HWACCEL
3637 +        *fmt++ = AV_PIX_FMT_DRM_PRIME;
3638  #endif
3639          break;
3640      case AV_PIX_FMT_YUV444P:
3641 @@ -3739,6 +3746,9 @@ const FFCodec ff_hevc_decoder = {
3642  #endif
3643  #if CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL
3644                                 HWACCEL_VIDEOTOOLBOX(hevc),
3645 +#endif
3646 +#if CONFIG_HEVC_V4L2REQUEST_HWACCEL
3647 +                               HWACCEL_V4L2REQUEST(hevc),
3648  #endif
3649                                 NULL
3650                             },
3651 diff --git a/libavcodec/hwaccels.h b/libavcodec/hwaccels.h
3652 index 6f9f0780019b..e4e4abc0606a 100644
3653 --- a/libavcodec/hwaccels.h
3654 +++ b/libavcodec/hwaccels.h
3655 @@ -41,6 +41,7 @@ extern const AVHWAccel ff_hevc_d3d11va_hwaccel;
3656  extern const AVHWAccel ff_hevc_d3d11va2_hwaccel;
3657  extern const AVHWAccel ff_hevc_dxva2_hwaccel;
3658  extern const AVHWAccel ff_hevc_nvdec_hwaccel;
3659 +extern const AVHWAccel ff_hevc_v4l2request_hwaccel;
3660  extern const AVHWAccel ff_hevc_vaapi_hwaccel;
3661  extern const AVHWAccel ff_hevc_vdpau_hwaccel;
3662  extern const AVHWAccel ff_hevc_videotoolbox_hwaccel;
3663 diff --git a/libavcodec/v4l2_request_hevc.c b/libavcodec/v4l2_request_hevc.c
3664 new file mode 100644
3665 index 000000000000..3e2b9a575ed0
3666 --- /dev/null
3667 +++ b/libavcodec/v4l2_request_hevc.c
3668 @@ -0,0 +1,679 @@
3669 +/*
3670 + * This file is part of FFmpeg.
3671 + *
3672 + * FFmpeg is free software; you can redistribute it and/or
3673 + * modify it under the terms of the GNU Lesser General Public
3674 + * License as published by the Free Software Foundation; either
3675 + * version 2.1 of the License, or (at your option) any later version.
3676 + *
3677 + * FFmpeg is distributed in the hope that it will be useful,
3678 + * but WITHOUT ANY WARRANTY; without even the implied warranty of
3679 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
3680 + * Lesser General Public License for more details.
3681 + *
3682 + * You should have received a copy of the GNU Lesser General Public
3683 + * License along with FFmpeg; if not, write to the Free Software
3684 + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
3685 + */
3686 +
3687 +#include "hevcdec.h"
3688 +#include "hwconfig.h"
3689 +#include "internal.h"
3690 +#include "v4l2_request.h"
3691 +
3692 +#define MAX_SLICES 600 // as per HEVC spec ?
3693 +#define V4L2_HEVC_CONTROLS_MAX 6
3694 +
3695 +typedef struct V4L2RequestControlsHEVC {
3696 +    struct v4l2_ctrl_hevc_sps sps;
3697 +    struct v4l2_ctrl_hevc_pps pps;
3698 +    struct v4l2_ctrl_hevc_decode_params dec_params;
3699 +    struct v4l2_ctrl_hevc_scaling_matrix scaling_matrix;
3700 +    struct v4l2_ctrl_hevc_slice_params slice_params[MAX_SLICES];
3701 +    __u32 *entry_point_offsets;
3702 +    unsigned int num_entry_point_offsets;
3703 +    int first_slice;
3704 +    int num_slices;
3705 +} V4L2RequestControlsHEVC;
3706 +
3707 +typedef struct V4L2RequestContextHEVC {
3708 +    V4L2RequestContext base;
3709 +    unsigned int decode_mode;
3710 +    unsigned int start_code;
3711 +    __u32 max_slices;
3712 +    unsigned int supports_entry_point_offsets;
3713 +    unsigned int supports_slices;
3714 +    unsigned int supports_scaling_matrix;
3715 +} V4L2RequestContextHEVC;
3716 +
3717 +static uint8_t nalu_slice_start_code[] = { 0x00, 0x00, 0x01 };
3718 +
3719 +static void v4l2_request_hevc_fill_pred_table(const HEVCContext *h, struct v4l2_hevc_pred_weight_table *table)
3720 +{
3721 +    int32_t luma_weight_denom, chroma_weight_denom;
3722 +    const SliceHeader *sh = &h->sh;
3723 +
3724 +    if (sh->slice_type == HEVC_SLICE_I ||
3725 +        (sh->slice_type == HEVC_SLICE_P && !h->ps.pps->weighted_pred_flag) ||
3726 +        (sh->slice_type == HEVC_SLICE_B && !h->ps.pps->weighted_bipred_flag))
3727 +        return;
3728 +
3729 +    table->luma_log2_weight_denom = sh->luma_log2_weight_denom;
3730 +
3731 +    if (h->ps.sps->chroma_format_idc)
3732 +        table->delta_chroma_log2_weight_denom = sh->chroma_log2_weight_denom - sh->luma_log2_weight_denom;
3733 +
3734 +    luma_weight_denom = (1 << sh->luma_log2_weight_denom);
3735 +    chroma_weight_denom = (1 << sh->chroma_log2_weight_denom);
3736 +
3737 +    for (int i = 0; i < 15 && i < sh->nb_refs[L0]; i++) {
3738 +        table->delta_luma_weight_l0[i] = sh->luma_weight_l0[i] - luma_weight_denom;
3739 +        table->luma_offset_l0[i] = sh->luma_offset_l0[i];
3740 +        table->delta_chroma_weight_l0[i][0] = sh->chroma_weight_l0[i][0] - chroma_weight_denom;
3741 +        table->delta_chroma_weight_l0[i][1] = sh->chroma_weight_l0[i][1] - chroma_weight_denom;
3742 +        table->chroma_offset_l0[i][0] = sh->chroma_offset_l0[i][0];
3743 +        table->chroma_offset_l0[i][1] = sh->chroma_offset_l0[i][1];
3744 +    }
3745 +
3746 +    if (sh->slice_type != HEVC_SLICE_B)
3747 +        return;
3748 +
3749 +    for (int i = 0; i < 15 && i < sh->nb_refs[L1]; i++) {
3750 +        table->delta_luma_weight_l1[i] = sh->luma_weight_l1[i] - luma_weight_denom;
3751 +        table->luma_offset_l1[i] = sh->luma_offset_l1[i];
3752 +        table->delta_chroma_weight_l1[i][0] = sh->chroma_weight_l1[i][0] - chroma_weight_denom;
3753 +        table->delta_chroma_weight_l1[i][1] = sh->chroma_weight_l1[i][1] - chroma_weight_denom;
3754 +        table->chroma_offset_l1[i][0] = sh->chroma_offset_l1[i][0];
3755 +        table->chroma_offset_l1[i][1] = sh->chroma_offset_l1[i][1];
3756 +    }
3757 +}
3758 +
3759 +static uint8_t get_ref_pic_index(const HEVCContext *h, const HEVCFrame *frame,
3760 +                                 struct v4l2_ctrl_hevc_decode_params *dec_params)
3761 +{
3762 +    uint64_t timestamp;
3763 +
3764 +    if (!frame)
3765 +        return 0;
3766 +
3767 +    timestamp = ff_v4l2_request_get_capture_timestamp(frame->frame);
3768 +
3769 +    for (uint8_t i = 0; i < dec_params->num_active_dpb_entries; i++) {
3770 +        struct v4l2_hevc_dpb_entry *entry = &dec_params->dpb[i];
3771 +        if (entry->timestamp == timestamp)
3772 +            return i;
3773 +    }
3774 +
3775 +    return 0;
3776 +}
3777 +
3778 +static void fill_dec_params(struct v4l2_ctrl_hevc_decode_params *dec_params, const HEVCContext *h)
3779 +{
3780 +    const HEVCFrame *pic = h->ref;
3781 +    const SliceHeader *sh = &h->sh;
3782 +    int i, entries = 0;
3783 +
3784 +    *dec_params = (struct v4l2_ctrl_hevc_decode_params) {
3785 +        .pic_order_cnt_val = pic->poc, /* FIXME: is this same as slice_params->slice_pic_order_cnt ? */
3786 +        .short_term_ref_pic_set_size = sh->short_term_ref_pic_set_size,
3787 +        .long_term_ref_pic_set_size = sh->long_term_ref_pic_set_size,
3788 +       .num_poc_st_curr_before = h->rps[ST_CURR_BEF].nb_refs,
3789 +        .num_poc_st_curr_after = h->rps[ST_CURR_AFT].nb_refs,
3790 +        .num_poc_lt_curr = h->rps[LT_CURR].nb_refs,
3791 +    };
3792 +
3793 +    for (i = 0; i < FF_ARRAY_ELEMS(h->DPB); i++) {
3794 +        const HEVCFrame *frame = &h->DPB[i];
3795 +        if (frame != pic && (frame->flags & (HEVC_FRAME_FLAG_LONG_REF | HEVC_FRAME_FLAG_SHORT_REF))) {
3796 +            struct v4l2_hevc_dpb_entry *entry = &dec_params->dpb[entries++];
3797 +
3798 +            entry->timestamp = ff_v4l2_request_get_capture_timestamp(frame->frame);
3799 +            entry->field_pic = frame->frame->interlaced_frame;
3800 +            entry->flags = 0;
3801 +            if (frame->flags & HEVC_FRAME_FLAG_LONG_REF)
3802 +                entry->flags |= V4L2_HEVC_DPB_ENTRY_LONG_TERM_REFERENCE;
3803 +
3804 +            entry->pic_order_cnt_val = frame->poc;
3805 +        }
3806 +    }
3807 +
3808 +    dec_params->num_active_dpb_entries = entries;
3809 +
3810 +    if (IS_IRAP(h))
3811 +        dec_params->flags |= V4L2_HEVC_DECODE_PARAM_FLAG_IRAP_PIC;
3812 +
3813 +    if (IS_IDR(h))
3814 +        dec_params->flags |= V4L2_HEVC_DECODE_PARAM_FLAG_IDR_PIC;
3815 +
3816 +    if (sh->no_output_of_prior_pics_flag)
3817 +        dec_params->flags |= V4L2_HEVC_DECODE_PARAM_FLAG_NO_OUTPUT_OF_PRIOR;
3818 +
3819 +    for (i = 0; i < V4L2_HEVC_DPB_ENTRIES_NUM_MAX; i++) {
3820 +        dec_params->poc_st_curr_before[i] = get_ref_pic_index(h, h->rps[ST_CURR_BEF].ref[i], dec_params);
3821 +        dec_params->poc_st_curr_after[i] = get_ref_pic_index(h, h->rps[ST_CURR_AFT].ref[i], dec_params);
3822 +        dec_params->poc_lt_curr[i] = get_ref_pic_index(h, h->rps[LT_CURR].ref[i], dec_params);
3823 +    }
3824 +}
3825 +
3826 +static int v4l2_request_hevc_fill_slice_params(const HEVCContext *h,
3827 +                                               V4L2RequestControlsHEVC *controls,
3828 +                                               int slice)
3829 +{
3830 +    struct v4l2_ctrl_hevc_slice_params *slice_params = &controls->slice_params[slice];
3831 +    struct v4l2_ctrl_hevc_decode_params *dec_params = &controls->dec_params;
3832 +    const HEVCFrame *pic = h->ref;
3833 +    const SliceHeader *sh = &h->sh;
3834 +    RefPicList *rpl;
3835 +    int i;
3836 +
3837 +    *slice_params = (struct v4l2_ctrl_hevc_slice_params) {
3838 +        .bit_size = 0,
3839 +        .data_byte_offset = (get_bits_count(&h->HEVClc->gb) + 1 + 7) / 8,
3840 +        .num_entry_point_offsets = sh->num_entry_point_offsets,
3841 +
3842 +        /* ISO/IEC 23008-2, ITU-T Rec. H.265: NAL unit header */
3843 +        .nal_unit_type = h->nal_unit_type,
3844 +        .nuh_temporal_id_plus1 = h->temporal_id + 1,
3845 +
3846 +        /* ISO/IEC 23008-2, ITU-T Rec. H.265: General slice segment header */
3847 +        .slice_type = sh->slice_type,
3848 +        .colour_plane_id = sh->colour_plane_id,
3849 +        .slice_pic_order_cnt = pic->poc,
3850 +        .num_ref_idx_l0_active_minus1 = sh->nb_refs[L0] ? sh->nb_refs[L0] - 1 : 0,
3851 +        .num_ref_idx_l1_active_minus1 = sh->nb_refs[L1] ? sh->nb_refs[L1] - 1 : 0,
3852 +        .collocated_ref_idx = sh->slice_temporal_mvp_enabled_flag ? sh->collocated_ref_idx : 0,
3853 +        .five_minus_max_num_merge_cand = sh->slice_type == HEVC_SLICE_I ? 0 : 5 - sh->max_num_merge_cand,
3854 +        .slice_qp_delta = sh->slice_qp_delta,
3855 +        .slice_cb_qp_offset = sh->slice_cb_qp_offset,
3856 +        .slice_cr_qp_offset = sh->slice_cr_qp_offset,
3857 +        .slice_act_y_qp_offset = 0,
3858 +        .slice_act_cb_qp_offset = 0,
3859 +        .slice_act_cr_qp_offset = 0,
3860 +        .slice_beta_offset_div2 = sh->beta_offset / 2,
3861 +        .slice_tc_offset_div2 = sh->tc_offset / 2,
3862 +
3863 +        /* ISO/IEC 23008-2, ITU-T Rec. H.265: Picture timing SEI message */
3864 +        .pic_struct = h->sei.picture_timing.picture_struct,
3865 +
3866 +        /* ISO/IEC 23008-2, ITU-T Rec. H.265: General slice segment header */
3867 +        .slice_segment_addr = sh->slice_segment_addr,
3868 +        .short_term_ref_pic_set_size = sh->short_term_ref_pic_set_size,
3869 +        .long_term_ref_pic_set_size = sh->long_term_ref_pic_set_size,
3870 +    };
3871 +
3872 +    if (sh->slice_sample_adaptive_offset_flag[0])
3873 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_SAO_LUMA;
3874 +
3875 +    if (sh->slice_sample_adaptive_offset_flag[1])
3876 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_SAO_CHROMA;
3877 +
3878 +    if (sh->slice_temporal_mvp_enabled_flag)
3879 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_TEMPORAL_MVP_ENABLED;
3880 +
3881 +    if (sh->mvd_l1_zero_flag)
3882 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_MVD_L1_ZERO;
3883 +
3884 +    if (sh->cabac_init_flag)
3885 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_CABAC_INIT;
3886 +
3887 +    if (sh->collocated_list == L0)
3888 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_COLLOCATED_FROM_L0;
3889 +
3890 +    /* TODO: V4L2_HEVC_SLICE_PARAMS_FLAG_USE_INTEGER_MV */
3891 +
3892 +    if (sh->disable_deblocking_filter_flag)
3893 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_DEBLOCKING_FILTER_DISABLED;
3894 +
3895 +    if (sh->slice_loop_filter_across_slices_enabled_flag)
3896 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_SLICE_LOOP_FILTER_ACROSS_SLICES_ENABLED;
3897 +
3898 +    if (sh->dependent_slice_segment_flag)
3899 +        slice_params->flags |= V4L2_HEVC_SLICE_PARAMS_FLAG_DEPENDENT_SLICE_SEGMENT;
3900 +
3901 +    if (sh->slice_type != HEVC_SLICE_I) {
3902 +        rpl = &h->ref->refPicList[0];
3903 +        for (i = 0; i < rpl->nb_refs; i++)
3904 +            slice_params->ref_idx_l0[i] = get_ref_pic_index(h, rpl->ref[i], dec_params);
3905 +    }
3906 +
3907 +    if (sh->slice_type == HEVC_SLICE_B) {
3908 +        rpl = &h->ref->refPicList[1];
3909 +        for (i = 0; i < rpl->nb_refs; i++)
3910 +            slice_params->ref_idx_l1[i] = get_ref_pic_index(h, rpl->ref[i], dec_params);
3911 +    }
3912 +
3913 +    v4l2_request_hevc_fill_pred_table(h, &slice_params->pred_weight_table);
3914 +
3915 +    if (controls->num_entry_point_offsets < sh->num_entry_point_offsets) {
3916 +        av_freep(&controls->entry_point_offsets);
3917 +        controls->entry_point_offsets = av_mallocz(sizeof(*controls->entry_point_offsets) * sh->num_entry_point_offsets);
3918 +        if (!controls->entry_point_offsets)
3919 +            return AVERROR(ENOMEM);
3920 +        controls->num_entry_point_offsets = sh->num_entry_point_offsets;
3921 +    }
3922 +
3923 +    for (i = 0; i < sh->num_entry_point_offsets; i++)
3924 +        controls->entry_point_offsets[i] = sh->entry_point_offset[i];
3925 +
3926 +    return 0;
3927 +}
3928 +
3929 +static void fill_sps(struct v4l2_ctrl_hevc_sps *ctrl, const HEVCContext *h)
3930 +{
3931 +    const HEVCSPS *sps = h->ps.sps;
3932 +    const HEVCPPS *pps = h->ps.pps;
3933 +
3934 +    /* ISO/IEC 23008-2, ITU-T Rec. H.265: Sequence parameter set */
3935 +    *ctrl = (struct v4l2_ctrl_hevc_sps) {
3936 +        .video_parameter_set_id = sps->vps_id,
3937 +        .seq_parameter_set_id = pps->sps_id,
3938 +        .pic_width_in_luma_samples = sps->width,
3939 +        .pic_height_in_luma_samples = sps->height,
3940 +        .bit_depth_luma_minus8 = sps->bit_depth - 8,
3941 +        .bit_depth_chroma_minus8 = sps->bit_depth_chroma - 8,
3942 +        .log2_max_pic_order_cnt_lsb_minus4 = sps->log2_max_poc_lsb - 4,
3943 +        .sps_max_dec_pic_buffering_minus1 = sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering - 1,
3944 +        .sps_max_num_reorder_pics = sps->temporal_layer[sps->max_sub_layers - 1].num_reorder_pics,
3945 +        .sps_max_latency_increase_plus1 = sps->temporal_layer[sps->max_sub_layers - 1].max_latency_increase + 1,
3946 +        .log2_min_luma_coding_block_size_minus3 = sps->log2_min_cb_size - 3,
3947 +        .log2_diff_max_min_luma_coding_block_size = sps->log2_diff_max_min_coding_block_size,
3948 +        .log2_min_luma_transform_block_size_minus2 = sps->log2_min_tb_size - 2,
3949 +        .log2_diff_max_min_luma_transform_block_size = sps->log2_max_trafo_size - sps->log2_min_tb_size,
3950 +        .max_transform_hierarchy_depth_inter = sps->max_transform_hierarchy_depth_inter,
3951 +        .max_transform_hierarchy_depth_intra = sps->max_transform_hierarchy_depth_intra,
3952 +        .pcm_sample_bit_depth_luma_minus1 = sps->pcm.bit_depth - 1,
3953 +        .pcm_sample_bit_depth_chroma_minus1 = sps->pcm.bit_depth_chroma - 1,
3954 +        .log2_min_pcm_luma_coding_block_size_minus3 = sps->pcm.log2_min_pcm_cb_size - 3,
3955 +        .log2_diff_max_min_pcm_luma_coding_block_size = sps->pcm.log2_max_pcm_cb_size - sps->pcm.log2_min_pcm_cb_size,
3956 +        .num_short_term_ref_pic_sets = sps->nb_st_rps,
3957 +        .num_long_term_ref_pics_sps = sps->num_long_term_ref_pics_sps,
3958 +        .chroma_format_idc = sps->chroma_format_idc,
3959 +        .sps_max_sub_layers_minus1 = sps->max_sub_layers - 1,
3960 +    };
3961 +
3962 +    if (sps->separate_colour_plane_flag)
3963 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_SEPARATE_COLOUR_PLANE;
3964 +
3965 +    if (sps->scaling_list_enable_flag)
3966 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_SCALING_LIST_ENABLED;
3967 +
3968 +    if (sps->amp_enabled_flag)
3969 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_AMP_ENABLED;
3970 +
3971 +    if (sps->sao_enabled)
3972 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_SAMPLE_ADAPTIVE_OFFSET;
3973 +
3974 +    if (sps->pcm_enabled_flag)
3975 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_PCM_ENABLED;
3976 +
3977 +    if (sps->pcm.loop_filter_disable_flag)
3978 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_PCM_LOOP_FILTER_DISABLED;
3979 +
3980 +    if (sps->long_term_ref_pics_present_flag)
3981 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_LONG_TERM_REF_PICS_PRESENT;
3982 +
3983 +    if (sps->sps_temporal_mvp_enabled_flag)
3984 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_SPS_TEMPORAL_MVP_ENABLED;
3985 +
3986 +    if (sps->sps_strong_intra_smoothing_enable_flag)
3987 +        ctrl->flags |= V4L2_HEVC_SPS_FLAG_STRONG_INTRA_SMOOTHING_ENABLED;
3988 +}
3989 +
3990 +static int v4l2_request_hevc_start_frame(AVCodecContext *avctx,
3991 +                                         av_unused const uint8_t *buffer,
3992 +                                         av_unused uint32_t size)
3993 +{
3994 +    const HEVCContext *h = avctx->priv_data;
3995 +    const HEVCPPS *pps = h->ps.pps;
3996 +    const HEVCSPS *sps = h->ps.sps;
3997 +    const ScalingList *sl = pps->scaling_list_data_present_flag ?
3998 +                            &pps->scaling_list :
3999 +                            sps->scaling_list_enable_flag ?
4000 +                            &sps->scaling_list : NULL;
4001 +    V4L2RequestControlsHEVC *controls = h->ref->hwaccel_picture_private;
4002 +    const SliceHeader *sh = &h->sh;
4003 +
4004 +    fill_sps(&controls->sps, h);
4005 +    fill_dec_params(&controls->dec_params, h);
4006 +
4007 +    if (sl) {
4008 +        for (int i = 0; i < 6; i++) {
4009 +            for (int j = 0; j < 16; j++)
4010 +                controls->scaling_matrix.scaling_list_4x4[i][j] = sl->sl[0][i][j];
4011 +            for (int j = 0; j < 64; j++) {
4012 +                controls->scaling_matrix.scaling_list_8x8[i][j]   = sl->sl[1][i][j];
4013 +                controls->scaling_matrix.scaling_list_16x16[i][j] = sl->sl[2][i][j];
4014 +                if (i < 2)
4015 +                    controls->scaling_matrix.scaling_list_32x32[i][j] = sl->sl[3][i * 3][j];
4016 +            }
4017 +            controls->scaling_matrix.scaling_list_dc_coef_16x16[i] = sl->sl_dc[0][i];
4018 +            if (i < 2)
4019 +                controls->scaling_matrix.scaling_list_dc_coef_32x32[i] = sl->sl_dc[1][i * 3];
4020 +        }
4021 +    }
4022 +
4023 +    /* ISO/IEC 23008-2, ITU-T Rec. H.265: Picture parameter set */
4024 +    controls->pps = (struct v4l2_ctrl_hevc_pps) {
4025 +        .pic_parameter_set_id = sh->pps_id,
4026 +        .num_extra_slice_header_bits = pps->num_extra_slice_header_bits,
4027 +        .num_ref_idx_l0_default_active_minus1 = pps->num_ref_idx_l0_default_active - 1,
4028 +        .num_ref_idx_l1_default_active_minus1 = pps->num_ref_idx_l1_default_active - 1,
4029 +        .init_qp_minus26 = pps->pic_init_qp_minus26,
4030 +        .diff_cu_qp_delta_depth = pps->diff_cu_qp_delta_depth,
4031 +        .pps_cb_qp_offset = pps->cb_qp_offset,
4032 +        .pps_cr_qp_offset = pps->cr_qp_offset,
4033 +        .pps_beta_offset_div2 = pps->beta_offset / 2,
4034 +        .pps_tc_offset_div2 = pps->tc_offset / 2,
4035 +        .log2_parallel_merge_level_minus2 = pps->log2_parallel_merge_level - 2,
4036 +    };
4037 +
4038 +    if (pps->dependent_slice_segments_enabled_flag)
4039 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_DEPENDENT_SLICE_SEGMENT_ENABLED;
4040 +
4041 +    if (pps->output_flag_present_flag)
4042 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_OUTPUT_FLAG_PRESENT;
4043 +
4044 +    if (pps->sign_data_hiding_flag)
4045 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_SIGN_DATA_HIDING_ENABLED;
4046 +
4047 +    if (pps->cabac_init_present_flag)
4048 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_CABAC_INIT_PRESENT;
4049 +
4050 +    if (pps->constrained_intra_pred_flag)
4051 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_CONSTRAINED_INTRA_PRED;
4052 +
4053 +    if (pps->transform_skip_enabled_flag)
4054 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_TRANSFORM_SKIP_ENABLED;
4055 +
4056 +    if (pps->cu_qp_delta_enabled_flag)
4057 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_CU_QP_DELTA_ENABLED;
4058 +
4059 +    if (pps->pic_slice_level_chroma_qp_offsets_present_flag)
4060 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_PPS_SLICE_CHROMA_QP_OFFSETS_PRESENT;
4061 +
4062 +    if (pps->weighted_pred_flag)
4063 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_WEIGHTED_PRED;
4064 +
4065 +    if (pps->weighted_bipred_flag)
4066 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_WEIGHTED_BIPRED;
4067 +
4068 +    if (pps->transquant_bypass_enable_flag)
4069 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_TRANSQUANT_BYPASS_ENABLED;
4070 +
4071 +    if (pps->tiles_enabled_flag)
4072 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_TILES_ENABLED;
4073 +
4074 +    if (pps->entropy_coding_sync_enabled_flag)
4075 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_ENTROPY_CODING_SYNC_ENABLED;
4076 +
4077 +    if (pps->loop_filter_across_tiles_enabled_flag)
4078 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_LOOP_FILTER_ACROSS_TILES_ENABLED;
4079 +
4080 +    if (pps->seq_loop_filter_across_slices_enabled_flag)
4081 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_PPS_LOOP_FILTER_ACROSS_SLICES_ENABLED;
4082 +
4083 +    if (pps->deblocking_filter_override_enabled_flag)
4084 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_DEBLOCKING_FILTER_OVERRIDE_ENABLED;
4085 +
4086 +    if (pps->disable_dbf)
4087 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_PPS_DISABLE_DEBLOCKING_FILTER;
4088 +
4089 +    if (pps->lists_modification_present_flag)
4090 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_LISTS_MODIFICATION_PRESENT;
4091 +
4092 +    if (pps->slice_header_extension_present_flag)
4093 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_SLICE_SEGMENT_HEADER_EXTENSION_PRESENT;
4094 +
4095 +    if (pps->deblocking_filter_control_present_flag)
4096 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_DEBLOCKING_FILTER_CONTROL_PRESENT;
4097 +
4098 +    if (pps->uniform_spacing_flag)
4099 +        controls->pps.flags |= V4L2_HEVC_PPS_FLAG_UNIFORM_SPACING;
4100 +
4101 +    if (pps->tiles_enabled_flag) {
4102 +        controls->pps.num_tile_columns_minus1 = pps->num_tile_columns - 1;
4103 +        controls->pps.num_tile_rows_minus1 = pps->num_tile_rows - 1;
4104 +
4105 +        for (int i = 0; i < pps->num_tile_columns; i++)
4106 +            controls->pps.column_width_minus1[i] = pps->column_width[i] - 1;
4107 +
4108 +        for (int i = 0; i < pps->num_tile_rows; i++)
4109 +            controls->pps.row_height_minus1[i] = pps->row_height[i] - 1;
4110 +    }
4111 +
4112 +    controls->first_slice = 1;
4113 +    controls->num_slices = 0;
4114 +    controls->num_entry_point_offsets = 0;
4115 +
4116 +    return ff_v4l2_request_reset_frame(avctx, h->ref->frame);
4117 +}
4118 +
4119 +static int v4l2_request_hevc_queue_decode(AVCodecContext *avctx, int last_slice)
4120 +{
4121 +    const HEVCContext *h = avctx->priv_data;
4122 +    V4L2RequestControlsHEVC *controls = h->ref->hwaccel_picture_private;
4123 +    struct v4l2_ctrl_hevc_slice_params *first_slice_params = &controls->slice_params[0];
4124 +    V4L2RequestContextHEVC *ctx = avctx->internal->hwaccel_priv_data;
4125 +    int num_controls = 0;
4126 +
4127 +    struct v4l2_ext_control control[V4L2_HEVC_CONTROLS_MAX] = {};
4128 +
4129 +    control[num_controls++] = (struct v4l2_ext_control) {
4130 +            .id = V4L2_CID_STATELESS_HEVC_SPS,
4131 +            .ptr = &controls->sps,
4132 +            .size = sizeof(controls->sps),
4133 +    };
4134 +
4135 +    control[num_controls++] = (struct v4l2_ext_control) {
4136 +            .id = V4L2_CID_STATELESS_HEVC_PPS,
4137 +            .ptr = &controls->pps,
4138 +            .size = sizeof(controls->pps),
4139 +    };
4140 +
4141 +    control[num_controls++] = (struct v4l2_ext_control) {
4142 +         .id = V4L2_CID_STATELESS_HEVC_DECODE_PARAMS,
4143 +         .ptr = &controls->dec_params,
4144 +         .size = sizeof(controls->dec_params),
4145 +    };
4146 +
4147 +    if (ctx->supports_scaling_matrix)
4148 +       control[num_controls++] = (struct v4l2_ext_control) {
4149 +            .id = V4L2_CID_STATELESS_HEVC_SCALING_MATRIX,
4150 +            .ptr = &controls->scaling_matrix,
4151 +            .size = sizeof(controls->scaling_matrix),
4152 +        };
4153 +
4154 +    if (ctx->supports_slices)
4155 +       control[num_controls++] = (struct v4l2_ext_control) {
4156 +            .id = V4L2_CID_STATELESS_HEVC_SLICE_PARAMS,
4157 +            .ptr = &controls->slice_params,
4158 +            .size = sizeof(*first_slice_params) * controls->num_slices,
4159 +        };
4160 +
4161 +    //this assumes that decoders supporting entry_point_offsets submit a single slice per request
4162 +    if (ctx->supports_entry_point_offsets && first_slice_params->num_entry_point_offsets > 0)
4163 +       control[num_controls++] = (struct v4l2_ext_control) {
4164 +            .id = V4L2_CID_STATELESS_HEVC_ENTRY_POINT_OFFSETS,
4165 +            .ptr = controls->entry_point_offsets,
4166 +            .size = sizeof(*controls->entry_point_offsets) * first_slice_params->num_entry_point_offsets,
4167 +        };
4168 +
4169 +    if (ctx->decode_mode == V4L2_STATELESS_HEVC_DECODE_MODE_SLICE_BASED)
4170 +        return ff_v4l2_request_decode_slice(avctx, h->ref->frame, control, num_controls, controls->first_slice, last_slice);
4171 +
4172 +    return ff_v4l2_request_decode_frame(avctx, h->ref->frame, control, num_controls);
4173 +}
4174 +
4175 +static int v4l2_request_hevc_decode_slice(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)
4176 +{
4177 +    const HEVCContext *h = avctx->priv_data;
4178 +    V4L2RequestControlsHEVC *controls = h->ref->hwaccel_picture_private;
4179 +    V4L2RequestContextHEVC *ctx = avctx->internal->hwaccel_priv_data;
4180 +    V4L2RequestDescriptor *req = (V4L2RequestDescriptor*)h->ref->frame->data[0];
4181 +    int ret, slice = FFMIN(controls->num_slices, MAX_SLICES - 1);
4182 +
4183 +    if (ctx->decode_mode == V4L2_STATELESS_HEVC_DECODE_MODE_SLICE_BASED && slice) {
4184 +        ret = v4l2_request_hevc_queue_decode(avctx, 0);
4185 +        if (ret)
4186 +            return ret;
4187 +
4188 +        ff_v4l2_request_reset_frame(avctx, h->ref->frame);
4189 +        slice = controls->num_slices = 0;
4190 +        controls->first_slice = 0;
4191 +    }
4192 +
4193 +    ret = v4l2_request_hevc_fill_slice_params(h, controls, slice);
4194 +    if (ret)
4195 +        return ret;
4196 +
4197 +    if (ctx->start_code == V4L2_STATELESS_HEVC_START_CODE_ANNEX_B) {
4198 +        ret = ff_v4l2_request_append_output_buffer(avctx, h->ref->frame, nalu_slice_start_code, 3);
4199 +        if (ret)
4200 +            return ret;
4201 +    }
4202 +
4203 +    ret = ff_v4l2_request_append_output_buffer(avctx, h->ref->frame, buffer, size);
4204 +    if (ret)
4205 +        return ret;
4206 +
4207 +    controls->slice_params[slice].bit_size = req->output.used * 8; //FIXME
4208 +    controls->num_slices++;
4209 +    return 0;
4210 +}
4211 +
4212 +static int v4l2_request_hevc_end_frame(AVCodecContext *avctx)
4213 +{
4214 +    const HEVCContext *h = avctx->priv_data;
4215 +    V4L2RequestControlsHEVC *controls = h->ref->hwaccel_picture_private;
4216 +    int ret;
4217 +
4218 +    ret = v4l2_request_hevc_queue_decode(avctx, 1);
4219 +
4220 +    av_freep(&controls->entry_point_offsets);
4221 +
4222 +    return ret;
4223 +}
4224 +
4225 +static int v4l2_request_hevc_set_controls(AVCodecContext *avctx)
4226 +{
4227 +    V4L2RequestContextHEVC *ctx = avctx->internal->hwaccel_priv_data;
4228 +    int ret;
4229 +
4230 +    struct v4l2_ext_control control[] = {
4231 +        { .id = V4L2_CID_STATELESS_HEVC_DECODE_MODE, },
4232 +        { .id = V4L2_CID_STATELESS_HEVC_START_CODE, },
4233 +    };
4234 +    struct v4l2_query_ext_ctrl entry_point_offsets = {
4235 +        .id = V4L2_CID_STATELESS_HEVC_ENTRY_POINT_OFFSETS,
4236 +    };
4237 +    struct v4l2_query_ext_ctrl slice_params = {
4238 +        .id = V4L2_CID_STATELESS_HEVC_SLICE_PARAMS,
4239 +    };
4240 +    struct v4l2_query_ext_ctrl scaling_matrix = {
4241 +        .id = V4L2_CID_STATELESS_HEVC_SCALING_MATRIX,
4242 +    };
4243 +
4244 +    ctx->decode_mode = ff_v4l2_request_query_control_default_value(avctx, V4L2_CID_STATELESS_HEVC_DECODE_MODE);
4245 +    if (ctx->decode_mode != V4L2_STATELESS_HEVC_DECODE_MODE_SLICE_BASED &&
4246 +        ctx->decode_mode != V4L2_STATELESS_HEVC_DECODE_MODE_FRAME_BASED) {
4247 +        av_log(avctx, AV_LOG_ERROR, "%s: unsupported decode mode, %d\n", __func__, ctx->decode_mode);
4248 +        return AVERROR(EINVAL);
4249 +    }
4250 +
4251 +    ctx->start_code = ff_v4l2_request_query_control_default_value(avctx, V4L2_CID_STATELESS_HEVC_START_CODE);
4252 +    if (ctx->start_code != V4L2_STATELESS_HEVC_START_CODE_NONE &&
4253 +        ctx->start_code != V4L2_STATELESS_HEVC_START_CODE_ANNEX_B) {
4254 +        av_log(avctx, AV_LOG_ERROR, "%s: unsupported start code, %d\n", __func__, ctx->start_code);
4255 +        return AVERROR(EINVAL);
4256 +    }
4257 +
4258 +    ret = ff_v4l2_request_query_control(avctx, &entry_point_offsets);
4259 +    if (ret) {
4260 +      ctx->supports_entry_point_offsets = 0;
4261 +    } else {
4262 +      ctx->supports_entry_point_offsets = 1;
4263 +    }
4264 +
4265 +    ret = ff_v4l2_request_query_control(avctx, &slice_params);
4266 +    if (ret) {
4267 +      ctx->supports_slices = 0;
4268 +      ctx->max_slices = 0;
4269 +      if (ctx->decode_mode == V4L2_STATELESS_HEVC_DECODE_MODE_SLICE_BASED) {
4270 +        av_log(avctx, AV_LOG_ERROR, "%s: decoder is slice-based, \
4271 +               but doesn't support V4L2_CID_STATELESS_HEVC_SLICE_PARAMS control \n", __func__);
4272 +        return AVERROR(EINVAL);
4273 +      }
4274 +
4275 +      if (ctx->supports_entry_point_offsets) {
4276 +        av_log(avctx, AV_LOG_ERROR, "%s: decoder supports entry_point_offsets, \
4277 +               but doesn't support V4L2_CID_STATELESS_HEVC_SLICE_PARAMS control \n", __func__);
4278 +        return AVERROR(EINVAL);
4279 +      }
4280 +    } else {
4281 +      ctx->supports_slices = 1;
4282 +      ctx->max_slices = slice_params.dims[0];
4283 +      if (ctx->max_slices > MAX_SLICES) {
4284 +        av_log(avctx, AV_LOG_ERROR, "%s: unsupported max slices, %u\n", __func__, ctx->max_slices);
4285 +        return AVERROR(EINVAL);
4286 +      }
4287 +    }
4288 +
4289 +    ret = ff_v4l2_request_query_control(avctx, &scaling_matrix);
4290 +    if (ret)
4291 +      ctx->supports_scaling_matrix = 0;
4292 +    else
4293 +      ctx->supports_scaling_matrix = 1;
4294 +
4295 +    av_log(avctx, AV_LOG_DEBUG, "%s: decoder is %s and supports slices %d, supports entry_point_offsets: %d supports scaling_matrix: %d max slices: %u\n",
4296 +           __func__,
4297 +          ctx->decode_mode == V4L2_STATELESS_HEVC_DECODE_MODE_SLICE_BASED ? "slice based" : "frame based",
4298 +          ctx->supports_slices,
4299 +          ctx->supports_entry_point_offsets,
4300 +          ctx->supports_scaling_matrix,
4301 +          ctx->max_slices
4302 +    );
4303 +
4304 +    control[0].value = ctx->decode_mode;
4305 +    control[1].value = ctx->start_code;
4306 +
4307 +    return ff_v4l2_request_set_controls(avctx, control, FF_ARRAY_ELEMS(control));
4308 +}
4309 +
4310 +static int v4l2_request_hevc_init(AVCodecContext *avctx)
4311 +{
4312 +    const HEVCContext *h = avctx->priv_data;
4313 +    struct v4l2_ctrl_hevc_sps sps;
4314 +    int ret;
4315 +
4316 +    struct v4l2_ext_control control[] = {
4317 +        {
4318 +            .id = V4L2_CID_STATELESS_HEVC_SPS,
4319 +            .ptr = &sps,
4320 +            .size = sizeof(sps),
4321 +        },
4322 +    };
4323 +
4324 +    fill_sps(&sps, h);
4325 +
4326 +    ret = ff_v4l2_request_init(avctx, V4L2_PIX_FMT_HEVC_SLICE, 4 * 1024 * 1024, control, FF_ARRAY_ELEMS(control));
4327 +    if (ret)
4328 +        return ret;
4329 +
4330 +    return v4l2_request_hevc_set_controls(avctx);
4331 +}
4332 +
4333 +const AVHWAccel ff_hevc_v4l2request_hwaccel = {
4334 +    .name           = "hevc_v4l2request",
4335 +    .type           = AVMEDIA_TYPE_VIDEO,
4336 +    .id             = AV_CODEC_ID_HEVC,
4337 +    .pix_fmt        = AV_PIX_FMT_DRM_PRIME,
4338 +    .start_frame    = v4l2_request_hevc_start_frame,
4339 +    .decode_slice   = v4l2_request_hevc_decode_slice,
4340 +    .end_frame      = v4l2_request_hevc_end_frame,
4341 +    .frame_priv_data_size = sizeof(V4L2RequestControlsHEVC),
4342 +    .init           = v4l2_request_hevc_init,
4343 +    .uninit         = ff_v4l2_request_uninit,
4344 +    .priv_data_size = sizeof(V4L2RequestContextHEVC),
4345 +    .frame_params   = ff_v4l2_request_frame_params,
4346 +    .caps_internal  = HWACCEL_CAP_ASYNC_SAFE,
4347 +};
This page took 0.345611 seconds and 3 git commands to generate.