Debian Codegraph @

tests/test_codec_context.py

raw
1 from __future__ import annotations
2
3 import os
4 from fractions import Fraction
5 from typing import Iterator, TypedDict, overload
6
7 import pytest
8
9 import av
10 from av import (
11 AudioCodecContext,
12 AudioFrame,
13 AudioLayout,
14 AudioResampler,
15 Codec,
16 Packet,
17 VideoCodecContext,
18 VideoFrame,
19 )
20 from av.codec.codec import UnknownCodecError
21 from av.video.frame import PictureType
22
23 from .common import TestCase, fate_suite
24
25
26 class Options(TypedDict, total=False):
27 b: str
28 crf: str
29 pix_fmt: str
30 width: int
31 height: int
32 max_frames: int
33 time_base: Fraction
34 gop_size: int
35
36
37 @overload
38 def iter_raw_frames(
39 path: str, packet_sizes: list[int], ctx: VideoCodecContext
40 ) -> Iterator[VideoFrame]: ...
41 @overload
42 def iter_raw_frames(
43 path: str, packet_sizes: list[int], ctx: AudioCodecContext
44 ) -> Iterator[AudioFrame]: ...
45 def iter_raw_frames(
46 path: str, packet_sizes: list[int], ctx: VideoCodecContext | AudioCodecContext
47 ) -> Iterator[VideoFrame | AudioFrame]:
48 with open(path, "rb") as f:
49 for i, size in enumerate(packet_sizes):
50 packet = Packet(size)
51 read_size = f.readinto(packet)
52 assert size
53 assert read_size == size
54 if not read_size:
55 break
56 for frame in ctx.decode(packet):
57 yield frame
58
59 while True:
60 try:
61 frames = ctx.decode(None)
62 except EOFError:
63 break
64 for frame in frames:
65 yield frame
66 if not frames:
67 break
68
69
70 class TestCodecContext(TestCase):
71 def test_global_quality(self):
72 ctx = Codec("mpeg4", "w").create()
73 ctx.global_quality = 5
74 assert ctx.global_quality == 5
75
76 def test_skip_frame_default(self):
77 ctx = Codec("png", "w").create()
78 assert ctx.skip_frame == "DEFAULT"
79
80 def test_codec_delay(self) -> None:
81 with av.open(fate_suite("mkv/codec_delay_opus.mkv")) as container:
82 assert container.streams.audio[0].codec_context.delay == 312
83 with av.open(fate_suite("h264/interlaced_crop.mp4")) as container:
84 assert container.streams.video[0].codec_context.delay == 0
85
86 def test_codec_tag(self):
87 ctx = Codec("mpeg4", "w").create()
88 assert ctx.codec_tag == "\x00\x00\x00\x00"
89 ctx.codec_tag = "xvid"
90 assert ctx.codec_tag == "xvid"
91
92 # wrong length
93 with pytest.raises(
94 ValueError, match="Codec tag should be a 4 character string"
95 ):
96 ctx.codec_tag = "bob"
97
98 # wrong type
99 with pytest.raises(
100 ValueError, match="Codec tag should be a 4 character string"
101 ):
102 ctx.codec_tag = 123
103
104 with av.open(fate_suite("h264/interlaced_crop.mp4")) as container:
105 assert container.streams[0].codec_tag == "avc1"
106
107 def test_decoder_extradata(self):
108 ctx = av.codec.Codec("h264", "r").create()
109 assert ctx.extradata is None
110 assert ctx.extradata_size == 0
111
112 ctx.extradata = b"123"
113 assert ctx.extradata == b"123"
114 assert ctx.extradata_size == 3
115
116 ctx.extradata = b"54321"
117 assert ctx.extradata == b"54321"
118 assert ctx.extradata_size == 5
119
120 ctx.extradata = None
121 assert ctx.extradata is None
122 assert ctx.extradata_size == 0
123
124 def test_decoder_gop_size(self) -> None:
125 ctx = av.codec.Codec("h264", "r").create("video")
126
127 with pytest.raises(RuntimeError):
128 ctx.gop_size
129
130 def test_decoder_timebase(self) -> None:
131 ctx = av.codec.Codec("h264", "r").create()
132
133 with pytest.raises(RuntimeError):
134 ctx.time_base
135
136 with pytest.raises(RuntimeError):
137 ctx.time_base = Fraction(1, 25)
138
139 def test_encoder_extradata(self) -> None:
140 ctx = av.codec.Codec("h264", "w").create()
141 assert ctx.extradata is None
142 assert ctx.extradata_size == 0
143
144 ctx.extradata = b"123"
145 assert ctx.extradata == b"123"
146 assert ctx.extradata_size == 3
147
148 def test_encoder_pix_fmt(self) -> None:
149 ctx = av.codec.Codec("h264", "w").create("video")
150
151 # valid format
152 ctx.pix_fmt = "yuv420p"
153 assert ctx.pix_fmt == "yuv420p"
154
155 # invalid format
156 with self.assertRaises(ValueError) as cm:
157 ctx.pix_fmt = "__unknown_pix_fmt"
158 assert str(cm.exception) == "not a pixel format: '__unknown_pix_fmt'"
159 assert ctx.pix_fmt == "yuv420p"
160
161 def test_bits_per_coded_sample(self):
162 with av.open(fate_suite("qtrle/aletrek-rle.mov")) as container:
163 stream = container.streams.video[0]
164 stream.bits_per_coded_sample = 32
165
166 for packet in container.demux(stream):
167 for frame in packet.decode():
168 pass
169 assert isinstance(packet.stream, av.VideoStream)
170 assert packet.stream.bits_per_coded_sample == 32
171
172 with av.open(fate_suite("qtrle/aletrek-rle.mov")) as container:
173 stream = container.streams.video[0]
174 stream.bits_per_coded_sample = 31
175
176 with pytest.raises(av.error.InvalidDataError):
177 for _ in container.decode(stream):
178 pass
179
180 with av.open(self.sandboxed("output.mov"), "w") as output:
181 stream = output.add_stream("qtrle")
182
183 with pytest.raises(ValueError):
184 stream.codec_context.bits_per_coded_sample = 32
185
186 def test_parse(self) -> None:
187 # This one parses into a single packet.
188 self._assert_parse("mpeg4", fate_suite("h264/interlaced_crop.mp4"))
189
190 # This one parses into many small packets.
191 self._assert_parse("mpeg2video", fate_suite("mpeg2/mpeg2_field_encoding.ts"))
192
193 def _assert_parse(self, codec_name: str, path: str) -> None:
194 fh = av.open(path)
195 packets = []
196 for packet in fh.demux(video=0):
197 packets.append(packet)
198
199 full_source = b"".join(bytes(p) for p in packets)
200
201 for size in 1024, 8192, 65535:
202 ctx = Codec(codec_name).create()
203 packets = []
204
205 for i in range(0, len(full_source), size):
206 block = full_source[i : i + size]
207 packets.extend(ctx.parse(block))
208 packets.extend(ctx.parse())
209
210 parsed_source = b"".join(bytes(p) for p in packets)
211 assert len(parsed_source) == len(full_source)
212 assert full_source == parsed_source
213
214 def test_parse_assigns_packet_timing(self) -> None:
215 # Regression test for #1919: the parser-inferred timing information
216 # should be propagated onto the returned packets.
217 path = fate_suite("mpeg2/mpeg2_field_encoding.ts")
218 full_source = b"".join(bytes(p) for p in av.open(path).demux(video=0))
219
220 ctx = Codec("mpeg2video").create()
221 packets = []
222 for i in range(0, len(full_source), 4096):
223 packets.extend(ctx.parse(full_source[i : i + 4096]))
224 packets.extend(ctx.parse())
225
226 # The parser is able to determine the byte position for this stream,
227 # so at least some packets should carry it through.
228 assert any(p.pos is not None for p in packets)
229
230
231 class TestEncoding(TestCase):
232 def test_encoding_png(self) -> None:
233 self.image_sequence_encode("png")
234
235 def test_encoding_mjpeg(self) -> None:
236 self.image_sequence_encode("mjpeg")
237
238 def test_encoding_tiff(self) -> None:
239 self.image_sequence_encode("tiff")
240
241 def image_sequence_encode(self, codec_name: str) -> None:
242 try:
243 codec = Codec(codec_name, "w")
244 except UnknownCodecError:
245 pytest.skip(f"Unknown codec: {codec_name}")
246
247 container = av.open(fate_suite("h264/interlaced_crop.mp4"))
248 video_stream = container.streams.video[0]
249
250 width = 640
251 height = 480
252
253 ctx = codec.create("video")
254
255 assert ctx.codec.video_formats
256 pix_fmt = ctx.codec.video_formats[0].name
257
258 ctx.width = width
259 ctx.height = height
260
261 assert video_stream.time_base is not None
262 ctx.time_base = video_stream.time_base
263 ctx.pix_fmt = pix_fmt
264 ctx.open()
265
266 frame_count = 1
267 path_list = []
268 for frame in container.decode(video_stream):
269 new_frame = frame.reformat(width, height, pix_fmt)
270 new_packets = ctx.encode(new_frame)
271
272 assert len(new_packets) == 1
273 new_packet = new_packets[0]
274
275 path = self.sandboxed(
276 "%s/encoder.%04d.%s"
277 % (
278 codec_name,
279 frame_count,
280 codec_name if codec_name != "mjpeg" else "jpg",
281 )
282 )
283 path_list.append(path)
284 with open(path, "wb") as f:
285 f.write(new_packet)
286 frame_count += 1
287 if frame_count > 5:
288 break
289
290 ctx = av.Codec(codec_name, "r").create("video")
291
292 for path in path_list:
293 with open(path, "rb") as f:
294 size = os.fstat(f.fileno()).st_size
295 packet = Packet(size)
296 size = f.readinto(packet)
297 frame = ctx.decode(packet)[0]
298 assert frame.width == width
299 assert frame.height == height
300 assert frame.format.name == pix_fmt
301
302 def test_encoding_h264(self) -> None:
303 self.video_encoding("h264", {"crf": "19"})
304
305 def test_encoding_mpeg4(self) -> None:
306 self.video_encoding("mpeg4")
307
308 def test_encoding_xvid(self) -> None:
309 self.video_encoding("mpeg4", codec_tag="xvid")
310
311 def test_encoding_mpeg1video(self) -> None:
312 self.video_encoding("mpeg1video")
313
314 def test_encoding_dvvideo(self) -> None:
315 options: Options = {"pix_fmt": "yuv411p", "width": 720, "height": 480}
316 self.video_encoding("dvvideo", options)
317
318 def test_encoding_dnxhd(self) -> None:
319 options: Options = {
320 "b": "90M", # bitrate
321 "pix_fmt": "yuv422p",
322 "width": 1920,
323 "height": 1080,
324 "time_base": Fraction(1001, 30_000),
325 "max_frames": 5,
326 }
327 self.video_encoding("dnxhd", options)
328
329 def video_encoding(
330 self,
331 codec_name: str,
332 options: Options = {},
333 codec_tag: str | None = None,
334 ) -> None:
335 try:
336 codec = Codec(codec_name, "w")
337 except UnknownCodecError:
338 pytest.skip(f"Unknown codec: {codec_name}")
339
340 container = av.open(fate_suite("h264/interlaced_crop.mp4"))
341 video_stream = container.streams.video[0]
342
343 assert video_stream.time_base is not None
344
345 pix_fmt = options.pop("pix_fmt", "yuv420p")
346 width = options.pop("width", 640)
347 height = options.pop("height", 480)
348 max_frames = options.pop("max_frames", 50)
349 time_base = options.pop("time_base", video_stream.time_base)
350 gop_size = options.pop("gop_size", 20)
351
352 ctx = codec.create("video")
353 ctx.width = width
354 ctx.height = height
355 ctx.time_base = time_base
356 ctx.framerate = 1 / ctx.time_base
357 ctx.pix_fmt = pix_fmt
358 ctx.gop_size = gop_size
359 ctx.options = options # type: ignore
360 if codec_tag:
361 ctx.codec_tag = codec_tag
362 ctx.open()
363
364 path = self.sandboxed(f"encoder.{codec_name}")
365 packet_sizes = []
366 frame_count = 0
367
368 with open(path, "wb") as f:
369 for frame in container.decode(video_stream):
370 new_frame = frame.reformat(width, height, pix_fmt)
371
372 # reset the picture type
373 new_frame.pict_type = PictureType.NONE
374
375 for packet in ctx.encode(new_frame):
376 packet_sizes.append(packet.size)
377 f.write(packet)
378
379 frame_count += 1
380 if frame_count >= max_frames:
381 break
382
383 for packet in ctx.encode(None):
384 packet_sizes.append(packet.size)
385 f.write(packet)
386
387 dec_codec_name = codec_name
388 if codec_name == "libx264":
389 dec_codec_name = "h264"
390
391 ctx = av.Codec(dec_codec_name, "r").create("video")
392 ctx.open()
393
394 keyframe_indices = []
395 decoded_frame_count = 0
396 for frame in iter_raw_frames(path, packet_sizes, ctx):
397 decoded_frame_count += 1
398 assert frame.width == width
399 assert frame.height == height
400 assert frame.format.name == pix_fmt
401 if frame.key_frame:
402 keyframe_indices.append(decoded_frame_count)
403
404 assert frame_count == decoded_frame_count
405
406 assert isinstance(
407 all(keyframe_index for keyframe_index in keyframe_indices), int
408 )
409 decoded_gop_sizes = [
410 j - i for i, j in zip(keyframe_indices[:-1], keyframe_indices[1:])
411 ]
412 if codec_name in ("dvvideo", "dnxhd") and all(
413 i == 1 for i in decoded_gop_sizes
414 ):
415 pytest.skip()
416 for i in decoded_gop_sizes:
417 assert i == gop_size
418
419 final_gop_size = decoded_frame_count - max(keyframe_indices)
420 assert final_gop_size < gop_size
421
422 def test_encoding_pcm_s24le(self) -> None:
423 self.audio_encoding("pcm_s24le")
424
425 def test_encoding_aac(self) -> None:
426 self.audio_encoding("aac")
427
428 def test_encoding_mp2(self) -> None:
429 self.audio_encoding("mp2")
430
431 def audio_encoding(self, codec_name: str) -> None:
432 self._audio_encoding(codec_name=codec_name, channel_layout="stereo")
433 self._audio_encoding(
434 codec_name=codec_name, channel_layout=AudioLayout("stereo")
435 )
436
437 def _audio_encoding(
438 self, *, codec_name: str, channel_layout: str | AudioLayout
439 ) -> None:
440 try:
441 codec = Codec(codec_name, "w")
442 except UnknownCodecError:
443 pytest.skip(f"Unknown codec: {codec_name}")
444
445 ctx = codec.create(kind="audio")
446
447 if ctx.codec.experimental:
448 pytest.skip(f"Experimental codec: {codec_name}")
449
450 assert ctx.codec.audio_formats
451 sample_fmt = ctx.codec.audio_formats[-1].name
452 sample_rate = 48000
453
454 ctx.time_base = Fraction(1) / sample_rate
455 ctx.sample_rate = sample_rate
456 ctx.format = sample_fmt
457 ctx.layout = channel_layout
458
459 ctx.open()
460
461 resampler = AudioResampler(sample_fmt, channel_layout, sample_rate)
462
463 container = av.open(fate_suite("audio-reference/chorusnoise_2ch_44kHz_s16.wav"))
464 audio_stream = container.streams.audio[0]
465
466 path = self.sandboxed(f"encoder.{codec_name}")
467
468 samples = 0
469 packet_sizes = []
470
471 with open(path, "wb") as f:
472 for frame in container.decode(audio_stream):
473 resampled_frames = resampler.resample(frame)
474 for resampled_frame in resampled_frames:
475 assert resampled_frame.time_base == Fraction(1, 48000)
476 samples += resampled_frame.samples
477
478 for packet in ctx.encode(resampled_frame):
479 assert packet.time_base == Fraction(1, 48000)
480 packet_sizes.append(packet.size)
481 f.write(packet)
482
483 for packet in ctx.encode(None):
484 assert packet.time_base == Fraction(1, 48000)
485 packet_sizes.append(packet.size)
486 f.write(packet)
487
488 ctx = Codec(codec_name, "r").create("audio")
489 ctx.sample_rate = sample_rate
490 ctx.format = sample_fmt
491 ctx.layout = channel_layout
492 ctx.open()
493
494 result_samples = 0
495
496 for frame in iter_raw_frames(path, packet_sizes, ctx):
497 result_samples += frame.samples
498 assert frame.sample_rate == sample_rate
499 assert frame.layout.nb_channels == 2