Skip to content

v4l2 codec does not support V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME #3171

Closed

Description

@tmm1

Describe the bug
Using bcm2835-codec there is no way to force key frame generation

To reproduce
While using v4l2 encoder, send ioctl with V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME

Expected behaviour
Expect ioctl to succeed and i-frame to be generated.

Actual behaviour
ioctl fails

System

  • Which model of Raspberry Pi? e.g. Pi3B+, PiZeroW
    Pi3B+

  • Which OS and version (cat /etc/rpi-issue)?
    Raspberry Pi reference 2019-07-10
    Generated using pi-gen, https://github.com/RPi-Distro/pi-gen, 175dfb027ffabd4b8d5080097af0e51ed9a4a56c, stage2

  • Which firmware version (vcgencmd version)?
    Jul 9 2019 14:40:53
    Copyright (c) 2012 Broadcom
    version 6c3fe3f096a93de3b34252ad98cdccadeb534be2 (clean) (release) (start)

  • Which kernel version (uname -a)?
    Linux tmm1-pi 4.19.57-v7+ Rpi 4.4.y #1244 SMP Thu Jul 4 18:45:25 BST 2019 armv7l GNU/Linux

Additional context
Similar functionality is available via the OMX encoder using either OMX_IndexConfigBrcmVideoRequestIFrame or OMX_IndexConfigVideoIntraVOPRefresh

bcm2835_codec_s_ctrl() needs to have a V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME case statement added. See for example https://lkml.org/lkml/2016/1/19/24

cc @6by9

Activity

  1. 6by9 commented on Aug 22, 2019

    @6by9
    Contributor

    MMAL_PARAMETER_VIDEO_REQUEST_I_FRAME is the MMAL parameter.
    Pull Requests welcome - it won't be a high priority for me to fix.

    I'd expect the actual active bit to be something like:

    		u32 mmal_bool = 1;
    		ret = vchiq_mmal_port_parameter_set(ctx->dev->instance,
    						    &ctx->component->output[0],
    						    MMAL_PARAMETER_VIDEO_REQUEST_I_FRAME,
    						    &mmal_bool,
    						    sizeof(mmal_bool));
    

    Have you actually got some software which uses this V4L2 parameter? It's one of those annoying things that for this sort of patch it'll take longer to produce a test app to verify that it works than it does to make the change.

  2. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    Great, that's all I needed. I will open a PR. I am using ffmpeg's h264_v4l2m2m encoder to test and that's how I discovered this ioctl was failing.

    diff --git a/libavcodec/v4l2_m2m_enc.c b/libavcodec/v4l2_m2m_enc.c
    index 636e1a96dd..2d5f388cc1 100644
    --- a/libavcodec/v4l2_m2m_enc.c
    +++ b/libavcodec/v4l2_m2m_enc.c
    @@ -245,6 +245,9 @@ static int v4l2_send_frame(AVCodecContext *avctx, const AVFrame *frame)
         V4L2m2mContext *s = ((V4L2m2mPriv*)avctx->priv_data)->context;
         V4L2Context *const output = &s->output;
     
    +    if (frame->pict_type == AV_PICTURE_TYPE_I)
    +        v4l2_set_ext_ctrl(s, MPEG_CID(FORCE_KEY_FRAME), 0, "force key frame");
    +
         return ff_v4l2_context_enqueue_frame(output, frame);
     }
     
  3. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    Another issue I ran into is that the driver doesn't seem to advertise MPLANE support. This check in ffmpeg fails: https://github.com/FFmpeg/FFmpeg/blob/9bcb1cb6ed50e66e0489beb871eed83533b3de97/libavcodec/v4l2_m2m.c#L53

    And so ffmpeg only ends up sending the Y-plane from a YUV420P picture.

    Should I look into fixing the capabilities advertised, or is the correct fix to teach ffmpeg to pack the planes together before sending them into the driver?

  4. 6by9 commented on Aug 22, 2019

    @6by9
    Contributor

    Is that on the latest kernel tree?
    The original version of the driver supported the single planar API, but that was replaced by #3097 to use the multiplanar API (although still the single planar formats).
    https://github.com/raspberrypi/linux/blob/rpi-4.19.y/drivers/staging/vc04_services/bcm2835-codec/bcm2835-v4l2-codec.c#L2607 seems to say multi planar, as does

    pi@raspberrypi:~ $ v4l2-ctl -D -d 11
    Driver Info:
    	Driver name      : bcm2835-codec
    	Card type        : bcm2835-codec
    	Bus info         : platform:bcm2835-codec
    	Driver version   : 4.19.64
    	Capabilities     : 0x84204000
    		Video Memory-to-Memory Multiplanar
    		Streaming
    		Extended Pix Format
    		Device Capabilities
    	Device Caps      : 0x04204000
    		Video Memory-to-Memory Multiplanar
    		Streaming
    		Extended Pix Format
    

    There is an ffmpeg patch that should be in Raspbian to add support for NV21 and YUV420P - the standard code only had NV12 support. That causes some grief with the chroma planes not being setup
    Off my local branch:

    commit 4ced57196354736ea2f831fd012be69f7a01dc30
    Author: Dave Stevenson <dave.stevenson@raspberrypi.org>
    Date:   Thu Jul 4 17:50:13 2019 +0100
    
        avcodec: v4l2_m2m: Support NV21 and YUV420P
        
        The single planar support was for NV21 only.
        Add NV21 and YUV420P support.
    
    diff --git a/libavcodec/v4l2_buffers.c b/libavcodec/v4l2_buffers.c
    index aef911f3bb..1934ff9377 100644
    --- a/libavcodec/v4l2_buffers.c
    +++ b/libavcodec/v4l2_buffers.c
    @@ -321,11 +321,21 @@ int ff_v4l2_buffer_buf_to_avframe(AVFrame *frame, V4L2Buffer *avbuf)
         /* 1.1 fixup special cases */
         switch (avbuf->context->av_pix_fmt) {
         case AV_PIX_FMT_NV12:
    +    case AV_PIX_FMT_NV21:
             if (avbuf->num_planes > 1)
                 break;
             frame->linesize[1] = avbuf->plane_info[0].bytesperline;
             frame->data[1] = frame->buf[0]->data + avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height;
             break;
    +    case AV_PIX_FMT_YUV420P:
    +    /* No YV12? support? */
    +        if (avbuf->num_planes > 1)
    +            break;
    +        frame->linesize[1] = avbuf->plane_info[0].bytesperline >> 1;
    +        frame->linesize[2] = avbuf->plane_info[0].bytesperline >> 1;
    +        frame->data[1] = frame->buf[0]->data + avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height;
    +        frame->data[2] = frame->data[1] + ((avbuf->plane_info[0].bytesperline * avbuf->context->format.fmt.pix_mp.height) >> 2);
    +        break;
         default:
             break;
         }
    
  5. 6by9 commented on Aug 22, 2019

    @6by9
    Contributor

    Oh, hang on, you're looking at encode, not decode.

    V4L2 dictates how the formats should be packed or the single planar formats.
    It does look like ff_v4l2_buffer_avframe_to_buf assumes that if the avframe is multiple planes then it doesn't check the pixel format nor the correct number of planes, ie the reverse conversion to that done in ff_v4l2_buffer_buf_to_avframe
    https://github.com/FFmpeg/FFmpeg/blob/9bcb1cb6ed50e66e0489beb871eed83533b3de97/libavcodec/v4l2_buffers.c#L289

    As a quick test, try reverting the patches I referenced from #3097 to see if it plays nicely with the single planar API. I have a suspicion that it won't, and yes FFmpeg should be munging the buffer pointers/sizes, having first confirmed that the planes are contiguous.

  6. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    replaced by #3097 to use the multiplanar API (although still the single planar formats)

    Wonderful, thanks for the link. I am on the stable release and v4l2-ctl wasn't showing mplane support.

    I will build tip and try again.

    ffmpeg patch that should be in Raspbian to add support for NV21 and YUV420P - the standard code only had NV12 support

    I did try this patch, but it only affects AVFrame generation (i.e decoding). I'm working with the encoder which doesn't use this code path.

    Would you mind dropping the comment and sending a copy of this to ffmpeg-devel? I will merge it into ffmpeg master.

  7. 6by9 commented on Aug 22, 2019

    @6by9
    Contributor

    sudo rpi-update will grab the latest kernel with this change to save you rebuilding your own kernel.

    I'm not sure where/when you were hitting the issue with not supporting MPLANE. On failure v4l2_prepare_contexts should have then checked for single plane and been happy. It will still go wrong as there is the missing mapping for single planar formats, but fundamentally it is correct.
    https://github.com/FFmpeg/FFmpeg/blob/9bcb1cb6ed50e66e0489beb871eed83533b3de97/libavcodec/v4l2_m2m.c#L81

    The question over single planar vs multi planar, and the use of single planar formats through the multi planar API, was brought up in discussing #3097 and had been discussed on linux-media
    https://www.spinics.net/lists/linux-media/msg154053.html
    Cedrus for one also uses the single planar API, therefore having support for the single planar formats in FFmpeg would be sensible.

    I'll try to sort out the decode YUV420/NV21 patch at some point.
    Sorry, but we've found ffmpeg-devel not the most welcoming or helpful of places.
    The bugtracker also seems to be a dead end. I opened a ticket 7 months ago for an omx issue, with a proposed patch to fix it, and got no response beyond "isn't this a duplicate" (it wasn't) https://trac.ffmpeg.org/ticket/7687.
    I guess it depends on the relevant people seeing messages.

  8. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    sudo rpi-update will grab the latest kernel with this change to save you rebuilding your own kernel.

    Thanks that's very helpful.

    I'm not sure where/when you were hitting the issue with not supporting MPLANE.

    Sorry I should have been more specific. There were no errors- it worked in single plane mode, but since only the Y-plane was sent to the encoder the generate picture was not color correct. I thought maybe if the driver supported mplane then the picture would get uploaded correctly. I will try that after rpi-update completes.

    I'll try to sort out the decode YUV420/NV21 patch at some point.
    Sorry, but we've found ffmpeg-devel not the most welcoming or helpful of places.

    Your experience is not uncommon.

    I opened a ticket 7 months ago for an omx issue, with a proposed patch to fix it, and got no response beyond "isn't this a duplicate" (it wasn't) https://trac.ffmpeg.org/ticket/7687.

    It seems the omx driver is pretty much unmaintained. I will be happy to add myself as the maintainer of omx.c and merge any relevant patches to improve RPi support.

  9. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    After rpi-update, I can confirm v4l2-ctl shows "Multiplanar" support.

    The behavior on ffmpeg's side is still the same- the images generated by the encoder are missing chroma. I will work on a patch to convert to V4L's requested pixel format. How does V4L signal that it wants packed planes?

  10. 6by9 commented on Aug 22, 2019

    @6by9
    Contributor

    How does V4L signal that it wants packed planes?

    https://www.linuxtv.org/downloads/v4l-dvb-apis-new/uapi/v4l/yuv-formats.html
    V4L2_PIX_FMT_YUV420 vs V4L2_PIX_FMT_YUV420M
    V4L2_PIX_FMT_NV12 vs V4L2_PIX_FMT_NV12M
    etc
    The device will enumerate the formats that it supports via ioctl(VIDIOC_ENUM_FMT), and allow selection via VIDIOC_S_FMT. If the format passed into S_FMT isn't supported then the driver will select some form of default (it does NOT fail the S_FMT call).
    https://www.linuxtv.org/downloads/v4l-dvb-apis-new/uapi/v4l/vidioc-enum-fmt.html#vidioc-enum-fmt

    Thanks for looking at my issue in the bug tracker. I can fully relate to things dropping to being unmaintained as people get bored, but I had hoped that it might have had some traction seeing as I had provided a fix for it.

  11. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    Thanks. I'm new to v4l2 so I appreciate the pointers.

    BTW, one thing I'm interested in adding to ffmpeg is accelerated scaling on the RPi.

    It looks like using "OMX.broadcom.resize" from avcodec/omx.c would be fairly straightfoward (although ffmpeg-devel would probably prefer if I wrote a separate avfilter/vf_scale_omx.c instead).

    But I'm curious what you think about adding the resize component to the v4l2 driver? (I saw /dev/video12 exposes ISP already, but it's unclear to me if I can use the second downscaling output port reasonably from v4l2).

  12. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    How does V4L signal that it wants packed planes?

    https://www.linuxtv.org/downloads/v4l-dvb-apis-new/uapi/v4l/yuv-formats.html
    V4L2_PIX_FMT_YUV420 vs V4L2_PIX_FMT_YUV420M

    I was able to teach ff_v4l2_buffer_avframe_to_buf about contiguous planar formats. However the each chroma in the encoded picture is offset. I assume there is some sort of padding requirement?

  13. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    I was able to teach ff_v4l2_buffer_avframe_to_buf about contiguous planar formats. However the each chroma in the encoded picture is offset. I assume there is some sort of padding requirement?

    ffmpeg's AVFrame had some padding, but it didn't match the padding expected by v4l2. I got this working and have submitted a patchset to ffmpeg-devel: http://ffmpeg.org/pipermail/ffmpeg-devel/2019-August/248775.html

    The change to ff_v4l2_buffer_avframe_to_buf specifically is in tmm1/FFmpeg@55380ac

    I also included your NV21/YUV420P decoding patch in my set.

  14. tmm1 commented on Aug 22, 2019

    @tmm1
    Author

    I'm getting random failures starting up the h264 encoder sometimes:

    [h264_v4l2m2m @ 0x28bda20] Using device /dev/video11
    [h264_v4l2m2m @ 0x28bda20] driver 'bcm2835-codec' on card 'bcm2835-codec' in mplane mode
    [h264_v4l2m2m @ 0x28bda20] requesting formats: output=YU12 capture=H264
    [h264_v4l2m2m @ 0x28bda20] output VIDIOC_REQBUFS failed: Cannot allocate memory
    [h264_v4l2m2m @ 0x28bda20] no v4l2 output context's buffers
    

    dmesg shows:

    [12205.119574] cma: cma_alloc: alloc failed, req-size: 765 pages, ret: -12
    [12205.119590] bcm2835-codec bcm2835-codec: dma_alloc_coherent of size 3133440 failed
    [12205.121366] cma: cma_alloc: alloc failed, req-size: 192 pages, ret: -12
    [12205.121375] bcm2835-codec bcm2835-codec: dma_alloc_coherent of size 786432 failed
    
  15. 6by9 commented on Aug 23, 2019

    @6by9
    Contributor

    It looks like using "OMX.broadcom.resize" from avcodec/omx.c would be fairly straightfoward (although ffmpeg-devel would probably prefer if I wrote a separate avfilter/vf_scale_omx.c instead).

    But I'm curious what you think about adding the resize component to the v4l2 driver? (I saw /dev/video12 exposes ISP already, but it's unclear to me if I can use the second downscaling output port reasonably from v4l2).

    /dev/video12 will happily rescale images for you using the ISP hardware block. GStreamer will happily use it via the v4l2convert component.
    OMX.broadcom.resize is done on the VPU (generic SIMD processor within the GPU). More power required, and slower. I see little point in exposing that via V4L2.

    Also note that the V4L2 M2M devices are set up to support dmabuf import and export, therefore can do zero copy paths around the place. This is something that has limited support in FFmpeg, but is used by GStreamer effectively. A pipeline of v4l2src to v4l2h264enc with zero copy should achieve 1080p30 easily, and potentially 1080p50.
    The OMX framework will always end up copying all buffers to and from GPU memory, therefore the performance is lower.

    I'm getting random failures starting up the h264 encoder sometimes:
    [12205.121366] cma: cma_alloc: alloc failed, req-size: 192 pages, ret: -12
    [12205.121375] bcm2835-codec bcm2835-codec: dma_alloc_coherent of size 786432 failed

    So V4L2 is using the kernel CMA heap for all allocations instead of gpu_mem (although there is still some requirement for gpu_mem).
    The default size of the cma heap on Pi0-3 is generally fairly small, unless you are using vc4-fkms-v3d or vc4-kms-v3d for 3D and rendering, in which case the heap is increased to 256MB.
    vc4-fkms-v3d is the default on Pi4 as there is no firmware GL driver, therefore it is generally 256MB.
    GL and DRM/KMS are the main reason the V4L2 drivers were written as it moves towards the Linux standard APIs for things like Kodi, and they are looking at removing as much platform specific stuff as possible.
    Add cma=128M to /boot/cmdline.txt to define the heap to be 128MB

    Padding is controlled via a combination of bytesperline, and the selection API. No padding is allowed between the planes for the single planar format. I'll check what you've done in your patch.

  16. 118 remaining items

  17. added 2 commits that reference this issue on Sep 1, 2020
    684a288
    7b81381
  18. added 2 commits that reference this issue on Sep 11, 2020
    f4ecb61
    762ef75
  19. added 3 commits that reference this issue on Sep 28, 2020
    ddd3693
    9b881ec
    a83af88
  20. added 2 commits that reference this issue on Oct 16, 2020
    881f514
    304f637
  21. added a commit that references this issue on Nov 4, 2020
    0d460a3
  22. qwertzui11 commented on Mar 29, 2021

    @qwertzui11

    Hi

    I'm trying to integrate the v4l2 with hardware encoding into googles c++ webrtc implementation. Which works great! However for a clean implementation I'd like to trigger an i-frame. I do it like:

    v4l2_control control;
    CLEAR(control);
    control.id = V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME;
    control.value = 1;
    ioctl(fd, VIDIOC_S_CTRL, &control);

    the ioctl call results in the error: Invalid argument.
    Any idea what I'm doing wrong?

    hw: rpi4
    camera: v2.1

    > cat /etc/rpi-issue
    Raspberry Pi reference 2021-01-11
    Generated using pi-gen, https://github.com/RPi-Distro/pi-gen, 21090519d85bdaa1615d5d5057d37b09368ea5d2, stage2
    > vcgencmd version
    Mar 26 2021 16:34:17
    Copyright (c) 2012 Broadcom
    version edf2e9c318863999c97c50cdb74eee235ede3af5 (clean) (release) (start_x)
    > uname -a
    Linux fubble 5.10.25-v7l+ #1408 SMP Mon Mar 22 12:49:24 GMT 2021 armv7l GNU/Linux
    
    
  23. 6by9 commented on Mar 29, 2021

    @6by9
    Contributor

    You're better off creating a new issue rather than commenting on a closed one, or use the forums.

    Please confirm you are talking about using the V4L2 M2M encoder (generally /dev/video11) and not the camera driver (normally /dev/video0).

  24. qwertzui11 commented on Mar 29, 2021

    @qwertzui11

    Thanks for the quick response, and the hint! I'm talking about the camera driver /dev/video0.

  25. 6by9 commented on Mar 29, 2021

    @6by9
    Contributor

    Not this issue then. This was adding V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME to the M2M encoder (/dev/video11).

    v4l2-ctl --list-ctrls would have told you that force-key-frame was not supported on /dev/video0.

    Adding it isn't too involved, but won't be immediate.

  26. qwertzui11 commented on Mar 29, 2021

    @qwertzui11

    Ah, oh! Thx for the feedback! and quick response!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions