diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 2ce32bc26..93832f375 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: 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 2ad2dcf6b..2acea41ba 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,60 @@ _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 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) + ): + 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 +142,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..a7a6bbe49 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,45 @@ 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, 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 + 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: + first_frame = next(frames) + except NotImplementedError: + pytest.skip(f"The {device_type} device cannot decode AV1.") + + 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()