WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC, VP8, VP9 and AV1 #20847

Draft
Jonas Karlman wants to merge 11 commits from Kwiboo/FFmpeg:v4l2request-v3 into master
First-time contributor

This is a follow up to a very old series from April 2019 (RFC),
December 2020 (v1) and August 2024 (v2), adding V4L2 Request API
hwaccels for stateless decoding of MPEG2, H.264, HEVC, VP8, VP9 and AV1.

These hwaccels has in one form or another been used in LibreELEC
community, nightly and release images since Dec 20, 2018. A version very
close to the one submitted in this PR has been used by LibreELEC since
Dec 22, 2024.

See August 2024 (v2) for a short summary of the history behind this PR.

CHANGES

In this version (and v2) a new V4L2 Request API hwdevice has been added.
Thanks to this it is now possible to specify what media device to use
for decoding, in case multiple decoders exist on a system. E.g. using a
-init_hw_device v4l2request:/dev/media1 parameter.

(temporary not implemented during refactoring)

Compared to v2 this only includes support for V4L2_PIX_FMTs that has
been merged into mainline Linux. As a result, this version cannot be
tested with the downstream rpivid driver on Raspberry Pi or using
AFBC buffers on Allwinner.

HOW TO USE

To use the V4L2 Request API hwaccels you must build FFmpeg on a system
with recent Linux kernel headers, v6.0+. It also requires libdrm and
libudev for the hwaccels to be enabled and successfully built.

This can then be runtime tested on multiple Allwinner and Rockchip
devices.

ffmpeg -hwaccel v4l2request -hwaccel_output_format drm_prime -i <input-path> -map 0:v -f null -

This series has been tested with cedrus driver on Allwinner H6, hantro
and rkvdec driver on Rockchip RK3399.

It should be possible to playback video using kodi-gbm and mpv (with PR14690)
using the v4l2request hwaccels on supported devices.

It should also be possible to run fluster test suites with PR179.

FUTURE

Following parts has been held back and will follow in future PRs.

  • Support V4L2_PIX_FMTs used by pending rpi-hevc-dec driver.
  • Support V4L2_PIX_FMTs used by mtk-vcodec-dec driver.
  • Check for PROFILE and LEVEL controls to filter out any video device
    not reporting support for current profile and level.
  • Estimate max output buffer size used for bitstream data instead of
    using a fixed value.
This is a follow up to a very old series from [April 2019 (RFC)](https://lists.ffmpeg.org/pipermail/ffmpeg-devel/2019-April/242316.html), [December 2020 (v1)](https://lists.ffmpeg.org/pipermail/ffmpeg-devel/2020-December/273579.html) and [August 2024 (v2)](https://lists.ffmpeg.org/pipermail/ffmpeg-devel/2024-August/332034.html), adding V4L2 Request API hwaccels for stateless decoding of MPEG2, H.264, HEVC, VP8, VP9 and AV1. These hwaccels has in one form or another been used in [LibreELEC](https://github.com/LibreELEC/LibreELEC.tv) community, nightly and release images since Dec 20, 2018. A version very close to the one submitted in this PR has been used by LibreELEC since Dec 22, 2024. See [August 2024 (v2)](https://lists.ffmpeg.org/pipermail/ffmpeg-devel/2024-August/332034.html) for a short summary of the history behind this PR. **CHANGES** ~In this version (and v2) a new V4L2 Request API hwdevice has been added. Thanks to this it is now possible to specify what media device to use for decoding, in case multiple decoders exist on a system. E.g. using a `-init_hw_device v4l2request:/dev/media1` parameter.~ (temporary not implemented during refactoring) Compared to v2 this only includes support for `V4L2_PIX_FMT`s that has been merged into mainline Linux. As a result, this version cannot be tested with the downstream `rpivid` driver on Raspberry Pi or using AFBC buffers on Allwinner. **HOW TO USE** To use the V4L2 Request API hwaccels you must build FFmpeg on a system with recent Linux kernel headers, `v6.0+`. It also requires `libdrm` and `libudev` for the hwaccels to be enabled and successfully built. This can then be runtime tested on multiple Allwinner and Rockchip devices. ``` ffmpeg -hwaccel v4l2request -hwaccel_output_format drm_prime -i <input-path> -map 0:v -f null - ``` This series has been tested with `cedrus` driver on Allwinner H6, `hantro` and `rkvdec` driver on Rockchip RK3399. It should be possible to playback video using `kodi-gbm` and `mpv` (with [PR14690](https://github.com/mpv-player/mpv/pull/14690)) using the v4l2request hwaccels on supported devices. It should also be possible to run [fluster](https://github.com/fluendo/fluster) test suites with [PR179](https://github.com/fluendo/fluster/pull/179). **FUTURE** Following parts has been held back and will follow in future PRs. - ~Support `V4L2_PIX_FMT`s used by pending [rpi-hevc-dec](https://lore.kernel.org/linux-media/[email protected]/) driver.~ - Support `V4L2_PIX_FMT`s used by `mtk-vcodec-dec` driver. - Check for PROFILE and LEVEL controls to filter out any video device not reporting support for current profile and level. - ~Estimate max output buffer size used for bitstream data instead of using a fixed value.~
MAINTAINERS Outdated
@ -284,6 +284,7 @@ Hardware acceleration:
d3d12va* Wu Jianhua
d3d12va_encode* Tong Wu
mediacodec* Matthieu Bouron, Aman Gupta, Zhao Zhili
v4l2_request* [2] Jonas Karlman (CC [email protected])
Member

By adding yourself to this file you're requesting push access. Is this what you'd like?

By adding yourself to this file you're requesting push access. Is this what you'd like?
Author
First-time contributor

This was something I added before the move to forgejo, the line in CODEOWNERS should probably be good enough, I will drop this, thanks.

This was something I added before the move to forgejo, the line in CODEOWNERS should probably be good enough, I will drop this, thanks.
Lynne marked this conversation as resolved
@ -0,0 +36,4 @@
* Defaults to -1 for auto-detect.
*/
int media_fd;
} AVV4L2RequestDeviceContext;
Member

Can't you extend hwcontext_drm instead? You're already using its frame structure.

Can't you extend hwcontext_drm instead? You're *already* using its frame structure.
Author
First-time contributor

The Linux DRM subsystem is not involved at all when decoding using the V4L2 subsystem, so extending or using hwcontext_drm seem inappropriate. With V4L2 you can technically decode video on devices without a DRM subsystem device.

The only DRM subsystem related is that these hwaccels export framebuffers that can be imported into a DRM subsystem device for rendering purposes, and the required information for zero-copy is stored as a AVDRMFrameDescriptors / DRM_PRIME output frame.

In the early versions of these hwaccels we did used the plain hwcontext_drm and was then forced to supply a path to a DRM subsystem device that was not used for anything.
With the change to use a hwcontext_v4l2request we now have the option to supply a path to a /dev/media device that should be used to decode.

Maybe the hwcontext part could/should be handled differently?

The Linux DRM subsystem is not involved at all when decoding using the V4L2 subsystem, so extending or using hwcontext_drm seem inappropriate. With V4L2 you can technically decode video on devices without a DRM subsystem device. The only DRM subsystem related is that these hwaccels export framebuffers that can be imported into a DRM subsystem device for rendering purposes, and the required information for zero-copy is stored as a `AVDRMFrameDescriptor`s / `DRM_PRIME` output frame. In the early versions of these hwaccels we did used the plain hwcontext_drm and was then forced to supply a path to a DRM subsystem device that was not used for anything. With the change to use a hwcontext_v4l2request we now have the option to supply a path to a /dev/media device that should be used to decode. Maybe the hwcontext part could/should be handled differently?
@ -0,0 +201,4 @@
// Wait on the specific request to complete, when needed
while (atomic_load(&ctx->queued_request) & (1 << output->index)) {
int ret = poll(&pollfd, 1, 2000);
Member

What's with the atomic variables and polls? Don't tell me after that many years of development drm_syncobj cannot be used?!?

Also, atomics do nothing here. Without the threadsafe flag, all calls to all hwaccel functions are locked behind a mutex. You don't need them.

What's with the atomic variables and polls? Don't tell me after **that** many years of development drm_syncobj cannot be used?!? Also, atomics do nothing here. Without the threadsafe flag, *all* calls to all hwaccel functions are locked behind a mutex. You don't need them.
Author
First-time contributor

Because the DRM subsystem is not involved in the decoding, use of drm_syncobj or fences does not help/work here.
For V4L2 decoding we have V4L2 buffers and must use ioctl and select/poll interface to interact with the V4L2 subsystem.

Use of atomics may be overkill, threadsafety is hard to get right for the decoding and rendering sync, use of atomics helped add an extra layer without digging too deep into FFmpeg internals.

Basically what we do is send a decoding request to the kernel and then quickly return knowing that the kernel should complete the decoding of the frame at some later time. Then there is a sync in post_process to ensure the frame is only returned to the application after the kernel has signaled that the frame in question has finished decoding.

Because the DRM subsystem is not involved in the decoding, use of drm_syncobj or fences does not help/work here. For V4L2 decoding we have V4L2 buffers and must use `ioctl` and `select`/`poll` interface to interact with the V4L2 subsystem. Use of atomics may be overkill, threadsafety is hard to get right for the decoding and rendering sync, use of atomics helped add an extra layer without digging too deep into FFmpeg internals. Basically what we do is send a decoding request to the kernel and then quickly return knowing that the kernel should complete the decoding of the frame at some later time. Then there is a sync in post_process to ensure the frame is only returned to the application after the kernel has signaled that the frame in question has finished decoding.
Member

Could you clean it up? There's no need for mutexes, as the framework already handle this, or atomics. poll() should be sufficient, shouldn't it?

Could you clean it up? There's no need for mutexes, as the framework already handle this, or atomics. poll() should be sufficient, shouldn't it?
Author
First-time contributor

I have removed the use of atomics, however I left the mutex for now. With limited understanding of FFmpeg internals the code seem to indicate that post_process may not be protected by hwaccel_mutex and instead is run on the application thread and some lock/sync may be needed, please correct me if I am wrong.

If my understanding is correct we should also be able to use the HWACCEL_CAP_ASYNC_SAFE flag, I still do not fully understand the impact of using or not using this flag.

Running ffmpeg cmd to test decoding seem to produce consistent md5 checksum for conformance test videos with current changes and the use of HWACCEL_CAP_ASYNC_SAFE flag. I will also run rendering tests using kodi-gbm and mpv to inspect video rendering.

I have removed the use of atomics, however I left the mutex for now. With limited understanding of FFmpeg internals the code seem to indicate that `post_process` may not be protected by `hwaccel_mutex` and instead is run on the application thread and some lock/sync may be needed, please correct me if I am wrong. If my understanding is correct we should also be able to use the `HWACCEL_CAP_ASYNC_SAFE` flag, I still do not fully understand the impact of using or not using this flag. Running `ffmpeg` cmd to test decoding seem to produce consistent `md5` checksum for conformance test videos with current changes and the use of `HWACCEL_CAP_ASYNC_SAFE` flag. I will also run rendering tests using `kodi-gbm` and `mpv` to inspect video rendering.
Member

Err, why are you using FrameDecodeData?
I'm not sure how HWACCEL_CAP_ASYNC_SAFE interacts at all with the FrameDecodeData API, since literally no one normal uses it internally.
Wouldn't it be simpler to just dispatch and then wait in end_frame?

Err, why are you using FrameDecodeData? I'm not sure how HWACCEL_CAP_ASYNC_SAFE interacts at all with the FrameDecodeData API, since literally no one **normal** uses it internally. Wouldn't it be simpler to just dispatch and then wait in end_frame?
Author
First-time contributor

To fully utilize the stateless decoders we should typically try to have multiple decoding requests in-flight at the time. Some HW decoders, e.g. the HEVC decoder in Raspberry Pi 4+, uses a two-step decoding process where first step of one frame can run at the same time as the second step for a different frame.

To best support multiple in-flight decoding requests we try to only issue the decoding request at decode_slice or end_frame without waiting for the request to complete and instead wait for it to complete in post_process just before the frame is returned to the application.

In our initial hwaccel implementation we used to wait for the decoding to complete in end_frame, however after we moved the wait for decoding to complete to a later stage the decoding performance has been increased a few percent due to the improved utilization of the HW.

To fully utilize the stateless decoders we should typically try to have multiple decoding requests in-flight at the time. Some HW decoders, e.g. the HEVC decoder in Raspberry Pi 4+, uses a two-step decoding process where first step of one frame can run at the same time as the second step for a different frame. To best support multiple in-flight decoding requests we try to only issue the decoding request at `decode_slice` or `end_frame` without waiting for the request to complete and instead wait for it to complete in `post_process` just before the frame is returned to the application. In our initial hwaccel implementation we used to wait for the decoding to complete in `end_frame`, however after we moved the wait for decoding to complete to a later stage the decoding performance has been increased a few percent due to the improved utilization of the HW.
Member

I looked at the code, and you could enable HWACCEL_CAP_ASYNC_SAFE, though there are modifications you'd need to make.

  1. You'll need to switch to using an AVBufferPool like I suggested.
  2. If that flag is enabled, each thread will have its own V4L2RequestContext. The FFHWAccel.init callback will get called for each thread. That means that you'll essentially have multiple active decoder instances, including their own mutex. If that's an issue, you can create a V4L2RequestSharedContext or similar on the first thread, and use an FFHWAccel.update_thread_context callback to propagate the shared context, as well as any flags needed to all other threads. Take a look at what libavcodec/vulkan_decode.c:ff_vk_update_thread_context() does.

You can implement this as a later patch too, though it would not be that much work to just implement it, since what I described above should be all that's needed.

I looked at the code, and you could enable HWACCEL_CAP_ASYNC_SAFE, though there are modifications you'd need to make. 1. You'll need to switch to using an AVBufferPool like I suggested. 2. If that flag is enabled, each thread **will have its own V4L2RequestContext**. The `FFHWAccel.init` callback will get called for each thread. That means that you'll essentially have multiple active decoder instances, including their own mutex. If that's an issue, you can create a V4L2Request*Shared*Context or similar on the first thread, and use an `FFHWAccel.update_thread_context` callback to propagate the shared context, as well as any flags needed to all other threads. Take a look at what `libavcodec/vulkan_decode.c:ff_vk_update_thread_context()` does. You can implement this as a later patch too, though it would not be that much work to just implement it, since what I described above should be all that's needed.
Author
First-time contributor

I did a test with HWACCEL_CAP_ASYNC_SAFE and it looks like the V4L2RequestContext / hwaccel_priv_data currently is shared among the thread unique AVCodecContext. Also the FFHWAccel.init is only called once, see below snippet and attached log.

I am still not sure if use of .caps_internal = HWACCEL_CAP_ASYNC_SAFE, affected anything, will test and trace some more.

This should hopefully also help illustrate that decoding requests are queued at end_frame/v4l2_request_queue_buffer() and does not need to be complete/dequeued until post_process (or when a target capture.index is being reused for a frame).

[h264 @ 0xaaaaef5177c0] Format drm_prime requires hwaccel h264_v4l2request initialisation.
ff_v4l2_request_init: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80
[h264 @ 0xaaaaef5177c0] Using V4L2 media driver hantro-vpu (6.17.7) for S264
v4l2_request_init_context: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80
ff_v4l2_request_start_frame: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff6808a3a0 capture.index=9
v4l2_request_queue_decode: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff6808a3a0 capture.index=9
v4l2_request_queue_buffer: pthread_self=281472899608960 ctx=0xffff6807cd80 capture.index=9
ff_v4l2_request_start_frame: pthread_self=281472891154816 avctx=0xaaaaef51a2e0 ctx=0xffff6807cd80 pic=0xffff5c079450 capture.index=8
v4l2_request_queue_decode: pthread_self=281472891154816 avctx=0xaaaaef51a2e0 ctx=0xffff6807cd80 pic=0xffff5c079450 capture.index=8
v4l2_request_queue_buffer: pthread_self=281472891154816 ctx=0xffff6807cd80 capture.index=8
ff_v4l2_request_start_frame: pthread_self=281472882700672 avctx=0xaaaaef5243a0 ctx=0xffff6807cd80 pic=0xffff60079340 capture.index=7
v4l2_request_dequeue_buffer: pthread_self=281472882700672 ctx=0xffff6807cd80 capture.index=9
v4l2_request_dequeue_buffer: pthread_self=281472882700672 ctx=0xffff6807cd80 capture.index=8
v4l2_request_queue_decode: pthread_self=281472882700672 avctx=0xaaaaef5243a0 ctx=0xffff6807cd80 pic=0xffff60079340 capture.index=7
v4l2_request_queue_buffer: pthread_self=281472882700672 ctx=0xffff6807cd80 capture.index=7
ff_v4l2_request_start_frame: pthread_self=281472874246528 avctx=0xaaaaef51eb20 ctx=0xffff6807cd80 pic=0xffff54078fc0 capture.index=6
v4l2_request_queue_decode: pthread_self=281472874246528 avctx=0xaaaaef51eb20 ctx=0xffff6807cd80 pic=0xffff54078fc0 capture.index=6
v4l2_request_queue_buffer: pthread_self=281472874246528 ctx=0xffff6807cd80 capture.index=6
ff_v4l2_request_start_frame: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff6808c460 capture.index=5
v4l2_request_dequeue_buffer: pthread_self=281472899608960 ctx=0xffff6807cd80 capture.index=7
v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=9
v4l2_request_queue_decode: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff6808c460 capture.index=5
v4l2_request_queue_buffer: pthread_self=281472899608960 ctx=0xffff6807cd80 capture.index=5

[...]

ff_v4l2_request_start_frame: pthread_self=281472882700672 avctx=0xaaaaef5243a0 ctx=0xffff6807cd80 pic=0xffff600792f0 capture.index=7
v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=9
v4l2_request_queue_decode: pthread_self=281472882700672 avctx=0xaaaaef5243a0 ctx=0xffff6807cd80 pic=0xffff600792f0 capture.index=7
v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=2
v4l2_request_queue_buffer: pthread_self=281472882700672 ctx=0xffff6807cd80 capture.index=7
ff_v4l2_request_start_frame: pthread_self=281472874246528 avctx=0xaaaaef51eb20 ctx=0xffff6807cd80 pic=0xffff540b3420 capture.index=8
v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=0
v4l2_request_queue_decode: pthread_self=281472874246528 avctx=0xaaaaef51eb20 ctx=0xffff6807cd80 pic=0xffff540b3420 capture.index=8
v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=3
v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=0
v4l2_request_queue_buffer: pthread_self=281472874246528 ctx=0xffff6807cd80 capture.index=8
ff_v4l2_request_start_frame: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff680ff480 capture.index=9
v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=7
v4l2_request_queue_decode: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff680ff480 capture.index=9
v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=7
v4l2_request_queue_buffer: pthread_self=281472899608960 ctx=0xffff6807cd80 capture.index=9
v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=6
v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=8
v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=8
v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=9
v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=9
v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=3
ff_v4l2_request_uninit: pthread_self=281472848884096 avctx=0xaaaaef516c80 ctx=0xffff6807cd80
I did a test with `HWACCEL_CAP_ASYNC_SAFE` and it looks like the `V4L2RequestContext` / `hwaccel_priv_data` currently is shared among the thread unique `AVCodecContext`. Also the `FFHWAccel.init` is only called once, see below snippet and attached log. I am still not sure if use of `.caps_internal = HWACCEL_CAP_ASYNC_SAFE,` affected anything, will test and trace some more. This should hopefully also help illustrate that decoding requests are queued at `end_frame`/`v4l2_request_queue_buffer()` and does not need to be complete/dequeued until `post_process` (or when a target capture.index is being reused for a frame). ``` [h264 @ 0xaaaaef5177c0] Format drm_prime requires hwaccel h264_v4l2request initialisation. ff_v4l2_request_init: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 [h264 @ 0xaaaaef5177c0] Using V4L2 media driver hantro-vpu (6.17.7) for S264 v4l2_request_init_context: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 ff_v4l2_request_start_frame: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff6808a3a0 capture.index=9 v4l2_request_queue_decode: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff6808a3a0 capture.index=9 v4l2_request_queue_buffer: pthread_self=281472899608960 ctx=0xffff6807cd80 capture.index=9 ff_v4l2_request_start_frame: pthread_self=281472891154816 avctx=0xaaaaef51a2e0 ctx=0xffff6807cd80 pic=0xffff5c079450 capture.index=8 v4l2_request_queue_decode: pthread_self=281472891154816 avctx=0xaaaaef51a2e0 ctx=0xffff6807cd80 pic=0xffff5c079450 capture.index=8 v4l2_request_queue_buffer: pthread_self=281472891154816 ctx=0xffff6807cd80 capture.index=8 ff_v4l2_request_start_frame: pthread_self=281472882700672 avctx=0xaaaaef5243a0 ctx=0xffff6807cd80 pic=0xffff60079340 capture.index=7 v4l2_request_dequeue_buffer: pthread_self=281472882700672 ctx=0xffff6807cd80 capture.index=9 v4l2_request_dequeue_buffer: pthread_self=281472882700672 ctx=0xffff6807cd80 capture.index=8 v4l2_request_queue_decode: pthread_self=281472882700672 avctx=0xaaaaef5243a0 ctx=0xffff6807cd80 pic=0xffff60079340 capture.index=7 v4l2_request_queue_buffer: pthread_self=281472882700672 ctx=0xffff6807cd80 capture.index=7 ff_v4l2_request_start_frame: pthread_self=281472874246528 avctx=0xaaaaef51eb20 ctx=0xffff6807cd80 pic=0xffff54078fc0 capture.index=6 v4l2_request_queue_decode: pthread_self=281472874246528 avctx=0xaaaaef51eb20 ctx=0xffff6807cd80 pic=0xffff54078fc0 capture.index=6 v4l2_request_queue_buffer: pthread_self=281472874246528 ctx=0xffff6807cd80 capture.index=6 ff_v4l2_request_start_frame: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff6808c460 capture.index=5 v4l2_request_dequeue_buffer: pthread_self=281472899608960 ctx=0xffff6807cd80 capture.index=7 v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=9 v4l2_request_queue_decode: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff6808c460 capture.index=5 v4l2_request_queue_buffer: pthread_self=281472899608960 ctx=0xffff6807cd80 capture.index=5 [...] ff_v4l2_request_start_frame: pthread_self=281472882700672 avctx=0xaaaaef5243a0 ctx=0xffff6807cd80 pic=0xffff600792f0 capture.index=7 v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=9 v4l2_request_queue_decode: pthread_self=281472882700672 avctx=0xaaaaef5243a0 ctx=0xffff6807cd80 pic=0xffff600792f0 capture.index=7 v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=2 v4l2_request_queue_buffer: pthread_self=281472882700672 ctx=0xffff6807cd80 capture.index=7 ff_v4l2_request_start_frame: pthread_self=281472874246528 avctx=0xaaaaef51eb20 ctx=0xffff6807cd80 pic=0xffff540b3420 capture.index=8 v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=0 v4l2_request_queue_decode: pthread_self=281472874246528 avctx=0xaaaaef51eb20 ctx=0xffff6807cd80 pic=0xffff540b3420 capture.index=8 v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=3 v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=0 v4l2_request_queue_buffer: pthread_self=281472874246528 ctx=0xffff6807cd80 capture.index=8 ff_v4l2_request_start_frame: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff680ff480 capture.index=9 v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=7 v4l2_request_queue_decode: pthread_self=281472899608960 avctx=0xaaaaef5177c0 ctx=0xffff6807cd80 pic=0xffff680ff480 capture.index=9 v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=7 v4l2_request_queue_buffer: pthread_self=281472899608960 ctx=0xffff6807cd80 capture.index=9 v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=6 v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=8 v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=8 v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=9 v4l2_request_dequeue_buffer: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=9 v4l2_request_post_process: pthread_self=281472848884096 ctx=0xffff6807cd80 capture.index=3 ff_v4l2_request_uninit: pthread_self=281472848884096 avctx=0xaaaaef516c80 ctx=0xffff6807cd80 ```
Member

Did you actually use multiple threads?

Did you actually use multiple threads?
Author
First-time contributor

I used -threads 4 and can see 5 different pthread_self values in the log, so I am expecting 4 threads are used for hwaccel decoding and the last one is for post_process related calls.

I used `-threads 4` and can see 5 different `pthread_self` values in the log, so I am expecting 4 threads are used for hwaccel decoding and the last one is for `post_process` related calls.
Jonas Karlman force-pushed v4l2request-v3 from 73b6aee53a
All checks were successful
/ pr_labeler (pull_request_target) Successful in 20s
/ lint (pull_request) Successful in 1m2s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m40s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 12m23s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 14m53s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 21m23s
to cbda6037d9
All checks were successful
/ lint (pull_request) Successful in 1m12s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 7m22s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m40s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 10m55s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 20m44s
/ pr_labeler (pull_request_target) Has been skipped
2025-11-06 18:19:00 +00:00
Compare
@ -0,0 +342,4 @@
{
V4L2RequestContext *ctx = v4l2_request_context(avctx);
int ret;
Member

You need to check for whether the profile is supported or not around here. You don't want to start decoding 444p12 when it isn't supported for the user to get errors and a green screen.

You need to check for whether the profile is supported or not around here. You don't want to start decoding 444p12 when it isn't supported for the user to get errors and a green screen.
Author
First-time contributor

There is a test in the init code path that will confirm that a known V4L2_PIX_FMT is supported and the kernel driver may also reject a format based on information in the provided SPS header/control, e.g. bit_depth_luma_minus8 and chroma_format_idc.

The kernel driver may also indicated the hw supported codec profiles and levels and there are plans for a future PR to implement a more profile and level check, for now there are checks for frame size, pix fmt and driver internal checks that could reject the hwaccel from being used.

There is a test in the init code path that will confirm that a known V4L2_PIX_FMT is supported and the kernel driver may also reject a format based on information in the provided SPS header/control, e.g. `bit_depth_luma_minus8` and `chroma_format_idc`. The kernel driver may also indicated the hw supported codec profiles and levels and there are plans for a future PR to implement a more profile and level check, for now there are checks for frame size, pix fmt and driver internal checks that could reject the hwaccel from being used.
Member

As long as its a non-fatal AV_LOG_INFO error, okay.
You should implement support for avctx->hwaccel_flags & AV_HWACCEL_FLAG_IGNORE_LEVEL. Most files on the internet lie about their level, and that option is enabled by default.

As long as its a non-fatal AV_LOG_INFO error, okay. You should implement support for avctx->hwaccel_flags & AV_HWACCEL_FLAG_IGNORE_LEVEL. Most files on the internet lie about their level, and that option is enabled by default.
@ -0,0 +252,4 @@
.frames_get_buffer = v4l2request_get_buffer,
.transfer_get_formats = v4l2request_transfer_get_formats,
.transfer_data_from = v4l2request_transfer_data_from,
Member

Could you implement support for .transfer_data_to?
It makes debugging easier.

Could you implement support for .transfer_data_to? It makes debugging easier.
Author
First-time contributor

The v4l2 capture buffers are exported as O_RDONLY, could that have an impact on how a transfer_data_to should work?
What use cases and debugging will transfer_data_to help enable?

I have only tested transfer_data_from using hwdownload as part of using fluster where fluster will run something like following:

ffmpeg -hide_banner -nostdin -hwaccel v4l2request -hwaccel_output_format drm_prime -threads 4 -codec h264 -i resources/JVT-AVC_V1/CABAST3_Sony_E/CABAST3_Sony_E.jsv -fps_mode passthrough -filter hwdownload,format=nv12,format=pix_fmts=yuv420p -f md5 -
[h264 @ 0xaaaab76b1850] Increasing reorder buffer to 2
Input #0, h264, from 'resources/JVT-AVC_V1/CABAST3_Sony_E/CABAST3_Sony_E.jsv':
  Duration: N/A, bitrate: N/A
  Stream #0:0: Video: h264 (Main), yuv420p(progressive), 352x288, 25 fps, 1200k tbr, 1200k tbn
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> rawvideo (native))
[h264 @ 0xaaaab76f97b0] Using V4L2 media driver hantro-vpu (6.17.7) for S264
Output #0, md5, to 'pipe:':
  Metadata:
    encoder         : Lavf62.6.101
  Stream #0:0: Video: rawvideo (I420 / 0x30323449), yuv420p(progressive), 352x288, q=2-31, 30412 kb/s, 25 fps, 25 tbn
    Metadata:
      encoder         : Lavc62.19.100 rawvideo
MD5=e95f27c3779af519c1a317adb2f699a5
[out#0/md5 @ 0xaaaab77bad50] video:3712KiB audio:0KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknown
frame=   25 fps=0.0 q=-0.0 Lsize=       0KiB time=00:00:01.00 bitrate=   0.3kbits/s speed=31.6x elapsed=0:00:00.03
The v4l2 capture buffers are exported as `O_RDONLY`, could that have an impact on how a `transfer_data_to` should work? What use cases and debugging will `transfer_data_to` help enable? I have only tested `transfer_data_from` using `hwdownload` as part of using [fluster](https://github.com/fluendo/fluster/pull/179) where fluster will run something like following: ``` ffmpeg -hide_banner -nostdin -hwaccel v4l2request -hwaccel_output_format drm_prime -threads 4 -codec h264 -i resources/JVT-AVC_V1/CABAST3_Sony_E/CABAST3_Sony_E.jsv -fps_mode passthrough -filter hwdownload,format=nv12,format=pix_fmts=yuv420p -f md5 - ``` ``` [h264 @ 0xaaaab76b1850] Increasing reorder buffer to 2 Input #0, h264, from 'resources/JVT-AVC_V1/CABAST3_Sony_E/CABAST3_Sony_E.jsv': Duration: N/A, bitrate: N/A Stream #0:0: Video: h264 (Main), yuv420p(progressive), 352x288, 25 fps, 1200k tbr, 1200k tbn Stream mapping: Stream #0:0 -> #0:0 (h264 (native) -> rawvideo (native)) [h264 @ 0xaaaab76f97b0] Using V4L2 media driver hantro-vpu (6.17.7) for S264 Output #0, md5, to 'pipe:': Metadata: encoder : Lavf62.6.101 Stream #0:0: Video: rawvideo (I420 / 0x30323449), yuv420p(progressive), 352x288, q=2-31, 30412 kb/s, 25 fps, 25 tbn Metadata: encoder : Lavc62.19.100 rawvideo MD5=e95f27c3779af519c1a317adb2f699a5 [out#0/md5 @ 0xaaaab77bad50] video:3712KiB audio:0KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknown frame= 25 fps=0.0 q=-0.0 Lsize= 0KiB time=00:00:01.00 bitrate= 0.3kbits/s speed=31.6x elapsed=0:00:00.03 ```
Member

Why would the capture buffers have anything to do with this? This is strictly for the hardware frame context, it lets you use hwupload to create frames.

Why would the capture buffers have anything to do with this? This is strictly for the hardware frame context, it lets you use hwupload to create frames.
@ -0,0 +120,4 @@
av_free(map);
}
static int v4l2request_map_frame(AVHWFramesContext *hwfc,
Member

You can expose this as .map_frame in the context, couldn't you?

You can expose this as .map_frame in the context, couldn't you?
Author
First-time contributor

Sure and thanks!, I have implemented the map_from ops for read and could with help of that use hwmap instead of hwdownload with fluster to produce the same MD5 value.

ffmpeg -hide_banner -nostdin -hwaccel v4l2request -hwaccel_output_format drm_prime -threads 4 -codec h264 -i resources/JVT-AVC_V1/CABAST3_Sony_E/CABAST3_Sony_E.jsv -fps_mode passthrough -filter hwmap=mode=read,format=nv12,format=pix_fmts=yuv420p -f md5 -
[h264 @ 0xaaaae3457850] Increasing reorder buffer to 2
Input #0, h264, from 'resources/JVT-AVC_V1/CABAST3_Sony_E/CABAST3_Sony_E.jsv':
  Duration: N/A, bitrate: N/A
  Stream #0:0: Video: h264 (Main), yuv420p(progressive), 352x288, 25 fps, 1200k tbr, 1200k tbn
Stream mapping:
  Stream #0:0 -> #0:0 (h264 (native) -> rawvideo (native))
[h264 @ 0xaaaae349f7b0] Using V4L2 media driver hantro-vpu (6.17.7) for S264
Output #0, md5, to 'pipe:':
  Metadata:
    encoder         : Lavf62.6.101
  Stream #0:0: Video: rawvideo (I420 / 0x30323449), yuv420p(progressive), 352x288, q=2-31, 30412 kb/s, 25 fps, 25 tbn
    Metadata:
      encoder         : Lavc62.19.100 rawvideo
MD5=e95f27c3779af519c1a317adb2f699a5
[out#0/md5 @ 0xaaaae3560d50] video:3712KiB audio:0KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknown
frame=   25 fps=0.0 q=-0.0 Lsize=       0KiB time=00:00:01.00 bitrate=   0.3kbits/s speed=33.3x elapsed=0:00:00.03
Sure and thanks!, I have implemented the `map_from` ops for read and could with help of that use `hwmap` instead of `hwdownload` with fluster to produce the same MD5 value. ``` ffmpeg -hide_banner -nostdin -hwaccel v4l2request -hwaccel_output_format drm_prime -threads 4 -codec h264 -i resources/JVT-AVC_V1/CABAST3_Sony_E/CABAST3_Sony_E.jsv -fps_mode passthrough -filter hwmap=mode=read,format=nv12,format=pix_fmts=yuv420p -f md5 - ``` ``` [h264 @ 0xaaaae3457850] Increasing reorder buffer to 2 Input #0, h264, from 'resources/JVT-AVC_V1/CABAST3_Sony_E/CABAST3_Sony_E.jsv': Duration: N/A, bitrate: N/A Stream #0:0: Video: h264 (Main), yuv420p(progressive), 352x288, 25 fps, 1200k tbr, 1200k tbn Stream mapping: Stream #0:0 -> #0:0 (h264 (native) -> rawvideo (native)) [h264 @ 0xaaaae349f7b0] Using V4L2 media driver hantro-vpu (6.17.7) for S264 Output #0, md5, to 'pipe:': Metadata: encoder : Lavf62.6.101 Stream #0:0: Video: rawvideo (I420 / 0x30323449), yuv420p(progressive), 352x288, q=2-31, 30412 kb/s, 25 fps, 25 tbn Metadata: encoder : Lavc62.19.100 rawvideo MD5=e95f27c3779af519c1a317adb2f699a5 [out#0/md5 @ 0xaaaae3560d50] video:3712KiB audio:0KiB subtitle:0KiB other streams:0KiB global headers:0KiB muxing overhead: unknown frame= 25 fps=0.0 q=-0.0 Lsize= 0KiB time=00:00:01.00 bitrate= 0.3kbits/s speed=33.3x elapsed=0:00:00.03 ```
Lynne marked this conversation as resolved
@ -0,0 +33,4 @@
/**
* File descriptor of media device.
*
* Defaults to -1 for auto-detect.
Member

Not if the user creates the context. This header assumes its the user creating the context. Just document it as "Set to -1 for auto-detection."

Not if the user creates the context. This header assumes its the user creating the context. Just document it as "Set to -1 for auto-detection."
Author
First-time contributor

Thanks, I have changed this to Set to -1 for auto-detection.

Thanks, I have changed this to `Set to -1 for auto-detection.`
Lynne marked this conversation as resolved
@ -0,0 +503,4 @@
// TODO: estimate max buffer size instead of using a fixed value
ctx->base.post_probe = v4l2_request_h264_post_probe;
return ff_v4l2_request_init(avctx, V4L2_PIX_FMT_H264_SLICE,
4 * 1024 * 1024,
Member

Set this to width*height*2*4. Wasting a bit of memory (still peanuts) is better than decoding junk (well, it'll still probably be junk, because SoCs).

Set this to width\*height\*2\*4. Wasting a bit of memory (still peanuts) is better than decoding junk (well, it'll still probably be junk, because SoCs).
Author
First-time contributor

This size is for the output buffers that are used to pass the bitstream data to kernel. The kernel driver will decide the size needed for the capture buffers for the video frames based on width*height and any other HW requirements.

This size is for the output buffers that are used to pass the bitstream data to kernel. The kernel driver will decide the size needed for the capture buffers for the video frames based on width*height and any other HW requirements.
Member

I know that this is to pass the bitstream data to the kernel. And width*height*2*4 is about right for a worst-case scenario in H264.

I know that this is to pass the bitstream data to the kernel. And width\*height\*2*4 is about right for a worst-case scenario in H264.
First-time contributor

Just a drive by comment, we had to use a minimum to pass all the tiny resolutions videos in the VP9 tests vectors in Fluster. I believe we used 256Kb, but that's totally random. We didn't double it, though we scale it up for higher bitdepth, I guess x2 is a good simple solution.

Just a drive by comment, we had to use a minimum to pass all the tiny resolutions videos in the VP9 tests vectors in Fluster. I believe we used 256Kb, but that's totally random. We didn't double it, though we scale it up for higher bitdepth, I guess x2 is a good simple solution.
@ -0,0 +166,4 @@
if (atomic_load(&ctx->queued_output))
v4l2_request_dequeue_completed_buffers(ctx, ctx->output_type);
// Wait on the specific output buffer, when needed
Member

When needed? But the code suggests its always needed.

When needed? But the code suggests its always needed.
Author
First-time contributor

The "when needed" refers to that normally the kernel has already processed and released the output buffer and request object combo and are ready to be used again, they have most likely been returned in a prior v4l2_request_dequeue_completed_buffers() call.

However in some circumstances the kernel may not have completed decoding and are still holding on the the output buffer or request object and we need to wait for the kernel to release the buffer before proceeding.

Basically the circular queue help limit/throttle the number of pending decode requests that are in-flight at the same time, and a little bit of waiting may be needed.

The "when needed" refers to that normally the kernel has already processed and released the output buffer and request object combo and are ready to be used again, they have most likely been returned in a prior `v4l2_request_dequeue_completed_buffers()` call. However in some circumstances the kernel may not have completed decoding and are still holding on the the output buffer or request object and we need to wait for the kernel to release the buffer before proceeding. Basically the circular queue help limit/throttle the number of pending decode requests that are in-flight at the same time, and a little bit of waiting may be needed.
@ -0,0 +279,4 @@
offsets = controls->allocated_entry_point_offsets == 0 ? 128 : controls->allocated_entry_point_offsets * 2;
while (controls->num_entry_point_offsets + sh->num_entry_point_offsets > offsets)
offsets *= 2;
entry_point_offsets = av_realloc_array(entry_point_offsets, offsets, sizeof(*controls->entry_point_offsets));
Member

You're potentially calling this on every single packet, or worse, every single slice. Can't you cache this and only update the decoder's state when needed? We have a FFHWAccel.decode_params callback.

You're potentially calling this on every single packet, or worse, every single slice. Can't you cache this and only update the decoder's state when needed? We have a FFHWAccel.decode_params callback.
Author
First-time contributor

It is true that the kernel will retain the state of v4l2 control values and we only need to set v4l2 controls that has changed value for a request. For simplicity we have opted to just set all v4l2 controls as part of each request as that does not seem to affect the performance too much. However this is probably something that should be improved and optimized in a future update.

At the moment it is only the cedrus driver, a slice based decoder, that is using the V4L2_CID_STATELESS_HEVC_ENTRY_POINT_OFFSETS control and current possible extra overhead does not seem to affect decoding performance that much.

It is true that the kernel will retain the state of v4l2 control values and we only need to set v4l2 controls that has changed value for a request. For simplicity we have opted to just set all v4l2 controls as part of each request as that does not seem to affect the performance too much. However this is probably something that should be improved and optimized in a future update. At the moment it is only the `cedrus` driver, a slice based decoder, that is using the `V4L2_CID_STATELESS_HEVC_ENTRY_POINT_OFFSETS` control and current possible extra overhead does not seem to affect decoding performance that much.
@ -0,0 +127,4 @@
// Wait on the specific capture buffer, when needed
while (atomic_load(&ctx->queued_capture) & (1 << capture->index)) {
int ret = poll(&pollfd, 1, 2000);
Member

Why 2 seconds?

Why 2 seconds?
Author
First-time contributor

I do not fully remember where the 2 seconds came from, likely because the initial stateless decoding kernel drivers used something like a 1 second internal max timeout and I just doubled that to 2 seconds, and it has been like that since forever.

Please advice if a different timeout value could be more appropriate.

I do not fully remember where the 2 seconds came from, likely because the initial stateless decoding kernel drivers used something like a 1 second internal max timeout and I just doubled that to 2 seconds, and it has been like that since forever. Please advice if a different timeout value could be more appropriate.
Member

This will only be exceeded if the decoder crashed, right?

This will only be exceeded if the decoder crashed, right?
Author
First-time contributor

Correct, the timeout is only here for worst case scenarios to prevent FFmpeg lockup in case the kernel driver crashes or similar. In normal circumstances the kernel will return the decoded frame/slice or an error signal long before this timeout is exceeded.

Correct, the timeout is only here for worst case scenarios to prevent FFmpeg lockup in case the kernel driver crashes or similar. In normal circumstances the kernel will return the decoded frame/slice or an error signal long before this timeout is exceeded.
Jonas Karlman force-pushed v4l2request-v3 from cbda6037d9
All checks were successful
/ lint (pull_request) Successful in 1m12s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 7m22s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m40s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 10m55s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 20m44s
/ pr_labeler (pull_request_target) Has been skipped
to bdd832311e
All checks were successful
/ lint (pull_request) Successful in 37s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m24s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m57s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 14m47s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 21m11s
/ pr_labeler (pull_request_target) Has been skipped
2025-11-11 07:29:31 +00:00
Compare
@ -0,0 +369,4 @@
if (ret < 0)
goto fail;
}
Member

Instead of a fixed circular buffer, could you switch to using an AVBufferPool and use refcounting? You can free them in v4l2_request__free_frame_priv().

Instead of a fixed circular buffer, could you switch to using an AVBufferPool and use refcounting? You can free them in v4l2_request_<codec>_free_frame_priv().
Author
First-time contributor

The fixed circular buffer currently also works as a throttle to prevent too many request being in-flight at the same time. Use of 4 buffers/requests seem to be a good balance for current tested drivers, i.e. under normal circumstances next buffer/request was mostly ready to be re-used without having to wait for the kernel to return/release it.

The fixed circular buffer currently also works as a throttle to prevent too many request being in-flight at the same time. Use of 4 buffers/requests seem to be a good balance for current tested drivers, i.e. under normal circumstances next buffer/request was mostly ready to be re-used without having to wait for the kernel to return/release it.
@ -0,0 +216,4 @@
AVFrame *map;
int ret;
if (dst->width > hwfc->width || dst->height > hwfc->height)
First-time contributor

Shouldn't be the other way around? Better yet, just remove it as av_frame_copy() does same check anyway.

Shouldn't be the other way around? Better yet, just remove it as av_frame_copy() does same check anyway.
Author
First-time contributor

That does seem more logical, however this matches what drm, vaapi and videotoolbox is currently doing. Not sure what to do here.

That does seem more logical, however this matches what `drm`, `vaapi` and `videotoolbox` is currently doing. Not sure what to do here.
@ -0,0 +35,4 @@
enum AVPixelFormat sw_format;
uint32_t drm_format;
uint64_t format_modifier;
} v4l2_request_capture_pixelformats[] = {
First-time contributor

Shouldn't this be somewhere in common functions like libavutil? As I plan to write V4L2 deinterlace filter, I plan to use same HW context, which will need same format conversion functions.

Shouldn't this be somewhere in common functions like libavutil? As I plan to write V4L2 deinterlace filter, I plan to use same HW context, which will need same format conversion functions.
Member

Just copy them. You can also do what Vulkan does by having libavutil/vulkan.c, and directly include the libavutil/vulkan.c to generate the same object file in other libraries, but really, only the Vulkan code needs that as its 3000+ lines of utilities.
Public or avpriv code is NG.

Just copy them. You can also do what Vulkan does by having libavutil/vulkan.c, and directly include the libavutil/vulkan.c to generate the same object file in other libraries, but really, only the Vulkan code needs that as its 3000+ lines of utilities. Public or avpriv code is NG.
Member

@Kwiboo wrote in #20847 (comment):

Compared to v2 this only includes support for V4L2_PIX_FMTs that has been merged into mainline Linux. As a result, this version cannot be tested with the downstream rpivid driver on Raspberry Pi or using AFBC buffers on Allwinner.

HOW TO USE

To use the V4L2 Request API hwaccels you must build FFmpeg on a system with recent Linux kernel headers, v6.0+. It also requires libdrm and libudev for the hwaccels to be enabled and successfully built.

I have rpi5, orange pi 3b with rk3566, and VisionFive 2(I remember this one use m2m mode). Are there any known prebuilt image which can be used to test the patchset?

@Kwiboo wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issue-1401: > Compared to v2 this only includes support for `V4L2_PIX_FMT`s that has been merged into mainline Linux. As a result, this version cannot be tested with the downstream `rpivid` driver on Raspberry Pi or using AFBC buffers on Allwinner. > > **HOW TO USE** > > To use the V4L2 Request API hwaccels you must build FFmpeg on a system with recent Linux kernel headers, `v6.0+`. It also requires `libdrm` and `libudev` for the hwaccels to be enabled and successfully built. I have rpi5, orange pi 3b with rk3566, and VisionFive 2(I remember this one use m2m mode). Are there any known prebuilt image which can be used to test the patchset?
First-time contributor

@quink https://chewitt.libreelec.tv/testing/LibreELEC-RK356X.aarch64-12.90.1-rock-3c.img.gz

The image is built using https://code.ffmpeg.org/Kwiboo/FFmpeg/commits/branch/v4l2request-2025-v3-rkvdec which contains the patches from this PR (in their initial state) plus patches @Kwiboo refers to as future follow-up series. If you need to validate the current state (with fixups/corrections) I can look into respinning the image with only the PR patches tomorrow.

@quink https://chewitt.libreelec.tv/testing/LibreELEC-RK356X.aarch64-12.90.1-rock-3c.img.gz The image is built using https://code.ffmpeg.org/Kwiboo/FFmpeg/commits/branch/v4l2request-2025-v3-rkvdec which contains the patches from this PR (in their initial state) plus patches @Kwiboo refers to as future follow-up series. If you need to validate the current state (with fixups/corrections) I can look into respinning the image with only the PR patches tomorrow.
Member

On rockchip, does this code require the rockchip mpp code which has copy and pasted code from FFmpeg (claimed to be apache2):
https://github.com/rockchip-linux/mpp/blob/develop/mpp/codec/dec/av1/av1d_cbs.c

If so, I don't think we should accept it until rockchip fix their code

On rockchip, does this code require the rockchip mpp code which has copy and pasted code from FFmpeg (claimed to be apache2): https://github.com/rockchip-linux/mpp/blob/develop/mpp/codec/dec/av1/av1d_cbs.c If so, I don't think we should accept it until rockchip fix their code
Author
First-time contributor

@kierank wrote in #20847 (comment):

On rockchip, does this code require the rockchip mpp code which has copy and pasted code from FFmpeg (claimed to be apache2): https://github.com/rockchip-linux/mpp/blob/develop/mpp/codec/dec/av1/av1d_cbs.c

If so, I don't think we should accept it until rockchip fix their code

This is a hwaccel interacting with the Linux kernel Memory-to-memory Stateless Video Decoder Interface and has no relation or dependency on any vendor userspace libraries.

The initial v4l2-request hwaccel code was mainly created as a proof of concept at the end of 2018 by me and Jernej Skrabec.
Back when Bootlin's crowdfunding campaign for upstream Linux kernel driver for Allwinner VPU had started to bear fruit.

See August 2024 (v2) for a continued summary of the history behind this PR.

@kierank wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issuecomment-15052: > On rockchip, does this code require the rockchip mpp code which has copy and pasted code from FFmpeg (claimed to be apache2): https://github.com/rockchip-linux/mpp/blob/develop/mpp/codec/dec/av1/av1d_cbs.c > > If so, I don't think we should accept it until rockchip fix their code This is a hwaccel interacting with the Linux kernel [Memory-to-memory Stateless Video Decoder Interface](https://docs.kernel.org/userspace-api/media/v4l/dev-stateless-decoder.html) and has no relation or dependency on any vendor userspace libraries. > The initial v4l2-request hwaccel code was mainly created as a proof of concept at the end of 2018 by me and Jernej Skrabec. > Back when Bootlin's crowdfunding campaign for upstream Linux kernel driver for Allwinner VPU had started to bear fruit. See [August 2024 (v2)](https://lists.ffmpeg.org/pipermail/ffmpeg-devel/2024-August/332034.html) for a continued summary of the history behind this PR.
@ -0,0 +137,4 @@
av_assert0(desc->nb_objects <= AV_DRM_MAX_PLANES);
for (i = 0; i < desc->nb_objects; i++) {
addr = mmap(NULL, desc->objects[i].size, AV_HWFRAME_MAP_READ, MAP_SHARED,
First-time contributor

I guess that should be PROT_READ instead of AV_HWFRAME_MAP_READ (values match, but we should use mmap's own flags here)

I guess that should be `PROT_READ` instead of `AV_HWFRAME_MAP_READ` (values match, but we should use mmap's own flags here)
Author
First-time contributor

Thanks!, this has now been fixed.

Thanks!, this has now been fixed.
Kwiboo marked this conversation as resolved
Jonas Karlman force-pushed v4l2request-v3 from bdd832311e
All checks were successful
/ lint (pull_request) Successful in 37s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m24s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m57s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 14m47s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 21m11s
/ pr_labeler (pull_request_target) Has been skipped
to 512c1b22d1
All checks were successful
/ pr_labeler (pull_request_target) Successful in 10s
/ lint (pull_request) Successful in 22s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m41s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m49s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 15m4s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 23m37s
2025-11-17 19:43:20 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 512c1b22d1
All checks were successful
/ pr_labeler (pull_request_target) Successful in 10s
/ lint (pull_request) Successful in 22s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m41s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m49s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 15m4s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 23m37s
to 02a6f48951
All checks were successful
/ pr_labeler (pull_request_target) Successful in 10s
/ lint (pull_request) Successful in 27s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 7m30s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m4s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 11m21s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 11m59s
2025-11-18 22:47:46 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 02a6f48951
All checks were successful
/ pr_labeler (pull_request_target) Successful in 10s
/ lint (pull_request) Successful in 27s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 7m30s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m4s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 11m21s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 11m59s
to 32dc05a593
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 26s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m45s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m42s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 14m41s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 23m6s
2025-11-20 17:32:29 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 32dc05a593
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 26s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m45s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m42s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 14m41s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 23m6s
to d31e6c3707
All checks were successful
/ pr_labeler (pull_request_target) Successful in 8s
/ lint (pull_request) Successful in 41s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m32s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m45s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 15m32s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 22m4s
2025-11-22 20:51:28 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from d31e6c3707
All checks were successful
/ pr_labeler (pull_request_target) Successful in 8s
/ lint (pull_request) Successful in 41s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m32s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m45s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 15m32s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 22m4s
to b3355891cd
All checks were successful
/ lint (pull_request) Successful in 45s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m30s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m55s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 16m10s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 21m26s
/ pr_labeler (pull_request_target) Has been skipped
2025-11-22 23:58:29 +00:00
Compare
@ -61,6 +61,7 @@ libavcodec/.*siren.* @lynne
libavcodec/smpte_436m.* @programmerjake
libavcodec/svq1.* @pross
libavcodec/svq3.* @pross
libavcodec/v4l2_request.* @Kwiboo
Author
First-time contributor

@jernej @knaerzche should I also add your usernames to the CODEOWNERS file?

@jernej @knaerzche should I also add your usernames to the `CODEOWNERS` file?
First-time contributor

sure, I can help with maintaining

sure, I can help with maintaining
First-time contributor

sure

sure
Author
First-time contributor

I have now added you both to the CODEOWNERS file, should hopefully mean we all get review pings when files are touched in future PRs.

I have now added you both to the `CODEOWNERS` file, should hopefully mean we all get review pings when files are touched in future PRs.
Kwiboo marked this conversation as resolved
@ -0,0 +205,4 @@
avctx->coded_width >= frmsize.stepwise.min_width &&
avctx->coded_height >= frmsize.stepwise.min_height &&
avctx->coded_width <= frmsize.stepwise.max_width &&
avctx->coded_height <= frmsize.stepwise.max_height) {
Author
First-time contributor

@knaerzche @jernej I have changed this to now only check min/max instead of the strict step_width/height check.

The provided coded_width/height is from the application and cannot fully be trusted, e.g. Kodi supply the width/height hint from the demuxer, not the coded_width/height for the codec.

@knaerzche @jernej I have changed this to now only check min/max instead of the strict `step_width/height` check. The provided `coded_width/height` is from the application and cannot fully be trusted, e.g. Kodi supply the width/height hint from the demuxer, not the coded_width/height for the codec.
Member

The provided coded_width/height is from the application and cannot fully be trusted, e.g. Kodi supply the width/height hint from the demuxer, not the coded_width/height for the codec.

What? They are trustworthy, they're set by parsers and decoders. All hwaccels use them.

> The provided coded_width/height is from the application and cannot fully be trusted, e.g. Kodi supply the width/height hint from the demuxer, not the coded_width/height for the codec. What? They are trustworthy, they're set by parsers and decoders. All hwaccels use them.
Author
First-time contributor

What? They are trustworthy, they're set by parsers and decoders. All hwaccels use them.

It most likely can be trusted, however we cannot fully trust the values reported from the drivers as they tend to report internal hw buffer requirements.

E.g. for hantro on a Rockchip RK3588 board the driver report min=48x48 max=3840x2160 step=16x16, and for a test video:

[vp8 @ 0xaaab03860000] parse: parse coded_size: 176x144
[vp8 @ 0xaaab0386de80] try_framesize: avctx coded_size: 175x143 type=2 min=48x48 max=3840x2160 step=16x16
[vp8 @ 0xaaab0386de80] Using V4L2 media driver hantro-vpu (6.18.0) for VP8F

Here we cannot have a strict step_width/height check, the AVCodecParserContext seem to report 16 aligned coded size (176x144) however not the coded size (175x143) from the AVCodecContext that reaches v4l2_request_try_framesize.

Changing to only check min/max seem to closer match what other hwaccels do and will allow use of drivers that possible report internal hw requirements to userspace.

> What? They are trustworthy, they're set by parsers and decoders. All hwaccels use them. It most likely can be trusted, however we cannot fully trust the values reported from the drivers as they tend to report internal hw buffer requirements. E.g. for `hantro` on a Rockchip RK3588 board the driver report min=48x48 max=3840x2160 step=16x16, and for a test video: ``` [vp8 @ 0xaaab03860000] parse: parse coded_size: 176x144 [vp8 @ 0xaaab0386de80] try_framesize: avctx coded_size: 175x143 type=2 min=48x48 max=3840x2160 step=16x16 [vp8 @ 0xaaab0386de80] Using V4L2 media driver hantro-vpu (6.18.0) for VP8F ``` Here we cannot have a strict `step_width/height` check, the `AVCodecParserContext` seem to report 16 aligned coded size (176x144) however not the coded size (175x143) from the `AVCodecContext` that reaches `v4l2_request_try_framesize`. Changing to only check min/max seem to closer match what other hwaccels do and will allow use of drivers that possible report internal hw requirements to userspace.
Member

Oh, yes, alignment is always flaky. I've spoken with vendors/driver authors and no one really has a clue. My point is that coded_width/height are reliable.

Oh, yes, alignment is always flaky. I've spoken with vendors/driver authors and no one really has a clue. My point is that coded_width/height are reliable.
First-time contributor

@Kwiboo wrote in #20847 (comment):

@knaerzche @jernej I have changed this to now only check min/max instead of the strict step_width/height check.

The provided coded_width/height is from the application and cannot fully be trusted, e.g. Kodi supply the width/height hint from the demuxer, not the coded_width/height for the codec.

Yeah sure, it's most likely that min/max framesize check is sufficient at this point. But actually we are working around driver bugs and hopefully there will never be a driver which really needs buffers/frames with a particular alignment (which is unlikely I admit)

The provided coded_width/height is from the application and cannot fully be trusted, e.g. Kodi supply the width/height hint from the demuxer, not the coded_width/height for the codec.

If that is true, does that mean we can never get away from the currently hardcoded size for the output (bitstream) buffers and let it depend on width/height?

@Kwiboo wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issuecomment-16216: > @knaerzche @jernej I have changed this to now only check min/max instead of the strict `step_width/height` check. > > The provided `coded_width/height` is from the application and cannot fully be trusted, e.g. Kodi supply the width/height hint from the demuxer, not the coded_width/height for the codec. Yeah sure, it's most likely that min/max framesize check is sufficient at this point. But actually we are working around driver bugs and hopefully there will never be a driver which really needs buffers/frames with a particular alignment (which is unlikely I admit) > The provided coded_width/height is from the application and cannot fully be trusted, e.g. Kodi supply the width/height hint from the demuxer, not the coded_width/height for the codec. If that is true, does that mean we can never get away from the currently hardcoded size for the output (bitstream) buffers and let it depend on width/height?
Author
First-time contributor

But actually we are working around driver bugs and hopefully there will never be a driver which really needs buffers/frames with a particular alignment (which is unlikely I admit)

I fully agree, and why I sent the patch media: rkvdec: Fix frame size enumeration based on your suggestion.

When I now was trying to do something similar for hantro and re-read the Linux documentation it is still ambiguous to me as to what the driver should provide. And if I am not mistaken the cedrus driver do not even implement the enum ops.

If that is true, does that mean we can never get away from the currently hardcoded size for the output (bitstream) buffers and let it depend on width/height?

As @Lynne pointed out the coded_width/height is more reliable than I initially thought, especially after the decoder has started parsing headers, so please disregard my comment related to this.

> But actually we are working around driver bugs and hopefully there will never be a driver which really needs buffers/frames with a particular alignment (which is unlikely I admit) I fully agree, and why I sent the patch [media: rkvdec: Fix frame size enumeration](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=f270005b99fa19fee9a6b4006e8dee37c10f1944) based on your suggestion. When I now was trying to do something similar for `hantro` and re-read the Linux documentation it is still ambiguous to me as to what the driver should provide. And if I am not mistaken the `cedrus` driver do not even implement the enum ops. > If that is true, does that mean we can never get away from the currently hardcoded size for the output (bitstream) buffers and let it depend on width/height? As @Lynne pointed out the `coded_width/height` is more reliable than I initially thought, especially after the decoder has started parsing headers, so please disregard my comment related to this.
@ -0,0 +297,4 @@
hwfc->initial_pool_size += 3;
break;
default:
hwfc->initial_pool_size += 2;
Contributor

If these are supposed to be adjusting for max DPB size, shouldn't we be using 16 for H.264/HEVC?

If these are supposed to be adjusting for max DPB size, shouldn't we be using 16 for H.264/HEVC?
Author
First-time contributor

This adjust the number of buffers that are pre-allocated during init, the hwaccel is capable of allocating more buffers when needed.

Based on real world testing in LibreELEC it does not seem we need to pre-allocated all 16 possible DPB buffers for H.264/HEVC, especially when some videos only use some of them.
Also the H.264 decoder re-init the hwaccel at each seek so that would mean that we may need 32+ pre-allocated buffers during seek, and that can take up a lot of system memory for 4K+ videos on embedded devices with limited amount of memory.

The pre-allocation for VP8 and VP9 could most likely be reduced, but this is how it has worked in LibreELEC for a long time.

This adjust the number of buffers that are pre-allocated during init, the hwaccel is capable of allocating more buffers when needed. Based on real world testing in LibreELEC it does not seem we need to pre-allocated all 16 possible DPB buffers for H.264/HEVC, especially when some videos only use some of them. Also the H.264 decoder re-init the hwaccel at each seek so that would mean that we may need 32+ pre-allocated buffers during seek, and that can take up a lot of system memory for 4K+ videos on embedded devices with limited amount of memory. The pre-allocation for VP8 and VP9 could most likely be reduced, but this is how it has worked in LibreELEC for a long time.
Member

Based on real world testing in LibreELEC

The pre-allocation for VP8 and VP9 could most likely be reduced, but this is how it has worked in LibreELEC for a long time.

I don't like this phrasing or how libreelec is the singular thing to compare and test with. Although it has been the primary user of this code, upstreaming it means it's open for everyone to use. mpv, vlc, and others too. I strongly suggest testing with mpv as well.

Regarding initial allocation, my suggestion is, if you don't need to allocate fixed arrays, don't. That way you minimize memory usage and just let the pools handle it.

> Based on real world testing in LibreELEC > The pre-allocation for VP8 and VP9 could most likely be reduced, but this is how it has worked in LibreELEC for a long time. I don't like this phrasing or how libreelec is the singular thing to compare and test with. Although it has been the primary user of this code, upstreaming it means it's open for everyone to use. mpv, vlc, and others too. I strongly suggest testing with mpv as well. Regarding initial allocation, my suggestion is, if you don't need to allocate fixed arrays, don't. That way you minimize memory usage and just let the pools handle it.
Author
First-time contributor

I don't like this phrasing or how libreelec is the singular thing to compare and test with.

I am sorry you read my comment in such way, that was not my intention, I was only trying to report what I have observed have worked in the past based on use with Kodi/LibreELEC.

Although it has been the primary user of this code, upstreaming it means it's open for everyone to use. mpv, vlc, and others too. I strongly suggest testing with mpv as well.

I always do basic runtime tests with mpv, and to my knowledge other ARM/SBC centric distros such as e.g. Armbian also uses this code, for their use I think browser and mpv integration have been the main use-case.

Regarding initial allocation, my suggestion is, if you don't need to allocate fixed arrays, don't. That way you minimize memory usage and just let the pools handle it.

I fully agree, this pre-allocation was initially just a c/p from VAAPI, and due to users reporting seek issues or issues opening a new video while playback was paused for H.264/HEVC on devices with limited memory / CMA pool we removed the 16 buffer pre-allocation for those codecs. For VP8/VP9 we had no such reports and because of this the initial_pool_size still matches VAAPI.

We most likely want to pre-allocate a few buffers to ensure we have enough memory to decode beyond 1-2 frames, will run some tests and tune the initial_pool_size used here.

> I don't like this phrasing or how libreelec is the singular thing to compare and test with. I am sorry you read my comment in such way, that was not my intention, I was only trying to report what I have observed have worked in the past based on use with Kodi/LibreELEC. > Although it has been the primary user of this code, upstreaming it means it's open for everyone to use. mpv, vlc, and others too. I strongly suggest testing with mpv as well. I always do basic runtime tests with mpv, and to my knowledge other ARM/SBC centric distros such as e.g. Armbian also uses this code, for their use I think browser and mpv integration have been the main use-case. > Regarding initial allocation, my suggestion is, if you don't need to allocate fixed arrays, don't. That way you minimize memory usage and just let the pools handle it. I fully agree, this pre-allocation was initially just a c/p from VAAPI, and due to users reporting seek issues or issues opening a new video while playback was paused for H.264/HEVC on devices with limited memory / CMA pool we removed the 16 buffer pre-allocation for those codecs. For VP8/VP9 we had no such reports and because of this the `initial_pool_size` still matches VAAPI. We most likely want to pre-allocate a few buffers to ensure we have enough memory to decode beyond 1-2 frames, will run some tests and tune the `initial_pool_size` used here.
Author
First-time contributor

I have now changed this to only use initial_pool_size = 1, without pre-allocating at least one capture buffer the capture queue cannot be started during init.

I have now changed this to only use `initial_pool_size = 1`, without pre-allocating at least one capture buffer the capture queue cannot be started during `init`.
@ -0,0 +422,4 @@
ctx->media_fd = -1;
ctx->video_fd = -1;
// Try to use media device file descriptor opened and owned by hwdevice
Member

Try to use? If it's not usable, you should error out.

Try to use? If it's not usable, you should error out.
Author
First-time contributor

The general idea is that when we supply a specific media device using the hwcontext we limit hwaccel to probe for a capable video device in the topology of that specific media device, otherwise we try all media devices and the video devices in their topology.

The general idea is that when we supply a specific media device using the hwcontext we limit hwaccel to probe for a capable video device in the topology of that specific media device, otherwise we try all media devices and the video devices in their topology.
@ -0,0 +441,4 @@
// Transfer (or return) ownership of media device file descriptor to hwdevice
if (hwctx) {
hwctx->media_fd = ctx->media_fd;
Member

That's incorrect, hwctx is immutable after initialization by lavu. Decoders are also able to be initialized asynchronously, so that's a race condition as well.

That's incorrect, hwctx is immutable after initialization by lavu. Decoders are also able to be initialized asynchronously, so that's a race condition as well.
Author
First-time contributor

Good to know, thanks, the idea was to update the AVV4L2RequestDeviceContext with the probed media controller device that contains a video device capable of decoding current video. So that in case the hwaccel was re-initialized the probing would be faster as only one media device topology is probed for a capable video device.

Any suggestions on how something like that could be handled if we cannot modify a AVV4L2RequestDeviceContext using media_fd = -1 (auto-detection)?

Good to know, thanks, the idea was to update the `AVV4L2RequestDeviceContext` with the probed media controller device that contains a video device capable of decoding current video. So that in case the hwaccel was re-initialized the probing would be faster as only one media device topology is probed for a capable video device. Any suggestions on how something like that could be handled if we cannot modify a `AVV4L2RequestDeviceContext` using `media_fd = -1` (auto-detection)?
Author
First-time contributor

I have now dropped this hwctx->media_fd assignment.

Use of media_fd = -1 (auto-detection) will probe all media and video device combos until a capable media+video combo is found, and use of a valid media device FD (media_fd >= 0) only video devices part of the media controller topology is probed.

I have now dropped this `hwctx->media_fd` assignment. Use of `media_fd = -1` (auto-detection) will probe all media and video device combos until a capable media+video combo is found, and use of a valid media device FD (`media_fd >= 0`) only video devices part of the media controller topology is probed.
Member

I don't think I can agree to the decoder determining what device to use by itself. Our hwaccel infra operates on the principle that it's the user's responsibility to set the device, as they may have particular requirements what to do with the image later (scanout, process, etc.), which would not work if the image is on some inaccessible location.

I don't think I can agree to the decoder determining what device to use by itself. Our hwaccel infra operates on the principle that it's the user's responsibility to set the device, as they may have particular requirements what to do with the image later (scanout, process, etc.), which would not work if the image is on some inaccessible location.
Author
First-time contributor

I don't think I can agree to the decoder determining what device to use by itself.

Please elaborate on how things can be done differently, I have very limited knowledge into ffmpeg internals and can mostly only see things from a application and kernel developer perspective.

From my application developer perspective we may have a chicken and egg problem, unless there is some other ffmpeg api that could be used to determine what v4l2 media and video device combo can/should be be used for decoding.

To fully be able to locate a capable media+video device combo an application/user may need to supply codec specific details i.e. a v4l2 control containing h264/hevc sps or similar codec header data, and parsing video bitstream is something the application typically do not want to do and rather offload to ffmpeg libs.

> I don't think I can agree to the decoder determining what device to use by itself. Please elaborate on how things can be done differently, I have very limited knowledge into ffmpeg internals and can mostly only see things from a application and kernel developer perspective. From my application developer perspective we may have a _chicken and egg problem_, unless there is some other ffmpeg api that could be used to determine what v4l2 media and video device combo can/should be be used for decoding. To fully be able to locate a capable media+video device combo an application/user may need to supply codec specific details i.e. a v4l2 control containing h264/hevc sps or similar codec header data, and parsing video bitstream is something the application typically do not want to do and rather offload to ffmpeg libs.
@ -0,0 +476,4 @@
return ret;
}
// Probe video devices of current media device
Member

Are video devices the equivalent of queue families in Vulkan? If so, you should initialize them all during hwcontext init and expose them from lavu, along with a similar queue locking mechanism from Vulkan.

Are video devices the equivalent of queue families in Vulkan? If so, you should initialize them all during hwcontext init and expose them from lavu, along with a similar queue locking mechanism from Vulkan.
Author
First-time contributor

Not to my knowledge based on what I could very quickly read about queue families in Vulkan.

To use the V4L2 Request API we must interact with both a media controller device node and a video device node part of the media controller topology.

The video device expose the kernel decoder driver and represent the underlying vpu ip block, we interact with this device node to e.g. query about supported formats, allocate buffers, queue/dequeue buffers and set codec specific controls. The video device does not really know anything about a media controller device.

The media controller device is where we interact with requests, e.g. we associate an output buffer and codec specific controls with a request object from the media device, and when we submit the request object for processing the media controller driver infrastructure will ensure all controls and the output buffer associated with the request is configured for the video device before it starts it run ops.

See Linux kernel documentation Part IV - Media Controller API and 4. Request API for some more details on the Request API.

There should not be any need for locking or similar from the userspace perspective, any locking would be handled by the driver in kernel.

Typically there is a 1:1 media -> video device relationship for current known drivers, however the infrastructure in kernel support 1:n media -> multiple video devices so that is what this code has been prepared for.

When we have a media controller device we try to find the first video device that is a part of the media controller topology that report it support current codec and resolution.

Without first knowing the codec and what video device will be capable of decoding the input I do not think we can open the video device in lavu, please correct me if I am wrong and possible point to some code that could inspire such use case.

Not to my knowledge based on what I could very quickly read about queue families in Vulkan. To use the V4L2 Request API we must interact with both a media controller device node and a video device node part of the media controller topology. The video device expose the kernel decoder driver and represent the underlying vpu ip block, we interact with this device node to e.g. query about supported formats, allocate buffers, queue/dequeue buffers and set codec specific controls. The video device does not really know anything about a media controller device. The media controller device is where we interact with requests, e.g. we associate an output buffer and codec specific controls with a request object from the media device, and when we submit the request object for processing the media controller driver infrastructure will ensure all controls and the output buffer associated with the request is configured for the video device before it starts it `run` ops. See Linux kernel documentation [Part IV - Media Controller API](https://www.kernel.org/doc/html/latest/userspace-api/media/mediactl/media-controller.html) and [4. Request API](https://www.kernel.org/doc/html/latest/userspace-api/media/mediactl/request-api.html) for some more details on the Request API. There should not be any need for locking or similar from the userspace perspective, any locking would be handled by the driver in kernel. Typically there is a 1:1 media -> video device relationship for current known drivers, however the infrastructure in kernel support 1:n media -> multiple video devices so that is what this code has been prepared for. When we have a media controller device we try to find the first video device that is a part of the media controller topology that report it support current codec and resolution. Without first knowing the codec and what video device will be capable of decoding the input I do not think we can open the video device in lavu, please correct me if I am wrong and possible point to some code that could inspire such use case.
Member

Can't you open FDs to all video devices in the context?

Can't you open FDs to all video devices in the context?
Author
First-time contributor

I am not sure that is a good idea, we also do not always know what media device will be used when using audo-detection, so may not be optimal to try and open all possible FDs?

Main reason that I know of to supply a media device would be to be explicit about what decoder ip block to use when there are multiple different decoder blocks available in a device/soc.

E.g. on a few rockchip soc there is typically a hantro ip block intended for jpeg decoding/encoding and a different rkvdec ip block intended for h264/hevc/vp9 decoding. However the hantro ip block is also capable of mpeg2, vp8 and h262 up to 1080p 60fps.
For such soc it may be good to specify what media device to use for h264 decoding when fps is important.

I am not sure that is a good idea, we also do not always know what media device will be used when using audo-detection, so may not be optimal to try and open all possible FDs? Main reason that I know of to supply a media device would be to be explicit about what decoder ip block to use when there are multiple different decoder blocks available in a device/soc. E.g. on a few rockchip soc there is typically a `hantro` ip block intended for jpeg decoding/encoding and a different `rkvdec` ip block intended for h264/hevc/vp9 decoding. However the `hantro` ip block is also capable of mpeg2, vp8 and h262 up to 1080p 60fps. For such soc it may be good to specify what media device to use for h264 decoding when fps is important.
Member

But you do know what media device to use. That's why you have the media FD.
I don't agree that autodetecting which device to use during decoding is a good idea, and it's the opposite of being explicit.

But you *do* know what media device to use. That's why you have the media FD. I don't agree that autodetecting which device to use during decoding is a good idea, and it's the opposite of being explicit.
Author
First-time contributor

But you do know what media device to use. That's why you have the media FD.

Applications will typically not know what media device to use, unless they also implement similar probing and format testing of media and video devices.

I don't agree that autodetecting which device to use during decoding is a good idea, and it's the opposite of being explicit.

When a caller wants to be explicit they can provide a path to a media device, else no path can be provided and all media+video device combos are probed looking for a capable device.

> But you _do_ know what media device to use. That's why you have the media FD. Applications will typically not know what media device to use, unless they also implement similar probing and format testing of media and video devices. > I don't agree that autodetecting which device to use during decoding is a good idea, and it's the opposite of being explicit. When a caller wants to be explicit they can provide a path to a media device, else no path can be provided and all media+video device combos are probed looking for a capable device.
Member

When a caller wants to be explicit they can provide a path to a media device, else no path can be provided and all media+video device combos are probed looking for a capable device.

None of our hwaccels do automatic initialization, and I don't see why this should be the case - the v4l2 hwcontext could expose all available decoder devices for a specific block, and decoders can just pick one that's supported by the codec.
If there are no incompatibilities between usage of frames associated with a different block, then I would not mind if the hwcontext just exposes all blocks and all decoder devices within them (by default, unless the user limits this), and lets decoders pick one. But hwaccels themselves probing for devices and opening them is NG.

> When a caller wants to be explicit they can provide a path to a media device, else no path can be provided and all media+video device combos are probed looking for a capable device. None of our hwaccels do automatic initialization, and I don't see why this should be the case - the v4l2 hwcontext could expose all available decoder devices for a specific block, and decoders can just pick one that's supported by the codec. If there are no incompatibilities between usage of frames associated with a different block, then I would not mind if the hwcontext just exposes all blocks and all decoder devices within them (by default, unless the user limits this), and lets decoders pick one. But hwaccels themselves probing for devices and opening them is NG.
First-time contributor

I think doing a single enumeration of available devices is wanted indeed. The recommended way for the stateless decoders is:

  1. enumerate the media devices (optimized with udev if possible).
  2. identify decoder from the tology (single video dev used as src and sink, with function MEDIA_ENT_F_PROC_VIDEO_DECODER in the middle)
  3. enumerate internal capabilities (formats it can decode, size, profile, level, whatever matter for you application)

While you can have a single media FD around from start to end of program, you must open a new video device FD per-stream. So I'd remember the path in the probed data. Enumerating video devices is just a bad idea, with the way ISP are done, we see a lot of devices with more then 100 of these, yet, its the only way to enumerate stateful decoders ....

I think doing a single enumeration of available devices is wanted indeed. The recommended way for the stateless decoders is: 1. enumerate the media devices (optimized with udev if possible). 2. identify decoder from the tology (single video dev used as src and sink, with function MEDIA_ENT_F_PROC_VIDEO_DECODER in the middle) 3. enumerate internal capabilities (formats it can decode, size, profile, level, whatever matter for you application) While you can have a single media FD around from start to end of program, you must open a new video device FD per-stream. So I'd remember the path in the probed data. Enumerating video devices is just a bad idea, with the way ISP are done, we see a lot of devices with more then 100 of these, yet, its the only way to enumerate stateful decoders ....
Member

I'm not entirely sure what you meant by this.
You can check whether a device supports the given profile inside the decoder, and dup the fd.

I'm not entirely sure what you meant by this. You can check whether a device supports the given profile inside the decoder, and dup the fd.
First-time contributor

I guess doing a dup may work, I never considered that since the original FD is a waste of a HW context. Why would I waste FDs ?

I guess doing a dup may work, I never considered that since the original FD is a waste of a HW context. Why would I waste FDs ?
First-time contributor

I've ask the maintainers, and the dup will point to the same m2m context. Only the "open()" call can create new context. This has to happen per stream.

I've ask the maintainers, and the dup will point to the same m2m context. Only the "open()" call can create new context. This has to happen per stream.
Author
First-time contributor

@Lynne wrote in #20847 (comment):

If there are no incompatibilities between usage of frames associated with a different block, then I would not mind if the hwcontext just exposes all blocks and all decoder devices within them (by default, unless the user limits this), and lets decoders pick one. But hwaccels themselves probing for devices and opening them is NG.

I have refactored and moved code around so that all media and video device probing is happening in lavu, and no longer in lavc.

This should now behave similar to e.g. DXAV2 where a video service is located from a device manager during frames context init.
Main difference is that there is no external lib and instead lavu is acting as the device manager.

A few other notable changes:

  • The media and video device file descriptor are now opened and owned by the frames context.
  • CAPTURE and OUTPUT buffers are now allocated from buffer pools owned by the frames context.
  • The frame buffer allocation and assigning of AVDRAMFrameDescriptor has moved to the hwcontext.

The device probing code has mostly just been moved around and is something I would like to refactor after a confirmation that this would be an acceptable direction.

Please take a new look at this and let me know if this is more in line what is expected from a hwaccel and hwcontext.

@Lynne wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issuecomment-16527: > If there are no incompatibilities between usage of frames associated with a different block, then I would not mind if the hwcontext just exposes all blocks and all decoder devices within them (by default, unless the user limits this), and lets decoders pick one. But hwaccels themselves probing for devices and opening them is NG. I have refactored and moved code around so that all media and video device probing is happening in lavu, and no longer in lavc. This should now behave similar to e.g. DXAV2 where a video service is located from a device manager during frames context init. Main difference is that there is no external lib and instead lavu is acting as the device manager. A few other notable changes: - The media and video device file descriptor are now opened and owned by the frames context. - CAPTURE and OUTPUT buffers are now allocated from buffer pools owned by the frames context. - The frame buffer allocation and assigning of AVDRAMFrameDescriptor has moved to the hwcontext. The device probing code has mostly just been moved around and is something I would like to refactor after a confirmation that this would be an acceptable direction. Please take a new look at this and let me know if this is more in line what is expected from a hwaccel and hwcontext.
Jonas Karlman force-pushed v4l2request-v3 from b3355891cd
All checks were successful
/ lint (pull_request) Successful in 45s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m30s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m55s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 16m10s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 21m26s
/ pr_labeler (pull_request_target) Has been skipped
to 13b83cc55f
All checks were successful
/ lint (pull_request) Successful in 44s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m47s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m56s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 15m28s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 23m2s
/ pr_labeler (pull_request_target) Has been skipped
2025-11-25 10:53:01 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 13b83cc55f
All checks were successful
/ lint (pull_request) Successful in 44s
/ run_fate (64, linux-aarch64, false) (pull_request) Successful in 11m47s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m56s
/ run_fate (32, linux-amd64, false) (pull_request) Successful in 15m28s
/ run_fate (64, linux-amd64, true) (pull_request) Successful in 23m2s
/ pr_labeler (pull_request_target) Has been skipped
to da1d1bd0c7
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 28s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m19s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m13s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 16m47s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 22m22s
2025-12-04 23:19:37 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from da1d1bd0c7
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 28s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m19s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m13s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 16m47s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 22m22s
to 5225fa694a
All checks were successful
/ pr_labeler (pull_request_target) Successful in 8s
/ lint (pull_request) Successful in 25s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m25s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m2s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 15m48s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 20m44s
2025-12-08 09:18:15 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 5225fa694a
All checks were successful
/ pr_labeler (pull_request_target) Successful in 8s
/ lint (pull_request) Successful in 25s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m25s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m2s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 15m48s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 20m44s
to 1ad9435f37
All checks were successful
/ lint (pull_request) Successful in 25s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m27s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 13m14s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m0s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 15m57s
/ pr_labeler (pull_request_target) Successful in 8s
2025-12-08 09:32:02 +00:00
Compare
Lynne left a comment

Could you point out where the check for whether the codec is supported is done?

Could you point out where the check for whether the codec is supported is done?
@ -0,0 +756,4 @@
// Start streaming on OUTPUT queue
type = ctx->fctxi->output.format.type;
if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMON, &type) < 0) {
Member

Would there be issues doing this? You would potentially be calling ioctl multiple times on the same FD when running multiple decoders.

Would there be issues doing this? You would potentially be calling ioctl multiple times on the same FD when running multiple decoders.
Author
First-time contributor

I would not expect there to be any issue since we are expected to open a new FD for each frames context / decoding context, so STREAMON should only be happen once for both CAPTURE and OUTOUT queues per decoder instance.

As @ndufresne mentioned a new V4L2 M2M context is created when a /dev/videoX device is open(), so we must open the video device for each decoding / frames context, trying to dup() or re-use an already opened FD for multiple decoders is not really an option or how you are intended to interact with V4L2 M2M devices.

I would not expect there to be any issue since we are expected to open a new FD for each frames context / decoding context, so STREAMON should only be happen once for both CAPTURE and OUTOUT queues per decoder instance. As @ndufresne mentioned a new V4L2 M2M context is created when a `/dev/videoX` device is `open()`, so we must open the video device for each decoding / frames context, trying to `dup()` or re-use an already opened FD for multiple decoders is not really an option or how you are intended to interact with V4L2 M2M devices.
@ -0,0 +34,4 @@
/**
* Media device file descriptor of the initialized session.
*/
int media_fd;
Member

Could this go into a AVV4L2RequestDeviceContext?

Could this go into a `AVV4L2RequestDeviceContext`?
Author
First-time contributor

I would advice against it, we should treat both opened media and video device FDs as unique per frames / decoder context as both the media and video devices are closely tied to each other and close() of media FD help enforce request objects is cleaned/freed between each decoder session.

E.g. on one of my devices I have following media+video device topology:

  • /dev/media0 (rkvdec)
    • /dev/video0 (rkvdec)
      • H264, HEVC and VP9
  • /dev/media1 (hantro)
    • /dev/video1 (hantro encoder)
      • JPEG
    • /dev/video2 (hantro decoder)
      • H264, VP8 and MPEG2
I would advice against it, we should treat both opened media and video device FDs as unique per frames / decoder context as both the media and video devices are closely tied to each other and `close()` of media FD help enforce request objects is cleaned/freed between each decoder session. E.g. on one of my devices I have following media+video device topology: - /dev/media0 (rkvdec) - /dev/video0 (rkvdec) - H264, HEVC and VP9 - /dev/media1 (hantro) - /dev/video1 (hantro encoder) - JPEG - /dev/video2 (hantro decoder) - H264, VP8 and MPEG2
@ -0,0 +53,4 @@
/**
* V4L2 buffer capabilities flags.
*/
uint32_t capabilities;
Member

format and capabilities sound like they definitely should be public, in AVV4L2RequestFramesContext.

format and capabilities sound like they definitely should be public, in `AVV4L2RequestFramesContext`.
Author
First-time contributor

Agreed, this is information that could be useful by applications.

Agreed, this is information that could be useful by applications.
@ -0,0 +60,4 @@
*
* AVBufferRef.data points to a struct v4l2_buffer for the created buffer.
*/
AVBufferPool *pool;
Member

Could you move this to V4L2RequestContext?

Could you move this to `V4L2RequestContext`?
Author
First-time contributor

I do not think it can, we have two buffer pools, CAPTURE and OUTPUT, for decoders the bitstream is written to OUTPUT buffers and decoded frames ends up in CAPTURE buffers.

For encoders I think this will be opposite, the raw frame data is written to OUTPUT buffers and the encoded bitstream ends up in CAPTURE buffers. I can be wrong as the stateless encoder API is still not fully defined.

Because of this I think it makes more sense to treat both underlying CAPTURE and OUTPUT buffer pools in a similar way and close to where the media+video FDs live.

I do not think it can, we have two buffer pools, CAPTURE and OUTPUT, for decoders the bitstream is written to OUTPUT buffers and decoded frames ends up in CAPTURE buffers. For encoders I think this will be opposite, the raw frame data is written to OUTPUT buffers and the encoded bitstream ends up in CAPTURE buffers. I can be wrong as the stateless encoder API is still not fully defined. Because of this I think it makes more sense to treat both underlying CAPTURE and OUTPUT buffer pools in a similar way and close to where the media+video FDs live.
Author
First-time contributor

@Lynne wrote in #20847 (comment):

Could you point out where the check for whether the codec is supported is done?

AVV4L2RequestFramesContext.pixelformat is set to the coded pixel format, e.g. V4L2_PIX_FMT_H264_SLICE or V4L2_PIX_FMT_HEVC_SLICE, from hwaccel frame_params ops.

This is then checked against the pixel formats the OUTPUT queue report is supported by /dev/videoX devices using VIDIOC_ENUM_FMT in v4l2request_try_format() and finally using VIDIOC_S_FMT in v4l2request_set_format() called from v4l2request_probe_video_device().

As hinted in the comment in v4l2request_device_create(), an idea is to probe for all available media+video decoder combos and add them to V4L2RequestDeviceContext.decoders along with the supported coded pixel formats in the device_create ops. If the device/opts is supplied the user could narrow down what media+video combos is probed in case they want to target a specific video device.

Later in v4l2request_open_decoder() one of the decoders that indicate support the requested coded pixel format can be picked for use, possible a new derived device can be initialized only keeping a reference to the picked decoder, or something to that effect.

@Lynne wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issuecomment-18343: > Could you point out where the check for whether the codec is supported is done? `AVV4L2RequestFramesContext.pixelformat` is set to the coded pixel format, e.g. `V4L2_PIX_FMT_H264_SLICE` or `V4L2_PIX_FMT_HEVC_SLICE`, from hwaccel `frame_params` ops. This is then checked against the pixel formats the OUTPUT queue report is supported by `/dev/videoX` devices using `VIDIOC_ENUM_FMT` in `v4l2request_try_format()` and finally using `VIDIOC_S_FMT` in `v4l2request_set_format()` called from `v4l2request_probe_video_device()`. As hinted in the comment in `v4l2request_device_create()`, an idea is to probe for all available media+video decoder combos and add them to `V4L2RequestDeviceContext.decoders` along with the supported coded pixel formats in the `device_create` ops. If the `device`/`opts` is supplied the user could narrow down what media+video combos is probed in case they want to target a specific video device. Later in `v4l2request_open_decoder()` one of the decoders that indicate support the requested coded pixel format can be picked for use, possible a new derived device can be initialized only keeping a reference to the picked decoder, or something to that effect.
Jonas Karlman changed title from WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC and VP8 to WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC, VP8 and VP9 2025-12-09 20:26:13 +00:00
Jonas Karlman force-pushed v4l2request-v3 from 53a8df8a58
All checks were successful
/ lint (pull_request) Successful in 42s
/ pr_labeler (pull_request_target) Successful in 8s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m27s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 9m44s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 15m44s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 21m39s
to 23d9e02325
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 29s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 7m56s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m54s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 11m49s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 12m17s
2025-12-13 22:06:08 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 23d9e02325
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 29s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 7m56s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m54s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 11m49s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 12m17s
to f6683d4930
All checks were successful
/ pr_labeler (pull_request_target) Successful in 8s
/ lint (pull_request) Successful in 25s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m28s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m53s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 11m43s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 15m38s
2025-12-13 22:37:24 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from f6683d4930
All checks were successful
/ pr_labeler (pull_request_target) Successful in 8s
/ lint (pull_request) Successful in 25s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m28s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m53s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 11m43s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 15m38s
to 24658b926b
All checks were successful
/ lint (pull_request) Successful in 37s
/ pr_labeler (pull_request_target) Successful in 8s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m39s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m55s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 14m35s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 23m30s
2025-12-14 00:29:50 +00:00
Compare
Jonas Karlman changed title from WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC, VP8 and VP9 to WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC, VP8, VP9 and AV1 2025-12-14 00:30:21 +00:00
Jonas Karlman force-pushed v4l2request-v3 from 24658b926b
All checks were successful
/ lint (pull_request) Successful in 37s
/ pr_labeler (pull_request_target) Successful in 8s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m39s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m55s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 14m35s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 23m30s
to a0e7a2f0be
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 36s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 7m57s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m5s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 11m43s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 12m23s
2025-12-14 00:31:55 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from a0e7a2f0be
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 36s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 7m57s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 11m5s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 11m43s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 12m23s
to ce1db52c00
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 29s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 8m5s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 12m36s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m47s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 11m48s
2025-12-14 00:35:53 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from ce1db52c00
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 29s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 8m5s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 12m36s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m47s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 11m48s
to ea34873176
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 29s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m50s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m51s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 16m38s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 23m15s
2025-12-14 18:49:56 +00:00
Compare
Author
First-time contributor

This PR has now been updated to also include hwaccels for VP9 and AV1.

It also got a small configure fix for a libavutil linking issue due to missing -udev after device probing code was moved from lavc to lavu.

This PR has now been updated to also include hwaccels for VP9 and AV1. It also got a small `configure` fix for a `libavutil` linking issue due to missing `-udev` after device probing code was moved from lavc to lavu.
Jonas Karlman force-pushed v4l2request-v3 from ea34873176
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 29s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m50s
/ compile_only (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest) (pull_request) Successful in 10m51s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 16m38s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 23m15s
to eea5530b31
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 25s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m38s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 15m50s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 23m14s
/ run_fate_full (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest, wine) (pull_request) Successful in 24m53s
2025-12-21 00:08:19 +00:00
Compare
@ -0,0 +741,4 @@
AVBufferRef *ref;
uint8_t *data;
data = av_mallocz(size);
Contributor

This allocation is leaked by v4l2request_frame_free().

This allocation is leaked by `v4l2request_frame_free()`.
Author
First-time contributor

Thanks!, fixed in a recent rebase/force push.

Thanks!, fixed in a recent rebase/force push.
Jonas Karlman force-pushed v4l2request-v3 from eea5530b31
All checks were successful
/ pr_labeler (pull_request_target) Successful in 9s
/ lint (pull_request) Successful in 25s
/ run_fate (64, linux-aarch64, static) (pull_request) Successful in 11m38s
/ run_fate (64, linux-amd64, shared) (pull_request) Successful in 15m50s
/ run_fate (32, linux-amd64, static) (pull_request) Successful in 23m14s
/ run_fate_full (ghcr.io/btbn/ffmpeg-builds/win64-gpl:latest, wine) (pull_request) Successful in 24m53s
to 4236d2aef2
Some checks failed
Autolabel / Labeler (pull_request_target) Successful in 9s
Lint / Pre-Commit (pull_request) Successful in 27s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Has been cancelled
Test / Fate (Full, wine) (pull_request) Has been cancelled
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Has been cancelled
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Has been cancelled
2026-01-31 10:24:13 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 4236d2aef2
Some checks failed
Autolabel / Labeler (pull_request_target) Successful in 9s
Lint / Pre-Commit (pull_request) Successful in 27s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Has been cancelled
Test / Fate (Full, wine) (pull_request) Has been cancelled
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Has been cancelled
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Has been cancelled
to 4beeac7298
All checks were successful
Lint / Pre-Commit (pull_request) Successful in 30s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 11m17s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 11m14s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 12m8s
Test / Fate (Full, wine) (pull_request) Successful in 25m4s
Autolabel / Labeler (pull_request_target) Successful in 11s
2026-01-31 10:33:03 +00:00
Compare
First-time contributor

Hello, what’s current status of this PR?

Hello, what’s current status of this PR?
Jonas Karlman force-pushed v4l2request-v3 from 4beeac7298
All checks were successful
Lint / Pre-Commit (pull_request) Successful in 30s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 11m17s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 11m14s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 12m8s
Test / Fate (Full, wine) (pull_request) Successful in 25m4s
Autolabel / Labeler (pull_request_target) Successful in 11s
to 5c5ae56db7
Some checks failed
Autolabel / Labeler (pull_request_target) Successful in 8s
Lint / Pre-Commit (pull_request) Successful in 28s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 11m30s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 12m33s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 15m10s
Test / Fate (Full, wine) (pull_request) Has been cancelled
2026-03-12 21:15:36 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 5c5ae56db7
Some checks failed
Autolabel / Labeler (pull_request_target) Successful in 8s
Lint / Pre-Commit (pull_request) Successful in 28s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 11m30s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 12m33s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 15m10s
Test / Fate (Full, wine) (pull_request) Has been cancelled
to 068725826f
All checks were successful
Autolabel / Labeler (pull_request_target) Successful in 9s
Lint / Pre-Commit (pull_request) Successful in 29s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 11m27s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 11m44s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 15m56s
Test / Fate (Full, wine) (pull_request) Successful in 24m11s
2026-03-12 21:51:06 +00:00
Compare
Jonas Karlman force-pushed v4l2request-v3 from 068725826f
All checks were successful
Autolabel / Labeler (pull_request_target) Successful in 9s
Lint / Pre-Commit (pull_request) Successful in 29s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 11m27s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 11m44s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 15m56s
Test / Fate (Full, wine) (pull_request) Successful in 24m11s
to 3ac4e07593
All checks were successful
Lint / Pre-Commit (pull_request) Successful in 25s
Autolabel / Labeler (pull_request_target) Successful in 8s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 11m32s
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 11m55s
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 11m52s
Test / Fate (Full, wine) (pull_request) Successful in 26m50s
2026-03-12 22:59:05 +00:00
Compare
Author
First-time contributor

This has now been updated to include support for the mainline (and rpi-6.18.y) Raspberry Pi HEVC decoder.

Recent changes include:

  • Memory leak fix
  • Adopt changes to match v4l2_ctrl_hevc_slice_params.bit_size clarification
  • Add support for NV12MT_COL128 and NV12MT_10_COL128 V4L2 pixel formats

Looking into adding support for V4L2_PIX_FMTs used by the mtk-vcodec-dec driver it has become apparent that a new AVPixelFormat is likely needed as the video decoder output format is not something that directly can be imported by the drm subsytem and instead has to be converted from a decoder specific tiled format into e.g. nv12, thus it is not possible to describe the raw decoded format using the drm_prime pix fmt.

This has now been updated to include support for the [mainline](https://lore.kernel.org/linux-media/[email protected]/) (and [rpi-6.18.y](https://github.com/raspberrypi/linux/tree/rpi-6.18.y/drivers/media/platform/raspberrypi/hevc_dec)) Raspberry Pi HEVC decoder. Recent changes include: - Memory leak fix - Adopt changes to match v4l2_ctrl_hevc_slice_params.bit_size clarification - Add support for `NV12MT_COL128` and `NV12MT_10_COL128` V4L2 pixel formats Looking into adding support for `V4L2_PIX_FMT`s used by the `mtk-vcodec-dec` driver it has become apparent that a new `AVPixelFormat` is likely needed as the video decoder output format is not something that directly can be imported by the drm subsytem and instead has to be converted from a decoder specific tiled format into e.g. nv12, thus it is not possible to describe the raw decoded format using the `drm_prime` pix fmt.
First-time contributor

@Kwiboo wrote in #20847 (comment):

This has now been updated to include support for the mainline (and rpi-6.18.y) Raspberry Pi HEVC decoder.

Recent changes include:

  • Memory leak fix
  • Adopt changes to match v4l2_ctrl_hevc_slice_params.bit_size clarification
  • Add support for NV12MT_COL128 and NV12MT_10_COL128 V4L2 pixel formats

Looking into adding support for V4L2_PIX_FMTs used by the mtk-vcodec-dec driver it has become apparent that a new AVPixelFormat is likely needed as the video decoder output format is not something that directly can be imported by the drm subsytem and instead has to be converted from a decoder specific tiled format into e.g. nv12, thus it is not possible to describe the raw decoded format using the drm_prime pix fmt.

Hello,I want to know,what's the status about this pull request?
Is avalible on rockchip's soc on mainline(7.0-rc6) with rkvdec/ho??? support
What's the diff of this and liberelec's v4l2-request patchset?
(seem work on your devices?)

@Kwiboo wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issuecomment-31699: > This has now been updated to include support for the [mainline](https://lore.kernel.org/linux-media/[email protected]/) (and [rpi-6.18.y](https://github.com/raspberrypi/linux/tree/rpi-6.18.y/drivers/media/platform/raspberrypi/hevc_dec)) Raspberry Pi HEVC decoder. > > Recent changes include: > > * Memory leak fix > * Adopt changes to match v4l2_ctrl_hevc_slice_params.bit_size clarification > * Add support for `NV12MT_COL128` and `NV12MT_10_COL128` V4L2 pixel formats > > Looking into adding support for `V4L2_PIX_FMT`s used by the `mtk-vcodec-dec` driver it has become apparent that a new `AVPixelFormat` is likely needed as the video decoder output format is not something that directly can be imported by the drm subsytem and instead has to be converted from a decoder specific tiled format into e.g. nv12, thus it is not possible to describe the raw decoded format using the `drm_prime` pix fmt. Hello,I want to know,what's the status about this pull request? Is avalible on rockchip's soc on mainline(7.0-rc6) with rkvdec/ho??? support What's the diff of this and liberelec's v4l2-request patchset? (seem work on your devices?)
First-time contributor

@4-Qbit wrote in #20847 (comment):

What's the diff of this and liberelec's v4l2-request patchset?

LE is tracking https://code.ffmpeg.org/Kwiboo/FFmpeg/commits/branch/v4l2-request-n8.1 which contains the commits in this PR plus a couple of additional commits for RPi support (will be submitted in a follow-on PR) along with a v4l2_request filter driver to support hardware deinterlacing (depends on some WIP kernel drivers that haven't been submitted yet). LE 13.0 images are using the kernel patchset here: https://github.com/chewitt/linux/commits/rockchip-7.0.y which is large but 85-90% the latest iterations of patches cherry-picked from mailing-lists, i.e. being actively upstreamed. The only codec supported in this PR and the LE kernel that is not yet upstream in rkvdec is VP9, everything else (H264, HEVC, AV1) is working with 6.18/6.19 and 7.0-rc kernels.

NB: If you have general integration/test Q's let's move the conversation to the LE forum. Feel free to ping me there.

@4-Qbit wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issuecomment-35024: > What's the diff of this and liberelec's v4l2-request patchset? LE is tracking https://code.ffmpeg.org/Kwiboo/FFmpeg/commits/branch/v4l2-request-n8.1 which contains the commits in this PR plus a couple of additional commits for RPi support (will be submitted in a follow-on PR) along with a v4l2_request filter driver to support hardware deinterlacing (depends on some WIP kernel drivers that haven't been submitted yet). LE 13.0 images are using the kernel patchset here: https://github.com/chewitt/linux/commits/rockchip-7.0.y which is large but 85-90% the latest iterations of patches cherry-picked from mailing-lists, i.e. being actively upstreamed. The only codec supported in this PR and the LE kernel that is not yet upstream in rkvdec is VP9, everything else (H264, HEVC, AV1) is working with 6.18/6.19 and 7.0-rc kernels. NB: If you have general integration/test Q's let's move the conversation to the LE forum. Feel free to ping me there.
First-time contributor

@chewitt wrote in #20847 (comment):

@4-Qbit wrote in #20847 (评论):

What's the diff of this and liberelec's v4l2-request patchset?

LE is tracking https://code.ffmpeg.org/Kwiboo/FFmpeg/commits/branch/v4l2-request-n8.1 which contains the commits in this PR plus a couple of additional commits for RPi support (will be submitted in a follow-on PR) along with a v4l2_request filter driver to support hardware deinterlacing (depends on some WIP kernel drivers that haven't been submitted yet). LE 13.0 images are using the kernel patchset here: https://github.com/chewitt/linux/commits/rockchip-7.0.y which is large but 85-90% the latest iterations of patches cherry-picked from mailing-lists, i.e. being actively upstreamed. The only codec supported in this PR and the LE kernel that is not yet upstream in rkvdec is VP9, everything else (H264, HEVC, AV1) is working with 6.18/6.19 and 7.0-rc kernels.

NB: If you have general integration/test Q's let's move the conversation to the LE forum. Feel free to ping me there.

Thanks,I just want use this patch on desktop side(kodi+firefox etc),but I also have many question,see you (a long time) later on LE forum.😄

@chewitt wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issuecomment-35039: > @4-Qbit wrote in #20847 (评论): > > > What's the diff of this and liberelec's v4l2-request patchset? > > LE is tracking https://code.ffmpeg.org/Kwiboo/FFmpeg/commits/branch/v4l2-request-n8.1 which contains the commits in this PR plus a couple of additional commits for RPi support (will be submitted in a follow-on PR) along with a v4l2_request filter driver to support hardware deinterlacing (depends on some WIP kernel drivers that haven't been submitted yet). LE 13.0 images are using the kernel patchset here: https://github.com/chewitt/linux/commits/rockchip-7.0.y which is large but 85-90% the latest iterations of patches cherry-picked from mailing-lists, i.e. being actively upstreamed. The only codec supported in this PR and the LE kernel that is not yet upstream in rkvdec is VP9, everything else (H264, HEVC, AV1) is working with 6.18/6.19 and 7.0-rc kernels. > > NB: If you have general integration/test Q's let's move the conversation to the LE forum. Feel free to ping me there. Thanks,I just want use this patch on desktop side(kodi+firefox etc),but I also have many question,see you (a long time) later on LE forum.😄
@ -0,0 +903,4 @@
fctxi->video_fd = -1;
}
if (fctxi->media_fd) {
First-time contributor

I think this should be >= 0, same as the video_fd check right above it. As-is, this tries to close(-1) when media_fd is at its init value, and would skip closing fd 0 if that ever happened to be the media fd.

I think this should be `>= 0`, same as the `video_fd` check right above it. As-is, this tries to `close(-1)` when `media_fd` is at its init value, and would skip closing fd 0 if that ever happened to be the media fd.
@ -0,0 +1041,4 @@
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;
First-time contributor

This silently tells callers "no transfer formats available" for tiled pixel formats, which is going to be confusing to debug for anyone trying to use Allwinner or RPi SAND formats. Worth an av_log at AV_LOG_VERBOSE here explaining why transfer isn't supported for the format.

This silently tells callers "no transfer formats available" for tiled pixel formats, which is going to be confusing to debug for anyone trying to use Allwinner or RPi SAND formats. Worth an `av_log` at `AV_LOG_VERBOSE` here explaining why transfer isn't supported for the format.
@ -0,0 +582,4 @@
output->request_fd = -1;
}
// Umap the OUTPUT buffer memory
First-time contributor

nit: Unmap

nit: `Unmap`
@ -0,0 +164,4 @@
// 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
First-time contributor

The TODO here is the biggest open question for the whole PR. Right now all the probing happens in frames_init, which means there's no way for a user to pick a specific device, and -init_hw_device v4l2request is a no-op. I understand this is WIP, but it's worth thinking about what the minimum viable device_create looks like before dropping the WIP tag. Even just accepting a /dev/mediaN path and storing it would be useful.

The TODO here is the biggest open question for the whole PR. Right now all the probing happens in `frames_init`, which means there's no way for a user to pick a specific device, and `-init_hw_device v4l2request` is a no-op. I understand this is WIP, but it's worth thinking about what the minimum viable `device_create` looks like before dropping the WIP tag. Even just accepting a `/dev/mediaN` path and storing it would be useful.
@ -0,0 +96,4 @@
return inv_map_table[d];
}
static void fill_compressed_hdr(struct v4l2_ctrl_vp9_compressed_hdr *ctrl,
First-time contributor

This re-parses the compressed header from the raw bitstream instead of pulling from the already-parsed VP9 decoder state. I assume this is because the V4L2 control wants the probability deltas rather than the final probability tables? If so, a one-line comment saying that would prevent the next reader from filing a "this duplicates parsing work" bug.

This re-parses the compressed header from the raw bitstream instead of pulling from the already-parsed VP9 decoder state. I assume this is because the V4L2 control wants the probability deltas rather than the final probability tables? If so, a one-line comment saying that would prevent the next reader from filing a "this duplicates parsing work" bug.
First-time contributor

Ping.

Ping.
First-time contributor

Is this PR still active, or is development taking place somewhere else, @Kwiboo?
Is there anything specific missing that needs help/testing? I have an Orange Pi 5, RK3588s, available for testing if needed.

I think many people would really appreciate if this was merged :)

Is this PR still active, or is development taking place somewhere else, @Kwiboo? Is there anything specific missing that needs help/testing? I have an Orange Pi 5, RK3588s, available for testing if needed. I think many people would really appreciate if this was merged :)
First-time contributor

Hi,

I'm following this PR with interest as I'm hitting the exact issue it aims to fix, on a Raspberry Pi 5.

Setup:

  • Hardware: Raspberry Pi 5 (BCM2712)
  • OS: Raspberry Pi OS Bookworm, fully updated
  • Kernel: 6.12.62+rpt-rpi-2712
  • Use case: hardware-accelerated HEVC decoding via Moonlight (moonlight-qt 6.1.0), streaming from a Sunshine/GameStream host

Symptom:
The HEVC hwaccel path finds /dev/video19 (driver rpi-hevc-dec) and passes the mem2mem capability check, but fails shortly after:

v4l2_request_probe_video_device: select capture format failed
No V4L2 media device found for S265
Failed setup for format drm_prime: hwaccel initialisation returned error.

I'd be happy to test patches or branches against my hardware/setup if that's useful for validation — just let me know what you'd like tested and I'll report back with logs.

Also curious if there's a rough timeline or open blockers for merging this into mainline FFmpeg — happy to help however I can in the meantime.

Thanks for the work on this!

Hi, I'm following this PR with interest as I'm hitting the exact issue it aims to fix, on a Raspberry Pi 5. **Setup:** - Hardware: Raspberry Pi 5 (BCM2712) - OS: Raspberry Pi OS Bookworm, fully updated - Kernel: 6.12.62+rpt-rpi-2712 - Use case: hardware-accelerated HEVC decoding via Moonlight (moonlight-qt 6.1.0), streaming from a Sunshine/GameStream host **Symptom:** The HEVC hwaccel path finds `/dev/video19` (driver `rpi-hevc-dec`) and passes the mem2mem capability check, but fails shortly after: ``` v4l2_request_probe_video_device: select capture format failed No V4L2 media device found for S265 Failed setup for format drm_prime: hwaccel initialisation returned error. ``` I'd be happy to test patches or branches against my hardware/setup if that's useful for validation — just let me know what you'd like tested and I'll report back with logs. Also curious if there's a rough timeline or open blockers for merging this into mainline FFmpeg — happy to help however I can in the meantime. Thanks for the work on this!
First-time contributor

Replying on behalf of @Kwiboo after chatting with him about plans a few days ago. He is currently focussed on submitting a large backlog of kernel/u-boot work to mailing-lists, then plans to circle back here soon to rebase and address remaining architectural concerns that should be ironed out before moving out of draft. The PR is not forgotten :)

Replying on behalf of @Kwiboo after chatting with him about plans a few days ago. He is currently focussed on submitting a large backlog of kernel/u-boot work to mailing-lists, then plans to circle back here soon to rebase and address remaining architectural concerns that should be ironed out before moving out of draft. The PR is not forgotten :)
First-time contributor

Hi Jonas,

I have been running this series on an Allwinner H616 (Orange Pi Zero2,
Cedrus) and have five fixes on top of the current head (3ac4e07593).
Feel free to squash them into your commits or take them as they are:

  1. avutil/hwcontext_v4l2request: accept frames smaller than the minimum
    frame size. Streams below the driver's minimum (VP9 8x8 ... 66x10)
    failed hwaccel init; the driver rounds the format up anyway. Fixes
    the 28 vp90-2-02-size vectors with a dimension below 16 on Cedrus.
  2. avcodec/v4l2_request: keep returning frames of a closed session safe.
    With frame threads, a VP9 key frame of a new size re-creates the
    hwaccel while frames of the old session are still waiting in
    post_process(), which then used the freed context. Random segfaults
    on the vp90-2-14-resize-fp-tiles- vectors; 720 decodes clean with
    the fix.
  3. avcodec/v4l2_request: track CAPTURE buffer indices above 31
    (1 << index on a 64-bit mask).
  4. avutil/hwcontext_v4l2request: change the frame size of a running
    session (VIDIOC_REMOVE_BUFS), and
  5. avcodec/vp9: keep the hwaccel across frame size changes of non-key
    frames (new optional FFHWAccel.update_frame_size()). VP9 inter
    frames that change size kept predicting from references the new
    session did not have. On the H616 the 26 resize_inter/resize
    vectors and svc_1280x720_3 now match the libvpx md5s (0 before),
    together with a Cedrus-only stride change that I left out (see the
    commit message of 5).
    Devices without VIDIOC_REMOVE_BUFS fall back to the old behaviour
    for larger frames.

Details and test results are in the commit messages. Built for aarch64
with --enable-v4l2-request against 7.3 headers, each commit separately,
no new warnings; FATE vp9/vp8/hevc/h264/api/source pass.

The patches are attached (git am v4l2-request-fixes-pr20847.patch on
3ac4e07593). They carry an Assisted-by: LLM trailer: I used an LLM
while writing them; I reviewed and tested them myself and can answer
questions on them.

Arun

Hi Jonas, I have been running this series on an Allwinner H616 (Orange Pi Zero2, Cedrus) and have five fixes on top of the current head (3ac4e07593). Feel free to squash them into your commits or take them as they are: 1. avutil/hwcontext_v4l2request: accept frames smaller than the minimum frame size. Streams below the driver's minimum (VP9 8x8 ... 66x10) failed hwaccel init; the driver rounds the format up anyway. Fixes the 28 vp90-2-02-size vectors with a dimension below 16 on Cedrus. 2. avcodec/v4l2_request: keep returning frames of a closed session safe. With frame threads, a VP9 key frame of a new size re-creates the hwaccel while frames of the old session are still waiting in post_process(), which then used the freed context. Random segfaults on the vp90-2-14-resize-*fp-tiles-* vectors; 720 decodes clean with the fix. 3. avcodec/v4l2_request: track CAPTURE buffer indices above 31 (1 << index on a 64-bit mask). 4. avutil/hwcontext_v4l2request: change the frame size of a running session (VIDIOC_REMOVE_BUFS), and 5. avcodec/vp9: keep the hwaccel across frame size changes of non-key frames (new optional FFHWAccel.update_frame_size()). VP9 inter frames that change size kept predicting from references the new session did not have. On the H616 the 26 resize_inter/resize vectors and svc_1280x720_3 now match the libvpx md5s (0 before), together with a Cedrus-only stride change that I left out (see the commit message of 5). Devices without VIDIOC_REMOVE_BUFS fall back to the old behaviour for larger frames. Details and test results are in the commit messages. Built for aarch64 with --enable-v4l2-request against 7.3 headers, each commit separately, no new warnings; FATE vp9/vp8/hevc/h264/api/source pass. The patches are attached (git am v4l2-request-fixes-pr20847.patch on 3ac4e07593). They carry an Assisted-by: LLM trailer: I used an LLM while writing them; I reviewed and tested them myself and can answer questions on them. Arun
First-time contributor

@SomeComputerGuy wrote in #20847 (comment):

...

+1 on fix 3 (CAPTURE indices above 31). Here is another data point, and a note on the width of the fix.

Setup: Apple M5 (AVD stateless decoder). The driver allows 128 CAPTURE buffers per context. mpv uses --hwdec=v4l2request --hwdec-extra-frames=104 --vd-queue-max-samples=96 to decode ahead through 4K60 H.264 bitrate bursts, so the pool grows to about 110 CAPTURE buffers.

Symptom: queued_capture is a uint64_t, but 1 << index is a 32-bit int shift. On aarch64 the shift count wraps, so buffer 48 marks bit 16 and shares it with buffer 16. Index 31 sign-extends into all the upper bits. Waits then spin on another buffer's bit until the 2 s poll gives up. A 10 s 4K60 clip logged 3 to 11 "Failed waiting on CAPTURE buffer 48/49/50" and took 15 to 40 s to play.

Width of the fix: a 64-bit shift (1ULL << index) fixes indices 32 to 63, but breaks again from 64. The attached patch tracks the queue in a 256-bit bitmap, refuses to queue a higher index, and bounds-checks the wait. With it there are 0 timeouts, and the clip plays in 10.3 s. H.264, HEVC Main/Main10, VP9 and AV1 framemd5 still match software.

@SomeComputerGuy wrote in https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/20847#issuecomment-83194: >... +1 on fix 3 (CAPTURE indices above 31). Here is another data point, and a note on the width of the fix. **Setup:** Apple M5 (AVD stateless decoder). The driver allows 128 CAPTURE buffers per context. mpv uses `--hwdec=v4l2request --hwdec-extra-frames=104 --vd-queue-max-samples=96` to decode ahead through 4K60 H.264 bitrate bursts, so the pool grows to about 110 CAPTURE buffers. **Symptom:** `queued_capture` is a `uint64_t`, but `1 << index` is a 32-bit int shift. On aarch64 the shift count wraps, so buffer 48 marks bit 16 and shares it with buffer 16. Index 31 sign-extends into all the upper bits. Waits then spin on another buffer's bit until the 2 s poll gives up. A 10 s 4K60 clip logged 3 to 11 "Failed waiting on CAPTURE buffer 48/49/50" and took 15 to 40 s to play. **Width of the fix:** a 64-bit shift (`1ULL << index`) fixes indices 32 to 63, but breaks again from 64. The attached patch tracks the queue in a 256-bit bitmap, refuses to queue a higher index, and bounds-checks the wait. With it there are 0 timeouts, and the clip plays in 10.3 s. H.264, HEVC Main/Main10, VP9 and AV1 framemd5 still match software.
First-time contributor

@sithglan thanks for the M5 data and the patch; you are right, the 64-bit shift only moved the limit.
Fix 3 now uses your 256-bit bitmap (Co-developed-by + your Signed-off-by), refuses the index in start_frame before any buffer is queued and clears only indices inside the bitmap on DQBUF; the VIDIOC_REMOVE_BUFS retry in fix 4 now covers 256 indices too.
Fix 4 had a use-after-free: it removed a released old-size CAPTURE buffer while a queued decode could still read it as a reference (vp90-2-22-svc_1280x720_3, one decode thread: IOMMU fault and timeout in 30 of 60 runs); it now waits until no CAPTURE buffer is queued (0 of 100) and downloads frames at their own size.
Updated series attached (git am on 3ac4e07593); fix 5 now exports frames decoded in place with the stride VIDIOC_TRY_FMT reports for their size.
The H616 (Cedrus) stops at 64 buffers, so indices >= 64 and the refusal at 256 did not run here. The VP9 suite now matches 301 of 306 (was 275; the 26 inter-frame size change vectors now match), H.264/HEVC/VP8 and 40 extra CAPTURE buffers decode as before.

@sithglan thanks for the M5 data and the patch; you are right, the 64-bit shift only moved the limit. Fix 3 now uses your 256-bit bitmap (Co-developed-by + your Signed-off-by), refuses the index in start_frame before any buffer is queued and clears only indices inside the bitmap on DQBUF; the VIDIOC_REMOVE_BUFS retry in fix 4 now covers 256 indices too. Fix 4 had a use-after-free: it removed a released old-size CAPTURE buffer while a queued decode could still read it as a reference (vp90-2-22-svc_1280x720_3, one decode thread: IOMMU fault and timeout in 30 of 60 runs); it now waits until no CAPTURE buffer is queued (0 of 100) and downloads frames at their own size. Updated series attached (git am on 3ac4e07593); fix 5 now exports frames decoded in place with the stride VIDIOC_TRY_FMT reports for their size. The H616 (Cedrus) stops at 64 buffers, so indices >= 64 and the refusal at 256 did not run here. The VP9 suite now matches 301 of 306 (was 275; the 26 inter-frame size change vectors now match), H.264/HEVC/VP8 and 40 extra CAPTURE buffers decode as before.
First-time contributor

@SomeComputerGuy I tested v2 on the Apple M5. It applies cleanly with git am on 3ac4e07593, and also on a 9.0.2 tree with Kwiboo's v4l2-request-n8.1 series, which I used for an mpv test. The AVD driver allows 128 CAPTURE buffers per queue and has no VIDIOC_REMOVE_BUFS.

Fix 3, indices >= 64:

  • ffmpeg holding 100 decoded 4K60 H.264 frames (-vf trim=end_frame=100,reverse,hwdownload,format=nv12) uses 111 CAPTURE buffers, indices up to 109, and framemd5 matches software. Holding 120 frames reaches index 127, the driver's limit, and the 120 frames still match.
  • mpv zero-copy (--hwdec=v4l2request --hwdec-extra-frames=104 --vd-queue-max-samples=96): a 10 s 4K60 H.264 clip, played 3 times with 8 seeks, after a 3 s pause at start so the decode queue fills. Without the fix: 38 to 42 "Failed waiting on CAPTURE buffer" per run, on buffers 3/35 and 4/100 (pairs equal mod 32), and 105 to 115 s per run. With v2: none in 3 runs, 46 s each, indices up to 100 (102 buffers). The display was off for these runs, so mpv presented without vsync. Under those conditions plain playback without seeks doesn't trip the old code, because buffers come back in order and the queued ones are never 32 apart. With the display on, it tripped without seeks (my first comment).
  • The refusal at 256 can't be reached here either, because the driver stops at 128. Holding 130 frames, VIDIOC_CREATE_BUFS fails with ENOBUFS once index 127 is in use, and decoding then fails with "get_buffer() failed". It doesn't hang or crash.

No regressions: H.264, HEVC Main/Main10, VP9 and AV1 clips (60 frames each) and the 600-frame 4K60 H.264 clip match software with v2, as they do with 3ac4e07593. In the libvpx VP9 suite (per-frame md5 against libvpx's .md5, 304 4:2:0 vectors) both trees match the same 216. Over 5 runs of the 36 resize-fp-tiles vectors, 180 of 180 decodes match on both trees, with no crash. The fix 2 crash doesn't reproduce on the AVD.

Fix 5 needs driver support: with the current AVD driver the in-place path doesn't help. The driver refuses a VP9 frame whose aligned size differs from the CAPTURE format ("unexpected bitstream resolution 320x192") and stops the stream. All 24 resize_inter vectors still fail; 3ac4e07593 decodes them without references instead. The check is the same as rkvdec's validate_dec_params() (rkvdec-vp9.c, aligned to 64x64), so RK3399 should refuse the same frames.

Relaxing that check wasn't enough. When userspace renegotiates on every size change, the driver never sees a size change within a session, so that code had never run, and three bugs showed up:

  • every stream that shrinks on an inter frame without error resilience crashed the AVD firmware, because the driver still used the previous frame's motion vectors;
  • the reference scale had x and y swapped;
  • the segmentation map wasn't reset.

The V4L2 VP9 controls have no flag for using the previous frame's motion vectors, so each driver works that out itself, and other drivers may have the same gaps. The libvpx vectors that change size on inter frames are all error resilient, which skips two of these paths. So I also tested with streams from libvpx's internal scaling, with segmentation and no error resilience.

The AVD fixes are in https://github.com/aurora-silicon/linux/pull/2136. With them, v2 matches 242 of 304 (216 without them). The new matches are all 24 resize_inter vectors, plus 05-resize and 18-resize: those shrink and then grow back to the first size, so they stay in place too. No vector stops matching. The AVD writes the smaller frame with the format's stride. Its TRY_FMT clamps the width to the OUTPUT width, so fix 5 keeps the full pitch, which is correct here. One case is still open on the driver side: a segmentation map kept across the size change, at 720p and above.

svc_1280x720_3 grows past the first size. That needs VIDIOC_REMOVE_BUFS, which the AVD doesn't have, so it falls back to renegotiation. The fix 4 removal path and its use-after-free fix never ran here.

Refused frames are silent: the frames the driver refused come out as green frames, with exit code 0 and no log line, because v4l2_request_dequeue_buffer() doesn't look at V4L2_BUF_FLAG_ERROR. The same happens for the 60 vp90-2-02-size vectors with a side below 64, which the AVD refuses. Checking the flag would at least report these.

@SomeComputerGuy I tested v2 on the Apple M5. It applies cleanly with `git am` on 3ac4e07593, and also on a 9.0.2 tree with Kwiboo's v4l2-request-n8.1 series, which I used for an mpv test. The AVD driver allows 128 CAPTURE buffers per queue and has no `VIDIOC_REMOVE_BUFS`. **Fix 3, indices >= 64:** - ffmpeg holding 100 decoded 4K60 H.264 frames (`-vf trim=end_frame=100,reverse,hwdownload,format=nv12`) uses 111 CAPTURE buffers, indices up to 109, and framemd5 matches software. Holding 120 frames reaches index 127, the driver's limit, and the 120 frames still match. - mpv zero-copy (`--hwdec=v4l2request --hwdec-extra-frames=104 --vd-queue-max-samples=96`): a 10 s 4K60 H.264 clip, played 3 times with 8 seeks, after a 3 s pause at start so the decode queue fills. Without the fix: 38 to 42 "Failed waiting on CAPTURE buffer" per run, on buffers 3/35 and 4/100 (pairs equal mod 32), and 105 to 115 s per run. With v2: none in 3 runs, 46 s each, indices up to 100 (102 buffers). The display was off for these runs, so mpv presented without vsync. Under those conditions plain playback without seeks doesn't trip the old code, because buffers come back in order and the queued ones are never 32 apart. With the display on, it tripped without seeks (my first comment). - The refusal at 256 can't be reached here either, because the driver stops at 128. Holding 130 frames, `VIDIOC_CREATE_BUFS` fails with ENOBUFS once index 127 is in use, and decoding then fails with "get_buffer() failed". It doesn't hang or crash. **No regressions:** H.264, HEVC Main/Main10, VP9 and AV1 clips (60 frames each) and the 600-frame 4K60 H.264 clip match software with v2, as they do with 3ac4e07593. In the libvpx VP9 suite (per-frame md5 against libvpx's .md5, 304 4:2:0 vectors) both trees match the same 216. Over 5 runs of the 36 resize-fp-tiles vectors, 180 of 180 decodes match on both trees, with no crash. The fix 2 crash doesn't reproduce on the AVD. **Fix 5 needs driver support:** with the current AVD driver the in-place path doesn't help. The driver refuses a VP9 frame whose aligned size differs from the CAPTURE format ("unexpected bitstream resolution 320x192") and stops the stream. All 24 resize_inter vectors still fail; 3ac4e07593 decodes them without references instead. The check is the same as rkvdec's `validate_dec_params()` (rkvdec-vp9.c, aligned to 64x64), so RK3399 should refuse the same frames. Relaxing that check wasn't enough. When userspace renegotiates on every size change, the driver never sees a size change within a session, so that code had never run, and three bugs showed up: - every stream that shrinks on an inter frame without error resilience crashed the AVD firmware, because the driver still used the previous frame's motion vectors; - the reference scale had x and y swapped; - the segmentation map wasn't reset. The V4L2 VP9 controls have no flag for using the previous frame's motion vectors, so each driver works that out itself, and other drivers may have the same gaps. The libvpx vectors that change size on inter frames are all error resilient, which skips two of these paths. So I also tested with streams from libvpx's internal scaling, with segmentation and no error resilience. The AVD fixes are in https://github.com/aurora-silicon/linux/pull/2136. With them, v2 matches 242 of 304 (216 without them). The new matches are all 24 resize_inter vectors, plus 05-resize and 18-resize: those shrink and then grow back to the first size, so they stay in place too. No vector stops matching. The AVD writes the smaller frame with the format's stride. Its `TRY_FMT` clamps the width to the OUTPUT width, so fix 5 keeps the full pitch, which is correct here. One case is still open on the driver side: a segmentation map kept across the size change, at 720p and above. svc_1280x720_3 grows past the first size. That needs `VIDIOC_REMOVE_BUFS`, which the AVD doesn't have, so it falls back to renegotiation. The fix 4 removal path and its use-after-free fix never ran here. **Refused frames are silent:** the frames the driver refused come out as green frames, with exit code 0 and no log line, because `v4l2_request_dequeue_buffer()` doesn't look at `V4L2_BUF_FLAG_ERROR`. The same happens for the 60 vp90-2-02-size vectors with a side below 64, which the AVD refuses. Checking the flag would at least report these.
First-time contributor

@sithglan thanks for testing v2 on the M5 and for the AVD fixes.
For the silent refused frames: fix 6 (attached, git am on top of v2) logs "Decode error on CAPTURE buffer N" and sets FF_DECODE_ERROR_INVALID_BITSTREAM on a frame whose CAPTURE buffer comes back with V4L2_BUF_FLAG_ERROR, as the V4L2 M2M decoder does. The frame is still output.
On Cedrus (H616), an H.264 slice cut short (the driver flags that buffer ERROR) was output as a good frame with exit code 0; with fix 6 ffmpeg prints "corrupt decoded frame", and -xerror stops there. The VP9 suite, H.264, VP8 and HEVC decode as before.
Not run on the AVD: its refused frames are reported only if the driver returns their CAPTURE buffer with the flag.
Fix 6 carries Assisted-by: LLM like the others: I used an LLM while writing it; I reviewed and tested it myself.

@sithglan thanks for testing v2 on the M5 and for the AVD fixes. For the silent refused frames: fix 6 (attached, git am on top of v2) logs "Decode error on CAPTURE buffer N" and sets FF_DECODE_ERROR_INVALID_BITSTREAM on a frame whose CAPTURE buffer comes back with V4L2_BUF_FLAG_ERROR, as the V4L2 M2M decoder does. The frame is still output. On Cedrus (H616), an H.264 slice cut short (the driver flags that buffer ERROR) was output as a good frame with exit code 0; with fix 6 ffmpeg prints "corrupt decoded frame", and -xerror stops there. The VP9 suite, H.264, VP8 and HEVC decode as before. Not run on the AVD: its refused frames are reported only if the driver returns their CAPTURE buffer with the flag. Fix 6 carries Assisted-by: LLM like the others: I used an LLM while writing it; I reviewed and tested it myself.
fix6.patch
3.1 KiB
First-time contributor

@SomeComputerGuy I ran fix 6 on the M5's AVD. It applies with git am on v2 (e78bb59e7a) and builds. The AVD driver returns the CAPTURE buffer of a frame it refuses with V4L2_BUF_FLAG_ERROR, so these frames are reported now. After a failed frame, the driver also stops the stream ("restart streaming to retry"), and every later frame comes back with the flag as well.

Refused VP9 frames:

  • vp90-2-02-size-08x08 (sides below 64, which the AVD refuses): v2 outputs 10 frames with exit code 0 and no log. With fix 6, each of the 10 gets "Decode error on CAPTURE buffer N" and "corrupt decoded frame", and -xerror stops at the first.
  • libvpx VP9 suite, 304 4:2:0 vectors, per-frame md5 against libvpx: v2 and fix 6 both match 215. This kernel doesn't have the AVD resize fixes (https://github.com/aurora-silicon/linux/pull/2136, not merged yet), so the driver refuses the in-place resizes again. None of the 215 logs a decode error. In the failing vectors, the flagged frames are exactly the frames that differ from libvpx:
    • the 60 size vectors with a side below 64: 10 of 10 each;
    • the 24 resize_inter vectors: 20 of 30 each, from the first size change on;
    • 05-resize: 7 of 10.
  • Two vectors flag more frames than differ:
    • 18-resize flags 97 frames, and 58 differ. Nearly all refused 155x115 frames come out as the same image. 45 of the stream's own frames at that size are that image too, so 39 refused frames match libvpx by chance.
    • svc_1280x720_3 flags every output after the first.

H.264 slice cut short (your Cedrus case): a 720p High profile clip of 60 frames, with one slice cut to half its length:

Cut slice Frames that differ from software v2 Fix 6
IDR, frame 0 60 exit 0, no log 60 flagged
IDR, frame 30 30 (30–59) exit 0, no log 30 flagged
P, frame 31 29 (31–59) exit 0, no log 29 flagged

In the last two rows, the frames before the cut match software. On the AVD, the cut slice makes the firmware fail that frame. The driver then resets the decoder and stops the stream, so the rest of the clip is lost, where software decode conceals the slice and recovers at the next IDR. That's on the driver side; fix 6 now reports it.

No regressions: H.264, HEVC Main and Main10, VP9, AV1 and the 600-frame 4K60 H.264 clip, all with -xerror, match software bit for bit and print nothing on stderr, the same as with v2.

The code looks right to me. v4l2_request_wait_on_capture() releases ctx->mutex before returning, so post_process can take it again. Every DQBUF rewrites the error bit of its index, so a reused buffer doesn't carry an old error.

@SomeComputerGuy I ran fix 6 on the M5's AVD. It applies with `git am` on v2 (`e78bb59e7a`) and builds. The AVD driver returns the CAPTURE buffer of a frame it refuses with `V4L2_BUF_FLAG_ERROR`, so these frames are reported now. After a failed frame, the driver also stops the stream ("restart streaming to retry"), and every later frame comes back with the flag as well. **Refused VP9 frames:** - vp90-2-02-size-08x08 (sides below 64, which the AVD refuses): v2 outputs 10 frames with exit code 0 and no log. With fix 6, each of the 10 gets "Decode error on CAPTURE buffer N" and "corrupt decoded frame", and `-xerror` stops at the first. - libvpx VP9 suite, 304 4:2:0 vectors, per-frame md5 against libvpx: v2 and fix 6 both match 215. This kernel doesn't have the AVD resize fixes (https://github.com/aurora-silicon/linux/pull/2136, not merged yet), so the driver refuses the in-place resizes again. None of the 215 logs a decode error. In the failing vectors, the flagged frames are exactly the frames that differ from libvpx: - the 60 size vectors with a side below 64: 10 of 10 each; - the 24 resize_inter vectors: 20 of 30 each, from the first size change on; - 05-resize: 7 of 10. - Two vectors flag more frames than differ: - 18-resize flags 97 frames, and 58 differ. Nearly all refused 155x115 frames come out as the same image. 45 of the stream's own frames at that size are that image too, so 39 refused frames match libvpx by chance. - svc_1280x720_3 flags every output after the first. **H.264 slice cut short (your Cedrus case):** a 720p High profile clip of 60 frames, with one slice cut to half its length: | Cut slice | Frames that differ from software | v2 | Fix 6 | |---|---|---|---| | IDR, frame 0 | 60 | exit 0, no log | 60 flagged | | IDR, frame 30 | 30 (30–59) | exit 0, no log | 30 flagged | | P, frame 31 | 29 (31–59) | exit 0, no log | 29 flagged | In the last two rows, the frames before the cut match software. On the AVD, the cut slice makes the firmware fail that frame. The driver then resets the decoder and stops the stream, so the rest of the clip is lost, where software decode conceals the slice and recovers at the next IDR. That's on the driver side; fix 6 now reports it. **No regressions:** H.264, HEVC Main and Main10, VP9, AV1 and the 600-frame 4K60 H.264 clip, all with `-xerror`, match software bit for bit and print nothing on stderr, the same as with v2. The code looks right to me. `v4l2_request_wait_on_capture()` releases `ctx->mutex` before returning, so `post_process` can take it again. Every DQBUF rewrites the error bit of its index, so a reused buffer doesn't carry an old error.
First-time contributor

I ran into another bug in libavcodec/v4l2_request.c during zero-copy playback (mpv --hwdec=v4l2request with vo=gpu / OpenGL on Wayland):

Symptom: Playing a 720p24 H.264 clip produces brief single-frame glitches (flashes of stale/corrupted luma content). The decoder output itself is clean: ffmpeg -hwaccel v4l2request -vf hwdownload over 7,200 frames and mpv --hwdec=v4l2request-copy over 600 frames are bit-exact against software H.264.

Isolation:

  • --hwdec=v4l2request-copy: clean
  • --vd-queue-enable=no --hwdec-extra-frames=10 --framedrop=no: still glitches
  • --opengl-early-flush=yes or --opengl-glfinish=yes (or synchronous GPU submission in Mesa): clean

Root cause: hwcontext_v4l2request allocates CAPTURE buffers as V4L2_MEMORY_MMAP and exports them with VIDIOC_EXPBUF as AV_PIX_FMT_DRM_PRIME dma-bufs. With zero-copy GPU rendering (mpv defaults: opengl-early-flush=no, opengl-glfinish=no):

  1. draw_frame(N) records GL draws sampling dmabuf_N without flushing yet.
  2. flip_page(N) calls eglSwapBuffers(), which submits the GPU job asynchronously and attaches its implicit read fence to dmabuf_N's dma_resv.
  3. Immediately afterwards, draw_frame(N+1) unmaps the previous image and calls av_frame_unref(), returning dmabuf_N to FFmpeg's LIFO AVBufferPool.
  4. FFmpeg immediately picks dmabuf_N for the next decode and calls VIDIOC_QBUF.

Linux videobuf2 does not wait on dma_resv fences of exported V4L2_MEMORY_MMAP buffers on VIDIOC_QBUF. When the hardware decoder is fast enough (e.g. 720p takes <1 ms), it starts overwriting dmabuf_N while the GPU is still sampling it for frame N. (4K60 hid this because decode took long enough for the GPU read to finish first.)

This affects any V4L2 Request API driver used with a zero-copy GPU/display consumer, not just one driver.

Fix: Before reusing a CAPTURE buffer in ff_v4l2_request_start_frame(), poll each exported AVDRMFrameDescriptor object fd for POLLOUT. In Linux drivers/dma-buf/dma-buf.c (dma_buf_poll), POLLOUT waits on dma_resv_usage_rw(true) (both DMA_RESV_USAGE_READ and DMA_RESV_USAGE_WRITE fences), works on O_RDONLY fds returned by VIDIOC_EXPBUF, and returns immediately when no unsignaled fences are attached.

With the attached patch, playback with default mpv settings is completely glitch-free, and software-compare decode tests remain bit-exact. The patch applies cleanly on both pr20847-v2 and fix 6.

I ran into another bug in `libavcodec/v4l2_request.c` during zero-copy playback (`mpv --hwdec=v4l2request` with `vo=gpu` / OpenGL on Wayland): **Symptom:** Playing a 720p24 H.264 clip produces brief single-frame glitches (flashes of stale/corrupted luma content). The decoder output itself is clean: `ffmpeg -hwaccel v4l2request -vf hwdownload` over 7,200 frames and `mpv --hwdec=v4l2request-copy` over 600 frames are bit-exact against software H.264. **Isolation:** - `--hwdec=v4l2request-copy`: clean - `--vd-queue-enable=no --hwdec-extra-frames=10 --framedrop=no`: still glitches - `--opengl-early-flush=yes` or `--opengl-glfinish=yes` (or synchronous GPU submission in Mesa): clean **Root cause:** `hwcontext_v4l2request` allocates CAPTURE buffers as `V4L2_MEMORY_MMAP` and exports them with `VIDIOC_EXPBUF` as `AV_PIX_FMT_DRM_PRIME` dma-bufs. With zero-copy GPU rendering (`mpv` defaults: `opengl-early-flush=no`, `opengl-glfinish=no`): 1. `draw_frame(N)` records GL draws sampling `dmabuf_N` without flushing yet. 2. `flip_page(N)` calls `eglSwapBuffers()`, which submits the GPU job asynchronously and attaches its implicit read fence to `dmabuf_N`'s `dma_resv`. 3. Immediately afterwards, `draw_frame(N+1)` unmaps the previous image and calls `av_frame_unref()`, returning `dmabuf_N` to FFmpeg's LIFO `AVBufferPool`. 4. FFmpeg immediately picks `dmabuf_N` for the next decode and calls `VIDIOC_QBUF`. Linux `videobuf2` does not wait on `dma_resv` fences of exported `V4L2_MEMORY_MMAP` buffers on `VIDIOC_QBUF`. When the hardware decoder is fast enough (e.g. 720p takes <1 ms), it starts overwriting `dmabuf_N` while the GPU is still sampling it for frame `N`. (4K60 hid this because decode took long enough for the GPU read to finish first.) This affects any V4L2 Request API driver used with a zero-copy GPU/display consumer, not just one driver. **Fix:** Before reusing a CAPTURE buffer in `ff_v4l2_request_start_frame()`, poll each exported `AVDRMFrameDescriptor` object fd for `POLLOUT`. In Linux `drivers/dma-buf/dma-buf.c` (`dma_buf_poll`), `POLLOUT` waits on `dma_resv_usage_rw(true)` (both `DMA_RESV_USAGE_READ` and `DMA_RESV_USAGE_WRITE` fences), works on `O_RDONLY` fds returned by `VIDIOC_EXPBUF`, and returns immediately when no unsignaled fences are attached. With the attached patch, playback with default `mpv` settings is completely glitch-free, and software-compare decode tests remain bit-exact. The patch applies cleanly on both `pr20847-v2` and fix 6.
First-time contributor

Two fixes on top of 3ac4e07593, tested on RK3588 (VPU981) with the libaom vectors:

  1. avcodec/v4l2_request_av1: fill only the tiles of the current tile group. av1-1-b8-22-svc-L1T2 (three tile groups per frame) now matches.
  2. avcodec/v4l2_request_av1: take the frame size from the frame header. The 640x360 base layer of svc-L2T1/L2T2 was sent as 1280x720 and 8 of 16 frames timed out; both now match.

219 of 242 vectors match (216 before), no regressions. Superres not tested.

Developed with Claude (Anthropic) as a coding assistant; I reviewed and tested the changes.

Two fixes on top of 3ac4e07593, tested on RK3588 (VPU981) with the libaom vectors: 7. avcodec/v4l2_request_av1: fill only the tiles of the current tile group. av1-1-b8-22-svc-L1T2 (three tile groups per frame) now matches. 8. avcodec/v4l2_request_av1: take the frame size from the frame header. The 640x360 base layer of svc-L2T1/L2T2 was sent as 1280x720 and 8 of 16 frames timed out; both now match. 219 of 242 vectors match (216 before), no regressions. Superres not tested. Developed with Claude (Anthropic) as a coding assistant; I reviewed and tested the changes.
First-time contributor

@SomeComputerGuy I reviewed and tested both patches on Apple M5 AVD (3ac4e07593 + av1-fixes-pr20847.patch) against the 242 libaom vectors and SVT-AV1 superres clips. Both fixes look right, and testing on AVD turned up one related bug in v4l2_request_av1.c plus one edge case in fix 7.

libaom 242-vector suite on M5 AVD:

  • base (3ac4e07593): 234/242 match bit-exact.
  • base + fixes 7 & 8: 234/242 (no regressions), because AVD's tile validator rejects all three 3x1-tile SVC vectors (AV1: 3x1 tiles do not cover the 640x360 frame; before fix 8, svc-L2T1/L2T2 logged 1280x720, confirming fix 8 fixes the base-layer dimensions).
    • The reason AVD rejects them is a separate pre-existing bug in fill_frame(): ctrl->tile_info.mi_col_starts[i] and mi_row_starts[i] assign frame_header->tile_start_col_sb[i] / tile_start_row_sb[i] directly (superblock units) instead of shifting left by sb_shift (s->raw_seq->use_128x128_superblock ? 5 : 4) to 4x4 MI units as required by struct v4l2_av1_tile_info (the sentinel mi_col_starts[tile_cols] already uses MI units, and vulkan_av1.c shifts by sb_shift). VPU981 presumably only uses width_in_sbs_minus_1 / height_in_sbs_minus_1, which is why it didn't trip on RK3588.
  • base + << sb_shift only: 234/242 (the 3 SVC vectors still fail without fixes 7 & 8).
  • base + fixes 7 & 8 + << sb_shift: 237/242 match bit-exact — av1-1-b8-22-svc-L1T2, av1-1-b8-22-svc-L2T1, and av1-1-b8-22-svc-L2T2 all match software with zero regressions. (The remaining 5 are the 2 monochrome vectors unsupported by AVD, the 2 film-grain vectors, and av1-1-b8-03-sizeup without v2 dynamic resize.)

Superres (tested with SVT-AV1 on M5 AVD):

  • All-intra clips across every superres denominator 9..16 (each mixing use_superres=1 and use_superres=0 frames): 8/8 match software bit-exact with fix 8, confirming the (upscaled_width * AV1_SUPERRES_NUM + superres_denom / 2) / superres_denom width calculation.
  • Random-denominator multi-frame temporal-unit stream (superres-mode=2): base fails with EINVAL (AV1: 1x1 tiles do not cover the 569x360 frame) from the stale cbctx->frame_width; fix 8 eliminates that EINVAL.

Two small code-review notes:

  1. Fix 7 (malformed streams): cbs_av1's tile_group_obu() enforces tg_start >= priv->tile_num, not ==, so a malformed bitstream whose tile groups skip a tile index still reaches end_frame (s->tile_num == tg_end + 1). Because tile_group_entries is allocated with av_realloc_array() without zeroing, skipped slots will now contain uninitialized heap memory passed to V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY (previously the 0..N-1 loop overwrote every slot). Zero-initializing the newly allocated region avoids that.
  2. Fix 8 (minor nit): cbctx->num_planes is the only remaining cbctx read in fill_frame(); replacing it with s->raw_seq->color_config.mono_chrome ? 1 : 3 drops cbctx from fill_frame() completely.

Attached is a 2-patch follow-up on top of av1-fixes-pr20847.patch (pr20847-av1-followup.patch, verified on M5 AVD with zero compiler warnings, 237/242 libaom vectors and 8/8 superres denominators matching):

  1. avcodec/v4l2_request_av1: convert tile start offsets to 4x4 MI units
  2. avcodec/v4l2_request_av1: zero-initialize allocated tile group entries
@SomeComputerGuy I reviewed and tested both patches on Apple M5 AVD (`3ac4e07593` + `av1-fixes-pr20847.patch`) against the 242 libaom vectors and SVT-AV1 superres clips. Both fixes look right, and testing on AVD turned up one related bug in `v4l2_request_av1.c` plus one edge case in fix 7. **libaom 242-vector suite on M5 AVD:** - `base` (`3ac4e07593`): **234/242** match bit-exact. - `base` + fixes 7 & 8: **234/242** (no regressions), because AVD's tile validator rejects all three 3x1-tile SVC vectors (`AV1: 3x1 tiles do not cover the 640x360 frame`; before fix 8, `svc-L2T1`/`L2T2` logged `1280x720`, confirming fix 8 fixes the base-layer dimensions). - The reason AVD rejects them is a separate pre-existing bug in `fill_frame()`: `ctrl->tile_info.mi_col_starts[i]` and `mi_row_starts[i]` assign `frame_header->tile_start_col_sb[i]` / `tile_start_row_sb[i]` directly (superblock units) instead of shifting left by `sb_shift` (`s->raw_seq->use_128x128_superblock ? 5 : 4`) to 4x4 MI units as required by `struct v4l2_av1_tile_info` (the sentinel `mi_col_starts[tile_cols]` already uses MI units, and `vulkan_av1.c` shifts by `sb_shift`). VPU981 presumably only uses `width_in_sbs_minus_1` / `height_in_sbs_minus_1`, which is why it didn't trip on RK3588. - `base` + `<< sb_shift` only: **234/242** (the 3 SVC vectors still fail without fixes 7 & 8). - `base` + fixes 7 & 8 + `<< sb_shift`: **237/242** match bit-exact — `av1-1-b8-22-svc-L1T2`, `av1-1-b8-22-svc-L2T1`, and `av1-1-b8-22-svc-L2T2` all match software with zero regressions. (The remaining 5 are the 2 monochrome vectors unsupported by AVD, the 2 film-grain vectors, and `av1-1-b8-03-sizeup` without v2 dynamic resize.) **Superres (tested with SVT-AV1 on M5 AVD):** - All-intra clips across every superres denominator `9..16` (each mixing `use_superres=1` and `use_superres=0` frames): **8/8 match software bit-exact** with fix 8, confirming the `(upscaled_width * AV1_SUPERRES_NUM + superres_denom / 2) / superres_denom` width calculation. - Random-denominator multi-frame temporal-unit stream (`superres-mode=2`): `base` fails with `EINVAL` (`AV1: 1x1 tiles do not cover the 569x360 frame`) from the stale `cbctx->frame_width`; fix 8 eliminates that `EINVAL`. **Two small code-review notes:** 1. **Fix 7 (malformed streams):** `cbs_av1`'s `tile_group_obu()` enforces `tg_start >= priv->tile_num`, not `==`, so a malformed bitstream whose tile groups skip a tile index still reaches `end_frame` (`s->tile_num == tg_end + 1`). Because `tile_group_entries` is allocated with `av_realloc_array()` without zeroing, skipped slots will now contain uninitialized heap memory passed to `V4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY` (previously the `0..N-1` loop overwrote every slot). Zero-initializing the newly allocated region avoids that. 2. **Fix 8 (minor nit):** `cbctx->num_planes` is the only remaining `cbctx` read in `fill_frame()`; replacing it with `s->raw_seq->color_config.mono_chrome ? 1 : 3` drops `cbctx` from `fill_frame()` completely. Attached is a 2-patch follow-up on top of `av1-fixes-pr20847.patch` (`pr20847-av1-followup.patch`, verified on M5 AVD with zero compiler warnings, 237/242 libaom vectors and 8/8 superres denominators matching): 1. `avcodec/v4l2_request_av1: convert tile start offsets to 4x4 MI units` 2. `avcodec/v4l2_request_av1: zero-initialize allocated tile group entries`
All checks were successful
Lint / Pre-Commit (pull_request) Successful in 25s
Required
Details
Autolabel / Labeler (pull_request_target) Successful in 8s
Test / Fate (linux-aarch64, static, 64 bit) (pull_request) Successful in 11m32s
Required
Details
Test / Fate (linux-amd64, static, 32 bit) (pull_request) Successful in 11m55s
Required
Details
Test / Fate (linux-amd64, shared, 64 bit) (pull_request) Successful in 11m52s
Required
Details
Test / Fate (Full, wine) (pull_request) Successful in 26m50s
Required
Details
This pull request has changes conflicting with the target branch.
  • Changelog
  • configure
  • libavcodec/Makefile
  • libavcodec/av1dec.c
  • libavcodec/h264_slice.c
  • libavcodec/hevc/hevcdec.c
  • libavcodec/hwaccels.h
  • libavcodec/vp8.c
  • libavcodec/vp9.c
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u 'v4l2request-v3:Kwiboo-v4l2request-v3'
git switch 'Kwiboo-v4l2request-v3'
Sign in to join this conversation.
No reviewers
No milestone
No assignees
16 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
FFmpeg/FFmpeg!20847
No description provided.