garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /media/src/video.rs

raw

//! The video codec: YCbCr 4:2:0 frames in 16×16 macroblocks, each skipped,
//! or coded as six 8×8 DCT blocks of its difference from the reference.
//!
//! A packet: frame number (u16), flags (bit 0: key frame), first macroblock
//! (u16), count (u16); then per macroblock a byte, 0 skipped or 1 coded, and
//! for a coded one its six blocks: (run of zeros, level) pairs, a level as a
//! zigzag varint, ended by run 0xff.

use alloc::vec;
use alloc::vec::Vec;

/// A picture in YCbCr 4:2:0, its sides multiples of 16.
#[derive(Clone, PartialEq, Debug)]
pub struct Frame {
    pub width: usize,
    pub height: usize,
    pub y: Vec<u8>,
    pub cb: Vec<u8>,
    pub cr: Vec<u8>,
}

impl Frame {
    pub fn new(width: usize, height: usize) -> Frame {
        assert!(width.is_multiple_of(16) && height.is_multiple_of(16));
        Frame {
            width,
            height,
            y: vec![128; width * height],
            cb: vec![128; width * height / 4],
            cr: vec![128; width * height / 4],
        }
    }

    /// From 0x00RRGGBB pixels, `width` a row (BT.601, full range).
    pub fn from_rgb(width: usize, height: usize, rgb: &[u32]) -> Frame {
        let mut f = Frame::new(width, height);
        for py in 0..height {
            for px in 0..width {
                let p = rgb[py * width + px];
                let (r, g, b) = ((p >> 16 & 255) as i32, (p >> 8 & 255) as i32, (p & 255) as i32);
                f.y[py * width + px] = ((77 * r + 150 * g + 29 * b) >> 8) as u8;
                if px % 2 == 0 && py % 2 == 0 {
                    let i = (py / 2) * (width / 2) + px / 2;
                    f.cb[i] = (((-43 * r - 85 * g + 128 * b) >> 8) + 128).clamp(0, 255) as u8;
                    f.cr[i] = (((128 * r - 107 * g - 21 * b) >> 8) + 128).clamp(0, 255) as u8;
                }
            }
        }
        f
    }

    /// To 0x00RRGGBB pixels, scaled by `scale` (1, 2, …) into `out`
    /// (`stride` pixels a row) at (x0, y0).
    pub fn to_rgb(&self, out: &mut [u32], stride: usize, x0: usize, y0: usize, scale: usize) {
        for py in 0..self.height {
            for px in 0..self.width {
                let y = i32::from(self.y[py * self.width + px]);
                let i = (py / 2) * (self.width / 2) + px / 2;
                let (cb, cr) = (i32::from(self.cb[i]) - 128, i32::from(self.cr[i]) - 128);
                let r = (y + ((359 * cr) >> 8)).clamp(0, 255) as u32;
                let g = (y - ((88 * cb + 183 * cr) >> 8)).clamp(0, 255) as u32;
                let b = (y + ((454 * cb) >> 8)).clamp(0, 255) as u32;
                let pixel = r << 16 | g << 8 | b;
                for sy in 0..scale {
                    let row = (y0 + py * scale + sy) * stride + x0 + px * scale;
                    if let Some(span) = out.get_mut(row..row + scale) {
                        span.fill(pixel);
                    }
                }
            }
        }
    }
}

/// cos(kπ/16), k = 0..8.
const COS: [f32; 9] = [
    1.0,
    0.980_785_3,
    0.923_879_5,
    0.831_469_6,
    0.707_106_77,
    0.555_570_2,
    0.382_683_43,
    0.195_090_32,
    0.0,
];

/// cos(mπ/16) for any m.
fn cos16(m: usize) -> f32 {
    match m % 32 {
        m @ 0..=8 => COS[m],
        m @ 9..=16 => -COS[16 - m],
        m @ 17..=24 => -COS[m - 16],
        m => COS[32 - m],
    }
}

fn basis() -> [[f32; 8]; 8] {
    // basis[u][x] = C(u)/2 · cos((2x + 1)uπ/16)
    core::array::from_fn(|u| {
        core::array::from_fn(|x| {
            let c = if u == 0 {
                core::f32::consts::FRAC_1_SQRT_2
            } else {
                1.0
            };
            c / 2.0 * cos16((2 * x + 1) * u)
        })
    })
}

fn dct(block: &[f32; 64], b: &[[f32; 8]; 8]) -> [f32; 64] {
    let mut tmp = [0f32; 64];
    let mut out = [0f32; 64];
    for y in 0..8 {
        for u in 0..8 {
            tmp[y * 8 + u] = (0..8).map(|x| block[y * 8 + x] * b[u][x]).sum();
        }
    }
    for v in 0..8 {
        for u in 0..8 {
            out[v * 8 + u] = (0..8).map(|y| tmp[y * 8 + u] * b[v][y]).sum();
        }
    }
    out
}

fn idct(coef: &[f32; 64], b: &[[f32; 8]; 8]) -> [f32; 64] {
    let mut tmp = [0f32; 64];
    let mut out = [0f32; 64];
    for v in 0..8 {
        for x in 0..8 {
            tmp[v * 8 + x] = (0..8).map(|u| coef[v * 8 + u] * b[u][x]).sum();
        }
    }
    for y in 0..8 {
        for x in 0..8 {
            out[y * 8 + x] = (0..8).map(|v| tmp[v * 8 + x] * b[v][y]).sum();
        }
    }
    out
}

const ZIGZAG: [usize; 64] = [
    0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7,
    14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39,
    46, 53, 60, 61, 54, 47, 55, 62, 63,
];

fn step(quality: u8, index: usize) -> f32 {
    let (u, v) = (index % 8, index / 8);
    f32::from(quality.max(1)) * (1.0 + (u + v) as f32 * 0.5)
}

fn put_varint(out: &mut Vec<u8>, mut v: u32) {
    while v >= 0x80 {
        out.push(v as u8 | 0x80);
        v >>= 7;
    }
    out.push(v as u8);
}

fn get_varint(data: &[u8], at: &mut usize) -> Option<u32> {
    let mut v = 0u32;
    for shift in (0..35).step_by(7) {
        let b = *data.get(*at)?;
        *at += 1;
        v |= u32::from(b & 0x7f) << shift;
        if b & 0x80 == 0 {
            return Some(v);
        }
    }
    None
}

/// One 8×8 block of a plane: its pixels' place.
#[derive(Clone, Copy)]
struct Block {
    plane: usize,
    x: usize,
    y: usize,
}

fn blocks_of(mb: usize, width: usize) -> [Block; 6] {
    let (mx, my) = ((mb % (width / 16)) * 16, (mb / (width / 16)) * 16);
    [
        Block {
            plane: 0,
            x: mx,
            y: my,
        },
        Block {
            plane: 0,
            x: mx + 8,
            y: my,
        },
        Block {
            plane: 0,
            x: mx,
            y: my + 8,
        },
        Block {
            plane: 0,
            x: mx + 8,
            y: my + 8,
        },
        Block {
            plane: 1,
            x: mx / 2,
            y: my / 2,
        },
        Block {
            plane: 2,
            x: mx / 2,
            y: my / 2,
        },
    ]
}

fn plane(f: &Frame, p: usize) -> (&[u8], usize) {
    match p {
        0 => (&f.y, f.width),
        1 => (&f.cb, f.width / 2),
        _ => (&f.cr, f.width / 2),
    }
}

fn plane_mut(f: &mut Frame, p: usize) -> (&mut [u8], usize) {
    match p {
        0 => (&mut f.y, f.width),
        1 => (&mut f.cb, f.width / 2),
        _ => (&mut f.cr, f.width / 2),
    }
}

/// Codes a block's difference from `reference` (or from grey in a key
/// frame) and writes its reconstruction back into `reference`.
fn code_block(
    source: &Frame,
    reference: &mut Frame,
    b: Block,
    key: bool,
    quality: u8,
    basis: &[[f32; 8]; 8],
    out: &mut Vec<u8>,
) {
    let (src, stride) = plane(source, b.plane);
    let mut residual = [0f32; 64];
    let predictions: [f32; 64] = {
        let (r, _) = plane(reference, b.plane);
        core::array::from_fn(|i| {
            if key {
                128.0
            } else {
                f32::from(r[(b.y + i / 8) * stride + b.x + i % 8])
            }
        })
    };
    for i in 0..64 {
        residual[i] = f32::from(src[(b.y + i / 8) * stride + b.x + i % 8]) - predictions[i];
    }
    let coef = dct(&residual, basis);
    let mut levels = [0i32; 64];
    let mut run = 0u8;
    for (z, &i) in ZIGZAG.iter().enumerate() {
        let level = (coef[i] / step(quality, i)) as i32;
        let level = if coef[i] / step(quality, i) - level as f32 >= 0.5 {
            level + 1
        } else if level as f32 - coef[i] / step(quality, i) >= 0.5 {
            level - 1
        } else {
            level
        };
        levels[i] = level;
        if level == 0 {
            run += 1;
            continue;
        }
        out.push(run);
        put_varint(out, ((level << 1) ^ (level >> 31)) as u32);
        run = 0;
        let _ = z;
    }
    out.push(0xff);
    reconstruct(reference, b, &levels, &predictions, quality, basis);
}

fn reconstruct(
    reference: &mut Frame,
    b: Block,
    levels: &[i32; 64],
    predictions: &[f32; 64],
    quality: u8,
    basis: &[[f32; 8]; 8],
) {
    let coef: [f32; 64] = core::array::from_fn(|i| levels[i] as f32 * step(quality, i));
    let pixels = idct(&coef, basis);
    let (r, stride) = plane_mut(reference, b.plane);
    for i in 0..64 {
        let v = pixels[i] + predictions[i] + 0.5;
        r[(b.y + i / 8) * stride + b.x + i % 8] = v.clamp(0.0, 255.0) as u8;
    }
}

const PACKET: usize = 1100;

pub struct Encoder {
    reference: Frame,
    frame: u16,
    quality: u8,
    basis: [[f32; 8]; 8],
}

impl Encoder {
    /// `quality` is the quantiser step: lower is sharper and larger.
    pub fn new(width: usize, height: usize, quality: u8) -> Encoder {
        Encoder {
            reference: Frame::new(width, height),
            frame: 0,
            quality,
            basis: basis(),
        }
    }

    /// The packets for `source`; a key frame codes every macroblock afresh.
    pub fn encode(&mut self, source: &Frame, key: bool) -> Vec<Vec<u8>> {
        let (w, h) = (source.width, source.height);
        let count = (w / 16) * (h / 16);
        self.frame = self.frame.wrapping_add(1);
        let mut packets = Vec::new();
        let mut body = Vec::new();
        let mut first = 0;
        let mut n = 0u16;
        for mb in 0..count {
            let blocks = blocks_of(mb, w);
            // Unchanged enough: one byte.
            let sad: u32 = (0..4)
                .map(|i| {
                    let b = blocks[i];
                    (0..64)
                        .map(|p| {
                            let at = (b.y + p / 8) * w + b.x + p % 8;
                            u32::from(source.y[at].abs_diff(self.reference.y[at]))
                        })
                        .sum::<u32>()
                })
                .sum();
            if !key && sad < 256 * u32::from(self.quality) / 4 {
                body.push(0);
            } else {
                body.push(1);
                for b in blocks {
                    code_block(
                        source,
                        &mut self.reference,
                        b,
                        key,
                        self.quality,
                        &self.basis,
                        &mut body,
                    );
                }
            }
            n += 1;
            if body.len() >= PACKET || mb + 1 == count {
                let mut p = Vec::with_capacity(7 + body.len());
                p.extend_from_slice(&self.frame.to_le_bytes());
                p.push(u8::from(key));
                p.extend_from_slice(&(first as u16).to_le_bytes());
                p.extend_from_slice(&n.to_le_bytes());
                p.append(&mut body);
                packets.push(p);
                first = mb + 1;
                n = 0;
            }
        }
        packets
    }
}

pub struct Decoder {
    pub frame: Frame,
    quality: u8,
    basis: [[f32; 8]; 8],
}

impl Decoder {
    pub fn new(width: usize, height: usize, quality: u8) -> Decoder {
        Decoder {
            frame: Frame::new(width, height),
            quality,
            basis: basis(),
        }
    }

    /// Applies a packet to the picture; false if it is damaged.
    pub fn decode(&mut self, packet: &[u8]) -> bool {
        if packet.len() < 7 {
            return false;
        }
        let key = packet[2] & 1 != 0;
        let first = usize::from(u16::from_le_bytes([packet[3], packet[4]]));
        let count = usize::from(u16::from_le_bytes([packet[5], packet[6]]));
        let total = (self.frame.width / 16) * (self.frame.height / 16);
        if first + count > total {
            return false;
        }
        let mut at = 7;
        for mb in first..first + count {
            match packet.get(at) {
                Some(0) => at += 1,
                Some(1) => {
                    at += 1;
                    for b in blocks_of(mb, self.frame.width) {
                        let mut levels = [0i32; 64];
                        let mut z = 0;
                        loop {
                            let Some(&run) = packet.get(at) else { return false };
                            at += 1;
                            if run == 0xff {
                                break;
                            }
                            z += usize::from(run);
                            let Some(v) = get_varint(packet, &mut at) else {
                                return false;
                            };
                            let level = (v >> 1) as i32 ^ -((v & 1) as i32);
                            let Some(&i) = ZIGZAG.get(z) else { return false };
                            levels[i] = level;
                            z += 1;
                        }
                        let (r, stride) = plane(&self.frame, b.plane);
                        let predictions: [f32; 64] = core::array::from_fn(|i| {
                            if key {
                                128.0
                            } else {
                                f32::from(r[(b.y + i / 8) * stride + b.x + i % 8])
                            }
                        });
                        reconstruct(
                            &mut self.frame,
                            b,
                            &levels,
                            &predictions,
                            self.quality,
                            &self.basis,
                        );
                    }
                }
                _ => return false,
            }
        }
        true
    }
}