forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB722dffdTahinli2 months ago3200 commits

gen-bmp-shapes.py168 lines, 6.2 KiBHistoryRawDownload
1"""Write the BMP shapes ImageMagick will not emit.
2
3ImageMagick covers the ordinary files (1/4/8-bit palettes, RLE8, 24-bit), but
4it has no switch for a 16-bit bitfield file, a top-down row order, a 32-bit
5file with an alpha channel, or the 12-byte OS/2 header -- all of which are
6shapes a decoder meets in the wild. Each is written here from a raw RGBA dump
7so the pixels are the same picture as the rest of the corpus.
8"""
9
10import struct
11import sys
12
13out, raw, width, height = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
14rgba = open(raw, "rb").read()
15rgba_alpha = open(sys.argv[5], "rb").read()
16
17
18def pixel(source, x, y):
19 at = (y * width + x) * 4
20 return source[at], source[at + 1], source[at + 2], source[at + 3]
21
22
23def rows(top_down, source=None):
24 source = rgba if source is None else source
25 order = range(height) if top_down else range(height - 1, -1, -1)
26 return [[pixel(source, x, y) for x in range(width)] for y in order]
27
28
29def file_header(offset, size):
30 return b"BM" + struct.pack("<IHHI", size, 0, 0, offset)
31
32
33def info_v3(bits, compression, masks=()):
34 header = struct.pack(
35 "<IiiHHIIiiII", 40, width, -height if masks == "topdown" else height,
36 1, bits, compression, 0, 2835, 2835, 0, 0,
37 )
38 return header
39
40
41def write(name, info, body, extra=b""):
42 offset = 14 + len(info) + len(extra)
43 blob = file_header(offset, offset + len(body)) + info + extra + body
44 open(f"{out}/{name}", "wb").write(blob)
45
46
47def packed(bits_per_pixel, encode, top_down=False, source=None):
48 """Pack rows to the format's four-byte row alignment."""
49 stride = ((width * bits_per_pixel + 31) // 32) * 4
50 body = bytearray()
51 for row in rows(top_down, source):
52 line = bytearray()
53 for pix in row:
54 line += encode(pix)
55 line += b"\0" * (stride - len(line))
56 body += line
57 return bytes(body)
58
59
60# 16-bit, 5-6-5, declared through BI_BITFIELDS masks.
61masks565 = struct.pack("<III", 0xF800, 0x07E0, 0x001F)
62body = packed(16, lambda p: struct.pack(
63 "<H", ((p[0] >> 3) << 11) | ((p[1] >> 2) << 5) | (p[2] >> 3)))
64write("bf565.bmp", info_v3(16, 3), body, masks565)
65
66# 16-bit, 5-5-5, the layout BI_RGB implies at this depth (no mask block).
67body = packed(16, lambda p: struct.pack(
68 "<H", ((p[0] >> 3) << 10) | ((p[1] >> 3) << 5) | (p[2] >> 3)))
69write("rgb555.bmp", info_v3(16, 0), body)
70
71# 32-bit with an alpha channel: the fourth mask only has a home in the
72# BITMAPV4HEADER, whose 108 bytes carry all four masks plus a colour space.
73body = packed(32, lambda p: bytes([p[2], p[1], p[0], p[3]]), source=rgba_alpha)
74v4 = struct.pack(
75 "<IiiHHIIiiII", 108, width, height, 1, 32, 3, len(body), 2835, 2835, 0, 0,
76) + struct.pack(
77 "<IIII", 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000,
78) + b"BGRs" + b"\0" * 48
79write("alpha32.bmp", v4, body)
80
81# Top-down rows: a negative height, first row stored first.
82body = packed(24, lambda p: bytes([p[2], p[1], p[0]]), top_down=True)
83info = struct.pack("<IiiHHIIiiII", 40, width, -height, 1, 24, 0, 0, 2835, 2835, 0, 0)
84write("topdown24.bmp", info, body)
85
86# RLE4, from the 4-bit palette file ImageMagick wrote: same palette, same
87# indices, only the run encoding differs -- ImageMagick's RLE switch produces
88# an 8-bit file whatever the colour count, so the 4-bit run path has no other
89# source.
90def rle4(source_name, name):
91 src = open(f"{out}/{source_name}", "rb").read()
92 offset, = struct.unpack_from("<I", src, 10)
93 w, h = struct.unpack_from("<ii", src, 18)
94 colours, = struct.unpack_from("<I", src, 46)
95 colours = colours or 16
96 palette = src[14 + 40:14 + 40 + colours * 4]
97 stride = ((w * 4 + 31) // 32) * 4
98 body = bytearray()
99 for y in range(h):
100 line = src[offset + y * stride:offset + (y + 1) * stride]
101 indices = []
102 for x in range(w):
103 byte = line[x // 2]
104 indices.append(byte >> 4 if x % 2 == 0 else byte & 0x0F)
105 x = 0
106 while x < w:
107 run = 1
108 while x + run < w and run < 254 and indices[x + run] == indices[x]:
109 run += 1
110 if run >= 2:
111 body += bytes([run, indices[x] << 4 | indices[x]])
112 x += run
113 continue
114 # A literal run needs at least three pixels to be legal; below that
115 # the encoded form is a run of one.
116 end = x
117 while end < w and end - x < 254:
118 same = 1
119 while end + same < w and indices[end + same] == indices[end]:
120 same += 1
121 if same >= 3:
122 break
123 end += same
124 count = end - x
125 if count < 3:
126 body += bytes([1, indices[x] << 4])
127 x += 1
128 continue
129 nibbles = bytearray()
130 for i in range(0, count, 2):
131 high = indices[x + i] << 4
132 low = indices[x + i + 1] if i + 1 < count else 0
133 nibbles.append(high | low)
134 while len(nibbles) % 2:
135 nibbles.append(0)
136 body += bytes([0, count]) + nibbles
137 x = end
138 body += b"\x00\x00"
139 body = body[:-2] + b"\x00\x01"
140 info = struct.pack("<IiiHHIIiiII", 40, w, h, 1, 4, 2, len(body), 2835, 2835,
141 colours, 0)
142 write(name, info, bytes(body), palette)
143
144
145rle4("pal4.bmp", "rle4.bmp")
146
147# BI_PNG and BI_JPEG: a BMP file header and info header wrapped around a whole
148# file of another format, which is what a printer driver or a clipboard writes.
149def wrap(name, payload_path, compression):
150 payload = open(payload_path, "rb").read()
151 info = struct.pack(
152 "<IiiHHIIiiII", 40, width, height, 1, 0, compression, len(payload),
153 2835, 2835, 0, 0,
154 )
155 write(name, info, payload)
156
157
158wrap("embedded-png.bmp", sys.argv[6], 5)
159wrap("embedded-jpeg.bmp", sys.argv[7], 4)
160
161# The OS/2 v2 header, in the 16-byte form writers actually emit: 32-bit
162# dimensions like a Windows header, and nothing after them.
163body = packed(24, lambda p: bytes([p[2], p[1], p[0]]))
164write("os2v2.bmp", struct.pack("<IiiHH", 16, width, height, 1, 24), body)
165
166# The 12-byte OS/2 v1 header, whose dimensions are 16-bit and unsigned.
167body = packed(24, lambda p: bytes([p[2], p[1], p[0]]))
168write("os2v1.bmp", struct.pack("<IhhHH", 12, width, height, 1, 24), body)