diff --git a/av/container/output.py b/av/container/output.py index d035b0265..7738086ad 100644 --- a/av/container/output.py +++ b/av/container/output.py @@ -144,6 +144,11 @@ def add_stream_from_template( if opaque is None: opaque = template.type != "video" + if template.codec_context is None: + raise ValueError( + f"template stream of type {template.type} has no codec context" + ) + codec_obj: Codec if opaque: # Copy ctx from template. codec_obj = template.codec_context.codec diff --git a/tests/test_streams.py b/tests/test_streams.py index c7b234d48..d07085de4 100644 --- a/tests/test_streams.py +++ b/tests/test_streams.py @@ -1,5 +1,6 @@ import os from fractions import Fraction +from typing import Any, cast import pytest @@ -146,3 +147,23 @@ def test_data_stream(self) -> None: assert repr.startswith("") container.close() + + def test_data_stream_from_template(self) -> None: + """Test that adding a data stream from a template raises ValueError.""" + + # Open an existing container with a data stream + input_container = av.open(fate_suite("mxf/track_01_v02.mxf")) + input_data_stream = input_container.streams.data[0] + + # Create a new container and ensure using a data stream as a template raises ValueError + output_container = av.open("out.mkv", "w") + with pytest.raises(ValueError): + # input_data_stream is a DataStream at runtime; the test asserts that + # using it as a template raises ValueError. The static type stubs + # intentionally restrict which Stream subclasses are valid templates, + # so cast to Any here to keep the runtime check while satisfying + # the type checker. + output_container.add_stream_from_template(cast(Any, input_data_stream)) + + input_container.close() + output_container.close()