guth-media 0.1.0

Optional, out-of-process inline video playback plugin for Guth.
Documentation
//! Small, versioned playback wire contract. The optional `player` binary owns VLC;
//! consumers with default features disabled do not compile or load a decoder.
#![forbid(unsafe_code)]

use serde::{Deserialize, Serialize};
use std::io::{self, BufRead, Read, Write};

pub const PLUGIN_ID: &str = "01a0bc38-c985-7a91-b5d4-c5752af2842c";
pub const PLUGIN_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const CAPABILITY: &str = "inline-video-v1";
pub const PROTOCOL_ARGUMENT: &str = "--guth-media-protocol";
pub const PROTOCOL_VERSION: &str = "1";
pub const MAX_VIDEO_PIXELS: usize = 16_777_216;
pub const MAX_TEXTURE_SIDE: usize = 8192;
const STATUS_LIMIT: usize = 4096;
const COMMAND_LIMIT: usize = 256;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PlaybackPhase {
    #[default]
    Idle,
    Loading,
    Playing,
    Paused,
    Ended,
    Failed,
}

#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PlaybackStatus {
    pub phase: PlaybackPhase,
    pub position_ms: u64,
    pub duration_ms: u64,
    pub seekable: bool,
    pub error: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum PlayerCommand {
    Pause(bool),
    Volume(u8),
    Seek(u64),
}

pub struct VideoFrame {
    pub size: [usize; 2],
    pub rgba: Vec<u8>,
}

pub enum PlayerEvent {
    Status(PlaybackStatus),
    Frame(VideoFrame),
}

fn invalid(message: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message)
}

fn frame_bytes(width: usize, height: usize, max_side: usize) -> io::Result<usize> {
    let side = max_side.min(MAX_TEXTURE_SIDE);
    if width == 0 || height == 0 || width > side || height > side {
        return Err(invalid("invalid media frame dimensions"));
    }
    width
        .checked_mul(height)
        .filter(|pixels| *pixels <= MAX_VIDEO_PIXELS)
        .and_then(|pixels| pixels.checked_mul(4))
        .ok_or_else(|| invalid("media frame exceeds pixel limit"))
}

/// The 5-byte header is type (1=status, 2=RGBA) plus little-endian payload length.
/// Frame payloads begin with little-endian width and height. Bounds are checked
/// before allocation, including the renderer's negotiated texture-size limit.
pub fn read_event(reader: &mut impl Read, max_side: usize) -> io::Result<PlayerEvent> {
    let mut header = [0; 5];
    reader.read_exact(&mut header)?;
    let length = u32::from_le_bytes(header[1..].try_into().unwrap()) as usize;
    match header[0] {
        1 if length <= STATUS_LIMIT => {
            let mut data = vec![0; length];
            reader.read_exact(&mut data)?;
            let status: PlaybackStatus = serde_json::from_slice(&data).map_err(io::Error::other)?;
            if status
                .error
                .as_ref()
                .is_some_and(|error| error.len() > 2400)
            {
                return Err(invalid("media error exceeds limit"));
            }
            Ok(PlayerEvent::Status(status))
        }
        2 if (8..=MAX_VIDEO_PIXELS * 4 + 8).contains(&length) => {
            let mut dimensions = [0; 8];
            reader.read_exact(&mut dimensions)?;
            let width = u32::from_le_bytes(dimensions[..4].try_into().unwrap()) as usize;
            let height = u32::from_le_bytes(dimensions[4..].try_into().unwrap()) as usize;
            let bytes = frame_bytes(width, height, max_side)?;
            if length != bytes + 8 {
                return Err(invalid("media frame length does not match dimensions"));
            }
            let mut rgba = Vec::new();
            rgba.try_reserve_exact(bytes).map_err(io::Error::other)?;
            rgba.resize(bytes, 0);
            reader.read_exact(&mut rgba)?;
            Ok(PlayerEvent::Frame(VideoFrame {
                size: [width, height],
                rgba,
            }))
        }
        _ => Err(invalid("unknown or oversized media packet")),
    }
}

fn write_header(writer: &mut impl Write, kind: u8, length: usize) -> io::Result<()> {
    writer.write_all(&[kind])?;
    writer.write_all(&(length as u32).to_le_bytes())
}

pub fn write_status(writer: &mut impl Write, status: &PlaybackStatus) -> io::Result<()> {
    let bytes = serde_json::to_vec(status).map_err(io::Error::other)?;
    if bytes.len() > STATUS_LIMIT {
        return Err(invalid("media status exceeds limit"));
    }
    write_header(writer, 1, bytes.len())?;
    writer.write_all(&bytes)
}

pub fn write_frame(writer: &mut impl Write, frame: &VideoFrame) -> io::Result<()> {
    let [width, height] = frame.size;
    let bytes = frame_bytes(width, height, MAX_TEXTURE_SIDE)?;
    if frame.rgba.len() != bytes {
        return Err(invalid("media frame has invalid pixel data"));
    }
    write_header(writer, 2, bytes + 8)?;
    writer.write_all(&(width as u32).to_le_bytes())?;
    writer.write_all(&(height as u32).to_le_bytes())?;
    writer.write_all(&frame.rgba)
}

pub fn write_command(writer: &mut impl Write, command: PlayerCommand) -> io::Result<()> {
    let mut bytes = serde_json::to_vec(&command).map_err(io::Error::other)?;
    bytes.push(b'\n');
    writer.write_all(&bytes)
}

pub fn read_command(reader: &mut impl BufRead) -> io::Result<Option<PlayerCommand>> {
    let mut bytes = Vec::new();
    if reader
        .take(COMMAND_LIMIT as u64 + 1)
        .read_until(b'\n', &mut bytes)?
        == 0
    {
        return Ok(None);
    }
    if bytes.len() > COMMAND_LIMIT || bytes.last() != Some(&b'\n') {
        return Err(invalid("unterminated or oversized media command"));
    }
    serde_json::from_slice(&bytes)
        .map(Some)
        .map_err(io::Error::other)
}

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

    #[test]
    fn wire_round_trips_frames_status_and_commands() {
        let frame = VideoFrame {
            size: [2, 1],
            rgba: vec![17; 8],
        };
        let mut bytes = Vec::new();
        write_frame(&mut bytes, &frame).unwrap();
        let PlayerEvent::Frame(read) = read_event(&mut bytes.as_slice(), 8192).unwrap() else {
            panic!()
        };
        assert_eq!(read.size, frame.size);
        assert_eq!(read.rgba, frame.rgba);
        bytes.clear();
        let status = PlaybackStatus {
            phase: PlaybackPhase::Paused,
            position_ms: 900,
            ..Default::default()
        };
        write_status(&mut bytes, &status).unwrap();
        let PlayerEvent::Status(read) = read_event(&mut bytes.as_slice(), 8192).unwrap() else {
            panic!()
        };
        assert_eq!(read, status);
        for command in [
            PlayerCommand::Pause(true),
            PlayerCommand::Volume(100),
            PlayerCommand::Seek(u64::MAX),
        ] {
            bytes.clear();
            write_command(&mut bytes, command).unwrap();
            assert_eq!(read_command(&mut bytes.as_slice()).unwrap(), Some(command));
        }
    }

    #[test]
    fn wire_rejects_invalid_and_oversized_data_before_reading_payload() {
        for header in [
            [9, 0, 0, 0, 0],
            [1, 255, 255, 255, 255],
            [2, 255, 255, 255, 255],
        ] {
            assert!(read_event(&mut header.as_slice(), 8192).is_err());
        }
        let mut bytes = Vec::new();
        write_frame(
            &mut bytes,
            &VideoFrame {
                size: [2, 2],
                rgba: vec![0; 16],
            },
        )
        .unwrap();
        assert!(read_event(&mut bytes.as_slice(), 1).is_err());
        bytes[5..9].copy_from_slice(&u32::MAX.to_le_bytes());
        assert!(read_event(&mut bytes.as_slice(), 8192).is_err());
        assert!(read_command(&mut vec![b'x'; 257].as_slice()).is_err());
        assert!(read_command(&mut b"{\"pause\":true}".as_slice()).is_err());
        assert!(read_command(&mut b"{\"run\":\"anything\"}\n".as_slice()).is_err());
        assert_eq!(read_command(&mut b"".as_slice()).unwrap(), None);
    }
}