#![allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_precision_loss,
clippy::cast_lossless,
clippy::too_many_arguments,
clippy::many_single_char_names,
clippy::map_unwrap_or
)]
use std::io::{Seek as _, Write};
use std::path::Path;
use rav1e::config::SpeedSettings;
use rav1e::prelude::*;
#[derive(Debug, thiserror::Error)]
pub enum RecordError {
#[error("rav1e: {0}")]
Encode(String),
#[error("frame size {got:?} does not match recording size {want:?}")]
SizeMismatch {
got: (usize, usize),
want: (usize, usize),
},
#[error("bad frame: {0}")]
Frame(&'static str),
#[error("png decode: {0}")]
Png(#[from] image::ImageError),
#[error("io: {0}")]
Io(#[from] std::io::Error),
}
type Result<T> = std::result::Result<T, RecordError>;
pub fn png_dimensions(png: &[u8]) -> Result<(usize, usize)> {
let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
Ok((img.width() as usize, img.height() as usize))
}
pub fn png_to_scaled_rgb(png: &[u8], max_width: u32) -> Result<(usize, usize, Vec<u8>)> {
let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
let img = if img.width() > max_width && max_width > 0 {
let h = u64::from(max_width) * u64::from(img.height()) / u64::from(img.width());
let h = u32::try_from(h).unwrap_or(u32::MAX).max(1);
img.resize_exact(max_width, h, image::imageops::FilterType::Triangle)
} else {
img
};
let rgb = img.to_rgb8();
Ok((rgb.width() as usize, rgb.height() as usize, rgb.into_raw()))
}
const ARROW: [(f64, f64); 7] = [
(0.0, 0.0),
(0.0, 15.6),
(3.6, 12.1),
(5.7, 17.4),
(7.7, 16.6),
(5.6, 11.2),
(10.2, 11.0),
];
const ARROW_H: f64 = 15.6;
fn blend_px(rgb: &mut [u8], w: usize, h: usize, px: i64, py: i64, r: u8, g: u8, b: u8, alpha: f64) {
if px < 0 || py < 0 || px as usize >= w || py as usize >= h || alpha <= 0.0 {
return;
}
let a = alpha.clamp(0.0, 1.0);
let i = (py as usize * w + px as usize) * 3;
rgb[i] = (f64::from(r) * a + f64::from(rgb[i]) * (1.0 - a)) as u8;
rgb[i + 1] = (f64::from(g) * a + f64::from(rgb[i + 1]) * (1.0 - a)) as u8;
rgb[i + 2] = (f64::from(b) * a + f64::from(rgb[i + 2]) * (1.0 - a)) as u8;
}
fn in_poly(px: f64, py: f64, pts: &[(f64, f64)]) -> bool {
let mut inside = false;
let n = pts.len();
let mut j = n - 1;
for i in 0..n {
let (xi, yi) = pts[i];
let (xj, yj) = pts[j];
if (yi > py) != (yj > py) && px < (xj - xi) * (py - yi) / (yj - yi) + xi {
inside = !inside;
}
j = i;
}
inside
}
fn coverage(px: i64, py: i64, pts: &[(f64, f64)]) -> f64 {
let mut hit = 0u32;
for sy in 0..4 {
for sx in 0..4 {
let x = px as f64 + (sx as f64 + 0.5) / 4.0;
let y = py as f64 + (sy as f64 + 0.5) / 4.0;
if in_poly(x, y, pts) {
hit += 1;
}
}
}
f64::from(hit) / 16.0
}
fn draw_click_ring(rgb: &mut [u8], w: usize, h: usize, cx: f64, cy: f64, phase: f32, scale: f64) {
let phase = f64::from(phase);
let base = 13.0 * scale;
let radius = base * (1.7 - phase);
let thickness = 2.2 * scale;
let alpha = phase * 0.6;
let lo = radius - thickness;
let hi = radius + thickness;
let x0 = (cx - hi).floor() as i64;
let x1 = (cx + hi).ceil() as i64;
let y0 = (cy - hi).floor() as i64;
let y1 = (cy + hi).ceil() as i64;
for py in y0..=y1 {
for px in x0..=x1 {
let dx = px as f64 + 0.5 - cx;
let dy = py as f64 + 0.5 - cy;
let d = (dx * dx + dy * dy).sqrt();
if d >= lo && d <= hi {
let edge = 1.0 - ((d - radius).abs() / thickness);
blend_px(rgb, w, h, px, py, 66, 133, 244, alpha * edge.max(0.0));
}
}
}
}
fn draw_arrow(rgb: &mut [u8], w: usize, h: usize, cx: f64, cy: f64, scale: f64) {
let fill: Vec<(f64, f64)> = ARROW
.iter()
.map(|&(x, y)| (cx + x * scale, cy + y * scale))
.collect();
let (mut mx, mut my) = (0.0, 0.0);
for &(x, y) in &fill {
mx += x;
my += y;
}
mx /= fill.len() as f64;
my /= fill.len() as f64;
let grow = 1.05 / (ARROW_H * scale); let border: Vec<(f64, f64)> = fill
.iter()
.map(|&(x, y)| (x + (x - mx) * grow, y + (y - my) * grow))
.collect();
let shadow: Vec<(f64, f64)> = border.iter().map(|&(x, y)| (x + 0.9, y + 1.2)).collect();
let pad = 3.0 * scale + 3.0;
let x0 = (cx - pad).floor() as i64;
let x1 = (cx + 13.0 * scale + pad).ceil() as i64;
let y0 = (cy - pad).floor() as i64;
let y1 = (cy + 20.0 * scale + pad).ceil() as i64;
for py in y0..=y1 {
for px in x0..=x1 {
let cs = coverage(px, py, &shadow);
if cs > 0.0 {
blend_px(rgb, w, h, px, py, 0, 0, 0, cs * 0.22);
}
let cb = coverage(px, py, &border);
if cb > 0.0 {
blend_px(rgb, w, h, px, py, 30, 30, 32, cb);
}
let cf = coverage(px, py, &fill);
if cf > 0.0 {
blend_px(rgb, w, h, px, py, 252, 252, 252, cf);
}
}
}
}
pub fn composite_cursor(rgb: &mut [u8], w: usize, h: usize, x: f64, y: f64, click: f32) {
let scale = (w as f64 / 1440.0 * 1.15).max(1.0);
if click > 0.0 {
draw_click_ring(rgb, w, h, x, y, click, scale);
}
draw_arrow(rgb, w, h, x, y, scale);
}
enum Sink {
File {
writer: std::io::BufWriter<std::fs::File>,
frames: u32,
},
Mem(Vec<Vec<u8>>),
}
fn ivf_header(width: usize, height: usize, fps: u32, frame_count: u32) -> [u8; 32] {
let mut h = [0u8; 32];
h[0..4].copy_from_slice(b"DKIF");
h[6..8].copy_from_slice(&32u16.to_le_bytes()); h[8..12].copy_from_slice(b"AV01");
h[12..14].copy_from_slice(&u16::try_from(width).unwrap_or(0).to_le_bytes());
h[14..16].copy_from_slice(&u16::try_from(height).unwrap_or(0).to_le_bytes());
h[16..20].copy_from_slice(&fps.max(1).to_le_bytes()); h[20..24].copy_from_slice(&1u32.to_le_bytes()); h[24..28].copy_from_slice(&frame_count.to_le_bytes());
h
}
fn write_frame_record(out: &mut impl Write, pkt: &[u8], ts: u64) -> std::io::Result<()> {
out.write_all(&u32::try_from(pkt.len()).unwrap_or(0).to_le_bytes())?;
out.write_all(&ts.to_le_bytes())?;
out.write_all(pkt)
}
pub struct Recorder {
width: usize,
height: usize,
fps: u32,
ctx: Context<u8>,
sink: Sink,
}
impl Recorder {
fn build_ctx(
width: usize,
height: usize,
fps: u32,
speed: u8,
) -> Result<(usize, usize, Context<u8>)> {
let width = width & !1;
let height = height & !1;
if width == 0 || height == 0 {
return Err(RecordError::Frame("zero-sized recording"));
}
let mut speed_settings = SpeedSettings::from_preset(speed.min(10));
speed_settings.rdo_lookahead_frames = 1;
let enc = EncoderConfig {
width,
height,
time_base: Rational::new(1, u64::from(fps.max(1))),
chroma_sampling: ChromaSampling::Cs420,
low_latency: true,
tile_cols: 2,
tile_rows: 2,
quantizer: 70,
speed_settings,
..Default::default()
};
let threads = std::thread::available_parallelism()
.map(|n| n.get().saturating_sub(1).clamp(2, 8))
.unwrap_or(4);
let cfg = Config::new().with_encoder_config(enc).with_threads(threads);
let ctx: Context<u8> = cfg
.new_context()
.map_err(|e| RecordError::Encode(format!("{e:?}")))?;
Ok((width, height, ctx))
}
pub fn new(width: usize, height: usize, fps: u32, speed: u8) -> Result<Self> {
let (width, height, ctx) = Self::build_ctx(width, height, fps, speed)?;
Ok(Self {
width,
height,
fps,
ctx,
sink: Sink::Mem(Vec::new()),
})
}
pub fn create(
path: &std::path::Path,
width: usize,
height: usize,
fps: u32,
speed: u8,
) -> Result<Self> {
let (width, height, ctx) = Self::build_ctx(width, height, fps, speed)?;
let mut f = std::fs::File::create(path)?;
f.write_all(&ivf_header(width, height, fps, 0))?;
Ok(Self {
width,
height,
fps,
ctx,
sink: Sink::File {
writer: std::io::BufWriter::new(f),
frames: 0,
},
})
}
pub fn push_png(&mut self, png: &[u8]) -> Result<()> {
let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
let rgb = img.to_rgb8();
self.push_rgb(rgb.width() as usize, rgb.height() as usize, &rgb)
}
pub fn push_rgb(&mut self, w: usize, h: usize, rgb: &[u8]) -> Result<()> {
if w < self.width || h < self.height {
return Err(RecordError::SizeMismatch {
got: (w, h),
want: (self.width, self.height),
});
}
if rgb.len() < w * h * 3 {
return Err(RecordError::Frame("rgb buffer too small"));
}
let mut frame = self.ctx.new_frame();
let (yp, up, vp) = rgb_to_yuv420(rgb, w, self.width, self.height);
frame.planes[0].copy_from_raw_u8(&yp, self.width, 1);
frame.planes[1].copy_from_raw_u8(&up, self.width / 2, 1);
frame.planes[2].copy_from_raw_u8(&vp, self.width / 2, 1);
self.ctx
.send_frame(frame)
.map_err(|e| RecordError::Encode(format!("send_frame: {e:?}")))?;
self.drain()
}
fn drain(&mut self) -> Result<()> {
loop {
match self.ctx.receive_packet() {
Ok(pkt) => match &mut self.sink {
Sink::File { writer, frames } => {
write_frame_record(writer, &pkt.data, u64::from(*frames))?;
*frames += 1;
}
Sink::Mem(packets) => packets.push(pkt.data),
},
Err(EncoderStatus::Encoded) => {}
Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
Err(e) => return Err(RecordError::Encode(format!("receive_packet: {e:?}"))),
}
}
}
pub fn finish(mut self) -> Result<()> {
self.ctx.flush();
self.drain()?;
match self.sink {
Sink::File { writer, frames } => {
let mut f = writer
.into_inner()
.map_err(std::io::IntoInnerError::into_error)?;
f.seek(std::io::SeekFrom::Start(24))?;
f.write_all(&frames.to_le_bytes())?;
f.flush()?;
Ok(())
}
Sink::Mem(_) => Err(RecordError::Frame(
"finish() on an in-memory recorder; use finish_to_vec",
)),
}
}
pub fn finish_to_vec(mut self) -> Result<Vec<u8>> {
self.ctx.flush();
self.drain()?;
match self.sink {
Sink::Mem(packets) => {
let mut out = Vec::new();
out.extend_from_slice(&ivf_header(
self.width,
self.height,
self.fps,
u32::try_from(packets.len()).unwrap_or(0),
));
for (i, pkt) in packets.iter().enumerate() {
write_frame_record(&mut out, pkt, i as u64)?;
}
Ok(out)
}
Sink::File { .. } => Err(RecordError::Frame(
"finish_to_vec() on a file recorder; use finish",
)),
}
}
}
#[allow(clippy::many_single_char_names)]
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
fn rgb_to_yuv420(rgb: &[u8], src_w: usize, w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
let mut y = vec![0u8; w * h];
let mut u = vec![0u8; (w / 2) * (h / 2)];
let mut v = vec![0u8; (w / 2) * (h / 2)];
let px = |x: usize, row: usize| -> (f32, f32, f32) {
let idx = (row * src_w + x) * 3;
(
f32::from(rgb[idx]),
f32::from(rgb[idx + 1]),
f32::from(rgb[idx + 2]),
)
};
let clamp = |val: f32| -> u8 { val.round().clamp(0.0, 255.0) as u8 };
for row in 0..h {
for x in 0..w {
let (r, g, b) = px(x, row);
y[row * w + x] = clamp(0.257 * r + 0.504 * g + 0.098 * b + 16.0);
}
}
for cy in 0..h / 2 {
for cx in 0..w / 2 {
let mut rs = 0.0;
let mut gs = 0.0;
let mut bs = 0.0;
for dy in 0..2 {
for dx in 0..2 {
let (r, g, b) = px(cx * 2 + dx, cy * 2 + dy);
rs += r;
gs += g;
bs += b;
}
}
let (r, g, b) = (rs / 4.0, gs / 4.0, bs / 4.0);
u[cy * (w / 2) + cx] = clamp(-0.148 * r - 0.291 * g + 0.439 * b + 128.0);
v[cy * (w / 2) + cx] = clamp(0.439 * r - 0.368 * g - 0.071 * b + 128.0);
}
}
(y, u, v)
}
pub struct H264Recorder {
enc: openh264::encoder::Encoder,
width: usize,
height: usize,
frame_ms: u32,
fps: f64,
path: std::path::PathBuf,
muxer: Option<muxide::api::Muxer<std::io::BufWriter<std::fs::File>>>,
}
impl H264Recorder {
pub fn create(path: &Path, width: usize, height: usize, fps: u32) -> Result<Self> {
use openh264::encoder::{BitRate, EncoderConfig, FrameRate, UsageType};
let width = width & !1;
let height = height & !1;
if width == 0 || height == 0 {
return Err(RecordError::Frame("zero-sized recording"));
}
let fps = fps.max(1);
#[allow(clippy::cast_possible_truncation)]
let bitrate = ((width as u64 * height as u64 * u64::from(fps)) / 5)
.clamp(1_000_000, 12_000_000) as u32;
let config = EncoderConfig::new()
.usage_type(UsageType::ScreenContentRealTime)
.max_frame_rate(FrameRate::from_hz(fps as f32))
.bitrate(BitRate::from_bps(bitrate));
let enc = openh264::encoder::Encoder::with_api_config(
openh264::OpenH264API::from_source(),
config,
)
.map_err(|e| RecordError::Encode(format!("openh264 init: {e:?}")))?;
Ok(Self {
enc,
width,
height,
frame_ms: 1000 / fps,
fps: f64::from(fps),
path: path.to_path_buf(),
muxer: None,
})
}
pub fn push_rgb(&mut self, w: usize, h: usize, rgb: &[u8]) -> Result<()> {
use openh264::formats::{RgbSliceU8, YUVBuffer};
if w < self.width || h < self.height {
return Err(RecordError::SizeMismatch {
got: (w, h),
want: (self.width, self.height),
});
}
if rgb.len() < w * h * 3 {
return Err(RecordError::Frame("rgb buffer too small"));
}
let cropped;
let src: &[u8] = if w == self.width && h == self.height {
rgb
} else {
let mut out = Vec::with_capacity(self.width * self.height * 3);
for row in 0..self.height {
let start = row * w * 3;
out.extend_from_slice(&rgb[start..start + self.width * 3]);
}
cropped = out;
&cropped
};
let yuv = YUVBuffer::from_rgb8_source(RgbSliceU8::new(src, (self.width, self.height)));
let bitstream = self
.enc
.encode(&yuv)
.map_err(|e| RecordError::Encode(format!("openh264 encode: {e:?}")))?;
let annexb = bitstream.to_vec();
if annexb.is_empty() {
return Ok(());
}
if self.muxer.is_none() {
let cfg = muxide::codec::h264::extract_avc_config(&annexb)
.ok_or_else(|| RecordError::Encode("no SPS/PPS in first frame".into()))?;
let file = std::io::BufWriter::new(std::fs::File::create(&self.path)?);
let muxer = muxide::api::MuxerBuilder::new(file)
.video(
muxide::api::VideoCodec::H264,
self.width as u32,
self.height as u32,
self.fps,
)
.with_sps(cfg.sps)
.with_pps(cfg.pps)
.with_fast_start(true)
.build()
.map_err(|e| RecordError::Encode(format!("mp4 mux init: {e}")))?;
self.muxer = Some(muxer);
}
self.muxer
.as_mut()
.expect("muxer set above")
.encode_video(&annexb, self.frame_ms)
.map_err(|e| RecordError::Encode(format!("mp4 write: {e}")))?;
Ok(())
}
pub fn finish(mut self) -> Result<()> {
match self.muxer.take() {
Some(mut m) => m
.finish_in_place()
.map_err(|e| RecordError::Encode(format!("mp4 finish: {e}"))),
None => Err(RecordError::Frame("no frames encoded")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn solid_rgb(w: usize, h: usize, c: [u8; 3]) -> Vec<u8> {
let mut v = Vec::with_capacity(w * h * 3);
for _ in 0..w * h {
v.extend_from_slice(&c);
}
v
}
#[test]
fn encodes_frames_to_a_valid_ivf() {
let (w, h) = (64, 48);
let mut rec = Recorder::new(w, h, 5, 9).expect("recorder");
for c in [[200, 30, 30], [30, 200, 30], [30, 30, 200], [220, 220, 30]] {
rec.push_rgb(w, h, &solid_rgb(w, h, c)).expect("push");
}
let ivf = rec.finish_to_vec().expect("finish");
assert_eq!(&ivf[0..4], b"DKIF", "IVF signature");
assert_eq!(&ivf[8..12], b"AV01", "codec fourcc");
let frame_count = u32::from_le_bytes(ivf[24..28].try_into().unwrap());
assert!(
frame_count >= 1,
"at least one encoded frame, got {frame_count}"
);
assert!(
ivf.len() > 32 + 12,
"encoded body present, got {} bytes",
ivf.len()
);
}
#[test]
fn odd_dimensions_are_rounded_even() {
let rec = Recorder::new(65, 49, 5, 9).expect("recorder");
assert_eq!((rec.width, rec.height), (64, 48));
}
}