BlpImagePlugin.py 14 KB

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