BlpImagePlugin.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. import os
  27. import struct
  28. from enum import IntEnum
  29. from io import BytesIO
  30. from . import Image, ImageFile
  31. from ._deprecate import deprecate
  32. class Format(IntEnum):
  33. JPEG = 0
  34. class Encoding(IntEnum):
  35. UNCOMPRESSED = 1
  36. DXT = 2
  37. UNCOMPRESSED_RAW_BGRA = 3
  38. class AlphaEncoding(IntEnum):
  39. DXT1 = 0
  40. DXT3 = 1
  41. DXT5 = 7
  42. def __getattr__(name):
  43. for enum, prefix in {
  44. Format: "BLP_FORMAT_",
  45. Encoding: "BLP_ENCODING_",
  46. AlphaEncoding: "BLP_ALPHA_ENCODING_",
  47. }.items():
  48. if name.startswith(prefix):
  49. name = name[len(prefix) :]
  50. if name in enum.__members__:
  51. deprecate(f"{prefix}{name}", 10, f"{enum.__name__}.{name}")
  52. return enum[name]
  53. raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
  54. def unpack_565(i):
  55. return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3
  56. def decode_dxt1(data, alpha=False):
  57. """
  58. input: one "row" of data (i.e. will produce 4*width pixels)
  59. """
  60. blocks = len(data) // 8 # number of blocks in row
  61. ret = (bytearray(), bytearray(), bytearray(), bytearray())
  62. for block in range(blocks):
  63. # Decode next 8-byte block.
  64. idx = block * 8
  65. color0, color1, bits = struct.unpack_from("<HHI", data, idx)
  66. r0, g0, b0 = unpack_565(color0)
  67. r1, g1, b1 = unpack_565(color1)
  68. # Decode this block into 4x4 pixels
  69. # Accumulate the results onto our 4 row accumulators
  70. for j in range(4):
  71. for i in range(4):
  72. # get next control op and generate a pixel
  73. control = bits & 3
  74. bits = bits >> 2
  75. a = 0xFF
  76. if control == 0:
  77. r, g, b = r0, g0, b0
  78. elif control == 1:
  79. r, g, b = r1, g1, b1
  80. elif control == 2:
  81. if color0 > color1:
  82. r = (2 * r0 + r1) // 3
  83. g = (2 * g0 + g1) // 3
  84. b = (2 * b0 + b1) // 3
  85. else:
  86. r = (r0 + r1) // 2
  87. g = (g0 + g1) // 2
  88. b = (b0 + b1) // 2
  89. elif control == 3:
  90. if color0 > color1:
  91. r = (2 * r1 + r0) // 3
  92. g = (2 * g1 + g0) // 3
  93. b = (2 * b1 + b0) // 3
  94. else:
  95. r, g, b, a = 0, 0, 0, 0
  96. if alpha:
  97. ret[j].extend([r, g, b, a])
  98. else:
  99. ret[j].extend([r, g, b])
  100. return ret
  101. def decode_dxt3(data):
  102. """
  103. input: one "row" of data (i.e. will produce 4*width pixels)
  104. """
  105. blocks = len(data) // 16 # number of blocks in row
  106. ret = (bytearray(), bytearray(), bytearray(), bytearray())
  107. for block in range(blocks):
  108. idx = block * 16
  109. block = data[idx : idx + 16]
  110. # Decode next 16-byte block.
  111. bits = struct.unpack_from("<8B", block)
  112. color0, color1 = struct.unpack_from("<HH", block, 8)
  113. (code,) = struct.unpack_from("<I", block, 12)
  114. r0, g0, b0 = unpack_565(color0)
  115. r1, g1, b1 = unpack_565(color1)
  116. for j in range(4):
  117. high = False # Do we want the higher bits?
  118. for i in range(4):
  119. alphacode_index = (4 * j + i) // 2
  120. a = bits[alphacode_index]
  121. if high:
  122. high = False
  123. a >>= 4
  124. else:
  125. high = True
  126. a &= 0xF
  127. a *= 17 # We get a value between 0 and 15
  128. color_code = (code >> 2 * (4 * j + i)) & 0x03
  129. if color_code == 0:
  130. r, g, b = r0, g0, b0
  131. elif color_code == 1:
  132. r, g, b = r1, g1, b1
  133. elif color_code == 2:
  134. r = (2 * r0 + r1) // 3
  135. g = (2 * g0 + g1) // 3
  136. b = (2 * b0 + b1) // 3
  137. elif color_code == 3:
  138. r = (2 * r1 + r0) // 3
  139. g = (2 * g1 + g0) // 3
  140. b = (2 * b1 + b0) // 3
  141. ret[j].extend([r, g, b, a])
  142. return ret
  143. def decode_dxt5(data):
  144. """
  145. input: one "row" of data (i.e. will produce 4 * width pixels)
  146. """
  147. blocks = len(data) // 16 # number of blocks in row
  148. ret = (bytearray(), bytearray(), bytearray(), bytearray())
  149. for block in range(blocks):
  150. idx = block * 16
  151. block = data[idx : idx + 16]
  152. # Decode next 16-byte block.
  153. a0, a1 = struct.unpack_from("<BB", block)
  154. bits = struct.unpack_from("<6B", block, 2)
  155. alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24)
  156. alphacode2 = bits[0] | (bits[1] << 8)
  157. color0, color1 = struct.unpack_from("<HH", block, 8)
  158. (code,) = struct.unpack_from("<I", block, 12)
  159. r0, g0, b0 = unpack_565(color0)
  160. r1, g1, b1 = unpack_565(color1)
  161. for j in range(4):
  162. for i in range(4):
  163. # get next control op and generate a pixel
  164. alphacode_index = 3 * (4 * j + i)
  165. if alphacode_index <= 12:
  166. alphacode = (alphacode2 >> alphacode_index) & 0x07
  167. elif alphacode_index == 15:
  168. alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06)
  169. else: # alphacode_index >= 18 and alphacode_index <= 45
  170. alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07
  171. if alphacode == 0:
  172. a = a0
  173. elif alphacode == 1:
  174. a = a1
  175. elif a0 > a1:
  176. a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7
  177. elif alphacode == 6:
  178. a = 0
  179. elif alphacode == 7:
  180. a = 255
  181. else:
  182. a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5
  183. color_code = (code >> 2 * (4 * j + i)) & 0x03
  184. if color_code == 0:
  185. r, g, b = r0, g0, b0
  186. elif color_code == 1:
  187. r, g, b = r1, g1, b1
  188. elif color_code == 2:
  189. r = (2 * r0 + r1) // 3
  190. g = (2 * g0 + g1) // 3
  191. b = (2 * b0 + b1) // 3
  192. elif color_code == 3:
  193. r = (2 * r1 + r0) // 3
  194. g = (2 * g1 + g0) // 3
  195. b = (2 * b1 + b0) // 3
  196. ret[j].extend([r, g, b, a])
  197. return ret
  198. class BLPFormatError(NotImplementedError):
  199. pass
  200. def _accept(prefix):
  201. return prefix[:4] in (b"BLP1", b"BLP2")
  202. class BlpImageFile(ImageFile.ImageFile):
  203. """
  204. Blizzard Mipmap Format
  205. """
  206. format = "BLP"
  207. format_description = "Blizzard Mipmap Format"
  208. def _open(self):
  209. self.magic = self.fp.read(4)
  210. self.fp.seek(5, os.SEEK_CUR)
  211. (self._blp_alpha_depth,) = struct.unpack("<b", self.fp.read(1))
  212. self.fp.seek(2, os.SEEK_CUR)
  213. self._size = struct.unpack("<II", self.fp.read(8))
  214. if self.magic in (b"BLP1", b"BLP2"):
  215. decoder = self.magic.decode()
  216. else:
  217. raise BLPFormatError(f"Bad BLP magic {repr(self.magic)}")
  218. self.mode = "RGBA" if self._blp_alpha_depth else "RGB"
  219. self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))]
  220. class _BLPBaseDecoder(ImageFile.PyDecoder):
  221. _pulls_fd = True
  222. def decode(self, buffer):
  223. try:
  224. self._read_blp_header()
  225. self._load()
  226. except struct.error as e:
  227. raise OSError("Truncated BLP file") from e
  228. return -1, 0
  229. def _read_blp_header(self):
  230. self.fd.seek(4)
  231. (self._blp_compression,) = struct.unpack("<i", self._safe_read(4))
  232. (self._blp_encoding,) = struct.unpack("<b", self._safe_read(1))
  233. (self._blp_alpha_depth,) = struct.unpack("<b", self._safe_read(1))
  234. (self._blp_alpha_encoding,) = struct.unpack("<b", self._safe_read(1))
  235. self.fd.seek(1, os.SEEK_CUR) # mips
  236. self.size = struct.unpack("<II", self._safe_read(8))
  237. if isinstance(self, BLP1Decoder):
  238. # Only present for BLP1
  239. (self._blp_encoding,) = struct.unpack("<i", self._safe_read(4))
  240. self.fd.seek(4, os.SEEK_CUR) # subtype
  241. self._blp_offsets = struct.unpack("<16I", self._safe_read(16 * 4))
  242. self._blp_lengths = struct.unpack("<16I", self._safe_read(16 * 4))
  243. def _safe_read(self, length):
  244. return ImageFile._safe_read(self.fd, length)
  245. def _read_palette(self):
  246. ret = []
  247. for i in range(256):
  248. try:
  249. b, g, r, a = struct.unpack("<4B", self._safe_read(4))
  250. except struct.error:
  251. break
  252. ret.append((b, g, r, a))
  253. return ret
  254. def _read_bgra(self, palette):
  255. data = bytearray()
  256. _data = BytesIO(self._safe_read(self._blp_lengths[0]))
  257. while True:
  258. try:
  259. (offset,) = struct.unpack("<B", _data.read(1))
  260. except struct.error:
  261. break
  262. b, g, r, a = palette[offset]
  263. d = (r, g, b)
  264. if self._blp_alpha_depth:
  265. d += (a,)
  266. data.extend(d)
  267. return data
  268. class BLP1Decoder(_BLPBaseDecoder):
  269. def _load(self):
  270. if self._blp_compression == Format.JPEG:
  271. self._decode_jpeg_stream()
  272. elif self._blp_compression == 1:
  273. if self._blp_encoding in (4, 5):
  274. palette = self._read_palette()
  275. data = self._read_bgra(palette)
  276. self.set_as_raw(bytes(data))
  277. else:
  278. raise BLPFormatError(
  279. f"Unsupported BLP encoding {repr(self._blp_encoding)}"
  280. )
  281. else:
  282. raise BLPFormatError(
  283. f"Unsupported BLP compression {repr(self._blp_encoding)}"
  284. )
  285. def _decode_jpeg_stream(self):
  286. from .JpegImagePlugin import JpegImageFile
  287. (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4))
  288. jpeg_header = self._safe_read(jpeg_header_size)
  289. self._safe_read(self._blp_offsets[0] - self.fd.tell()) # What IS this?
  290. data = self._safe_read(self._blp_lengths[0])
  291. data = jpeg_header + data
  292. data = BytesIO(data)
  293. image = JpegImageFile(data)
  294. Image._decompression_bomb_check(image.size)
  295. image.mode = "RGB"
  296. image.tile = [("jpeg", (0, 0) + self.size, 0, ("BGRX", ""))]
  297. self.set_as_raw(image.tobytes())
  298. class BLP2Decoder(_BLPBaseDecoder):
  299. def _load(self):
  300. palette = self._read_palette()
  301. self.fd.seek(self._blp_offsets[0])
  302. if self._blp_compression == 1:
  303. # Uncompressed or DirectX compression
  304. if self._blp_encoding == Encoding.UNCOMPRESSED:
  305. data = self._read_bgra(palette)
  306. elif self._blp_encoding == Encoding.DXT:
  307. data = bytearray()
  308. if self._blp_alpha_encoding == AlphaEncoding.DXT1:
  309. linesize = (self.size[0] + 3) // 4 * 8
  310. for yb in range((self.size[1] + 3) // 4):
  311. for d in decode_dxt1(
  312. self._safe_read(linesize), alpha=bool(self._blp_alpha_depth)
  313. ):
  314. data += d
  315. elif self._blp_alpha_encoding == AlphaEncoding.DXT3:
  316. linesize = (self.size[0] + 3) // 4 * 16
  317. for yb in range((self.size[1] + 3) // 4):
  318. for d in decode_dxt3(self._safe_read(linesize)):
  319. data += d
  320. elif self._blp_alpha_encoding == AlphaEncoding.DXT5:
  321. linesize = (self.size[0] + 3) // 4 * 16
  322. for yb in range((self.size[1] + 3) // 4):
  323. for d in decode_dxt5(self._safe_read(linesize)):
  324. data += d
  325. else:
  326. raise BLPFormatError(
  327. f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}"
  328. )
  329. else:
  330. raise BLPFormatError(f"Unknown BLP encoding {repr(self._blp_encoding)}")
  331. else:
  332. raise BLPFormatError(
  333. f"Unknown BLP compression {repr(self._blp_compression)}"
  334. )
  335. self.set_as_raw(bytes(data))
  336. class BLPEncoder(ImageFile.PyEncoder):
  337. _pushes_fd = True
  338. def _write_palette(self):
  339. data = b""
  340. palette = self.im.getpalette("RGBA", "RGBA")
  341. for i in range(256):
  342. r, g, b, a = palette[i * 4 : (i + 1) * 4]
  343. data += struct.pack("<4B", b, g, r, a)
  344. return data
  345. def encode(self, bufsize):
  346. palette_data = self._write_palette()
  347. offset = 20 + 16 * 4 * 2 + len(palette_data)
  348. data = struct.pack("<16I", offset, *((0,) * 15))
  349. w, h = self.im.size
  350. data += struct.pack("<16I", w * h, *((0,) * 15))
  351. data += palette_data
  352. for y in range(h):
  353. for x in range(w):
  354. data += struct.pack("<B", self.im.getpixel((x, y)))
  355. return len(data), 0, data
  356. def _save(im, fp, filename, save_all=False):
  357. if im.mode != "P":
  358. raise ValueError("Unsupported BLP image mode")
  359. magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2"
  360. fp.write(magic)
  361. fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression
  362. fp.write(struct.pack("<b", Encoding.UNCOMPRESSED))
  363. fp.write(struct.pack("<b", 1 if im.palette.mode == "RGBA" else 0))
  364. fp.write(struct.pack("<b", 0)) # alpha encoding
  365. fp.write(struct.pack("<b", 0)) # mips
  366. fp.write(struct.pack("<II", *im.size))
  367. if magic == b"BLP1":
  368. fp.write(struct.pack("<i", 5))
  369. fp.write(struct.pack("<i", 0))
  370. ImageFile._save(im, fp, [("BLP", (0, 0) + im.size, 0, im.mode)])
  371. Image.register_open(BlpImageFile.format, BlpImageFile, _accept)
  372. Image.register_extension(BlpImageFile.format, ".blp")
  373. Image.register_decoder("BLP1", BLP1Decoder)
  374. Image.register_decoder("BLP2", BLP2Decoder)
  375. Image.register_save(BlpImageFile.format, _save)
  376. Image.register_encoder("BLP", BLPEncoder)