1#![allow(
23 clippy::cast_possible_truncation,
24 clippy::cast_sign_loss,
25 clippy::cast_precision_loss,
26 clippy::cast_lossless,
27 clippy::too_many_arguments,
28 clippy::many_single_char_names,
29 clippy::map_unwrap_or
30)]
31
32use std::io::{Seek as _, Write};
33use std::path::Path;
34
35use rav1e::config::SpeedSettings;
36use rav1e::prelude::*;
37
38#[derive(Debug, thiserror::Error)]
39pub enum RecordError {
40 #[error("rav1e: {0}")]
41 Encode(String),
42 #[error("frame size {got:?} does not match recording size {want:?}")]
43 SizeMismatch {
44 got: (usize, usize),
45 want: (usize, usize),
46 },
47 #[error("bad frame: {0}")]
48 Frame(&'static str),
49 #[error("png decode: {0}")]
50 Png(#[from] image::ImageError),
51 #[error("io: {0}")]
52 Io(#[from] std::io::Error),
53}
54
55type Result<T> = std::result::Result<T, RecordError>;
56
57pub fn png_dimensions(png: &[u8]) -> Result<(usize, usize)> {
60 let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
61 Ok((img.width() as usize, img.height() as usize))
62}
63
64pub fn png_to_scaled_rgb(png: &[u8], max_width: u32) -> Result<(usize, usize, Vec<u8>)> {
71 let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
72 let img = if img.width() > max_width && max_width > 0 {
73 let h = u64::from(max_width) * u64::from(img.height()) / u64::from(img.width());
74 let h = u32::try_from(h).unwrap_or(u32::MAX).max(1);
75 img.resize_exact(max_width, h, image::imageops::FilterType::Triangle)
76 } else {
77 img
78 };
79 let rgb = img.to_rgb8();
80 Ok((rgb.width() as usize, rgb.height() as usize, rgb.into_raw()))
81}
82
83const ARROW: [(f64, f64); 7] = [
90 (0.0, 0.0),
91 (0.0, 15.6),
92 (3.6, 12.1),
93 (5.7, 17.4),
94 (7.7, 16.6),
95 (5.6, 11.2),
96 (10.2, 11.0),
97];
98const ARROW_H: f64 = 15.6;
100
101fn blend_px(rgb: &mut [u8], w: usize, h: usize, px: i64, py: i64, r: u8, g: u8, b: u8, alpha: f64) {
103 if px < 0 || py < 0 || px as usize >= w || py as usize >= h || alpha <= 0.0 {
104 return;
105 }
106 let a = alpha.clamp(0.0, 1.0);
107 let i = (py as usize * w + px as usize) * 3;
108 rgb[i] = (f64::from(r) * a + f64::from(rgb[i]) * (1.0 - a)) as u8;
109 rgb[i + 1] = (f64::from(g) * a + f64::from(rgb[i + 1]) * (1.0 - a)) as u8;
110 rgb[i + 2] = (f64::from(b) * a + f64::from(rgb[i + 2]) * (1.0 - a)) as u8;
111}
112
113fn in_poly(px: f64, py: f64, pts: &[(f64, f64)]) -> bool {
115 let mut inside = false;
116 let n = pts.len();
117 let mut j = n - 1;
118 for i in 0..n {
119 let (xi, yi) = pts[i];
120 let (xj, yj) = pts[j];
121 if (yi > py) != (yj > py) && px < (xj - xi) * (py - yi) / (yj - yi) + xi {
122 inside = !inside;
123 }
124 j = i;
125 }
126 inside
127}
128
129fn coverage(px: i64, py: i64, pts: &[(f64, f64)]) -> f64 {
132 let mut hit = 0u32;
133 for sy in 0..4 {
134 for sx in 0..4 {
135 let x = px as f64 + (sx as f64 + 0.5) / 4.0;
136 let y = py as f64 + (sy as f64 + 0.5) / 4.0;
137 if in_poly(x, y, pts) {
138 hit += 1;
139 }
140 }
141 }
142 f64::from(hit) / 16.0
143}
144
145fn draw_click_ring(rgb: &mut [u8], w: usize, h: usize, cx: f64, cy: f64, phase: f32, scale: f64) {
148 let phase = f64::from(phase);
149 let base = 13.0 * scale;
150 let radius = base * (1.7 - phase);
151 let thickness = 2.2 * scale;
152 let alpha = phase * 0.6;
153 let lo = radius - thickness;
154 let hi = radius + thickness;
155 let x0 = (cx - hi).floor() as i64;
156 let x1 = (cx + hi).ceil() as i64;
157 let y0 = (cy - hi).floor() as i64;
158 let y1 = (cy + hi).ceil() as i64;
159 for py in y0..=y1 {
160 for px in x0..=x1 {
161 let dx = px as f64 + 0.5 - cx;
162 let dy = py as f64 + 0.5 - cy;
163 let d = (dx * dx + dy * dy).sqrt();
164 if d >= lo && d <= hi {
165 let edge = 1.0 - ((d - radius).abs() / thickness);
166 blend_px(rgb, w, h, px, py, 66, 133, 244, alpha * edge.max(0.0));
167 }
168 }
169 }
170}
171
172fn draw_arrow(rgb: &mut [u8], w: usize, h: usize, cx: f64, cy: f64, scale: f64) {
175 let fill: Vec<(f64, f64)> = ARROW
177 .iter()
178 .map(|&(x, y)| (cx + x * scale, cy + y * scale))
179 .collect();
180 let (mut mx, mut my) = (0.0, 0.0);
182 for &(x, y) in &fill {
183 mx += x;
184 my += y;
185 }
186 mx /= fill.len() as f64;
187 my /= fill.len() as f64;
188 let grow = 1.05 / (ARROW_H * scale); let border: Vec<(f64, f64)> = fill
190 .iter()
191 .map(|&(x, y)| (x + (x - mx) * grow, y + (y - my) * grow))
192 .collect();
193 let shadow: Vec<(f64, f64)> = border.iter().map(|&(x, y)| (x + 0.9, y + 1.2)).collect();
194
195 let pad = 3.0 * scale + 3.0;
196 let x0 = (cx - pad).floor() as i64;
197 let x1 = (cx + 13.0 * scale + pad).ceil() as i64;
198 let y0 = (cy - pad).floor() as i64;
199 let y1 = (cy + 20.0 * scale + pad).ceil() as i64;
200 for py in y0..=y1 {
201 for px in x0..=x1 {
202 let cs = coverage(px, py, &shadow);
203 if cs > 0.0 {
204 blend_px(rgb, w, h, px, py, 0, 0, 0, cs * 0.22);
205 }
206 let cb = coverage(px, py, &border);
207 if cb > 0.0 {
208 blend_px(rgb, w, h, px, py, 30, 30, 32, cb);
209 }
210 let cf = coverage(px, py, &fill);
211 if cf > 0.0 {
212 blend_px(rgb, w, h, px, py, 252, 252, 252, cf);
213 }
214 }
215 }
216}
217
218pub fn composite_cursor(rgb: &mut [u8], w: usize, h: usize, x: f64, y: f64, click: f32) {
222 let scale = (w as f64 / 1440.0 * 1.15).max(1.0);
224 if click > 0.0 {
225 draw_click_ring(rgb, w, h, x, y, click, scale);
226 }
227 draw_arrow(rgb, w, h, x, y, scale);
228}
229
230enum Sink {
234 File {
235 writer: std::io::BufWriter<std::fs::File>,
236 frames: u32,
237 },
238 Mem(Vec<Vec<u8>>),
239}
240
241fn ivf_header(width: usize, height: usize, fps: u32, frame_count: u32) -> [u8; 32] {
244 let mut h = [0u8; 32];
245 h[0..4].copy_from_slice(b"DKIF");
246 h[6..8].copy_from_slice(&32u16.to_le_bytes()); h[8..12].copy_from_slice(b"AV01");
248 h[12..14].copy_from_slice(&u16::try_from(width).unwrap_or(0).to_le_bytes());
249 h[14..16].copy_from_slice(&u16::try_from(height).unwrap_or(0).to_le_bytes());
250 h[16..20].copy_from_slice(&fps.max(1).to_le_bytes()); h[20..24].copy_from_slice(&1u32.to_le_bytes()); h[24..28].copy_from_slice(&frame_count.to_le_bytes());
253 h
254}
255
256fn write_frame_record(out: &mut impl Write, pkt: &[u8], ts: u64) -> std::io::Result<()> {
258 out.write_all(&u32::try_from(pkt.len()).unwrap_or(0).to_le_bytes())?;
259 out.write_all(&ts.to_le_bytes())?;
260 out.write_all(pkt)
261}
262
263pub struct Recorder {
265 width: usize,
266 height: usize,
267 fps: u32,
268 ctx: Context<u8>,
269 sink: Sink,
270}
271
272impl Recorder {
273 fn build_ctx(
274 width: usize,
275 height: usize,
276 fps: u32,
277 speed: u8,
278 ) -> Result<(usize, usize, Context<u8>)> {
279 let width = width & !1;
280 let height = height & !1;
281 if width == 0 || height == 0 {
282 return Err(RecordError::Frame("zero-sized recording"));
283 }
284 let mut speed_settings = SpeedSettings::from_preset(speed.min(10));
291 speed_settings.rdo_lookahead_frames = 1;
292 let enc = EncoderConfig {
299 width,
300 height,
301 time_base: Rational::new(1, u64::from(fps.max(1))),
302 chroma_sampling: ChromaSampling::Cs420,
303 low_latency: true,
304 tile_cols: 2,
305 tile_rows: 2,
306 quantizer: 70,
310 speed_settings,
311 ..Default::default()
312 };
313 let threads = std::thread::available_parallelism()
314 .map(|n| n.get().saturating_sub(1).clamp(2, 8))
315 .unwrap_or(4);
316 let cfg = Config::new().with_encoder_config(enc).with_threads(threads);
317 let ctx: Context<u8> = cfg
318 .new_context()
319 .map_err(|e| RecordError::Encode(format!("{e:?}")))?;
320 Ok((width, height, ctx))
321 }
322
323 pub fn new(width: usize, height: usize, fps: u32, speed: u8) -> Result<Self> {
328 let (width, height, ctx) = Self::build_ctx(width, height, fps, speed)?;
329 Ok(Self {
330 width,
331 height,
332 fps,
333 ctx,
334 sink: Sink::Mem(Vec::new()),
335 })
336 }
337
338 pub fn create(
343 path: &std::path::Path,
344 width: usize,
345 height: usize,
346 fps: u32,
347 speed: u8,
348 ) -> Result<Self> {
349 let (width, height, ctx) = Self::build_ctx(width, height, fps, speed)?;
350 let mut f = std::fs::File::create(path)?;
351 f.write_all(&ivf_header(width, height, fps, 0))?;
352 Ok(Self {
353 width,
354 height,
355 fps,
356 ctx,
357 sink: Sink::File {
358 writer: std::io::BufWriter::new(f),
359 frames: 0,
360 },
361 })
362 }
363
364 pub fn push_png(&mut self, png: &[u8]) -> Result<()> {
366 let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)?;
367 let rgb = img.to_rgb8();
368 self.push_rgb(rgb.width() as usize, rgb.height() as usize, &rgb)
369 }
370
371 pub fn push_rgb(&mut self, w: usize, h: usize, rgb: &[u8]) -> Result<()> {
373 if w < self.width || h < self.height {
376 return Err(RecordError::SizeMismatch {
377 got: (w, h),
378 want: (self.width, self.height),
379 });
380 }
381 if rgb.len() < w * h * 3 {
382 return Err(RecordError::Frame("rgb buffer too small"));
383 }
384 let mut frame = self.ctx.new_frame();
385 let (yp, up, vp) = rgb_to_yuv420(rgb, w, self.width, self.height);
386 frame.planes[0].copy_from_raw_u8(&yp, self.width, 1);
387 frame.planes[1].copy_from_raw_u8(&up, self.width / 2, 1);
388 frame.planes[2].copy_from_raw_u8(&vp, self.width / 2, 1);
389
390 self.ctx
391 .send_frame(frame)
392 .map_err(|e| RecordError::Encode(format!("send_frame: {e:?}")))?;
393 self.drain()
394 }
395
396 fn drain(&mut self) -> Result<()> {
400 loop {
401 match self.ctx.receive_packet() {
402 Ok(pkt) => match &mut self.sink {
403 Sink::File { writer, frames } => {
404 write_frame_record(writer, &pkt.data, u64::from(*frames))?;
405 *frames += 1;
406 }
407 Sink::Mem(packets) => packets.push(pkt.data),
408 },
409 Err(EncoderStatus::Encoded) => {}
410 Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
411 Err(e) => return Err(RecordError::Encode(format!("receive_packet: {e:?}"))),
412 }
413 }
414 }
415
416 pub fn finish(mut self) -> Result<()> {
419 self.ctx.flush();
420 self.drain()?;
421 match self.sink {
422 Sink::File { writer, frames } => {
423 let mut f = writer
424 .into_inner()
425 .map_err(std::io::IntoInnerError::into_error)?;
426 f.seek(std::io::SeekFrom::Start(24))?;
427 f.write_all(&frames.to_le_bytes())?;
428 f.flush()?;
429 Ok(())
430 }
431 Sink::Mem(_) => Err(RecordError::Frame(
432 "finish() on an in-memory recorder; use finish_to_vec",
433 )),
434 }
435 }
436
437 pub fn finish_to_vec(mut self) -> Result<Vec<u8>> {
439 self.ctx.flush();
440 self.drain()?;
441 match self.sink {
442 Sink::Mem(packets) => {
443 let mut out = Vec::new();
444 out.extend_from_slice(&ivf_header(
445 self.width,
446 self.height,
447 self.fps,
448 u32::try_from(packets.len()).unwrap_or(0),
449 ));
450 for (i, pkt) in packets.iter().enumerate() {
451 write_frame_record(&mut out, pkt, i as u64)?;
452 }
453 Ok(out)
454 }
455 Sink::File { .. } => Err(RecordError::Frame(
456 "finish_to_vec() on a file recorder; use finish",
457 )),
458 }
459 }
460}
461
462#[allow(clippy::many_single_char_names)]
465#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
468fn rgb_to_yuv420(rgb: &[u8], src_w: usize, w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
469 let mut y = vec![0u8; w * h];
470 let mut u = vec![0u8; (w / 2) * (h / 2)];
471 let mut v = vec![0u8; (w / 2) * (h / 2)];
472 let px = |x: usize, row: usize| -> (f32, f32, f32) {
473 let idx = (row * src_w + x) * 3;
474 (
475 f32::from(rgb[idx]),
476 f32::from(rgb[idx + 1]),
477 f32::from(rgb[idx + 2]),
478 )
479 };
480 let clamp = |val: f32| -> u8 { val.round().clamp(0.0, 255.0) as u8 };
481 for row in 0..h {
482 for x in 0..w {
483 let (r, g, b) = px(x, row);
484 y[row * w + x] = clamp(0.257 * r + 0.504 * g + 0.098 * b + 16.0);
485 }
486 }
487 for cy in 0..h / 2 {
488 for cx in 0..w / 2 {
489 let mut rs = 0.0;
491 let mut gs = 0.0;
492 let mut bs = 0.0;
493 for dy in 0..2 {
494 for dx in 0..2 {
495 let (r, g, b) = px(cx * 2 + dx, cy * 2 + dy);
496 rs += r;
497 gs += g;
498 bs += b;
499 }
500 }
501 let (r, g, b) = (rs / 4.0, gs / 4.0, bs / 4.0);
502 u[cy * (w / 2) + cx] = clamp(-0.148 * r - 0.291 * g + 0.439 * b + 128.0);
503 v[cy * (w / 2) + cx] = clamp(0.439 * r - 0.368 * g - 0.071 * b + 128.0);
504 }
505 }
506 (y, u, v)
507}
508
509pub struct H264Recorder {
516 enc: openh264::encoder::Encoder,
517 width: usize,
518 height: usize,
519 frame_ms: u32,
522 fps: f64,
523 path: std::path::PathBuf,
524 muxer: Option<muxide::api::Muxer<std::io::BufWriter<std::fs::File>>>,
525}
526
527impl H264Recorder {
528 pub fn create(path: &Path, width: usize, height: usize, fps: u32) -> Result<Self> {
532 use openh264::encoder::{BitRate, EncoderConfig, FrameRate, UsageType};
533 let width = width & !1;
534 let height = height & !1;
535 if width == 0 || height == 0 {
536 return Err(RecordError::Frame("zero-sized recording"));
537 }
538 let fps = fps.max(1);
539 #[allow(clippy::cast_possible_truncation)]
542 let bitrate = ((width as u64 * height as u64 * u64::from(fps)) / 5)
543 .clamp(1_000_000, 12_000_000) as u32;
544 let config = EncoderConfig::new()
545 .usage_type(UsageType::ScreenContentRealTime)
547 .max_frame_rate(FrameRate::from_hz(fps as f32))
548 .bitrate(BitRate::from_bps(bitrate));
549 let enc = openh264::encoder::Encoder::with_api_config(
550 openh264::OpenH264API::from_source(),
551 config,
552 )
553 .map_err(|e| RecordError::Encode(format!("openh264 init: {e:?}")))?;
554 Ok(Self {
555 enc,
556 width,
557 height,
558 frame_ms: 1000 / fps,
559 fps: f64::from(fps),
560 path: path.to_path_buf(),
561 muxer: None,
562 })
563 }
564
565 pub fn push_rgb(&mut self, w: usize, h: usize, rgb: &[u8]) -> Result<()> {
569 use openh264::formats::{RgbSliceU8, YUVBuffer};
570 if w < self.width || h < self.height {
571 return Err(RecordError::SizeMismatch {
572 got: (w, h),
573 want: (self.width, self.height),
574 });
575 }
576 if rgb.len() < w * h * 3 {
577 return Err(RecordError::Frame("rgb buffer too small"));
578 }
579 let cropped;
581 let src: &[u8] = if w == self.width && h == self.height {
582 rgb
583 } else {
584 let mut out = Vec::with_capacity(self.width * self.height * 3);
585 for row in 0..self.height {
586 let start = row * w * 3;
587 out.extend_from_slice(&rgb[start..start + self.width * 3]);
588 }
589 cropped = out;
590 &cropped
591 };
592 let yuv = YUVBuffer::from_rgb8_source(RgbSliceU8::new(src, (self.width, self.height)));
593 let bitstream = self
594 .enc
595 .encode(&yuv)
596 .map_err(|e| RecordError::Encode(format!("openh264 encode: {e:?}")))?;
597 let annexb = bitstream.to_vec();
598 if annexb.is_empty() {
600 return Ok(());
601 }
602 if self.muxer.is_none() {
603 let cfg = muxide::codec::h264::extract_avc_config(&annexb)
604 .ok_or_else(|| RecordError::Encode("no SPS/PPS in first frame".into()))?;
605 let file = std::io::BufWriter::new(std::fs::File::create(&self.path)?);
606 let muxer = muxide::api::MuxerBuilder::new(file)
607 .video(
608 muxide::api::VideoCodec::H264,
609 self.width as u32,
610 self.height as u32,
611 self.fps,
612 )
613 .with_sps(cfg.sps)
614 .with_pps(cfg.pps)
615 .with_fast_start(true)
618 .build()
619 .map_err(|e| RecordError::Encode(format!("mp4 mux init: {e}")))?;
620 self.muxer = Some(muxer);
621 }
622 self.muxer
626 .as_mut()
627 .expect("muxer set above")
628 .encode_video(&annexb, self.frame_ms)
629 .map_err(|e| RecordError::Encode(format!("mp4 write: {e}")))?;
630 Ok(())
631 }
632
633 pub fn finish(mut self) -> Result<()> {
635 match self.muxer.take() {
636 Some(mut m) => m
637 .finish_in_place()
638 .map_err(|e| RecordError::Encode(format!("mp4 finish: {e}"))),
639 None => Err(RecordError::Frame("no frames encoded")),
640 }
641 }
642}
643
644#[cfg(test)]
645mod tests {
646 use super::*;
647
648 fn solid_rgb(w: usize, h: usize, c: [u8; 3]) -> Vec<u8> {
649 let mut v = Vec::with_capacity(w * h * 3);
650 for _ in 0..w * h {
651 v.extend_from_slice(&c);
652 }
653 v
654 }
655
656 #[test]
657 fn encodes_frames_to_a_valid_ivf() {
658 let (w, h) = (64, 48);
659 let mut rec = Recorder::new(w, h, 5, 9).expect("recorder");
660 for c in [[200, 30, 30], [30, 200, 30], [30, 30, 200], [220, 220, 30]] {
662 rec.push_rgb(w, h, &solid_rgb(w, h, c)).expect("push");
663 }
664 let ivf = rec.finish_to_vec().expect("finish");
665 assert_eq!(&ivf[0..4], b"DKIF", "IVF signature");
666 assert_eq!(&ivf[8..12], b"AV01", "codec fourcc");
667 let frame_count = u32::from_le_bytes(ivf[24..28].try_into().unwrap());
668 assert!(
669 frame_count >= 1,
670 "at least one encoded frame, got {frame_count}"
671 );
672 assert!(
674 ivf.len() > 32 + 12,
675 "encoded body present, got {} bytes",
676 ivf.len()
677 );
678 }
679
680 #[test]
681 fn odd_dimensions_are_rounded_even() {
682 let rec = Recorder::new(65, 49, 5, 9).expect("recorder");
683 assert_eq!((rec.width, rec.height), (64, 48));
684 }
685}