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

+1 -1
View File
@@ -34,7 +34,7 @@ jobs:
run: | run: |
apt-get update -q apt-get update -q
apt-get install -y -q --no-install-recommends libseat-dev libdrm-dev libinput-dev libudev-dev libxkbcommon-dev \ apt-get install -y -q --no-install-recommends libseat-dev libdrm-dev libinput-dev libudev-dev libxkbcommon-dev \
libpam0g-dev pamtester libpam0g-dev pamtester ffmpeg
- name: Install wasm-tools, wit-bindgen, wasmtime, wasmer C API - name: Install wasm-tools, wit-bindgen, wasmtime, wasmer C API
run: scripts/setup-toolchain.sh run: scripts/setup-toolchain.sh
+1
View File
@@ -529,6 +529,7 @@ fn draw_frame(comp : @host.ChandraCompositor, trace : Bool, pacer : Pacer) -> Bo
@raster.submit(sg) @raster.submit(sg)
let r1 = @sys.monotonic_ms() let r1 = @sys.monotonic_ms()
comp.prof_raster_ms = comp.prof_raster_ms + (r1 - r0) comp.prof_raster_ms = comp.prof_raster_ms + (r1 - r0)
comp.recording_frame_drawn() // a recording takes each drawn frame
if trace { if trace {
@sys.log("frame " + r1.to_string() + " compose " + (r0 - c0).to_string() + " raster " + (r1 - r0).to_string()) @sys.log("frame " + r1.to_string() + " compose " + (r0 - c0).to_string() + " raster " + (r1 - r0).to_string())
} }
+1
View File
@@ -1025,6 +1025,7 @@ pub fn ChandraCompositor::compose_frame(
let px = @renderer.render_scene(scene) let px = @renderer.render_scene(scene)
self.last_frame = Some(px) self.last_frame = Some(px)
self.prof_raster_ms = self.prof_raster_ms + (@sys.monotonic_ms() - t1) self.prof_raster_ms = self.prof_raster_ms + (@sys.monotonic_ms() - t1)
self.recording_frame_drawn()
px px
} }
+5
View File
@@ -18,6 +18,11 @@ import {
supported_targets = "+native+wasm" supported_targets = "+native+wasm"
import {
"moonbitlang/core/buffer" @buffer,
"moonbitlang/core/string" @string,
} for "test"
options( options(
link: { link: {
"native": { "native": {
+300 -84
View File
@@ -7,11 +7,16 @@
/// the video unless that is switched off (P on the overlay, or the screenshot panel module). /// 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 /// 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, /// the frames into it as uncompressed RGBA in Matroska, each stamped with the time it was drawn.
/// so the video plays at real speed even when frames are skipped), and ffmpeg writes H.264 in an /// A frame is taken each time the desktop draws a changed frame (at most 60 a second; the pointer
/// MP4: ~/Videos/Screencasts/Screencast_YYYYMMDD_HHMMSS.mp4. Writes never block: a frame that /// moving counts as a change), so animations are recorded at the rate they are drawn and a still
/// ffmpeg hasn't taken yet when the next one is due makes that next one wait (it is skipped). /// screen costs nothing. ffmpeg (at a lower CPU priority than the desktop) turns that into
/// Without ffmpeg on PATH a notification says so. /// 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. ///| A recording in progress.
pub(all) struct Recording { pub(all) struct Recording {
@@ -24,16 +29,35 @@ pub(all) struct Recording {
mut fd : Int mut fd : Int
connect_until : UInt64 connect_until : UInt64
started : 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 pending : Bytes
mut sent : Int 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 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 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` /// screen (with the pointer at a screen position when asked) into the host's queue, stamped with
/// writes what is left of it to the encoder's socket (the bytes still left, or -1). /// 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 { pub(all) struct FrameRecorder {
grab : (@scene.Rect, Bool, Int, Int) -> Bool grab : (@scene.Rect, Bool, Int, Int) -> Bool
send : (Int) -> Int send : (Int) -> Int
@@ -143,10 +167,13 @@ fn ChandraCompositor::start_recording(self : ChandraCompositor, r : @scene.Rect)
d => d d => d
} }
let sock = rt + "/chandra-rec-" + @sys.getpid().to_string() + "-" + @sys.monotonic_ms().to_string() + ".sock" let sock = rt + "/chandra-rec-" + @sys.getpid().to_string() + "-" + @sys.monotonic_ms().to_string() + ".sock"
let size = w.to_string() + "x" + h.to_string() // nice: encoding takes whatever CPU the desktop leaves, so recording doesn't slow animations
let cmd = "exec ffmpeg -hide_banner -loglevel error -nostdin -y -f rawvideo -pix_fmt rgba -video_size " + // down; when ffmpeg can't keep up, frames are left out rather than the desktop held back.
size + " -use_wallclock_as_timestamps 1 -listen 1 -timeout 10000 -i 'unix:" + sock + "'" + let cmd = "exec nice -n 10 ffmpeg -hide_banner -loglevel error -nostdin -y -f matroska -listen 1 -timeout 10000 -i 'unix:" +
" -c:v libx264 -preset ultrafast -crf 23 -pix_fmt yuv420p -fps_mode cfr -r 30 -movflags +faststart '" + 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 + "'" path + "' ; rm -f '" + sock + "'"
if !@sys.spawn(cmd, self.server.socket_path) { if !@sys.spawn(cmd, self.server.socket_path) {
self.notify("Can't record the screen", "ffmpeg didn't start") 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, fd: -1,
connect_until: now + 5000UL, connect_until: now + 5000UL,
started: now, started: now,
header: mkv_stream_header(w, h),
header_sent: 0,
pending: Bytes::from_array([]), pending: Bytes::from_array([]),
sent: 0, sent: 0,
next_at: now, last_grab: 0UL,
grab_px: -1,
grab_py: -1,
dirty: true,
shown_secs: 0,
frames: 0, frames: 0,
}) })
self.damage.mark_full() 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 { pub fn ChandraCompositor::stop_recording(self : ChandraCompositor) -> Unit {
match self.rec { self.end_recording(None)
Some(rec) => { }
self.rec = None
if rec.fd >= 0 { ///| End the recording; `error` says why when it broke.
// Whatever is left of the frame in flight is dropped; ffmpeg ignores a partial frame. fn ChandraCompositor::end_recording(self : ChandraCompositor, error : String?) -> Unit {
@sys.close_fd(rec.fd) let rec = match self.rec {
let secs = (@sys.monotonic_ms() - rec.started) / 1000UL Some(r) => r
self.last_recording = rec.path None => return
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 => ()
} }
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. ///| The path of the last recording saved.
@@ -210,8 +311,8 @@ fn ChandraCompositor::notify(self : ChandraCompositor, title : String, detail :
self.damage.mark_full() self.damage.mark_full()
} }
///| Move the recording along (called from `step`): connect to ffmpeg, push out what the socket ///| Move the recording along (called from `step`): connect to ffmpeg and send the stream
/// takes, and grab the next frame when one is due and the last one is out. /// header, keep the writer going, and take a frame that was drawn but not recorded yet.
fn ChandraCompositor::recording_tick(self : ChandraCompositor) -> Unit { fn ChandraCompositor::recording_tick(self : ChandraCompositor) -> Unit {
let rec = match self.rec { let rec = match self.rec {
Some(r) => r Some(r) => r
@@ -227,64 +328,179 @@ fn ChandraCompositor::recording_tick(self : ChandraCompositor) -> Unit {
return 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 { match self.frame_recorder {
Some(host) => { Some(host) =>
// The host holds the frame in flight. if (host.send)(rec.fd) < 0 {
if rec.sent > 0 { self.end_recording(Some("ffmpeg stopped reading the video stream"))
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 {
return return
} }
rec.next_at = now + 33UL None =>
if (host.grab)(rec.rect, self.rec_pointer, self.ptr_x.to_int(), self.ptr_y.to_int()) { if self.push_recording(rec) is None {
rec.sent = 1 // a frame is waiting on the host self.end_recording(Some("ffmpeg stopped reading the video stream"))
rec.frames = rec.frames + 1 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 => () None => ()
} }
// The frame in flight. }
while rec.sent < rec.pending.length() {
let len = (rec.pending.length() - rec.sent).min(1 << 20) ///| Take the screen's current frame into the recording, unless the last one was taken less than
let n = @sys.write_nonblock(rec.fd, rec.pending[rec.sent:rec.sent + len].to_bytes()) /// a 60th of a second ago or the previous frame is still going out (it stays `dirty` then, and
if n < 0 { /// `recording_tick` takes it as soon as it can).
// ffmpeg went away (killed, disk full): end the recording with what it has. fn ChandraCompositor::take_recording_frame(self : ChandraCompositor, rec : Recording, now : UInt64) -> Unit {
self.stop_recording() if rec.last_grab > 0UL && now - rec.last_grab < rec_gap_ms {
return
}
if n == 0 {
return
}
rec.sent = rec.sent + n
}
if now < rec.next_at {
return return
} }
rec.next_at = now + 33UL let px = self.ptr_x.to_int()
match self.grab_region(rec.rect) { let py = self.ptr_y.to_int()
Some(px) => { let taken = match self.frame_recorder {
if self.rec_pointer { Some(host) => (host.grab)(rec.rect, self.rec_pointer, px, py)
draw_pointer(px, self.ptr_x.to_int() - rec.rect.x, self.ptr_y.to_int() - rec.rect.y) 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. if taken {
self.damage.mark_full() 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). ///| The pixels of `r` on screen now (opaque).
+80 -11
View File
@@ -142,25 +142,87 @@ test "the screenshot module's request waits for a frame, then opens the overlay"
assert_eq(png_size(@sys.read_file_bytes(comp.last_screenshot())), (1280, 720)) assert_eq(png_size(@sys.read_file_bytes(comp.last_screenshot())), (1280, 720))
} }
///| Recording tests need ffmpeg (and ffprobe, from the same package) on PATH.
fn need_ffmpeg() -> Unit raise {
if !@sys.has_exe("ffmpeg") || !@sys.has_exe("ffprobe") {
fail("recording tests need ffmpeg and ffprobe on PATH (apt install ffmpeg)")
}
}
///| Run a shell command to completion and give its stdout (via a file; `spawn` doesn't wait).
fn run_capture(cmd : String, tag : String) -> String {
let out = "/tmp/chandra-rec-" + tag + "-" + @sys.getpid().to_string() + ".txt"
let done = out + ".done"
ignore(@sys.spawn("(" + cmd + ") > '" + out + "' 2>&1; touch '" + done + "'", ""))
let t0 = @sys.monotonic_ms()
while @sys.read_file_bytes(done).length() == 0 && @sys.monotonic_ms() - t0 < 20000UL {
@sys.sleep_ms(20)
}
let bytes = @sys.read_file_bytes(out)
let text = @utf8.decode_lossy(bytes)
@sys.unlink(out)
@sys.unlink(done)
text
}
///|
test "each recorded frame is a 42-byte Matroska cluster header, then the pixels" {
let h = @host.mkv_frame_header(0x0102030405UL, 16)
assert_eq(h.length(), 42)
// Cluster, size 30 + 16.
assert_eq(h[0:12].to_bytes(), b"\x1f\x43\xb6\x75\x01\x00\x00\x00\x00\x00\x00\x2e")
// Timestamp (ms), 8 bytes.
assert_eq(h[12:26].to_bytes(), b"\xe7\x01\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x01\x02")
// SimpleBlock of 4 + 16 bytes: track 1, relative time 0, keyframe.
assert_eq(h[26:42].to_bytes(), b"\x03\x04\x05\xa3\x01\x00\x00\x00\x00\x00\x00\x14\x81\x00\x00\x80")
}
///|
test "ffmpeg reads the recording stream with each frame's own time" {
need_ffmpeg()
let path = "/tmp/chandra-rec-stream-" + @sys.getpid().to_string() + ".mkv"
let buf = @buffer.new()
buf.write_bytes(@host.mkv_stream_header(4, 2))
// Frames drawn at uneven times, as an animation that stalls once.
for t in [5000UL, 5016UL, 5033UL, 5150UL] {
buf.write_bytes(@host.mkv_frame_header(t, 32))
for _ in 0..<8 {
buf.write_bytes(b"\x10\x20\x30\xff")
}
}
ignore(@sys.write_file_bytes(path, buf.to_bytes()))
let out = run_capture(
"ffprobe -v error -show_entries stream=codec_name,pix_fmt,width,height -show_entries frame=pts_time -of csv=p=0 '" +
path + "'",
"probe",
)
@sys.unlink(path)
assert_eq(out, "5.000000\n5.016000\n5.033000\n5.150000\nrawvideo,4,2,rgba\n")
}
///| ///|
test "super+alt+r records the screen to a video with ffmpeg; the REC pill stops it" { test "super+alt+r records the screen to a video with ffmpeg; the REC pill stops it" {
need_ffmpeg()
let (comp, dir) = shot_comp("rec") let (comp, dir) = shot_comp("rec")
chord(comp, [125U, 56U], 64U | 8U, 19U, 1U) chord(comp, [125U, 56U], 64U | 8U, 19U, 1U)
if !@sys.has_exe("ffmpeg") {
assert_false(comp.recording())
assert_true(comp.screenshot_toast_shown())
return
}
assert_true(comp.recording()) assert_true(comp.recording())
assert_eq(comp.recording_rect(), Some(@scene.Rect::new(0, 0, 1280, 720))) assert_eq(comp.recording_rect(), Some(@scene.Rect::new(0, 0, 1280, 720)))
// Run the loop for a little over a second. // Run the loop for a little over a second, the pointer moving all the while: each step a
// changed picture, so frames are taken as often as the recorder allows.
let t0 = @sys.monotonic_ms() let t0 = @sys.monotonic_ms()
let mut i = 0
while @sys.monotonic_ms() - t0 < 1500UL { while @sys.monotonic_ms() - t0 < 1500UL {
i = i + 1
comp.handle_input(@nested.InputEvent::PointerMove((300 + i % 400).to_double(), 300.0), 50U + i.reinterpret_as_uint())
comp.step() comp.step()
ignore(comp.compose_frame()) ignore(comp.compose_frame())
@sys.sleep_ms(10) @sys.sleep_ms(5)
} }
assert_true(comp.recorded_frames() >= 5) let frames = comp.recorded_frames()
let elapsed = @sys.monotonic_ms() - t0
// Never more than 60 a second, and not far under it either.
assert_true(frames.to_uint64() <= elapsed * 60UL / 1000UL + 2UL)
assert_true(frames >= 20)
// A click on the pill stops it; ffmpeg then finishes the file. // A click on the pill stops it; ffmpeg then finishes the file.
click_at(comp, 640, 15, 100U) click_at(comp, 640, 15, 100U)
assert_false(comp.recording()) assert_false(comp.recording())
@@ -178,14 +240,21 @@ test "super+alt+r records the screen to a video with ffmpeg; the REC pill stops
@sys.sleep_ms(50) @sys.sleep_ms(50)
} }
assert_true(size > 1000) assert_true(size > 1000)
// Constant 60 fps, as long as the recording ran (the frames carry their own times).
let probe = run_capture(
"ffprobe -v error -select_streams v -show_entries stream=r_frame_rate,duration -of csv=p=0 '" + path + "'",
"dur",
)
let parts = probe.trim_space().split(",").collect()
assert_eq(parts[0].to_string(), "60/1")
let dur_ms = (@string.parse_double(parts[1]) * 1000.0).to_int()
assert_true(dur_ms > 1200 && dur_ms < 2200)
} }
///| ///|
test "super+shift+r records a region picked on the overlay" { test "super+shift+r records a region picked on the overlay" {
need_ffmpeg()
let (comp, _) = shot_comp("recregion") let (comp, _) = shot_comp("recregion")
if !@sys.has_exe("ffmpeg") {
return
}
chord(comp, [125U, 42U], 65U, 19U, 1U) chord(comp, [125U, 42U], 65U, 19U, 1U)
assert_true(comp.screenshot_active()) assert_true(comp.screenshot_active())
drag(comp, 100, 100, 301, 251, 10U) drag(comp, 100, 100, 301, 251, 10U)
+4 -3
View File
@@ -102,13 +102,14 @@ pub fn write_frame_png(path : String) -> Bool {
@hostraster.write_frame_png(path) @hostraster.write_frame_png(path)
} }
///| Copy `r` of the host framebuffer into the host's recording frame (pointer drawn at screen ///| Queue a copy of `r` of the host framebuffer for the recording, stamped with the host's clock
/// position (`px`, `py`) when `pointer`). /// (pointer drawn at screen position (`px`, `py`) when `pointer`). False when the queue is full.
pub fn grab_recording_frame(r : @scene.Rect, pointer : Bool, px : Int, py : Int) -> Bool { pub fn grab_recording_frame(r : @scene.Rect, pointer : Bool, px : Int, py : Int) -> Bool {
@hostraster.grab_recording_frame(r.x, r.y, r.w, r.h, pointer, px, py) @hostraster.grab_recording_frame(r.x, r.y, r.w, r.h, pointer, px, py)
} }
///| Write what is left of the recording frame to `fd`: the bytes still left, or -1. ///| Keep the host's recording writer sending to `fd` (frames queued, or -1 once a write failed);
/// a negative `fd` sends what is queued and stops it (0, or -1).
pub fn send_recording_frame(fd : Int) -> Int { pub fn send_recording_frame(fd : Int) -> Int {
@hostraster.send_recording_frame(fd) @hostraster.send_recording_frame(fd)
} }
+161 -31
View File
@@ -56,9 +56,9 @@ struct State {
pl: Option<plasmoid::Runtime>, pl: Option<plasmoid::Runtime>,
/// Fds beyond the first that arrived with the last `recvmsg` on a socket, for `take-fd`. /// 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>>, 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. /// The screen recording's frame queue and writer thread (`grab-recording-frame`,
rec_frame: Vec<u8>, /// `send-recording-frame`).
rec_sent: usize, rec: Recorder,
/// The frozen screen of a screenshot (`snapshot-frame`): RGBA8888, its width and height. /// The frozen screen of a screenshot (`snapshot-frame`): RGBA8888, its width and height.
snap: Vec<u8>, snap: Vec<u8>,
snap_w: i32, 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 { if w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fw || y + h > fh {
return false; return false;
} }
let Some(mut out) = self.rec.free_slot() else { return false };
let (w, h) = (w as usize, h as usize); let (w, h) = (w as usize, h as usize);
let mut out = std::mem::take(&mut self.rec_frame);
out.clear(); 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 { for row in 0..h {
let at = ((y as usize + row) * fw as usize + x as usize) * 4; let at = ((y as usize + row) * fw as usize + x as usize) * 4;
out.extend_from_slice(&self.raster.fb[at..at + w * 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; *a = 255;
} }
if pointer { 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.queue(out);
self.rec_sent = 0;
true true
} }
fn send_recording_frame(&mut self, fd: i32) -> i32 { fn send_recording_frame(&mut self, fd: i32) -> i32 {
unsafe { if fd >= 0 { self.rec.run(fd) } else { self.rec.finish() }
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
} }
fn snapshot_frame(&mut self) -> bool { 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 /// 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. /// 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) { fn draw_record_pointer(px: &mut [u8], w: i32, h: i32, x: i32, y: i32) {
+7 -5
View File
@@ -644,9 +644,10 @@ pub fn write_frame_png(path : String) -> Bool {
} }
///| ///|
/// Screen recording, without the pixels crossing into the component: copy the framebuffer's /// Screen recording, without the pixels crossing into the component: copy the framebuffer's
/// `x`, `y`, `w` x `h` (on screen) into the host's recording frame as opaque RGBA8888, with an /// `x`, `y`, `w` x `h` (on screen) into the host's recording queue as opaque RGBA8888, with an
/// arrow pointer drawn at screen position (`px`, `py`) when `pointer`. It replaces a frame /// arrow pointer drawn at screen position (`px`, `py`) when `pointer`, as a Matroska cluster
/// still being sent. False when the rectangle is not on screen. /// stamped with the host's monotonic clock in ms. False when the rectangle is not on screen or
/// the queue is full (the encoder is behind).
pub fn grab_recording_frame(x : Int, y : Int, w : Int, h : Int, pointer : Bool, px : Int, py : Int) -> Bool { pub fn grab_recording_frame(x : Int, y : Int, w : Int, h : Int, pointer : Bool, px : Int, py : Int) -> Bool {
let result : Int = wasmImportGrabRecordingFrame(x, y, w, h, if pointer { 1 } else { 0 }, px, py); let result : Int = wasmImportGrabRecordingFrame(x, y, w, h, if pointer { 1 } else { 0 }, px, py);
@@ -655,8 +656,9 @@ pub fn grab_recording_frame(x : Int, y : Int, w : Int, h : Int, pointer : Bool,
} }
///| ///|
/// Write what is left of the recording frame to `fd` (a socket; made non-blocking): the bytes /// fd >= 0: the host's writer thread sends the queue to `fd` (a socket, after the stream
/// still left after this (0: it all went out), or -1 when the write failed. /// header; started on the first call): the frames still queued, or -1 once a write failed.
/// fd < 0: send what is queued and stop the writer: 0, or -1 when a write failed.
pub fn send_recording_frame(fd : Int) -> Int { pub fn send_recording_frame(fd : Int) -> Int {
let result : Int = wasmImportSendRecordingFrame(fd); let result : Int = wasmImportSendRecordingFrame(fd);
+140 -18
View File
@@ -11,6 +11,8 @@
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <math.h> #include <math.h>
#include <poll.h>
#include <pthread.h>
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@@ -990,10 +992,22 @@ void rs_present_kms(void) {
kms_damage = (Box){ 0, 0, 0, 0 }; kms_damage = (Box){ 0, 0, 0, 0 };
} }
/* ---- screen recording: the frame in flight stays here ---- */ /* ---- screen recording: a short queue of frames and a writer thread ----
* rs_grab_recording copies a frame into a free slot (a Matroska Cluster header with the time it
* was taken, then the pixels; recorder.mbt's mkv_frame_header writes the same 42 bytes) and the
* writer thread sends the slots to ffmpeg's socket in order, so a frame never waits on the main
* loop. A full queue means ffmpeg is behind: that frame is not taken. */
#define REC_SLOTS 3
#define REC_HEAD 42
static uint8_t *rec_slot[REC_SLOTS];
static size_t rec_cap[REC_SLOTS], rec_size[REC_SLOTS];
static int rec_first, rec_count; /* the queue: slots rec_first.. (mod REC_SLOTS), rec_count of them */
static int rec_fd = -1, rec_running, rec_stop, rec_failed;
static pthread_t rec_thread;
static pthread_mutex_t rec_mu = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t rec_cv = PTHREAD_COND_INITIALIZER;
static uint8_t *rec_px; static uint8_t *rec_px;
static size_t rec_len, rec_sent;
static void rec_fill(int32_t w, int32_t h, int32_t x, int32_t y, int32_t rw, int32_t rh, uint8_t v) { static void rec_fill(int32_t w, int32_t h, int32_t x, int32_t y, int32_t rw, int32_t rh, uint8_t v) {
for (int32_t j = imax(y, 0); j < imin(y + rh, h); j++) for (int32_t j = imax(y, 0); j < imin(y + rh, h); j++)
@@ -1016,33 +1030,141 @@ static void rec_pointer(int32_t w, int32_t h, int32_t x, int32_t y) {
} }
} }
/* An EBML ID and an 8-byte size. */
static uint8_t *rec_id_size(uint8_t *o, const uint8_t *id, int idn, uint64_t n) {
memcpy(o, id, idn); o += idn;
*o++ = 0x01;
for (int i = 6; i >= 0; i--) *o++ = (uint8_t)(n >> (i * 8));
return o;
}
static void rec_frame_header(uint8_t *o, uint64_t ms, size_t n) {
static const uint8_t cluster[] = { 0x1f, 0x43, 0xb6, 0x75 }, tc[] = { 0xe7 }, block[] = { 0xa3 };
o = rec_id_size(o, cluster, 4, 30 + n);
o = rec_id_size(o, tc, 1, 8);
for (int i = 7; i >= 0; i--) *o++ = (uint8_t)(ms >> (i * 8));
o = rec_id_size(o, block, 1, 4 + n);
o[0] = 0x81; o[1] = 0; o[2] = 0; o[3] = 0x80;
}
static uint64_t rec_now_ms(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
}
/* Write all of buf; ffmpeg not taking anything for 5 s counts as a failure (so stopping never
* hangs on a stuck encoder). */
static int rec_write_all(int fd, const uint8_t *buf, size_t len) {
size_t done = 0;
while (done < len) {
ssize_t w = send(fd, buf + done, len - done, MSG_NOSIGNAL);
if (w < 0 && errno == ENOTSOCK) w = write(fd, buf + done, len - done);
if (w < 0) {
if (errno == EINTR) continue;
if (errno == EAGAIN || errno == EWOULDBLOCK) {
struct pollfd p = { .fd = fd, .events = POLLOUT };
int r = poll(&p, 1, 5000);
if (r < 0 && errno == EINTR) continue;
if (r <= 0) { fprintf(stderr, "recording: ffmpeg took nothing for 5 s\n"); return -1; }
continue;
}
fprintf(stderr, "recording: writing to ffmpeg failed: %s\n", strerror(errno));
return -1;
}
done += (size_t)w;
}
return 0;
}
static void *rec_writer(void *arg) {
(void)arg;
pthread_mutex_lock(&rec_mu);
for (;;) {
while (rec_count == 0 && !rec_stop) pthread_cond_wait(&rec_cv, &rec_mu);
if (rec_count == 0) break; /* stopping, and all of it went out */
int i = rec_first;
pthread_mutex_unlock(&rec_mu);
int bad = rec_write_all(rec_fd, rec_slot[i], rec_size[i]) < 0;
pthread_mutex_lock(&rec_mu);
if (bad) { rec_failed = 1; break; }
rec_first = (rec_first + 1) % REC_SLOTS;
rec_count--;
}
pthread_mutex_unlock(&rec_mu);
return NULL;
}
int32_t rs_grab_recording(int32_t x, int32_t y, int32_t w, int32_t h, int32_t pointer, int32_t px, int32_t py) { int32_t rs_grab_recording(int32_t x, int32_t y, int32_t w, int32_t h, int32_t pointer, int32_t px, int32_t py) {
if (!fb || w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fb_w || y + h > fb_h) return 0; if (!fb || w <= 0 || h <= 0 || x < 0 || y < 0 || x + w > fb_w || y + h > fb_h) return 0;
pthread_mutex_lock(&rec_mu);
int full = rec_count == REC_SLOTS || rec_failed;
int i = (rec_first + rec_count) % REC_SLOTS;
pthread_mutex_unlock(&rec_mu);
if (full) return 0;
/* Slot i is not in the queue, so the writer doesn't touch it while it is filled. */
size_t n = (size_t)w * h * 4; size_t n = (size_t)w * h * 4;
if (n != rec_len) { free(rec_px); rec_px = malloc(n); rec_len = n; } if (rec_cap[i] < REC_HEAD + n) {
for (int32_t j = 0; j < h; j++) memcpy(rec_px + (size_t)j * w * 4, fb + ((size_t)(y + j) * fb_w + x) * 4, (size_t)w * 4); free(rec_slot[i]);
for (size_t i = 3; i < n; i += 4) rec_px[i] = 0xff; rec_slot[i] = malloc(REC_HEAD + n);
if (!rec_slot[i]) { rec_cap[i] = 0; fprintf(stderr, "recording: out of memory for a frame\n"); return 0; }
rec_cap[i] = REC_HEAD + n;
}
rec_frame_header(rec_slot[i], rec_now_ms(), n);
rec_px = rec_slot[i] + REC_HEAD;
/* Copy and make opaque in one pass (alpha is the high byte of each little-endian pixel). */
for (int32_t j = 0; j < h; j++) {
const uint8_t *src = fb + ((size_t)(y + j) * fb_w + x) * 4;
uint8_t *dst = rec_px + (size_t)j * w * 4;
for (int32_t k = 0; k < w; k++) {
uint32_t v;
memcpy(&v, src + (size_t)k * 4, 4);
v |= 0xff000000u;
memcpy(dst + (size_t)k * 4, &v, 4);
}
}
if (pointer) rec_pointer(w, h, px - x, py - y); if (pointer) rec_pointer(w, h, px - x, py - y);
rec_sent = 0; rec_size[i] = REC_HEAD + n;
pthread_mutex_lock(&rec_mu);
rec_count++;
pthread_cond_signal(&rec_cv);
pthread_mutex_unlock(&rec_mu);
return 1; return 1;
} }
/* fd >= 0: the writer sends to fd (started on the first call): the frames still queued, or -1
* once a write failed. fd < 0: send what is queued, stop the writer (0, or -1 when it failed). */
int32_t rs_send_recording(int32_t fd) { int32_t rs_send_recording(int32_t fd) {
if (!rec_px) return 0; if (fd >= 0) {
int fl = fcntl(fd, F_GETFL); if (!rec_running) {
if (fl >= 0 && !(fl & O_NONBLOCK)) fcntl(fd, F_SETFL, fl | O_NONBLOCK); rec_fd = fd; rec_stop = 0; rec_failed = 0; rec_first = 0; rec_count = 0;
while (rec_sent < rec_len) { int fl = fcntl(fd, F_GETFL);
ssize_t w = send(fd, rec_px + rec_sent, rec_len - rec_sent, MSG_NOSIGNAL); if (fl >= 0 && !(fl & O_NONBLOCK)) fcntl(fd, F_SETFL, fl | O_NONBLOCK);
if (w < 0 && errno == ENOTSOCK) w = write(fd, rec_px + rec_sent, rec_len - rec_sent); if (pthread_create(&rec_thread, NULL, rec_writer, NULL) != 0) {
if (w < 0) { fprintf(stderr, "recording: can't start the writer thread\n");
if (errno == EINTR) continue; return -1;
if (errno == EAGAIN || errno == EWOULDBLOCK) break; }
rec_running = 1;
} else if (fd != rec_fd) {
fprintf(stderr, "recording: a second stream while one is running\n");
return -1; return -1;
} }
rec_sent += (size_t)w; pthread_mutex_lock(&rec_mu);
int32_t r = rec_failed ? -1 : rec_count;
pthread_mutex_unlock(&rec_mu);
return r;
} }
size_t left = rec_len - rec_sent; if (!rec_running) return 0;
return left > 0x7fffffff ? 0x7fffffff : (int32_t)left; pthread_mutex_lock(&rec_mu);
rec_stop = 1;
pthread_cond_signal(&rec_cv);
pthread_mutex_unlock(&rec_mu);
pthread_join(rec_thread, NULL);
rec_running = 0;
rec_fd = -1;
int32_t r = rec_failed ? -1 : 0;
rec_count = 0;
return r;
} }
/* ---- screenshots: the frozen screen stays here ---- */ /* ---- screenshots: the frozen screen stays here ---- */
+7 -5
View File
@@ -77,12 +77,14 @@ interface raster {
/// host. False when it can't be written. /// host. False when it can't be written.
write-frame-png: func(path: string) -> bool; write-frame-png: func(path: string) -> bool;
/// Screen recording, without the pixels crossing into the component: copy the framebuffer's /// Screen recording, without the pixels crossing into the component: copy the framebuffer's
/// `x`, `y`, `w` x `h` (on screen) into the host's recording frame as opaque RGBA8888, with an /// `x`, `y`, `w` x `h` (on screen) into the host's recording queue as opaque RGBA8888, with an
/// arrow pointer drawn at screen position (`px`, `py`) when `pointer`. It replaces a frame /// arrow pointer drawn at screen position (`px`, `py`) when `pointer`, as a Matroska cluster
/// still being sent. False when the rectangle is not on screen. /// stamped with the host's monotonic clock in ms. False when the rectangle is not on screen or
/// the queue is full (the encoder is behind).
grab-recording-frame: func(x: s32, y: s32, w: s32, h: s32, pointer: bool, px: s32, py: s32) -> bool; grab-recording-frame: func(x: s32, y: s32, w: s32, h: s32, pointer: bool, px: s32, py: s32) -> bool;
/// Write what is left of the recording frame to `fd` (a socket; made non-blocking): the bytes /// fd >= 0: the host's writer thread sends the queue to `fd` (a socket, after the stream
/// still left after this (0: it all went out), or -1 when the write failed. /// header; started on the first call): the frames still queued, or -1 once a write failed.
/// fd < 0: send what is queued and stop the writer: 0, or -1 when a write failed.
send-recording-frame: func(fd: s32) -> s32; send-recording-frame: func(fd: s32) -> s32;
/// Screenshots, without the whole screen crossing into the component: freeze the framebuffer /// Screenshots, without the whole screen crossing into the component: freeze the framebuffer
/// on the host as the snapshot (replacing the last one). False when there is no framebuffer. /// on the host as the snapshot (replacing the last one). False when there is no framebuffer.