wtrenderlib 0.1.0

Dependency-free terminal rendering primitives for RGB and RGBA frames
Documentation
use std::io::Write;

use crate::{FrameView, PixelFormat, Result};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KittyOptions {
    pub image_id: u32,
    pub width: usize,
    pub height: usize,
    pub chunk_size: usize,
    pub delete_after: bool,
}

impl Default for KittyOptions {
    fn default() -> Self {
        Self {
            image_id: 1,
            width: 0,
            height: 0,
            chunk_size: 3072,
            delete_after: false,
        }
    }
}

pub fn render_kitty<W: Write>(
    frame: FrameView<'_>,
    output: &mut W,
    options: KittyOptions,
) -> Result<()> {
    let width = if options.width == 0 {
        frame.width()
    } else {
        options.width
    };
    let height = if options.height == 0 {
        frame.height()
    } else {
        options.height
    };
    let format = match frame.format() {
        PixelFormat::Rgb8 => 24,
        PixelFormat::Rgba8 => 32,
    };
    let chunk_size = options.chunk_size.max(4) / 4 * 4;
    let mut encoded = Vec::new();
    let mut raw = Vec::new();
    for y in 0..frame.height() {
        raw.extend_from_slice(frame.row(y).expect("validated row"));
    }
    for chunk in raw.chunks(chunk_size / 4 * 3) {
        encoded.clear();
        encode_base64(chunk, &mut encoded);
        let is_last = chunk.as_ptr_range().end == raw.as_ptr_range().end;
        write!(
            output,
            "\x1b_Ga=T,f={format},s={width},v={height},i={},m={};",
            options.image_id,
            if is_last { 0 } else { 1 }
        )?;
        output.write_all(&encoded)?;
        output.write_all(b"\x1b\\")?;
    }
    if options.delete_after {
        write!(output, "\x1b_Ga=d,d=I,i={}\x1b\\", options.image_id)?;
    }
    Ok(())
}

fn encode_base64(input: &[u8], output: &mut Vec<u8>) {
    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for chunk in input.chunks(3) {
        let a = chunk[0];
        let b = chunk.get(1).copied().unwrap_or(0);
        let c = chunk.get(2).copied().unwrap_or(0);
        output.push(TABLE[(a >> 2) as usize]);
        output.push(TABLE[((a & 0x03) << 4 | b >> 4) as usize]);
        output.push(if chunk.len() > 1 {
            TABLE[((b & 0x0f) << 2 | c >> 6) as usize]
        } else {
            b'='
        });
        output.push(if chunk.len() > 2 {
            TABLE[(c & 0x3f) as usize]
        } else {
            b'='
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn emits_rgb_kitty_payload() {
        let frame = FrameView::new(&[255, 0, 0], 1, 1, 3, PixelFormat::Rgb8).unwrap();
        let mut output = Vec::new();
        render_kitty(
            frame,
            &mut output,
            KittyOptions {
                chunk_size: 4,
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(
            String::from_utf8(output).unwrap(),
            "\x1b_Ga=T,f=24,s=1,v=1,i=1,m=0;/wAA\x1b\\"
        );
    }

    #[test]
    fn marks_intermediate_chunks() {
        let frame = FrameView::new(&[255, 0, 0, 0, 255, 0], 2, 1, 6, PixelFormat::Rgb8).unwrap();
        let mut output = Vec::new();
        render_kitty(
            frame,
            &mut output,
            KittyOptions {
                chunk_size: 4,
                ..Default::default()
            },
        )
        .unwrap();
        let output = String::from_utf8(output).unwrap();
        assert!(output.contains("m=1;"));
        assert!(output.contains("m=0;"));
    }
}