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

+300 -84
View File
@@ -7,11 +7,16 @@
/// the video unless that is switched off (P on the overlay, or the screenshot panel module).
///
/// Encoding is ffmpeg's: the compositor starts `ffmpeg` listening on a unix socket and streams
/// raw RGBA frames into it (at most 30 a second, each stamped with the wall clock as it arrives,
/// so the video plays at real speed even when frames are skipped), and ffmpeg writes H.264 in an
/// MP4: ~/Videos/Screencasts/Screencast_YYYYMMDD_HHMMSS.mp4. Writes never block: a frame that
/// ffmpeg hasn't taken yet when the next one is due makes that next one wait (it is skipped).
/// Without ffmpeg on PATH a notification says so.
/// the frames into it as uncompressed RGBA in Matroska, each stamped with the time it was drawn.
/// A frame is taken each time the desktop draws a changed frame (at most 60 a second; the pointer
/// moving counts as a change), so animations are recorded at the rate they are drawn and a still
/// screen costs nothing. ffmpeg (at a lower CPU priority than the desktop) turns that into
/// constant 60 fps H.264 in an MP4, repeating a frame for as long as it stayed on screen:
/// ~/Videos/Screencasts/Screencast_YYYYMMDD_HHMMSS.mp4. The host that draws the screen copies a
/// frame into a short queue and a writer thread of its own sends it, so a frame never waits on
/// the main loop; when ffmpeg falls behind and the queue is full, that drawn frame is not
/// recorded (the next one is, with its own time, so the video still plays at real speed).
/// Without ffmpeg on PATH a notification says so, and so does ffmpeg going away mid-recording.
///| A recording in progress.
pub(all) struct Recording {
@@ -24,16 +29,35 @@ pub(all) struct Recording {
mut fd : Int
connect_until : UInt64
started : UInt64
/// The frame being written and how much of it went out.
/// The Matroska stream header, sent first, and how much of it went out.
header : Bytes
mut header_sent : Int
/// The frame being written and how much of it went out (when the compositor writes frames
/// itself; a host with a frame recorder keeps its own).
mut pending : Bytes
mut sent : Int
mut next_at : UInt64
/// When the last frame was taken, and the pointer position drawn into it.
mut last_grab : UInt64
mut grab_px : Int
mut grab_py : Int
/// A drawn frame not recorded yet (too soon after the last one, or the queue was full).
mut dirty : Bool
/// The seconds shown on the REC pill.
mut shown_secs : Int
mut frames : Int
}
///| Frames a second recorded at most, and the gap that makes.
let rec_fps : Int = 60
///|
let rec_gap_ms : UInt64 = 12UL
///| Screen recording done by the host that draws the screen: `grab` copies a rectangle of the
/// screen (with the pointer at a screen position when asked) into the host's frame, and `send`
/// writes what is left of it to the encoder's socket (the bytes still left, or -1).
/// screen (with the pointer at a screen position when asked) into the host's queue, stamped with
/// the host's monotonic clock (false when the queue is full), and `send` hands the encoder's
/// socket to the host's writer thread (fd >= 0: the frames still queued, or -1 once a write
/// failed; -1: send what is queued, stop the writer, and say 0 or -1 the same way).
pub(all) struct FrameRecorder {
grab : (@scene.Rect, Bool, Int, Int) -> Bool
send : (Int) -> Int
@@ -143,10 +167,13 @@ fn ChandraCompositor::start_recording(self : ChandraCompositor, r : @scene.Rect)
d => d
}
let sock = rt + "/chandra-rec-" + @sys.getpid().to_string() + "-" + @sys.monotonic_ms().to_string() + ".sock"
let size = w.to_string() + "x" + h.to_string()
let cmd = "exec ffmpeg -hide_banner -loglevel error -nostdin -y -f rawvideo -pix_fmt rgba -video_size " +
size + " -use_wallclock_as_timestamps 1 -listen 1 -timeout 10000 -i 'unix:" + sock + "'" +
" -c:v libx264 -preset ultrafast -crf 23 -pix_fmt yuv420p -fps_mode cfr -r 30 -movflags +faststart '" +
// nice: encoding takes whatever CPU the desktop leaves, so recording doesn't slow animations
// down; when ffmpeg can't keep up, frames are left out rather than the desktop held back.
let cmd = "exec nice -n 10 ffmpeg -hide_banner -loglevel error -nostdin -y -f matroska -listen 1 -timeout 10000 -i 'unix:" +
sock + "'" +
" -c:v libx264 -preset ultrafast -crf 23 -pix_fmt yuv420p -fps_mode cfr -r " +
rec_fps.to_string() +
" -movflags +faststart '" +
path + "' ; rm -f '" + sock + "'"
if !@sys.spawn(cmd, self.server.socket_path) {
self.notify("Can't record the screen", "ffmpeg didn't start")
@@ -160,38 +187,112 @@ fn ChandraCompositor::start_recording(self : ChandraCompositor, r : @scene.Rect)
fd: -1,
connect_until: now + 5000UL,
started: now,
header: mkv_stream_header(w, h),
header_sent: 0,
pending: Bytes::from_array([]),
sent: 0,
next_at: now,
last_grab: 0UL,
grab_px: -1,
grab_py: -1,
dirty: true,
shown_secs: 0,
frames: 0,
})
self.damage.mark_full()
}
///| Stop the recording: closing the stream makes ffmpeg finish the file.
///| Stop the recording: the last frame goes out (so the video lasts until now), and closing the
/// stream makes ffmpeg finish the file.
pub fn ChandraCompositor::stop_recording(self : ChandraCompositor) -> Unit {
match self.rec {
Some(rec) => {
self.rec = None
if rec.fd >= 0 {
// Whatever is left of the frame in flight is dropped; ffmpeg ignores a partial frame.
@sys.close_fd(rec.fd)
let secs = (@sys.monotonic_ms() - rec.started) / 1000UL
self.last_recording = rec.path
self.notify("Recording saved", base_name(rec.path) + " · " + clock_text(secs.to_int()))
} else {
// ffmpeg may be about to listen: connect and hang up so it ends now (it also gives up
// by itself after ten seconds).
let fd = @sys.unix_connect(rec.sock)
if fd >= 0 {
@sys.close_fd(fd)
}
self.notify("Recording stopped", "ffmpeg never started listening; nothing was saved")
}
self.damage.mark_full()
}
None => ()
self.end_recording(None)
}
///| End the recording; `error` says why when it broke.
fn ChandraCompositor::end_recording(self : ChandraCompositor, error : String?) -> Unit {
let rec = match self.rec {
Some(r) => r
None => return
}
let streaming = rec.fd >= 0 && rec.header_sent == rec.header.length()
let mut error = error
if streaming && error is None {
// One more frame with the time now, so the last picture lasts until the stop.
rec.dirty = true
rec.last_grab = 0UL
self.take_recording_frame(rec, @sys.monotonic_ms())
match self.frame_recorder {
Some(host) =>
if (host.send)(-1) < 0 {
error = Some("ffmpeg stopped reading the video stream")
}
None =>
if !self.flush_recording(rec, 2000UL) {
error = Some("ffmpeg stopped reading the video stream")
}
}
} else if streaming {
match self.frame_recorder {
Some(host) => ignore((host.send)(-1))
None => ()
}
}
self.rec = None
if rec.fd >= 0 {
@sys.close_fd(rec.fd)
let secs = (@sys.monotonic_ms() - rec.started) / 1000UL
self.last_recording = rec.path
match error {
None => self.notify("Recording saved", base_name(rec.path) + " · " + clock_text(secs.to_int()))
Some(e) =>
self.notify("Recording stopped: " + e, base_name(rec.path) + " has what was recorded until then (" + clock_text(secs.to_int()) + ")")
}
} else {
// ffmpeg may be about to listen: connect and hang up so it ends now (it also gives up
// by itself after ten seconds).
let fd = @sys.unix_connect(rec.sock)
if fd >= 0 {
@sys.close_fd(fd)
}
self.notify("Recording stopped", "ffmpeg never started listening; nothing was saved")
}
self.damage.mark_full()
}
///| Write out the frame in flight (the compositor writing frames itself), for up to `ms`. False
/// when ffmpeg stopped taking it.
fn ChandraCompositor::flush_recording(self : ChandraCompositor, rec : Recording, ms : UInt64) -> Bool {
let until = @sys.monotonic_ms() + ms
while rec.sent < rec.pending.length() {
match self.push_recording(rec) {
Some(true) => ()
Some(false) =>
if @sys.monotonic_ms() > until {
return false
} else {
@sys.sleep_ms(2)
}
None => return false
}
}
true
}
///| Write what the socket takes of the frame in flight: Some(true) when it all went out,
/// Some(false) when the socket is full, None when the write failed.
fn ChandraCompositor::push_recording(self : ChandraCompositor, rec : Recording) -> Bool? {
ignore(self)
while rec.sent < rec.pending.length() {
let len = (rec.pending.length() - rec.sent).min(1 << 20)
let n = @sys.write_nonblock(rec.fd, rec.pending[rec.sent:rec.sent + len].to_bytes())
if n < 0 {
return None
}
if n == 0 {
return Some(false)
}
rec.sent = rec.sent + n
}
Some(true)
}
///| The path of the last recording saved.
@@ -210,8 +311,8 @@ fn ChandraCompositor::notify(self : ChandraCompositor, title : String, detail :
self.damage.mark_full()
}
///| Move the recording along (called from `step`): connect to ffmpeg, push out what the socket
/// takes, and grab the next frame when one is due and the last one is out.
///| Move the recording along (called from `step`): connect to ffmpeg and send the stream
/// header, keep the writer going, and take a frame that was drawn but not recorded yet.
fn ChandraCompositor::recording_tick(self : ChandraCompositor) -> Unit {
let rec = match self.rec {
Some(r) => r
@@ -227,64 +328,179 @@ fn ChandraCompositor::recording_tick(self : ChandraCompositor) -> Unit {
return
}
}
if rec.header_sent < rec.header.length() {
let n = @sys.write_nonblock(rec.fd, rec.header[rec.header_sent:].to_bytes())
if n < 0 {
self.end_recording(Some("ffmpeg closed the video stream"))
return
}
rec.header_sent = rec.header_sent + n
if rec.header_sent < rec.header.length() {
return
}
}
// The REC pill's clock: redrawn when its seconds turn, not on every frame.
let secs = ((now - rec.started) / 1000UL).to_int()
if secs != rec.shown_secs {
rec.shown_secs = secs
self.damage.mark_rect(self.rec_pill())
}
match self.frame_recorder {
Some(host) => {
// The host holds the frame in flight.
if rec.sent > 0 {
let left = (host.send)(rec.fd)
if left < 0 {
self.stop_recording()
return
}
if left > 0 {
return
}
rec.sent = 0
}
if now < rec.next_at {
Some(host) =>
if (host.send)(rec.fd) < 0 {
self.end_recording(Some("ffmpeg stopped reading the video stream"))
return
}
rec.next_at = now + 33UL
if (host.grab)(rec.rect, self.rec_pointer, self.ptr_x.to_int(), self.ptr_y.to_int()) {
rec.sent = 1 // a frame is waiting on the host
rec.frames = rec.frames + 1
None =>
if self.push_recording(rec) is None {
self.end_recording(Some("ffmpeg stopped reading the video stream"))
return
}
}
// The pointer isn't part of the drawn desktop: it moving is a change of its own.
if self.rec_pointer && (self.ptr_x.to_int() != rec.grab_px || self.ptr_y.to_int() != rec.grab_py) {
rec.dirty = true
}
if rec.dirty {
self.take_recording_frame(rec, now)
}
}
///| A changed frame was drawn (the host's framebuffer, or `last_frame`): record it.
pub fn ChandraCompositor::recording_frame_drawn(self : ChandraCompositor) -> Unit {
match self.rec {
Some(rec) => {
rec.dirty = true
if rec.fd >= 0 && rec.header_sent == rec.header.length() {
self.take_recording_frame(rec, @sys.monotonic_ms())
}
self.damage.mark_full()
return
}
None => ()
}
// The frame in flight.
while rec.sent < rec.pending.length() {
let len = (rec.pending.length() - rec.sent).min(1 << 20)
let n = @sys.write_nonblock(rec.fd, rec.pending[rec.sent:rec.sent + len].to_bytes())
if n < 0 {
// ffmpeg went away (killed, disk full): end the recording with what it has.
self.stop_recording()
return
}
if n == 0 {
return
}
rec.sent = rec.sent + n
}
if now < rec.next_at {
}
///| Take the screen's current frame into the recording, unless the last one was taken less than
/// a 60th of a second ago or the previous frame is still going out (it stays `dirty` then, and
/// `recording_tick` takes it as soon as it can).
fn ChandraCompositor::take_recording_frame(self : ChandraCompositor, rec : Recording, now : UInt64) -> Unit {
if rec.last_grab > 0UL && now - rec.last_grab < rec_gap_ms {
return
}
rec.next_at = now + 33UL
match self.grab_region(rec.rect) {
Some(px) => {
if self.rec_pointer {
draw_pointer(px, self.ptr_x.to_int() - rec.rect.x, self.ptr_y.to_int() - rec.rect.y)
let px = self.ptr_x.to_int()
let py = self.ptr_y.to_int()
let taken = match self.frame_recorder {
Some(host) => (host.grab)(rec.rect, self.rec_pointer, px, py)
None => {
if rec.sent < rec.pending.length() {
return
}
match self.grab_region(rec.rect) {
Some(p) => {
if self.rec_pointer {
draw_pointer(p, px - rec.rect.x, py - rec.rect.y)
}
let head = mkv_frame_header(now, p.data.length())
let buf = FixedArray::make(head.length() + p.data.length(), b'\x00')
buf.blit_from_bytes(0, head, 0, head.length())
FixedArray::blit_to(p.data, buf, len=p.data.length(), dst_offset=head.length())
rec.pending = Bytes::from_fixedarray(buf)
rec.sent = 0
true
}
None => false
}
rec.pending = Bytes::from_fixedarray(px.data)
rec.sent = 0
rec.frames = rec.frames + 1
}
None => ()
}
// Redraw now and then so the elapsed time on the pill moves on.
self.damage.mark_full()
if taken {
rec.dirty = false
rec.last_grab = now
rec.grab_px = px
rec.grab_py = py
rec.frames = rec.frames + 1
}
}
///| An EBML element ID followed by `n` as an 8-byte size (vint with the 0x01 length marker).
fn mkv_put_id_size(out : Array[Byte], id : Array[Byte], n : Int64) -> Unit {
out.append(id)
out.push(b'\x01')
for i = 6; i >= 0; i = i - 1 {
out.push((n >> (i * 8)).land(0xffL).to_byte())
}
}
///| An unsigned-integer element, 8 bytes wide.
fn mkv_put_uint(out : Array[Byte], id : Array[Byte], v : Int64) -> Unit {
mkv_put_id_size(out, id, 8L)
for i = 7; i >= 0; i = i - 1 {
out.push((v >> (i * 8)).land(0xffL).to_byte())
}
}
///| A string or binary element.
fn mkv_put_bytes(out : Array[Byte], id : Array[Byte], data : Array[Byte]) -> Unit {
mkv_put_id_size(out, id, data.length().to_int64())
out.append(data)
}
///| An element holding other elements.
fn mkv_put_master(out : Array[Byte], id : Array[Byte], body : Array[Byte]) -> Unit {
mkv_put_bytes(out, id, body)
}
///|
fn ascii(s : String) -> Array[Byte] {
s.to_array().map(c => c.to_int().to_byte())
}
///| The start of the Matroska stream sent to ffmpeg: the EBML header, a Segment of unknown size
/// (it is a live stream), millisecond timestamps, and one video track of uncompressed RGBA
/// `w` x `h` frames. The hosts' writers (wasmhost raster_stub.c, host-wasm main.rs) then send
/// each frame as a Cluster made by `mkv_frame_header`.
pub fn mkv_stream_header(w : Int, h : Int) -> Bytes {
let out : Array[Byte] = []
let ebml : Array[Byte] = []
mkv_put_uint(ebml, [b'\x42', b'\x86'], 1L) // EBMLVersion
mkv_put_uint(ebml, [b'\x42', b'\xf7'], 1L) // EBMLReadVersion
mkv_put_uint(ebml, [b'\x42', b'\xf2'], 4L) // EBMLMaxIDLength
mkv_put_uint(ebml, [b'\x42', b'\xf3'], 8L) // EBMLMaxSizeLength
mkv_put_bytes(ebml, [b'\x42', b'\x82'], ascii("matroska")) // DocType
mkv_put_uint(ebml, [b'\x42', b'\x87'], 4L) // DocTypeVersion
mkv_put_uint(ebml, [b'\x42', b'\x85'], 2L) // DocTypeReadVersion
mkv_put_master(out, [b'\x1a', b'\x45', b'\xdf', b'\xa3'], ebml)
// Segment, size unknown.
out.append([b'\x18', b'\x53', b'\x80', b'\x67', b'\x01', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff'])
let info : Array[Byte] = []
mkv_put_uint(info, [b'\x2a', b'\xd7', b'\xb1'], 1000000L) // TimestampScale: 1 ms
mkv_put_bytes(info, [b'\x4d', b'\x80'], ascii("Chandra")) // MuxingApp
mkv_put_bytes(info, [b'\x57', b'\x41'], ascii("Chandra")) // WritingApp
mkv_put_master(out, [b'\x15', b'\x49', b'\xa9', b'\x66'], info)
let video : Array[Byte] = []
mkv_put_uint(video, [b'\xb0'], w.to_int64()) // PixelWidth
mkv_put_uint(video, [b'\xba'], h.to_int64()) // PixelHeight
mkv_put_bytes(video, [b'\x2e', b'\xb5', b'\x24'], ascii("RGBA")) // ColourSpace (FourCC)
let track : Array[Byte] = []
mkv_put_uint(track, [b'\xd7'], 1L) // TrackNumber
mkv_put_uint(track, [b'\x73', b'\xc5'], 1L) // TrackUID
mkv_put_uint(track, [b'\x83'], 1L) // TrackType: video
mkv_put_bytes(track, [b'\x86'], ascii("V_UNCOMPRESSED")) // CodecID
mkv_put_master(track, [b'\xe0'], video)
let tracks : Array[Byte] = []
mkv_put_master(tracks, [b'\xae'], track) // TrackEntry
mkv_put_master(out, [b'\x16', b'\x54', b'\xae', b'\x6b'], tracks)
Bytes::from_array(out)
}
///| What goes before each frame's `n` bytes of pixels: a Cluster at time `ms` holding one
/// SimpleBlock (track 1, relative time 0, a keyframe). 42 bytes; the hosts write the same.
pub fn mkv_frame_header(ms : UInt64, n : Int) -> Bytes {
let out : Array[Byte] = []
// Cluster = Timestamp element (17 bytes) + SimpleBlock ID and size (9) + block header (4) + pixels.
mkv_put_id_size(out, [b'\x1f', b'\x43', b'\xb6', b'\x75'], (30 + n).to_int64())
mkv_put_uint(out, [b'\xe7'], ms.reinterpret_as_int64())
mkv_put_id_size(out, [b'\xa3'], (4 + n).to_int64())
out.append([b'\x81', b'\x00', b'\x00', b'\x80'])
Bytes::from_array(out)
}
///| The pixels of `r` on screen now (opaque).