Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/PIL/BlpImagePlugin.py: 34%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

325 statements  

1""" 

2Blizzard Mipmap Format (.blp) 

3Jerome Leclanche <jerome@leclan.ch> 

4 

5The contents of this file are hereby released in the public domain (CC0) 

6Full text of the CC0 license: 

7 https://creativecommons.org/publicdomain/zero/1.0/ 

8 

9BLP1 files, used mostly in Warcraft III, are not fully supported. 

10All types of BLP2 files used in World of Warcraft are supported. 

11 

12The BLP file structure consists of a header, up to 16 mipmaps of the 

13texture 

14 

15Texture sizes must be powers of two, though the two dimensions do 

16not have to be equal; 512x256 is valid, but 512x200 is not. 

17The first mipmap (mipmap #0) is the full size image; each subsequent 

18mipmap halves both dimensions. The final mipmap should be 1x1. 

19 

20BLP files come in many different flavours: 

21* JPEG-compressed (type == 0) - only supported for BLP1. 

22* RAW images (type == 1, encoding == 1). Each mipmap is stored as an 

23 array of 8-bit values, one per pixel, left to right, top to bottom. 

24 Each value is an index to the palette. 

25* DXT-compressed (type == 1, encoding == 2): 

26- DXT1 compression is used if alpha_encoding == 0. 

27 - An additional alpha bit is used if alpha_depth == 1. 

28 - DXT3 compression is used if alpha_encoding == 1. 

29 - DXT5 compression is used if alpha_encoding == 7. 

30""" 

31 

32from __future__ import annotations 

33 

34import abc 

35import os 

36import struct 

37from enum import IntEnum 

38from io import BytesIO 

39from typing import IO 

40 

41from . import Image, ImageFile 

42 

43 

44class Format(IntEnum): 

45 JPEG = 0 

46 

47 

48class Encoding(IntEnum): 

49 UNCOMPRESSED = 1 

50 DXT = 2 

51 UNCOMPRESSED_RAW_BGRA = 3 

52 

53 

54class AlphaEncoding(IntEnum): 

55 DXT1 = 0 

56 DXT3 = 1 

57 DXT5 = 7 

58 

59 

60def unpack_565(i: int) -> tuple[int, int, int]: 

61 return ((i >> 11) & 0x1F) << 3, ((i >> 5) & 0x3F) << 2, (i & 0x1F) << 3 

62 

63 

64def decode_dxt1( 

65 data: bytes, alpha: bool = False 

66) -> tuple[bytearray, bytearray, bytearray, bytearray]: 

67 """ 

68 input: one "row" of data (i.e. will produce 4*width pixels) 

69 """ 

70 

71 blocks = len(data) // 8 # number of blocks in row 

72 ret = (bytearray(), bytearray(), bytearray(), bytearray()) 

73 

74 for block_index in range(blocks): 

75 # Decode next 8-byte block. 

76 idx = block_index * 8 

77 color0, color1, bits = struct.unpack_from("<HHI", data, idx) 

78 

79 r0, g0, b0 = unpack_565(color0) 

80 r1, g1, b1 = unpack_565(color1) 

81 

82 # Decode this block into 4x4 pixels 

83 # Accumulate the results onto our 4 row accumulators 

84 for j in range(4): 

85 for i in range(4): 

86 # get next control op and generate a pixel 

87 

88 control = bits & 3 

89 bits = bits >> 2 

90 

91 a = 0xFF 

92 if control == 0: 

93 r, g, b = r0, g0, b0 

94 elif control == 1: 

95 r, g, b = r1, g1, b1 

96 elif control == 2: 

97 if color0 > color1: 

98 r = (2 * r0 + r1) // 3 

99 g = (2 * g0 + g1) // 3 

100 b = (2 * b0 + b1) // 3 

101 else: 

102 r = (r0 + r1) // 2 

103 g = (g0 + g1) // 2 

104 b = (b0 + b1) // 2 

105 elif control == 3: 

106 if color0 > color1: 

107 r = (2 * r1 + r0) // 3 

108 g = (2 * g1 + g0) // 3 

109 b = (2 * b1 + b0) // 3 

110 else: 

111 r, g, b, a = 0, 0, 0, 0 

112 

113 if alpha: 

114 ret[j].extend([r, g, b, a]) 

115 else: 

116 ret[j].extend([r, g, b]) 

117 

118 return ret 

119 

120 

121def decode_dxt3(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]: 

122 """ 

123 input: one "row" of data (i.e. will produce 4*width pixels) 

124 """ 

125 

126 blocks = len(data) // 16 # number of blocks in row 

127 ret = (bytearray(), bytearray(), bytearray(), bytearray()) 

128 

129 for block_index in range(blocks): 

130 idx = block_index * 16 

131 block = data[idx : idx + 16] 

132 # Decode next 16-byte block. 

133 bits = struct.unpack_from("<8B", block) 

134 color0, color1 = struct.unpack_from("<HH", block, 8) 

135 

136 (code,) = struct.unpack_from("<I", block, 12) 

137 

138 r0, g0, b0 = unpack_565(color0) 

139 r1, g1, b1 = unpack_565(color1) 

140 

141 for j in range(4): 

142 high = False # Do we want the higher bits? 

143 for i in range(4): 

144 alphacode_index = (4 * j + i) // 2 

145 a = bits[alphacode_index] 

146 if high: 

147 high = False 

148 a >>= 4 

149 else: 

150 high = True 

151 a &= 0xF 

152 a *= 17 # We get a value between 0 and 15 

153 

154 color_code = (code >> 2 * (4 * j + i)) & 0x03 

155 

156 if color_code == 0: 

157 r, g, b = r0, g0, b0 

158 elif color_code == 1: 

159 r, g, b = r1, g1, b1 

160 elif color_code == 2: 

161 r = (2 * r0 + r1) // 3 

162 g = (2 * g0 + g1) // 3 

163 b = (2 * b0 + b1) // 3 

164 elif color_code == 3: 

165 r = (2 * r1 + r0) // 3 

166 g = (2 * g1 + g0) // 3 

167 b = (2 * b1 + b0) // 3 

168 

169 ret[j].extend([r, g, b, a]) 

170 

171 return ret 

172 

173 

174def decode_dxt5(data: bytes) -> tuple[bytearray, bytearray, bytearray, bytearray]: 

175 """ 

176 input: one "row" of data (i.e. will produce 4 * width pixels) 

177 """ 

178 

179 blocks = len(data) // 16 # number of blocks in row 

180 ret = (bytearray(), bytearray(), bytearray(), bytearray()) 

181 

182 for block_index in range(blocks): 

183 idx = block_index * 16 

184 block = data[idx : idx + 16] 

185 # Decode next 16-byte block. 

186 a0, a1 = struct.unpack_from("<BB", block) 

187 

188 bits = struct.unpack_from("<6B", block, 2) 

189 alphacode1 = bits[2] | (bits[3] << 8) | (bits[4] << 16) | (bits[5] << 24) 

190 alphacode2 = bits[0] | (bits[1] << 8) 

191 

192 color0, color1 = struct.unpack_from("<HH", block, 8) 

193 

194 (code,) = struct.unpack_from("<I", block, 12) 

195 

196 r0, g0, b0 = unpack_565(color0) 

197 r1, g1, b1 = unpack_565(color1) 

198 

199 for j in range(4): 

200 for i in range(4): 

201 # get next control op and generate a pixel 

202 alphacode_index = 3 * (4 * j + i) 

203 

204 if alphacode_index <= 12: 

205 alphacode = (alphacode2 >> alphacode_index) & 0x07 

206 elif alphacode_index == 15: 

207 alphacode = (alphacode2 >> 15) | ((alphacode1 << 1) & 0x06) 

208 else: # alphacode_index >= 18 and alphacode_index <= 45 

209 alphacode = (alphacode1 >> (alphacode_index - 16)) & 0x07 

210 

211 if alphacode == 0: 

212 a = a0 

213 elif alphacode == 1: 

214 a = a1 

215 elif a0 > a1: 

216 a = ((8 - alphacode) * a0 + (alphacode - 1) * a1) // 7 

217 elif alphacode == 6: 

218 a = 0 

219 elif alphacode == 7: 

220 a = 255 

221 else: 

222 a = ((6 - alphacode) * a0 + (alphacode - 1) * a1) // 5 

223 

224 color_code = (code >> 2 * (4 * j + i)) & 0x03 

225 

226 if color_code == 0: 

227 r, g, b = r0, g0, b0 

228 elif color_code == 1: 

229 r, g, b = r1, g1, b1 

230 elif color_code == 2: 

231 r = (2 * r0 + r1) // 3 

232 g = (2 * g0 + g1) // 3 

233 b = (2 * b0 + b1) // 3 

234 elif color_code == 3: 

235 r = (2 * r1 + r0) // 3 

236 g = (2 * g1 + g0) // 3 

237 b = (2 * b1 + b0) // 3 

238 

239 ret[j].extend([r, g, b, a]) 

240 

241 return ret 

242 

243 

244class BLPFormatError(NotImplementedError): 

245 pass 

246 

247 

248def _accept(prefix: bytes) -> bool: 

249 return prefix.startswith((b"BLP1", b"BLP2")) 

250 

251 

252class BlpImageFile(ImageFile.ImageFile): 

253 """ 

254 Blizzard Mipmap Format 

255 """ 

256 

257 format = "BLP" 

258 format_description = "Blizzard Mipmap Format" 

259 

260 def _open(self) -> None: 

261 self.magic = self.fp.read(4) 

262 if not _accept(self.magic): 

263 msg = f"Bad BLP magic {repr(self.magic)}" 

264 raise BLPFormatError(msg) 

265 

266 compression = struct.unpack("<i", self.fp.read(4))[0] 

267 if self.magic == b"BLP1": 

268 alpha = struct.unpack("<I", self.fp.read(4))[0] != 0 

269 else: 

270 encoding = struct.unpack("<b", self.fp.read(1))[0] 

271 alpha = struct.unpack("<b", self.fp.read(1))[0] != 0 

272 alpha_encoding = struct.unpack("<b", self.fp.read(1))[0] 

273 self.fp.seek(1, os.SEEK_CUR) # mips 

274 

275 self._size = struct.unpack("<II", self.fp.read(8)) 

276 

277 args: tuple[int, int, bool] | tuple[int, int, bool, int] 

278 if self.magic == b"BLP1": 

279 encoding = struct.unpack("<i", self.fp.read(4))[0] 

280 self.fp.seek(4, os.SEEK_CUR) # subtype 

281 

282 args = (compression, encoding, alpha) 

283 offset = 28 

284 else: 

285 args = (compression, encoding, alpha, alpha_encoding) 

286 offset = 20 

287 

288 decoder = self.magic.decode() 

289 

290 self._mode = "RGBA" if alpha else "RGB" 

291 self.tile = [ImageFile._Tile(decoder, (0, 0) + self.size, offset, args)] 

292 

293 

294class _BLPBaseDecoder(abc.ABC, ImageFile.PyDecoder): 

295 _pulls_fd = True 

296 

297 def decode(self, buffer: bytes | Image.SupportsArrayInterface) -> tuple[int, int]: 

298 try: 

299 self._read_header() 

300 self._load() 

301 except struct.error as e: 

302 msg = "Truncated BLP file" 

303 raise OSError(msg) from e 

304 return -1, 0 

305 

306 @abc.abstractmethod 

307 def _load(self) -> None: 

308 pass 

309 

310 def _read_header(self) -> None: 

311 self._offsets = struct.unpack("<16I", self._safe_read(16 * 4)) 

312 self._lengths = struct.unpack("<16I", self._safe_read(16 * 4)) 

313 

314 def _safe_read(self, length: int) -> bytes: 

315 assert self.fd is not None 

316 return ImageFile._safe_read(self.fd, length) 

317 

318 def _read_palette(self) -> list[tuple[int, int, int, int]]: 

319 ret = [] 

320 for i in range(256): 

321 try: 

322 b, g, r, a = struct.unpack("<4B", self._safe_read(4)) 

323 except struct.error: 

324 break 

325 ret.append((b, g, r, a)) 

326 return ret 

327 

328 def _read_bgra( 

329 self, palette: list[tuple[int, int, int, int]], alpha: bool 

330 ) -> bytearray: 

331 data = bytearray() 

332 _data = BytesIO(self._safe_read(self._lengths[0])) 

333 while True: 

334 try: 

335 (offset,) = struct.unpack("<B", _data.read(1)) 

336 except struct.error: 

337 break 

338 b, g, r, a = palette[offset] 

339 d: tuple[int, ...] = (r, g, b) 

340 if alpha: 

341 d += (a,) 

342 data.extend(d) 

343 return data 

344 

345 

346class BLP1Decoder(_BLPBaseDecoder): 

347 def _load(self) -> None: 

348 self._compression, self._encoding, alpha = self.args 

349 

350 if self._compression == Format.JPEG: 

351 self._decode_jpeg_stream() 

352 

353 elif self._compression == 1: 

354 if self._encoding in (4, 5): 

355 palette = self._read_palette() 

356 data = self._read_bgra(palette, alpha) 

357 self.set_as_raw(data) 

358 else: 

359 msg = f"Unsupported BLP encoding {repr(self._encoding)}" 

360 raise BLPFormatError(msg) 

361 else: 

362 msg = f"Unsupported BLP compression {repr(self._encoding)}" 

363 raise BLPFormatError(msg) 

364 

365 def _decode_jpeg_stream(self) -> None: 

366 from .JpegImagePlugin import JpegImageFile 

367 

368 (jpeg_header_size,) = struct.unpack("<I", self._safe_read(4)) 

369 jpeg_header = self._safe_read(jpeg_header_size) 

370 assert self.fd is not None 

371 self._safe_read(self._offsets[0] - self.fd.tell()) # What IS this? 

372 data = self._safe_read(self._lengths[0]) 

373 data = jpeg_header + data 

374 image = JpegImageFile(BytesIO(data)) 

375 Image._decompression_bomb_check(image.size) 

376 if image.mode == "CMYK": 

377 args = image.tile[0].args 

378 assert isinstance(args, tuple) 

379 image.tile = [image.tile[0]._replace(args=(args[0], "CMYK"))] 

380 self.set_as_raw(image.convert("RGB").tobytes(), "BGR") 

381 

382 

383class BLP2Decoder(_BLPBaseDecoder): 

384 def _load(self) -> None: 

385 self._compression, self._encoding, alpha, self._alpha_encoding = self.args 

386 

387 palette = self._read_palette() 

388 

389 assert self.fd is not None 

390 self.fd.seek(self._offsets[0]) 

391 

392 if self._compression == 1: 

393 # Uncompressed or DirectX compression 

394 

395 if self._encoding == Encoding.UNCOMPRESSED: 

396 data = self._read_bgra(palette, alpha) 

397 

398 elif self._encoding == Encoding.DXT: 

399 data = bytearray() 

400 if self._alpha_encoding == AlphaEncoding.DXT1: 

401 linesize = (self.state.xsize + 3) // 4 * 8 

402 for yb in range((self.state.ysize + 3) // 4): 

403 for d in decode_dxt1(self._safe_read(linesize), alpha): 

404 data += d 

405 

406 elif self._alpha_encoding == AlphaEncoding.DXT3: 

407 linesize = (self.state.xsize + 3) // 4 * 16 

408 for yb in range((self.state.ysize + 3) // 4): 

409 for d in decode_dxt3(self._safe_read(linesize)): 

410 data += d 

411 

412 elif self._alpha_encoding == AlphaEncoding.DXT5: 

413 linesize = (self.state.xsize + 3) // 4 * 16 

414 for yb in range((self.state.ysize + 3) // 4): 

415 for d in decode_dxt5(self._safe_read(linesize)): 

416 data += d 

417 else: 

418 msg = f"Unsupported alpha encoding {repr(self._alpha_encoding)}" 

419 raise BLPFormatError(msg) 

420 else: 

421 msg = f"Unknown BLP encoding {repr(self._encoding)}" 

422 raise BLPFormatError(msg) 

423 

424 else: 

425 msg = f"Unknown BLP compression {repr(self._compression)}" 

426 raise BLPFormatError(msg) 

427 

428 self.set_as_raw(data) 

429 

430 

431class BLPEncoder(ImageFile.PyEncoder): 

432 _pushes_fd = True 

433 

434 def _write_palette(self) -> bytes: 

435 data = b"" 

436 assert self.im is not None 

437 palette = self.im.getpalette("RGBA", "RGBA") 

438 for i in range(len(palette) // 4): 

439 r, g, b, a = palette[i * 4 : (i + 1) * 4] 

440 data += struct.pack("<4B", b, g, r, a) 

441 while len(data) < 256 * 4: 

442 data += b"\x00" * 4 

443 return data 

444 

445 def encode(self, bufsize: int) -> tuple[int, int, bytes]: 

446 palette_data = self._write_palette() 

447 

448 offset = 20 + 16 * 4 * 2 + len(palette_data) 

449 data = struct.pack("<16I", offset, *((0,) * 15)) 

450 

451 assert self.im is not None 

452 w, h = self.im.size 

453 data += struct.pack("<16I", w * h, *((0,) * 15)) 

454 

455 data += palette_data 

456 

457 for y in range(h): 

458 for x in range(w): 

459 data += struct.pack("<B", self.im.getpixel((x, y))) 

460 

461 return len(data), 0, data 

462 

463 

464def _save(im: Image.Image, fp: IO[bytes], filename: str | bytes) -> None: 

465 if im.mode != "P": 

466 msg = "Unsupported BLP image mode" 

467 raise ValueError(msg) 

468 

469 magic = b"BLP1" if im.encoderinfo.get("blp_version") == "BLP1" else b"BLP2" 

470 fp.write(magic) 

471 

472 assert im.palette is not None 

473 fp.write(struct.pack("<i", 1)) # Uncompressed or DirectX compression 

474 

475 alpha_depth = 1 if im.palette.mode == "RGBA" else 0 

476 if magic == b"BLP1": 

477 fp.write(struct.pack("<L", alpha_depth)) 

478 else: 

479 fp.write(struct.pack("<b", Encoding.UNCOMPRESSED)) 

480 fp.write(struct.pack("<b", alpha_depth)) 

481 fp.write(struct.pack("<b", 0)) # alpha encoding 

482 fp.write(struct.pack("<b", 0)) # mips 

483 fp.write(struct.pack("<II", *im.size)) 

484 if magic == b"BLP1": 

485 fp.write(struct.pack("<i", 5)) 

486 fp.write(struct.pack("<i", 0)) 

487 

488 ImageFile._save(im, fp, [ImageFile._Tile("BLP", (0, 0) + im.size, 0, im.mode)]) 

489 

490 

491Image.register_open(BlpImageFile.format, BlpImageFile, _accept) 

492Image.register_extension(BlpImageFile.format, ".blp") 

493Image.register_decoder("BLP1", BLP1Decoder) 

494Image.register_decoder("BLP2", BLP2Decoder) 

495 

496Image.register_save(BlpImageFile.format, _save) 

497Image.register_encoder("BLP", BLPEncoder)