type Rgba = [u8; 4];
type Block = [Rgba; 16];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
Etc1,
Etc2,
Etc2A1,
Etc2A8,
EacR,
EacRSigned,
EacRg,
EacRgSigned,
}
const WRITE_ORDER: [usize; 16] = [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15];
const WRITE_ORDER_REV: [usize; 16] = [15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0];
const ETC1_MODIFIERS: [[u8; 2]; 8] = [
[2, 8],
[5, 17],
[9, 29],
[13, 42],
[18, 60],
[24, 80],
[33, 106],
[47, 183],
];
const ETC2A_MODIFIERS: [[[u8; 2]; 8]; 2] = [
[
[0, 8],
[0, 17],
[0, 29],
[0, 42],
[0, 60],
[0, 80],
[0, 106],
[0, 183],
],
ETC1_MODIFIERS,
];
const ETC1_SUBBLOCKS: [[usize; 16]; 2] = [
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
];
const ETC2_DISTANCES: [i32; 8] = [3, 6, 11, 16, 23, 32, 41, 64];
const ETC2_ALPHA_MODS: [[i32; 8]; 16] = [
[-3, -6, -9, -15, 2, 5, 8, 14],
[-3, -7, -10, -13, 2, 6, 9, 12],
[-2, -5, -8, -13, 1, 4, 7, 12],
[-2, -4, -6, -13, 1, 3, 5, 12],
[-3, -6, -8, -12, 2, 5, 7, 11],
[-3, -7, -9, -11, 2, 6, 8, 10],
[-4, -7, -8, -11, 3, 6, 7, 10],
[-3, -5, -8, -11, 2, 4, 7, 10],
[-2, -6, -8, -10, 1, 5, 7, 9],
[-2, -5, -8, -10, 1, 4, 7, 9],
[-2, -4, -8, -10, 1, 3, 7, 9],
[-2, -5, -7, -10, 1, 4, 6, 9],
[-3, -4, -7, -10, 2, 3, 6, 9],
[-1, -2, -3, -10, 0, 1, 2, 9],
[-4, -6, -8, -9, 3, 5, 7, 8],
[-3, -5, -7, -9, 2, 4, 6, 8],
];
const TRANSPARENT: Rgba = [0, 0, 0, 0];
fn pick<T: Copy + Default>(table: &[T], i: usize) -> T {
table.get(i).copied().unwrap_or_default()
}
fn index(v: u64) -> usize {
usize::try_from(v).unwrap_or(0)
}
fn low(v: i32) -> u8 {
u8::try_from(v & 0xFF).unwrap_or(0)
}
fn clamp(n: i32) -> u8 {
u8::try_from(n.clamp(0, 255)).unwrap_or(u8::MAX)
}
fn applicate(colour: [u8; 3], modifier: i32) -> Rgba {
let [red, green, blue] = colour.map(|v| clamp(i32::from(v) + modifier));
[red, green, blue, 255]
}
fn raw(colour: [u8; 3]) -> Rgba {
let [red, green, blue] = colour;
[red, green, blue, 255]
}
pub(crate) fn decode(kind: Kind, data: &[u8], w: usize, h: usize, out: &mut [u8]) {
match kind {
Kind::EacR => return eac_image::<8, false>(data, w, h, out),
Kind::EacRSigned => return eac_image::<8, true>(data, w, h, out),
Kind::EacRg => return eac_image::<16, false>(data, w, h, out),
Kind::EacRgSigned => return eac_image::<16, true>(data, w, h, out),
_ => {}
}
let block_bytes = match kind {
Kind::Etc1 | Kind::Etc2 | Kind::Etc2A1 | Kind::EacR | Kind::EacRSigned => 8,
Kind::Etc2A8 | Kind::EacRg | Kind::EacRgSigned => 16,
};
let (blocks_x, blocks_y) = (w.div_ceil(4), h.div_ceil(4));
let row = w.saturating_mul(4);
let mut blocks = data.chunks_exact(block_bytes);
for by in 0..blocks_y {
for bx in 0..blocks_x {
let Some(src) = blocks.next() else {
return;
};
let px = block(kind, half(src, 0), half(src, 8));
let x0 = bx * 4;
let cols = (w - x0).min(4);
for (r, line) in px.as_chunks::<4>().0.iter().enumerate() {
let y = by * 4 + r;
if y >= h {
break;
}
let at = (h - 1 - y).saturating_mul(row).saturating_add(x0 * 4);
match out.get_mut(at..at.saturating_add(4 * cols)) {
Some(dst) => crate::place::put_row(dst, line),
None => put_short(out, at, line, cols),
}
}
}
}
}
#[cold]
#[inline(never)]
fn put_short(out: &mut [u8], at: usize, line: &[Rgba; 4], cols: usize) {
for (c, px) in line.iter().enumerate().take(cols) {
let at = at.saturating_add(c * 4);
if let Some(dst) = out.get_mut(at..at.saturating_add(4)) {
dst.copy_from_slice(px);
}
}
}
fn block(kind: Kind, first: [u8; 8], second: [u8; 8]) -> Block {
match kind {
Kind::Etc1 => etc1(first),
Kind::Etc2 => etc2(first, None),
Kind::Etc2A1 => etc2(first, Some(first[3] >> 1 & 1 == 1)),
Kind::Etc2A8 => {
let mut px = etc2(second, None);
etc2_alpha(first, &mut px);
px
}
Kind::EacR | Kind::EacRSigned | Kind::EacRg | Kind::EacRgSigned => {
let signed = matches!(kind, Kind::EacRSigned | Kind::EacRgSigned);
let mut px = [[0, 0, 0, 255]; 16];
eac(first, 0, signed, &mut px);
if matches!(kind, Kind::EacRg | Kind::EacRgSigned) {
eac(second, 1, signed, &mut px);
}
px
}
}
}
fn half(src: &[u8], at: usize) -> [u8; 8] {
src.get(at..at + 8)
.and_then(|s| <[u8; 8]>::try_from(s).ok())
.unwrap_or_default()
}
fn index_bits(bytes: [u8; 8]) -> (u32, u32) {
let [_, _, _, _, b4, b5, b6, b7] = bytes.map(u32::from);
(b6 << 8 | b7, b4 << 8 | b5)
}
fn sub_blocks(
bytes: [u8; 8],
colours: [[u8; 3]; 2],
modifier: impl Fn(usize, usize) -> u8,
transparent: impl Fn(u32, u32) -> bool,
) -> Block {
let code = [usize::from(bytes[3] >> 5), usize::from(bytes[3] >> 2 & 7)];
let table = pick(&ETC1_SUBBLOCKS, usize::from(bytes[3] & 1));
let mut set = [[0; 4]; 8];
for (k, px) in set.iter_mut().enumerate() {
let (sub, n) = (k >> 2, k & 3);
let (lsb, msb) = (u32::from(n & 1 == 1), u32::from(n >> 1 == 1));
let size = i32::from(modifier(pick(&code, sub), n & 1));
*px = applicate(pick(&colours, sub), if msb == 1 { -size } else { size });
if transparent(lsb, msb) {
*px = TRANSPARENT;
}
}
let (mut lsb, mut msb) = index_bits(bytes);
let mut out = [[0; 4]; 16];
for (&at, &sub) in WRITE_ORDER.iter().zip(&table) {
let n = index(u64::from((msb & 1) << 1 | (lsb & 1)));
if let Some(px) = out.get_mut(at) {
*px = pick(&set, (sub << 2 | n) & 7);
}
lsb >>= 1;
msb >>= 1;
}
out
}
fn etc1_modifier(code: usize, lsb: usize) -> u8 {
pick(&pick(&ETC1_MODIFIERS, code), lsb)
}
fn pairs(bytes: [u8; 8], channel: impl Fn(u8) -> (u8, u8)) -> [[u8; 3]; 2] {
let [(r0, r1), (g0, g1), (b0, b1)] = [bytes[0], bytes[1], bytes[2]].map(channel);
[[r0, g0, b0], [r1, g1, b1]]
}
fn individual(bytes: [u8; 8]) -> [[u8; 3]; 2] {
pairs(bytes, |byte| {
let v = i32::from(byte);
(low((v & 0xf0) | v >> 4), low((v & 0x0f) | v << 4))
})
}
fn etc1(bytes: [u8; 8]) -> Block {
let colours = if bytes[3] & 2 != 0 {
pairs(bytes, |byte| {
let v = i32::from(byte);
let base = low(v & 0xf8);
let other = low(i32::from(base) + (v << 3 & 0x18) - (v << 3 & 0x20));
(base | base >> 5, other | other >> 5)
})
} else {
individual(bytes)
};
sub_blocks(bytes, colours, etc1_modifier, |_, _| false)
}
fn four_colours(bytes: [u8; 8], mut set: [Rgba; 4], punch: bool) -> Block {
if let (true, Some(px)) = (punch, set.get_mut(2)) {
*px = TRANSPARENT;
}
let (mut lsb, msb) = index_bits(bytes);
let mut msb = msb << 1;
let mut out = [[0; 4]; 16];
for &at in &WRITE_ORDER {
if let Some(px) = out.get_mut(at) {
*px = pick(&set, index(u64::from((msb & 2) | (lsb & 1))) & 3);
}
lsb >>= 1;
msb >>= 1;
}
out
}
fn delta(v: i32) -> i32 {
(v << 3 & 0x18) - (v << 3 & 0x20)
}
fn etc2(bytes: [u8; 8], opaque: Option<bool>) -> Block {
let punch = opaque == Some(false);
if opaque.is_none() && bytes[3] & 2 == 0 {
return sub_blocks(bytes, individual(bytes), etc1_modifier, |_, _| false);
}
let [red, green, blue] = [bytes[0], bytes[1], bytes[2]].map(|v| i32::from(v & 0xf8));
let [dr, dg, db] = [bytes[0], bytes[1], bytes[2]].map(|v| delta(i32::from(v)));
let out_of_range = |v: i32| !(0..=255).contains(&v);
if out_of_range(red + dr) {
four_colours(bytes, t_mode(bytes), punch)
} else if out_of_range(green + dg) {
four_colours(bytes, h_mode(bytes), punch)
} else if out_of_range(blue + db) {
planar(bytes)
} else {
let channel = |base: i32, delta: i32| {
let base = low(base);
let other = low(i32::from(base) + delta);
(base | base >> 5, other | other >> 5)
};
let [(r0, r1), (g0, g1), (b0, b1)] =
[(red, dr), (green, dg), (blue, db)].map(|(base, d)| channel(base, d));
let colours = [[r0, g0, b0], [r1, g1, b1]];
match opaque {
None => sub_blocks(bytes, colours, etc1_modifier, |_, _| false),
Some(opaque) => sub_blocks(
bytes,
colours,
|code, lsb| {
pick(
&pick(&pick(&ETC2A_MODIFIERS, usize::from(opaque)), code),
lsb,
)
},
|lsb, msb| punch && msb == 1 && lsb == 0,
),
}
}
}
fn t_mode(bytes: [u8; 8]) -> [Rgba; 4] {
let [b0, b1, b2, b3, ..] = bytes.map(i32::from);
let c0 = [
low((b0 << 3 & 0xc0) | (b0 << 4 & 0x30) | (b0 >> 1 & 0xc) | (b0 & 3)),
low((b1 & 0xf0) | b1 >> 4),
low((b1 & 0x0f) | b1 << 4),
];
let c1 = [
low((b2 & 0xf0) | b2 >> 4),
low((b2 & 0x0f) | b2 << 4),
low((b3 & 0xf0) | b3 >> 4),
];
let dist = pick(
&ETC2_DISTANCES,
index(u64::from(bytes[3] >> 1 & 6 | bytes[3] & 1)),
);
[raw(c0), applicate(c1, dist), raw(c1), applicate(c1, -dist)]
}
fn h_mode(bytes: [u8; 8]) -> [Rgba; 4] {
let [b0, b1, b2, b3, ..] = bytes.map(i32::from);
let g0 = low((b0 << 5 & 0xe0) | (b1 & 0x10));
let blue0 = low((b1 & 8) | (b1 << 1 & 6) | b2 >> 7);
let g1 = low((b2 << 5 & 0xe0) | (b3 >> 3 & 0x10));
let c0 = [
low((b0 << 1 & 0xf0) | (b0 >> 3 & 0xf)),
g0 | g0 >> 4,
low(i32::from(blue0) | i32::from(blue0) << 4),
];
let c1 = [
low((b2 << 1 & 0xf0) | (b2 >> 3 & 0xf)),
g1 | g1 >> 4,
low((b3 << 1 & 0xf0) | (b3 >> 3 & 0xf)),
];
let mut n = index(u64::from(bytes[3] & 4 | bytes[3] << 1 & 2));
if c0 >= c1 {
n += 1;
}
let dist = pick(&ETC2_DISTANCES, n);
[
applicate(c0, dist),
applicate(c0, -dist),
applicate(c1, dist),
applicate(c1, -dist),
]
}
fn planar(bytes: [u8; 8]) -> Block {
let [b0, b1, b2, b3, b4, b5, b6, b7] = bytes.map(i32::from);
let blue_o = low((b1 << 7 & 0x80) | (b2 << 2 & 0x60) | (b2 << 3 & 0x18) | (b3 >> 5 & 4));
let blue_h = low((b4 << 7 & 0x80) | (b5 >> 1 & 0x7c));
let colours = [
[
low((b0 << 1 & 0xfc) | (b0 >> 5 & 3)),
low((b0 << 7 & 0x80) | (b1 & 0x7e) | (b0 & 1)),
blue_o | blue_o >> 6,
],
[
low((b3 << 1 & 0xf8) | (b3 << 2 & 4) | (b3 >> 5 & 3)),
low((b4 & 0xfe) | b4 >> 7),
blue_h | blue_h >> 6,
],
[
low((b5 << 5 & 0xe0) | (b6 >> 3 & 0x1c) | (b5 >> 1 & 3)),
low((b6 << 3 & 0xf8) | (b7 >> 5 & 0x6) | (b6 >> 4 & 1)),
low(b7 << 2 | (b7 >> 4 & 3)),
],
];
let [origin, horizontal, vertical] = colours.map(|c| c.map(i32::from));
let mut out = [[0; 4]; 16];
for (i, px) in out.iter_mut().enumerate() {
let x = i32::try_from(i % 4).unwrap_or(0);
let y = i32::try_from(i / 4).unwrap_or(0);
let channel = |n: usize| {
let o = pick(&origin, n);
clamp((x * (pick(&horizontal, n) - o) + y * (pick(&vertical, n) - o) + 4 * o + 2) >> 2)
};
*px = [channel(0), channel(1), channel(2), 255];
}
out
}
fn alpha_indices(bytes: [u8; 8]) -> u64 {
u64::from_be_bytes(bytes)
}
fn etc2_alpha(bytes: [u8; 8], px: &mut Block) {
let base = i32::from(bytes[0]);
if bytes[1] & 0xf0 != 0 {
let multiplier = i32::from(bytes[1] >> 4);
let table = pick(&ETC2_ALPHA_MODS, usize::from(bytes[1] & 0xf));
let alphas = table.map(|m| clamp(base + multiplier * m));
let mut indices = alpha_indices(bytes);
for &at in &WRITE_ORDER_REV {
if let Some(p) = px.get_mut(at) {
p[3] = pick(&alphas, index(indices & 7) & 7);
}
indices >>= 3;
}
} else {
for p in px.iter_mut() {
p[3] = bytes[0];
}
}
}
fn eac_image<const B: usize, const S: bool>(data: &[u8], w: usize, h: usize, out: &mut [u8]) {
crate::place::put_block_data::<B, 16>(
out,
w.saturating_mul(4),
h,
(w.div_ceil(4), h.div_ceil(4)),
data.as_chunks::<B>().0,
|src, rows| {
let red = u64::from_be_bytes(half(src, 0));
let reds = eac_values::<S>(red).map(|v| v | 0xFF00_0000);
if B == 16 {
let green = u64::from_be_bytes(half(src, 8));
let greens = eac_values::<S>(green).map(|v| v << 8);
put_eac(rows, |at| {
pick(&reds, index(red >> at & 7)) | pick(&greens, index(green >> at & 7))
});
} else {
put_eac(rows, |at| pick(&reds, index(red >> at & 7)));
}
true
},
);
}
#[allow(clippy::inline_always, reason = "measured: every block's pixels")]
#[inline(always)]
fn put_eac(rows: [&mut [u8; 16]; 4], pixel: impl Fn(u32) -> u32) {
for (y, row) in (0u32..).zip(rows) {
let [a, b, c, d] = [0, 1, 2, 3].map(|x| u128::from(pixel(45 - 12 * x - 3 * y)));
*row = (a | b << 32 | c << 64 | d << 96).to_le_bytes();
}
}
#[allow(clippy::inline_always, reason = "measured: every block's values")]
#[inline(always)]
fn eac_values<const S: bool>(block: u64) -> [u32; 8] {
let [b0, b1, ..] = block.to_be_bytes();
let (base, offset) = if S {
(i32::from(i8::from_ne_bytes([b0])).max(-127), 1023)
} else {
(i32::from(b0), 4)
};
let multiplier = match i32::from(b1 >> 1 & 0x78) {
0 => 1,
m => m,
};
let table = pick(&ETC2_ALPHA_MODS, usize::from(b1 & 0xf));
let start = base * 8 + offset;
table.map(|m| {
let value = start + multiplier * m;
u32::try_from(value.clamp(0, 2047) >> 3).unwrap_or(0)
})
}
fn eac(bytes: [u8; 8], channel: usize, signed: bool, px: &mut Block) {
let indices = alpha_indices(bytes);
let values = if signed {
eac_values::<true>(indices)
} else {
eac_values::<false>(indices)
};
let mut indices = indices;
for &at in &WRITE_ORDER_REV {
if let Some(c) = px.get_mut(at).and_then(|p| p.get_mut(channel & 3)) {
*c = low(i32::try_from(pick(&values, index(indices & 7))).unwrap_or(0));
}
indices >>= 3;
}
}
#[cfg(test)]
mod tests;