From 934e6b6e31f38c0301542448947fbc6cc0d261d3 Mon Sep 17 00:00:00 2001 From: Mark Harfouche Date: Sat, 21 Nov 2026 18:54:54 -0500 Subject: [PATCH 1/3] Pick a decoder that supports the requested hwaccel device
Claude's draft av.open(path, hwaccel=...) always used avcodec_find_decoder(), which returns the first decoder registered for a codec. For AV1 that is libdav1d when FFmpeg is built with it, and libdav1d has no hardware configs, so the stream was decoded in software, or the open failed with "Hardware accelerated decode requested but no stream is compatible" when allow_software_fallback is False. When a hwaccel is given and the default decoder cannot use its device type, look for another decoder of the same codec that can. The default is still preferred, so nothing changes for codecs whose default decoder already supports the device. That alone is not enough for AV1. The decoder context was given the hardware pixel format before it was opened, and FFmpeg's AV1 decoder treats a context that already holds a hardware format as one whose hwaccel is set up: it skips get_format(), never initialises the hwaccel, and fails on the first packet with "get_buffer() failed". Stop setting pix_fmt up front and let the decoder negotiate it through the get_format callback that is already installed. CodecContext.pix_fmt now reports the stream's software format until the first frame is decoded.
--- CHANGELOG.rst | 1 + av/container/input.py | 54 +++++++++++++++++++++++++++++++++++++++- av/video/codeccontext.py | 4 ++- tests/test_decode.py | 51 +++++++++++++++++++++++++++++++++++++ 4 files changed, 108 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2ce32bc26..a425bc0b1 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -47,6 +47,7 @@ Features: Fixes: - Support slicing ``Container.streams``, which raised ``TypeError`` despite being typed. +- Hardware decoding now works for AV1 when FFmpeg also provides libdav1d: ``av.open(..., hwaccel=...)`` picks a decoder that supports the requested device, and no longer sets the hardware pixel format before the decoder is opened. - ``AssSubtitle.dialogue`` now strips override tags such as ``{\b1}``, turns ``\n`` and ``\h`` into spaces, and keeps a ``{`` with no closing ``}`` instead of dropping the rest of the line. - ``HWConfig.methods`` no longer raises ``ValueError`` for configs that support several methods; ``HWConfigMethod`` is now an ``IntFlag``. - ``CodecContext.is_encoder``, ``CodecContext.is_decoder``, ``Container.input_was_opened``, and ``VideoFormatComponent.is_chroma`` now return ``bool`` instead of ``int``. diff --git a/av/container/input.py b/av/container/input.py index 2ad2dcf6b..116b8891d 100644 --- a/av/container/input.py +++ b/av/container/input.py @@ -1,5 +1,6 @@ import cython from cython.cimports.av.codec.context import CodecContext, wrap_codec_context +from cython.cimports.av.codec.hwaccel import HWAccel from cython.cimports.av.container.pyio import PyIOFile, pyio_close_custom_gil from cython.cimports.av.container.streams import StreamContainer from cython.cimports.av.dictionary import Dictionary @@ -14,6 +15,57 @@ _cinit_bypass_sentinel = cython.declare(object, object()) +@cython.cfunc +def _supports_device_type( + codec: cython.pointer[cython.const[lib.AVCodec]], device_type: cython.int +) -> cython.bint: + config: cython.pointer[cython.const[lib.AVCodecHWConfig]] + i: cython.int = 0 + while True: + config = lib.avcodec_get_hw_config(codec, i) + if config == cython.NULL: + return False + if ( + config.methods & lib.AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX + and config.device_type == device_type + ): + return True + i += 1 + + +@cython.cfunc +def _find_decoder( + codec_id: lib.AVCodecID, hwaccel: HWAccel | None +) -> cython.pointer[cython.const[lib.AVCodec]]: + # avcodec_find_decoder() returns the first decoder registered for the codec, + # which is not always one that can use the requested device: for AV1 it is + # libdav1d when FFmpeg is built with it, while the hwaccels belong to the + # native decoder. Prefer the default, and only look further when it cannot + # use the device. + codec: cython.pointer[cython.const[lib.AVCodec]] = lib.avcodec_find_decoder( + codec_id + ) + if ( + hwaccel is None + or codec == cython.NULL + or _supports_device_type(codec, hwaccel._device_type) + ): + return codec + + other: cython.pointer[cython.const[lib.AVCodec]] + opaque: cython.p_void = cython.NULL + while True: + other = lib.av_codec_iterate(cython.address(opaque)) + if other == cython.NULL: + return codec + if ( + other.id == codec_id + and lib.av_codec_is_decoder(other) + and _supports_device_type(other, hwaccel._device_type) + ): + return other + + @cython.cfunc def close_input(self: InputContainer) -> cython.int: self.streams = StreamContainer() @@ -87,7 +139,7 @@ def __cinit__(self, *args, **kwargs): self.streams = StreamContainer() for i in range(self.ptr.nb_streams): stream = self.ptr.streams[i] - codec = lib.avcodec_find_decoder(stream.codecpar.codec_id) + codec = _find_decoder(stream.codecpar.codec_id, self.hwaccel) if codec: codec_context = lib.avcodec_alloc_context3(codec) if codec_context == cython.NULL: diff --git a/av/video/codeccontext.py b/av/video/codeccontext.py index 33c4840f4..f8c7e4660 100644 --- a/av/video/codeccontext.py +++ b/av/video/codeccontext.py @@ -66,7 +66,9 @@ def _init( try: self.hwaccel_ctx = hwaccel.create(self.codec) self.ptr.hw_device_ctx = lib.av_buffer_ref(self.hwaccel_ctx.ptr) - self.ptr.pix_fmt = self.hwaccel_ctx.config.ptr.pix_fmt + # Leave pix_fmt alone: the decoder negotiates the hardware format through + # get_format. FFmpeg's AV1 decoder skips that negotiation, and with it the + # hwaccel setup, when pix_fmt already holds a hardware format. self.ptr.get_format = _get_hw_format self._private_data.hardware_pix_fmt = self.hwaccel_ctx.config.ptr.pix_fmt self._private_data.allow_software_fallback = ( diff --git a/tests/test_decode.py b/tests/test_decode.py index a95b66d8c..88451326c 100644 --- a/tests/test_decode.py +++ b/tests/test_decode.py @@ -55,6 +55,30 @@ def make_h264_test_video(path: str) -> None: output_container.close() +def make_av1_test_video(path: str) -> None: + """Generates a black AV1 test video, or skips the test without an AV1 encoder.""" + for encoder in ("libsvtav1", "libaom-av1", "librav1e"): + if encoder in av.codecs_available: + break + else: + pytest.skip("No AV1 encoder is available to generate the test video.") + + pathlib.Path(path).parent.mkdir(parents=True, exist_ok=True) + with av.open(path, "w") as output_container: + stream = output_container.add_stream(encoder, rate=24) + assert isinstance(stream, av.VideoStream) + stream.width = 1280 + stream.height = 720 + stream.pix_fmt = "yuv420p" + + for _ in range(24): + frame = av.VideoFrame.from_ndarray( + np.zeros((720, 1280, 3), dtype=np.uint8), format="rgb24" + ) + output_container.mux(stream.encode(frame)) + output_container.mux(stream.encode()) + + @pytest.mark.parametrize( "cls", [HWConfig, SideData, MotionVectors, MotionVector, VideoEncParams, VideoBlockParams], @@ -397,6 +421,33 @@ def test_hardware_decode(self) -> None: assert frame_count == video_stream.frames + def test_hardware_decode_picks_a_decoder_for_the_device(self) -> None: + device_type = hwaccel_device_type() + + # The default AV1 decoder is libdav1d when FFmpeg is built with it, and + # it has no hardware configs. The native decoder owns the hwaccels. + native = av.Codec("av1", "r") + if not any( + config.device_type.name == device_type for config in native.hardware_configs + ): + pytest.skip(f"FFmpeg has no AV1 hwaccel for {device_type}.") + + test_video_path = "tests/assets/black_av1.mp4" + make_av1_test_video(test_video_path) + + hwaccel = av.codec.hwaccel.HWAccel( + device_type=device_type, allow_software_fallback=False + ) + + with av.open(test_video_path, hwaccel=hwaccel) as container: + video_stream = container.streams.video[0] + assert video_stream.codec_context.is_hwaccel + assert video_stream.codec_context.codec.hardware_configs + + frame_count = sum(1 for _ in container.decode(video_stream)) + + assert frame_count == 24 + def test_hardware_create_keeps_flags(self) -> None: device_type = hwaccel_device_type() From c97a6670388f049a7a4a753705ce46893fda0cad Mon Sep 17 00:00:00 2001 From: Mark Harfouche Date: Sun, 22 Nov 2026 15:20:06 -0500 Subject: [PATCH 2/3] allow software fallback --- CHANGELOG.rst | 2 +- av/container/input.py | 5 ++++- tests/test_decode.py | 5 ++++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index a425bc0b1..93832f375 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -47,7 +47,7 @@ Features: Fixes: - Support slicing ``Container.streams``, which raised ``TypeError`` despite being typed. -- Hardware decoding now works for AV1 when FFmpeg also provides libdav1d: ``av.open(..., hwaccel=...)`` picks a decoder that supports the requested device, and no longer sets the hardware pixel format before the decoder is opened. +- Hardware decoding now works for AV1 when FFmpeg also provides libdav1d: with ``allow_software_fallback=False``, ``av.open(..., hwaccel=...)`` picks a decoder that supports the requested device. The hardware pixel format is also no longer set before the decoder is opened. - ``AssSubtitle.dialogue`` now strips override tags such as ``{\b1}``, turns ``\n`` and ``\h`` into spaces, and keeps a ``{`` with no closing ``}`` instead of dropping the rest of the line. - ``HWConfig.methods`` no longer raises ``ValueError`` for configs that support several methods; ``HWConfigMethod`` is now an ``IntFlag``. - ``CodecContext.is_encoder``, ``CodecContext.is_decoder``, ``Container.input_was_opened``, and ``VideoFormatComponent.is_chroma`` now return ``bool`` instead of ``int``. diff --git a/av/container/input.py b/av/container/input.py index 116b8891d..2acea41ba 100644 --- a/av/container/input.py +++ b/av/container/input.py @@ -41,12 +41,15 @@ def _find_decoder( # which is not always one that can use the requested device: for AV1 it is # libdav1d when FFmpeg is built with it, while the hwaccels belong to the # native decoder. Prefer the default, and only look further when it cannot - # use the device. + # use the device and software decoding is not allowed: a decoder like the + # native AV1 one cannot decode at all on a device without support for the + # codec, so with fallback allowed the default decoder is the safe choice. codec: cython.pointer[cython.const[lib.AVCodec]] = lib.avcodec_find_decoder( codec_id ) if ( hwaccel is None + or hwaccel.allow_software_fallback or codec == cython.NULL or _supports_device_type(codec, hwaccel._device_type) ): diff --git a/tests/test_decode.py b/tests/test_decode.py index 88451326c..03f4f9712 100644 --- a/tests/test_decode.py +++ b/tests/test_decode.py @@ -444,7 +444,10 @@ def test_hardware_decode_picks_a_decoder_for_the_device(self) -> None: assert video_stream.codec_context.is_hwaccel assert video_stream.codec_context.codec.hardware_configs - frame_count = sum(1 for _ in container.decode(video_stream)) + try: + frame_count = sum(1 for _ in container.decode(video_stream)) + except NotImplementedError: + pytest.skip(f"The {device_type} device cannot decode AV1.") assert frame_count == 24 From db12391ae65b4a358d65b5292cb7f28ca6fe4471 Mon Sep 17 00:00:00 2001 From: Mark Harfouche Date: Sun, 22 Nov 2026 16:44:58 -0500 Subject: [PATCH 3/3] Assert frames stay on device --- tests/test_decode.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/tests/test_decode.py b/tests/test_decode.py index 03f4f9712..a7a6bbe49 100644 --- a/tests/test_decode.py +++ b/tests/test_decode.py @@ -436,20 +436,29 @@ def test_hardware_decode_picks_a_decoder_for_the_device(self) -> None: make_av1_test_video(test_video_path) hwaccel = av.codec.hwaccel.HWAccel( - device_type=device_type, allow_software_fallback=False + device_type=device_type, allow_software_fallback=False, is_hw_owned=True ) with av.open(test_video_path, hwaccel=hwaccel) as container: video_stream = container.streams.video[0] assert video_stream.codec_context.is_hwaccel - assert video_stream.codec_context.codec.hardware_configs + hardware_format = next( + config.format + for config in video_stream.codec_context.codec.hardware_configs + if config.device_type.name == device_type + ) + assert hardware_format is not None + frames = container.decode(video_stream) try: - frame_count = sum(1 for _ in container.decode(video_stream)) + first_frame = next(frames) except NotImplementedError: pytest.skip(f"The {device_type} device cannot decode AV1.") - assert frame_count == 24 + formats = [first_frame.format.name] + formats.extend(frame.format.name for frame in frames) + + assert formats == [hardware_format.name] * 24 def test_hardware_create_keeps_flags(self) -> None: device_type = hwaccel_device_type()