Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/PIL/BlpImagePlugin.py: 16%

303 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2023-07-17 14:22 -0600

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 

32import os 

33import struct 

34from enum import IntEnum 

35from io import BytesIO 

36 

37from . import Image, ImageFile 

38from ._deprecate import deprecate 

39 

40 

41class Format(IntEnum): 

42 JPEG = 0 

43 

44 

45class Encoding(IntEnum): 

46 UNCOMPRESSED = 1 

47 DXT = 2 

48 UNCOMPRESSED_RAW_BGRA = 3 

49 

50 

51class AlphaEncoding(IntEnum): 

52 DXT1 = 0 

53 DXT3 = 1 

54 DXT5 = 7 

55 

56 

57def __getattr__(name): 

58 for enum, prefix in { 

59 Format: "BLP_FORMAT_", 

60 Encoding: "BLP_ENCODING_", 

61 AlphaEncoding: "BLP_ALPHA_ENCODING_", 

62 }.items(): 

63 if name.startswith(prefix): 

64 name = name[len(prefix) :] 

65 if name in enum.__members__: 

66 deprecate(f"{prefix}{name}", 10, f"{enum.__name__}.{name}") 

67 return enum[name] 

68 raise AttributeError(f"module '{__name__}' has no attribute '{name}'") 

69 

70 

71def unpack_565(i): 

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

73 

74 

75def decode_dxt1(data, alpha=False): 

76 """ 

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

78 """ 

79 

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

81 ret = (bytearray(), bytearray(), bytearray(), bytearray()) 

82 

83 for block in range(blocks): 

84 # Decode next 8-byte block. 

85 idx = block * 8 

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

87 

88 r0, g0, b0 = unpack_565(color0) 

89 r1, g1, b1 = unpack_565(color1) 

90 

91 # Decode this block into 4x4 pixels 

92 # Accumulate the results onto our 4 row accumulators 

93 for j in range(4): 

94 for i in range(4): 

95 # get next control op and generate a pixel 

96 

97 control = bits & 3 

98 bits = bits >> 2 

99 

100 a = 0xFF 

101 if control == 0: 

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

103 elif control == 1: 

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

105 elif control == 2: 

106 if color0 > color1: 

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

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

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

110 else: 

111 r = (r0 + r1) // 2 

112 g = (g0 + g1) // 2 

113 b = (b0 + b1) // 2 

114 elif control == 3: 

115 if color0 > color1: 

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

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

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

119 else: 

120 r, g, b, a = 0, 0, 0, 0 

121 

122 if alpha: 

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

124 else: 

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

126 

127 return ret 

128 

129 

130def decode_dxt3(data): 

131 """ 

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

133 """ 

134 

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

136 ret = (bytearray(), bytearray(), bytearray(), bytearray()) 

137 

138 for block in range(blocks): 

139 idx = block * 16 

140 block = data[idx : idx + 16] 

141 # Decode next 16-byte block. 

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

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

144 

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

146 

147 r0, g0, b0 = unpack_565(color0) 

148 r1, g1, b1 = unpack_565(color1) 

149 

150 for j in range(4): 

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

152 for i in range(4): 

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

154 a = bits[alphacode_index] 

155 if high: 

156 high = False 

157 a >>= 4 

158 else: 

159 high = True 

160 a &= 0xF 

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

162 

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

164 

165 if color_code == 0: 

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

167 elif color_code == 1: 

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

169 elif color_code == 2: 

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

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

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

173 elif color_code == 3: 

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

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

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

177 

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

179 

180 return ret 

181 

182 

183def decode_dxt5(data): 

184 """ 

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

186 """ 

187 

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

189 ret = (bytearray(), bytearray(), bytearray(), bytearray()) 

190 

191 for block in range(blocks): 

192 idx = block * 16 

193 block = data[idx : idx + 16] 

194 # Decode next 16-byte block. 

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

196 

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

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

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

200 

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

202 

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

204 

205 r0, g0, b0 = unpack_565(color0) 

206 r1, g1, b1 = unpack_565(color1) 

207 

208 for j in range(4): 

209 for i in range(4): 

210 # get next control op and generate a pixel 

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

212 

213 if alphacode_index <= 12: 

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

215 elif alphacode_index == 15: 

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

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

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

219 

220 if alphacode == 0: 

221 a = a0 

222 elif alphacode == 1: 

223 a = a1 

224 elif a0 > a1: 

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

226 elif alphacode == 6: 

227 a = 0 

228 elif alphacode == 7: 

229 a = 255 

230 else: 

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

232 

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

234 

235 if color_code == 0: 

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

237 elif color_code == 1: 

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

239 elif color_code == 2: 

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

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

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

243 elif color_code == 3: 

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

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

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

247 

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

249 

250 return ret 

251 

252 

253class BLPFormatError(NotImplementedError): 

254 pass 

255 

256 

257def _accept(prefix): 

258 return prefix[:4] in (b"BLP1", b"BLP2") 

259 

260 

261class BlpImageFile(ImageFile.ImageFile): 

262 """ 

263 Blizzard Mipmap Format 

264 """ 

265 

266 format = "BLP" 

267 format_description = "Blizzard Mipmap Format" 

268 

269 def _open(self): 

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

271 

272 self.fp.seek(5, os.SEEK_CUR) 

273 (self._blp_alpha_depth,) = struct.unpack("<b", self.fp.read(1)) 

274 

275 self.fp.seek(2, os.SEEK_CUR) 

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

277 

278 if self.magic in (b"BLP1", b"BLP2"): 

279 decoder = self.magic.decode() 

280 else: 

281 raise BLPFormatError(f"Bad BLP magic {repr(self.magic)}") 

282 

283 self.mode = "RGBA" if self._blp_alpha_depth else "RGB" 

284 self.tile = [(decoder, (0, 0) + self.size, 0, (self.mode, 0, 1))] 

285 

286 

287class _BLPBaseDecoder(ImageFile.PyDecoder): 

288 _pulls_fd = True 

289 

290 def decode(self, buffer): 

291 try: 

292 self._read_blp_header() 

293 self._load() 

294 except struct.error as e: 

295 raise OSError("Truncated BLP file") from e 

296 return -1, 0 

297 

298 def _read_blp_header(self): 

299 self.fd.seek(4) 

300 (self._blp_compression,) = struct.unpack("<i", self._safe_read(4)) 

301 

302 (self._blp_encoding,) = struct.unpack("<b", self._safe_read(1)) 

303 (self._blp_alpha_depth,) = struct.unpack("<b", self._safe_read(1)) 

304 (self._blp_alpha_encoding,) = struct.unpack("<b", self._safe_read(1)) 

305 self.fd.seek(1, os.SEEK_CUR) # mips 

306 

307 self.size = struct.unpack("<II", self._safe_read(8)) 

308 

309 if isinstance(self, BLP1Decoder): 

310 # Only present for BLP1 

311 (self._blp_encoding,) = struct.unpack("<i", self._safe_read(4)) 

312 self.fd.seek(4, os.SEEK_CUR) # subtype 

313 

314 self._blp_offsets = struct.unpack("<16I", self._safe_read(16 * 4)) 

315 self._blp_lengths = struct.unpack("<16I", self._safe_read(16 * 4)) 

316 

317 def _safe_read(self, length): 

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

319 

320 def _read_palette(self): 

321 ret = [] 

322 for i in range(256): 

323 try: 

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

325 except struct.error: 

326 break 

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

328 return ret 

329 

330 def _read_bgra(self, palette): 

331 data = bytearray() 

332 _data = BytesIO(self._safe_read(self._blp_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 = (r, g, b) 

340 if self._blp_alpha_depth: 

341 d += (a,) 

342 data.extend(d) 

343 return data 

344 

345 

346class BLP1Decoder(_BLPBaseDecoder): 

347 def _load(self): 

348 if self._blp_compression == Format.JPEG: 

349 self._decode_jpeg_stream() 

350 

351 elif self._blp_compression == 1: 

352 if self._blp_encoding in (4, 5): 

353 palette = self._read_palette() 

354 data = self._read_bgra(palette) 

355 self.set_as_raw(bytes(data)) 

356 else: 

357 raise BLPFormatError( 

358 f"Unsupported BLP encoding {repr(self._blp_encoding)}" 

359 ) 

360 else: 

361 raise BLPFormatError( 

362 f"Unsupported BLP compression {repr(self._blp_encoding)}" 

363 ) 

364 

365 def _decode_jpeg_stream(self): 

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 self._safe_read(self._blp_offsets[0] - self.fd.tell()) # What IS this? 

371 data = self._safe_read(self._blp_lengths[0]) 

372 data = jpeg_header + data 

373 data = BytesIO(data) 

374 image = JpegImageFile(data) 

375 Image._decompression_bomb_check(image.size) 

376 image.mode = "RGB" 

377 image.tile = [("jpeg", (0, 0) + self.size, 0, ("BGRX", ""))] 

378 self.set_as_raw(image.tobytes()) 

379 

380 

381class BLP2Decoder(_BLPBaseDecoder): 

382 def _load(self): 

383 palette = self._read_palette() 

384 

385 self.fd.seek(self._blp_offsets[0]) 

386 

387 if self._blp_compression == 1: 

388 # Uncompressed or DirectX compression 

389 

390 if self._blp_encoding == Encoding.UNCOMPRESSED: 

391 data = self._read_bgra(palette) 

392 

393 elif self._blp_encoding == Encoding.DXT: 

394 data = bytearray() 

395 if self._blp_alpha_encoding == AlphaEncoding.DXT1: 

396 linesize = (self.size[0] + 3) // 4 * 8 

397 for yb in range((self.size[1] + 3) // 4): 

398 for d in decode_dxt1( 

399 self._safe_read(linesize), alpha=bool(self._blp_alpha_depth) 

400 ): 

401 data += d 

402 

403 elif self._blp_alpha_encoding == AlphaEncoding.DXT3: 

404 linesize = (self.size[0] + 3) // 4 * 16 

405 for yb in range((self.size[1] + 3) // 4): 

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

407 data += d 

408 

409 elif self._blp_alpha_encoding == AlphaEncoding.DXT5: 

410 linesize = (self.size[0] + 3) // 4 * 16 

411 for yb in range((self.size[1] + 3) // 4): 

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

413 data += d 

414 else: 

415 raise BLPFormatError( 

416 f"Unsupported alpha encoding {repr(self._blp_alpha_encoding)}" 

417 ) 

418 else: 

419 raise BLPFormatError(f"Unknown BLP encoding {repr(self._blp_encoding)}") 

420 

421 else: 

422 raise BLPFormatError( 

423 f"Unknown BLP compression {repr(self._blp_compression)}" 

424 ) 

425 

426 self.set_as_raw(bytes(data)) 

427 

428 

429class BLPEncoder(ImageFile.PyEncoder): 

430 _pushes_fd = True 

431 

432 def _write_palette(self): 

433 data = b"" 

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

435 for i in range(256): 

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

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

438 return data 

439 

440 def encode(self, bufsize): 

441 palette_data = self._write_palette() 

442 

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

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

445 

446 w, h = self.im.size 

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

448 

449 data += palette_data 

450 

451 for y in range(h): 

452 for x in range(w): 

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

454 

455 return len(data), 0, data 

456 

457 

458def _save(im, fp, filename, save_all=False): 

459 if im.mode != "P": 

460 raise ValueError("Unsupported BLP image mode") 

461 

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

463 fp.write(magic) 

464 

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

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

467 fp.write(struct.pack("<b", 1 if im.palette.mode == "RGBA" else 0)) 

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

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

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

471 if magic == b"BLP1": 

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

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

474 

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

476 

477 

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

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

480Image.register_decoder("BLP1", BLP1Decoder) 

481Image.register_decoder("BLP2", BLP2Decoder) 

482 

483Image.register_save(BlpImageFile.format, _save) 

484Image.register_encoder("BLP", BLPEncoder)