use std::io::Write;
use icy_sixel::{EncodeOptions, sixel_encode};
use crate::{Backend, Error, RgbaFrame};
#[derive(Debug, Default)]
pub struct Sixel {
background: [u8; 3],
}
impl Sixel {
pub fn new(background: [u8; 3]) -> Self {
Self { background }
}
}
impl Backend for Sixel {
fn draw(&mut self, frame: &RgbaFrame, output: &mut dyn Write) -> Result<(), Error> {
let height = frame
.height()
.checked_next_multiple_of(6)
.ok_or(Error::InvalidFrame("SIXEL padded height exceeds u32"))?;
let mut pixels = vec![0; RgbaFrame::byte_len(frame.width(), height)?];
pixels[..frame.pixels().len()].copy_from_slice(frame.pixels());
for pixel in pixels.chunks_exact_mut(4) {
let alpha = u32::from(pixel[3]);
for (channel, background) in pixel[..3].iter_mut().zip(self.background) {
*channel =
((u32::from(*channel) * alpha + u32::from(background) * (255 - alpha) + 127)
/ 255) as u8;
}
pixel[3] = 255;
}
let encoded = sixel_encode(
&pixels,
frame.width() as usize,
height as usize,
&EncodeOptions {
diffusion: 0.0,
..Default::default()
},
)?;
output.write_all(b"\x1b7")?;
output.write_all(encoded.as_bytes())?;
output.write_all(b"\x1b8")?;
output.flush()?;
Ok(())
}
}