BlpImagePlugin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 _read_palette(self):
  225. ret = []
  226. for i in range(256):
  227. try:
  228. b, g, r, a = struct.unpack("<4B", self.fd.read(4))
  229. except struct.error:
  230. break
  231. ret.append((b, g, r, a))
  232. return ret
  233. def _read_blp_header(self):
  234. (self._blp_compression,) = struct.unpack("<i", self.fd.read(4))
  235. (self._blp_encoding,) = struct.unpack("<b", self.fd.read(1))
  236. (self._blp_alpha_depth,) = struct.unpack("<b", self.fd.read(1))
  237. (self._blp_alpha_encoding,) = struct.unpack("<b", self.fd.read(1))
  238. (self._blp_mips,) = struct.unpack("<b", self.fd.read(1))
  239. self.size = struct.unpack("<II", self.fd.read(8))
  240. if self.magic == b"BLP1":
  241. # Only present for BLP1
  242. (self._blp_encoding,) = struct.unpack("<i", self.fd.read(4))
  243. (self._blp_subtype,) = struct.unpack("<i", self.fd.read(4))
  244. self._blp_offsets = struct.unpack("<16I", self.fd.read(16 * 4))
  245. self._blp_lengths = struct.unpack("<16I", self.fd.read(16 * 4))
  246. class BLP1Decoder(_BLPBaseDecoder):
  247. def _load(self):
  248. if self._blp_compression == BLP_FORMAT_JPEG:
  249. self._decode_jpeg_stream()
  250. elif self._blp_compression == 1:
  251. if self._blp_encoding in (4, 5):
  252. data = bytearray()
  253. palette = self._read_palette()
  254. _data = BytesIO(self.fd.read(self._blp_lengths[0]))
  255. while True:
  256. try:
  257. (offset,) = struct.unpack("<B", _data.read(1))
  258. except struct.error:
  259. break
  260. b, g, r, a = palette[offset]
  261. data.extend([r, g, b])
  262. self.set_as_raw(bytes(data))
  263. else:
  264. raise BLPFormatError(
  265. f"Unsupported BLP encoding {repr(self._blp_encoding)}"
  266. )
  267. else:
  268. raise BLPFormatError(
  269. f"Unsupported BLP compression {repr(self._blp_encoding)}"
  270. )
  271. def _decode_jpeg_stream(self):
  272. from PIL.JpegImagePlugin import JpegImageFile
  273. (jpeg_header_size,) = struct.unpack("<I", self.fd.read(4))
  274. jpeg_header = self.fd.read(jpeg_header_size)
  275. self.fd.read(self._blp_offsets[0] - self.fd.tell()) # What IS this?
  276. data = self.fd.read(self._blp_lengths[0])
  277. data = jpeg_header + data
  278. data = BytesIO(data)
  279. image = JpegImageFile(data)
  280. self.tile = image.tile # :/
  281. self.fd = image.fp
  282. self.mode = image.mode
  283. class BLP2Decoder(_BLPBaseDecoder):
  284. def _load(self):
  285. palette = self._read_palette()
  286. data = bytearray()
  287. self.fd.seek(self._blp_offsets[0])
  288. if self._blp_compression == 1:
  289. # Uncompressed or DirectX compression
  290. if self._blp_encoding == BLP_ENCODING_UNCOMPRESSED:
  291. _data = BytesIO(self.fd.read(self._blp_lengths[0]))
  292. while True:
  293. try:
  294. (offset,) = struct.unpack("<B", _data.read(1))
  295. except struct.error:
  296. break
  297. b, g, r, a = palette[offset]
  298. data.extend((r, g, b))
  299. elif self._blp_encoding == BLP_ENCODING_DXT:
  300. if self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT1:
  301. linesize = (self.size[0] + 3) // 4 * 8
  302. for yb in range((self.size[1] + 3) // 4):
  303. for d in decode_dxt1(
  304. self.fd.read(linesize), alpha=bool(self._blp_alpha_depth)
  305. ):
  306. data += d
  307. elif self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT3:
  308. linesize = (self.size[0] + 3) // 4 * 16
  309. for yb in range((self.size[1] + 3) // 4):
  310. for d in decode_dxt3(self.fd.read(linesize)):
  311. data += d
  312. elif self._blp_alpha_encoding == BLP_ALPHA_ENCODING_DXT5:
  313. linesize = (self.size[0] + 3) // 4 * 16
  314. for yb in range((self.size[1] + 3) // 4):
  315. for d in decode_dxt5(self.fd.read(linesize)):
  316. data += d
  317. else:
  318. raise BLPFormatError(
  319. f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}"
  320. )
  321. else:
  322. raise BLPFormatError(f"Unknown BLP encoding {repr(self._blp_encoding)}")
  323. else:
  324. raise BLPFormatError(
  325. f"Unknown BLP compression {repr(self._blp_compression)}"
  326. )
  327. self.set_as_raw(bytes(data))
  328. Image.register_open(
  329. BlpImageFile.format, BlpImageFile, lambda p: p[:4] in (b"BLP1", b"BLP2")
  330. )
  331. Image.register_extension(BlpImageFile.format, ".blp")
  332. Image.register_decoder("BLP1", BLP1Decoder)
  333. Image.register_decoder("BLP2", BLP2Decoder)