69 lines
3.3 KiB
Python
69 lines
3.3 KiB
Python
"""Small bounded decoder for the supplied non-interlaced 8-bit PNG textures."""
|
|
from pathlib import Path
|
|
import struct
|
|
import zlib
|
|
|
|
from omt import FormatError, Reader
|
|
|
|
|
|
def read_png(path: Path) -> dict:
|
|
r = Reader(path.read_bytes())
|
|
if r.take(8) != b'\x89PNG\r\n\x1a\n': raise FormatError('Invalid PNG signature')
|
|
header, palette, transparency = None, None, b''
|
|
compressed = bytearray()
|
|
ended = False
|
|
while r.position < len(r.data):
|
|
size = r.u32()
|
|
tag, data = r.take(4), r.take(size)
|
|
if r.u32() != zlib.crc32(tag+data): raise FormatError('PNG checksum mismatch')
|
|
if tag == b'IHDR': header = struct.unpack('>IIBBBBB',data)
|
|
elif tag == b'PLTE': palette = data
|
|
elif tag == b'tRNS': transparency = data
|
|
elif tag == b'IDAT': compressed.extend(data)
|
|
elif tag == b'IEND': ended = True; break
|
|
elif tag[0] & 32 == 0: raise FormatError(f'Unsupported critical PNG chunk {tag!r}')
|
|
if not ended or not header: raise FormatError('Incomplete PNG')
|
|
r.end()
|
|
width,height,depth,colour,compression,filter_method,interlace = header
|
|
if depth != 8 or compression or filter_method or interlace: raise FormatError('Only non-interlaced 8-bit PNG is supported')
|
|
channels = {0:1,2:3,3:1,4:2,6:4}.get(colour)
|
|
if not channels or not width or not height or width*height > 16777216: raise FormatError('Invalid PNG dimensions/colour')
|
|
stride = width*channels
|
|
expected = (stride+1)*height
|
|
decoder = zlib.decompressobj()
|
|
raw = decoder.decompress(bytes(compressed),expected+1)
|
|
if len(raw)!=expected or not decoder.eof or decoder.unused_data or decoder.unconsumed_tail:
|
|
raise FormatError('Invalid PNG decoded length')
|
|
rgba, previous = bytearray(), bytearray(stride)
|
|
for y in range(height):
|
|
mode = raw[y*(stride+1)]
|
|
scan = bytearray(raw[y*(stride+1)+1:(y+1)*(stride+1)])
|
|
if mode > 4: raise FormatError('Invalid PNG scanline filter')
|
|
for x in range(stride):
|
|
a = scan[x-channels] if x>=channels else 0
|
|
b = previous[x]
|
|
c = previous[x-channels] if x>=channels else 0
|
|
if mode==1: predict = a
|
|
elif mode==2: predict = b
|
|
elif mode==3: predict = (a+b)//2
|
|
elif mode==4:
|
|
p=a+b-c;pa,pb,pc=abs(p-a),abs(p-b),abs(p-c)
|
|
predict = a if pa<=pb and pa<=pc else b if pb<=pc else c
|
|
else: predict=0
|
|
scan[x] = (scan[x]+predict)&255
|
|
for x in range(width):
|
|
pixel = scan[x*channels:(x+1)*channels]
|
|
if colour==3:
|
|
index=pixel[0]
|
|
if palette is None or index*3+3>len(palette): raise FormatError('PNG pixel outside palette')
|
|
rgba.extend((*palette[index*3:index*3+3],transparency[index] if index<len(transparency) else 255))
|
|
elif colour==6: rgba.extend(pixel)
|
|
elif colour==2:
|
|
alpha=0 if transparency and tuple(pixel)==struct.unpack('>3H',transparency) else 255
|
|
rgba.extend((*pixel,alpha))
|
|
else:
|
|
alpha=pixel[1] if colour==4 else 0 if transparency and pixel[0]==struct.unpack('>H',transparency)[0] else 255
|
|
rgba.extend((pixel[0],pixel[0],pixel[0],alpha))
|
|
previous=scan
|
|
return {'width':width,'height':height,'rgba':bytes(rgba)}
|