"""`hhstream.png`: the hand-rolled PNG encoder, checked against zlib itself. There is no image library in the unit environment (the whole point of this encoder is that it needs none), so the decoder below is written from the PNG spec too. That is not a weakness of the test: it re-derives the scanlines from the file the encoder produced and compares them with the pixels that went in, which is exactly the property that matters -- a wrong stride, a wrong colour type or a byte order slip all show up as a mismatch rather than as a file that merely starts with the right eight bytes. """ from __future__ import annotations import struct import zlib import pytest from hhstream.png import encode_rgb SIGNATURE = b"\x89PNG\r\n\x1a\n" def decode(png: bytes) -> tuple[int, int, bytes]: """Return (width, height, rgb scanlines) for a PNG this encoder can produce.""" assert png.startswith(SIGNATURE), "missing PNG signature" offset = len(SIGNATURE) width = height = None idat = b"" while offset < len(png): (length,) = struct.unpack(">I", png[offset:offset + 4]) kind = png[offset + 4:offset + 8] payload = png[offset + 8:offset + 8 + length] crc = png[offset + 8 + length:offset + 12 + length] assert struct.unpack(">I", crc)[0] == zlib.crc32(kind + payload) & 0xFFFFFFFF, ( f"bad CRC on {kind!r} chunk -- the file is corrupt" ) if kind == b"IHDR": width, height, depth, color, comp, filt, interlace = struct.unpack(">IIBBBBB", payload) assert (depth, color, comp, filt, interlace) == (8, 2, 0, 0, 0) elif kind == b"IDAT": idat += payload offset += 12 + length assert width is not None and height is not None, "no IHDR chunk in the file" raw = zlib.decompress(idat) stride = width * 3 assert len(raw) == height * (1 + stride), "the scanline payload is the wrong length" out = bytearray() for row in range(height): start = row * (1 + stride) assert raw[start] == 0, "every scanline should be written unfiltered" out += raw[start + 1:start + 1 + stride] return width, height, bytes(out) def bgrx(width: int, height: int, stride: int | None = None) -> bytes: """A frame in the compositor's memory order: B, G, R, X per pixel.""" stride = stride if stride is not None else width * 4 out = bytearray() for y in range(height): row = bytearray() for x in range(width): row += bytes(((x * 3) % 256, (y * 5) % 256, (x + y) % 256, 0x00)) row += b"\xee" * (stride - width * 4) # row padding, if any out += row return bytes(out) def test_pixels_round_trip_in_the_right_channel_order(): frame = bgrx(4, 2) width, height, rgb = decode(encode_rgb(4, 2, 16, frame)) assert (width, height) == (4, 2) # Pixel (x, y) went in as B,G,R,X; it must come out as R,G,B. for y in range(2): for x in range(4): b, g, r, _ = frame[(y * 4 + x) * 4:(y * 4 + x) * 4 + 4] assert rgb[(y * 4 + x) * 3:(y * 4 + x) * 3 + 3] == bytes((r, g, b)), ( f"channel order is wrong at ({x}, {y})" ) def test_a_padded_stride_is_honoured_rather_than_assumed(): """`stride` is the compositor's row pitch, not `width * 4`. Assuming it would shear the image, which is the bug grim 1.5 shipped -- so the padding bytes below are deliberately not black: if they leak into the output the comparison fails. """ width, height, stride = 3, 2, 20 # 12 meaningful bytes, 8 bytes of padding frame = bgrx(width, height, stride) _, _, rgb = decode(encode_rgb(width, height, stride, frame)) assert rgb == b"".join( bytes(reversed(frame[(y * stride + x * 4):(y * stride + x * 4) + 3])) for y in range(height) for x in range(width) ) def test_a_memoryview_of_a_mapping_is_accepted(): """The caller passes `memoryview(shm_map)`, not `bytes`.""" frame = bgrx(2, 2) assert encode_rgb(2, 2, 8, memoryview(frame)) == encode_rgb(2, 2, 8, frame) @pytest.mark.parametrize( "kwargs, message", [ (dict(width=0, height=4, stride=0), "positive size"), (dict(width=4, height=0, stride=16), "positive size"), (dict(width=4, height=4, stride=8), "too small"), ], ) def test_bad_geometry_is_rejected_before_anything_is_encoded(kwargs, message): with pytest.raises(ValueError, match=message): encode_rgb(pixels=b"\x00" * 64, **kwargs) def test_a_short_buffer_is_rejected_rather_than_encoding_garbage(): with pytest.raises(ValueError, match="needs"): encode_rgb(4, 4, 16, b"\x00" * 63)