Files
mtusi2026lab6/src/messenger/attachments/infrastructure/png.py
T

119 lines
3.8 KiB
Python

import struct
import zlib
from collections.abc import Iterator
type PngHeader = tuple[int, int, int, int, int, int, int]
SIGNATURE = b"\x89PNG\r\n\x1a\n"
HEADER_BYTES = 13
CHUNK_OVERHEAD = 12
BLOCK_BYTES = 65_536
MAX_FILTER = 4
PIXELS = {
0: (1, (1, 2, 4, 8, 16)),
2: (3, (8, 16)),
3: (1, (1, 2, 4, 8)),
4: (2, (8, 16)),
6: (4, (8, 16)),
}
ADAM7 = (
(0, 0, 8, 8),
(4, 0, 8, 8),
(0, 4, 4, 8),
(2, 0, 4, 4),
(0, 2, 2, 4),
(1, 0, 2, 2),
(0, 1, 1, 2),
)
def _chunks(data: bytes) -> Iterator[tuple[bytes, memoryview]]:
view = memoryview(data)
offset = len(SIGNATURE)
while offset + CHUNK_OVERHEAD <= len(data):
size = struct.unpack_from(">I", data, offset)[0]
kind = data[offset + 4 : offset + 8]
start, end = offset + 8, offset + 8 + size
if end + 4 > len(data):
raise ValueError("truncated PNG chunk")
yield kind, view[start:end]
if kind == b"IEND":
return
offset = end + 4
raise ValueError("missing PNG end")
def read_png_header(data: bytes) -> PngHeader:
chunks = _chunks(data)
kind, header = next(chunks)
if kind != b"IHDR" or len(header) != HEADER_BYTES:
raise ValueError("invalid first PNG header")
if any(kind == b"IHDR" for kind, _ in chunks):
raise ValueError("duplicate PNG header")
return struct.unpack(">IIBBBBB", header)
def _scanlines(header: PngHeader) -> Iterator[tuple[int, int]]:
width, height, depth, color, compression, filtering, interlace = header
samples, depths = PIXELS[color]
if depth not in depths or compression or filtering or interlace not in (0, 1):
raise ValueError("invalid PNG header")
passes = ADAM7 if interlace else ((0, 0, 1, 1),)
for x, y, dx, dy in passes:
columns, rows = (width - x + dx - 1) // dx, (height - y + dy - 1) // dy
if columns > 0 and rows > 0:
stride = 1 + (columns * samples * depth + 7) // 8
yield stride, stride * rows
def _idat(data: bytes) -> Iterator[memoryview]:
started = ended = False
for kind, payload in _chunks(data):
if kind == b"IDAT":
if ended:
raise ValueError("nonconsecutive PNG image data")
started = True
for position in range(0, len(payload), BLOCK_BYTES):
yield payload[position : position + BLOCK_BYTES]
elif started:
ended = True
def _inflate(data: bytes) -> Iterator[bytes]:
decoder = zlib.decompressobj()
for block in _idat(data):
if decoder.eof:
continue
pending = block
while True:
decoded = decoder.decompress(pending, BLOCK_BYTES)
yield decoded
pending = decoder.unconsumed_tail
if decoder.eof or (not pending and len(decoded) < BLOCK_BYTES):
break
if not decoder.eof:
raise ValueError("incomplete PNG compressed data")
def verify_png_pixels(data: bytes, header: PngHeader) -> None:
passes = _scanlines(header)
stride, remaining = next(passes)
offset = 0
for decoded in _inflate(data):
cursor = 0
while cursor < len(decoded):
if not remaining:
stride, remaining = next(passes, (0, 0))
offset = 0
if not remaining:
raise ValueError("extra PNG pixel data")
size = min(remaining, len(decoded) - cursor)
filters = decoded[cursor + (-offset % stride) : cursor + size : stride]
if max(filters, default=0) > MAX_FILTER:
raise ValueError("invalid PNG filter")
cursor += size
offset += size
remaining -= size
if remaining or next(passes, None) is not None:
raise ValueError("incomplete PNG pixel data")