BlpImagePlugin.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. """
  2. Blizzard Mipmap Format (.blp)
  3. Jerome Leclanche <jerome@leclan.ch>
  4. The contents of this file are hereby released in the public domain (CC0)
  5. Full text of the CC0 license:
  6. https://creativecommons.org/publicdomain/zero/1.0/
  7. BLP1 files, used mostly in Warcraft III, are not fully supported.
  8. All types of BLP2 files used in World of Warcraft are supported.
  9. The BLP file structure consists of a header, up to 16 mipmaps of the
  10. texture
  11. Texture sizes must be powers of two, though the two dimensions do
  12. not have to be equal; 512x256 is valid, but 512x200 is not.
  13. The first mipmap (mipmap #0) is the full size image; each subsequent
  14. mipmap halves both dimensions. The final mipmap should be 1x1.
  15. BLP files come in many different flavours:
  16. * JPEG-compressed (type == 0) - only supported for BLP1.
  17. * RAW images (type == 1, encoding == 1). Each mipmap is stored as an
  18. array of 8-bit values, one per pixel, left to right, top to bottom.
  19. Each value is an index to the palette.
  20. * DXT-compressed (type == 1, encoding == 2):
  21. - DXT1 compression is used if alpha_encoding == 0.
  22. - An additional alpha bit is used if alpha_depth == 1.
  23. - DXT3 compression is used if alpha_encoding == 1.
  24. - DXT5 compression is used if alpha_encoding == 7.
  25. """
  26. from __future__ import annotations
  27. __lazy_modules__ = {"io", "struct"}
  28. import abc
  29. import os
  30. import struct
  31. from enum import IntEnum
  32. from io import BytesIO
  33. from . import Image, ImageFile
  34. TYPE_CHECKING = False
  35. if TYPE_CHECKING:
  36. from typing import IO
  37. class Format(IntEnum):
  38. JPEG = 0
  39. class Encoding(IntEnum):
  40. UNCOMPRESSED = 1
  41. DXT = 2
  42. UNCOMPRESSED_RAW_BGRA = 3
  43. class AlphaEncoding(IntEnum):
  44. DXT1 = 0
  45. DXT3 = 1
  46. DXT5 = 7
  47. def unpack_565(i: int) -> tuple[int, int, int]:
  48. return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3
  49. def decode_dxt1(
  50. data: bytes, alpha: bool = False
  51. ) -> tuple[bytearray, bytearray, bytearray, bytearray]:
  52. """
  53. input: one "row" of data (i.e. will produce 4*width pixels)
  54. """
  55. blocks = len(data) // 8 # number of blocks in row
  56. ret = (bytearray(), bytearray(), bytearray(), bytearray())
  57. for block_index in range(blocks):
  58. # Decode next 8-byte block.
  59. idx = block_index * 8
  60. color0, color1, bits = struct.unpack_from("<HHI", data, idx)
  61. r0, g0, b0 = unpack_565(color0)
  62. r1, g1, b1 = unpack_565(color1)
  63. # Decode this block into 4x4 pixels
  64. # Accumulate the results onto our 4 row accumulators
  65. for j in range(4):
  66. for i in range(4):
  67. # get next control op and generate a pixel
  68. control = bits & 3
  69. bits = bits >> 2
  70. a = 0xFF
  71. if control == 0:
  72. r, g, b = r0, g0, b0
  73. elif control == 1:
  74. r, g, b = r1, g1, b1
  75. elif control == 2:
  76. if color0 > color1:
  77. r = (2 * r0 + r1) // 3
  78. g = (2 * g0 + g1) // 3
  79. b = (2 * b0 + b1) // 3
  80. else:
  81. r = (r0 + r1) // 2
  82. g = (g0 + g1) // 2
  83. b = (b0 + b1) // 2
  84. elif control == 3:
  85. if color0 > color1:
  86. r = (2 * r1 + r0) // 3
  87. g = (2 * g1 + g0) // 3
  88. b = (2 * b1 + b0) // 3
  89. else:
  90. r, g, b, a = 0, 0, 0, 0
  91. if alpha:
  92. ret[j].extend([r, g, b, a])
  93. else:
  94. ret[j].extend([r, g, b])
  95. return ret
  96. def decode_dxt3(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
  97. """
  98. input: one "row" of data (i.e. will produce 4*width pixels)
  99. """
  100. blocks = len(data) // 16 # number of blocks in row
  101. ret = (bytearray(), bytearray(), bytearray(), bytearray())
  102. for block_index in range(blocks):
  103. idx = block_index * 16
  104. block = data[idx : idx + 16]
  105. # Decode next 16-byte block.
  106. bits = struct.unpack_from("<8B", block)
  107. color0, color1 = struct.unpack_from("<HH", block, 8)
  108. (code,) = struct.unpack_from("<I", block, 12)
  109. r0, g0, b0 = unpack_565(color0)
  110. r1, g1, b1 = unpack_565(color1)
  111. for j in range(4):
  112. high = False # Do we want the higher bits?
  113. for i in range(4):
  114. alphacode_index = (4 * j + i) // 2
  115. a = bits[alphacode_index]
  116. if high:
  117. high = False
  118. a >>= 4
  119. else:
  120. high = True
  121. a &= 0xF
  122. a *= 17 # We get a value between 0 and 15
  123. color_code = (code >> 2 * (4 * j + i)) & 0x03
  124. if color_code == 0:
  125. r, g, b = r0, g0, b0
  126. elif color_code == 1:
  127. r, g, b = r1, g1, b1
  128. elif color_code == 2:
  129. r = (2 * r0 + r1) // 3
  130. g = (2 * g0 + g1) // 3
  131. b = (2 * b0 + b1) // 3
  132. elif color_code == 3:
  133. r = (2 * r1 + r0) // 3
  134. g = (2 * g1 + g0) // 3
  135. b = (2 * b1 + b0) // 3
  136. ret[j].extend([r, g, b, a])
  137. return ret
  138. def decode_dxt5(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]:
  139. """
  140. input: one "row" of data (i.e. will produce 4 * width pixels)
  141. """
  142. blocks = len(data) // 16 # number of blocks in row
  143. ret = (bytearray(), bytearray(), bytearray(), bytearray())
  144. for block_index in range(blocks):
  145. idx = block_index * 16
  146. block = data[idx : idx + 16]
  147. # Decode next 16-byte block.
  148. a0, a1 = struct.unpack_from("<BB", block)
  149. bits = struct.unpack_from("<6B", block, 2)
  150. alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
  151. alphacode2 = bits[0] | (bits[1] << 8)
  152. color0, color1 = struct.unpack_from("<HH", block, 8)
  153. (code,) = struct.unpack_from("<I", block, 12)
  154. r0, g0, b0 = unpack_565(color0)
  155. r1, g1, b1 = unpack_565(color1)
  156. for j in range(4):
  157. for i in range(4):
  158. # get next control op and generate a pixel
  159. alphacode_index = 3 * (4 * j + i)
  160. if alphacode_index <= 12:
  161. alphacode = (alphacode2 >> alphacode_index) & 0x07
  162. elif alphacode_index == 15:
  163. alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
  164. else: # alphacode_index >= 18 and alphacode_index <= 45
  165. alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
  166. if alphacode == 0:
  167. a = a0
  168. elif alphacode == 1:
  169. a = a1
  170. elif a0 > a1:
  171. a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
  172. elif alphacode == 6:
  173. a = 0
  174. elif alphacode == 7:
  175. a = 255
  176. else:
  177. a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
  178. color_code = (code >> 2 * (4 * j + i)) & 0x03
  179. if color_code == 0:
  180. r, g, b = r0, g0, b0
  181. elif color_code == 1:
  182. r, g, b = r1, g1, b1
  183. elif color_code == 2:
  184. r = (2 * r0 + r1) // 3
  185. g = (2 * g0 + g1) // 3
  186. b = (2 * b0 + b1) // 3
  187. elif color_code == 3:
  188. r = (2 * r1 + r0) // 3
  189. g = (2 * g1 + g0) // 3
  190. b = (2 * b1 + b0) // 3
  191. ret[j].extend([r, g, b, a])
  192. return ret
  193. class BLPFormatError(NotImplementedError):
  194. pass
  195. def _accept(prefix: bytes) -> bool:
  196. return prefix.startswith((b"BLP1", b"BLP2"))
  197. class BlpImageFile(ImageFile.ImageFile):
  198. """
  199. Blizzard Mipmap Format
  200. """
  201. format = "BLP"
  202. format_description = "Blizzard Mipmap Format"
  203. def _open(self) -> None:
  204. assert self.fp is not None
  205. self.magic = self.fp.read(4)
  206. if not _accept(self.magic):
  207. msg = f"Bad BLP magic {repr(self.magic)}"
  208. raise BLPFormatError(msg)
  209. compression = struct.unpack("<i", self.fp.read(4))[0]
  210. if self.magic == b"BLP1":
  211. alpha = struct.unpack("<I", self.fp.read(4))[0] != 0
  212. else:
  213. encoding = struct.unpack("<b", self.fp.read(1))[0]
  214. alpha = struct.unpack("<b", self.fp.read(1))[0] != 0
  215. alpha_encoding = struct.unpack("<b", self.fp.read(1))[0]
  216. self.fp.seek(1, os.SEEK_CUR) # mips
  217. self._size = struct.unpack("<II", self.fp.read(8))
  218. args: tuple[int, int, bool] | tuple[int, int, bool, int]
  219. if self.magic == b"BLP1":
  220. encoding = struct.unpack("<i", self.fp.read(4))[0]
  221. self.fp.seek(4, os.SEEK_CUR) # subtype
  222. args = (compression, encoding, alpha)
  223. offset = 28
  224. else:
  225. args = (compression, encoding, alpha, alpha_encoding)
  226. offset = 20
  227. decoder = self.magic.decode()
  228. self._mode = "RGBA" if alpha else "RGB"
  229. self.tile = [ImageFile._Tile(decoder, (0, 0, *self.size), offset, args)]
  230. class _BLPBaseDecoder(abc.ABC, ImageFile.PyDecoder):
  231. _pulls_fd = True
  232. def decode(self, buffer: Image.DecoderInput) -> tuple[int, int]:
  233. try:
  234. self._read_header()
  235. self._load()
  236. except struct.error as e:
  237. msg = "Truncated BLP file"
  238. raise OSError(msg) from e
  239. return -1, 0
  240. @abc.abstractmethod
  241. def _load(self) -> None:
  242. pass
  243. def _read_header(self) -> None:
  244. self._offsets = struct.unpack("<16I", self._safe_read(16 * 4))
  245. self._lengths = struct.unpack("<16I", self._safe_read(16 * 4))
  246. def _safe_read(self, length: int) -> bytes:
  247. assert self.fd is not None
  248. return ImageFile._safe_read(self.fd, length)
  249. def _read_palette(self) -> list[tuple[int, int, int, int]]:
  250. ret = []
  251. for i in range(256):
  252. try:
  253. b, g, r, a = struct.unpack("<4B", self._safe_read(4))
  254. except struct.error:
  255. break
  256. ret.append((b, g, r, a))
  257. return ret
  258. def _read_bgra(
  259. self, palette: list[tuple[int, int, int, int]], alpha: bool
  260. ) -> bytearray:
  261. data = bytearray()
  262. _data = BytesIO(self._safe_read(self._lengths[0]))
  263. while True:
  264. try:
  265. (offset,) = struct.unpack("<B", _data.read(1))
  266. except struct.error:
  267. break
  268. b, g, r, a = palette[offset]
  269. d: tuple[int, ...] = (r, g, b)
  270. if alpha:
  271. d += (a,)
  272. data.extend(d)
  273. return data
  274. class BLP1Decoder(_BLPBaseDecoder):
  275. def _load(self) -> None:
  276. _compression, _encoding, alpha = self.args
  277. if _compression == Format.JPEG:
  278. self._decode_jpeg_stream()
  279. elif _compression == 1:
  280. if _encoding in (4, 5):
  281. palette = self._read_palette()
  282. data = self._read_bgra(palette, alpha)
  283. self.set_as_raw(data)
  284. else:
  285. msg = f"Unsupported BLP encoding {repr(_encoding)}"
  286. raise BLPFormatError(msg)
  287. else:
  288. msg = f"Unsupported BLP compression {repr(_encoding)}"
  289. raise BLPFormatError(msg)
  290. def _decode_jpeg_stream(self) -> None:
  291. from .JpegImagePlugin import JpegImageFile
  292. (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
  293. jpeg_header = self._safe_read(jpeg_header_size)
  294. assert self.fd is not None
  295. self._safe_read(self._offsets[0] - self.fd.tell()) # What IS this?
  296. data = self._safe_read(self._lengths[0])
  297. data = jpeg_header + data
  298. image = JpegImageFile(BytesIO(data))
  299. Image._decompression_bomb_check(image.size)
  300. if image.mode == "CMYK":
  301. args = image.tile[0].args
  302. assert isinstance(args, tuple)
  303. image.tile = [image.tile[0]._replace(args=(args[0], "CMYK"))]
  304. self.set_as_raw(image.convert("RGB").tobytes(), "BGR")
  305. class BLP2Decoder(_BLPBaseDecoder):
  306. def _load(self) -> None:
  307. _compression, _encoding, alpha, _alpha_encoding = self.args
  308. palette = self._read_palette()
  309. assert self.fd is not None
  310. self.fd.seek(self._offsets[0])
  311. if _compression == 1:
  312. # Uncompressed or DirectX compression
  313. if _encoding == Encoding.UNCOMPRESSED:
  314. data = self._read_bgra(palette, alpha)
  315. elif _encoding == Encoding.DXT:
  316. data = bytearray()
  317. if _alpha_encoding == AlphaEncoding.DXT1:
  318. linesize = (self.state.xsize + 3) // 4 * 8
  319. for yb in range((self.state.ysize + 3) // 4):
  320. for d in decode_dxt1(self._safe_read(linesize), alpha):
  321. data += d
  322. elif _alpha_encoding == AlphaEncoding.DXT3:
  323. linesize = (self.state.xsize + 3) // 4 * 16
  324. for yb in range((self.state.ysize + 3) // 4):
  325. for d in decode_dxt3(self._safe_read(linesize)):
  326. data += d
  327. elif _alpha_encoding == AlphaEncoding.DXT5:
  328. linesize = (self.state.xsize + 3) // 4 * 16
  329. for yb in range((self.state.ysize + 3) // 4):
  330. for d in decode_dxt5(self._safe_read(linesize)):
  331. data += d
  332. else:
  333. msg = f"Unsupported alpha encoding {repr(_alpha_encoding)}"
  334. raise BLPFormatError(msg)
  335. else:
  336. msg = f"Unknown BLP encoding {repr(_encoding)}"
  337. raise BLPFormatError(msg)
  338. else:
  339. msg = f"Unknown BLP compression {repr(_compression)}"
  340. raise BLPFormatError(msg)
  341. self.set_as_raw(data)
  342. class BLPEncoder(ImageFile.PyEncoder):
  343. _pushes_fd = True
  344. def _write_palette(self) -> bytes:
  345. data = b""
  346. assert self.im is not None
  347. palette = self.im.getpalette("RGBA")
  348. for i in range(len(palette) // 4):
  349. r, g, b, a = palette[i * 4 : (i + 1) * 4]
  350. data += struct.pack("<4B", b, g, r, a)
  351. while len(data) < 256 * 4:
  352. data += b"\x00" * 4
  353. return data
  354. def encode(self, bufsize: int) -> tuple[int, int, bytes]:
  355. palette_data = self._write_palette()
  356. offset = 20 + 16 * 4 * 2 + len(palette_data)
  357. data = struct.pack("<16I", offset, *((0,) * 15))
  358. assert self.im is not None
  359. w, h = self.im.size
  360. data += struct.pack("<16I", w * h, *((0,) * 15))
  361. data += palette_data
  362. for y in range(h):
  363. for x in range(w):
  364. data += struct.pack("<B", self.im.getpixel((x, y)))
  365. return len(data), 0, data
  366. def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None:
  367. if im.mode != "P":
  368. msg = "Unsupported BLP image mode"
  369. raise ValueError(msg)
  370. magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
  371. fp.write(magic)
  372. assert im.palette is not None
  373. fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
  374. alpha_depth = 1 if im.palette.mode == "RGBA" else 0
  375. if magic == b"BLP1":
  376. fp.write(struct.pack("<L", alpha_depth))
  377. else:
  378. fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
  379. fp.write(struct.pack("<b", alpha_depth))
  380. fp.write(struct.pack("<b", 0)) # alpha encoding
  381. fp.write(struct.pack("<b", 0)) # mips
  382. fp.write(struct.pack("<II", *im.size))
  383. if magic == b"BLP1":
  384. fp.write(struct.pack("<i", 5))
  385. fp.write(struct.pack("<i", 0))
  386. ImageFile._save(im, fp, [ImageFile._Tile("BLP", (0, 0, *im.size), 0, im.mode)])
  387. Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
  388. Image.register_extension(BlpImageFile.format, ".blp")
  389. Image.register_decoder("BLP1", BLP1Decoder)
  390. Image.register_decoder("BLP2", BLP2Decoder)
  391. Image.register_save(BlpImageFile.format, _save)
  392. Image.register_encoder("BLP", BLPEncoder)