Screen recordings keep up with animations: every drawn frame, up to 60 fps, with its real time
CI / test (push) Canceled after 0s

A recording of an animation looked choppy because frames barely reached ffmpeg: each 8 MB
1080p frame went out only as far as the socket buffer took it on each main loop pass, so a
new frame could be taken only every few hundred ms (V's recording changed picture ~12 times a
second; headless, 2 a second). Frames were also stamped when ffmpeg read them, not when drawn,
and every grab forced a full redraw.

Now:
- Both hosts (wasmhost raster_stub.c, host-wasm main.rs) copy a frame into a 3-slot queue and
  a writer thread sends it, so a frame never waits on the main loop. A full queue (ffmpeg
  behind) means that frame is not taken; the next one is, with its own time.
- The stream is uncompressed RGBA in Matroska (recorder.mbt mkv_stream_header /
  mkv_frame_header; the hosts write the same 42-byte cluster header), each frame stamped
  with the time it was drawn. ffmpeg makes constant 60 fps H.264 from it, under nice -n 10.
- A frame is taken when the desktop draws a changed frame (app.mbt draw_frame,
  compose_frame), at most 60 a second, or when the pointer moves. A still screen sends
  nothing; the REC pill redraws only its own rectangle when its seconds turn.
- ffmpeg going away mid-recording says so in the notification.
- Tests: the cluster header bytes, ffprobe reading the stream with each frame's own time,
  and the recording test now checks a 60 fps file as long as the recording ran. The
  recording tests fail with a clear message when ffmpeg/ffprobe are missing instead of
  returning early; CI installs ffmpeg.

Headless 1080p, one window redrawing at 60 fps (rec-bench.sh in project files
recorder-smooth/): distinct frames in the video 2.1/s -> 58.9/s (MoonBit host), 59.1/s
(Rust host); overview open/close 1.8/s -> 38.7/s (its previews refresh at 5-10/s live).
Compositor kept drawing 57 fps while recording; still screen: compositor 8% CPU.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hjEUQq16Te1LPYMinT
This commit is contained in:
Claude committed 2026-11-26 04:14:28 +00:00
1 parent 14acc5d42e
commit 024f18ce61
11 files changed
+707 -158

No files matched your search

+161 -31
View File
@@ -56,9 +56,9 @@ struct State {
pl: Option<plasmoid::Runtime>,
/// Fds beyond the first that arrived with the last `recvmsg` on a socket, for `take-fd`.
extra_fds: std::collections::HashMap<i32, std::collections::VecDeque<i32>>,
/// The screen recording frame in flight (`grab-recording-frame`) and how much of it went out.
rec_frame: Vec<u8>,
rec_sent: usize,
/// The screen recording's frame queue and writer thread (`grab-recording-frame`,
/// `send-recording-frame`).
rec: Recorder,
/// The frozen screen of a screenshot (`snapshot-frame`): RGBA8888, its width and height.
snap: Vec<u8>,
snap_w: i32,
@@ -493,48 +493,27 @@ impl chandra::host::raster::Host for State {
if w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fw || y + h > fh {
return false;
}
let Some(mut out) = self.rec.free_slot() else { return false };
let (w, h) = (w as usize, h as usize);
let mut out = std::mem::take(&mut self.rec_frame);
out.clear();
out.reserve(w * h * 4);
out.reserve(REC_HEAD + w * h * 4);
rec_frame_header(&mut out, rec_now_ms(), w * h * 4);
for row in 0..h {
let at = ((y as usize + row) * fw as usize + x as usize) * 4;
out.extend_from_slice(&self.raster.fb[at..at + w * 4]);
}
for a in out.iter_mut().skip(3).step_by(4) {
for a in out[REC_HEAD..].iter_mut().skip(3).step_by(4) {
*a = 255;
}
if pointer {
draw_record_pointer(&mut out, w as i32, h as i32, px - x, py - y);
draw_record_pointer(&mut out[REC_HEAD..], w as i32, h as i32, px - x, py - y);
}
self.rec_frame = out;
self.rec_sent = 0;
self.rec.queue(out);
true
}
fn send_recording_frame(&mut self, fd: i32) -> i32 {
unsafe {
let fl = libc::fcntl(fd, libc::F_GETFL);
if fl >= 0 && fl & libc::O_NONBLOCK == 0 {
libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
}
while self.rec_sent < self.rec_frame.len() {
let rest = &self.rec_frame[self.rec_sent..];
let n = libc::write(fd, rest.as_ptr() as *const _, rest.len());
if n < 0 {
let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
if e == libc::EINTR {
continue;
}
if e == libc::EAGAIN || e == libc::EWOULDBLOCK {
break;
}
return -1;
}
self.rec_sent += n as usize;
}
}
(self.rec_frame.len() - self.rec_sent).min(i32::MAX as usize) as i32
if fd >= 0 { self.rec.run(fd) } else { self.rec.finish() }
}
fn snapshot_frame(&mut self) -> bool {
@@ -587,6 +566,157 @@ impl chandra::host::raster::Host for State {
}
}
/// Frames queued for the recording at most: when ffmpeg is this far behind, a drawn frame is
/// not taken (the next one is, with its own time).
const REC_SLOTS: usize = 3;
/// The Matroska Cluster header before each frame's pixels, as recorder.mbt's mkv_frame_header.
const REC_HEAD: usize = 42;
/// The screen recording's writer: frames (each a Cluster header with the time it was taken, then
/// the pixels) go through a channel to a thread that writes them to ffmpeg's socket in order, so
/// a frame never waits on the main loop. Sent buffers come back for reuse.
#[derive(Default)]
struct Recorder {
fd: i32,
tx: Option<std::sync::mpsc::Sender<Vec<u8>>>,
rx: Option<std::sync::mpsc::Receiver<Vec<u8>>>,
back: Option<std::sync::mpsc::Receiver<Vec<u8>>>,
back_tx: Option<std::sync::mpsc::Sender<Vec<u8>>>,
queued: std::sync::Arc<std::sync::atomic::AtomicUsize>,
failed: std::sync::Arc<std::sync::atomic::AtomicBool>,
thread: Option<std::thread::JoinHandle<()>>,
}
impl Recorder {
fn channels(&mut self) {
if self.tx.is_none() {
let (tx, rx) = std::sync::mpsc::channel();
let (back_tx, back) = std::sync::mpsc::channel();
(self.tx, self.rx, self.back, self.back_tx) = (Some(tx), Some(rx), Some(back), Some(back_tx));
self.queued.store(0, std::sync::atomic::Ordering::SeqCst);
self.failed.store(false, std::sync::atomic::Ordering::SeqCst);
}
}
/// A buffer to fill, or None when the queue is full or the writer failed.
fn free_slot(&mut self) -> Option<Vec<u8>> {
use std::sync::atomic::Ordering::SeqCst;
self.channels();
if self.failed.load(SeqCst) || self.queued.load(SeqCst) >= REC_SLOTS {
return None;
}
Some(self.back.as_ref().and_then(|b| b.try_recv().ok()).unwrap_or_default())
}
fn queue(&mut self, buf: Vec<u8>) {
self.queued.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if let Some(tx) = &self.tx {
if tx.send(buf).is_err() {
self.failed.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
}
/// Start the writer on `fd` (once): the frames still queued, or -1 once a write failed.
fn run(&mut self, fd: i32) -> i32 {
use std::sync::atomic::Ordering::SeqCst;
self.channels();
if self.thread.is_none() {
self.fd = fd;
unsafe {
let fl = libc::fcntl(fd, libc::F_GETFL);
if fl >= 0 && fl & libc::O_NONBLOCK == 0 {
libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK);
}
}
let rx = self.rx.take().expect("recording channel");
let back = self.back_tx.clone().expect("recording channel");
let (queued, failed) = (self.queued.clone(), self.failed.clone());
self.thread = Some(std::thread::spawn(move || {
for buf in rx {
if let Err(e) = rec_write_all(fd, &buf) {
eprintln!("recording: writing to ffmpeg failed: {e}");
failed.store(true, SeqCst);
break;
}
queued.fetch_sub(1, SeqCst);
let _ = back.send(buf); // the main side may be gone: nothing to reuse it for then
}
}));
} else if fd != self.fd {
eprintln!("recording: a second stream while one is running");
return -1;
}
if self.failed.load(SeqCst) { -1 } else { self.queued.load(SeqCst) as i32 }
}
/// Send what is queued and stop the writer: 0, or -1 when a write failed.
fn finish(&mut self) -> i32 {
self.tx = None; // ends the writer's loop once the queue is empty
if let Some(t) = self.thread.take() {
if t.join().is_err() {
eprintln!("recording: the writer thread panicked");
self.failed.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
let failed = self.failed.load(std::sync::atomic::Ordering::SeqCst);
*self = Recorder::default();
if failed { -1 } else { 0 }
}
}
fn rec_now_ms() -> u64 {
let mut ts: libc::timespec = unsafe { std::mem::zeroed() };
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut ts) };
ts.tv_sec as u64 * 1000 + ts.tv_nsec as u64 / 1_000_000
}
/// An EBML ID and an 8-byte size.
fn rec_id_size(out: &mut Vec<u8>, id: &[u8], n: u64) {
out.extend_from_slice(id);
out.push(0x01);
out.extend_from_slice(&n.to_be_bytes()[1..]);
}
/// A Cluster at `ms` holding one SimpleBlock of `n` bytes of pixels (track 1, a keyframe).
fn rec_frame_header(out: &mut Vec<u8>, ms: u64, n: usize) {
rec_id_size(out, &[0x1f, 0x43, 0xb6, 0x75], 30 + n as u64);
rec_id_size(out, &[0xe7], 8);
out.extend_from_slice(&ms.to_be_bytes());
rec_id_size(out, &[0xa3], 4 + n as u64);
out.extend_from_slice(&[0x81, 0x00, 0x00, 0x80]);
}
/// Write all of `buf` to the non-blocking `fd`; ffmpeg taking nothing for 5 s is an error (so
/// stopping never hangs on a stuck encoder).
fn rec_write_all(fd: i32, buf: &[u8]) -> std::io::Result<()> {
let mut done = 0;
while done < buf.len() {
let rest = &buf[done..];
let n = unsafe { libc::send(fd, rest.as_ptr() as *const _, rest.len(), libc::MSG_NOSIGNAL) };
if n < 0 {
let e = std::io::Error::last_os_error();
match e.raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::EAGAIN) => {
let mut p = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 };
let r = unsafe { libc::poll(&mut p, 1, 5000) };
if r == 0 {
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "ffmpeg took nothing for 5 s"));
}
if r < 0 && std::io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) {
return Err(std::io::Error::last_os_error());
}
continue;
}
_ => return Err(e),
}
}
done += n as usize;
}
Ok(())
}
/// The arrow pointer with its tip at (x, y) in an RGBA `w` x `h` frame, as the compositor's
/// recorder draws it: a black body widening over 13 rows and a short tail, then the white inside.
fn draw_record_pointer(px: &mut [u8], w: i32, h: i32, x: i32, y: i32) {