use super::*;
pub fn decode_base64(input: &str) -> io::Result<Vec<u8>> {
let mut out: Vec<u8> = Vec::with_capacity((input.len() * 3) / 4);
let mut quartet: [u8; 4] = [0u8; 4];
let mut q_len: usize = 0;
let mut pad_count: usize = 0;
for byte_val in input.bytes() {
if byte_val.is_ascii_whitespace() {
continue;
}
if byte_val == b'=' {
pad_count += 1;
quartet[q_len] = 0;
q_len += 1;
} else {
if pad_count > 0 {
return Err(Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID));
}
let decoded: u8 = decode_base64_char(byte_val)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID))?;
quartet[q_len] = decoded;
q_len += 1;
}
if q_len == 4 {
let triple: u32 = (u32::from(quartet[0]) << 18)
| (u32::from(quartet[1]) << 12)
| (u32::from(quartet[2]) << 6)
| u32::from(quartet[3]);
out.push(((triple >> 16) & 0xFF) as u8);
if pad_count < 2 {
out.push(((triple >> 8) & 0xFF) as u8);
}
if pad_count < 1 {
out.push((triple & 0xFF) as u8);
}
q_len = 0;
pad_count = 0;
}
}
if q_len != 0 {
return Err(Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID));
}
Ok(out)
}
#[must_use]
pub fn encode_base64(bytes: &[u8]) -> String {
let mut out: String = String::with_capacity(bytes.len().div_ceil(3) * 4);
let mut idx: usize = 0;
while idx < bytes.len() {
let first: u32 = u32::from(bytes[idx]);
let has_second: bool = idx + 1 < bytes.len();
let has_third: bool = idx + 2 < bytes.len();
let second: u32 = if has_second {
u32::from(bytes[idx + 1])
} else {
0
};
let third: u32 = if has_third {
u32::from(bytes[idx + 2])
} else {
0
};
let triple: u32 = (first << 16) | (second << 8) | third;
out.push(BASE64_ALPHABET[((triple >> 18) & 0x3F) as usize] as char);
out.push(BASE64_ALPHABET[((triple >> 12) & 0x3F) as usize] as char);
if has_second {
out.push(BASE64_ALPHABET[((triple >> 6) & 0x3F) as usize] as char);
} else {
out.push('=');
}
if has_third {
out.push(BASE64_ALPHABET[(triple & 0x3F) as usize] as char);
} else {
out.push('=');
}
idx += 3;
}
out
}
pub fn default_brand_logo_png_bytes() -> io::Result<Vec<u8>> {
let payload: &str = DEFAULT_BRAND_LOGO_DATA_URI
.strip_prefix(PNG_DATA_URI_PREFIX)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID))?;
decode_base64(payload)
}
pub fn resolve_icon_png_bytes(custom_icon: Option<&Path>) -> io::Result<Vec<u8>> {
if let Some(path) = custom_icon {
let bytes: Vec<u8> = fs::read(path)?;
if bytes.starts_with(&PNG_SIGNATURE) {
return Ok(bytes);
}
return Err(Error::new(
ErrorKind::InvalidInput,
format!("{ERR_ICON_SOURCE_INVALID}: {}", path.display()),
));
}
if let Ok(env_val) = env::var(ENV_APP_ICON) {
let trimmed: &str = env_val.trim();
if !trimmed.is_empty() {
let env_path: PathBuf = PathBuf::from(trimmed);
if env_path.is_file() {
let bytes: Vec<u8> = fs::read(&env_path)?;
if bytes.starts_with(&PNG_SIGNATURE) {
return Ok(bytes);
}
}
}
}
default_brand_logo_png_bytes()
}
pub fn resolve_icon_rgba(custom_icon: Option<&Path>) -> io::Result<RgbaImage> {
let png_bytes: Vec<u8> = resolve_icon_png_bytes(custom_icon)?;
decode_png_rgba(&png_bytes)
}
pub fn resolve_icon_data_uri(custom_icon: Option<&Path>) -> io::Result<String> {
let env_icon: Option<PathBuf> = env::var(ENV_APP_ICON)
.ok()
.map(|val: String| val.trim().to_string())
.filter(|val: &String| !val.is_empty())
.map(PathBuf::from)
.filter(|path: &PathBuf| path.is_file());
if custom_icon.is_none() && env_icon.is_none() {
return Ok(DEFAULT_BRAND_LOGO_DATA_URI.to_string());
}
let rgba: RgbaImage = resolve_icon_rgba(custom_icon)?;
let resized: RgbaImage = resize_rgba(&rgba, ICON_DATA_URI_SIZE, ICON_DATA_URI_SIZE);
let png_bytes: Vec<u8> = encode_png_rgba(&resized);
let encoded: String = encode_base64(&png_bytes);
Ok(format!("{PNG_DATA_URI_PREFIX}{encoded}"))
}
pub fn decode_png_rgba(png_bytes: &[u8]) -> io::Result<RgbaImage> {
if png_bytes.len() < 33 || !png_bytes.starts_with(&PNG_SIGNATURE) {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
}
let mut pos: usize = PNG_SIGNATURE.len();
let mut width: u32 = 0;
let mut height: u32 = 0;
let mut bit_depth: u8 = 0;
let mut color_type: u8 = 0;
let mut seen_ihdr: bool = false;
let mut palette: Vec<[u8; 3]> = Vec::new();
let mut trns: Vec<u8> = Vec::new();
let mut idat_all: Vec<u8> = Vec::new();
while pos + 12 <= png_bytes.len() {
let chunk_len: usize = read_be_u32(png_bytes, pos)? as usize;
let tag: [u8; 4] = [
png_bytes[pos + 4],
png_bytes[pos + 5],
png_bytes[pos + 6],
png_bytes[pos + 7],
];
let data_start: usize = pos + 8;
let data_end: usize = data_start
.checked_add(chunk_len)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
let crc_end: usize = data_end
.checked_add(4)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
let chunk_data: &[u8] = png_bytes
.get(data_start..data_end)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
if crc_end > png_bytes.len() {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
}
if tag == PNG_CHUNK_IHDR {
if chunk_data.len() != 13 {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
}
width = read_be_u32(chunk_data, 0)?;
height = read_be_u32(chunk_data, 4)?;
bit_depth = chunk_data[8];
color_type = chunk_data[9];
let comp_method: u8 = chunk_data[10];
let filter_method: u8 = chunk_data[11];
let interlace_method: u8 = chunk_data[12];
let supported_depth: bool = [1u8, 2, 4, 8].contains(&bit_depth);
if width == 0
|| height == 0
|| comp_method != 0
|| filter_method != 0
|| interlace_method != 0
|| !supported_depth
{
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
}
seen_ihdr = true;
} else if tag == PNG_CHUNK_PLTE {
if !chunk_data.len().is_multiple_of(3) {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
}
palette.clear();
let mut idx: usize = 0;
while idx < chunk_data.len() {
palette.push([chunk_data[idx], chunk_data[idx + 1], chunk_data[idx + 2]]);
idx += 3;
}
} else if tag == PNG_CHUNK_TRNS {
trns = chunk_data.to_vec();
} else if tag == PNG_CHUNK_IDAT {
idat_all.extend_from_slice(chunk_data);
} else if tag == PNG_CHUNK_IEND {
break;
}
pos = crc_end;
}
if !seen_ihdr || idat_all.is_empty() {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
}
let samples_per_pixel: usize = match color_type {
0 | 3 => 1,
2 => 3,
4 => 2,
6 => 4,
_ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED)),
};
let bits_per_pixel: usize = samples_per_pixel * usize::from(bit_depth);
let stride: usize = (usize::try_from(width).unwrap_or(0) * bits_per_pixel).div_ceil(8);
let filter_bpp: usize = cmp::max(1, bits_per_pixel.div_ceil(8));
let expected_raw_len: usize = (stride + 1)
.checked_mul(usize::try_from(height).unwrap_or(0))
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
let raw_scanlines: Vec<u8> = zlib_decompress(&idat_all)?;
if raw_scanlines.len() < expected_raw_len {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
}
let mut prev_row: Vec<u8> = vec![0u8; stride];
let mut curr_row: Vec<u8> = vec![0u8; stride];
let mut rgba: Vec<u8> = Vec::with_capacity(
usize::try_from(width).unwrap_or(0) * usize::try_from(height).unwrap_or(0) * 4,
);
let height_usize: usize = usize::try_from(height).unwrap_or(0);
let width_usize: usize = usize::try_from(width).unwrap_or(0);
let mut row_idx: usize = 0;
while row_idx < height_usize {
let row_start: usize = row_idx * (stride + 1);
let filter_type: u8 = raw_scanlines[row_start];
let src_row: &[u8] = &raw_scanlines[row_start + 1..row_start + 1 + stride];
unfilter_png_scanline(filter_type, src_row, &prev_row, &mut curr_row, filter_bpp)?;
expand_png_row_to_rgba(
&curr_row,
width_usize,
bit_depth,
color_type,
&palette,
&trns,
&mut rgba,
)?;
prev_row.copy_from_slice(&curr_row);
row_idx += 1;
}
Ok(RgbaImage::new(width, height, rgba))
}
#[must_use]
pub fn resize_rgba(image: &RgbaImage, target_width: u32, target_height: u32) -> RgbaImage {
let dst_w: u32 = cmp::max(1, target_width);
let dst_h: u32 = cmp::max(1, target_height);
let src_w: u32 = image.get_width();
let src_h: u32 = image.get_height();
if src_w == dst_w && src_h == dst_h {
return image.clone();
}
let src_pixels: &[u8] = image.get_pixels();
let mut dst_pixels: Vec<u8> = vec![0u8; (dst_w as usize) * (dst_h as usize) * 4];
let scale_x: f64 = f64::from(src_w) / f64::from(dst_w);
let scale_y: f64 = f64::from(src_h) / f64::from(dst_h);
if dst_w < src_w && dst_h < src_h {
let mut dst_y: u32 = 0;
while dst_y < dst_h {
let y0: f64 = f64::from(dst_y) * scale_y;
let y1: f64 = (f64::from(dst_y) + 1.0) * scale_y;
let row_start: u32 = (y0.floor() as u32).min(src_h - 1);
let row_end: u32 = (y1.ceil() as u32).min(src_h);
let mut dst_x: u32 = 0;
while dst_x < dst_w {
let x0: f64 = f64::from(dst_x) * scale_x;
let x1: f64 = (f64::from(dst_x) + 1.0) * scale_x;
let col_start: u32 = (x0.floor() as u32).min(src_w - 1);
let col_end: u32 = (x1.ceil() as u32).min(src_w);
let mut acc_r: f64 = 0.0;
let mut acc_g: f64 = 0.0;
let mut acc_b: f64 = 0.0;
let mut acc_a: f64 = 0.0;
let mut weight_sum: f64 = 0.0;
let mut sy: u32 = row_start;
while sy < row_end {
let wy: f64 = (f64::from(sy + 1).min(y1) - f64::from(sy).max(y0)).max(0.0);
let mut sx: u32 = col_start;
while sx < col_end {
let wx: f64 = (f64::from(sx + 1).min(x1) - f64::from(sx).max(x0)).max(0.0);
let weight: f64 = wx * wy;
let offset: usize = ((sy * src_w + sx) as usize) * 4;
let alpha: f64 = f64::from(src_pixels[offset + 3]) / 255.0;
acc_r += f64::from(src_pixels[offset]) * alpha * weight;
acc_g += f64::from(src_pixels[offset + 1]) * alpha * weight;
acc_b += f64::from(src_pixels[offset + 2]) * alpha * weight;
acc_a += alpha * weight;
weight_sum += weight;
sx += 1;
}
sy += 1;
}
let dst_offset: usize = ((dst_y * dst_w + dst_x) as usize) * 4;
if weight_sum > 0.0 && acc_a > 1e-6 {
let out_a: f64 = (acc_a / weight_sum).clamp(0.0, 1.0);
dst_pixels[dst_offset] = (acc_r / acc_a).round().clamp(0.0, 255.0) as u8;
dst_pixels[dst_offset + 1] = (acc_g / acc_a).round().clamp(0.0, 255.0) as u8;
dst_pixels[dst_offset + 2] = (acc_b / acc_a).round().clamp(0.0, 255.0) as u8;
dst_pixels[dst_offset + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
}
dst_x += 1;
}
dst_y += 1;
}
} else {
let mut dst_y: u32 = 0;
while dst_y < dst_h {
let src_fy: f64 =
((f64::from(dst_y) + 0.5) * scale_y - 0.5).clamp(0.0, f64::from(src_h - 1));
let y_lo: u32 = src_fy.floor() as u32;
let y_hi: u32 = cmp::min(y_lo + 1, src_h - 1);
let ty: f64 = src_fy - f64::from(y_lo);
let mut dst_x: u32 = 0;
while dst_x < dst_w {
let src_fx: f64 =
((f64::from(dst_x) + 0.5) * scale_x - 0.5).clamp(0.0, f64::from(src_w - 1));
let x_lo: u32 = src_fx.floor() as u32;
let x_hi: u32 = cmp::min(x_lo + 1, src_w - 1);
let tx: f64 = src_fx - f64::from(x_lo);
let weights: [f64; 4] = [
(1.0 - tx) * (1.0 - ty),
tx * (1.0 - ty),
(1.0 - tx) * ty,
tx * ty,
];
let coords: [(u32, u32); 4] =
[(x_lo, y_lo), (x_hi, y_lo), (x_lo, y_hi), (x_hi, y_hi)];
let mut acc_r: f64 = 0.0;
let mut acc_g: f64 = 0.0;
let mut acc_b: f64 = 0.0;
let mut acc_a: f64 = 0.0;
let mut idx: usize = 0;
while idx < 4 {
let (cx, cy): (u32, u32) = coords[idx];
let weight: f64 = weights[idx];
let offset: usize = ((cy * src_w + cx) as usize) * 4;
let alpha: f64 = f64::from(src_pixels[offset + 3]) / 255.0;
acc_r += f64::from(src_pixels[offset]) * alpha * weight;
acc_g += f64::from(src_pixels[offset + 1]) * alpha * weight;
acc_b += f64::from(src_pixels[offset + 2]) * alpha * weight;
acc_a += alpha * weight;
idx += 1;
}
let dst_offset: usize = ((dst_y * dst_w + dst_x) as usize) * 4;
if acc_a > 1e-6 {
dst_pixels[dst_offset] = (acc_r / acc_a).round().clamp(0.0, 255.0) as u8;
dst_pixels[dst_offset + 1] = (acc_g / acc_a).round().clamp(0.0, 255.0) as u8;
dst_pixels[dst_offset + 2] = (acc_b / acc_a).round().clamp(0.0, 255.0) as u8;
dst_pixels[dst_offset + 3] = (acc_a * 255.0).round().clamp(0.0, 255.0) as u8;
}
dst_x += 1;
}
dst_y += 1;
}
}
RgbaImage::new(dst_w, dst_h, dst_pixels)
}
#[must_use]
pub fn encode_png_rgba(image: &RgbaImage) -> Vec<u8> {
let width: u32 = image.get_width();
let height: u32 = image.get_height();
let stride: usize = (width as usize) * 4;
let pixels: &[u8] = image.get_pixels();
let mut scanlines: Vec<u8> = Vec::with_capacity((stride + 1) * (height as usize));
let mut row: usize = 0;
while row < (height as usize) {
scanlines.push(0u8);
let start: usize = row * stride;
let end: usize = start + stride;
if end <= pixels.len() {
scanlines.extend_from_slice(&pixels[start..end]);
} else {
scanlines.resize(scanlines.len() + stride, 0u8);
}
row += 1;
}
let compressed: Vec<u8> = zlib_compress(&scanlines);
let mut ihdr: [u8; 13] = [0u8; 13];
ihdr[0..4].copy_from_slice(&width.to_be_bytes());
ihdr[4..8].copy_from_slice(&height.to_be_bytes());
ihdr[8] = 8;
ihdr[9] = 6;
ihdr[10] = 0;
ihdr[11] = 0;
ihdr[12] = 0;
let mut out: Vec<u8> = Vec::with_capacity(PNG_SIGNATURE.len() + compressed.len() + 64);
out.extend_from_slice(&PNG_SIGNATURE);
push_png_chunk(&mut out, PNG_CHUNK_IHDR, &ihdr);
push_png_chunk(&mut out, PNG_CHUNK_IDAT, &compressed);
push_png_chunk(&mut out, PNG_CHUNK_IEND, &[]);
out
}
#[must_use]
pub fn encode_ico_from_rgba(source: &RgbaImage) -> Vec<u8> {
let mut frames: Vec<(u32, Vec<u8>)> = Vec::with_capacity(ICO_ICON_SIZES.len());
for &size in ICO_ICON_SIZES.iter() {
let resized: RgbaImage = resize_rgba(source, size, size);
frames.push((size, encode_png_rgba(&resized)));
}
let count: u16 = frames.len() as u16;
let mut out: Vec<u8> = Vec::new();
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&count.to_le_bytes());
let mut data_offset: u32 = 6 + u32::from(count) * 16;
for (size, png_bytes) in frames.iter() {
let dim_byte: u8 = if *size >= 256 { 0 } else { *size as u8 };
out.push(dim_byte);
out.push(dim_byte);
out.push(0u8);
out.push(0u8);
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&32u16.to_le_bytes());
out.extend_from_slice(&(png_bytes.len() as u32).to_le_bytes());
out.extend_from_slice(&data_offset.to_le_bytes());
data_offset += png_bytes.len() as u32;
}
for (_, png_bytes) in frames.into_iter() {
out.extend_from_slice(&png_bytes);
}
out
}
#[must_use]
pub fn encode_icns_from_rgba(source: &RgbaImage) -> Vec<u8> {
let mut body: Vec<u8> = Vec::new();
for &(tag, size) in ICNS_ICON_SPECS.iter() {
let resized: RgbaImage = resize_rgba(source, size, size);
let png_bytes: Vec<u8> = encode_png_rgba(&resized);
let chunk_len: u32 = (8 + png_bytes.len()) as u32;
body.extend_from_slice(&tag);
body.extend_from_slice(&chunk_len.to_be_bytes());
body.extend_from_slice(&png_bytes);
}
let total_len: u32 = (8 + body.len()) as u32;
let mut out: Vec<u8> = Vec::with_capacity(8 + body.len());
out.extend_from_slice(&ICNS_MAGIC);
out.extend_from_slice(&total_len.to_be_bytes());
out.extend_from_slice(&body);
out
}
pub fn write_icon_png(output_path: &Path, size: u32, custom_icon: Option<&Path>) -> io::Result<()> {
let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
let resized: RgbaImage = resize_rgba(&source, size, size);
let encoded: Vec<u8> = encode_png_rgba(&resized);
write_icon_file(output_path, &encoded)
}
pub fn write_icon_ico(output_path: &Path, custom_icon: Option<&Path>) -> io::Result<()> {
let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
let encoded: Vec<u8> = encode_ico_from_rgba(&source);
write_icon_file(output_path, &encoded)
}
pub fn write_icon_icns(output_path: &Path, custom_icon: Option<&Path>) -> io::Result<()> {
let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
let encoded: Vec<u8> = encode_icns_from_rgba(&source);
write_icon_file(output_path, &encoded)
}
pub fn write_android_mipmap_icons(
res_dir: &Path,
custom_icon: Option<&Path>,
) -> io::Result<Vec<PathBuf>> {
let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
let mut written: Vec<PathBuf> = Vec::with_capacity(ANDROID_MIPMAP_SPECS.len());
for &(density_dir, size) in ANDROID_MIPMAP_SPECS.iter() {
let dest: PathBuf = res_dir.join(density_dir).join(ANDROID_LAUNCHER_ICON_NAME);
let resized: RgbaImage = resize_rgba(&source, size, size);
write_icon_file(&dest, &encode_png_rgba(&resized))?;
written.push(dest);
}
Ok(written)
}
pub fn write_ios_bundle_icons(
bundle_dir: &Path,
custom_icon: Option<&Path>,
) -> io::Result<Vec<PathBuf>> {
let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
let mut written: Vec<PathBuf> = Vec::with_capacity(IOS_BUNDLE_ICON_SPECS.len());
for &(filename, size) in IOS_BUNDLE_ICON_SPECS.iter() {
let dest: PathBuf = bundle_dir.join(filename);
let resized: RgbaImage = resize_rgba(&source, size, size);
write_icon_file(&dest, &encode_png_rgba(&resized))?;
written.push(dest);
}
Ok(written)
}
pub fn write_web_icons(out_dir: &Path, custom_icon: Option<&Path>) -> io::Result<Vec<PathBuf>> {
write_named_png_specs(out_dir, &WEB_BUNDLE_ICON_SPECS, custom_icon)
}
pub fn write_web_raw_icons(out_dir: &Path, custom_icon: Option<&Path>) -> io::Result<Vec<PathBuf>> {
write_named_png_specs(out_dir, &WEB_RAW_ICON_SPECS, custom_icon)
}
fn write_named_png_specs(
out_dir: &Path,
specs: &[(&str, u32)],
custom_icon: Option<&Path>,
) -> io::Result<Vec<PathBuf>> {
let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
let mut cache: BTreeMap<u32, Vec<u8>> = BTreeMap::new();
let mut written: Vec<PathBuf> = Vec::with_capacity(specs.len());
for &(filename, size) in specs.iter() {
let png_bytes: &Vec<u8> = cache.entry(size).or_insert_with(|| {
let resized: RgbaImage = resize_rgba(&source, size, size);
encode_png_rgba(&resized)
});
let dest: PathBuf = out_dir.join(filename);
write_icon_file(&dest, png_bytes)?;
written.push(dest);
}
Ok(written)
}
fn write_icon_file(output_path: &Path, bytes: &[u8]) -> io::Result<()> {
if let Some(parent) = output_path.parent()
&& !parent.as_os_str().is_empty()
{
fs::create_dir_all(parent)?;
}
fs::write(output_path, bytes)
}
fn push_png_chunk(out: &mut Vec<u8>, tag: [u8; 4], data: &[u8]) {
let mut crc_buf: Vec<u8> = Vec::with_capacity(4 + data.len());
crc_buf.extend_from_slice(&tag);
crc_buf.extend_from_slice(data);
let checksum: u32 = crc32_bytes(&crc_buf);
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(&tag);
out.extend_from_slice(data);
out.extend_from_slice(&checksum.to_be_bytes());
}
fn decode_base64_char(byte_val: u8) -> Option<u8> {
match byte_val {
b'A'..=b'Z' => Some(byte_val - b'A'),
b'a'..=b'z' => Some(byte_val - b'a' + 26),
b'0'..=b'9' => Some(byte_val - b'0' + 52),
b'+' => Some(62),
b'/' => Some(63),
_ => None,
}
}
fn read_be_u32(bytes: &[u8], offset: usize) -> io::Result<u32> {
let slice: &[u8] = bytes
.get(offset..offset + 4)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
}
fn unfilter_png_scanline(
filter_type: u8,
src: &[u8],
prev: &[u8],
dst: &mut [u8],
bpp: usize,
) -> io::Result<()> {
match filter_type {
0 => dst.copy_from_slice(src),
1 => {
let mut idx: usize = 0;
while idx < src.len() {
let left: u8 = if idx >= bpp { dst[idx - bpp] } else { 0 };
dst[idx] = src[idx].wrapping_add(left);
idx += 1;
}
}
2 => {
let mut idx: usize = 0;
while idx < src.len() {
dst[idx] = src[idx].wrapping_add(prev[idx]);
idx += 1;
}
}
3 => {
let mut idx: usize = 0;
while idx < src.len() {
let left: u16 = if idx >= bpp {
u16::from(dst[idx - bpp])
} else {
0
};
let up: u16 = u16::from(prev[idx]);
let avg: u8 = ((left + up) / 2) as u8;
dst[idx] = src[idx].wrapping_add(avg);
idx += 1;
}
}
4 => {
let mut idx: usize = 0;
while idx < src.len() {
let left: u8 = if idx >= bpp { dst[idx - bpp] } else { 0 };
let up: u8 = prev[idx];
let up_left: u8 = if idx >= bpp { prev[idx - bpp] } else { 0 };
dst[idx] = src[idx].wrapping_add(paeth_predictor(left, up, up_left));
idx += 1;
}
}
_ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_FILTER)),
}
Ok(())
}
fn paeth_predictor(left: u8, up: u8, up_left: u8) -> u8 {
let left_i: i32 = i32::from(left);
let up_i: i32 = i32::from(up);
let up_left_i: i32 = i32::from(up_left);
let pred: i32 = left_i + up_i - up_left_i;
let dist_left: i32 = (pred - left_i).abs();
let dist_up: i32 = (pred - up_i).abs();
let dist_up_left: i32 = (pred - up_left_i).abs();
if dist_left <= dist_up && dist_left <= dist_up_left {
left
} else if dist_up <= dist_up_left {
up
} else {
up_left
}
}
fn expand_png_row_to_rgba(
row: &[u8],
width: usize,
bit_depth: u8,
color_type: u8,
palette: &[[u8; 3]],
trns: &[u8],
out: &mut Vec<u8>,
) -> io::Result<()> {
match color_type {
6 => {
if bit_depth != 8 || row.len() < width * 4 {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
}
out.extend_from_slice(&row[..width * 4]);
}
2 => {
if bit_depth != 8 || row.len() < width * 3 {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
}
let has_key: bool = trns.len() >= 6;
let key_r: u8 = if has_key { trns[1] } else { 0 };
let key_g: u8 = if has_key { trns[3] } else { 0 };
let key_b: u8 = if has_key { trns[5] } else { 0 };
let mut col: usize = 0;
while col < width {
let offset: usize = col * 3;
let red: u8 = row[offset];
let green: u8 = row[offset + 1];
let blue: u8 = row[offset + 2];
let alpha: u8 = if has_key && red == key_r && green == key_g && blue == key_b {
0
} else {
255
};
out.extend_from_slice(&[red, green, blue, alpha]);
col += 1;
}
}
4 => {
if bit_depth != 8 || row.len() < width * 2 {
return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
}
let mut col: usize = 0;
while col < width {
let gray: u8 = row[col * 2];
let alpha: u8 = row[col * 2 + 1];
out.extend_from_slice(&[gray, gray, gray, alpha]);
col += 1;
}
}
3 => {
let mut col: usize = 0;
while col < width {
let pal_idx: usize = usize::from(extract_packed_sample(row, col, bit_depth)?);
let rgb: [u8; 3] = *palette
.get(pal_idx)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
let alpha: u8 = trns.get(pal_idx).copied().unwrap_or(255);
out.extend_from_slice(&[rgb[0], rgb[1], rgb[2], alpha]);
col += 1;
}
}
0 => {
let max_sample: u16 = (1u16 << bit_depth) - 1;
let has_key: bool = trns.len() >= 2;
let key_gray: u8 = if has_key { trns[1] } else { 0 };
let mut col: usize = 0;
while col < width {
let raw_val: u8 = extract_packed_sample(row, col, bit_depth)?;
let gray: u8 = if bit_depth == 8 {
raw_val
} else {
((u16::from(raw_val) * 255) / max_sample) as u8
};
let alpha: u8 = if has_key && raw_val == key_gray {
0
} else {
255
};
out.extend_from_slice(&[gray, gray, gray, alpha]);
col += 1;
}
}
_ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED)),
}
Ok(())
}
fn extract_packed_sample(row: &[u8], col: usize, bit_depth: u8) -> io::Result<u8> {
if bit_depth == 8 {
return row
.get(col)
.copied()
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
}
let samples_per_byte: usize = usize::from(8 / bit_depth);
let byte_idx: usize = col / samples_per_byte;
let sub_idx: usize = col % samples_per_byte;
let byte_val: u8 = *row
.get(byte_idx)
.ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
let shift: u8 = 8 - bit_depth * ((sub_idx as u8) + 1);
let mask: u8 = (1u8 << bit_depth) - 1;
Ok((byte_val >> shift) & mask)
}