[packages/ffmpeg] update v4l2_request patch
atler
atler at pld-linux.org
Tue Oct 27 16:10:10 CET 2026
commit cfb3bf8a9e7804b8141749d5ffd89ac75cc6a555
Author: Jan Palus <atler at pld-linux.org>
Date: Tue Oct 27 16:04:56 2026 +0100
update v4l2_request patch
based on https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847
v4l2-request-hwdec.patch | 9807 ++++++++++++++++++++++++----------------------
1 file changed, 5206 insertions(+), 4601 deletions(-)
---
diff --git a/v4l2-request-hwdec.patch b/v4l2-request-hwdec.patch
index 31740f4..8d4f69a 100644
--- a/v4l2-request-hwdec.patch
+++ b/v4l2-request-hwdec.patch
@@ -1,487 +1,173 @@
-V4L2 stateless Request API hwaccels (h264, hevc, vp8, vp9, mpeg2, av1) for FFmpeg.
-Out-of-tree series maintained by Jonas Karlman (Kwiboo); not merged upstream.
+From ea330b5f5e503039db5b48e7bec4e77976b7e3ee Mon Sep 17 00:00:00 2001
+From: Jonas Karlman <jonas at kwiboo.se>
+Date: Tue, 6 Aug 2024 09:06:00 +0000
+Subject: [PATCH 01/11] avutil/hwcontext: Add hwdevice type for V4L2 Request
+ API
-Source: https://github.com/Kwiboo/FFmpeg branch v4l2-request-n8.1
- combined diff: git diff n8.1..v4l2-request-n8.1
-Regenerate on ffmpeg bump from the matching v4l2-request-nX.Y branch.
-(No n9.x branch yet: n8.1 series with the configure --help context refreshed for 9.0.2.)
+Add a hwdevice type for use with V4L2 Request API stateless decoding.
+AVV4L2RequestFramesContext is expected to be filled with a V4L2 coded
+pixel format and optional codec-specific extended controls before an
+AVHWFramesContext is initialized.
+
+Once initialized AVV4L2RequestFramesContextInternal describe the opened
+V4L2 stateless decoder session, with details about media/video file
+descriptors, formats of CAPTURE/OUTPUT queues and buffer pools for
+creating CAPTURE/OUTPUT buffers.
+
+AVHWFramesContext.pool defaults to create frame descriptors around a
+CAPTURE buffer, and frames are returned with AVFrame.data[0] pointing
+to a AVDRMFrameDescriptor and AVFrame.data[1] the CAPTURE buffer index.
+
+Signed-off-by: Jonas Karlman <jonas at kwiboo.se>
+---
+ .forgejo/CODEOWNERS | 1 +
+ configure | 8 +
+ libavutil/Makefile | 4 +
+ libavutil/hwcontext.c | 4 +
+ libavutil/hwcontext.h | 1 +
+ libavutil/hwcontext_internal.h | 1 +
+ libavutil/hwcontext_v4l2request.c | 617 +++++++++++++++++++++
+ libavutil/hwcontext_v4l2request.h | 70 +++
+ libavutil/hwcontext_v4l2request_internal.h | 67 +++
+ 9 files changed, 773 insertions(+)
+ create mode 100644 libavutil/hwcontext_v4l2request.c
+ create mode 100644 libavutil/hwcontext_v4l2request.h
+ create mode 100644 libavutil/hwcontext_v4l2request_internal.h
+
+diff --git a/.forgejo/CODEOWNERS b/.forgejo/CODEOWNERS
+index 89e22d3c01f..6bd76dc7777 100644
+--- a/.forgejo/CODEOWNERS
++++ b/.forgejo/CODEOWNERS
+@@ -174,6 +174,7 @@ libavutil/film_grain.* @haasn
+ libavutil/dovi_meta.* @haasn
+ libavutil/hwcontext_oh.* @quink
+ libavutil/hwcontext_mediacodec.* @quink
++libavutil/hwcontext_v4l2request.* @Kwiboo @jernej @knaerzche
+ libavutil/hwcontext_videotoolbox.* @ePirat
+ libavutil/iamf.* @jamrial
+ libavutil/integer.* @michaelni
diff --git a/configure b/configure
-index 17596942749ab..3d4009f3480de 100755
+index 2f6167fddb2..872e3d57b4b 100755
--- a/configure
+++ b/configure
-@@ -364,6 +364,7 @@ External library support:
+@@ -368,6 +368,7 @@ External library support:
--disable-nvenc disable Nvidia video encoding code [autodetect]
--enable-rkmpp enable Rockchip Media Process Platform code [no]
--disable-v4l2-m2m disable V4L2 mem2mem code [autodetect]
-+ --disable-v4l2-request disable V4L2 Request API code [autodetect]
++ --enable-v4l2-request enable V4L2 Request API code [no]
--disable-vaapi disable Video Acceleration API (mainly Unix/Intel) code [autodetect]
--disable-vdpau disable Nvidia Video Decode and Presentation API for Unix code [autodetect]
--disable-videotoolbox disable VideoToolbox code [autodetect]
-@@ -2097,6 +2098,7 @@ EXTERNAL_LIBRARY_LIST="
- libtorch
- libtwolame
- libuavs3d
-+ libudev
- libv4l2
- libvmaf
- libvorbis
-@@ -2141,6 +2143,7 @@ HWACCEL_AUTODETECT_LIBRARY_LIST="
- videotoolbox
- vulkan
- v4l2_m2m
+@@ -2164,6 +2165,7 @@ HWACCEL_LIBRARY_LIST="
+ libvpl
+ mmal
+ opencl
+ v4l2_request
"
- # catchall list of things that require external libs to link
-@@ -2642,6 +2645,7 @@ TYPES_LIST="
- struct_sockaddr_sa_len
- struct_sockaddr_storage
- struct_stat_st_mtim_tv_nsec
-+ struct_v4l2_ctrl_hevc_decode_params_num_delta_pocs_of_ref_rps_idx
- struct_v4l2_frmivalenum_discrete
- struct_mfxConfigInterface
- "
-@@ -3341,6 +3345,8 @@ dxva2_deps="dxva2api_h DXVA2_ConfigPictureDecode ole32 user32"
+ DOCUMENT_LIST="
+@@ -3349,6 +3351,8 @@ dxva2_deps="dxva2api_h DXVA2_ConfigPictureDecode ole32 user32"
ffnvcodec_deps_any="libdl LoadLibrary"
mediacodec_deps="android mediandk pthreads"
nvdec_deps="ffnvcodec"
-+v4l2_request_deps="linux_media_h v4l2_timeval_to_ns v4l2_m2m_hold_capture_buf libdrm libudev"
-+v4l2_request_suggest="libdrm libudev"
++v4l2_request_deps="linux_media_h v4l2_timeval_to_ns libdrm"
++v4l2_request_suggest="libdrm"
vaapi_x11_deps="xlib_x11"
videotoolbox_hwaccel_deps="videotoolbox pthreads"
videotoolbox_hwaccel_extralibs="-framework QuartzCore"
-@@ -3357,6 +3363,8 @@ av1_dxva2_hwaccel_deps="dxva2 DXVA_PicParams_AV1"
- av1_dxva2_hwaccel_select="av1_decoder"
- av1_nvdec_hwaccel_deps="nvdec CUVIDAV1PICPARAMS"
- av1_nvdec_hwaccel_select="av1_decoder"
-+av1_v4l2request_hwaccel_deps="v4l2_request av1_v4l2_request"
-+av1_v4l2request_hwaccel_select="av1_decoder"
- av1_vaapi_hwaccel_deps="vaapi VADecPictureParameterBufferAV1_bit_depth_idx"
- av1_vaapi_hwaccel_select="av1_decoder"
- av1_vdpau_hwaccel_deps="vdpau VdpPictureInfoAV1"
-@@ -3383,6 +3391,8 @@ h264_dxva2_hwaccel_deps="dxva2"
- h264_dxva2_hwaccel_select="h264_decoder"
- h264_nvdec_hwaccel_deps="nvdec"
- h264_nvdec_hwaccel_select="h264_decoder"
-+h264_v4l2request_hwaccel_deps="v4l2_request h264_v4l2_request"
-+h264_v4l2request_hwaccel_select="h264_decoder"
- h264_vaapi_hwaccel_deps="vaapi"
- h264_vaapi_hwaccel_select="h264_decoder"
- h264_vdpau_hwaccel_deps="vdpau"
-@@ -3401,6 +3411,8 @@ hevc_dxva2_hwaccel_deps="dxva2 DXVA_PicParams_HEVC"
- hevc_dxva2_hwaccel_select="hevc_decoder"
- hevc_nvdec_hwaccel_deps="nvdec"
- hevc_nvdec_hwaccel_select="hevc_decoder"
-+hevc_v4l2request_hwaccel_deps="v4l2_request hevc_v4l2_request"
-+hevc_v4l2request_hwaccel_select="hevc_decoder"
- hevc_vaapi_hwaccel_deps="vaapi VAPictureParameterBufferHEVC"
- hevc_vaapi_hwaccel_select="hevc_decoder"
- hevc_vdpau_hwaccel_deps="vdpau VdpPictureInfoHEVC"
-@@ -3429,6 +3441,8 @@ mpeg2_dxva2_hwaccel_deps="dxva2"
- mpeg2_dxva2_hwaccel_select="mpeg2video_decoder"
- mpeg2_nvdec_hwaccel_deps="nvdec"
- mpeg2_nvdec_hwaccel_select="mpeg2video_decoder"
-+mpeg2_v4l2request_hwaccel_deps="v4l2_request mpeg2_v4l2_request"
-+mpeg2_v4l2request_hwaccel_select="mpeg2video_decoder"
- mpeg2_vaapi_hwaccel_deps="vaapi"
- mpeg2_vaapi_hwaccel_select="mpeg2video_decoder"
- mpeg2_vdpau_hwaccel_deps="vdpau"
-@@ -3465,6 +3479,8 @@ vc1_vdpau_hwaccel_deps="vdpau"
- vc1_vdpau_hwaccel_select="vc1_decoder"
- vp8_nvdec_hwaccel_deps="nvdec"
- vp8_nvdec_hwaccel_select="vp8_decoder"
-+vp8_v4l2request_hwaccel_deps="v4l2_request vp8_v4l2_request"
-+vp8_v4l2request_hwaccel_select="vp8_decoder"
- vp8_vaapi_hwaccel_deps="vaapi"
- vp8_vaapi_hwaccel_select="vp8_decoder"
- vp9_d3d11va_hwaccel_deps="d3d11va DXVA_PicParams_VP9"
-@@ -3477,6 +3493,8 @@ vp9_dxva2_hwaccel_deps="dxva2 DXVA_PicParams_VP9"
- vp9_dxva2_hwaccel_select="vp9_decoder"
- vp9_nvdec_hwaccel_deps="nvdec"
- vp9_nvdec_hwaccel_select="vp9_decoder"
-+vp9_v4l2request_hwaccel_deps="v4l2_request vp9_v4l2_request"
-+vp9_v4l2request_hwaccel_select="vp9_decoder"
- vp9_vaapi_hwaccel_deps="vaapi VADecPictureParameterBufferVP9_bit_depth"
- vp9_vaapi_hwaccel_select="vp9_decoder"
- vp9_vdpau_hwaccel_deps="vdpau VdpPictureInfoVP9"
-@@ -4309,7 +4327,7 @@ shader_compression_suggest="zlib"
-
- avcodec_extralibs="pthreads_extralibs iconv_extralibs dxva2_extralibs liblcevc_dec_extralibs lcms2_extralibs"
- avfilter_extralibs="pthreads_extralibs"
--avutil_extralibs="d3d11va_extralibs d3d12va_extralibs mediacodec_extralibs nanosleep_extralibs pthreads_extralibs vaapi_drm_extralibs vaapi_x11_extralibs vaapi_win32_extralibs vdpau_x11_extralibs"
-+avutil_extralibs="d3d11va_extralibs d3d12va_extralibs mediacodec_extralibs nanosleep_extralibs pthreads_extralibs v4l2_request_extralibs vaapi_drm_extralibs vaapi_x11_extralibs vaapi_win32_extralibs vdpau_x11_extralibs"
-
- # programs
- ffmpeg_deps="avcodec avfilter avformat threads"
-@@ -7588,6 +7606,20 @@ if enabled v4l2_m2m; then
+@@ -7598,6 +7602,10 @@ if enabled v4l2_m2m; then
check_cc vp9_v4l2_m2m linux/videodev2.h "int i = V4L2_PIX_FMT_VP9;"
fi
+if enabled v4l2_request; then
-+ check_cc av1_v4l2_request linux/videodev2.h "int i = V4L2_CID_STATELESS_AV1_SEQUENCE"
-+ check_cc h264_v4l2_request linux/videodev2.h "int i = V4L2_CID_STATELESS_H264_DECODE_MODE"
-+ check_cc hevc_v4l2_request linux/videodev2.h "int i = V4L2_CID_STATELESS_HEVC_SPS"
-+ check_cc mpeg2_v4l2_request linux/videodev2.h "int i = V4L2_CID_STATELESS_MPEG2_SEQUENCE"
-+ check_cc v4l2_m2m_hold_capture_buf linux/videodev2.h "int i = V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF"
-+ check_cc vp8_v4l2_request linux/videodev2.h "int i = V4L2_CID_STATELESS_VP8_FRAME"
-+ check_cc vp9_v4l2_request linux/videodev2.h "int i = V4L2_CID_STATELESS_VP9_FRAME"
+ check_func_headers "linux/media.h linux/videodev2.h" v4l2_timeval_to_ns
-+ check_pkg_config libudev libudev libudev.h udev_new
-+ check_struct linux/videodev2.h "struct v4l2_ctrl_hevc_decode_params" num_delta_pocs_of_ref_rps_idx
-+ v4l2_request_extralibs="$libudev_extralibs"
+fi
+
check_headers sys/videoio.h
test_code cc sys/videoio.h "struct v4l2_frmsizeenum vfse; vfse.discrete.width = 0;" && enable_sanitized struct_v4l2_frmivalenum_discrete
-diff --git a/libavcodec/Makefile b/libavcodec/Makefile
-index 12a8265025bc7..c6735d32a511a 100644
---- a/libavcodec/Makefile
-+++ b/libavcodec/Makefile
-@@ -185,6 +185,7 @@ OBJS-$(CONFIG_VIDEODSP) += videodsp.o
- OBJS-$(CONFIG_VP3DSP) += vp3dsp.o
- OBJS-$(CONFIG_VP8DSP) += vp8dsp.o
- OBJS-$(CONFIG_V4L2_M2M) += v4l2_m2m.o v4l2_context.o v4l2_buffers.o v4l2_fmt.o
-+OBJS-$(CONFIG_V4L2_REQUEST) += v4l2_request.o
- OBJS-$(CONFIG_WMA_FREQS) += wma_freqs.o
- OBJS-$(CONFIG_WMV2DSP) += wmv2dsp.o
-
-@@ -1050,6 +1051,7 @@ OBJS-$(CONFIG_AV1_D3D11VA_HWACCEL) += dxva2_av1.o
- OBJS-$(CONFIG_AV1_DXVA2_HWACCEL) += dxva2_av1.o
- OBJS-$(CONFIG_AV1_D3D12VA_HWACCEL) += dxva2_av1.o d3d12va_av1.o
- OBJS-$(CONFIG_AV1_NVDEC_HWACCEL) += nvdec_av1.o
-+OBJS-$(CONFIG_AV1_V4L2REQUEST_HWACCEL) += v4l2_request_av1.o
- OBJS-$(CONFIG_AV1_VAAPI_HWACCEL) += vaapi_av1.o
- OBJS-$(CONFIG_AV1_VDPAU_HWACCEL) += vdpau_av1.o
- OBJS-$(CONFIG_AV1_VIDEOTOOLBOX_HWACCEL) += videotoolbox_av1.o
-@@ -1063,6 +1065,7 @@ OBJS-$(CONFIG_H264_DXVA2_HWACCEL) += dxva2_h264.o
- OBJS-$(CONFIG_H264_D3D12VA_HWACCEL) += dxva2_h264.o d3d12va_h264.o
- OBJS-$(CONFIG_H264_NVDEC_HWACCEL) += nvdec_h264.o
- OBJS-$(CONFIG_H264_QSV_HWACCEL) += qsvdec.o
-+OBJS-$(CONFIG_H264_V4L2REQUEST_HWACCEL) += v4l2_request_h264.o
- OBJS-$(CONFIG_H264_VAAPI_HWACCEL) += vaapi_h264.o
- OBJS-$(CONFIG_H264_VDPAU_HWACCEL) += vdpau_h264.o
- OBJS-$(CONFIG_H264_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o
-@@ -1072,6 +1075,7 @@ OBJS-$(CONFIG_HEVC_DXVA2_HWACCEL) += dxva2_hevc.o
- OBJS-$(CONFIG_HEVC_D3D12VA_HWACCEL) += dxva2_hevc.o d3d12va_hevc.o
- OBJS-$(CONFIG_HEVC_NVDEC_HWACCEL) += nvdec_hevc.o
- OBJS-$(CONFIG_HEVC_QSV_HWACCEL) += qsvdec.o
-+OBJS-$(CONFIG_HEVC_V4L2REQUEST_HWACCEL) += v4l2_request_hevc.o
- OBJS-$(CONFIG_HEVC_VAAPI_HWACCEL) += vaapi_hevc.o h265_profile_level.o
- OBJS-$(CONFIG_HEVC_VDPAU_HWACCEL) += vdpau_hevc.o h265_profile_level.o
- OBJS-$(CONFIG_HEVC_VULKAN_HWACCEL) += vulkan_decode.o vulkan_hevc.o
-@@ -1085,6 +1089,7 @@ OBJS-$(CONFIG_MPEG2_DXVA2_HWACCEL) += dxva2_mpeg2.o
- OBJS-$(CONFIG_MPEG2_D3D12VA_HWACCEL) += dxva2_mpeg2.o d3d12va_mpeg2.o
- OBJS-$(CONFIG_MPEG2_NVDEC_HWACCEL) += nvdec_mpeg12.o
- OBJS-$(CONFIG_MPEG2_QSV_HWACCEL) += qsvdec.o
-+OBJS-$(CONFIG_MPEG2_V4L2REQUEST_HWACCEL) += v4l2_request_mpeg2.o
- OBJS-$(CONFIG_MPEG2_VAAPI_HWACCEL) += vaapi_mpeg2.o
- OBJS-$(CONFIG_MPEG2_VDPAU_HWACCEL) += vdpau_mpeg12.o
- OBJS-$(CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL) += videotoolbox.o
-@@ -1100,11 +1105,13 @@ OBJS-$(CONFIG_VC1_QSV_HWACCEL) += qsvdec.o
- OBJS-$(CONFIG_VC1_VAAPI_HWACCEL) += vaapi_vc1.o
- OBJS-$(CONFIG_VC1_VDPAU_HWACCEL) += vdpau_vc1.o
- OBJS-$(CONFIG_VP8_NVDEC_HWACCEL) += nvdec_vp8.o
-+OBJS-$(CONFIG_VP8_V4L2REQUEST_HWACCEL) += v4l2_request_vp8.o
- OBJS-$(CONFIG_VP8_VAAPI_HWACCEL) += vaapi_vp8.o
- OBJS-$(CONFIG_VP9_D3D11VA_HWACCEL) += dxva2_vp9.o
- OBJS-$(CONFIG_VP9_DXVA2_HWACCEL) += dxva2_vp9.o
- OBJS-$(CONFIG_VP9_D3D12VA_HWACCEL) += dxva2_vp9.o d3d12va_vp9.o
- OBJS-$(CONFIG_VP9_NVDEC_HWACCEL) += nvdec_vp9.o
-+OBJS-$(CONFIG_VP9_V4L2REQUEST_HWACCEL) += v4l2_request_vp9.o
- OBJS-$(CONFIG_VP9_VAAPI_HWACCEL) += vaapi_vp9.o
- OBJS-$(CONFIG_VP9_VDPAU_HWACCEL) += vdpau_vp9.o
- OBJS-$(CONFIG_VP9_VIDEOTOOLBOX_HWACCEL) += videotoolbox_vp9.o
-@@ -1360,6 +1367,7 @@ SKIPHEADERS-$(CONFIG_VIDEOTOOLBOX) += videotoolbox.h vt_internal.h
- SKIPHEADERS-$(CONFIG_VULKAN) += ffv1_vulkan.h prores_vulkan.h vulkan_video.h \
- vulkan_encode.h vulkan_decode.h
- SKIPHEADERS-$(CONFIG_V4L2_M2M) += v4l2_buffers.h v4l2_context.h v4l2_m2m.h
-+SKIPHEADERS-$(CONFIG_V4L2_REQUEST) += v4l2_request.h
- SKIPHEADERS-$(CONFIG_ZLIB) += zlib_wrapper.h
-
- TESTPROGS = avcodec \
-diff --git a/libavcodec/av1dec.c b/libavcodec/av1dec.c
-index ba8442077a9ec..dd89bf857bc57 100644
---- a/libavcodec/av1dec.c
-+++ b/libavcodec/av1dec.c
-@@ -542,6 +542,7 @@ static int get_pixel_format(AVCodecContext *avctx)
- CONFIG_AV1_D3D11VA_HWACCEL * 2 + \
- CONFIG_AV1_D3D12VA_HWACCEL + \
- CONFIG_AV1_NVDEC_HWACCEL + \
-+ CONFIG_AV1_V4L2REQUEST_HWACCEL + \
- CONFIG_AV1_VAAPI_HWACCEL + \
- CONFIG_AV1_VDPAU_HWACCEL + \
- CONFIG_AV1_VIDEOTOOLBOX_HWACCEL + \
-@@ -577,6 +578,9 @@ static int get_pixel_format(AVCodecContext *avctx)
- #endif
- #if CONFIG_AV1_VULKAN_HWACCEL
- *fmtp++ = AV_PIX_FMT_VULKAN;
-+#endif
-+#if CONFIG_AV1_V4L2REQUEST_HWACCEL
-+ *fmtp++ = AV_PIX_FMT_DRM_PRIME;
- #endif
- break;
- case AV_PIX_FMT_YUV420P10:
-@@ -604,6 +608,9 @@ static int get_pixel_format(AVCodecContext *avctx)
+diff --git a/libavutil/Makefile b/libavutil/Makefile
+index c5241895ff5..fa161b9bc58 100644
+--- a/libavutil/Makefile
++++ b/libavutil/Makefile
+@@ -52,6 +52,7 @@ HEADERS = adler32.h \
+ hwcontext_mediacodec.h \
+ hwcontext_opencl.h \
+ hwcontext_oh.h \
++ hwcontext_v4l2request.h \
+ hwcontext_vaapi.h \
+ hwcontext_videotoolbox.h \
+ hwcontext_vdpau.h \
+@@ -214,6 +215,7 @@ OBJS-$(CONFIG_MEDIACODEC) += hwcontext_mediacodec.o
+ OBJS-$(CONFIG_OHCODEC) += hwcontext_oh.o
+ OBJS-$(CONFIG_OPENCL) += hwcontext_opencl.o
+ OBJS-$(CONFIG_QSV) += hwcontext_qsv.o
++OBJS-$(CONFIG_V4L2_REQUEST) += hwcontext_v4l2request.o
+ OBJS-$(CONFIG_VAAPI) += hwcontext_vaapi.o
+ OBJS-$(CONFIG_VIDEOTOOLBOX) += hwcontext_videotoolbox.o
+ OBJS-$(CONFIG_VDPAU) += hwcontext_vdpau.o
+@@ -245,6 +247,8 @@ SKIPHEADERS-$(CONFIG_AMF) += hwcontext_amf.h \
+ hwcontext_amf_internal.h
+ SKIPHEADERS-$(CONFIG_QSV) += hwcontext_qsv.h
+ SKIPHEADERS-$(CONFIG_OPENCL) += hwcontext_opencl.h
++SKIPHEADERS-$(CONFIG_V4L2_REQUEST) += hwcontext_v4l2request.h \
++ hwcontext_v4l2request_internal.h
+ SKIPHEADERS-$(CONFIG_VAAPI) += hwcontext_vaapi.h
+ SKIPHEADERS-$(CONFIG_VIDEOTOOLBOX) += hwcontext_videotoolbox.h
+ SKIPHEADERS-$(CONFIG_VDPAU) += hwcontext_vdpau.h
+diff --git a/libavutil/hwcontext.c b/libavutil/hwcontext.c
+index 83bd7457e8e..7f93d90c8e0 100644
+--- a/libavutil/hwcontext.c
++++ b/libavutil/hwcontext.c
+@@ -71,6 +71,9 @@ static const HWContextType * const hw_table[] = {
#endif
- #if CONFIG_AV1_VULKAN_HWACCEL
- *fmtp++ = AV_PIX_FMT_VULKAN;
+ #if CONFIG_OHCODEC
+ &ff_hwcontext_type_oh,
+#endif
-+#if CONFIG_AV1_V4L2REQUEST_HWACCEL
-+ *fmtp++ = AV_PIX_FMT_DRM_PRIME;
- #endif
- break;
- case AV_PIX_FMT_YUV420P12:
-@@ -1630,6 +1637,9 @@ const FFCodec ff_av1_decoder = {
- #if CONFIG_AV1_VULKAN_HWACCEL
- HWACCEL_VULKAN(av1),
++#if CONFIG_V4L2_REQUEST
++ &ff_hwcontext_type_v4l2request,
#endif
-+#if CONFIG_AV1_V4L2REQUEST_HWACCEL
-+ HWACCEL_V4L2REQUEST(av1),
-+#endif
-
- NULL
- },
-diff --git a/libavcodec/h264_slice.c b/libavcodec/h264_slice.c
-index 0ce8e46c72b4a..97fab7085c726 100644
---- a/libavcodec/h264_slice.c
-+++ b/libavcodec/h264_slice.c
-@@ -789,6 +789,7 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
- (CONFIG_H264_D3D11VA_HWACCEL * 2) + \
- CONFIG_H264_D3D12VA_HWACCEL + \
- CONFIG_H264_NVDEC_HWACCEL + \
-+ CONFIG_H264_V4L2REQUEST_HWACCEL + \
- CONFIG_H264_VAAPI_HWACCEL + \
- CONFIG_H264_VIDEOTOOLBOX_HWACCEL + \
- CONFIG_H264_VDPAU_HWACCEL + \
-@@ -817,6 +818,9 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
- #endif
- #if CONFIG_H264_NVDEC_HWACCEL
- *fmt++ = AV_PIX_FMT_CUDA;
-+#endif
-+#if CONFIG_H264_V4L2REQUEST_HWACCEL
-+ *fmt++ = AV_PIX_FMT_DRM_PRIME;
- #endif
- if (CHROMA444(h)) {
- if (h->avctx->colorspace == AVCOL_SPC_RGB) {
-@@ -873,6 +877,9 @@ static enum AVPixelFormat get_pixel_format(H264Context *h, int force_callback)
- #if CONFIG_H264_VIDEOTOOLBOX_HWACCEL
- if (h->avctx->colorspace != AVCOL_SPC_RGB)
- *fmt++ = AV_PIX_FMT_VIDEOTOOLBOX;
-+#endif
-+#if CONFIG_H264_V4L2REQUEST_HWACCEL
-+ *fmt++ = AV_PIX_FMT_DRM_PRIME;
- #endif
- if (CHROMA444(h)) {
- if (h->avctx->colorspace == AVCOL_SPC_RGB)
-@@ -1701,7 +1708,7 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
- unsigned int slice_type, tmp, i;
- int field_pic_flag, bottom_field_flag;
- int first_slice = sl == h->slice_ctx && !h->current_slice;
-- int picture_structure;
-+ int picture_structure, pos;
-
- if (first_slice)
- av_assert0(!h->setup_finished);
-@@ -1792,6 +1799,7 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
-
- sl->poc_lsb = 0;
- sl->delta_poc_bottom = 0;
-+ pos = get_bits_left(&sl->gb);
- if (sps->poc_type == 0) {
- sl->poc_lsb = get_bits(&sl->gb, sps->log2_max_poc_lsb);
-
-@@ -1806,6 +1814,7 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
- if (pps->pic_order_present == 1 && picture_structure == PICT_FRAME)
- sl->delta_poc[1] = get_se_golomb(&sl->gb);
- }
-+ sl->pic_order_cnt_bit_size = pos - get_bits_left(&sl->gb);
-
- sl->redundant_pic_count = 0;
- if (pps->redundant_pic_cnt_present)
-@@ -1845,9 +1854,11 @@ static int h264_slice_header_parse(const H264Context *h, H264SliceContext *sl,
-
- sl->explicit_ref_marking = 0;
- if (nal->ref_idc) {
-+ pos = get_bits_left(&sl->gb);
- ret = ff_h264_decode_ref_pic_marking(sl, &sl->gb, nal, h->avctx);
- if (ret < 0 && (h->avctx->err_recognition & AV_EF_EXPLODE))
- return AVERROR_INVALIDDATA;
-+ sl->ref_pic_marking_bit_size = pos - get_bits_left(&sl->gb);
- }
-
- if (sl->slice_type_nos != AV_PICTURE_TYPE_I && pps->cabac) {
-diff --git a/libavcodec/h264dec.c b/libavcodec/h264dec.c
-index 809a938386438..6c4ce97f63f99 100644
---- a/libavcodec/h264dec.c
-+++ b/libavcodec/h264dec.c
-@@ -1144,6 +1144,9 @@ const FFCodec ff_h264_decoder = {
- #endif
- #if CONFIG_H264_VULKAN_HWACCEL
- HWACCEL_VULKAN(h264),
-+#endif
-+#if CONFIG_H264_V4L2REQUEST_HWACCEL
-+ HWACCEL_V4L2REQUEST(h264),
- #endif
- NULL
- },
-diff --git a/libavcodec/h264dec.h b/libavcodec/h264dec.h
-index 74fd09dfaacd0..33d788627f383 100644
---- a/libavcodec/h264dec.h
-+++ b/libavcodec/h264dec.h
-@@ -322,6 +322,7 @@ typedef struct H264SliceContext {
- MMCO mmco[H264_MAX_MMCO_COUNT];
- int nb_mmco;
- int explicit_ref_marking;
-+ int ref_pic_marking_bit_size;
-
- int frame_num;
- int idr_pic_id;
-@@ -330,6 +331,7 @@ typedef struct H264SliceContext {
- int delta_poc[2];
- int curr_pic_num;
- int max_pic_num;
-+ int pic_order_cnt_bit_size;
- } H264SliceContext;
+ NULL,
+ };
+@@ -83,6 +86,7 @@ static const char *const hw_type_names[] = {
+ [AV_HWDEVICE_TYPE_D3D12VA] = "d3d12va",
+ [AV_HWDEVICE_TYPE_OPENCL] = "opencl",
+ [AV_HWDEVICE_TYPE_QSV] = "qsv",
++ [AV_HWDEVICE_TYPE_V4L2REQUEST] = "v4l2request",
+ [AV_HWDEVICE_TYPE_VAAPI] = "vaapi",
+ [AV_HWDEVICE_TYPE_VDPAU] = "vdpau",
+ [AV_HWDEVICE_TYPE_VIDEOTOOLBOX] = "videotoolbox",
+diff --git a/libavutil/hwcontext.h b/libavutil/hwcontext.h
+index 29374cf0a7e..88e47cc7f51 100644
+--- a/libavutil/hwcontext.h
++++ b/libavutil/hwcontext.h
+@@ -41,6 +41,7 @@ enum AVHWDeviceType {
+ AV_HWDEVICE_TYPE_AMF,
+ /* OpenHarmony Codec device */
+ AV_HWDEVICE_TYPE_OHCODEC,
++ AV_HWDEVICE_TYPE_V4L2REQUEST,
+ };
/**
-diff --git a/libavcodec/hevc/hevcdec.c b/libavcodec/hevc/hevcdec.c
-index ae5f0fe69d895..647251e6f0248 100644
---- a/libavcodec/hevc/hevcdec.c
-+++ b/libavcodec/hevc/hevcdec.c
-@@ -580,6 +580,7 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
- CONFIG_HEVC_D3D11VA_HWACCEL * 2 + \
- CONFIG_HEVC_D3D12VA_HWACCEL + \
- CONFIG_HEVC_NVDEC_HWACCEL + \
-+ CONFIG_HEVC_V4L2REQUEST_HWACCEL + \
- CONFIG_HEVC_VAAPI_HWACCEL + \
- CONFIG_HEVC_VIDEOTOOLBOX_HWACCEL + \
- CONFIG_HEVC_VDPAU_HWACCEL + \
-@@ -618,6 +619,9 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
- #endif
- #if CONFIG_HEVC_VULKAN_HWACCEL
- *fmt++ = AV_PIX_FMT_VULKAN;
-+#endif
-+#if CONFIG_HEVC_V4L2REQUEST_HWACCEL
-+ *fmt++ = AV_PIX_FMT_DRM_PRIME;
- #endif
- break;
- case AV_PIX_FMT_YUV420P10:
-@@ -645,6 +649,9 @@ static enum AVPixelFormat get_format(HEVCContext *s, const HEVCSPS *sps)
- #endif
- #if CONFIG_HEVC_NVDEC_HWACCEL
- *fmt++ = AV_PIX_FMT_CUDA;
-+#endif
-+#if CONFIG_HEVC_V4L2REQUEST_HWACCEL
-+ *fmt++ = AV_PIX_FMT_DRM_PRIME;
- #endif
- break;
- case AV_PIX_FMT_YUV444P:
-@@ -4280,6 +4287,9 @@ const FFCodec ff_hevc_decoder = {
- #endif
- #if CONFIG_HEVC_VULKAN_HWACCEL
- HWACCEL_VULKAN(hevc),
-+#endif
-+#if CONFIG_HEVC_V4L2REQUEST_HWACCEL
-+ HWACCEL_V4L2REQUEST(hevc),
- #endif
- NULL
- },
-diff --git a/libavcodec/hwaccels.h b/libavcodec/hwaccels.h
-index 3de191288a597..7b6f67330a3cd 100644
---- a/libavcodec/hwaccels.h
-+++ b/libavcodec/hwaccels.h
-@@ -24,6 +24,7 @@ extern const struct FFHWAccel ff_av1_d3d11va2_hwaccel;
- extern const struct FFHWAccel ff_av1_d3d12va_hwaccel;
- extern const struct FFHWAccel ff_av1_dxva2_hwaccel;
- extern const struct FFHWAccel ff_av1_nvdec_hwaccel;
-+extern const struct FFHWAccel ff_av1_v4l2request_hwaccel;
- extern const struct FFHWAccel ff_av1_vaapi_hwaccel;
- extern const struct FFHWAccel ff_av1_vdpau_hwaccel;
- extern const struct FFHWAccel ff_av1_videotoolbox_hwaccel;
-@@ -37,6 +38,7 @@ extern const struct FFHWAccel ff_h264_d3d11va2_hwaccel;
- extern const struct FFHWAccel ff_h264_d3d12va_hwaccel;
- extern const struct FFHWAccel ff_h264_dxva2_hwaccel;
- extern const struct FFHWAccel ff_h264_nvdec_hwaccel;
-+extern const struct FFHWAccel ff_h264_v4l2request_hwaccel;
- extern const struct FFHWAccel ff_h264_vaapi_hwaccel;
- extern const struct FFHWAccel ff_h264_vdpau_hwaccel;
- extern const struct FFHWAccel ff_h264_videotoolbox_hwaccel;
-@@ -46,6 +48,7 @@ extern const struct FFHWAccel ff_hevc_d3d11va2_hwaccel;
- extern const struct FFHWAccel ff_hevc_d3d12va_hwaccel;
- extern const struct FFHWAccel ff_hevc_dxva2_hwaccel;
- extern const struct FFHWAccel ff_hevc_nvdec_hwaccel;
-+extern const struct FFHWAccel ff_hevc_v4l2request_hwaccel;
- extern const struct FFHWAccel ff_hevc_vaapi_hwaccel;
- extern const struct FFHWAccel ff_hevc_vdpau_hwaccel;
- extern const struct FFHWAccel ff_hevc_videotoolbox_hwaccel;
-@@ -60,6 +63,7 @@ extern const struct FFHWAccel ff_mpeg2_d3d11va2_hwaccel;
- extern const struct FFHWAccel ff_mpeg2_d3d12va_hwaccel;
- extern const struct FFHWAccel ff_mpeg2_dxva2_hwaccel;
- extern const struct FFHWAccel ff_mpeg2_nvdec_hwaccel;
-+extern const struct FFHWAccel ff_mpeg2_v4l2request_hwaccel;
- extern const struct FFHWAccel ff_mpeg2_vaapi_hwaccel;
- extern const struct FFHWAccel ff_mpeg2_vdpau_hwaccel;
- extern const struct FFHWAccel ff_mpeg2_videotoolbox_hwaccel;
-@@ -78,12 +82,14 @@ extern const struct FFHWAccel ff_vc1_nvdec_hwaccel;
- extern const struct FFHWAccel ff_vc1_vaapi_hwaccel;
- extern const struct FFHWAccel ff_vc1_vdpau_hwaccel;
- extern const struct FFHWAccel ff_vp8_nvdec_hwaccel;
-+extern const struct FFHWAccel ff_vp8_v4l2request_hwaccel;
- extern const struct FFHWAccel ff_vp8_vaapi_hwaccel;
- extern const struct FFHWAccel ff_vp9_d3d11va_hwaccel;
- extern const struct FFHWAccel ff_vp9_d3d11va2_hwaccel;
- extern const struct FFHWAccel ff_vp9_d3d12va_hwaccel;
- extern const struct FFHWAccel ff_vp9_dxva2_hwaccel;
- extern const struct FFHWAccel ff_vp9_nvdec_hwaccel;
-+extern const struct FFHWAccel ff_vp9_v4l2request_hwaccel;
- extern const struct FFHWAccel ff_vp9_vaapi_hwaccel;
- extern const struct FFHWAccel ff_vp9_vdpau_hwaccel;
- extern const struct FFHWAccel ff_vp9_videotoolbox_hwaccel;
-diff --git a/libavcodec/hwconfig.h b/libavcodec/hwconfig.h
-index ee29ca631df03..159064a1f14cd 100644
---- a/libavcodec/hwconfig.h
-+++ b/libavcodec/hwconfig.h
-@@ -79,6 +79,8 @@ void ff_hwaccel_uninit(AVCodecContext *avctx);
- HW_CONFIG_HWACCEL(0, 0, 1, D3D11VA_VLD, NONE, ff_ ## codec ## _d3d11va_hwaccel)
- #define HWACCEL_D3D12VA(codec) \
- HW_CONFIG_HWACCEL(1, 1, 0, D3D12, D3D12VA, ff_ ## codec ## _d3d12va_hwaccel)
-+#define HWACCEL_V4L2REQUEST(codec) \
-+ HW_CONFIG_HWACCEL(1, 0, 0, DRM_PRIME, V4L2REQUEST, ff_ ## codec ## _v4l2request_hwaccel)
-
- #define HW_CONFIG_ENCODER(device, frames, ad_hoc, format, device_type_) \
- &(const AVCodecHWConfigInternal) { \
-diff --git a/libavcodec/mpeg12dec.c b/libavcodec/mpeg12dec.c
-index 4c83bcfa90e3f..c65e9e3b86a88 100644
---- a/libavcodec/mpeg12dec.c
-+++ b/libavcodec/mpeg12dec.c
-@@ -821,6 +821,9 @@ static const enum AVPixelFormat mpeg2_hwaccel_pixfmt_list_420[] = {
- #endif
- #if CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL
- AV_PIX_FMT_VIDEOTOOLBOX,
-+#endif
-+#if CONFIG_MPEG2_V4L2REQUEST_HWACCEL
-+ AV_PIX_FMT_DRM_PRIME,
- #endif
- AV_PIX_FMT_YUV420P,
- AV_PIX_FMT_NONE
-@@ -2736,6 +2739,9 @@ const FFCodec ff_mpeg2video_decoder = {
- #endif
- #if CONFIG_MPEG2_VIDEOTOOLBOX_HWACCEL
- HWACCEL_VIDEOTOOLBOX(mpeg2),
-+#endif
-+#if CONFIG_MPEG2_V4L2REQUEST_HWACCEL
-+ HWACCEL_V4L2REQUEST(mpeg2),
- #endif
- NULL
- },
-diff --git a/libavcodec/v4l2_request.c b/libavcodec/v4l2_request.c
+diff --git a/libavutil/hwcontext_internal.h b/libavutil/hwcontext_internal.h
+index dcfdc2016a3..94e4da16c0c 100644
+--- a/libavutil/hwcontext_internal.h
++++ b/libavutil/hwcontext_internal.h
+@@ -158,6 +158,7 @@ extern const HWContextType ff_hwcontext_type_drm;
+ extern const HWContextType ff_hwcontext_type_dxva2;
+ extern const HWContextType ff_hwcontext_type_opencl;
+ extern const HWContextType ff_hwcontext_type_qsv;
++extern const HWContextType ff_hwcontext_type_v4l2request;
+ extern const HWContextType ff_hwcontext_type_vaapi;
+ extern const HWContextType ff_hwcontext_type_vdpau;
+ extern const HWContextType ff_hwcontext_type_videotoolbox;
+diff --git a/libavutil/hwcontext_v4l2request.c b/libavutil/hwcontext_v4l2request.c
new file mode 100644
-index 0000000000000..36eec8540295a
+index 00000000000..3d92b633675
--- /dev/null
-+++ b/libavcodec/v4l2_request.c
-@@ -0,0 +1,784 @@
++++ b/libavutil/hwcontext_v4l2request.c
+@@ -0,0 +1,617 @@
+/*
+ * This file is part of FFmpeg.
+ *
@@ -502,2067 +188,2612 @@ index 0000000000000..36eec8540295a
+
+#include "config.h"
+
++#include <fcntl.h>
++#include <linux/dma-buf.h>
+#include <linux/media.h>
-+#include <poll.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
-+#include "libavutil/hwcontext_v4l2request_internal.h"
-+#include "libavutil/mem.h"
-+#include "decode.h"
-+#include "internal.h"
-+#include "v4l2_request.h"
-+
-+#define V4L2_PLANES_MAX 2
++#include <drm_fourcc.h>
+
-+static const AVClass v4l2_request_context_class = {
-+ .class_name = "V4L2RequestContext",
-+ .item_name = av_default_item_name,
-+ .version = LIBAVUTIL_VERSION_INT,
-+};
++#include "avassert.h"
++#include "hwcontext_drm.h"
++#include "hwcontext_internal.h"
++#include "hwcontext_v4l2request_internal.h"
++#include "mem.h"
+
-+static inline V4L2RequestContext *v4l2_request_context(AVCodecContext *avctx)
-+{
-+ return (V4L2RequestContext *)avctx->internal->hwaccel_priv_data;
-+}
++typedef struct V4L2RequestDeviceContext {
++} V4L2RequestDeviceContext;
+
-+static inline uint32_t v4l2_request_frameindex(AVFrame *frame)
-+{
-+ return (uint32_t)(uintptr_t)frame->data[1];
-+}
++typedef struct V4L2RequestFramesContext {
++ AVV4L2RequestFramesContext p;
++ AVV4L2RequestFramesContextInternal internal;
++} V4L2RequestFramesContext;
+
-+uint64_t ff_v4l2_request_get_capture_timestamp(AVFrame *frame)
-+{
-+ /*
-+ * The CAPTURE buffer index is used as a base for V4L2 frame reference.
-+ * This works because frames are decoded into a CAPTURE buffer that is
-+ * closely tied to an AVFrame.
-+ */
-+ struct timeval timestamp = {
-+ .tv_sec = 0,
-+ .tv_usec = v4l2_request_frameindex(frame) + 1,
-+ };
-+ return v4l2_timeval_to_ns(×tamp);
-+}
++typedef struct V4L2RequestFrameDescriptor {
++ AVDRMFrameDescriptor base;
++ AVBufferRef *ref;
++ uint32_t index;
++ int fd[AV_DRM_MAX_PLANES];
++} V4L2RequestFrameDescriptor;
+
-+int ff_v4l2_request_query_control(AVCodecContext *avctx,
-+ struct v4l2_query_ext_ctrl *control)
++static const struct {
++ uint32_t pixelformat;
++ enum AVPixelFormat sw_format;
++ uint32_t drm_format;
++ uint64_t format_modifier;
++ uint32_t bit_depth;
++} v4l2request_capture_pixelformats[] = {
++ { V4L2_PIX_FMT_NV12, AV_PIX_FMT_NV12, DRM_FORMAT_NV12, DRM_FORMAT_MOD_LINEAR, 8 },
++#if defined(V4L2_PIX_FMT_NV12_32L32)
++ { V4L2_PIX_FMT_NV12_32L32, AV_PIX_FMT_YUV420P, DRM_FORMAT_NV12, DRM_FORMAT_MOD_ALLWINNER_TILED, 8 },
++#endif
++#if defined(V4L2_PIX_FMT_NV15) && defined(DRM_FORMAT_NV15)
++ { V4L2_PIX_FMT_NV15, AV_PIX_FMT_YUV420P10, DRM_FORMAT_NV15, DRM_FORMAT_MOD_LINEAR, 10 },
++#endif
++ { V4L2_PIX_FMT_NV16, AV_PIX_FMT_NV16, DRM_FORMAT_NV16, DRM_FORMAT_MOD_LINEAR, 8 },
++#if defined(V4L2_PIX_FMT_NV20) && defined(DRM_FORMAT_NV20)
++ { V4L2_PIX_FMT_NV20, AV_PIX_FMT_YUV422P10, DRM_FORMAT_NV20, DRM_FORMAT_MOD_LINEAR, 10 },
++#endif
++#if defined(V4L2_PIX_FMT_P010) && defined(DRM_FORMAT_P010)
++ { V4L2_PIX_FMT_P010, AV_PIX_FMT_P010, DRM_FORMAT_P010, DRM_FORMAT_MOD_LINEAR, 10 },
++#endif
++#if defined(V4L2_PIX_FMT_NV12MT_COL128) && defined(V4L2_PIX_FMT_NV12MT_10_COL128)
++ { V4L2_PIX_FMT_NV12MT_COL128, AV_PIX_FMT_YUV420P, DRM_FORMAT_NV12, DRM_FORMAT_MOD_BROADCOM_SAND128, 8 },
++#if defined(DRM_FORMAT_P030)
++ { V4L2_PIX_FMT_NV12MT_10_COL128, AV_PIX_FMT_YUV420P10, DRM_FORMAT_P030, DRM_FORMAT_MOD_BROADCOM_SAND128, 10 },
++#endif
++#endif
++};
++
++static int v4l2request_set_drm_descriptor(AVDRMFrameDescriptor *desc,
++ struct v4l2_format *format)
+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
++ AVDRMLayerDescriptor *layer = &desc->layers[0];
++ uint32_t pixelformat = V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
++ format->fmt.pix_mp.pixelformat :
++ format->fmt.pix.pixelformat;
++ uint64_t format_modifier;
+
-+ if (ioctl(ctx->fctxi->video_fd, VIDIOC_QUERY_EXT_CTRL, control) < 0) {
-+ int ret = AVERROR(errno);
-+ // Skip error logging when driver does not support control id (EINVAL)
-+ if (errno != EINVAL)
-+ av_log(ctx, AV_LOG_ERROR, "Failed to query control %u: %s (%d)\n",
-+ control->id, strerror(errno), errno);
-+ return ret;
++ layer->format = 0;
++ for (int i = 0; i < FF_ARRAY_ELEMS(v4l2request_capture_pixelformats); i++) {
++ if (pixelformat == v4l2request_capture_pixelformats[i].pixelformat) {
++ layer->format = v4l2request_capture_pixelformats[i].drm_format;
++ format_modifier = v4l2request_capture_pixelformats[i].format_modifier;
++ break;
++ }
+ }
++ if (!layer->format)
++ return AVERROR(ENOENT);
+
-+ return 0;
-+}
-+
-+int ff_v4l2_request_query_control_default_value(AVCodecContext *avctx,
-+ uint32_t id)
-+{
-+ struct v4l2_query_ext_ctrl control = {
-+ .id = id,
-+ };
-+ int ret;
-+
-+ ret = ff_v4l2_request_query_control(avctx, &control);
-+ if (ret < 0)
-+ return ret;
++ for (int i = 0; i < desc->nb_objects; i++) {
++ desc->objects[i].format_modifier = format_modifier;
++ desc->objects[i].size = V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
++ format->fmt.pix_mp.plane_fmt[i].sizeimage :
++ format->fmt.pix.sizeimage;
++ }
+
-+ return control.default_value;
-+}
++ desc->nb_layers = 1;
++ layer->nb_planes = 2;
+
-+static int v4l2_request_set_controls(V4L2RequestContext *ctx, int request_fd,
-+ struct v4l2_ext_control *control, int count)
-+{
-+ struct v4l2_ext_controls controls = {
-+ .controls = control,
-+ .count = count,
-+ .request_fd = request_fd,
-+ .which = (request_fd >= 0) ? V4L2_CTRL_WHICH_REQUEST_VAL : 0,
-+ };
++ layer->planes[0].object_index = 0;
++ layer->planes[0].offset = 0;
++ layer->planes[0].pitch = V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
++ format->fmt.pix_mp.plane_fmt[0].bytesperline :
++ format->fmt.pix.bytesperline;
+
-+ if (!control || !count)
-+ return 0;
++ layer->planes[1].object_index = 0;
++ layer->planes[1].offset = layer->planes[0].pitch *
++ (V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
++ format->fmt.pix_mp.height :
++ format->fmt.pix.height);
++ layer->planes[1].pitch = layer->planes[0].pitch;
+
-+ if (ioctl(ctx->fctxi->video_fd, VIDIOC_S_EXT_CTRLS, &controls) < 0)
-+ return AVERROR(errno);
++#if defined(V4L2_PIX_FMT_NV12MT_COL128) && defined(V4L2_PIX_FMT_NV12MT_10_COL128)
++ // Raspberry Pi formats need special handling
++ if (pixelformat == V4L2_PIX_FMT_NV12MT_COL128 ||
++ pixelformat == V4L2_PIX_FMT_NV12MT_10_COL128) {
++ layer->planes[1].object_index = 1;
++ layer->planes[1].offset = 0;
++ layer->planes[0].pitch = (V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
++ format->fmt.pix_mp.height :
++ format->fmt.pix.height);
++ layer->planes[1].pitch = layer->planes[0].pitch / 2;
++ }
++#endif
+
+ return 0;
+}
+
-+int ff_v4l2_request_set_controls(AVCodecContext *avctx,
-+ struct v4l2_ext_control *control, int count)
++static void v4l2request_device_uninit(AVHWDeviceContext *hwdev)
+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
-+ int ret;
-+
-+ ret = v4l2_request_set_controls(ctx, -1, control, count);
-+ if (ret < 0)
-+ av_log(ctx, AV_LOG_ERROR, "Failed to set %d control(s): %s (%d)\n",
-+ count, strerror(errno), errno);
-+
-+ return ret;
+}
+
-+static int v4l2_request_queue_buffer(V4L2RequestContext *ctx,
-+ struct v4l2_buffer *buffer)
++static int v4l2request_device_create(AVHWDeviceContext *hwdev, const char *device,
++ AVDictionary *opts, int flags)
+{
-+ struct v4l2_plane planes[V4L2_PLANES_MAX] = {};
++ return 0;
++}
+
-+ if (V4L2_TYPE_IS_MULTIPLANAR(buffer->type)) {
-+ planes[0].bytesused = buffer->bytesused;
-+ buffer->bytesused = 0;
-+ buffer->length = FF_ARRAY_ELEMS(planes);
-+ buffer->m.planes = planes;
-+ }
++static int v4l2request_open_decoder(AVHWFramesContext *hwfc)
++{
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
+
-+ // Queue the buffer
-+ if (ioctl(ctx->fctxi->video_fd, VIDIOC_QBUF, buffer) < 0)
-+ return AVERROR(errno);
++ // Ensure codec pixelformat is set
++ if (!fctx->pixelformat)
++ return AVERROR(EINVAL);
+
-+ // Mark the buffer as queued
-+ if (V4L2_TYPE_IS_OUTPUT(buffer->type))
-+ ctx->queued_output |= 1 << buffer->index;
-+ else
-+ ctx->queued_capture |= 1 << buffer->index;
++ // TODO: locate a decoder supporting the requested pixelformat
+
-+ return 0;
++ return AVERROR(ENOSYS);
+}
+
-+static int v4l2_request_queue_capture_buffer(V4L2RequestContext *ctx,
-+ uint32_t index)
++static AVBufferRef *v4l2request_v4l2_buffer_alloc(AVHWFramesContext *hwfc,
++ struct v4l2_format *format)
+{
-+ struct v4l2_buffer buffer = {
-+ .index = index,
-+ .type = ctx->fctxi->capture.format.type,
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ struct v4l2_create_buffers buffers = {
++ .count = 1,
+ .memory = V4L2_MEMORY_MMAP,
++ .format = *format,
+ };
-+ return v4l2_request_queue_buffer(ctx, &buffer);
-+}
++ struct v4l2_buffer *buffer;
++ uint8_t num_planes;
++ AVBufferRef *ref;
+
-+static int v4l2_request_queue_output_buffer(V4L2RequestContext *ctx,
-+ V4L2RequestOutputBuffer *output,
-+ uint32_t flags)
-+{
-+ struct v4l2_buffer buffer = {
-+ .index = output->index,
-+ .type = ctx->fctxi->output.format.type,
-+ .memory = V4L2_MEMORY_MMAP,
-+ .timestamp = output->timestamp,
-+ .bytesused = output->bytesused,
-+ .request_fd = output->request_fd,
-+ .flags = V4L2_BUF_FLAG_REQUEST_FD | flags,
-+ };
-+ return v4l2_request_queue_buffer(ctx, &buffer);
-+}
++ num_planes = V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
++ format->fmt.pix_mp.num_planes : 0;
+
-+static int v4l2_request_dequeue_buffer(V4L2RequestContext *ctx,
-+ enum v4l2_buf_type type)
-+{
-+ struct v4l2_plane planes[V4L2_PLANES_MAX] = {};
-+ struct v4l2_buffer buffer = {
-+ .type = type,
-+ .memory = V4L2_MEMORY_MMAP,
-+ };
++ ref = av_buffer_allocz(sizeof(struct v4l2_buffer) +
++ (sizeof(struct v4l2_plane) * num_planes));
++ if (!ref)
++ return NULL;
+
-+ if (V4L2_TYPE_IS_MULTIPLANAR(buffer.type)) {
-+ buffer.length = FF_ARRAY_ELEMS(planes);
-+ buffer.m.planes = planes;
-+ }
++ buffer = (struct v4l2_buffer *)ref->data;
++ buffer->type = format->type;
+
-+ // Dequeue next completed buffer
-+ if (ioctl(ctx->fctxi->video_fd, VIDIOC_DQBUF, &buffer) < 0)
-+ return AVERROR(errno);
++ if (num_planes) {
++ buffer->length = num_planes;
++ buffer->m.planes = (struct v4l2_plane *)(buffer + 1);
++ }
+
-+ // Mark the buffer as dequeued
-+ if (V4L2_TYPE_IS_OUTPUT(buffer.type))
-+ ctx->queued_output &= ~(1 << buffer.index);
-+ else
-+ ctx->queued_capture &= ~(1 << buffer.index);
++ // Create the buffer
++ if (ioctl(fctxi->video_fd, VIDIOC_CREATE_BUFS, &buffers) < 0) {
++ av_log(hwfc, AV_LOG_ERROR, "Failed to create buffer of type %d: %s (%d)\n",
++ buffer->type, strerror(errno), errno);
++ goto fail;
++ }
+
-+ return 0;
-+}
++ buffer->memory = buffers.memory;
++ buffer->index = buffers.index;
+
-+static inline int v4l2_request_dequeue_completed_buffers(V4L2RequestContext *ctx,
-+ enum v4l2_buf_type type)
-+{
-+ int ret;
++ // Query more details of the created buffer
++ if (ioctl(fctxi->video_fd, VIDIOC_QUERYBUF, buffer) < 0) {
++ av_log(hwfc, AV_LOG_ERROR, "Failed to query buffer %d of type %d: %s (%d)\n",
++ buffer->index, buffer->type, strerror(errno), errno);
++ goto fail;
++ }
+
-+ do {
-+ ret = v4l2_request_dequeue_buffer(ctx, type);
-+ } while (!ret);
++ return ref;
+
-+ return ret;
++fail:
++ av_buffer_unref(&ref);
++ return NULL;
+}
+
-+static int v4l2_request_wait_on_capture(V4L2RequestContext *ctx, uint32_t index)
++static AVBufferRef *v4l2request_capture_buffer_alloc(void *opaque, size_t size)
+{
-+ enum v4l2_buf_type type = ctx->fctxi->capture.format.type;
-+ struct pollfd pollfd = {
-+ .fd = ctx->fctxi->video_fd,
-+ .events = POLLIN,
-+ };
++ AVHWFramesContext *hwfc = opaque;
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
+
-+ ff_mutex_lock(&ctx->mutex);
++ return v4l2request_v4l2_buffer_alloc(hwfc, &fctxi->capture.format);
++}
+
-+ // Dequeue all completed CAPTURE buffers
-+ if (ctx->queued_capture)
-+ v4l2_request_dequeue_completed_buffers(ctx, type);
++static AVBufferRef *v4l2request_output_buffer_alloc(void *opaque, size_t size)
++{
++ AVHWFramesContext *hwfc = opaque;
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
+
-+ // Wait on the specific CAPTURE buffer
-+ while (ctx->queued_capture & (1 << index)) {
-+ int ret = poll(&pollfd, 1, 2000);
-+ if (ret <= 0)
-+ goto fail;
++ return v4l2request_v4l2_buffer_alloc(hwfc, &fctxi->output.format);
++}
+
-+ ret = v4l2_request_dequeue_buffer(ctx, type);
-+ if (ret < 0 && ret != AVERROR(EAGAIN))
-+ goto fail;
++static void v4l2request_frame_free(void *opaque, uint8_t *data)
++{
++ V4L2RequestFrameDescriptor *desc = (V4L2RequestFrameDescriptor *)data;
++
++ // Close the exported CAPTURE buffer memory planes
++ for (int i = 0; i < FF_ARRAY_ELEMS(desc->fd); i++) {
++ if (desc->fd[i] >= 0) {
++ close(desc->fd[i]);
++ desc->fd[i] = -1;
++ }
+ }
+
-+ ff_mutex_unlock(&ctx->mutex);
-+ return 0;
++ // Return the CAPTURE buffer to the frames context CAPTURE pool
++ av_buffer_unref(&desc->ref);
+
-+fail:
-+ ff_mutex_unlock(&ctx->mutex);
-+ av_log(ctx, AV_LOG_ERROR, "Failed waiting on CAPTURE buffer %d\n", index);
-+ return AVERROR(EINVAL);
++ av_free(data);
+}
+
-+static V4L2RequestOutputBuffer *v4l2_request_next_output(V4L2RequestContext *ctx)
++static AVBufferRef *v4l2request_frame_alloc(void *opaque, size_t size)
+{
-+ enum v4l2_buf_type type = ctx->fctxi->output.format.type;
-+ V4L2RequestOutputBuffer *output;
-+ struct pollfd pollfd = {
-+ .fd = ctx->fctxi->video_fd,
-+ .events = POLLOUT,
-+ };
-+ uint8_t index;
++ AVHWFramesContext *hwfc = opaque;
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ struct v4l2_format *format = &fctxi->capture.format;
++ V4L2RequestFrameDescriptor *desc;
++ struct v4l2_buffer *buffer;
++ AVBufferRef *ref;
++ uint8_t *data;
+
-+ ff_mutex_lock(&ctx->mutex);
++ data = av_mallocz(size);
++ if (!data)
++ return NULL;
+
-+ // Use next OUTPUT buffer in the circular queue
-+ index = ctx->next_output;
-+ output = &ctx->output[index];
-+ ctx->next_output = (index + 1) % FF_ARRAY_ELEMS(ctx->output);
++ ref = av_buffer_create(data, size, v4l2request_frame_free,
++ hwfc, AV_BUFFER_FLAG_READONLY);
++ if (!ref) {
++ av_free(data);
++ return NULL;
++ }
+
-+ // Dequeue all completed OUTPUT buffers
-+ if (ctx->queued_output)
-+ v4l2_request_dequeue_completed_buffers(ctx, type);
++ // Set initial default values
++ desc = (V4L2RequestFrameDescriptor *)data;
++ for (int i = 0; i < FF_ARRAY_ELEMS(desc->fd); i++)
++ desc->fd[i] = -1;
+
-+ // Wait on the specific OUTPUT buffer
-+ while (ctx->queued_output & (1 << output->index)) {
-+ int ret = poll(&pollfd, 1, 2000);
-+ if (ret <= 0)
-+ goto fail;
++ // Get a CAPTURE buffer from frames context CAPTURE pool
++ desc->ref = av_buffer_pool_get(fctxi->capture.pool);
++ if (!desc->ref)
++ goto fail;
+
-+ ret = v4l2_request_dequeue_buffer(ctx, type);
-+ if (ret < 0 && ret != AVERROR(EAGAIN))
++ buffer = (struct v4l2_buffer *)desc->ref->data;
++ desc->index = buffer->index;
++
++ // Export CAPTURE buffer memory planes
++ desc->base.nb_objects = V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
++ format->fmt.pix_mp.num_planes : 1;
++ av_assert0(desc->base.nb_objects <= AV_DRM_MAX_PLANES);
++ for (int i = 0; i < desc->base.nb_objects; i++) {
++ struct v4l2_exportbuffer exportbuffer = {
++ .type = buffer->type,
++ .index = buffer->index,
++ .plane = i,
++ .flags = O_RDONLY,
++ };
++ if (ioctl(fctxi->video_fd, VIDIOC_EXPBUF, &exportbuffer) < 0) {
++ av_log(hwfc, AV_LOG_ERROR, "Failed to export memory plane %d (%d): %s (%d)\n",
++ i, buffer->index, strerror(errno), errno);
+ goto fail;
++ }
++ desc->base.objects[i].fd = desc->fd[i] = exportbuffer.fd;
+ }
+
-+ ff_mutex_unlock(&ctx->mutex);
-+
-+ // Reset bytesused state
-+ output->bytesused = 0;
++ // Set AVDRMFrameDescriptor based on CAPTURE buffer format
++ if (v4l2request_set_drm_descriptor(&desc->base, format) < 0)
++ goto fail;
+
-+ return output;
++ return ref;
+
+fail:
-+ ff_mutex_unlock(&ctx->mutex);
-+ av_log(ctx, AV_LOG_ERROR, "Failed waiting on OUTPUT buffer %d\n",
-+ output->index);
++ av_buffer_unref(&ref);
+ return NULL;
+}
+
-+static int v4l2_request_wait_on_request(V4L2RequestContext *ctx,
-+ V4L2RequestOutputBuffer *output)
++static int v4l2request_frames_init(AVHWFramesContext *hwfc)
+{
-+ struct pollfd pollfd = {
-+ .fd = output->request_fd,
-+ .events = POLLPRI,
-+ };
++ V4L2RequestFramesContext *hwctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi;
++ uint32_t pixelformat;
++ int ret;
+
-+ // Wait on the specific request to complete
-+ while (ctx->queued_request & (1 << output->index)) {
-+ int ret = poll(&pollfd, 1, 2000);
-+ if (ret <= 0)
-+ break;
++ // Set initial default values
++ fctxi = &hwctx->internal;
++ hwctx->p.internal = fctxi;
++ fctxi->media_fd = -1;
++ fctxi->video_fd = -1;
+
-+ // Mark request as dequeued
-+ if (pollfd.revents & (POLLPRI | POLLERR)) {
-+ ctx->queued_request &= ~(1 << output->index);
++ // Locate and open a capable video decoder device
++ ret = v4l2request_open_decoder(hwfc);
++ if (ret < 0)
++ return ret;
++
++ // Reset init controls after video device is opened
++ hwctx->p.init_controls = NULL;
++ hwctx->p.nb_init_controls = 0;
++
++ // Update frames context with CAPTURE format details
++ if (V4L2_TYPE_IS_MULTIPLANAR(fctxi->capture.format.type)) {
++ hwfc->width = fctxi->capture.format.fmt.pix_mp.width;
++ hwfc->height = fctxi->capture.format.fmt.pix_mp.height;
++ pixelformat = fctxi->capture.format.fmt.pix_mp.pixelformat;
++ } else {
++ hwfc->width = fctxi->capture.format.fmt.pix.width;
++ hwfc->height = fctxi->capture.format.fmt.pix.height;
++ pixelformat = fctxi->capture.format.fmt.pix.pixelformat;
++ }
++
++ hwfc->sw_format = AV_PIX_FMT_NONE;
++ for (int i = 0; i < FF_ARRAY_ELEMS(v4l2request_capture_pixelformats); i++) {
++ if (pixelformat == v4l2request_capture_pixelformats[i].pixelformat) {
++ hwctx->p.bit_depth = v4l2request_capture_pixelformats[i].bit_depth;
++ hwfc->sw_format = v4l2request_capture_pixelformats[i].sw_format;
+ break;
+ }
+ }
+
-+ // Reinit the request object
-+ if (ioctl(output->request_fd, MEDIA_REQUEST_IOC_REINIT) < 0) {
-+ int ret = AVERROR(errno);
-+ av_log(ctx, AV_LOG_ERROR, "Failed to reinit request object %d: %s (%d)\n",
-+ output->request_fd, strerror(errno), errno);
-+ return ret;
-+ }
++ // Initialize buffer pool for CAPTURE buffers
++ fctxi->capture.pool = av_buffer_pool_init2(sizeof(struct v4l2_buffer), hwfc,
++ v4l2request_capture_buffer_alloc, NULL);
++ if (!fctxi->capture.pool)
++ return AVERROR(ENOMEM);
+
-+ // Ensure request is marked as dequeued
-+ ctx->queued_request &= ~(1 << output->index);
++ // Initialize buffer pool for OUTPUT buffers
++ fctxi->output.pool = av_buffer_pool_init2(sizeof(struct v4l2_buffer), hwfc,
++ v4l2request_output_buffer_alloc, NULL);
++ if (!fctxi->output.pool)
++ return AVERROR(ENOMEM);
++
++ // Initialize buffer pool for frame descriptors
++ ffhwframesctx(hwfc)->pool_internal =
++ av_buffer_pool_init2(sizeof(V4L2RequestFrameDescriptor), hwfc,
++ v4l2request_frame_alloc, NULL);
++ if (!ffhwframesctx(hwfc)->pool_internal)
++ return AVERROR(ENOMEM);
++
++ av_log(hwfc, AV_LOG_VERBOSE, "Using CAPTURE buffer format %s (%dx%d)\n",
++ av_fourcc2str(pixelformat), hwfc->width, hwfc->height);
+
+ return 0;
+}
+
-+int ff_v4l2_request_append_output(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic,
-+ const uint8_t *data, uint32_t size)
++static void v4l2request_frames_uninit(AVHWFramesContext *hwfc)
+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
+
-+ // Append data to OUTPUT buffer and ensure there is enough space for padding
-+ if (pic->output->bytesused + size + AV_INPUT_BUFFER_PADDING_SIZE <= pic->output->size) {
-+ memcpy(pic->output->addr + pic->output->bytesused, data, size);
-+ pic->output->bytesused += size;
-+ return 0;
-+ } else {
-+ av_log(ctx, AV_LOG_ERROR,
-+ "Failed to append %u bytes data to OUTPUT buffer %d (%u of %u used)\n",
-+ size, pic->output->index, pic->output->bytesused, pic->output->size);
-+ return AVERROR(ENOMEM);
++ av_buffer_pool_uninit(&fctxi->capture.pool);
++ av_buffer_pool_uninit(&fctxi->output.pool);
++
++ if (fctxi->video_fd >= 0) {
++ close(fctxi->video_fd);
++ fctxi->video_fd = -1;
++ }
++
++ if (fctxi->media_fd) {
++ close(fctxi->media_fd);
++ fctxi->media_fd = -1;
+ }
+}
+
-+static int v4l2_request_queue_decode(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic,
-+ struct v4l2_ext_control *control, int count,
-+ bool first_slice, bool last_slice)
++static int v4l2request_get_buffer(AVHWFramesContext *hwfc, AVFrame *frame)
+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
-+ uint32_t flags;
-+ int ret;
++ V4L2RequestFrameDescriptor *desc;
+
-+ if (first_slice) {
-+ /*
-+ * Wait on dequeue of the target CAPTURE buffer. Otherwise V4L2 decoder
-+ * may use a different CAPTURE buffer than hwaccel expects.
-+ *
-+ * Normally decoding has already completed when a CAPTURE buffer is
-+ * reused so this is more or less a no-op, however in some situations
-+ * FFmpeg may reuse an AVFrame early, i.e. when no output frame was
-+ * produced prior time, and a synchronization is necessary.
-+ */
-+ ret = v4l2_request_wait_on_capture(ctx, pic->capture_index);
-+ if (ret < 0)
-+ return ret;
-+ }
++ frame->buf[0] = av_buffer_pool_get(hwfc->pool);
++ if (!frame->buf[0])
++ return AVERROR(ENOMEM);
+
-+ ff_mutex_lock(&ctx->mutex);
++ desc = (V4L2RequestFrameDescriptor *)frame->buf[0]->data;
++ frame->data[0] = (uint8_t *)&desc->base;
++ frame->data[1] = (uint8_t *)(uintptr_t)desc->index;
+
-+ /*
-+ * The OUTPUT buffer tied to prior use of current request object can
-+ * independently be dequeued before the full decode request has been
-+ * completed. This may happen when a decoder use multi stage decoding,
-+ * e.g. rpi-hevc-dec. In such case we can start reusing the OUTPUT buffer,
-+ * however we must wait on the prior request to fully complete before we
-+ * can reuse the request object, and a synchronization is necessary.
-+ */
-+ ret = v4l2_request_wait_on_request(ctx, pic->output);
-+ if (ret < 0)
-+ goto fail;
++ frame->format = AV_PIX_FMT_DRM_PRIME;
++ frame->width = hwfc->width;
++ frame->height = hwfc->height;
+
-+ /*
-+ * Dequeue any completed OUTPUT buffers, this is strictly not necessary,
-+ * however if a synchronization was necessary for the CAPTURE and/or request
-+ * there is more than likely one or more OUTPUT buffers that can be dequeued.
-+ */
-+ if (ctx->queued_output)
-+ v4l2_request_dequeue_completed_buffers(ctx, ctx->fctxi->output.format.type);
++ return 0;
++}
+
-+ // Set codec controls for current request
-+ ret = v4l2_request_set_controls(ctx, pic->output->request_fd, control, count);
-+ if (ret < 0) {
-+ av_log(ctx, AV_LOG_ERROR, "Failed to set %d control(s) for request %d: %s (%d)\n",
-+ count, pic->output->request_fd, strerror(errno), errno);
-+ goto fail;
++typedef struct V4L2RequestMapping {
++ // Address and length of each mmap()ed region.
++ int nb_regions;
++ int object[AV_DRM_MAX_PLANES];
++ void *address[AV_DRM_MAX_PLANES];
++ size_t length[AV_DRM_MAX_PLANES];
++} V4L2RequestMapping;
++
++static void v4l2request_unmap_frame(AVHWFramesContext *hwfc,
++ HWMapDescriptor *hwmap)
++{
++ V4L2RequestMapping *map = hwmap->priv;
++
++ for (int i = 0; i < map->nb_regions; i++) {
++ struct dma_buf_sync sync = {
++ .flags = DMA_BUF_SYNC_END | DMA_BUF_SYNC_READ,
++ };
++ ioctl(map->object[i], DMA_BUF_IOCTL_SYNC, &sync);
++ munmap(map->address[i], map->length[i]);
+ }
+
-+ // Ensure there is zero padding at the end of bitstream data
-+ memset(pic->output->addr + pic->output->bytesused, 0, AV_INPUT_BUFFER_PADDING_SIZE);
++ av_free(map);
++}
+
-+ /*
-+ * Use CAPTURE buffer index as base for V4L2 frame reference.
-+ * This works because a CAPTURE buffer is closely tied to a AVFrame
-+ * and FFmpeg handle all frame reference tracking for us.
-+ */
-+ pic->output->timestamp = (struct timeval) {
-+ .tv_sec = 0,
-+ .tv_usec = pic->capture_index + 1,
++static int v4l2request_map_frame(AVHWFramesContext *hwfc,
++ AVFrame *dst, const AVFrame *src)
++{
++ const AVDRMFrameDescriptor *desc = (AVDRMFrameDescriptor *)src->data[0];
++ struct dma_buf_sync sync = {
++ .flags = DMA_BUF_SYNC_START | DMA_BUF_SYNC_READ,
+ };
++ V4L2RequestMapping *map;
++ int ret, i, p, plane;
++ void *addr;
+
-+ /*
-+ * Queue the OUTPUT buffer of current request. The CAPTURE buffer may be
-+ * hold by the V4L2 decoder unless this is the last slice of a frame.
-+ */
-+ flags = last_slice ? 0 : V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF;
-+ ret = v4l2_request_queue_output_buffer(ctx, pic->output, flags);
-+ if (ret < 0) {
-+ av_log(ctx, AV_LOG_ERROR, "Failed to queue OUTPUT buffer %d for request %d: %s (%d)\n",
-+ pic->output->index, pic->output->request_fd, strerror(errno), errno);
-+ goto fail;
-+ }
++ map = av_mallocz(sizeof(*map));
++ if (!map)
++ return AVERROR(ENOMEM);
++
++ av_assert0(desc->nb_objects <= AV_DRM_MAX_PLANES);
++ for (i = 0; i < desc->nb_objects; i++) {
++ addr = mmap(NULL, desc->objects[i].size, PROT_READ, MAP_SHARED,
++ desc->objects[i].fd, 0);
++ if (addr == MAP_FAILED) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR, "Failed to map DRM object %d to memory: %s (%d)\n",
++ desc->objects[i].fd, strerror(errno), errno);
++ goto fail;
++ }
++
++ map->address[i] = addr;
++ map->length[i] = desc->objects[i].size;
++ map->object[i] = desc->objects[i].fd;
+
-+ if (first_slice) {
+ /*
-+ * Queue the target CAPTURE buffer, hwaccel expect and depend on that
-+ * this specific CAPTURE buffer will be used as decode target for
-+ * current request, otherwise frames may be output in wrong order or
-+ * wrong CAPTURE buffer could get used as a reference frame.
++ * We're not checking for errors here because the kernel may not
++ * support the ioctl, in which case its okay to carry on
+ */
-+ ret = v4l2_request_queue_capture_buffer(ctx, pic->capture_index);
-+ if (ret < 0) {
-+ av_log(ctx, AV_LOG_ERROR, "Failed to queue CAPTURE buffer %d for request %d: %s (%d)\n",
-+ pic->capture_index, pic->output->request_fd, strerror(errno), errno);
-+ goto fail;
++ ioctl(desc->objects[i].fd, DMA_BUF_IOCTL_SYNC, &sync);
++ }
++ map->nb_regions = i;
++
++ plane = 0;
++ for (i = 0; i < desc->nb_layers; i++) {
++ const AVDRMLayerDescriptor *layer = &desc->layers[i];
++ for (p = 0; p < layer->nb_planes; p++) {
++ dst->data[plane] =
++ (uint8_t *)map->address[layer->planes[p].object_index] +
++ layer->planes[p].offset;
++ dst->linesize[plane] = layer->planes[p].pitch;
++ ++plane;
+ }
+ }
++ av_assert0(plane <= AV_DRM_MAX_PLANES);
+
-+ // Queue current request
-+ ret = ioctl(pic->output->request_fd, MEDIA_REQUEST_IOC_QUEUE);
-+ if (ret < 0) {
-+ ret = AVERROR(errno);
-+ av_log(ctx, AV_LOG_ERROR, "Failed to queue request object %d: %s (%d)\n",
-+ pic->output->request_fd, strerror(errno), errno);
++ dst->width = src->width;
++ dst->height = src->height;
++
++ ret = ff_hwframe_map_create(src->hw_frames_ctx, dst, src,
++ v4l2request_unmap_frame, map);
++ if (ret < 0)
+ goto fail;
-+ }
+
-+ // Mark current request as queued
-+ ctx->queued_request |= 1 << pic->output->index;
++ return 0;
+
-+ ret = 0;
+fail:
-+ ff_mutex_unlock(&ctx->mutex);
++ for (i = 0; i < desc->nb_objects; i++) {
++ if (map->address[i])
++ munmap(map->address[i], map->length[i]);
++ }
++ av_free(map);
+ return ret;
+}
+
-+int ff_v4l2_request_decode_slice(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic,
-+ struct v4l2_ext_control *control, int count,
-+ bool first_slice, bool last_slice)
-+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
-+
-+ /*
-+ * Fallback to queue each slice as a full frame when holding CAPTURE
-+ * buffers is not supported by the driver.
-+ */
-+ if ((ctx->fctxi->output.capabilities & V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF) !=
-+ V4L2_BUF_CAP_SUPPORTS_M2M_HOLD_CAPTURE_BUF)
-+ return v4l2_request_queue_decode(avctx, pic, control, count, true, true);
-+
-+ return v4l2_request_queue_decode(avctx, pic, control, count,
-+ first_slice, last_slice);
-+}
-+
-+int ff_v4l2_request_decode_frame(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic,
-+ struct v4l2_ext_control *control, int count)
++static int v4l2request_transfer_get_formats(AVHWFramesContext *hwfc,
++ enum AVHWFrameTransferDirection dir,
++ enum AVPixelFormat **formats)
+{
-+ return v4l2_request_queue_decode(avctx, pic, control, count, true, true);
-+}
++ enum AVPixelFormat *fmts;
+
-+static int v4l2_request_post_process(void *logctx, AVFrame *frame)
-+{
-+ uint32_t index = v4l2_request_frameindex(frame);
-+ FrameDecodeData *fdd = frame->private_ref;
-+ V4L2RequestContext *ctx = fdd->hwaccel_priv;
++ if (dir == AV_HWFRAME_TRANSFER_DIRECTION_TO)
++ return AVERROR(ENOSYS);
+
-+ // Wait on CAPTURE buffer before returning the frame to application
-+ return v4l2_request_wait_on_capture(ctx, index);
-+}
++ fmts = av_malloc_array(2, sizeof(*fmts));
++ if (!fmts)
++ return AVERROR(ENOMEM);
+
-+int ff_v4l2_request_reset_picture(AVCodecContext *avctx, V4L2RequestPictureContext *pic)
-+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
++ fmts[0] = hwfc->sw_format;
++ fmts[1] = AV_PIX_FMT_NONE;
+
-+ // Get and wait on next OUTPUT buffer from circular queue
-+ pic->output = v4l2_request_next_output(ctx);
-+ if (!pic->output)
-+ return AVERROR(EINVAL);
++ if (hwfc->sw_format == AV_PIX_FMT_YUV420P ||
++ hwfc->sw_format == AV_PIX_FMT_YUV420P10 ||
++ hwfc->sw_format == AV_PIX_FMT_YUV422P10)
++ fmts[0] = AV_PIX_FMT_NONE;
+
++ *formats = fmts;
+ return 0;
+}
+
-+int ff_v4l2_request_start_frame(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic,
-+ AVFrame *frame)
++static int v4l2request_transfer_data_from(AVHWFramesContext *hwfc,
++ AVFrame *dst, const AVFrame *src)
+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
-+ uint32_t index = v4l2_request_frameindex(frame);
-+ FrameDecodeData *fdd = frame->private_ref;
++ AVFrame *map;
+ int ret;
+
-+ // Get next OUTPUT buffer from circular queue
-+ ret = ff_v4l2_request_reset_picture(avctx, pic);
-+ if (ret)
-+ return ret;
++ if (dst->width > hwfc->width || dst->height > hwfc->height)
++ return AVERROR(EINVAL);
+
-+ // Ensure CAPTURE buffer is dequeued before reuse
-+ ret = v4l2_request_wait_on_capture(ctx, index);
++ map = av_frame_alloc();
++ if (!map)
++ return AVERROR(ENOMEM);
++ map->format = dst->format;
++
++ ret = v4l2request_map_frame(hwfc, map, src);
+ if (ret)
-+ return ret;
++ goto fail;
+
-+ // Wait on CAPTURE buffer in post_process() before returning to application
-+ fdd->hwaccel_priv = ctx;
-+ fdd->post_process = v4l2_request_post_process;
++ map->width = dst->width;
++ map->height = dst->height;
+
-+ // CAPTURE buffer used for current frame
-+ pic->capture_index = index;
++ ret = av_frame_copy(dst, map);
++ if (ret)
++ goto fail;
+
-+ return 0;
++ ret = 0;
++fail:
++ av_frame_free(&map);
++ return ret;
+}
+
-+void ff_v4l2_request_flush(AVCodecContext *avctx)
++static int v4l2request_map_from(AVHWFramesContext *hwfc, AVFrame *dst,
++ const AVFrame *src, int flags)
+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
-+ enum v4l2_buf_type type = ctx->fctxi->output.format.type;
-+ struct pollfd pollfd = {
-+ .fd = ctx->fctxi->video_fd,
-+ .events = POLLOUT,
-+ };
-+
-+ ff_mutex_lock(&ctx->mutex);
-+
-+ // Dequeue all completed OUTPUT buffers
-+ if (ctx->queued_output)
-+ v4l2_request_dequeue_completed_buffers(ctx, type);
++ int ret;
+
-+ // Wait on any remaining OUTPUT buffer
-+ while (ctx->queued_output) {
-+ int ret = poll(&pollfd, 1, 2000);
-+ if (ret <= 0)
-+ break;
++ if (!(flags & AV_HWFRAME_MAP_READ))
++ return AVERROR(ENOSYS);
+
-+ ret = v4l2_request_dequeue_buffer(ctx, type);
-+ if (ret < 0 && ret != AVERROR(EAGAIN))
-+ break;
-+ }
++ if (hwfc->sw_format == AV_PIX_FMT_NONE ||
++ hwfc->sw_format == AV_PIX_FMT_YUV420P ||
++ hwfc->sw_format == AV_PIX_FMT_YUV420P10 ||
++ hwfc->sw_format == AV_PIX_FMT_YUV422P10)
++ return AVERROR(ENOSYS);
++ else if (dst->format == AV_PIX_FMT_NONE)
++ dst->format = hwfc->sw_format;
++ else if (hwfc->sw_format != dst->format)
++ return AVERROR(ENOSYS);
+
-+ // Dequeue all completed CAPTURE buffers
-+ if (ctx->queued_capture)
-+ v4l2_request_dequeue_completed_buffers(ctx, ctx->fctxi->capture.format.type);
++ ret = v4l2request_map_frame(hwfc, dst, src);
++ if (ret)
++ return ret;
+
-+ ff_mutex_unlock(&ctx->mutex);
++ return av_frame_copy_props(dst, src);
+}
+
-+static void v4l2_request_output_buffer_uninit(V4L2RequestOutputBuffer *output)
-+{
-+ // Close the request associated with the OUTPUT buffer
-+ if (output->request_fd >= 0) {
-+ close(output->request_fd);
-+ output->request_fd = -1;
-+ }
++const HWContextType ff_hwcontext_type_v4l2request = {
++ .type = AV_HWDEVICE_TYPE_V4L2REQUEST,
++ .name = "V4L2 Request API",
+
-+ // Umap the OUTPUT buffer memory
-+ if (output->addr) {
-+ munmap(output->addr, output->size);
-+ output->addr = NULL;
-+ }
++ .device_hwctx_size = sizeof(V4L2RequestDeviceContext),
++ .device_create = v4l2request_device_create,
++ .device_uninit = v4l2request_device_uninit,
+
-+ // Return the OUTPUT buffer to the frames context OUTPUT pool
-+ av_buffer_unref(&output->ref);
-+}
++ .frames_hwctx_size = sizeof(V4L2RequestFramesContext),
++ .frames_init = v4l2request_frames_init,
++ .frames_uninit = v4l2request_frames_uninit,
++ .frames_get_buffer = v4l2request_get_buffer,
++ .transfer_get_formats = v4l2request_transfer_get_formats,
++ .transfer_data_from = v4l2request_transfer_data_from,
++ .map_from = v4l2request_map_from,
+
-+static int v4l2_request_output_buffer_init(V4L2RequestContext *ctx,
-+ V4L2RequestOutputBuffer *output)
-+{
-+ struct v4l2_format *format = &ctx->fctxi->output.format;
-+ struct v4l2_buffer *buffer;
-+ off_t offset;
-+ void *addr;
-+ int ret;
++ .pix_fmts = (const enum AVPixelFormat[]) {
++ AV_PIX_FMT_DRM_PRIME,
++ AV_PIX_FMT_NONE
++ },
++};
+diff --git a/libavutil/hwcontext_v4l2request.h b/libavutil/hwcontext_v4l2request.h
+new file mode 100644
+index 00000000000..ec6beadd649
+--- /dev/null
++++ b/libavutil/hwcontext_v4l2request.h
+@@ -0,0 +1,70 @@
++/*
++ * This file is part of FFmpeg.
++ *
++ * FFmpeg is free software; you can redistribute it and/or
++ * modify it under the terms of the GNU Lesser General Public
++ * License as published by the Free Software Foundation; either
++ * version 2.1 of the License, or (at your option) any later version.
++ *
++ * FFmpeg is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
++ * Lesser General Public License for more details.
++ *
++ * You should have received a copy of the GNU Lesser General Public
++ * License along with FFmpeg; if not, write to the Free Software
++ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
++ */
+
-+ // Get an OUTPUT buffer from frames context OUTPUT pool
-+ output->ref = av_buffer_pool_get(ctx->fctxi->output.pool);
-+ if (!output->ref)
-+ return AVERROR(ENOMEM);
++#ifndef AVUTIL_HWCONTEXT_V4L2REQUEST_H
++#define AVUTIL_HWCONTEXT_V4L2REQUEST_H
+
-+ buffer = (struct v4l2_buffer *)output->ref->data;
-+ output->index = buffer->index;
-+ output->size = V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
-+ format->fmt.pix_mp.plane_fmt[0].sizeimage :
-+ format->fmt.pix.sizeimage;
-+ output->bytesused = 0;
++#include <stdint.h>
++#include <linux/videodev2.h>
+
-+ // Map the OUTPUT buffer memory, raw bitstream data is written into it
-+ offset = V4L2_TYPE_IS_MULTIPLANAR(buffer->type) ?
-+ buffer->m.planes[0].m.mem_offset :
-+ buffer->m.offset;
-+ addr = mmap(NULL, output->size, PROT_READ | PROT_WRITE, MAP_SHARED,
-+ ctx->fctxi->video_fd, offset);
-+ if (addr == MAP_FAILED) {
-+ ret = AVERROR(errno);
-+ av_log(ctx, AV_LOG_ERROR, "Failed to map OUTPUT buffer %d: %s (%d)\n",
-+ output->index, strerror(errno), errno);
-+ goto fail;
-+ }
-+ output->addr = addr;
++/**
++ * @file
++ * An API-specific header for AV_HWDEVICE_TYPE_V4L2REQUEST.
++ */
+
-+ // Allocate and associated a request for the OUTPUT buffer
-+ if (ioctl(ctx->fctxi->media_fd, MEDIA_IOC_REQUEST_ALLOC, &output->request_fd) < 0) {
-+ ret = AVERROR(errno);
-+ av_log(ctx, AV_LOG_ERROR, "Failed to allocate request for OUTPUT buffer %d: %s (%d)\n",
-+ output->index, strerror(errno), errno);
-+ goto fail;
-+ }
++typedef struct AVV4L2RequestFramesContextInternal AVV4L2RequestFramesContextInternal;
+
-+ return 0;
++/**
++ * V4L2 Request API frames context.
++ *
++ * This struct is allocated as AVHWFramesContext.hwctx
++ */
++typedef struct AVV4L2RequestFramesContext {
++ /**
++ * Internal context for the initialized V4L2 stateless decoder/encoder session.
++ */
++ AVV4L2RequestFramesContextInternal *internal;
+
-+fail:
-+ v4l2_request_output_buffer_uninit(output);
-+ return ret;
-+}
++ /**
++ * V4L2_PIX_FMT_* coded pixel format to set on the OUTPUT queue (decoders)
++ * or the CAPTURE queue (encoders) during initialization.
++ *
++ * This field must be set by caller before av_hwframe_ctx_init() is called.
++ */
++ uint32_t pixelformat;
+
-+int ff_v4l2_request_frame_params(AVCodecContext *avctx,
-+ AVBufferRef *hw_frames_ctx,
-+ uint32_t pixelformat,
-+ uint8_t bit_depth)
-+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
-+ AVHWFramesContext *hwfc = (AVHWFramesContext *)hw_frames_ctx->data;
-+ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ /**
++ * Optional bit depth of the frame pixel format, e.g. 8 or 10.
++ *
++ * This field should be set by caller before av_hwframe_ctx_init() is called,
++ * the field will be updated to match the selected frame pixel format after
++ * successful initialization.
++ */
++ uint32_t bit_depth;
+
-+ // Set parameters used during frames context initialization
-+ fctx->pixelformat = pixelformat;
-+ fctx->bit_depth = bit_depth;
-+ if (ctx) {
-+ fctx->init_controls = ctx->init_controls;
-+ fctx->nb_init_controls = ctx->nb_init_controls;
-+ }
++ /**
++ * Optional codec-specific extended controls to be set during initialization.
++ *
++ * These fields should be set by caller before av_hwframe_ctx_init() is called,
++ * fields are reset to NULL and 0 after successful initialization.
++ */
++ struct v4l2_ext_control *init_controls;
++ int nb_init_controls;
++} AVV4L2RequestFramesContext;
+
-+ hwfc->format = AV_PIX_FMT_DRM_PRIME;
-+ hwfc->sw_format = AV_PIX_FMT_NONE;
-+ hwfc->width = avctx->coded_width;
-+ hwfc->height = avctx->coded_height;
++#endif /* AVUTIL_HWCONTEXT_V4L2REQUEST_H */
+diff --git a/libavutil/hwcontext_v4l2request_internal.h b/libavutil/hwcontext_v4l2request_internal.h
+new file mode 100644
+index 00000000000..20436b2b2d6
+--- /dev/null
++++ b/libavutil/hwcontext_v4l2request_internal.h
+@@ -0,0 +1,67 @@
++/*
++ * This file is part of FFmpeg.
++ *
++ * FFmpeg is free software; you can redistribute it and/or
++ * modify it under the terms of the GNU Lesser General Public
++ * License as published by the Free Software Foundation; either
++ * version 2.1 of the License, or (at your option) any later version.
++ *
++ * FFmpeg is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
++ * Lesser General Public License for more details.
++ *
++ * You should have received a copy of the GNU Lesser General Public
++ * License along with FFmpeg; if not, write to the Free Software
++ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
++ */
+
-+ // Pre-allocate CAPTURE buffers to ensure CAPTURE queue can be started
-+ hwfc->initial_pool_size = 1;
++#ifndef AVUTIL_HWCONTEXT_V4L2REQUEST_INTERNAL_H
++#define AVUTIL_HWCONTEXT_V4L2REQUEST_INTERNAL_H
+
-+ return 0;
-+}
++#include "buffer.h"
++#include "hwcontext_v4l2request.h"
+
-+int ff_v4l2_request_uninit(AVCodecContext *avctx)
-+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
-+ enum v4l2_buf_type type;
++/**
++ * @file
++ * FFmpeg internal API-specific header for AV_HWDEVICE_TYPE_V4L2REQUEST.
++ */
+
-+ if (ctx->fctxi) {
-+ // Flush and wait on all pending requests
-+ ff_v4l2_request_flush(avctx);
++/**
++ * Internal context for the initialized V4L2 stateless decoder/encoder session.
++ */
++struct AVV4L2RequestFramesContextInternal {
++ /**
++ * Media device file descriptor of the initialized session.
++ */
++ int media_fd;
+
-+ // Stop streaming on OUTPUT queue
-+ type = ctx->fctxi->output.format.type;
-+ if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMOFF, &type) < 0)
-+ av_log(ctx, AV_LOG_WARNING, "Failed to stop OUTPUT streaming: %s (%d)\n",
-+ strerror(errno), errno);
++ /**
++ * Video device file descriptor of the initialized session.
++ */
++ int video_fd;
+
-+ // Stop streaming on CAPTURE queue
-+ type = ctx->fctxi->capture.format.type;
-+ if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMOFF, &type) < 0)
-+ av_log(ctx, AV_LOG_WARNING, "Failed to stop CAPTURE streaming: %s (%d)\n",
-+ strerror(errno), errno);
++ /**
++ * Details of the initialized CAPTURE and OUTPUT queues.
++ */
++ struct {
++ /**
++ * V4L2 buffer format.
++ */
++ struct v4l2_format format;
+
-+ // Release OUTPUT buffers and requests
-+ for (int i = 0; i < FF_ARRAY_ELEMS(ctx->output); i++)
-+ v4l2_request_output_buffer_uninit(&ctx->output[i]);
++ /**
++ * V4L2 buffer capabilities flags.
++ */
++ uint32_t capabilities;
+
-+ ctx->fctxi = NULL;
-+ }
++ /**
++ * Buffer pool of allocated V4L2 buffers.
++ *
++ * AVBufferRef.data points to a struct v4l2_buffer for the created buffer.
++ */
++ AVBufferPool *pool;
++ } capture, output;
++};
+
-+ av_buffer_unref(&ctx->frames_ref);
-+ ff_mutex_destroy(&ctx->mutex);
++#endif /* AVUTIL_HWCONTEXT_V4L2REQUEST_INTERNAL_H */
+--
+2.54.0
+
+
+From b61e532f75d0b5937d010f65c1df099cc5a5983c Mon Sep 17 00:00:00 2001
+From: Jonas Karlman <jonas at kwiboo.se>
+Date: Tue, 6 Aug 2024 09:06:02 +0000
+Subject: [PATCH 02/11] avutil/hwcontext_v4l2request: Probe for a capable media
+ and video device
+
+Probe all media devices and its linked video devices to locate a video
+device that support stateless decoding of the specific codec using the
+V4L2 Request API.
+
+A video device is deemed capable when all tests pass, e.g. kernel
+drivers support the coded pixel format and the frame size is supported.
+
+Basic flow for initialization follows the kernel Memory-to-memory
+Stateless Video Decoder Interface > Initialization [1].
+
+[1] https://www.kernel.org/doc/html/latest/userspace-api/media/v4l/dev-stateless-decoder.html#initialization
+
+Co-developed-by: Jernej Skrabec <jernej.skrabec at gmail.com>
+Signed-off-by: Jernej Skrabec <jernej.skrabec at gmail.com>
+Co-developed-by: Alex Bee <knaerzche at gmail.com>
+Signed-off-by: Alex Bee <knaerzche at gmail.com>
+Signed-off-by: Jonas Karlman <jonas at kwiboo.se>
+---
+ configure | 9 +-
+ libavutil/hwcontext_v4l2request.c | 513 +++++++++++++++++++++++++++++-
+ 2 files changed, 517 insertions(+), 5 deletions(-)
+
+diff --git a/configure b/configure
+index 872e3d57b4b..765345560f5 100755
+--- a/configure
++++ b/configure
+@@ -2100,6 +2100,7 @@ EXTERNAL_LIBRARY_LIST="
+ libtorch
+ libtwolame
+ libuavs3d
++ libudev
+ libv4l2
+ libvmaf
+ libvorbis
+@@ -3351,8 +3352,8 @@ dxva2_deps="dxva2api_h DXVA2_ConfigPictureDecode ole32 user32"
+ ffnvcodec_deps_any="libdl LoadLibrary"
+ mediacodec_deps="android mediandk pthreads"
+ nvdec_deps="ffnvcodec"
+-v4l2_request_deps="linux_media_h v4l2_timeval_to_ns libdrm"
+-v4l2_request_suggest="libdrm"
++v4l2_request_deps="linux_media_h v4l2_timeval_to_ns libdrm libudev"
++v4l2_request_suggest="libdrm libudev"
+ vaapi_x11_deps="xlib_x11"
+ videotoolbox_hwaccel_deps="videotoolbox pthreads"
+ videotoolbox_hwaccel_extralibs="-framework QuartzCore"
+@@ -4321,7 +4322,7 @@ shader_compression_suggest="zlib"
+
+ avcodec_extralibs="pthreads_extralibs iconv_extralibs dxva2_extralibs liblcevc_dec_extralibs lcms2_extralibs"
+ avfilter_extralibs="pthreads_extralibs"
+-avutil_extralibs="d3d11va_extralibs d3d12va_extralibs mediacodec_extralibs nanosleep_extralibs pthreads_extralibs vaapi_drm_extralibs vaapi_x11_extralibs vaapi_win32_extralibs vdpau_x11_extralibs"
++avutil_extralibs="d3d11va_extralibs d3d12va_extralibs mediacodec_extralibs nanosleep_extralibs pthreads_extralibs v4l2_request_extralibs vaapi_drm_extralibs vaapi_x11_extralibs vaapi_win32_extralibs vdpau_x11_extralibs"
+
+ # programs
+ ffmpeg_deps="avcodec avfilter avformat threads"
+@@ -7604,6 +7605,8 @@ fi
+
+ if enabled v4l2_request; then
+ check_func_headers "linux/media.h linux/videodev2.h" v4l2_timeval_to_ns
++ check_pkg_config libudev libudev libudev.h udev_new
++ v4l2_request_extralibs="$libudev_extralibs"
+ fi
+
+ check_headers sys/videoio.h
+diff --git a/libavutil/hwcontext_v4l2request.c b/libavutil/hwcontext_v4l2request.c
+index 3d92b633675..f99eea6eaeb 100644
+--- a/libavutil/hwcontext_v4l2request.c
++++ b/libavutil/hwcontext_v4l2request.c
+@@ -26,6 +26,7 @@
+ #include <unistd.h>
+
+ #include <drm_fourcc.h>
++#include <libudev.h>
+
+ #include "avassert.h"
+ #include "hwcontext_drm.h"
+@@ -33,7 +34,16 @@
+ #include "hwcontext_v4l2request_internal.h"
+ #include "mem.h"
+
++typedef struct V4L2RequestVideoDecoder {
++ dev_t media_dev;
++ dev_t video_dev;
++ uint32_t *pixelformats;
++ int nb_pixelformats;
++} V4L2RequestVideoDecoder;
+
-+ return 0;
-+}
+ typedef struct V4L2RequestDeviceContext {
++ V4L2RequestVideoDecoder *decoders;
++ int nb_decoders;
+ } V4L2RequestDeviceContext;
+
+ typedef struct V4L2RequestFramesContext {
+@@ -138,25 +148,524 @@ static int v4l2request_set_drm_descriptor(AVDRMFrameDescriptor *desc,
+
+ static void v4l2request_device_uninit(AVHWDeviceContext *hwdev)
+ {
++ V4L2RequestDeviceContext *hwctx = hwdev->hwctx;
+
-+int ff_v4l2_request_init(AVCodecContext *avctx,
-+ struct v4l2_ext_control *control, int count,
-+ int (*post_frames_ctx)(AVCodecContext *avctx))
++ av_freep(&hwctx->decoders);
++ hwctx->nb_decoders = 0;
+ }
+
+ static int v4l2request_device_create(AVHWDeviceContext *hwdev, const char *device,
+ AVDictionary *opts, int flags)
+ {
++ V4L2RequestDeviceContext *hwctx = hwdev->hwctx;
++
++ hwctx->decoders = NULL;
++ hwctx->nb_decoders = 0;
++
++ // TODO: enumerate V4L2 Request API capable video decoders
++ // and fill hwctx->decoders and hwctx->nb_decoders,
++ // limit to decoders for the media 'device' when specified
++
+ return 0;
+ }
+
++static int v4l2request_set_format(AVHWFramesContext *hwfc,
++ enum v4l2_buf_type type,
++ uint32_t pixelformat,
++ uint32_t buffersize)
+{
-+ V4L2RequestContext *ctx = v4l2_request_context(avctx);
-+ AVHWFramesContext *hwfc;
-+ AVV4L2RequestFramesContext *fctx;
-+ enum v4l2_buf_type type;
-+ int ret;
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ struct v4l2_format format = {
++ .type = type,
++ };
+
-+ // Set initial default values
-+ ctx->av_class = &v4l2_request_context_class;
-+ ctx->init_controls = control;
-+ ctx->nb_init_controls = count;
-+ ff_mutex_init(&ctx->mutex, NULL);
-+ for (int i = 0; i < FF_ARRAY_ELEMS(ctx->output); i++) {
-+ ctx->output[i].index = i;
-+ ctx->output[i].request_fd = -1;
++ if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
++ format.fmt.pix_mp.width = hwfc->width;
++ format.fmt.pix_mp.height = hwfc->height;
++ format.fmt.pix_mp.pixelformat = pixelformat;
++ format.fmt.pix_mp.plane_fmt[0].sizeimage = buffersize;
++ format.fmt.pix_mp.num_planes = 1;
++ } else {
++ format.fmt.pix.width = hwfc->width;
++ format.fmt.pix.height = hwfc->height;
++ format.fmt.pix.pixelformat = pixelformat;
++ format.fmt.pix.sizeimage = buffersize;
+ }
+
-+ // Create frames context and allocate initial CAPTURE buffers
-+ ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_V4L2REQUEST);
-+ if (ret < 0)
-+ goto fail;
++ if (ioctl(fctxi->video_fd, VIDIOC_S_FMT, &format) < 0)
++ return AVERROR(errno);
+
-+ ctx->frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
-+ if (!ctx->frames_ref) {
-+ ret = AVERROR(ENOMEM);
-+ goto fail;
-+ }
++ return 0;
++}
+
-+ // Get internal hwctx from frames context
-+ hwfc = (AVHWFramesContext *)ctx->frames_ref->data;
-+ fctx = hwfc->hwctx;
-+ ctx->fctxi = fctx->internal;
++static int v4l2request_select_capture_format(AVHWFramesContext *hwfc)
++{
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ enum v4l2_buf_type type = fctxi->capture.format.type;
++ uint32_t pixelformat, fallback = 0;
++ struct v4l2_format format = {
++ .type = type,
++ };
++ struct v4l2_fmtdesc fmtdesc = {
++ .index = 0,
++ .type = type,
++ };
+
-+ // Reset init controls after successful frames context initialization
-+ ctx->init_controls = NULL;
-+ ctx->nb_init_controls = 0;
++ // Get the driver preferred (or default) format
++ if (ioctl(fctxi->video_fd, VIDIOC_G_FMT, &format) < 0)
++ return AVERROR(errno);
+
-+ // Check codec-specific controls, e.g. profile and level
-+ if (post_frames_ctx) {
-+ ret = post_frames_ctx(avctx);
-+ if (ret < 0)
-+ goto fail;
-+ }
++ pixelformat = V4L2_TYPE_IS_MULTIPLANAR(type) ?
++ format.fmt.pix_mp.pixelformat :
++ format.fmt.pix.pixelformat;
+
-+ // Allocate OUTPUT buffers and requests for circular queue
-+ for (int i = 0; i < FF_ARRAY_ELEMS(ctx->output); i++) {
-+ ret = v4l2_request_output_buffer_init(ctx, &ctx->output[i]);
-+ if (ret < 0)
-+ goto fail;
++ // Try to use the driver preferred format when it is a known format
++ for (int i = 0; i < FF_ARRAY_ELEMS(v4l2request_capture_pixelformats); i++) {
++ if (pixelformat == v4l2request_capture_pixelformats[i].pixelformat &&
++ (fctx->bit_depth == v4l2request_capture_pixelformats[i].bit_depth ||
++ !fctx->bit_depth))
++ return v4l2request_set_format(hwfc, type, pixelformat, 0);
+ }
+
-+ // Start streaming on OUTPUT queue
-+ type = ctx->fctxi->output.format.type;
-+ if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMON, &type) < 0) {
-+ ret = AVERROR(errno);
-+ av_log(ctx, AV_LOG_ERROR, "Failed to start OUTPUT streaming: %s (%d)\n",
-+ strerror(errno), errno);
-+ goto fail;
-+ }
++ // Next try to use the first known format with matching bit depth
++ while (ioctl(fctxi->video_fd, VIDIOC_ENUM_FMT, &fmtdesc) >= 0) {
++ for (int i = 0; i < FF_ARRAY_ELEMS(v4l2request_capture_pixelformats); i++) {
++ if (fmtdesc.pixelformat == v4l2request_capture_pixelformats[i].pixelformat) {
++ if (fctx->bit_depth == v4l2request_capture_pixelformats[i].bit_depth ||
++ !fctx->bit_depth)
++ return v4l2request_set_format(hwfc, type, fmtdesc.pixelformat, 0);
++ else if (!fallback)
++ fallback = fmtdesc.pixelformat;
++ }
++ }
+
-+ // Start streaming on CAPTURE queue
-+ type = ctx->fctxi->capture.format.type;
-+ if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMON, &type) < 0) {
-+ ret = AVERROR(errno);
-+ av_log(ctx, AV_LOG_ERROR, "Failed to start CAPTURE streaming: %s (%d)\n",
-+ strerror(errno), errno);
-+ goto fail;
++ fmtdesc.index++;
+ }
+
-+ return 0;
++ // Fallback to use the first known format
++ if (fallback)
++ return v4l2request_set_format(hwfc, type, fallback, 0);
+
-+fail:
-+ ff_v4l2_request_uninit(avctx);
-+ return ret;
++ return AVERROR(errno);
+}
-diff --git a/libavcodec/v4l2_request.h b/libavcodec/v4l2_request.h
-new file mode 100644
-index 0000000000000..53759f20bb105
---- /dev/null
-+++ b/libavcodec/v4l2_request.h
-@@ -0,0 +1,105 @@
-+/*
-+ * This file is part of FFmpeg.
-+ *
-+ * FFmpeg is free software; you can redistribute it and/or
-+ * modify it under the terms of the GNU Lesser General Public
-+ * License as published by the Free Software Foundation; either
-+ * version 2.1 of the License, or (at your option) any later version.
-+ *
-+ * FFmpeg is distributed in the hope that it will be useful,
-+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
-+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-+ * Lesser General Public License for more details.
-+ *
-+ * You should have received a copy of the GNU Lesser General Public
-+ * License along with FFmpeg; if not, write to the Free Software
-+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-+ */
+
-+#ifndef AVCODEC_V4L2_REQUEST_H
-+#define AVCODEC_V4L2_REQUEST_H
-+
-+#include <stdbool.h>
-+#include <stdint.h>
-+#include <linux/videodev2.h>
++static int v4l2request_try_framesize(AVHWFramesContext *hwfc,
++ uint32_t pixelformat)
++{
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ struct v4l2_frmsizeenum frmsize = {
++ .index = 0,
++ .pixel_format = pixelformat,
++ };
+
-+#include "libavutil/buffer.h"
-+#include "libavutil/log.h"
-+#include "libavutil/thread.h"
-+#include "avcodec.h"
++ // Enumerate and check if frame size is supported
++ while (ioctl(fctxi->video_fd, VIDIOC_ENUM_FRAMESIZES, &frmsize) >= 0) {
++ if (frmsize.type == V4L2_FRMSIZE_TYPE_DISCRETE &&
++ hwfc->width == frmsize.discrete.width &&
++ hwfc->height == frmsize.discrete.height) {
++ return 0;
++ } else if ((frmsize.type == V4L2_FRMSIZE_TYPE_STEPWISE ||
++ frmsize.type == V4L2_FRMSIZE_TYPE_CONTINUOUS) &&
++ hwfc->width >= frmsize.stepwise.min_width &&
++ hwfc->height >= frmsize.stepwise.min_height &&
++ hwfc->width <= frmsize.stepwise.max_width &&
++ hwfc->height <= frmsize.stepwise.max_height) {
++ return 0;
++ }
+
-+typedef struct AVV4L2RequestFramesContextInternal AVV4L2RequestFramesContextInternal;
++ frmsize.index++;
++ }
+
-+typedef struct V4L2RequestOutputBuffer {
-+ AVBufferRef *ref;
-+ uint32_t index;
-+ int request_fd;
-+ uint8_t *addr;
-+ uint32_t size;
-+ uint32_t bytesused;
-+ struct timeval timestamp;
-+} V4L2RequestOutputBuffer;
++ return AVERROR(errno);
++}
+
-+typedef struct V4L2RequestContext {
-+ const AVClass *av_class;
-+ AVBufferRef *frames_ref;
-+ AVV4L2RequestFramesContextInternal *fctxi;
-+ AVMutex mutex;
-+ V4L2RequestOutputBuffer output[4];
-+ uint8_t next_output;
-+ uint32_t queued_output;
-+ uint32_t queued_request;
-+ uint64_t queued_capture;
-+ struct v4l2_ext_control *init_controls;
-+ int nb_init_controls;
-+} V4L2RequestContext;
++static int v4l2request_try_format(AVHWFramesContext *hwfc,
++ enum v4l2_buf_type type,
++ uint32_t pixelformat)
++{
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ struct v4l2_fmtdesc fmtdesc = {
++ .index = 0,
++ .type = type,
++ };
+
-+typedef struct V4L2RequestPictureContext {
-+ V4L2RequestOutputBuffer *output;
-+ uint32_t capture_index;
-+} V4L2RequestPictureContext;
++ // Enumerate and check if format is supported
++ while (ioctl(fctxi->video_fd, VIDIOC_ENUM_FMT, &fmtdesc) >= 0) {
++ if (fmtdesc.pixelformat == pixelformat)
++ return 0;
+
-+uint64_t ff_v4l2_request_get_capture_timestamp(AVFrame *frame);
++ fmtdesc.index++;
++ }
+
-+int ff_v4l2_request_query_control(AVCodecContext *avctx,
-+ struct v4l2_query_ext_ctrl *control);
++ return AVERROR(errno);
++}
+
-+int ff_v4l2_request_query_control_default_value(AVCodecContext *avctx,
-+ uint32_t id);
++static int v4l2request_set_controls(AVHWFramesContext *hwfc,
++ struct v4l2_ext_control *control, int count)
++{
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ struct v4l2_ext_controls controls = {
++ .controls = control,
++ .count = count,
++ };
+
-+int ff_v4l2_request_set_controls(AVCodecContext *avctx,
-+ struct v4l2_ext_control *control, int count);
++ if (!control || !count)
++ return 0;
+
-+int ff_v4l2_request_append_output(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic,
-+ const uint8_t *data, uint32_t size);
++ if (ioctl(fctxi->video_fd, VIDIOC_S_EXT_CTRLS, &controls) < 0)
++ return AVERROR(errno);
+
-+int ff_v4l2_request_decode_slice(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic,
-+ struct v4l2_ext_control *control, int count,
-+ bool first_slice, bool last_slice);
++ return 0;
++}
+
-+int ff_v4l2_request_decode_frame(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic,
-+ struct v4l2_ext_control *control, int count);
++static int v4l2request_probe_video_device(AVHWFramesContext *hwfc,
++ const char *path,
++ uint32_t pixelformat,
++ uint32_t buffersize)
++{
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ struct v4l2_capability capability;
++ struct v4l2_create_buffers buffers;
++ unsigned int capabilities;
++ int ret;
+
-+int ff_v4l2_request_reset_picture(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic);
++ /*
++ * Open video device in non-blocking mode to support decoding using
++ * multiple queued requests, required for e.g. multi stage decoding.
++ */
++ fctxi->video_fd = open(path, O_RDWR | O_NONBLOCK);
++ if (fctxi->video_fd < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR, "Failed to open video device %s: %s (%d)\n",
++ path, strerror(errno), errno);
++ return ret;
++ }
+
-+int ff_v4l2_request_start_frame(AVCodecContext *avctx,
-+ V4L2RequestPictureContext *pic, AVFrame *frame);
++ // Query capabilities of the video device
++ if (ioctl(fctxi->video_fd, VIDIOC_QUERYCAP, &capability) < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR, "Failed to query capabilities of %s: %s (%d)\n",
++ path, strerror(errno), errno);
++ goto fail;
++ }
+
-+void ff_v4l2_request_flush(AVCodecContext *avctx);
++ // Use device capabilities of the opened device when supported
++ capabilities = (capability.capabilities & V4L2_CAP_DEVICE_CAPS) ?
++ capability.device_caps : capability.capabilities;
+
-+int ff_v4l2_request_frame_params(AVCodecContext *avctx,
-+ AVBufferRef *hw_frames_ctx,
-+ uint32_t pixelformat,
-+ uint8_t bit_depth);
++ // Ensure streaming is supported on the video device
++ if ((capabilities & V4L2_CAP_STREAMING) != V4L2_CAP_STREAMING) {
++ ret = AVERROR(EINVAL);
++ av_log(hwfc, AV_LOG_VERBOSE, "Device %s is missing streaming capability\n", path);
++ goto fail;
++ }
+
-+int ff_v4l2_request_uninit(AVCodecContext *avctx);
++ // Ensure multi- or single-planar API can be used
++ if ((capabilities & V4L2_CAP_VIDEO_M2M_MPLANE) == V4L2_CAP_VIDEO_M2M_MPLANE) {
++ fctxi->output.format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
++ fctxi->capture.format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
++ } else if ((capabilities & V4L2_CAP_VIDEO_M2M) == V4L2_CAP_VIDEO_M2M) {
++ fctxi->output.format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
++ fctxi->capture.format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
++ } else {
++ ret = AVERROR(EINVAL);
++ av_log(hwfc, AV_LOG_VERBOSE, "Device %s is missing mem2mem capability\n", path);
++ goto fail;
++ }
+
-+int ff_v4l2_request_init(AVCodecContext *avctx,
-+ struct v4l2_ext_control *control, int count,
-+ int (*post_frames_ctx)(AVCodecContext *avctx));
++ // Query OUTPUT buffer capabilities
++ buffers = (struct v4l2_create_buffers) {
++ .count = 0,
++ .memory = V4L2_MEMORY_MMAP,
++ .format.type = fctxi->output.format.type,
++ };
++ if (ioctl(fctxi->video_fd, VIDIOC_CREATE_BUFS, &buffers) < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR,
++ "Failed to query OUTPUT buffer capabilities of %s: %s (%d)\n",
++ path, strerror(errno), errno);
++ goto fail;
++ }
++ fctxi->output.capabilities = buffers.capabilities;
+
-+#endif /* AVCODEC_V4L2_REQUEST_H */
-diff --git a/libavcodec/v4l2_request_av1.c b/libavcodec/v4l2_request_av1.c
-new file mode 100644
-index 0000000000000..4eabdbf31b95e
---- /dev/null
-+++ b/libavcodec/v4l2_request_av1.c
-@@ -0,0 +1,636 @@
-+/*
-+ * This file is part of FFmpeg.
-+ *
-+ * FFmpeg is free software; you can redistribute it and/or
-+ * modify it under the terms of the GNU Lesser General Public
-+ * License as published by the Free Software Foundation; either
-+ * version 2.1 of the License, or (at your option) any later version.
-+ *
-+ * FFmpeg is distributed in the hope that it will be useful,
-+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
-+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-+ * Lesser General Public License for more details.
-+ *
-+ * You should have received a copy of the GNU Lesser General Public
-+ * License along with FFmpeg; if not, write to the Free Software
-+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-+ */
++ // Ensure requests can be used
++ if ((buffers.capabilities & V4L2_BUF_CAP_SUPPORTS_REQUESTS) !=
++ V4L2_BUF_CAP_SUPPORTS_REQUESTS) {
++ ret = AVERROR(EINVAL);
++ av_log(hwfc, AV_LOG_VERBOSE, "Device %s is missing support for requests\n", path);
++ goto fail;
++ }
+
-+#include "config.h"
++ // Ensure the codec pixelformat can be used
++ ret = v4l2request_try_format(hwfc, fctxi->output.format.type, pixelformat);
++ if (ret < 0) {
++ av_log(hwfc, AV_LOG_VERBOSE, "Device %s is missing support for pixelformat %s\n",
++ path, av_fourcc2str(pixelformat));
++ goto fail;
++ }
+
-+#include "libavutil/mem.h"
-+#include "hwaccel_internal.h"
-+#include "hwconfig.h"
-+#include "av1dec.h"
-+#include "internal.h"
-+#include "v4l2_request.h"
++ // Ensure frame size is supported, when driver support ENUM_FRAMESIZES
++ ret = v4l2request_try_framesize(hwfc, pixelformat);
++ if (ret < 0 && ret != AVERROR(ENOTTY)) {
++ av_log(hwfc, AV_LOG_VERBOSE,
++ "Device %s is missing support for frame size %dx%d of pixelformat %s\n",
++ path, hwfc->width, hwfc->height, av_fourcc2str(pixelformat));
++ goto fail;
++ }
+
-+#define V4L2_AV1_CONTROLS_MAX 4
++ // Set the codec pixelformat and OUTPUT buffersize to be used
++ ret = v4l2request_set_format(hwfc, fctxi->output.format.type, pixelformat, buffersize);
++ if (ret < 0) {
++ av_log(hwfc, AV_LOG_ERROR,
++ "Failed to set OUTPUT pixelformat %s of %s: %s (%d)\n",
++ av_fourcc2str(pixelformat), path, strerror(errno), errno);
++ goto fail;
++ }
+
-+typedef struct V4L2RequestContextAV1 {
-+ V4L2RequestContext base;
-+ bool has_film_grain;
-+} V4L2RequestContextAV1;
-+
-+typedef struct V4L2RequestControlsAV1 {
-+ V4L2RequestPictureContext pic;
-+ struct v4l2_ctrl_av1_sequence sequence;
-+ struct v4l2_ctrl_av1_frame frame;
-+ struct v4l2_ctrl_av1_film_grain film_grain;
-+ struct v4l2_ctrl_av1_tile_group_entry tile_group_entry;
-+ struct v4l2_ctrl_av1_tile_group_entry *tile_group_entries;
-+ unsigned int allocated_tile_group_entries;
-+ unsigned int num_tile_group_entries;
-+} V4L2RequestControlsAV1;
++ // Get format details for OUTPUT buffers
++ if (ioctl(fctxi->video_fd, VIDIOC_G_FMT, &fctxi->output.format) < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR, "Failed to get OUTPUT format: %s (%d)\n",
++ strerror(errno), errno);
++ goto fail;
++ }
+
-+static int get_bit_depth_from_seq(const AV1RawSequenceHeader *seq)
-+{
-+ if (seq->seq_profile == AV_PROFILE_AV1_PROFESSIONAL &&
-+ seq->color_config.high_bitdepth)
-+ return seq->color_config.twelve_bit ? 12 : 10;
-+ else
-+ return seq->color_config.high_bitdepth ? 10 : 8;
-+}
++ /*
++ * Set any codec specific controls that can help assist the driver
++ * make a decision on what CAPTURE buffer format can be used.
++ */
++ ret = v4l2request_set_controls(hwfc, fctx->init_controls, fctx->nb_init_controls);
++ if (ret < 0) {
++ av_log(hwfc, AV_LOG_VERBOSE,
++ "Failed to set %d control(s): %s (%d)\n",
++ fctx->nb_init_controls, strerror(errno), errno);
++ goto fail;
++ }
+
-+static void fill_sequence(struct v4l2_ctrl_av1_sequence *ctrl,
-+ const AV1DecContext *s)
-+{
-+ const AV1RawSequenceHeader *seq = s->raw_seq;
++ // Select a supported CAPTURE buffer format
++ ret = v4l2request_select_capture_format(hwfc);
++ if (ret < 0) {
++ av_log(hwfc, AV_LOG_VERBOSE,
++ "Failed to select a CAPTURE format %s of %s: %s (%d)\n",
++ av_fourcc2str(pixelformat), path, strerror(errno), errno);
++ goto fail;
++ }
+
-+ *ctrl = (struct v4l2_ctrl_av1_sequence) {
-+ .seq_profile = seq->seq_profile,
-+ .order_hint_bits = seq->enable_order_hint ?
-+ seq->order_hint_bits_minus_1 + 1 : 0,
-+ .bit_depth = get_bit_depth_from_seq(seq),
-+ .max_frame_width_minus_1 = seq->max_frame_width_minus_1,
-+ .max_frame_height_minus_1 = seq->max_frame_height_minus_1,
++ // Query CAPTURE buffer capabilities
++ buffers = (struct v4l2_create_buffers) {
++ .count = 0,
++ .memory = V4L2_MEMORY_MMAP,
++ .format.type = fctxi->capture.format.type,
+ };
++ if (ioctl(fctxi->video_fd, VIDIOC_CREATE_BUFS, &buffers) < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR,
++ "Failed to query CAPTURE buffer capabilities of %s: %s (%d)\n",
++ path, strerror(errno), errno);
++ goto fail;
++ }
++ fctxi->capture.capabilities = buffers.capabilities;
+
-+ if (seq->still_picture)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_STILL_PICTURE;
++ // Get format details for CAPTURE buffers
++ if (ioctl(fctxi->video_fd, VIDIOC_G_FMT, &fctxi->capture.format) < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR, "Failed to get CAPTURE format: %s (%d)\n",
++ strerror(errno), errno);
++ goto fail;
++ }
+
-+ if (seq->use_128x128_superblock)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_USE_128X128_SUPERBLOCK;
++ // All tests passed, video device should be capable
++ return 0;
+
-+ if (seq->enable_filter_intra)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_FILTER_INTRA;
++fail:
++ if (fctxi->video_fd >= 0) {
++ close(fctxi->video_fd);
++ fctxi->video_fd = -1;
++ }
++ return ret;
++}
+
-+ if (seq->enable_intra_edge_filter)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_INTRA_EDGE_FILTER;
++static int v4l2request_probe_video_devices(AVHWFramesContext *hwfc,
++ struct udev *udev,
++ uint32_t pixelformat,
++ uint32_t buffersize)
++{
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ struct media_device_info device_info;
++ struct media_v2_topology topology = {0};
++ struct media_v2_interface *interfaces;
++ struct udev_device *device;
++ const char *path;
++ dev_t devnum;
++ int ret;
+
-+ if (seq->enable_interintra_compound)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_INTERINTRA_COMPOUND;
++ if (ioctl(fctxi->media_fd, MEDIA_IOC_DEVICE_INFO, &device_info) < 0)
++ return AVERROR(errno);
+
-+ if (seq->enable_masked_compound)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_MASKED_COMPOUND;
++ if (ioctl(fctxi->media_fd, MEDIA_IOC_G_TOPOLOGY, &topology) < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR, "Failed to get media topology: %s (%d)\n",
++ strerror(errno), errno);
++ return ret;
++ }
+
-+ if (seq->enable_warped_motion)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_WARPED_MOTION;
++ if (!topology.num_interfaces)
++ return AVERROR(ENOENT);
+
-+ if (seq->enable_dual_filter)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_DUAL_FILTER;
++ interfaces = av_calloc(topology.num_interfaces, sizeof(struct media_v2_interface));
++ if (!interfaces)
++ return AVERROR(ENOMEM);
+
-+ if (seq->enable_order_hint)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_ORDER_HINT;
++ topology.ptr_interfaces = (__u64)(uintptr_t)interfaces;
++ if (ioctl(fctxi->media_fd, MEDIA_IOC_G_TOPOLOGY, &topology) < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR, "Failed to get media topology: %s (%d)\n",
++ strerror(errno), errno);
++ goto fail;
++ }
+
-+ if (seq->enable_jnt_comp)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_JNT_COMP;
++ ret = AVERROR(ENOENT);
++ for (int i = 0; i < topology.num_interfaces; i++) {
++ if (interfaces[i].intf_type != MEDIA_INTF_T_V4L_VIDEO)
++ continue;
+
-+ if (seq->enable_ref_frame_mvs)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_REF_FRAME_MVS;
++ devnum = makedev(interfaces[i].devnode.major, interfaces[i].devnode.minor);
++ device = udev_device_new_from_devnum(udev, 'c', devnum);
++ if (!device)
++ continue;
+
-+ if (seq->enable_superres)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_SUPERRES;
++ path = udev_device_get_devnode(device);
++ if (path)
++ ret = v4l2request_probe_video_device(hwfc, path, pixelformat, buffersize);
++ udev_device_unref(device);
+
-+ if (seq->enable_cdef)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_CDEF;
++ // Stop when we have found a capable video device
++ if (!ret) {
++ av_log(hwfc, AV_LOG_INFO,
++ "Using V4L2 media driver %s (%u.%u.%u) for %s\n",
++ device_info.driver,
++ device_info.driver_version >> 16,
++ (device_info.driver_version >> 8) & 0xff,
++ device_info.driver_version & 0xff,
++ av_fourcc2str(pixelformat));
++ break;
++ }
++ }
+
-+ if (seq->enable_restoration)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_ENABLE_RESTORATION;
++fail:
++ av_free(interfaces);
++ return ret;
++}
+
-+ if (seq->color_config.mono_chrome)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_MONO_CHROME;
++static int v4l2request_probe_media_device(AVHWFramesContext *hwfc,
++ struct udev_device *device,
++ uint32_t pixelformat,
++ uint32_t buffersize)
++{
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ AVV4L2RequestFramesContextInternal *fctxi = fctx->internal;
++ const char *path;
++ int ret;
+
-+ if (seq->color_config.color_range)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_COLOR_RANGE;
++ path = udev_device_get_devnode(device);
++ if (!path)
++ return AVERROR(ENODEV);
+
-+ if (seq->color_config.subsampling_x)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_X;
++ // Open enumerated media device
++ fctxi->media_fd = open(path, O_RDWR);
++ if (fctxi->media_fd < 0) {
++ ret = AVERROR(errno);
++ av_log(hwfc, AV_LOG_ERROR, "Failed to open media device %s: %s (%d)\n",
++ path, strerror(errno), errno);
++ return ret;
++ }
+
-+ if (seq->color_config.subsampling_y)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_SUBSAMPLING_Y;
++ // Probe video devices of current media device
++ ret = v4l2request_probe_video_devices(hwfc, udev_device_get_udev(device),
++ pixelformat, buffersize);
+
-+ if (seq->film_grain_params_present)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_FILM_GRAIN_PARAMS_PRESENT;
++ // Cleanup when no capable video device was found
++ if (ret < 0) {
++ close(fctxi->media_fd);
++ fctxi->media_fd = -1;
++ }
+
-+ if (seq->color_config.separate_uv_delta_q)
-+ ctrl->flags |= V4L2_AV1_SEQUENCE_FLAG_SEPARATE_UV_DELTA_Q;
++ return ret;
+}
+
-+static void fill_frame(struct v4l2_ctrl_av1_frame *ctrl, const AV1DecContext *s)
++static int v4l2request_probe_media_devices(AVHWFramesContext *hwfc,
++ struct udev *udev,
++ uint32_t pixelformat,
++ uint32_t buffersize)
+{
-+ const AV1RawFrameHeader *frame_header = s->raw_frame_header;
-+ const CodedBitstreamAV1Context *cbctx = s->cbc->priv_data;
-+ uint8_t remap_lr_type[4] = {
-+ V4L2_AV1_FRAME_RESTORE_NONE,
-+ V4L2_AV1_FRAME_RESTORE_SWITCHABLE,
-+ V4L2_AV1_FRAME_RESTORE_WIENER,
-+ V4L2_AV1_FRAME_RESTORE_SGRPROJ,
-+ };
-+ int i, j;
++ struct udev_enumerate *enumerate;
++ struct udev_list_entry *devices;
++ struct udev_list_entry *entry;
++ struct udev_device *device;
++ int ret;
+
-+ *ctrl = (struct v4l2_ctrl_av1_frame) {
-+ .tile_info = {
-+ .context_update_tile_id = frame_header->context_update_tile_id,
-+ .tile_cols = frame_header->tile_cols,
-+ .tile_rows = frame_header->tile_rows,
-+ .tile_size_bytes = frame_header->tile_cols_log2 > 0 ||
-+ frame_header->tile_rows_log2 > 0 ?
-+ frame_header->tile_size_bytes_minus1 + 1 : 0,
-+ },
++ enumerate = udev_enumerate_new(udev);
++ if (!enumerate)
++ return AVERROR(ENOMEM);
+
-+ .quantization = {
-+ .base_q_idx = frame_header->base_q_idx,
-+ .delta_q_y_dc = frame_header->delta_q_y_dc,
-+ .delta_q_u_dc = frame_header->delta_q_u_dc,
-+ .delta_q_u_ac = frame_header->delta_q_u_ac,
-+ .delta_q_v_dc = frame_header->delta_q_v_dc,
-+ .delta_q_v_ac = frame_header->delta_q_v_ac,
-+ .qm_y = frame_header->qm_y,
-+ .qm_u = frame_header->qm_u,
-+ .qm_v = frame_header->qm_v,
-+ .delta_q_res = frame_header->delta_q_res,
-+ },
-+
-+ .loop_filter = {
-+ .level[0] = frame_header->loop_filter_level[0],
-+ .level[1] = frame_header->loop_filter_level[1],
-+ .level[2] = frame_header->loop_filter_level[2],
-+ .level[3] = frame_header->loop_filter_level[3],
-+ .sharpness = frame_header->loop_filter_sharpness,
-+ .mode_deltas[0] = frame_header->loop_filter_mode_deltas[0],
-+ .mode_deltas[1] = frame_header->loop_filter_mode_deltas[1],
-+ .delta_lf_res = frame_header->delta_lf_res,
-+ },
-+
-+ .cdef = {
-+ .damping_minus_3 = frame_header->cdef_damping_minus_3,
-+ .bits = frame_header->cdef_bits,
-+ },
-+
-+ .loop_restoration = {
-+ .lr_unit_shift = frame_header->lr_unit_shift,
-+ .lr_uv_shift = frame_header->lr_uv_shift,
-+ },
-+
-+ .superres_denom = frame_header->use_superres ?
-+ frame_header->coded_denom + AV1_SUPERRES_DENOM_MIN :
-+ AV1_SUPERRES_NUM,
-+ .skip_mode_frame[0] = frame_header->skip_mode_present ?
-+ s->cur_frame.skip_mode_frame_idx[0] : 0,
-+ .skip_mode_frame[1] = frame_header->skip_mode_present ?
-+ s->cur_frame.skip_mode_frame_idx[1] : 0,
-+ .primary_ref_frame = frame_header->primary_ref_frame,
-+ .frame_type = frame_header->frame_type,
-+ .order_hint = frame_header->order_hint,
-+ .upscaled_width = cbctx->upscaled_width,
-+ .interpolation_filter = frame_header->interpolation_filter,
-+ .tx_mode = frame_header->tx_mode,
-+ .frame_width_minus_1 = cbctx->frame_width - 1,
-+ .frame_height_minus_1 = cbctx->frame_height - 1,
-+ .render_width_minus_1 = cbctx->render_width - 1,
-+ .render_height_minus_1 = cbctx->render_height - 1,
-+ .current_frame_id = frame_header->current_frame_id,
-+ .refresh_frame_flags = frame_header->refresh_frame_flags,
-+ };
-+
-+ if (frame_header->segmentation_enabled)
-+ ctrl->segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_ENABLED;
++ udev_enumerate_add_match_subsystem(enumerate, "media");
++ udev_enumerate_scan_devices(enumerate);
++ devices = udev_enumerate_get_list_entry(enumerate);
+
-+ if (frame_header->segmentation_update_map)
-+ ctrl->segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_UPDATE_MAP;
++ ret = AVERROR(ENOENT);
++ udev_list_entry_foreach(entry, devices) {
++ const char *path = udev_list_entry_get_name(entry);
++ if (!path)
++ continue;
+
-+ if (frame_header->segmentation_temporal_update)
-+ ctrl->segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_TEMPORAL_UPDATE;
++ device = udev_device_new_from_syspath(udev, path);
++ if (!device)
++ continue;
+
-+ if (frame_header->segmentation_update_data)
-+ ctrl->segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_UPDATE_DATA;
++ // Probe media device for a capable video device
++ ret = v4l2request_probe_media_device(hwfc, device, pixelformat, buffersize);
++ udev_device_unref(device);
+
-+ for (i = 0; i < AV1_MAX_SEGMENTS; i++) {
-+ for (j = 0; j < AV1_SEG_LVL_MAX; j++) {
-+ if (frame_header->feature_enabled[i][j]) {
-+ ctrl->segmentation.feature_enabled[i] |= V4L2_AV1_SEGMENT_FEATURE_ENABLED(j);
-+ ctrl->segmentation.last_active_seg_id = i;
-+ if (j >= AV1_SEG_LVL_REF_FRAME)
-+ ctrl->segmentation.flags |= V4L2_AV1_SEGMENTATION_FLAG_SEG_ID_PRE_SKIP;
-+ }
-+ ctrl->segmentation.feature_data[i][j] = frame_header->feature_value[i][j];
-+ }
++ // Stop when we have found a capable media and video device
++ if (!ret)
++ break;
+ }
+
-+ if (frame_header->uniform_tile_spacing_flag)
-+ ctrl->tile_info.flags |= V4L2_AV1_TILE_INFO_FLAG_UNIFORM_TILE_SPACING;
++ udev_enumerate_unref(enumerate);
++ return ret;
++}
+
-+ for (i = 0; i < frame_header->tile_cols; i++) {
-+ ctrl->tile_info.mi_col_starts[i] = frame_header->tile_start_col_sb[i];
-+ ctrl->tile_info.width_in_sbs_minus_1[i] = frame_header->width_in_sbs_minus_1[i];
-+ }
-+ ctrl->tile_info.mi_col_starts[i] = 2 * ((cbctx->frame_width + 7) >> 3);
+ static int v4l2request_open_decoder(AVHWFramesContext *hwfc)
+ {
+ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
++ uint32_t buffersize;
++ struct udev *udev;
++ int ret;
+
+ // Ensure codec pixelformat is set
+ if (!fctx->pixelformat)
+ return AVERROR(EINVAL);
+
+- // TODO: locate a decoder supporting the requested pixelformat
++ // FIXME: locate a decoder using hwdevice context decoders
+
+- return AVERROR(ENOSYS);
++ udev = udev_new();
++ if (!udev)
++ return AVERROR(ENOMEM);
+
-+ for (i = 0; i < frame_header->tile_rows; i++) {
-+ ctrl->tile_info.mi_row_starts[i] = frame_header->tile_start_row_sb[i];
-+ ctrl->tile_info.height_in_sbs_minus_1[i] = frame_header->height_in_sbs_minus_1[i];
-+ }
-+ ctrl->tile_info.mi_row_starts[i] = 2 * ((cbctx->frame_height + 7) >> 3);
++ buffersize = FFMAX(hwfc->width * hwfc->height * 3 / 2, 256 * 1024);
+
-+ if (frame_header->diff_uv_delta)
-+ ctrl->quantization.flags |= V4L2_AV1_QUANTIZATION_FLAG_DIFF_UV_DELTA;
++ // Probe all media devices (auto-detection)
++ ret = v4l2request_probe_media_devices(hwfc, udev, fctx->pixelformat, buffersize);
+
-+ if (frame_header->using_qmatrix)
-+ ctrl->quantization.flags |= V4L2_AV1_QUANTIZATION_FLAG_USING_QMATRIX;
++ udev_unref(udev);
++ return ret;
+ }
+
+ static AVBufferRef *v4l2request_v4l2_buffer_alloc(AVHWFramesContext *hwfc,
+--
+2.54.0
+
+
+From b002d7464d0c5824f21e01f66261bba815f3ae4f Mon Sep 17 00:00:00 2001
+From: Jonas Karlman <jonas at kwiboo.se>
+Date: Tue, 6 Aug 2024 09:06:01 +0000
+Subject: [PATCH 03/11] avcodec: Add common V4L2 Request API code
+
+Add initial helpers for supporting V4L2 Request API hwaccels.
+
+Basic flow for initialization follows the kernel Memory-to-memory
+Stateless Video Decoder Interface > Initialization [1].
+
+In init a hw frame ctx is created and initialized to start a new V4L2
+video decoding session, initial CAPTURE buffers is pre-allocated,
+OUTPUT buffers and request objects are allocated for a circular queue.
+
+In frame_params the codec pixel format and optional codec-specific
+extended controls is configured before the hw frame ctx is initialized.
+
+In uninit any pending request is flushed before resources are released.
+
+[1] https://www.kernel.org/doc/html/latest/userspace-api/media/v4l/dev-stateless-decoder.html#initialization
+
+Co-developed-by: Jernej Skrabec <jernej.skrabec at gmail.com>
+Signed-off-by: Jernej Skrabec <jernej.skrabec at gmail.com>
+Co-developed-by: Alex Bee <knaerzche at gmail.com>
+Signed-off-by: Alex Bee <knaerzche at gmail.com>
+Signed-off-by: Jonas Karlman <jonas at kwiboo.se>
+---
+ .forgejo/CODEOWNERS | 1 +
+ Changelog | 1 +
+ libavcodec/Makefile | 2 +
+ libavcodec/v4l2_request.c | 249 ++++++++++++++++++++++++++++++++++++++
+ libavcodec/v4l2_request.h | 64 ++++++++++
+ 5 files changed, 317 insertions(+)
+ create mode 100644 libavcodec/v4l2_request.c
+ create mode 100644 libavcodec/v4l2_request.h
+
+diff --git a/.forgejo/CODEOWNERS b/.forgejo/CODEOWNERS
+index 6bd76dc7777..24bb4d9c72d 100644
+--- a/.forgejo/CODEOWNERS
++++ b/.forgejo/CODEOWNERS
+@@ -63,6 +63,7 @@ libavcodec/.*siren.* @lynne
+ libavcodec/smpte_436m.* @programmerjake
+ libavcodec/svq1.* @pross
+ libavcodec/svq3.* @pross
++libavcodec/v4l2_request.* @Kwiboo @jernej @knaerzche
+ libavcodec/.*vc2.* @lynne
+ libavcodec/videotoolbox.* @ePirat
+ libavcodec/vp3.* @pross
+diff --git a/libavcodec/Makefile b/libavcodec/Makefile
+index 12a8265025b..a2212bbf950 100644
+--- a/libavcodec/Makefile
++++ b/libavcodec/Makefile
+@@ -185,6 +185,7 @@ OBJS-$(CONFIG_VIDEODSP) += videodsp.o
+ OBJS-$(CONFIG_VP3DSP) += vp3dsp.o
+ OBJS-$(CONFIG_VP8DSP) += vp8dsp.o
+ OBJS-$(CONFIG_V4L2_M2M) += v4l2_m2m.o v4l2_context.o v4l2_buffers.o v4l2_fmt.o
++OBJS-$(CONFIG_V4L2_REQUEST) += v4l2_request.o
+ OBJS-$(CONFIG_WMA_FREQS) += wma_freqs.o
+ OBJS-$(CONFIG_WMV2DSP) += wmv2dsp.o
+
+@@ -1360,6 +1361,7 @@ SKIPHEADERS-$(CONFIG_VIDEOTOOLBOX) += videotoolbox.h vt_internal.h
+ SKIPHEADERS-$(CONFIG_VULKAN) += ffv1_vulkan.h prores_vulkan.h vulkan_video.h \
+ vulkan_encode.h vulkan_decode.h
+ SKIPHEADERS-$(CONFIG_V4L2_M2M) += v4l2_buffers.h v4l2_context.h v4l2_m2m.h
++SKIPHEADERS-$(CONFIG_V4L2_REQUEST) += v4l2_request.h
+ SKIPHEADERS-$(CONFIG_ZLIB) += zlib_wrapper.h
+
+ TESTPROGS = avcodec \
+diff --git a/libavcodec/v4l2_request.c b/libavcodec/v4l2_request.c
+new file mode 100644
+index 00000000000..dfec0e8906a
+--- /dev/null
++++ b/libavcodec/v4l2_request.c
+@@ -0,0 +1,249 @@
++/*
++ * This file is part of FFmpeg.
++ *
++ * FFmpeg is free software; you can redistribute it and/or
++ * modify it under the terms of the GNU Lesser General Public
++ * License as published by the Free Software Foundation; either
++ * version 2.1 of the License, or (at your option) any later version.
++ *
++ * FFmpeg is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
++ * Lesser General Public License for more details.
++ *
++ * You should have received a copy of the GNU Lesser General Public
++ * License along with FFmpeg; if not, write to the Free Software
++ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
++ */
+
-+ if (frame_header->delta_q_present)
-+ ctrl->quantization.flags |= V4L2_AV1_QUANTIZATION_FLAG_DELTA_Q_PRESENT;
++#include "config.h"
+
-+ if (frame_header->loop_filter_delta_enabled)
-+ ctrl->loop_filter.flags |= V4L2_AV1_LOOP_FILTER_FLAG_DELTA_ENABLED;
++#include <linux/media.h>
++#include <sys/ioctl.h>
++#include <sys/mman.h>
++#include <unistd.h>
+
-+ if (frame_header->loop_filter_delta_update)
-+ ctrl->loop_filter.flags |= V4L2_AV1_LOOP_FILTER_FLAG_DELTA_UPDATE;
++#include "libavutil/hwcontext_v4l2request_internal.h"
++#include "libavutil/mem.h"
++#include "decode.h"
++#include "internal.h"
++#include "v4l2_request.h"
+
-+ if (frame_header->delta_lf_present)
-+ ctrl->loop_filter.flags |= V4L2_AV1_LOOP_FILTER_FLAG_DELTA_LF_PRESENT;
++static const AVClass v4l2_request_context_class = {
++ .class_name = "V4L2RequestContext",
++ .item_name = av_default_item_name,
++ .version = LIBAVUTIL_VERSION_INT,
++};
+
-+ if (frame_header->delta_lf_multi)
-+ ctrl->loop_filter.flags |= V4L2_AV1_LOOP_FILTER_FLAG_DELTA_LF_MULTI;
++static inline V4L2RequestContext *v4l2_request_context(AVCodecContext *avctx)
++{
++ return (V4L2RequestContext *)avctx->internal->hwaccel_priv_data;
++}
+
-+ for (i = 0; i < AV1_NUM_REF_FRAMES; i++) {
-+ ctrl->loop_filter.ref_deltas[i] = frame_header->loop_filter_ref_deltas[i];
++static void v4l2_request_output_buffer_uninit(V4L2RequestOutputBuffer *output)
++{
++ // Close the request associated with the OUTPUT buffer
++ if (output->request_fd >= 0) {
++ close(output->request_fd);
++ output->request_fd = -1;
+ }
+
-+ for (i = 0; i < cbctx->num_planes; i++) {
-+ ctrl->loop_restoration.frame_restoration_type[i] =
-+ remap_lr_type[frame_header->lr_type[i]];
-+ if (frame_header->lr_type[i] != AV1_RESTORE_NONE) {
-+ ctrl->loop_restoration.flags |= V4L2_AV1_LOOP_RESTORATION_FLAG_USES_LR;
-+ if (i > 0)
-+ ctrl->loop_restoration.flags |= V4L2_AV1_LOOP_RESTORATION_FLAG_USES_CHROMA_LR;
-+ }
-+ }
-+ if (ctrl->loop_restoration.flags & V4L2_AV1_LOOP_RESTORATION_FLAG_USES_LR) {
-+ ctrl->loop_restoration.loop_restoration_size[0] =
-+ 1 << (6 + frame_header->lr_unit_shift);
-+ ctrl->loop_restoration.loop_restoration_size[1] =
-+ 1 << (6 + frame_header->lr_unit_shift - frame_header->lr_uv_shift);
-+ ctrl->loop_restoration.loop_restoration_size[2] =
-+ 1 << (6 + frame_header->lr_unit_shift - frame_header->lr_uv_shift);
++ // Umap the OUTPUT buffer memory
++ if (output->addr) {
++ munmap(output->addr, output->size);
++ output->addr = NULL;
+ }
+
-+ for (i = 0; i < AV1_TOTAL_REFS_PER_FRAME; i++) {
-+ ctrl->global_motion.type[i] = s->cur_frame.gm_type[i];
-+ for (j = 0; j < 6; ++j) {
-+ ctrl->global_motion.params[i][j] = s->cur_frame.gm_params[i][j];
-+ if (s->cur_frame.gm_invalid[i])
-+ ctrl->global_motion.invalid |= V4L2_AV1_GLOBAL_MOTION_IS_INVALID(i);
-+ }
-+
-+ if (frame_header->is_global[i])
-+ ctrl->global_motion.flags[i] |= V4L2_AV1_GLOBAL_MOTION_FLAG_IS_GLOBAL;
-+
-+ if (frame_header->is_rot_zoom[i])
-+ ctrl->global_motion.flags[i] |= V4L2_AV1_GLOBAL_MOTION_FLAG_IS_ROT_ZOOM;
++ // Return the OUTPUT buffer to the frames context OUTPUT pool
++ av_buffer_unref(&output->ref);
++}
+
-+ if (frame_header->is_translation[i])
-+ ctrl->global_motion.flags[i] |= V4L2_AV1_GLOBAL_MOTION_FLAG_IS_TRANSLATION;
-+ }
++static int v4l2_request_output_buffer_init(V4L2RequestContext *ctx,
++ V4L2RequestOutputBuffer *output)
++{
++ struct v4l2_format *format = &ctx->fctxi->output.format;
++ struct v4l2_buffer *buffer;
++ off_t offset;
++ void *addr;
++ int ret;
+
-+ for (i = 0; i < AV1_TOTAL_REFS_PER_FRAME; i++) {
-+ AVFrame *ref = s->ref[i].f;
++ // Get an OUTPUT buffer from frames context OUTPUT pool
++ output->ref = av_buffer_pool_get(ctx->fctxi->output.pool);
++ if (!output->ref)
++ return AVERROR(ENOMEM);
+
-+ ctrl->order_hints[i] = s->cur_frame.order_hints[i];
-+ if (ref)
-+ ctrl->reference_frame_ts[i] = ff_v4l2_request_get_capture_timestamp(ref);
-+ if (i < AV1_REFS_PER_FRAME)
-+ ctrl->ref_frame_idx[i] = frame_header->ref_frame_idx[i];
-+ }
++ buffer = (struct v4l2_buffer *)output->ref->data;
++ output->index = buffer->index;
++ output->size = V4L2_TYPE_IS_MULTIPLANAR(format->type) ?
++ format->fmt.pix_mp.plane_fmt[0].sizeimage :
++ format->fmt.pix.sizeimage;
++ output->bytesused = 0;
+
-+ for (i = 0; i < (1 << frame_header->cdef_bits); i++) {
-+ ctrl->cdef.y_pri_strength[i] = frame_header->cdef_y_pri_strength[i];
-+ ctrl->cdef.y_sec_strength[i] = frame_header->cdef_y_sec_strength[i];
-+ ctrl->cdef.uv_pri_strength[i] = frame_header->cdef_uv_pri_strength[i];
-+ ctrl->cdef.uv_sec_strength[i] = frame_header->cdef_uv_sec_strength[i];
++ // Map the OUTPUT buffer memory, raw bitstream data is written into it
++ offset = V4L2_TYPE_IS_MULTIPLANAR(buffer->type) ?
++ buffer->m.planes[0].m.mem_offset :
++ buffer->m.offset;
++ addr = mmap(NULL, output->size, PROT_READ | PROT_WRITE, MAP_SHARED,
++ ctx->fctxi->video_fd, offset);
++ if (addr == MAP_FAILED) {
++ ret = AVERROR(errno);
++ av_log(ctx, AV_LOG_ERROR, "Failed to map OUTPUT buffer %d: %s (%d)\n",
++ output->index, strerror(errno), errno);
++ goto fail;
+ }
++ output->addr = addr;
+
-+ if (frame_header->show_frame)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_SHOW_FRAME;
-+
-+ if (frame_header->showable_frame)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_SHOWABLE_FRAME;
-+
-+ if (frame_header->error_resilient_mode)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_ERROR_RESILIENT_MODE;
++ // Allocate and associated a request for the OUTPUT buffer
++ if (ioctl(ctx->fctxi->media_fd, MEDIA_IOC_REQUEST_ALLOC, &output->request_fd) < 0) {
++ ret = AVERROR(errno);
++ av_log(ctx, AV_LOG_ERROR, "Failed to allocate request for OUTPUT buffer %d: %s (%d)\n",
++ output->index, strerror(errno), errno);
++ goto fail;
++ }
+
-+ if (frame_header->disable_cdf_update)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_DISABLE_CDF_UPDATE;
++ return 0;
+
-+ if (frame_header->allow_screen_content_tools)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_ALLOW_SCREEN_CONTENT_TOOLS;
++fail:
++ v4l2_request_output_buffer_uninit(output);
++ return ret;
++}
+
-+ if (s->cur_frame.force_integer_mv)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_FORCE_INTEGER_MV;
++int ff_v4l2_request_frame_params(AVCodecContext *avctx,
++ AVBufferRef *hw_frames_ctx,
++ uint32_t pixelformat,
++ uint8_t bit_depth)
++{
++ V4L2RequestContext *ctx = v4l2_request_context(avctx);
++ AVHWFramesContext *hwfc = (AVHWFramesContext *)hw_frames_ctx->data;
++ AVV4L2RequestFramesContext *fctx = hwfc->hwctx;
+
-+ if (frame_header->allow_intrabc)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_ALLOW_INTRABC;
++ // Set parameters used during frames context initialization
++ fctx->pixelformat = pixelformat;
++ fctx->bit_depth = bit_depth;
++ if (ctx) {
++ fctx->init_controls = ctx->init_controls;
++ fctx->nb_init_controls = ctx->nb_init_controls;
++ }
+
-+ if (frame_header->use_superres)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_USE_SUPERRES;
++ hwfc->format = AV_PIX_FMT_DRM_PRIME;
++ hwfc->sw_format = AV_PIX_FMT_NONE;
++ hwfc->width = avctx->coded_width;
++ hwfc->height = avctx->coded_height;
+
-+ if (frame_header->allow_high_precision_mv)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_ALLOW_HIGH_PRECISION_MV;
++ // Pre-allocate CAPTURE buffers to ensure CAPTURE queue can be started
++ hwfc->initial_pool_size = 1;
+
-+ if (frame_header->is_motion_mode_switchable)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_IS_MOTION_MODE_SWITCHABLE;
++ return 0;
++}
+
-+ if (frame_header->use_ref_frame_mvs)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_USE_REF_FRAME_MVS;
++int ff_v4l2_request_uninit(AVCodecContext *avctx)
++{
++ V4L2RequestContext *ctx = v4l2_request_context(avctx);
++ enum v4l2_buf_type type;
+
-+ if (frame_header->disable_frame_end_update_cdf)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_DISABLE_FRAME_END_UPDATE_CDF;
++ if (ctx->fctxi) {
++ // TODO: Flush and wait on all pending requests
+
-+ if (frame_header->allow_warped_motion)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_ALLOW_WARPED_MOTION;
++ // Stop streaming on OUTPUT queue
++ type = ctx->fctxi->output.format.type;
++ if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMOFF, &type) < 0)
++ av_log(ctx, AV_LOG_WARNING, "Failed to stop OUTPUT streaming: %s (%d)\n",
++ strerror(errno), errno);
+
-+ if (frame_header->reference_select)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_REFERENCE_SELECT;
++ // Stop streaming on CAPTURE queue
++ type = ctx->fctxi->capture.format.type;
++ if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMOFF, &type) < 0)
++ av_log(ctx, AV_LOG_WARNING, "Failed to stop CAPTURE streaming: %s (%d)\n",
++ strerror(errno), errno);
+
-+ if (frame_header->reduced_tx_set)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_REDUCED_TX_SET;
++ // Release OUTPUT buffers and requests
++ for (int i = 0; i < FF_ARRAY_ELEMS(ctx->output); i++)
++ v4l2_request_output_buffer_uninit(&ctx->output[i]);
+
-+ if (frame_header->skip_mode_present) {
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_SKIP_MODE_ALLOWED; // FIXME
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_SKIP_MODE_PRESENT;
++ ctx->fctxi = NULL;
+ }
+
-+ if (frame_header->frame_size_override_flag)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_FRAME_SIZE_OVERRIDE;
-+
-+ if (frame_header->buffer_removal_time_present_flag) {
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_BUFFER_REMOVAL_TIME_PRESENT;
-+ for (i = 0; i < AV1_MAX_OPERATING_POINTS; i++)
-+ ctrl->buffer_removal_time[i] = frame_header->buffer_removal_time[i];
-+ }
++ av_buffer_unref(&ctx->frames_ref);
++ ff_mutex_destroy(&ctx->mutex);
+
-+ if (frame_header->frame_refs_short_signaling)
-+ ctrl->flags |= V4L2_AV1_FRAME_FLAG_FRAME_REFS_SHORT_SIGNALING;
++ return 0;
+}
+
-+static void fill_film_grain(struct v4l2_ctrl_av1_film_grain *ctrl,
-+ const AV1DecContext *s)
++int ff_v4l2_request_init(AVCodecContext *avctx,
++ struct v4l2_ext_control *control, int count,
++ int (*post_frames_ctx)(AVCodecContext *avctx))
+{
-+ const AV1RawFilmGrainParams *film_grain = &s->cur_frame.film_grain;
-+ int i;
-+
-+ *ctrl = (struct v4l2_ctrl_av1_film_grain) {
-+ .cr_mult = film_grain->cr_mult,
-+ .grain_seed = film_grain->grain_seed,
-+ .film_grain_params_ref_idx = film_grain->film_grain_params_ref_idx,
-+ .num_y_points = film_grain->num_y_points,
-+ .num_cb_points = film_grain->num_cb_points,
-+ .num_cr_points = film_grain->num_cr_points,
-+ .grain_scaling_minus_8 = film_grain->grain_scaling_minus_8,
-+ .ar_coeff_lag = film_grain->ar_coeff_lag,
-+ .ar_coeff_shift_minus_6 = film_grain->ar_coeff_shift_minus_6,
-+ .grain_scale_shift = film_grain->grain_scale_shift,
-+ .cb_mult = film_grain->cb_mult,
-+ .cb_luma_mult = film_grain->cb_luma_mult,
-+ .cr_luma_mult = film_grain->cr_luma_mult,
-+ .cb_offset = film_grain->cb_offset,
-+ .cr_offset = film_grain->cr_offset,
-+ };
-+
-+ if (film_grain->apply_grain)
-+ ctrl->flags |= V4L2_AV1_FILM_GRAIN_FLAG_APPLY_GRAIN;
-+
-+ if (film_grain->update_grain)
-+ ctrl->flags |= V4L2_AV1_FILM_GRAIN_FLAG_UPDATE_GRAIN;
++ V4L2RequestContext *ctx = v4l2_request_context(avctx);
++ AVHWFramesContext *hwfc;
++ AVV4L2RequestFramesContext *fctx;
++ enum v4l2_buf_type type;
++ int ret;
+
-+ if (film_grain->chroma_scaling_from_luma)
-+ ctrl->flags |= V4L2_AV1_FILM_GRAIN_FLAG_CHROMA_SCALING_FROM_LUMA;
++ // Set initial default values
++ ctx->av_class = &v4l2_request_context_class;
++ ctx->init_controls = control;
++ ctx->nb_init_controls = count;
++ ff_mutex_init(&ctx->mutex, NULL);
++ for (int i = 0; i < FF_ARRAY_ELEMS(ctx->output); i++) {
++ ctx->output[i].index = i;
++ ctx->output[i].request_fd = -1;
++ }
+
-+ if (film_grain->overlap_flag)
-+ ctrl->flags |= V4L2_AV1_FILM_GRAIN_FLAG_OVERLAP;
++ // Create frames context and allocate initial CAPTURE buffers
++ ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_V4L2REQUEST);
++ if (ret < 0)
++ goto fail;
+
-+ if (film_grain->clip_to_restricted_range)
-+ ctrl->flags |= V4L2_AV1_FILM_GRAIN_FLAG_CLIP_TO_RESTRICTED_RANGE;
++ ctx->frames_ref = av_buffer_ref(avctx->hw_frames_ctx);
++ if (!ctx->frames_ref) {
++ ret = AVERROR(ENOMEM);
++ goto fail;
++ }
+
-+ if (!film_grain->apply_grain)
-+ return;
++ // Get internal hwctx from frames context
++ hwfc = (AVHWFramesContext *)ctx->frames_ref->data;
++ fctx = hwfc->hwctx;
++ ctx->fctxi = fctx->internal;
+
-+ for (i = 0; i < film_grain->num_y_points; i++) {
-+ ctrl->point_y_value[i] = film_grain->point_y_value[i];
-+ ctrl->point_y_scaling[i] = film_grain->point_y_scaling[i];
-+ }
++ // Reset init controls after successful frames context initialization
++ ctx->init_controls = NULL;
++ ctx->nb_init_controls = 0;
+
-+ for (i = 0; i < film_grain->num_cb_points; i++) {
-+ ctrl->point_cb_value[i] = film_grain->point_cb_value[i];
-+ ctrl->point_cb_scaling[i] = film_grain->point_cb_scaling[i];
++ // Check codec-specific controls, e.g. profile and level
++ if (post_frames_ctx) {
++ ret = post_frames_ctx(avctx);
++ if (ret < 0)
++ goto fail;
+ }
+
-+ for (i = 0; i < film_grain->num_cr_points; i++) {
-+ ctrl->point_cr_value[i] = film_grain->point_cr_value[i];
-+ ctrl->point_cr_scaling[i] = film_grain->point_cr_scaling[i];
++ // Allocate OUTPUT buffers and requests for circular queue
++ for (int i = 0; i < FF_ARRAY_ELEMS(ctx->output); i++) {
++ ret = v4l2_request_output_buffer_init(ctx, &ctx->output[i]);
++ if (ret < 0)
++ goto fail;
+ }
+
-+ for (i = 0; i < 24; i++) {
-+ ctrl->ar_coeffs_y_plus_128[i] = film_grain->ar_coeffs_y_plus_128[i];
++ // Start streaming on OUTPUT queue
++ type = ctx->fctxi->output.format.type;
++ if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMON, &type) < 0) {
++ ret = AVERROR(errno);
++ av_log(ctx, AV_LOG_ERROR, "Failed to start OUTPUT streaming: %s (%d)\n",
++ strerror(errno), errno);
++ goto fail;
+ }
+
-+ for (i = 0; i < 25; i++) {
-+ ctrl->ar_coeffs_cb_plus_128[i] = film_grain->ar_coeffs_cb_plus_128[i];
-+ ctrl->ar_coeffs_cr_plus_128[i] = film_grain->ar_coeffs_cr_plus_128[i];
++ // Start streaming on CAPTURE queue
++ type = ctx->fctxi->capture.format.type;
++ if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMON, &type) < 0) {
++ ret = AVERROR(errno);
++ av_log(ctx, AV_LOG_ERROR, "Failed to start CAPTURE streaming: %s (%d)\n",
++ strerror(errno), errno);
++ goto fail;
+ }
-+}
-+
-+static int v4l2_request_av1_start_frame(AVCodecContext *avctx,
-+ av_unused const AVBufferRef *buf_ref,
-+ av_unused const uint8_t *buffer,
-+ av_unused uint32_t size)
-+{
-+ const AV1DecContext *s = avctx->priv_data;
-+ V4L2RequestContextAV1 *ctx = avctx->internal->hwaccel_priv_data;
-+ V4L2RequestControlsAV1 *controls = s->cur_frame.hwaccel_picture_private;
-+ int ret;
-+
-+ ret = ff_v4l2_request_start_frame(avctx, &controls->pic, s->cur_frame.f);
-+ if (ret)
-+ return ret;
+
-+ fill_sequence(&controls->sequence, s);
-+ fill_frame(&controls->frame, s);
++ return 0;
+
-+ if (ctx->has_film_grain)
-+ fill_film_grain(&controls->film_grain, s);
-+
-+ controls->tile_group_entries = &controls->tile_group_entry;
-+ controls->allocated_tile_group_entries = 0;
-+ controls->num_tile_group_entries = 0;
-+
-+ return 0;
++fail:
++ ff_v4l2_request_uninit(avctx);
++ return ret;
+}
+diff --git a/libavcodec/v4l2_request.h b/libavcodec/v4l2_request.h
+new file mode 100644
+index 00000000000..d09bbf73441
+--- /dev/null
++++ b/libavcodec/v4l2_request.h
+@@ -0,0 +1,64 @@
++/*
++ * This file is part of FFmpeg.
++ *
++ * FFmpeg is free software; you can redistribute it and/or
++ * modify it under the terms of the GNU Lesser General Public
++ * License as published by the Free Software Foundation; either
++ * version 2.1 of the License, or (at your option) any later version.
++ *
++ * FFmpeg is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
++ * Lesser General Public License for more details.
++ *
++ * You should have received a copy of the GNU Lesser General Public
++ * License along with FFmpeg; if not, write to the Free Software
++ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
++ */
+
-+static int v4l2_request_av1_decode_slice(AVCodecContext *avctx,
-+ const uint8_t *buffer, uint32_t size)
-+{
-+ const AV1DecContext *s = avctx->priv_data;
-+ const AV1RawFrameHeader *fh = s->raw_frame_header;
-+ V4L2RequestControlsAV1 *controls = s->cur_frame.hwaccel_picture_private;
++#ifndef AVCODEC_V4L2_REQUEST_H
++#define AVCODEC_V4L2_REQUEST_H
+
-+ controls->num_tile_group_entries = fh->tile_cols * fh->tile_rows;
-+ if (controls->num_tile_group_entries > V4L2_AV1_MAX_TILE_COUNT)
-+ return AVERROR(EINVAL);
++#include <stdbool.h>
++#include <stdint.h>
++#include <linux/videodev2.h>
+
-+ if (controls->num_tile_group_entries > 1 &&
-+ controls->num_tile_group_entries > controls->allocated_tile_group_entries) {
-+ struct v4l2_ctrl_av1_tile_group_entry *tile_group_entries;
++#include "libavutil/buffer.h"
++#include "libavutil/log.h"
++#include "libavutil/thread.h"
++#include "avcodec.h"
+
-+ tile_group_entries = av_realloc_array(controls->allocated_tile_group_entries ?
-+ controls->tile_group_entries : NULL,
-+ controls->num_tile_group_entries,
-+ sizeof(*controls->tile_group_entries));
-+ if (!tile_group_entries)
-+ return AVERROR(ENOMEM);
++typedef struct AVV4L2RequestFramesContextInternal AVV4L2RequestFramesContextInternal;
+
-+ if (!controls->allocated_tile_group_entries)
-+ memcpy(tile_group_entries, controls->tile_group_entries,
-+ sizeof(*controls->tile_group_entries));
++typedef struct V4L2RequestOutputBuffer {
++ AVBufferRef *ref;
++ uint32_t index;
++ int request_fd;
++ uint8_t *addr;
++ uint32_t size;
++ uint32_t bytesused;
++ struct timeval timestamp;
++} V4L2RequestOutputBuffer;
+
-+ controls->tile_group_entries = tile_group_entries;
-+ controls->allocated_tile_group_entries = controls->num_tile_group_entries;
-+ }
++typedef struct V4L2RequestContext {
++ const AVClass *av_class;
++ AVBufferRef *frames_ref;
++ AVV4L2RequestFramesContextInternal *fctxi;
++ AVMutex mutex;
++ V4L2RequestOutputBuffer output[4];
++ struct v4l2_ext_control *init_controls;
++ int nb_init_controls;
++} V4L2RequestContext;
+
-+ for (int i = 0; i < controls->num_tile_group_entries; i++) {
-+ controls->tile_group_entries[i] = (struct v4l2_ctrl_av1_tile_group_entry) {
-+ .tile_offset = controls->pic.output->bytesused +
-+ s->tile_group_info[i].tile_offset,
-+ .tile_size = s->tile_group_info[i].tile_size,
-+ .tile_row = s->tile_group_info[i].tile_row,
-+ .tile_col = s->tile_group_info[i].tile_column,
-+ };
-+ }
++int ff_v4l2_request_frame_params(AVCodecContext *avctx,
++ AVBufferRef *hw_frames_ctx,
++ uint32_t pixelformat,
++ uint8_t bit_depth);
+
-+ return ff_v4l2_request_append_output(avctx, &controls->pic, buffer, size);
-+}
++int ff_v4l2_request_uninit(AVCodecContext *avctx);
+
-+static int v4l2_request_av1_end_frame(AVCodecContext *avctx)
-+{
-+ const AV1DecContext *s = avctx->priv_data;
-+ V4L2RequestContextAV1 *ctx = avctx->internal->hwaccel_priv_data;
-+ V4L2RequestControlsAV1 *controls = s->cur_frame.hwaccel_picture_private;
-+ int count = 0;
++int ff_v4l2_request_init(AVCodecContext *avctx,
++ struct v4l2_ext_control *control, int count,
++ int (*post_frames_ctx)(AVCodecContext *avctx));
+
-+ struct v4l2_ext_control control[V4L2_AV1_CONTROLS_MAX] = {};
++#endif /* AVCODEC_V4L2_REQUEST_H */
+--
+2.54.0
+
+
+From 77b4c717f87fa56039f5b69fe7dccba3a3154ebd Mon Sep 17 00:00:00 2001
+From: Jonas Karlman <jonas at kwiboo.se>
+Date: Tue, 6 Aug 2024 09:06:03 +0000
+Subject: [PATCH 04/11] avcodec/v4l2request: Add common decode support for
+ hwaccels
+
+Add common support for decoding using the V4L2 Request API.
+
+Basic flow for decoding follows the kernel Memory-to-memory Stateless
+Video Decoder Interface > Decoding [1].
+
+A codec hwaccel typically handle decoding as follow:
+
+In start_frame next OUTPUT buffer and its related request object is
+picked from a circular queue and any codec specific CONTROLs are
+prepared.
+
+In decode_slice the slice bitstream data is appended to the OUTPUT
+buffer.
+
+In end_frame a CAPTURE buffer tied to the AVFrame is queued, it will be
+used as the decoding target by the driver / hw decoder. The prepared
+codec specific CONTROLs are queued as part of the request object.
+Finally, the request object is submitted for decoding.
+
+In post_process the AVFrame is only returned once the CAPTURE buffer
+tied to the AVFrame has been made available for dequeuing by the driver.
+
+For slice based hw decoders only the request for the final slice of the
+frame is submitted in end_frame, remaining is submitted in decode_slice.
+
+[1] https://www.kernel.org/doc/html/latest/userspace-api/media/v4l/dev-stateless-decoder.html#decoding
+
+Co-developed-by: Jernej Skrabec <jernej.skrabec at gmail.com>
+Signed-off-by: Jernej Skrabec <jernej.skrabec at gmail.com>
+Co-developed-by: Alex Bee <knaerzche at gmail.com>
+Signed-off-by: Alex Bee <knaerzche at gmail.com>
+Signed-off-by: Jonas Karlman <jonas at kwiboo.se>
+---
+ configure | 3 +-
+ libavcodec/hwconfig.h | 2 +
+ libavcodec/v4l2_request.c | 537 +++++++++++++++++++++++++++++++++++++-
+ libavcodec/v4l2_request.h | 41 +++
+ 4 files changed, 581 insertions(+), 2 deletions(-)
+
+diff --git a/configure b/configure
+index 765345560f5..e62e6985bbc 100755
+--- a/configure
++++ b/configure
+@@ -3352,7 +3352,7 @@ dxva2_deps="dxva2api_h DXVA2_ConfigPictureDecode ole32 user32"
+ ffnvcodec_deps_any="libdl LoadLibrary"
+ mediacodec_deps="android mediandk pthreads"
+ nvdec_deps="ffnvcodec"
+-v4l2_request_deps="linux_media_h v4l2_timeval_to_ns libdrm libudev"
++v4l2_request_deps="linux_media_h v4l2_timeval_to_ns v4l2_m2m_hold_capture_buf libdrm libudev"
+ v4l2_request_suggest="libdrm libudev"
+ vaapi_x11_deps="xlib_x11"
+ videotoolbox_hwaccel_deps="videotoolbox pthreads"
+@@ -7604,6 +7604,7 @@ if enabled v4l2_m2m; then
+ fi
+
+ if enabled v4l2_request; then
++ check_cc v4l2_m2m_hold_capture_buf linux/videodev2.h "int i = V4L2_BUF_FLAG_M2M_HOLD_CAPTURE_BUF"
+ check_func_headers "linux/media.h linux/videodev2.h" v4l2_timeval_to_ns
+ check_pkg_config libudev libudev libudev.h udev_new
+ v4l2_request_extralibs="$libudev_extralibs"
+diff --git a/libavcodec/hwconfig.h b/libavcodec/hwconfig.h
+index ee29ca631df..159064a1f14 100644
+--- a/libavcodec/hwconfig.h
++++ b/libavcodec/hwconfig.h
+@@ -79,6 +79,8 @@ void ff_hwaccel_uninit(AVCodecContext *avctx);
+ HW_CONFIG_HWACCEL(0, 0, 1, D3D11VA_VLD, NONE, ff_ ## codec ## _d3d11va_hwaccel)
+ #define HWACCEL_D3D12VA(codec) \
+ HW_CONFIG_HWACCEL(1, 1, 0, D3D12, D3D12VA, ff_ ## codec ## _d3d12va_hwaccel)
++#define HWACCEL_V4L2REQUEST(codec) \
++ HW_CONFIG_HWACCEL(1, 0, 0, DRM_PRIME, V4L2REQUEST, ff_ ## codec ## _v4l2request_hwaccel)
+
+ #define HW_CONFIG_ENCODER(device, frames, ad_hoc, format, device_type_) \
+ &(const AVCodecHWConfigInternal) { \
+diff --git a/libavcodec/v4l2_request.c b/libavcodec/v4l2_request.c
+index dfec0e8906a..36eec854029 100644
+--- a/libavcodec/v4l2_request.c
++++ b/libavcodec/v4l2_request.c
+@@ -19,6 +19,7 @@
+ #include "config.h"
+
+ #include <linux/media.h>
++#include <poll.h>
+ #include <sys/ioctl.h>
+ #include <sys/mman.h>
+ #include <unistd.h>
+@@ -29,6 +30,8 @@
+ #include "internal.h"
+ #include "v4l2_request.h"
+
++#define V4L2_PLANES_MAX 2
+
-+ control[count++] = (struct v4l2_ext_control) {
-+ .id = V4L2_CID_STATELESS_AV1_SEQUENCE,
-+ .ptr = &controls->sequence,
-+ .size = sizeof(controls->sequence),
-+ };
+ static const AVClass v4l2_request_context_class = {
+ .class_name = "V4L2RequestContext",
+ .item_name = av_default_item_name,
+@@ -40,6 +43,537 @@ static inline V4L2RequestContext *v4l2_request_context(AVCodecContext *avctx)
+ return (V4L2RequestContext *)avctx->internal->hwaccel_priv_data;
+ }
+
++static inline uint32_t v4l2_request_frameindex(AVFrame *frame)
++{
++ return (uint32_t)(uintptr_t)frame->data[1];
++}
+
-+ control[count++] = (struct v4l2_ext_control) {
-+ .id = V4L2_CID_STATELESS_AV1_FRAME,
-+ .ptr = &controls->frame,
-+ .size = sizeof(controls->frame),
++uint64_t ff_v4l2_request_get_capture_timestamp(AVFrame *frame)
++{
++ /*
++ * The CAPTURE buffer index is used as a base for V4L2 frame reference.
++ * This works because frames are decoded into a CAPTURE buffer that is
++ * closely tied to an AVFrame.
++ */
++ struct timeval timestamp = {
++ .tv_sec = 0,
++ .tv_usec = v4l2_request_frameindex(frame) + 1,
+ };
++ return v4l2_timeval_to_ns(×tamp);
++}
+
-+ control[count++] = (struct v4l2_ext_control) {
-+ .id = V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY,
-+ .ptr = controls->tile_group_entries,
-+ .size = sizeof(*controls->tile_group_entries) *
-+ FFMAX(controls->num_tile_group_entries, 1),
-+ };
++int ff_v4l2_request_query_control(AVCodecContext *avctx,
++ struct v4l2_query_ext_ctrl *control)
++{
++ V4L2RequestContext *ctx = v4l2_request_context(avctx);
+
-+ if (ctx->has_film_grain) {
-+ control[count++] = (struct v4l2_ext_control) {
-+ .id = V4L2_CID_STATELESS_AV1_FILM_GRAIN,
-+ .ptr = &controls->film_grain,
-+ .size = sizeof(controls->film_grain),
-+ };
++ if (ioctl(ctx->fctxi->video_fd, VIDIOC_QUERY_EXT_CTRL, control) < 0) {
++ int ret = AVERROR(errno);
++ // Skip error logging when driver does not support control id (EINVAL)
++ if (errno != EINVAL)
++ av_log(ctx, AV_LOG_ERROR, "Failed to query control %u: %s (%d)\n",
++ control->id, strerror(errno), errno);
++ return ret;
+ }
+
-+ return ff_v4l2_request_decode_frame(avctx, &controls->pic, control, count);
++ return 0;
+}
+
-+static void v4l2_request_av1_free_frame_priv(AVRefStructOpaque hwctx, void *data)
++int ff_v4l2_request_query_control_default_value(AVCodecContext *avctx,
++ uint32_t id)
+{
-+ V4L2RequestControlsAV1 *controls = data;
++ struct v4l2_query_ext_ctrl control = {
++ .id = id,
++ };
++ int ret;
+
-+ if (controls->allocated_tile_group_entries)
-+ av_freep(&controls->tile_group_entries);
++ ret = ff_v4l2_request_query_control(avctx, &control);
++ if (ret < 0)
++ return ret;
++
++ return control.default_value;
+}
+
-+static int v4l2_request_av1_post_frames_ctx(AVCodecContext *avctx)
++static int v4l2_request_set_controls(V4L2RequestContext *ctx, int request_fd,
++ struct v4l2_ext_control *control, int count)
+{
-+ V4L2RequestContextAV1 *ctx = avctx->internal->hwaccel_priv_data;
-+
-+ struct v4l2_query_ext_ctrl film_grain = {
-+ .id = V4L2_CID_STATELESS_AV1_FILM_GRAIN,
++ struct v4l2_ext_controls controls = {
++ .controls = control,
++ .count = count,
++ .request_fd = request_fd,
++ .which = (request_fd >= 0) ? V4L2_CTRL_WHICH_REQUEST_VAL : 0,
+ };
+
-+ // TODO: check V4L2_CID_MPEG_VIDEO_AV1_PROFILE
-+ // TODO: check V4L2_CID_MPEG_VIDEO_AV1_LEVEL
++ if (!control || !count)
++ return 0;
+
-+ if (!ff_v4l2_request_query_control(avctx, &film_grain))
-+ ctx->has_film_grain = true;
-+ else
-+ ctx->has_film_grain = false;
++ if (ioctl(ctx->fctxi->video_fd, VIDIOC_S_EXT_CTRLS, &controls) < 0)
++ return AVERROR(errno);
+
+ return 0;
+}
+
-+static int v4l2_request_av1_init(AVCodecContext *avctx)
++int ff_v4l2_request_set_controls(AVCodecContext *avctx,
++ struct v4l2_ext_control *control, int count)
+{
-+ const AV1DecContext *s = avctx->priv_data;
-+ struct v4l2_ctrl_av1_sequence sequence;
++ V4L2RequestContext *ctx = v4l2_request_context(avctx);
++ int ret;
+
-+ struct v4l2_ext_control control[] = {
-+ {
-+ .id = V4L2_CID_STATELESS_AV1_SEQUENCE,
-+ .ptr = &sequence,
-+ .size = sizeof(sequence),
-+ },
-+ };
-+
-+ fill_sequence(&sequence, s);
++ ret = v4l2_request_set_controls(ctx, -1, control, count);
++ if (ret < 0)
++ av_log(ctx, AV_LOG_ERROR, "Failed to set %d control(s): %s (%d)\n",
++ count, strerror(errno), errno);
+
-+ return ff_v4l2_request_init(avctx, control, FF_ARRAY_ELEMS(control),
-+ v4l2_request_av1_post_frames_ctx);
++ return ret;
+}
+
-+static int v4l2_request_av1_frame_params(AVCodecContext *avctx,
-+ AVBufferRef *hw_frames_ctx)
++static int v4l2_request_queue_buffer(V4L2RequestContext *ctx,
++ struct v4l2_buffer *buffer)
+{
-+ const AV1DecContext *s = avctx->priv_data;
-+ const AV1RawSequenceHeader *seq = s ? s->raw_seq : NULL;
-+ uint8_t bit_depth = seq ? get_bit_depth_from_seq(seq) : 0;
-+
-+ return ff_v4l2_request_frame_params(avctx, hw_frames_ctx,
-+ V4L2_PIX_FMT_AV1_FRAME, bit_depth);
-+}
-+
-+const FFHWAccel ff_av1_v4l2request_hwaccel = {
-+ .p.name = "av1_v4l2request",
-+ .p.type = AVMEDIA_TYPE_VIDEO,
-+ .p.id = AV_CODEC_ID_AV1,
-+ .p.pix_fmt = AV_PIX_FMT_DRM_PRIME,
-+ .start_frame = v4l2_request_av1_start_frame,
-+ .decode_slice = v4l2_request_av1_decode_slice,
-+ .end_frame = v4l2_request_av1_end_frame,
-+ .flush = ff_v4l2_request_flush,
-+ .free_frame_priv = v4l2_request_av1_free_frame_priv,
-+ .frame_priv_data_size = sizeof(V4L2RequestControlsAV1),
-+ .init = v4l2_request_av1_init,
-+ .uninit = ff_v4l2_request_uninit,
-+ .priv_data_size = sizeof(V4L2RequestContextAV1),
-+ .frame_params = v4l2_request_av1_frame_params,
-+ .caps_internal = HWACCEL_CAP_ASYNC_SAFE,
-+};
-diff --git a/libavcodec/v4l2_request_h264.c b/libavcodec/v4l2_request_h264.c
-new file mode 100644
-index 0000000000000..5abf631090ac0
---- /dev/null
-+++ b/libavcodec/v4l2_request_h264.c
-@@ -0,0 +1,532 @@
-+/*
-+ * This file is part of FFmpeg.
-+ *
-+ * FFmpeg is free software; you can redistribute it and/or
-+ * modify it under the terms of the GNU Lesser General Public
-+ * License as published by the Free Software Foundation; either
-+ * version 2.1 of the License, or (at your option) any later version.
-+ *
-+ * FFmpeg is distributed in the hope that it will be useful,
-+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
-+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-+ * Lesser General Public License for more details.
-+ *
-+ * You should have received a copy of the GNU Lesser General Public
-+ * License along with FFmpeg; if not, write to the Free Software
-+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
-+ */
-+
-+#include "config.h"
++ struct v4l2_plane planes[V4L2_PLANES_MAX] = {};
+
-+#include "h264dec.h"
-+#include "hwaccel_internal.h"
-+#include "hwconfig.h"
-+#include "internal.h"
-+#include "v4l2_request.h"
++ if (V4L2_TYPE_IS_MULTIPLANAR(buffer->type)) {
++ planes[0].bytesused = buffer->bytesused;
++ buffer->bytesused = 0;
++ buffer->length = FF_ARRAY_ELEMS(planes);
++ buffer->m.planes = planes;
++ }
+
-+typedef struct V4L2RequestContextH264 {
-+ V4L2RequestContext base;
-+ enum v4l2_stateless_h264_decode_mode decode_mode;
-+ enum v4l2_stateless_h264_start_code start_code;
-+} V4L2RequestContextH264;
++ // Queue the buffer
++ if (ioctl(ctx->fctxi->video_fd, VIDIOC_QBUF, buffer) < 0)
++ return AVERROR(errno);
+
-+typedef struct V4L2RequestControlsH264 {
-+ V4L2RequestPictureContext pic;
-+ struct v4l2_ctrl_h264_sps sps;
-+ struct v4l2_ctrl_h264_pps pps;
-+ struct v4l2_ctrl_h264_scaling_matrix scaling_matrix;
-+ struct v4l2_ctrl_h264_decode_params decode_params;
-+ struct v4l2_ctrl_h264_slice_params slice_params;
-+ struct v4l2_ctrl_h264_pred_weights pred_weights;
-+ bool pred_weights_required;
-+ bool first_slice;
-+ int num_slices;
-+} V4L2RequestControlsH264;
++ // Mark the buffer as queued
++ if (V4L2_TYPE_IS_OUTPUT(buffer->type))
++ ctx->queued_output |= 1 << buffer->index;
++ else
++ ctx->queued_capture |= 1 << buffer->index;
+
-+static uint8_t nalu_slice_start_code[] = { 0x00, 0x00, 0x01 };
++ return 0;
++}
+
-+static void fill_weight_factors(struct v4l2_h264_weight_factors *weight_factors,
-+ int list, const H264SliceContext *sl)
++static int v4l2_request_queue_capture_buffer(V4L2RequestContext *ctx,
++ uint32_t index)
+{
-+ for (int i = 0; i < sl->ref_count[list]; i++) {
-+ if (sl->pwt.luma_weight_flag[list]) {
-+ weight_factors->luma_weight[i] = sl->pwt.luma_weight[i][list][0];
-+ weight_factors->luma_offset[i] = sl->pwt.luma_weight[i][list][1];
-+ } else {
-+ weight_factors->luma_weight[i] = 1 << sl->pwt.luma_log2_weight_denom;
-+ weight_factors->luma_offset[i] = 0;
-+ }
-+ for (int j = 0; j < 2; j++) {
-+ if (sl->pwt.chroma_weight_flag[list]) {
-+ weight_factors->chroma_weight[i][j] = sl->pwt.chroma_weight[i][list][j][0];
-+ weight_factors->chroma_offset[i][j] = sl->pwt.chroma_weight[i][list][j][1];
-+ } else {
-+ weight_factors->chroma_weight[i][j] = 1 << sl->pwt.chroma_log2_weight_denom;
-+ weight_factors->chroma_offset[i][j] = 0;
-+ }
-+ }
-+ }
++ struct v4l2_buffer buffer = {
++ .index = index,
++ .type = ctx->fctxi->capture.format.type,
++ .memory = V4L2_MEMORY_MMAP,
++ };
++ return v4l2_request_queue_buffer(ctx, &buffer);
+}
+
-+static void fill_dpb_entry(struct v4l2_h264_dpb_entry *entry,
-+ const H264Picture *pic, int long_idx)
++static int v4l2_request_queue_output_buffer(V4L2RequestContext *ctx,
++ V4L2RequestOutputBuffer *output,
++ uint32_t flags)
+{
-+ entry->reference_ts = ff_v4l2_request_get_capture_timestamp(pic->f);
-+ entry->pic_num = pic->pic_id;
-+ entry->frame_num = pic->long_ref ? long_idx : pic->frame_num;
-+ entry->fields = pic->reference & V4L2_H264_FRAME_REF;
-+ entry->flags = V4L2_H264_DPB_ENTRY_FLAG_VALID;
-+ if (entry->fields)
-+ entry->flags |= V4L2_H264_DPB_ENTRY_FLAG_ACTIVE;
-+ if (pic->long_ref)
-+ entry->flags |= V4L2_H264_DPB_ENTRY_FLAG_LONG_TERM;
-+ if (pic->field_picture)
-+ entry->flags |= V4L2_H264_DPB_ENTRY_FLAG_FIELD;
-+ if (pic->field_poc[0] != INT_MAX)
-+ entry->top_field_order_cnt = pic->field_poc[0];
-+ if (pic->field_poc[1] != INT_MAX)
-+ entry->bottom_field_order_cnt = pic->field_poc[1];
++ struct v4l2_buffer buffer = {
++ .index = output->index,
++ .type = ctx->fctxi->output.format.type,
++ .memory = V4L2_MEMORY_MMAP,
++ .timestamp = output->timestamp,
++ .bytesused = output->bytesused,
++ .request_fd = output->request_fd,
++ .flags = V4L2_BUF_FLAG_REQUEST_FD | flags,
++ };
++ return v4l2_request_queue_buffer(ctx, &buffer);
+}
+
-+static void fill_dpb(struct v4l2_ctrl_h264_decode_params *decode_params,
-+ const H264Context *h)
++static int v4l2_request_dequeue_buffer(V4L2RequestContext *ctx,
++ enum v4l2_buf_type type)
+{
-+ int entries = 0;
++ struct v4l2_plane planes[V4L2_PLANES_MAX] = {};
++ struct v4l2_buffer buffer = {
++ .type = type,
++ .memory = V4L2_MEMORY_MMAP,
++ };
+
-+ for (int i = 0; i < h->short_ref_count; i++) {
-+ const H264Picture *pic = h->short_ref[i];
-+ if (pic && (pic->field_poc[0] != INT_MAX || pic->field_poc[1] != INT_MAX))
-+ fill_dpb_entry(&decode_params->dpb[entries++], pic, pic->pic_id);
++ if (V4L2_TYPE_IS_MULTIPLANAR(buffer.type)) {
++ buffer.length = FF_ARRAY_ELEMS(planes);
++ buffer.m.planes = planes;
+ }
+
-+ if (!h->long_ref_count)
-+ return;
++ // Dequeue next completed buffer
++ if (ioctl(ctx->fctxi->video_fd, VIDIOC_DQBUF, &buffer) < 0)
++ return AVERROR(errno);
+
-+ for (int i = 0; i < FF_ARRAY_ELEMS(h->long_ref); i++) {
-+ const H264Picture *pic = h->long_ref[i];
-+ if (pic && (pic->field_poc[0] != INT_MAX || pic->field_poc[1] != INT_MAX))
-+ fill_dpb_entry(&decode_params->dpb[entries++], pic, i);
-+ }
++ // Mark the buffer as dequeued
++ if (V4L2_TYPE_IS_OUTPUT(buffer.type))
++ ctx->queued_output &= ~(1 << buffer.index);
++ else
++ ctx->queued_capture &= ~(1 << buffer.index);
++
++ return 0;
+}
+
-+static void fill_ref_list(struct v4l2_h264_reference *reference,
-+ struct v4l2_ctrl_h264_decode_params *decode_params,
-+ const H264Ref *ref)
++static inline int v4l2_request_dequeue_completed_buffers(V4L2RequestContext *ctx,
++ enum v4l2_buf_type type)
+{
-+ uint64_t timestamp;
-+
-+ if (!ref->parent)
-+ return;
++ int ret;
+
-+ timestamp = ff_v4l2_request_get_capture_timestamp(ref->parent->f);
++ do {
<Skipped 6923 lines>
================================================================
---- gitweb:
http://git.pld-linux.org/gitweb.cgi/packages/ffmpeg.git/commitdiff/cfb3bf8a9e7804b8141749d5ffd89ac75cc6a555
More information about the pld-cvs-commit
mailing list