anitty 0.1.0

Anime character animation rendering for terminals
Documentation
use std::io::Write;

use icy_sixel::{EncodeOptions, sixel_encode};

use crate::{Backend, Error, RgbaFrame};

/// SIXEL output for Konsole and other SIXEL-capable terminals.
///
/// Each frame is composited onto an explicit background and quantized to at most
/// 256 colors. A fully painted canvas prevents transparent pixels from leaving
/// trails from earlier frames. The height is rounded up to a six-pixel band;
/// the extra rows use the same background, without scaling the source image.
/// Leave room in the terminal viewport for this padded height.
/// Terminal capabilities are not probed automatically.
/// Use [`super::Iterm2`] or [`super::Kitty`] to preserve alpha in Konsole.
#[derive(Debug, Default)]
pub struct Sixel {
    background: [u8; 3],
}

impl Sixel {
    /// Choose the RGB background used for alpha compositing (black by default).
    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"))?;
        // Konsole expands the last band even when raster attributes specify a
        // shorter image. Unpainted rows otherwise take arbitrary palette color
        // zero. Composite zero-alpha padding onto our background as well.
        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()
            },
        )?;
        // DECSC / DECRC keep successive frames anchored at the caller's cursor.
        output.write_all(b"\x1b7")?;
        output.write_all(encoded.as_bytes())?;
        output.write_all(b"\x1b8")?;
        output.flush()?;
        Ok(())
    }
}