| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import io |
| 4 |
import math |
| 5 |
from fractions import Fraction |
| 6 |
|
| 7 |
import numpy as np |
| 8 |
import pytest |
| 9 |
|
| 10 |
import av |
| 11 |
from av import AudioFrame, VideoFrame |
| 12 |
from av.audio.stream import AudioStream |
| 13 |
from av.video.stream import VideoStream |
| 14 |
|
| 15 |
from .common import TestCase, fate_suite, has_pillow |
| 16 |
|
| 17 |
WIDTH = 320 |
| 18 |
HEIGHT = 240 |
| 19 |
DURATION = 48 |
| 20 |
|
| 21 |
|
| 22 |
def write_rgb_rotate(output: av.container.OutputContainer) -> None: |
| 23 |
if not has_pillow: |
| 24 |
pytest.skip() |
| 25 |
|
| 26 |
import PIL.Image as Image |
| 27 |
|
| 28 |
output.metadata["title"] = "container" |
| 29 |
output.metadata["key"] = "value" |
| 30 |
|
| 31 |
stream = output.add_stream("mpeg4", 24) |
| 32 |
stream.width = WIDTH |
| 33 |
stream.height = HEIGHT |
| 34 |
stream.pix_fmt = "yuv420p" |
| 35 |
|
| 36 |
for frame_i in range(DURATION): |
| 37 |
frame = VideoFrame(WIDTH, HEIGHT, "rgb24") |
| 38 |
image = Image.new( |
| 39 |
"RGB", |
| 40 |
(WIDTH, HEIGHT), |
| 41 |
( |
| 42 |
int(255 * (0.5 + 0.5 * math.sin(frame_i / DURATION * 2 * math.pi))), |
| 43 |
int( |
| 44 |
255 |
| 45 |
* ( |
| 46 |
0.5 |
| 47 |
+ 0.5 |
| 48 |
* math.sin(frame_i / DURATION * 2 * math.pi + 2 / 3 * math.pi) |
| 49 |
) |
| 50 |
), |
| 51 |
int( |
| 52 |
255 |
| 53 |
* ( |
| 54 |
0.5 |
| 55 |
+ 0.5 |
| 56 |
* math.sin(frame_i / DURATION * 2 * math.pi + 4 / 3 * math.pi) |
| 57 |
) |
| 58 |
), |
| 59 |
), |
| 60 |
) |
| 61 |
frame.planes[0].update(image.tobytes()) |
| 62 |
|
| 63 |
for packet in stream.encode_lazy(frame): |
| 64 |
output.mux(packet) |
| 65 |
|
| 66 |
for packet in stream.encode_lazy(None): |
| 67 |
output.mux(packet) |
| 68 |
|
| 69 |
|
| 70 |
def assert_rgb_rotate( |
| 71 |
self, input_: av.container.InputContainer, is_dash: bool = False |
| 72 |
) -> None: |
| 73 |
# Now inspect it a little. |
| 74 |
assert len(input_.streams) == 1 |
| 75 |
assert input_.metadata.get("Title" if is_dash else "title") == "container" |
| 76 |
assert input_.metadata.get("key") is None |
| 77 |
|
| 78 |
stream = input_.streams[0] |
| 79 |
|
| 80 |
if is_dash: |
| 81 |
# The DASH format doesn't provide a duration for the stream |
| 82 |
# and so the container duration (micro seconds) is checked instead |
| 83 |
assert input_.duration == 2000000 |
| 84 |
expected_average_rate = 24 |
| 85 |
expected_duration = None |
| 86 |
expected_frames = 0 |
| 87 |
expected_id = 0 |
| 88 |
else: |
| 89 |
expected_average_rate = 24 |
| 90 |
expected_duration = 24576 |
| 91 |
expected_frames = 48 |
| 92 |
expected_id = 1 |
| 93 |
|
| 94 |
# actual stream properties |
| 95 |
assert isinstance(stream, VideoStream) |
| 96 |
assert stream.average_rate == expected_average_rate |
| 97 |
assert stream.base_rate == 24 |
| 98 |
assert stream.duration == expected_duration |
| 99 |
assert stream.guessed_rate == 24 |
| 100 |
assert stream.frames == expected_frames |
| 101 |
assert stream.id == expected_id |
| 102 |
assert stream.index == 0 |
| 103 |
assert stream.profile == "Simple Profile" |
| 104 |
assert stream.start_time == 0 |
| 105 |
assert stream.time_base == Fraction(1, 12288) |
| 106 |
assert stream.type == "video" |
| 107 |
|
| 108 |
# codec context properties |
| 109 |
assert stream.codec.name == "mpeg4" |
| 110 |
assert stream.codec.long_name == "MPEG-4 part 2" |
| 111 |
assert stream.format.name == "yuv420p" |
| 112 |
assert stream.format.width == WIDTH |
| 113 |
assert stream.format.height == HEIGHT |
| 114 |
|
| 115 |
|
| 116 |
class TestBasicVideoEncoding(TestCase): |
| 117 |
def test_default_options(self) -> None: |
| 118 |
with av.open(self.sandboxed("output.mov"), "w") as output: |
| 119 |
stream = output.add_stream("mpeg4") |
| 120 |
assert stream in output.streams.video |
| 121 |
assert stream.average_rate == Fraction(24, 1) |
| 122 |
assert stream.time_base is None |
| 123 |
|
| 124 |
# codec context properties |
| 125 |
assert stream.format.height == 480 |
| 126 |
assert stream.format.name == "yuv420p" |
| 127 |
assert stream.format.width == 640 |
| 128 |
assert stream.height == 480 |
| 129 |
assert stream.pix_fmt == "yuv420p" |
| 130 |
assert stream.width == 640 |
| 131 |
|
| 132 |
def test_encoding(self) -> None: |
| 133 |
path = self.sandboxed("rgb_rotate.mov") |
| 134 |
|
| 135 |
with av.open(path, "w") as output: |
| 136 |
write_rgb_rotate(output) |
| 137 |
with av.open(path) as input: |
| 138 |
assert_rgb_rotate(self, input) |
| 139 |
|
| 140 |
def test_encoding_with_pts(self) -> None: |
| 141 |
path = self.sandboxed("video_with_pts.mov") |
| 142 |
|
| 143 |
with av.open(path, "w") as output: |
| 144 |
stream = output.add_stream("h264", 24) |
| 145 |
assert stream in output.streams.video |
| 146 |
stream.width = WIDTH |
| 147 |
stream.height = HEIGHT |
| 148 |
stream.pix_fmt = "yuv420p" |
| 149 |
|
| 150 |
for i in range(DURATION): |
| 151 |
frame = VideoFrame(WIDTH, HEIGHT, "rgb24") |
| 152 |
frame.pts = i * 2000 |
| 153 |
frame.time_base = Fraction(1, 48000) |
| 154 |
|
| 155 |
for packet in stream.encode(frame): |
| 156 |
assert packet.time_base == Fraction(1, 24) |
| 157 |
output.mux(packet) |
| 158 |
|
| 159 |
for packet in stream.encode(None): |
| 160 |
assert packet.time_base == Fraction(1, 24) |
| 161 |
output.mux(packet) |
| 162 |
|
| 163 |
def test_encoding_with_unicode_filename(self) -> None: |
| 164 |
path = self.sandboxed("¢∞§¶•ªº.mov") |
| 165 |
|
| 166 |
with av.open(path, "w") as output: |
| 167 |
write_rgb_rotate(output) |
| 168 |
with av.open(path) as input: |
| 169 |
assert_rgb_rotate(self, input) |
| 170 |
|
| 171 |
|
| 172 |
class TestBasicAudioEncoding(TestCase): |
| 173 |
def test_default_options(self) -> None: |
| 174 |
with av.open(self.sandboxed("output.mov"), "w") as output: |
| 175 |
stream = output.add_stream("mp2") |
| 176 |
assert stream in output.streams.audio |
| 177 |
assert stream.time_base is None |
| 178 |
|
| 179 |
# codec context properties |
| 180 |
assert stream.format.name == "s16" |
| 181 |
assert stream.sample_rate == 48000 |
| 182 |
|
| 183 |
def test_transcode(self) -> None: |
| 184 |
path = self.sandboxed("audio_transcode.mov") |
| 185 |
|
| 186 |
with av.open(path, "w") as output: |
| 187 |
output.metadata["title"] = "container" |
| 188 |
output.metadata["key"] = "value" |
| 189 |
|
| 190 |
sample_rate = 48000 |
| 191 |
channel_layout = "stereo" |
| 192 |
sample_fmt = "s16" |
| 193 |
|
| 194 |
stream = output.add_stream("mp2", sample_rate) |
| 195 |
assert stream in output.streams.audio |
| 196 |
|
| 197 |
ctx = stream.codec_context |
| 198 |
ctx.sample_rate = sample_rate |
| 199 |
stream.format = sample_fmt |
| 200 |
ctx.layout = channel_layout |
| 201 |
|
| 202 |
with av.open( |
| 203 |
fate_suite("audio-reference/chorusnoise_2ch_44kHz_s16.wav") |
| 204 |
) as src: |
| 205 |
for frame in src.decode(audio=0): |
| 206 |
for packet in stream.encode(frame): |
| 207 |
output.mux(packet) |
| 208 |
|
| 209 |
for packet in stream.encode(None): |
| 210 |
output.mux(packet) |
| 211 |
|
| 212 |
with av.open(path) as container: |
| 213 |
assert len(container.streams) == 1 |
| 214 |
assert container.metadata.get("title") == "container" |
| 215 |
assert container.metadata.get("key") is None |
| 216 |
|
| 217 |
assert isinstance(container.streams[0], AudioStream) |
| 218 |
stream = container.streams[0] |
| 219 |
|
| 220 |
# codec context properties |
| 221 |
assert stream.format.name == "s16p" |
| 222 |
assert stream.sample_rate == sample_rate |
| 223 |
|
| 224 |
|
| 225 |
class TestSubtitleEncoding: |
| 226 |
def test_subtitle_muxing(self) -> None: |
| 227 |
input_ = av.open(fate_suite("sub/MovText_capability_tester.mp4")) |
| 228 |
in_stream = input_.streams.subtitles[0] |
| 229 |
|
| 230 |
output_bytes = io.BytesIO() |
| 231 |
output = av.open(output_bytes, "w", format="mp4") |
| 232 |
|
| 233 |
out_stream = output.add_stream_from_template(in_stream) |
| 234 |
|
| 235 |
for packet in input_.demux(in_stream): |
| 236 |
if packet.size == 0: |
| 237 |
continue |
| 238 |
packet.stream = out_stream |
| 239 |
output.mux(packet) |
| 240 |
|
| 241 |
output.close() |
| 242 |
output_bytes.seek(0) |
| 243 |
assert output_bytes.getvalue().startswith( |
| 244 |
b"\x00\x00\x00\x1cftypisom\x00\x00\x02\x00isomiso2mp41\x00\x00\x00\x08free" |
| 245 |
) |
| 246 |
|
| 247 |
|
| 248 |
class TestEncodeStreamSemantics(TestCase): |
| 249 |
def test_stream_index(self) -> None: |
| 250 |
with av.open(self.sandboxed("output.mov"), "w") as output: |
| 251 |
vstream = output.add_stream("mpeg4", 24) |
| 252 |
assert vstream in output.streams.video |
| 253 |
vstream.pix_fmt = "yuv420p" |
| 254 |
vstream.width = 320 |
| 255 |
vstream.height = 240 |
| 256 |
|
| 257 |
astream = output.add_stream("mp2", 48000) |
| 258 |
assert astream in output.streams.audio |
| 259 |
astream.layout = "stereo" |
| 260 |
astream.format = "s16" |
| 261 |
|
| 262 |
assert vstream.index == 0 |
| 263 |
assert astream.index == 1 |
| 264 |
|
| 265 |
vframe = VideoFrame(320, 240, "yuv420p") |
| 266 |
vpacket = vstream.encode(vframe)[0] |
| 267 |
|
| 268 |
assert vpacket.stream is vstream |
| 269 |
assert vpacket.stream_index == 0 |
| 270 |
|
| 271 |
for i in range(10): |
| 272 |
if astream.frame_size != 0: |
| 273 |
frame_size = astream.frame_size |
| 274 |
else: |
| 275 |
# decoder didn't indicate constant frame size |
| 276 |
frame_size = 1000 |
| 277 |
aframe = AudioFrame("s16", "stereo", samples=frame_size) |
| 278 |
aframe.sample_rate = 48000 |
| 279 |
apackets = astream.encode(aframe) |
| 280 |
if apackets: |
| 281 |
apacket = apackets[0] |
| 282 |
break |
| 283 |
|
| 284 |
assert apacket.stream is astream |
| 285 |
assert apacket.stream_index == 1 |
| 286 |
|
| 287 |
def test_stream_audio_resample(self) -> None: |
| 288 |
with av.open(self.sandboxed("output.mov"), "w") as output: |
| 289 |
vstream = output.add_stream("mpeg4", 24) |
| 290 |
vstream.pix_fmt = "yuv420p" |
| 291 |
vstream.width = 320 |
| 292 |
vstream.height = 240 |
| 293 |
|
| 294 |
astream = output.add_stream("aac", sample_rate=8000, layout="mono") |
| 295 |
frame_size = 512 |
| 296 |
|
| 297 |
pts_expected = [-1024, 0, 512, 1024, 1536, 2048, 2560] |
| 298 |
pts = 0 |
| 299 |
for i in range(15): |
| 300 |
aframe = AudioFrame("s16", "mono", samples=frame_size) |
| 301 |
aframe.sample_rate = 8000 |
| 302 |
aframe.time_base = Fraction(1, 1000) |
| 303 |
aframe.pts = pts |
| 304 |
aframe.dts = pts |
| 305 |
pts += 32 |
| 306 |
apackets = astream.encode(aframe) |
| 307 |
if apackets: |
| 308 |
apacket = apackets[0] |
| 309 |
assert apacket.pts == pts_expected.pop(0) |
| 310 |
assert apacket.time_base == Fraction(1, 8000) |
| 311 |
|
| 312 |
apackets = astream.encode(None) |
| 313 |
if apackets: |
| 314 |
apacket = apackets[0] |
| 315 |
assert apacket.pts == pts_expected.pop(0) |
| 316 |
assert apacket.time_base == Fraction(1, 8000) |
| 317 |
|
| 318 |
def test_set_id_and_time_base(self) -> None: |
| 319 |
with av.open(self.sandboxed("output.mov"), "w") as output: |
| 320 |
stream = output.add_stream("mp2") |
| 321 |
assert stream in output.streams.audio |
| 322 |
|
| 323 |
# set id |
| 324 |
assert stream.id == 0 |
| 325 |
stream.id = 1 |
| 326 |
assert stream.id == 1 |
| 327 |
|
| 328 |
# set time_base |
| 329 |
assert stream.time_base is None |
| 330 |
stream.time_base = Fraction(1, 48000) |
| 331 |
assert stream.time_base == Fraction(1, 48000) |
| 332 |
|
| 333 |
|
| 334 |
def encode_file_with_max_b_frames(max_b_frames: int) -> io.BytesIO: |
| 335 |
""" |
| 336 |
Create an encoded video file (or file-like object) with the given |
| 337 |
maximum run of B frames. |
| 338 |
|
| 339 |
max_b_frames: non-negative integer which is the maximum allowed run |
| 340 |
of consecutive B frames. |
| 341 |
|
| 342 |
Returns: a file-like object. |
| 343 |
""" |
| 344 |
# Create a video file that is entirely arbitrary, but with the passed |
| 345 |
# max_b_frames parameter. |
| 346 |
file = io.BytesIO() |
| 347 |
container = av.open(file, mode="w", format="mp4") |
| 348 |
stream = container.add_stream("h264", rate=30) |
| 349 |
stream.width = 640 |
| 350 |
stream.height = 480 |
| 351 |
stream.pix_fmt = "yuv420p" |
| 352 |
stream.codec_context.gop_size = 15 |
| 353 |
stream.codec_context.max_b_frames = max_b_frames |
| 354 |
|
| 355 |
for i in range(50): |
| 356 |
array = np.empty((stream.height, stream.width, 3), dtype=np.uint8) |
| 357 |
# This appears to hit a complexity "sweet spot" that makes the codec |
| 358 |
# want to use B frames. |
| 359 |
array[:, :] = (i, 0, 255 - i) |
| 360 |
frame = av.VideoFrame.from_ndarray(array, format="rgb24") |
| 361 |
for packet in stream.encode(frame): |
| 362 |
container.mux(packet) |
| 363 |
|
| 364 |
for packet in stream.encode(): |
| 365 |
container.mux(packet) |
| 366 |
|
| 367 |
container.close() |
| 368 |
file.seek(0) |
| 369 |
|
| 370 |
return file |
| 371 |
|
| 372 |
|
| 373 |
def max_b_frame_run_in_file(file: io.BytesIO) -> int: |
| 374 |
""" |
| 375 |
Count the maximum run of B frames in a file (or file-like object). |
| 376 |
|
| 377 |
file: the file or file-like object in which to count the maximum run |
| 378 |
of B frames. The file should contain just one video stream. |
| 379 |
|
| 380 |
Returns: non-negative integer which is the maximum B frame run length. |
| 381 |
""" |
| 382 |
container = av.open(file, "r") |
| 383 |
stream = container.streams.video[0] |
| 384 |
|
| 385 |
max_b_frame_run = 0 |
| 386 |
b_frame_run = 0 |
| 387 |
for frame in container.decode(stream): |
| 388 |
if frame.pict_type == av.video.frame.PictureType.B: |
| 389 |
b_frame_run += 1 |
| 390 |
else: |
| 391 |
max_b_frame_run = max(max_b_frame_run, b_frame_run) |
| 392 |
b_frame_run = 0 |
| 393 |
|
| 394 |
# Outside chance that the longest run was at the end of the file. |
| 395 |
max_b_frame_run = max(max_b_frame_run, b_frame_run) |
| 396 |
|
| 397 |
container.close() |
| 398 |
|
| 399 |
return max_b_frame_run |
| 400 |
|
| 401 |
|
| 402 |
class TestMaxBFrameEncoding(TestCase): |
| 403 |
def test_max_b_frames(self) -> None: |
| 404 |
""" |
| 405 |
Test that we never get longer runs of B frames than we asked for with |
| 406 |
the max_b_frames property. |
| 407 |
""" |
| 408 |
for max_b_frames in range(4): |
| 409 |
file = encode_file_with_max_b_frames(max_b_frames) |
| 410 |
actual_max_b_frames = max_b_frame_run_in_file(file) |
| 411 |
assert actual_max_b_frames <= max_b_frames |
| 412 |
|
| 413 |
|
| 414 |
def encode_frames_with_qminmax( |
| 415 |
frames: list[VideoFrame], shape: tuple[int, int, int], qminmax: tuple[int, int] |
| 416 |
) -> int: |
| 417 |
""" |
| 418 |
Encode a video with the given quantiser limits, and return how many encoded |
| 419 |
bytes we made in total. |
| 420 |
|
| 421 |
frames: the frames to encode |
| 422 |
shape: the (numpy) shape of the video frames |
| 423 |
qminmax: two integers with 1 <= qmin <= 31 giving the min and max quantiser. |
| 424 |
|
| 425 |
Returns: total length of the encoded bytes. |
| 426 |
""" |
| 427 |
|
| 428 |
if av.codec.Codec("h264", "w").name != "libx264": |
| 429 |
pytest.skip() |
| 430 |
|
| 431 |
file = io.BytesIO() |
| 432 |
container = av.open(file, mode="w", format="mp4") |
| 433 |
stream = container.add_stream("h264", rate=30) |
| 434 |
stream.height, stream.width, _ = shape |
| 435 |
stream.pix_fmt = "yuv420p" |
| 436 |
stream.codec_context.gop_size = 15 |
| 437 |
stream.codec_context.qmin, stream.codec_context.qmax = qminmax |
| 438 |
|
| 439 |
bytes_encoded = 0 |
| 440 |
for frame in frames: |
| 441 |
for packet in stream.encode(frame): |
| 442 |
bytes_encoded += packet.size |
| 443 |
|
| 444 |
for packet in stream.encode(): |
| 445 |
bytes_encoded += packet.size |
| 446 |
|
| 447 |
container.close() |
| 448 |
|
| 449 |
return bytes_encoded |
| 450 |
|
| 451 |
|
| 452 |
class TestQminQmaxEncoding(TestCase): |
| 453 |
def test_qmin_qmax(self) -> None: |
| 454 |
""" |
| 455 |
Test that we can set the min and max quantisers, and the encoder is reacting |
| 456 |
correctly to them. |
| 457 |
|
| 458 |
Can't see a way to get hold of the quantisers in a decoded video, so instead |
| 459 |
we'll encode the same frames with decreasing quantisers, and check that the |
| 460 |
file size increases (by a noticeable factor) each time. |
| 461 |
""" |
| 462 |
# Make a random - but repeatable - 10 frame video sequence. |
| 463 |
np.random.seed(0) |
| 464 |
frames = [] |
| 465 |
shape = (480, 640, 3) |
| 466 |
for _ in range(10): |
| 467 |
frames.append( |
| 468 |
av.VideoFrame.from_ndarray( |
| 469 |
np.random.randint(0, 256, shape, dtype=np.uint8), format="rgb24" |
| 470 |
) |
| 471 |
) |
| 472 |
|
| 473 |
# Get the size of the encoded output for different quantisers. |
| 474 |
quantisers = ((31, 31), (15, 15), (1, 1)) |
| 475 |
sizes = [ |
| 476 |
encode_frames_with_qminmax(frames, shape, qminmax) for qminmax in quantisers |
| 477 |
] |
| 478 |
|
| 479 |
factor = 1.3 # insist at least 30% larger each time |
| 480 |
assert all(small * factor < large for small, large in zip(sizes, sizes[1:])) |
| 481 |
|
| 482 |
|
| 483 |
class TestProfiles(TestCase): |
| 484 |
def test_profiles(self) -> None: |
| 485 |
""" |
| 486 |
Test that we can set different encoder profiles. |
| 487 |
""" |
| 488 |
# Let's try a video and an audio codec. |
| 489 |
file = io.BytesIO() |
| 490 |
codecs = ( |
| 491 |
("h264", 30), |
| 492 |
("aac", 48000), |
| 493 |
) |
| 494 |
|
| 495 |
for codec_name, rate in codecs: |
| 496 |
print("Testing:", codec_name) |
| 497 |
container = av.open(file, mode="w", format="mp4") |
| 498 |
stream = container.add_stream(codec_name, rate=rate) |
| 499 |
assert len(stream.profiles) >= 1 # check that we're testing something! |
| 500 |
|
| 501 |
# It should be enough to test setting and retrieving the code. That means |
| 502 |
# libav has recognised the profile and set it correctly. |
| 503 |
for profile in stream.profiles: |
| 504 |
stream.profile = profile |
| 505 |
print("Set", profile, "got", stream.profile) |
| 506 |
assert stream.profile == profile |