image_blp/types/
jpeg.rs

1use super::locator::*;
2use super::{BlpHeader, BlpVersion};
3use log::*;
4
5/// There is a limit on size of JPEG header as some tools might crash.
6///
7/// Larger values are prone to causing image corruption and crashes in some BLP
8/// reader implementations like Warcraft III 1.27b where buffer bounds are
9/// not strongly enforced. This limit applies especially when generating a
10/// BLP file with JPEG content and without mipmaps as it can prevent dumping
11/// the entire full scale image JPEG file into jpegHeaderChunk and using an
12/// empty mipmap block. If values larger than 624 are encountered it is
13/// recommended that a warning be generated and loading continues as normal
14/// using the larger size.
15pub const MAX_JPEG_HEADER: usize = 624;
16
17#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
18pub struct BlpJpeg {
19    /// JPEG header that is appended to each mipmap level data
20    pub header: Vec<u8>,
21    /// Image itself and all mipmaps levels. If there are no mipmaps,
22    /// the length of the vector is 1.
23    pub images: Vec<Vec<u8>>,
24}
25
26impl BlpJpeg {
27    /// Concat JPEG header with body and get the required mipmap level.
28    pub fn full_jpeg(&self, i: usize) -> Option<Vec<u8>> {
29        if i >= self.images.len() {
30            None
31        } else {
32            // Remove those bugged 2 bytes from the end
33            let header_size = self.header.len() - 2;
34            trace!(
35                "Getting JPEG with header size {} and body size {}",
36                header_size,
37                self.images[i].len()
38            );
39            let mut buffer = Vec::with_capacity(header_size + self.images[i].len());
40            buffer.extend(&self.header[0..header_size]);
41            buffer.extend(self.images[i].as_slice());
42            Some(buffer)
43        }
44    }
45
46    /// Predict internal locator to write down mipmaps
47    pub fn mipmap_locator(&self, version: BlpVersion) -> MipmapLocator {
48        let mut offsets = [0; 16];
49        let mut sizes = [0; 16];
50        let mut cur_offset = BlpHeader::size(version) + self.header.len() + 4;
51        for (i, image) in self.images.iter().take(16).enumerate() {
52            offsets[i] = cur_offset as u32;
53            sizes[i] = image.len() as u32;
54            cur_offset += image.len();
55        }
56
57        MipmapLocator::Internal { offsets, sizes }
58    }
59}