Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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``.
Expand Down
57 changes: 56 additions & 1 deletion av/container/input.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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()
Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Providing hwaccel here is what allows pyav to find the hardware accelerated encoder you want to find

if codec:
codec_context = lib.avcodec_alloc_context3(codec)
if codec_context == cython.NULL:
Expand Down
4 changes: 3 additions & 1 deletion av/video/codeccontext.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down
63 changes: 63 additions & 0 deletions tests/test_decode.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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()

Expand Down