WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC, VP8, VP9 and AV1 #20847
Labels
No labels
avcodec
avdevice
avfilter
avformat
avutil
backport/release/4.3
backport/release/4.4
backport/release/5.0
backport/release/5.1
backport/release/6.0
backport/release/6.1
backport/release/7.0
backport/release/7.1
backport/release/8.0
backport/release/8.1
backport/release/9.0
backport/release/9.1
CLI
doc
Forgejo Fairy
swresample
swscale
vulkan
API
API major
bug
enhancement
fix/bug
fix/regression
GSoC
GSoC-Qualification
help wanted
important
LGTM
meta
needs backport
needs docs
needs fate test
needs info
needs sample
needs testing
new
question
regression
repro
flaky
repro
no
repro
no(env)
repro
yes
resolution
duplicate
resolution
external
resolution
fixed
resolution
invalid
resolution
wontfix
security
small
No milestone
No assignees
16 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
FFmpeg/FFmpeg!20847
Loading…
Reference in a new issue
No description provided.
Delete branch "Kwiboo/FFmpeg:v4l2request-v3"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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/media1parameter.(temporary not implemented during refactoring)
Compared to v2 this only includes support for
V4L2_PIX_FMTs that hasbeen merged into mainline Linux. As a result, this version cannot be
tested with the downstream
rpividdriver on Raspberry Pi or usingAFBC 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 requireslibdrmandlibudevfor the hwaccels to be enabled and successfully built.This can then be runtime tested on multiple Allwinner and Rockchip
devices.
This series has been tested with
cedrusdriver on Allwinner H6,hantroand
rkvdecdriver on Rockchip RK3399.It should be possible to playback video using
kodi-gbmandmpv(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.
SupportV4L2_PIX_FMTs used by pending rpi-hevc-dec driver.V4L2_PIX_FMTs used bymtk-vcodec-decdriver.not reporting support for current profile and level.
Estimate max output buffer size used for bitstream data instead ofusing a fixed value.
@ -284,6 +284,7 @@ Hardware acceleration:d3d12va* Wu Jianhuad3d12va_encode* Tong Wumediacodec* Matthieu Bouron, Aman Gupta, Zhao Zhiliv4l2_request* [2] Jonas Karlman (CC [email protected])By adding yourself to this file you're requesting push access. Is this what you'd like?
This was something I added before the move to forgejo, the line in CODEOWNERS should probably be good enough, I will drop this, thanks.
@ -0,0 +36,4 @@* Defaults to -1 for auto-detect.*/int media_fd;} AVV4L2RequestDeviceContext;Can't you extend hwcontext_drm instead? You're already using its frame structure.
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_PRIMEoutput 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 neededwhile (atomic_load(&ctx->queued_request) & (1 << output->index)) {int ret = poll(&pollfd, 1, 2000);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.
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
ioctlandselect/pollinterface 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.
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?
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_processmay not be protected byhwaccel_mutexand 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_SAFEflag, I still do not fully understand the impact of using or not using this flag.Running
ffmpegcmd to test decoding seem to produce consistentmd5checksum for conformance test videos with current changes and the use ofHWACCEL_CAP_ASYNC_SAFEflag. I will also run rendering tests usingkodi-gbmandmpvto inspect video rendering.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?
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_sliceorend_framewithout waiting for the request to complete and instead wait for it to complete inpost_processjust 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.I looked at the code, and you could enable HWACCEL_CAP_ASYNC_SAFE, though there are modifications you'd need to make.
FFHWAccel.initcallback 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 anFFHWAccel.update_thread_contextcallback to propagate the shared context, as well as any flags needed to all other threads. Take a look at whatlibavcodec/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 did a test with
HWACCEL_CAP_ASYNC_SAFEand it looks like theV4L2RequestContext/hwaccel_priv_datacurrently is shared among the thread uniqueAVCodecContext. Also theFFHWAccel.initis 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 untilpost_process(or when a target capture.index is being reused for a frame).Did you actually use multiple threads?
I used
-threads 4and can see 5 differentpthread_selfvalues in the log, so I am expecting 4 threads are used for hwaccel decoding and the last one is forpost_processrelated calls.73b6aee53acbda6037d9@ -0,0 +342,4 @@{V4L2RequestContext *ctx = v4l2_request_context(avctx);int ret;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.
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_minus8andchroma_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.
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,Could you implement support for .transfer_data_to?
It makes debugging easier.
The v4l2 capture buffers are exported as
O_RDONLY, could that have an impact on how atransfer_data_toshould work?What use cases and debugging will
transfer_data_tohelp enable?I have only tested
transfer_data_fromusinghwdownloadas part of using fluster where fluster will run something like following: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,You can expose this as .map_frame in the context, couldn't you?
Sure and thanks!, I have implemented the
map_fromops for read and could with help of that usehwmapinstead ofhwdownloadwith fluster to produce the same MD5 value.@ -0,0 +33,4 @@/*** File descriptor of media device.** Defaults to -1 for auto-detect.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."
Thanks, I have changed this to
Set to -1 for auto-detection.@ -0,0 +503,4 @@// TODO: estimate max buffer size instead of using a fixed valuectx->base.post_probe = v4l2_request_h264_post_probe;return ff_v4l2_request_init(avctx, V4L2_PIX_FMT_H264_SLICE,4 * 1024 * 1024,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).
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.
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.
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 neededWhen needed? But the code suggests its always 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));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.
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
cedrusdriver, a slice based decoder, that is using theV4L2_CID_STATELESS_HEVC_ENTRY_POINT_OFFSETScontrol 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 neededwhile (atomic_load(&ctx->queued_capture) & (1 << capture->index)) {int ret = poll(&pollfd, 1, 2000);Why 2 seconds?
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.
This will only be exceeded if the decoder crashed, right?
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.
cbda6037d9bdd832311e@ -0,0 +369,4 @@if (ret < 0)goto fail;}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().
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)Shouldn't be the other way around? Better yet, just remove it as av_frame_copy() does same check anyway.
That does seem more logical, however this matches what
drm,vaapiandvideotoolboxis 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[] = {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.
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.
@Kwiboo wrote in #20847 (comment):
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?
@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.
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
@kierank wrote in #20847 (comment):
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.
See August 2024 (v2) 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,I guess that should be
PROT_READinstead ofAV_HWFRAME_MAP_READ(values match, but we should use mmap's own flags here)Thanks!, this has now been fixed.
bdd832311e512c1b22d1512c1b22d102a6f4895102a6f4895132dc05a59332dc05a593d31e6c3707d31e6c3707b3355891cd@ -61,6 +61,7 @@ libavcodec/.*siren.* @lynnelibavcodec/smpte_436m.* @programmerjakelibavcodec/svq1.* @prosslibavcodec/svq3.* @prosslibavcodec/v4l2_request.* @Kwiboo@jernej @knaerzche should I also add your usernames to the
CODEOWNERSfile?sure, I can help with maintaining
sure
I have now added you both to the
CODEOWNERSfile, should hopefully mean we all get review pings when files are touched in future PRs.@ -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) {@knaerzche @jernej I have changed this to now only check min/max instead of the strict
step_width/heightcheck.The provided
coded_width/heightis 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.
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
hantroon a Rockchip RK3588 board the driver report min=48x48 max=3840x2160 step=16x16, and for a test video:Here we cannot have a strict
step_width/heightcheck, theAVCodecParserContextseem to report 16 aligned coded size (176x144) however not the coded size (175x143) from theAVCodecContextthat reachesv4l2_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.
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.
@Kwiboo wrote in #20847 (comment):
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)
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?
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
hantroand re-read the Linux documentation it is still ambiguous to me as to what the driver should provide. And if I am not mistaken thecedrusdriver do not even implement the enum ops.As @Lynne pointed out the
coded_width/heightis 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;If these are supposed to be adjusting for max DPB size, shouldn't we be using 16 for H.264/HEVC?
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.
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.
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.
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.
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_sizestill 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_sizeused here.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 duringinit.@ -0,0 +422,4 @@ctx->media_fd = -1;ctx->video_fd = -1;// Try to use media device file descriptor opened and owned by hwdeviceTry to use? If it's not usable, you should error out.
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 hwdeviceif (hwctx) {hwctx->media_fd = ctx->media_fd;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.
Good to know, thanks, the idea was to update the
AVV4L2RequestDeviceContextwith 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
AVV4L2RequestDeviceContextusingmedia_fd = -1(auto-detection)?I have now dropped this
hwctx->media_fdassignment.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 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.
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 deviceAre 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.
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
runops.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.
Can't you open FDs to all video devices in the context?
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
hantroip block intended for jpeg decoding/encoding and a differentrkvdecip block intended for h264/hevc/vp9 decoding. However thehantroip 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.
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.
Applications will typically not know what media device to use, unless they also implement similar probing and format testing of media and video devices.
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.
I think doing a single enumeration of available devices is wanted indeed. The recommended way for the stateless decoders is:
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'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 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'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.
@Lynne wrote in #20847 (comment):
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 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.
b3355891cd13b83cc55f13b83cc55fda1d1bd0c7da1d1bd0c75225fa694a5225fa694a1ad9435f37Could you point out where the check for whether the codec is supported is done?
@ -0,0 +756,4 @@// Start streaming on OUTPUT queuetype = ctx->fctxi->output.format.type;if (ioctl(ctx->fctxi->video_fd, VIDIOC_STREAMON, &type) < 0) {Would there be issues doing this? You would potentially be calling ioctl multiple times on the same FD when running multiple decoders.
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/videoXdevice isopen(), so we must open the video device for each decoding / frames context, trying todup()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;Could this go into a
AVV4L2RequestDeviceContext?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:
@ -0,0 +53,4 @@/*** V4L2 buffer capabilities flags.*/uint32_t capabilities;format and capabilities sound like they definitely should be public, in
AVV4L2RequestFramesContext.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;Could you move this to
V4L2RequestContext?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.
@Lynne wrote in #20847 (comment):
AVV4L2RequestFramesContext.pixelformatis set to the coded pixel format, e.g.V4L2_PIX_FMT_H264_SLICEorV4L2_PIX_FMT_HEVC_SLICE, from hwaccelframe_paramsops.This is then checked against the pixel formats the OUTPUT queue report is supported by
/dev/videoXdevices usingVIDIOC_ENUM_FMTinv4l2request_try_format()and finally usingVIDIOC_S_FMTinv4l2request_set_format()called fromv4l2request_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 toV4L2RequestDeviceContext.decodersalong with the supported coded pixel formats in thedevice_createops. If thedevice/optsis 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.WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC and VP8to WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC, VP8 and VP953a8df8a5823d9e0232523d9e02325f6683d4930f6683d493024658b926bWIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC, VP8 and VP9to WIP: Add V4L2 Request API hwaccels for MPEG2, H.264, HEVC, VP8, VP9 and AV124658b926ba0e7a2f0bea0e7a2f0bece1db52c00ce1db52c00ea34873176This PR has now been updated to also include hwaccels for VP9 and AV1.
It also got a small
configurefix for alibavutillinking issue due to missing-udevafter device probing code was moved from lavc to lavu.ea34873176eea5530b31@ -0,0 +741,4 @@AVBufferRef *ref;uint8_t *data;data = av_mallocz(size);This allocation is leaked by
v4l2request_frame_free().Thanks!, fixed in a recent rebase/force push.
eea5530b314236d2aef24236d2aef24beeac7298Hello, what’s current status of this PR?
4beeac72985c5ae56db75c5ae56db7068725826f068725826f3ac4e07593This has now been updated to include support for the mainline (and rpi-6.18.y) Raspberry Pi HEVC decoder.
Recent changes include:
NV12MT_COL128andNV12MT_10_COL128V4L2 pixel formatsLooking into adding support for
V4L2_PIX_FMTs used by themtk-vcodec-decdriver it has become apparent that a newAVPixelFormatis 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 thedrm_primepix fmt.@Kwiboo wrote in #20847 (comment):
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?)
@4-Qbit wrote in #20847 (comment):
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.
@chewitt wrote in #20847 (comment):
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) {I think this should be
>= 0, same as thevideo_fdcheck right above it. As-is, this tries toclose(-1)whenmedia_fdis 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;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_logatAV_LOG_VERBOSEhere explaining why transfer isn't supported for the format.@ -0,0 +582,4 @@output->request_fd = -1;}// Umap the OUTPUT buffer memorynit:
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 specifiedThe 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 v4l2requestis a no-op. I understand this is WIP, but it's worth thinking about what the minimum viabledevice_createlooks like before dropping the WIP tag. Even just accepting a/dev/mediaNpath 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,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.
Ping.
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 :)
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:
Symptom:
The HEVC hwaccel path finds
/dev/video19(driverrpi-hevc-dec) and passes the mem2mem capability check, but fails shortly after: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!
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 :)
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:
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.
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.
(1 << index on a 64-bit mask).
session (VIDIOC_REMOVE_BUFS), and
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 LLMwhile writing them; I reviewed and tested them myself and can answer
questions on them.
Arun
@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=96to decode ahead through 4K60 H.264 bitrate bursts, so the pool grows to about 110 CAPTURE buffers.Symptom:
queued_captureis auint64_t, but1 << indexis 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.@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.
@SomeComputerGuy I tested v2 on the Apple M5. It applies cleanly with
git amon3ac4e07593, 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 noVIDIOC_REMOVE_BUFS.Fix 3, indices >= 64:
-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.--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).VIDIOC_CREATE_BUFSfails 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;
3ac4e07593decodes them without references instead. The check is the same as rkvdec'svalidate_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:
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_FMTclamps 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 atV4L2_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.@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.
@SomeComputerGuy I ran fix 6 on the M5's AVD. It applies with
git amon v2 (e78bb59e7a) and builds. The AVD driver returns the CAPTURE buffer of a frame it refuses withV4L2_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:
-xerrorstops at 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:
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()releasesctx->mutexbefore returning, sopost_processcan take it again. Every DQBUF rewrites the error bit of its index, so a reused buffer doesn't carry an old error.I ran into another bug in
libavcodec/v4l2_request.cduring zero-copy playback (mpv --hwdec=v4l2requestwithvo=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 hwdownloadover 7,200 frames andmpv --hwdec=v4l2request-copyover 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=yesor--opengl-glfinish=yes(or synchronous GPU submission in Mesa): cleanRoot cause:
hwcontext_v4l2requestallocates CAPTURE buffers asV4L2_MEMORY_MMAPand exports them withVIDIOC_EXPBUFasAV_PIX_FMT_DRM_PRIMEdma-bufs. With zero-copy GPU rendering (mpvdefaults:opengl-early-flush=no,opengl-glfinish=no):draw_frame(N)records GL draws samplingdmabuf_Nwithout flushing yet.flip_page(N)callseglSwapBuffers(), which submits the GPU job asynchronously and attaches its implicit read fence todmabuf_N'sdma_resv.draw_frame(N+1)unmaps the previous image and callsav_frame_unref(), returningdmabuf_Nto FFmpeg's LIFOAVBufferPool.dmabuf_Nfor the next decode and callsVIDIOC_QBUF.Linux
videobuf2does not wait ondma_resvfences of exportedV4L2_MEMORY_MMAPbuffers onVIDIOC_QBUF. When the hardware decoder is fast enough (e.g. 720p takes <1 ms), it starts overwritingdmabuf_Nwhile the GPU is still sampling it for frameN. (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 exportedAVDRMFrameDescriptorobject fd forPOLLOUT. In Linuxdrivers/dma-buf/dma-buf.c(dma_buf_poll),POLLOUTwaits ondma_resv_usage_rw(true)(bothDMA_RESV_USAGE_READandDMA_RESV_USAGE_WRITEfences), works onO_RDONLYfds returned byVIDIOC_EXPBUF, and returns immediately when no unsignaled fences are attached.With the attached patch, playback with default
mpvsettings is completely glitch-free, and software-compare decode tests remain bit-exact. The patch applies cleanly on bothpr20847-v2and fix 6.Two fixes on top of
3ac4e07593, tested on RK3588 (VPU981) with the libaom vectors: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.
@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 inv4l2_request_av1.cplus 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/L2T2logged1280x720, confirming fix 8 fixes the base-layer dimensions).fill_frame():ctrl->tile_info.mi_col_starts[i]andmi_row_starts[i]assignframe_header->tile_start_col_sb[i]/tile_start_row_sb[i]directly (superblock units) instead of shifting left bysb_shift(s->raw_seq->use_128x128_superblock ? 5 : 4) to 4x4 MI units as required bystruct v4l2_av1_tile_info(the sentinelmi_col_starts[tile_cols]already uses MI units, andvulkan_av1.cshifts bysb_shift). VPU981 presumably only useswidth_in_sbs_minus_1/height_in_sbs_minus_1, which is why it didn't trip on RK3588.base+<< sb_shiftonly: 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, andav1-1-b8-22-svc-L2T2all match software with zero regressions. (The remaining 5 are the 2 monochrome vectors unsupported by AVD, the 2 film-grain vectors, andav1-1-b8-03-sizeupwithout v2 dynamic resize.)Superres (tested with SVT-AV1 on M5 AVD):
9..16(each mixinguse_superres=1anduse_superres=0frames): 8/8 match software bit-exact with fix 8, confirming the(upscaled_width * AV1_SUPERRES_NUM + superres_denom / 2) / superres_denomwidth calculation.superres-mode=2):basefails withEINVAL(AV1: 1x1 tiles do not cover the 569x360 frame) from the stalecbctx->frame_width; fix 8 eliminates thatEINVAL.Two small code-review notes:
cbs_av1'stile_group_obu()enforcestg_start >= priv->tile_num, not==, so a malformed bitstream whose tile groups skip a tile index still reachesend_frame(s->tile_num == tg_end + 1). Becausetile_group_entriesis allocated withav_realloc_array()without zeroing, skipped slots will now contain uninitialized heap memory passed toV4L2_CID_STATELESS_AV1_TILE_GROUP_ENTRY(previously the0..N-1loop overwrote every slot). Zero-initializing the newly allocated region avoids that.cbctx->num_planesis the only remainingcbctxread infill_frame(); replacing it withs->raw_seq->color_config.mono_chrome ? 1 : 3dropscbctxfromfill_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):avcodec/v4l2_request_av1: convert tile start offsets to 4x4 MI unitsavcodec/v4l2_request_av1: zero-initialize allocated tile group entriesView 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.