Skip to main content

vs_record/
lib.rs

1//! Session video recording for vibesurfer.
2//!
3//! Turns a sequence of RGB frames (captured from a page) into a real
4//! video. Two encoders, both cross-platform:
5//!
6//! - [`H264Recorder`]: real-time H.264 via openh264 (built from vendored
7//!   source), muxed to MP4 with muxide (pure Rust). Fast enough to keep
8//!   up with capture and produces a file that plays everywhere with no
9//!   remux. This is the default.
10//! - [`Recorder`]: pure-Rust AV1 via rav1e in an IVF container. No build
11//!   tools, but far too slow for real time at screen resolution. Kept as
12//!   a portable fallback.
13//!
14//! Both are fed decoded RGB frames (see [`Recorder::push_png`] for the
15//! capture path, which decodes vibesurfer's PNG captures). All frames in
16//! one recording must share dimensions; the first fixes them.
17
18// This crate is pixel and signal math: cursor rasterization, RGB<->YUV,
19// bitrate/dimension arithmetic. The numeric casts are deliberate and
20// range-checked by construction, so the pedantic cast lints are noise
21// here.
22#![allow(
23    clippy::cast_possible_truncation,
24    clippy::cast_sign_loss,
25    clippy::cast_precision_loss,
26    clippy::cast_lossless,
27    clippy::too_many_arguments,
28    clippy::many_single_char_names,
29    clippy::map_unwrap_or
30)]
31
32use std::io::{Seek as _, Write};
33use std::path::Path;
34
35use rav1e::config::SpeedSettings;
36use rav1e::prelude::*;
37
38#[derive(Debug, thiserror::Error)]
39pub enum RecordError {
40    #[error("rav1e: {0}")]
41    Encode(String),
42    #[error("frame size {got:?} does not match recording size {want:?}")]
43    SizeMismatch {
44        got: (usize, usize),
45        want: (usize, usize),
46    },
47    #[error("bad frame: {0}")]
48    Frame(&'static str),
49    #[error("png decode: {0}")]
50    Png(#[from] image::ImageError),
51    #[error("io: {0}")]
52    Io(#[from] std::io::Error),
53}
54
55type Result<T> = std::result::Result<T, RecordError>;
56
57/// Decode just the dimensions of a PNG, so a caller can size a
58/// [`Recorder`] from the first captured frame.
59pub fn png_dimensions(png: &[u8]) -> Result<(usize, usize)> {
60    let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
61    Ok((img.width() as usize, img.height() as usize))
62}
63
64/// Decode a PNG and downscale it so its width is at most `max_width`
65/// (aspect preserved), returning `(width, height, rgb)`. Screen captures
66/// arrive at the device backing scale (retina 2x), which is needlessly
67/// large for a recording: it slows capture and multiplies the encoder's
68/// per-frame memory. Downscaling to a sane width keeps recordings small
69/// and light. A frame already within `max_width` is returned unscaled.
70pub fn png_to_scaled_rgb(png: &[u8], max_width: u32) -> Result<(usize, usize, Vec<u8>)> {
71    let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
72    let img = if img.width() > max_width && max_width > 0 {
73        let h = u64::from(max_width) * u64::from(img.height()) / u64::from(img.width());
74        let h = u32::try_from(h).unwrap_or(u32::MAX).max(1);
75        img.resize_exact(max_width, h, image::imageops::FilterType::Triangle)
76    } else {
77        img
78    };
79    let rgb = img.to_rgb8();
80    Ok((rgb.width() as usize, rgb.height() as usize, rgb.into_raw()))
81}
82
83/// macOS-style arrow pointer as a polygon, tip at the origin, in a
84/// nominal ~16 px tall unit space (scaled per frame). A headless snapshot
85/// never contains the OS pointer, so the recorder draws it from the
86/// position the engine reported for each frame — anti-aliased with a fill,
87/// a dark border, and a soft drop shadow so it reads like a real cursor
88/// rather than a blocky sprite.
89const ARROW: [(f64, f64); 7] = [
90    (0.0, 0.0),
91    (0.0, 15.6),
92    (3.6, 12.1),
93    (5.7, 17.4),
94    (7.7, 16.6),
95    (5.6, 11.2),
96    (10.2, 11.0),
97];
98/// Nominal arrow height in unit space (for border-width scaling).
99const ARROW_H: f64 = 15.6;
100
101/// Blend `(r,g,b)` at `alpha` (0..1) into the RGB frame at `(px,py)`.
102fn blend_px(rgb: &mut [u8], w: usize, h: usize, px: i64, py: i64, r: u8, g: u8, b: u8, alpha: f64) {
103    if px < 0 || py < 0 || px as usize >= w || py as usize >= h || alpha <= 0.0 {
104        return;
105    }
106    let a = alpha.clamp(0.0, 1.0);
107    let i = (py as usize * w + px as usize) * 3;
108    rgb[i] = (f64::from(r) * a + f64::from(rgb[i]) * (1.0 - a)) as u8;
109    rgb[i + 1] = (f64::from(g) * a + f64::from(rgb[i + 1]) * (1.0 - a)) as u8;
110    rgb[i + 2] = (f64::from(b) * a + f64::from(rgb[i + 2]) * (1.0 - a)) as u8;
111}
112
113/// Even-odd point-in-polygon test.
114fn in_poly(px: f64, py: f64, pts: &[(f64, f64)]) -> bool {
115    let mut inside = false;
116    let n = pts.len();
117    let mut j = n - 1;
118    for i in 0..n {
119        let (xi, yi) = pts[i];
120        let (xj, yj) = pts[j];
121        if (yi > py) != (yj > py) && px < (xj - xi) * (py - yi) / (yj - yi) + xi {
122            inside = !inside;
123        }
124        j = i;
125    }
126    inside
127}
128
129/// Coverage of pixel `(px,py)` by `pts`, via a 4x4 sub-sample grid, for
130/// anti-aliased edges.
131fn coverage(px: i64, py: i64, pts: &[(f64, f64)]) -> f64 {
132    let mut hit = 0u32;
133    for sy in 0..4 {
134        for sx in 0..4 {
135            let x = px as f64 + (sx as f64 + 0.5) / 4.0;
136            let y = py as f64 + (sy as f64 + 0.5) / 4.0;
137            if in_poly(x, y, pts) {
138                hit += 1;
139            }
140        }
141    }
142    f64::from(hit) / 16.0
143}
144
145/// Draw an expanding click ripple centred at `(cx,cy)`. `phase` runs
146/// `1.0` (just pressed, tight bright ring) down to `0.0` (gone).
147fn draw_click_ring(rgb: &mut [u8], w: usize, h: usize, cx: f64, cy: f64, phase: f32, scale: f64) {
148    let phase = f64::from(phase);
149    let base = 13.0 * scale;
150    let radius = base * (1.7 - phase);
151    let thickness = 2.2 * scale;
152    let alpha = phase * 0.6;
153    let lo = radius - thickness;
154    let hi = radius + thickness;
155    let x0 = (cx - hi).floor() as i64;
156    let x1 = (cx + hi).ceil() as i64;
157    let y0 = (cy - hi).floor() as i64;
158    let y1 = (cy + hi).ceil() as i64;
159    for py in y0..=y1 {
160        for px in x0..=x1 {
161            let dx = px as f64 + 0.5 - cx;
162            let dy = py as f64 + 0.5 - cy;
163            let d = (dx * dx + dy * dy).sqrt();
164            if d >= lo && d <= hi {
165                let edge = 1.0 - ((d - radius).abs() / thickness);
166                blend_px(rgb, w, h, px, py, 66, 133, 244, alpha * edge.max(0.0));
167            }
168        }
169    }
170}
171
172/// Anti-aliased arrow pointer with tip at `(cx,cy)`, scaled by `scale`.
173/// Draws a soft shadow, a dark border, then the white fill.
174fn draw_arrow(rgb: &mut [u8], w: usize, h: usize, cx: f64, cy: f64, scale: f64) {
175    // Fill polygon in frame space.
176    let fill: Vec<(f64, f64)> = ARROW
177        .iter()
178        .map(|&(x, y)| (cx + x * scale, cy + y * scale))
179        .collect();
180    // Centroid, to grow a slightly larger border polygon around the fill.
181    let (mut mx, mut my) = (0.0, 0.0);
182    for &(x, y) in &fill {
183        mx += x;
184        my += y;
185    }
186    mx /= fill.len() as f64;
187    my /= fill.len() as f64;
188    let grow = 1.05 / (ARROW_H * scale); // ~1 px of border
189    let border: Vec<(f64, f64)> = fill
190        .iter()
191        .map(|&(x, y)| (x + (x - mx) * grow, y + (y - my) * grow))
192        .collect();
193    let shadow: Vec<(f64, f64)> = border.iter().map(|&(x, y)| (x + 0.9, y + 1.2)).collect();
194
195    let pad = 3.0 * scale + 3.0;
196    let x0 = (cx - pad).floor() as i64;
197    let x1 = (cx + 13.0 * scale + pad).ceil() as i64;
198    let y0 = (cy - pad).floor() as i64;
199    let y1 = (cy + 20.0 * scale + pad).ceil() as i64;
200    for py in y0..=y1 {
201        for px in x0..=x1 {
202            let cs = coverage(px, py, &shadow);
203            if cs > 0.0 {
204                blend_px(rgb, w, h, px, py, 0, 0, 0, cs * 0.22);
205            }
206            let cb = coverage(px, py, &border);
207            if cb > 0.0 {
208                blend_px(rgb, w, h, px, py, 30, 30, 32, cb);
209            }
210            let cf = coverage(px, py, &fill);
211            if cf > 0.0 {
212                blend_px(rgb, w, h, px, py, 252, 252, 252, cf);
213            }
214        }
215    }
216}
217
218/// Composite the cursor (and any click ripple) onto an RGB frame at
219/// `(x,y)` frame pixels. The pointer scale tracks the frame width so it
220/// looks the same size across recording resolutions.
221pub fn composite_cursor(rgb: &mut [u8], w: usize, h: usize, x: f64, y: f64, click: f32) {
222    // ~20 px tall at 1440 wide, matching a real macOS pointer.
223    let scale = (w as f64 / 1440.0 * 1.15).max(1.0);
224    if click > 0.0 {
225        draw_click_ring(rgb, w, h, x, y, click, scale);
226    }
227    draw_arrow(rgb, w, h, x, y, scale);
228}
229
230/// Where encoded frames go. A file-backed recorder streams each frame
231/// straight to disk so memory stays at ~one frame regardless of how long
232/// the recording runs; the in-memory sink is only for tests.
233enum Sink {
234    File {
235        writer: std::io::BufWriter<std::fs::File>,
236        frames: u32,
237    },
238    Mem(Vec<Vec<u8>>),
239}
240
241/// The 32-byte IVF file header. `frame_count` is patched in at finish
242/// for the streaming path (written as 0 up front, seeked back later).
243fn ivf_header(width: usize, height: usize, fps: u32, frame_count: u32) -> [u8; 32] {
244    let mut h = [0u8; 32];
245    h[0..4].copy_from_slice(b"DKIF");
246    h[6..8].copy_from_slice(&32u16.to_le_bytes()); // header length (version 0)
247    h[8..12].copy_from_slice(b"AV01");
248    h[12..14].copy_from_slice(&u16::try_from(width).unwrap_or(0).to_le_bytes());
249    h[14..16].copy_from_slice(&u16::try_from(height).unwrap_or(0).to_le_bytes());
250    h[16..20].copy_from_slice(&fps.max(1).to_le_bytes()); // timebase den
251    h[20..24].copy_from_slice(&1u32.to_le_bytes()); // timebase num
252    h[24..28].copy_from_slice(&frame_count.to_le_bytes());
253    h
254}
255
256/// One IVF frame record: 12-byte header (size u32, timestamp u64) + data.
257fn write_frame_record(out: &mut impl Write, pkt: &[u8], ts: u64) -> std::io::Result<()> {
258    out.write_all(&u32::try_from(pkt.len()).unwrap_or(0).to_le_bytes())?;
259    out.write_all(&ts.to_le_bytes())?;
260    out.write_all(pkt)
261}
262
263/// Encodes RGB frames to AV1 and writes an IVF file.
264pub struct Recorder {
265    width: usize,
266    height: usize,
267    fps: u32,
268    ctx: Context<u8>,
269    sink: Sink,
270}
271
272impl Recorder {
273    fn build_ctx(
274        width: usize,
275        height: usize,
276        fps: u32,
277        speed: u8,
278    ) -> Result<(usize, usize, Context<u8>)> {
279        let width = width & !1;
280        let height = height & !1;
281        if width == 0 || height == 0 {
282            return Err(RecordError::Frame("zero-sized recording"));
283        }
284        // Low-latency, no lookahead: encode and emit each frame as it
285        // arrives. Without this, rav1e buffers its whole reorder /
286        // lookahead window of *uncompressed* frames — tens of MB each at
287        // screen resolution — which grew unbounded during a live
288        // recording (~90 MB/s). Screen capture doesn't benefit from the
289        // lookahead anyway.
290        let mut speed_settings = SpeedSettings::from_preset(speed.min(10));
291        speed_settings.rdo_lookahead_frames = 1;
292        // Tile the frame so rav1e can encode it across threads. A screen
293        // recording at 1440p is far too heavy for the single-threaded
294        // encoder to keep up with real-time capture (~1 s/frame); tiling
295        // into a 2x2 grid and giving it real threads brings that down by
296        // roughly the tile count. Tiles cost a little quality and memory,
297        // both of which a headless screen recording can spare.
298        let enc = EncoderConfig {
299            width,
300            height,
301            time_base: Rational::new(1, u64::from(fps.max(1))),
302            chroma_sampling: ChromaSampling::Cs420,
303            low_latency: true,
304            tile_cols: 2,
305            tile_rows: 2,
306            // Lower base quantizer = higher quality. A screen recording of
307            // text needs sharp edges; the default (100) smears them. The
308            // encode is offline (after `stop`), so we can afford it.
309            quantizer: 70,
310            speed_settings,
311            ..Default::default()
312        };
313        let threads = std::thread::available_parallelism()
314            .map(|n| n.get().saturating_sub(1).clamp(2, 8))
315            .unwrap_or(4);
316        let cfg = Config::new().with_encoder_config(enc).with_threads(threads);
317        let ctx: Context<u8> = cfg
318            .new_context()
319            .map_err(|e| RecordError::Encode(format!("{e:?}")))?;
320        Ok((width, height, ctx))
321    }
322
323    /// Start an in-memory recording at `width` x `height` (both rounded
324    /// down to even, required by 4:2:0 chroma) and `fps`. `speed` is
325    /// 0..=10; higher is faster and lower quality. For tests — real
326    /// recordings should use [`Recorder::create`], which streams to disk.
327    pub fn new(width: usize, height: usize, fps: u32, speed: u8) -> Result<Self> {
328        let (width, height, ctx) = Self::build_ctx(width, height, fps, speed)?;
329        Ok(Self {
330            width,
331            height,
332            fps,
333            ctx,
334            sink: Sink::Mem(Vec::new()),
335        })
336    }
337
338    /// Start a recording that streams straight to the IVF file at `path`.
339    /// Each encoded frame is written and dropped, so memory stays at
340    /// about one frame no matter how long the recording runs. Finalize
341    /// with [`Recorder::finish`].
342    pub fn create(
343        path: &std::path::Path,
344        width: usize,
345        height: usize,
346        fps: u32,
347        speed: u8,
348    ) -> Result<Self> {
349        let (width, height, ctx) = Self::build_ctx(width, height, fps, speed)?;
350        let mut f = std::fs::File::create(path)?;
351        f.write_all(&ivf_header(width, height, fps, 0))?;
352        Ok(Self {
353            width,
354            height,
355            fps,
356            ctx,
357            sink: Sink::File {
358                writer: std::io::BufWriter::new(f),
359                frames: 0,
360            },
361        })
362    }
363
364    /// Decode a vibesurfer PNG capture and push it as a frame.
365    pub fn push_png(&mut self, png: &[u8]) -> Result<()> {
366        let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
367        let rgb = img.to_rgb8();
368        self.push_rgb(rgb.width() as usize, rgb.height() as usize, &rgb)
369    }
370
371    /// Push one RGB frame (`w*h*3` bytes, row-major, no padding).
372    pub fn push_rgb(&mut self, w: usize, h: usize, rgb: &[u8]) -> Result<()> {
373        // Crop to the recording size if the source is a couple pixels
374        // larger from the even-rounding; reject a real mismatch.
375        if w < self.width || h < self.height {
376            return Err(RecordError::SizeMismatch {
377                got: (w, h),
378                want: (self.width, self.height),
379            });
380        }
381        if rgb.len() < w * h * 3 {
382            return Err(RecordError::Frame("rgb buffer too small"));
383        }
384        let mut frame = self.ctx.new_frame();
385        let (yp, up, vp) = rgb_to_yuv420(rgb, w, self.width, self.height);
386        frame.planes[0].copy_from_raw_u8(&yp, self.width, 1);
387        frame.planes[1].copy_from_raw_u8(&up, self.width / 2, 1);
388        frame.planes[2].copy_from_raw_u8(&vp, self.width / 2, 1);
389
390        self.ctx
391            .send_frame(frame)
392            .map_err(|e| RecordError::Encode(format!("send_frame: {e:?}")))?;
393        self.drain()
394    }
395
396    /// Pull whatever packets are ready and route them to the sink,
397    /// stopping when the encoder wants more input or reports it is
398    /// drained. Safe to call after each send and after flush.
399    fn drain(&mut self) -> Result<()> {
400        loop {
401            match self.ctx.receive_packet() {
402                Ok(pkt) => match &mut self.sink {
403                    Sink::File { writer, frames } => {
404                        write_frame_record(writer, &pkt.data, u64::from(*frames))?;
405                        *frames += 1;
406                    }
407                    Sink::Mem(packets) => packets.push(pkt.data),
408                },
409                Err(EncoderStatus::Encoded) => {}
410                Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
411                Err(e) => return Err(RecordError::Encode(format!("receive_packet: {e:?}"))),
412            }
413        }
414    }
415
416    /// Flush the encoder and finalize the streamed IVF file: patch the
417    /// real frame count into the header. Use with [`Recorder::create`].
418    pub fn finish(mut self) -> Result<()> {
419        self.ctx.flush();
420        self.drain()?;
421        match self.sink {
422            Sink::File { writer, frames } => {
423                let mut f = writer
424                    .into_inner()
425                    .map_err(std::io::IntoInnerError::into_error)?;
426                f.seek(std::io::SeekFrom::Start(24))?;
427                f.write_all(&frames.to_le_bytes())?;
428                f.flush()?;
429                Ok(())
430            }
431            Sink::Mem(_) => Err(RecordError::Frame(
432                "finish() on an in-memory recorder; use finish_to_vec",
433            )),
434        }
435    }
436
437    /// Flush and return the IVF bytes (in-memory recorders / tests).
438    pub fn finish_to_vec(mut self) -> Result<Vec<u8>> {
439        self.ctx.flush();
440        self.drain()?;
441        match self.sink {
442            Sink::Mem(packets) => {
443                let mut out = Vec::new();
444                out.extend_from_slice(&ivf_header(
445                    self.width,
446                    self.height,
447                    self.fps,
448                    u32::try_from(packets.len()).unwrap_or(0),
449                ));
450                for (i, pkt) in packets.iter().enumerate() {
451                    write_frame_record(&mut out, pkt, i as u64)?;
452                }
453                Ok(out)
454            }
455            Sink::File { .. } => Err(RecordError::Frame(
456                "finish_to_vec() on a file recorder; use finish",
457            )),
458        }
459    }
460}
461
462/// Convert row-major RGB (`src_stride` pixels wide) to planar YUV420,
463/// cropping to `w` x `h`. BT.601 limited range. Returns (Y, U, V).
464#[allow(clippy::many_single_char_names)]
465// The clamp guarantees the 0..=255 range, so the u8 cast cannot
466// truncate or lose sign; clippy cannot see the guarantee.
467#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
468fn rgb_to_yuv420(rgb: &[u8], src_w: usize, w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
469    let mut y = vec![0u8; w * h];
470    let mut u = vec![0u8; (w / 2) * (h / 2)];
471    let mut v = vec![0u8; (w / 2) * (h / 2)];
472    let px = |x: usize, row: usize| -> (f32, f32, f32) {
473        let idx = (row * src_w + x) * 3;
474        (
475            f32::from(rgb[idx]),
476            f32::from(rgb[idx + 1]),
477            f32::from(rgb[idx + 2]),
478        )
479    };
480    let clamp = |val: f32| -> u8 { val.round().clamp(0.0, 255.0) as u8 };
481    for row in 0..h {
482        for x in 0..w {
483            let (r, g, b) = px(x, row);
484            y[row * w + x] = clamp(0.257 * r + 0.504 * g + 0.098 * b + 16.0);
485        }
486    }
487    for cy in 0..h / 2 {
488        for cx in 0..w / 2 {
489            // Average the 2x2 block for chroma.
490            let mut rs = 0.0;
491            let mut gs = 0.0;
492            let mut bs = 0.0;
493            for dy in 0..2 {
494                for dx in 0..2 {
495                    let (r, g, b) = px(cx * 2 + dx, cy * 2 + dy);
496                    rs += r;
497                    gs += g;
498                    bs += b;
499                }
500            }
501            let (r, g, b) = (rs / 4.0, gs / 4.0, bs / 4.0);
502            u[cy * (w / 2) + cx] = clamp(-0.148 * r - 0.291 * g + 0.439 * b + 128.0);
503            v[cy * (w / 2) + cx] = clamp(0.439 * r - 0.368 * g - 0.071 * b + 128.0);
504        }
505    }
506    (y, u, v)
507}
508
509/// Real-time H.264 recorder: encodes RGB frames with openh264 and muxes
510/// them into an MP4 with muxide. Unlike [`Recorder`] (rav1e/AV1, far too
511/// slow for real time), this keeps up with capture and writes a file
512/// that plays natively everywhere without a remux. The MP4 is finalized
513/// on [`finish`](Self::finish); the muxer is built lazily on the first
514/// frame because it needs the SPS/PPS that the encoder emits with it.
515pub struct H264Recorder {
516    enc: openh264::encoder::Encoder,
517    width: usize,
518    height: usize,
519    /// Milliseconds each frame is shown (1000 / fps); the muxer PTS
520    /// advances by this per frame.
521    frame_ms: u32,
522    fps: f64,
523    path: std::path::PathBuf,
524    muxer: Option<muxide::api::Muxer<std::io::BufWriter<std::fs::File>>>,
525}
526
527impl H264Recorder {
528    /// Create a recorder for `width` x `height` at `fps`, writing an MP4
529    /// to `path` when finished. Dimensions are rounded down to even
530    /// (required by 4:2:0 chroma).
531    pub fn create(path: &Path, width: usize, height: usize, fps: u32) -> Result<Self> {
532        use openh264::encoder::{BitRate, EncoderConfig, FrameRate, UsageType};
533        let width = width & !1;
534        let height = height & !1;
535        if width == 0 || height == 0 {
536            return Err(RecordError::Frame("zero-sized recording"));
537        }
538        let fps = fps.max(1);
539        // Generous bitrate ceiling for sharp text; screen content is
540        // mostly static so the encoder spends far less on average.
541        #[allow(clippy::cast_possible_truncation)]
542        let bitrate = ((width as u64 * height as u64 * u64::from(fps)) / 5)
543            .clamp(1_000_000, 12_000_000) as u32;
544        let config = EncoderConfig::new()
545            // Screen-content mode keeps UI text and edges crisp.
546            .usage_type(UsageType::ScreenContentRealTime)
547            .max_frame_rate(FrameRate::from_hz(fps as f32))
548            .bitrate(BitRate::from_bps(bitrate));
549        let enc = openh264::encoder::Encoder::with_api_config(
550            openh264::OpenH264API::from_source(),
551            config,
552        )
553        .map_err(|e| RecordError::Encode(format!("openh264 init: {e:?}")))?;
554        Ok(Self {
555            enc,
556            width,
557            height,
558            frame_ms: 1000 / fps,
559            fps: f64::from(fps),
560            path: path.to_path_buf(),
561            muxer: None,
562        })
563    }
564
565    /// Encode and mux one RGB frame (`w*h*3` bytes). A source a couple
566    /// pixels larger than the recording size (even-rounding) is cropped;
567    /// a smaller one is rejected.
568    pub fn push_rgb(&mut self, w: usize, h: usize, rgb: &[u8]) -> Result<()> {
569        use openh264::formats::{RgbSliceU8, YUVBuffer};
570        if w < self.width || h < self.height {
571            return Err(RecordError::SizeMismatch {
572                got: (w, h),
573                want: (self.width, self.height),
574            });
575        }
576        if rgb.len() < w * h * 3 {
577            return Err(RecordError::Frame("rgb buffer too small"));
578        }
579        // Crop to the exact (even) encoder size if the source is larger.
580        let cropped;
581        let src: &[u8] = if w == self.width && h == self.height {
582            rgb
583        } else {
584            let mut out = Vec::with_capacity(self.width * self.height * 3);
585            for row in 0..self.height {
586                let start = row * w * 3;
587                out.extend_from_slice(&rgb[start..start + self.width * 3]);
588            }
589            cropped = out;
590            &cropped
591        };
592        let yuv = YUVBuffer::from_rgb8_source(RgbSliceU8::new(src, (self.width, self.height)));
593        let bitstream = self
594            .enc
595            .encode(&yuv)
596            .map_err(|e| RecordError::Encode(format!("openh264 encode: {e:?}")))?;
597        let annexb = bitstream.to_vec();
598        // A skipped frame (rate control) yields no bytes; drop it.
599        if annexb.is_empty() {
600            return Ok(());
601        }
602        if self.muxer.is_none() {
603            let cfg = muxide::codec::h264::extract_avc_config(&annexb)
604                .ok_or_else(|| RecordError::Encode("no SPS/PPS in first frame".into()))?;
605            let file = std::io::BufWriter::new(std::fs::File::create(&self.path)?);
606            let muxer = muxide::api::MuxerBuilder::new(file)
607                .video(
608                    muxide::api::VideoCodec::H264,
609                    self.width as u32,
610                    self.height as u32,
611                    self.fps,
612                )
613                .with_sps(cfg.sps)
614                .with_pps(cfg.pps)
615                // moov at the front so the file streams / plays while
616                // downloading (browsers need this for <video>).
617                .with_fast_start(true)
618                .build()
619                .map_err(|e| RecordError::Encode(format!("mp4 mux init: {e}")))?;
620            self.muxer = Some(muxer);
621        }
622        // muxide takes Annex-B and converts to AVCC internally (it also
623        // detects the IDR keyframe by scanning start codes), so pass the
624        // raw bitstream, not a pre-converted one.
625        self.muxer
626            .as_mut()
627            .expect("muxer set above")
628            .encode_video(&annexb, self.frame_ms)
629            .map_err(|e| RecordError::Encode(format!("mp4 write: {e}")))?;
630        Ok(())
631    }
632
633    /// Flush and finalize the MP4. Errors if no frame was ever pushed.
634    pub fn finish(mut self) -> Result<()> {
635        match self.muxer.take() {
636            Some(mut m) => m
637                .finish_in_place()
638                .map_err(|e| RecordError::Encode(format!("mp4 finish: {e}"))),
639            None => Err(RecordError::Frame("no frames encoded")),
640        }
641    }
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647
648    fn solid_rgb(w: usize, h: usize, c: [u8; 3]) -> Vec<u8> {
649        let mut v = Vec::with_capacity(w * h * 3);
650        for _ in 0..w * h {
651            v.extend_from_slice(&c);
652        }
653        v
654    }
655
656    #[test]
657    fn encodes_frames_to_a_valid_ivf() {
658        let (w, h) = (64, 48);
659        let mut rec = Recorder::new(w, h, 5, 9).expect("recorder");
660        // A few frames of changing color, so there is real motion.
661        for c in [[200, 30, 30], [30, 200, 30], [30, 30, 200], [220, 220, 30]] {
662            rec.push_rgb(w, h, &solid_rgb(w, h, c)).expect("push");
663        }
664        let ivf = rec.finish_to_vec().expect("finish");
665        assert_eq!(&ivf[0..4], b"DKIF", "IVF signature");
666        assert_eq!(&ivf[8..12], b"AV01", "codec fourcc");
667        let frame_count = u32::from_le_bytes(ivf[24..28].try_into().unwrap());
668        assert!(
669            frame_count >= 1,
670            "at least one encoded frame, got {frame_count}"
671        );
672        // Header plus at least one framed packet.
673        assert!(
674            ivf.len() > 32 + 12,
675            "encoded body present, got {} bytes",
676            ivf.len()
677        );
678    }
679
680    #[test]
681    fn odd_dimensions_are_rounded_even() {
682        let rec = Recorder::new(65, 49, 5, 9).expect("recorder");
683        assert_eq!((rec.width, rec.height), (64, 48));
684    }
685}