Debian Codegraph @

tests/test_remux.py

raw
1 import io
2
3 import numpy as np
4 import pytest
5
6 import av
7 import av.datasets
8
9 from .common import fate_suite, sandboxed
10
11
12 def test_video_remux() -> None:
13 input_path = av.datasets.curated("pexels/time-lapse-video-of-night-sky-857195.mp4")
14 output_path = sandboxed("remuxed.mkv")
15 input_ = av.open(input_path)
16 output = av.open(output_path, "w")
17
18 in_stream = input_.streams.video[0]
19 out_stream = output.add_stream_from_template(in_stream)
20
21 for packet in input_.demux(in_stream):
22 if packet.size == 0: # skip the flushing packet, not keyframes with no DTS
23 continue
24
25 packet.stream = out_stream
26 output.mux(packet)
27
28 input_.close()
29 output.close()
30
31 with av.open(output_path) as container:
32 # Assert output is a valid media file
33 assert len(container.streams.video) == 1
34 assert len(container.streams.audio) == 0
35 assert container.streams.video[0].codec.name == "h264"
36
37 packet_count = 0
38 for packet in container.demux(video=0):
39 packet_count += 1
40
41 assert packet_count > 50
42
43
44 def test_add_mux_stream_video() -> None:
45 """add_mux_stream creates a video stream without a CodecContext."""
46 input_path = av.datasets.curated("pexels/time-lapse-video-of-night-sky-857195.mp4")
47
48 buf = io.BytesIO()
49 with av.open(input_path) as input_:
50 in_stream = input_.streams.video[0]
51 width = in_stream.codec_context.width
52 height = in_stream.codec_context.height
53
54 with av.open(buf, "w", format="mp4") as output:
55 out_stream = output.add_mux_stream(
56 in_stream.codec_context.name, width=width, height=height
57 )
58 assert out_stream.codec_context is None
59 assert out_stream.type == "video"
60
61 out_stream.time_base = in_stream.time_base
62
63 for packet in input_.demux(in_stream):
64 if packet.size == 0:
65 continue
66 packet.stream = out_stream
67 output.mux(packet)
68
69 buf.seek(0)
70 with av.open(buf) as result:
71 assert len(result.streams.video) == 1
72 assert result.streams.video[0].codec_context.width == width
73 assert result.streams.video[0].codec_context.height == height
74
75
76 def test_add_mux_stream_no_codec_context() -> None:
77 """add_mux_stream streams have no codec context and repr does not crash."""
78 buf = io.BytesIO()
79 with av.open(buf, "w", format="mp4") as output:
80 video_stream = output.add_mux_stream("h264", width=1920, height=1080)
81 audio_stream = output.add_mux_stream("aac", rate=44100)
82
83 assert video_stream.codec_context is None
84 assert audio_stream.codec_context is None
85 # repr should not crash
86 assert "video/<nocodec>" in repr(video_stream)
87 assert "audio/<nocodec>" in repr(audio_stream)
88
89
90 def test_add_stream_from_template_copies_time_base() -> None:
91 """add_stream_from_template must propagate the source stream's time_base.
92
93 AVCodecParameters does not carry time_base, so without an explicit copy
94 the output stream's time_base stays as None
95 """
96 video_path = av.datasets.curated("pexels/time-lapse-video-of-night-sky-857195.mp4")
97 with (
98 av.open(video_path) as input_,
99 av.open(io.BytesIO(), "w", format="mp4") as output,
100 ):
101 in_video = input_.streams.video[0]
102 out_video = output.add_stream_from_template(in_video)
103 assert out_video.time_base is not None
104 assert out_video.time_base == in_video.time_base
105
106 audio_path = fate_suite("audio-reference/chorusnoise_2ch_44kHz_s16.wav")
107 with (
108 av.open(audio_path) as input_,
109 av.open(io.BytesIO(), "w", format="wav") as output,
110 ):
111 in_audio = input_.streams.audio[0]
112 out_audio = output.add_stream_from_template(in_audio)
113 assert out_audio.time_base is not None
114 assert out_audio.time_base == in_audio.time_base
115
116
117 def _make_b_frame_mkv(n: int = 48) -> io.BytesIO:
118 """Encode `n` frames with B-frames into an in-memory MKV.
119
120 Matroska stores only presentation timestamps, so when this is demuxed again
121 libavformat cannot reconstruct a DTS for the leading reordered packets and
122 leaves it as None -- including on the very first packet, which is the
123 keyframe. That is exactly the layout that broke the remux example in #1917.
124 """
125 buf = io.BytesIO()
126 with av.open(buf, "w", format="matroska") as out:
127 stream = out.add_stream("h264", rate=30)
128 stream.width, stream.height, stream.pix_fmt = 160, 120, "yuv420p"
129 stream.options = {"bf": "3", "g": "30"}
130 for i in range(n):
131 img = np.full((120, 160, 3), (i * 5) % 256, dtype="uint8")
132 frame = av.VideoFrame.from_ndarray(img, format="rgb24")
133 for packet in stream.encode(frame):
134 out.mux(packet)
135 for packet in stream.encode(None):
136 out.mux(packet)
137 buf.seek(0)
138 return buf
139
140
141 def _decoded_frame_count(buf: io.BytesIO) -> int:
142 buf.seek(0)
143 with av.open(buf, "r") as container:
144 return sum(1 for _ in container.decode(video=0))
145
146
147 def test_remux_keeps_keyframe_with_none_dts() -> None:
148 """Regression test for #1917.
149
150 A keyframe can legitimately demux with ``dts is None`` (B-frame stream in a
151 PTS-only container like MKV). The remux loop must skip only the empty
152 flushing packet (``size == 0``), not every ``dts is None`` packet, otherwise
153 the keyframe is dropped and the output is undecodable.
154 """
155 if av.codec.Codec("h264", "w").name != "libx264":
156 pytest.skip("requires libx264")
157
158 source = _make_b_frame_mkv()
159 expected_frames = _decoded_frame_count(source)
160 assert expected_frames > 0
161
162 # Precondition: the first packet really is a keyframe without a DTS, which is
163 # what the old `dts is None` filter would have wrongly discarded.
164 source.seek(0)
165 with av.open(source, "r") as input_:
166 first = next(p for p in input_.demux(input_.streams.video[0]) if p.size)
167 assert first.is_keyframe
168 assert first.dts is None
169
170 source.seek(0)
171 output = io.BytesIO()
172 with (
173 av.open(source, "r") as input_,
174 av.open(output, "w", format="matroska") as out,
175 ):
176 in_video = input_.streams.video[0]
177 out_video = out.add_stream_from_template(in_video)
178 for packet in input_.demux(in_video):
179 if packet.size == 0: # the flushing packet, not a keyframe with no DTS
180 continue
181 packet.stream = out_video
182 out.mux(packet)
183
184 # The keyframe survived: every frame still decodes and the first packet of
185 # the remuxed stream is a keyframe.
186 assert _decoded_frame_count(output) == expected_frames
187 output.seek(0)
188 with av.open(output, "r") as container:
189 first_out = next(p for p in container.demux(video=0) if p.size)
190 assert first_out.is_keyframe