///| Screen recording, after Spectacle's recording modes. /// /// Super+Shift+R (by default; the shortcut table can rebind it) puts the selection overlay up to pick a region to record (drag a rectangle or /// click a window, Enter starts); Super+Alt+R records the whole screen; Super+Ctrl+R the window /// under the pointer. While recording, a red "REC" pill with the elapsed time sits at the top /// centre; clicking it, or any of the recording shortcuts again, stops. The pointer is drawn into /// 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 /// 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 { /// The part of the screen recorded (even width and height, as H.264 wants). rect : @scene.Rect /// Where the video goes, and the socket ffmpeg listens on. path : String sock : String /// The connection to ffmpeg (-1 until it is listening), and until when to keep trying. mut fd : Int connect_until : UInt64 started : UInt64 /// 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 /// 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 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 } ///| Whether a recording is running. pub fn ChandraCompositor::recording(self : ChandraCompositor) -> Bool { self.rec is Some(_) } ///| The region being recorded. pub fn ChandraCompositor::recording_rect(self : ChandraCompositor) -> @scene.Rect? { self.rec.map(r => r.rect) } ///| Frames sent to the encoder so far in the current recording. pub fn ChandraCompositor::recorded_frames(self : ChandraCompositor) -> Int { match self.rec { Some(r) => r.frames None => 0 } } ///| Whether recordings show the pointer. pub fn ChandraCompositor::record_pointer(self : ChandraCompositor) -> Bool { self.rec_pointer } ///| Draw the pointer into recordings, or not. pub fn ChandraCompositor::set_record_pointer(self : ChandraCompositor, on : Bool) -> Unit { self.rec_pointer = on self.damage.mark_full() } ///| Start recording in `mode` (Region opens the overlay; WindowUnderCursor asks for a click when /// no window is under the pointer); stop instead when a recording is running. pub fn ChandraCompositor::toggle_recording(self : ChandraCompositor, mode : ShotMode) -> Unit { if self.rec is Some(_) { self.stop_recording() return } if self.shot is Some(_) { return } let full = @scene.Rect::new(0, 0, self.output_w, self.output_h) match mode { FullScreen => self.start_recording(full) ActiveWindow => match self.active_window().bind(w => self.outer_rect(w)) { Some(r) => self.start_recording(r) None => self.start_recording(full) } WindowUnderCursor => match self.window_at(self.ptr_x.to_int(), self.ptr_y.to_int()).bind(w => self.outer_rect(w.0)) { Some(r) => self.start_recording(r) None => self.open_record_overlay(true) } Region => self.open_record_overlay(false) } } ///| The overlay, picking what to record. fn ChandraCompositor::open_record_overlay(self : ChandraCompositor, pick : Bool) -> Unit { match self.freeze_screen() { Some(frame) => { self.open_overlay(frame, pick) match self.shot { Some(o) => o.record = true None => () } } None => () } } ///| The user's videos folder: XDG_VIDEOS_DIR from user-dirs.dirs, else ~/Videos. fn videos_dir() -> String { match user_dir("XDG_VIDEOS_DIR") { Some(d) => d None => @sys.getenv("HOME") + "/Videos" } } ///| Start recording `r` (made even-sized and kept on screen). fn ChandraCompositor::start_recording(self : ChandraCompositor, r : @scene.Rect) -> Unit { let r = self.clip_to_screen(r) let w = r.w / 2 * 2 let h = r.h / 2 * 2 if w < 2 || h < 2 { return } if !@sys.has_exe("ffmpeg") { self.notify("Can't record the screen", "Screen recording needs ffmpeg; install it and try again") return } let dir = if self.shot_dir.length() > 0 { self.shot_dir } else { videos_dir() + "/Screencasts" } ignore(@sys.mkdir_p(dir)) let base = dir + "/Screencast_" + timestamp() let mut path = base + ".mp4" let mut n = 2 while @sys.read_file_bytes(path).length() > 0 && n < 100 { path = base + "-" + n.to_string() + ".mp4" n = n + 1 } let rt = match @sys.getenv("XDG_RUNTIME_DIR") { "" => "/tmp" d => d } let sock = rt + "/chandra-rec-" + @sys.getpid().to_string() + "-" + @sys.monotonic_ms().to_string() + ".sock" // 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") return } let now = @sys.monotonic_ms() self.rec = Some({ rect: @scene.Rect::new(r.x, r.y, w, h), path, sock, fd: -1, connect_until: now + 5000UL, started: now, header: mkv_stream_header(w, h), header_sent: 0, pending: Bytes::from_array([]), sent: 0, last_grab: 0UL, grab_px: -1, grab_py: -1, dirty: true, shown_secs: 0, frames: 0, }) self.damage.mark_full() } ///| 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 { 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. pub fn ChandraCompositor::last_recording(self : ChandraCompositor) -> String { self.last_recording } ///| m:ss. fn clock_text(secs : Int) -> String { (secs / 60).to_string() + ":" + pad2(secs % 60) } ///| A notification without a picture. fn ChandraCompositor::notify(self : ChandraCompositor, title : String, detail : String) -> Unit { self.shot_toast = Some({ title, detail, until: @sys.monotonic_ms() + 5000UL, thumb: [], tw: 0, th: 0 }) self.damage.mark_full() } ///| 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 None => return } let now = @sys.monotonic_ms() if rec.fd < 0 { rec.fd = @sys.unix_connect(rec.sock) if rec.fd < 0 { if now > rec.connect_until { self.stop_recording() } 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) => if (host.send)(rec.fd) < 0 { self.end_recording(Some("ffmpeg stopped reading the video stream")) return } 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()) } } None => () } } ///| 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 } 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 } } } 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 host's writer (wasmhost raster_stub.c) then sends /// 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). fn ChandraCompositor::grab_region(self : ChandraCompositor, r : @scene.Rect) -> @renderer.Pixmap? { let src = match self.frame_source { Some(f) => f() None => self.last_frame } match src { Some(p) => { if r.x < 0 || r.y < 0 || r.x + r.w > p.width || r.y + r.h > p.height || p.data.length() < p.width * p.height * 4 { return None } let data = FixedArray::make(r.w * r.h * 4, b'\xff') for y = 0; y < r.h; y = y + 1 { FixedArray::blit_to(p.data, data, len=r.w * 4, src_offset=((r.y + y) * p.width + r.x) * 4, dst_offset=y * r.w * 4) } for i = 3; i < data.length(); i = i + 4 { data[i] = b'\xff' } Some({ width: r.w, height: r.h, data }) } None => None } } ///| Draw an arrow pointer with its tip at (x, y): white, outlined in black. fn draw_pointer(p : @renderer.Pixmap, x : Int, y : Int) -> Unit { let ops : Array[@scene.DrawOp] = [] let black = @scene.Rgba::new(0, 0, 0, 255) let white = @scene.Rgba::new(255, 255, 255, 255) // Rows of a classic arrow: the body widens to 9 pixels over 13 rows, then a short tail. for i = 0; i < 17; i = i + 1 { let (l, w) = if i < 13 { (0, i * 2 / 3 + 1) } else { (3 + (i - 13), 3) } ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x + l - 1, y + i - 1, w + 2, 3), black, 0)) } for i = 1; i < 16; i = i + 1 { let (l, w) = if i < 13 { (0, i * 2 / 3 - 1) } else { (4 + (i - 13), 1) } if w > 0 { ops.push(@scene.DrawOp::FillRect(@scene.Rect::new(x + l + 1, y + i, w, 1), white, 0)) } } @renderer.draw_ops(p, ops, 0, 0) } ///| The REC pill (top right), and the outline of a region smaller than the screen. fn ChandraCompositor::recording_ops(self : ChandraCompositor, ops : Array[@scene.DrawOp]) -> Unit { match self.rec { Some(rec) => { let red = @scene.Rgba::new(235, 64, 52, 255) let r = rec.rect if r.w < self.output_w || r.h < self.output_h { ops.push(@scene.DrawOp::StrokeRect(@scene.Rect::new(r.x - 2, r.y - 2, r.w + 4, r.h + 4), red, 2, 0)) } let pill = self.rec_pill() let p = self.theme.palette let fs = self.theme.font_size let secs = ((@sys.monotonic_ms() - rec.started) / 1000UL).to_int() let starting = rec.fd < 0 ops.push(@scene.DrawOp::FillRect(pill, p.surface_popup, pill.h / 2)) ops.push(@scene.DrawOp::StrokeRect(pill, red, 1, pill.h / 2)) ops.push(@scene.DrawOp::Circle(pill.x + 16, pill.y + pill.h / 2, 6, red, true)) let label = if starting { "Starting…" } else { "REC " + clock_text(secs) + " Stop" } ops.push(@scene.DrawOp::Text(pill.x + 30, pill.y + pill.h / 2, label, fs - 1, p.foreground, @scene.TextAlign::Left, true)) } None => () } } ///| Where the REC pill is (it stops the recording when clicked): top centre, where title bars /// have no buttons. fn ChandraCompositor::rec_pill(self : ChandraCompositor) -> @scene.Rect { let w = 150 let h = 26 @scene.Rect::new((self.output_w - w) / 2, 3, w, h) } ///| A press on the REC pill stops the recording. True when it was one. fn ChandraCompositor::recording_click(self : ChandraCompositor, x : Int, y : Int) -> Bool { if self.rec is None { return false } let r = self.rec_pill() if x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h { self.stop_recording() true } else { false } }