| 1 |
import io |
| 2 |
import os |
| 3 |
import struct |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
import av |
| 8 |
import av.datasets |
| 9 |
|
| 10 |
from .common import fate_suite |
| 11 |
|
| 12 |
|
| 13 |
def _crc32_mpeg(data: bytes) -> int: |
| 14 |
crc = 0xFFFFFFFF |
| 15 |
for byte in data: |
| 16 |
crc ^= byte << 24 |
| 17 |
for _ in range(8): |
| 18 |
if crc & 0x80000000: |
| 19 |
crc = (crc << 1) ^ 0x04C11DB7 |
| 20 |
else: |
| 21 |
crc <<= 1 |
| 22 |
crc &= 0xFFFFFFFF |
| 23 |
return crc |
| 24 |
|
| 25 |
|
| 26 |
def _make_ts_packet(pid: int, payload: bytes, pusi: bool = False, cc: int = 0) -> bytes: |
| 27 |
pid_hi = (pid >> 8) & 0x1F |
| 28 |
pid_lo = pid & 0xFF |
| 29 |
if pusi: |
| 30 |
pid_hi |= 0x40 |
| 31 |
header = bytes([0x47, pid_hi, pid_lo, 0x10 | (cc & 0x0F)]) |
| 32 |
pkt = header + payload |
| 33 |
return (pkt + b"\xff" * (188 - len(pkt)))[:188] |
| 34 |
|
| 35 |
|
| 36 |
def _make_unknown_stream_ts() -> bytes: |
| 37 |
"""Build a minimal MPEG-TS byte string whose only stream has AVMEDIA_TYPE_UNKNOWN. |
| 38 |
|
| 39 |
Uses stream_type=0x82 in the PMT, which FFmpeg does not map to any known |
| 40 |
media type, resulting in ``stream.type == "unknown"``. |
| 41 |
""" |
| 42 |
pat_data = bytes( |
| 43 |
[0x00, 0xB0, 0x0D, 0x00, 0x01, 0xC1, 0x00, 0x00, 0x00, 0x01, 0xE1, 0x00] |
| 44 |
) |
| 45 |
pat_data += struct.pack(">I", _crc32_mpeg(pat_data)) |
| 46 |
pat_payload = bytes([0x00]) + pat_data |
| 47 |
|
| 48 |
# fmt: off |
| 49 |
pmt_data = bytes([0x02, 0xB0, 0x12, 0x00, 0x01, 0xC1, 0x00, 0x00, |
| 50 |
0xE1, 0x02, 0xF0, 0x00, 0x82, 0xE1, 0x02, 0xF0, 0x00, |
| 51 |
]) |
| 52 |
# fmt: on |
| 53 |
pmt_data += struct.pack(">I", _crc32_mpeg(pmt_data)) |
| 54 |
pmt_payload = bytes([0x00]) + pmt_data |
| 55 |
|
| 56 |
pes_header = bytes([0x00, 0x00, 0x01, 0xBD, 0x00, 0x0A, 0x80, 0x00, 0x00]) |
| 57 |
pes_data = pes_header + b"\xaa" * (184 - len(pes_header)) |
| 58 |
|
| 59 |
packets: list[bytes] = [] |
| 60 |
for i in range(2): |
| 61 |
packets.append(_make_ts_packet(0x0000, pat_payload, pusi=True, cc=i)) |
| 62 |
for i in range(2): |
| 63 |
packets.append(_make_ts_packet(0x0100, pmt_payload, pusi=True, cc=i)) |
| 64 |
for i in range(200): |
| 65 |
packets.append(_make_ts_packet(0x0102, pes_data, pusi=(i % 10 == 0), cc=i % 16)) |
| 66 |
|
| 67 |
return b"".join(packets) |
| 68 |
|
| 69 |
|
| 70 |
class TestStreams: |
| 71 |
@pytest.fixture(autouse=True) |
| 72 |
def cleanup(self): |
| 73 |
yield |
| 74 |
for file in ( |
| 75 |
"data.ts", |
| 76 |
"data_source.ts", |
| 77 |
"data_copy.ts", |
| 78 |
"data_with_codec.ts", |
| 79 |
"data_invalid.ts", |
| 80 |
"out.mkv", |
| 81 |
"video_with_attachment.mkv", |
| 82 |
"remuxed_attachment.mkv", |
| 83 |
): |
| 84 |
if os.path.exists(file): |
| 85 |
os.remove(file) |
| 86 |
|
| 87 |
def test_stream_tuples(self) -> None: |
| 88 |
for fate_name in ("h264/interlaced_crop.mp4",): |
| 89 |
container = av.open(fate_suite(fate_name)) |
| 90 |
|
| 91 |
video_streams = tuple([s for s in container.streams if s.type == "video"]) |
| 92 |
assert video_streams == container.streams.video |
| 93 |
|
| 94 |
audio_streams = tuple([s for s in container.streams if s.type == "audio"]) |
| 95 |
assert audio_streams == container.streams.audio |
| 96 |
|
| 97 |
def test_loudnorm(self) -> None: |
| 98 |
container = av.open( |
| 99 |
fate_suite("amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv") |
| 100 |
) |
| 101 |
audio = container.streams.audio[0] |
| 102 |
stats = av.filter.loudnorm.stats("i=-24.0:lra=7.0:tp=-2.0", audio) |
| 103 |
|
| 104 |
assert isinstance(stats, bytes) and len(stats) > 30 |
| 105 |
assert b"inf" not in stats |
| 106 |
assert b'"input_i"' in stats |
| 107 |
|
| 108 |
def test_selection(self) -> None: |
| 109 |
container = av.open( |
| 110 |
fate_suite("amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv") |
| 111 |
) |
| 112 |
video = container.streams.video[0] |
| 113 |
|
| 114 |
video.thread_type = av.codec.context.ThreadType.AUTO |
| 115 |
assert video.thread_type == av.codec.context.ThreadType.AUTO |
| 116 |
|
| 117 |
video.thread_type = 0x03 |
| 118 |
assert video.thread_type == av.codec.context.ThreadType.AUTO |
| 119 |
|
| 120 |
video.thread_type = "AUTO" |
| 121 |
assert video.thread_type == av.codec.context.ThreadType.AUTO |
| 122 |
|
| 123 |
audio = container.streams.audio[0] |
| 124 |
|
| 125 |
assert [video] == container.streams.get(video=0) |
| 126 |
assert [video] == container.streams.get(video=(0,)) |
| 127 |
|
| 128 |
assert video == container.streams.best("video") |
| 129 |
assert audio == container.streams.best("audio") |
| 130 |
|
| 131 |
container = av.open(fate_suite("sub/MovText_capability_tester.mp4")) |
| 132 |
subtitle = container.streams.subtitles[0] |
| 133 |
assert subtitle == container.streams.best("subtitle") |
| 134 |
|
| 135 |
container = av.open(fate_suite("mxf/track_01_v02.mxf")) |
| 136 |
data = container.streams.data[0] |
| 137 |
assert data == container.streams.best("data") |
| 138 |
|
| 139 |
def test_discard(self) -> None: |
| 140 |
from av.stream import Discard |
| 141 |
|
| 142 |
container = av.open( |
| 143 |
fate_suite("amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv") |
| 144 |
) |
| 145 |
audio = container.streams.audio[0] |
| 146 |
|
| 147 |
# Default discard policy. |
| 148 |
assert audio.discard == Discard.default |
| 149 |
|
| 150 |
# Setter accepts the enum and round-trips. |
| 151 |
audio.discard = Discard.all |
| 152 |
assert audio.discard == Discard.all |
| 153 |
|
| 154 |
audio.discard = Discard.nonkey |
| 155 |
assert audio.discard == Discard.nonkey |
| 156 |
container.close() |
| 157 |
|
| 158 |
# Discarding a stream makes demux skip (almost) all of its packets. |
| 159 |
def audio_packets(discard: Discard | None) -> int: |
| 160 |
c = av.open( |
| 161 |
fate_suite( |
| 162 |
"amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv" |
| 163 |
) |
| 164 |
) |
| 165 |
if discard is not None: |
| 166 |
c.streams.audio[0].discard = discard |
| 167 |
count = sum( |
| 168 |
1 for p in c.demux() if p.dts is not None and p.stream.type == "audio" |
| 169 |
) |
| 170 |
c.close() |
| 171 |
return count |
| 172 |
|
| 173 |
baseline = audio_packets(None) |
| 174 |
discarded = audio_packets(Discard.all) |
| 175 |
assert baseline > 0 |
| 176 |
assert discarded < baseline |
| 177 |
|
| 178 |
def test_printing_video_stream(self) -> None: |
| 179 |
input_ = av.open( |
| 180 |
fate_suite("amv/MTV_high_res_320x240_sample_Penguin_Joke_MTV_from_WMV.amv") |
| 181 |
) |
| 182 |
container = av.open("out.mkv", "w") |
| 183 |
|
| 184 |
video_stream = container.add_stream("h264", rate=30) |
| 185 |
encoder = video_stream.codec.name |
| 186 |
|
| 187 |
video_stream.width = input_.streams.video[0].width |
| 188 |
video_stream.height = input_.streams.video[0].height |
| 189 |
video_stream.pix_fmt = "yuv420p" |
| 190 |
|
| 191 |
for frame in input_.decode(video=0): |
| 192 |
container.mux(video_stream.encode(frame)) |
| 193 |
break |
| 194 |
|
| 195 |
repr = f"{video_stream}" |
| 196 |
assert repr.startswith(f"<av.VideoStream #0 {encoder}, yuv420p 160x120 at ") |
| 197 |
assert repr.endswith(">") |
| 198 |
|
| 199 |
container.close() |
| 200 |
input_.close() |
| 201 |
|
| 202 |
def test_printing_video_stream2(self) -> None: |
| 203 |
input_ = av.open(fate_suite("h264/interlaced_crop.mp4")) |
| 204 |
input_stream = input_.streams.video[0] |
| 205 |
container = av.open("out.mkv", "w") |
| 206 |
|
| 207 |
video_stream = container.add_stream_from_template(input_stream) |
| 208 |
encoder = video_stream.codec.name |
| 209 |
|
| 210 |
for frame in input_.decode(video=0): |
| 211 |
container.mux(video_stream.encode(frame)) |
| 212 |
break |
| 213 |
|
| 214 |
repr = f"{video_stream}" |
| 215 |
assert repr.startswith(f"<av.VideoStream #0 {encoder}, yuv420p 640x360 at ") |
| 216 |
assert repr.endswith(">") |
| 217 |
|
| 218 |
container.close() |
| 219 |
input_.close() |
| 220 |
|
| 221 |
def test_data_stream(self) -> None: |
| 222 |
# First test writing and reading a simple data stream |
| 223 |
container1 = av.open("data.ts", "w") |
| 224 |
data_stream = container1.add_data_stream() |
| 225 |
|
| 226 |
test_data = [b"test data 1", b"test data 2", b"test data 3"] |
| 227 |
for i, data_ in enumerate(test_data): |
| 228 |
packet = av.Packet(data_) |
| 229 |
packet.pts = i |
| 230 |
packet.stream = data_stream |
| 231 |
container1.mux(packet) |
| 232 |
container1.close() |
| 233 |
|
| 234 |
# Test reading back the data stream |
| 235 |
container = av.open("data.ts") |
| 236 |
|
| 237 |
# Test best stream selection |
| 238 |
data = container.streams.best("data") |
| 239 |
assert data == container.streams.data[0] |
| 240 |
|
| 241 |
# Test get method |
| 242 |
assert [data] == container.streams.get(data=0) |
| 243 |
assert [data] == container.streams.get(data=(0,)) |
| 244 |
|
| 245 |
# Verify we can read back all the packets, ignoring empty ones |
| 246 |
packets = [p for p in container.demux(data) if bytes(p)] |
| 247 |
assert len(packets) == len(test_data) |
| 248 |
for read_packet, original_data in zip(packets, test_data): |
| 249 |
assert bytes(read_packet) == original_data |
| 250 |
|
| 251 |
# Test string representation |
| 252 |
repr = f"{data_stream}" |
| 253 |
assert repr.startswith("<av.DataStream #0") and repr.endswith(">") |
| 254 |
|
| 255 |
container.close() |
| 256 |
|
| 257 |
def test_data_stream_from_template(self) -> None: |
| 258 |
source_path = "data_source.ts" |
| 259 |
payloads = [b"payload-a", b"payload-b", b"payload-c"] |
| 260 |
|
| 261 |
with av.open(source_path, "w") as source: |
| 262 |
source_stream = source.add_data_stream() |
| 263 |
for i, payload in enumerate(payloads): |
| 264 |
packet = av.Packet(payload) |
| 265 |
packet.pts = i |
| 266 |
packet.stream = source_stream |
| 267 |
source.mux(packet) |
| 268 |
|
| 269 |
copied_payloads: list[bytes] = [] |
| 270 |
|
| 271 |
with av.open(source_path) as input_container: |
| 272 |
input_data_stream = input_container.streams.data[0] |
| 273 |
|
| 274 |
with av.open("data_copy.ts", "w") as output_container: |
| 275 |
output_data_stream = output_container.add_stream_from_template( |
| 276 |
input_data_stream |
| 277 |
) |
| 278 |
|
| 279 |
for data_packet in input_container.demux(input_data_stream): |
| 280 |
payload = bytes(data_packet) |
| 281 |
if not payload: |
| 282 |
continue |
| 283 |
copied_payloads.append(payload) |
| 284 |
clone = av.Packet(payload) |
| 285 |
clone.pts = data_packet.pts |
| 286 |
clone.dts = data_packet.dts |
| 287 |
clone.time_base = data_packet.time_base |
| 288 |
clone.stream = output_data_stream |
| 289 |
output_container.mux(clone) |
| 290 |
|
| 291 |
with av.open("data_copy.ts") as remuxed: |
| 292 |
output_stream = remuxed.streams.data[0] |
| 293 |
assert output_stream.codec_context is None |
| 294 |
|
| 295 |
remuxed_payloads: list[bytes] = [] |
| 296 |
for data_packet in remuxed.demux(output_stream): |
| 297 |
payload = bytes(data_packet) |
| 298 |
if payload: |
| 299 |
remuxed_payloads.append(payload) |
| 300 |
|
| 301 |
assert remuxed_payloads == copied_payloads |
| 302 |
|
| 303 |
def test_data_stream_with_codec(self) -> None: |
| 304 |
"""Test adding a data stream with a specific codec name.""" |
| 305 |
# Test that invalid codec names raise appropriate errors |
| 306 |
with pytest.raises(ValueError, match="Unknown data codec"): |
| 307 |
container = av.open("data_invalid.ts", "w") |
| 308 |
try: |
| 309 |
container.add_data_stream("not_a_real_codec_name_12345") |
| 310 |
finally: |
| 311 |
container.close() |
| 312 |
|
| 313 |
# Test that add_data_stream with codec parameter works correctly |
| 314 |
# We use "bin_data" which is a data codec that's always available |
| 315 |
output_path = "data_with_codec.ts" |
| 316 |
with av.open(output_path, "w") as container: |
| 317 |
# Try to create a data stream with a codec |
| 318 |
# bin_data is a simple passthrough codec for binary data |
| 319 |
data_stream = container.add_data_stream("bin_data") |
| 320 |
klv_stream = container.add_data_stream("klv") |
| 321 |
|
| 322 |
assert data_stream.type == "data" |
| 323 |
assert klv_stream.type == "data" |
| 324 |
# Note: codec_context may be None for descriptor-only data codecs |
| 325 |
|
| 326 |
test_data = [b"test1", b"test2", b"test3"] |
| 327 |
for i, data in enumerate(test_data): |
| 328 |
packet = av.Packet(data) |
| 329 |
packet.pts = i |
| 330 |
packet.stream = data_stream |
| 331 |
container.mux(packet) |
| 332 |
|
| 333 |
with av.open(output_path) as newcontainer: |
| 334 |
data_stream = newcontainer.streams.data[0] |
| 335 |
klv_stream = newcontainer.streams.data[1] |
| 336 |
assert data_stream.type == "data" |
| 337 |
assert klv_stream.type == "data" |
| 338 |
assert "bin_data" in str(data_stream) |
| 339 |
assert "klv" in str(klv_stream) |
| 340 |
assert data_stream.name == "bin_data" |
| 341 |
assert klv_stream.name == "klv" |
| 342 |
try: |
| 343 |
os.remove(output_path) |
| 344 |
except Exception: |
| 345 |
pass |
| 346 |
|
| 347 |
def test_attachment_stream(self) -> None: |
| 348 |
input_path = av.datasets.curated( |
| 349 |
"pexels/time-lapse-video-of-night-sky-857195.mp4" |
| 350 |
) |
| 351 |
input_ = av.open(input_path) |
| 352 |
out1_path = "video_with_attachment.mkv" |
| 353 |
|
| 354 |
with av.open(out1_path, "w") as out1: |
| 355 |
out1.add_attachment( |
| 356 |
name="attachment.txt", mimetype="text/plain", data=b"hello\n" |
| 357 |
) |
| 358 |
|
| 359 |
in_v = input_.streams.video[0] |
| 360 |
out_v = out1.add_stream_from_template(in_v) |
| 361 |
|
| 362 |
for packet in input_.demux(in_v): |
| 363 |
if packet.size == 0: |
| 364 |
continue |
| 365 |
packet.stream = out_v |
| 366 |
out1.mux(packet) |
| 367 |
|
| 368 |
input_.close() |
| 369 |
|
| 370 |
with av.open(out1_path) as c: |
| 371 |
attachments = c.streams.attachments |
| 372 |
assert len(attachments) == 1 |
| 373 |
att = attachments[0] |
| 374 |
assert att.name == "attachment.txt" |
| 375 |
assert att.mimetype == "text/plain" |
| 376 |
assert att.data == b"hello\n" |
| 377 |
|
| 378 |
out2_path = "remuxed_attachment.mkv" |
| 379 |
with av.open(out1_path) as ic, av.open(out2_path, "w") as oc: |
| 380 |
stream_map = {} |
| 381 |
for s in ic.streams: |
| 382 |
stream_map[s.index] = oc.add_stream_from_template(s) |
| 383 |
|
| 384 |
for packet in ic.demux(ic.streams.video): |
| 385 |
if packet.size == 0: |
| 386 |
continue |
| 387 |
updated_stream = stream_map.get(packet.stream.index) |
| 388 |
if isinstance(updated_stream, av.video.stream.VideoStream): |
| 389 |
packet.stream = updated_stream |
| 390 |
else: |
| 391 |
raise ValueError("Expected a VideoStream") |
| 392 |
oc.mux(packet) |
| 393 |
|
| 394 |
with av.open(out2_path) as c: |
| 395 |
attachments = c.streams.attachments |
| 396 |
assert len(attachments) == 1 |
| 397 |
att = attachments[0] |
| 398 |
assert att.name == "attachment.txt" |
| 399 |
assert att.mimetype == "text/plain" |
| 400 |
assert att.data == b"hello\n" |
| 401 |
|
| 402 |
def test_unknown_stream_type(self) -> None: |
| 403 |
ts_data = _make_unknown_stream_ts() |
| 404 |
|
| 405 |
with av.open(io.BytesIO(ts_data), format="mpegts") as container: |
| 406 |
assert len(container.streams) == 1 |
| 407 |
stream = container.streams[0] |
| 408 |
assert stream.type == "unknown" |
| 409 |
assert type(stream) is av.stream.Stream |