use std::cell::Cell;
use std::sync::mpsc::Sender;
use objc2::MainThreadMarker;
use objc2_web_kit::WKWebView;
use super::capture::snapshot_to_png_bytes;
use crate::engine::RecFrame;
pub(super) struct RecSink {
tx: Sender<RecFrame>,
snapshot_width: f64,
scale: f64,
frame_ms: f64,
accum: Cell<f64>,
}
impl RecSink {
pub(super) fn new(tx: Sender<RecFrame>, logical_width: f64, max_width: u32, fps: u32) -> Self {
let snapshot_width = if max_width == 0 {
logical_width.max(1.0)
} else {
f64::from(max_width)
};
let scale = if logical_width > 0.0 {
snapshot_width / logical_width
} else {
1.0
};
let fps = fps.clamp(1, 30);
Self {
tx,
snapshot_width,
scale,
frame_ms: 1000.0 / f64::from(fps),
accum: Cell::new(0.0),
}
}
pub(super) fn frame(
&self,
web_view: &WKWebView,
mtm: MainThreadMarker,
x: f64,
y: f64,
click: f32,
dt_ms: u32,
) {
if let Ok(png) = snapshot_to_png_bytes(web_view, mtm, Some(self.snapshot_width)) {
let _ = self.tx.send(RecFrame {
png,
cx: x * self.scale,
cy: y * self.scale,
click,
dt_ms,
});
}
}
pub(super) fn step(
&self,
web_view: &WKWebView,
mtm: MainThreadMarker,
x: f64,
y: f64,
dt_ms: f64,
) {
let a = self.accum.get() + dt_ms;
if a >= self.frame_ms {
self.accum.set(0.0);
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let dt = a.round() as u32;
self.frame(web_view, mtm, x, y, 0.0, dt);
} else {
self.accum.set(a);
}
}
}