Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Fix editor playback, in progress recording and fragmented MP4 (Windows)
Richie McIlroy915de586b0b8
diff --git a/apps/desktop/src-tauri/src/editor_window.rs b/apps/desktop/src-tauri/src/editor_window.rsindex 46a3bbd1c..66ea67b97 100644--- a/apps/desktop/src-tauri/src/editor_window.rs+++ b/apps/desktop/src-tauri/src/editor_window.rs@@ -16,6 +16,7 @@ fn strip_frame_padding(frame: RenderedFrame) -> Result<(Vec<u8>, u32), &'static.width.checked_mul(4).ok_or("overflow computing expected_stride")?;+if frame.padded_bytes_per_row == expected_stride {Ok((frame.data, expected_stride))} else {@@ -30,6 +31,7 @@ fn strip_frame_padding(frame: RenderedFrame) -> Result<(Vec<u8>, u32), &'staticlet end = start + expected_stride as usize;stripped.extend_from_slice(&frame.data[start..end]);}+Ok((stripped, expected_stride))}}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 98eccdfef..63e874c35 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -809,7 +809,7 @@ pub struct RecordingInfo {enum CurrentRecordingTarget {Window {id: WindowId,- bounds: LogicalBounds,+ bounds: Option<LogicalBounds>,},Screen {id: DisplayId,@@ -841,33 +841,55 @@ struct CurrentRecording {async fn get_current_recording(state: MutableState<'_, App>,) -> Result<JsonValue<Option<CurrentRecording>>, ()> {+ tracing::debug!("get_current_recording called");let state = state.read().await;let (mode, capture_target, status) = match &state.recording_state {- RecordingState::None => return Ok(JsonValue::new(&None)),- RecordingState::Pending { mode, target } => (*mode, target, RecordingStatus::Pending),- RecordingState::Active(inner) => (- inner.mode(),- inner.capture_target(),- RecordingStatus::Recording,- ),+ RecordingState::None => {+ tracing::debug!("get_current_recording: state is None");+ return Ok(JsonValue::new(&None));+ }+ RecordingState::Pending { mode, target } => {+ tracing::debug!("get_current_recording: state is Pending");+ (*mode, target, RecordingStatus::Pending)+ }+ RecordingState::Active(inner) => {+ tracing::debug!("get_current_recording: state is Active");+ (+ inner.mode(),+ inner.capture_target(),+ RecordingStatus::Recording,+ )+ }};let target = match capture_target {- ScreenCaptureTarget::Display { id } => CurrentRecordingTarget::Screen { id: id.clone() },- ScreenCaptureTarget::Window { id } => CurrentRecordingTarget::Window {- id: id.clone(),- bounds: scap_targets::Window::from_id(id)- .ok_or(())?- .display_relative_logical_bounds()- .ok_or(())?,- },- ScreenCaptureTarget::Area { screen, bounds } => CurrentRecordingTarget::Area {- screen: screen.clone(),- bounds: *bounds,- },+ ScreenCaptureTarget::Display { id } => {+ tracing::debug!("get_current_recording: target is Display");+ CurrentRecordingTarget::Screen { id: id.clone() }+ }+ ScreenCaptureTarget::Window { id } => {+ let bounds =+ scap_targets::Window::from_id(id).and_then(|w| w.display_relative_logical_bounds());+ tracing::debug!(+ "get_current_recording: target is Window, bounds={:?}",+ bounds+ );+ CurrentRecordingTarget::Window {+ id: id.clone(),+ bounds,+ }+ }+ ScreenCaptureTarget::Area { screen, bounds } => {+ tracing::debug!("get_current_recording: target is Area");+ CurrentRecordingTarget::Area {+ screen: screen.clone(),+ bounds: *bounds,+ }+ }};+ tracing::debug!("get_current_recording: returning Some(CurrentRecording)");Ok(JsonValue::new(&Some(CurrentRecording {target,mode,diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex b92284305..e1bbc509e 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -708,34 +708,95 @@ impl ShowCapWindow {let title = CapWindowId::RecordingControls.title();let should_protect = should_protect_window(app, &title);- let window = self- .window_builder(app, "/in-progress-recording")- .maximized(false)- .resizable(false)- .fullscreen(false)- .shadow(false)- .always_on_top(true)- .transparent(true)- .visible_on_all_workspaces(true)- .content_protected(should_protect)- .inner_size(width, height)- .position(- ((monitor.size().width as f64) / monitor.scale_factor() - width) / 2.0,- (monitor.size().height as f64) / monitor.scale_factor() - height - 120.0,- )- .skip_taskbar(true)- .initialization_script(format!(- "window.COUNTDOWN = {};",- countdown.unwrap_or_default()- ))- .build()?;+ let pos_x = ((monitor.size().width as f64) / monitor.scale_factor() - width) / 2.0;+ let pos_y =+ (monitor.size().height as f64) / monitor.scale_factor() - height - 120.0;++ debug!(+ "InProgressRecording window: monitor size={:?}, scale={}, pos=({}, {})",+ monitor.size(),+ monitor.scale_factor(),+ pos_x,+ pos_y+ );++ #[cfg(target_os = "macos")]+ let window = {+ self.window_builder(app, "/in-progress-recording")+ .maximized(false)+ .resizable(false)+ .fullscreen(false)+ .shadow(false)+ .always_on_top(true)+ .transparent(true)+ .visible_on_all_workspaces(true)+ .content_protected(should_protect)+ .inner_size(width, height)+ .position(pos_x, pos_y)+ .skip_taskbar(true)+ .initialization_script(format!(+ "window.COUNTDOWN = {};",+ countdown.unwrap_or_default()+ ))+ .build()?+ };++ #[cfg(windows)]+ let window = {+ let window = self+ .window_builder(app, "/in-progress-recording")+ .maximized(false)+ .resizable(false)+ .fullscreen(false)+ .shadow(false)+ .always_on_top(true)+ .transparent(true)+ .visible_on_all_workspaces(true)+ .content_protected(should_protect)+ .inner_size(width, height)+ .position(pos_x, pos_y)+ .skip_taskbar(false)+ .initialization_script(format!(+ "window.COUNTDOWN = {};",+ countdown.unwrap_or_default()+ ))+ .build()?;++ window+ };++ debug!(+ "InProgressRecording window created: label={}, inner_size={:?}, outer_position={:?}",+ window.label(),+ window.inner_size(),+ window.outer_position()+ );#[cfg(target_os = "macos")]{crate::platform::set_window_level(window.as_ref().window(), 1000);}- fake_window::spawn_fake_window_listener(app.clone(), window.clone());+ #[cfg(target_os = "macos")]+ {+ let show_result = window.show();+ debug!(+ "InProgressRecording window.show() result: {:?}",+ show_result+ );+ fake_window::spawn_fake_window_listener(app.clone(), window.clone());+ }++ #[cfg(windows)]+ {+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ let show_result = window.show();+ debug!(+ "InProgressRecording window.show() result: {:?}",+ show_result+ );+ let _ = window.set_focus();+ }window}diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsxindex 251a08d25..5f12c3e42 100644--- a/apps/desktop/src/App.tsx+++ b/apps/desktop/src/App.tsx@@ -22,7 +22,6 @@ import titlebar from "./utils/titlebar-state";const queryClient = new QueryClient({defaultOptions: {queries: {- experimental_prefetchInRender: true,refetchOnWindowFocus: false,refetchOnReconnect: false,},diff --git a/apps/desktop/src/routes/editor/Player.tsx b/apps/desktop/src/routes/editor/Player.tsxindex 315db42cc..19fa97e29 100644--- a/apps/desktop/src/routes/editor/Player.tsx+++ b/apps/desktop/src/routes/editor/Player.tsx@@ -485,11 +485,19 @@ function PreviewCanvas() {}});+ const isWindows = navigator.userAgent.includes("Windows");+const initCanvas = (canvas: HTMLCanvasElement) => {if (canvasTransferredRef.current) return;const controls = canvasControls();if (!controls) return;+ if (isWindows) {+ controls.initDirectCanvas(canvas);+ canvasTransferredRef.current = true;+ return;+ }+try {const offscreen = canvas.transferControlToOffscreen();controls.initCanvas(offscreen);diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsxindex 050f7c21a..a47ac36e1 100644--- a/apps/desktop/src/routes/in-progress-recording.tsx+++ b/apps/desktop/src/routes/in-progress-recording.tsx@@ -20,6 +20,7 @@ import {createSignal,For,onCleanup,+ onMount,Show,} from "solid-js";import { createStore, produce } from "solid-js/store";@@ -60,6 +61,17 @@ const NO_WEBCAM = "No Webcam";const FAKE_WINDOW_BOUNDS_NAME = "recording-controls-interactive-area";export default function () {+ console.log("[in-progress-recording] Wrapper rendering");++ document.documentElement.setAttribute("data-transparent-window", "true");+ document.body.style.background = "transparent";++ return <InProgressRecordingInner />;+}++function InProgressRecordingInner() {+ console.log("[in-progress-recording] Inner component rendering");+const [state, setState] = createSignal<State>(window.COUNTDOWN === 0? { variant: "initializing" }@@ -75,7 +87,16 @@ export default function () {const optionsQuery = createOptionsQuery();const startedWithMicrophone = optionsQuery.rawOptions.micName != null;const startedWithCameraInput = optionsQuery.rawOptions.cameraID != null;- const auth = authStore.createQuery();++ const [authData, setAuthData] = createSignal<{+ plan?: { upgraded?: boolean };+ } | null>(null);+ onMount(() => {+ authStore+ .get()+ .then(setAuthData)+ .catch(() => setAuthData(null));+ });const audioLevel = createAudioInputLevel();const [disconnectedInputs, setDisconnectedInputs] =@@ -498,7 +519,7 @@ export default function () {return (optionsQuery.rawOptions.mode === "instant" &&// If the data is loaded and the user is not upgraded- auth.data?.plan?.upgraded === false+ authData()?.plan?.upgraded === false);};diff --git a/apps/desktop/src/utils/frame-worker.ts b/apps/desktop/src/utils/frame-worker.tsindex 18a9c7573..8bd4223a8 100644--- a/apps/desktop/src/utils/frame-worker.ts+++ b/apps/desktop/src/utils/frame-worker.ts@@ -241,7 +241,9 @@ async function initCanvas(canvas: OffscreenCanvas): Promise<void> {const doInit = async () => {offscreenCanvas = canvas;- if (await isWebGPUSupported()) {+ const webgpuSupported = await isWebGPUSupported();++ if (webgpuSupported) {try {webgpuRenderer = await initWebGPU(canvas);renderMode = "webgpu";@@ -249,7 +251,8 @@ async function initCanvas(canvas: OffscreenCanvas): Promise<void> {type: "renderer-mode",mode: "webgpu",} satisfies RendererModeMessage);- } catch {+ } catch (e) {+ console.error("[frame-worker] WebGPU init failed:", e);renderMode = "canvas2d";offscreenCtx = canvas.getContext("2d", {alpha: false,diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.tsindex 8ee5c89a8..53cfee00d 100644--- a/apps/desktop/src/utils/queries.ts+++ b/apps/desktop/src/utils/queries.ts@@ -76,6 +76,7 @@ export const listDisplaysWithThumbnails = queryOptions({const getCurrentRecording = queryOptions({queryKey: ["currentRecording"] as const,queryFn: () => commands.getCurrentRecording().then((d) => d[0]),+ staleTime: 0,});export const listRecordings = queryOptions({diff --git a/apps/desktop/src/utils/socket.ts b/apps/desktop/src/utils/socket.tsindex b34511f85..c4b8fe0d1 100644--- a/apps/desktop/src/utils/socket.ts+++ b/apps/desktop/src/utils/socket.ts@@ -25,6 +25,7 @@ export type CanvasControls = {initCanvas: (canvas: OffscreenCanvas) => void;resizeCanvas: (width: number, height: number) => void;hasRenderedFrame: () => boolean;+ initDirectCanvas: (canvas: HTMLCanvasElement) => void;};interface ReadyMessage {@@ -107,6 +108,9 @@ export function createImageDataWS(const [hasRenderedFrame, setHasRenderedFrame] = createSignal(false);let isCleanedUp = false;+ let directCanvas: HTMLCanvasElement | null = null;+ let directCtx: CanvasRenderingContext2D | null = null;+function cleanup() {if (isCleanedUp) return;isCleanedUp = true;@@ -134,6 +138,10 @@ export function createImageDataWS(worker.postMessage({ type: "resize", width, height });},hasRenderedFrame,+ initDirectCanvas: (canvas: HTMLCanvasElement) => {+ directCanvas = canvas;+ directCtx = canvas.getContext("2d", { alpha: false });+ },};worker.onmessage = (e: MessageEvent<WorkerMessage>) => {@@ -217,6 +225,54 @@ export function createImageDataWS(ws.onmessage = (event) => {const buffer = event.data as ArrayBuffer;+ if (directCanvas && directCtx) {+ const data = new Uint8Array(buffer);+ if (data.length >= 12) {+ const metadataOffset = data.length - 12;+ const meta = new DataView(buffer, metadataOffset, 12);+ const strideBytes = meta.getUint32(0, true);+ const height = meta.getUint32(4, true);+ const width = meta.getUint32(8, true);++ if (width > 0 && height > 0) {+ const expectedRowBytes = width * 4;+ let frameData: Uint8ClampedArray;++ if (strideBytes === expectedRowBytes) {+ frameData = new Uint8ClampedArray(+ buffer,+ 0,+ expectedRowBytes * height,+ );+ } else {+ frameData = new Uint8ClampedArray(expectedRowBytes * height);+ for (let row = 0; row < height; row++) {+ const srcStart = row * strideBytes;+ const destStart = row * expectedRowBytes;+ frameData.set(+ new Uint8ClampedArray(buffer, srcStart, expectedRowBytes),+ destStart,+ );+ }+ }++ if (directCanvas.width !== width || directCanvas.height !== height) {+ directCanvas.width = width;+ directCanvas.height = height;+ }++ const imageData = new ImageData(frameData, width, height);+ directCtx.putImageData(imageData, 0, 0);++ if (!hasRenderedFrame()) {+ setHasRenderedFrame(true);+ }+ onmessage({ width, height });+ }+ }+ return;+ }+if (isProcessing) {nextFrame = buffer;} else {diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex bdabd6466..dd122e78c 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -392,7 +392,7 @@ export type CornerStyle = "squircle" | "rounded"export type Crop = { position: XY<number>; size: XY<number> }export type CurrentRecording = { target: CurrentRecordingTarget; mode: RecordingMode; status: RecordingStatus }export type CurrentRecordingChanged = null-export type CurrentRecordingTarget = { window: { id: WindowId; bounds: LogicalBounds } } | { screen: { id: DisplayId } } | { area: { screen: DisplayId; bounds: LogicalBounds } }+export type CurrentRecordingTarget = { window: { id: WindowId; bounds: LogicalBounds | null } } | { screen: { id: DisplayId } } | { area: { screen: DisplayId; bounds: LogicalBounds } }export type CursorAnimationStyle = "slow" | "mellow" | "custom"export type CursorConfiguration = { hide?: boolean; hideWhenIdle?: boolean; hideWhenIdleDelay?: number; size: number; type: CursorType; animationStyle: CursorAnimationStyle; tension: number; mass: number; friction: number; raw?: boolean; motionBlur?: number; useSvg?: boolean }export type CursorMeta = { imagePath: string; hotspot: XY<number>; shape?: string | null }diff --git a/crates/mediafoundation-utils/src/lib.rs b/crates/mediafoundation-utils/src/lib.rsindex 5893a2e04..3ead730fc 100644--- a/crates/mediafoundation-utils/src/lib.rs+++ b/crates/mediafoundation-utils/src/lib.rs@@ -22,6 +22,7 @@ pub fn thread_init() {pub trait IMFMediaBufferExt {fn lock(&self) -> Result<IMFMediaBufferLock<'_>>;+ fn lock_for_write(&self) -> Result<IMFMediaBufferLock<'_>>;}impl IMFMediaBufferExt for IMFMediaBuffer {@@ -38,6 +39,20 @@ impl IMFMediaBufferExt for IMFMediaBuffer {bytes: unsafe { std::slice::from_raw_parts_mut(bytes_ptr, size as usize) },})}++ fn lock_for_write(&self) -> Result<IMFMediaBufferLock<'_>> {+ let mut bytes_ptr = null_mut();+ let mut max_length = 0;++ unsafe {+ self.Lock(&mut bytes_ptr, Some(&mut max_length), None)?;+ }++ Ok(IMFMediaBufferLock {+ source: self,+ bytes: unsafe { std::slice::from_raw_parts_mut(bytes_ptr, max_length as usize) },+ })+ }}pub struct IMFMediaBufferLock<'a> {diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rsindex c308820f7..7f53cf99a 100644--- a/crates/recording/src/capture_pipeline.rs+++ b/crates/recording/src/capture_pipeline.rs@@ -138,29 +138,41 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {) -> anyhow::Result<OutputPipeline> {let d3d_device = screen_capture.d3d_device.clone();- let actual_output_path = if fragmented {- output_path+ if fragmented {+ let fragments_dir = output_path.parent()- .map(|p| p.join("display.mp4"))- .unwrap_or_else(|| output_path.with_file_name("display.mp4"))- } else {- output_path.clone()- };+ .map(|p| p.join("display"))+ .unwrap_or_else(|| output_path.with_file_name("display"));- OutputPipeline::builder(actual_output_path)- .with_video::<screen_capture::VideoSource>(screen_capture)- .with_timestamps(start_time)- .build::<WindowsMuxer>(WindowsMuxerConfig {- pixel_format: screen_capture::Direct3DCapture::PIXEL_FORMAT.as_dxgi(),- d3d_device,- bitrate_multiplier: 0.15f32,- frame_rate: 30u32,- output_size: None,- encoder_preferences,- fragmented,- frag_duration_us: 2_000_000,- })- .await+ OutputPipeline::builder(fragments_dir)+ .with_video::<screen_capture::VideoSource>(screen_capture)+ .with_timestamps(start_time)+ .build::<WindowsSegmentedMuxer>(WindowsSegmentedMuxerConfig {+ pixel_format: screen_capture::Direct3DCapture::PIXEL_FORMAT.as_dxgi(),+ d3d_device,+ bitrate_multiplier: 0.15f32,+ frame_rate: 30u32,+ output_size: None,+ encoder_preferences,+ segment_duration: std::time::Duration::from_secs(3),+ })+ .await+ } else {+ OutputPipeline::builder(output_path.clone())+ .with_video::<screen_capture::VideoSource>(screen_capture)+ .with_timestamps(start_time)+ .build::<WindowsMuxer>(WindowsMuxerConfig {+ pixel_format: screen_capture::Direct3DCapture::PIXEL_FORMAT.as_dxgi(),+ d3d_device,+ bitrate_multiplier: 0.15f32,+ frame_rate: 30u32,+ output_size: None,+ encoder_preferences,+ fragmented: false,+ frag_duration_us: 2_000_000,+ })+ .await+ }}async fn make_instant_mode_pipeline(diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rsindex 73ed99a91..5d06df067 100644--- a/crates/recording/src/feeds/camera.rs+++ b/crates/recording/src/feeds/camera.rs@@ -507,7 +507,7 @@ async fn setup_camera(.try_send();if callback_num.is_multiple_of(30) {- tracing::debug!(+ tracing::trace!("Camera callback: sent frame {} to actor, result={:?}",callback_num,send_result.is_ok()@@ -564,7 +564,7 @@ async fn setup_camera(let data_len = bytes.len();if let Ok(buffer) = unsafe { MFCreateMemoryBuffer(data_len as u32) } {let buffer_ready = {- if let Ok(mut lock) = buffer.lock() {+ if let Ok(mut lock) = buffer.lock_for_write() {lock.copy_from_slice(&bytes);true} else {@@ -615,7 +615,7 @@ async fn setup_camera(.try_send();if callback_num.is_multiple_of(30) {- tracing::debug!(+ tracing::trace!("Camera callback: sent frame {} to actor, result={:?}",callback_num,send_result.is_ok()@@ -792,7 +792,7 @@ impl Message<NewFrame> for CameraFeed {let frame_num = CAMERA_FRAME_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);if frame_num.is_multiple_of(30) {- debug!(+ trace!("CameraFeed: received frame {}, broadcasting to {} senders",frame_num,self.senders.len()@@ -846,7 +846,7 @@ impl Message<NewNativeFrame> for CameraFeed {NATIVE_CAMERA_FRAME_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);if frame_num.is_multiple_of(30) {- debug!(+ trace!("CameraFeed: received native frame {}, broadcasting to {} native senders",frame_num,self.native_senders.len()diff --git a/crates/recording/src/output_pipeline/mod.rs b/crates/recording/src/output_pipeline/mod.rsindex 458b20d90..8087f6a40 100644--- a/crates/recording/src/output_pipeline/mod.rs+++ b/crates/recording/src/output_pipeline/mod.rs@@ -19,3 +19,13 @@ pub use macos::*;mod win;#[cfg(windows)]pub use win::*;++#[cfg(windows)]+mod win_segmented;+#[cfg(windows)]+pub use win_segmented::*;++#[cfg(windows)]+mod win_segmented_camera;+#[cfg(windows)]+pub use win_segmented_camera::*;diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rsindex 419cc7159..15a3842c1 100644--- a/crates/recording/src/output_pipeline/win.rs+++ b/crates/recording/src/output_pipeline/win.rs@@ -721,7 +721,7 @@ impl AudioMuxer for WindowsCameraMuxer {}}-fn upload_mf_buffer_to_texture(+pub fn upload_mf_buffer_to_texture(device: &ID3D11Device,frame: &NativeCameraFrame,) -> windows::core::Result<windows::Win32::Graphics::Direct3D11::ID3D11Texture2D> {diff --git a/crates/recording/src/output_pipeline/win_segmented.rs b/crates/recording/src/output_pipeline/win_segmented.rsnew file mode 100644index 000000000..0ecb1f717--- /dev/null+++ b/crates/recording/src/output_pipeline/win_segmented.rs@@ -0,0 +1,620 @@+use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer, screen_capture};+use anyhow::{Context, anyhow};+use cap_media_info::{AudioInfo, VideoInfo};+use serde::Serialize;+use std::{+ path::PathBuf,+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ mpsc::{SyncSender, sync_channel},+ },+ thread::JoinHandle,+ time::Duration,+};+use tracing::*;+use windows::{+ Foundation::TimeSpan,+ Graphics::SizeInt32,+ Win32::Graphics::{Direct3D11::ID3D11Device, Dxgi::Common::DXGI_FORMAT},+};++#[derive(Debug, Clone)]+pub struct SegmentInfo {+ pub path: PathBuf,+ pub index: u32,+ pub duration: Duration,+}++#[derive(Serialize)]+struct FragmentEntry {+ path: String,+ index: u32,+ duration: f64,+ is_complete: bool,+}++#[derive(Serialize)]+struct Manifest {+ fragments: Vec<FragmentEntry>,+ #[serde(skip_serializing_if = "Option::is_none")]+ total_duration: Option<f64>,+ is_complete: bool,+}++struct SegmentState {+ video_tx: SyncSender<Option<(scap_direct3d::Frame, Duration)>>,+ output: Arc<Mutex<ffmpeg::format::context::Output>>,+ encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,+}++struct PauseTracker {+ flag: Arc<AtomicBool>,+ paused_at: Option<Duration>,+ offset: Duration,+}++impl PauseTracker {+ fn new(flag: Arc<AtomicBool>) -> Self {+ Self {+ flag,+ paused_at: None,+ offset: Duration::ZERO,+ }+ }++ fn adjust(&mut self, timestamp: Duration) -> anyhow::Result<Option<Duration>> {+ if self.flag.load(Ordering::Relaxed) {+ if self.paused_at.is_none() {+ self.paused_at = Some(timestamp);+ }+ return Ok(None);+ }++ if let Some(start) = self.paused_at.take() {+ let delta = timestamp.checked_sub(start).ok_or_else(|| {+ anyhow!(+ "Frame timestamp went backward during unpause (resume={start:?}, current={timestamp:?})"+ )+ })?;++ self.offset = self.offset.checked_add(delta).ok_or_else(|| {+ anyhow!(+ "Pause offset overflow (offset={:?}, delta={delta:?})",+ self.offset+ )+ })?;+ }++ let adjusted = timestamp.checked_sub(self.offset).ok_or_else(|| {+ anyhow!(+ "Adjusted timestamp underflow (timestamp={timestamp:?}, offset={:?})",+ self.offset+ )+ })?;++ Ok(Some(adjusted))+ }+}++pub struct WindowsSegmentedMuxer {+ base_path: PathBuf,+ segment_duration: Duration,+ current_index: u32,+ segment_start_time: Option<Duration>,+ completed_segments: Vec<SegmentInfo>,++ current_state: Option<SegmentState>,++ video_config: VideoInfo,+ pixel_format: DXGI_FORMAT,+ d3d_device: ID3D11Device,+ frame_rate: u32,+ bitrate_multiplier: f32,+ output_size: Option<SizeInt32>,+ encoder_preferences: crate::capture_pipeline::EncoderPreferences,++ pause: PauseTracker,+}++pub struct WindowsSegmentedMuxerConfig {+ pub pixel_format: DXGI_FORMAT,+ pub d3d_device: ID3D11Device,+ pub frame_rate: u32,+ pub bitrate_multiplier: f32,+ pub output_size: Option<SizeInt32>,+ pub encoder_preferences: crate::capture_pipeline::EncoderPreferences,+ pub segment_duration: Duration,+}++impl Muxer for WindowsSegmentedMuxer {+ type Config = WindowsSegmentedMuxerConfig;++ async fn setup(+ config: Self::Config,+ output_path: PathBuf,+ video_config: Option<VideoInfo>,+ _audio_config: Option<AudioInfo>,+ pause_flag: Arc<AtomicBool>,+ _tasks: &mut TaskPool,+ ) -> anyhow::Result<Self>+ where+ Self: Sized,+ {+ let video_config =+ video_config.ok_or_else(|| anyhow!("invariant: video config expected"))?;++ std::fs::create_dir_all(&output_path)+ .with_context(|| format!("Failed to create segments directory: {output_path:?}"))?;++ Ok(Self {+ base_path: output_path,+ segment_duration: config.segment_duration,+ current_index: 0,+ segment_start_time: None,+ completed_segments: Vec::new(),+ current_state: None,+ video_config,+ pixel_format: config.pixel_format,+ d3d_device: config.d3d_device,+ frame_rate: config.frame_rate,+ bitrate_multiplier: config.bitrate_multiplier,+ output_size: config.output_size,+ encoder_preferences: config.encoder_preferences,+ pause: PauseTracker::new(pause_flag),+ })+ }++ fn stop(&mut self) {+ if let Some(state) = &self.current_state {+ let _ = state.video_tx.send(None);+ }+ }++ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ if let Some(segment_start) = self.segment_start_time {+ let final_duration = timestamp.saturating_sub(segment_start);++ self.completed_segments.push(SegmentInfo {+ path: self.current_segment_path(),+ index: self.current_index,+ duration: final_duration,+ });+ }++ if let Some(mut state) = self.current_state.take() {+ let _ = state.video_tx.send(None);++ if let Some(handle) = state.encoder_handle.take() {+ let timeout = Duration::from_secs(5);+ let start = std::time::Instant::now();+ loop {+ if handle.is_finished() {+ let _ = handle.join();+ break;+ }+ if start.elapsed() > timeout {+ warn!(+ "Screen encoder thread did not finish within {:?}, abandoning",+ timeout+ );+ break;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ }++ let mut output = state+ .output+ .lock()+ .map_err(|_| anyhow!("Failed to lock output"))?;+ output.write_trailer()?;+ }++ self.finalize_manifest();++ Ok(Ok(()))+ }+}++impl WindowsSegmentedMuxer {+ fn current_segment_path(&self) -> PathBuf {+ self.base_path+ .join(format!("fragment_{:03}.mp4", self.current_index))+ }++ fn write_manifest(&self) {+ let manifest = Manifest {+ fragments: self+ .completed_segments+ .iter()+ .map(|s| FragmentEntry {+ path: s+ .path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: s.index,+ duration: s.duration.as_secs_f64(),+ is_complete: true,+ })+ .collect(),+ total_duration: None,+ is_complete: false,+ };++ let manifest_path = self.base_path.join("manifest.json");+ let _ = std::fs::write(+ manifest_path,+ serde_json::to_string_pretty(&manifest).unwrap_or_default(),+ );+ }++ fn finalize_manifest(&self) {+ let total_duration: Duration = self.completed_segments.iter().map(|s| s.duration).sum();++ let manifest = Manifest {+ fragments: self+ .completed_segments+ .iter()+ .map(|s| FragmentEntry {+ path: s+ .path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: s.index,+ duration: s.duration.as_secs_f64(),+ is_complete: true,+ })+ .collect(),+ total_duration: Some(total_duration.as_secs_f64()),+ is_complete: true,+ };++ let manifest_path = self.base_path.join("manifest.json");+ let _ = std::fs::write(+ manifest_path,+ serde_json::to_string_pretty(&manifest).unwrap_or_default(),+ );+ }++ fn create_segment(&mut self) -> anyhow::Result<()> {+ let segment_path = self.current_segment_path();+ let input_size = SizeInt32 {+ Width: self.video_config.width as i32,+ Height: self.video_config.height as i32,+ };+ let output_size = self.output_size.unwrap_or(input_size);++ let (video_tx, video_rx) = sync_channel::<Option<(scap_direct3d::Frame, Duration)>>(8);+ let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);+ let output = ffmpeg::format::output(&segment_path)?;+ let output = Arc::new(Mutex::new(output));++ let d3d_device = self.d3d_device.clone();+ let pixel_format = self.pixel_format;+ let frame_rate = self.frame_rate;+ let bitrate_multiplier = self.bitrate_multiplier;+ let video_config = self.video_config;+ let encoder_preferences = self.encoder_preferences.clone();+ let output_clone = output.clone();++ let encoder_handle = std::thread::Builder::new()+ .name(format!("segment-encoder-{}", self.current_index))+ .spawn(move || {+ cap_mediafoundation_utils::thread_init();++ let encoder = (|| {+ let fallback = |reason: Option<String>| {+ encoder_preferences.force_software_only();+ if let Some(reason) = reason.as_ref() {+ error!("Falling back to software H264 encoder: {reason}");+ } else {+ info!("Falling back to software H264 encoder");+ }++ let fallback_width = if output_size.Width > 0 {+ output_size.Width as u32+ } else {+ video_config.width+ };+ let fallback_height = if output_size.Height > 0 {+ output_size.Height as u32+ } else {+ video_config.height+ };++ let mut output_guard = match output_clone.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ return Err(anyhow!(+ "ScreenSoftwareEncoder: failed to lock output mutex: {}",+ poisoned+ ));+ }+ };++ cap_enc_ffmpeg::h264::H264Encoder::builder(video_config)+ .with_output_size(fallback_width, fallback_height)+ .and_then(|builder| builder.build(&mut output_guard))+ .map(either::Right)+ .map_err(|e| anyhow!("ScreenSoftwareEncoder/{e}"))+ };++ if encoder_preferences.should_force_software() {+ return fallback(None);+ }++ match cap_enc_mediafoundation::H264Encoder::new_with_scaled_output(+ &d3d_device,+ pixel_format,+ input_size,+ output_size,+ frame_rate,+ bitrate_multiplier,+ ) {+ Ok(encoder) => {+ let width = match u32::try_from(output_size.Width) {+ Ok(width) if width > 0 => width,+ _ => {+ return fallback(Some(format!(+ "Invalid output width: {}",+ output_size.Width+ )));+ }+ };++ let height = match u32::try_from(output_size.Height) {+ Ok(height) if height > 0 => height,+ _ => {+ return fallback(Some(format!(+ "Invalid output height: {}",+ output_size.Height+ )));+ }+ };++ let muxer = {+ let mut output_guard = match output_clone.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ return fallback(Some(format!(+ "Failed to lock output mutex: {poisoned}"+ )));+ }+ };++ cap_mediafoundation_ffmpeg::H264StreamMuxer::new(+ &mut output_guard,+ cap_mediafoundation_ffmpeg::MuxerConfig {+ width,+ height,+ fps: frame_rate,+ bitrate: encoder.bitrate(),+ fragmented: false,+ frag_duration_us: 0,+ },+ )+ };++ match muxer {+ Ok(muxer) => Ok(either::Left((encoder, muxer))),+ Err(err) => fallback(Some(err.to_string())),+ }+ }+ Err(err) => fallback(Some(err.to_string())),+ }+ })();++ let encoder = match encoder {+ Ok(encoder) => {+ if ready_tx.send(Ok(())).is_err() {+ error!("Failed to send ready signal - receiver dropped");+ return Ok(());+ }+ encoder+ }+ Err(e) => {+ error!("Encoder setup failed: {:#}", e);+ let _ = ready_tx.send(Err(anyhow!("{e}")));+ return Err(anyhow!("{e}"));+ }+ };++ match encoder {+ either::Left((mut encoder, mut muxer)) => {+ trace!("Running native encoder for segment");+ let mut first_timestamp: Option<Duration> = None;+ encoder+ .run(+ Arc::new(AtomicBool::default()),+ || {+ let Ok(Some((frame, timestamp))) = video_rx.recv() else {+ trace!("No more frames available for segment");+ return Ok(None);+ };++ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };+ let frame_time = duration_to_timespan(relative);++ Ok(Some((frame.texture().clone(), frame_time)))+ },+ |output_sample| {+ let mut output = output_clone.lock().unwrap();++ let _ = muxer+ .write_sample(&output_sample, &mut output)+ .map_err(|e| format!("WriteSample: {e}"));++ Ok(())+ },+ )+ .context("run native encoder for segment")+ }+ either::Right(mut encoder) => {+ while let Ok(Some((frame, time))) = video_rx.recv() {+ let Ok(mut output) = output_clone.lock() else {+ continue;+ };++ use scap_ffmpeg::AsFFmpeg;++ frame+ .as_ffmpeg()+ .context("frame as_ffmpeg")+ .and_then(|frame| {+ encoder+ .queue_frame(frame, time, &mut output)+ .context("queue_frame")+ })?;+ }++ Ok(())+ }+ }+ })?;++ ready_rx+ .recv()+ .map_err(|_| anyhow!("Encoder thread ended unexpectedly"))??;++ output.lock().unwrap().write_header()?;++ self.current_state = Some(SegmentState {+ video_tx,+ output,+ encoder_handle: Some(encoder_handle),+ });++ Ok(())+ }++ fn rotate_segment(&mut self, timestamp: Duration) -> anyhow::Result<()> {+ let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);+ let segment_duration = timestamp.saturating_sub(segment_start);++ if let Some(mut state) = self.current_state.take() {+ let _ = state.video_tx.send(None);++ if let Some(handle) = state.encoder_handle.take() {+ let timeout = Duration::from_secs(5);+ let start = std::time::Instant::now();+ loop {+ if handle.is_finished() {+ let _ = handle.join();+ break;+ }+ if start.elapsed() > timeout {+ warn!(+ "Screen encoder thread did not finish within {:?} during rotation, abandoning",+ timeout+ );+ break;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ }++ let mut output = state+ .output+ .lock()+ .map_err(|_| anyhow!("Failed to lock output"))?;+ output.write_trailer()?;++ self.completed_segments.push(SegmentInfo {+ path: self.current_segment_path(),+ index: self.current_index,+ duration: segment_duration,+ });+ }++ self.current_index += 1;+ self.segment_start_time = Some(timestamp);++ self.create_segment()?;+ self.write_manifest();++ info!(+ "Rotated to segment {} at {:?}",+ self.current_index, timestamp+ );++ Ok(())+ }+}++impl VideoMuxer for WindowsSegmentedMuxer {+ type VideoFrame = screen_capture::VideoFrame;++ fn send_video_frame(+ &mut self,+ frame: Self::VideoFrame,+ timestamp: Duration,+ ) -> anyhow::Result<()> {+ let Some(adjusted_timestamp) = self.pause.adjust(timestamp)? else {+ return Ok(());+ };++ if self.current_state.is_none() {+ self.segment_start_time = Some(adjusted_timestamp);+ self.create_segment()?;+ }++ if self.segment_start_time.is_none() {+ self.segment_start_time = Some(adjusted_timestamp);+ }++ let segment_elapsed =+ adjusted_timestamp.saturating_sub(self.segment_start_time.unwrap_or(Duration::ZERO));++ if segment_elapsed >= self.segment_duration {+ self.rotate_segment(adjusted_timestamp)?;+ }++ if let Some(state) = &self.current_state {+ if let Err(e) = state+ .video_tx+ .try_send(Some((frame.frame, adjusted_timestamp)))+ {+ match e {+ std::sync::mpsc::TrySendError::Full(_) => {+ trace!("Screen encoder channel full, dropping frame");+ }+ std::sync::mpsc::TrySendError::Disconnected(_) => {+ trace!("Screen encoder channel disconnected");+ }+ }+ }+ }++ Ok(())+ }+}++impl AudioMuxer for WindowsSegmentedMuxer {+ fn send_audio_frame(&mut self, _frame: AudioFrame, _timestamp: Duration) -> anyhow::Result<()> {+ Ok(())+ }+}++fn duration_to_timespan(duration: Duration) -> TimeSpan {+ const TICKS_PER_SEC: u64 = 10_000_000;+ const NANOS_PER_TICK: u32 = 100;++ let secs_ticks = duration.as_secs().saturating_mul(TICKS_PER_SEC);+ let nanos_ticks = (duration.subsec_nanos() / NANOS_PER_TICK) as u64;+ let total_ticks = secs_ticks.saturating_add(nanos_ticks);+ let clamped = total_ticks.min(i64::MAX as u64);++ TimeSpan {+ Duration: clamped as i64,+ }+}diff --git a/crates/recording/src/output_pipeline/win_segmented_camera.rs b/crates/recording/src/output_pipeline/win_segmented_camera.rsnew file mode 100644index 000000000..c50dcefb4--- /dev/null+++ b/crates/recording/src/output_pipeline/win_segmented_camera.rs@@ -0,0 +1,552 @@+use crate::output_pipeline::win::{NativeCameraFrame, upload_mf_buffer_to_texture};+use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer};+use anyhow::{Context, anyhow};+use cap_media_info::{AudioInfo, VideoInfo};+use serde::Serialize;+use std::{+ path::PathBuf,+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ mpsc::{SyncSender, sync_channel},+ },+ thread::JoinHandle,+ time::Duration,+};+use tracing::*;+use windows::{Foundation::TimeSpan, Graphics::SizeInt32};++#[derive(Debug, Clone)]+struct SegmentInfo {+ path: PathBuf,+ index: u32,+ duration: Duration,+}++#[derive(Serialize)]+struct FragmentEntry {+ path: String,+ index: u32,+ duration: f64,+ is_complete: bool,+}++#[derive(Serialize)]+struct Manifest {+ fragments: Vec<FragmentEntry>,+ #[serde(skip_serializing_if = "Option::is_none")]+ total_duration: Option<f64>,+ is_complete: bool,+}++struct SegmentState {+ video_tx: SyncSender<Option<(NativeCameraFrame, Duration)>>,+ output: Arc<Mutex<ffmpeg::format::context::Output>>,+ encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,+}++struct PauseTracker {+ flag: Arc<AtomicBool>,+ paused_at: Option<Duration>,+ offset: Duration,+}++impl PauseTracker {+ fn new(flag: Arc<AtomicBool>) -> Self {+ Self {+ flag,+ paused_at: None,+ offset: Duration::ZERO,+ }+ }++ fn adjust(&mut self, timestamp: Duration) -> anyhow::Result<Option<Duration>> {+ if self.flag.load(Ordering::Relaxed) {+ if self.paused_at.is_none() {+ self.paused_at = Some(timestamp);+ }+ return Ok(None);+ }++ if let Some(start) = self.paused_at.take() {+ let delta = timestamp.checked_sub(start).ok_or_else(|| {+ anyhow!(+ "Frame timestamp went backward during unpause (resume={start:?}, current={timestamp:?})"+ )+ })?;++ self.offset = self.offset.checked_add(delta).ok_or_else(|| {+ anyhow!(+ "Pause offset overflow (offset={:?}, delta={delta:?})",+ self.offset+ )+ })?;+ }++ let adjusted = timestamp.checked_sub(self.offset).ok_or_else(|| {+ anyhow!(+ "Adjusted timestamp underflow (timestamp={timestamp:?}, offset={:?})",+ self.offset+ )+ })?;++ Ok(Some(adjusted))+ }+}++pub struct WindowsSegmentedCameraMuxer {+ base_path: PathBuf,+ segment_duration: Duration,+ current_index: u32,+ segment_start_time: Option<Duration>,+ completed_segments: Vec<SegmentInfo>,++ current_state: Option<SegmentState>,++ video_config: VideoInfo,+ output_height: Option<u32>,++ pause: PauseTracker,+}++pub struct WindowsSegmentedCameraMuxerConfig {+ pub output_height: Option<u32>,+ pub segment_duration: Duration,+}++impl Default for WindowsSegmentedCameraMuxerConfig {+ fn default() -> Self {+ Self {+ output_height: None,+ segment_duration: Duration::from_secs(3),+ }+ }+}++impl Muxer for WindowsSegmentedCameraMuxer {+ type Config = WindowsSegmentedCameraMuxerConfig;++ async fn setup(+ config: Self::Config,+ output_path: PathBuf,+ video_config: Option<VideoInfo>,+ _audio_config: Option<AudioInfo>,+ pause_flag: Arc<AtomicBool>,+ _tasks: &mut TaskPool,+ ) -> anyhow::Result<Self>+ where+ Self: Sized,+ {+ let video_config =+ video_config.ok_or_else(|| anyhow!("invariant: video config expected"))?;++ std::fs::create_dir_all(&output_path)+ .with_context(|| format!("Failed to create segments directory: {output_path:?}"))?;++ Ok(Self {+ base_path: output_path,+ segment_duration: config.segment_duration,+ current_index: 0,+ segment_start_time: None,+ completed_segments: Vec::new(),+ current_state: None,+ video_config,+ output_height: config.output_height,+ pause: PauseTracker::new(pause_flag),+ })+ }++ fn stop(&mut self) {+ if let Some(state) = &self.current_state {+ let _ = state.video_tx.send(None);+ }+ }++ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ if let Some(segment_start) = self.segment_start_time {+ let final_duration = timestamp.saturating_sub(segment_start);++ self.completed_segments.push(SegmentInfo {+ path: self.current_segment_path(),+ index: self.current_index,+ duration: final_duration,+ });+ }++ if let Some(mut state) = self.current_state.take() {+ let _ = state.video_tx.send(None);++ if let Some(handle) = state.encoder_handle.take() {+ let timeout = Duration::from_secs(5);+ let start = std::time::Instant::now();+ loop {+ if handle.is_finished() {+ let _ = handle.join();+ break;+ }+ if start.elapsed() > timeout {+ warn!(+ "Camera encoder thread did not finish within {:?}, abandoning",+ timeout+ );+ break;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ }++ let mut output = state+ .output+ .lock()+ .map_err(|_| anyhow!("Failed to lock output"))?;+ output.write_trailer()?;+ }++ self.finalize_manifest();++ Ok(Ok(()))+ }+}++impl WindowsSegmentedCameraMuxer {+ fn current_segment_path(&self) -> PathBuf {+ self.base_path+ .join(format!("fragment_{:03}.mp4", self.current_index))+ }++ fn write_manifest(&self) {+ let manifest = Manifest {+ fragments: self+ .completed_segments+ .iter()+ .map(|s| FragmentEntry {+ path: s+ .path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: s.index,+ duration: s.duration.as_secs_f64(),+ is_complete: true,+ })+ .collect(),+ total_duration: None,+ is_complete: false,+ };++ let manifest_path = self.base_path.join("manifest.json");+ let _ = std::fs::write(+ manifest_path,+ serde_json::to_string_pretty(&manifest).unwrap_or_default(),+ );+ }++ fn finalize_manifest(&self) {+ let total_duration: Duration = self.completed_segments.iter().map(|s| s.duration).sum();++ let manifest = Manifest {+ fragments: self+ .completed_segments+ .iter()+ .map(|s| FragmentEntry {+ path: s+ .path+ .file_name()+ .unwrap_or_default()+ .to_string_lossy()+ .into_owned(),+ index: s.index,+ duration: s.duration.as_secs_f64(),+ is_complete: true,+ })+ .collect(),+ total_duration: Some(total_duration.as_secs_f64()),+ is_complete: true,+ };++ let manifest_path = self.base_path.join("manifest.json");+ let _ = std::fs::write(+ manifest_path,+ serde_json::to_string_pretty(&manifest).unwrap_or_default(),+ );+ }++ fn create_segment(&mut self, first_frame: &NativeCameraFrame) -> anyhow::Result<()> {+ let segment_path = self.current_segment_path();++ let input_size = SizeInt32 {+ Width: self.video_config.width as i32,+ Height: self.video_config.height as i32,+ };++ let output_height = self.output_height.unwrap_or(self.video_config.height);+ let output_width = (self.video_config.width * output_height) / self.video_config.height;+ let output_width = output_width & !1;+ let output_height = output_height & !1;++ let output_size = SizeInt32 {+ Width: output_width as i32,+ Height: output_height as i32,+ };++ let frame_rate = self.video_config.fps();+ let bitrate_multiplier = 0.2f32;+ let input_format = first_frame.dxgi_format();++ let (video_tx, video_rx) = sync_channel::<Option<(NativeCameraFrame, Duration)>>(30);+ let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);+ let output = ffmpeg::format::output(&segment_path)?;+ let output = Arc::new(Mutex::new(output));+ let output_clone = output.clone();++ let encoder_handle = std::thread::Builder::new()+ .name(format!("camera-segment-encoder-{}", self.current_index))+ .spawn(move || {+ cap_mediafoundation_utils::thread_init();++ let d3d_device = match crate::capture_pipeline::create_d3d_device() {+ Ok(device) => device,+ Err(e) => {+ let _ = ready_tx.send(Err(anyhow!("Failed to create D3D device: {e}")));+ return Err(anyhow!("Failed to create D3D device: {e}"));+ }+ };++ let encoder_result = cap_enc_mediafoundation::H264Encoder::new_with_scaled_output(+ &d3d_device,+ input_format,+ input_size,+ output_size,+ frame_rate,+ bitrate_multiplier,+ );++ let (mut encoder, mut muxer) = match encoder_result {+ Ok(encoder) => {+ let muxer = {+ let mut output_guard = match output_clone.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ let _ = ready_tx.send(Err(anyhow!(+ "Failed to lock output mutex: {poisoned}"+ )));+ return Err(anyhow!(+ "Failed to lock output mutex: {}",+ poisoned+ ));+ }+ };++ cap_mediafoundation_ffmpeg::H264StreamMuxer::new(+ &mut output_guard,+ cap_mediafoundation_ffmpeg::MuxerConfig {+ width: output_width,+ height: output_height,+ fps: frame_rate,+ bitrate: encoder.bitrate(),+ fragmented: false,+ frag_duration_us: 0,+ },+ )+ };++ match muxer {+ Ok(muxer) => (encoder, muxer),+ Err(err) => {+ let _ =+ ready_tx.send(Err(anyhow!("Failed to create muxer: {err}")));+ return Err(anyhow!("Failed to create muxer: {err}"));+ }+ }+ }+ Err(err) => {+ let _ = ready_tx.send(Err(anyhow!("Failed to create H264 encoder: {err}")));+ return Err(anyhow!("Failed to create H264 encoder: {err}"));+ }+ };++ if ready_tx.send(Ok(())).is_err() {+ error!("Failed to send ready signal - receiver dropped");+ return Ok(());+ }++ info!(+ "Camera segment encoder started: {:?} {}x{} -> NV12 {}x{} @ {}fps",+ input_format,+ input_size.Width,+ input_size.Height,+ output_size.Width,+ output_size.Height,+ frame_rate+ );++ let mut first_timestamp: Option<Duration> = None;++ encoder+ .run(+ Arc::new(AtomicBool::default()),+ || {+ let Ok(Some((frame, timestamp))) = video_rx.recv() else {+ trace!("No more camera frames available for segment");+ return Ok(None);+ };++ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };++ let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;+ Ok(Some((texture, duration_to_timespan(relative))))+ },+ |output_sample| {+ let mut output = output_clone.lock().unwrap();+ let _ = muxer+ .write_sample(&output_sample, &mut output)+ .map_err(|e| format!("WriteSample: {e}"));+ Ok(())+ },+ )+ .context("run camera encoder for segment")+ })?;++ ready_rx+ .recv()+ .map_err(|_| anyhow!("Camera encoder thread ended unexpectedly"))??;++ output.lock().unwrap().write_header()?;++ self.current_state = Some(SegmentState {+ video_tx,+ output,+ encoder_handle: Some(encoder_handle),+ });++ Ok(())+ }++ fn rotate_segment(+ &mut self,+ timestamp: Duration,+ next_frame: &NativeCameraFrame,+ ) -> anyhow::Result<()> {+ let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);+ let segment_duration = timestamp.saturating_sub(segment_start);++ if let Some(mut state) = self.current_state.take() {+ let _ = state.video_tx.send(None);++ if let Some(handle) = state.encoder_handle.take() {+ let timeout = Duration::from_secs(5);+ let start = std::time::Instant::now();+ loop {+ if handle.is_finished() {+ let _ = handle.join();+ break;+ }+ if start.elapsed() > timeout {+ warn!(+ "Camera encoder thread did not finish within {:?} during rotation, abandoning",+ timeout+ );+ break;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ }++ let mut output = state+ .output+ .lock()+ .map_err(|_| anyhow!("Failed to lock output"))?;+ output.write_trailer()?;++ self.completed_segments.push(SegmentInfo {+ path: self.current_segment_path(),+ index: self.current_index,+ duration: segment_duration,+ });+ }++ self.current_index += 1;+ self.segment_start_time = Some(timestamp);++ self.create_segment(next_frame)?;+ self.write_manifest();++ info!(+ "Camera rotated to segment {} at {:?}",+ self.current_index, timestamp+ );++ Ok(())+ }+}++impl VideoMuxer for WindowsSegmentedCameraMuxer {+ type VideoFrame = NativeCameraFrame;++ fn send_video_frame(+ &mut self,+ frame: Self::VideoFrame,+ timestamp: Duration,+ ) -> anyhow::Result<()> {+ let Some(adjusted_timestamp) = self.pause.adjust(timestamp)? else {+ return Ok(());+ };++ if self.current_state.is_none() {+ self.segment_start_time = Some(adjusted_timestamp);+ self.create_segment(&frame)?;+ }++ if self.segment_start_time.is_none() {+ self.segment_start_time = Some(adjusted_timestamp);+ }++ let segment_elapsed =+ adjusted_timestamp.saturating_sub(self.segment_start_time.unwrap_or(Duration::ZERO));++ if segment_elapsed >= self.segment_duration {+ self.rotate_segment(adjusted_timestamp, &frame)?;+ }++ if let Some(state) = &self.current_state {+ if let Err(e) = state.video_tx.try_send(Some((frame, adjusted_timestamp))) {+ match e {+ std::sync::mpsc::TrySendError::Full(_) => {+ trace!("Camera encoder channel full, dropping frame");+ }+ std::sync::mpsc::TrySendError::Disconnected(_) => {+ trace!("Camera encoder channel disconnected");+ }+ }+ }+ }++ Ok(())+ }+}++impl AudioMuxer for WindowsSegmentedCameraMuxer {+ fn send_audio_frame(&mut self, _frame: AudioFrame, _timestamp: Duration) -> anyhow::Result<()> {+ Ok(())+ }+}++fn duration_to_timespan(duration: Duration) -> TimeSpan {+ const TICKS_PER_SEC: u64 = 10_000_000;+ const NANOS_PER_TICK: u32 = 100;++ let secs_ticks = duration.as_secs().saturating_mul(TICKS_PER_SEC);+ let nanos_ticks = (duration.subsec_nanos() / NANOS_PER_TICK) as u64;+ let total_ticks = secs_ticks.saturating_add(nanos_ticks);+ let clamped = total_ticks.min(i64::MAX as u64);++ TimeSpan {+ Duration: clamped as i64,+ }+}diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 592679b8b..443da9cd2 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -18,7 +18,10 @@ use crate::output_pipeline::{};#[cfg(windows)]-use crate::output_pipeline::{WindowsCameraMuxer, WindowsCameraMuxerConfig};+use crate::output_pipeline::{+ WindowsCameraMuxer, WindowsCameraMuxerConfig, WindowsSegmentedCameraMuxer,+ WindowsSegmentedCameraMuxerConfig,+};use anyhow::{Context as _, anyhow, bail};use cap_media_info::VideoInfo;use cap_project::{@@ -901,16 +904,27 @@ async fn create_segment_pipeline(};#[cfg(windows)]- let camera = OptionFuture::from(base_inputs.camera_feed.map(|camera_feed| {- OutputPipeline::builder(dir.join("camera.mp4"))- .with_video::<sources::NativeCamera>(camera_feed)- .with_timestamps(start_time)- .build::<WindowsCameraMuxer>(WindowsCameraMuxerConfig::default())- .instrument(error_span!("camera-out"))- }))- .await- .transpose()- .context("camera pipeline setup")?;+ let camera = if let Some(camera_feed) = base_inputs.camera_feed {+ let pipeline = if fragmented {+ let fragments_dir = dir.join("camera");+ OutputPipeline::builder(fragments_dir)+ .with_video::<sources::NativeCamera>(camera_feed)+ .with_timestamps(start_time)+ .build::<WindowsSegmentedCameraMuxer>(WindowsSegmentedCameraMuxerConfig::default())+ .instrument(error_span!("camera-out"))+ .await+ } else {+ OutputPipeline::builder(dir.join("camera.mp4"))+ .with_video::<sources::NativeCamera>(camera_feed)+ .with_timestamps(start_time)+ .build::<WindowsCameraMuxer>(WindowsCameraMuxerConfig::default())+ .instrument(error_span!("camera-out"))+ .await+ };+ Some(pipeline.context("camera pipeline setup")?)+ } else {+ None+ };let microphone = if let Some(mic_feed) = base_inputs.mic_feed {let pipeline = if fragmented {diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rsindex e4742b115..01f8e6afc 100644--- a/crates/rendering/src/composite_frame.rs+++ b/crates/rendering/src/composite_frame.rs@@ -187,7 +187,7 @@ impl CompositeVideoFramePipeline {mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,usage: wgpu::TextureUsages::TEXTURE_BINDING| wgpu::TextureUsages::RENDER_ATTACHMENT| wgpu::TextureUsages::COPY_DST,diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rsindex bbeeef8c3..49084728e 100644--- a/crates/rendering/src/frame_pipeline.rs+++ b/crates/rendering/src/frame_pipeline.rs@@ -195,7 +195,7 @@ impl RenderSession {mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,usage: wgpu::TextureUsages::TEXTURE_BINDING| wgpu::TextureUsages::RENDER_ATTACHMENT| wgpu::TextureUsages::COPY_SRC,@@ -230,7 +230,7 @@ impl RenderSession {mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,usage: wgpu::TextureUsages::TEXTURE_BINDING| wgpu::TextureUsages::RENDER_ATTACHMENT| wgpu::TextureUsages::COPY_SRC,diff --git a/crates/rendering/src/layers/background.rs b/crates/rendering/src/layers/background.rsindex 199245f58..7413117bf 100644--- a/crates/rendering/src/layers/background.rs+++ b/crates/rendering/src/layers/background.rs@@ -136,7 +136,7 @@ impl BackgroundLayer {mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,usage: wgpu::TextureUsages::TEXTURE_BINDING| wgpu::TextureUsages::COPY_DST,view_formats: &[],@@ -337,7 +337,7 @@ impl ImageBackgroundPipeline {module: &shader,entry_point: Some("fs_main"),targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,blend: Some(wgpu::BlendState::REPLACE),write_mask: wgpu::ColorWrites::ALL,})],diff --git a/crates/rendering/src/layers/blur.rs b/crates/rendering/src/layers/blur.rsindex 2aa75c82c..59e202ac5 100644--- a/crates/rendering/src/layers/blur.rs+++ b/crates/rendering/src/layers/blur.rs@@ -148,7 +148,7 @@ impl BlurPipeline {module: &shader,entry_point: Some("fs_main"),targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,blend: Some(wgpu::BlendState::REPLACE),write_mask: wgpu::ColorWrites::ALL,})],diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rsindex 85ec8a4ba..17754734e 100644--- a/crates/rendering/src/layers/camera.rs+++ b/crates/rendering/src/layers/camera.rs@@ -213,7 +213,7 @@ impl CameraLayer {{pass.set_pipeline(&self.pipeline.render_pipeline);pass.set_bind_group(0, bind_group, &[]);- pass.draw(0..4, 0..1);+ pass.draw(0..3, 0..1);}}}diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rsindex 667b1a3f3..b17b451bb 100644--- a/crates/rendering/src/layers/captions.rs+++ b/crates/rendering/src/layers/captions.rs@@ -265,8 +265,7 @@ impl CaptionsLayer {let swash_cache = SwashCache::new();let cache = Cache::new(device);let viewport = Viewport::new(device, &cache);- let mut text_atlas =- TextAtlas::new(device, queue, &cache, wgpu::TextureFormat::Rgba8UnormSrgb);+ let mut text_atlas = TextAtlas::new(device, queue, &cache, wgpu::TextureFormat::Rgba8Unorm);let text_renderer = TextRenderer::new(&mut text_atlas,device,@@ -339,7 +338,7 @@ impl CaptionsLayer {module: &background_shader,entry_point: Some("fs_main"),targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,blend: Some(wgpu::BlendState::ALPHA_BLENDING),write_mask: wgpu::ColorWrites::ALL,})],diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rsindex 59ce16359..2fa10cbbd 100644--- a/crates/rendering/src/layers/cursor.rs+++ b/crates/rendering/src/layers/cursor.rs@@ -102,7 +102,7 @@ impl Statics {module: &shader,entry_point: Some("fs_main"),targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,blend: Some(wgpu::BlendState {color: wgpu::BlendComponent {src_factor: wgpu::BlendFactor::One,@@ -677,7 +677,7 @@ impl CursorTexture {mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,view_formats: &[],});diff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rsindex f6aee5362..701a34b37 100644--- a/crates/rendering/src/layers/display.rs+++ b/crates/rendering/src/layers/display.rs@@ -69,6 +69,15 @@ impl DisplayLayer {let format = segment_frames.screen_frame.format();let current_recording_time = segment_frames.recording_time;+ tracing::trace!(+ format = ?format,+ actual_width,+ actual_height,+ frame_data_len = frame_data.len(),+ recording_time = current_recording_time,+ "DisplayLayer::prepare - frame info"+ );+let skipped = self.last_recording_time.is_some_and(|last| (last - current_recording_time).abs() < f32::EPSILON);@@ -197,6 +206,7 @@ impl DisplayLayer {{let y_stride = screen_frame.y_stride();let uv_stride = screen_frame.uv_stride();+let convert_result = self.yuv_converter.convert_nv12(device,queue,@@ -208,6 +218,10 @@ impl DisplayLayer {uv_stride,);+ if let Err(e) = device.poll(wgpu::PollType::Wait) {+ tracing::warn!(error = ?e, "Failed to poll device after NV12 conversion");+ }+match convert_result {Ok(_) => {if self.yuv_converter.output_texture().is_some() {@@ -218,25 +232,10 @@ impl DisplayLayer {});true} else {- tracing::debug!(- width = frame_size.x,- height = frame_size.y,- y_stride,- "NV12 conversion succeeded but output texture is None, skipping copy"- );false}}- Err(e) => {- tracing::debug!(- error = ?e,- width = frame_size.x,- height = frame_size.y,- y_stride,- "NV12 to RGBA conversion failed"- );- false- }+ Err(_) => false,}} else {false@@ -244,13 +243,13 @@ impl DisplayLayer {}PixelFormat::Yuv420p => {let screen_frame = &segment_frames.screen_frame;- if let (Some(y_data), Some(u_data), Some(v_data)) = (- screen_frame.y_plane(),- screen_frame.u_plane(),- screen_frame.v_plane(),- ) && self- .yuv_converter- .convert_yuv420p(+ let y_plane = screen_frame.y_plane();+ let u_plane = screen_frame.u_plane();+ let v_plane = screen_frame.v_plane();++ if let (Some(y_data), Some(u_data), Some(v_data)) = (y_plane, u_plane, v_plane)+ {+ let convert_result = self.yuv_converter.convert_yuv420p(device,queue,y_data,@@ -260,16 +259,27 @@ impl DisplayLayer {frame_size.y,screen_frame.y_stride(),screen_frame.uv_stride(),- )- .is_ok()- && self.yuv_converter.output_texture().is_some()- {- self.pending_copy = Some(PendingTextureCopy {- width: frame_size.x,- height: frame_size.y,- dst_texture_index: next_texture,- });- true+ );++ if let Err(e) = device.poll(wgpu::PollType::Wait) {+ tracing::warn!(error = ?e, "Failed to poll device after YUV420P conversion");+ }++ match convert_result {+ Ok(_) => {+ if self.yuv_converter.output_texture().is_some() {+ self.pending_copy = Some(PendingTextureCopy {+ width: frame_size.x,+ height: frame_size.y,+ dst_texture_index: next_texture,+ });+ true+ } else {+ false+ }+ }+ Err(_) => false,+ }} else {false}@@ -288,10 +298,12 @@ impl DisplayLayer {pub fn copy_to_texture(&mut self, encoder: &mut wgpu::CommandEncoder) {let Some(pending) = self.pending_copy.take() else {+ tracing::trace!("copy_to_texture: no pending copy");return;};let Some(src_texture) = self.yuv_converter.output_texture() else {+ tracing::warn!("copy_to_texture: no source texture from YUV converter");return;};@@ -318,9 +330,18 @@ impl DisplayLayer {pub fn render(&self, pass: &mut wgpu::RenderPass<'_>) {if let Some(bind_group) = &self.bind_groups[self.current_texture] {+ tracing::trace!(+ current_texture_index = self.current_texture,+ "DisplayLayer::render - rendering with bind group"+ );pass.set_pipeline(&self.pipeline.render_pipeline);pass.set_bind_group(0, bind_group, &[]);- pass.draw(0..4, 0..1);+ pass.draw(0..3, 0..1);+ } else {+ tracing::warn!(+ current_texture_index = self.current_texture,+ "DisplayLayer::render - no bind group available"+ );}}}diff --git a/crates/rendering/src/layers/mask.rs b/crates/rendering/src/layers/mask.rsindex daf62fac4..58192660b 100644--- a/crates/rendering/src/layers/mask.rs+++ b/crates/rendering/src/layers/mask.rs@@ -176,7 +176,7 @@ impl MaskPipeline {module: &shader,entry_point: Some("fs_main"),targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,blend: Some(wgpu::BlendState::REPLACE),write_mask: wgpu::ColorWrites::ALL,})],diff --git a/crates/rendering/src/layers/text.rs b/crates/rendering/src/layers/text.rsindex 5891efbe0..59265eeb1 100644--- a/crates/rendering/src/layers/text.rs+++ b/crates/rendering/src/layers/text.rs@@ -23,8 +23,7 @@ impl TextLayer {let swash_cache = SwashCache::new();let cache = Cache::new(device);let viewport = Viewport::new(device, &cache);- let mut text_atlas =- TextAtlas::new(device, queue, &cache, wgpu::TextureFormat::Rgba8UnormSrgb);+ let mut text_atlas = TextAtlas::new(device, queue, &cache, wgpu::TextureFormat::Rgba8Unorm);let text_renderer = TextRenderer::new(&mut text_atlas,device,diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 7aa34d19a..0f0167a2a 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -1735,12 +1735,20 @@ impl RendererLayers {session.swap_textures();}- if uniforms.scene.should_render_screen() {+ let should_render = uniforms.scene.should_render_screen();+ tracing::trace!(+ should_render_screen = should_render,+ screen_opacity = uniforms.scene.screen_opacity,+ screen_blur = uniforms.scene.screen_blur,+ "RendererLayers::render - checking should_render_screen"+ );++ if should_render {let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);self.display.render(&mut pass);}- if uniforms.scene.should_render_screen() {+ if should_render {let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);self.cursor.render(&mut pass);}@@ -1860,7 +1868,7 @@ pub fn create_shader_render_pipeline(module: &shader,entry_point: Some("fs_main"),targets: &[Some(wgpu::ColorTargetState {- format: wgpu::TextureFormat::Rgba8UnormSrgb,+ format: wgpu::TextureFormat::Rgba8Unorm,blend: Some(wgpu::BlendState::ALPHA_BLENDING),write_mask: wgpu::ColorWrites::ALL,})],diff --git a/crates/scap-direct3d/src/lib.rs b/crates/scap-direct3d/src/lib.rsindex 4ed2bdaec..ac704e934 100644--- a/crates/scap-direct3d/src/lib.rs+++ b/crates/scap-direct3d/src/lib.rs@@ -147,7 +147,9 @@ pub struct Capturer {d3d_device: ID3D11Device,d3d_context: ID3D11DeviceContext,session: GraphicsCaptureSession,- _frame_pool: Direct3D11CaptureFramePool,+ frame_pool: Direct3D11CaptureFramePool,+ frame_arrived_token: i64,+ stop_flag: Arc<AtomicBool>,}impl Capturer {@@ -265,11 +267,12 @@ impl Capturer {}).transpose()?;- frame_pool+ let frame_arrived_token = frame_pool.FrameArrived(&TypedEventHandler::<Direct3D11CaptureFramePool, IInspectable>::new({let d3d_context = d3d_context.clone();let d3d_device = d3d_device.clone();+ let stop_flag = stop_flag.clone();move |frame_pool, _| {if stop_flag.load(Ordering::Relaxed) {@@ -337,11 +340,12 @@ impl Capturer {Ok(Capturer {settings,- // thread_handle: None,d3d_device,d3d_context,session,- _frame_pool: frame_pool,+ frame_pool,+ frame_arrived_token,+ stop_flag,})}@@ -380,7 +384,12 @@ pub enum StopCapturerError {impl Capturer {pub fn stop(&mut self) -> windows::core::Result<()> {- self.session.Close()+ if self.stop_flag.swap(true, Ordering::SeqCst) {+ return Ok(());+ }+ let _ = self.frame_pool.RemoveFrameArrived(self.frame_arrived_token);+ let _ = self.session.Close();+ self.frame_pool.Close()}}