Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: address remaining camera feedback

Richie McIlroy2e6868e2238c
diff --git a/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs b/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs
index 587de53b4..78527f481 100644
--- a/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs
+++ b/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs
@@ -220,7 +220,8 @@ async fn main() {
};
let (frame_watch_tx, frame_watch_rx) = watch::channel(None);
- let (ws_port, ws_shutdown_token) = create_watch_frame_ws(frame_watch_rx).await;
+ let (ws_port, ws_shutdown_token) =
+ create_watch_frame_ws(frame_watch_rx, Default::default()).await;
println!("DISPLAY_WS_URL=ws://127.0.0.1:{ws_port}");
println!(
@@ -248,7 +249,7 @@ async fn main() {
let ws_frame = match output {
EditorFrameOutput::Nv12(frame) => {
let ws_format = match frame.format {
- GpuOutputFormat::Nv12 => WSFrameFormat::Nv12,
+ GpuOutputFormat::Nv12 => WSFrameFormat::Nv12 { full_range: false },
GpuOutputFormat::Rgba => WSFrameFormat::Rgba,
};
let metadata_bytes = match frame.format {
@@ -292,8 +293,6 @@ async fn main() {
let renderer = match Renderer::spawn_with_telemetry(
render_constants.clone(),
frame_cb,
- &recording_meta,
- meta.as_ref(),
layers_rx,
Some(telemetry.clone()),
) {
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rs
index 63bea17cd..7e2620c1f 100644
--- a/apps/desktop/src-tauri/src/editor_window.rs
+++ b/apps/desktop/src-tauri/src/editor_window.rs
@@ -35,7 +35,7 @@ async fn do_prewarm(app: AppHandle, path: PathBuf) -> PendingResult {
let ws_frame = match output {
cap_editor::EditorFrameOutput::Nv12(frame) => {
let ws_format = match frame.format {
- GpuOutputFormat::Nv12 => WSFrameFormat::Nv12,
+ GpuOutputFormat::Nv12 => WSFrameFormat::Nv12 { full_range: false },
GpuOutputFormat::Rgba => WSFrameFormat::Rgba,
};
WSFrame {
@@ -353,7 +353,9 @@ impl EditorInstances {
let ws_frame = match output {
cap_editor::EditorFrameOutput::Nv12(frame) => {
let ws_format = match frame.format {
- GpuOutputFormat::Nv12 => WSFrameFormat::Nv12,
+ GpuOutputFormat::Nv12 => {
+ WSFrameFormat::Nv12 { full_range: false }
+ }
GpuOutputFormat::Rgba => WSFrameFormat::Rgba,
};
WSFrame {
diff --git a/apps/desktop/src-tauri/src/fake_window.rs b/apps/desktop/src-tauri/src/fake_window.rs
index 70634dfe6..773d882fe 100644
--- a/apps/desktop/src-tauri/src/fake_window.rs
+++ b/apps/desktop/src-tauri/src/fake_window.rs
@@ -469,6 +469,23 @@ pub fn spawn_fake_window_listener(app: AppHandle, window: WebviewWindow) {
});
}
+pub fn cancel_fake_window_listener(app: &AppHandle, label: &str) {
+ if let Some(listeners) = app.try_state::<FakeWindowListeners>() {
+ listeners.cancel(label);
+ }
+}
+
+pub fn cancel_all_fake_window_listeners(app: &AppHandle) {
+ if let Some(listeners) = app.try_state::<FakeWindowListeners>() {
+ listeners.cancel_all();
+ }
+}
+
+pub fn init(app: &AppHandle) {
+ app.manage(FakeWindowBounds(Default::default()));
+ app.manage(FakeWindowListeners::default());
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -586,20 +603,3 @@ mod tests {
));
}
}
-
-pub fn cancel_fake_window_listener(app: &AppHandle, label: &str) {
- if let Some(listeners) = app.try_state::<FakeWindowListeners>() {
- listeners.cancel(label);
- }
-}
-
-pub fn cancel_all_fake_window_listeners(app: &AppHandle) {
- if let Some(listeners) = app.try_state::<FakeWindowListeners>() {
- listeners.cancel_all();
- }
-}
-
-pub fn init(app: &AppHandle) {
- app.manage(FakeWindowBounds(Default::default()));
- app.manage(FakeWindowListeners::default());
-}
diff --git a/apps/desktop/src-tauri/src/frame_ws.rs b/apps/desktop/src-tauri/src/frame_ws.rs
index 0e6d7a834..8542707ff 100644
--- a/apps/desktop/src-tauri/src/frame_ws.rs
+++ b/apps/desktop/src-tauri/src/frame_ws.rs
@@ -1,21 +1,12 @@
use std::sync::Arc;
-use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
+use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, watch};
use tokio_util::sync::CancellationToken;
-static TOTAL_BYTES_SENT: AtomicU64 = AtomicU64::new(0);
-static TOTAL_FRAMES_SENT: AtomicU32 = AtomicU32::new(0);
-static LAST_LOG_TIME: AtomicU64 = AtomicU64::new(0);
-static TOTAL_PACK_NS: AtomicU64 = AtomicU64::new(0);
-static MAX_PACK_NS: AtomicU64 = AtomicU64::new(0);
-static TOTAL_SEND_NS: AtomicU64 = AtomicU64::new(0);
-static MAX_SEND_NS: AtomicU64 = AtomicU64::new(0);
-static TOTAL_CREATED_TO_SENT_NS: AtomicU64 = AtomicU64::new(0);
-static MAX_CREATED_TO_SENT_NS: AtomicU64 = AtomicU64::new(0);
-
-const NV12_FORMAT_MAGIC: u32 = 0x4e563132;
+const NV12_VIDEO_FORMAT_MAGIC: u32 = 0x4e563132;
+const NV12_FULL_FORMAT_MAGIC: u32 = 0x4e563146;
fn pack_frame_data(
mut data: Vec<u8>,
@@ -37,7 +28,7 @@ fn pack_frame_data(
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum WSFrameFormat {
Rgba,
- Nv12,
+ Nv12 { full_range: bool },
}
#[derive(Clone)]
@@ -55,20 +46,25 @@ pub struct WSFrame {
fn pack_ws_frame(frame: &WSFrame) -> Vec<u8> {
let metadata_size = match frame.format {
- WSFrameFormat::Nv12 => 28usize,
+ WSFrameFormat::Nv12 { .. } => 28usize,
WSFrameFormat::Rgba => 24,
};
let mut buf = Vec::with_capacity(frame.data.len() + metadata_size);
buf.extend_from_slice(&frame.data);
match frame.format {
- WSFrameFormat::Nv12 => {
+ WSFrameFormat::Nv12 { full_range } => {
buf.extend_from_slice(&frame.stride.to_le_bytes());
buf.extend_from_slice(&frame.height.to_le_bytes());
buf.extend_from_slice(&frame.width.to_le_bytes());
buf.extend_from_slice(&frame.frame_number.to_le_bytes());
buf.extend_from_slice(&frame.target_time_ns.to_le_bytes());
- buf.extend_from_slice(&NV12_FORMAT_MAGIC.to_le_bytes());
+ let magic = if full_range {
+ NV12_FULL_FORMAT_MAGIC
+ } else {
+ NV12_VIDEO_FORMAT_MAGIC
+ };
+ buf.extend_from_slice(&magic.to_le_bytes());
}
WSFrameFormat::Rgba => {
buf.extend_from_slice(&frame.stride.to_le_bytes());
@@ -86,23 +82,64 @@ fn duration_ns(duration: std::time::Duration) -> u64 {
duration.as_nanos().min(u128::from(u64::MAX)) as u64
}
-fn record_ws_frame_stats(
- packed_len: usize,
- pack_duration: std::time::Duration,
- send_duration: std::time::Duration,
- created_to_sent: std::time::Duration,
-) {
- TOTAL_BYTES_SENT.fetch_add(packed_len as u64, Ordering::Relaxed);
- TOTAL_FRAMES_SENT.fetch_add(1, Ordering::Relaxed);
- let pack_ns = duration_ns(pack_duration);
- let send_ns = duration_ns(send_duration);
- let created_to_sent_ns = duration_ns(created_to_sent);
- TOTAL_PACK_NS.fetch_add(pack_ns, Ordering::Relaxed);
- MAX_PACK_NS.fetch_max(pack_ns, Ordering::Relaxed);
- TOTAL_SEND_NS.fetch_add(send_ns, Ordering::Relaxed);
- MAX_SEND_NS.fetch_max(send_ns, Ordering::Relaxed);
- TOTAL_CREATED_TO_SENT_NS.fetch_add(created_to_sent_ns, Ordering::Relaxed);
- MAX_CREATED_TO_SENT_NS.fetch_max(created_to_sent_ns, Ordering::Relaxed);
+#[derive(Default)]
+struct WsFrameStats {
+ total_bytes_sent: u64,
+ total_frames_sent: u32,
+ last_log_time_ms: u64,
+ total_pack_ns: u64,
+ max_pack_ns: u64,
+ total_send_ns: u64,
+ max_send_ns: u64,
+ total_created_to_sent_ns: u64,
+ max_created_to_sent_ns: u64,
+}
+
+impl WsFrameStats {
+ fn record(
+ &mut self,
+ packed_len: usize,
+ pack_duration: std::time::Duration,
+ send_duration: std::time::Duration,
+ created_to_sent: std::time::Duration,
+ ) {
+ self.total_bytes_sent += packed_len as u64;
+ self.total_frames_sent += 1;
+ let pack_ns = duration_ns(pack_duration);
+ let send_ns = duration_ns(send_duration);
+ let created_to_sent_ns = duration_ns(created_to_sent);
+ self.total_pack_ns += pack_ns;
+ self.max_pack_ns = self.max_pack_ns.max(pack_ns);
+ self.total_send_ns += send_ns;
+ self.max_send_ns = self.max_send_ns.max(send_ns);
+ self.total_created_to_sent_ns += created_to_sent_ns;
+ self.max_created_to_sent_ns = self.max_created_to_sent_ns.max(created_to_sent_ns);
+ }
+
+ fn reset_window(&mut self, now_ms: u64) -> WsFrameStatsWindow {
+ self.last_log_time_ms = now_ms;
+ WsFrameStatsWindow {
+ total_bytes_sent: std::mem::take(&mut self.total_bytes_sent),
+ total_frames_sent: std::mem::take(&mut self.total_frames_sent),
+ total_pack_ns: std::mem::take(&mut self.total_pack_ns),
+ max_pack_ns: std::mem::take(&mut self.max_pack_ns),
+ total_send_ns: std::mem::take(&mut self.total_send_ns),
+ max_send_ns: std::mem::take(&mut self.max_send_ns),
+ total_created_to_sent_ns: std::mem::take(&mut self.total_created_to_sent_ns),
+ max_created_to_sent_ns: std::mem::take(&mut self.max_created_to_sent_ns),
+ }
+ }
+}
+
+struct WsFrameStatsWindow {
+ total_bytes_sent: u64,
+ total_frames_sent: u32,
+ total_pack_ns: u64,
+ max_pack_ns: u64,
+ total_send_ns: u64,
+ max_send_ns: u64,
+ total_created_to_sent_ns: u64,
+ max_created_to_sent_ns: u64,
}
struct SubscriberCountGuard(Arc<AtomicUsize>);
@@ -146,6 +183,7 @@ pub async fn create_watch_frame_ws(
) {
tracing::info!("Socket connection established");
let now = std::time::Instant::now();
+ let mut stats = WsFrameStats::default();
subscribers.fetch_add(1, Ordering::AcqRel);
let _subscriber_guard = SubscriberCountGuard(subscribers);
@@ -184,7 +222,8 @@ pub async fn create_watch_frame_ws(
let width = frame.width;
let height = frame.height;
let format_label = match frame.format {
- WSFrameFormat::Nv12 => "NV12",
+ WSFrameFormat::Nv12 { full_range: false } => "NV12",
+ WSFrameFormat::Nv12 { full_range: true } => "NV12-full",
WSFrameFormat::Rgba => "RGBA",
};
@@ -197,7 +236,7 @@ pub async fn create_watch_frame_ws(
match socket.send(Message::Binary(packed)).await {
Ok(()) => {
let send_duration = send_start.elapsed();
- record_ws_frame_stats(
+ stats.record(
packed_len,
pack_duration,
send_duration,
@@ -207,31 +246,20 @@ pub async fn create_watch_frame_ws(
.duration_since(UNIX_EPOCH)
.map(|duration| duration.as_millis() as u64)
.unwrap_or_default();
- let last_log = LAST_LOG_TIME.load(Ordering::Relaxed);
- if now_ms - last_log > 2000 {
- LAST_LOG_TIME.store(now_ms, Ordering::Relaxed);
- let total_bytes = TOTAL_BYTES_SENT.swap(0, Ordering::Relaxed);
- let total_frames = TOTAL_FRAMES_SENT.swap(0, Ordering::Relaxed);
- let total_pack_ns = TOTAL_PACK_NS.swap(0, Ordering::Relaxed);
- let max_pack_ns = MAX_PACK_NS.swap(0, Ordering::Relaxed);
- let total_send_ns = TOTAL_SEND_NS.swap(0, Ordering::Relaxed);
- let max_send_ns = MAX_SEND_NS.swap(0, Ordering::Relaxed);
- let total_created_to_sent_ns =
- TOTAL_CREATED_TO_SENT_NS.swap(0, Ordering::Relaxed);
- let max_created_to_sent_ns =
- MAX_CREATED_TO_SENT_NS.swap(0, Ordering::Relaxed);
- let frames = total_frames.max(1) as f64;
- let mb_per_sec = total_bytes as f64 / 1_000_000.0 / 2.0;
+ if now_ms.saturating_sub(stats.last_log_time_ms) > 2000 {
+ let window = stats.reset_window(now_ms);
+ let frames = window.total_frames_sent.max(1) as f64;
+ let mb_per_sec = window.total_bytes_sent as f64 / 1_000_000.0 / 2.0;
tracing::info!(
- fps = total_frames / 2,
+ fps = window.total_frames_sent / 2,
mb_per_sec = format!("{:.1}", mb_per_sec),
- avg_kb = format!("{:.1}", (total_bytes as f64 / total_frames.max(1) as f64) / 1024.0),
- pack_avg_ms = format!("{:.3}", total_pack_ns as f64 / frames / 1_000_000.0),
- pack_max_ms = format!("{:.3}", max_pack_ns as f64 / 1_000_000.0),
- send_avg_ms = format!("{:.3}", total_send_ns as f64 / frames / 1_000_000.0),
- send_max_ms = format!("{:.3}", max_send_ns as f64 / 1_000_000.0),
- created_to_sent_avg_ms = format!("{:.3}", total_created_to_sent_ns as f64 / frames / 1_000_000.0),
- created_to_sent_max_ms = format!("{:.3}", max_created_to_sent_ns as f64 / 1_000_000.0),
+ avg_kb = format!("{:.1}", (window.total_bytes_sent as f64 / window.total_frames_sent.max(1) as f64) / 1024.0),
+ pack_avg_ms = format!("{:.3}", window.total_pack_ns as f64 / frames / 1_000_000.0),
+ pack_max_ms = format!("{:.3}", window.max_pack_ns as f64 / 1_000_000.0),
+ send_avg_ms = format!("{:.3}", window.total_send_ns as f64 / frames / 1_000_000.0),
+ send_max_ms = format!("{:.3}", window.max_send_ns as f64 / 1_000_000.0),
+ created_to_sent_avg_ms = format!("{:.3}", window.total_created_to_sent_ns as f64 / frames / 1_000_000.0),
+ created_to_sent_max_ms = format!("{:.3}", window.max_created_to_sent_ns as f64 / 1_000_000.0),
dims = format!("{}x{}", width, height),
format = format_label,
"WS frame stats"
diff --git a/apps/desktop/src/utils/frame-worker.ts b/apps/desktop/src/utils/frame-worker.ts
index 2be2376cb..3e3cd042d 100644
--- a/apps/desktop/src/utils/frame-worker.ts
+++ b/apps/desktop/src/utils/frame-worker.ts
@@ -128,6 +128,7 @@ interface PendingFrameWebGPUNv12 {
width: number;
height: number;
yStride: number;
+ fullRange: boolean;
timing: FrameTiming;
releaseCallback?: () => void;
}
@@ -205,6 +206,7 @@ interface FrameMetadataNv12 {
width: number;
height: number;
yStride: number;
+ fullRange: boolean;
frameNumber: number;
targetTimeNs: bigint;
ySize: number;
@@ -214,7 +216,8 @@ interface FrameMetadataNv12 {
type FrameMetadata = FrameMetadataRgba | FrameMetadataNv12;
-const NV12_MAGIC = 0x4e563132;
+const NV12_VIDEO_MAGIC = 0x4e563132;
+const NV12_FULL_MAGIC = 0x4e563146;
function parseFrameMetadata(bytes: Uint8Array): FrameMetadata | null {
if (bytes.byteLength < 24) return null;
@@ -224,7 +227,7 @@ function parseFrameMetadata(bytes: Uint8Array): FrameMetadata | null {
const formatView = new DataView(bytes.buffer, formatOffset, 4);
const formatFlag = formatView.getUint32(0, true);
- if (formatFlag === NV12_MAGIC) {
+ if (formatFlag === NV12_VIDEO_MAGIC || formatFlag === NV12_FULL_MAGIC) {
const metadataOffset = bytes.byteOffset + bytes.byteLength - 28;
const meta = new DataView(bytes.buffer, metadataOffset, 28);
const yStride = meta.getUint32(0, true);
@@ -248,6 +251,7 @@ function parseFrameMetadata(bytes: Uint8Array): FrameMetadata | null {
width,
height,
yStride,
+ fullRange: formatFlag === NV12_FULL_MAGIC,
frameNumber,
targetTimeNs,
ySize,
@@ -297,6 +301,7 @@ function convertNv12ToRgba(
width: number,
height: number,
yStride: number,
+ fullRange = false,
): Uint8ClampedArray {
const rgbaSize = width * height * 4;
if (!nv12ConversionBuffer || nv12ConversionBufferSize < rgbaSize) {
@@ -322,11 +327,20 @@ function convertNv12ToRgba(
const d = u;
const e = v;
- const y0 = yPlane[yRowOffset + col] - 16;
- const c0 = 298 * y0;
- let r = (c0 + 409 * e + 128) >> 8;
- let g = (c0 - 100 * d - 208 * e + 128) >> 8;
- let b = (c0 + 516 * d + 128) >> 8;
+ const y0 = yPlane[yRowOffset + col];
+ let r: number;
+ let g: number;
+ let b: number;
+ if (fullRange) {
+ r = y0 + ((359 * e + 128) >> 8);
+ g = y0 - ((88 * d + 183 * e + 128) >> 8);
+ b = y0 + ((454 * d + 128) >> 8);
+ } else {
+ const c0 = 298 * (y0 - 16);
+ r = (c0 + 409 * e + 128) >> 8;
+ g = (c0 - 100 * d - 208 * e + 128) >> 8;
+ b = (c0 + 516 * d + 128) >> 8;
+ }
r = r < 0 ? 0 : r > 255 ? 255 : r;
g = g < 0 ? 0 : g > 255 ? 255 : g;
@@ -340,11 +354,20 @@ function convertNv12ToRgba(
const nextCol = col + 1;
if (nextCol < width) {
- const y1 = yPlane[yRowOffset + nextCol] - 16;
- const c1 = 298 * y1;
- let nextR = (c1 + 409 * e + 128) >> 8;
- let nextG = (c1 - 100 * d - 208 * e + 128) >> 8;
- let nextB = (c1 + 516 * d + 128) >> 8;
+ const y1 = yPlane[yRowOffset + nextCol];
+ let nextR: number;
+ let nextG: number;
+ let nextB: number;
+ if (fullRange) {
+ nextR = y1 + ((359 * e + 128) >> 8);
+ nextG = y1 - ((88 * d + 183 * e + 128) >> 8);
+ nextB = y1 + ((454 * d + 128) >> 8);
+ } else {
+ const c1 = 298 * (y1 - 16);
+ nextR = (c1 + 409 * e + 128) >> 8;
+ nextG = (c1 - 100 * d - 208 * e + 128) >> 8;
+ nextB = (c1 + 516 * d + 128) >> 8;
+ }
nextR = nextR < 0 ? 0 : nextR > 255 ? 255 : nextR;
nextG = nextG < 0 ? 0 : nextG > 255 ? 255 : nextG;
@@ -407,6 +430,7 @@ function renderBorrowedWebGPU(bytes: Uint8Array, release: () => void): boolean {
width,
height,
meta.yStride,
+ meta.fullRange,
);
release();
} else {
@@ -489,6 +513,7 @@ function queueFrameFromBytes(
width,
height,
yStride: meta.yStride,
+ fullRange: meta.fullRange,
timing,
releaseCallback,
});
@@ -664,6 +689,7 @@ function renderLoop() {
frame.width,
frame.height,
frame.yStride,
+ frame.fullRange,
);
} else {
const expectedRowBytes = frame.width * 4;
@@ -735,6 +761,7 @@ function renderLoop() {
frame.width,
frame.height,
frame.yStride,
+ frame.fullRange,
);
} else {
renderFrameWebGPU(
@@ -996,6 +1023,7 @@ function processFrameBytesSync(
width,
height,
yStride: meta.yStride,
+ fullRange: meta.fullRange,
timing,
releaseCallback,
});
@@ -1035,6 +1063,7 @@ function processFrameBytesSync(
width,
height,
meta.yStride,
+ meta.fullRange,
);
} else {
const frameData = new Uint8ClampedArray(
diff --git a/apps/desktop/src/utils/socket.ts b/apps/desktop/src/utils/socket.ts
index 46af09bbe..11448ad13 100644
--- a/apps/desktop/src/utils/socket.ts
+++ b/apps/desktop/src/utils/socket.ts
@@ -30,6 +30,34 @@ const FRAME_BUFFER_CONFIG: SharedFrameBufferConfig = {
let mainThreadNv12Buffer: Uint8ClampedArray | null = null;
let mainThreadNv12BufferSize = 0;
+const NV12_VIDEO_MAGIC = 0x4e563132;
+const NV12_FULL_MAGIC = 0x4e563146;
+const NV12_METADATA_SIZE = 28;
+
+type Nv12Metadata = {
+ yStride: number;
+ height: number;
+ width: number;
+ fullRange: boolean;
+};
+
+function readNv12Metadata(buffer: ArrayBuffer): Nv12Metadata | null {
+ if (buffer.byteLength < NV12_METADATA_SIZE) return null;
+
+ const formatCheck = new DataView(buffer, buffer.byteLength - 4, 4);
+ const magic = formatCheck.getUint32(0, true);
+ if (magic !== NV12_VIDEO_MAGIC && magic !== NV12_FULL_MAGIC) return null;
+
+ const metadataOffset = buffer.byteLength - NV12_METADATA_SIZE;
+ const meta = new DataView(buffer, metadataOffset, NV12_METADATA_SIZE);
+ return {
+ yStride: meta.getUint32(0, true),
+ height: meta.getUint32(4, true),
+ width: meta.getUint32(8, true),
+ fullRange: magic === NV12_FULL_MAGIC,
+ };
+}
+
export type FpsStats = {
fps: number;
renderFps: number;
@@ -67,6 +95,7 @@ function convertNv12ToRgbaMainThread(
width: number,
height: number,
yStride: number,
+ fullRange = false,
): Uint8ClampedArray {
const rgbaSize = width * height * 4;
if (!mainThreadNv12Buffer || mainThreadNv12BufferSize < rgbaSize) {
@@ -92,11 +121,20 @@ function convertNv12ToRgbaMainThread(
const d = u;
const e = v;
- const y0 = yPlane[yRowOffset + col] - 16;
- const c0 = 298 * y0;
- let r = (c0 + 409 * e + 128) >> 8;
- let g = (c0 - 100 * d - 208 * e + 128) >> 8;
- let b = (c0 + 516 * d + 128) >> 8;
+ const y0 = yPlane[yRowOffset + col];
+ let r: number;
+ let g: number;
+ let b: number;
+ if (fullRange) {
+ r = y0 + ((359 * e + 128) >> 8);
+ g = y0 - ((88 * d + 183 * e + 128) >> 8);
+ b = y0 + ((454 * d + 128) >> 8);
+ } else {
+ const c0 = 298 * (y0 - 16);
+ r = (c0 + 409 * e + 128) >> 8;
+ g = (c0 - 100 * d - 208 * e + 128) >> 8;
+ b = (c0 + 516 * d + 128) >> 8;
+ }
r = r < 0 ? 0 : r > 255 ? 255 : r;
g = g < 0 ? 0 : g > 255 ? 255 : g;
@@ -110,11 +148,20 @@ function convertNv12ToRgbaMainThread(
const nextCol = col + 1;
if (nextCol < width) {
- const y1 = yPlane[yRowOffset + nextCol] - 16;
- const c1 = 298 * y1;
- let nextR = (c1 + 409 * e + 128) >> 8;
- let nextG = (c1 - 100 * d - 208 * e + 128) >> 8;
- let nextB = (c1 + 516 * d + 128) >> 8;
+ const y1 = yPlane[yRowOffset + nextCol];
+ let nextR: number;
+ let nextG: number;
+ let nextB: number;
+ if (fullRange) {
+ nextR = y1 + ((359 * e + 128) >> 8);
+ nextG = y1 - ((88 * d + 183 * e + 128) >> 8);
+ nextB = y1 + ((454 * d + 128) >> 8);
+ } else {
+ const c1 = 298 * (y1 - 16);
+ nextR = (c1 + 409 * e + 128) >> 8;
+ nextG = (c1 - 100 * d - 208 * e + 128) >> 8;
+ nextB = (c1 + 516 * d + 128) >> 8;
+ }
nextR = nextR < 0 ? 0 : nextR > 255 ? 255 : nextR;
nextG = nextG < 0 ? 0 : nextG > 255 ? 255 : nextG;
@@ -278,6 +325,7 @@ export function createImageDataWS(
height: number;
yStride: number;
isNv12: boolean;
+ nv12FullRange: boolean;
} | null = null;
function storeRenderedFrame(
@@ -286,6 +334,7 @@ export function createImageDataWS(
height: number,
yStride: number,
isNv12: boolean,
+ nv12FullRange = false,
) {
lastRenderedFrameData = {
data: frameData,
@@ -293,6 +342,7 @@ export function createImageDataWS(
height,
yStride,
isNv12,
+ nv12FullRange,
};
if (!hasRenderedFrame()) {
setHasRenderedFrame(true);
@@ -381,17 +431,10 @@ export function createImageDataWS(
const { buffer, receivedAt } = pendingNv12Frame;
pendingNv12Frame = null;
- const NV12_MAGIC = 0x4e563132;
- if (buffer.byteLength < 28) return;
+ const metadata = readNv12Metadata(buffer);
+ if (!metadata) return;
- const formatCheck = new DataView(buffer, buffer.byteLength - 4, 4);
- if (formatCheck.getUint32(0, true) !== NV12_MAGIC) return;
-
- const metadataOffset = buffer.byteLength - 28;
- const meta = new DataView(buffer, metadataOffset, 28);
- const yStride = meta.getUint32(0, true);
- const height = meta.getUint32(4, true);
- const width = meta.getUint32(8, true);
+ const { yStride, height, width, fullRange } = metadata;
if (width > 0 && height > 0) {
const ySize = yStride * height;
@@ -412,9 +455,10 @@ export function createImageDataWS(
width,
height,
yStride,
+ fullRange,
);
- storeRenderedFrame(frameData, width, height, yStride, true);
+ storeRenderedFrame(frameData, width, height, yStride, true, fullRange);
recordRender(
performance.now() - renderStart,
"webgpu",
@@ -495,6 +539,7 @@ export function createImageDataWS(
width: number,
height: number,
yStride: number,
+ fullRange: boolean,
receivedAt?: number,
) {
if (!directCanvas || !directCtx) return;
@@ -506,7 +551,13 @@ export function createImageDataWS(
directCanvas.height = height;
}
- const rgba = convertNv12ToRgbaMainThread(frameData, width, height, yStride);
+ const rgba = convertNv12ToRgbaMainThread(
+ frameData,
+ width,
+ height,
+ yStride,
+ fullRange,
+ );
if (
!cachedDirectImageData ||
@@ -520,7 +571,7 @@ export function createImageDataWS(
cachedDirectImageData.data.set(rgba);
directCtx.putImageData(cachedDirectImageData, 0, 0);
- storeRenderedFrame(frameData, width, height, yStride, true);
+ storeRenderedFrame(frameData, width, height, yStride, true, fullRange);
recordRender(
performance.now() - renderStart,
"canvas2d",
@@ -536,17 +587,10 @@ export function createImageDataWS(
const { buffer, receivedAt } = pendingNv12Frame;
pendingNv12Frame = null;
- const NV12_MAGIC = 0x4e563132;
- if (buffer.byteLength < 28) return;
+ const metadata = readNv12Metadata(buffer);
+ if (!metadata) return;
- const formatCheck = new DataView(buffer, buffer.byteLength - 4, 4);
- if (formatCheck.getUint32(0, true) !== NV12_MAGIC) return;
-
- const metadataOffset = buffer.byteLength - 28;
- const meta = new DataView(buffer, metadataOffset, 28);
- const yStride = meta.getUint32(0, true);
- const height = meta.getUint32(4, true);
- const width = meta.getUint32(8, true);
+ const { yStride, height, width, fullRange } = metadata;
if (width > 0 && height > 0) {
const ySize = yStride * height;
@@ -554,7 +598,14 @@ export function createImageDataWS(
const totalSize = ySize + uvSize;
const frameData = new Uint8ClampedArray(buffer, 0, totalSize);
- renderNv12FrameCanvas2D(frameData, width, height, yStride, receivedAt);
+ renderNv12FrameCanvas2D(
+ frameData,
+ width,
+ height,
+ yStride,
+ fullRange,
+ receivedAt,
+ );
}
}
@@ -814,10 +865,17 @@ export function createImageDataWS(
if (!lastRenderedFrameData) {
return null;
}
- const { data, width, height, yStride, isNv12 } = lastRenderedFrameData;
+ const { data, width, height, yStride, isNv12, nv12FullRange } =
+ lastRenderedFrameData;
let imageData: ImageData;
if (isNv12) {
- const rgba = convertNv12ToRgbaMainThread(data, width, height, yStride);
+ const rgba = convertNv12ToRgbaMainThread(
+ data,
+ width,
+ height,
+ yStride,
+ nv12FullRange,
+ );
imageData = new ImageData(new Uint8ClampedArray(rgba), width, height);
} else {
const expectedRowBytes = width * 4;
@@ -1060,8 +1118,6 @@ export function createImageDataWS(
globalFpsStatsGetter = getLocalFpsStats;
(globalThis as Record<string, unknown>).__capFpsStats = getLocalFpsStats;
- const NV12_MAGIC = 0x4e563132;
-
ws.binaryType = "arraybuffer";
ws.onmessage = (event) => {
const buffer = event.data as ArrayBuffer;
@@ -1071,11 +1127,7 @@ export function createImageDataWS(
}
totalBytesReceived += buffer.byteLength;
- let isNv12Format = false;
- if (buffer.byteLength >= 28) {
- const formatCheck = new DataView(buffer, buffer.byteLength - 4, 4);
- isNv12Format = formatCheck.getUint32(0, true) === NV12_MAGIC;
- }
+ const nv12Metadata = readNv12Metadata(buffer);
if (lastFrameTime > 0) {
const delta = now - lastFrameTime;
@@ -1086,12 +1138,9 @@ export function createImageDataWS(
}
lastFrameTime = now;
- if (isNv12Format) {
+ if (nv12Metadata) {
if (mainThreadWebGPU && directCanvas) {
- const metadataOffset = buffer.byteLength - 28;
- const meta = new DataView(buffer, metadataOffset, 28);
- const height = meta.getUint32(4, true);
- const width = meta.getUint32(8, true);
+ const { height, width } = nv12Metadata;
if (width > 0 && height > 0) {
if (directCanvas.width !== width || directCanvas.height !== height) {
@@ -1106,10 +1155,7 @@ export function createImageDataWS(
if (mainThreadWebGPUInitializing || !directCanvas) {
pendingNv12Frame = { buffer, receivedAt: now };
- const metadataOffset = buffer.byteLength - 28;
- const meta = new DataView(buffer, metadataOffset, 28);
- const height = meta.getUint32(4, true);
- const width = meta.getUint32(8, true);
+ const { height, width } = nv12Metadata;
if (width > 0 && height > 0) {
onmessage({ width, height });
}
@@ -1135,11 +1181,7 @@ export function createImageDataWS(
}
}
- const metadataOffset = buffer.byteLength - 28;
- const meta = new DataView(buffer, metadataOffset, 28);
- const yStride = meta.getUint32(0, true);
- const height = meta.getUint32(4, true);
- const width = meta.getUint32(8, true);
+ const { yStride, height, width } = nv12Metadata;
if (width > 0 && height > 0) {
const ySize = yStride * height;
@@ -1164,10 +1206,7 @@ export function createImageDataWS(
}
pendingNv12Frame = { buffer, receivedAt: now };
- const metadataOffset = buffer.byteLength - 28;
- const meta = new DataView(buffer, metadataOffset, 28);
- const height = meta.getUint32(4, true);
- const width = meta.getUint32(8, true);
+ const { height, width } = nv12Metadata;
if (width > 0 && height > 0) {
onmessage({ width, height });
}
diff --git a/apps/desktop/src/utils/webgpu-renderer.ts b/apps/desktop/src/utils/webgpu-renderer.ts
index 0d48775a2..3167ddd2e 100644
--- a/apps/desktop/src/utils/webgpu-renderer.ts
+++ b/apps/desktop/src/utils/webgpu-renderer.ts
@@ -56,11 +56,33 @@ fn fs(@location(0) texCoord: vec2f) -> @location(0) vec4f {
}
`;
+const NV12_FULL_FRAGMENT_SHADER = `
+@group(0) @binding(0) var frameSampler: sampler;
+@group(0) @binding(1) var yTexture: texture_2d<f32>;
+@group(0) @binding(2) var uvTexture: texture_2d<f32>;
+
+@fragment
+fn fs(@location(0) texCoord: vec2f) -> @location(0) vec4f {
+ let y = textureSample(yTexture, frameSampler, texCoord).r;
+ let uv = textureSample(uvTexture, frameSampler, texCoord).rg;
+
+ let u = uv.r - 0.5;
+ let v = uv.g - 0.5;
+
+ let r = clamp(y + 1.402 * v, 0.0, 1.0);
+ let g = clamp(y - 0.344136 * u - 0.714136 * v, 0.0, 1.0);
+ let b = clamp(y + 1.772 * u, 0.0, 1.0);
+
+ return vec4f(r, g, b, 1.0);
+}
+`;
+
export interface WebGPURenderer {
device: GPUDevice;
context: GPUCanvasContext;
pipeline: GPURenderPipeline;
nv12Pipeline: GPURenderPipeline;
+ nv12FullPipeline: GPURenderPipeline;
sampler: GPUSampler;
frameTexture: GPUTexture | null;
bindGroup: GPUBindGroup | null;
@@ -200,6 +222,9 @@ export async function initWebGPU(
const nv12FragmentModule = device.createShaderModule({
code: NV12_FRAGMENT_SHADER,
});
+ const nv12FullFragmentModule = device.createShaderModule({
+ code: NV12_FULL_FRAGMENT_SHADER,
+ });
const pipeline = device.createRenderPipeline({
layout: pipelineLayout,
@@ -233,6 +258,22 @@ export async function initWebGPU(
},
});
+ const nv12FullPipeline = device.createRenderPipeline({
+ layout: nv12PipelineLayout,
+ vertex: {
+ module: vertexModule,
+ entryPoint: "vs",
+ },
+ fragment: {
+ module: nv12FullFragmentModule,
+ entryPoint: "fs",
+ targets: [{ format }],
+ },
+ primitive: {
+ topology: "triangle-list",
+ },
+ });
+
const sampler = device.createSampler({
magFilter: "linear",
minFilter: "linear",
@@ -245,6 +286,7 @@ export async function initWebGPU(
context,
pipeline,
nv12Pipeline,
+ nv12FullPipeline,
sampler,
frameTexture: null,
bindGroup: null,
@@ -370,6 +412,7 @@ export function renderNv12FrameWebGPU(
width: number,
height: number,
yStride: number,
+ fullRange = false,
): WebGPURenderTiming {
const totalStart = performance.now();
let resizeMs = 0;
@@ -380,6 +423,7 @@ export function renderNv12FrameWebGPU(
device,
context,
nv12Pipeline,
+ nv12FullPipeline,
sampler,
nv12BindGroupLayout,
canvas,
@@ -482,7 +526,7 @@ export function renderNv12FrameWebGPU(
],
});
- pass.setPipeline(nv12Pipeline);
+ pass.setPipeline(fullRange ? nv12FullPipeline : nv12Pipeline);
pass.setBindGroup(0, renderer.nv12BindGroup);
pass.draw(3);
pass.end();
diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rs
index 67528cd2d..858f4820d 100644
--- a/crates/recording/src/feeds/camera.rs
+++ b/crates/recording/src/feeds/camera.rs
@@ -975,6 +975,7 @@ async fn setup_camera(
settings: Option<CameraDeviceSettings>,
recipient: Recipient<NewFrame>,
_native_recipient: Recipient<NewNativeFrame>,
+ _ffmpeg_sender_count: Arc<std::sync::atomic::AtomicUsize>,
_native_sender_count: Arc<std::sync::atomic::AtomicUsize>,
) -> Result<SetupCameraResult, SetInputError> {
let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?;