Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: preserve requested media and recording lifecycle
Richie McIlroy3feb85d3a479
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex 1342331d8..8c0a790f7 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -447,6 +447,14 @@ struct CompletionsArgs {}fn main() {+ #[cfg(target_os = "linux")]+ if let Some(threads) = cap_utils::linux_runtime::llvmpipe_thread_count() {+ // Mesa counts host CPUs inside containers; configure it before creating the CLI runtime.+ unsafe {+ std::env::set_var("LP_NUM_THREADS", threads.to_string());+ }+ }+#[cfg(windows)]{use windows::Win32::UI::HiDpi::{PROCESS_PER_MONITOR_DPI_AWARE, SetProcessDpiAwareness};diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rsindex c86d6097b..241f9b2bd 100644--- a/apps/desktop-gpui/src/app_windows.rs+++ b/apps/desktop-gpui/src/app_windows.rs@@ -81,6 +81,141 @@ pub struct AppWindows {/// Where the camera bubble sat before a window picker parked it inside the/// highlighted window -- see [`CameraPark`].pub camera_park: CameraPark,+ #[cfg(target_os = "linux")]+ clean_capture: Option<CleanCaptureUi>,+ #[cfg(target_os = "linux")]+ clean_capture_generation: u64,+}++#[cfg(target_os = "linux")]+struct CleanCaptureUi {+ generation: u64,+ config: Option<StartConfig>,+ gate: CleanCaptureGate,+ camera: Option<WindowHandle<CameraWindow>>,+ camera_was_visible: bool,+ main_was_visible: bool,+ requested_inputs: CleanCaptureInputs,+ preview_was_rendering: Option<bool>,+ wayland: bool,+ retained_windows: Vec<(gpui::AnyWindowHandle, bool)>,+ restoring: bool,+ restoration_error: Option<String>,+}++#[cfg(target_os = "linux")]+impl CleanCaptureUi {+ fn begin_restore(&mut self) -> bool {+ self.config = None;+ if self.restoring {+ return false;+ }+ self.restoring = true;+ true+ }++ fn prepare_restore_retry(&mut self, phase: Phase, instant_cleanup_safe: bool) -> bool {+ if phase != Phase::Idle+ || !instant_cleanup_safe+ || !self.wayland+ || self.restoration_error.is_none()+ {+ return false;+ }+ self.config = None;+ self.restoration_error = None;+ self.restoring = false;+ true+ }++ fn take_start_config(&mut self, generation: u64) -> Option<StartConfig> {+ if self.generation != generation+ || !self.gate.started+ || self.restoring+ || self.restoration_error.is_some()+ {+ return None;+ }+ self.config.take()+ }+}++#[cfg(target_os = "linux")]+#[derive(Debug, PartialEq, Eq)]+enum CleanCaptureReopenAction {+ Continue,+ RetryRestore,+ WaitForRestore,+}++#[cfg(target_os = "linux")]+fn clean_capture_reopen_action(+ lease: Option<&mut CleanCaptureUi>,+ phase: Phase,+ instant_cleanup_safe: bool,+) -> CleanCaptureReopenAction {+ let Some(lease) = lease else {+ return CleanCaptureReopenAction::Continue;+ };+ if lease.prepare_restore_retry(phase, instant_cleanup_safe) {+ CleanCaptureReopenAction::RetryRestore+ } else if lease.wayland && lease.restoring {+ CleanCaptureReopenAction::WaitForRestore+ } else {+ CleanCaptureReopenAction::Continue+ }+}++#[cfg(target_os = "linux")]+#[derive(PartialEq)]+struct CleanCaptureInputs {+ camera: Option<crate::recording::DeviceOrModelID>,+ microphone: Option<String>,+}++#[cfg(target_os = "linux")]+impl CleanCaptureInputs {+ fn current(cx: &App) -> Self {+ let feeds = crate::feeds::Feeds::global(cx);+ let feeds = feeds.read(cx);+ Self {+ camera: feeds.camera.as_ref().map(|camera| camera.id.clone()),+ microphone: feeds.microphone.clone(),+ }+ }+}++#[cfg(target_os = "linux")]+#[derive(Default)]+struct CleanCaptureGate {+ pressed: bool,+ started: bool,+}++#[cfg(target_os = "linux")]+#[derive(Debug, PartialEq, Eq)]+enum CleanCaptureAction {+ Start,+ Stop,+}++#[cfg(target_os = "linux")]+impl CleanCaptureGate {+ fn shortcut(&mut self, state: global_hotkey::HotKeyState) -> Option<CleanCaptureAction> {+ if state == global_hotkey::HotKeyState::Pressed {+ self.pressed = true;+ return None;+ }+ if !std::mem::take(&mut self.pressed) {+ return None;+ }+ if self.started {+ Some(CleanCaptureAction::Stop)+ } else {+ self.started = true;+ Some(CleanCaptureAction::Start)+ }+ }}/// `originalCameraBounds` / `lastRepositionedWindowId` in the window variant of@@ -177,6 +312,10 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, cmain_hidden_for_picker: false,editor_hidden_for_picker: None,camera_park: CameraPark::default(),+ #[cfg(target_os = "linux")]+ clean_capture: None,+ #[cfg(target_os = "linux")]+ clean_capture_generation: 0,});// The global-Escape drain: the Carbon hotkey (registered only while the@@ -201,7 +340,15 @@ pub fn init(main: WindowHandle<MainWindow>, session: Entity<RecordingSession>, ccrate::tray::set_recording(recording, cx);}if phase == Phase::Idle && last_phase != Phase::Idle {+ #[cfg(target_os = "linux")]+ if !session.read(cx).instant_cleanup_safe() {+ return;+ }close_controls(&session, cx);+ #[cfg(target_os = "linux")]+ if !restore_clean_capture_ui(cx) {+ return;+ }let finished_studio = session.update(cx, |session, _| session.finished_studio.take());// The in-editor re-record target is consumed first, before// `postStudioRecordingBehaviour` is even consulted -- the order@@ -352,6 +499,50 @@ pub fn broadcast_theme(cx: &mut App) {/// Public because the tray's "Open Main Window" is exactly this/// (`ShowCapWindow::Main { init_target_mode: None }`).pub fn show_main_window(cx: &mut App) {+ #[cfg(target_os = "linux")]+ {+ let session = RecordingSession::global(cx);+ let phase = session.read(cx).phase;+ let instant_cleanup_safe = session.read(cx).instant_cleanup_safe();+ match clean_capture_reopen_action(+ cx.global_mut::<AppWindows>().clean_capture.as_mut(),+ phase,+ instant_cleanup_safe,+ ) {+ CleanCaptureReopenAction::RetryRestore => {+ begin_retained_capture_restore(cx);+ return;+ }+ CleanCaptureReopenAction::WaitForRestore => return,+ CleanCaptureReopenAction::Continue => {}+ }+ }+ #[cfg(target_os = "linux")]+ if clean_capture_active(cx) && RecordingSession::global(cx).read(cx).phase != Phase::Idle {+ RecordingSession::global(cx).update(cx, |session, cx| {+ session.show_clean_capture_controls(cx);+ });+ return;+ }+ show_main_window_after_capture_pause(cx);+}++pub(crate) fn show_main_window_after_capture_pause(cx: &mut App) {+ #[cfg(target_os = "linux")]+ if RecordingSession::global(cx).read(cx).phase == Phase::Idle+ && !RecordingSession::global(cx).read(cx).instant_cleanup_safe()+ {+ RecordingSession::global(cx).update(cx, |session, cx| session.stop(cx));+ return;+ }+ #[cfg(target_os = "linux")]+ if clean_capture_active(cx) {+ let session = RecordingSession::global(cx);+ if !session.read(cx).clean_capture_controls_safe() {+ session.update(cx, |session, cx| session.show_clean_capture_controls(cx));+ return;+ }+ }if crate::store::should_show_onboarding() {open_onboarding(cx);return;@@ -384,7 +575,12 @@ pub fn show_main_window(cx: &mut App) {// made a moment ago is in the list without a restart.view.refresh_recents(window, cx);#[cfg(target_os = "linux")]- if let Err(error) = platform::set_x11_window_visible(window, true) {+ if window.retained_visibility().is_some() {+ match window.set_retained_visibility(true) {+ Ok(receipt) => observe_visibility(receipt, true, cx),+ Err(error) => tracing::warn!(%error, "could not restore the main window"),+ }+ } else if let Err(error) = platform::set_x11_window_visible(window, true) {tracing::warn!(%error, "could not show the X11 main window");}platform::native_window(window)@@ -458,9 +654,16 @@ pub fn heal_main_window_style(cx: &mut App) {pub fn hide_main_window(cx: &mut App) {let main = cx.global::<AppWindows>().main;let native = main- .update(cx, |_, window, _| {+ .update(cx, |_, window, cx| {+ #[cfg(not(target_os = "linux"))]+ let _ = cx;#[cfg(target_os = "linux")]- if let Err(error) = platform::set_x11_window_visible(window, false) {+ if window.retained_visibility().is_some() {+ match window.set_retained_visibility(false) {+ Ok(receipt) => observe_visibility(receipt, false, cx),+ Err(error) => tracing::warn!(%error, "could not hide the main window"),+ }+ } else if let Err(error) = platform::set_x11_window_visible(window, false) {tracing::warn!(%error, "could not hide the X11 main window");}platform::native_window(window)@@ -506,6 +709,11 @@ fn camera_preview_can_be_parked(phase: Phase) -> bool {/// has no counterpart because there is no preview stream server here -- the/// preview is the bubble, and closing it stops the pump.pub fn request_close_main(cx: &mut App) {+ #[cfg(target_os = "linux")]+ if clean_capture_pending(cx) {+ cancel_clean_capture(cx);+ return;+ }hide_main_window(cx);// `state.is_recording_active_or_pending()`: everything but Idle.@@ -574,6 +782,10 @@ pub fn handle_dock_reopen(cx: &mut App) {/// through `cx.defer` from anything inside an entity update: opening a window/// paints it synchronously and would double-lease the caller.pub fn open_settings(page: Page, cx: &mut App) {+ #[cfg(target_os = "linux")]+ if defer_window_until_capture_safe(cx) {+ return;+ }if let Some(handle) = cx.global::<AppWindows>().settings {// `ShowCapWindow::show` reuses a live window: show, focus, and let// the page argument re-target it.@@ -729,6 +941,10 @@ pub fn settings_closed(cx: &mut App) {}pub fn open_onboarding(cx: &mut App) {+ #[cfg(target_os = "linux")]+ if defer_window_until_capture_safe(cx) {+ return;+ }if let Some(handle) = cx.global::<AppWindows>().onboarding {let native = handle.update(cx, |_, window, _| platform::native_window(window))@@ -849,6 +1065,10 @@ fn restore_after_settings(cx: &mut App) {/// Must be reached through `cx.defer` from inside an entity update: opening a/// window paints it synchronously and would double-lease the caller.pub fn open_mode_select(cx: &mut App) -> bool {+ #[cfg(target_os = "linux")]+ if defer_window_until_capture_safe(cx) {+ return false;+ }let main = cx.global::<AppWindows>().main;let mode = main.update(cx, |view, _window, _cx| view.mode())@@ -976,6 +1196,10 @@ pub fn set_recording_mode(mode: Mode, cx: &mut App) {/// `utils/teleprompter.ts`, which reuses a live window with/// `unminimize()`/`show()`/`setFocus()` and otherwise builds a new one.pub fn open_teleprompter(cx: &mut App) {+ #[cfg(target_os = "linux")]+ if defer_window_until_capture_safe(cx) {+ return;+ }if let Some(handle) = cx.global::<AppWindows>().teleprompter {let native = handle.update(cx, |_, window, _| platform::native_window(window))@@ -1229,6 +1453,10 @@ pub(crate) fn reject_unavailable_window(cx: &mut App) {/// cheaper to reason about and what the Tauri flow does (the webviews are/// recreated with a new `targetMode` query parameter).pub fn open_target_overlays(request: OverlayRequest, cx: &mut App) {+ #[cfg(target_os = "linux")]+ if defer_window_until_capture_safe(cx) {+ return;+ }if !open_overlays_core(request, cx) {reject_unavailable_window(cx);return;@@ -1254,6 +1482,10 @@ pub fn open_target_overlays(request: OverlayRequest, cx: &mut App) {/// Must be reached through `cx.defer` from anything inside an entity update,/// same as [`open_target_overlays`].pub fn open_editor_target_overlays(editor_path: PathBuf, request: OverlayRequest, cx: &mut App) {+ #[cfg(target_os = "linux")]+ if defer_window_until_capture_safe(cx) {+ return;+ }// A live recording keeps its own picker semantics; the modal's actions// are guarded on Idle already, so this is the belt-and-braces the Tauri// backend has in `set_pending_recording`.@@ -1814,6 +2046,10 @@ fn own_windows(cx: &mut App) -> Vec<OwnWindowHandle> {main_hidden_for_picker: _,editor_hidden_for_picker: _,camera_park: _,+ #[cfg(target_os = "linux")]+ clean_capture: _,+ #[cfg(target_os = "linux")]+ clean_capture_generation: _,} = cx.global::<AppWindows>();let main = *main;let controls = *controls;@@ -1953,130 +2189,968 @@ pub fn restore_content_protection(cx: &mut App) {apply_content_protection(windows, |_| false, cx);}-/// The whole start flow: bar up (in its Starting state), main window hidden,-/// engine started with the bar excluded from capture.-pub fn begin_recording(config: StartConfig, cx: &mut App) {- let session = RecordingSession::global(cx);- if session.read(cx).phase != Phase::Idle {- return;+#[cfg(target_os = "linux")]+fn clean_capture_supported(+ mode: RecordingMode,+ target: &ScreenCaptureTarget,+ camera_requested: bool,+ wayland: bool,+) -> bool {+ matches!(+ target,+ ScreenCaptureTarget::Display { .. } | ScreenCaptureTarget::Area { .. }+ ) || (!wayland+ && mode == RecordingMode::Instant+ && camera_requested+ && matches!(target, ScreenCaptureTarget::Window { .. }))+}++#[cfg(target_os = "linux")]+fn linux_capture_bounds(+ target: &ScreenCaptureTarget,+) -> anyhow::Result<camera_window::LinuxCameraPhysicalRect> {+ let (display, crop) = cap_recording::target_to_display_and_crop(target)?;+ let position = display+ .raw_handle()+ .physical_position()+ .ok_or_else(|| anyhow::anyhow!("Capture display position is unavailable"))?;+ if matches!(target, ScreenCaptureTarget::Window { .. }) {+ let crop = crop.ok_or_else(|| anyhow::anyhow!("Capture window bounds are unavailable"))?;+ return linux_window_capture_bounds(+ position.x() + crop.position().x(),+ position.y() + crop.position().y(),+ crop.size().width(),+ crop.size().height(),+ );}+ let size = display+ .physical_size()+ .ok_or_else(|| anyhow::anyhow!("Capture display size is unavailable"))?;+ let (x, y, width, height) = cap_recording::sources::screen_capture::x11_capture_rect(+ position.x(),+ position.y(),+ size.width(),+ size.height(),+ crop.map(|crop| {+ (+ crop.position().x(),+ crop.position().y(),+ crop.size().width(),+ crop.size().height(),+ )+ }),+ )?;+ Ok(camera_window::LinuxCameraPhysicalRect {+ x,+ y,+ width,+ height,+ })+}- // `start_recording`'s first act (`src-tauri/src/recording.rs:1492-1494`):- // an armed editor recording target forces Studio, whatever mode the main- // window is in -- the finished capture has to append as an editable clip.- let mut config = config;- let editor_target = session.read(cx).editor_recording_target();- if editor_target.is_some() {- config.mode = RecordingMode::Studio;+#[cfg(target_os = "linux")]+fn linux_window_capture_bounds(+ x: f64,+ y: f64,+ width: f64,+ height: f64,+) -> anyhow::Result<camera_window::LinuxCameraPhysicalRect> {+ anyhow::ensure!(+ [x, y, width, height]+ .iter()+ .all(|value| value.is_finite() && value.fract() == 0.0)+ && x >= f64::from(i32::MIN)+ && x <= f64::from(i32::MAX)+ && y >= f64::from(i32::MIN)+ && y <= f64::from(i32::MAX)+ && width >= 2.0+ && width <= f64::from(i32::MAX)+ && height >= 2.0+ && height <= f64::from(i32::MAX),+ "Capture window has invalid physical bounds"+ );+ Ok(camera_window::LinuxCameraPhysicalRect {+ x: x as i32,+ y: y as i32,+ width: width as u32,+ height: height as u32,+ })+}++#[cfg(target_os = "linux")]+fn linux_camera_presentation(+ snapshot: camera_window::LinuxCameraRecordingSnapshot,+ capture: camera_window::LinuxCameraPhysicalRect,+) -> anyhow::Result<cap_recording::instant_recording::LinuxCameraPresentation> {+ use crate::store::{BlurMode, CameraShape};+ use cap_recording::instant_recording::{+ LinuxCameraEffect, LinuxCameraPresentation, LinuxCameraRect, LinuxCameraShape,+ };++ let rect = snapshot.content_rect;+ let x = i64::from(rect.x) - i64::from(capture.x);+ let y = i64::from(rect.y) - i64::from(capture.y);+ anyhow::ensure!(+ x >= 0+ && y >= 0+ && x + i64::from(rect.width) <= i64::from(capture.width)+ && y + i64::from(rect.height) <= i64::from(capture.height),+ "Move the whole camera preview inside the capture area before starting Instant recording"+ );+ let radius = snapshot.corner_radius_pixels.round();+ anyhow::ensure!(+ radius.is_finite() && radius >= 0.0 && f64::from(radius) <= f64::from(u32::MAX),+ "Camera preview has an invalid corner radius"+ );+ let shape = match snapshot.state.shape {+ CameraShape::Round if rect.width == rect.height => LinuxCameraShape::Round,+ CameraShape::Round if rect.width.abs_diff(rect.height) <= 1 => {+ LinuxCameraShape::RoundedRectangle {+ radius_pixels: rect.width.min(rect.height) / 2,+ }+ }+ CameraShape::Round => anyhow::bail!("Round camera preview has invalid physical bounds"),+ CameraShape::Square | CameraShape::Full => LinuxCameraShape::RoundedRectangle {+ radius_pixels: (radius as u32).min(rect.width.min(rect.height) / 2),+ },+ };+ let mut presentation = LinuxCameraPresentation {+ rect: LinuxCameraRect {+ x: u32::try_from(x)?,+ y: u32::try_from(y)?,+ width: rect.width,+ height: rect.height,+ },+ shape,+ mirrored: snapshot.state.mirrored,+ effect: LinuxCameraEffect::None,+ };+ presentation.validate(capture.width, capture.height)?;+ if snapshot.state.background_blur != BlurMode::Off {+ presentation.effect = LinuxCameraEffect::BackgroundBlur;}- // `recording.rs:1775-1780`: the target editor gets content protection for- // the recording's duration (it is hidden-for-picker already, but a dock- // click can bring it back mid-capture, and a protected window stays out of- // the frame when it does). The Tauri arm also `minimize()`s it; here the- // picker's hide already took it off screen, and the finish path's reveal- // is the same un-hiding either way.- if let Some(editor_path) = &editor_target {- set_editor_content_protection(editor_path, true, cx);+ Ok(presentation)+}++#[cfg(target_os = "linux")]+pub(crate) fn refresh_linux_instant_camera(+ config: &mut StartConfig,+ cx: &mut App,+) -> anyhow::Result<()> {+ use crate::{feeds::Feeds, recording::LinuxInstantCameraRequest, store::BlurMode};+ use cap_recording::instant_recording::{LinuxCameraBlur, LinuxCameraProcessing};++ config.linux_instant_camera = None;+ if config.mode != RecordingMode::Instant+ || config.camera.is_none()+ || matches!(config.target, ScreenCaptureTarget::CameraOnly)+ {+ return Ok(());}+ anyhow::ensure!(+ !cap_recording::screenshot::uses_wayland_portal(),+ "Instant camera overlays require an X11 desktop on Linux"+ );+ let camera = cx.global::<AppWindows>().camera.ok_or_else(|| {+ anyhow::anyhow!("Open the selected camera preview before Instant recording")+ })?;+ let snapshot = camera.update(cx, |camera, window, _| camera.recording_snapshot(window))??;+ let capture = linux_capture_bounds(&config.target)?;+ let presentation = linux_camera_presentation(snapshot, capture)?;+ let processing = Feeds::global(cx)+ .read(cx)+ .camera_processing_factory()+ .ok_or_else(|| anyhow::anyhow!("Wait for the selected camera preview before recording"))?;+ config.linux_instant_camera = Some(LinuxInstantCameraRequest {+ presentation,+ reference_size: (capture.width, capture.height),+ effects: LinuxCameraProcessing {+ mirrored: snapshot.state.mirrored,+ blur: match snapshot.state.background_blur {+ BlurMode::Off => LinuxCameraBlur::Off,+ BlurMode::Light => LinuxCameraBlur::Light,+ BlurMode::Heavy => LinuxCameraBlur::Heavy,+ },+ },+ processing,+ });+ Ok(())+}- let mut excluded: Vec<scap_targets::WindowId> = config.excluded_windows.clone();- excluded.extend(open_controls(&config, session.clone(), cx));- // The camera bubble is excluded from studio captures (the camera is its own- // track, composited in the editor) but *included* in instant captures --- // `filter_for_instant_mode` in the Tauri app strips the camera exclusion- // there because instant has no compositing step.- if config.mode == RecordingMode::Studio- && let Some(number) = camera_window_number(cx)- && let Ok(id) = number.to_string().parse()+pub(crate) fn clean_capture_camera_message(cx: &App) -> &'static str {+ #[cfg(target_os = "linux")]+ if cx+ .try_global::<AppWindows>()+ .and_then(|windows| windows.clean_capture.as_ref())+ .and_then(|lease| lease.config.as_ref())+ .is_some_and(|config| config.mode == RecordingMode::Instant){- excluded.push(id);+ return "Cap will hide its preview and controls. Any selected camera will appear at its preview position with the selected shape and effects. Keep the whole preview inside the capture area. Opening Cap will stop this Instant recording before showing its controls.";}- // `recording.rs:1897-1904` adds a `teleprompter_exclusion` to every active- // recording, in both modes -- the script is for the presenter, never for- // the audience. The window number is the exclusion; the content protection- // below is the second half, for captures that are not ours.- if let Some(number) = teleprompter_window_number(cx)- && let Ok(id) = number.to_string().parse()+ #[cfg(not(target_os = "linux"))]+ let _ = cx;+ "Cap will hide its camera preview and recording controls. Any selected camera will keep recording as a separate editable track."+}++pub fn clean_capture_owned(cx: &App) -> bool {+ #[cfg(target_os = "linux")]{- tracing::info!(number, "excluding the teleprompter window from the capture");- excluded.push(id);+ cx.try_global::<AppWindows>()+ .is_some_and(|windows| windows.clean_capture.is_some())}- set_teleprompter_content_protection(true, cx);+ #[cfg(not(target_os = "linux"))]+ {+ let _ = cx;+ false+ }+}- // `crate::target_select_overlay::close_target_select_overlay_windows(&app)`- // at `recording.rs:1758`: the pickers come down at *every* recording start,- // not just the ones the overlay's own Start button drove. The overlay path- // hands its ids in already (`start_recording_from_overlay`), but the- // hotkey, deeplink and tile paths pass an empty list, and an overlay that- // has not finished closing is still on screen when the capture opens.- for id in overlay_window_ids(cx) {- if !excluded.contains(&id) {- excluded.push(id);- }+pub fn clean_capture_pending(cx: &App) -> bool {+ #[cfg(target_os = "linux")]+ {+ cx.try_global::<AppWindows>()+ .and_then(|windows| windows.clean_capture.as_ref())+ .is_some_and(|lease| !lease.gate.started && !lease.restoring)}- close_target_overlays(cx);+ #[cfg(not(target_os = "linux"))]+ {+ let _ = cx;+ false+ }+}- // The user-configurable half. `resolve_excluded_window_ids` (in- // `recording::start`) walks `CGWindowList` for *other* processes' windows;- // our own carry no native title for it to match, so they are resolved from- // the canonical-title table here -- `append_matching_webview_window_ids`- // (`recording.rs:1905-1910`). The hard number-gates above are the same- // defaults spelled out twice on purpose: they hold even if the user has- // emptied the rule list.- let rules = own_window_exclusion_rules(- crate::store::GeneralSettings::load().excluded_windows,- config.mode,- );- let own = own_windows(cx);- append_own_excluded_window_ids(&mut excluded, &own, &rules);- // `crate::windows::apply_content_protection(&app, true)` at- // `recording.rs:1773`, camera at `:1617-1624`. The second half of the same- // job: an excluded id keeps a window out of *our* capture, the sharing type- // keeps it out of everyone else's.- let camera_hidden = camera_content_protected(config.mode);- let protected = content_protection_targets(&rules);- apply_content_protection(- own,- move |kind| match kind {- OwnWindow::Camera => camera_hidden,- kind => protected.contains(&kind),- },- cx,- );+#[cfg(target_os = "linux")]+pub fn clean_capture_active(cx: &App) -> bool {+ cx.try_global::<AppWindows>()+ .and_then(|windows| windows.clean_capture.as_ref())+ .is_some_and(|lease| lease.gate.started)+}- let bar_open = cx.global::<AppWindows>().controls.is_some();- session.update(cx, |session, cx| {- session.set_controls_open(bar_open, cx);- });- // `general_settings.main_window_recording_start_behaviour.perform(&window)`- // at `recording.rs:1766-1771`, whose default (`Close`) is `window.hide()`- // on macOS: the main window goes away at every recording start, whatever- // else happened. Gating this on the bar having opened left the window in- // the frame on any start that never got a bar.- hide_main_window(cx);+pub fn clean_capture_shortcut_message(cx: &App) -> String {+ #[cfg(target_os = "linux")]+ {+ crate::hotkeys::clean_capture_stop_message(cx)+ }+ #[cfg(not(target_os = "linux"))]+ {+ let _ = cx;+ String::new()+ }+}- let config = StartConfig {- excluded_windows: excluded,- ..config- };- session.update(cx, |session, cx| session.start(config, cx));+#[cfg(target_os = "linux")]+pub fn notify_clean_capture_preflight(cx: &mut App) {+ let main = cx.global::<AppWindows>().main;+ let _ = main.update(cx, |_, _, cx| cx.notify());}-/// Open the camera preview bubble (idempotent). Placement is the Tauri-/// decision (`windows.rs:2278-2345`): the persisted position from the shared-/// store's `cameraWindowPosition` keys when it is still on the preferred-/// monitor -- the main window's, falling back to the cursor's, like-/// `CursorMonitorInfo::from_window(main)` over there -- else the default-/// bottom-right slot (see `camera_window::opening_position`).-pub fn open_camera_window(cx: &mut App) {- if cx.global::<AppWindows>().camera.is_some() {+#[cfg(target_os = "linux")]+fn clean_capture_generation_matches(generation: u64, cx: &App) -> bool {+ cx.try_global::<AppWindows>()+ .and_then(|windows| windows.clean_capture.as_ref())+ .is_some_and(|lease| lease.generation == generation)+}++#[cfg(target_os = "linux")]+pub fn handle_owned_clean_capture_shortcut(+ generation: u64,+ state: global_hotkey::HotKeyState,+ cx: &mut App,+) {+ if clean_capture_generation_matches(generation, cx) {+ handle_clean_capture_shortcut(state, cx);+ }+}++#[cfg(target_os = "linux")]+pub fn clean_capture_stop_unavailable(generation: u64, error: String, cx: &mut App) {+ if !clean_capture_generation_matches(generation, cx) {+ return;+ }+ if cx+ .global::<AppWindows>()+ .clean_capture+ .as_ref()+ .is_some_and(|lease| lease.restoring)+ {return;}+ let session = RecordingSession::global(cx);+ if session.read(cx).phase == Phase::Idle {+ cancel_clean_capture(cx);+ report_clean_capture_error(anyhow::Error::msg(error), cx);+ } else {+ session.update(cx, |session, cx| {+ session.error = Some(error);+ session.stop(cx);+ });+ }+}- let state = crate::store::load().camera_window.unwrap_or_default();- let (width, height) = camera_window::window_size(&state, None);+#[cfg(target_os = "linux")]+fn defer_window_until_capture_safe(cx: &mut App) -> bool {+ if !cx+ .try_global::<AppWindows>()+ .and_then(|windows| windows.clean_capture.as_ref())+ .is_some_and(|lease| lease.wayland && lease.gate.started)+ {+ return false;+ }+ let session = RecordingSession::global(cx);+ if session.read(cx).clean_capture_controls_safe() {+ return false;+ }+ session.update(cx, |session, cx| session.show_clean_capture_controls(cx));+ true+}- let main = cx.global::<AppWindows>().main;+#[cfg(target_os = "linux")]+fn x11_window_visible(window: &gpui::Window) -> anyhow::Result<bool> {+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};+ use x11rb::protocol::xproto::{ConnectionExt, MapState};+ let id = match HasWindowHandle::window_handle(window)?.as_raw() {+ RawWindowHandle::Xlib(handle) => u32::try_from(handle.window)?,+ RawWindowHandle::Xcb(handle) => handle.window.get(),+ _ => anyhow::bail!("Clean Studio capture requires an X11 window."),+ };+ let (connection, _) = x11rb::connect(None)?;+ Ok(connection.get_window_attributes(id)?.reply()?.map_state == MapState::VIEWABLE)+}++#[cfg(target_os = "linux")]+fn prepare_clean_capture(config: StartConfig, cx: &mut App) -> anyhow::Result<()> {+ if cx.global::<AppWindows>().controls.is_some() {+ anyhow::bail!("Close the previous recording controls before starting a clean capture.");+ }+ let main = cx.global::<AppWindows>().main;+ let wayland = cap_recording::screenshot::uses_wayland_portal();+ let main_was_visible = main.update(cx, |_, window, _| {+ if wayland {+ window.retained_visibility().ok_or_else(|| {+ anyhow::anyhow!(+ "The window backend cannot retain and acknowledge capture visibility"+ )+ })+ } else {+ x11_window_visible(window)+ }+ })??;+ let requested_inputs = CleanCaptureInputs::current(cx);+ let generation = cx+ .global::<AppWindows>()+ .clean_capture_generation+ .wrapping_add(1);+ crate::hotkeys::reserve_clean_capture_stop(generation, wayland, cx)?;+ let windows = cx.global_mut::<AppWindows>();+ windows.clean_capture_generation = generation;+ windows.clean_capture = Some(CleanCaptureUi {+ generation: windows.clean_capture_generation,+ config: Some(config),+ gate: CleanCaptureGate::default(),+ camera: None,+ camera_was_visible: false,+ main_was_visible,+ requested_inputs,+ preview_was_rendering: None,+ wayland,+ restoring: false,+ restoration_error: None,+ retained_windows: if wayland {+ vec![(main.into(), main_was_visible)]+ } else {+ Vec::new()+ },+ });+ close_target_overlays(cx);+ let shown = main.update(cx, |_, window, cx| {+ if wayland {+ observe_visibility(window.set_retained_visibility(true)?, true, cx);+ } else {+ platform::set_x11_window_visible(window, true)?;+ }+ window.activate_window();+ cx.notify();+ Ok::<_, anyhow::Error>(())+ });+ if let Err(error) = shown.and_then(|result| result) {+ restore_clean_capture_ui(cx);+ return Err(error);+ }+ Ok(())+}++pub fn cancel_clean_capture(cx: &mut App) {+ #[cfg(target_os = "linux")]+ if RecordingSession::global(cx).read(cx).phase == Phase::Idle+ && RecordingSession::global(cx).read(cx).instant_cleanup_safe()+ {+ restore_clean_capture_ui(cx);+ abort_editor_recording_flow(cx);+ }+ #[cfg(not(target_os = "linux"))]+ let _ = cx;+}++#[cfg(target_os = "linux")]+fn report_clean_capture_error(error: anyhow::Error, cx: &mut App) {+ tracing::error!(%error, "clean capture preflight failed");+ RecordingSession::global(cx).update(cx, |session, cx| {+ session.error = Some(error.to_string());+ cx.notify();+ });+ show_main_window_after_capture_pause(cx);+ abort_editor_recording_flow(cx);+}++#[cfg(target_os = "linux")]+pub type CleanVisibility = futures_util::future::BoxFuture<'static, anyhow::Result<()>>;++#[cfg(target_os = "linux")]+fn observe_visibility<F, E>(receipt: F, visible: bool, cx: &mut App)+where+ F: std::future::Future<Output = Result<anyhow::Result<(u64, bool)>, E>> + Send + 'static,+ E: std::error::Error + Send + Sync + 'static,+{+ let task = gpui_tokio::Tokio::spawn(cx, async move {+ let (_, acknowledged) =+ tokio::time::timeout(std::time::Duration::from_secs(3), receipt).await???;+ anyhow::ensure!(+ acknowledged == visible,+ "Unexpected retained visibility acknowledgement"+ );+ Ok::<_, anyhow::Error>(())+ });+ cx.spawn(async move |_| {+ if let Err(error) = task+ .await+ .map_err(|error| error.to_string())+ .and_then(|result| result.map_err(|error| error.to_string()))+ {+ tracing::error!(%error, "Could not restore retained window visibility");+ }+ })+ .detach();+}++#[cfg(target_os = "linux")]+pub fn hide_clean_capture_main(cx: &mut App) -> anyhow::Result<CleanVisibility> {+ if cx+ .global::<AppWindows>()+ .clean_capture+ .as_ref()+ .is_some_and(|lease| lease.wayland)+ {+ return hide_retained_capture_windows(cx);+ }+ let main = cx.global::<AppWindows>().main;+ main.update(cx, |_, window, _| {+ platform::set_x11_window_visible(window, false)+ })??;+ Ok(Box::pin(async { Ok(()) }))+}++#[cfg(target_os = "linux")]+fn hide_retained_capture_windows(cx: &mut App) -> anyhow::Result<CleanVisibility> {+ let handles = cx.windows();+ let mut visible = Vec::new();+ for handle in handles {+ let was_visible = handle+ .update(cx, |_, window, _| window.retained_visibility())?+ .ok_or_else(|| {+ anyhow::anyhow!("A Cap window cannot acknowledge clean capture visibility")+ })?;+ visible.push((handle, was_visible));+ }+ let lease = cx+ .global_mut::<AppWindows>()+ .clean_capture+ .as_mut()+ .ok_or_else(|| anyhow::anyhow!("The capture visibility lease ended"))?;+ for &(handle, was_visible) in &visible {+ if !lease+ .retained_windows+ .iter()+ .any(|(saved, _)| *saved == handle)+ {+ lease.retained_windows.push((handle, was_visible));+ }+ }+ let mut receipts = Vec::new();+ for (handle, _) in visible {+ receipts.push(handle.update(cx, |_, window, _| window.set_retained_visibility(false))??);+ }+ Ok(Box::pin(async move {+ tokio::time::timeout(std::time::Duration::from_secs(3), async move {+ for receipt in receipts {+ let (_, visible) = receipt.await??;+ anyhow::ensure!(+ !visible,+ "The compositor did not acknowledge hiding a Cap window"+ );+ }+ Ok::<_, anyhow::Error>(())+ })+ .await?+ }))+}++#[cfg(target_os = "linux")]+fn hide_clean_capture_ui(cx: &mut App) -> anyhow::Result<CleanVisibility> {+ let wayland = cx+ .global::<AppWindows>()+ .clean_capture+ .as_ref()+ .ok_or_else(|| anyhow::anyhow!("Clean capture is no longer waiting to start"))?+ .wayland;+ let camera = cx.global::<AppWindows>().camera;+ let camera_was_visible = if wayland {+ false+ } else {+ match camera {+ Some(camera) => camera.update(cx, |_, window, _| x11_window_visible(window))??,+ None => false,+ }+ };+ let preview_was_rendering = crate::feeds::Feeds::global(cx)+ .read(cx)+ .set_camera_preview_rendering(false);+ if let Some(lease) = cx.global_mut::<AppWindows>().clean_capture.as_mut() {+ lease.camera = camera;+ lease.camera_was_visible = camera_was_visible;+ let _ = lease+ .preview_was_rendering+ .get_or_insert(preview_was_rendering);+ }+ if let Some(camera) = camera.filter(|_| camera_was_visible) {+ camera.update(cx, |_, window, _| {+ platform::set_x11_window_visible(window, false)+ })??;+ }+ hide_clean_capture_main(cx)+}++#[cfg(target_os = "linux")]+async fn acknowledge_restored_windows<F, E>(+ receipts: Vec<(bool, F)>,+ mut errors: Vec<String>,+) -> Result<(), String>+where+ F: std::future::Future<Output = Result<anyhow::Result<(u64, bool)>, E>>,+ E: std::fmt::Display,+{+ for (expected, receipt) in receipts {+ match receipt.await {+ Ok(Ok((_, visible))) if visible == expected => {}+ Ok(Ok(_)) => errors.push("A restored window acknowledged the wrong visibility".into()),+ Ok(Err(error)) => errors.push(error.to_string()),+ Err(error) => errors.push(error.to_string()),+ }+ }+ if errors.is_empty() {+ Ok(())+ } else {+ Err(errors.join("; "))+ }+}++#[cfg(target_os = "linux")]+fn begin_retained_capture_restore(cx: &mut App) {+ let Some(lease) = cx.global_mut::<AppWindows>().clean_capture.as_mut() else {+ return;+ };+ if !lease.begin_restore() {+ return;+ }+ let generation = lease.generation;+ let windows = lease.retained_windows.clone();+ let rendering = lease.preview_was_rendering;+ if let Some(rendering) = rendering {+ crate::feeds::Feeds::global(cx)+ .read(cx)+ .set_camera_preview_rendering(rendering);+ }+ let mut receipts = Vec::new();+ let mut errors = Vec::new();+ for (handle, visible) in windows {+ match handle+ .update(cx, |_, window, _| {+ let receipt = window.set_retained_visibility(visible)?;+ window.refresh();+ Ok::<_, anyhow::Error>(receipt)+ })+ .and_then(|result| result)+ {+ Ok(receipt) => receipts.push((visible, receipt)),+ Err(error) => errors.push(error.to_string()),+ }+ }+ let visibility = gpui_tokio::Tokio::spawn(cx, async move {+ tokio::time::timeout(+ std::time::Duration::from_secs(3),+ acknowledge_restored_windows(receipts, errors),+ )+ .await+ .map_err(|_| {+ "Window restoration has not been acknowledged; its lease remains owned".to_string()+ })?+ });+ cx.spawn(async move |cx| {+ let visibility = visibility.await.map_err(|error| error.to_string()).and_then(|result| result);+ let result = match visibility {+ Ok(()) => {+ let cleanup = cx.update(|cx| {+ if !clean_capture_generation_matches(generation, cx) { return None; }+ let cleanup = crate::hotkeys::begin_wayland_stop_cleanup(cx);+ Some(gpui_tokio::Tokio::spawn(cx, cleanup))+ });+ match cleanup {+ Some(cleanup) => cleanup.await.map_err(|error| error.to_string()).and_then(|result| result),+ None => return,+ }+ }+ Err(error) => Err(error),+ };+ cx.update(|cx| {+ if !clean_capture_generation_matches(generation, cx) { return; }+ match result {+ Ok(()) => {+ crate::hotkeys::complete_clean_capture_stop(generation, cx);+ let _restored = cx.global_mut::<AppWindows>().clean_capture.take();+ RecordingSession::global(cx).update(cx, |_, cx| cx.notify());+ }+ Err(error) => {+ if let Some(lease) = cx.global_mut::<AppWindows>().clean_capture.as_mut() {+ lease.restoration_error = Some(error.clone());+ }+ tracing::error!(%error, "Recording UI restoration or Stop cleanup is unconfirmed");+ RecordingSession::global(cx).update(cx, |session, cx| {+ session.error = Some(format!("Recording cleanup is incomplete: {error}. A new recording is blocked."));+ cx.notify();+ });+ }+ }+ });+ }).detach();+}++#[cfg(target_os = "linux")]+fn restore_clean_capture_ui(cx: &mut App) -> bool {+ if !RecordingSession::global(cx).read(cx).instant_cleanup_safe() {+ return false;+ }+ if cx+ .global::<AppWindows>()+ .clean_capture+ .as_ref()+ .is_some_and(|lease| lease.wayland)+ {+ begin_retained_capture_restore(cx);+ return false;+ }+ let Some(lease) = cx.global_mut::<AppWindows>().clean_capture.take() else {+ return true;+ };+ crate::hotkeys::release_clean_capture_stop(cx);+ if let Some(rendering) = lease.preview_was_rendering {+ // Camera selection does not reset the shared render flag owned by this lease.+ crate::feeds::Feeds::global(cx)+ .read(cx)+ .set_camera_preview_rendering(rendering);+ }+ if lease.camera_was_visible+ && let Some(camera) = lease.camera+ && cx.global::<AppWindows>().camera == Some(camera)+ {+ let result = camera.update(cx, |_, window, cx| {+ platform::set_x11_window_visible(window, true)?;+ cx.notify();+ Ok::<_, anyhow::Error>(())+ });+ if let Err(error) = result.and_then(|result| result) {+ tracing::warn!(%error, "could not restore the camera preview");+ }+ }+ let main = cx.global::<AppWindows>().main;+ let result = main.update(cx, |_, window, cx| {+ platform::set_x11_window_visible(window, lease.main_was_visible)?;+ cx.notify();+ Ok::<_, anyhow::Error>(())+ });+ if let Err(error) = result.and_then(|result| result) {+ tracing::warn!(%error, "could not restore the main window");+ }+ true+}++#[cfg(target_os = "linux")]+pub fn handle_clean_capture_shortcut(state: global_hotkey::HotKeyState, cx: &mut App) {+ let Some(lease) = cx.global_mut::<AppWindows>().clean_capture.as_mut() else {+ return;+ };+ if lease.restoring {+ return;+ }+ let Some(action) = lease.gate.shortcut(state) else {+ return;+ };+ if action == CleanCaptureAction::Stop {+ if RecordingSession::global(cx).read(cx).phase == Phase::Idle {+ cancel_clean_capture(cx);+ } else {+ RecordingSession::global(cx).update(cx, |session, cx| session.stop(cx));+ }+ return;+ }+ let generation = lease.generation;+ let Some(mut config) = lease.config.take() else {+ return;+ };+ let current_inputs = CleanCaptureInputs::current(cx);+ if cx+ .global::<AppWindows>()+ .clean_capture+ .as_ref()+ .is_none_or(|lease| lease.requested_inputs != current_inputs)+ {+ restore_clean_capture_ui(cx);+ report_clean_capture_error(+ anyhow::anyhow!(+ "Selected devices changed. Start again to confirm the new recording inputs."+ ),+ cx,+ );+ return;+ }+ if let Err(error) = refresh_linux_instant_camera(&mut config, cx) {+ restore_clean_capture_ui(cx);+ report_clean_capture_error(error, cx);+ return;+ }+ if let Some(lease) = cx.global_mut::<AppWindows>().clean_capture.as_mut() {+ lease.config = Some(config);+ }+ let visibility = match hide_clean_capture_ui(cx) {+ Ok(visibility) => visibility,+ Err(error) => {+ restore_clean_capture_ui(cx);+ report_clean_capture_error(error, cx);+ return;+ }+ };+ let visibility = gpui_tokio::Tokio::spawn(cx, visibility);+ cx.spawn(async move |cx| {+ let result = visibility.await.map_err(anyhow::Error::from).and_then(|result| result);+ if let Err(error) = result {+ cx.update(|cx| {+ if clean_capture_generation_matches(generation, cx) {+ restore_clean_capture_ui(cx);+ report_clean_capture_error(error, cx);+ }+ });+ return;+ }+ cx.background_executor()+ .timer(std::time::Duration::from_millis(150))+ .await;+ cx.update(|cx| {+ let current_inputs = CleanCaptureInputs::current(cx);+ if cx+ .global::<AppWindows>()+ .clean_capture+ .as_ref()+ .is_some_and(|lease| {+ lease.generation == generation && lease.requested_inputs != current_inputs+ })+ {+ restore_clean_capture_ui(cx);+ report_clean_capture_error(+ anyhow::anyhow!("Selected devices changed before recording started. Start again to confirm the inputs."),+ cx,+ );+ return;+ }+ let config = cx+ .global_mut::<AppWindows>()+ .clean_capture+ .as_mut()+ .and_then(|lease| lease.take_start_config(generation));+ if let Some(config) = config {+ begin_recording_after_preflight(config, cx);+ }+ });+ })+ .detach();+}++/// The whole start flow: bar up (in its Starting state), main window hidden,+/// engine started with the bar excluded from capture.+pub fn begin_recording(mut config: StartConfig, cx: &mut App) {+ let session = RecordingSession::global(cx);+ if session.read(cx).phase != Phase::Idle {+ return;+ }+ if session.read(cx).editor_recording_target().is_some() {+ config.mode = RecordingMode::Studio;+ }+ #[cfg(target_os = "linux")]+ {+ if let Some(lease) = cx.global::<AppWindows>().clean_capture.as_ref() {+ if let Some(error) = lease.restoration_error.clone() {+ session.update(cx, |session, cx| {+ session.error = Some(format!(+ "Recording cleanup is incomplete: {error}. A new recording is blocked."+ ));+ cx.notify();+ });+ }+ return;+ }+ let wayland = cap_recording::screenshot::uses_wayland_portal();+ if clean_capture_supported(+ config.mode,+ &config.target,+ config.camera.is_some(),+ wayland,+ ) {+ if let Err(error) = prepare_clean_capture(config, cx) {+ report_clean_capture_error(error, cx);+ }+ return;+ }+ if let Err(error) = refresh_linux_instant_camera(&mut config, cx) {+ report_clean_capture_error(error, cx);+ return;+ }+ }+ begin_recording_after_preflight(config, cx);+}++fn begin_recording_after_preflight(config: StartConfig, cx: &mut App) {+ let session = RecordingSession::global(cx);+ if session.read(cx).phase != Phase::Idle {+ return;+ }++ // `start_recording`'s first act (`src-tauri/src/recording.rs:1492-1494`):+ // an armed editor recording target forces Studio, whatever mode the main+ // window is in -- the finished capture has to append as an editable clip.+ let mut config = config;+ let editor_target = session.read(cx).editor_recording_target();+ if editor_target.is_some() {+ config.mode = RecordingMode::Studio;+ }+ // `recording.rs:1775-1780`: the target editor gets content protection for+ // the recording's duration (it is hidden-for-picker already, but a dock+ // click can bring it back mid-capture, and a protected window stays out of+ // the frame when it does). The Tauri arm also `minimize()`s it; here the+ // picker's hide already took it off screen, and the finish path's reveal+ // is the same un-hiding either way.+ if let Some(editor_path) = &editor_target {+ set_editor_content_protection(editor_path, true, cx);+ }++ let mut excluded: Vec<scap_targets::WindowId> = config.excluded_windows.clone();+ excluded.extend(open_controls(&config, session.clone(), cx));+ // The camera bubble is excluded from studio captures (the camera is its own+ // track, composited in the editor) but *included* in instant captures --+ // `filter_for_instant_mode` in the Tauri app strips the camera exclusion+ // there because instant has no compositing step.+ if config.mode == RecordingMode::Studio+ && let Some(number) = camera_window_number(cx)+ && let Ok(id) = number.to_string().parse()+ {+ excluded.push(id);+ }+ // `recording.rs:1897-1904` adds a `teleprompter_exclusion` to every active+ // recording, in both modes -- the script is for the presenter, never for+ // the audience. The window number is the exclusion; the content protection+ // below is the second half, for captures that are not ours.+ if let Some(number) = teleprompter_window_number(cx)+ && let Ok(id) = number.to_string().parse()+ {+ tracing::info!(number, "excluding the teleprompter window from the capture");+ excluded.push(id);+ }+ set_teleprompter_content_protection(true, cx);++ // `crate::target_select_overlay::close_target_select_overlay_windows(&app)`+ // at `recording.rs:1758`: the pickers come down at *every* recording start,+ // not just the ones the overlay's own Start button drove. The overlay path+ // hands its ids in already (`start_recording_from_overlay`), but the+ // hotkey, deeplink and tile paths pass an empty list, and an overlay that+ // has not finished closing is still on screen when the capture opens.+ for id in overlay_window_ids(cx) {+ if !excluded.contains(&id) {+ excluded.push(id);+ }+ }+ close_target_overlays(cx);++ // The user-configurable half. `resolve_excluded_window_ids` (in+ // `recording::start`) walks `CGWindowList` for *other* processes' windows;+ // our own carry no native title for it to match, so they are resolved from+ // the canonical-title table here -- `append_matching_webview_window_ids`+ // (`recording.rs:1905-1910`). The hard number-gates above are the same+ // defaults spelled out twice on purpose: they hold even if the user has+ // emptied the rule list.+ let rules = own_window_exclusion_rules(+ crate::store::GeneralSettings::load().excluded_windows,+ config.mode,+ );+ let own = own_windows(cx);+ append_own_excluded_window_ids(&mut excluded, &own, &rules);+ // `crate::windows::apply_content_protection(&app, true)` at+ // `recording.rs:1773`, camera at `:1617-1624`. The second half of the same+ // job: an excluded id keeps a window out of *our* capture, the sharing type+ // keeps it out of everyone else's.+ let camera_hidden = camera_content_protected(config.mode);+ let protected = content_protection_targets(&rules);+ apply_content_protection(+ own,+ move |kind| match kind {+ OwnWindow::Camera => camera_hidden,+ kind => protected.contains(&kind),+ },+ cx,+ );++ let bar_open = cx.global::<AppWindows>().controls.is_some();+ session.update(cx, |session, cx| {+ session.set_controls_open(bar_open, cx);+ });+ // `general_settings.main_window_recording_start_behaviour.perform(&window)`+ // at `recording.rs:1766-1771`, whose default (`Close`) is `window.hide()`+ // on macOS: the main window goes away at every recording start, whatever+ // else happened. Gating this on the bar having opened left the window in+ // the frame on any start that never got a bar.+ hide_main_window(cx);++ let config = StartConfig {+ excluded_windows: excluded,+ ..config+ };+ session.update(cx, |session, cx| session.start(config, cx));+}++/// Open the camera preview bubble (idempotent). Placement is the Tauri+/// decision (`windows.rs:2278-2345`): the persisted position from the shared+/// store's `cameraWindowPosition` keys when it is still on the preferred+/// monitor -- the main window's, falling back to the cursor's, like+/// `CursorMonitorInfo::from_window(main)` over there -- else the default+/// bottom-right slot (see `camera_window::opening_position`).+pub fn open_camera_window(cx: &mut App) {+ #[cfg(target_os = "linux")]+ if clean_capture_active(cx) {+ return;+ }+ if cx.global::<AppWindows>().camera.is_some() {+ return;+ }++ let state = crate::store::load().camera_window.unwrap_or_default();+ let (width, height) = camera_window::window_size(&state, None);++ let main = cx.global::<AppWindows>().main;let display = main.update(cx, |_, window, _| window.bounds()).ok()@@ -2409,6 +3483,10 @@ fn editor_key(path: &Path) -> PathBuf {/// Must be reached through `cx.defer` from anything inside an entity update:/// opening a window paints it synchronously and would double-lease the caller.pub fn open_editor(project_path: PathBuf, cx: &mut App) {+ #[cfg(target_os = "linux")]+ if defer_window_until_capture_safe(cx) {+ return;+ }let key = editor_key(&project_path);if let Some(handle) = cx@@ -3481,6 +4559,10 @@ fn open_controls(session: Entity<RecordingSession>,cx: &mut App,) -> Option<scap_targets::WindowId> {+ #[cfg(target_os = "linux")]+ if clean_capture_active(cx) {+ return None;+ }let (x, y) = controls_origin(config);let has_microphone = config.microphone.is_some();@@ -3597,6 +4679,10 @@ pub fn screenshot_finished(captured: Option<PathBuf>, cx: &mut App) {/// Must be reached through `cx.defer` from anything inside an entity update:/// opening a window paints it synchronously and would double-lease the caller.pub fn open_screenshot_editor(path: PathBuf, cx: &mut App) {+ #[cfg(target_os = "linux")]+ if defer_window_until_capture_safe(cx) {+ return;+ }let Some(bundle) = screenshot_editor::resolve_bundle(&path) else {tracing::error!(path = %path.display(), "not a screenshot bundle; not opening the editor");return;@@ -3785,6 +4871,635 @@ mod tests {use super::*;use crate::store::{DEFAULT_EXCLUDED_WINDOW_TITLES, WindowExclusion, default_excluded_windows};+ #[cfg(target_os = "linux")]+ fn pending_clean_capture(mode: RecordingMode, wayland: bool) -> CleanCaptureUi {+ CleanCaptureUi {+ generation: 7,+ config: Some(StartConfig {+ mode,+ target: ScreenCaptureTarget::Display {+ id: "1".parse().unwrap(),+ },+ microphone: None,+ camera: None,+ system_audio: false,+ excluded_windows: Vec::new(),+ camera_feed: None,+ mic_feed: None,+ linux_instant_camera: None,+ }),+ gate: CleanCaptureGate::default(),+ camera: None,+ camera_was_visible: false,+ main_was_visible: true,+ requested_inputs: CleanCaptureInputs {+ camera: None,+ microphone: None,+ },+ preview_was_rendering: Some(true),+ wayland,+ retained_windows: Vec::new(),+ restoring: false,+ restoration_error: None,+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_delayed_start_consumes_only_the_started_generation() {+ use global_hotkey::HotKeyState::{Pressed, Released};+ for mode in [RecordingMode::Studio, RecordingMode::Instant] {+ for wayland in [false, true] {+ let mut lease = pending_clean_capture(mode, wayland);+ let generation = lease.generation;+ assert!(lease.take_start_config(generation).is_none());+ assert_eq!(lease.gate.shortcut(Pressed), None);+ assert!(lease.take_start_config(generation).is_none());+ assert_eq!(+ lease.gate.shortcut(Released),+ Some(CleanCaptureAction::Start)+ );+ assert!(lease.take_start_config(generation + 1).is_none());+ assert!(lease.config.is_some());+ assert!(lease.take_start_config(generation).is_some());+ assert!(lease.take_start_config(generation).is_none());+ assert_eq!(lease.gate.shortcut(Pressed), None);+ assert_eq!(+ lease.gate.shortcut(Released),+ Some(CleanCaptureAction::Stop)+ );+ assert!(lease.gate.started);+ if wayland {+ assert!(lease.begin_restore());+ assert!(lease.config.is_none());+ assert!(lease.gate.started);+ }+ }+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_stop_cancels_delayed_start_before_restore_finishes() {+ use global_hotkey::HotKeyState::{Pressed, Released};+ for mode in [RecordingMode::Studio, RecordingMode::Instant] {+ let mut lease = pending_clean_capture(mode, true);+ let generation = lease.generation;+ assert_eq!(lease.gate.shortcut(Pressed), None);+ assert_eq!(+ lease.gate.shortcut(Released),+ Some(CleanCaptureAction::Start)+ );+ assert_eq!(lease.gate.shortcut(Pressed), None);+ assert_eq!(+ lease.gate.shortcut(Released),+ Some(CleanCaptureAction::Stop)+ );+ assert!(lease.begin_restore());+ assert!(lease.config.is_none());+ assert!(lease.restoring);+ assert!(lease.gate.started);+ assert!(lease.take_start_config(generation).is_none());+ assert!(!lease.begin_restore());+ assert!(lease.take_start_config(generation).is_none());+ lease.restoration_error = Some("Stop cleanup is unconfirmed".into());+ assert!(lease.take_start_config(generation).is_none());+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_delayed_start_rejects_restoring_and_failed_leases() {+ for (restoring, restoration_error) in [+ (true, None),+ (false, Some("Window restoration failed")),+ (true, Some("Stop cleanup failed")),+ ] {+ let mut lease = pending_clean_capture(RecordingMode::Studio, true);+ lease.gate.started = true;+ lease.restoring = restoring;+ lease.restoration_error = restoration_error.map(str::to_string);+ assert!(lease.take_start_config(lease.generation).is_none());+ assert!(lease.config.is_some());+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_restoration_invalidates_preflight_config() {+ for started in [false, true] {+ let mut lease = pending_clean_capture(RecordingMode::Studio, true);+ lease.gate.started = started;+ assert!(lease.begin_restore());+ assert!(lease.config.is_none());+ assert_eq!(lease.gate.started, started);+ assert!(lease.take_start_config(lease.generation).is_none());+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_restore_retry_requires_safe_idle_wayland_failure() {+ for phase in [+ Phase::Idle,+ Phase::Starting,+ Phase::Recording { paused: false },+ Phase::Recording { paused: true },+ Phase::Stopping,+ ] {+ for cleanup_safe in [false, true] {+ for (wayland, failed) in+ [(false, false), (false, true), (true, false), (true, true)]+ {+ let mut lease = pending_clean_capture(RecordingMode::Studio, wayland);+ lease.gate.started = true;+ lease.restoring = true;+ lease.restoration_error = failed.then(|| "Window restoration failed".into());+ let permitted = phase == Phase::Idle && cleanup_safe && wayland && failed;+ assert_eq!(lease.prepare_restore_retry(phase, cleanup_safe), permitted);+ if permitted {+ assert!(lease.config.is_none());+ assert!(lease.restoration_error.is_none());+ assert!(!lease.restoring);+ assert!(lease.take_start_config(7).is_none());+ assert!(lease.begin_restore());+ } else {+ assert!(lease.config.is_some());+ assert_eq!(lease.restoration_error.is_some(), failed);+ assert!(lease.restoring);+ }+ assert_eq!(lease.generation, 7);+ assert!(lease.gate.started);+ assert!(lease.take_start_config(7).is_none());+ }+ }+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_restore_retry_allows_one_attempt_per_failure() {+ for mode in [RecordingMode::Studio, RecordingMode::Instant] {+ for started in [false, true] {+ let mut lease = pending_clean_capture(mode, true);+ lease.gate.started = started;+ assert!(lease.begin_restore());+ for error in ["Window restoration failed", "Stop cleanup failed"] {+ lease.restoration_error = Some(error.into());+ assert!(!lease.begin_restore());+ assert!(lease.prepare_restore_retry(Phase::Idle, true));+ assert!(lease.begin_restore());+ assert!(!lease.prepare_restore_retry(Phase::Idle, true));+ assert!(!lease.begin_restore());+ assert!(lease.config.is_none());+ assert!(lease.restoration_error.is_none());+ assert!(lease.restoring);+ assert_eq!(lease.generation, 7);+ assert_eq!(lease.gate.started, started);+ assert_eq!(lease.preview_was_rendering, Some(true));+ assert!(lease.main_was_visible);+ assert!(lease.take_start_config(7).is_none());+ }+ }+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_reopen_waits_for_owned_wayland_restoration() {+ for mode in [RecordingMode::Studio, RecordingMode::Instant] {+ for started in [false, true] {+ let mut lease = pending_clean_capture(mode, true);+ lease.gate.started = started;+ assert!(lease.begin_restore());+ for _ in 0..2 {+ assert_eq!(+ clean_capture_reopen_action(Some(&mut lease), Phase::Idle, true),+ CleanCaptureReopenAction::WaitForRestore+ );+ assert!(lease.restoring);+ assert!(lease.restoration_error.is_none());+ assert!(lease.config.is_none());+ assert_eq!(lease.gate.started, started);+ assert_eq!(lease.generation, 7);+ }+ }+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_reopen_retries_failure_then_waits_until_cleanup() {+ for mode in [RecordingMode::Studio, RecordingMode::Instant] {+ for started in [false, true] {+ let mut lease = pending_clean_capture(mode, true);+ lease.gate.started = started;+ assert!(lease.begin_restore());+ for error in ["Window restoration failed", "Stop cleanup failed"] {+ lease.restoration_error = Some(error.into());+ assert_eq!(+ clean_capture_reopen_action(Some(&mut lease), Phase::Idle, true),+ CleanCaptureReopenAction::RetryRestore+ );+ assert!(lease.take_start_config(7).is_none());+ assert!(lease.begin_restore());+ assert_eq!(+ clean_capture_reopen_action(Some(&mut lease), Phase::Idle, true),+ CleanCaptureReopenAction::WaitForRestore+ );+ assert!(lease.restoring);+ assert!(lease.restoration_error.is_none());+ assert_eq!(lease.gate.started, started);+ assert_eq!(lease.generation, 7);+ }+ assert_eq!(+ clean_capture_reopen_action(None, Phase::Idle, true),+ CleanCaptureReopenAction::Continue+ );+ }+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_reopen_preserves_other_paths_and_rejects_unsafe_retry() {+ use CleanCaptureReopenAction::{Continue, WaitForRestore};+ for (phase, cleanup_safe, wayland, restoring, failed, expected) in [+ (Phase::Idle, true, false, false, false, Continue),+ (Phase::Idle, true, false, true, true, Continue),+ (Phase::Idle, true, true, false, false, Continue),+ (Phase::Idle, false, true, true, true, WaitForRestore),+ (Phase::Starting, true, true, true, true, WaitForRestore),+ (+ Phase::Recording { paused: false },+ true,+ true,+ true,+ true,+ WaitForRestore,+ ),+ (+ Phase::Recording { paused: true },+ true,+ true,+ true,+ true,+ WaitForRestore,+ ),+ (Phase::Stopping, true, true, true, true, WaitForRestore),+ ] {+ let mut lease = pending_clean_capture(RecordingMode::Studio, wayland);+ lease.restoring = restoring;+ lease.restoration_error = failed.then(|| "Window restoration failed".into());+ assert_eq!(+ clean_capture_reopen_action(Some(&mut lease), phase, cleanup_safe),+ expected+ );+ assert!(lease.config.is_some());+ assert_eq!(lease.restoring, restoring);+ assert_eq!(lease.restoration_error.is_some(), failed);+ assert_eq!(lease.generation, 7);+ }+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn restoration_waits_for_the_last_owned_window() {+ let (send, receive) = flume::bounded::<anyhow::Result<(u64, bool)>>(1);+ let receipt = async move { receive.recv_async().await };+ let mut restored = Box::pin(acknowledge_restored_windows(+ vec![(true, receipt)],+ Vec::new(),+ ));+ assert!(futures_util::poll!(&mut restored).is_pending());+ send.send(Ok((1, true))).unwrap();+ restored.await.unwrap();+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn restoration_keeps_errors_and_checks_every_window() {+ let receipts = vec![+ (true, std::future::ready(Ok::<_, String>(Ok((1, false))))),+ (+ true,+ std::future::ready(Err::<anyhow::Result<(u64, bool)>, _>(+ "window closed".to_string(),+ )),+ ),+ ];+ let error = acknowledge_restored_windows(receipts, vec!["missing window".into()])+ .await+ .unwrap_err();+ assert!(error.contains("wrong visibility"));+ assert!(error.contains("window closed"));+ assert!(error.contains("missing window"));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_requires_delivered_press_and_release() {+ use global_hotkey::HotKeyState::{Pressed, Released};+ let mut gate = CleanCaptureGate::default();+ assert_eq!(gate.shortcut(Released), None);+ assert_eq!(gate.shortcut(Pressed), None);+ assert!(!gate.started);+ assert_eq!(gate.shortcut(Pressed), None);+ assert_eq!(gate.shortcut(Released), Some(CleanCaptureAction::Start));+ assert!(gate.started);+ assert_eq!(gate.shortcut(Released), None);+ assert_eq!(gate.shortcut(Pressed), None);+ assert_eq!(gate.shortcut(Released), Some(CleanCaptureAction::Stop));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_restart_keeps_stop_and_new_lease_requires_proof() {+ use global_hotkey::HotKeyState::{Pressed, Released};+ let mut gate = CleanCaptureGate {+ pressed: false,+ started: true,+ };+ assert_eq!(gate.shortcut(Pressed), None);+ assert_eq!(gate.shortcut(Released), Some(CleanCaptureAction::Stop));+ let mut new_gate = CleanCaptureGate::default();+ assert_eq!(new_gate.shortcut(Released), None);+ assert!(!new_gate.started);+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn monitor_capture_uses_acknowledged_visibility_on_x11_and_wayland() {+ let display = ScreenCaptureTarget::Display {+ id: "1".parse().unwrap(),+ };+ let area = ScreenCaptureTarget::Area {+ screen: "1".parse().unwrap(),+ bounds: scap_targets::bounds::LogicalBounds::new(+ scap_targets::bounds::LogicalPosition::new(0.0, 0.0),+ scap_targets::bounds::LogicalSize::new(100.0, 100.0),+ ),+ };+ let window = ScreenCaptureTarget::Window {+ id: "1".parse().unwrap(),+ };+ for mode in [RecordingMode::Studio, RecordingMode::Instant] {+ for camera_requested in [false, true] {+ for target in [&display, &area] {+ assert!(clean_capture_supported(+ mode,+ target,+ camera_requested,+ true+ ));+ assert!(clean_capture_supported(+ mode,+ target,+ camera_requested,+ false+ ));+ }+ }+ }+ for target in [&window, &ScreenCaptureTarget::CameraOnly] {+ assert!(!clean_capture_supported(+ RecordingMode::Studio,+ target,+ true,+ true+ ));+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn clean_capture_covers_screen_overlays_but_not_camera_only() {+ let display = ScreenCaptureTarget::Display {+ id: "1".parse().unwrap(),+ };+ assert!(clean_capture_supported(+ RecordingMode::Studio,+ &display,+ false,+ false+ ));+ assert!(clean_capture_supported(+ RecordingMode::Studio,+ &display,+ false,+ true+ ));+ assert!(clean_capture_supported(+ RecordingMode::Instant,+ &display,+ false,+ false+ ));+ assert!(!clean_capture_supported(+ RecordingMode::Studio,+ &ScreenCaptureTarget::CameraOnly,+ true,+ false+ ));+ assert!(!clean_capture_supported(+ RecordingMode::Studio,+ &ScreenCaptureTarget::Window {+ id: "1".parse().unwrap()+ },+ true,+ false+ ));+ let window = ScreenCaptureTarget::Window {+ id: "1".parse().unwrap(),+ };+ assert!(clean_capture_supported(+ RecordingMode::Instant,+ &window,+ true,+ false+ ));+ assert!(!clean_capture_supported(+ RecordingMode::Instant,+ &window,+ false,+ false+ ));+ assert!(!clean_capture_supported(+ RecordingMode::Instant,+ &window,+ true,+ true+ ));+ assert!(!clean_capture_supported(+ RecordingMode::Instant,+ &ScreenCaptureTarget::CameraOnly,+ true,+ false+ ));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn instant_camera_maps_physical_origins_without_monitor_scale_guessing() {+ use camera_window::{LinuxCameraPhysicalRect, LinuxCameraRecordingSnapshot};+ let capture = LinuxCameraPhysicalRect {+ x: -1920,+ y: -1200,+ width: 1920,+ height: 1080,+ };+ let snapshot = LinuxCameraRecordingSnapshot {+ content_rect: LinuxCameraPhysicalRect {+ x: -1860,+ y: -1100,+ width: 230,+ height: 230,+ },+ state: crate::store::CameraWindowState::default(),+ corner_radius_pixels: 115.0,+ };+ let presentation = linux_camera_presentation(snapshot, capture).unwrap();+ assert_eq!(presentation.rect.x, 60);+ assert_eq!(presentation.rect.y, 100);+ assert_eq!(presentation.rect.width, 230);+ assert_eq!(presentation.rect.height, 230);+ assert_eq!(+ presentation.shape,+ cap_recording::instant_recording::LinuxCameraShape::Round+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn instant_camera_keeps_live_full_shape_mirror_and_effect_request() {+ use crate::store::{BlurMode, CameraShape, CameraWindowState};+ use camera_window::{LinuxCameraPhysicalRect, LinuxCameraRecordingSnapshot};+ use cap_recording::instant_recording::{LinuxCameraEffect, LinuxCameraShape};+ let capture = LinuxCameraPhysicalRect {+ x: 0,+ y: 0,+ width: 1280,+ height: 720,+ };+ let snapshot = LinuxCameraRecordingSnapshot {+ content_rect: LinuxCameraPhysicalRect {+ x: 160,+ y: 80,+ width: 600,+ height: 300,+ },+ state: CameraWindowState {+ shape: CameraShape::Full,+ mirrored: true,+ background_blur: BlurMode::Heavy,+ ..CameraWindowState::default()+ },+ corner_radius_pixels: 36.0,+ };+ let presentation = linux_camera_presentation(snapshot, capture).unwrap();+ assert!(presentation.mirrored);+ assert_eq!(presentation.effect, LinuxCameraEffect::BackgroundBlur);+ assert_eq!(presentation.rect.width, 600);+ assert_eq!(presentation.rect.height, 300);+ assert_eq!(+ presentation.shape,+ LinuxCameraShape::RoundedRectangle { radius_pixels: 36 }+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn instant_camera_does_not_crop_or_omit_an_outside_preview() {+ use camera_window::{LinuxCameraPhysicalRect, LinuxCameraRecordingSnapshot};+ let capture = LinuxCameraPhysicalRect {+ x: 100,+ y: 100,+ width: 1000,+ height: 600,+ };+ for (x, y) in [(99, 100), (100, 99), (871, 100), (100, 471)] {+ let snapshot = LinuxCameraRecordingSnapshot {+ content_rect: LinuxCameraPhysicalRect {+ x,+ y,+ width: 230,+ height: 230,+ },+ state: crate::store::CameraWindowState::default(),+ corner_radius_pixels: 115.0,+ };+ let error = linux_camera_presentation(snapshot, capture).unwrap_err();+ assert!(error.to_string().contains("Move the whole camera preview"));+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn instant_camera_preserves_one_pixel_rounding_without_square_crop() {+ use camera_window::{LinuxCameraPhysicalRect, LinuxCameraRecordingSnapshot};+ let capture = LinuxCameraPhysicalRect {+ x: 0,+ y: 0,+ width: 1280,+ height: 720,+ };+ let mut snapshot = LinuxCameraRecordingSnapshot {+ content_rect: LinuxCameraPhysicalRect {+ x: 200,+ y: 100,+ width: 307,+ height: 306,+ },+ state: crate::store::CameraWindowState::default(),+ corner_radius_pixels: 153.3333,+ };+ let presentation = linux_camera_presentation(snapshot, capture).unwrap();+ assert_eq!(presentation.rect.width, 307);+ assert_eq!(presentation.rect.height, 306);+ assert_eq!(+ presentation.shape,+ cap_recording::instant_recording::LinuxCameraShape::RoundedRectangle {+ radius_pixels: 153+ }+ );+ snapshot.content_rect.width = 308;+ assert!(linux_camera_presentation(snapshot, capture).is_err());+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn instant_camera_reference_keeps_odd_window_dimensions_and_rejects_invalid_bounds() {+ let bounds = linux_window_capture_bounds(-40.0, 31.0, 1281.0, 721.0).unwrap();+ assert_eq!((bounds.x, bounds.y), (-40, 31));+ assert_eq!((bounds.width, bounds.height), (1281, 721));+ for value in [+ f64::NAN,+ f64::INFINITY,+ 0.0,+ 1.0,+ 400.5,+ f64::from(u32::MAX),+ ] {+ assert!(linux_window_capture_bounds(0.0, 0.0, value, 720.0).is_err());+ }+ assert!(linux_window_capture_bounds(-0.5, 0.0, 1280.0, 720.0).is_err());+ assert!(linux_window_capture_bounds(0.0, f64::INFINITY, 1280.0, 720.0).is_err());+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn instant_camera_area_reference_uses_shared_capture_edge_rounding() {+ let capture = cap_recording::sources::screen_capture::x11_capture_rect(+ -1920.0,+ 0.0,+ 1920.0,+ 1080.0,+ Some((10.25, 20.5, 800.25, 600.25)),+ )+ .unwrap();+ assert_eq!(capture, (-1910, 20, 800, 600));+ }+/// `restore_main_windows_if_no_editors` (`lib.rs:6242-6262`): the main/// window comes back only when the closing editor was the last one of/// either kind *and* no Settings window exists. Settings -> Recordings ->diff --git a/apps/desktop-gpui/src/camera_blur_portable.rs b/apps/desktop-gpui/src/camera_blur_portable.rsindex 85fa7b450..735eebb74 100644--- a/apps/desktop-gpui/src/camera_blur_portable.rs+++ b/apps/desktop-gpui/src/camera_blur_portable.rs@@ -105,6 +105,16 @@ impl PortableCameraBlur {dimensions: (usize, usize),mode: cap_camera_effects::BlurMode,) -> anyhow::Result<Arc<gpui::RenderImage>> {+ self.process_with_status(image, dimensions, mode)+ .map(|(image, _)| image)+ }++ pub fn process_with_status(+ &mut self,+ image: &gpui::RenderImage,+ dimensions: (usize, usize),+ mode: cap_camera_effects::BlurMode,+ ) -> anyhow::Result<(Arc<gpui::RenderImage>, cap_camera_effects::BlurOutputStatus)> {let width = u32::try_from(dimensions.0).context("camera frame width")?;let height = u32::try_from(dimensions.1).context("camera frame height")?;let row_bytes = width.checked_mul(4).context("camera frame row size")?;@@ -215,9 +225,16 @@ impl PortableCameraBlur {let image = image::RgbaImage::from_raw(width, height, pixels).context("camera blur output image")?;- Ok(Arc::new(gpui::RenderImage::new(smallvec::smallvec![- image::Frame::new(image)- ])))+ let status = self+ .processor+ .output_status()+ .context("camera blur output status missing")?;+ Ok((+ Arc::new(gpui::RenderImage::new(smallvec::smallvec![+ image::Frame::new(image)+ ])),+ status,+ ))}fn ensure_resources(&mut self, width: u32, height: u32) -> anyhow::Result<()> {@@ -299,10 +316,13 @@ mod tests {let image = image::RgbaImage::from_raw(64, 32, pixels).unwrap();let input = gpui::RenderImage::new(smallvec::smallvec![image::Frame::new(image)]);let mut processor = PortableCameraBlur::new().expect("portable camera blur initialized");- let output = processor- .process(&input, (64, 32), cap_camera_effects::BlurMode::Heavy)+ let (output, status) = processor+ .process_with_status(&input, (64, 32), cap_camera_effects::BlurMode::Heavy).expect("portable camera blur processed a frame");+ assert_eq!(status.mode, cap_camera_effects::BlurMode::Heavy);+ assert_eq!(status.output_sequence, 1);+ assert_eq!(status.output_dimensions, (64, 32));assert_eq!(output.size(0).width.0, 64);assert_eq!(output.size(0).height.0, 32);assert_eq!(output.as_bytes(0).unwrap().len(), 64 * 32 * 4);diff --git a/apps/desktop-gpui/src/camera_window.rs b/apps/desktop-gpui/src/camera_window.rsindex 353fad823..9d5bdd249 100644--- a/apps/desktop-gpui/src/camera_window.rs+++ b/apps/desktop-gpui/src/camera_window.rs@@ -121,6 +121,101 @@ fn preview_radius(state: &CameraWindowState) -> f32 {}}+#[cfg(target_os = "linux")]+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct LinuxCameraPhysicalRect {+ pub x: i32,+ pub y: i32,+ pub width: u32,+ pub height: u32,+}++#[cfg(target_os = "linux")]+#[derive(Debug, Clone, Copy, PartialEq)]+pub(crate) struct LinuxCameraRecordingSnapshot {+ pub content_rect: LinuxCameraPhysicalRect,+ pub state: CameraWindowState,+ pub corner_radius_pixels: f32,+}++#[cfg(target_os = "linux")]+fn recording_physical_extent(logical: f32, scale_factor: f32) -> anyhow::Result<u32> {+ let physical = (logical * scale_factor).round();+ if !logical.is_finite()+ || logical <= 0.0+ || !physical.is_finite()+ || physical < 1.0+ || f64::from(physical) > f64::from(i32::MAX)+ {+ anyhow::bail!("Camera geometry has invalid or unsupported physical dimensions");+ }+ Ok(physical as u32)+}++#[cfg(target_os = "linux")]+fn linux_camera_recording_snapshot(+ state: CameraWindowState,+ frame_dimensions: (usize, usize),+ client_rect: LinuxCameraPhysicalRect,+ viewport: (f32, f32),+ scale_factor: f32,+) -> anyhow::Result<LinuxCameraRecordingSnapshot> {+ if !scale_factor.is_finite() || scale_factor <= 0.0 {+ anyhow::bail!("Camera window has an invalid scale factor");+ }+ if !state.size.is_finite() || state.size <= 0.0 {+ anyhow::bail!("Camera window has an invalid preview size");+ }+ let (frame_width, frame_height) = frame_dimensions;+ if frame_width == 0+ || frame_height == 0+ || u32::try_from(frame_width).is_err()+ || u32::try_from(frame_height).is_err()+ {+ anyhow::bail!("Camera recording requires valid delivered frame dimensions");+ }+ let physical_viewport = (+ recording_physical_extent(viewport.0, scale_factor)?,+ recording_physical_extent(viewport.1, scale_factor)?,+ );+ if physical_viewport != (client_rect.width, client_rect.height) {+ anyhow::bail!("Camera viewport and X11 client dimensions disagree; wait for resizing");+ }+ let expected = window_size(&state, Some(frame_width as f32 / frame_height as f32));+ if (+ recording_physical_extent(expected.0, scale_factor)?,+ recording_physical_extent(expected.1, scale_factor)?,+ ) != physical_viewport+ {+ anyhow::bail!("Camera presentation and viewport disagree; wait for resizing");+ }++ // X11 supplies the client origin; only the local toolbar offset uses GPUI's scale.+ let toolbar_height = recording_physical_extent(CAMERA_TOOLBAR_HEIGHT, scale_factor)?;+ let content_height = client_rect+ .height+ .checked_sub(toolbar_height)+ .filter(|height| *height > 0)+ .ok_or_else(|| anyhow::anyhow!("Camera viewport has no preview below its toolbar"))?;+ let content_y = i32::try_from(i64::from(client_rect.y) + i64::from(toolbar_height))?;+ i32::try_from(i64::from(client_rect.x) + i64::from(client_rect.width))?;+ i32::try_from(i64::from(client_rect.y) + i64::from(client_rect.height))?;+ if state.shape == CameraShape::Round && client_rect.width.abs_diff(content_height) > 1 {+ anyhow::bail!("Round camera preview does not have square physical bounds");+ }++ Ok(LinuxCameraRecordingSnapshot {+ content_rect: LinuxCameraPhysicalRect {+ x: client_rect.x,+ y: content_y,+ width: client_rect.width,+ height: content_height,+ },+ state,+ corner_radius_pixels: preview_radius(&state) * scale_factor,+ })+}+#[cfg(target_os = "macos")]mod frame {use cidre::{arc, cf, cv, vt};@@ -657,6 +752,46 @@ pub struct CameraWindow {}impl CameraWindow {+ #[cfg(target_os = "linux")]+ pub(crate) fn recording_snapshot(+ &self,+ window: &Window,+ ) -> anyhow::Result<LinuxCameraRecordingSnapshot> {+ use anyhow::Context as _;+ use raw_window_handle::{HasWindowHandle, RawWindowHandle};+ use x11rb::protocol::xproto::ConnectionExt as _;++ let frame_dimensions = self+ .frame_dims+ .context("Camera recording requires a delivered preview frame")?;+ let window_id = match HasWindowHandle::window_handle(window)?.as_raw() {+ RawWindowHandle::Xlib(handle) => u32::try_from(handle.window)?,+ RawWindowHandle::Xcb(handle) => handle.window.get(),+ _ => anyhow::bail!("Camera recording geometry requires an X11 window"),+ };+ let (connection, _) = x11rb::connect(None)?;+ let geometry = connection.get_geometry(window_id)?.reply()?;+ let origin = connection+ .translate_coordinates(window_id, geometry.root, 0, 0)?+ .reply()?;+ if !origin.same_screen {+ anyhow::bail!("Camera client and root window are on different X11 screens");+ }+ let viewport = window.viewport_size();+ linux_camera_recording_snapshot(+ self.state,+ frame_dimensions,+ LinuxCameraPhysicalRect {+ x: i32::from(origin.dst_x),+ y: i32::from(origin.dst_y),+ width: u32::from(geometry.width),+ height: u32::from(geometry.height),+ },+ (f32::from(viewport.width), f32::from(viewport.height)),+ window.scale_factor(),+ )+ }+pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {// `document.documentElement.classList.toggle("dark", true)`// (`camera.tsx:128`): the bubble is always dark, whatever the app@@ -1633,3 +1768,204 @@ fn persist_camera_position(x: f64, y: f64) {);}}++#[cfg(all(test, target_os = "linux"))]+mod recording_snapshot_tests {+ use super::*;++ fn geometry(+ state: CameraWindowState,+ frame_dimensions: (usize, usize),+ scale: f32,+ origin: (i32, i32),+ ) -> (LinuxCameraPhysicalRect, (f32, f32)) {+ let logical = window_size(+ &state,+ Some(frame_dimensions.0 as f32 / frame_dimensions.1 as f32),+ );+ let width = (logical.0 * scale).round() as u32;+ let height = (logical.1 * scale).round() as u32;+ (+ LinuxCameraPhysicalRect {+ x: origin.0,+ y: origin.1,+ width,+ height,+ },+ (width as f32 / scale, height as f32 / scale),+ )+ }++ #[test]+ fn snapshot_uses_client_origin_and_scaled_toolbar_at_supported_scales() {+ let state = CameraWindowState::default();+ for scale in [1.0, 1.25, 1.5, 2.0] {+ for origin in [(37, 91), (-1920, -1080)] {+ let (client, viewport) = geometry(state, (640, 480), scale, origin);+ let snapshot =+ linux_camera_recording_snapshot(state, (640, 480), client, viewport, scale)+ .unwrap();+ let expected_side = (state.size * scale).round() as u32;+ assert_eq!(+ snapshot.content_rect,+ LinuxCameraPhysicalRect {+ x: origin.0,+ y: origin.1 + (CAMERA_TOOLBAR_HEIGHT * scale).round() as i32,+ width: expected_side,+ height: expected_side,+ }+ );+ assert_eq!(snapshot.corner_radius_pixels, state.size * scale / 2.0);+ assert_eq!(snapshot.state, state);+ }+ }+ }++ #[test]+ fn snapshot_preserves_full_aspect_and_live_effect_state() {+ let state = CameraWindowState {+ size: 400.0,+ shape: CameraShape::Full,+ mirrored: true,+ background_blur: BlurMode::Heavy,+ };+ let (client, viewport) = geometry(state, (1920, 1080), 1.5, (-1400, 20));+ let snapshot =+ linux_camera_recording_snapshot(state, (1920, 1080), client, viewport, 1.5).unwrap();+ assert_eq!(snapshot.content_rect.width, 1067);+ assert_eq!(snapshot.content_rect.height, 600);+ assert_eq!(snapshot.content_rect.x, -1400);+ assert_eq!(snapshot.content_rect.y, 104);+ assert_eq!(snapshot.corner_radius_pixels, 36.0);+ assert_eq!(snapshot.state, state);+ }++ #[test]+ fn snapshot_square_radius_scales_without_becoming_a_circle() {+ let state = CameraWindowState {+ shape: CameraShape::Square,+ background_blur: BlurMode::Light,+ ..CameraWindowState::default()+ };+ for scale in [1.0, 1.25, 1.5, 2.0] {+ let (client, viewport) = geometry(state, (1280, 720), scale, (0, 0));+ let snapshot =+ linux_camera_recording_snapshot(state, (1280, 720), client, viewport, scale)+ .unwrap();+ assert_eq!(snapshot.content_rect.width, snapshot.content_rect.height);+ assert_eq!(snapshot.corner_radius_pixels, 24.0 * scale);+ assert_eq!(snapshot.state, state);+ }+ }++ #[test]+ fn snapshot_rejects_native_viewport_and_pending_state_resize_mismatches() {+ let state = CameraWindowState::default();+ let (client, viewport) = geometry(state, (640, 480), 1.25, (0, 0));+ assert!(+ linux_camera_recording_snapshot(+ state,+ (640, 480),+ client,+ (viewport.0 + 1.0, viewport.1),+ 1.25,+ )+ .is_err()+ );+ assert!(+ linux_camera_recording_snapshot(+ CameraWindowState {+ size: 400.0,+ ..state+ },+ (640, 480),+ client,+ viewport,+ 1.25,+ )+ .is_err()+ );+ let full = CameraWindowState {+ shape: CameraShape::Full,+ ..state+ };+ let (client, viewport) = geometry(full, (1920, 1080), 1.0, (0, 0));+ assert!(+ linux_camera_recording_snapshot(full, (2400, 1000), client, viewport, 1.0).is_err()+ );+ }++ #[test]+ fn snapshot_rejects_invalid_scale_size_frame_and_viewport() {+ let state = CameraWindowState::default();+ let (client, viewport) = geometry(state, (640, 480), 1.0, (0, 0));+ for invalid in [0.0, -1.0, f32::NAN, f32::INFINITY] {+ assert!(+ linux_camera_recording_snapshot(state, (640, 480), client, viewport, invalid)+ .is_err()+ );+ assert!(+ linux_camera_recording_snapshot(+ CameraWindowState {+ size: invalid,+ ..state+ },+ (640, 480),+ client,+ viewport,+ 1.0,+ )+ .is_err()+ );+ assert!(+ linux_camera_recording_snapshot(+ state,+ (640, 480),+ client,+ (invalid, viewport.1),+ 1.0,+ )+ .is_err()+ );+ }+ for frame in [(0, 480), (640, 0)] {+ assert!(linux_camera_recording_snapshot(state, frame, client, viewport, 1.0).is_err());+ }+ assert!(+ linux_camera_recording_snapshot(+ state,+ (640, 480),+ LinuxCameraPhysicalRect { width: 0, ..client },+ viewport,+ 1.0,+ )+ .is_err()+ );+ }++ #[test]+ fn snapshot_rejects_coordinate_and_scaled_extent_overflow() {+ let state = CameraWindowState::default();+ for origin in [(i32::MAX, 0), (0, i32::MAX)] {+ let (client, viewport) = geometry(state, (640, 480), 1.0, origin);+ assert!(+ linux_camera_recording_snapshot(state, (640, 480), client, viewport, 1.0).is_err()+ );+ }+ assert!(recording_physical_extent(f32::MAX, 2.0).is_err());+ assert!(recording_physical_extent(i32::MAX as f32, 1.0).is_err());+ }++ #[test]+ fn snapshot_preserves_one_pixel_rounding_difference_at_fractional_scale() {+ let state = CameraWindowState::default();+ let scale = 4.0 / 3.0;+ let (client, viewport) = geometry(state, (640, 480), scale, (0, 0));+ let snapshot =+ linux_camera_recording_snapshot(state, (640, 480), client, viewport, scale).unwrap();+ assert_eq!(snapshot.content_rect.width, 307);+ assert_eq!(snapshot.content_rect.height, 306);+ assert_eq!(snapshot.content_rect.x, client.x);+ assert_eq!(snapshot.content_rect.y, client.y + 75);+ }+}diff --git a/apps/desktop-gpui/src/deeplink.rs b/apps/desktop-gpui/src/deeplink.rsindex ce119e51b..4eb7ca684 100644--- a/apps/desktop-gpui/src/deeplink.rs+++ b/apps/desktop-gpui/src/deeplink.rs@@ -25,9 +25,8 @@//! second instance on macOS -- the AppleEvent goes to the running process.//! * **App launched by the URL.** Tauri's single-instance plugin hands the new//! launch's `cap-desktop://` argv to the surviving old instance-//! (`lib.rs:5193-5204`). This app's single instancing is new-instance-wins-//! (see [`crate::single_instance`]), so the launch that carries the URL *is*-//! the instance that survives: [`init`] reads its own argv. On macOS the+//! (`lib.rs:5193-5204`). Linux and Windows forward action URLs to the+//! surviving instance; [`init`] reads argv on the initial launch. On macOS the//! launch URL additionally arrives as the same GURL event once the run loop//! starts; both roads feed one channel, and the channel buffers until the//! drain task exists, so neither ordering loses the action.@@ -52,7 +51,7 @@ use crate::{app_windows,feeds::{Feeds, SelectedCamera},library, recording,- session::RecordingSession,+ session::{Phase, RecordingSession},settings_window::Page,};@@ -200,6 +199,13 @@ fn channel() -> &'static (CHANNEL.get_or_init(flume::unbounded)}+pub(crate) fn submit_action(action: DeepLinkAction) {+ tracing::info!("queueing deep link action");+ if channel().0.send(action).is_err() {+ tracing::error!("failed to queue deep link action");+ }+}+/// The one entry point for a URL handed over by the OS -- what/// `platform::install_url_scheme_handler`'s AppleEvent handler calls. Safe/// from any thread; does no gpui work itself.@@ -231,12 +237,7 @@ fn submit_action_url(raw: &str) {return;};match DeepLinkAction::try_from(&url) {- Ok(action) => {- tracing::info!(?action, "queueing deep link action");- if let Err(error) = channel().0.send(action) {- tracing::error!(%error, "failed to queue deep link action");- }- }+ Ok(action) => submit_action(action),Err(ActionParseFromUrlError::ParseFailed(message)) => {tracing::error!(scheme = url.scheme(),@@ -257,9 +258,7 @@ fn submit_action_url(raw: &str) {}}-/// Wire the executor: scan the launch argv for action URLs (the-/// new-instance-wins counterpart of Tauri's single-instance argv forwarding,-/// `lib.rs:5195-5204`, which filters on the `cap-desktop://` prefix), then+/// Wire the executor: scan the initial launch argv for action URLs, then/// start the drain task that runs each queued action on the main thread with/// a clean borrow. Called once from [`crate::app_windows::init`], after the/// window registry the actions dispatch into exists.@@ -274,7 +273,7 @@ pub fn init(cx: &mut App) {cx.spawn(async move |cx| {while let Ok(action) = rx.recv_async().await {cx.update(|cx| {- tracing::info!(?action, "executing deep link action");+ tracing::info!("executing deep link action");if let Err(error) = action.execute(cx) {tracing::error!(%error, "failed to handle deep link action");}@@ -284,6 +283,20 @@ pub fn init(cx: &mut App) {.detach();}+fn dispatch_recording_stop<C>(+ phase: Phase,+ clean_capture_owned: bool,+ context: &mut C,+ cancel_preflight: impl FnOnce(&mut C),+ stop_session: impl FnOnce(&mut C),+) {+ if phase == Phase::Idle && clean_capture_owned {+ cancel_preflight(context);+ } else {+ stop_session(context);+ }+}+impl DeepLinkAction {/// `DeepLinkAction::execute` (`deeplink_actions.rs:186-296`), arm for arm,/// against this app's counterparts: the session and feeds globals where@@ -298,20 +311,6 @@ impl DeepLinkAction {capture_system_audio,mode,} => {- // `set_camera_input` / `set_mic_input`: the deep link's devices- // replace the current selections (including `None` clearing- // them). `Feeds::set_camera` also opens/closes the preview- // bubble, which is what `set_camera_input` does through the- // camera preview over there.- let selection = camera.clone().map(|id| SelectedCamera {- label: camera_label(&id),- id,- });- Feeds::global(cx).update(cx, |feeds, cx| {- feeds.set_camera(selection, cx);- feeds.set_microphone(mic_label.clone(), cx);- });-// The name -> target resolution, verbatim from// `deeplink_actions.rs:200-231`.let capture_target: ScreenCaptureTarget = match capture_mode {@@ -357,42 +356,79 @@ impl DeepLinkAction {}};+ let main = cx.global::<app_windows::AppWindows>().main;+ let permit = main+ .update(cx, |view, _, cx| view.prepare_deep_link_start(cx))+ .map_err(|_| "The recording window is unavailable".to_string())??;+ let selection = camera.clone().map(|id| SelectedCamera {+ label: camera_label(&id),+ id,+ });+ if !permit.is_current(cx) {+ let _ = main.update(cx, |view, _, _| view.finish_deep_link_start(&permit));+ return Err("Recording preparation is no longer current".into());+ }+ Feeds::global(cx).update(cx, |feeds, cx| {+ feeds.set_camera(selection, cx);+ feeds.set_microphone(mic_label.clone(), cx);+ });+// Deferred behind `set_camera`'s own deferred// `open_camera_window`, so a studio start finds the bubble// already open and excludes it from capture// (`begin_recording`'s `camera_window_number` read). gpui// flushes deferred callbacks in FIFO order.cx.defer(move |cx| {+ if !permit.is_current(cx) {+ let _ = main.update(cx, |view, _, _| view.finish_deep_link_start(&permit));+ return;+ }let (camera_feed, mic_feed) = {let feeds = Feeds::global(cx);feeds.update(cx, |feeds, cx| feeds.resume_camera_preview(cx));let feeds = feeds.read(cx);(feeds.camera_actor(), feeds.mic_actor())};- let main = cx.global::<app_windows::AppWindows>().main;- main.update(cx, |view, _, cx| {- view.start_recording_config(- recording::StartConfig {- mode,- target: capture_target,- microphone: mic_label,- camera,- system_audio: capture_system_audio,- excluded_windows: Vec::new(),- camera_feed,- mic_feed,- },- cx,- )- })- .ok();+ if main+ .update(cx, |view, _, cx| {+ view.start_recording_config_with_permit(+ recording::StartConfig {+ mode,+ target: capture_target,+ microphone: mic_label,+ camera,+ system_audio: capture_system_audio,+ excluded_windows: Vec::new(),+ camera_feed,+ mic_feed,+ #[cfg(target_os = "linux")]+ linux_instant_camera: None,+ },+ permit.clone(),+ cx,+ )+ })+ .is_err()+ {+ permit.cancel();+ }});Ok(())}- // `recording::stop_recording`; the session's own phase guard is- // the Tauri command's "no recording in progress" early-out.DeepLinkAction::StopRecording => {- RecordingSession::global(cx).update(cx, |session, cx| session.stop(cx));+ let main = cx.global::<app_windows::AppWindows>().main;+ let _ = main.update(cx, |view, _, cx| {+ view.cancel_deep_link_start();+ cx.notify();+ });+ let session = RecordingSession::global(cx);+ dispatch_recording_stop(+ session.read(cx).phase,+ app_windows::clean_capture_owned(cx),+ cx,+ app_windows::cancel_clean_capture,+ |cx| session.update(cx, |session, cx| session.stop(cx)),+ );Ok(())}// `pause_recording` / `resume_recording`@@ -536,6 +572,53 @@ fn camera_label(id: &DeviceOrModelID) -> String {mod tests {use super::*;+ #[test]+ fn stop_dispatch_cancels_idle_preflight_and_preserves_live_session_stop() {+ for phase in [+ Phase::Idle,+ Phase::Starting,+ Phase::Recording { paused: false },+ Phase::Recording { paused: true },+ Phase::Stopping,+ ] {+ for owned in [false, true] {+ let mut effects = (0, 0);+ dispatch_recording_stop(+ phase,+ owned,+ &mut effects,+ |effects| effects.0 += 1,+ |effects| effects.1 += 1,+ );+ assert_eq!(+ effects,+ if phase == Phase::Idle && owned {+ (1, 0)+ } else {+ (0, 1)+ }+ );+ }+ }+ }++ #[test]+ fn forwarded_actions_wait_in_the_existing_queue_until_dispatch() {+ let expected = [+ DeepLinkAction::OpenSettings { page: None },+ DeepLinkAction::OpenEditor {+ project_path: "/tmp/forwarded-recording.cap".into(),+ },+ ];+ for action in &expected {+ submit_action(action.clone());+ }+ for action in expected {+ assert_eq!(channel().1.try_recv().unwrap(), action);+ }+ assert!(channel().1.is_empty());+ }+// -- The Tauri parser's own tests (`deeplink_actions.rs:299-514`),// -- unchanged except for crate paths, so grammar drift fails loudly.diff --git a/apps/desktop-gpui/src/feeds.rs b/apps/desktop-gpui/src/feeds.rsindex 0c9fcd3f2..12e217efc 100644--- a/apps/desktop-gpui/src/feeds.rs+++ b/apps/desktop-gpui/src/feeds.rs@@ -43,6 +43,515 @@ pub fn bar_level(db: f64) -> f64 {((db + 60.0) / 60.0).clamp(0.0, 1.0)}+#[cfg(not(target_os = "macos"))]+enum CameraWorkerCommand {+ Reset,+ #[cfg(target_os = "linux")]+ Record(RecordingCameraWorker),+}++#[cfg(target_os = "linux")]+#[derive(Clone)]+pub struct CameraProcessingFactory {+ commands: flume::Sender<CameraWorkerCommand>,+ actor: ActorRef<CameraFeed>,+ selected: DeviceOrModelID,+ epoch: u64,+ current_epoch: Arc<std::sync::atomic::AtomicU64>,+ recording_active: Arc<AtomicBool>,+ next_generation: Arc<std::sync::atomic::AtomicU64>,+}++#[cfg(target_os = "linux")]+struct CameraRecordingReservation(Arc<AtomicBool>);++#[cfg(target_os = "linux")]+impl CameraRecordingReservation {+ fn try_acquire(active: &Arc<AtomicBool>) -> Option<Self> {+ active+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)+ .ok()+ .map(|_| Self(active.clone()))+ }+}++#[cfg(target_os = "linux")]+impl Drop for CameraRecordingReservation {+ fn drop(&mut self) {+ self.0.store(false, Ordering::Release);+ }+}++#[cfg(target_os = "linux")]+struct RecordingCameraAttachment {+ feed: ActorRef<CameraFeed>,+ sender: flume::Sender<cap_recording::FFmpegVideoFrame>,+ runtime: tokio::runtime::Handle,+ _reservation: CameraRecordingReservation,+}++#[cfg(target_os = "linux")]+impl Drop for RecordingCameraAttachment {+ fn drop(&mut self) {+ let feed = self.feed.clone();+ let sender = self.sender.clone();+ drop(self.runtime.spawn(async move {+ let _ = feed.ask(camera::RemoveSender(sender)).await;+ }));+ }+}++#[cfg(target_os = "linux")]+struct RecordingCameraWorker {+ frames: flume::Receiver<cap_recording::FFmpegVideoFrame>,+ publisher: cap_recording::instant_recording::LinuxCameraPublisher,+ processing: cap_recording::instant_recording::LinuxCameraProcessing,+ epoch: u64,+ current_epoch: Arc<std::sync::atomic::AtomicU64>,+ generation: u64,+ not_before: Instant,+ _attachment: RecordingCameraAttachment,+}++#[cfg(target_os = "linux")]+impl CameraProcessingFactory {+ pub async fn subscribe(+ &self,+ feed: Arc<camera::CameraFeedLock>,+ processing: cap_recording::instant_recording::LinuxCameraProcessing,+ ) -> anyhow::Result<cap_recording::instant_recording::LinuxProcessedCameraSource> {+ let info = feed.camera_info();+ let matches = match &self.selected {+ DeviceOrModelID::DeviceID(id) => info.device_id() == id,+ DeviceOrModelID::ModelID(id) => info.model_id() == Some(id),+ };+ anyhow::ensure!(+ matches && feed.id() == self.actor.id(),+ "Processed camera factory does not match the locked camera"+ );+ anyhow::ensure!(+ self.current_epoch.load(Ordering::Acquire) == self.epoch,+ "Camera selection changed before recording"+ );+ let reservation = tokio::time::timeout(Duration::from_millis(1500), async {+ loop {+ if let Some(reservation) =+ CameraRecordingReservation::try_acquire(&self.recording_active)+ {+ break reservation;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .map_err(|_| anyhow::anyhow!("A processed camera recording is already active"))?;+ let (sender, frames) = flume::bounded(2);+ let attachment = RecordingCameraAttachment {+ feed: self.actor.clone(),+ sender: sender.clone(),+ runtime: tokio::runtime::Handle::current(),+ _reservation: reservation,+ };+ anyhow::ensure!(+ self.current_epoch.load(Ordering::Acquire) == self.epoch,+ "Camera selection changed while waiting for recording processing"+ );+ let not_before = Instant::now();+ let generation = self.next_generation.fetch_add(1, Ordering::AcqRel) + 1;+ let (publisher, mut source) =+ cap_recording::instant_recording::LinuxProcessedCameraSource::channel(+ feed.clone(),+ processing,+ generation,+ not_before,+ );+ tokio::time::timeout(+ Duration::from_millis(1500),+ feed.ask(camera::AddSender(sender)),+ )+ .await+ .map_err(|_| anyhow::anyhow!("Timed out attaching processed camera"))?+ .map_err(|error| anyhow::anyhow!("Attaching processed camera: {error}"))?;+ tokio::time::timeout(+ Duration::from_millis(1500),+ self.commands+ .send_async(CameraWorkerCommand::Record(RecordingCameraWorker {+ frames,+ publisher,+ processing,+ epoch: self.epoch,+ current_epoch: self.current_epoch.clone(),+ generation,+ not_before,+ _attachment: attachment,+ })),+ )+ .await+ .map_err(|_| anyhow::anyhow!("Camera processing worker command deadline exceeded"))?+ .map_err(|_| anyhow::anyhow!("Camera preview processing worker is unavailable"))?;+ source.wait_ready(Duration::from_secs(10)).await?;+ anyhow::ensure!(+ self.current_epoch.load(Ordering::Acquire) == self.epoch,+ "Camera selection changed while preparing recording effects"+ );+ Ok(source)+ }+}++#[cfg(target_os = "linux")]+impl RecordingCameraWorker {+ fn publish(+ &self,+ image: &gpui::RenderImage,+ dims: (usize, usize),+ timestamp: cap_timestamp::Timestamp,+ mask: Option<cap_recording::instant_recording::LinuxCameraMaskReceipt>,+ ) {+ if self.publisher.is_cancelled() {+ return;+ }+ match validate_recording_camera_frame(+ timestamp,+ self.not_before,+ self.epoch,+ self.current_epoch.load(Ordering::Acquire),+ ) {+ Ok(true) => {}+ Ok(false) => return,+ Err(error) => {+ self.publisher.fail(error);+ return;+ }+ }+ let Some(bytes) = image.as_bytes(0) else {+ self.publisher+ .fail("Processed camera pixels unavailable".to_string());+ return;+ };+ self.publisher.publish(+ cap_recording::instant_recording::LinuxProcessedCameraFrame {+ bgra: Arc::from(bytes),+ dimensions: (dims.0 as u32, dims.1 as u32),+ stride: dims.0 * 4,+ timestamp,+ generation: self.generation,+ processing: self.processing,+ mask,+ },+ );+ }+}++#[cfg(target_os = "linux")]+fn validate_recording_camera_frame(+ timestamp: cap_timestamp::Timestamp,+ not_before: Instant,+ epoch: u64,+ current_epoch: u64,+) -> Result<bool, String> {+ if epoch != current_epoch {+ return Err("Camera selection changed during recording".to_string());+ }+ let cap_timestamp::Timestamp::Instant(captured_at) = timestamp else {+ return Err("Camera capture timestamp is not monotonic".to_string());+ };+ Ok(captured_at >= not_before)+}++#[cfg(target_os = "linux")]+fn checked_recording_blur(+ status: &cap_camera_effects::BlurOutputStatus,+ expected_mode: cap_camera_effects::BlurMode,+ dimensions: (u32, u32),+ now: Instant,+) -> Result<Option<cap_recording::instant_recording::LinuxCameraMaskReceipt>, String> {+ match status.applied_at(+ now,+ cap_recording::instant_recording::LINUX_CAMERA_MAX_MASK_AGE,+ ) {+ Ok(applied) if applied.mode == expected_mode && applied.output_dimensions == dimensions => {+ Ok(Some(+ cap_recording::instant_recording::LinuxCameraMaskReceipt {+ generation: applied.mask.generation,+ submitted_at: applied.mask.input_submitted_at,+ completed_at: applied.mask.inference_completed_at,+ },+ ))+ }+ Err(cap_camera_effects::BlurOutputUnavailable::Pending) => Ok(None),+ other => Err(format!("Requested camera blur was not applied: {other:?}")),+ }+}++#[cfg(target_os = "linux")]+fn frozen_processing_state(+ processing: cap_recording::instant_recording::LinuxCameraProcessing,+) -> (u8, bool) {+ use cap_recording::instant_recording::LinuxCameraBlur;+ (+ match processing.blur {+ LinuxCameraBlur::Off => 0,+ LinuxCameraBlur::Light => 1,+ LinuxCameraBlur::Heavy => 2,+ },+ processing.mirrored,+ )+}++#[cfg(not(target_os = "macos"))]+struct CameraPreviewWorkerConfig {+ frames: flume::Receiver<cap_recording::FFmpegVideoFrame>,+ previews: flume::Sender<crate::camera_window::CameraPreviewFrame>,+ commands: flume::Receiver<CameraWorkerCommand>,+ mirrored: Arc<AtomicBool>,+ active: Arc<AtomicBool>,+ blur: Arc<AtomicU8>,+}++#[cfg(not(target_os = "macos"))]+fn run_camera_preview_worker(config: CameraPreviewWorkerConfig) {+ let CameraPreviewWorkerConfig {+ frames: frame_rx,+ previews: preview_tx,+ commands: reset_rx,+ mirrored,+ active,+ blur,+ } = config;+ let mut scaler = None;+ let mut processor = None;+ let mut previous_blur = 0;+ let mut blur_failed = false;+ #[cfg(target_os = "linux")]+ let mut recording: Option<RecordingCameraWorker> = None;+ loop {+ #[cfg(target_os = "linux")]+ if recording+ .as_ref()+ .is_some_and(|recording| recording.publisher.is_cancelled())+ {+ recording = None;+ scaler = None;+ processor = None;+ previous_blur = 0;+ blur_failed = false;+ }+ enum Event {+ Frame(Result<cap_recording::FFmpegVideoFrame, flume::RecvError>),+ Command(Result<CameraWorkerCommand, flume::RecvError>),+ }+ let input = &frame_rx;+ #[cfg(target_os = "linux")]+ let input = recording+ .as_ref()+ .map_or(input, |recording| &recording.frames);+ let selector = flume::Selector::new()+ .recv(input, Event::Frame)+ .recv(&reset_rx, Event::Command);+ #[cfg(target_os = "linux")]+ let poll_cancellation = recording.is_some();+ #[cfg(not(target_os = "linux"))]+ let poll_cancellation = false;+ let event = if poll_cancellation {+ selector.wait_timeout(Duration::from_millis(50)).ok()+ } else {+ Some(selector.wait())+ };+ let mut frame = match event {+ Some(Event::Frame(Ok(frame))) => frame,+ Some(Event::Command(Ok(command))) => {+ match command {+ CameraWorkerCommand::Reset =>+ {+ #[cfg(target_os = "linux")]+ if let Some(recording) = &recording {+ recording+ .publisher+ .fail("Camera preview was reset during recording".to_string());+ }+ }+ #[cfg(target_os = "linux")]+ CameraWorkerCommand::Record(next) => {+ if recording.is_some() {+ next.publisher+ .fail("Another processed camera lease is still active".to_string());+ continue;+ }+ recording = Some(next);+ }+ }+ scaler = None;+ processor = None;+ previous_blur = 0;+ blur_failed = false;+ continue;+ }+ Some(Event::Frame(Err(_)) | Event::Command(Err(_))) => break,+ None => continue,+ };+ let processing_active = active.load(Ordering::Acquire);+ #[cfg(target_os = "linux")]+ let processing_active = processing_active || recording.is_some();+ if !processing_active {+ continue;+ }+ while let Ok(newer) = input.try_recv() {+ frame = newer;+ }+ let requested_blur = blur.load(Ordering::Relaxed);+ let requested_mirror = mirrored.load(Ordering::Relaxed);+ #[cfg(target_os = "linux")]+ let (requested_blur, requested_mirror) = if let Some(recording) = &recording {+ match validate_recording_camera_frame(+ frame.timestamp,+ recording.not_before,+ recording.epoch,+ recording.current_epoch.load(Ordering::Acquire),+ ) {+ Ok(true) => {}+ Ok(false) => continue,+ Err(error) => {+ recording.publisher.fail(error);+ continue;+ }+ }+ frozen_processing_state(recording.processing)+ } else {+ (requested_blur, requested_mirror)+ };+ if requested_blur != previous_blur {+ processor = None;+ blur_failed = false;+ previous_blur = requested_blur;+ }+ let blur_mode = match requested_blur {+ 1 => Some(cap_camera_effects::BlurMode::Light),+ 2 => Some(cap_camera_effects::BlurMode::Heavy),+ _ => None,+ }+ .filter(|_| !blur_failed && crate::camera_blur_portable::blur_allowed());+ #[cfg(target_os = "linux")]+ if requested_blur != 0+ && blur_mode.is_none()+ && let Some(recording) = &recording+ {+ recording+ .publisher+ .fail("Requested camera blur is unavailable".to_string());+ }+ let max_dims = blur_mode.map(|_| crate::camera_blur_portable::MAX_DIMS);+ let Some((mut image, dims)) =+ camera_preview_image(&frame.inner, &mut scaler, requested_mirror, max_dims)+ else {+ #[cfg(target_os = "linux")]+ if let Some(recording) = &recording {+ recording+ .publisher+ .fail("Camera frame conversion failed".to_string());+ }+ continue;+ };+ #[cfg(target_os = "linux")]+ let mut applied_mask = None;+ #[cfg(target_os = "linux")]+ let mut effects_ready = requested_blur == 0;+ if let Some(mode) = blur_mode+ && !blur_failed+ {+ if processor.is_none() {+ match crate::camera_blur_portable::PortableCameraBlur::new() {+ Ok(worker) => {+ tracing::info!("camera blur preview initialized");+ processor = Some(worker);+ }+ Err(error) => {+ tracing::warn!("camera blur preview unavailable: {error:#}");+ blur_failed = true;+ #[cfg(target_os = "linux")]+ if let Some(recording) = &recording {+ recording.publisher.fail(format!(+ "Requested camera blur initialization failed: {error:#}"+ ));+ }+ }+ }+ }+ if let Some(worker) = processor.as_mut() {+ #[cfg(target_os = "linux")]+ let require_verified_output = recording.is_some();+ #[cfg(not(target_os = "linux"))]+ let require_verified_output = false;+ let processed = if require_verified_output {+ worker+ .process_with_status(&image, dims, mode)+ .map(|(image, status)| (image, Some(status)))+ } else {+ worker+ .process(&image, dims, mode)+ .map(|image| (image, None))+ };+ match processed {+ Ok((blurred, status)) => {+ image = blurred;+ #[cfg(not(target_os = "linux"))]+ drop(status);+ #[cfg(target_os = "linux")]+ if let Some(recording) = &recording {+ let applied = status+ .as_ref()+ .ok_or_else(|| {+ "Requested camera blur has no output receipt".to_string()+ })+ .and_then(|status| {+ checked_recording_blur(+ status,+ mode,+ (dims.0 as u32, dims.1 as u32),+ Instant::now(),+ )+ });+ match applied {+ Ok(mask) => {+ effects_ready = mask.is_some();+ applied_mask = mask;+ }+ Err(error) => recording.publisher.fail(error),+ }+ }+ }+ Err(error) => {+ tracing::warn!("camera blur preview stopped: {error:#}");+ processor = None;+ blur_failed = true;+ #[cfg(target_os = "linux")]+ if let Some(recording) = &recording {+ recording+ .publisher+ .fail(format!("Requested camera blur failed: {error:#}"));+ }+ }+ }+ }+ }+ #[cfg(target_os = "linux")]+ if effects_ready && let Some(recording) = &recording {+ recording.publish(&image, dims, frame.timestamp, applied_mask);+ }+ if active.load(Ordering::Acquire) {+ match preview_tx.try_send(crate::camera_window::CameraPreviewFrame { image, dims }) {+ Ok(()) | Err(flume::TrySendError::Full(_)) => {}+ Err(flume::TrySendError::Disconnected(_)) => {+ #[cfg(target_os = "linux")]+ if recording.is_some() {+ continue;+ }+ break;+ }+ }+ }+ }+}+pub struct Feeds {camera_actor: Option<ActorRef<CameraFeed>>,mic_actor: Option<ActorRef<MicrophoneFeed>>,@@ -65,7 +574,13 @@ pub struct Feeds {#[cfg(not(target_os = "macos"))]camera_preview_blur: Arc<AtomicU8>,#[cfg(not(target_os = "macos"))]- camera_preview_reset: Option<flume::Sender<()>>,+ camera_preview_reset: Option<flume::Sender<CameraWorkerCommand>>,+ #[cfg(target_os = "linux")]+ camera_processing_epoch: Arc<std::sync::atomic::AtomicU64>,+ #[cfg(target_os = "linux")]+ camera_recording_active: Arc<AtomicBool>,+ #[cfg(target_os = "linux")]+ camera_recording_generation: Arc<std::sync::atomic::AtomicU64>,// Channel-holding tasks; dropping them ends the pumps._frame_pump: Option<gpui::Task<()>>,_meter_pump: Option<gpui::Task<()>>,@@ -102,6 +617,12 @@ impl Feeds {camera_preview_blur: Arc::new(AtomicU8::new(0)),#[cfg(not(target_os = "macos"))]camera_preview_reset: None,+ #[cfg(target_os = "linux")]+ camera_processing_epoch: Arc::new(std::sync::atomic::AtomicU64::new(0)),+ #[cfg(target_os = "linux")]+ camera_recording_active: Arc::new(AtomicBool::new(false)),+ #[cfg(target_os = "linux")]+ camera_recording_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),_frame_pump: None,_meter_pump: None,_mic_errors: None,@@ -125,11 +646,29 @@ impl Feeds {self.camera_actor.clone().filter(|actor| actor.is_alive())}+ #[cfg(target_os = "linux")]+ pub fn camera_processing_factory(&self) -> Option<CameraProcessingFactory> {+ Some(CameraProcessingFactory {+ commands: self.camera_preview_reset.clone()?,+ actor: self.camera_actor()?,+ selected: self.camera.as_ref()?.id.clone(),+ epoch: self.camera_epoch,+ current_epoch: self.camera_processing_epoch.clone(),+ recording_active: self.camera_recording_active.clone(),+ next_generation: self.camera_recording_generation.clone(),+ })+ }+pub fn mic_actor(&self) -> Option<ActorRef<MicrophoneFeed>> {self.microphone.as_ref()?;self.mic_actor.clone().filter(|actor| actor.is_alive())}+ #[cfg(target_os = "linux")]+ pub(crate) fn set_camera_preview_rendering(&self, enabled: bool) -> bool {+ self.camera_preview_active.swap(enabled, Ordering::AcqRel)+ }+#[cfg(not(target_os = "macos"))]pub fn set_camera_preview_state(&self, mirrored: bool, blur: crate::store::BlurMode) {self.camera_preview_mirrored@@ -151,6 +690,9 @@ impl Feeds {return;}self.camera_epoch += 1;+ #[cfg(target_os = "linux")]+ self.camera_processing_epoch+ .store(self.camera_epoch, Ordering::Release);self.camera = selection.clone();self.camera_error = None;cx.notify();@@ -179,12 +721,15 @@ impl Feeds {self.camera_preview_parked = true;self.camera_epoch += 1;+ #[cfg(target_os = "linux")]+ self.camera_processing_epoch+ .store(self.camera_epoch, Ordering::Release);#[cfg(not(target_os = "macos"))]{self.camera_preview_active.store(false, Ordering::Release);if let Some(reset) = &self.camera_preview_reset {- let _ = reset.try_send(());+ let _ = reset.try_send(CameraWorkerCommand::Reset);}}@@ -210,6 +755,9 @@ impl Feeds {self.camera_preview_active.store(true, Ordering::Release);if let Some(selection) = self.camera.clone() {self.camera_epoch += 1;+ #[cfg(target_os = "linux")]+ self.camera_processing_epoch+ .store(self.camera_epoch, Ordering::Release);self.start_camera_preview(selection, cx);tracing::info!("camera preview resumed");}@@ -363,7 +911,7 @@ impl Feeds {let pump = {let (frame_tx, frame_rx) = flume::bounded::<cap_recording::FFmpegVideoFrame>(4);let (preview_tx, preview_rx) = flume::bounded(2);- let (reset_tx, reset_rx) = flume::bounded(1);+ let (reset_tx, reset_rx) = flume::bounded(4);self.camera_preview_reset = Some(reset_tx);let mirrored = self.camera_preview_mirrored.clone();let active = self.camera_preview_active.clone();@@ -371,88 +919,14 @@ impl Feeds {if let Err(error) = std::thread::Builder::new().name("camera-preview".into()).spawn(move || {- let mut scaler = None;- let mut processor = None;- let mut previous_blur = 0;- let mut blur_failed = false;- loop {- let received = flume::Selector::new()- .recv(&frame_rx, |result| result.map(Some))- .recv(&reset_rx, |result| result.map(|()| None))- .wait();- let mut frame = match received {- Ok(Some(frame)) => frame,- Ok(None) => {- scaler = None;- processor = None;- previous_blur = 0;- blur_failed = false;- continue;- }- Err(_) => break,- };- if !active.load(Ordering::Acquire) {- continue;- }- while let Ok(newer) = frame_rx.try_recv() {- frame = newer;- }- let requested_blur = blur.load(Ordering::Relaxed);- if requested_blur != previous_blur {- processor = None;- blur_failed = false;- previous_blur = requested_blur;- }- let blur_mode = match requested_blur {- 1 => Some(cap_camera_effects::BlurMode::Light),- 2 => Some(cap_camera_effects::BlurMode::Heavy),- _ => None,- }- .filter(|_| !blur_failed && crate::camera_blur_portable::blur_allowed());- let max_dims = blur_mode.map(|_| crate::camera_blur_portable::MAX_DIMS);- let Some((mut image, dims)) = camera_preview_image(- &frame.inner,- &mut scaler,- mirrored.load(Ordering::Relaxed),- max_dims,- ) else {- continue;- };- if let Some(mode) = blur_mode- && !blur_failed- {- if processor.is_none() {- match crate::camera_blur_portable::PortableCameraBlur::new() {- Ok(worker) => {- tracing::info!("camera blur preview initialized");- processor = Some(worker);- }- Err(error) => {- tracing::warn!(- "camera blur preview unavailable: {error:#}"- );- blur_failed = true;- }- }- }- if let Some(worker) = processor.as_mut() {- match worker.process(&image, dims, mode) {- Ok(blurred) => image = blurred,- Err(error) => {- tracing::warn!("camera blur preview stopped: {error:#}");- processor = None;- blur_failed = true;- }- }- }- }- match preview_tx- .try_send(crate::camera_window::CameraPreviewFrame { image, dims })- {- Ok(()) | Err(flume::TrySendError::Full(_)) => {}- Err(flume::TrySendError::Disconnected(_)) => break,- }- }+ run_camera_preview_worker(CameraPreviewWorkerConfig {+ frames: frame_rx,+ previews: preview_tx,+ commands: reset_rx,+ mirrored,+ active,+ blur,+ });}){tracing::error!("starting camera preview worker: {error}");@@ -685,6 +1159,142 @@ fn db_fs(samples: &MicrophoneSamples) -> f64 {mod tests {use super::*;+ #[cfg(target_os = "linux")]+ #[test]+ fn recording_blur_pending_failure_stale_and_wrong_effect_cannot_certify_pixels() {+ use cap_camera_effects::{+ BlurFailure, BlurMaskReceipt, BlurMaskStatus, BlurMode, BlurOutputStatus,+ };+ let now = Instant::now();+ let mut status = BlurOutputStatus {+ mode: BlurMode::Light,+ output_sequence: 1,+ output_dimensions: (4, 2),+ mask: BlurMaskStatus::Pending,+ };+ assert!(+ checked_recording_blur(&status, BlurMode::Light, (4, 2), now)+ .unwrap()+ .is_none()+ );+ for failure in [+ BlurFailure::Inference("failed".into()),+ BlurFailure::Readback("failed".into()),+ ] {+ status.mask = BlurMaskStatus::Failed(failure);+ assert!(checked_recording_blur(&status, BlurMode::Light, (4, 2), now).is_err());+ }+ status.mask = BlurMaskStatus::Ready(BlurMaskReceipt {+ generation: 7,+ input_submitted_at: now,+ inference_completed_at: now,+ input_dimensions: (4, 2),+ });+ let applied = checked_recording_blur(&status, BlurMode::Light, (4, 2), now)+ .unwrap()+ .unwrap();+ assert_eq!(applied.generation, 7);+ assert_eq!(applied.submitted_at, now);+ assert!(checked_recording_blur(&status, BlurMode::Heavy, (4, 2), now).is_err());+ assert!(checked_recording_blur(&status, BlurMode::Light, (2, 4), now).is_err());+ assert!(+ checked_recording_blur(+ &status,+ BlurMode::Light,+ (4, 2),+ now + cap_recording::instant_recording::LINUX_CAMERA_MAX_MASK_AGE+ + Duration::from_millis(1)+ )+ .is_err()+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn recording_camera_reservation_releases_only_its_owned_attempt() {+ let active = Arc::new(AtomicBool::new(false));+ let first = CameraRecordingReservation::try_acquire(&active).unwrap();+ assert!(active.load(Ordering::Acquire));+ assert!(CameraRecordingReservation::try_acquire(&active).is_none());+ assert!(active.load(Ordering::Acquire));+ drop(first);+ assert!(!active.load(Ordering::Acquire));+ let restarted = CameraRecordingReservation::try_acquire(&active).unwrap();+ assert!(CameraRecordingReservation::try_acquire(&active).is_none());+ drop(restarted);+ assert!(!active.load(Ordering::Acquire));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn recording_camera_rejects_queued_frames_and_changed_selection() {+ let old = Instant::now();+ let subscribed = old + Duration::from_millis(1);+ assert_eq!(+ validate_recording_camera_frame(+ cap_timestamp::Timestamp::Instant(old),+ subscribed,+ 7,+ 7+ ),+ Ok(false)+ );+ assert_eq!(+ validate_recording_camera_frame(+ cap_timestamp::Timestamp::Instant(subscribed),+ subscribed,+ 7,+ 7+ ),+ Ok(true)+ );+ assert!(+ validate_recording_camera_frame(+ cap_timestamp::Timestamp::Instant(subscribed),+ subscribed,+ 7,+ 8+ )+ .is_err()+ );+ assert!(+ validate_recording_camera_frame(+ cap_timestamp::Timestamp::Instant(old),+ subscribed,+ 7,+ 8+ )+ .is_err()+ );+ assert!(+ validate_recording_camera_frame(+ cap_timestamp::Timestamp::SystemTime(std::time::SystemTime::now()),+ subscribed,+ 7,+ 7,+ )+ .is_err()+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn recording_processing_keeps_exact_mirror_and_light_heavy_identity() {+ use cap_recording::instant_recording::{LinuxCameraBlur, LinuxCameraProcessing};+ for (blur, encoded) in [+ (LinuxCameraBlur::Off, 0),+ (LinuxCameraBlur::Light, 1),+ (LinuxCameraBlur::Heavy, 2),+ ] {+ for mirrored in [false, true] {+ assert_eq!(+ frozen_processing_state(LinuxCameraProcessing { mirrored, blur }),+ (encoded, mirrored)+ );+ }+ }+ }+/// Both level mappings keep the web app's orientation: `picker_level` is 1/// at silence (it is the overlay's *right* offset), `bar_level` is 0 at/// silence (it is the track's fill fraction).diff --git a/apps/desktop-gpui/src/hotkeys.rs b/apps/desktop-gpui/src/hotkeys.rsindex f335069f0..cee359243 100644--- a/apps/desktop-gpui/src/hotkeys.rs+++ b/apps/desktop-gpui/src/hotkeys.rs@@ -77,6 +77,8 @@ impl HotkeyAction {struct Hotkeys {manager: GlobalHotKeyManager,bindings: Vec<(HotKey, HotkeyAction)>,+ #[cfg(target_os = "linux")]+ capture_stop: Option<HotKey>,}impl Global for Hotkeys {}@@ -96,6 +98,8 @@ pub fn init(cx: &mut App) {cx.set_global(Hotkeys {manager,bindings: Vec::new(),+ #[cfg(target_os = "linux")]+ capture_stop: None,});register_from_store(cx);@@ -105,6 +109,21 @@ pub fn init(cx: &mut App) {}));cx.spawn(async move |cx| {while let Ok(event) = rx.recv_async().await {+ #[cfg(target_os = "linux")]+ if cx.update(|cx| {+ if cx+ .global::<Hotkeys>()+ .capture_stop+ .is_some_and(|key| key.id() == event.id())+ {+ app_windows::handle_clean_capture_shortcut(event.state, cx);+ true+ } else {+ false+ }+ }) {+ continue;+ }// Pressed only, like the Tauri handler (`hotkeys.rs:183-185`).if event.state == HotKeyState::Pressed {cx.update(|cx| dispatch_id(event.id(), cx));@@ -120,6 +139,10 @@ pub fn reload(cx: &mut App) {if !cx.has_global::<Hotkeys>() {return;}+ #[cfg(target_os = "linux")]+ if cx.global::<Hotkeys>().capture_stop.is_some() {+ return;+ }let hotkeys = cx.global_mut::<Hotkeys>();// Two actions on one combo share one OS registration, so unregister each// combo once.@@ -136,6 +159,369 @@ pub fn reload(cx: &mut App) {register_from_store(cx);}+#[cfg(target_os = "linux")]+fn clean_capture_shortcut_conflicts(actions: &[HotkeyAction]) -> bool {+ actions+ .iter()+ .any(|action| *action != HotkeyAction::StopRecording)+}++#[cfg(target_os = "linux")]+struct WaylandStop {+ generation: u64,+ label: String,+ ready: bool,+ cancel: flume::Sender<()>,+ worker: Option<tokio::task::JoinHandle<Result<(), String>>>,+ cleanup: Option<futures_util::future::Shared<gpui::Task<Result<(), String>>>>,+}++#[cfg(target_os = "linux")]+impl Global for WaylandStop {}++#[cfg(target_os = "linux")]+enum WaylandStopEvent {+ Ready(String),+ Key(HotKeyState),+ Activate,+ Unavailable(String),+}++#[cfg(target_os = "linux")]+pub fn clean_capture_stop_message(cx: &App) -> String {+ if let Some(stop) = cx.try_global::<WaylandStop>() {+ return stop.label.clone();+ }+ "Press and release Ctrl+Shift+F9 to start. Use the same shortcut to stop. This temporary shortcut does not change your settings.".into()+}++#[cfg(target_os = "linux")]+fn reserve_wayland_stop(generation: u64, cx: &mut App) -> anyhow::Result<()> {+ anyhow::ensure!(+ !cx.has_global::<WaylandStop>(),+ "A recording Stop control is already reserved"+ );+ let (cancel, cancelled) = flume::bounded(1);+ let (events, received) = flume::unbounded();+ let worker =+ gpui_tokio::Tokio::handle(cx).spawn(run_wayland_stop(generation, cancelled, events));+ cx.set_global(WaylandStop {+ generation,+ label: "Approve a recording shortcut, or activate the Cap Stop tray icon when it appears. Recording has not started.".into(),+ ready: false,+ cancel,+ worker: Some(worker),+ cleanup: None,+ });+ cx.spawn(async move |cx| {+ while let Ok(event) = received.recv_async().await {+ cx.update(|cx| {+ if !cx.has_global::<WaylandStop>() {+ return;+ }+ let stop = cx.global_mut::<WaylandStop>();+ if stop.generation != generation {+ return;+ }+ match event {+ WaylandStopEvent::Ready(label) => {+ stop.ready = true;+ stop.label = label;+ app_windows::notify_clean_capture_preflight(cx);+ }+ WaylandStopEvent::Key(state) if stop.ready => {+ app_windows::handle_owned_clean_capture_shortcut(generation, state, cx);+ }+ WaylandStopEvent::Activate if stop.ready => {+ app_windows::handle_owned_clean_capture_shortcut(+ generation,+ HotKeyState::Pressed,+ cx,+ );+ app_windows::handle_owned_clean_capture_shortcut(+ generation,+ HotKeyState::Released,+ cx,+ );+ }+ WaylandStopEvent::Unavailable(error) => {+ stop.ready = false;+ app_windows::clean_capture_stop_unavailable(generation, error, cx);+ }+ _ => {}+ }+ });+ }+ cx.update(|cx| {+ if cx+ .try_global::<WaylandStop>()+ .is_some_and(|stop| stop.generation == generation && stop.cleanup.is_none())+ {+ app_windows::clean_capture_stop_unavailable(+ generation,+ "The recording Stop worker ended".into(),+ cx,+ );+ }+ });+ })+ .detach();+ Ok(())+}++#[cfg(target_os = "linux")]+async fn run_wayland_stop(+ generation: u64,+ cancel: flume::Receiver<()>,+ events: flume::Sender<WaylandStopEvent>,+) -> Result<(), String> {+ let mut ready = false;+ let mut fallback_safe = true;+ let result =+ run_portal_stop(generation, &cancel, &events, &mut ready, &mut fallback_safe).await;+ if cancel.is_disconnected() || !cancel.is_empty() {+ return result.map_err(|error| error.to_string());+ }+ if result.is_ok() {+ return Ok(());+ }+ if !fallback_safe {+ let error = format!(+ "The recording shortcut registration could not be cleaned up safely: {}",+ result.unwrap_err()+ );+ let _ = events.send(WaylandStopEvent::Unavailable(error.clone()));+ return Err(error);+ }+ if ready {+ if let Err(error) = result {+ let _ = events.send(WaylandStopEvent::Unavailable(error.to_string()));+ }+ return Ok(());+ }+ if let Err(error) = result {+ tracing::info!(%error, "Using the recording Stop tray instead of GlobalShortcuts");+ }+ let result = run_tray_stop(generation, &cancel, &events)+ .await+ .map_err(|error| error.to_string());+ if let Err(error) = &result {+ let _ = events.send(WaylandStopEvent::Unavailable(error.clone()));+ }+ result+}++#[cfg(target_os = "linux")]+fn wayland_stop_icon() -> anyhow::Result<cap_utils::linux_recording_stop::StopTrayIcon> {+ let image = image::load_from_memory(include_bytes!("../assets/tray/tray-stop-icon.png"))?+ .resize_exact(32, 32, image::imageops::FilterType::Triangle)+ .into_rgba8();+ cap_utils::linux_recording_stop::StopTrayIcon::from_rgba(+ image.width(),+ image.height(),+ image.as_raw(),+ )+ .map_err(anyhow::Error::msg)+}++#[cfg(target_os = "linux")]+async fn join_wayland_stop_worker(+ worker: Option<tokio::task::JoinHandle<Result<(), String>>>,+) -> Result<(), String> {+ let worker = worker.ok_or_else(|| "Recording Stop worker ownership was lost".to_string())?;+ worker+ .await+ .map_err(|error| format!("Recording Stop worker failed: {error}"))?+}++#[cfg(target_os = "linux")]+async fn run_tray_stop(+ generation: u64,+ cancel: &flume::Receiver<()>,+ events: &flume::Sender<WaylandStopEvent>,+) -> anyhow::Result<()> {+ use cap_utils::linux_recording_stop::{StopTray, StopTrayEvent};+ let icon = wayland_stop_icon()?;+ let tray = StopTray::open(generation, icon).await.map_err(|error| {+ if error.can_fallback() {+ anyhow::Error::msg(error)+ } else {+ anyhow::anyhow!("Recording Stop tray registration cleanup is unconfirmed: {error}")+ }+ })?;+ let received = tray.events();+ let outcome = async {+ events.send(WaylandStopEvent::Ready("Activate the Cap Stop tray icon to start. Activate the same icon again to stop. Recording will not start until you use that control.".into()))?;+ loop {+ tokio::select! {+ biased;+ _ = cancel.recv_async() => return Ok(()),+ event = received.recv_async() => match event? {+ StopTrayEvent::Activated { generation: owner } if owner == generation => events.send(WaylandStopEvent::Activate)?,+ StopTrayEvent::Unavailable { generation: owner } if owner == generation => anyhow::bail!("The recording Stop tray is no longer available"),+ _ => {}+ }+ }+ }+ }.await;+ let closed = tray.close().await.map_err(anyhow::Error::msg);+ outcome.and(closed)+}++#[cfg(target_os = "linux")]+async fn run_portal_stop(+ generation: u64,+ cancel: &flume::Receiver<()>,+ events: &flume::Sender<WaylandStopEvent>,+ ready: &mut bool,+ fallback_safe: &mut bool,+) -> anyhow::Result<()> {+ use ashpd::desktop::global_shortcuts::{GlobalShortcuts, NewShortcut};+ use futures_util::StreamExt;+ use std::time::Duration;+ let portal = tokio::time::timeout(Duration::from_secs(5), GlobalShortcuts::new()).await??;+ tokio::time::timeout(+ Duration::from_secs(5),+ portal.get_property::<u32>("version"),+ )+ .await??;+ *fallback_safe = false;+ let session = tokio::time::timeout(Duration::from_secs(5), portal.create_session()).await??;+ let outcome = async {+ let session_path = serde_json::to_value(&session)?.as_str().ok_or_else(|| anyhow::anyhow!("Invalid shortcut session identity"))?.to_owned();+ let shortcut_id = format!("cap-recording-stop-{generation}");+ let activated = portal.receive_activated().await?;+ let deactivated = portal.receive_deactivated().await?;+ let changed = portal.receive_shortcuts_changed().await?;+ let closed = session.receive_closed().await?;+ futures_util::pin_mut!(activated, deactivated, changed, closed);+ let shortcuts = [NewShortcut::new(&shortcut_id, "Start or stop this Cap recording").preferred_trigger("CTRL+SHIFT+F9")];+ let bind = portal.bind_shortcuts(&session, &shortcuts, None);+ let response = tokio::select! {+ _ = cancel.recv_async() => return Ok(()),+ response = tokio::time::timeout(Duration::from_secs(60), bind) => response??.response()?,+ };+ let shortcut = response.shortcuts().iter().find(|shortcut| shortcut.id() == shortcut_id).ok_or_else(|| anyhow::anyhow!("The portal did not grant the recording Stop shortcut"))?;+ let label = shortcut.trigger_description();+ anyhow::ensure!(!label.trim().is_empty(), "The portal did not describe the granted Stop shortcut");+ events.send(WaylandStopEvent::Ready(format!("Press and release {label} to start. Use the same shortcut to stop. This temporary shortcut does not change your settings.")))?;+ *ready = true;+ loop {+ tokio::select! {+ biased;+ _ = cancel.recv_async() => return Ok(()),+ event = activated.next() => {+ let event = event.ok_or_else(|| anyhow::anyhow!("Recording shortcut activation stream closed"))?;+ if event.session_handle().as_str() == session_path && event.shortcut_id() == shortcut_id { events.send(WaylandStopEvent::Key(HotKeyState::Pressed))?; }+ }+ event = deactivated.next() => {+ let event = event.ok_or_else(|| anyhow::anyhow!("Recording shortcut release stream closed"))?;+ if event.session_handle().as_str() == session_path && event.shortcut_id() == shortcut_id { events.send(WaylandStopEvent::Key(HotKeyState::Released))?; }+ }+ event = changed.next() => {+ let event = event.ok_or_else(|| anyhow::anyhow!("Recording shortcut change stream closed"))?;+ if event.session_handle().as_str() == session_path { anyhow::bail!("The recording shortcut changed; recording must stop before proving the new shortcut"); }+ }+ _ = closed.next() => anyhow::bail!("The recording shortcut session closed"),+ }+ }+ }.await;+ let closed = tokio::time::timeout(Duration::from_secs(3), session.close()).await;+ match closed {+ Ok(Ok(())) => {+ *fallback_safe = true;+ outcome+ }+ Ok(Err(error)) => Err(error.into()),+ Err(error) => Err(error.into()),+ }+}++#[cfg(target_os = "linux")]+pub fn reserve_clean_capture_stop(+ generation: u64,+ wayland: bool,+ cx: &mut App,+) -> anyhow::Result<()> {+ if wayland {+ return reserve_wayland_stop(generation, cx);+ }+ if !cx.has_global::<Hotkeys>() {+ anyhow::bail!("Global shortcuts are unavailable. Recording has not started.");+ }+ let hotkeys = cx.global_mut::<Hotkeys>();+ if hotkeys.capture_stop.is_some() {+ anyhow::bail!("A recording shortcut is already reserved.");+ }+ let key = HotKey::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::F9);+ let actions = actions_for(&hotkeys.bindings, key.id());+ if clean_capture_shortcut_conflicts(&actions) {+ anyhow::bail!(+ "Ctrl+Shift+F9 is assigned to another Cap action. Change that shortcut before recording."+ );+ }+ if actions.is_empty() {+ hotkeys.manager.register(key).map_err(|error| {+ anyhow::anyhow!("Ctrl+Shift+F9 is unavailable: {error}. Recording has not started.")+ })?;+ }+ hotkeys.capture_stop = Some(key);+ Ok(())+}++#[cfg(target_os = "linux")]+pub type CleanStopCleanup = futures_util::future::BoxFuture<'static, Result<(), String>>;++#[cfg(target_os = "linux")]+pub fn begin_wayland_stop_cleanup(cx: &mut App) -> CleanStopCleanup {+ if cx.has_global::<WaylandStop>() {+ use futures_util::FutureExt;+ let executor = cx.background_executor().clone();+ let stop = cx.global_mut::<WaylandStop>();+ if stop.cleanup.is_none() {+ let worker = stop.worker.take();+ let _ = stop.cancel.send(());+ stop.cleanup = Some(executor.spawn(join_wayland_stop_worker(worker)).shared());+ }+ let cleanup = stop.cleanup.as_ref().unwrap().clone();+ return Box::pin(async move {+ tokio::time::timeout(std::time::Duration::from_secs(3), cleanup)+ .await+ .map_err(|_| {+ "Recording Stop cleanup has not joined; its worker remains owned".to_string()+ })?+ });+ }+ Box::pin(async { Ok(()) })+}++#[cfg(target_os = "linux")]+pub fn release_clean_capture_stop(cx: &mut App) {+ if !cx.has_global::<Hotkeys>() {+ return;+ }+ let hotkeys = cx.global_mut::<Hotkeys>();+ let Some(key) = hotkeys.capture_stop.take() else {+ return;+ };+ if actions_for(&hotkeys.bindings, key.id()).is_empty()+ && let Err(error) = hotkeys.manager.unregister(key)+ {+ tracing::warn!(%error, "Could not release the temporary recording shortcut");+ }+ reload(cx);+}++#[cfg(target_os = "linux")]+pub fn complete_clean_capture_stop(generation: u64, cx: &mut App) {+ if cx+ .try_global::<WaylandStop>()+ .is_some_and(|stop| stop.generation == generation && stop.cleanup.is_some())+ {+ let _closed = cx.remove_global::<WaylandStop>();+ }+}+fn register_from_store(cx: &mut App) {let stored = store::hotkeys_raw();let hotkeys = cx.global_mut::<Hotkeys>();@@ -396,8 +782,57 @@ fn stored_target() -> Option<ScreenCaptureTarget> {#[cfg(test)]mod tests {+ #[cfg(target_os = "linux")]+ #[test]+ fn actual_stop_asset_is_resized_for_shared_tray_contract() {+ assert!(super::wayland_stop_icon().is_ok());+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn wayland_stop_join_preserves_close_failure() {+ let worker = tokio::spawn(async { Err("native close failed".to_string()) });+ assert_eq!(+ super::join_wayland_stop_worker(Some(worker)).await,+ Err("native close failed".to_string())+ );+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn wayland_stop_join_waits_for_the_owned_worker() {+ let (send, receive) = flume::bounded::<()>(1);+ let worker = tokio::spawn(async move {+ receive+ .recv_async()+ .await+ .map_err(|error| error.to_string())?;+ Ok(())+ });+ let mut joined = Box::pin(super::join_wayland_stop_worker(Some(worker)));+ assert!(futures_util::poll!(&mut joined).is_pending());+ send.send(()).unwrap();+ joined.await.unwrap();+ }+use super::*;+ #[cfg(target_os = "linux")]+ #[test]+ fn temporary_stop_reuses_only_an_existing_stop_binding() {+ assert!(!clean_capture_shortcut_conflicts(&[]));+ assert!(!clean_capture_shortcut_conflicts(&[+ HotkeyAction::StopRecording+ ]));+ assert!(clean_capture_shortcut_conflicts(&[+ HotkeyAction::StartStudioRecording+ ]));+ assert!(clean_capture_shortcut_conflicts(&[+ HotkeyAction::StopRecording,+ HotkeyAction::StartStudioRecording+ ]));+ }+/// Every store key the Tauri `HotkeyAction`'s camelCase serde produces/// maps to a variant here, and an unknown key registers nothing.#[test]diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rsindex b0b10d00b..4f6edbabb 100644--- a/apps/desktop-gpui/src/main.rs+++ b/apps/desktop-gpui/src/main.rs@@ -176,6 +176,14 @@ fn init_logging() -> Option<tracing_appender::non_blocking::WorkerGuard> {}fn main() {+ #[cfg(target_os = "linux")]+ if let Some(threads) = cap_utils::linux_runtime::llvmpipe_thread_count() {+ // Mesa counts host CPUs inside containers; apply the process limit before logging starts threads.+ unsafe {+ std::env::set_var("LP_NUM_THREADS", threads.to_string());+ }+ }+#[cfg(target_os = "linux")]if let Some(config) = cap_utils::linux_package::appimage_alsa_config_path() {// Logging starts a worker thread, so configure the process environment first.@@ -295,6 +303,8 @@ fn main() {.detach();app_windows::init(window_handle, session, cx);+ #[cfg(target_os = "linux")]+ single_instance::init_linux_reopen(cx);updates::schedule_startup_check(cx);// The app menu (and with it ⌘W/⌘M/⌘Q) and the status-bar item. Bothdiff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rsindex e033b5acf..fae8f11b9 100644--- a/apps/desktop-gpui/src/main_window.rs+++ b/apps/desktop-gpui/src/main_window.rs@@ -300,6 +300,40 @@ struct LibraryRow<T> {thumbnail: Option<std::sync::Arc<gpui::RenderImage>>,}+#[derive(Clone)]+pub(crate) struct RecordingStartPermit(std::rc::Rc<std::cell::Cell<bool>>);++impl RecordingStartPermit {+ fn prepare(phase: Phase, clean_capture_owned: bool, preparing: bool) -> Result<Self, String> {+ if phase != Phase::Idle || clean_capture_owned || preparing {+ return Err("Another recording or recording preparation owns the inputs".into());+ }+ Ok(Self(std::rc::Rc::new(std::cell::Cell::new(true))))+ }++ fn allows(&self, phase: Phase, clean_capture_owned: bool) -> bool {+ if phase != Phase::Idle || clean_capture_owned {+ self.cancel();+ }+ self.0.get()+ }++ pub(crate) fn is_current(&self, cx: &gpui::App) -> bool {+ self.allows(+ RecordingSession::global(cx).read(cx).phase,+ app_windows::clean_capture_owned(cx),+ )+ }++ pub(crate) fn cancel(&self) {+ self.0.set(false);+ }++ fn same(&self, other: &Self) -> bool {+ std::rc::Rc::ptr_eq(&self.0, &other.0)+ }+}+pub struct MainWindow {theme: Theme,expanded: bool,@@ -331,6 +365,7 @@ pub struct MainWindow {/// controls bar window can drive the same recording.session: Entity<RecordingSession>,checking_storage: bool,+ deep_link_start: Option<RecordingStartPermit>,/// The Recents scan, or `None` while the first one is in flight -- which/// is the query's `isLoading`, and draws the same three skeleton cards.recents: Option<Vec<RecentEntry>>,@@ -412,6 +447,9 @@ impl MainWindow {let mut previous_phase = Phase::Idle;cx.observe_in(&session, window, move |this, session, window, cx| {let phase = session.read(cx).phase;+ if phase != Phase::Idle {+ this.cancel_deep_link_start();+ }if phase == Phase::Idle && previous_phase != Phase::Idle {this.scan_incomplete_recordings(window, cx, std::time::Duration::ZERO);if let Some(notice) = session.read(cx).storage_notice.clone() {@@ -493,6 +531,7 @@ impl MainWindow {enumerating: true,session,checking_storage: false,+ deep_link_start: None,recents: None,recents_task: None,library: None,@@ -1735,6 +1774,8 @@ impl MainWindow {excluded_windows,camera_feed,mic_feed,+ #[cfg(target_os = "linux")]+ linux_instant_camera: None,};self.start_recording_config(config, cx);@@ -1745,16 +1786,84 @@ impl MainWindow {config: recording::StartConfig,cx: &mut Context<Self>,) {- self.check_storage_before_start(config, false, cx);+ self.check_storage_before_start(config, false, None, cx);+ }++ pub(crate) fn prepare_deep_link_start(+ &mut self,+ cx: &mut Context<Self>,+ ) -> Result<RecordingStartPermit, String> {+ let permit = RecordingStartPermit::prepare(+ self.session.read(cx).phase,+ app_windows::clean_capture_owned(cx),+ self.checking_storage,+ )?;+ self.checking_storage = true;+ self.deep_link_start = Some(permit.clone());+ Ok(permit)+ }++ pub(crate) fn cancel_deep_link_start(&mut self) {+ if let Some(permit) = self.deep_link_start.take() {+ permit.cancel();+ self.checking_storage = false;+ }+ }++ pub(crate) fn finish_deep_link_start(&mut self, permit: &RecordingStartPermit) {+ if self+ .deep_link_start+ .as_ref()+ .is_some_and(|current| current.same(permit))+ {+ self.cancel_deep_link_start();+ }+ }++ pub(crate) fn start_recording_config_with_permit(+ &mut self,+ config: recording::StartConfig,+ permit: RecordingStartPermit,+ cx: &mut Context<Self>,+ ) {+ self.check_storage_before_start(config, false, Some(permit), cx);+ }++ fn recording_start_is_current(+ &self,+ permit: Option<&RecordingStartPermit>,+ cx: &gpui::App,+ ) -> bool {+ self.session.read(cx).phase == Phase::Idle+ && permit.is_none_or(|permit| {+ self.deep_link_start+ .as_ref()+ .is_some_and(|current| current.same(permit))+ && permit.is_current(cx)+ })+ }++ fn finish_recording_start(&mut self, permit: Option<&RecordingStartPermit>) {+ if let Some(permit) = permit {+ self.finish_deep_link_start(permit);+ } else {+ self.checking_storage = false;+ }}fn check_storage_before_start(&mut self,config: recording::StartConfig,acknowledged: bool,+ permit: Option<RecordingStartPermit>,cx: &mut Context<Self>,) {- if self.checking_storage || self.session.read(cx).phase != Phase::Idle {+ if (permit.is_none() && self.checking_storage)+ || !self.recording_start_is_current(permit.as_ref(), cx)+ {+ if permit.is_some() {+ self.finish_recording_start(permit.as_ref());+ }return;}self.checking_storage = true;@@ -1764,8 +1873,8 @@ impl MainWindow {recording::available_recording_storage()}).await;if !this.update(cx, |this, cx| {- if this.session.read(cx).phase != Phase::Idle {- this.checking_storage = false;+ if !this.recording_start_is_current(permit.as_ref(), cx) {+ this.finish_recording_start(permit.as_ref());return false;}true@@ -1776,7 +1885,11 @@ impl MainWindow {Ok(storage) => storage,Err(error) => {this.update(cx, |this, cx| {- this.checking_storage = false;+ if !this.recording_start_is_current(permit.as_ref(), cx) {+ this.finish_recording_start(permit.as_ref());+ return;+ }+ this.finish_recording_start(permit.as_ref());this.session.update(cx, |session, cx| {session.error = Some(format!("Could not check recording storage: {error}"));cx.notify();@@ -1792,8 +1905,26 @@ impl MainWindow {let can_start = storage.status() != cap_utils::disk_space::DiskSpaceStatus::Exhausted;if storage.status() == cap_utils::disk_space::DiskSpaceStatus::Ok || acknowledged && can_start {this.update(cx, |this, cx| {- this.checking_storage = false;- cx.defer(move |cx| app_windows::begin_recording(config, cx));+ if !this.recording_start_is_current(permit.as_ref(), cx) {+ this.finish_recording_start(permit.as_ref());+ return;+ }+ if permit.is_none() {+ this.checking_storage = false;+ }+ cx.defer(move |cx| {+ if let Some(permit) = permit {+ let allowed = main.update(cx, |this, _, cx| {+ let allowed = this.recording_start_is_current(Some(&permit), cx);+ this.finish_deep_link_start(&permit);+ allowed+ }).unwrap_or(false);+ if !allowed {+ return;+ }+ }+ app_windows::begin_recording(config, cx);+ });}).ok();return;}@@ -1809,8 +1940,10 @@ impl MainWindow {vec![gpui::PromptButton::cancel("OK")]};let receiver = cx.update(|cx| {- if RecordingSession::global(cx).read(cx).phase != Phase::Idle {- return Err(anyhow::anyhow!("A recording has already started."));+ if RecordingSession::global(cx).read(cx).phase != Phase::Idle+ || permit.as_ref().is_some_and(|permit| !permit.is_current(cx))+ {+ return Err(anyhow::anyhow!("Recording preparation is no longer current."));}app_windows::show_main_window(cx);cx.activate(true);@@ -1823,14 +1956,20 @@ impl MainWindow {Err(_) => false,};this.update(cx, |this, cx| {- this.checking_storage = false;- if this.session.read(cx).phase != Phase::Idle {+ if !this.recording_start_is_current(permit.as_ref(), cx) {+ this.finish_recording_start(permit.as_ref());return;}+ if permit.is_none() {+ this.checking_storage = false;+ }if confirmed {- this.check_storage_before_start(config, true, cx);- } else if this.session.read(cx).editor_recording_target().is_some() {- cx.defer(app_windows::abort_editor_recording_flow);+ this.check_storage_before_start(config, true, permit, cx);+ } else {+ this.finish_recording_start(permit.as_ref());+ if this.session.read(cx).editor_recording_target().is_some() {+ cx.defer(app_windows::abort_editor_recording_flow);+ }}cx.notify();}).ok();@@ -1973,10 +2112,49 @@ impl Render for MainWindow {.filter(|_| self.session.read(cx).phase == Phase::Idle),|this, recording| this.child(self.render_recovery_toast(recording, cx)),)+ .when(app_windows::clean_capture_pending(cx), |this| {+ this.child(self.render_clean_capture_preflight(cx))+ })}}impl MainWindow {+ fn render_clean_capture_preflight(&self, cx: &mut Context<Self>) -> impl IntoElement {+ let theme = self.theme;+ div()+ .absolute()+ .inset_0()+ .bg(theme.gray_1)+ .flex()+ .flex_col()+ .justify_center()+ .gap(px(16.))+ .p(px(24.))+ .child(div().text_size(px(18.)).child("Keep your capture clean"))+ .child(+ div()+ .text_size(px(14.))+ .child(app_windows::clean_capture_camera_message(cx)),+ )+ .child(+ div()+ .text_size(px(14.))+ .child(app_windows::clean_capture_shortcut_message(cx)),+ )+ .child(+ div()+ .id("cancel-clean-capture")+ .rounded(px(8.))+ .p(px(12.))+ .bg(theme.gray_3)+ .cursor_pointer()+ .child("Cancel")+ .on_click(+ cx.listener(|_, _, _, cx| cx.defer(app_windows::cancel_clean_capture)),+ ),+ )+ }+fn render_recovery_toast(&self,recording: library::IncompleteRecordingItem,@@ -2419,6 +2597,63 @@ impl MainWindow {actions}+ fn render_idle_error(&self, error: String, cx: &mut Context<Self>) -> impl IntoElement {+ let copy_error = error.clone();+ let shown_error = error.clone();++ div()+ .id("recording-error-panel")+ .flex()+ .flex_col()+ .flex_shrink_0()+ .min_w_0()+ .max_h(px(72.))+ .gap(px(4.))+ .overflow_hidden()+ .child(recording_error_text(error).text_color(self.theme.red_9))+ .child(+ div()+ .flex()+ .flex_shrink_0()+ .justify_end()+ .gap(px(6.))+ .child(+ ui::Button::body(+ &self.theme,+ "copy-recording-error",+ ui::ButtonVariant::Gray,+ ui::ButtonSize::Xs,+ )+ .label("Copy error")+ .on_click(cx.listener(move |_, _, _, cx| {+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(+ copy_error.clone(),+ ));+ })),+ )+ .child(+ ui::Button::body(+ &self.theme,+ "dismiss-recording-error",+ ui::ButtonVariant::Gray,+ ui::ButtonSize::Xs,+ )+ .label("Dismiss")+ .on_click(cx.listener(move |this, _, _, cx| {+ this.session.update(cx, |session, cx| {+ if clear_shown_idle_error(+ session.phase,+ &mut session.error,+ &shown_error,+ ) {+ cx.notify();+ }+ });+ })),+ ),+ )+ }+/// Page root: `px-[13px] gap-2 pb-[8px]`.fn render_body(&self, cx: &mut Context<Self>) -> impl IntoElement {let root = div()@@ -2465,16 +2700,7 @@ impl MainWindow {.error.clone().filter(|_| self.session.read(cx).phase == Phase::Idle),- |this, error| {- this.child(- div()- .flex_shrink_0()- .text_size(px(11.))- .text_color(self.theme.red_9)- .text_center()- .child(error),- )- },+ |this, error| this.child(self.render_idle_error(error, cx)),),}}@@ -2488,6 +2714,14 @@ impl MainWindow {let phase = self.session.read(cx).phase;let stopping = phase == Phase::Stopping;let starting = phase == Phase::Starting;+ #[cfg(target_os = "linux")]+ let can_resume = clean_capture_resume_available(+ phase,+ app_windows::clean_capture_active(cx),+ self.session.read(cx).clean_capture_controls_safe(),+ );+ #[cfg(not(target_os = "linux"))]+ let can_resume = false;let mut wash: Hsla = theme.gray_1.into();wash.a = 0.8;@@ -2502,6 +2736,61 @@ impl MainWindow {.px(px(24.)).pb(px(32.)).bg(wash)+ .when_some(self.session.read(cx).error.clone(), |this, error| {+ this.child(+ div()+ .flex_shrink_0()+ .mb(px(8.))+ .text_size(px(11.))+ .text_color(theme.red_9)+ .text_center()+ .child(error),+ )+ })+ .when(can_resume, |this| {+ this.child(+ div()+ .mb(px(12.))+ .flex()+ .flex_col()+ .gap(px(8.))+ .text_size(px(12.))+ .child("Recording paused. Cap will hide before resuming.")+ .child(+ div()+ .id("resume-clean-recording")+ .h(px(36.))+ .w_full()+ .flex()+ .items_center()+ .justify_center()+ .rounded(px(8.))+ .border_1()+ .border_color(theme.gray_5)+ .bg(theme.gray_3)+ .child("Resume")+ .on_click(cx.listener(|this, _, _, cx| {+ #[cfg(target_os = "linux")]+ {+ let session = this.session.clone();+ cx.defer(move |cx| {+ if clean_capture_resume_available(+ session.read(cx).phase,+ app_windows::clean_capture_active(cx),+ session.read(cx).clean_capture_controls_safe(),+ ) {+ session.update(cx, |session, cx| {+ session.toggle_pause(cx)+ });+ }+ });+ }+ #[cfg(not(target_os = "linux"))]+ let _ = (this, cx);+ })),+ ),+ )+ }).child(div().id("stop-recording")@@ -5038,3 +5327,201 @@ impl PillState {.child(text)}}++fn recording_error_text(error: String) -> impl IntoElement + Styled {+ div()+ .id("recording-error-text")+ .w_full()+ .min_w_0()+ .min_h_0()+ .max_h(px(48.))+ .text_size(px(12.))+ .line_height(px(16.))+ .whitespace_normal()+ .overflow_scroll()+ .child(error)+}++#[cfg(any(target_os = "linux", test))]+fn clean_capture_resume_available(phase: Phase, active: bool, paused_acknowledged: bool) -> bool {+ active && phase == (Phase::Recording { paused: true }) && paused_acknowledged+}++fn clear_shown_idle_error(phase: Phase, current: &mut Option<String>, shown: &str) -> bool {+ if phase != Phase::Idle || current.as_deref() != Some(shown) {+ return false;+ }+ *current = None;+ true+}++#[cfg(test)]+mod recording_start_permit_tests {+ use super::*;++ #[test]+ fn start_dispatch_rejects_owned_inputs_before_any_side_effect() {+ for phase in [+ Phase::Idle,+ Phase::Starting,+ Phase::Recording { paused: false },+ Phase::Recording { paused: true },+ Phase::Stopping,+ ] {+ for owned in [false, true] {+ for preparing in [false, true] {+ let mut inputs = ("original camera", "original microphone");+ let result = RecordingStartPermit::prepare(phase, owned, preparing).map(|_| {+ inputs = ("requested camera", "requested microphone");+ });+ let allowed = phase == Phase::Idle && !owned && !preparing;+ assert_eq!(result.is_ok(), allowed);+ assert_eq!(+ inputs,+ if allowed {+ ("requested camera", "requested microphone")+ } else {+ ("original camera", "original microphone")+ }+ );+ }+ }+ }+ }++ #[test]+ fn rejected_start_does_not_revoke_the_request_that_owns_preparation() {+ let current = RecordingStartPermit::prepare(Phase::Idle, false, false).unwrap();+ assert!(RecordingStartPermit::prepare(Phase::Idle, false, true).is_err());+ assert!(current.allows(Phase::Idle, false));+ }++ #[test]+ fn cancelled_permit_blocks_preview_storage_prompt_and_final_handoff_callbacks() {+ for stop_before in 0..5 {+ let permit = RecordingStartPermit::prepare(Phase::Idle, false, false).unwrap();+ let callbacks: [_; 5] = std::array::from_fn(|_| permit.clone());+ let mut started = false;+ for (step, callback) in callbacks.iter().enumerate() {+ if step == stop_before {+ permit.cancel();+ }+ if !callback.allows(Phase::Idle, false) {+ continue;+ }+ if step == callbacks.len() - 1 {+ started = true;+ }+ }+ assert!(!started);+ }+ }++ #[test]+ fn observing_transition_or_clean_ownership_permanently_revokes_a_request() {+ for (phase, owned) in [+ (Phase::Starting, false),+ (Phase::Recording { paused: false }, false),+ (Phase::Stopping, false),+ (Phase::Idle, true),+ ] {+ let permit = RecordingStartPermit::prepare(Phase::Idle, false, false).unwrap();+ assert!(!permit.allows(phase, owned));+ assert!(!permit.allows(Phase::Idle, false));+ }+ }++ #[test]+ fn stale_completion_cannot_revoke_a_later_start_permit() {+ let previous = RecordingStartPermit::prepare(Phase::Idle, false, false).unwrap();+ let completion = previous.clone();+ assert!(completion.same(&previous));+ previous.cancel();+ let current = RecordingStartPermit::prepare(Phase::Idle, false, false).unwrap();+ assert!(!completion.same(¤t));+ completion.cancel();+ assert!(current.allows(Phase::Idle, false));+ }+}++#[cfg(test)]+mod recording_error_panel_tests {+ use super::*;++ #[test]+ fn clean_capture_resume_requires_the_acknowledged_active_paused_session() {+ for phase in [+ Phase::Idle,+ Phase::Starting,+ Phase::Recording { paused: false },+ Phase::Recording { paused: true },+ Phase::Stopping,+ ] {+ for active in [false, true] {+ for acknowledged in [false, true] {+ assert_eq!(+ clean_capture_resume_available(phase, active, acknowledged),+ active && acknowledged && phase == (Phase::Recording { paused: true }),+ );+ }+ }+ }+ }++ #[test]+ fn long_error_keeps_bounded_scrollable_text() {+ let mut element = recording_error_text("Requested microphone unavailable. ".repeat(200));+ let style = element.style();+ assert_eq!(style.max_size.height, Some(px(48.).into()));+ assert_eq!(style.min_size.height, Some(px(0.).into()));+ assert_eq!(style.overflow.x, Some(gpui::Overflow::Scroll));+ assert_eq!(style.overflow.y, Some(gpui::Overflow::Scroll));+ }++ #[test]+ fn unbroken_error_keeps_both_scroll_axes() {+ let mut element = recording_error_text("x".repeat(8192));+ let style = element.style();+ assert_eq!(style.max_size.height, Some(px(48.).into()));+ assert_eq!(style.overflow.x, Some(gpui::Overflow::Scroll));+ assert_eq!(style.overflow.y, Some(gpui::Overflow::Scroll));+ }++ #[test]+ fn dismiss_clears_only_matching_idle_error() {+ let shown = "Requested microphone unavailable. ".repeat(200);+ let mut current = Some(shown.clone());+ assert!(clear_shown_idle_error(Phase::Idle, &mut current, &shown));+ assert!(current.is_none());+ assert!(!clear_shown_idle_error(Phase::Idle, &mut current, &shown));+ }++ #[test]+ fn stale_dismiss_retains_new_error() {+ let mut current = Some("A different failure".to_owned());+ assert!(!clear_shown_idle_error(+ Phase::Idle,+ &mut current,+ "Old failure"+ ));+ assert_eq!(current.as_deref(), Some("A different failure"));+ }++ #[test]+ fn dismiss_never_clears_active_or_unconfirmed_cleanup_error() {+ for phase in [+ Phase::Starting,+ Phase::Recording { paused: false },+ Phase::Recording { paused: true },+ Phase::Stopping,+ ] {+ let mut current = Some("Capture cleanup is unconfirmed".to_owned());+ assert!(!clear_shown_idle_error(+ phase,+ &mut current,+ "Capture cleanup is unconfirmed",+ ));+ assert_eq!(current.as_deref(), Some("Capture cleanup is unconfirmed"));+ }+ }+}diff --git a/apps/desktop-gpui/src/recording.rs b/apps/desktop-gpui/src/recording.rsindex 48ab9c63a..baaf4231d 100644--- a/apps/desktop-gpui/src/recording.rs+++ b/apps/desktop-gpui/src/recording.rs@@ -18,6 +18,8 @@ use cap_recording::{sources::screen_capture::ScreenCaptureTarget,studio_recording,};+#[cfg(target_os = "linux")]+use futures_util::FutureExt as _;use kameo::{Actor, actor::ActorRef};pub use cap_recording::feeds::camera::DeviceOrModelID;@@ -46,8 +48,20 @@ pub struct StartConfig {/// recording locks these instead of spawning its own -- the Tauri model.pub camera_feed: Option<ActorRef<CameraFeed>>,pub mic_feed: Option<ActorRef<MicrophoneFeed>>,+ #[cfg(target_os = "linux")]+ pub linux_instant_camera: Option<LinuxInstantCameraRequest>,}+#[cfg(target_os = "linux")]+#[derive(Clone)]+pub struct LinuxInstantCameraRequest {+ pub presentation: instant_recording::LinuxCameraPresentation,+ pub reference_size: (u32, u32),+ pub effects: instant_recording::LinuxCameraProcessing,+ pub processing: crate::feeds::CameraProcessingFactory,+}++#[cfg_attr(target_os = "linux", derive(Clone))]enum Handle {// Studio's handle is `Clone`; instant's is not, so it rides in an `Arc`.// Both give the owned handles pause/resume need for `'static` futures.@@ -55,12 +69,20 @@ enum Handle {Instant(Arc<instant_recording::ActorHandle>),}+type SharedInstantUpload = Arc<tokio::sync::Mutex<Option<crate::upload::InstantUpload>>>;+/// A live recording. Stopping consumes it; dropping it without stopping leaves/// the actors to wind down on their own when the refs go away.+#[cfg_attr(target_os = "linux", derive(Clone))]pub struct ActiveRecording {handle: Handle,pub project_dir: PathBuf,- instant_upload: Option<crate::upload::InstantUpload>,+ instant_upload: Option<SharedInstantUpload>,+ instant_share_link: Option<String>,+ #[cfg(target_os = "linux")]+ instant_completion: Option<crate::upload::CompletionControl>,+ #[cfg(target_os = "linux")]+ instant_operation: Arc<tokio::sync::Mutex<()>>,/// Recording-scoped mic mute (payload zeroing at the consumer seam; the/// stream cadence is unaffected). `None` when the recording has no mic.pub mic_mute: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,@@ -74,11 +96,464 @@ pub struct ActiveRecording {_mic_errors: Option<flume::Receiver<cpal::StreamError>>,}+#[cfg(target_os = "linux")]+#[derive(Clone)]+pub(crate) struct InstantAttempt(Arc<InstantAttemptInner>);++#[cfg(target_os = "linux")]+struct InstantAttemptInner {+ lifecycle: Mutex<Option<instant_recording::InstantLifecycle>>,+ cancelled: tokio::sync::watch::Sender<bool>,+ startup: tokio::sync::watch::Sender<StartupState>,+}++#[cfg(target_os = "linux")]+#[derive(Clone, Copy, PartialEq, Eq)]+enum StartupState {+ Unstarted,+ Running,+ Finished,+ Unconfirmed,+}++#[cfg(target_os = "linux")]+impl InstantAttempt {+ pub fn new() -> Self {+ Self(Arc::new(InstantAttemptInner {+ lifecycle: Mutex::new(None),+ cancelled: tokio::sync::watch::channel(false).0,+ startup: tokio::sync::watch::channel(StartupState::Unstarted).0,+ }))+ }++ pub fn cancel(&self) {+ self.0.cancelled.send_replace(true);+ self.0.startup.send_if_modified(|state| {+ if *state == StartupState::Unstarted {+ *state = StartupState::Finished;+ true+ } else {+ false+ }+ });+ if let Some(lifecycle) = self.0.lifecycle.lock().unwrap().as_ref() {+ lifecycle.cancel();+ }+ }++ fn attach(&self, lifecycle: instant_recording::InstantLifecycle) -> anyhow::Result<()> {+ let mut current = self.0.lifecycle.lock().unwrap();+ anyhow::ensure!(+ current.is_none(),+ "An Instant attempt cannot replace its capture lifecycle"+ );+ if *self.0.cancelled.borrow() {+ lifecycle.cancel();+ }+ *current = Some(lifecycle);+ Ok(())+ }++ pub fn quiescence(&self) -> instant_recording::InstantQuiescence {+ use instant_recording::InstantQuiescence;+ match *self.0.startup.borrow() {+ StartupState::Unconfirmed => InstantQuiescence::Unconfirmed,+ StartupState::Unstarted | StartupState::Running => InstantQuiescence::Pending,+ StartupState::Finished => self.0.lifecycle.lock().unwrap().as_ref().map_or(+ InstantQuiescence::Joined,+ instant_recording::InstantLifecycle::quiescence,+ ),+ }+ }++ pub async fn wait_for_quiescence(&self) -> instant_recording::InstantQuiescence {+ let mut startup = self.0.startup.subscribe();+ loop {+ let state = *startup.borrow_and_update();+ match state {+ StartupState::Unconfirmed => {+ return instant_recording::InstantQuiescence::Unconfirmed;+ }+ StartupState::Finished => break,+ _ => {}+ }+ if startup.changed().await.is_err() {+ return instant_recording::InstantQuiescence::Unconfirmed;+ }+ }+ let lifecycle = self.0.lifecycle.lock().unwrap().clone();+ match lifecycle {+ Some(lifecycle) => lifecycle.wait_for_quiescence().await,+ None => instant_recording::InstantQuiescence::Joined,+ }+ }++ async fn cancelled(&self) {+ let mut cancelled = self.0.cancelled.subscribe();+ loop {+ let requested = *cancelled.borrow_and_update();+ if requested || cancelled.changed().await.is_err() {+ break;+ }+ }+ }+}++#[cfg(target_os = "linux")]+struct StartupWaiter {+ attempt: InstantAttempt,+ armed: bool,+}+#[cfg(target_os = "linux")]+impl Drop for StartupWaiter {+ fn drop(&mut self) {+ if self.armed {+ self.attempt.cancel();+ }+ }+}++#[cfg(target_os = "linux")]+struct StartupCompletion {+ attempt: InstantAttempt,+ armed: bool,+}+#[cfg(target_os = "linux")]+impl Drop for StartupCompletion {+ fn drop(&mut self) {+ if self.armed {+ self.attempt.cancel();+ self.attempt+ .0+ .startup+ .send_replace(StartupState::Unconfirmed);+ }+ }+}++#[cfg(target_os = "linux")]+fn owned_instant_start<T, F>(+ attempt: InstantAttempt,+ build: impl Future<Output = anyhow::Result<T>> + Send + 'static,+ cleanup: impl Fn(T) -> F + Send + 'static,+) -> impl Future<Output = anyhow::Result<T>> + Send+where+ T: Send + 'static,+ F: Future<Output = anyhow::Result<()>> + Send + 'static,+{+ let waiter = StartupWaiter {+ attempt: attempt.clone(),+ armed: true,+ };+ async move {+ let mut waiter = waiter;+ if *attempt.0.cancelled.borrow() {+ anyhow::bail!("Recording startup cancelled");+ }+ let mut started = false;+ attempt.0.startup.send_if_modified(|state| {+ if *state == StartupState::Unstarted {+ *state = StartupState::Running;+ started = true;+ true+ } else {+ false+ }+ });+ if !started {+ waiter.armed = false;+ drop(waiter);+ anyhow::bail!("Instant startup attempt was already used or cancelled");+ }+ let completion = StartupCompletion {+ attempt: attempt.clone(),+ armed: true,+ };+ let (sender, receiver) = tokio::sync::oneshot::channel();+ drop(tokio::spawn(async move {+ let mut completion = completion;+ let result = tokio::select! {+ biased;+ _ = attempt.cancelled() => Err(anyhow!("Recording startup cancelled")),+ result = std::panic::AssertUnwindSafe(build).catch_unwind() => {+ match result {+ Ok(result) => result,+ Err(_) => {+ attempt.0.startup.send_replace(StartupState::Unconfirmed);+ Err(anyhow!("Recording startup panicked; cleanup is unconfirmed"))+ }+ }+ }+ };+ let cancelled = *attempt.0.cancelled.borrow();+ let result = match result {+ Ok(active) if cancelled => {+ let _ = cleanup(active).await;+ Err(anyhow!(+ "Recording startup cancelled; local files preserved"+ ))+ }+ result => result,+ };+ if result.is_err() {+ attempt.cancel();+ let lifecycle = attempt.0.lifecycle.lock().unwrap().clone();+ if let Some(lifecycle) = lifecycle {+ lifecycle.wait_for_quiescence().await;+ }+ }+ if let Err(Ok(active)) = sender.send(result) {+ let _ = cleanup(active).await;+ }+ attempt.0.startup.send_if_modified(|state| {+ if *state == StartupState::Unconfirmed {+ false+ } else {+ *state = StartupState::Finished;+ true+ }+ });+ completion.armed = false;+ drop(completion);+ }));+ let result = receiver+ .await+ .context("Recording startup acknowledgement lost")?;+ waiter.armed = false;+ drop(waiter);+ result+ }+}++#[cfg(target_os = "linux")]+fn owned_instant_operation(+ operation: impl Future<Output = (bool, anyhow::Result<PathBuf>)> + Send + 'static,+ cancel: impl Fn() + Send + 'static,+) -> CaptureStopFuture {+ let waiter = InstantOperationWaiter {+ cancel: Box::new(cancel),+ armed: true,+ };+ Box::pin(async move {+ let mut waiter = waiter;+ let result = match tokio::spawn(operation).await {+ Ok(result) => result,+ Err(error) => (false, Err(anyhow!("Instant cleanup task failed: {error}"))),+ };+ if result.1.is_err() {+ (waiter.cancel)();+ }+ waiter.armed = false;+ drop(waiter);+ result+ })+}++#[cfg(target_os = "linux")]+struct InstantOperationWaiter {+ cancel: Box<dyn Fn() + Send>,+ armed: bool,+}+#[cfg(target_os = "linux")]+impl Drop for InstantOperationWaiter {+ fn drop(&mut self) {+ if self.armed {+ (self.cancel)();+ }+ }+}++#[cfg(target_os = "linux")]+async fn joined_instant_result<T>(+ lifecycle: instant_recording::InstantLifecycle,+ operation: impl Future<Output = anyhow::Result<T>>,+) -> (bool, anyhow::Result<T>) {+ run_instant_operation(+ operation,+ || lifecycle.cancel(),+ lifecycle.wait_for_quiescence(),+ )+ .await+}++#[cfg(target_os = "linux")]+async fn run_instant_operation<T>(+ operation: impl Future<Output = anyhow::Result<T>>,+ cancel: impl FnOnce(),+ quiescence: impl Future<Output = instant_recording::InstantQuiescence>,+) -> (bool, anyhow::Result<T>) {+ let result = std::panic::AssertUnwindSafe(operation)+ .catch_unwind()+ .await+ .unwrap_or_else(|_| Err(anyhow!("Instant operation panicked")));+ if result.is_err() {+ cancel();+ }+ let joined = quiescence.await == instant_recording::InstantQuiescence::Joined;+ if !joined {+ return (+ false,+ Err(anyhow!(+ "Instant capture cleanup is unconfirmed; local files preserved"+ )),+ );+ }+ (true, result)+}++async fn finalize_studio(+ completed: studio_recording::CompletedRecording,+ capture_target: ScreenCaptureTarget,+) -> anyhow::Result<PathBuf> {+ let project_path = completed.project_path.clone();+ let needs_remux = matches!(+ completed.meta.status(),+ cap_project::StudioRecordingStatus::NeedsRemux+ );+ tokio::task::spawn_blocking(move || {+ if needs_remux {+ ensure_finalization_storage(&project_path)?;+ }+ cap_recording::recovery::RecoveryManager::remux_if_needed(&project_path)+ .map_err(anyhow::Error::from)+ })+ .await+ .context("studio finalize task")?+ .context("studio finalize")?;++ // Everything `handle_recording_finish` does after the remux,+ // in its order: the first-frame JPEG the library's card is+ // drawn from, then the camera preview's blur toggle copied+ // into the project's configuration. Neither is fatal to a+ // recording that is already on disk, so both only warn.+ let project_path = completed.project_path.clone();+ tokio::task::spawn_blocking(move || {+ if let Some(display_path) = studio_display_path(&project_path) {+ write_bundle_thumbnail(&project_path, &display_path);+ }+ apply_camera_blur_to_project_config(&project_path, current_camera_blur());+ let library = serde_json::from_value(serde_json::Value::Object(+ crate::store::store_section("animated_gradients"),+ ))+ .unwrap_or_default();+ apply_animated_gradient_to_project_config(&project_path, &capture_target, &library);+ })+ .await+ .context("studio post-finalize task")?;++ Ok(completed.project_path)+}++#[cfg(target_os = "linux")]+async fn finish_studio_after_join<T, F>(+ stop: impl Future<Output = studio_recording::StudioStopReport>,+ finish: impl FnOnce(studio_recording::CompletedRecording) -> F,+) -> (bool, anyhow::Result<T>)+where+ F: Future<Output = anyhow::Result<T>>,+{+ let report = stop.await;+ if !report.accepted_intent {+ return (+ false,+ Err(anyhow!("Another Studio terminal action owns cleanup")),+ );+ }+ if report.quiescence != studio_recording::StudioQuiescence::Joined {+ return (false, Err(anyhow!("Studio capture cleanup is unconfirmed")));+ }+ let result = match report.result {+ Ok(completed) => std::panic::AssertUnwindSafe(finish(completed))+ .catch_unwind()+ .await+ .unwrap_or_else(|_| {+ Err(anyhow!(+ "Studio finalization task panicked after capture stopped"+ ))+ }),+ Err(error) => Err(anyhow!(error)),+ };+ (true, result)+}++#[cfg(any(windows, all(target_os = "linux", test)))]+async fn finish_after_capture_stop<T, F>(+ stop: impl Future<Output = anyhow::Result<T>>,+ finalize: impl FnOnce(T) -> F,+) -> (bool, anyhow::Result<PathBuf>)+where+ F: Future<Output = anyhow::Result<PathBuf>>,+{+ match stop.await {+ Ok(completed) => {+ let result = std::panic::AssertUnwindSafe(finalize(completed))+ .catch_unwind()+ .await+ .unwrap_or_else(|_| {+ Err(anyhow!(+ "Studio finalization task panicked after capture stopped"+ ))+ });+ (true, result)+ }+ Err(error) => (false, Err(error)),+ }+}++pub(crate) type CaptureStopFuture =+ std::pin::Pin<Box<dyn Future<Output = (bool, anyhow::Result<PathBuf>)> + Send>>;++#[cfg(any(windows, test))]+async fn finish_windows_startup_setup<T>(+ setup: anyhow::Result<T>,+ cancel: impl std::future::Future<Output = anyhow::Result<()>>,+) -> anyhow::Result<T> {+ match setup {+ Ok(output) => Ok(output),+ Err(error) => match cancel.await {+ Ok(()) => Err(error),+ Err(cleanup) => Err(error.context(format!(+ "Windows startup cleanup failed: {cleanup:#}; partial recording preserved"+ ))),+ },+ }+}++#[cfg(any(windows, test))]+async fn finish_windows_failed_capture(+ cancel: impl Future<Output = anyhow::Result<()>>,+ persist_stopped: impl FnOnce() -> anyhow::Result<()>,+) -> (bool, anyhow::Result<PathBuf>) {+ if let Err(error) = cancel.await {+ return (+ false,+ Err(error.context("Failed capture cancellation is unconfirmed; local files preserved")),+ );+ }+ if let Err(error) = persist_stopped() {+ return (+ true,+ Err(error.context(+ "Capture cancelled, but stopped metadata could not be saved; local files preserved",+ )),+ );+ }+ (+ true,+ Err(anyhow!("Recording pipeline failed; local files preserved")),+ )+}+impl ActiveRecording {+ pub fn done_fut(&self) -> cap_recording::DoneFut {+ match &self.handle {+ Handle::Studio(handle) => handle.done_fut(),+ Handle::Instant(handle) => handle.done_fut(),+ }+ }+pub fn instant_share_url(&self) -> Option<&str> {- self.instant_upload- .as_ref()- .map(|upload| upload.video().link.as_str())+ self.instant_share_link.as_deref()}/// Stop and finalize. Returns the project directory.@@ -121,19 +596,271 @@ impl ActiveRecording {}}+ #[cfg(target_os = "linux")]+ pub fn is_paused_handle(+ &self,+ ) -> std::pin::Pin<Box<dyn Future<Output = anyhow::Result<bool>> + Send>> {+ match &self.handle {+ Handle::Studio(handle) => {+ let handle = handle.clone();+ Box::pin(async move { handle.is_paused().await })+ }+ Handle::Instant(handle) => {+ let handle = handle.clone();+ Box::pin(async move { handle.is_paused().await })+ }+ }+ }++ #[cfg(target_os = "linux")]+ pub fn clean_studio_stop_handle(&self) -> Option<CaptureStopFuture> {+ let Handle::Studio(handle) = &self.handle else {+ return None;+ };+ let handle = handle.clone();+ Some(Box::pin(async move {+ let capture_target = handle.capture_target.clone();+ finish_studio_after_join(handle.stop_with_report(), |completed| {+ finalize_studio(completed, capture_target)+ })+ .await+ }))+ }++ #[cfg(windows)]+ pub fn clean_windows_studio_stop_handle(&self) -> Option<CaptureStopFuture> {+ let Handle::Studio(handle) = &self.handle else {+ return None;+ };+ let handle = handle.clone();+ Some(Box::pin(async move {+ let capture_target = handle.capture_target.clone();+ finish_after_capture_stop(handle.stop(), |completed| {+ finalize_studio(completed, capture_target)+ })+ .await+ }))+ }++ #[cfg(windows)]+ pub fn windows_studio_delete_handle(&self) -> Option<CaptureStopFuture> {+ let Handle::Studio(handle) = &self.handle else {+ return None;+ };+ let handle = handle.clone();+ let directory = self.project_dir.clone();+ Some(Box::pin(async move {+ let report = handle+ .stop_with_intent(studio_recording::StudioStopIntent::Discard)+ .await;+ if !report.accepted_intent || !report.stop_acknowledged {+ return (+ false,+ Err(anyhow!(+ "Studio discard stop is unconfirmed; local files preserved"+ )),+ );+ }+ if let Err(error) = report.result {+ return (false, Err(anyhow!(error)));+ }+ let output = directory.clone();+ let result = tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&directory))+ .await+ .context("Studio discard task failed")+ .and_then(|result| result.map_err(anyhow::Error::from));+ (true, result.map(|_| output))+ }))+ }++ #[cfg(target_os = "linux")]+ pub fn instant_lifecycle(&self) -> Option<instant_recording::InstantLifecycle> {+ match &self.handle {+ Handle::Instant(handle) => Some(handle.lifecycle()),+ _ => None,+ }+ }++ #[cfg(target_os = "linux")]+ pub fn instant_stop_handle(+ &self,+ preserve_local: bool,+ failed: bool,+ ) -> Option<CaptureStopFuture> {+ let lifecycle = self.instant_lifecycle()?;+ let active = self.clone();+ let cancel = active.instant_cancellation();+ Some(owned_instant_operation(+ async move {+ if failed {+ joined_instant_result(lifecycle, async move {+ active.cancel_preserving().await?;+ Err(anyhow!("Recording pipeline failed; local files preserved"))+ })+ .await+ } else {+ joined_instant_result(lifecycle, active.stop(preserve_local)).await+ }+ },+ cancel,+ ))+ }++ #[cfg(target_os = "linux")]+ fn instant_cancellation(&self) -> impl Fn() + Send + 'static {+ let lifecycle = self.instant_lifecycle();+ let completion = self.instant_completion.clone();+ move || {+ if let Some(completion) = &completion {+ completion.deny();+ }+ if let Some(lifecycle) = &lifecycle {+ lifecycle.cancel();+ }+ }+ }++ #[cfg(target_os = "linux")]+ pub fn instant_delete_handle(&self) -> Option<CaptureStopFuture> {+ let lifecycle = self.instant_lifecycle()?;+ let active = self.clone();+ let directory = self.project_dir.clone();+ let cancel = active.instant_cancellation();+ Some(owned_instant_operation(+ async move {+ joined_instant_result(lifecycle, async move {+ active.cancel_and_delete().await?;+ Ok(directory)+ })+ .await+ },+ cancel,+ ))+ }++ #[cfg(windows)]+ pub(crate) fn failed_windows_stop_handle(&self) -> CaptureStopFuture {+ let cancel: futures_util::future::BoxFuture<'static, anyhow::Result<()>> =+ match &self.handle {+ Handle::Studio(handle) => {+ let handle = handle.clone();+ Box::pin(async move { handle.stop().await.map(|_| ()) })+ }+ Handle::Instant(handle) => {+ let handle = handle.clone();+ Box::pin(async move { handle.cancel().await })+ }+ };+ let upload = self.instant_upload.clone();+ let directory = self.project_dir.clone();+ Box::pin(async move {+ let mut upload_guard = match &upload {+ Some(upload) => Some(upload.lock().await),+ None => None,+ };+ let mut upload = upload_guard.as_deref_mut().and_then(Option::as_mut);+ if let Some(upload) = upload.as_mut() {+ upload.abort_segments().await;+ }+ finish_windows_failed_capture(cancel, || {+ if let Some(upload) = upload.as_ref() {+ mark_instant_recording_stopped(&directory, upload.metadata_lock())?;+ }+ Ok(())+ })+ .await+ })+ }++ #[cfg(target_os = "linux")]+ pub(crate) async fn cancel_preserving(self) -> anyhow::Result<()> {+ if let Some(completion) = &self.instant_completion {+ completion.deny();+ }+ let _operation = self.instant_operation.lock().await;+ if let Handle::Studio(handle) = &self.handle {+ return handle.cancel().await;+ }+ let lifecycle = self+ .instant_lifecycle()+ .context("Instant lifecycle missing")?;+ let Handle::Instant(handle) = &self.handle else {+ unreachable!()+ };+ let (joined, result) = joined_instant_result(lifecycle, handle.cancel()).await;+ if let Some(upload) = &self.instant_upload+ && let Some(upload) = upload.lock().await.as_mut()+ {+ upload.abort_segments().await;+ return persist_preserved_instant_stop(+ &self.project_dir,+ Some(upload.metadata_lock()),+ joined,+ result,+ );+ }+ persist_preserved_instant_stop(&self.project_dir, None, joined, result)+ }+/// Cancel without finalizing and delete the project directory -- the/// delete and restart flows. Deleting a directory this app just created is/// app behavior, same as the Tauri delete button.pub async fn cancel_and_delete(self) -> anyhow::Result<()> {- match &self.handle {- Handle::Studio(handle) => handle.cancel().await?,- Handle::Instant(handle) => handle.cancel().await?,+ #[cfg(target_os = "linux")]+ if let Some(completion) = &self.instant_completion {+ completion.deny();+ }+ #[cfg(target_os = "linux")]+ let _operation = self.instant_operation.lock().await;+ let result = match &self.handle {+ Handle::Studio(handle) => {+ #[cfg(windows)]+ {+ let report = handle+ .stop_with_intent(studio_recording::StudioStopIntent::Discard)+ .await;+ if !report.accepted_intent || !report.stop_acknowledged {+ return Err(anyhow!(+ "Studio discard is unconfirmed; local files preserved"+ ));+ }+ report.result.map(|_| ()).map_err(anyhow::Error::msg)+ }+ #[cfg(not(windows))]+ handle.cancel().await+ }+ Handle::Instant(handle) => {+ #[cfg(target_os = "linux")]+ {+ let (_, result) =+ joined_instant_result(handle.lifecycle(), handle.cancel()).await;+ result+ }+ #[cfg(not(target_os = "linux"))]+ {+ handle.cancel().await+ }+ }+ };+ if let Err(error) = result {+ if let Some(upload) = &self.instant_upload+ && let Some(upload) = upload.lock().await.as_mut()+ {+ upload.abort_segments().await;+ }+ return Err(error);}- let remote_result = if let Some(upload) = self.instant_upload {+ let upload = match self.instant_upload.as_ref() {+ Some(upload) => upload.lock().await.take(),+ None => None,+ };+ let remote_result = if let Some(upload) = upload {upload.cancel().await} else {Ok(())};+ #[cfg(target_os = "linux")]+ remote_result.map_err(anyhow::Error::msg)?;tokio::task::spawn_blocking({let dir = self.project_dir.clone();move || std::fs::remove_dir_all(&dir)@@ -141,60 +868,34 @@ impl ActiveRecording {.await.context("delete task")?.with_context(|| format!("deleting {}", self.project_dir.display()))?;+ #[cfg(not(target_os = "linux"))]remote_result.map_err(anyhow::Error::msg)?;Ok(())}pub async fn stop(self, preserve_local: bool) -> anyhow::Result<PathBuf> {- let mut instant_upload = self.instant_upload;+ #[cfg(target_os = "linux")]+ let _operation = self.instant_operation.lock().await;+ let mut upload_guard = match self.instant_upload.as_ref() {+ Some(upload) => Some(upload.lock().await),+ None => None,+ };+ let mut instant_upload = upload_guard.as_deref_mut().and_then(Option::as_mut);match self.handle {Handle::Studio(handle) => {let capture_target = handle.capture_target.clone();let completed = handle.stop().await?;- let project_path = completed.project_path.clone();- let needs_remux = matches!(- completed.meta.status(),- cap_project::StudioRecordingStatus::NeedsRemux- );- tokio::task::spawn_blocking(move || {- if needs_remux {- ensure_finalization_storage(&project_path)?;- }- cap_recording::recovery::RecoveryManager::remux_if_needed(&project_path)- .map_err(anyhow::Error::from)- })- .await- .context("studio finalize task")?- .context("studio finalize")?;-- // Everything `handle_recording_finish` does after the remux,- // in its order: the first-frame JPEG the library's card is- // drawn from, then the camera preview's blur toggle copied- // into the project's configuration. Neither is fatal to a- // recording that is already on disk, so both only warn.- let project_path = completed.project_path.clone();- tokio::task::spawn_blocking(move || {- if let Some(display_path) = studio_display_path(&project_path) {- write_bundle_thumbnail(&project_path, &display_path);- }- apply_camera_blur_to_project_config(&project_path, current_camera_blur());- let library = serde_json::from_value(serde_json::Value::Object(- crate::store::store_section("animated_gradients"),- ))- .unwrap_or_default();- apply_animated_gradient_to_project_config(- &project_path,- &capture_target,- &library,- );- })- .await- .context("studio post-finalize task")?;-- Ok(completed.project_path)+ finalize_studio(completed, capture_target).await}Handle::Instant(handle) => {let result = async {+ #[cfg(target_os = "linux")]+ let stopped = {+ let (joined, result) = joined_instant_result(handle.lifecycle(), handle.stop()).await;+ anyhow::ensure!(joined, "Instant capture cleanup is unconfirmed; local files preserved");+ result+ };+ #[cfg(not(target_os = "linux"))]let stopped = handle.stop().await;let metadata_result = match instant_upload.as_ref() {Some(upload) => {@@ -252,6 +953,14 @@ impl ActiveRecording {.await.context("instant thumbnail task")?;+ #[cfg(any(target_os = "linux", windows))]+ if segmented {+ if let Err(error) = upload.finish_screenshot(&completed.project_path).await {+ persist_instant_upload_failure(&completed.project_path, &error, upload.metadata_lock())?;+ return Err(anyhow!(error));+ }+ upload.authorize_completion().map_err(anyhow::Error::msg)?;+ }if let Err(error) = upload.finish_segments().await {persist_instant_upload_failure(&completed.project_path,@@ -262,12 +971,18 @@ impl ActiveRecording {}let upload_result = if segmented {- upload.finish_screenshot(&completed.project_path).await+ #[cfg(any(target_os = "linux", windows))]+ { Ok(()) }+ #[cfg(not(any(target_os = "linux", windows)))]+ { upload.finish_screenshot(&completed.project_path).await }} else {crate::upload::upload_exported_video(completed.project_path.clone(),None,|_| {},+ #[cfg(target_os = "linux")]+ upload.cancellation_token(),+ #[cfg(not(target_os = "linux"))]Arc::new(std::sync::atomic::AtomicBool::new(false)),).await@@ -282,25 +997,70 @@ impl ActiveRecording {}})};- if let Err(error) = upload_result {- persist_instant_upload_failure(+ #[cfg(target_os = "linux")]+ {+ let upload_cancel = Some(upload.cancellation_token());+ let delete_local = !preserve_local+ && crate::store::GeneralSettings::load()+ .delete_instant_recordings_after_upload;+ let local_result = finish_instant_upload_locally(+ upload_cancel.as_deref(),+ async { upload_result },+ || {+ persist_instant_upload_complete(+ &completed.project_path,+ upload.metadata_lock(),+ upload_cancel.as_deref(),+ )+ },+ async {+ if delete_local {+ let directory = completed.project_path.clone();+ let cancel = upload_cancel.clone();+ tokio::task::spawn_blocking(move || {+ remove_uploaded_instant_recording(&directory, cancel.as_deref())+ })+ .await+ .context("instant upload cleanup task")??;+ }+ Ok(())+ },+ )+ .await;+ if let Err(error) = local_result {+ persist_instant_upload_failure(+ &completed.project_path,+ &error.to_string(),+ upload.metadata_lock(),+ )?;+ return Err(error);+ }+ }+ #[cfg(not(target_os = "linux"))]+ {+ if let Err(error) = upload_result {+ persist_instant_upload_failure(+ &completed.project_path,+ &error,+ upload.metadata_lock(),+ )?;+ return Err(anyhow!(error));+ }+ persist_instant_upload_complete(&completed.project_path,- &error,upload.metadata_lock(),+ None,)?;- return Err(anyhow!(error));- }-- persist_instant_upload_complete(&completed.project_path, upload.metadata_lock())?;-- if !preserve_local- && crate::store::GeneralSettings::load().delete_instant_recordings_after_upload- {- let directory = completed.project_path.clone();- tokio::task::spawn_blocking(move || std::fs::remove_dir_all(directory))- .await- .context("instant upload cleanup task")?- .context("deleting uploaded instant recording")?;+ if !preserve_local+ && crate::store::GeneralSettings::load()+ .delete_instant_recordings_after_upload+ {+ let directory = completed.project_path.clone();+ tokio::task::spawn_blocking(move || std::fs::remove_dir_all(directory))+ .await+ .context("instant upload cleanup task")?+ .context("deleting uploaded instant recording")?;+ }}Ok(completed.project_path)@@ -356,6 +1116,25 @@ fn write_instant_metadata(result.context("saving instant recording metadata")}+#[cfg(target_os = "linux")]+fn persist_preserved_instant_stop(+ project_path: &std::path::Path,+ metadata_lock: Option<&Mutex<()>>,+ joined: bool,+ capture_result: anyhow::Result<()>,+) -> anyhow::Result<()> {+ if !joined {+ return capture_result;+ }+ let metadata_result = metadata_lock+ .context("instant recording has no upload session")+ .and_then(|lock| mark_instant_recording_stopped(project_path, lock));+ if let Err(error) = &metadata_result {+ tracing::warn!(%error, "Could not mark the preserved instant recording as stopped");+ }+ capture_result.and(metadata_result)+}+fn mark_instant_recording_stopped(project_path: &std::path::Path,metadata_lock: &Mutex<()>,@@ -756,14 +1535,51 @@ pub(crate) fn persist_instant_upload_failure(})}+fn check_instant_publication_cancelled(+ cancel: Option<&std::sync::atomic::AtomicBool>,+) -> anyhow::Result<()> {+ anyhow::ensure!(+ !cancel.is_some_and(|cancel| cancel.load(std::sync::atomic::Ordering::Acquire)),+ "Instant recording upload cancelled; local success withheld"+ );+ Ok(())+}++#[cfg(any(test, target_os = "linux"))]+fn remove_uploaded_instant_recording(+ directory: &std::path::Path,+ cancel: Option<&std::sync::atomic::AtomicBool>,+) -> anyhow::Result<()> {+ check_instant_publication_cancelled(cancel)?;+ std::fs::remove_dir_all(directory).context("deleting uploaded instant recording")+}++#[cfg(any(test, target_os = "linux"))]+pub(crate) async fn finish_instant_upload_locally(+ cancel: Option<&std::sync::atomic::AtomicBool>,+ upload: impl std::future::Future<Output = Result<(), String>>,+ persist: impl FnOnce() -> anyhow::Result<()>,+ cleanup: impl std::future::Future<Output = anyhow::Result<()>>,+) -> anyhow::Result<()> {+ upload.await.map_err(anyhow::Error::msg)?;+ check_instant_publication_cancelled(cancel)?;+ persist()?;+ check_instant_publication_cancelled(cancel)?;+ cleanup.await?;+ check_instant_publication_cancelled(cancel)+}+fn persist_instant_upload_complete(project_path: &std::path::Path,metadata_lock: &Mutex<()>,+ cancel: Option<&std::sync::atomic::AtomicBool>,) -> anyhow::Result<()> {with_instant_metadata_lock(metadata_lock, || {+ check_instant_publication_cancelled(cancel)?;let mut meta = cap_project::RecordingMeta::load_for_project(project_path).map_err(|error| anyhow!("loading instant recording metadata: {error}"))?;meta.upload = Some(cap_project::UploadMeta::Complete);+ check_instant_publication_cancelled(cancel)?;save_instant_metadata(&meta)?;Ok(())})@@ -812,30 +1628,63 @@ fn persist_in_progress_instant_meta(})}+#[cfg(target_os = "linux")]+fn validate_linux_camera_request(+ mode: RecordingMode,+ target: &ScreenCaptureTarget,+ camera_requested: bool,+ prepared: bool,+) -> anyhow::Result<()> {+ let required = mode == RecordingMode::Instant+ && !matches!(target, ScreenCaptureTarget::CameraOnly)+ && camera_requested;+ anyhow::ensure!(+ !required || prepared,+ "Requested Instant camera has not been prepared. Please select the camera again."+ );+ anyhow::ensure!(+ !prepared || required,+ "Processed camera requires an Instant screen capture with a selected camera"+ );+ Ok(())+}+pub async fn start(config: StartConfig) -> anyhow::Result<ActiveRecording> {- match start_attempt(config.clone()).await {- Ok(active) => Ok(active),- // The mic actor can die between our health checks and the recording- // actor's own audio setup (flaky Bluetooth/Continuity devices, or- // CoreAudio still tearing down a previous session). One retry without- // the mic keeps the screen recording alive; the real fix is app-scoped- // feeds with reconnect, which arrive with the camera preview window.- Err(error)- if config.microphone.is_some() && format!("{error:#}").contains("microphone") =>- {- tracing::warn!("start failed on the microphone path, retrying without: {error:#}");- start_attempt(StartConfig {- microphone: None,- mic_feed: None,- ..config- })- .await- }- Err(error) => Err(error),+ #[cfg(target_os = "linux")]+ if config.mode == RecordingMode::Instant {+ return start_tracked(config, InstantAttempt::new()).await;}+ start_internal(+ config,+ #[cfg(target_os = "linux")]+ None,+ )+ .await+}++#[cfg(target_os = "linux")]+pub(crate) fn start_tracked(+ config: StartConfig,+ attempt: InstantAttempt,+) -> impl Future<Output = anyhow::Result<ActiveRecording>> + Send {+ owned_instant_start(+ attempt.clone(),+ start_internal(config, Some(attempt)),+ ActiveRecording::cancel_preserving,+ )}-async fn start_attempt(config: StartConfig) -> anyhow::Result<ActiveRecording> {+async fn start_internal(+ config: StartConfig,+ #[cfg(target_os = "linux")] attempt: Option<InstantAttempt>,+) -> anyhow::Result<ActiveRecording> {+ #[cfg(target_os = "linux")]+ validate_linux_camera_request(+ config.mode,+ &config.target,+ config.camera.is_some(),+ config.linux_instant_camera.is_some(),+ )?;if matches!(config.target, ScreenCaptureTarget::CameraOnly) && config.camera.is_none() {return Err(anyhow!("Camera-only recording requires a selected camera."));}@@ -869,7 +1718,28 @@ async fn start_attempt(config: StartConfig) -> anyhow::Result<ActiveRecording> {None};- let result = start_attempt_with_upload(config, project_dir, pre_created_video.clone()).await;+ let result = start_attempt_with_upload(+ config,+ project_dir,+ pre_created_video.clone(),+ #[cfg(target_os = "linux")]+ attempt.clone(),+ )+ .await;+ #[cfg(target_os = "linux")]+ if result.is_err()+ && let Some(attempt) = &attempt+ {+ let lifecycle = attempt.0.lifecycle.lock().unwrap().clone();+ if let Some(lifecycle) = lifecycle {+ lifecycle.cancel();+ anyhow::ensure!(+ lifecycle.wait_for_quiescence().await+ == instant_recording::InstantQuiescence::Joined,+ "Recording startup failed; capture cleanup is unconfirmed and files are preserved"+ );+ }+ }if result.is_err()&& let Some(video) = pre_created_video&& let Err(error) = crate::upload::delete_instant_video(&video.id).await@@ -884,40 +1754,42 @@ async fn start_attempt_with_upload(config: StartConfig,project_dir: PathBuf,pre_created_video: Option<cap_project::VideoUploadInfo>,+ #[cfg(target_os = "linux")] attempt: Option<InstantAttempt>,) -> anyhow::Result<ActiveRecording> {+ #[cfg(target_os = "linux")]+ validate_linux_camera_request(+ config.mode,+ &config.target,+ config.camera.is_some(),+ config.linux_instant_camera.is_some(),+ )?;+tracing::info!(dir = %project_dir.display(), "starting recording");- // The app-scoped feeds (running previews/meters, owned by `Feeds`) are- // locked in place when available -- the Tauri model. The per-recording- // spawn below is the fallback for a feed that died between selection and- // start.- // A microphone that enumerates but fails to open (Bluetooth profile- // switch, a Continuity iPhone that wandered off) must not kill the whole- // recording -- degrade to no-mic, the way the Tauri app's app-scoped feed- // surfaces "Not connected" and records on.let (mic_feed, mic_lock, mic_errors) = match (&config.mic_feed, &config.microphone) {(Some(actor), Some(label)) => match actor.ask(microphone::Lock).await {- Ok(lock) => (None, Some(Arc::new(lock)), None),- Err(error) => {- tracing::warn!("app mic feed lock failed ({error}), spawning one for '{label}'");- match setup_microphone(label).await {- Ok((feed, lock, error_rx)) => (Some(feed), Some(lock), Some(error_rx)),- Err(error) => {- tracing::warn!(- "microphone '{label}' unavailable, recording without: {error:#}"- );- (None, None, None)- }- }+ Ok(lock) => {+ anyhow::ensure!(+ lock.device_name() == label,+ "Selected microphone '{label}' is not the connected microphone '{}'. Please select it again.",+ lock.device_name()+ );+ (None, Some(Arc::new(lock)), None)}- },- (None, Some(label)) => match setup_microphone(label).await {- Ok((feed, lock, error_rx)) => (Some(feed), Some(lock), Some(error_rx)),Err(error) => {- tracing::warn!("microphone '{label}' unavailable, recording without: {error:#}");- (None, None, None)+ tracing::warn!("app mic feed lock failed ({error}), spawning one for '{label}'");+ let (feed, lock, error_rx) = setup_microphone(label)+ .await+ .with_context(|| format!("Selected microphone '{label}' is unavailable"))?;+ (Some(feed), Some(lock), Some(error_rx))}},+ (None, Some(label)) => {+ let (feed, lock, error_rx) = setup_microphone(label)+ .await+ .with_context(|| format!("Selected microphone '{label}' is unavailable"))?;+ (Some(feed), Some(lock), Some(error_rx))+ }_ => (None, None, None),};@@ -925,7 +1797,18 @@ async fn start_attempt_with_upload(Some(id) => {if let Some(actor) = &config.camera_feed {match actor.ask(camera::Lock).await {- Ok(lock) => (None, Some(Arc::new(lock))),+ Ok(lock) => {+ let info = lock.camera_info();+ let matches_selection = match id {+ DeviceOrModelID::DeviceID(device_id) => info.device_id() == device_id,+ DeviceOrModelID::ModelID(model_id) => info.model_id() == Some(model_id),+ };+ anyhow::ensure!(+ matches_selection,+ "The selected camera is not the connected camera. Please select it again."+ );+ (None, Some(Arc::new(lock)))+ }Err(error) => {tracing::warn!("app camera feed lock failed ({error}), spawning one");let (feed, lock) = setup_camera(id).await?;@@ -945,6 +1828,36 @@ async fn start_attempt_with_upload(}};+ #[cfg(target_os = "linux")]+ let processed_camera = if let Some(request) = &config.linux_instant_camera {+ anyhow::ensure!(+ config.mode == RecordingMode::Instant+ && !matches!(config.target, ScreenCaptureTarget::CameraOnly),+ "Processed camera requires an Instant screen capture"+ );+ anyhow::ensure!(+ request.presentation.mirrored == request.effects.mirrored,+ "Camera presentation mirror differs from requested processing"+ );+ anyhow::ensure!(+ (request.presentation.effect == instant_recording::LinuxCameraEffect::None)+ == (request.effects.blur == instant_recording::LinuxCameraBlur::Off),+ "Camera presentation blur differs from requested processing"+ );+ let lock = camera_lock+ .clone()+ .context("Processed camera requires a selected camera")?;+ Some(+ request+ .processing+ .subscribe(lock, request.effects)+ .await+ .context("Preparing requested camera effects")?,+ )+ } else {+ None+ };+let mic_mute = mic_lock.as_ref().map(|lock| lock.recording_muted_handle());// ScreenCaptureKit content, exactly as `read_recording_shareable_content`@@ -1038,6 +1951,19 @@ async fn start_attempt_with_upload(if let Some(lock) = mic_lock.clone() {builder = builder.with_mic_feed(lock);}+ #[cfg(target_os = "linux")]+ if let (Some(source), Some(request)) = (processed_camera, &config.linux_instant_camera)+ {+ builder = builder.with_linux_processed_camera(+ source,+ request.presentation,+ request.reference_size,+ );+ }+ #[cfg(target_os = "linux")]+ if let Some(attempt) = &attempt {+ attempt.attach(builder.lifecycle())?;+ }let handle = Arc::new(builder.build(@@ -1047,33 +1973,54 @@ async fn start_attempt_with_upload(.await.context("instant recording actor")?,);- let video = pre_created_video- .ok_or_else(|| anyhow!("instant recording has no reserved upload"))?;- let segment_rx = handle.take_segment_rx();- let metadata_lock = Arc::new(Mutex::new(()));- persist_in_progress_instant_meta(- &project_dir,- &video,- segment_rx.is_some(),- &metadata_lock,- )?;- instant_upload = Some(+ let setup = (|| {+ let video = pre_created_video+ .ok_or_else(|| anyhow!("instant recording has no reserved upload"))?;+ let segment_rx = handle.take_segment_rx();+ let metadata_lock = Arc::new(Mutex::new(()));+ persist_in_progress_instant_meta(+ &project_dir,+ &video,+ segment_rx.is_some(),+ &metadata_lock,+ )?;crate::upload::start_instant_upload(video,project_dir.clone(),segment_rx,metadata_lock,+ #[cfg(any(target_os = "linux", windows))]+ Some(crate::upload::CompletionAuthorization::new()),+ #[cfg(not(any(target_os = "linux", windows)))]+ None,)- .map_err(anyhow::Error::msg)?,- );+ .map_err(anyhow::Error::msg)+ })();+ #[cfg(windows)]+ let setup = finish_windows_startup_setup(setup, handle.cancel()).await;+ instant_upload = Some(setup?);Handle::Instant(handle)}};+ #[cfg(target_os = "linux")]+ let instant_completion = instant_upload+ .as_ref()+ .and_then(crate::upload::InstantUpload::completion_control);+ let instant_share_link = instant_upload+ .as_ref()+ .map(|upload| upload.video().link.clone());+ let instant_upload =+ instant_upload.map(|upload| Arc::new(tokio::sync::Mutex::new(Some(upload))));Ok(ActiveRecording {handle,project_dir,instant_upload,+ instant_share_link,+ #[cfg(target_os = "linux")]+ instant_completion,+ #[cfg(target_os = "linux")]+ instant_operation: Arc::new(tokio::sync::Mutex::new(())),mic_mute,_mic_feed: mic_feed,_camera_feed: camera_feed,@@ -1361,8 +2308,37 @@ mod tests {use super::*;use crate::store::BlurMode;use chrono::TimeZone as _;+ #[cfg(target_os = "linux")]+ use instant_recording::InstantQuiescence;use serde_json::Value;use std::sync::{Arc, Barrier};+ #[cfg(target_os = "linux")]+ use std::time::Duration;++ #[cfg(target_os = "linux")]+ #[test]+ fn instant_screen_requested_camera_cannot_bypass_processing_preparation() {+ let screen = ScreenCaptureTarget::Window {+ id: "1".parse().unwrap(),+ };+ for mode in [RecordingMode::Instant, RecordingMode::Studio] {+ for target in [&screen, &ScreenCaptureTarget::CameraOnly] {+ for camera_requested in [false, true] {+ let required = mode == RecordingMode::Instant+ && !matches!(target, ScreenCaptureTarget::CameraOnly)+ && camera_requested;+ for prepared in [false, true] {+ assert_eq!(+ validate_linux_camera_request(mode, target, camera_requested, prepared)+ .is_ok(),+ required == prepared,+ "{mode:?}, {target:?}, camera={camera_requested}, prepared={prepared}"+ );+ }+ }+ }+ }+ }#[test]fn recording_project_names_honor_mode_target_and_custom_datetime_formats() {@@ -1424,6 +2400,81 @@ mod tests {}}+ #[tokio::test]+ async fn revoked_upload_response_preserves_actual_local_metadata_and_files() {+ use std::sync::atomic::{AtomicBool, Ordering};+ let dir = temp_project("revoked-upload");+ let metadata_lock = Mutex::new(());+ let video = cap_project::VideoUploadInfo {+ id: "revoked".into(),+ link: "https://example.invalid/s/revoked".into(),+ config: cap_project::S3UploadMeta {+ id: "revoked".into(),+ },+ };+ persist_in_progress_instant_meta(&dir, &video, true, &metadata_lock).unwrap();+ let original = std::fs::read(dir.join("recording-meta.json")).unwrap();+ let cancel = AtomicBool::new(false);+ let (response, received) = tokio::sync::oneshot::channel();+ let future = finish_instant_upload_locally(+ Some(&cancel),+ async { received.await.unwrap() },+ || persist_instant_upload_complete(&dir, &metadata_lock, Some(&cancel)),+ async { remove_uploaded_instant_recording(&dir, Some(&cancel)) },+ );+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(1), &mut future)+ .await+ .is_err()+ );+ cancel.store(true, Ordering::Release);+ response.send(Ok(())).unwrap();+ assert!(future.await.is_err());+ assert_eq!(+ std::fs::read(dir.join("recording-meta.json")).unwrap(),+ original+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[tokio::test]+ async fn revoked_local_upload_persist_cannot_begin_cleanup() {+ use std::sync::atomic::{AtomicBool, Ordering};+ let dir = temp_project("revoked-before-cleanup");+ let cancel = AtomicBool::new(false);+ let result = finish_instant_upload_locally(+ Some(&cancel),+ async { Ok(()) },+ || {+ cancel.store(true, Ordering::Release);+ Ok(())+ },+ async { remove_uploaded_instant_recording(&dir, Some(&cancel)) },+ )+ .await;+ assert!(result.is_err());+ assert!(dir.is_dir());+ assert!(remove_uploaded_instant_recording(&dir, Some(&cancel)).is_err());+ assert!(dir.is_dir());+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[tokio::test]+ async fn failed_local_upload_persist_after_remote_success_preserves_recording() {+ let dir = temp_project("failed-upload-persist");+ let result = finish_instant_upload_locally(+ None,+ async { Ok(()) },+ || anyhow::bail!("local metadata could not be saved"),+ async { remove_uploaded_instant_recording(&dir, None) },+ )+ .await;+ assert!(result.unwrap_err().to_string().contains("local metadata"));+ assert!(dir.is_dir());+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn animated_gradient_preference_preserves_camera_only_presentation() {let dir = temp_project("animated-camera-only");@@ -1625,6 +2676,187 @@ mod tests {std::fs::remove_dir_all(dir).unwrap();}+ #[cfg(target_os = "linux")]+ fn preserved_instant_project(tag: &str) -> PathBuf {+ let dir = temp_project(tag);+ std::fs::write(+ dir.join("recording-meta.json"),+ r#"{"pretty_name":"Preserved capture","sharing":null,"recording":true,"upload":{"state":"Failed","error":"offline"}}"#,+ )+ .unwrap();+ std::fs::write(dir.join("partial-media"), b"preserved media").unwrap();+ dir+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn preserved_instant_joined_results_stop_actual_metadata_without_publication() {+ for capture_failed in [false, true] {+ let dir = preserved_instant_project("preserved-joined");+ let builder =+ instant_recording::Actor::builder(PathBuf::new(), ScreenCaptureTarget::CameraOnly);+ let lifecycle = builder.lifecycle();+ drop(builder);+ let (joined, result) = joined_instant_result(lifecycle, async move {+ if capture_failed {+ Err(anyhow!("required audio failed"))+ } else {+ Ok(())+ }+ })+ .await;+ assert!(joined);+ let result =+ persist_preserved_instant_stop(&dir, Some(&Mutex::new(())), joined, result);+ if capture_failed {+ assert_eq!(result.unwrap_err().to_string(), "required audio failed");+ } else {+ result.unwrap();+ }+ let meta = cap_project::RecordingMeta::load_for_project(&dir).unwrap();+ assert!(matches!(+ meta.inner,+ cap_project::RecordingMetaInner::Instant(+ cap_project::InstantRecordingMeta::InProgress { recording: false }+ )+ ));+ assert!(matches!(+ meta.upload,+ Some(cap_project::UploadMeta::Failed { error }) if error == "offline"+ ));+ assert!(meta.sharing.is_none());+ assert_eq!(+ std::fs::read(dir.join("partial-media")).unwrap(),+ b"preserved media"+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn preserved_instant_pending_join_does_not_write_stopped_metadata_early() {+ let dir = preserved_instant_project("preserved-pending");+ let original = std::fs::read(dir.join("recording-meta.json")).unwrap();+ let (joined_tx, joined_rx) = tokio::sync::oneshot::channel();+ let future = async {+ let (joined, result) = run_instant_operation(+ async { Err::<(), _>(anyhow!("capture failed before join")) },+ || {},+ async { joined_rx.await.unwrap() },+ )+ .await;+ persist_preserved_instant_stop(&dir, Some(&Mutex::new(())), joined, result)+ };+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ assert_eq!(+ std::fs::read(dir.join("recording-meta.json")).unwrap(),+ original+ );+ joined_tx.send(InstantQuiescence::Joined).unwrap();+ assert_eq!(+ future.await.unwrap_err().to_string(),+ "capture failed before join"+ );+ let meta = cap_project::RecordingMeta::load_for_project(&dir).unwrap();+ assert!(matches!(+ meta.inner,+ cap_project::RecordingMetaInner::Instant(+ cap_project::InstantRecordingMeta::InProgress { recording: false }+ )+ ));+ std::fs::remove_dir_all(&dir).unwrap();+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn preserved_instant_unconfirmed_results_leave_actual_metadata_untouched() {+ for state in [InstantQuiescence::Pending, InstantQuiescence::Unconfirmed] {+ for capture_failed in [false, true] {+ let dir = preserved_instant_project("preserved-unconfirmed");+ let original = std::fs::read(dir.join("recording-meta.json")).unwrap();+ let (joined, result) = run_instant_operation(+ async move {+ if capture_failed {+ Err(anyhow!("capture failed"))+ } else {+ Ok(())+ }+ },+ || {},+ async move { state },+ )+ .await;+ assert!(!joined);+ assert!(+ persist_preserved_instant_stop(&dir, Some(&Mutex::new(())), joined, result)+ .is_err()+ );+ assert_eq!(+ std::fs::read(dir.join("recording-meta.json")).unwrap(),+ original+ );+ assert!(dir.join("partial-media").is_file());+ std::fs::remove_dir_all(&dir).unwrap();+ }+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn preserved_instant_metadata_io_error_retains_first_capture_failure_and_files() {+ for capture_failed in [false, true] {+ let dir = preserved_instant_project("preserved-metadata-io");+ std::fs::remove_file(dir.join("recording-meta.json")).unwrap();+ let result = persist_preserved_instant_stop(+ &dir,+ Some(&Mutex::new(())),+ true,+ if capture_failed {+ Err(anyhow!("original capture error"))+ } else {+ Ok(())+ },+ );+ let error = result.unwrap_err().to_string();+ if capture_failed {+ assert_eq!(error, "original capture error");+ } else {+ assert!(error.contains("loading recording metadata"));+ }+ assert_eq!(+ std::fs::read(dir.join("partial-media")).unwrap(),+ b"preserved media"+ );+ assert!(!dir.join("recording-meta.json").exists());+ std::fs::remove_dir_all(&dir).unwrap();+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn preserved_instant_missing_upload_lock_never_rewrites_metadata() {+ let dir = preserved_instant_project("preserved-missing-lock");+ let original = std::fs::read(dir.join("recording-meta.json")).unwrap();+ assert!(persist_preserved_instant_stop(&dir, None, true, Ok(())).is_err());+ assert_eq!(+ persist_preserved_instant_stop(&dir, None, true, Err(anyhow!("capture failed")))+ .unwrap_err()+ .to_string(),+ "capture failed"+ );+ assert_eq!(+ std::fs::read(dir.join("recording-meta.json")).unwrap(),+ original+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn stopped_instant_metadata_preserves_recovery_and_upload_state() {let dir = temp_project("instant-stopped");@@ -1887,3 +3119,506 @@ mod tests {}}}++#[cfg(all(test, target_os = "linux"))]+mod capture_stop_contract_tests {+ use super::*;++ #[tokio::test]+ async fn failed_capture_stop_retains_retry_and_never_runs_finalization() {+ let (stopped, result) = finish_after_capture_stop(+ async { anyhow::bail!("cleanup unconfirmed") },+ |(): ()| async { panic!("Failed capture must not finalize") },+ )+ .await;+ assert!(!stopped);+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("cleanup unconfirmed")+ );+ }++ #[tokio::test]+ async fn failed_finalization_after_confirmed_capture_stop_is_safe_to_release() {+ let (stopped, result) = finish_after_capture_stop(async { Ok(()) }, |()| async {+ anyhow::bail!("remux failed")+ })+ .await;+ assert!(stopped);+ assert!(result.unwrap_err().to_string().contains("remux failed"));+ }++ #[tokio::test]+ async fn pending_capture_stop_cannot_finalize_or_acknowledge_success() {+ let (stop_tx, stop_rx) = tokio::sync::oneshot::channel();+ let future = finish_after_capture_stop(async { stop_rx.await.unwrap() }, |()| async {+ Ok(PathBuf::from("saved-project"))+ });+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ stop_tx.send(Ok(())).unwrap();+ let (stopped, result) = future.await;+ assert!(stopped);+ assert_eq!(result.unwrap(), PathBuf::from("saved-project"));+ }+ #[tokio::test]+ async fn finalization_panic_preserves_the_successful_capture_stop_acknowledgement() {+ let (stopped, result) =+ finish_after_capture_stop(async { Ok(()) }, |()| async { panic!("post-stop failure") })+ .await;+ assert!(stopped);+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("after capture stopped")+ );+ }+}++#[cfg(all(test, target_os = "linux"))]+mod instant_lifecycle_tests {+ use super::*;+ use instant_recording::InstantQuiescence;+ use std::sync::atomic::{AtomicBool, Ordering};+ use std::time::Duration;++ #[tokio::test]+ async fn dropping_unpolled_start_or_cancelling_before_build_never_runs_setup() {+ let attempt = InstantAttempt::new();+ let future = owned_instant_start::<(), _>(+ attempt.clone(),+ async { panic!("Unpolled setup must not run") },+ |()| async { Ok(()) },+ );+ drop(future);+ assert_eq!(+ attempt.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ let attempt = InstantAttempt::new();+ attempt.cancel();+ let result = owned_instant_start(attempt.clone(), async { Ok(()) }, |()| async {+ panic!("No active recording exists")+ })+ .await;+ assert!(result.is_err());+ assert_eq!(+ attempt.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ }++ #[tokio::test]+ async fn dropped_start_waiter_keeps_lifecycle_until_owned_setup_is_dropped() {+ let attempt = InstantAttempt::new();+ let builder =+ instant_recording::Actor::builder(PathBuf::new(), ScreenCaptureTarget::CameraOnly);+ attempt.attach(builder.lifecycle()).unwrap();+ let (started, started_rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(owned_instant_start(+ attempt.clone(),+ async move {+ let _builder = builder;+ started.send(()).unwrap();+ std::future::pending::<anyhow::Result<()>>().await+ },+ |()| async { Ok(()) },+ ));+ started_rx.await.unwrap();+ task.abort();+ assert!(task.await.unwrap_err().is_cancelled());+ assert_eq!(+ tokio::time::timeout(Duration::from_secs(2), attempt.wait_for_quiescence())+ .await+ .unwrap(),+ InstantQuiescence::Joined+ );+ }++ #[tokio::test]+ async fn cancelled_successful_setup_waits_for_owned_cleanup_before_reveal() {+ let attempt = InstantAttempt::new();+ let build_attempt = attempt.clone();+ let (entered, entered_rx) = tokio::sync::oneshot::channel();+ let (release, released) = tokio::sync::oneshot::channel();+ let cleanup = Arc::new(Mutex::new(Some((entered, released))));+ let task = tokio::spawn(owned_instant_start(+ attempt.clone(),+ async move {+ build_attempt.cancel();+ Ok(())+ },+ move |()| {+ let (entered, released) = cleanup.lock().unwrap().take().unwrap();+ async move {+ entered.send(()).unwrap();+ released.await.unwrap();+ Ok(())+ }+ },+ ));+ entered_rx.await.unwrap();+ assert_eq!(attempt.quiescence(), InstantQuiescence::Pending);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), attempt.wait_for_quiescence())+ .await+ .is_err()+ );+ release.send(()).unwrap();+ assert!(task.await.unwrap().is_err());+ assert_eq!(+ attempt.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ }++ #[tokio::test]+ async fn startup_panic_is_unconfirmed_even_without_a_live_core_handle() {+ let attempt = InstantAttempt::new();+ let result = owned_instant_start(+ attempt.clone(),+ async { Err::<(), _>(anyhow!("setup failed")) },+ |()| async { Ok(()) },+ )+ .await;+ assert!(result.unwrap_err().to_string().contains("setup failed"));+ assert_eq!(+ attempt.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ let attempt = InstantAttempt::new();+ let result = owned_instant_start::<(), _>(+ attempt.clone(),+ async { panic!("setup panic") },+ |()| async { Ok(()) },+ )+ .await;+ assert!(result.is_err());+ attempt.cancel();+ assert_eq!(+ attempt.wait_for_quiescence().await,+ InstantQuiescence::Unconfirmed+ );+ }++ #[tokio::test]+ async fn actor_error_waits_for_joined_acknowledgement_and_retains_error() {+ let cancelled = Arc::new(AtomicBool::new(false));+ let cancel = cancelled.clone();+ let (joined, joined_rx) = tokio::sync::oneshot::channel();+ let future = run_instant_operation(+ async { Err::<(), _>(anyhow!("required audio failed")) },+ move || {+ cancel.store(true, Ordering::Release);+ },+ async { joined_rx.await.unwrap() },+ );+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ assert!(cancelled.load(Ordering::Acquire));+ joined.send(InstantQuiescence::Joined).unwrap();+ let (safe, result) = future.await;+ assert!(safe);+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("required audio failed")+ );+ }++ #[tokio::test]+ async fn actor_transport_error_or_success_cannot_override_unconfirmed_cleanup() {+ for succeeds in [false, true] {+ let (safe, result) = run_instant_operation(+ async move {+ if succeeds {+ Ok(())+ } else {+ Err(anyhow!("actor no longer exists"))+ }+ },+ || {},+ async { InstantQuiescence::Unconfirmed },+ )+ .await;+ assert!(!safe);+ assert!(result.is_err());+ }+ }++ #[tokio::test]+ async fn successful_joined_operation_retains_success_without_requesting_cancellation() {+ let builder =+ instant_recording::Actor::builder(PathBuf::new(), ScreenCaptureTarget::CameraOnly);+ let lifecycle = builder.lifecycle();+ drop(builder);+ let (safe, result) =+ joined_instant_result(lifecycle, async { Ok(PathBuf::from("completed")) }).await;+ assert!(safe);+ assert_eq!(result.unwrap(), PathBuf::from("completed"));+ }+ #[tokio::test]+ async fn reused_start_attempt_cannot_replace_or_cancel_the_original_owner() {+ let attempt = InstantAttempt::new();+ let (started, started_rx) = tokio::sync::oneshot::channel();+ let first = tokio::spawn(owned_instant_start(+ attempt.clone(),+ async move {+ started.send(()).unwrap();+ std::future::pending::<anyhow::Result<()>>().await+ },+ |()| async { Ok(()) },+ ));+ started_rx.await.unwrap();+ let second =+ owned_instant_start(attempt.clone(), async { Ok(()) }, |()| async { Ok(()) }).await;+ assert!(second.is_err());+ assert!(!*attempt.0.cancelled.borrow());+ attempt.cancel();+ assert!(first.await.unwrap().is_err());+ assert_eq!(+ attempt.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ }+ #[tokio::test]+ async fn dropped_operation_waiter_does_not_release_serialization_before_owned_work_finishes() {+ let serialized = Arc::new(tokio::sync::Mutex::new(()));+ let first_lock = serialized.clone();+ let revoked = Arc::new(AtomicBool::new(false));+ let revoke = revoked.clone();+ let finished = Arc::new(AtomicBool::new(false));+ let first_finished = finished.clone();+ let (entered, entered_rx) = tokio::sync::oneshot::channel();+ let (release, wait) = tokio::sync::oneshot::channel();+ let caller = tokio::spawn(owned_instant_operation(+ async move {+ let _held = first_lock.lock().await;+ entered.send(()).unwrap();+ wait.await.unwrap();+ first_finished.store(true, Ordering::Release);+ (true, Ok(PathBuf::from("preserved")))+ },+ move || {+ revoke.store(true, Ordering::Release);+ },+ ));+ entered_rx.await.unwrap();+ caller.abort();+ assert!(caller.await.unwrap_err().is_cancelled());+ assert!(revoked.load(Ordering::Acquire));+ let retry = serialized.lock();+ tokio::pin!(retry);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut retry)+ .await+ .is_err()+ );+ assert!(!finished.load(Ordering::Acquire));+ release.send(()).unwrap();+ let _joined = retry.await;+ assert!(finished.load(Ordering::Acquire));+ }+}++#[cfg(test)]+mod windows_failed_capture_tests {+ use super::*;+ use std::sync::atomic::{AtomicBool, Ordering};++ #[tokio::test]+ async fn startup_metadata_error_waits_for_actual_cleanup_future() {+ let (release, wait) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(finish_windows_startup_setup(+ Err::<(), _>(anyhow!("metadata denied")),+ async { wait.await.map_err(anyhow::Error::from) },+ ));+ tokio::task::yield_now().await;+ assert!(!task.is_finished());+ release.send(()).unwrap();+ assert_eq!(+ task.await.unwrap().unwrap_err().to_string(),+ "metadata denied"+ );+ }++ #[tokio::test]+ async fn startup_cleanup_error_retains_original_failure() {+ let error =+ finish_windows_startup_setup(Err::<(), _>(anyhow!("upload setup failed")), async {+ Err(anyhow!("stop failed"))+ })+ .await+ .unwrap_err();+ let chain = format!("{error:#}");+ assert!(chain.contains("upload setup failed"));+ assert!(chain.contains("stop failed"));+ }++ #[tokio::test]+ async fn successful_startup_setup_does_not_cancel_capture() {+ let output = finish_windows_startup_setup(Ok(7), async {+ panic!("successful capture must not be cancelled")+ })+ .await+ .unwrap();+ assert_eq!(output, 7);+ }++ #[tokio::test]+ async fn cancellation_error_never_persists_stopped_or_reports_success() {+ let written = AtomicBool::new(false);+ let (stopped, result) =+ finish_windows_failed_capture(async { Err(anyhow!("cancel failed")) }, || {+ written.store(true, Ordering::SeqCst);+ Ok(())+ })+ .await;+ assert!(!stopped);+ assert!(!written.load(Ordering::SeqCst));+ assert!(format!("{:#}", result.unwrap_err()).contains("cancel failed"));+ }++ #[tokio::test]+ async fn acknowledged_cancel_only_persists_stopped_and_keeps_failure() {+ let written = AtomicBool::new(false);+ let (stopped, result) = finish_windows_failed_capture(async { Ok(()) }, || {+ written.store(true, Ordering::SeqCst);+ Ok(())+ })+ .await;+ assert!(stopped);+ assert!(written.load(Ordering::SeqCst));+ assert!(result.is_err());+ }++ #[tokio::test]+ async fn metadata_failure_preserves_error_after_acknowledged_cancel() {+ let (stopped, result) =+ finish_windows_failed_capture(async { Ok(()) }, || Err(anyhow!("metadata denied")))+ .await;+ assert!(stopped);+ assert!(format!("{:#}", result.unwrap_err()).contains("metadata denied"));+ }++ #[tokio::test]+ async fn held_cancel_cannot_persist_metadata_early() {+ let (sender, receiver) = tokio::sync::oneshot::channel();+ let written = Arc::new(AtomicBool::new(false));+ let observed = written.clone();+ let task = tokio::spawn(async move {+ finish_windows_failed_capture(+ async { receiver.await.map_err(anyhow::Error::from) },+ || {+ observed.store(true, Ordering::SeqCst);+ Ok(())+ },+ )+ .await+ });+ tokio::task::yield_now().await;+ assert!(!written.load(Ordering::SeqCst));+ sender.send(()).unwrap();+ let (stopped, result) = task.await.unwrap();+ assert!(stopped);+ assert!(result.is_err());+ }+}++#[cfg(all(test, target_os = "linux"))]+mod studio_report_completion_tests {+ use super::*;+ use std::sync::atomic::{AtomicUsize, Ordering};++ #[tokio::test]+ async fn conflicting_studio_action_cannot_authorize_local_completion() {+ let effects = AtomicUsize::new(0);+ let (joined, result) = finish_studio_after_join(+ async {+ studio_recording::StudioStopReport {+ accepted_intent: false,+ quiescence: studio_recording::StudioQuiescence::Joined,+ result: Err("Discard owns terminal action".into()),+ }+ },+ |_| async {+ effects.fetch_add(1, Ordering::SeqCst);+ Ok(())+ },+ )+ .await;+ assert!(!joined);+ assert!(result.is_err());+ assert_eq!(effects.load(Ordering::SeqCst), 0);+ }++ #[tokio::test]+ async fn joined_required_track_failure_never_finalizes_as_success() {+ let effects = AtomicUsize::new(0);+ let (joined, result) = finish_studio_after_join(+ async {+ studio_recording::StudioStopReport {+ accepted_intent: true,+ quiescence: studio_recording::StudioQuiescence::Joined,+ result: Err("DeviceNotFound".into()),+ }+ },+ |_| async {+ effects.fetch_add(1, Ordering::SeqCst);+ Ok(())+ },+ )+ .await;+ assert!(joined);+ assert!(result.is_err());+ assert_eq!(effects.load(Ordering::SeqCst), 0);+ }+}++#[cfg(all(test, windows))]+mod windows_studio_stop_tests {+ use super::*;++ #[tokio::test]+ async fn studio_stop_error_never_finalizes_or_acknowledges_cleanup() {+ let called = std::sync::atomic::AtomicBool::new(false);+ let (acknowledged, result) = finish_after_capture_stop(+ async { Err::<(), _>(anyhow!("encoder join timed out")) },+ |_| async {+ called.store(true, std::sync::atomic::Ordering::SeqCst);+ Ok(PathBuf::new())+ },+ )+ .await;+ assert!(!acknowledged);+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("encoder join timed out")+ );+ assert!(!called.load(std::sync::atomic::Ordering::SeqCst));+ }++ #[tokio::test]+ async fn healthy_studio_stop_retains_existing_finalization() {+ let (acknowledged, result) = finish_after_capture_stop(async { Ok(()) }, |_| async {+ Ok(PathBuf::from("preserved.cap"))+ })+ .await;+ assert!(acknowledged);+ assert_eq!(result.unwrap(), PathBuf::from("preserved.cap"));+ }+}diff --git a/apps/desktop-gpui/src/session.rs b/apps/desktop-gpui/src/session.rsindex e543690e0..8c332b49e 100644--- a/apps/desktop-gpui/src/session.rs+++ b/apps/desktop-gpui/src/session.rs@@ -23,6 +23,187 @@ pub enum Phase {Stopping,}+#[cfg(target_os = "linux")]+#[derive(Clone, Debug, PartialEq, Eq)]+struct RecordingOwner {+ generation: u64,+ project_dir: std::path::PathBuf,+}++#[cfg(target_os = "linux")]+#[derive(Clone)]+struct TerminalTicket {+ owner: RecordingOwner,+ operation: u64,+}++#[cfg(target_os = "linux")]+impl TerminalTicket {+ fn is_current(+ &self,+ phase: Phase,+ generation: u64,+ operation: u64,+ owner: Option<&RecordingOwner>,+ retains_active: bool,+ ) -> bool {+ phase == Phase::Stopping+ && generation == self.owner.generation+ && operation == self.operation+ && (!retains_active || owner == Some(&self.owner))+ }+}++#[cfg(target_os = "linux")]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum CleanControlKind {+ Pause,+ Resume,+ VerifyPaused,+}++#[cfg(target_os = "linux")]+#[derive(Clone, Debug, PartialEq, Eq)]+struct CleanControlTicket {+ owner: RecordingOwner,+ sequence: u64,+ kind: CleanControlKind,+}++#[cfg(target_os = "linux")]+struct PendingCleanControl {+ ticket: CleanControlTicket,+ abort: futures_util::future::AbortHandle,+}++#[cfg(target_os = "linux")]+#[derive(Default)]+struct CleanControlState {+ pending: Option<PendingCleanControl>,+ sequence: u64,+ paused_owner: Option<RecordingOwner>,+ uncertain: bool,+}++#[cfg(target_os = "linux")]+impl CleanControlState {+ fn begin(+ &mut self,+ owner: RecordingOwner,+ kind: CleanControlKind,+ ) -> (CleanControlTicket, futures_util::future::AbortRegistration) {+ self.invalidate();+ self.sequence = self.sequence.wrapping_add(1);+ let ticket = CleanControlTicket {+ owner,+ sequence: self.sequence,+ kind,+ };+ let (abort, registration) = futures_util::future::AbortHandle::new_pair();+ self.pending = Some(PendingCleanControl {+ ticket: ticket.clone(),+ abort,+ });+ (ticket, registration)+ }++ fn invalidate(&mut self) {+ if let Some(pending) = self.pending.take() {+ pending.abort.abort();+ }+ self.paused_owner = None;+ }++ fn pending_kind(&self) -> Option<CleanControlKind> {+ self.pending.as_ref().map(|pending| pending.ticket.kind)+ }++ fn complete(+ &mut self,+ ticket: &CleanControlTicket,+ owner: Option<&RecordingOwner>,+ phase: Phase,+ outcome: &CleanControlOutcome,+ ) -> bool {+ if owner != Some(&ticket.owner)+ || !matches!(phase, Phase::Recording { .. })+ || self+ .pending+ .as_ref()+ .is_none_or(|pending| pending.ticket != *ticket)+ {+ return false;+ }+ self.pending = None;+ self.uncertain = outcome.paused.is_none();+ self.paused_owner = (outcome.paused == Some(true)).then(|| ticket.owner.clone());+ true+ }++ fn paused_for(&self, owner: Option<&RecordingOwner>) -> bool {+ !self.uncertain+ && self.pending.is_none()+ && owner.is_some()+ && self.paused_owner.as_ref() == owner+ }+}++#[cfg(target_os = "linux")]+#[derive(Debug)]+struct CleanControlOutcome {+ paused: Option<bool>,+ error: Option<String>,+}++#[cfg(target_os = "linux")]+async fn after_clean_visibility(+ visibility: Option<crate::app_windows::CleanVisibility>,+ control: impl Future<Output = anyhow::Result<()>>,+) -> anyhow::Result<()> {+ if let Some(visibility) = visibility {+ visibility.await?;+ }+ control.await+}++#[cfg(target_os = "linux")]+async fn run_clean_control(+ kind: CleanControlKind,+ control: impl Future<Output = anyhow::Result<()>>,+ query_paused: impl Future<Output = anyhow::Result<bool>>,+ settle: impl Future<Output = ()>,+) -> CleanControlOutcome {+ if kind == CleanControlKind::Resume {+ settle.await;+ }+ let result = control.await;+ let control_succeeded = result.is_ok();+ let state = tokio::time::timeout(Duration::from_secs(2), query_paused).await;+ let (paused, state_error) = match state {+ Ok(Ok(paused)) => (Some(paused), None),+ Ok(Err(error)) => (+ None,+ Some(format!("Could not confirm capture state: {error:#}")),+ ),+ Err(_) => (None, Some("Timed out confirming capture state".into())),+ };+ let paused = match paused {+ Some(true) => Some(true),+ Some(false) if control_succeeded && kind == CleanControlKind::Resume => Some(false),+ _ => None,+ };+ let error = result+ .err()+ .map(|error| format!("{error:#}"))+ .or(state_error)+ .or_else(|| {+ let expected = kind != CleanControlKind::Resume;+ (paused != Some(expected))+ .then(|| "Capture did not acknowledge the requested pause state".into())+ });+ CleanControlOutcome { paused, error }+}+pub struct RecordingSession {pub phase: Phase,active: Option<ActiveRecording>,@@ -59,6 +240,22 @@ pub struct RecordingSession {paused_accum: Duration,paused_since: Option<Instant>,storage_monitor: Option<Task<()>>,+ #[cfg(any(target_os = "linux", windows))]+ failure_monitor: Option<Task<()>>,+ #[cfg(any(target_os = "linux", windows))]+ recording_generation: u64,+ #[cfg(target_os = "linux")]+ instant_attempt: Option<recording::InstantAttempt>,+ #[cfg(target_os = "linux")]+ terminal_operation: u64,+ #[cfg(any(target_os = "linux", windows))]+ pipeline_failed: bool,+ #[cfg(target_os = "linux")]+ stop_requested: bool,+ #[cfg(target_os = "linux")]+ clean_control: CleanControlState,+ #[cfg(target_os = "linux")]+ show_controls_after_pause: bool,}struct SessionGlobal(Entity<RecordingSession>);@@ -83,6 +280,22 @@ impl RecordingSession {paused_accum: Duration::ZERO,paused_since: None,storage_monitor: None,+ #[cfg(any(target_os = "linux", windows))]+ failure_monitor: None,+ #[cfg(any(target_os = "linux", windows))]+ recording_generation: 0,+ #[cfg(target_os = "linux")]+ instant_attempt: None,+ #[cfg(target_os = "linux")]+ terminal_operation: 0,+ #[cfg(any(target_os = "linux", windows))]+ pipeline_failed: false,+ #[cfg(target_os = "linux")]+ stop_requested: false,+ #[cfg(target_os = "linux")]+ clean_control: CleanControlState::default(),+ #[cfg(target_os = "linux")]+ show_controls_after_pause: false,});cx.set_global(SessionGlobal(session.clone()));session@@ -180,6 +393,22 @@ impl RecordingSession {return;}self.storage_monitor = None;+ #[cfg(windows)]+ {+ self.failure_monitor = None;+ self.recording_generation = self.recording_generation.wrapping_add(1);+ self.pipeline_failed = false;+ }+ #[cfg(target_os = "linux")]+ {+ self.failure_monitor = None;+ self.recording_generation = self.recording_generation.wrapping_add(1);+ self.instant_attempt = (config.mode == recording::RecordingMode::Instant)+ .then(recording::InstantAttempt::new);+ self.pipeline_failed = false;+ self.clean_control.invalidate();+ self.clean_control.uncertain = false;+ }self.phase = Phase::Starting;self.error = None;self.storage_warning = false;@@ -189,14 +418,51 @@ impl RecordingSession {self.last_config = Some(config.clone());cx.notify();- let task = gpui_tokio::Tokio::spawn(cx, recording::start(config));+ #[cfg(target_os = "linux")]+ let generation = self.recording_generation;+ #[cfg(target_os = "linux")]+ let attempt = self.instant_attempt.clone();+ #[cfg(target_os = "linux")]+ let start: std::pin::Pin<+ Box<dyn Future<Output = anyhow::Result<ActiveRecording>> + Send>,+ > = match attempt.clone() {+ Some(attempt) => Box::pin(recording::start_tracked(config, attempt)),+ None => Box::pin(recording::start(config)),+ };+ #[cfg(not(target_os = "linux"))]+ let start = recording::start(config);+ let task = gpui_tokio::Tokio::spawn(cx, start);cx.spawn(async move |this, cx| {let result = task.await;+ #[cfg(target_os = "linux")]+ let startup_failed = !matches!(&result, Ok(Ok(_)));+ #[cfg(target_os = "linux")]+ let startup_joined = if startup_failed {+ match &attempt {+ Some(attempt) => {+ attempt.cancel();+ attempt.wait_for_quiescence().await+ == cap_recording::instant_recording::InstantQuiescence::Joined+ }+ None => true,+ }+ } else {+ false+ };this.update(cx, |this, cx| {+ #[cfg(target_os = "linux")]+ if this.recording_generation != generation || this.phase != Phase::Starting {+ if let Ok(Ok(active)) = result {+ gpui_tokio::Tokio::spawn(cx, active.cancel_preserving()).detach();+ }+ return;+ }match result {Ok(Ok(active)) => {tracing::info!(dir = %active.project_dir.display(), "recording started");let project_dir = active.project_dir.clone();+ #[cfg(any(target_os = "linux", windows))]+ let done = active.done_fut();this.active = Some(active);this.phase = Phase::Recording { paused: false };// A fresh mic lock always starts unmuted.@@ -205,18 +471,63 @@ impl RecordingSession {this.paused_accum = Duration::ZERO;this.paused_since = None;this.monitor_storage(project_dir, cx);+ #[cfg(any(target_os = "linux", windows))]+ this.monitor_recording_failure(done, cx);+ #[cfg(target_os = "linux")]+ if this.stop_requested {+ this.stop(cx);+ } else if this.show_controls_after_pause {+ this.show_clean_capture_controls(cx);+ }}Ok(Err(error)) => {tracing::error!("recording failed to start: {error:#}");this.error = Some(format!("{error:#}"));- this.phase = Phase::Idle;+ #[cfg(target_os = "linux")]+ {+ this.phase = if startup_joined {+ Phase::Idle+ } else {+ Phase::Starting+ };+ }+ #[cfg(not(target_os = "linux"))]+ {+ this.phase = Phase::Idle;+ }}Err(join_error) => {tracing::error!("recording start task died: {join_error}");this.error = Some("Recording task failed.".into());- this.phase = Phase::Idle;+ #[cfg(target_os = "linux")]+ {+ this.phase = if startup_joined {+ Phase::Idle+ } else {+ Phase::Starting+ };+ }+ #[cfg(not(target_os = "linux"))]+ {+ this.phase = Phase::Idle;+ }}}+ #[cfg(target_os = "linux")]+ if startup_failed && !startup_joined {+ this.stop_requested = false;+ this.clean_control.uncertain = true;+ this.error = Some(format!(+ "{}. Capture cleanup is unconfirmed. Use Ctrl+Shift+F9 to retry Stop.",+ this.error.as_deref().unwrap_or("Recording startup failed")+ ));+ }+ #[cfg(target_os = "linux")]+ if this.phase == Phase::Idle {+ this.stop_requested = false;+ this.clean_control = CleanControlState::default();+ this.show_controls_after_pause = false;+ }cx.notify();}).ok();@@ -224,6 +535,32 @@ impl RecordingSession {.detach();}+ #[cfg(any(target_os = "linux", windows))]+ fn monitor_recording_failure(&mut self, done: cap_recording::DoneFut, cx: &mut Context<Self>) {+ let generation = self.recording_generation;+ let task = gpui_tokio::Tokio::spawn(cx, done);+ self.failure_monitor = Some(cx.spawn(async move |this, cx| {+ let error = match task.await {+ Ok(Ok(())) => return,+ Ok(Err(error)) => error.to_string(),+ Err(error) => format!("Recording completion task failed: {error}"),+ };+ this.update(cx, |this, cx| {+ if !recording_failure_is_current(this.phase, this.recording_generation, generation)+ || this.active.is_none()+ {+ return;+ }+ tracing::error!(%error, "recording pipeline failed");+ this.pipeline_failed = true;+ this.error = Some(error);+ this.stop(cx);+ cx.notify();+ })+ .ok();+ }));+ }+fn monitor_storage(&mut self, project_dir: std::path::PathBuf, cx: &mut Context<Self>) {self.storage_monitor = None;let task = cx.spawn(async move |this, cx| {@@ -297,31 +634,176 @@ impl RecordingSession {}pub fn stop(&mut self, cx: &mut Context<Self>) {+ #[cfg(target_os = "linux")]+ if matches!(self.phase, Phase::Starting | Phase::Stopping)+ && let Some(attempt) = self.instant_attempt.clone()+ {+ attempt.cancel();+ if self.phase == Phase::Stopping || self.stop_requested {+ self.stop_requested = true;+ cx.notify();+ return;+ }+ self.stop_requested = true;+ let generation = self.recording_generation;+ let task =+ gpui_tokio::Tokio::spawn(cx, async move { attempt.wait_for_quiescence().await });+ cx.spawn(async move |this, cx| {+ let result = task.await;+ this.update(cx, |this, cx| {+ if this.recording_generation != generation || this.phase != Phase::Starting || this.active.is_some() { return; }+ if matches!(result, Ok(cap_recording::instant_recording::InstantQuiescence::Joined)) {+ this.finish(cx);+ } else {+ this.stop_requested = false;+ this.clean_control.uncertain = true;+ this.error = Some("Capture cleanup is unconfirmed. Local files are preserved; use Ctrl+Shift+F9 to retry Stop.".into());+ cx.notify();+ }+ }).ok();+ }).detach();+ cx.notify();+ return;+ }+ #[cfg(target_os = "linux")]+ if crate::app_windows::clean_capture_active(cx)+ && clean_capture_stop_must_wait(self.phase, self.clean_control.pending_kind())+ {+ self.stop_requested = true;+ cx.notify();+ return;+ }if !matches!(self.phase, Phase::Recording { .. }) {return;}self.storage_monitor = None;- let Some(active) = self.active.take() else {+ #[cfg(target_os = "linux")]+ {+ self.failure_monitor = None;+ }+ let Some(active) = self.active.as_ref() else {return;};let instant_share_url = active.instant_share_url().map(ToString::to_string);+ #[cfg(target_os = "linux")]+ let stop_owner = RecordingOwner {+ generation: self.recording_generation,+ project_dir: active.project_dir.clone(),+ };+ #[cfg(target_os = "linux")]+ let operation = {+ self.terminal_operation = self.terminal_operation.wrapping_add(1);+ self.terminal_operation+ };+ #[cfg(target_os = "linux")]+ let stop_ticket = TerminalTicket {+ owner: stop_owner.clone(),+ operation,+ };+ #[cfg(windows)]+ let stop_generation = self.recording_generation;+ let phase_before_stop = self.phase;let low_storage = self.stopped_for_low_storage;+ #[cfg(any(target_os = "linux", windows))]+ let recording_failed = self.pipeline_failed;+ #[cfg(not(any(target_os = "linux", windows)))]+ let recording_failed = false;+ #[cfg(windows)]+ let original_failure = recording_failed.then(|| self.error.clone()).flatten();+ #[cfg(target_os = "linux")]+ let defer_share_until_success =+ crate::app_windows::clean_capture_active(cx) || active.instant_lifecycle().is_some();+ #[cfg(windows)]+ let defer_share_until_success = true;+ #[cfg(not(any(target_os = "linux", windows)))]+ let defer_share_until_success = false;if let Some(link) = &instant_share_url&& !low_storage+ && !recording_failed+ && !defer_share_until_success&& !crate::store::GeneralSettings::load().disable_auto_open_links{let separator = if link.contains('?') { '&' } else { '?' };cx.open_url(&format!("{link}{separator}recordingStopped=1"));}+ #[cfg(target_os = "linux")]+ let retained_stop = active+ .instant_stop_handle(low_storage || recording_failed, recording_failed)+ .or_else(|| active.clean_studio_stop_handle());+ #[cfg(windows)]+ let retained_stop = recording_failed+ .then(|| active.failed_windows_stop_handle())+ .or_else(|| active.clean_windows_studio_stop_handle());+ #[cfg(not(any(target_os = "linux", windows)))]+ let retained_stop: Option<recording::CaptureStopFuture> = None;+ let retains_active = retained_stop.is_some();+ let stop_future: recording::CaptureStopFuture = match retained_stop {+ Some(future) => future,+ None => {+ let active = self.active.take().unwrap();+ Box::pin(async move { (true, active.stop(low_storage || recording_failed).await) })+ }+ };+ #[cfg(target_os = "linux")]+ {+ self.clean_control.invalidate();+ self.stop_requested = false;+ }self.stopped_elapsed = Some(self.elapsed());self.phase = Phase::Stopping;cx.notify();- let task = gpui_tokio::Tokio::spawn(cx, active.stop(low_storage));+ let task = gpui_tokio::Tokio::spawn(cx, stop_future);cx.spawn(async move |this, cx| {let result = task.await;this.update(cx, |this, cx| {+ #[cfg(target_os = "linux")]+ if !stop_ticket.is_current(this.phase, this.recording_generation, this.terminal_operation, this.recording_owner().as_ref(), retains_active) { return; }+ #[cfg(windows)]+ if this.recording_generation != stop_generation || this.phase != Phase::Stopping { return; }+ let capture_stopped = match &result {+ Ok((stopped, _)) => *stopped,+ Err(_) => !retains_active,+ };+ if !capture_stopped {+ let error = match result {+ Ok((_, Err(error))) => format!("{error:#}"),+ Err(error) => format!("Stop task failed: {error}"),+ Ok((_, Ok(_))) => "Capture stop was not acknowledged".into(),+ };+ #[cfg(windows)]+ let error = match &original_failure {+ Some(first) => format!("{first}; cleanup: {error}"),+ None => error,+ };+ tracing::error!(%error, "Capture cleanup is unconfirmed; retaining Stop control");+ this.phase = phase_before_stop;+ this.stopped_elapsed = None;+ #[cfg(windows)]+ let message = if this.mode() == Some(recording::RecordingMode::Studio) {+ format!("{error}. Studio shutdown remains unconfirmed; recording and files retained.")+ } else {+ format!("{error}. Capture cleanup is unconfirmed. Use Ctrl+Shift+F9 to retry Stop.")+ };+ #[cfg(not(windows))]+ let message = format!("{error}. Capture cleanup is unconfirmed. Use Ctrl+Shift+F9 to retry Stop.");+ this.error = Some(message);+ #[cfg(target_os = "linux")]+ { this.clean_control.uncertain = true; }+ cx.notify();+ return;+ }+ let result = result.map(|(_, result)| result);+ #[cfg(windows)]+ let result = result.map(|result| result.map_err(|error| match &original_failure {+ Some(first) => error.context(first.clone()),+ None => error,+ }));+ if retains_active { this.active = None; }match result {+ Ok(Ok(project_dir)) if recording_failed => {+ tracing::warn!(dir = %project_dir.display(), "failed recording files preserved");+ }Ok(Ok(project_dir)) => {// The completion affordance is Recents now: the main// window comes back with this recording at the head of@@ -336,6 +818,13 @@ impl RecordingSession {if this.mode() == Some(crate::recording::RecordingMode::Studio) && !low_storage {this.finished_studio = Some(project_dir);} else if let Some(link) = instant_share_url {+ if defer_share_until_success+ && !low_storage+ && !crate::store::GeneralSettings::load().disable_auto_open_links+ {+ let separator = if link.contains('?') { '&' } else { '?' };+ cx.open_url(&format!("{link}{separator}recordingStopped=1"));+ }cx.write_to_clipboard(gpui::ClipboardItem::new_string(link));}}@@ -358,6 +847,11 @@ impl RecordingSession {}pub fn toggle_pause(&mut self, cx: &mut Context<Self>) {+ #[cfg(target_os = "linux")]+ if crate::app_windows::clean_capture_active(cx) {+ self.toggle_clean_capture_pause(cx);+ return;+ }let Phase::Recording { paused } = self.phase else {return;};@@ -390,12 +884,183 @@ impl RecordingSession {.detach();}+ #[cfg(target_os = "linux")]+ fn recording_owner(&self) -> Option<RecordingOwner> {+ self.active.as_ref().map(|active| RecordingOwner {+ generation: self.recording_generation,+ project_dir: active.project_dir.clone(),+ })+ }++ #[cfg(target_os = "linux")]+ pub fn instant_cleanup_safe(&self) -> bool {+ self.instant_attempt.as_ref().is_none_or(|attempt| {+ attempt.quiescence() == cap_recording::instant_recording::InstantQuiescence::Joined+ })+ }++ #[cfg(target_os = "linux")]+ pub fn clean_capture_controls_safe(&self) -> bool {+ clean_capture_controls_can_reveal(+ self.mode(),+ self.phase,+ self.clean_control+ .paused_for(self.recording_owner().as_ref()),+ )+ }++ #[cfg(target_os = "linux")]+ pub fn show_clean_capture_controls(&mut self, cx: &mut Context<Self>) {+ if self.mode() == Some(crate::recording::RecordingMode::Instant) {+ self.stop(cx);+ return;+ }+ self.show_controls_after_pause = true;+ if self.clean_capture_controls_safe() {+ cx.defer(crate::app_windows::show_main_window_after_capture_pause);+ } else if self.clean_control.pending.is_none() && !self.clean_control.uncertain {+ match self.phase {+ Phase::Recording { paused: true } => {+ self.begin_clean_control(CleanControlKind::VerifyPaused, cx)+ }+ Phase::Recording { paused: false } => {+ self.begin_clean_control(CleanControlKind::Pause, cx)+ }+ _ => {}+ }+ }+ }++ #[cfg(target_os = "linux")]+ fn toggle_clean_capture_pause(&mut self, cx: &mut Context<Self>) {+ if self.clean_control.pending.is_some() || self.clean_control.uncertain {+ return;+ }+ let Phase::Recording { paused } = self.phase else {+ return;+ };+ self.begin_clean_control(+ if paused {+ CleanControlKind::Resume+ } else {+ CleanControlKind::Pause+ },+ cx,+ );+ }++ #[cfg(target_os = "linux")]+ fn begin_clean_control(&mut self, kind: CleanControlKind, cx: &mut Context<Self>) {+ let Some(active) = self.active.as_ref() else {+ return;+ };+ let owner = RecordingOwner {+ generation: self.recording_generation,+ project_dir: active.project_dir.clone(),+ };+ let control = match kind {+ CleanControlKind::Resume => active.resume_handle(),+ CleanControlKind::Pause => active.pause_handle(),+ CleanControlKind::VerifyPaused => Box::pin(async { Ok(()) }),+ };+ let query_paused = active.is_paused_handle();+ let visibility = if kind == CleanControlKind::Resume {+ match crate::app_windows::hide_clean_capture_main(cx) {+ Ok(visibility) => Some(visibility),+ Err(error) => {+ self.error = Some(error.to_string());+ cx.notify();+ return;+ }+ }+ } else {+ None+ };+ if kind == CleanControlKind::Resume {+ self.show_controls_after_pause = false;+ }+ let control = after_clean_visibility(visibility, control);+ let (ticket, registration) = self.clean_control.begin(owner, kind);+ cx.notify();+ let task = gpui_tokio::Tokio::spawn(+ cx,+ futures_util::future::Abortable::new(+ run_clean_control(kind, control, query_paused, async {+ tokio::time::sleep(Duration::from_millis(150)).await+ }),+ registration,+ ),+ );+ cx.spawn(async move |this, cx| {+ let result = task.await;+ let outcome = match result {+ Ok(Ok(outcome)) => outcome,+ Ok(Err(_)) => return,+ Err(error) => CleanControlOutcome {+ paused: None,+ error: Some(format!("Capture control task failed: {error}")),+ },+ };+ this.update(cx, |this, cx| {+ let owner = this.recording_owner();+ if !this+ .clean_control+ .complete(&ticket, owner.as_ref(), this.phase, &outcome)+ {+ return;+ }+ if let Some(paused) = outcome.paused {+ let was_paused = this.is_paused();+ this.phase = Phase::Recording { paused };+ if was_paused && !paused {+ if let Some(since) = this.paused_since.take() {+ this.paused_accum += since.elapsed();+ }+ } else if !was_paused && paused {+ this.paused_since = Some(Instant::now());+ }+ }+ if let Some(error) = outcome.error {+ tracing::error!(%error, "clean capture pause/resume failed");+ this.error = Some(format!(+ "{error}. Use your recording Stop control to stop recording."+ ));+ if outcome.paused == Some(true) {+ this.show_controls_after_pause = true;+ }+ }+ if this.stop_requested {+ this.stop(cx);+ } else if this.show_controls_after_pause && this.clean_capture_controls_safe() {+ cx.defer(crate::app_windows::show_main_window_after_capture_pause);+ }+ cx.notify();+ })+ .ok();+ })+ .detach();+ }+/// Cancel the live recording and delete its project directory (the bar's/// trash button).pub fn delete(&mut self, cx: &mut Context<Self>) {+ #[cfg(target_os = "linux")]+ if self.clean_control.pending.is_some() || self.clean_control.uncertain {+ return;+ }if !matches!(self.phase, Phase::Recording { .. }) {return;}+ #[cfg(target_os = "linux")]+ if self.mode() == Some(recording::RecordingMode::Instant) {+ self.discard_instant(None, cx);+ return;+ }+ #[cfg(windows)]+ if self.mode() == Some(recording::RecordingMode::Studio) {+ self.discard_windows_studio(None, cx);+ return;+ }self.storage_monitor = None;let Some(active) = self.active.take() else {return;@@ -416,16 +1081,52 @@ impl RecordingSession {/// The bar's restart button: throw away the live recording and immediately/// start a new one with the same config.pub fn restart(&mut self, cx: &mut Context<Self>) {+ #[cfg(target_os = "linux")]+ if self.clean_control.pending.is_some() || self.clean_control.uncertain {+ return;+ }if !matches!(self.phase, Phase::Recording { .. }) {return;}- self.storage_monitor = None;- let Some(active) = self.active.take() else {+ let Some(config) = self.last_config.clone() else {return;};- let Some(config) = self.last_config.clone() else {+ #[cfg(target_os = "linux")]+ let config = {+ let mut config = config;+ if let Err(error) = crate::app_windows::refresh_linux_instant_camera(&mut config, cx) {+ self.error = Some(error.to_string());+ cx.notify();+ return;+ }+ config+ };+ #[cfg(target_os = "linux")]+ let clean_capture = crate::app_windows::clean_capture_active(cx);+ #[cfg(target_os = "linux")]+ if clean_capture {+ self.show_controls_after_pause = false;+ }+ #[cfg(target_os = "linux")]+ if self.mode() == Some(recording::RecordingMode::Instant) {+ self.discard_instant(Some(config), cx);+ return;+ }+ #[cfg(windows)]+ if self.mode() == Some(recording::RecordingMode::Studio) {+ self.discard_windows_studio(Some(config), cx);+ return;+ }+ #[cfg(target_os = "linux")]+ let restart_generation = self.recording_generation;+ self.storage_monitor = None;+ let Some(active) = self.active.take() else {return;};+ #[cfg(target_os = "linux")]+ {+ self.failure_monitor = None;+ }self.phase = Phase::Starting;self.started_at = None;cx.notify();@@ -435,10 +1136,59 @@ impl RecordingSession {if let Ok(Err(error)) = task.await {tracing::error!("restart: discarding old recording: {error:#}");}+ #[cfg(target_os = "linux")]+ if !this+ .update(cx, |this, _| {+ this.recording_generation == restart_generation && this.phase == Phase::Starting+ })+ .unwrap_or(false)+ {+ return;+ }+ #[cfg(target_os = "linux")]+ if clean_capture {+ let visibility = cx.update(|cx| {+ crate::app_windows::hide_clean_capture_main(cx)+ .map(|visibility| gpui_tokio::Tokio::spawn(cx, visibility))+ });+ let result = match visibility {+ Ok(task) => task+ .await+ .map_err(anyhow::Error::from)+ .and_then(|result| result),+ Err(error) => Err(error),+ };+ if let Err(error) = result {+ this.update(cx, |this, cx| {+ if this.recording_generation != restart_generation+ || this.phase != Phase::Starting+ {+ return;+ }+ this.error = Some(format!("Restart could not hide Cap windows: {error}"));+ this.finish(cx);+ })+ .ok();+ return;+ }+ cx.background_executor()+ .timer(Duration::from_millis(150))+ .await;+ }this.update(cx, |this, cx| {// Restart bypasses the Idle guard in `start` by construction:// we are in `Starting` and `start` would bail, so inline the// same transition.+ #[cfg(target_os = "linux")]+ if this.recording_generation != restart_generation || this.phase != Phase::Starting+ {+ return;+ }+ #[cfg(target_os = "linux")]+ if this.stop_requested {+ this.finish(cx);+ return;+ }this.phase = Phase::Idle;this.start(config, cx);})@@ -447,7 +1197,171 @@ impl RecordingSession {.detach();}+ #[cfg(windows)]+ fn discard_windows_studio(&mut self, restart: Option<StartConfig>, cx: &mut Context<Self>) {+ let Some(active) = self.active.as_ref() else {+ return;+ };+ let Some(future) = active.windows_studio_delete_handle() else {+ return;+ };+ let directory = active.project_dir.clone();+ let generation = self.recording_generation;+ let phase = self.phase;+ self.storage_monitor = None;+ self.phase = Phase::Stopping;+ cx.notify();+ let task = gpui_tokio::Tokio::spawn(cx, future);+ cx.spawn(async move |this, cx| {+ let result = task.await;+ this.update(cx, |this, cx| {+ if this.recording_generation != generation+ || this.phase != Phase::Stopping+ || this+ .active+ .as_ref()+ .is_none_or(|active| active.project_dir != directory)+ {+ return;+ }+ match result {+ Ok((true, Ok(_))) => {+ this.active = None;+ this.finish(cx);+ if let Some(config) = restart {+ this.start(config, cx);+ }+ }+ result => {+ this.phase = phase;+ this.error = Some(match result {+ Ok((_, Err(error))) => format!(+ "{error:#}; discard/restart stopped, local recording retained"+ ),+ Err(error) => format!(+ "Studio discard task failed: {error}; cleanup is unconfirmed"+ ),+ _ => {+ "Studio discard stop was not acknowledged; local recording retained"+ .into()+ }+ });+ cx.notify();+ }+ }+ })+ .ok();+ })+ .detach();+ }++ #[cfg(target_os = "linux")]+ fn discard_instant(&mut self, restart: Option<StartConfig>, cx: &mut Context<Self>) {+ let Some(active) = self.active.as_ref() else {+ return;+ };+ let Some(future) = active.instant_delete_handle() else {+ return;+ };+ let owner = self.recording_owner().unwrap();+ self.terminal_operation = self.terminal_operation.wrapping_add(1);+ let operation = self.terminal_operation;+ let ticket = TerminalTicket {+ owner: owner.clone(),+ operation,+ };+ self.storage_monitor = None;+ self.failure_monitor = None;+ self.clean_control.invalidate();+ self.phase = Phase::Stopping;+ self.stop_requested = false;+ let settle = restart.is_some() && crate::app_windows::clean_capture_active(cx);+ cx.notify();+ let task = gpui_tokio::Tokio::spawn(cx, future);+ cx.spawn(async move |this, cx| {+ let result = task.await;+ let continue_restart = this.update(cx, |this, cx| {+ if !ticket.is_current(this.phase, this.recording_generation, this.terminal_operation, this.recording_owner().as_ref(), true) { return false; }+ match result {+ Ok((true, Ok(_))) => {+ this.active = None;+ if restart.is_some() && !this.stop_requested { true } else { this.finish(cx); false }+ }+ Ok((true, Err(error))) => {+ this.active = None;+ this.error = Some(format!("{error:#}. Failed recording files were preserved."));+ this.finish(cx);+ false+ }+ result => {+ this.phase = Phase::Recording { paused: false };+ this.clean_control.uncertain = true;+ this.error = Some(match result {+ Ok((_, Err(error))) => format!("{error:#}. Cleanup is unconfirmed; retry Stop."),+ Err(error) => format!("Cancel task failed: {error}. Cleanup is unconfirmed; retry Stop."),+ _ => "Capture cleanup is unconfirmed; retry Stop.".into(),+ });+ cx.notify();+ false+ }+ }+ }).unwrap_or(false);+ if !continue_restart { return; }+ if settle {+ let visibility = cx.update(|cx| crate::app_windows::hide_clean_capture_main(cx)+ .map(|visibility| gpui_tokio::Tokio::spawn(cx, visibility)));+ let result = match visibility {+ Ok(task) => task.await.map_err(anyhow::Error::from).and_then(|result| result),+ Err(error) => Err(error),+ };+ if let Err(error) = result {+ this.update(cx, |this, cx| {+ if ticket.is_current(this.phase, this.recording_generation, this.terminal_operation, None, false) && this.active.is_none() {+ this.error = Some(format!("Restart could not hide Cap windows: {error}"));+ this.finish(cx);+ }+ }).ok();+ return;+ }+ cx.background_executor().timer(Duration::from_millis(150)).await;+ }+ this.update(cx, |this, cx| {+ if !ticket.is_current(this.phase, this.recording_generation, this.terminal_operation, None, false) || this.active.is_some() { return; }+ if this.stop_requested { this.finish(cx); return; }+ if !this.instant_cleanup_safe() { this.finish(cx); return; }+ this.phase = Phase::Idle;+ this.start(restart.unwrap(), cx);+ }).ok();+ }).detach();+ }+fn finish(&mut self, cx: &mut Context<Self>) {+ #[cfg(target_os = "linux")]+ if !self.instant_cleanup_safe() {+ self.clean_control.uncertain = true;+ self.error = Some("Capture cleanup is unconfirmed. Local files are preserved; use Ctrl+Shift+F9 to retry Stop.".into());+ self.phase = if self.active.is_some() {+ Phase::Recording { paused: false }+ } else {+ Phase::Starting+ };+ cx.notify();+ return;+ }+ #[cfg(target_os = "linux")]+ {+ self.stop_requested = false;+ self.clean_control.invalidate();+ self.clean_control.uncertain = false;+ self.show_controls_after_pause = false;+ self.failure_monitor = None;+ self.pipeline_failed = false;+ }+ #[cfg(windows)]+ {+ self.failure_monitor = None;+ self.pipeline_failed = false;+ }self.storage_monitor = None;self.phase = Phase::Idle;self.mic_muted = false;@@ -459,3 +1373,466 @@ impl RecordingSession {cx.notify();}}++#[cfg(any(target_os = "linux", windows, test))]+fn recording_failure_is_current(phase: Phase, current: u64, completed: u64) -> bool {+ current == completed && matches!(phase, Phase::Recording { .. })+}++#[cfg(target_os = "linux")]+fn clean_capture_stop_must_wait(phase: Phase, transition: Option<CleanControlKind>) -> bool {+ phase == Phase::Starting || transition == Some(CleanControlKind::Pause)+}++#[cfg(target_os = "linux")]+fn clean_capture_controls_can_reveal(+ mode: Option<crate::recording::RecordingMode>,+ phase: Phase,+ paused_acknowledged: bool,+) -> bool {+ mode == Some(crate::recording::RecordingMode::Studio)+ && phase == (Phase::Recording { paused: true })+ && paused_acknowledged+}++#[cfg(all(test, target_os = "linux"))]+mod clean_capture_tests {+ use super::*;++ #[tokio::test]+ async fn resume_waits_for_visibility_before_polling_capture_control() {+ let (send, receive) = flume::bounded::<()>(1);+ let polled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let observed = polled.clone();+ let visibility = Box::pin(async move {+ receive.recv_async().await?;+ Ok(())+ });+ let control = async move {+ observed.store(true, std::sync::atomic::Ordering::SeqCst);+ Ok(())+ };+ let mut pending = Box::pin(after_clean_visibility(Some(visibility), control));+ assert!(futures_util::poll!(&mut pending).is_pending());+ assert!(!polled.load(std::sync::atomic::Ordering::SeqCst));+ send.send(()).unwrap();+ pending.await.unwrap();+ assert!(polled.load(std::sync::atomic::Ordering::SeqCst));+ }++ #[tokio::test]+ async fn failed_visibility_never_resumes_capture() {+ let visibility = Box::pin(async { anyhow::bail!("unmap not acknowledged") });+ let control = async { Err(anyhow::anyhow!("capture control must not be polled")) };+ assert_eq!(+ after_clean_visibility(Some(visibility), control)+ .await+ .unwrap_err()+ .to_string(),+ "unmap not acknowledged"+ );+ }++ #[test]+ fn instant_pause_never_authorizes_mapping_recording_controls() {+ for paused_acknowledged in [false, true] {+ for phase in [+ Phase::Idle,+ Phase::Starting,+ Phase::Recording { paused: false },+ Phase::Recording { paused: true },+ Phase::Stopping,+ ] {+ assert!(!clean_capture_controls_can_reveal(+ Some(crate::recording::RecordingMode::Instant),+ phase,+ paused_acknowledged,+ ));+ assert_eq!(+ clean_capture_controls_can_reveal(+ Some(crate::recording::RecordingMode::Studio),+ phase,+ paused_acknowledged,+ ),+ phase == (Phase::Recording { paused: true }) && paused_acknowledged,+ );+ }+ }+ }++ #[test]+ fn recording_failure_targets_only_the_current_recording() {+ for paused in [false, true] {+ assert!(recording_failure_is_current(+ Phase::Recording { paused },+ 2,+ 2+ ));+ assert!(!recording_failure_is_current(+ Phase::Recording { paused },+ 2,+ 1+ ));+ }+ }++ #[test]+ fn recording_failure_does_not_repeat_stop_or_interrupt_restart() {+ for phase in [Phase::Idle, Phase::Starting, Phase::Stopping] {+ assert!(!recording_failure_is_current(phase, 2, 2));+ }+ }++ #[test]+ fn stop_waits_only_for_start_and_pause_acknowledgement() {+ assert!(clean_capture_stop_must_wait(Phase::Starting, None));+ for paused in [true, false] {+ let phase = Phase::Recording { paused };+ assert!(clean_capture_stop_must_wait(+ phase,+ Some(CleanControlKind::Pause)+ ));+ for kind in [+ None,+ Some(CleanControlKind::Resume),+ Some(CleanControlKind::VerifyPaused),+ ] {+ assert!(!clean_capture_stop_must_wait(phase, kind));+ }+ }+ }+ fn owner(generation: u64, project: &str) -> RecordingOwner {+ RecordingOwner {+ generation,+ project_dir: project.into(),+ }+ }++ #[tokio::test]+ async fn pause_only_reveals_after_the_same_actor_acknowledges_paused() {+ let owner = owner(1, "recording-a");+ let mut state = CleanControlState::default();+ let (ticket, registration) = state.begin(owner.clone(), CleanControlKind::Pause);+ let (queried_tx, queried_rx) = tokio::sync::oneshot::channel();+ let (ack_tx, ack_rx) = tokio::sync::oneshot::channel();+ let mut task = tokio::spawn(futures_util::future::Abortable::new(+ run_clean_control(+ CleanControlKind::Pause,+ async { Ok(()) },+ async {+ queried_tx.send(()).unwrap();+ Ok(ack_rx.await.unwrap())+ },+ async {},+ ),+ registration,+ ));+ queried_rx.await.unwrap();+ assert!(!state.paused_for(Some(&owner)));+ assert!(clean_capture_stop_must_wait(+ Phase::Recording { paused: false },+ state.pending_kind()+ ));+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut task)+ .await+ .is_err()+ );+ ack_tx.send(true).unwrap();+ let outcome = task.await.unwrap().unwrap();+ assert!(outcome.error.is_none());+ assert!(state.complete(+ &ticket,+ Some(&owner),+ Phase::Recording { paused: false },+ &outcome+ ));+ assert!(state.paused_for(Some(&owner)));+ }++ #[tokio::test]+ async fn failed_resume_or_pause_requires_true_paused_acknowledgement() {+ for kind in [CleanControlKind::Resume, CleanControlKind::Pause] {+ for acknowledged in [true, false] {+ let outcome = run_clean_control(+ kind,+ async { anyhow::bail!("setup or teardown failed") },+ async { Ok(acknowledged) },+ async {},+ )+ .await;+ assert!(outcome.error.is_some());+ assert_eq!(outcome.paused, acknowledged.then_some(true));+ let owner = owner(1, "recording-a");+ let mut state = CleanControlState::default();+ let (ticket, _) = state.begin(owner.clone(), kind);+ assert!(state.complete(+ &ticket,+ Some(&owner),+ Phase::Recording { paused: true },+ &outcome+ ));+ assert_eq!(state.paused_for(Some(&owner)), acknowledged);+ assert_eq!(state.uncertain, !acknowledged);+ }+ }+ }++ #[tokio::test]+ async fn actor_transport_error_never_confirms_a_safe_pause() {+ let outcome = run_clean_control(+ CleanControlKind::Pause,+ async { Ok(()) },+ async { anyhow::bail!("actor stopped") },+ async {},+ )+ .await;+ assert_eq!(outcome.paused, None);+ assert!(outcome.error.unwrap().contains("actor stopped"));+ }++ #[tokio::test]+ async fn stop_interrupts_a_blocked_resume_without_waiting_for_control_completion() {+ struct Dropped(std::sync::Arc<std::sync::atomic::AtomicBool>);+ impl Drop for Dropped {+ fn drop(&mut self) {+ self.0.store(true, std::sync::atomic::Ordering::Release);+ }+ }+ let owner = owner(2, "recording-b");+ let mut state = CleanControlState::default();+ let (ticket, registration) = state.begin(owner.clone(), CleanControlKind::Resume);+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ let dropped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let control_dropped = dropped.clone();+ let task = tokio::spawn(futures_util::future::Abortable::new(+ run_clean_control(+ CleanControlKind::Resume,+ async move {+ let _guard = Dropped(control_dropped);+ started_tx.send(()).unwrap();+ std::future::pending::<anyhow::Result<()>>().await+ },+ async { panic!("A cancelled resume must not query state") },+ async {},+ ),+ registration,+ ));+ started_rx.await.unwrap();+ assert!(!clean_capture_stop_must_wait(+ Phase::Recording { paused: true },+ state.pending_kind()+ ));+ state.invalidate();+ let (stop_tx, stop_rx) = tokio::sync::oneshot::channel();+ let stopping = tokio::spawn(async move {+ stop_tx.send(()).unwrap();+ });+ tokio::time::timeout(Duration::from_secs(1), stop_rx)+ .await+ .unwrap()+ .unwrap();+ stopping.await.unwrap();+ assert!(task.await.unwrap().is_err());+ assert!(dropped.load(std::sync::atomic::Ordering::Acquire));+ assert!(!state.complete(+ &ticket,+ Some(&owner),+ Phase::Stopping,+ &CleanControlOutcome {+ paused: Some(true),+ error: None+ }+ ));+ }++ #[tokio::test]+ async fn stop_during_hidden_window_settle_never_dispatches_resume() {+ let owner = owner(1, "recording-a");+ let mut state = CleanControlState::default();+ let (_, registration) = state.begin(owner, CleanControlKind::Resume);+ let (settled_tx, settled_rx) = tokio::sync::oneshot::channel();+ let dispatched = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let called = dispatched.clone();+ let task = tokio::spawn(futures_util::future::Abortable::new(+ run_clean_control(+ CleanControlKind::Resume,+ async move {+ called.store(true, std::sync::atomic::Ordering::Release);+ Ok(())+ },+ async { Ok(false) },+ async {+ settled_tx.send(()).unwrap();+ std::future::pending::<()>().await;+ },+ ),+ registration,+ ));+ settled_rx.await.unwrap();+ state.invalidate();+ assert!(task.await.unwrap().is_err());+ assert!(!dispatched.load(std::sync::atomic::Ordering::Acquire));+ }++ #[tokio::test]+ async fn queued_control_completion_cannot_clear_a_newer_recording_or_operation() {+ for next_owner in [+ owner(1, "recording-a"),+ owner(2, "recording-a"),+ owner(1, "recording-b"),+ ] {+ let prior = owner(1, "recording-a");+ let mut state = CleanControlState::default();+ let (ticket, _) = state.begin(prior, CleanControlKind::Pause);+ let outcome = run_clean_control(+ CleanControlKind::Pause,+ async { Ok(()) },+ async { Ok(true) },+ async {},+ )+ .await;+ let (next_ticket, _) = state.begin(next_owner.clone(), CleanControlKind::Resume);+ assert!(!state.complete(+ &ticket,+ Some(&next_owner),+ Phase::Recording { paused: true },+ &outcome+ ));+ assert_eq!(state.pending.as_ref().unwrap().ticket, next_ticket);+ assert!(!state.paused_for(Some(&next_owner)));+ }+ }++ #[tokio::test]+ async fn successful_resume_requires_nonpaused_ack_and_never_authorizes_main() {+ let outcome = run_clean_control(+ CleanControlKind::Resume,+ async { Ok(()) },+ async { Ok(false) },+ async {},+ )+ .await;+ assert_eq!(outcome.paused, Some(false));+ assert!(outcome.error.is_none());+ let owner = owner(1, "recording-a");+ let mut state = CleanControlState::default();+ let (ticket, _) = state.begin(owner.clone(), CleanControlKind::Resume);+ assert!(state.complete(+ &ticket,+ Some(&owner),+ Phase::Recording { paused: true },+ &outcome+ ));+ assert!(!state.paused_for(Some(&owner)));+ assert!(!state.uncertain);+ }+ #[tokio::test]+ async fn missing_paused_acknowledgement_times_out_without_authorizing_main() {+ let outcome = run_clean_control(+ CleanControlKind::Pause,+ async { Ok(()) },+ std::future::pending::<anyhow::Result<bool>>(),+ async {},+ )+ .await;+ assert_eq!(outcome.paused, None);+ assert!(outcome.error.unwrap().contains("Timed out"));+ }+}++#[cfg(all(test, target_os = "linux"))]+mod instant_terminal_tests {+ use super::*;++ fn owner(generation: u64, directory: &str) -> RecordingOwner {+ RecordingOwner {+ generation,+ project_dir: directory.into(),+ }+ }++ #[tokio::test]+ async fn late_stop_completion_cannot_release_a_retry_or_new_recording() {+ let original = owner(3, "original.cap");+ let ticket = TerminalTicket {+ owner: original.clone(),+ operation: 1,+ };+ let (complete, completed) = tokio::sync::oneshot::channel();+ let operation = async {+ completed.await.unwrap();+ ticket+ };+ tokio::pin!(operation);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut operation)+ .await+ .is_err()+ );+ complete.send(()).unwrap();+ let ticket = operation.await;+ assert!(!ticket.is_current(Phase::Stopping, 3, 2, Some(&original), true));+ assert!(!ticket.is_current(Phase::Stopping, 4, 1, Some(&owner(4, "next.cap")), true));+ assert!(!ticket.is_current(+ Phase::Stopping,+ 3,+ 1,+ Some(&owner(3, "different.cap")),+ true+ ));+ assert!(ticket.is_current(Phase::Stopping, 3, 1, Some(&original), true));+ }++ #[tokio::test]+ async fn restart_settle_completion_cannot_override_stop_or_later_generation() {+ let ticket = TerminalTicket {+ owner: owner(8, "prior.cap"),+ operation: 5,+ };+ let (release, wait) = tokio::sync::oneshot::channel();+ let settle = async {+ wait.await.unwrap();+ ticket+ };+ tokio::pin!(settle);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut settle)+ .await+ .is_err()+ );+ release.send(()).unwrap();+ let ticket = settle.await;+ assert!(!ticket.is_current(Phase::Idle, 8, 5, None, false));+ assert!(!ticket.is_current(Phase::Starting, 9, 5, None, false));+ assert!(ticket.is_current(Phase::Stopping, 8, 5, None, false));+ }+}++#[cfg(all(test, windows))]+mod windows_recording_failure_tests {+ use super::*;++ #[test]+ fn only_current_recording_failure_can_request_stop() {+ for paused in [false, true] {+ assert!(recording_failure_is_current(+ Phase::Recording { paused },+ 4,+ 4+ ));+ assert!(!recording_failure_is_current(+ Phase::Recording { paused },+ 5,+ 4+ ));+ }+ }++ #[test]+ fn late_failure_does_not_interrupt_start_stop_or_idle() {+ for phase in [Phase::Idle, Phase::Starting, Phase::Stopping] {+ assert!(!recording_failure_is_current(phase, 4, 4));+ }+ }+}diff --git a/apps/desktop-gpui/src/single_instance.rs b/apps/desktop-gpui/src/single_instance.rsindex 1b566df39..f4f79af41 100644--- a/apps/desktop-gpui/src/single_instance.rs+++ b/apps/desktop-gpui/src/single_instance.rs@@ -1,33 +1,9 @@-//! New-instance-wins single instancing.-//!-//! The app lives in the tray: closing the main window hides it, the process-//! stays. Without a guard, a `cargo run` after an edit launches a second-//! instance next to the stale one, and the tray icon and level-100 window the-//! user is looking at may still belong to the *old* build -- which reads as-//! "my change only applied on the second run". The Tauri app's single-instance-//! plugin keeps the old instance and exits the new one; for a parallel-//! implementation that is mostly launched to see fresh code, the useful-//! polarity is the reverse: the new instance terminates the old one and takes-//! over. A capture killed this way lands in the bundle's `InProgress` /-//! `NeedsRemux` recovery path rather than being lost.-//!-//! The pidfile lives in [`crate::store::app_data_dir`], so a harness run-//! pointed at a `CAP_GPUI_APP_DATA_DIR` sandbox never kills the dev app.-//!-//! Deep links need no forwarding under this polarity. The Tauri plugin's-//! callback relays a second launch's `cap-desktop://` argv to the surviving-//! old instance (`src-tauri/src/lib.rs:5193-5204`); here the launch that-//! carries the URL *is* the survivor, and [`crate::deeplink::init`] reads its-//! own argv. A URL opened while the app is already running never launches a-//! second instance on macOS at all -- the GURL AppleEvent goes straight to-//! the running process (`crate::platform::install_url_scheme_handler`).-use std::path::{Path, PathBuf};#[cfg(windows)]static INSTANCE_MUTEX: std::sync::OnceLock<usize> = std::sync::OnceLock::new();-#[cfg(any(windows, target_os = "macos", test))]+#[cfg(any(windows, target_os = "macos", target_os = "linux", test))]const MAX_FORWARDED_DEEP_LINK_BYTES: usize = 1024 * 1024;#[cfg(any(windows, target_os = "macos", test))]@@ -53,20 +29,35 @@ pub fn acquire() {&& pid != std::process::id() as i32&& is_cap_gpui(pid){- tracing::info!(pid, "terminating the previous instance");- unsafe {- libc::kill(pid, libc::SIGTERM);- }- for _ in 0..40 {- if unsafe { libc::kill(pid, 0) } != 0 {- break;+ #[cfg(target_os = "linux")]+ {+ match forward_linux_reopen(&path, pid as u32) {+ Ok(()) => tracing::info!(pid, "Requested the existing Cap GPUI controls"),+ Err(error) => tracing::warn!(+ pid,+ %error,+ "Could not reopen Cap GPUI; the existing instance remains unchanged"+ ),}- std::thread::sleep(std::time::Duration::from_millis(50));+ std::process::exit(0);}- if unsafe { libc::kill(pid, 0) } == 0 {- tracing::warn!(pid, "previous instance ignored SIGTERM; killing it");+ #[cfg(not(target_os = "linux"))]+ {+ tracing::info!(pid, "terminating the previous instance");unsafe {- libc::kill(pid, libc::SIGKILL);+ libc::kill(pid, libc::SIGTERM);+ }+ for _ in 0..40 {+ if unsafe { libc::kill(pid, 0) } != 0 {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ if unsafe { libc::kill(pid, 0) } == 0 {+ tracing::warn!(pid, "previous instance ignored SIGTERM; killing it");+ unsafe {+ libc::kill(pid, libc::SIGKILL);+ }}}}@@ -77,6 +68,12 @@ pub fn acquire() {tracing::warn!(%error, "could not write the instance pidfile");}+ #[cfg(target_os = "linux")]+ if let Err(error) = start_linux_reopen(&path) {+ tracing::error!(%error, "could not start Cap GPUI activation");+ std::process::exit(1);+ }+#[cfg(target_os = "macos")]if let Err(error) = start_deep_link_forwarding(&path) {tracing::error!(%error, "could not start Cap GPUI deep-link forwarding");@@ -88,6 +85,7 @@ pub fn acquire() {/// binary. Linux zombies retain their comm name but lose their exe link.#[cfg(unix)]fn is_cap_gpui(pid: i32) -> bool {+ #[cfg(not(target_os = "linux"))]if unsafe { libc::kill(pid, 0) } != 0 {return false;}@@ -121,6 +119,391 @@ fn is_cap_gpui_image(path: &Path) -> bool {name.eq_ignore_ascii_case(IMAGE_NAME)}+#[cfg(target_os = "linux")]+const LINUX_REOPEN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);++#[cfg(target_os = "linux")]+const MAX_LINUX_REOPEN_ACTIONS: usize = 32;++#[cfg(target_os = "linux")]+type LinuxReopenActions = Vec<crate::deeplink::DeepLinkAction>;++#[cfg(target_os = "linux")]+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+struct LinuxInstanceIdentity {+ pid: u32,+ started: u64,+ boot: [u8; 36],+}++#[cfg(target_os = "linux")]+fn linux_instance_identity(pid: u32) -> std::io::Result<LinuxInstanceIdentity> {+ let stat = std::fs::read_to_string(format!("/proc/{pid}/stat"))?;+ let fields = stat+ .rsplit_once(") ")+ .map(|(_, fields)| fields.split_whitespace().collect::<Vec<_>>())+ .ok_or_else(|| std::io::Error::other("Invalid instance process identity"))?;+ if fields+ .first()+ .is_none_or(|state| matches!(*state, "Z" | "X"))+ {+ return Err(std::io::Error::other("The instance is no longer running"));+ }+ let started = fields+ .get(19)+ .and_then(|value| value.parse().ok())+ .ok_or_else(|| std::io::Error::other("Invalid instance start identity"))?;+ let boot = std::fs::read_to_string("/proc/sys/kernel/random/boot_id")?;+ let boot = boot+ .trim()+ .as_bytes()+ .try_into()+ .map_err(|_| std::io::Error::other("Invalid boot identity"))?;+ Ok(LinuxInstanceIdentity { pid, started, boot })+}++#[cfg(target_os = "linux")]+fn linux_reopen_address(+ path: &Path,+ owner: LinuxInstanceIdentity,+) -> std::io::Result<std::os::unix::net::SocketAddr> {+ use std::{+ hash::{Hash, Hasher},+ os::linux::net::SocketAddrExt,+ };+ let directory = path+ .parent()+ .ok_or_else(|| std::io::Error::other("The instance directory is missing"))?+ .canonicalize()?;+ let mut scope = std::collections::hash_map::DefaultHasher::new();+ directory.hash(&mut scope);+ owner.hash(&mut scope);+ for name in [+ "XDG_RUNTIME_DIR",+ "XDG_SESSION_ID",+ "DBUS_SESSION_BUS_ADDRESS",+ "WAYLAND_DISPLAY",+ "DISPLAY",+ ] {+ std::env::var_os(name).hash(&mut scope);+ }+ std::os::unix::net::SocketAddr::from_abstract_name(format!(+ "cap-gpui-reopen-{:016x}",+ scope.finish()+ ))+}++#[cfg(target_os = "linux")]+fn linux_reopen_payload(owner: LinuxInstanceIdentity) -> [u8; 56] {+ let mut bytes = [0; 56];+ bytes[..8].copy_from_slice(b"CAPREOP1");+ bytes[8..12].copy_from_slice(&owner.pid.to_be_bytes());+ bytes[12..20].copy_from_slice(&owner.started.to_be_bytes());+ bytes[20..].copy_from_slice(&owner.boot);+ bytes+}++#[cfg(target_os = "linux")]+fn write_linux_reopen_actions(+ writer: &mut impl std::io::Write,+ owner: LinuxInstanceIdentity,+ actions: &[u8],+) -> std::io::Result<()> {+ if actions.len() > MAX_FORWARDED_DEEP_LINK_BYTES {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "Too many forwarded Cap action bytes",+ ));+ }+ let mut header = linux_reopen_payload(owner);+ if !actions.is_empty() {+ header[..8].copy_from_slice(b"CAPREOP2");+ }+ writer.write_all(&header)?;+ if !actions.is_empty() {+ writer.write_all(&(actions.len() as u32).to_be_bytes())?;+ writer.write_all(actions)?;+ }+ Ok(())+}++#[cfg(target_os = "linux")]+fn parse_linux_reopen_action(raw: &str) -> std::io::Result<crate::deeplink::DeepLinkAction> {+ let invalid = || {+ std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "Invalid forwarded Cap action URL",+ )+ };+ if raw.len() > MAX_FORWARDED_DEEP_LINK_BYTES+ || !(raw.starts_with("cap-desktop://") || raw.starts_with("cap://"))+ {+ return Err(invalid());+ }+ let url = reqwest::Url::parse(raw).map_err(|_| invalid())?;+ crate::deeplink::DeepLinkAction::try_from(&url).map_err(|_| invalid())+}++#[cfg(target_os = "linux")]+fn linux_reopen_action_payload(+ arguments: impl IntoIterator<Item = String>,+) -> std::io::Result<Vec<u8>> {+ let mut payload = Vec::new();+ for (count, argument) in arguments+ .into_iter()+ .filter(|argument| parse_linux_reopen_action(argument).is_ok())+ .enumerate()+ {+ if count == MAX_LINUX_REOPEN_ACTIONS+ || argument.len() > MAX_FORWARDED_DEEP_LINK_BYTES.saturating_sub(payload.len() + 4)+ {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "Too many forwarded Cap actions",+ ));+ }+ payload.extend_from_slice(&(argument.len() as u32).to_be_bytes());+ payload.extend_from_slice(argument.as_bytes());+ }+ Ok(payload)+}++#[cfg(target_os = "linux")]+fn read_linux_reopen_actions(+ reader: &mut impl std::io::Read,+ owner: LinuxInstanceIdentity,+) -> std::io::Result<LinuxReopenActions> {+ let invalid = || {+ std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "Invalid forwarded Cap action payload",+ )+ };+ let mut request = [0; 56];+ reader.read_exact(&mut request)?;+ let mut header = linux_reopen_payload(owner);+ if request == header {+ return Ok(Vec::new());+ }+ header[..8].copy_from_slice(b"CAPREOP2");+ if request != header {+ return Err(std::io::Error::new(+ std::io::ErrorKind::PermissionDenied,+ "The activation request belongs to another instance",+ ));+ }+ let mut size = [0; 4];+ reader.read_exact(&mut size)?;+ let size = u32::from_be_bytes(size) as usize;+ if size > MAX_FORWARDED_DEEP_LINK_BYTES {+ return Err(invalid());+ }+ let mut payload = vec![0; size];+ reader.read_exact(&mut payload)?;+ let mut remaining = payload.as_slice();+ let mut actions = Vec::new();+ while !remaining.is_empty() {+ if actions.len() == MAX_LINUX_REOPEN_ACTIONS {+ return Err(invalid());+ }+ let (size, rest) = remaining.split_first_chunk::<4>().ok_or_else(invalid)?;+ let (raw, rest) = rest+ .split_at_checked(u32::from_be_bytes(*size) as usize)+ .ok_or_else(invalid)?;+ let raw = std::str::from_utf8(raw).map_err(|_| invalid())?;+ actions.push(parse_linux_reopen_action(raw)?);+ remaining = rest;+ }+ Ok(actions)+}++#[cfg(target_os = "linux")]+fn linux_peer(stream: &std::os::unix::net::UnixStream) -> std::io::Result<libc::ucred> {+ use std::os::fd::AsRawFd;+ let mut credentials: libc::ucred = unsafe { std::mem::zeroed() };+ let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;+ let result = unsafe {+ libc::getsockopt(+ stream.as_raw_fd(),+ libc::SOL_SOCKET,+ libc::SO_PEERCRED,+ std::ptr::addr_of_mut!(credentials).cast(),+ std::ptr::addr_of_mut!(length),+ )+ };+ if result != 0 {+ return Err(std::io::Error::last_os_error());+ }+ if length as usize != std::mem::size_of::<libc::ucred>()+ || credentials.uid != unsafe { libc::geteuid() }+ || credentials.pid <= 0+ {+ return Err(std::io::Error::new(+ std::io::ErrorKind::PermissionDenied,+ "The activation peer is not in this user session",+ ));+ }+ Ok(credentials)+}++#[cfg(target_os = "linux")]+fn linux_reopen_channel() -> &'static (+ flume::Sender<LinuxReopenActions>,+ flume::Receiver<LinuxReopenActions>,+) {+ static CHANNEL: std::sync::OnceLock<(+ flume::Sender<LinuxReopenActions>,+ flume::Receiver<LinuxReopenActions>,+ )> = std::sync::OnceLock::new();+ CHANNEL.get_or_init(|| flume::bounded(1))+}++#[cfg(target_os = "linux")]+fn receive_linux_reopen(+ stream: &mut std::os::unix::net::UnixStream,+ owner: LinuxInstanceIdentity,+ requests: &flume::Sender<LinuxReopenActions>,+) -> std::io::Result<()> {+ use std::io::Write;+ stream.set_read_timeout(Some(std::time::Duration::from_millis(250)))?;+ stream.set_write_timeout(Some(std::time::Duration::from_millis(250)))?;+ linux_peer(stream)?;+ let actions = read_linux_reopen_actions(stream, owner)?;+ match requests.try_send(actions) {+ Ok(()) => {}+ Err(flume::TrySendError::Full(actions)) if actions.is_empty() => {}+ Err(flume::TrySendError::Full(actions)) => {+ requests+ .send_timeout(actions, std::time::Duration::from_millis(250))+ .map_err(|_| std::io::Error::other("The activation queue is busy"))?;+ }+ Err(flume::TrySendError::Disconnected(_)) => {+ return Err(std::io::Error::other("The activation handler has closed"));+ }+ }+ stream.write_all(&[1])+}++#[cfg(target_os = "linux")]+fn start_linux_reopen(path: &Path) -> std::io::Result<()> {+ let owner = linux_instance_identity(std::process::id())?;+ let address = linux_reopen_address(path, owner)?;+ let listener = std::os::unix::net::UnixListener::bind_addr(&address)?;+ let requests = linux_reopen_channel().0.clone();+ std::thread::Builder::new()+ .name("cap-gpui-activation".into())+ .spawn(move || {+ for connection in listener.incoming() {+ let result = connection+ .and_then(|mut stream| receive_linux_reopen(&mut stream, owner, &requests));+ if let Err(error) = result {+ tracing::warn!(%error, "Rejected a Cap GPUI activation request");+ }+ }+ })?;+ Ok(())+}++#[cfg(target_os = "linux")]+fn send_linux_reopen(+ address: std::os::unix::net::SocketAddr,+ owner: LinuxInstanceIdentity,+ actions: &[u8],+) -> std::io::Result<()> {+ use std::io::Read;+ let started = std::time::Instant::now();+ let mut stream = loop {+ if linux_instance_identity(owner.pid)? != owner {+ return Err(std::io::Error::other("The activation owner changed"));+ }+ match std::os::unix::net::UnixStream::connect_addr(&address) {+ Ok(stream) => break stream,+ Err(error)+ if matches!(+ error.kind(),+ std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::NotFound+ ) && started.elapsed() < std::time::Duration::from_secs(1) =>+ {+ std::thread::sleep(std::time::Duration::from_millis(25));+ }+ Err(error) => return Err(error),+ }+ };+ stream.set_read_timeout(Some(std::time::Duration::from_millis(500)))?;+ stream.set_write_timeout(Some(std::time::Duration::from_millis(500)))?;+ if linux_peer(&stream)?.pid as u32 != owner.pid {+ return Err(std::io::Error::new(+ std::io::ErrorKind::PermissionDenied,+ "The activation socket belongs to another process",+ ));+ }+ write_linux_reopen_actions(&mut stream, owner, actions)?;+ let mut reply = [0];+ stream.read_exact(&mut reply)?;+ if reply != [1] || linux_instance_identity(owner.pid)? != owner {+ return Err(std::io::Error::other(+ "The activation owner did not acknowledge the request",+ ));+ }+ Ok(())+}++#[cfg(target_os = "linux")]+fn forward_linux_reopen(path: &Path, pid: u32) -> std::io::Result<()> {+ let actions = linux_reopen_action_payload(std::env::args().skip(1))?;+ let owner = linux_instance_identity(pid)?;+ let address = linux_reopen_address(path, owner)?;+ let (send, receive) = std::sync::mpsc::sync_channel(1);+ std::thread::Builder::new()+ .name("cap-gpui-reopen-request".into())+ .spawn(move || {+ let _ = send.send(send_linux_reopen(address, owner, &actions));+ })?;+ receive.recv_timeout(LINUX_REOPEN_TIMEOUT).map_err(|_| {+ std::io::Error::new(+ std::io::ErrorKind::TimedOut,+ "The activation request timed out",+ )+ })?+}++#[cfg(target_os = "linux")]+fn linux_reopen_allowed(+ phase: crate::session::Phase,+ mode: Option<crate::recording::RecordingMode>,+ cleanup_safe: bool,+) -> bool {+ cleanup_safe+ && (phase == crate::session::Phase::Idle+ || (matches!(phase, crate::session::Phase::Recording { .. })+ && mode == Some(crate::recording::RecordingMode::Studio)))+}++#[cfg(target_os = "linux")]+pub fn init_linux_reopen(cx: &mut gpui::App) {+ let requests = linux_reopen_channel().1.clone();+ cx.spawn(async move |cx| {+ while let Ok(actions) = requests.recv_async().await {+ cx.update(|cx| {+ if !actions.is_empty() {+ for action in actions {+ crate::deeplink::submit_action(action);+ }+ return;+ }+ let session = crate::session::RecordingSession::global(cx);+ let current = session.read(cx);+ if linux_reopen_allowed(current.phase, current.mode(), current.instant_cleanup_safe()) {+ crate::app_windows::show_main_window(cx);+ } else {+ tracing::info!("Cap controls remain hidden while recording is changing state or cannot pause");+ }+ });+ }+ })+ .detach();+}+#[cfg(windows)]fn acquire_windows_instance(path: &Path) {use std::hash::{Hash, Hasher};@@ -510,6 +893,164 @@ mod tests {assert!(!super::is_cap_gpui(std::process::id() as i32));}+ #[cfg(target_os = "linux")]+ #[test]+ fn linux_acquire_child_probe() {+ if std::env::var_os("CAP_GPUI_ACQUIRE_CHILD_PROBE").is_none() {+ return;+ }+ super::acquire();+ let marker = crate::store::app_data_dir().join("acquire-returned");+ std::fs::write(marker, std::process::id().to_string()).unwrap();+ }++ #[cfg(target_os = "linux")]+ pub(super) struct LinuxAcquireFixture {+ directory: std::path::PathBuf,+ pub(super) children: Vec<std::process::Child>,+ }++ #[cfg(target_os = "linux")]+ impl LinuxAcquireFixture {+ pub(super) fn new() -> Self {+ let directory = std::env::temp_dir().join(format!(+ "cap-gpui-acquire-test-{}",+ crate::store::new_uuid_v4()+ ));+ std::fs::create_dir(&directory).unwrap();+ Self {+ directory,+ children: Vec::new(),+ }+ }++ pub(super) fn start_incumbent(&mut self) -> u32 {+ let binary = self.directory.join("cap-gpui");+ std::fs::copy("/bin/sleep", &binary).unwrap();+ let child = std::process::Command::new(&binary)+ .arg("30")+ .spawn()+ .unwrap();+ let pid = child.id();+ self.children.push(child);+ let started = std::time::Instant::now();+ while !std::fs::read_link(format!("/proc/{pid}/exe")).is_ok_and(|path| path == binary) {+ assert!(started.elapsed() < std::time::Duration::from_secs(5));+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ pid+ }++ fn launch_again(&mut self) -> u32 {+ let child = std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "single_instance::tests::linux_acquire_child_probe",+ "--test-threads=1",+ ])+ .env("CAP_GPUI_ACQUIRE_CHILD_PROBE", "1")+ .env("CAP_GPUI_APP_DATA_DIR", &self.directory)+ .stdout(std::process::Stdio::null())+ .spawn()+ .unwrap();+ let pid = child.id();+ self.children.push(child);+ let child = self.children.last_mut().unwrap();+ let started = std::time::Instant::now();+ loop {+ if let Some(status) = child.try_wait().unwrap() {+ assert!(status.success());+ return pid;+ }+ assert!(started.elapsed() < std::time::Duration::from_secs(5));+ std::thread::sleep(std::time::Duration::from_millis(1));+ }+ }+ }++ #[cfg(target_os = "linux")]+ impl Drop for LinuxAcquireFixture {+ fn drop(&mut self) {+ for child in &mut self.children {+ let _ = child.kill();+ let _ = child.wait();+ }+ let _ = std::fs::remove_dir_all(&self.directory);+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn linux_initial_launch_owns_only_its_pidfile() {+ let mut fixture = LinuxAcquireFixture::new();+ let launched = fixture.launch_again().to_string();+ assert_eq!(+ std::fs::read_to_string(fixture.directory.join("cap-gpui.pid")).unwrap(),+ launched,+ );+ assert_eq!(+ std::fs::read_to_string(fixture.directory.join("acquire-returned")).unwrap(),+ launched,+ );+ let mut entries = std::fs::read_dir(&fixture.directory)+ .unwrap()+ .map(|entry| entry.unwrap().file_name().into_string().unwrap())+ .collect::<Vec<_>>();+ entries.sort();+ assert_eq!(entries, ["acquire-returned", "cap-gpui.pid"]);+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn linux_relaunch_preserves_live_and_unlinked_incumbent_pidfile() {+ use std::os::unix::fs::MetadataExt;++ let mut fixture = LinuxAcquireFixture::new();+ let incumbent = fixture.start_incumbent();+ let pidfile = fixture.directory.join("cap-gpui.pid");+ let original = incumbent.to_string();+ std::fs::write(&pidfile, &original).unwrap();+ let before = std::fs::metadata(&pidfile).unwrap();+ for unlinked in [false, true] {+ if unlinked {+ std::fs::remove_file(fixture.directory.join("cap-gpui")).unwrap();+ }+ fixture.launch_again();+ assert!(fixture.children[0].try_wait().unwrap().is_none());+ assert_eq!(std::fs::read_to_string(&pidfile).unwrap(), original);+ let after = std::fs::metadata(&pidfile).unwrap();+ assert_eq!(after.ino(), before.ino());+ assert_eq!(after.mtime(), before.mtime());+ assert_eq!(after.mtime_nsec(), before.mtime_nsec());+ assert_eq!(after.ctime(), before.ctime());+ assert_eq!(after.ctime_nsec(), before.ctime_nsec());+ assert!(!fixture.directory.join("acquire-returned").exists());+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn linux_relaunch_after_dead_or_stale_owner_starts_normally() {+ let mut fixture = LinuxAcquireFixture::new();+ let incumbent = fixture.start_incumbent();+ fixture.children[0].kill().unwrap();+ fixture.children[0].wait().unwrap();+ let pidfile = fixture.directory.join("cap-gpui.pid");+ for stale in [+ incumbent.to_string(),+ "not-a-pid".to_string(),+ "0".to_string(),+ ] {+ std::fs::write(&pidfile, stale).unwrap();+ let launched = fixture.launch_again().to_string();+ assert_eq!(std::fs::read_to_string(&pidfile).unwrap(), launched);+ assert_eq!(+ std::fs::read_to_string(fixture.directory.join("acquire-returned")).unwrap(),+ launched+ );+ }+ }+#[test]fn forwarding_endpoint_requires_a_live_instance_shape() {assert_eq!(@@ -642,3 +1183,362 @@ mod tests {);}}++#[cfg(all(test, target_os = "linux"))]+mod linux_reopen_tests {+ use super::*;+ use crate::deeplink::DeepLinkAction;+ use std::io::{Read, Write};+ use std::os::{+ linux::net::SocketAddrExt,+ unix::net::{UnixListener, UnixStream},+ };++ fn packet(owner: LinuxInstanceIdentity, payload: &[u8]) -> Vec<u8> {+ let mut packet = Vec::new();+ write_linux_reopen_actions(&mut packet, owner, payload).unwrap();+ packet+ }++ fn action_url(action: &DeepLinkAction) -> String {+ reqwest::Url::parse_with_params(+ "cap-desktop://action",+ &[("value", serde_json::to_string(action).unwrap())],+ )+ .unwrap()+ .to_string()+ }++ fn raw_action_payload(raw: &[u8]) -> Vec<u8> {+ let mut payload = (raw.len() as u32).to_be_bytes().to_vec();+ payload.extend_from_slice(raw);+ payload+ }++ #[test]+ fn duplicate_launch_during_startup_is_authenticated_and_coalesced() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let (requests, received) = flume::bounded(1);+ for _ in 0..3 {+ let (mut server, mut client) = UnixStream::pair().unwrap();+ client.write_all(&packet(owner, &[])).unwrap();+ receive_linux_reopen(&mut server, owner, &requests).unwrap();+ let mut reply = [0];+ client.read_exact(&mut reply).unwrap();+ assert_eq!(reply, [1]);+ }+ assert_eq!(received.len(), 1);+ assert!(received.recv().unwrap().is_empty());+ }++ #[test]+ fn plain_relaunch_keeps_its_legacy_frame_and_actions_require_the_new_version() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let plain = packet(owner, &[]);+ assert_eq!(plain, linux_reopen_payload(owner));+ assert!(+ read_linux_reopen_actions(&mut plain.as_slice(), owner)+ .unwrap()+ .is_empty()+ );+ let payload =+ linux_reopen_action_payload([action_url(&DeepLinkAction::StopRecording)]).unwrap();+ let mut framed = packet(owner, &payload);+ assert_eq!(&framed[..8], b"CAPREOP2");+ framed[..8].copy_from_slice(b"CAPREOP3");+ assert_eq!(+ read_linux_reopen_actions(&mut framed.as_slice(), owner)+ .unwrap_err()+ .kind(),+ std::io::ErrorKind::PermissionDenied+ );+ }++ #[test]+ fn client_requires_the_current_owner_acknowledgement() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let address = std::os::unix::net::SocketAddr::from_abstract_name(format!(+ "cap-gpui-owner-ack-{}",+ crate::store::new_uuid_v4()+ ))+ .unwrap();+ let listener = UnixListener::bind_addr(&address).unwrap();+ let (requests, received) = flume::bounded(1);+ let worker = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ receive_linux_reopen(&mut stream, owner, &requests)+ });+ send_linux_reopen(address, owner, &[]).unwrap();+ worker.join().unwrap().unwrap();+ assert!(received.recv().unwrap().is_empty());+ }++ #[test]+ fn editor_and_settings_actions_remain_ordered_until_initialization() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let expected = vec![+ DeepLinkAction::OpenEditor {+ project_path: "/tmp/recording.cap".into(),+ },+ DeepLinkAction::OpenSettings {+ page: Some("general".into()),+ },+ ];+ let payload = linux_reopen_action_payload(expected.iter().map(action_url)).unwrap();+ let (requests, received) = flume::bounded(1);+ let (mut server, mut client) = UnixStream::pair().unwrap();+ client.write_all(&packet(owner, &payload)).unwrap();+ receive_linux_reopen(&mut server, owner, &requests).unwrap();+ let mut reply = [0];+ client.read_exact(&mut reply).unwrap();+ assert_eq!(reply, [1]);+ assert_eq!(received.len(), 1);+ assert_eq!(received.recv().unwrap(), expected);+ }++ #[test]+ fn action_queue_saturation_never_acknowledges_dropped_actions() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let payload =+ linux_reopen_action_payload([action_url(&DeepLinkAction::StopRecording)]).unwrap();+ let (requests, received) = flume::bounded(1);+ requests.send(Vec::new()).unwrap();+ let (mut server, mut client) = UnixStream::pair().unwrap();+ client.write_all(&packet(owner, &payload)).unwrap();+ assert!(receive_linux_reopen(&mut server, owner, &requests).is_err());+ drop(server);+ let mut reply = [0];+ assert!(client.read_exact(&mut reply).is_err());+ assert!(received.recv().unwrap().is_empty());+ assert!(received.is_empty());+ }++ #[test]+ fn action_payload_bounds_apply_before_reading_or_accumulating_more_urls() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let url = action_url(&DeepLinkAction::OpenSettings { page: None });+ let payload =+ linux_reopen_action_payload(vec![url.clone(); MAX_LINUX_REOPEN_ACTIONS]).unwrap();+ assert_eq!(+ read_linux_reopen_actions(&mut packet(owner, &payload).as_slice(), owner)+ .unwrap()+ .len(),+ MAX_LINUX_REOPEN_ACTIONS+ );+ assert!(+ linux_reopen_action_payload(vec![url.clone(); MAX_LINUX_REOPEN_ACTIONS + 1]).is_err()+ );+ let payload = raw_action_payload(url.as_bytes()).repeat(MAX_LINUX_REOPEN_ACTIONS + 1);+ assert!(read_linux_reopen_actions(&mut packet(owner, &payload).as_slice(), owner).is_err());+ let mut oversized = linux_reopen_payload(owner).to_vec();+ oversized[..8].copy_from_slice(b"CAPREOP2");+ oversized.extend_from_slice(&((MAX_FORWARDED_DEEP_LINK_BYTES + 1) as u32).to_be_bytes());+ let mut oversized = std::io::Cursor::new(oversized);+ assert_eq!(+ read_linux_reopen_actions(&mut oversized, owner)+ .unwrap_err()+ .kind(),+ std::io::ErrorKind::InvalidData+ );+ assert_eq!(oversized.position(), 60);+ let mut written = Vec::new();+ assert!(+ write_linux_reopen_actions(+ &mut written,+ owner,+ &vec![0; MAX_FORWARDED_DEEP_LINK_BYTES + 1],+ )+ .is_err()+ );+ assert!(written.is_empty());+ let oversized = format!(+ "cap://action?value={}",+ "x".repeat(MAX_FORWARDED_DEEP_LINK_BYTES)+ );+ assert!(linux_reopen_action_payload([oversized]).unwrap().is_empty());+ let large = action_url(&DeepLinkAction::OpenSettings {+ page: Some("x".repeat(MAX_FORWARDED_DEEP_LINK_BYTES / 2)),+ });+ assert!(linux_reopen_action_payload([large.clone(), large]).is_err());+ }++ #[test]+ fn malformed_action_packets_never_reach_the_app_or_expose_the_url() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let (requests, received) = flume::bounded(1);+ for raw in [+ b"".as_slice(),+ b"not a URL",+ b"https://action?value=%22stop_recording%22",+ b"cap://auth?token=private-secret",+ b"cap://action?value=private-secret",+ b"cap://action?value=%22private-secret%22",+ b"cap://action?value=%FF\xff",+ ] {+ let (mut server, mut client) = UnixStream::pair().unwrap();+ client+ .write_all(&packet(owner, &raw_action_payload(raw)))+ .unwrap();+ let error = receive_linux_reopen(&mut server, owner, &requests).unwrap_err();+ assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);+ assert!(!error.to_string().contains("private-secret"));+ assert!(received.is_empty());+ }+ }++ #[test]+ fn argv_filter_preserves_supported_schemes_and_excludes_invalid_actions() {+ assert!(+ linux_reopen_action_payload(["--foreground".into()])+ .unwrap()+ .is_empty()+ );+ for scheme in ["cap", "cap-desktop"] {+ let raw = format!("{scheme}://action?value=%22stop_recording%22");+ assert_eq!(+ parse_linux_reopen_action(&raw).unwrap(),+ DeepLinkAction::StopRecording+ );+ assert!(!linux_reopen_action_payload([raw]).unwrap().is_empty());+ }+ for raw in [+ "cap://auth?token=private-secret",+ "cap://action?value=private-secret",+ ] {+ assert!(+ linux_reopen_action_payload([raw.into()])+ .unwrap()+ .is_empty()+ );+ }+ let valid = action_url(&DeepLinkAction::OpenSettings { page: None });+ let mixed = linux_reopen_action_payload([+ "cap://action?value=private-secret".into(),+ valid.clone(),+ ])+ .unwrap();+ assert_eq!(mixed, linux_reopen_action_payload([valid]).unwrap());+ }++ #[test]+ fn truncated_action_packets_never_reach_the_app() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let (requests, received) = flume::bounded(1);+ let payload =+ linux_reopen_action_payload([action_url(&DeepLinkAction::StopRecording)]).unwrap();+ let complete = packet(owner, &payload);+ for size in [56, 58, complete.len() - 1] {+ let (mut server, mut client) = UnixStream::pair().unwrap();+ client.write_all(&complete[..size]).unwrap();+ client.shutdown(std::net::Shutdown::Write).unwrap();+ assert!(receive_linux_reopen(&mut server, owner, &requests).is_err());+ assert!(received.is_empty());+ }+ for malformed in [vec![0; 3], 10_u32.to_be_bytes().to_vec()] {+ assert!(+ read_linux_reopen_actions(&mut packet(owner, &malformed).as_slice(), owner)+ .is_err()+ );+ }+ }++ #[test]+ fn stale_pid_start_and_boot_requests_never_reach_the_app() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let mut stale_pid = owner;+ stale_pid.pid = stale_pid.pid.wrapping_add(1);+ let mut stale_start = owner;+ stale_start.started = stale_start.started.wrapping_add(1);+ let mut stale_boot = owner;+ stale_boot.boot[0] ^= 1;+ let payload =+ linux_reopen_action_payload([action_url(&DeepLinkAction::StopRecording)]).unwrap();+ let (requests, received) = flume::bounded(1);+ for stale in [stale_pid, stale_start, stale_boot] {+ let (mut server, mut client) = UnixStream::pair().unwrap();+ client.write_all(&packet(stale, &payload)).unwrap();+ let error = receive_linux_reopen(&mut server, owner, &requests).unwrap_err();+ assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);+ assert!(received.is_empty());+ }+ }++ #[test]+ fn truncated_request_never_reaches_the_app() {+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let (requests, received) = flume::bounded(1);+ let (mut server, mut client) = UnixStream::pair().unwrap();+ client+ .write_all(&linux_reopen_payload(owner)[..55])+ .unwrap();+ client.shutdown(std::net::Shutdown::Write).unwrap();+ assert!(receive_linux_reopen(&mut server, owner, &requests).is_err());+ assert!(received.is_empty());+ }++ #[test]+ fn kernel_credentials_identify_the_actual_peer() {+ let (server, _client) = UnixStream::pair().unwrap();+ let peer = linux_peer(&server).unwrap();+ assert_eq!(peer.pid as u32, std::process::id());+ assert_eq!(peer.uid, unsafe { libc::geteuid() });+ }++ #[test]+ fn client_refuses_a_socket_served_by_another_process() {+ let mut fixture = super::tests::LinuxAcquireFixture::new();+ let pid = fixture.start_incumbent();+ let owner = linux_instance_identity(pid).unwrap();+ let address = std::os::unix::net::SocketAddr::from_abstract_name(format!(+ "cap-gpui-wrong-peer-{}",+ crate::store::new_uuid_v4()+ ))+ .unwrap();+ let _listener = UnixListener::bind_addr(&address).unwrap();+ let error = send_linux_reopen(address, owner, &[]).unwrap_err();+ assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);+ assert!(fixture.children[0].try_wait().unwrap().is_none());+ }++ #[test]+ fn long_instance_directories_use_no_filesystem_socket() {+ let directory = std::env::temp_dir()+ .join(format!(+ "cap-gpui-reopen-scope-{}",+ crate::store::new_uuid_v4()+ ))+ .join("a".repeat(150));+ std::fs::create_dir_all(&directory).unwrap();+ let owner = linux_instance_identity(std::process::id()).unwrap();+ let address = linux_reopen_address(&directory.join("cap-gpui.pid"), owner).unwrap();+ assert!(address.as_pathname().is_none());+ assert!(address.as_abstract_name().unwrap().len() < 107);+ assert!(std::fs::read_dir(&directory).unwrap().next().is_none());+ std::fs::remove_dir(&directory).unwrap();+ std::fs::remove_dir(directory.parent().unwrap()).unwrap();+ }++ #[test]+ fn reopen_never_finalizes_instant_or_an_unconfirmed_transition() {+ use crate::{recording::RecordingMode, session::Phase};+ for phase in [+ Phase::Idle,+ Phase::Starting,+ Phase::Recording { paused: false },+ Phase::Recording { paused: true },+ Phase::Stopping,+ ] {+ for mode in [+ None,+ Some(RecordingMode::Studio),+ Some(RecordingMode::Instant),+ ] {+ assert!(!linux_reopen_allowed(phase, mode, false));+ let expected = phase == Phase::Idle+ || (matches!(phase, Phase::Recording { .. })+ && mode == Some(RecordingMode::Studio));+ assert_eq!(linux_reopen_allowed(phase, mode, true), expected);+ }+ }+ }+}diff --git a/apps/desktop-gpui/src/upload.rs b/apps/desktop-gpui/src/upload.rsindex 811b371c4..fc05437dc 100644--- a/apps/desktop-gpui/src/upload.rs+++ b/apps/desktop-gpui/src/upload.rs@@ -40,6 +40,51 @@ pub struct InstantUpload {segment_upload: Option<tokio::task::JoinHandle<Result<(), String>>>,cancel: Arc<AtomicBool>,metadata_lock: Arc<Mutex<()>>,+ completion_permit: Option<tokio::sync::oneshot::Sender<()>>,+ completion_control: Option<CompletionControl>,+}++#[derive(Clone)]+pub(crate) struct CompletionControl {+ denied: tokio::sync::watch::Sender<bool>,+ cancel: Arc<AtomicBool>,+}++impl CompletionControl {+ pub(crate) fn deny(&self) {+ self.cancel.store(true, Ordering::Release);+ self.denied.send_replace(true);+ }+}++pub(crate) struct CompletionAuthorization {+ permit: tokio::sync::oneshot::Sender<()>,+ required: CompletionRequirement,+ control: CompletionControl,+}++struct CompletionRequirement {+ permission: tokio::sync::oneshot::Receiver<()>,+ denied: tokio::sync::watch::Receiver<bool>,+}++impl CompletionAuthorization {+ #[cfg(any(test, target_os = "linux", windows))]+ pub(crate) fn new() -> Self {+ let (permit, permission) = tokio::sync::oneshot::channel();+ let (denied, denial) = tokio::sync::watch::channel(false);+ Self {+ permit,+ required: CompletionRequirement {+ permission,+ denied: denial,+ },+ control: CompletionControl {+ denied,+ cancel: Arc::new(AtomicBool::new(false)),+ },+ }+ }}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]@@ -140,13 +185,25 @@ pub async fn prepare_instant_upload(})}-pub fn start_instant_upload(+pub(crate) fn start_instant_upload(video: VideoUploadInfo,project_path: PathBuf,segment_rx: Option<std::sync::mpsc::Receiver<SegmentCompletedEvent>>,metadata_lock: Arc<Mutex<()>>,+ authorization: Option<CompletionAuthorization>,) -> Result<InstantUpload, String> {- let cancel = Arc::new(AtomicBool::new(false));+ let (completion_permit, required, completion_control) = match authorization {+ Some(authorization) => (+ Some(authorization.permit),+ Some(authorization.required),+ Some(authorization.control),+ ),+ None => (None, None, None),+ };+ let cancel = completion_control.as_ref().map_or_else(+ || Arc::new(AtomicBool::new(false)),+ |control| control.cancel.clone(),+ );let segment_upload = if let Some(segment_rx) = segment_rx {let (events_tx, events_rx) = flume::unbounded();std::thread::Builder::new()@@ -170,6 +227,7 @@ pub fn start_instant_upload(events_rx,upload_cancel,upload_metadata_lock,+ required,).await}))@@ -182,6 +240,8 @@ pub fn start_instant_upload(segment_upload,cancel,metadata_lock,+ completion_permit,+ completion_control,})}@@ -198,22 +258,57 @@ impl InstantUpload {&self.metadata_lock}+ #[cfg(any(test, target_os = "linux"))]+ pub(crate) fn cancellation_token(&self) -> Arc<AtomicBool> {+ self.cancel.clone()+ }++ #[cfg(target_os = "linux")]+ pub(crate) fn completion_control(&self) -> Option<CompletionControl> {+ self.completion_control.clone()+ }++ #[cfg(any(test, target_os = "linux", windows))]+ pub(crate) fn authorize_completion(&mut self) -> Result<(), String> {+ if self.cancel.load(Ordering::Acquire) {+ return Err("Cancelled Instant recording cannot complete".into());+ }+ if let Some(permit) = self.completion_permit.take() {+ permit+ .send(())+ .map_err(|_| "Instant completion authorization was lost".to_string())?;+ }+ Ok(())+ }+pub async fn finish_segments(&mut self) -> Result<(), String> {- let Some(upload) = self.segment_upload.take() else {+ check_segment_cancelled(&self.cancel)?;+ let Some(upload) = self.segment_upload.as_mut() else {return Ok(());};- upload+ let result = upload.await- .map_err(|error| format!("Instant segment upload task failed: {error}"))?+ .map_err(|error| format!("Instant segment upload task failed: {error}"));+ drop(self.segment_upload.take());+ check_segment_cancelled(&self.cancel)?;+ result?}pub async fn finish_screenshot(&self, project_path: &Path) -> Result<(), String> {- upload_screenshot(+ #[cfg(target_os = "linux")]+ let result = upload_screenshot_with_cancel(&self.video.id,&project_path.join("screenshots/display.jpg"),+ &self.cancel,)- .await- .map_err(|error| format!("Instant recording thumbnail upload failed: {error}"))+ .await;+ #[cfg(not(target_os = "linux"))]+ let result = upload_screenshot(+ &self.video.id,+ &project_path.join("screenshots/display.jpg"),+ )+ .await;+ result.map_err(|error| format!("Instant recording thumbnail upload failed: {error}"))}pub async fn cancel(mut self) -> Result<(), String> {@@ -222,6 +317,10 @@ impl InstantUpload {}pub(crate) async fn abort_segments(&mut self) {+ if let Some(control) = &self.completion_control {+ control.deny();+ }+ drop(self.completion_permit.take());self.cancel.store(true, Ordering::Release);if let Some(upload) = self.segment_upload.take() {upload.abort();@@ -254,8 +353,16 @@ async fn run_segment_upload(events: flume::Receiver<SegmentCompletedEvent>,cancel: Arc<AtomicBool>,metadata_lock: Arc<Mutex<()>>,+ authorization: Option<CompletionRequirement>,) -> Result<(), String> {- let result = upload_segments(&video.id, events, cancel.clone()).await;+ let result = upload_segments(+ &LiveSegmentTransport,+ &video.id,+ events,+ cancel.clone(),+ authorization,+ )+ .await;if let Err(error) = &result&& !cancel.load(Ordering::Acquire)&& let Err(save_error) =@@ -266,27 +373,113 @@ async fn run_segment_upload(result}+trait SegmentTransport: Send + Sync {+ fn prefetch(+ &self,+ video_id: &str,+ start: u32,+ count: u32,+ ) -> impl Future<Output = Result<HashMap<String, String>, String>> + Send;+ fn segment(+ &self,+ video_id: String,+ event: SegmentCompletedEvent,+ signed_urls: Arc<Mutex<HashMap<String, String>>>,+ cancel: Arc<AtomicBool>,+ ) -> impl Future<Output = Result<SegmentCompletedEvent, String>> + Send;+ fn manifest(+ &self,+ video_id: &str,+ manifest: &SegmentUploadManifest,+ cancel: &Arc<AtomicBool>,+ ) -> impl Future<Output = Result<(), String>> + Send;+ fn complete(+ &self,+ video_id: &str,+ cancel: &Arc<AtomicBool>,+ ) -> impl Future<Output = Result<(), String>> + Send;+}++struct LiveSegmentTransport;+impl SegmentTransport for LiveSegmentTransport {+ async fn prefetch(+ &self,+ video_id: &str,+ start: u32,+ count: u32,+ ) -> Result<HashMap<String, String>, String> {+ prefetch_segment_urls(video_id, start, count)+ .await+ .map_err(|error| error.to_string())+ }+ async fn segment(+ &self,+ video_id: String,+ event: SegmentCompletedEvent,+ signed_urls: Arc<Mutex<HashMap<String, String>>>,+ cancel: Arc<AtomicBool>,+ ) -> Result<SegmentCompletedEvent, String> {+ upload_segment_with_retry(video_id, event, signed_urls, cancel).await+ }+ async fn manifest(+ &self,+ video_id: &str,+ manifest: &SegmentUploadManifest,+ cancel: &Arc<AtomicBool>,+ ) -> Result<(), String> {+ upload_segment_manifest_with_retry(video_id, manifest, cancel).await+ }+ async fn complete(&self, video_id: &str, cancel: &Arc<AtomicBool>) -> Result<(), String> {+ signal_recording_complete_with_retry(video_id, cancel).await+ }+}+async fn upload_segments(+ transport: &impl SegmentTransport,video_id: &str,events: flume::Receiver<SegmentCompletedEvent>,cancel: Arc<AtomicBool>,+ mut authorization: Option<CompletionRequirement>,) -> Result<(), String> {+ let mut authorized = authorization.is_none();let mut manifest = SegmentUploadManifest::default();let mut uploads = FuturesUnordered::new();let mut events_closed = false;let mut last_manifest_upload: Option<Instant> = None;let mut next_prefetch = SEGMENT_URL_PREFETCH + 1;- let signed_urls = Arc::new(Mutex::new(- prefetch_segment_urls(video_id, 1, SEGMENT_URL_PREFETCH)- .await- .unwrap_or_else(|error| {- tracing::warn!("Failed to prefetch instant upload URLs: {error}");- HashMap::new()- }),- ));+ let prefetched = checked_segment_step(&cancel, || async {+ Ok(transport.prefetch(video_id, 1, SEGMENT_URL_PREFETCH).await)+ })+ .await?;+ let signed_urls = Arc::new(Mutex::new(prefetched.unwrap_or_else(|error| {+ tracing::warn!("Failed to prefetch instant upload URLs: {error}");+ HashMap::new()+ })));loop {+ if cancel.load(Ordering::Acquire) {+ return Err("Instant recording upload cancelled".into());+ }+ if events_closed && uploads.is_empty() && authorized {+ break;+ }+ let guarded = authorization.is_some();+ let (permission, denial) = match authorization.as_mut() {+ Some(required) => (Some(&mut required.permission), Some(&mut required.denied)),+ None => (None, None),+ };tokio::select! {+ permission = async { permission.unwrap().await }, if !authorized => {+ permission.map_err(|_| "Instant completion was not authorized".to_string())?;+ authorized = true;+ }+ _ = async {+ let denial = denial.unwrap();+ let denied = *denial.borrow_and_update();+ if !denied { let _ = denial.changed().await; }+ }, if guarded => {+ return Err("Instant completion authorization was revoked".into());+ }next_event = events.recv_async(), if !events_closed && uploads.len() < MAX_SEGMENT_UPLOADS => {match next_event {Ok(event) => {@@ -296,7 +489,9 @@ async fn upload_segments(if event.media_type == SegmentMediaType::Video&& event.index.saturating_add(5) >= next_prefetch{- match prefetch_segment_urls(video_id, next_prefetch, SEGMENT_URL_PREFETCH).await {+ match checked_segment_step(&cancel, || async {+ Ok(transport.prefetch(video_id, next_prefetch, SEGMENT_URL_PREFETCH).await)+ }).await? {Ok(urls) => {signed_urls.lock().unwrap_or_else(|error| error.into_inner()).extend(urls);next_prefetch = next_prefetch.saturating_add(SEGMENT_URL_PREFETCH);@@ -304,7 +499,7 @@ async fn upload_segments(Err(error) => tracing::warn!("Failed to extend instant upload URLs: {error}"),}}- uploads.push(upload_segment_with_retry(+ uploads.push(transport.segment(video_id.to_string(),event,signed_urls.clone(),@@ -315,12 +510,13 @@ async fn upload_segments(}}Some(upload) = uploads.next(), if !uploads.is_empty() => {+ check_segment_cancelled(&cancel)?;let event = upload?;manifest.record(&event);if manifest.has_video_content()&& last_manifest_upload.is_none_or(|last| last.elapsed() >= MANIFEST_UPLOAD_INTERVAL){- upload_segment_manifest_with_retry(video_id, &manifest, &cancel).await?;+ checked_segment_step(&cancel, || transport.manifest(video_id, &manifest, &cancel)).await?;last_manifest_upload = Some(Instant::now());}}@@ -338,8 +534,37 @@ async fn upload_segments(}manifest.is_complete = true;- upload_segment_manifest_with_retry(video_id, &manifest, &cancel).await?;- signal_recording_complete_with_retry(video_id, &cancel).await+ checked_segment_step(&cancel, || transport.manifest(video_id, &manifest, &cancel)).await?;+ checked_segment_step(&cancel, || transport.complete(video_id, &cancel)).await+}++fn check_segment_cancelled(cancel: &AtomicBool) -> Result<(), String> {+ if cancel.load(Ordering::Acquire) {+ Err("Instant recording upload cancelled".into())+ } else {+ Ok(())+ }+}++async fn checked_segment_step<T, F>(+ cancel: &AtomicBool,+ step: impl FnOnce() -> F,+) -> Result<T, String>+where+ F: Future<Output = Result<T, String>>,+{+ check_segment_cancelled(cancel)?;+ let result = step().await;+ check_segment_cancelled(cancel)?;+ result+}++async fn segment_retry_delay(cancel: &AtomicBool, delay: Duration) -> Result<(), String> {+ checked_segment_step(cancel, || async {+ tokio::time::sleep(delay).await;+ Ok(())+ })+ .await}fn prefetched_segment_paths(start: u32, count: u32) -> Vec<String> {@@ -407,23 +632,26 @@ async fn upload_segment_with_retry(return Err("Instant recording upload cancelled".to_string());}if attempt > 0 {- tokio::time::sleep(Duration::from_millis(250u64 << attempt)).await;+ segment_retry_delay(&cancel, Duration::from_millis(250u64 << attempt)).await?;}let result = if let Some(url) = cached_url.take() {- upload_signed_bytes(+ upload_signed_bytes_inner(SignedUploadTarget {url,headers: HashMap::new(),},&subpath,bytes.clone(),+ Some(&cancel),).await} else {- presigned_put_bytes(&video_id, &subpath, bytes.clone()).await+ presigned_put_bytes_inner(&video_id, &subpath, bytes.clone(), Some(&cancel)).await};+ check_segment_cancelled(&cancel)?;+match result {Ok(()) => return Ok(event),Err(AuthApiError::InvalidAuthentication) => {@@ -498,10 +726,11 @@ fn segment_subpath(event: &SegmentCompletedEvent) -> String {async fn upload_segment_manifest(video_id: &str,manifest: &SegmentUploadManifest,+ cancel: &AtomicBool,) -> Result<(), String> {let bytes = serde_json::to_vec(manifest).map_err(|error| format!("Failed to serialize instant upload manifest: {error}"))?;- presigned_put_bytes(video_id, "segments/manifest.json", bytes)+ presigned_put_bytes_inner(video_id, "segments/manifest.json", bytes, Some(cancel)).await.map_err(|error| format!("Failed to upload instant recording manifest: {error}"))}@@ -515,7 +744,11 @@ async fn upload_segment_manifest_with_retry(if cancel.load(Ordering::Acquire) {return Err("Instant recording upload cancelled".to_string());}- match upload_segment_manifest(video_id, manifest).await {+ match checked_segment_step(cancel, || {+ upload_segment_manifest(video_id, manifest, cancel)+ })+ .await+ {Ok(()) => return Ok(()),Err(error) if attempt + 1 == SEGMENT_UPLOAD_ATTEMPTS => return Err(error),Err(error) => {@@ -523,7 +756,7 @@ async fn upload_segment_manifest_with_retry(attempt = attempt + 1,"Instant manifest upload failed: {error}");- tokio::time::sleep(Duration::from_millis(250u64 << attempt)).await;+ segment_retry_delay(cancel, Duration::from_millis(250u64 << attempt)).await?;}}}@@ -538,7 +771,7 @@ async fn signal_recording_complete_with_retry(if cancel.load(Ordering::Acquire) {return Err("Instant recording upload cancelled".to_string());}- match signal_recording_complete(video_id).await {+ match checked_segment_step(cancel, || signal_recording_complete(video_id)).await {Ok(()) => return Ok(()),Err(error) if attempt + 1 == SEGMENT_UPLOAD_ATTEMPTS => return Err(error),Err(error) => {@@ -546,7 +779,7 @@ async fn signal_recording_complete_with_retry(attempt = attempt + 1,"Instant completion signal failed: {error}");- tokio::time::sleep(Duration::from_millis(250u64 << attempt)).await;+ segment_retry_delay(cancel, Duration::from_millis(250u64 << attempt)).await?;}}}@@ -590,12 +823,34 @@ struct VideoMeta {fps: Option<f32>,}+fn check_export_cancelled(cancel: &AtomicBool) -> Result<(), AuthApiError> {+ if cancel.load(Ordering::Acquire) {+ Err(AuthApiError::Other("Export cancelled".into()))+ } else {+ Ok(())+ }+}++async fn checked_upload_step<T, F>(+ cancel: &AtomicBool,+ step: impl FnOnce() -> F,+) -> Result<T, AuthApiError>+where+ F: Future<Output = Result<T, AuthApiError>>,+{+ check_export_cancelled(cancel)?;+ let result = step().await;+ check_export_cancelled(cancel)?;+ result+}+pub async fn upload_exported_video(project_path: PathBuf,organization_id: Option<String>,progress: impl Fn(f64),cancel: std::sync::Arc<AtomicBool>,) -> Result<UploadResult, String> {+ check_export_cancelled(&cancel).map_err(|error| error.to_string())?;if store_auth_missing() {let _ = crate::store::set_auth(None);return Ok(UploadResult::NotAuthenticated);@@ -631,7 +886,7 @@ pub async fn upload_exported_video(let video_id = match reusable_video_id(meta.sharing.as_ref(), meta.upload.as_ref()) {Some(video_id) => video_id,None => {- let video_id = match request_video_id().await {+ let video_id = match checked_upload_step(&cancel, request_video_id).await {Ok(video_id) => video_id,Err(AuthApiError::InvalidAuthentication) => {return Ok(UploadResult::NotAuthenticated);@@ -651,13 +906,15 @@ pub async fn upload_exported_video(}};- let s3_config = match create_or_get_video(- false,- Some(video_id.clone()),- Some(meta.pretty_name.clone()),- Some(&metadata),- organization_id,- )+ let s3_config = match checked_upload_step(&cancel, || {+ create_or_get_video(+ false,+ Some(video_id.clone()),+ Some(meta.pretty_name.clone()),+ Some(&metadata),+ organization_id,+ )+ }).await{Ok(config) => config,@@ -678,7 +935,11 @@ pub async fn upload_exported_video(meta.save_for_project().map_err(|error| format!("Failed to persist upload state: {error}"))?;- match upload_video(&s3_config.id, &file_path, &metadata, progress, &cancel).await {+ match checked_upload_step(&cancel, || {+ upload_video(&s3_config.id, &file_path, &metadata, progress, &cancel)+ })+ .await+ {Ok(link) => {meta.sharing = Some(SharingMeta {link: link.clone(),@@ -688,13 +949,19 @@ pub async fn upload_exported_video(meta.save_for_project().map_err(|error| format!("Failed to persist sharing state: {error}"))?;- if let Err(error) = upload_screenshot(&s3_config.id, &screenshot_path).await {+ if let Err(error) = checked_upload_step(&cancel, || {+ upload_screenshot_with_cancel(&s3_config.id, &screenshot_path, &cancel)+ })+ .await+ {return Err(format!("thumbnail upload failed: {error}"));}+ check_export_cancelled(&cancel).map_err(|error| error.to_string())?;meta.upload = Some(UploadMeta::Complete);meta.save_for_project().map_err(|error| format!("Failed to persist completed upload: {error}"))?;+ check_export_cancelled(&cancel).map_err(|error| error.to_string())?;Ok(UploadResult::Success(link))}Err(AuthApiError::UpgradeRequired) => Ok(UploadResult::UpgradeRequired),@@ -823,7 +1090,7 @@ async fn upload_video(progress: impl Fn(f64),cancel: &AtomicBool,) -> Result<String, AuthApiError> {- let initiate = multipart_initiate(video_id).await?;+ let initiate = checked_upload_step(cancel, || multipart_initiate(video_id)).await?;let is_drive = is_google_drive_upload(initiate.provider.as_deref(), &initiate.upload_id);let parts = upload_parts(video_id,@@ -837,7 +1104,10 @@ async fn upload_video(if cancel.load(Ordering::Relaxed) {return Err(AuthApiError::Other("Export cancelled".into()));}- multipart_complete(video_id, &initiate.upload_id, &parts, Some(metadata)).await?;+ checked_upload_step(cancel, || {+ multipart_complete(video_id, &initiate.upload_id, &parts, Some(metadata))+ })+ .await?;progress(1.0);Ok(format!("{}/s/{video_id}", auth::server_url()))@@ -1007,11 +1277,13 @@ async fn upload_parts(&chunk,is_drive,use_md5,+ cancel,).await{Ok(part) => parts.push(part),Err(error) => {+ check_export_cancelled(cancel)?;tracing::warn!(part_number, error = %error, "chunk upload failed; will retry");failed.push((part_number, offset, chunk, error));}@@ -1034,11 +1306,13 @@ async fn upload_parts(&chunk,is_drive,use_md5,+ cancel,).await{Ok(part) => parts.push(part),Err(_) => {+ check_export_cancelled(cancel)?;return Err(first_error);}}@@ -1064,9 +1338,13 @@ async fn put_part(chunk: &[u8],is_drive: bool,use_md5: bool,+ cancel: &AtomicBool,) -> Result<UploadedPart, AuthApiError> {let md5_sum = use_md5.then(|| md5_base64(chunk));- let url = multipart_presign(video_id, upload_id, part_number, md5_sum.as_deref()).await?;+ let url = checked_upload_step(cancel, || {+ multipart_presign(video_id, upload_id, part_number, md5_sum.as_deref())+ })+ .await?;let client = reqwest::Client::new();let mut attempt = 0u32;loop {@@ -1085,7 +1363,8 @@ async fn put_part(if let Some(md5_sum) = &md5_sum {request = request.header("Content-MD5", md5_sum);}- match request.send().await {+ let response = checked_upload_step(cancel, || async { Ok(request.send().await) }).await?;+ match response {Ok(response) => {if !upload_status_ok(&url,@@ -1121,7 +1400,11 @@ async fn put_part(attempt,"network error uploading chunk; retrying in {delay:?}: {error}");- tokio::time::sleep(delay).await;+ checked_upload_step(cancel, || async {+ tokio::time::sleep(delay).await;+ Ok(())+ })+ .await?;}Err(error) => {return Err(AuthApiError::Other(format!(@@ -1132,6 +1415,23 @@ async fn put_part(}}+async fn upload_screenshot_with_cancel(+ video_id: &str,+ path: &Path,+ cancel: &AtomicBool,+) -> Result<(), AuthApiError> {+ check_export_cancelled(cancel)?;+ let bytes = compress_image(path)?;+ presigned_put_bytes_inner(+ video_id,+ "screenshot/screen-capture.jpg",+ bytes,+ Some(cancel),+ )+ .await+}++#[cfg(not(target_os = "linux"))]async fn upload_screenshot(video_id: &str, path: &Path) -> Result<(), AuthApiError> {let bytes = compress_image(path)?;presigned_put_bytes(video_id, "screenshot/screen-capture.jpg", bytes).await@@ -1145,6 +1445,28 @@ async fn presigned_put_bytes(video_id: &str,subpath: &str,bytes: Vec<u8>,+) -> Result<(), AuthApiError> {+ presigned_put_bytes_inner(video_id, subpath, bytes, None).await+}++async fn optional_upload_step<T, F>(+ cancel: Option<&AtomicBool>,+ step: impl FnOnce() -> F,+) -> Result<T, AuthApiError>+where+ F: Future<Output = Result<T, AuthApiError>>,+{+ match cancel {+ Some(cancel) => checked_upload_step(cancel, step).await,+ None => step().await,+ }+}++async fn presigned_put_bytes_inner(+ video_id: &str,+ subpath: &str,+ bytes: Vec<u8>,+ cancel: Option<&AtomicBool>,) -> Result<(), AuthApiError> {#[derive(Deserialize)]#[serde(rename_all = "camelCase")]@@ -1152,15 +1474,17 @@ async fn presigned_put_bytes(presigned_put_data: SignedUploadTarget,}- let response = auth::authed_request(- reqwest::Method::POST,- "/api/upload/signed",- Some(json!({- "videoId": video_id,- "subpath": subpath,- "method": "put",- })),- )+ let response = optional_upload_step(cancel, || {+ auth::authed_request(+ reqwest::Method::POST,+ "/api/upload/signed",+ Some(json!({+ "videoId": video_id,+ "subpath": subpath,+ "method": "put",+ })),+ )+ }).await?;if !response.status().is_success() {let status = response.status().as_u16();@@ -1174,13 +1498,14 @@ async fn presigned_put_bytes(.await.map_err(|error| AuthApiError::Other(format!("api/upload_signed/response: {error}")))?.presigned_put_data;- upload_signed_bytes(target, subpath, bytes).await+ upload_signed_bytes_inner(target, subpath, bytes, cancel).await}-async fn upload_signed_bytes(+async fn upload_signed_bytes_inner(target: SignedUploadTarget,subpath: &str,bytes: Vec<u8>,+ cancel: Option<&AtomicBool>,) -> Result<(), AuthApiError> {static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();@@ -1201,13 +1526,16 @@ async fn upload_signed_bytes(for (name, value) in target.headers {request = request.header(name, value);}- let response = request.send().await.map_err(|error| {- if error.is_timeout() {- AuthApiError::Timeout- } else {- AuthApiError::Other(error.to_string())- }- })?;+ let response = optional_upload_step(cancel, || async {+ request.send().await.map_err(|error| {+ if error.is_timeout() {+ AuthApiError::Timeout+ } else {+ AuthApiError::Other(error.to_string())+ }+ })+ })+ .await?;if !response.status().is_success() {return Err(AuthApiError::Other(format!("upload failed: {}",@@ -1452,8 +1780,21 @@ mod tests {segment_upload: Some(task),cancel: Arc::new(AtomicBool::new(false)),metadata_lock: Arc::new(Mutex::new(())),+ completion_permit: None,+ completion_control: None,};+ {+ let mut finish = Box::pin(upload.finish_segments());+ assert!(+ std::future::poll_fn(|context| std::task::Poll::Ready(+ finish.as_mut().poll(context)+ ))+ .await+ .is_pending()+ );+ }+ assert!(upload.segment_upload.is_some());upload.abort_segments().await;assert!(dropped.load(Ordering::Acquire));@@ -1461,6 +1802,119 @@ mod tests {});}+ fn upload_with_task(+ task: tokio::task::JoinHandle<Result<(), String>>,+ control: Option<CompletionControl>,+ ) -> InstantUpload {+ InstantUpload {+ video: VideoUploadInfo {+ id: "owned-upload".into(),+ link: "https://example.invalid/s/owned-upload".into(),+ config: S3UploadMeta {+ id: "owned-upload".into(),+ },+ },+ segment_upload: Some(task),+ cancel: control+ .as_ref()+ .map(|control| control.cancel.clone())+ .unwrap_or_else(|| Arc::new(AtomicBool::new(false))),+ metadata_lock: Arc::new(Mutex::new(())),+ completion_permit: None,+ completion_control: control,+ }+ }++ #[tokio::test]+ async fn denied_segment_finish_waits_until_the_owned_task_has_joined() {+ let authorization = CompletionAuthorization::new();+ let control = authorization.control.clone();+ let finished = Arc::new(AtomicBool::new(false));+ let task_finished = finished.clone();+ let (release, released) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(async move {+ released.await.unwrap();+ task_finished.store(true, Ordering::Release);+ Ok(())+ });+ let mut upload = upload_with_task(task, Some(control.clone()));+ {+ let mut finish = Box::pin(upload.finish_segments());+ assert!(+ std::future::poll_fn(|context| std::task::Poll::Ready(+ finish.as_mut().poll(context)+ ))+ .await+ .is_pending()+ );+ control.deny();+ assert!(+ std::future::poll_fn(|context| std::task::Poll::Ready(+ finish.as_mut().poll(context)+ ))+ .await+ .is_pending()+ );+ assert!(!finished.load(Ordering::Acquire));+ release.send(()).unwrap();+ assert!(finish.await.unwrap_err().contains("cancelled"));+ }+ assert!(finished.load(Ordering::Acquire));+ assert!(upload.segment_upload.is_none());+ upload.abort_segments().await;+ }++ #[tokio::test]+ async fn segment_finish_preserves_results_and_removes_only_joined_handles() {+ for result in [Ok(()), Err("segment transfer failed".to_string())] {+ let expected = result.clone();+ let mut upload = upload_with_task(tokio::spawn(async move { result }), None);+ assert_eq!(upload.finish_segments().await, expected);+ assert!(upload.segment_upload.is_none());+ upload.abort_segments().await;+ }++ let task = tokio::spawn(std::future::pending::<Result<(), String>>());+ task.abort();+ let mut upload = upload_with_task(task, None);+ assert!(+ upload+ .finish_segments()+ .await+ .unwrap_err()+ .contains("Instant segment upload task failed")+ );+ assert!(upload.segment_upload.is_none());+ upload.abort_segments().await;++ let task: tokio::task::JoinHandle<Result<(), String>> =+ tokio::spawn(async { panic!("synthetic segment task panic") });+ let mut upload = upload_with_task(task, None);+ assert!(+ upload+ .finish_segments()+ .await+ .unwrap_err()+ .contains("Instant segment upload task failed")+ );+ assert!(upload.segment_upload.is_none());+ upload.abort_segments().await;++ let task = tokio::spawn(std::future::pending::<Result<(), String>>());+ let mut upload = upload_with_task(task, None);+ upload.cancel.store(true, Ordering::Release);+ assert!(+ upload+ .finish_segments()+ .await+ .unwrap_err()+ .contains("cancelled")+ );+ assert!(upload.segment_upload.is_some());+ upload.abort_segments().await;+ assert!(upload.segment_upload.is_none());+ }+fn segment_event(index: u32,duration: f64,@@ -1657,4 +2111,571 @@ mod tests {None);}+ #[derive(Default)]+ struct FakeSegmentTransport {+ manifests: Mutex<Vec<bool>>,+ completed: std::sync::atomic::AtomicUsize,+ uploaded: std::sync::atomic::AtomicUsize,+ fail_segment: AtomicBool,+ delay_complete: AtomicBool,+ complete_started: tokio::sync::Notify,+ complete_response: tokio::sync::Notify,+ prefetch_count: std::sync::atomic::AtomicUsize,+ delay_prefetch_at: std::sync::atomic::AtomicUsize,+ prefetch_started: tokio::sync::Notify,+ prefetch_response: tokio::sync::Notify,+ }+ impl SegmentTransport for FakeSegmentTransport {+ async fn prefetch(+ &self,+ _: &str,+ _: u32,+ _: u32,+ ) -> Result<HashMap<String, String>, String> {+ let request = self.prefetch_count.fetch_add(1, Ordering::AcqRel) + 1;+ if request == self.delay_prefetch_at.load(Ordering::Acquire) {+ self.prefetch_started.notify_one();+ self.prefetch_response.notified().await;+ }+ Ok(HashMap::new())+ }+ async fn segment(+ &self,+ _: String,+ event: SegmentCompletedEvent,+ _: Arc<Mutex<HashMap<String, String>>>,+ _: Arc<AtomicBool>,+ ) -> Result<SegmentCompletedEvent, String> {+ if self.fail_segment.load(Ordering::Acquire) {+ Err("segment upload failed".into())+ } else {+ self.uploaded.fetch_add(1, Ordering::AcqRel);+ Ok(event)+ }+ }+ async fn manifest(+ &self,+ _: &str,+ manifest: &SegmentUploadManifest,+ _: &Arc<AtomicBool>,+ ) -> Result<(), String> {+ self.manifests.lock().unwrap().push(manifest.is_complete);+ Ok(())+ }+ async fn complete(&self, _: &str, _: &Arc<AtomicBool>) -> Result<(), String> {+ self.completed.fetch_add(1, Ordering::AcqRel);+ if self.delay_complete.load(Ordering::Acquire) {+ self.complete_started.notify_one();+ self.complete_response.notified().await;+ }+ Ok(())+ }+ }+ fn closed_segment_events() -> flume::Receiver<SegmentCompletedEvent> {+ let (sender, receiver) = flume::unbounded();+ sender+ .send(segment_event(0, 0.0, true, SegmentMediaType::Video))+ .unwrap();+ sender+ .send(segment_event(1, 1.0, false, SegmentMediaType::Video))+ .unwrap();+ drop(sender);+ receiver+ }++ #[tokio::test]+ async fn segmented_complete_response_after_revocation_cannot_publish_delete_or_share() {+ let transport = FakeSegmentTransport::default();+ transport.delay_complete.store(true, Ordering::Release);+ let authorization = CompletionAuthorization::new();+ let cancel = authorization.control.cancel.clone();+ authorization.permit.send(()).unwrap();+ let published = AtomicBool::new(false);+ let deleted = AtomicBool::new(false);+ let shared = AtomicBool::new(false);+ let future = async {+ crate::recording::finish_instant_upload_locally(+ Some(&cancel),+ upload_segments(+ &transport,+ "revoked-completion",+ closed_segment_events(),+ cancel.clone(),+ Some(authorization.required),+ ),+ || {+ published.store(true, Ordering::Release);+ Ok(())+ },+ async {+ deleted.store(true, Ordering::Release);+ Ok(())+ },+ )+ .await?;+ shared.store(true, Ordering::Release);+ Ok::<(), anyhow::Error>(())+ };+ tokio::pin!(future);+ tokio::select! {+ _ = transport.complete_started.notified() => {}+ result = &mut future => panic!("Completion did not wait: {result:?}"),+ }+ authorization.control.deny();+ transport.complete_response.notify_one();+ assert!(future.await.unwrap_err().to_string().contains("cancelled"));+ assert_eq!(transport.completed.load(Ordering::Acquire), 1);+ assert!(!published.load(Ordering::Acquire));+ assert!(!deleted.load(Ordering::Acquire));+ assert!(!shared.load(Ordering::Acquire));+ }++ #[tokio::test]+ async fn segmented_prefetch_response_after_revocation_cannot_start_more_uploads() {+ for pause_at in [1, 2] {+ let transport = FakeSegmentTransport::default();+ transport+ .delay_prefetch_at+ .store(pause_at, Ordering::Release);+ let authorization = CompletionAuthorization::new();+ authorization.permit.send(()).unwrap();+ let (sender, receiver) = flume::unbounded();+ sender+ .send(segment_event(0, 0.0, true, SegmentMediaType::Video))+ .unwrap();+ sender+ .send(segment_event(20, 1.0, false, SegmentMediaType::Video))+ .unwrap();+ drop(sender);+ let future = upload_segments(+ &transport,+ "revoked-prefetch",+ receiver,+ authorization.control.cancel.clone(),+ Some(authorization.required),+ );+ tokio::pin!(future);+ tokio::select! {+ _ = transport.prefetch_started.notified() => {}+ result = &mut future => panic!("Prefetch did not wait: {result:?}"),+ }+ let uploaded = transport.uploaded.load(Ordering::Acquire);+ authorization.control.deny();+ transport.prefetch_response.notify_one();+ assert!(future.await.unwrap_err().contains("cancelled"));+ assert_eq!(transport.uploaded.load(Ordering::Acquire), uploaded);+ assert_eq!(transport.prefetch_count.load(Ordering::Acquire), pause_at);+ assert_eq!(transport.completed.load(Ordering::Acquire), 0);+ }+ }++ #[tokio::test]+ async fn segmented_retry_delay_observes_revocation_before_next_request() {+ let cancel = AtomicBool::new(false);+ let requested = AtomicBool::new(false);+ let future = async {+ segment_retry_delay(&cancel, Duration::from_millis(20)).await?;+ checked_segment_step(&cancel, || async {+ requested.store(true, Ordering::Release);+ Ok(())+ })+ .await+ };+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(1), &mut future)+ .await+ .is_err()+ );+ cancel.store(true, Ordering::Release);+ assert!(future.await.unwrap_err().contains("cancelled"));+ assert!(!requested.load(Ordering::Acquire));+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn segmented_screenshot_uses_shared_revocation_before_reading_file() {+ let authorization = CompletionAuthorization::new();+ let control = authorization.control.clone();+ let upload = InstantUpload {+ video: VideoUploadInfo {+ id: "cancelled-thumbnail".into(),+ link: "https://example.invalid/s/cancelled-thumbnail".into(),+ config: S3UploadMeta {+ id: "cancelled-thumbnail".into(),+ },+ },+ segment_upload: None,+ cancel: control.cancel.clone(),+ metadata_lock: Arc::new(Mutex::new(())),+ completion_permit: Some(authorization.permit),+ completion_control: Some(control.clone()),+ };+ control.deny();+ assert!(+ upload+ .finish_screenshot(Path::new("/not-a-recording/cancelled.cap"))+ .await+ .unwrap_err()+ .contains("Export cancelled")+ );+ }++ #[tokio::test]+ async fn segmented_presign_response_revocation_prevents_following_put() {+ let cancel = AtomicBool::new(false);+ let put_started = AtomicBool::new(false);+ let (response, received) = tokio::sync::oneshot::channel();+ let future = async {+ optional_upload_step(Some(&cancel), || async {+ received.await.unwrap();+ Ok(())+ })+ .await?;+ optional_upload_step(Some(&cancel), || async {+ put_started.store(true, Ordering::Release);+ Ok(())+ })+ .await+ };+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(1), &mut future)+ .await+ .is_err()+ );+ cancel.store(true, Ordering::Release);+ response.send(()).unwrap();+ assert!(future.await.is_err());+ assert!(!put_started.load(Ordering::Acquire));+ }++ #[tokio::test]+ async fn closed_capture_events_wait_for_successful_stop_permission_before_complete() {+ let transport = FakeSegmentTransport::default();+ let authorization = CompletionAuthorization::new();+ let future = upload_segments(+ &transport,+ "owned-attempt",+ closed_segment_events(),+ Arc::new(AtomicBool::new(false)),+ Some(authorization.required),+ );+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ assert_eq!(transport.completed.load(Ordering::Acquire), 0);+ assert!(+ transport+ .manifests+ .lock()+ .unwrap()+ .iter()+ .all(|complete| !complete)+ );+ authorization.permit.send(()).unwrap();+ future.await.unwrap();+ assert_eq!(transport.completed.load(Ordering::Acquire), 1);+ assert_eq!(transport.manifests.lock().unwrap().last(), Some(&true));+ }++ #[tokio::test]+ async fn failed_stop_denies_completion_even_after_all_segments_uploaded() {+ let transport = FakeSegmentTransport::default();+ let authorization = CompletionAuthorization::new();+ let future = upload_segments(+ &transport,+ "failed-attempt",+ closed_segment_events(),+ Arc::new(AtomicBool::new(false)),+ Some(authorization.required),+ );+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ assert_eq!(transport.uploaded.load(Ordering::Acquire), 2);+ drop(authorization.permit);+ assert!(future.await.unwrap_err().contains("not authorized"));+ assert_eq!(transport.completed.load(Ordering::Acquire), 0);+ assert!(+ transport+ .manifests+ .lock()+ .unwrap()+ .iter()+ .all(|complete| !complete)+ );+ }++ #[tokio::test]+ async fn cancelled_or_failed_upload_cannot_complete_with_a_queued_permission() {+ for fail_segment in [false, true] {+ let transport = FakeSegmentTransport::default();+ transport+ .fail_segment+ .store(fail_segment, Ordering::Release);+ let authorization = CompletionAuthorization::new();+ authorization.permit.send(()).unwrap();+ assert!(+ upload_segments(+ &transport,+ "failed-attempt",+ closed_segment_events(),+ Arc::new(AtomicBool::new(!fail_segment)),+ Some(authorization.required)+ )+ .await+ .is_err()+ );+ assert_eq!(transport.completed.load(Ordering::Acquire), 0);+ assert!(+ transport+ .manifests+ .lock()+ .unwrap()+ .iter()+ .all(|complete| !complete)+ );+ }+ }++ #[tokio::test]+ async fn permission_from_an_old_attempt_cannot_release_a_new_attempt() {+ let old = CompletionAuthorization::new();+ drop(old.required);+ let current = CompletionAuthorization::new();+ let transport = FakeSegmentTransport::default();+ let future = upload_segments(+ &transport,+ "new-attempt",+ closed_segment_events(),+ Arc::new(AtomicBool::new(false)),+ Some(current.required),+ );+ tokio::pin!(future);+ assert!(old.permit.send(()).is_err());+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ assert_eq!(transport.completed.load(Ordering::Acquire), 0);+ current.permit.send(()).unwrap();+ future.await.unwrap();+ assert_eq!(transport.completed.load(Ordering::Acquire), 1);+ }++ #[tokio::test]+ async fn legacy_upload_without_authorization_preserves_channel_close_completion() {+ let transport = FakeSegmentTransport::default();+ upload_segments(+ &transport,+ "legacy-attempt",+ closed_segment_events(),+ Arc::new(AtomicBool::new(false)),+ None,+ )+ .await+ .unwrap();+ assert_eq!(transport.completed.load(Ordering::Acquire), 1);+ }+ #[tokio::test]+ async fn aborting_upload_revokes_its_completion_permission_before_retry() {+ let authorization = CompletionAuthorization::new();+ let mut upload = InstantUpload {+ video: VideoUploadInfo {+ id: "cancelled".into(),+ link: "https://example.invalid/s/cancelled".into(),+ config: S3UploadMeta {+ id: "cancelled".into(),+ },+ },+ segment_upload: None,+ cancel: Arc::new(AtomicBool::new(false)),+ metadata_lock: Arc::new(Mutex::new(())),+ completion_permit: Some(authorization.permit),+ completion_control: Some(authorization.control),+ };+ upload.abort_segments().await;+ assert!(authorization.required.permission.await.is_err());+ assert!(upload.authorize_completion().is_err());+ }+ #[tokio::test]+ async fn revocation_wakes_pending_completion_without_upload_mutex_or_permit_drop() {+ let authorization = CompletionAuthorization::new();+ let transport = FakeSegmentTransport::default();+ let future = upload_segments(+ &transport,+ "revoked-attempt",+ closed_segment_events(),+ authorization.control.cancel.clone(),+ Some(authorization.required),+ );+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ authorization.control.deny();+ assert!(+ tokio::time::timeout(Duration::from_secs(1), future)+ .await+ .unwrap()+ .is_err()+ );+ assert_eq!(transport.completed.load(Ordering::Acquire), 0);+ assert!(+ transport+ .manifests+ .lock()+ .unwrap()+ .iter()+ .all(|complete| !complete)+ );+ assert!(authorization.permit.send(()).is_err());+ }+}++#[cfg(test)]+mod exported_upload_cancellation_tests {+ use super::*;+ use std::sync::atomic::AtomicUsize;++ #[tokio::test]+ async fn cancelled_export_returns_before_auth_metadata_or_upload_submission() {+ let result = upload_exported_video(+ PathBuf::from("/not-a-recording/cancelled.cap"),+ None,+ |_| panic!("Cancelled export must not start"),+ Arc::new(AtomicBool::new(true)),+ )+ .await;+ assert!(result.unwrap_err().contains("Export cancelled"));+ }++ #[tokio::test]+ async fn cancellation_during_an_inflight_step_prevents_following_complete_submission() {+ let cancel = Arc::new(AtomicBool::new(false));+ let requested = Arc::new(AtomicUsize::new(0));+ let worker_cancel = cancel.clone();+ let worker_requested = requested.clone();+ let (entered, entered_rx) = tokio::sync::oneshot::channel();+ let (release, released) = tokio::sync::oneshot::channel();+ let worker = tokio::spawn(async move {+ checked_upload_step(&worker_cancel, || async {+ entered.send(()).unwrap();+ released.await.unwrap();+ Ok(())+ })+ .await?;+ checked_upload_step(&worker_cancel, || async {+ worker_requested.fetch_add(1, Ordering::AcqRel);+ Ok(())+ })+ .await+ });+ entered_rx.await.unwrap();+ cancel.store(true, Ordering::Release);+ release.send(()).unwrap();+ assert!(+ worker+ .await+ .unwrap()+ .unwrap_err()+ .to_string()+ .contains("Export cancelled")+ );+ assert_eq!(requested.load(Ordering::Acquire), 0);+ }++ #[tokio::test]+ async fn cancellation_while_retry_waits_prevents_retry_and_complete() {+ let cancel = Arc::new(AtomicBool::new(false));+ let attempts = Arc::new(AtomicUsize::new(0));+ let worker_cancel = cancel.clone();+ let worker_attempts = attempts.clone();+ let (waiting, waiting_rx) = tokio::sync::oneshot::channel();+ let (release, released) = tokio::sync::oneshot::channel();+ let worker = tokio::spawn(async move {+ let first = checked_upload_step(&worker_cancel, || async {+ worker_attempts.fetch_add(1, Ordering::AcqRel);+ Err::<(), _>(AuthApiError::Other("network failure".into()))+ })+ .await;+ assert!(first.is_err());+ checked_upload_step(&worker_cancel, || async {+ waiting.send(()).unwrap();+ released.await.unwrap();+ Ok(())+ })+ .await?;+ checked_upload_step(&worker_cancel, || async {+ worker_attempts.fetch_add(1, Ordering::AcqRel);+ Ok(())+ })+ .await+ });+ waiting_rx.await.unwrap();+ cancel.store(true, Ordering::Release);+ release.send(()).unwrap();+ assert!(worker.await.unwrap().is_err());+ assert_eq!(attempts.load(Ordering::Acquire), 1);+ }++ #[tokio::test]+ async fn instant_camera_only_export_observes_the_same_revocation_token() {+ let authorization = CompletionAuthorization::new();+ let control = authorization.control.clone();+ let upload = InstantUpload {+ video: VideoUploadInfo {+ id: "camera-only".into(),+ link: "https://example.invalid/s/camera-only".into(),+ config: S3UploadMeta {+ id: "camera-only".into(),+ },+ },+ segment_upload: None,+ cancel: control.cancel.clone(),+ metadata_lock: Arc::new(Mutex::new(())),+ completion_permit: Some(authorization.permit),+ completion_control: Some(authorization.control),+ };+ let token = upload.cancellation_token();+ assert!(Arc::ptr_eq(&token, &control.cancel));+ control.deny();+ assert!(+ upload_exported_video(PathBuf::new(), None, |_| {}, token)+ .await+ .unwrap_err()+ .contains("Export cancelled")+ );+ }++ #[tokio::test]+ async fn optional_legacy_step_and_uncancelled_export_step_keep_results() {+ assert_eq!(+ optional_upload_step(None, || async { Ok(7) })+ .await+ .unwrap(),+ 7+ );+ assert_eq!(+ checked_upload_step(&AtomicBool::new(false), || async { Ok(9) })+ .await+ .unwrap(),+ 9+ );+ let result: Result<(), _> = checked_upload_step(&AtomicBool::new(true), || async {+ panic!("No new request may be submitted")+ })+ .await;+ assert!(result.is_err());+ }}diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rsindex 111d9effe..f505e86b5 100644--- a/apps/desktop/src-tauri/src/camera.rs+++ b/apps/desktop/src-tauri/src/camera.rs@@ -24,7 +24,7 @@ use std::{},thread,};-use tauri::{LogicalPosition, LogicalSize, PhysicalSize, WebviewWindow};+use tauri::{LogicalPosition, LogicalSize, Manager, PhysicalSize, WebviewWindow};use tokio::{runtime::Runtime,sync::{broadcast, oneshot},@@ -392,6 +392,7 @@ impl CameraPreviewManager {window: WebviewWindow,actor: ActorRef<CameraFeed>,) -> anyhow::Result<()> {+ let reveal_generation = crate::clean_capture::generation(window.app_handle());if let Some(preview) = &mut self.preview {CameraPreviewSender::from_tx(preview.camera_tx.clone()).attach(&actor)@@ -411,7 +412,7 @@ impl CameraPreviewManager {.run_on_main_thread({let window = window.clone();move || {- let _ = window.show();+ let _ = crate::clean_capture::reveal_now(&window, reveal_generation);}}).ok();@@ -447,7 +448,7 @@ impl CameraPreviewManager {.run_on_main_thread({let window = window.clone();move || {- let _ = window.show();+ let _ = crate::clean_capture::reveal_now(&window, reveal_generation);}}).ok();diff --git a/apps/desktop/src-tauri/src/camera_legacy.rs b/apps/desktop/src-tauri/src/camera_legacy.rsindex 0c4690675..b929d9a8e 100644--- a/apps/desktop/src-tauri/src/camera_legacy.rs+++ b/apps/desktop/src-tauri/src/camera_legacy.rs@@ -16,9 +16,47 @@ const WS_READBACK_PENDING: u8 = 0;const WS_READBACK_READY_OK: u8 = 1;const WS_READBACK_READY_ERR: u8 = 2;+const WS_READBACK_CONSUMED: u8 = 3;++#[cfg(target_os = "linux")]+type OutputReceipt = Option<crate::linux_instant_camera::FrameReceipt>;+#[cfg(not(target_os = "linux"))]+#[derive(Default)]+struct PreviewReceipt;+#[cfg(not(target_os = "linux"))]+type OutputReceipt = PreviewReceipt;++struct ReadbackTicket {+ status: Arc<AtomicU8>,+ receipt: OutputReceipt,+}++impl ReadbackTicket {+ fn new(receipt: OutputReceipt) -> Self {+ Self {+ status: Arc::new(AtomicU8::new(WS_READBACK_PENDING)),+ receipt,+ }+ }++ fn take_ready(&mut self) -> Result<Option<OutputReceipt>, String> {+ match self.status.load(Ordering::Acquire) {+ WS_READBACK_READY_OK => {+ self.status.store(WS_READBACK_CONSUMED, Ordering::Release);+ Ok(Some(std::mem::take(&mut self.receipt)))+ }+ WS_READBACK_READY_ERR => {+ self.status.store(WS_READBACK_CONSUMED, Ordering::Release);+ Err("Requested camera blur GPU readback failed".into())+ }+ _ => Ok(None),+ }+ }+}+enum WsReadbackState {Idle,- InFlight(Arc<AtomicU8>),+ InFlight(ReadbackTicket),}struct WsReadback {@@ -26,6 +64,60 @@ struct WsReadback {state: WsReadbackState,}+struct BlurInput<'a> {+ rgba: &'a [u8],+ width: u32,+ height: u32,+ stride: u32,+ mode: cap_camera_effects::BlurMode,+ receipt: OutputReceipt,+}++struct BlurredFrame {+ data: Arc<Vec<u8>>,+ #[cfg(target_os = "linux")]+ receipt: Option<crate::linux_instant_camera::FrameReceipt>,+}++pub struct CameraPreviewWs {+ pub sender: Sender<FFmpegVideoFrame>,+ pub port: u16,+ pub shutdown: CancellationToken,+ #[cfg(target_os = "linux")]+ pub processing: crate::linux_instant_camera::ProcessingFactory,+}++#[cfg(target_os = "linux")]+enum WorkerEvent<F, C> {+ Frame(F),+ Command(C),+ Closed,+ Tick,+}++#[cfg(target_os = "linux")]+fn next_worker_event<F, C>(+ frames: &flume::Receiver<F>,+ commands: &flume::Receiver<C>,+ timeout: Option<Duration>,+) -> WorkerEvent<F, C> {+ let selector = flume::Selector::new()+ .recv(frames, |result| {+ result.map_or(WorkerEvent::Closed, WorkerEvent::Frame)+ })+ .recv(commands, |result| {+ result.map_or(WorkerEvent::Closed, WorkerEvent::Command)+ });+ match timeout {+ Some(timeout) => selector.wait_timeout(timeout).unwrap_or(WorkerEvent::Tick),+ None => selector.wait(),+ }+}++fn processing_needed(preview: bool, recording: bool) -> bool {+ preview || recording+}+const WS_PREVIEW_SURFACE_SCALE: u32 = 2;// Same drag-resize hysteresis as the native preview: only rebuild the scaler// and reallocate buffers when the target width crosses a 64px bucket.@@ -187,8 +279,10 @@ fn scaled_preview_dimensions(width: u32, height: u32, state: &CameraPreviewStatepub async fn create_camera_preview_ws(state_rx: watch::Receiver<CameraPreviewState>,-) -> (Sender<FFmpegVideoFrame>, u16, CancellationToken) {+) -> CameraPreviewWs {let (camera_tx, camera_rx) = flume::bounded::<FFmpegVideoFrame>(1);+ #[cfg(target_os = "linux")]+ let (processing, commands) = crate::linux_instant_camera::processing_channel();let (frame_tx, frame_rx) = watch::channel::<Option<Arc<WSFrame>>>(None);let subscriber_count = Arc::new(AtomicUsize::new(0));let instant_subscriber_count = Arc::new(AtomicUsize::new(0));@@ -226,20 +320,98 @@ pub async fn create_camera_preview_ws(let mut frame_pool: Vec<Arc<Vec<u8>>> = Vec::new();let mut frame_counter: u32 = 0;let mut idle = true;- while let Ok(raw_frame) = camera_rx.recv() {- let mut frame = raw_frame.inner;-- while let Ok(newer) = camera_rx.try_recv() {- frame = newer.inner;+ #[cfg(target_os = "linux")]+ let mut recording: Option<crate::linux_instant_camera::RecordingWork> = None;+ #[cfg(target_os = "linux")]+ let mut warm_until: Option<Instant> = None;+ loop {+ #[cfg(target_os = "linux")]+ if recording.as_ref().is_some_and(|work| work.cancelled()) {+ recording = None;+ warm_until = Some(Instant::now() + Duration::from_millis(500));}-+ #[cfg(target_os = "linux")]+ if let Some(deadline) = warm_until {+ if thread_subscriber_count.load(Ordering::Acquire) > 0 {+ warm_until = None;+ } else if Instant::now() >= deadline {+ converter = None;+ reusable_frame = None;+ frame_pool.clear();+ blur_state.release();+ last_preview_at = None;+ idle = true;+ warm_until = None;+ let _previous_frame = frame_tx_clone.send_replace(None);+ }+ }+ let input = &camera_rx;+ #[cfg(target_os = "linux")]+ let input = recording.as_ref().map_or(input, |work| &work.frames);+ #[cfg(target_os = "linux")]+ let raw_frame = {+ let timeout = if recording.is_some() {+ Some(Duration::from_millis(50))+ } else {+ warm_until.map(|deadline| deadline.saturating_duration_since(Instant::now()))+ };+ let event = next_worker_event(input, &commands, timeout);+ match event {+ WorkerEvent::Frame(frame) => frame,+ WorkerEvent::Command(work) => {+ if work.cancelled() {+ continue;+ }+ if recording.is_some() {+ work.fail("Another camera processing lease is active");+ continue;+ }+ warm_until = None;+ blur_state.begin_recording_epoch();+ last_preview_at = None;+ recording = Some(*work);+ continue;+ }+ WorkerEvent::Closed => break,+ WorkerEvent::Tick => continue,+ }+ };+ #[cfg(not(target_os = "linux"))]+ let raw_frame = match input.recv() {+ Ok(frame) => frame,+ Err(_) => break,+ };+ let mut raw_frame = raw_frame;+ while let Ok(newer) = input.try_recv() {+ raw_frame = newer;+ }+ #[cfg(target_os = "linux")]+ if let Some(work) = &recording {+ match work.accepts(raw_frame.timestamp) {+ Ok(true) => {}+ Ok(false) => continue,+ Err(error) => {+ work.fail(error);+ continue;+ }+ }+ }+ #[cfg(target_os = "linux")]+ let capture_timestamp = raw_frame.timestamp;+ let frame = raw_frame.inner;let instant_preview_active =thread_instant_subscriber_count.load(Ordering::Acquire) > 0;-- // With no connected ws clients, skip all conversion work and- // release retained resources; the cleared watch cell also stops- // stale frames from being replayed to the next connection.- if thread_subscriber_count.load(Ordering::Acquire) == 0 {+ let ws_active = thread_subscriber_count.load(Ordering::Acquire) > 0;+ #[cfg(target_os = "linux")]+ let recording_active = recording.is_some();+ #[cfg(not(target_os = "linux"))]+ let recording_active = false;+ let processing_active = processing_needed(ws_active, recording_active);+ if !processing_active {+ #[cfg(target_os = "linux")]+ if warm_until.is_some() {+ continue;+ }if !idle {idle = true;converter = None;@@ -252,14 +424,14 @@ pub async fn create_camera_preview_ws(continue;}idle = false;-let now = Instant::now();if !preview_frame_due(last_preview_at, now) {continue;}last_preview_at = Some(now);-let state = state_rx.borrow_and_update().clone();+ #[cfg(target_os = "linux")]+ let state = recording.as_ref().map_or(state, |work| work.state.clone());let blur_mode = state.background_blur;let blur_enabled = blur_mode != cap_project::BackgroundBlurMode::Off;let effects_mode = match blur_mode {@@ -268,7 +440,6 @@ pub async fn create_camera_preview_ws(}cap_project::BackgroundBlurMode::Heavy => cap_camera_effects::BlurMode::Heavy,};-let (mut target_width, mut target_height) =scaled_preview_dimensions(frame.width(), frame.height(), &state);let use_nv12 = cfg!(target_os = "macos")@@ -290,12 +461,10 @@ pub async fn create_camera_preview_ws(let needs_convert = frame.format() != output_pixel|| frame.width() != target_width|| frame.height() != target_height;-if !blur_enabled {blur_state.release();}-- if needs_convert {+ let output_frame = if needs_convert {let ctx = match &mut converter {Some((input_format, cached_output_format, ctx))if *input_format == frame.format()@@ -308,7 +477,7 @@ pub async fn create_camera_preview_ws(ctx}_ => {- let Ok(new_converter) = ffmpeg::software::scaling::Context::get(+ let new_converter = ffmpeg::software::scaling::Context::get(frame.format(),frame.width(),frame.height(),@@ -316,17 +485,20 @@ pub async fn create_camera_preview_ws(target_width,target_height,ffmpeg::software::scaling::flag::Flags::FAST_BILINEAR,- ) else {+ );+ let Ok(new_converter) = new_converter else {+ #[cfg(target_os = "linux")]+ if let Some(work) = &recording {+ work.fail("Camera pixel conversion is unavailable");+ }continue;};-reusable_frame = None;&mut converter.insert((frame.format(), output_pixel, new_converter)).2}};-let out_frame = reusable_frame.get_or_insert_with(|| {ffmpeg::util::frame::Video::new(output_pixel,@@ -334,59 +506,66 @@ pub async fn create_camera_preview_ws(ctx.output().height,)});-if ctx.run(&frame, out_frame).is_err() {+ #[cfg(target_os = "linux")]+ if let Some(work) = &recording {+ work.fail("Camera pixel conversion failed");+ }continue;}-- let width = out_frame.width();- let height = out_frame.height();- let src_stride = out_frame.stride(0) as u32;- let (data, stride) = if blur_enabled {- blur_state.process(- out_frame.data(0),- width,- height,- src_stride,- effects_mode,- &mut frame_pool,- )- } else {- None- }- .map(|data| (data, width * 4))- .unwrap_or_else(|| prepare_ws_data(out_frame, output_format, &mut frame_pool));-- frame_counter = frame_counter.wrapping_add(1);- let _previous_frame = frame_tx_clone.send_replace(Some(Arc::new(WSFrame {- data,- width,- height,- stride,- frame_number: frame_counter,- target_time_ns: 0,- format: output_format,- created_at: Instant::now(),- })));+ &*out_frame} else {- let width = frame.width();- let height = frame.height();- let src_stride = frame.stride(0) as u32;- let (data, stride) = if blur_enabled {- blur_state.process(- frame.data(0),+ &frame+ };+ let width = output_frame.width();+ let height = output_frame.height();+ #[cfg(target_os = "linux")]+ let receipt = recording+ .as_ref()+ .map(|work| work.receipt(capture_timestamp, (width, height)));+ let blurred = if blur_enabled {+ blur_state.process(+ BlurInput {+ rgba: output_frame.data(0),width,height,- src_stride,- effects_mode,- &mut frame_pool,- )+ stride: output_frame.stride(0) as u32,+ mode: effects_mode,+ #[cfg(target_os = "linux")]+ receipt: receipt.clone(),+ #[cfg(not(target_os = "linux"))]+ receipt: PreviewReceipt,+ },+ &mut frame_pool,+ )+ } else {+ Ok(None)+ };+ #[cfg(target_os = "linux")]+ if let Some(work) = &recording {+ if !blur_enabled {+ let (data, _) = prepare_ws_data(output_frame, output_format, &mut frame_pool);+ work.publish(&data, receipt.unwrap());} else {- None+ match &blurred {+ Ok(Some(output)) => {+ if let Some(receipt) = output.receipt.clone() {+ work.publish(&output.data, receipt);+ }+ }+ Ok(None) => {}+ Err(error) => work.fail(error.clone()),+ }}- .map(|data| (data, width * 4))- .unwrap_or_else(|| prepare_ws_data(&frame, output_format, &mut frame_pool));-+ }+ if ws_active {+ let (data, stride) = blurred+ .ok()+ .flatten()+ .map(|frame| (frame.data, width * 4))+ .unwrap_or_else(|| {+ prepare_ws_data(output_frame, output_format, &mut frame_pool)+ });frame_counter = frame_counter.wrapping_add(1);let _previous_frame = frame_tx_clone.send_replace(Some(Arc::new(WSFrame {data,@@ -398,6 +577,8 @@ pub async fn create_camera_preview_ws(format: output_format,created_at: Instant::now(),})));+ } else {+ frame_tx_clone.send_if_modified(|frame| frame.take().is_some());}}});@@ -408,7 +589,13 @@ pub async fn create_camera_preview_ws().await;- (camera_tx, camera_ws_port, _shutdown)+ CameraPreviewWs {+ sender: camera_tx,+ port: camera_ws_port,+ shutdown: _shutdown,+ #[cfg(target_os = "linux")]+ processing,+ }}struct WsBlurState {@@ -433,6 +620,17 @@ impl WsBlurState {}}+ #[cfg(target_os = "linux")]+ fn begin_recording_epoch(&mut self) {+ if let Some(resources) = &mut self.processor {+ resources.readbacks = None;+ resources.current_idx = 0;+ resources.processor.reset_mask_history();+ } else {+ self.init_attempted = false;+ }+ }+// Drops the dedicated wgpu device, ONNX session, and readback buffers as// soon as blur is off; re-enabling re-runs the lazy init.fn release(&mut self) {@@ -445,30 +643,37 @@ impl WsBlurState {fn process(&mut self,- rgba_data: &[u8],- width: u32,- height: u32,- stride: u32,- mode: cap_camera_effects::BlurMode,+ input: BlurInput<'_>,pool: &mut Vec<Arc<Vec<u8>>>,- ) -> Option<Arc<Vec<u8>>> {- // Low-spec: never spin up the headless ONNX/wgpu blur processor (the- // heaviest preview cost). Returning `None` makes the caller fall back to- // packing the raw camera rows, so the preview is unblurred but cheap.- // The UI blur toggle is unaffected; it just has no visual effect here.- // Same fallback when crash recovery disabled blur: bail before creating- // any GPU resources at all, since the whole blur stack is suspect on- // this machine.+ ) -> Result<Option<BlurredFrame>, String> {+ let BlurInput {+ rgba: rgba_data,+ width,+ height,+ stride,+ mode,+ receipt,+ } = input;+ // Idle preview keeps its compatibility fallback; recording requires this error to stay terminal.if is_low_spec_preview() || cap_camera_effects::blur_disabled() {- return None;+ return Err("Requested camera blur is disabled or unavailable on this device".into());}if !self.init_attempted {self.init_attempted = true;- self.processor = init_headless_blur();+ self.processor = Some(init_headless_blur()?);}- let res = self.processor.as_mut()?;+ let res = self+ .processor+ .as_mut()+ .ok_or("Requested camera blur initialization failed")?;++ #[cfg(target_os = "linux")]+ if receipt.as_ref().is_some_and(|receipt| matches!(receipt.timestamp,+ cap_timestamp::Timestamp::Instant(captured) if captured.elapsed() > Duration::from_secs(1))) {+ return Ok(None);+ }let src = match &res.source_texture {Some((w, h, t)) if *w == width && *h == height => t,@@ -563,7 +768,15 @@ impl WsBlurState {bytes_per_row_aligned,pool,);- let blurred_out = prev_data.or(curr_data);+ #[cfg(target_os = "linux")]+ let require_verified_output = receipt.is_some();+ #[cfg(not(target_os = "linux"))]+ let require_verified_output = false;+ let blurred_out = if require_verified_output {+ prev_data?.or(curr_data?)+ } else {+ prev_data.ok().flatten().or(curr_data.ok().flatten())+ };let issue_idx = if matches!(res.readbacks.as_ref().unwrap().2[current_idx].state,@@ -610,27 +823,32 @@ impl WsBlurState {},);+ #[cfg(target_os = "linux")]+ let receipt = receipt.map(|mut receipt| {+ receipt.blur = res.processor.output_status();+ receipt+ });res.queue.submit(std::iter::once(encoder.finish()));-- let status = Arc::new(AtomicU8::new(WS_READBACK_PENDING));- let status_cb = status.clone();+ let ticket = ReadbackTicket::new(receipt);+ let status_cb = ticket.status.clone();res.readbacks.as_ref().unwrap().2[idx].buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| {- let code = if result.is_ok() {- WS_READBACK_READY_OK- } else {- WS_READBACK_READY_ERR- };- status_cb.store(code, Ordering::Release);+ status_cb.store(+ if result.is_ok() {+ WS_READBACK_READY_OK+ } else {+ WS_READBACK_READY_ERR+ },+ Ordering::Release,+ );});-- res.readbacks.as_mut().unwrap().2[idx].state = WsReadbackState::InFlight(status);+ res.readbacks.as_mut().unwrap().2[idx].state = WsReadbackState::InFlight(ticket);res.current_idx = 1 - idx;}- blurred_out+ Ok(blurred_out)}}@@ -640,36 +858,42 @@ fn try_drain_readback(height: u32,bytes_per_row_aligned: u32,pool: &mut Vec<Arc<Vec<u8>>>,-) -> Option<Arc<Vec<u8>>> {- let WsReadbackState::InFlight(status) = &readback.state else {- return None;+) -> Result<Option<BlurredFrame>, String> {+ let WsReadbackState::InFlight(ticket) = &mut readback.state else {+ return Ok(None);};- match status.load(Ordering::Acquire) {- WS_READBACK_READY_OK => {- let slice = readback.buffer.slice(..);- let data = slice.get_mapped_range();- let row_bytes = (width * 4) as usize;- let out = with_pooled_buffer(pool, |vec| {- vec.reserve(row_bytes * height as usize);- for row in 0..height as usize {- let start = row * bytes_per_row_aligned as usize;- vec.extend_from_slice(&data[start..start + row_bytes]);- }- });- drop(data);+ let receipt = match ticket.take_ready() {+ Ok(Some(receipt)) => receipt,+ Ok(None) => return Ok(None),+ Err(error) => {readback.buffer.unmap();readback.state = WsReadbackState::Idle;- Some(out)+ return Err(error);}- WS_READBACK_READY_ERR => {- readback.state = WsReadbackState::Idle;- None+ };+ let slice = readback.buffer.slice(..);+ let data = slice.get_mapped_range();+ let row_bytes = (width * 4) as usize;+ let out = with_pooled_buffer(pool, |vec| {+ vec.reserve(row_bytes * height as usize);+ for row in 0..height as usize {+ let start = row * bytes_per_row_aligned as usize;+ vec.extend_from_slice(&data[start..start + row_bytes]);}- _ => None,- }+ });+ drop(data);+ readback.buffer.unmap();+ readback.state = WsReadbackState::Idle;+ #[cfg(not(target_os = "linux"))]+ let _ = receipt;+ Ok(Some(BlurredFrame {+ data: out,+ #[cfg(target_os = "linux")]+ receipt,+ }))}-fn init_headless_blur() -> Option<WsBlurResources> {+fn init_headless_blur() -> Result<WsBlurResources, String> {// Arm the sentinel's blur marker around the blur-dedicated wgpu// adapter/device setup too, so a native death here is attributed to blur.// Deliberately not `enter_gpu_init_phase`: that would cross-trigger WARP@@ -690,7 +914,7 @@ fn init_headless_blur() -> Option<WsBlurResources> {force_fallback_adapter: force_software_adapter,compatible_surface: None,}))- .ok()?;+ .map_err(|error| format!("Camera blur adapter unavailable: {error}"))?;let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {label: Some("WS Blur Device"),@@ -700,15 +924,16 @@ fn init_headless_blur() -> Option<WsBlurResources> {memory_hints: Default::default(),trace: wgpu::Trace::Off,}))- .ok()?;+ .map_err(|error| format!("Camera blur device unavailable: {error}"))?;let mut processor =- cap_camera_effects::BlurProcessor::new(&device, wgpu::TextureFormat::Rgba8Unorm).ok()?;+ cap_camera_effects::BlurProcessor::new(&device, wgpu::TextureFormat::Rgba8Unorm)+ .map_err(|error| format!("Camera blur processor unavailable: {error}"))?;processor.set_inference_interval(WS_BLUR_INFERENCE_INTERVAL);tracing::info!("WebSocket camera blur processor initialized (headless)");- Some(WsBlurResources {+ Ok(WsBlurResources {device,queue,processor,@@ -741,4 +966,104 @@ mod tests {assert_eq!(dst, src);}++ #[cfg(target_os = "linux")]+ fn receipt(generation: u64, captured: Instant) -> crate::linux_instant_camera::FrameReceipt {+ crate::linux_instant_camera::FrameReceipt {+ timestamp: cap_timestamp::Timestamp::Instant(captured),+ generation,+ processing: cap_recording::instant_recording::LinuxCameraProcessing {+ mirrored: false,+ blur: cap_recording::instant_recording::LinuxCameraBlur::Off,+ },+ dimensions: (2, 1),+ blur: None,+ }+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn asynchronous_readback_keeps_its_original_capture_and_generation() {+ let first = Instant::now();+ let second = first + Duration::from_millis(10);+ let mut a = ReadbackTicket::new(Some(receipt(7, first)));+ let mut b = ReadbackTicket::new(Some(receipt(8, second)));+ let a_ready = a.status.clone();+ let b_ready = b.status.clone();+ let (release, delayed) = tokio::sync::oneshot::channel();+ let (ready, notified) = tokio::sync::oneshot::channel();+ let worker = tokio::spawn(async move {+ b_ready.store(WS_READBACK_READY_OK, Ordering::Release);+ ready.send(()).unwrap();+ delayed.await.unwrap();+ a_ready.store(WS_READBACK_READY_OK, Ordering::Release);+ });+ notified.await.unwrap();+ assert!(a.take_ready().unwrap().is_none());+ let newer = b.take_ready().unwrap().unwrap().unwrap();+ assert_eq!(newer.generation, 8);+ assert!(matches!(newer.timestamp,cap_timestamp::Timestamp::Instant(at) if at==second));+ assert!(b.take_ready().unwrap().is_none());+ release.send(()).unwrap();+ worker.await.unwrap();+ let older = a.take_ready().unwrap().unwrap().unwrap();+ assert_eq!(older.generation, 7);+ assert!(matches!(older.timestamp,cap_timestamp::Timestamp::Instant(at) if at==first));+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn cancelled_readback_callback_cannot_certify_a_new_lease() {+ let old = ReadbackTicket::new(Some(receipt(1, Instant::now())));+ let callback = old.status.clone();+ drop(old);+ let mut fresh = ReadbackTicket::new(Some(receipt(2, Instant::now())));+ tokio::spawn(async move {+ callback.store(WS_READBACK_READY_OK, Ordering::Release);+ })+ .await+ .unwrap();+ assert!(fresh.take_ready().unwrap().is_none());+ fresh.status.store(WS_READBACK_READY_ERR, Ordering::Release);+ assert!(fresh.take_ready().is_err());+ assert!(fresh.take_ready().unwrap().is_none());+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn hidden_websocket_does_not_disable_recording_demand_or_command_delivery() {+ let (frame_tx, frames) = flume::bounded::<u32>(2);+ let (command_tx, commands) = flume::bounded::<u32>(1);+ let frame_input = frames.clone();+ let command_input = commands.clone();+ let waiting = tokio::task::spawn_blocking(move || {+ next_worker_event(&frame_input, &command_input, None)+ });+ command_tx.send_async(7).await.unwrap();+ assert!(matches!(waiting.await.unwrap(), WorkerEvent::Command(7)));+ assert!(processing_needed(false, true));+ frame_tx.send_async(42).await.unwrap();+ assert!(matches!(+ next_worker_event(&frames, &commands, Some(Duration::from_secs(1))),+ WorkerEvent::Frame(42)+ ));+ assert!(!processing_needed(false, false));+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn active_worker_polls_cancellation_without_needing_a_camera_frame() {+ let (_frame_tx, frames) = flume::bounded::<u32>(2);+ let (_command_tx, commands) = flume::bounded::<u32>(1);+ let waiting = tokio::task::spawn_blocking(move || {+ next_worker_event(&frames, &commands, Some(Duration::from_millis(1)))+ });+ assert!(matches!(+ tokio::time::timeout(Duration::from_secs(1), waiting)+ .await+ .unwrap()+ .unwrap(),+ WorkerEvent::Tick+ ));+ }}diff --git a/apps/desktop/src-tauri/src/clean_capture.rs b/apps/desktop/src-tauri/src/clean_capture.rsnew file mode 100644index 000000000..79e613247--- /dev/null+++ b/apps/desktop/src-tauri/src/clean_capture.rs@@ -0,0 +1,4195 @@+use std::{path::PathBuf, sync::Mutex, time::Duration};++use serde::Serialize;+use specta::Type;+use tauri::{AppHandle, Manager, WebviewWindow};+use tauri_specta::Event;+use tokio::sync::Notify;++use crate::{CurrentRecordingChanged, windows::CapWindowId};++pub const STOP_SHORTCUT: &str = "Ctrl+Shift+F9";++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Type)]+#[serde(rename_all = "camelCase")]+pub enum Phase {+ AwaitingShortcut,+ Starting,+ Recording,+ Pausing,+ Paused,+ Resuming,+ ResumeFailed,+ Restarting,+ Stopping,+ Restoring,+}++impl Phase {+ fn can_stop(self) -> bool {+ matches!(+ self,+ Self::Recording | Self::Paused | Self::Resuming | Self::ResumeFailed+ )+ }+}++#[derive(Clone, Serialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct Snapshot {+ pub generation: u32,+ pub phase: Option<Phase>,+ pub mode: Option<cap_recording::RecordingMode>,+ pub shortcut: Option<String>,+ pub error: Option<String>,+}++#[derive(Clone)]+struct SavedWindow {+ label: String,+ native_id: u64,+ visible: bool,+}++impl SavedWindow {+ fn visibility_for(&self, native_id: u64) -> Option<bool> {+ (self.native_id == native_id).then_some(self.visible)+ }+}++#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum StopRoute {+ Tray,+ Portal,+}++struct Lease {+ mode: cap_recording::RecordingMode,+ generation: u32,+ phase: Phase,+ pressed: bool,+ stop_requested: bool,+ registered_shortcut: bool,+ wayland: bool,+ stop_route: Option<StopRoute>,+ stop_description: Option<String>,+ stop_error: Option<String>,+ lost_stop_routes: [bool; 2],+ recording_dir: Option<PathBuf>,+ windows: Vec<SavedWindow>,+}++impl StopRoute {+ fn index(self) -> usize {+ match self {+ Self::Tray => 0,+ Self::Portal => 1,+ }+ }+}++impl Lease {+ fn accept_stop_input(&mut self, route: Option<(u32, StopRoute)>, pressed: bool) -> bool {+ match route {+ Some((generation, route))+ if self.wayland+ && self.generation == generation+ && !self.lost_stop_routes[route.index()] =>+ {+ if self.phase == Phase::AwaitingShortcut {+ if pressed {+ self.stop_route = Some(route);+ } else if self.stop_route != Some(route) {+ return false;+ }+ }+ true+ }+ None if !self.wayland => true,+ _ => false,+ }+ }++ #[cfg(any(target_os = "linux", test))]+ fn lose_stop_route(&mut self, route: StopRoute) -> bool {+ self.lost_stop_routes[route.index()] = true;+ let lost = self.stop_route == Some(route) || self.lost_stop_routes.iter().all(|lost| *lost);+ if lost {+ self.stop_requested = true;+ }+ lost && self.phase.can_stop()+ }+}++struct ControlError {+ generation: u32,+ dir: PathBuf,+ message: String,+}++struct RestorationReceipt {+ generation: u32,+ result: Result<(), String>,+ #[cfg(target_os = "linux")]+ stop_requested: bool,+}++impl RestorationReceipt {+ #[cfg(target_os = "linux")]+ fn restart_result(&self) -> Result<(), String> {+ self.result.clone()?;+ if self.stop_requested {+ Err("Recording restart was cancelled by Stop".into())+ } else {+ Ok(())+ }+ }+}++#[derive(Default)]+struct Inner {+ generation: u32,+ lease: Option<Lease>,+ control_error: Option<ControlError>,+ restored: Option<RestorationReceipt>,+ #[cfg(target_os = "linux")]+ x11_cleanup_sequence: u64,+ #[cfg(target_os = "linux")]+ x11_cleanup: Option<X11StudioCleanup>,+}++#[cfg(target_os = "linux")]+#[derive(Clone, Copy, PartialEq, Eq)]+struct X11StudioCleanup {+ generation: u32,+ sequence: u64,+ registered_shortcut: bool,+}++#[derive(Default)]+pub struct State {+ #[cfg(target_os = "linux")]+ pub(crate) instant: Mutex<Option<crate::recording::linux_instant::Attempt>>,+ #[cfg(target_os = "linux")]+ pub(crate) portal_stop: tokio::sync::Mutex<Option<crate::hotkeys::WaylandStop>>,+ inner: Mutex<Inner>,+ changed: Notify,+}++impl Inner {+ #[cfg(target_os = "linux")]+ fn reserve_x11_studio_cleanup(+ &mut self,+ generation: u32,+ windows: Result<(), String>,+ ) -> Option<X11StudioCleanup> {+ if self.x11_cleanup.is_some()+ || self+ .restored+ .as_ref()+ .is_some_and(|receipt| receipt.generation == generation)+ {+ return None;+ }+ let lease = self.lease.as_ref().filter(|lease| {+ self.generation == generation+ && lease.generation == generation+ && lease.phase == Phase::Restoring+ && lease.mode == cap_recording::RecordingMode::Studio+ && !lease.wayland+ })?;+ let registered_shortcut = lease.registered_shortcut;+ if let Err(error) = windows {+ let _ = self.complete_instant_restoration(generation, Err(error));+ return None;+ }+ self.x11_cleanup_sequence = self.x11_cleanup_sequence.wrapping_add(1);+ let cleanup = X11StudioCleanup {+ generation,+ sequence: self.x11_cleanup_sequence,+ registered_shortcut,+ };+ self.x11_cleanup = Some(cleanup);+ Some(cleanup)+ }++ #[cfg(target_os = "linux")]+ fn complete_x11_studio_restoration(+ &mut self,+ cleanup: X11StudioCleanup,+ result: Result<(), String>,+ ) -> bool {+ if self.x11_cleanup != Some(cleanup)+ || self.generation != cleanup.generation+ || self.lease.as_ref().is_none_or(|lease| {+ lease.generation != cleanup.generation+ || lease.phase != Phase::Restoring+ || lease.mode != cap_recording::RecordingMode::Studio+ || lease.wayland+ || lease.registered_shortcut != cleanup.registered_shortcut+ })+ {+ return false;+ }+ self.x11_cleanup = None;+ self.complete_instant_restoration(cleanup.generation, result)+ .is_some()+ }++ #[cfg(target_os = "linux")]+ fn begin_x11_studio_restore_retry(&mut self, pressed: bool) -> Option<u32> {+ if !pressed || self.x11_cleanup.is_some() {+ return None;+ }+ let generation = self.generation;+ let lease = self.lease.as_mut().filter(|lease| {+ lease.generation == generation+ && lease.phase == Phase::Restoring+ && lease.mode == cap_recording::RecordingMode::Studio+ && !lease.wayland+ })?;+ if !self.restored.as_ref().is_some_and(|receipt| {+ receipt.generation == lease.generation && receipt.result.is_err()+ }) {+ return None;+ }+ lease.stop_requested = true;+ self.restored = None;+ Some(lease.generation)+ }++ #[cfg(target_os = "linux")]+ fn complete_instant_restoration(+ &mut self,+ generation: u32,+ result: Result<(), String>,+ ) -> Option<bool> {+ if self+ .lease+ .as_ref()+ .is_none_or(|lease| lease.generation != generation || lease.phase != Phase::Restoring)+ {+ return None;+ }+ let succeeded = result.is_ok();+ self.restored = Some(RestorationReceipt {+ generation,+ result,+ stop_requested: self.lease.as_ref().unwrap().stop_requested,+ });+ if succeeded {+ let owned = self.lease.take().unwrap().registered_shortcut;+ self.generation = self.generation.wrapping_add(1);+ Some(owned)+ } else {+ None+ }+ }++ fn owner(&self, dir: &std::path::Path) -> Option<u32> {+ self.lease.as_ref().and_then(|lease| {+ (lease.recording_dir.as_deref() == Some(dir)).then_some(lease.generation)+ })+ }+ fn queue_stop(&mut self) -> bool {+ let Some(lease) = self.lease.as_mut() else {+ return false;+ };+ lease.stop_requested = true;+ let deferred = !lease.phase.can_stop();+ if !deferred {+ lease.phase = Phase::Stopping;+ }+ deferred+ }++ fn control_current(&self, generation: u32, dir: &std::path::Path, resume: bool) -> bool {+ let transition = if resume {+ Phase::Resuming+ } else {+ Phase::Pausing+ };+ self.generation == generation+ && self.lease.as_ref().is_some_and(|lease| {+ lease.generation == generation+ && lease.phase == transition+ && lease.recording_dir.as_deref() == Some(dir)+ })+ }++ fn complete_control(+ &mut self,+ generation: u32,+ dir: &std::path::Path,+ resume: bool,+ outcome: &ControlOutcome,+ ) -> bool {+ if !self.control_current(generation, dir, resume) {+ return false;+ }+ self.control_error = match outcome {+ ControlOutcome::Succeeded | ControlOutcome::StoppedBeforeResume => None,+ ControlOutcome::HideFailed(message)+ | ControlOutcome::ActorFailed { error: message, .. } => Some(ControlError {+ generation,+ dir: dir.to_path_buf(),+ message: message.clone(),+ }),+ };+ self.lease.as_mut().unwrap().phase = match (resume, outcome) {+ (true, ControlOutcome::Succeeded) | (false, ControlOutcome::ActorFailed { .. }) => {+ Phase::Recording+ }+ (true, ControlOutcome::ActorFailed { paused: false, .. }) => Phase::ResumeFailed,+ _ => Phase::Paused,+ };+ true+ }++ fn may_restore_paused_main(&self, generation: u32, dir: &std::path::Path) -> bool {+ self.owner(dir) == Some(generation)+ && self+ .lease+ .as_ref()+ .is_some_and(|lease| lease.phase == Phase::Paused && !lease.stop_requested)+ && self.may_reveal(generation, "main")+ }++ fn snapshot(&self) -> Snapshot {+ Snapshot {+ generation: self.generation,+ phase: self.lease.as_ref().map(|lease| lease.phase),+ mode: self.lease.as_ref().map(|lease| lease.mode),+ shortcut: self.lease.as_ref().map(|lease| {+ lease.stop_description.clone().unwrap_or_else(|| {+ if lease.wayland {+ "the Cap Stop tray icon".to_string()+ } else {+ STOP_SHORTCUT.to_string()+ }+ })+ }),+ error: self+ .control_error+ .as_ref()+ .filter(|error| {+ error.generation == self.generation+ && self+ .lease+ .as_ref()+ .is_none_or(|lease| lease.recording_dir.as_ref() == Some(&error.dir))+ })+ .map(|error| error.message.clone())+ .or_else(|| {+ self.lease+ .as_ref()+ .and_then(|lease| lease.stop_error.clone())+ })+ .or_else(|| {+ self.restored.as_ref().and_then(|receipt| {+ self.lease+ .as_ref()+ .filter(|lease| lease.generation == receipt.generation)+ .and_then(|_| receipt.result.as_ref().err().cloned())+ })+ }),+ }+ }++ fn may_reveal(&self, generation: u32, label: &str) -> bool {+ if generation != self.generation {+ return false;+ }+ let Some(lease) = &self.lease else {+ return true;+ };+ if lease.wayland && wayland_blocks_mapping(lease.phase) {+ return false;+ }+ match label.parse::<CapWindowId>() {+ Ok(CapWindowId::Main) => {+ matches!(+ lease.phase,+ Phase::AwaitingShortcut | Phase::Paused | Phase::Restoring+ ) && (!lease.stop_requested || lease.phase == Phase::Restoring)+ }+ Ok(+ CapWindowId::Camera+ | CapWindowId::RecordingControls+ | CapWindowId::TargetSelectOverlay { .. },+ ) => false,+ _ => true,+ }+ }++ fn shortcut(&mut self, pressed: bool) -> bool {+ let Some(lease) = self.lease.as_mut() else {+ return false;+ };+ if lease.phase == Phase::AwaitingShortcut {+ if pressed {+ lease.pressed = true;+ } else if lease.pressed {+ lease.phase = Phase::Starting;+ lease.pressed = false;+ }+ } else if pressed {+ lease.stop_requested = true;+ }+ true+ }+}++pub fn generation(app: &AppHandle) -> u32 {+ app.try_state::<State>()+ .map(|state| state.inner.lock().unwrap().generation)+ .unwrap_or(0)+}++pub fn phase(app: &AppHandle) -> Option<Phase> {+ app.try_state::<State>()+ .and_then(|state| state.inner.lock().unwrap().lease.as_ref().map(|l| l.phase))+}++pub fn blocks_idle_cleanup(app: &AppHandle) -> bool {+ #[cfg(target_os = "linux")]+ if crate::recording::linux_instant::current(app).is_some() {+ return true;+ }+ phase(app).is_some_and(|phase| phase != Phase::Restoring)+}++pub fn cancel_closed_preflight(app: &AppHandle) {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ let Some(lease) = inner+ .lease+ .as_mut()+ .filter(|lease| lease.phase == Phase::AwaitingShortcut)+ else {+ return;+ };+ lease.stop_requested = true;+ for saved in &mut lease.windows {+ if saved.label == CapWindowId::Main.label() {+ saved.visible = false;+ }+ }+ drop(inner);+ notify(app);+}++pub fn is_current(app: &AppHandle, generation: u32) -> bool {+ app.state::<State>()+ .inner+ .lock()+ .unwrap()+ .lease+ .as_ref()+ .is_some_and(|lease| lease.generation == generation)+}++pub fn stop_requested(app: &AppHandle, generation: u32) -> bool {+ app.state::<State>()+ .inner+ .lock()+ .unwrap()+ .lease+ .as_ref()+ .filter(|lease| lease.generation == generation)+ .is_none_or(|lease| lease.stop_requested)+}++fn notify(app: &AppHandle) {+ app.state::<State>().changed.notify_waiters();+ let _ = CurrentRecordingChanged.emit(app);+}++pub fn set_phase(app: &AppHandle, generation: u32, phase: Phase) -> bool {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ let Some(lease) = inner.lease.as_mut().filter(|l| l.generation == generation) else {+ return false;+ };+ lease.phase = phase;+ drop(inner);+ notify(app);+ true+}++pub fn publish(app: &AppHandle, generation: u32, dir: PathBuf) -> bool {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ let Some(lease) = inner.lease.as_mut().filter(|l| l.generation == generation) else {+ return false;+ };+ if lease.phase != Phase::Starting {+ return false;+ }+ lease.recording_dir = Some(dir);+ lease.phase = Phase::Recording;+ true+}++pub fn set_start_directory(app: &AppHandle, generation: u32, dir: PathBuf) -> Result<(), String> {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ let lease = inner+ .lease+ .as_mut()+ .filter(|lease| lease.generation == generation && lease.phase == Phase::Starting)+ .ok_or("Recording startup was superseded")?;+ lease.recording_dir = Some(dir);+ Ok(())+}++pub fn owner(app: &AppHandle, dir: &std::path::Path) -> Option<u32> {+ let state = app.state::<State>();+ let inner = state.inner.lock().unwrap();+ inner.owner(dir)+}++pub fn queue_stop(app: &AppHandle) -> bool {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ if inner.lease.is_none() {+ return false;+ }+ let deferred = inner.queue_stop();+ drop(inner);+ notify(app);+ deferred+}++pub fn handle_shortcut(app: &AppHandle, pressed: bool) -> bool {+ handle_stop_input(app, pressed, None)+}++#[cfg(target_os = "linux")]+pub(crate) fn handle_wayland_stop(+ app: &AppHandle,+ generation: u32,+ route: StopRoute,+ pressed: bool,+) -> bool {+ handle_stop_input(app, pressed, Some((generation, route)))+}++fn handle_stop_input(app: &AppHandle, pressed: bool, route: Option<(u32, StopRoute)>) -> bool {+ let Some(state) = app.try_state::<State>() else {+ return false;+ };+ let mut inner = state.inner.lock().unwrap();+ if !inner+ .lease+ .as_mut()+ .is_some_and(|lease| lease.accept_stop_input(route, pressed))+ {+ return false;+ }+ #[cfg(target_os = "linux")]+ if let Some(generation) = inner.begin_x11_studio_restore_retry(pressed) {+ drop(inner);+ spawn_x11_studio_restore(app.clone(), generation, true);+ return true;+ }+ #[cfg(target_os = "linux")]+ if pressed+ && inner.lease.as_ref().is_some_and(|lease| {+ (lease.mode == cap_recording::RecordingMode::Instant || lease.wayland)+ && lease.phase == Phase::Restoring+ })+ && inner+ .restored+ .as_ref()+ .is_some_and(|receipt| receipt.result.is_err())+ {+ let generation = inner.lease.as_ref().unwrap().generation;+ inner.restored = None;+ drop(inner);+ spawn_instant_restore(app.clone(), generation, true);+ return true;+ }+ #[cfg(target_os = "linux")]+ let instant_stop = pressed+ && crate::recording::linux_instant::current(app).is_some()+ && inner+ .lease+ .as_ref()+ .is_some_and(|lease| lease.phase != Phase::AwaitingShortcut);+ let handled = inner.shortcut(pressed);+ let stop = handled+ && pressed+ && inner+ .lease+ .as_ref()+ .is_some_and(|lease| lease.phase.can_stop());+ #[cfg(target_os = "linux")]+ let stop = stop || (handled && instant_stop);+ drop(inner);+ if handled {+ notify(app);+ }+ if stop {+ let app = app.clone();+ drop(tauri::async_runtime::spawn(async move {+ if let Err(error) = crate::recording::stop_recording(app.clone(), app.state()).await {+ tracing::error!(%error, "Clean capture shortcut could not stop recording");+ }+ }));+ }+ handled+}++pub fn reveal_now(window: &WebviewWindow, expected_generation: u32) -> tauri::Result<bool> {+ reveal_now_with_options(window, expected_generation, false, false)+}++pub fn schedule_overlay_reveal(window: &WebviewWindow, generation: u32, focus: bool) {+ let handle = window.clone();+ let _ = window.run_on_main_thread(move || {+ let result = reveal_now_with_options(&handle, generation, focus, false);+ if matches!(result, Ok(true)) {+ let _ = handle.set_ignore_cursor_events(false);+ }+ });+}++pub fn schedule_overlay_focus(window: &WebviewWindow, generation: u32) {+ let handle = window.clone();+ let _ = window.run_on_main_thread(move || {+ let allowed = handle+ .app_handle()+ .state::<State>()+ .inner+ .lock()+ .unwrap()+ .may_reveal(generation, handle.label());+ if allowed {+ let _ = handle.set_focus();+ }+ });+}++fn reveal_now_with_options(+ window: &WebviewWindow,+ expected_generation: u32,+ focus: bool,+ unminimize: bool,+) -> tauri::Result<bool> {+ let app = window.app_handle();+ #[cfg(target_os = "linux")]+ if crate::recording::linux_instant::current(app)+ .is_some_and(|attempt| attempt.has_capture() && !attempt.ui_ready())+ {+ return Ok(false);+ }+ let Some(state) = app.try_state::<State>() else {+ window.show()?;+ return Ok(true);+ };+ let inner = state.inner.lock().unwrap();+ if !inner.may_reveal(expected_generation, window.label()) {+ #[cfg(target_os = "linux")]+ let deferred_editor = inner.lease.as_ref().is_some_and(|lease| {+ lease.wayland+ && lease.generation == expected_generation+ && lease.phase == Phase::Stopping+ && matches!(window.label().parse(), Ok(CapWindowId::Editor { .. }))+ });+ drop(inner);+ #[cfg(target_os = "linux")]+ if deferred_editor {+ use gtk::prelude::*;+ let native = window.gtk_window()?;+ remember_wayland_window(app, expected_generation, native.upcast_ref(), true);+ }+ return Ok(false);+ }+ // Mapping runs on the UI thread; a new capture must acknowledge its queued hide+ // before starting. Do not retain this mutex across synchronous GTK callbacks.+ drop(inner);+ set_native_visibility(window, true)+ .map_err(|error| tauri::Error::Io(std::io::Error::other(error)))?;+ if unminimize {+ window.unminimize()?;+ }+ if focus {+ window.set_focus()?;+ }+ Ok(true)+}++pub async fn reveal(window: WebviewWindow, expected_generation: u32) -> Result<bool, String> {+ reveal_with_options(window, expected_generation, false, false).await+}++async fn reveal_with_options(+ window: WebviewWindow,+ expected_generation: u32,+ focus: bool,+ unminimize: bool,+) -> Result<bool, String> {+ #[cfg(target_os = "linux")]+ if window.label() == CapWindowId::Main.label()+ && let Some(attempt) = crate::recording::linux_instant::current(window.app_handle())+ && attempt.has_capture()+ && !attempt.ui_ready()+ {+ crate::recording::linux_instant::control(window.app_handle().clone(), attempt, false)+ .await?;+ }+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = window.clone();+ window+ .run_on_main_thread(move || {+ let _ = tx.send(+ reveal_now_with_options(&handle, expected_generation, focus, unminimize)+ .map_err(|e| e.to_string()),+ );+ })+ .map_err(|e| e.to_string())?;+ tokio::time::timeout(Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Timed out revealing recording window".to_string())?+ .map_err(|_| "Recording window closed before it could be shown".to_string())?+}++pub async fn guarded_show(+ window: WebviewWindow,+ generation: u32,+ focus: bool,+ unminimize: bool,+) -> tauri::Result<()> {+ reveal_with_options(window, generation, focus, unminimize)+ .await+ .map(|_| ())+ .map_err(|error| tauri::Error::Io(std::io::Error::other(error)))+}++async fn finish_main_controls<I, S>(+ phase: Option<Phase>,+ instant_stop: Option<I>,+ studio_pause: S,+) -> Result<(), String>+where+ I: std::future::Future<Output = Result<(), String>>,+ S: std::future::Future<Output = Result<(), String>>,+{+ if phase != Some(Phase::AwaitingShortcut)+ && let Some(stop) = instant_stop+ {+ return stop.await;+ }+ match phase {+ Some(Phase::Recording) => studio_pause.await,+ None | Some(Phase::AwaitingShortcut | Phase::Paused | Phase::Restoring) => Ok(()),+ _ => Err("Recording is changing state. Use Ctrl+Shift+F9 to stop.".into()),+ }+}++pub async fn show_main_controls(app: &AppHandle) -> Result<(), String> {+ #[cfg(target_os = "linux")]+ let instant_stop = crate::recording::linux_instant::current(app)+ .filter(|attempt| !attempt.ui_ready())+ .map(|attempt| crate::recording::linux_instant::control(app.clone(), attempt, false));+ #[cfg(not(target_os = "linux"))]+ let instant_stop = None::<std::future::Ready<Result<(), String>>>;+ finish_main_controls(phase(app), instant_stop, control(app, false)).await+}++pub fn control(+ app: &AppHandle,+ resume: bool,+) -> futures::future::BoxFuture<'_, Result<(), String>> {+ Box::pin(async move {+ let app_state = app.state::<crate::ArcLock<crate::App>>();+ let (handle, dir, generation) = {+ let app_state = app_state.read().await;+ let Some(crate::recording::InProgressRecording::Studio { handle, common, .. }) =+ app_state.current_recording()+ else {+ return Err("No Studio recording is available".into());+ };+ let generation = owner(app, &common.recording_dir).ok_or("Recording was superseded")?;+ (handle.clone(), common.recording_dir.clone(), generation)+ };+ let expected = if resume {+ Phase::Paused+ } else {+ Phase::Recording+ };+ let transition = if resume {+ Phase::Resuming+ } else {+ Phase::Pausing+ };+ {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ let lease = inner+ .lease+ .as_mut()+ .filter(|lease| {+ lease.generation == generation+ && lease.phase == expected+ && lease.recording_dir.as_deref() == Some(dir.as_path())+ })+ .ok_or("Recording is already changing state. Use Ctrl+Shift+F9 to stop.")?;+ lease.phase = transition;+ inner.control_error = None;+ }+ notify(app);+ let state = app.state::<State>();+ ControlOperation {+ resume,+ generation,+ dir: &dir,+ hide: hide(app, generation),+ change: async {+ if resume {+ handle.resume().await.map_err(|error| error.to_string())+ } else {+ handle.pause().await.map_err(|error| error.to_string())+ }+ },+ paused: async {+ matches!(+ tokio::time::timeout(Duration::from_secs(2), handle.is_paused()).await,+ Ok(Ok(true))+ )+ },+ restore: restore_paused_main(app, generation, dir.clone()),+ stop: async {+ Box::pin(crate::recording::stop_recording(app.clone(), app.state())).await+ },+ notify: || notify(app),+ }+ .run(&state.inner)+ .await?;+ let event = if resume {+ crate::recording::RecordingEvent::Resumed+ } else {+ crate::recording::RecordingEvent::Paused+ };+ let _ = event.emit(app);+ Ok(())+ })+}++#[derive(Debug)]+enum ControlOutcome {+ Succeeded,+ StoppedBeforeResume,+ HideFailed(String),+ ActorFailed { error: String, paused: bool },+}++struct ControlOperation<'a, H, C, P, R, S, N> {+ resume: bool,+ generation: u32,+ dir: &'a std::path::Path,+ hide: H,+ change: C,+ paused: P,+ restore: R,+ stop: S,+ notify: N,+}++impl<H, C, P, R, S, N> ControlOperation<'_, H, C, P, R, S, N>+where+ H: std::future::Future<Output = Result<(), String>>,+ C: std::future::Future<Output = Result<(), String>>,+ P: std::future::Future<Output = bool>,+ R: std::future::Future<Output = Result<(), String>>,+ S: std::future::Future<Output = Result<(), String>>,+ N: Fn(),+{+ async fn run(self, state: &Mutex<Inner>) -> Result<(), String> {+ let hide_result = if self.resume { self.hide.await } else { Ok(()) };+ let outcome = match hide_result {+ Err(error) => ControlOutcome::HideFailed(error),+ Ok(()) => {+ let stop_requested = {+ let inner = state.lock().unwrap();+ if !inner.control_current(self.generation, self.dir, self.resume) {+ return Err("Recording stopped or changed during the operation".into());+ }+ inner.lease.as_ref().unwrap().stop_requested+ };+ if self.resume && stop_requested {+ ControlOutcome::StoppedBeforeResume+ } else {+ match self.change.await {+ Ok(()) => ControlOutcome::Succeeded,+ Err(error) => ControlOutcome::ActorFailed {+ error,+ // This acknowledgement relies on Studio's transactional Resume teardown.+ paused: self.resume && self.paused.await,+ },+ }+ }+ }+ };+ let stop_requested = {+ let mut inner = state.lock().unwrap();+ if !inner.complete_control(self.generation, self.dir, self.resume, &outcome) {+ return Err("Recording stopped or changed during the operation".into());+ }+ inner.lease.as_ref().unwrap().stop_requested+ };+ (self.notify)();+ if stop_requested {+ self.stop.await?;+ return Err("Recording stopped".into());+ }+ match outcome {+ ControlOutcome::Succeeded => Ok(()),+ ControlOutcome::StoppedBeforeResume => Err("Recording stopped".into()),+ ControlOutcome::HideFailed(error)+ | ControlOutcome::ActorFailed {+ error,+ paused: true,+ } => {+ if let Err(reveal_error) = self.restore.await {+ return Err(format!(+ "{error}. Could not restore controls: {reveal_error}. Use {STOP_SHORTCUT} to stop."+ ));+ }+ Err(error)+ }+ ControlOutcome::ActorFailed {+ error,+ paused: false,+ } if self.resume => Err(format!(+ "{error}. Recording pause could not be confirmed. Controls remain hidden; use {STOP_SHORTCUT} to stop."+ )),+ ControlOutcome::ActorFailed { error, .. } => Err(error),+ }+ }+}++async fn restore_paused_main(app: &AppHandle, generation: u32, dir: PathBuf) -> Result<(), String> {+ let main = CapWindowId::Main+ .get(app)+ .ok_or("Recording controls window is unavailable")?;+ let (tx, rx) = tokio::sync::oneshot::channel();+ let window = main.clone();+ main.run_on_main_thread(move || {+ let allowed = window+ .app_handle()+ .state::<State>()+ .inner+ .lock()+ .unwrap()+ .may_restore_paused_main(generation, &dir);+ let result = if allowed {+ reveal_now_with_options(&window, generation, true, true)+ .map_err(|error| error.to_string())+ } else {+ Ok(false)+ };+ let _ = tx.send(result);+ })+ .map_err(|error| error.to_string())?;+ let revealed = tokio::time::timeout(Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Timed out restoring paused controls".to_string())?+ .map_err(|_| "Paused controls restore was cancelled".to_string())??;+ if !revealed {+ return Err("Recording stopped or changed before controls could be restored".into());+ }+ Ok(())+}++pub async fn is_paused(app: &AppHandle) -> Result<bool, String> {+ let state = app.state::<crate::ArcLock<crate::App>>();+ let handle = {+ let state = state.read().await;+ match state.current_recording() {+ Some(crate::recording::InProgressRecording::Studio { handle, .. }) => handle.clone(),+ _ => return Err("No Studio recording is available".into()),+ }+ };+ handle.is_paused().await.map_err(|error| error.to_string())+}++pub fn begin_restart(app: &AppHandle, dir: &std::path::Path) -> Result<Option<u32>, String> {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ let Some(lease) = inner.lease.as_mut() else {+ return Ok(None);+ };+ if lease.recording_dir.as_deref() != Some(dir)+ || !matches!(lease.phase, Phase::Recording | Phase::Paused)+ || lease.stop_requested+ {+ return Err("Recording is changing state. Use Ctrl+Shift+F9 to stop.".into());+ }+ lease.phase = Phase::Restarting;+ lease.recording_dir = None;+ Ok(Some(lease.generation))+}++#[cfg(target_os = "linux")]+fn native_id(window: &WebviewWindow) -> Result<u64, String> {+ use wgpu::rwh::{HasWindowHandle, RawWindowHandle};+ if cap_recording::screenshot::uses_wayland_portal() {+ use gtk::prelude::*;+ return window+ .gtk_window()+ .map(|window| window.as_ptr() as u64)+ .map_err(|error| error.to_string());+ }+ match window.window_handle().map_err(|e| e.to_string())?.as_raw() {+ RawWindowHandle::Xlib(handle) => Ok(handle.window),+ RawWindowHandle::Xcb(handle) => Ok(u64::from(handle.window.get())),+ RawWindowHandle::Wayland(_) => {+ use gtk::prelude::*;+ let gtk = window.gtk_window().map_err(|error| error.to_string())?;+ Ok(gtk.as_ptr() as u64)+ }+ _ => Err("Clean capture requires an X11 or Wayland window".into()),+ }+}++#[cfg(not(target_os = "linux"))]+fn native_id(_window: &WebviewWindow) -> Result<u64, String> {+ Err("Clean Studio capture is only available on X11".into())+}++fn x11_environment(display: bool, wayland: bool, session: Option<&str>) -> bool {+ display && !wayland && session.is_some_and(|session| session.eq_ignore_ascii_case("x11"))+}++pub(crate) async fn wait_for_shortcut(state: &State, generation: u32) -> Result<(), String> {+ loop {+ let notified = state.changed.notified();+ tokio::pin!(notified);+ notified.as_mut().enable();+ {+ let inner = state.inner.lock().unwrap();+ let lease = inner+ .lease+ .as_ref()+ .filter(|lease| lease.generation == generation)+ .ok_or("Recording cancelled")?;+ if lease.stop_requested {+ return Err(+ if lease.wayland && lease.lost_stop_routes.iter().any(|lost| *lost) {+ lease.stop_error.clone().unwrap_or_else(|| {+ "The recording Stop control became unavailable".into()+ })+ } else {+ "Recording cancelled".into()+ },+ );+ }+ if lease.phase == Phase::Starting {+ return Ok(());+ }+ }+ notified.await;+ }+}++#[cfg(target_os = "linux")]+pub(crate) async fn await_instant_shortcut(+ state: &State,+ generation: u32,+ attempt: &crate::recording::linux_instant::Attempt,+) -> Result<(), String> {+ attempt+ .while_active(wait_for_shortcut(state, generation))+ .await+}++#[cfg(all(test, target_os = "linux"))]+pub(crate) fn instant_preflight_fixture(generation: u32) -> State {+ State {+ instant: Mutex::new(None),+ portal_stop: tokio::sync::Mutex::new(None),+ inner: Mutex::new(Inner {+ generation,+ lease: Some(Lease {+ mode: cap_recording::RecordingMode::Instant,+ generation,+ phase: Phase::AwaitingShortcut,+ pressed: false,+ stop_requested: false,+ registered_shortcut: true,+ wayland: false,+ stop_route: None,+ stop_description: None,+ stop_error: None,+ lost_stop_routes: [false; 2],+ recording_dir: None,+ windows: Vec::new(),+ }),+ ..Inner::default()+ }),+ changed: Notify::new(),+ }+}++#[cfg(all(test, target_os = "linux"))]+pub(crate) fn deliver_preflight_shortcut(state: &State) {+ let mut inner = state.inner.lock().unwrap();+ assert!(inner.shortcut(true));+ assert!(inner.shortcut(false));+ drop(inner);+ state.changed.notify_waiters();+}++fn capture_environment_is_x11(+ mode: cap_recording::RecordingMode,+ strict_x11: bool,+ uses_wayland_portal: bool,+) -> bool {+ if mode == cap_recording::RecordingMode::Instant {+ !uses_wayland_portal+ } else {+ strict_x11+ }+}++fn validate_capture_visibility(+ mode: cap_recording::RecordingMode,+ target: &cap_recording::screen_capture::ScreenCaptureTarget,+ supported: bool,+) -> Result<bool, String> {+ if !matches!(+ mode,+ cap_recording::RecordingMode::Studio | cap_recording::RecordingMode::Instant+ ) || !matches!(+ target,+ cap_recording::screen_capture::ScreenCaptureTarget::Display { .. }+ | cap_recording::screen_capture::ScreenCaptureTarget::Area { .. }+ ) {+ return Ok(false);+ }+ if !supported {+ return Err("This display backend cannot acknowledge hidden recording windows. Recording has not started and selected inputs are unchanged.".into());+ }+ Ok(true)+}++pub async fn prepare(+ app: &AppHandle,+ inputs: &crate::recording::StartRecordingInputs,+ restart: Option<u32>,+) -> Result<Option<u32>, String> {+ if !cfg!(target_os = "linux") {+ return Ok(None);+ }+ if let Some(generation) = restart {+ if phase(app) != Some(Phase::Restarting) || stop_requested(app, generation) {+ return Err("Recording restart was cancelled".into());+ }+ set_phase(app, generation, Phase::Starting);+ return Ok(Some(generation));+ }+ if phase(app).is_some() {+ return Err("Finish or cancel the current recording before starting another".into());+ }+ #[cfg(target_os = "linux")]+ let uses_wayland_portal = cap_recording::screenshot::uses_wayland_portal();+ #[cfg(not(target_os = "linux"))]+ let uses_wayland_portal = false;+ if !validate_capture_visibility(+ inputs.mode,+ &inputs.capture_target,+ capture_environment_is_x11(+ inputs.mode,+ x11_environment(+ std::env::var_os("DISPLAY").is_some(),+ std::env::var_os("WAYLAND_DISPLAY").is_some(),+ std::env::var("XDG_SESSION_TYPE").ok().as_deref(),+ ),+ uses_wayland_portal,+ ) || uses_wayland_portal,+ )? {+ return Ok(None);+ }+ #[cfg(target_os = "linux")]+ let instant_attempt = if inputs.mode == cap_recording::RecordingMode::Instant {+ let attempt = crate::recording::linux_instant::current(app)+ .ok_or("Instant preflight owner was lost")?;+ attempt.checked(Ok(()))?;+ Some(attempt)+ } else {+ None+ };+ let main = CapWindowId::Main+ .get(app)+ .ok_or("Open Cap before starting this recording")?;++ let app_state = app.state::<crate::ArcLock<crate::App>>();+ let mut app_state = app_state.write().await;+ if !matches!(app_state.recording_state, crate::RecordingState::None) {+ return Err("Recording already in progress".into());+ }+ let state = app.state::<State>();+ let generation = {+ let mut inner = state.inner.lock().unwrap();+ if inner.lease.is_some() {+ return Err("Recording preflight already in progress".into());+ }+ inner.generation = inner.generation.wrapping_add(1);+ inner.control_error = None;+ let generation = inner.generation;+ inner.restored = None;+ inner.lease = Some(Lease {+ mode: inputs.mode,+ generation,+ phase: Phase::AwaitingShortcut,+ pressed: false,+ stop_requested: false,+ registered_shortcut: false,+ wayland: uses_wayland_portal,+ stop_route: None,+ stop_description: None,+ stop_error: None,+ lost_stop_routes: [false; 2],+ recording_dir: None,+ windows: Vec::new(),+ });+ generation+ };+ app_state.set_pending_recording(inputs.mode, inputs.capture_target.clone())?;+ drop(app_state);+ let result = async {+ let saved = save_windows(app, generation).await?;+ state.inner.lock().unwrap().lease.as_mut().unwrap().windows = saved;+ #[cfg(target_os = "linux")]+ if uses_wayland_portal {+ crate::hotkeys::reserve_wayland_stop(app, generation).await?;+ } else {+ let registered = crate::hotkeys::reserve_clean_capture_stop(app)?;+ state+ .inner+ .lock()+ .unwrap()+ .lease+ .as_mut()+ .unwrap()+ .registered_shortcut = registered;+ }+ crate::target_select_overlay::close_target_select_overlay_windows(app);+ if stop_requested(app, generation) {+ return Err("Recording cancelled".into());+ }+ guarded_show(main, generation, true, true)+ .await+ .map_err(|error| error.to_string())?;+ notify(app);+ #[cfg(target_os = "linux")]+ if let Some(attempt) = &instant_attempt {+ await_instant_shortcut(&state, generation, attempt).await?;+ } else {+ wait_for_shortcut(&state, generation).await?;+ }+ #[cfg(not(target_os = "linux"))]+ wait_for_shortcut(&state, generation).await?;+ #[cfg(target_os = "linux")]+ if uses_wayland_portal {+ crate::tray::set_clean_stop_mode(app, generation, true).await?;+ }+ if inputs.mode == cap_recording::RecordingMode::Studio {+ hide(app, generation).await?;+ }+ Ok(Some(generation))+ }+ .await;+ if result.is_err() {+ app.state::<crate::ArcLock<crate::App>>()+ .write()+ .await+ .clear_pending_recording();+ release(app, generation, false);+ }+ result+}++fn hide_windows(app: &AppHandle) -> Result<(), String> {+ #[cfg(target_os = "linux")]+ if let Some(generation) = wayland_generation(app) {+ return hide_wayland_windows(app, generation);+ }+ for (label, window) in app.webview_windows() {+ if matches!(+ label.parse::<CapWindowId>(),+ Ok(CapWindowId::Main+ | CapWindowId::Camera+ | CapWindowId::RecordingControls+ | CapWindowId::TargetSelectOverlay { .. })+ ) {+ native_id(&window)?;+ set_native_visibility(&window, false)?;+ if window.is_visible().map_err(|e| e.to_string())? {+ return Err("Cap could not hide its recording windows safely".into());+ }+ }+ }+ Ok(())+}++pub async fn hide(app: &AppHandle, generation: u32) -> Result<(), String> {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = app.clone();+ app.run_on_main_thread(move || {+ let result = (|| {+ if !is_current(&handle, generation) {+ return Err("Recording preflight was superseded".to_string());+ }+ hide_windows(&handle)?;+ Ok(())+ })();+ let _ = tx.send(result);+ })+ .map_err(|e| e.to_string())?;+ tokio::time::timeout(Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Timed out hiding Cap windows".to_string())?+ .map_err(|_| "Cap window hide task was cancelled".to_string())??;+ #[cfg(target_os = "linux")]+ if wayland_generation(app) == Some(generation) {+ wayland_fence(app, generation, true).await?;+ }+ tokio::time::sleep(Duration::from_millis(150)).await;+ if stop_requested(app, generation) {+ return Err("Recording cancelled".into());+ }+ Ok(())+}++#[cfg(target_os = "linux")]+pub(crate) struct InstantSeal {+ pub generation: u32,+ pub attempt: crate::recording::linux_instant::Attempt,+ pub requested: crate::RequestedInputs,+ pub target: cap_recording::screen_capture::ScreenCaptureTarget,+ pub capture: crate::linux_instant_camera::PhysicalRect,+ pub presentation: Option<crate::linux_instant_camera::PreparedPresentation>,+}++#[cfg(target_os = "linux")]+fn validate_instant_seal(app: &AppHandle, seal: &InstantSeal) -> Result<(), String> {+ let requested = app.state::<crate::RequestedInputsState>();+ requested.ready_snapshot()?;+ if !is_current(app, seal.generation)+ || phase(app) != Some(Phase::Starting)+ || stop_requested(app, seal.generation)+ || !requested.is_current(&seal.requested)+ || crate::recording::linux_instant::current(app)+ .is_none_or(|attempt| !attempt.same(&seal.attempt))+ {+ return Err("Instant preparation was cancelled or changed".into());+ }+ seal.attempt.checked(Ok(()))?;+ if crate::recording::linux_instant::capture_rect(&seal.target)? != seal.capture {+ return Err("Capture bounds changed while preparing Instant recording".into());+ }+ if let Some(presentation) = &seal.presentation {+ let window = CapWindowId::Camera+ .get(app)+ .ok_or("Camera window disappeared")?;+ presentation.validate_before_hide(&window)?;+ }+ Ok(())+}++#[cfg(target_os = "linux")]+async fn instant_ui_seal(+ app: &AppHandle,+ seal: InstantSeal,+ hide: bool,+) -> Result<InstantSeal, String> {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = app.clone();+ let attempt = seal.attempt.clone();+ app.run_on_main_thread(move || {+ let result = (|| {+ validate_instant_seal(&handle, &seal)?;+ if hide {+ hide_windows(&handle)?;+ }+ Ok(seal)+ })();+ let _ = tx.send(result);+ })+ .map_err(|error| error.to_string())?;+ let result = tokio::time::timeout(Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Instant camera hide acknowledgement timed out".to_string())+ .and_then(|result| {+ result.map_err(|_| "Instant camera hide acknowledgement was lost".to_string())+ })+ .and_then(|result| result);+ if result.is_err() {+ attempt.cancel();+ }+ result+}++#[cfg(target_os = "linux")]+async fn seal_then_settle<T, H, S, V, F>(hide: H, settle: S, validate: V) -> Result<T, String>+where+ H: std::future::Future<Output = Result<T, String>>,+ S: std::future::Future<Output = Result<(), String>>,+ V: FnOnce(T) -> F,+ F: std::future::Future<Output = Result<T, String>>,+{+ let sealed = hide.await?;+ settle.await?;+ validate(sealed).await+}++#[cfg(target_os = "linux")]+pub(crate) async fn seal_instant(+ app: &AppHandle,+ seal: InstantSeal,+) -> Result<InstantSeal, String> {+ let attempt = seal.attempt.clone();+ let generation = seal.generation;+ seal_then_settle(+ instant_ui_seal(app, seal, true),+ attempt.while_active(async {+ #[cfg(target_os = "linux")]+ if wayland_generation(app) == Some(generation) {+ wayland_fence(app, generation, true).await?;+ }+ tokio::time::sleep(Duration::from_millis(150)).await;+ Ok(())+ }),+ |seal| instant_ui_seal(app, seal, false),+ )+ .await+}++#[cfg(target_os = "linux")]+async fn restore_instant_windows(+ app: &AppHandle,+ generation: u32,+ main_only: bool,+) -> Result<(), String> {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = app.clone();+ app.run_on_main_thread(move || {+ let result = (|| {+ if crate::recording::linux_instant::current(&handle)+ .is_some_and(|attempt| attempt.has_capture() && !attempt.ui_ready())+ {+ return Err("Instant capture cleanup is unconfirmed".to_string());+ }+ if wayland_generation(&handle) == Some(generation) {+ return restore_wayland_windows(&handle, generation, main_only);+ }+ let windows = {+ let state = handle.state::<State>();+ let inner = state.inner.lock().unwrap();+ inner+ .lease+ .as_ref()+ .filter(|lease| {+ lease.generation == generation && lease.phase == Phase::Restoring+ })+ .ok_or("Instant restoration was superseded")?+ .windows+ .clone()+ };+ let requested = handle+ .state::<crate::RequestedInputsState>()+ .ready_snapshot();+ if !main_only {+ requested.as_ref().map_err(Clone::clone)?;+ }+ for saved in windows {+ let main = saved.label == CapWindowId::Main.label();+ if main != main_only {+ continue;+ }+ if !main+ && requested+ .as_ref()+ .is_ok_and(|snapshot| snapshot.camera.value.is_none())+ {+ continue;+ }+ let window = match handle.get_webview_window(&saved.label) {+ Some(window) => window,+ None if wayland_generation(&handle) == Some(generation) && !saved.visible => {+ continue;+ }+ None => return Err("Recording restoration window disappeared".into()),+ };+ let visible = saved+ .visibility_for(native_id(&window)?)+ .ok_or("Instant restoration window identity changed")?;+ if !main+ && !handle+ .state::<crate::RequestedInputsState>()+ .is_current(requested.as_ref().map_err(Clone::clone)?)+ {+ return Err("Requested inputs changed during Instant restoration".into());+ }+ set_native_visibility(&window, visible)?;+ if window.is_visible().map_err(|error| error.to_string())? != visible {+ return Err("Instant window restoration was not acknowledged".into());+ }+ }+ Ok(())+ })();+ let _ = tx.send(result);+ })+ .map_err(|error| error.to_string())?;+ tokio::time::timeout(Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Instant restore acknowledgement timed out".to_string())?+ .map_err(|_| "Instant restore acknowledgement was lost".to_string())?+}++#[cfg(target_os = "linux")]+async fn restore_instant_sequence<M, I, IF, C, CF>(+ main: M,+ inputs: I,+ camera: C,+) -> Result<(), String>+where+ M: std::future::Future<Output = Result<(), String>>,+ I: FnOnce() -> IF,+ IF: std::future::Future<Output = ()>,+ C: FnOnce() -> CF,+ CF: std::future::Future<Output = Result<(), String>>,+{+ main.await?;+ inputs().await;+ camera().await+}++#[cfg(target_os = "linux")]+fn finish_x11_studio_restoration(+ inner: &Mutex<Inner>,+ generation: u32,+ windows: Result<(), String>,+ release_shortcut: impl FnOnce() -> Result<(), String>,+) -> bool {+ let cleanup = {+ let mut inner = inner.lock().unwrap();+ inner.reserve_x11_studio_cleanup(generation, windows)+ };+ let Some(cleanup) = cleanup else {+ return false;+ };+ let result = if cleanup.registered_shortcut {+ release_shortcut()+ } else {+ Ok(())+ };+ inner+ .lock()+ .unwrap()+ .complete_x11_studio_restoration(cleanup, result)+}++#[cfg(target_os = "linux")]+fn spawn_x11_studio_restore(app: AppHandle, generation: u32, restore_inputs: bool) {+ drop(tauri::async_runtime::spawn(async move {+ let result = restore_instant_sequence(+ restore_instant_windows(&app, generation, true),+ || async {+ if restore_inputs {+ crate::restore_requested_inputs(&app).await;+ }+ },+ || restore_instant_windows(&app, generation, false),+ )+ .await;+ let handle = app.clone();+ let scheduled = app.run_on_main_thread(move || {+ use tauri_plugin_global_shortcut::GlobalShortcutExt;++ {+ let state = handle.state::<State>();+ finish_x11_studio_restoration(&state.inner, generation, result, || {+ handle+ .global_shortcut()+ .unregister(STOP_SHORTCUT)+ .map_err(|error| {+ format!("Recording Stop shortcut cleanup is unconfirmed: {error}")+ })+ });+ }+ notify(&handle);+ });+ if let Err(error) = scheduled {+ {+ let state = app.state::<State>();+ finish_x11_studio_restoration(+ &state.inner,+ generation,+ Err(format!(+ "Recording restoration completion could not be scheduled: {error}"+ )),+ || Ok(()),+ );+ }+ notify(&app);+ }+ }));+}++#[cfg(target_os = "linux")]+fn spawn_instant_restore(app: AppHandle, generation: u32, restore_inputs: bool) {+ drop(tauri::async_runtime::spawn(async move {+ let result = restore_instant_sequence(+ restore_instant_windows(&app, generation, true),+ || async {+ if restore_inputs {+ crate::restore_requested_inputs(&app).await;+ }+ },+ || restore_instant_windows(&app, generation, false),+ )+ .await;+ let result = if wayland_generation(&app) == Some(generation) {+ match result {+ Ok(()) => {+ async {+ wayland_fence(&app, generation, false).await?;+ crate::tray::set_clean_stop_mode(&app, generation, false).await?;+ crate::hotkeys::release_wayland_stop(&app, generation).await+ }+ .await+ }+ Err(error) => Err(error),+ }+ } else {+ result+ };+ let owned = {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ inner.complete_instant_restoration(generation, result)+ };+ if let Some(owned) = owned {+ crate::hotkeys::release_clean_capture_stop(&app, owned);+ let _ = app.run_on_main_thread(move || {+ WAYLAND_WINDOWS.with_borrow_mut(|windows| {+ windows.remove(&generation);+ });+ WAYLAND_CAPTURE_WINDOWS.with_borrow_mut(|windows| {+ windows.remove(&generation);+ });+ });+ }+ notify(&app);+ }));+}++#[cfg(target_os = "linux")]+pub(crate) async fn wait_restored(app: &AppHandle, generation: u32) -> Result<(), String> {+ let state = app.state::<State>();+ wait_for_restoration(&state, generation).await+}++#[cfg(target_os = "linux")]+async fn wait_for_restoration(state: &State, generation: u32) -> Result<(), String> {+ loop {+ let changed = state.changed.notified();+ tokio::pin!(changed);+ changed.as_mut().enable();+ {+ let inner = state.inner.lock().unwrap();+ if let Some(receipt) = &inner.restored+ && receipt.generation == generation+ {+ return receipt.restart_result();+ }+ if inner+ .lease+ .as_ref()+ .is_none_or(|lease| lease.generation != generation)+ {+ return Err("Instant restoration ownership changed without acknowledgement".into());+ }+ }+ changed.await;+ }+}++pub fn release(app: &AppHandle, generation: u32, editor_took_foreground: bool) {+ release_inner(app, generation, editor_took_foreground, false);+}++pub fn release_after_recording(app: &AppHandle, generation: u32, editor_took_foreground: bool) {+ release_inner(app, generation, editor_took_foreground, true);+}++async fn restore_pass_acknowledged(+ scheduled: bool,+ acknowledgement: tokio::sync::oneshot::Receiver<Result<(), String>>,+) -> bool {+ scheduled && matches!(acknowledgement.await, Ok(Ok(())))+}++fn release_inner(+ app: &AppHandle,+ generation: u32,+ editor_took_foreground: bool,+ restore_inputs: bool,+) {+ #[cfg(target_os = "linux")]+ if crate::recording::linux_instant::current(app)+ .is_some_and(|attempt| attempt.has_capture() && !attempt.ui_ready())+ {+ return;+ }+ {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ let Some(lease) = inner+ .lease+ .as_mut()+ .filter(|lease| lease.generation == generation && lease.phase != Phase::Restoring)+ else {+ return;+ };+ if editor_took_foreground+ && (lease.wayland || lease.mode == cap_recording::RecordingMode::Studio)+ {+ for window in &mut lease.windows {+ if window.label == CapWindowId::Main.label() {+ window.visible = false;+ }+ }+ }+ lease.phase = Phase::Restoring;+ }+ notify(app);+ #[cfg(target_os = "linux")]+ if app+ .state::<State>()+ .inner+ .lock()+ .unwrap()+ .lease+ .as_ref()+ .is_some_and(|lease| {+ lease.generation == generation+ && (lease.mode == cap_recording::RecordingMode::Instant || lease.wayland)+ })+ {+ spawn_instant_restore(app.clone(), generation, restore_inputs);+ return;+ }+ #[cfg(target_os = "linux")]+ if app+ .state::<State>()+ .inner+ .lock()+ .unwrap()+ .lease+ .as_ref()+ .is_some_and(|lease| {+ lease.generation == generation+ && lease.mode == cap_recording::RecordingMode::Studio+ && !lease.wayland+ })+ {+ spawn_x11_studio_restore(app.clone(), generation, restore_inputs);+ return;+ }+ let app = app.clone();+ drop(tauri::async_runtime::spawn(async move {+ let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), String>>();+ let handle = app.clone();+ let scheduled = app.run_on_main_thread(move || {+ #[cfg(target_os = "linux")]+ if crate::recording::linux_instant::current(&handle)+ .is_some_and(|attempt| attempt.has_capture() && !attempt.ui_ready())+ {+ let _ = tx.send(Err("Instant cleanup is unconfirmed".to_string()));+ return;+ }+ let saved = {+ let state = handle.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ inner+ .lease+ .as_mut()+ .filter(|lease| lease.generation == generation)+ .map(|lease| {+ let owned = std::mem::take(&mut lease.registered_shortcut);+ (+ lease+ .windows+ .iter()+ .find(|saved| saved.label == CapWindowId::Main.label())+ .cloned(),+ owned,+ )+ })+ };+ if let Some((saved, owned)) = saved {+ crate::hotkeys::release_clean_capture_stop(&handle, owned);+ if !editor_took_foreground+ && let Some(saved) = saved+ && let Some(window) = handle.get_webview_window(&saved.label)+ && let Some(visible) = native_id(&window)+ .ok()+ .and_then(|id| saved.visibility_for(id))+ {+ let result = if visible {+ window.show()+ } else {+ window.hide()+ };+ if let Err(error) = result {+ tracing::warn!(%error, "Could not restore Main after recording");+ }+ }+ }+ let _ = tx.send(Ok(()));+ });+ if !restore_pass_acknowledged(scheduled.is_ok(), rx).await {+ return;+ }+ if restore_inputs {+ crate::restore_requested_inputs(&app).await;+ }+ let requested = app.state::<crate::RequestedInputsState>().snapshot();+ let handle = app.clone();+ let _ = app.run_on_main_thread(move || {+ #[cfg(target_os = "linux")]+ if crate::recording::linux_instant::current(&handle)+ .is_some_and(|attempt| attempt.has_capture() && !attempt.ui_ready())+ {+ return;+ }+ let state = handle.state::<State>();+ let windows = {+ let inner = state.inner.lock().unwrap();+ let Some(lease) = inner.lease.as_ref().filter(|lease| {+ lease.generation == generation && lease.phase == Phase::Restoring+ }) else {+ return;+ };+ lease.windows.clone()+ };+ for saved in windows {+ if saved.label == CapWindowId::Main.label() {+ continue;+ }+ if matches!(saved.label.parse::<CapWindowId>(), Ok(CapWindowId::Camera))+ && (requested.camera.value.is_none()+ || requested.camera.pending+ || requested.camera.error.is_some()+ || !handle+ .state::<crate::RequestedInputsState>()+ .is_current(&requested))+ {+ continue;+ }+ if let Some(window) = handle.get_webview_window(&saved.label)+ && let Some(visible) = native_id(&window)+ .ok()+ .and_then(|id| saved.visibility_for(id))+ {+ let result = if visible {+ window.show()+ } else {+ window.hide()+ };+ if let Err(error) = result {+ tracing::warn!(%error, "Could not restore clean capture window");+ }+ }+ }+ {+ let mut inner = state.inner.lock().unwrap();+ inner.lease = None;+ inner.generation = inner.generation.wrapping_add(1);+ }+ notify(&handle);+ });+ }));+}++#[tauri::command]+#[specta::specta]+pub fn get_clean_capture_state(app: AppHandle) -> Snapshot {+ app.state::<State>().inner.lock().unwrap().snapshot()+}++#[tauri::command]+#[specta::specta]+pub async fn reveal_capture_window(+ window: WebviewWindow,+ generation: u32,+ target_overlay: Option<String>,+) -> Result<bool, String> {+ if let Some(label) = target_overlay {+ if window.label() != CapWindowId::Main.label()+ || !matches!(+ label.parse::<CapWindowId>(),+ Ok(CapWindowId::TargetSelectOverlay { .. })+ )+ {+ return Err("Only Main can restore a target selection overlay".into());+ }+ let target = window+ .app_handle()+ .get_webview_window(&label)+ .ok_or("Target selection overlay no longer exists")?;+ return reveal(target, generation).await;+ }+ if !matches!(+ window.label().parse::<CapWindowId>(),+ Ok(CapWindowId::Main | CapWindowId::Camera | CapWindowId::RecordingControls)+ ) {+ return Err("Only Cap recording windows can use this command".into());+ }+ if matches!(+ window.label().parse::<CapWindowId>(),+ Ok(CapWindowId::RecordingControls)+ ) && window+ .app_handle()+ .state::<crate::ArcLock<crate::App>>()+ .read()+ .await+ .current_recording()+ .is_none()+ {+ return Ok(false);+ }+ let main = matches!(window.label().parse::<CapWindowId>(), Ok(CapWindowId::Main));+ reveal_with_options(window, generation, main, main).await+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn wayland_blocks_all_floating_labels_while_capture_can_run() {+ for mode in [+ cap_recording::RecordingMode::Studio,+ cap_recording::RecordingMode::Instant,+ ] {+ for phase in [+ Phase::Starting,+ Phase::Recording,+ Phase::Pausing,+ Phase::Resuming,+ Phase::ResumeFailed,+ Phase::Restarting,+ Phase::Stopping,+ ] {+ let mut inner = fixture();+ let lease = inner.lease.as_mut().unwrap();+ lease.mode = mode;+ lease.wayland = true;+ lease.phase = phase;+ for label in [+ "main",+ "camera",+ "teleprompter",+ "settings",+ "editor-4",+ "unknown-js-window",+ ] {+ assert!(!inner.may_reveal(1, label), "{phase:?}: {label}");+ }+ }+ }+ }++ #[test]+ fn x11_floating_admission_is_unchanged() {+ let mut inner = fixture();+ inner.lease.as_mut().unwrap().phase = Phase::Recording;+ assert!(!inner.lease.as_ref().unwrap().wayland);+ assert!(inner.may_reveal(1, "teleprompter"));+ assert!(inner.may_reveal(1, "settings"));+ assert!(!inner.may_reveal(1, "camera"));+ }++ #[test]+ fn wayland_restore_keeps_non_camera_window_intent() {+ for label in ["teleprompter", "settings", "editor-4", "unknown-js-window"] {+ assert!(restore_floating_window(Some(label)));+ }+ assert!(restore_floating_window(None));+ for label in [+ "capture-area",+ "in-progress-recording",+ "target-select-overlay-1",+ "window-capture-occluder-1",+ ] {+ assert!(!restore_floating_window(Some(label)));+ }+ }++ #[test]+ fn wayland_safe_ui_phases_allow_mapping_but_old_generation_does_not() {+ for phase in [Phase::AwaitingShortcut, Phase::Paused, Phase::Restoring] {+ assert!(!wayland_blocks_mapping(phase));+ let mut inner = fixture();+ let lease = inner.lease.as_mut().unwrap();+ lease.wayland = true;+ lease.phase = phase;+ assert!(inner.may_reveal(1, "teleprompter"));+ assert!(!inner.may_reveal(0, "teleprompter"));+ }+ }++ #[tokio::test]+ async fn restore_pass_waits_for_successful_ack_before_following_work() {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let work = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let observed = work.clone();+ let task = tokio::spawn(async move {+ if restore_pass_acknowledged(true, rx).await {+ observed.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ }+ });+ tokio::task::yield_now().await;+ assert!(!task.is_finished());+ assert_eq!(work.load(std::sync::atomic::Ordering::SeqCst), 0);+ tx.send(Ok(())).unwrap();+ task.await.unwrap();+ assert_eq!(work.load(std::sync::atomic::Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn rejected_restore_pass_does_not_authorize_following_work() {+ let (tx, rx) = tokio::sync::oneshot::channel();+ tx.send(Err("Instant cleanup is unconfirmed".into()))+ .unwrap();+ assert!(!restore_pass_acknowledged(true, rx).await);+ }++ #[tokio::test]+ async fn dropped_restore_ack_does_not_authorize_following_work() {+ let (tx, rx) = tokio::sync::oneshot::channel();+ drop(tx);+ assert!(!restore_pass_acknowledged(true, rx).await);+ }++ #[tokio::test]+ async fn unscheduled_restore_pass_does_not_wait_for_an_ack() {+ let (tx, rx) = tokio::sync::oneshot::channel();+ assert!(+ !tokio::time::timeout(+ std::time::Duration::from_millis(100),+ restore_pass_acknowledged(false, rx),+ )+ .await+ .unwrap()+ );+ assert!(tx.is_closed());+ }++ #[cfg(target_os = "linux")]+ fn x11_studio_restoring_fixture() -> Mutex<Inner> {+ let mut inner = fixture();+ inner.lease.as_mut().unwrap().phase = Phase::Restoring;+ Mutex::new(inner)+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn x11_studio_restore_waits_for_windows_before_stop_cleanup_and_receipt() {+ use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+ };++ let inner = Arc::new(x11_studio_restoring_fixture());+ let inputs = Arc::new(AtomicUsize::new(0));+ let cleanup = Arc::new(AtomicUsize::new(0));+ let (main_tx, main_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();+ let (camera_tx, camera_rx) = tokio::sync::oneshot::channel::<Result<(), String>>();+ let (inputs_tx, inputs_rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn({+ let inner = inner.clone();+ let inputs = inputs.clone();+ let cleanup = cleanup.clone();+ async move {+ let result = restore_instant_sequence(+ async { main_rx.await.unwrap() },+ || async move {+ inputs.fetch_add(1, Ordering::SeqCst);+ inputs_tx.send(()).unwrap();+ },+ || async { camera_rx.await.unwrap() },+ )+ .await;+ assert!(finish_x11_studio_restoration(&inner, 1, result, || {+ cleanup.fetch_add(1, Ordering::SeqCst);+ Ok(())+ }));+ }+ });+ tokio::task::yield_now().await;+ assert!(!task.is_finished());+ assert_eq!(inputs.load(Ordering::SeqCst), 0);+ assert_eq!(cleanup.load(Ordering::SeqCst), 0);+ assert!(inner.lock().unwrap().restored.is_none());+ main_tx.send(Ok(())).unwrap();+ inputs_rx.await.unwrap();+ assert!(!task.is_finished());+ assert_eq!(inputs.load(Ordering::SeqCst), 1);+ assert_eq!(cleanup.load(Ordering::SeqCst), 0);+ assert!(inner.lock().unwrap().lease.is_some());+ assert!(inner.lock().unwrap().restored.is_none());+ camera_tx.send(Ok(())).unwrap();+ task.await.unwrap();+ let inner = inner.lock().unwrap();+ assert!(inner.lease.is_none());+ assert_eq!(inner.generation, 2);+ let receipt = inner.restored.as_ref().unwrap();+ assert_eq!(receipt.generation, 1);+ assert_eq!(receipt.restart_result(), Ok(()));+ assert_eq!(cleanup.load(Ordering::SeqCst), 1);+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn x11_studio_restore_failures_retain_ownership_and_report_failure_until_retry() {+ for (windows, cleanup, error, cleanup_calls) in [+ (+ Err("window restoration failed".to_string()),+ Ok(()),+ "window restoration failed",+ 0,+ ),+ (+ Ok(()),+ Err("Stop cleanup failed".to_string()),+ "Stop cleanup failed",+ 1,+ ),+ ] {+ let state = x11_studio_restoring_fixture();+ let calls = std::cell::Cell::new(0);+ assert!(!finish_x11_studio_restoration(&state, 1, windows, || {+ calls.set(calls.get() + 1);+ cleanup+ }));+ assert_eq!(calls.get(), cleanup_calls);+ {+ let inner = state.lock().unwrap();+ assert_eq!(inner.generation, 1);+ let lease = inner.lease.as_ref().unwrap();+ assert_eq!(lease.phase, Phase::Restoring);+ assert!(lease.registered_shortcut);+ assert!(inner.x11_cleanup.is_none());+ assert_eq!(inner.snapshot().error.as_deref(), Some(error));+ let receipt = inner.restored.as_ref().unwrap();+ assert_eq!(receipt.generation, 1);+ assert_eq!(receipt.restart_result(), Err(error.to_string()));+ }+ assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {+ panic!("a duplicate completion cannot retry cleanup")+ }));+ {+ let mut inner = state.lock().unwrap();+ assert_eq!(inner.begin_x11_studio_restore_retry(false), None);+ assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));+ assert!(inner.lease.as_ref().unwrap().stop_requested);+ }+ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));+ let inner = state.lock().unwrap();+ assert!(inner.lease.is_none());+ assert_eq!(inner.generation, 2);+ assert_eq!(+ inner.restored.as_ref().unwrap().restart_result(),+ Err("Recording restart was cancelled by Stop".into())+ );+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn x11_studio_stale_and_duplicate_restore_cannot_release_another_owner() {+ let state = x11_studio_restoring_fixture();+ assert!(!finish_x11_studio_restoration(&state, 0, Ok(()), || {+ panic!("a stale generation must not release the shortcut")+ }));+ assert!(state.lock().unwrap().restored.is_none());+ state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Starting;+ assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {+ panic!("a live recording must not release the shortcut")+ }));+ state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;+ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));+ assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {+ panic!("a duplicate completion must not release the shortcut")+ }));+ assert_eq!(state.lock().unwrap().generation, 2);+ let next = x11_studio_restoring_fixture();+ {+ let mut inner = next.lock().unwrap();+ inner.generation = 2;+ inner.lease.as_mut().unwrap().generation = 2;+ }+ assert!(!finish_x11_studio_restoration(&next, 1, Ok(()), || {+ panic!("an old completion must not release the new shortcut")+ }));+ let inner = next.lock().unwrap();+ assert_eq!(inner.generation, 2);+ assert!(inner.lease.as_ref().unwrap().registered_shortcut);+ assert!(inner.restored.is_none());+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn x11_studio_restore_keeps_the_users_existing_stop_shortcut() {+ let state = x11_studio_restoring_fixture();+ state+ .lock()+ .unwrap()+ .lease+ .as_mut()+ .unwrap()+ .registered_shortcut = false;+ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || {+ panic!("the user shortcut is not owned by this restoration")+ }));+ let inner = state.lock().unwrap();+ assert_eq!(inner.restored.as_ref().unwrap().restart_result(), Ok(()));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn x11_studio_stop_during_restoration_prevents_restart_after_cleanup() {+ let state = x11_studio_restoring_fixture();+ assert!(state.lock().unwrap().shortcut(true));+ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || Ok(())));+ let inner = state.lock().unwrap();+ assert!(inner.lease.is_none());+ assert_eq!(+ inner.restored.as_ref().unwrap().restart_result(),+ Err("Recording restart was cancelled by Stop".into())+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn x11_studio_completion_does_not_accept_instant_or_wayland_leases() {+ for (mode, wayland) in [+ (cap_recording::RecordingMode::Instant, false),+ (cap_recording::RecordingMode::Studio, true),+ ] {+ let state = x11_studio_restoring_fixture();+ {+ let mut inner = state.lock().unwrap();+ let lease = inner.lease.as_mut().unwrap();+ lease.mode = mode;+ lease.wayland = wayland;+ assert_eq!(inner.begin_x11_studio_restore_retry(true), None);+ }+ assert!(!finish_x11_studio_restoration(&state, 1, Ok(()), || {+ panic!("another restoration path owns this shortcut")+ }));+ let inner = state.lock().unwrap();+ assert!(inner.restored.is_none());+ assert!(inner.lease.is_some());+ }+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn x11_studio_unregister_allows_the_f9_callback_to_lock_and_latch_stop() {+ let state = x11_studio_restoring_fixture();+ let (request_tx, request_rx) = std::sync::mpsc::channel();+ let (reply_tx, reply_rx) = std::sync::mpsc::channel();+ std::thread::scope(|scope| {+ let callback_state = &state;+ let callback = scope.spawn(move || {+ request_rx.recv_timeout(Duration::from_secs(1)).unwrap();+ let mut inner = callback_state.lock().unwrap();+ assert!(inner.x11_cleanup.is_some());+ assert!(inner.lease.as_ref().unwrap().registered_shortcut);+ assert!(inner.reserve_x11_studio_cleanup(1, Ok(())).is_none());+ assert!(inner.shortcut(true));+ drop(inner);+ reply_tx.send(()).unwrap();+ });+ assert!(finish_x11_studio_restoration(&state, 1, Ok(()), || {+ request_tx.send(()).unwrap();+ reply_rx+ .recv_timeout(Duration::from_secs(1))+ .map_err(|_| "F9 callback could not acquire restoration state".into())+ }));+ callback.join().unwrap();+ });+ let inner = state.lock().unwrap();+ assert!(inner.x11_cleanup.is_none());+ assert!(inner.lease.is_none());+ assert_eq!(+ inner.restored.as_ref().unwrap().restart_result(),+ Err("Recording restart was cancelled by Stop".into())+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn x11_studio_old_cleanup_completion_cannot_finish_a_retry() {+ let state = x11_studio_restoring_fixture();+ let mut inner = state.lock().unwrap();+ let first = inner.reserve_x11_studio_cleanup(1, Ok(())).unwrap();+ assert!(inner.reserve_x11_studio_cleanup(1, Ok(())).is_none());+ assert!(!inner.complete_x11_studio_restoration(first, Err("unregister failed".into())));+ assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));+ let retry = inner.reserve_x11_studio_cleanup(1, Ok(())).unwrap();+ assert_ne!(first.sequence, retry.sequence);+ assert!(!inner.complete_x11_studio_restoration(first, Ok(())));+ assert!(inner.x11_cleanup == Some(retry));+ assert!(inner.lease.as_ref().unwrap().registered_shortcut);+ assert!(inner.complete_x11_studio_restoration(retry, Ok(())));+ assert!(!inner.complete_x11_studio_restoration(retry, Ok(())));+ assert_eq!(inner.generation, 2);+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn x11_studio_pending_waiter_rejects_restart_after_error_f9_and_retry_success() {+ let state = State {+ inner: x11_studio_restoring_fixture(),+ ..State::default()+ };+ let mut waiter = Box::pin(wait_for_restoration(&state, 1));+ assert!(futures::poll!(&mut waiter).is_pending());+ assert!(!finish_x11_studio_restoration(+ &state.inner,+ 1,+ Err("window acknowledgement failed".into()),+ || panic!("window failure must retain the Stop shortcut"),+ ));+ state.changed.notify_waiters();+ {+ let mut inner = state.inner.lock().unwrap();+ assert_eq!(inner.begin_x11_studio_restore_retry(true), Some(1));+ assert!(inner.restored.is_none());+ assert!(inner.lease.as_ref().unwrap().stop_requested);+ }+ assert!(finish_x11_studio_restoration(+ &state.inner,+ 1,+ Ok(()),+ || Ok(())+ ));+ state.changed.notify_waiters();+ assert_eq!(+ waiter.await,+ Err("Recording restart was cancelled by Stop".into())+ );+ }++ fn fixture() -> Inner {+ Inner {+ generation: 1,+ control_error: None,+ restored: None,+ #[cfg(target_os = "linux")]+ x11_cleanup_sequence: 0,+ #[cfg(target_os = "linux")]+ x11_cleanup: None,+ lease: Some(Lease {+ mode: cap_recording::RecordingMode::Studio,+ generation: 1,+ phase: Phase::AwaitingShortcut,+ pressed: false,+ stop_requested: false,+ registered_shortcut: true,+ wayland: false,+ stop_route: None,+ stop_description: None,+ stop_error: None,+ lost_stop_routes: [false; 2],+ recording_dir: None,+ windows: Vec::new(),+ }),+ }+ }++ #[test]+ fn requires_delivered_press_then_release() {+ let mut state = fixture();+ assert!(state.shortcut(false));+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::AwaitingShortcut);+ assert!(state.shortcut(true));+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::AwaitingShortcut);+ assert!(state.shortcut(false));+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);+ assert!(!state.lease.as_ref().unwrap().stop_requested);+ assert!(state.shortcut(true));+ assert!(state.lease.as_ref().unwrap().stop_requested);+ }++ #[test]+ fn delayed_reveal_cannot_cross_generation() {+ let mut state = fixture();+ assert!(state.may_reveal(1, "main"));+ state.generation = 2;+ state.lease = None;+ assert!(!state.may_reveal(1, "main"));+ assert!(!state.may_reveal(1, "camera"));+ assert!(state.may_reveal(2, "main"));+ }++ #[test]+ fn wayland_requires_delivered_current_stop_input() {+ let mut state = fixture();+ let lease = state.lease.as_mut().unwrap();+ lease.wayland = true;+ assert!(!lease.accept_stop_input(None, true));+ assert!(!lease.accept_stop_input(Some((2, StopRoute::Tray)), true));+ assert!(!lease.accept_stop_input(Some((1, StopRoute::Portal)), false));+ assert_eq!(lease.phase, Phase::AwaitingShortcut);+ assert!(lease.accept_stop_input(Some((1, StopRoute::Portal)), true));+ assert!(state.shortcut(true));+ assert!(+ !state+ .lease+ .as_mut()+ .unwrap()+ .accept_stop_input(Some((1, StopRoute::Tray)), false)+ );+ assert!(+ state+ .lease+ .as_mut()+ .unwrap()+ .accept_stop_input(Some((1, StopRoute::Portal)), false)+ );+ assert!(state.shortcut(false));+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);+ }++ #[test]+ fn wayland_tray_activation_starts_and_next_activation_stops() {+ let mut state = fixture();+ state.lease.as_mut().unwrap().wayland = true;+ for pressed in [true, false] {+ assert!(+ state+ .lease+ .as_mut()+ .unwrap()+ .accept_stop_input(Some((1, StopRoute::Tray)), pressed)+ );+ assert!(state.shortcut(pressed));+ }+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Starting);+ state.lease.as_mut().unwrap().phase = Phase::Recording;+ assert!(+ state+ .lease+ .as_mut()+ .unwrap()+ .accept_stop_input(Some((1, StopRoute::Tray)), true)+ );+ assert!(state.shortcut(true));+ assert!(state.lease.as_ref().unwrap().stop_requested);+ }++ #[test]+ fn wayland_loss_cannot_start_or_silently_switch_control() {+ let mut state = fixture();+ let lease = state.lease.as_mut().unwrap();+ lease.wayland = true;+ assert!(!lease.lose_stop_route(StopRoute::Portal));+ assert!(!lease.stop_requested);+ assert!(!lease.accept_stop_input(Some((1, StopRoute::Portal)), true));+ assert!(lease.accept_stop_input(Some((1, StopRoute::Tray)), true));+ lease.phase = Phase::Recording;+ assert!(lease.lose_stop_route(StopRoute::Tray));+ assert!(lease.stop_requested);+ assert!(!lease.accept_stop_input(Some((1, StopRoute::Tray)), true));+ }++ #[test]+ fn wayland_both_missing_controls_cancel_visible_preflight() {+ let mut state = fixture();+ let lease = state.lease.as_mut().unwrap();+ lease.wayland = true;+ assert!(!lease.lose_stop_route(StopRoute::Tray));+ assert!(!lease.lose_stop_route(StopRoute::Portal));+ assert!(lease.stop_requested);+ assert_eq!(lease.phase, Phase::AwaitingShortcut);+ }++ #[test]+ fn wayland_control_loss_during_start_is_retained_until_cleanup() {+ let mut state = fixture();+ let lease = state.lease.as_mut().unwrap();+ lease.wayland = true;+ lease.stop_route = Some(StopRoute::Tray);+ lease.phase = Phase::Starting;+ assert!(!lease.lose_stop_route(StopRoute::Tray));+ assert!(lease.stop_requested);+ assert_eq!(lease.phase, Phase::Starting);+ }++ #[test]+ fn only_acknowledged_pause_allows_main() {+ let mut state = fixture();+ for phase in [+ Phase::Starting,+ Phase::Recording,+ Phase::Pausing,+ Phase::Resuming,+ Phase::Restarting,+ Phase::Stopping,+ ] {+ state.lease.as_mut().unwrap().phase = phase;+ assert!(!state.may_reveal(1, "main"));+ assert!(!state.may_reveal(1, "camera"));+ assert!(!state.may_reveal(1, "in-progress-recording"));+ }+ state.lease.as_mut().unwrap().phase = Phase::Paused;+ assert!(state.may_reveal(1, "main"));+ assert!(!state.may_reveal(1, "camera"));+ }++ #[test]+ fn instant_uses_capture_backend_without_loosening_studio_environment() {+ use cap_recording::RecordingMode;+ for strict_x11 in [false, true] {+ assert!(capture_environment_is_x11(+ RecordingMode::Instant,+ strict_x11,+ false+ ));+ assert!(!capture_environment_is_x11(+ RecordingMode::Instant,+ strict_x11,+ true+ ));+ for uses_wayland_portal in [false, true] {+ assert_eq!(+ capture_environment_is_x11(+ RecordingMode::Studio,+ strict_x11,+ uses_wayland_portal+ ),+ strict_x11+ );+ }+ }+ assert!(!x11_environment(true, false, None));+ assert!(capture_environment_is_x11(+ RecordingMode::Instant,+ x11_environment(true, false, None),+ false+ ));+ assert!(!x11_environment(true, true, Some("x11")));+ assert!(capture_environment_is_x11(+ RecordingMode::Instant,+ x11_environment(true, true, Some("x11")),+ false+ ));+ }++ #[test]+ fn monitor_visibility_requires_x11_for_both_recording_modes() {+ use cap_recording::{RecordingMode, screen_capture::ScreenCaptureTarget};+ let display = ScreenCaptureTarget::Display {+ id: "1".parse().unwrap(),+ };+ let area = ScreenCaptureTarget::Area {+ screen: "1".parse().unwrap(),+ bounds: scap_targets::bounds::LogicalBounds::new(+ scap_targets::bounds::LogicalPosition::new(0.0, 0.0),+ scap_targets::bounds::LogicalSize::new(100.0, 100.0),+ ),+ };+ let window = ScreenCaptureTarget::Window {+ id: "1".parse().unwrap(),+ };+ for mode in [RecordingMode::Studio, RecordingMode::Instant] {+ for target in [&display, &area] {+ assert_eq!(validate_capture_visibility(mode, target, true), Ok(true));+ assert!(validate_capture_visibility(mode, target, false).is_err());+ }+ for target in [&window, &ScreenCaptureTarget::CameraOnly] {+ assert_eq!(validate_capture_visibility(mode, target, true), Ok(false));+ assert_eq!(validate_capture_visibility(mode, target, false), Ok(false));+ }+ }+ assert_eq!(+ validate_capture_visibility(RecordingMode::Screenshot, &display, false),+ Ok(false)+ );+ }++ #[test]+ fn refuses_wayland_and_ambiguous_sessions() {+ assert!(x11_environment(true, false, Some("x11")));+ assert!(!x11_environment(true, true, Some("x11")));+ assert!(!x11_environment(true, false, Some("wayland")));+ assert!(!x11_environment(true, false, None));+ assert!(!x11_environment(false, false, Some("x11")));+ }++ #[test]+ fn cancel_preflight_never_starts() {+ let mut state = fixture();+ assert!(state.queue_stop());+ assert!(state.shortcut(true));+ assert!(state.shortcut(false));+ assert!(state.lease.as_ref().unwrap().stop_requested);+ }++ #[test]+ fn stop_is_retained_through_start_restart_and_control_transitions() {+ for phase in [Phase::Starting, Phase::Restarting, Phase::Pausing] {+ let mut state = fixture();+ state.lease.as_mut().unwrap().phase = phase;+ assert!(state.queue_stop());+ assert!(state.lease.as_ref().unwrap().stop_requested);+ assert_eq!(state.lease.as_ref().unwrap().phase, phase);+ }+ }++ #[test]+ fn active_stop_claims_cleanup_once() {+ let mut state = fixture();+ state.lease.as_mut().unwrap().phase = Phase::Recording;+ assert!(!state.queue_stop());+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Stopping);+ assert!(state.queue_stop());+ assert!(state.lease.as_ref().unwrap().stop_requested);+ }++ #[test]+ fn unconfirmed_resume_failure_keeps_main_hidden_and_stop_actionable() {+ let mut state = fixture();+ let dir = PathBuf::from("recording-a");+ let lease = state.lease.as_mut().unwrap();+ lease.recording_dir = Some(dir.clone());+ lease.phase = Phase::Resuming;+ assert!(state.complete_control(+ 1,+ &dir,+ true,+ &ControlOutcome::ActorFailed {+ error: "actor transport failed".into(),+ paused: false,+ }+ ));+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::ResumeFailed);+ assert!(state.shortcut(true));+ assert!(state.lease.as_ref().unwrap().phase.can_stop());+ assert!(!state.may_reveal(1, "main"));+ assert!(!state.queue_stop());+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Stopping);+ }++ #[test]+ fn old_control_acknowledgement_cannot_publish_into_new_recording() {+ let mut state = fixture();+ let lease = state.lease.as_mut().unwrap();+ lease.phase = Phase::Pausing;+ lease.recording_dir = Some(PathBuf::from("recording-b"));+ lease.generation = 2;+ state.generation = 2;+ assert!(!state.complete_control(+ 1,+ std::path::Path::new("recording-a"),+ false,+ &ControlOutcome::Succeeded+ ));+ assert!(!state.complete_control(+ 2,+ std::path::Path::new("recording-a"),+ false,+ &ControlOutcome::Succeeded+ ));+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::Pausing);+ }++ #[test]+ fn target_overlays_stay_hidden_even_during_preflight_and_pause() {+ let mut state = fixture();+ for phase in [+ Phase::AwaitingShortcut,+ Phase::Recording,+ Phase::Paused,+ Phase::Restarting,+ Phase::Restoring,+ ] {+ state.lease.as_mut().unwrap().phase = phase;+ assert!(!state.may_reveal(1, "target-select-overlay-1"));+ }+ }++ #[test]+ fn restore_preserves_hidden_camera_and_rejects_replaced_native_window() {+ for visible in [false, true] {+ let saved = SavedWindow {+ label: "camera".into(),+ native_id: 42,+ visible,+ };+ assert_eq!(saved.visibility_for(42), Some(visible));+ assert_eq!(saved.visibility_for(43), None);+ }+ }++ #[test]+ fn startup_failure_cannot_own_a_different_pending_recording() {+ let mut state = fixture();+ let old = PathBuf::from("failed-start-a");+ let new = PathBuf::from("pending-start-b");+ state.lease.as_mut().unwrap().phase = Phase::Starting;+ state.lease.as_mut().unwrap().recording_dir = Some(old.clone());+ assert_eq!(state.owner(&old), Some(1));+ assert_eq!(state.owner(&new), None);+ state.lease.as_mut().unwrap().recording_dir = Some(new.clone());+ state.lease.as_mut().unwrap().generation = 2;+ state.generation = 2;+ assert_eq!(state.owner(&old), None);+ assert_eq!(state.owner(&new), Some(2));+ }++ #[tokio::test]+ async fn pending_pause_does_not_reveal_main_and_retains_queued_stop_after_ack() {+ let state = std::sync::Arc::new(Mutex::new(fixture()));+ let dir = PathBuf::from("recording-a");+ {+ let mut state = state.lock().unwrap();+ let lease = state.lease.as_mut().unwrap();+ lease.phase = Phase::Pausing;+ lease.recording_dir = Some(dir.clone());+ }+ let (acknowledge, received) = tokio::sync::oneshot::channel();+ let pending = {+ let state = state.clone();+ tokio::spawn(async move {+ received.await.unwrap();+ state+ .lock()+ .unwrap()+ .complete_control(1, &dir, false, &ControlOutcome::Succeeded)+ })+ };+ {+ let mut state = state.lock().unwrap();+ assert!(!state.may_reveal(1, "main"));+ assert!(state.queue_stop());+ }+ acknowledge.send(()).unwrap();+ assert!(pending.await.unwrap());+ let mut state = state.lock().unwrap();+ assert!(state.lease.as_ref().unwrap().stop_requested);+ assert!(!state.queue_stop());+ assert!(!state.may_reveal(1, "main"));+ }++ #[tokio::test]+ async fn stopped_owner_rejects_delayed_resume_acknowledgement() {+ let state = std::sync::Arc::new(Mutex::new(fixture()));+ let dir = PathBuf::from("recording-a");+ {+ let mut state = state.lock().unwrap();+ let lease = state.lease.as_mut().unwrap();+ lease.phase = Phase::Resuming;+ lease.recording_dir = Some(dir.clone());+ }+ let (acknowledge, received) = tokio::sync::oneshot::channel();+ let pending = {+ let state = state.clone();+ tokio::spawn(async move {+ received.await.unwrap();+ state+ .lock()+ .unwrap()+ .complete_control(1, &dir, true, &ControlOutcome::Succeeded)+ })+ };+ state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;+ acknowledge.send(()).unwrap();+ assert!(!pending.await.unwrap());+ assert_eq!(+ state.lock().unwrap().lease.as_ref().unwrap().phase,+ Phase::Restoring+ );+ }++ struct RunningControl {+ state: std::sync::Arc<Mutex<Inner>>,+ stages: tokio::sync::mpsc::UnboundedReceiver<&'static str>,+ hide: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,+ change: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,+ paused: Option<tokio::sync::oneshot::Sender<bool>>,+ reveal: Option<tokio::sync::oneshot::Sender<()>>,+ result: tokio::task::JoinHandle<Result<(), String>>,+ }++ impl RunningControl {+ fn start(resume: bool) -> Self {+ let state = std::sync::Arc::new(Mutex::new(fixture()));+ {+ let mut inner = state.lock().unwrap();+ let lease = inner.lease.as_mut().unwrap();+ lease.phase = if resume {+ Phase::Resuming+ } else {+ Phase::Pausing+ };+ lease.recording_dir = Some(PathBuf::from("recording-a"));+ }+ let (stages, observed) = tokio::sync::mpsc::unbounded_channel();+ let (hide, hidden) = tokio::sync::oneshot::channel();+ let (change, changed) = tokio::sync::oneshot::channel();+ let (paused, acknowledged) = tokio::sync::oneshot::channel();+ let (reveal, mapping) = tokio::sync::oneshot::channel();+ let control_state = state.clone();+ let result = tokio::spawn(async move {+ let dir = PathBuf::from("recording-a");+ ControlOperation {+ resume,+ generation: 1,+ dir: &dir,+ hide: async {+ stages.send("hide").unwrap();+ hidden.await.unwrap()+ },+ change: async {+ stages.send("actor").unwrap();+ changed.await.unwrap()+ },+ paused: async {+ stages.send("confirm-paused").unwrap();+ acknowledged.await.unwrap()+ },+ restore: async {+ stages.send("queue-main").unwrap();+ mapping.await.unwrap();+ if control_state+ .lock()+ .unwrap()+ .may_restore_paused_main(1, &dir)+ {+ stages.send("show-main").unwrap();+ Ok(())+ } else {+ stages.send("suppress-main").unwrap();+ Err("Recording changed before mapping".into())+ }+ },+ stop: async {+ stages.send("stop").unwrap();+ assert!(!control_state.lock().unwrap().queue_stop());+ Ok(())+ },+ notify: || stages.send("notify").unwrap(),+ }+ .run(&control_state)+ .await+ });+ Self {+ state,+ stages: observed,+ hide: Some(hide),+ change: Some(change),+ paused: Some(paused),+ reveal: Some(reveal),+ result,+ }+ }++ async fn dispatch_stop(+ &self,+ ) -> (+ tokio::sync::oneshot::Sender<()>,+ tokio::task::JoinHandle<()>,+ ) {+ {+ let mut inner = self.state.lock().unwrap();+ assert!(inner.shortcut(true));+ assert!(inner.lease.as_ref().unwrap().phase.can_stop());+ assert!(!inner.queue_stop());+ }+ let (entered, delivered) = tokio::sync::oneshot::channel();+ let (acknowledge, joined) = tokio::sync::oneshot::channel();+ let state = self.state.clone();+ let stop = tokio::spawn(async move {+ entered.send(()).unwrap();+ joined.await.unwrap();+ let mut inner = state.lock().unwrap();+ if inner.owner(std::path::Path::new("recording-a")) == Some(1)+ && inner.lease.as_ref().unwrap().phase == Phase::Stopping+ {+ inner.lease.as_mut().unwrap().phase = Phase::Restoring;+ }+ });+ tokio::time::timeout(Duration::from_secs(1), delivered)+ .await+ .unwrap()+ .unwrap();+ (acknowledge, stop)+ }++ async fn expect(&mut self, stage: &'static str) {+ assert_eq!(+ tokio::time::timeout(Duration::from_secs(1), self.stages.recv())+ .await+ .unwrap(),+ Some(stage)+ );+ }++ async fn finish(self) -> Result<(), String> {+ tokio::time::timeout(Duration::from_secs(1), self.result)+ .await+ .unwrap()+ .unwrap()+ }+ }++ #[tokio::test]+ async fn resume_hide_failure_restores_main_without_calling_actor() {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ run.hide+ .take()+ .unwrap()+ .send(Err("partial unmap failed".into()))+ .unwrap();+ run.expect("notify").await;+ run.expect("queue-main").await;+ {+ let inner = run.state.lock().unwrap();+ assert_eq!(inner.lease.as_ref().unwrap().phase, Phase::Paused);+ assert!(!inner.may_reveal(1, "camera"));+ assert!(!inner.may_reveal(1, "in-progress-recording"));+ assert!(inner.lease.as_ref().unwrap().registered_shortcut);+ }+ run.reveal.take().unwrap().send(()).unwrap();+ run.expect("show-main").await;+ assert_eq!(run.finish().await.unwrap_err(), "partial unmap failed");+ }++ #[tokio::test]+ async fn actor_resume_error_waits_for_quiescent_pause_ack_before_mapping() {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ run.hide.take().unwrap().send(Ok(())).unwrap();+ run.expect("actor").await;+ run.change+ .take()+ .unwrap()+ .send(Err("segment setup failed".into()))+ .unwrap();+ run.expect("confirm-paused").await;+ assert!(!run.state.lock().unwrap().may_reveal(1, "main"));+ run.paused.take().unwrap().send(true).unwrap();+ run.expect("notify").await;+ run.expect("queue-main").await;+ run.reveal.take().unwrap().send(()).unwrap();+ run.expect("show-main").await;+ assert_eq!(run.finish().await.unwrap_err(), "segment setup failed");+ }++ #[tokio::test]+ async fn unknown_resume_error_does_not_map_and_stop_remains_executable() {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ run.hide.take().unwrap().send(Ok(())).unwrap();+ run.expect("actor").await;+ run.change+ .take()+ .unwrap()+ .send(Err("transport failed".into()))+ .unwrap();+ run.expect("confirm-paused").await;+ run.paused.take().unwrap().send(false).unwrap();+ run.expect("notify").await;+ let state = run.state.clone();+ assert!(+ run.finish()+ .await+ .unwrap_err()+ .contains("pause could not be confirmed")+ );+ let mut state = state.lock().unwrap();+ assert_eq!(state.lease.as_ref().unwrap().phase, Phase::ResumeFailed);+ assert!(state.shortcut(true));+ assert!(state.lease.as_ref().unwrap().phase.can_stop());+ assert!(!state.may_reveal(1, "main"));+ assert!(!state.queue_stop());+ }++ #[tokio::test]+ async fn stop_during_hide_executes_before_resume_and_rejects_late_hide() {+ for hidden in [Ok(()), Err("hide failed".into())] {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ let (ack, stopped) = run.dispatch_stop().await;+ assert!(!run.result.is_finished());+ ack.send(()).unwrap();+ stopped.await.unwrap();+ run.hide.take().unwrap().send(hidden).unwrap();+ assert!(run.finish().await.unwrap_err().contains("changed during"));+ }+ }++ #[tokio::test]+ async fn stop_during_pause_confirmation_executes_without_waiting_for_it() {+ for paused in [true, false] {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ run.hide.take().unwrap().send(Ok(())).unwrap();+ run.expect("actor").await;+ run.change+ .take()+ .unwrap()+ .send(Err("setup failed".into()))+ .unwrap();+ run.expect("confirm-paused").await;+ let (ack, stopped) = run.dispatch_stop().await;+ assert!(!run.result.is_finished());+ ack.send(()).unwrap();+ stopped.await.unwrap();+ run.paused.take().unwrap().send(paused).unwrap();+ assert!(run.finish().await.unwrap_err().contains("changed during"));+ }+ }++ #[tokio::test]+ async fn pending_resume_does_not_block_stop_and_late_result_cannot_publish() {+ for resumed in [Ok(()), Err("cancelled setup".into())] {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ run.hide.take().unwrap().send(Ok(())).unwrap();+ run.expect("actor").await;+ let (ack, stopped) = run.dispatch_stop().await;+ assert!(!run.result.is_finished());+ assert_eq!(+ run.state.lock().unwrap().lease.as_ref().unwrap().phase,+ Phase::Stopping+ );+ ack.send(()).unwrap();+ stopped.await.unwrap();+ assert!(!run.result.is_finished());+ let failed = resumed.is_err();+ run.change.take().unwrap().send(resumed).unwrap();+ if failed {+ run.expect("confirm-paused").await;+ run.paused.take().unwrap().send(true).unwrap();+ }+ let state = run.state.clone();+ assert!(run.finish().await.unwrap_err().contains("changed during"));+ let inner = state.lock().unwrap();+ assert_eq!(inner.lease.as_ref().unwrap().phase, Phase::Restoring);+ assert!(inner.snapshot().error.is_none());+ }+ }++ #[tokio::test]+ async fn delayed_pause_confirmation_cannot_publish_to_new_owner() {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ run.hide.take().unwrap().send(Ok(())).unwrap();+ run.expect("actor").await;+ run.change+ .take()+ .unwrap()+ .send(Err("setup failed".into()))+ .unwrap();+ run.expect("confirm-paused").await;+ {+ let mut inner = run.state.lock().unwrap();+ inner.generation = 2;+ let lease = inner.lease.as_mut().unwrap();+ lease.generation = 2;+ lease.recording_dir = Some(PathBuf::from("recording-b"));+ }+ run.paused.take().unwrap().send(true).unwrap();+ let state = run.state.clone();+ assert!(run.finish().await.unwrap_err().contains("changed during"));+ assert_eq!(+ state.lock().unwrap().lease.as_ref().unwrap().phase,+ Phase::Resuming+ );+ }++ #[tokio::test]+ async fn delayed_main_mapping_rechecks_owner_phase_and_stop() {+ for mutation in 0..4 {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ run.hide+ .take()+ .unwrap()+ .send(Err("hide failed".into()))+ .unwrap();+ run.expect("notify").await;+ run.expect("queue-main").await;+ {+ let mut inner = run.state.lock().unwrap();+ match mutation {+ 0 => {+ inner.generation = 2;+ inner.lease.as_mut().unwrap().generation = 2;+ }+ 1 => {+ inner.lease.as_mut().unwrap().recording_dir =+ Some(PathBuf::from("recording-b"))+ }+ 2 => inner.lease.as_mut().unwrap().phase = Phase::Resuming,+ _ => inner.lease.as_mut().unwrap().stop_requested = true,+ }+ }+ run.reveal.take().unwrap().send(()).unwrap();+ run.expect("suppress-main").await;+ assert!(+ run.finish()+ .await+ .unwrap_err()+ .contains("Could not restore controls")+ );+ }+ }++ #[tokio::test]+ async fn ordinary_pause_and_successful_resume_never_use_failure_restore() {+ for resume in [false, true] {+ let mut run = RunningControl::start(resume);+ if resume {+ run.expect("hide").await;+ run.hide.take().unwrap().send(Ok(())).unwrap();+ }+ run.expect("actor").await;+ run.change.take().unwrap().send(Ok(())).unwrap();+ run.expect("notify").await;+ let state = run.state.clone();+ assert!(run.finish().await.is_ok());+ assert_eq!(+ state.lock().unwrap().lease.as_ref().unwrap().phase,+ if resume {+ Phase::Recording+ } else {+ Phase::Paused+ }+ );+ }+ }++ #[tokio::test]+ async fn stale_hide_completion_never_invokes_actor_or_restores_main() {+ for success in [false, true] {+ let mut run = RunningControl::start(true);+ run.expect("hide").await;+ run.state.lock().unwrap().lease.as_mut().unwrap().phase = Phase::Restoring;+ run.hide+ .take()+ .unwrap()+ .send(if success {+ Ok(())+ } else {+ Err("hide failed".into())+ })+ .unwrap();+ assert!(run.finish().await.unwrap_err().contains("changed during"));+ }+ }++ #[tokio::test]+ async fn failed_pause_does_not_run_resume_probe_or_restore() {+ let mut run = RunningControl::start(false);+ run.expect("actor").await;+ run.change+ .take()+ .unwrap()+ .send(Err("pause failed".into()))+ .unwrap();+ run.expect("notify").await;+ let state = run.state.clone();+ assert_eq!(run.finish().await.unwrap_err(), "pause failed");+ assert_eq!(+ state.lock().unwrap().lease.as_ref().unwrap().phase,+ Phase::Recording+ );+ assert!(!state.lock().unwrap().may_reveal(1, "main"));+ }++ #[test]+ fn control_error_survives_stop_and_release_but_not_a_new_owner() {+ let mut inner = fixture();+ let dir = PathBuf::from("recording-a");+ inner.lease.as_mut().unwrap().recording_dir = Some(dir.clone());+ inner.lease.as_mut().unwrap().phase = Phase::Resuming;+ assert!(inner.complete_control(+ 1,+ &dir,+ true,+ &ControlOutcome::ActorFailed {+ error: "capture setup failed".into(),+ paused: false+ }+ ));+ assert_eq!(+ inner.snapshot().error.as_deref(),+ Some("capture setup failed")+ );+ assert!(!inner.queue_stop());+ assert_eq!(+ inner.snapshot().error.as_deref(),+ Some("capture setup failed")+ );+ inner.lease = None;+ assert_eq!(+ inner.snapshot().error.as_deref(),+ Some("capture setup failed")+ );+ inner.generation = 2;+ assert!(inner.snapshot().error.is_none());+ }+}++#[cfg(all(test, target_os = "linux"))]+mod instant_activation_tests {+ use super::*;+ use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+ };++ #[tokio::test]+ async fn instant_seal_waits_for_hide_ack_then_settle_then_revalidates() {+ let (hide_tx, hide_rx) = tokio::sync::oneshot::channel();+ let (settle_tx, settle_rx) = tokio::sync::oneshot::channel();+ let (settling_tx, settling_rx) = tokio::sync::oneshot::channel();+ let stage = Arc::new(AtomicUsize::new(0));+ let observed = stage.clone();+ let task = tokio::spawn(async move {+ let validated = observed.clone();+ seal_then_settle(+ async { hide_rx.await.map_err(|_| "hide ack lost".to_string()) },+ async {+ observed.store(1, Ordering::SeqCst);+ settling_tx.send(()).unwrap();+ settle_rx.await.map_err(|_| "settle cancelled".to_string())+ },+ |owner| async move {+ validated.store(2, Ordering::SeqCst);+ Ok(owner)+ },+ )+ .await+ });+ tokio::task::yield_now().await;+ assert_eq!(stage.load(Ordering::SeqCst), 0);+ assert!(!task.is_finished());+ hide_tx.send(7).unwrap();+ settling_rx.await.unwrap();+ assert_eq!(stage.load(Ordering::SeqCst), 1);+ assert!(!task.is_finished());+ settle_tx.send(()).unwrap();+ assert_eq!(task.await.unwrap().unwrap(), 7);+ assert_eq!(stage.load(Ordering::SeqCst), 2);+ }++ #[tokio::test]+ async fn instant_lost_hide_ack_never_settles_or_builds() {+ let (tx, rx) = tokio::sync::oneshot::channel::<u32>();+ drop(tx);+ let result = seal_then_settle(+ async { rx.await.map_err(|_| "hide ack lost".to_string()) },+ async { panic!("settle cannot begin before hide acknowledgement") },+ |_| async { panic!("build validation cannot begin") },+ )+ .await;+ assert_eq!(result.unwrap_err(), "hide ack lost");+ }++ #[tokio::test]+ async fn instant_cancelled_settle_does_not_revalidate_or_build() {+ let result = seal_then_settle(+ async { Ok(7) },+ async { Err("cancelled".into()) },+ |_| async { panic!("cancelled preparation cannot build") },+ )+ .await;+ assert_eq!(result.unwrap_err(), "cancelled");+ }++ #[tokio::test]+ async fn instant_changed_effect_or_geometry_after_settle_rejects_owner() {+ let result = seal_then_settle(async { Ok(7) }, async { Ok(()) }, |owner| async move {+ assert_eq!(owner, 7);+ Err("prepared presentation changed".into())+ })+ .await;+ assert_eq!(result.unwrap_err(), "prepared presentation changed");+ }++ #[tokio::test]+ async fn instant_restore_waits_for_main_and_camera_acknowledgements() {+ let (main_tx, main_rx) = tokio::sync::oneshot::channel();+ let (camera_tx, camera_rx) = tokio::sync::oneshot::channel();+ let (inputs_tx, inputs_rx) = tokio::sync::oneshot::channel();+ let stage = Arc::new(AtomicUsize::new(0));+ let observed = stage.clone();+ let task = tokio::spawn(async move {+ restore_instant_sequence(+ async { main_rx.await.map_err(|_| "main ack lost".to_string()) },+ || async {+ observed.store(1, Ordering::SeqCst);+ inputs_tx.send(()).unwrap();+ },+ || async { camera_rx.await.map_err(|_| "camera ack lost".to_string()) },+ )+ .await+ });+ tokio::task::yield_now().await;+ assert_eq!(stage.load(Ordering::SeqCst), 0);+ main_tx.send(()).unwrap();+ inputs_rx.await.unwrap();+ assert_eq!(stage.load(Ordering::SeqCst), 1);+ assert!(!task.is_finished());+ camera_tx.send(()).unwrap();+ task.await.unwrap().unwrap();+ }++ #[tokio::test]+ async fn instant_restore_rejected_or_lost_main_ack_never_restores_inputs() {+ for rejected in [true, false] {+ let (tx, rx) = tokio::sync::oneshot::channel::<Result<(), String>>();+ if rejected {+ tx.send(Err("unsafe cleanup".into())).unwrap();+ } else {+ drop(tx);+ }+ let result = restore_instant_sequence(+ async { rx.await.map_err(|_| "main ack lost".to_string())? },+ || async { panic!("inputs must remain untouched") },+ || async { panic!("camera must remain hidden") },+ )+ .await;+ assert!(result.is_err());+ }+ }++ #[tokio::test]+ async fn instant_open_cap_waits_for_stop_ack_and_never_polls_studio_pause() {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(finish_main_controls(+ Some(Phase::Recording),+ Some(async { rx.await.map_err(|_| "stop ack lost".to_string()) }),+ async { panic!("Instant OpenCap must not pause") },+ ));+ tokio::task::yield_now().await;+ assert!(!task.is_finished());+ tx.send(()).unwrap();+ task.await.unwrap().unwrap();+ }++ #[tokio::test]+ async fn instant_open_cap_preserves_stop_failure_without_pause_or_reveal_permission() {+ let result = finish_main_controls(+ Some(Phase::Starting),+ Some(async { Err("capture cleanup unconfirmed".into()) }),+ async { panic!("Instant OpenCap must not pause") },+ )+ .await;+ assert_eq!(result.unwrap_err(), "capture cleanup unconfirmed");+ }++ #[tokio::test]+ async fn studio_open_cap_waits_for_pause_ack_before_allowing_reveal() {+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ let (paused_tx, paused_rx) = tokio::sync::oneshot::channel();+ let reveals = Arc::new(AtomicUsize::new(0));+ let observed = reveals.clone();+ let task = tokio::spawn(async move {+ finish_main_controls(+ Some(Phase::Recording),+ None::<std::future::Ready<Result<(), String>>>,+ async {+ started_tx.send(()).unwrap();+ paused_rx.await.map_err(|_| "pause ack lost".to_string())+ },+ )+ .await?;+ observed.fetch_add(1, Ordering::SeqCst);+ Ok::<(), String>(())+ });+ started_rx.await.unwrap();+ assert!(!task.is_finished());+ assert_eq!(reveals.load(Ordering::SeqCst), 0);+ paused_tx.send(()).unwrap();+ task.await.unwrap().unwrap();+ assert_eq!(reveals.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn studio_open_cap_preserves_pause_failure_without_allowing_reveal() {+ let result: Result<(), String> = async {+ finish_main_controls(+ Some(Phase::Recording),+ None::<std::future::Ready<Result<(), String>>>,+ async { Err("pause acknowledgement failed".into()) },+ )+ .await?;+ panic!("a failed pause must not permit controls to be revealed")+ }+ .await;+ assert_eq!(result.unwrap_err(), "pause acknowledgement failed");+ }++ #[tokio::test]+ async fn repeated_studio_open_cap_keeps_the_recording_paused() {+ for _ in 0..3 {+ finish_main_controls(+ Some(Phase::Paused),+ None::<std::future::Ready<Result<(), String>>>,+ async { panic!("an already paused recording must not be changed") },+ )+ .await+ .unwrap();+ }+ }++ #[tokio::test]+ async fn studio_open_cap_rejects_pending_transitions_without_changing_capture() {+ for phase in [+ Phase::Starting,+ Phase::Pausing,+ Phase::Resuming,+ Phase::ResumeFailed,+ Phase::Restarting,+ Phase::Stopping,+ ] {+ let result = finish_main_controls(+ Some(phase),+ None::<std::future::Ready<Result<(), String>>>,+ async { panic!("a pending recording transition must not be changed") },+ )+ .await;+ assert_eq!(+ result.unwrap_err(),+ "Recording is changing state. Use Ctrl+Shift+F9 to stop."+ );+ }+ }++ #[tokio::test]+ async fn open_cap_keeps_preflight_visible_and_studio_pause_semantics() {+ finish_main_controls(+ Some(Phase::AwaitingShortcut),+ Some(async { panic!("preflight must not issue Stop") }),+ async { panic!("preflight must not issue Pause") },+ )+ .await+ .unwrap();+ finish_main_controls(+ Some(Phase::Recording),+ None::<std::future::Ready<Result<(), String>>>,+ async { Ok(()) },+ )+ .await+ .unwrap();+ }++ fn restoring() -> Inner {+ Inner {+ generation: 7,+ lease: Some(Lease {+ mode: cap_recording::RecordingMode::Instant,+ generation: 7,+ phase: Phase::Restoring,+ pressed: false,+ stop_requested: false,+ registered_shortcut: true,+ wayland: false,+ stop_route: None,+ stop_description: None,+ stop_error: None,+ lost_stop_routes: [false; 2],+ recording_dir: None,+ windows: Vec::new(),+ }),+ ..Inner::default()+ }+ }++ #[test]+ fn instant_restore_error_retains_lease_shortcut_and_error_until_successful_retry() {+ let mut inner = restoring();+ assert_eq!(+ inner.complete_instant_restoration(7, Err("camera ack lost".into())),+ None+ );+ assert_eq!(inner.snapshot().error.as_deref(), Some("camera ack lost"));+ assert!(inner.lease.as_ref().unwrap().registered_shortcut);+ assert_eq!(inner.generation, 7);+ assert_eq!(inner.complete_instant_restoration(7, Ok(())), Some(true));+ assert!(inner.lease.is_none());+ assert_eq!(inner.generation, 8);+ let receipt = inner.restored.as_ref().unwrap();+ assert_eq!(receipt.generation, 7);+ assert_eq!(receipt.restart_result(), Ok(()));+ }++ #[test]+ fn instant_stop_during_restoration_prevents_restart_after_successful_window_ack() {+ let mut inner = restoring();+ assert!(inner.shortcut(true));+ assert_eq!(inner.complete_instant_restoration(7, Ok(())), Some(true));+ assert!(inner.lease.is_none());+ assert_eq!(inner.generation, 8);+ assert!(inner.restored.as_ref().unwrap().restart_result().is_err());+ }++ #[test]+ fn instant_stale_restore_receipt_cannot_clear_new_lease_or_error() {+ let mut inner = restoring();+ assert_eq!(inner.complete_instant_restoration(6, Ok(())), None);+ assert!(inner.restored.is_none());+ inner.lease.as_mut().unwrap().phase = Phase::Starting;+ assert_eq!(inner.complete_instant_restoration(7, Ok(())), None);+ assert!(inner.lease.as_ref().unwrap().registered_shortcut);+ assert!(inner.restored.is_none());+ }+}++#[cfg(target_os = "linux")]+thread_local! {+ static WAYLAND_WINDOWS: std::cell::RefCell<std::collections::HashMap<u32, Vec<gtk::ApplicationWindow>>> = std::cell::RefCell::new(std::collections::HashMap::new());+}++#[cfg(target_os = "linux")]+pub(crate) fn wayland_generation(app: &AppHandle) -> Option<u32> {+ let state = app.try_state::<State>()?;+ let inner = state.inner.lock().unwrap();+ inner+ .lease+ .as_ref()+ .filter(|lease| lease.wayland)+ .map(|lease| lease.generation)+}++#[cfg(target_os = "linux")]+pub(crate) fn describe_wayland_stop(app: &AppHandle, generation: u32, description: String) {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ if let Some(lease) = inner+ .lease+ .as_mut()+ .filter(|lease| lease.generation == generation && lease.wayland)+ {+ lease.stop_description = Some(description);+ }+ drop(inner);+ notify(app);+}++async fn save_windows(app: &AppHandle, generation: u32) -> Result<Vec<SavedWindow>, String> {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = app.clone();+ app.run_on_main_thread(move || {+ let result = (|| {+ if !is_current(&handle, generation) {+ return Err("Recording preflight was superseded".to_string());+ }+ #[cfg(target_os = "linux")]+ if wayland_generation(&handle) == Some(generation) {+ install_wayland_window_guard(&handle)?;+ remember_wayland_windows(&handle, generation)?;+ }+ #[cfg(target_os = "linux")]+ let save_all = wayland_generation(&handle) == Some(generation);+ #[cfg(not(target_os = "linux"))]+ let save_all = false;+ let mut saved = Vec::new();+ for (label, window) in handle.webview_windows() {+ if save_all+ || matches!(+ label.parse::<CapWindowId>(),+ Ok(CapWindowId::Main | CapWindowId::Camera)+ )+ {+ #[cfg(target_os = "linux")]+ if wayland_generation(&handle) == Some(generation) {+ let gtk = window.gtk_window().map_err(|error| error.to_string())?;+ WAYLAND_WINDOWS.with_borrow_mut(|windows| {+ windows.entry(generation).or_default().push(gtk)+ });+ }+ saved.push(SavedWindow {+ label,+ native_id: native_id(&window)?,+ visible: window.is_visible().map_err(|error| error.to_string())?,+ });+ }+ }+ Ok(saved)+ })();+ let _ = tx.send(result);+ })+ .map_err(|error| error.to_string())?;+ tokio::time::timeout(Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Timed out saving recording windows".to_string())?+ .map_err(|_| "Recording windows could not be saved".to_string())?+}++fn set_native_visibility(window: &WebviewWindow, visible: bool) -> Result<(), String> {+ #[cfg(target_os = "linux")]+ if cap_recording::screenshot::uses_wayland_portal() {+ use gtk::prelude::*;+ let gtk = window.gtk_window().map_err(|error| error.to_string())?;+ if visible {+ gtk.show();+ } else {+ gtk.hide();+ }+ if gtk.is_visible() != visible || (!visible && gtk.is_mapped()) {+ return Err("GTK did not acknowledge the recording window visibility change".into());+ }+ return Ok(());+ }+ if visible {+ window.show()+ } else {+ window.hide()+ }+ .map_err(|error| error.to_string())+}++#[cfg(target_os = "linux")]+async fn wayland_fence(app: &AppHandle, generation: u32, hidden: bool) -> Result<(), String> {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = app.clone();+ app.run_on_main_thread(move || {+ let display = (|| {+ use gtk::prelude::*;+ if !is_current(&handle, generation) {+ return Err("Recording visibility fence was superseded".to_string());+ }+ let gtk = if let Some(window) = CapWindowId::Main.get(&handle) {+ window.gtk_window().map_err(|error| error.to_string())?+ } else if !hidden && phase(&handle) == Some(Phase::Restoring) {+ WAYLAND_WINDOWS+ .with_borrow(|windows| {+ windows+ .get(&generation)+ .and_then(|windows| windows.first())+ .cloned()+ })+ .ok_or("Retained recording display disappeared")?+ } else {+ return Err("Main recording window disappeared".into());+ };+ let display = gtk.display();+ if display.type_().name() != "GdkWaylandDisplay" {+ return Err(+ "The recording window is not connected to the Wayland compositor".into(),+ );+ }+ Ok(display)+ })();+ match display {+ Ok(display) => wayland_ack::start(display, handle, generation, hidden, tx),+ Err(error) => {+ let _ = tx.send(Err(error));+ }+ }+ })+ .map_err(|error| error.to_string())?;+ tokio::time::timeout(Duration::from_secs(3), rx)+ .await+ .map_err(|_| "Wayland visibility acknowledgement timed out".to_string())?+ .map_err(|_| "Wayland visibility acknowledgement was lost".to_string())??;+ if !is_current(app, generation) {+ return Err("Recording visibility acknowledgement was superseded".into());+ }+ Ok(())+}++#[cfg(target_os = "linux")]+mod wayland_ack {+ use gtk::{gdk, prelude::*};+ use std::{+ cell::{Cell, RefCell},+ ffi::c_void,+ rc::Rc,+ time::Duration,+ };+ use wayland_sys::{client::*, common::*};++ type Reply = tokio::sync::oneshot::Sender<Result<(), String>>;+ struct Pending {+ callback: Cell<*mut wl_proxy>,+ reply: RefCell<Option<Reply>>,+ _display: gdk::Display,+ app: tauri::AppHandle,+ generation: u32,+ hidden: bool,+ }+ impl Pending {+ fn finish(&self, result: Result<(), String>) {+ let callback = self.callback.replace(std::ptr::null_mut());+ if !callback.is_null() {+ unsafe {+ (wayland_client_handle().wl_proxy_destroy)(callback);+ }+ }+ if let Some(reply) = self.reply.borrow_mut().take() {+ let _ = reply.send(result);+ }+ }+ }+ static CALLBACK: wl_interface = wl_interface {+ name: c"wl_callback".as_ptr(),+ version: 1,+ request_count: 0,+ requests: std::ptr::null(),+ event_count: 1,+ events: &wl_message {+ name: c"done".as_ptr(),+ signature: c"u".as_ptr(),+ types: std::ptr::null(),+ },+ };+ unsafe extern "C" fn dispatch(+ _: *const c_void,+ data: *mut c_void,+ opcode: u32,+ _: *const wl_message,+ _: *const wl_argument,+ ) -> i32 {+ let pending = unsafe {+ &*((wayland_client_handle().wl_proxy_get_user_data)(data.cast()).cast::<Pending>())+ };+ pending.finish(if opcode == 0 {+ if pending.hidden {+ super::verify_wayland_hidden(&pending.app, pending.generation)+ } else {+ super::verify_wayland_restored(&pending.app, pending.generation)+ }+ } else {+ Err("Unexpected Wayland visibility acknowledgement".into())+ });+ 0+ }+ pub(super) fn start(+ display: gdk::Display,+ app: tauri::AppHandle,+ generation: u32,+ hidden: bool,+ reply: Reply,+ ) {+ let Some(client) = wayland_client_option() else {+ let _ = reply.send(Err("Wayland client library is unavailable".into()));+ return;+ };+ let raw =+ unsafe { gdk_wayland_sys::gdk_wayland_display_get_wl_display(display.as_ptr().cast()) }+ .cast::<wl_display>();+ if raw.is_null() {+ let _ = reply.send(Err("Wayland display connection is unavailable".into()));+ return;+ }+ let mut args = [wl_argument {+ o: std::ptr::null(),+ }];+ let callback = unsafe {+ (client.wl_proxy_marshal_array_constructor)(raw.cast(), 0, args.as_mut_ptr(), &CALLBACK)+ };+ if callback.is_null() {+ let _ = reply.send(Err(+ "Could not queue Wayland visibility acknowledgement".into()+ ));+ return;+ }+ let pending = Rc::new(Pending {+ callback: Cell::new(callback),+ reply: RefCell::new(Some(reply)),+ _display: display.clone(),+ app,+ generation,+ hidden,+ });+ let result = unsafe {+ (client.wl_proxy_add_dispatcher)(+ callback,+ dispatch,+ std::ptr::null(),+ Rc::as_ptr(&pending).cast_mut().cast(),+ )+ };+ if result != 0 {+ pending.finish(Err(+ "Could not subscribe to Wayland visibility acknowledgement".into(),+ ));+ return;+ }+ // GDK owns dispatch on this connection. The timeout retains listener data until+ // either the callback or timeout destroys the proxy, without reading GDK's queue.+ gtk::glib::timeout_add_local_once(Duration::from_secs(2), move || {+ pending.finish(Err(+ "Wayland compositor did not acknowledge window visibility".into(),+ ))+ });+ display.flush();+ }+}++#[cfg(target_os = "linux")]+pub(crate) fn wayland_stop_lost(app: &AppHandle, generation: u32, route: StopRoute, error: String) {+ let state = app.state::<State>();+ let mut inner = state.inner.lock().unwrap();+ let Some(lease) = inner+ .lease+ .as_mut()+ .filter(|lease| lease.generation == generation && lease.wayland)+ else {+ return;+ };+ let stop = lease.lose_stop_route(route);+ if lease.stop_requested {+ lease.stop_error = Some(error);+ } else if route == StopRoute::Tray {+ lease.stop_description = Some("the portal shortcut shown by your desktop".into());+ }+ drop(inner);+ notify(app);+ if stop {+ let app = app.clone();+ drop(tauri::async_runtime::spawn(async move {+ if let Err(error) = crate::recording::stop_recording(app.clone(), app.state()).await {+ tracing::error!(%error, "Could not stop recording after losing its Stop control");+ }+ }));+ }+}++#[cfg(target_os = "linux")]+fn verify_wayland_hidden(app: &AppHandle, generation: u32) -> Result<(), String> {+ use gtk::prelude::*;+ if !is_current(app, generation) || stop_requested(app, generation) {+ return Err("Recording hide acknowledgement was superseded or cancelled".into());+ }+ let main = CapWindowId::Main+ .get(app)+ .ok_or("Main recording window disappeared")?+ .gtk_window()+ .map_err(|error| error.to_string())?;+ let display = main.display();+ for window in wayland_application(app)?.windows() {+ if window.display() != display || window.is_visible() || window.is_mapped() {+ return Err("A Cap window is visible or uses another display connection".into());+ }+ }+ Ok(())+}++#[cfg(target_os = "linux")]+fn verify_wayland_restored(app: &AppHandle, generation: u32) -> Result<(), String> {+ use gtk::prelude::*;+ for (saved, wanted) in wayland_restore_plan(app, generation, true)? {+ if saved.window.is_visible() != wanted || saved.window.is_mapped() != wanted {+ return Err("The compositor restore acknowledgement did not match Cap windows".into());+ }+ }+ Ok(())+}++fn wayland_blocks_mapping(phase: Phase) -> bool {+ !matches!(+ phase,+ Phase::AwaitingShortcut | Phase::Paused | Phase::Restoring+ )+}++#[cfg(any(target_os = "linux", test))]+fn restore_floating_window(label: Option<&str>) -> bool {+ !matches!(+ label.and_then(|label| label.parse::<CapWindowId>().ok()),+ Some(+ CapWindowId::RecordingControls+ | CapWindowId::TargetSelectOverlay { .. }+ | CapWindowId::WindowCaptureOccluder { .. }+ | CapWindowId::CaptureArea+ )+ )+}++#[cfg(target_os = "linux")]+#[derive(Clone)]+struct RetainedWaylandWindow {+ window: gtk::Window,+ label: Option<String>,+ visible: bool,+ requested_during_stop: bool,+}++#[cfg(target_os = "linux")]+thread_local! {+ static WAYLAND_GUARD_APPLICATION: std::cell::RefCell<Option<gtk::glib::WeakRef<gtk::Application>>> = const { std::cell::RefCell::new(None) };+ static WAYLAND_GUARDED_WINDOWS: std::cell::RefCell<Vec<gtk::glib::WeakRef<gtk::Window>>> = const { std::cell::RefCell::new(Vec::new()) };+ static WAYLAND_CAPTURE_WINDOWS: std::cell::RefCell<std::collections::HashMap<u32, Vec<RetainedWaylandWindow>>> = std::cell::RefCell::new(std::collections::HashMap::new());+}++#[cfg(target_os = "linux")]+fn wayland_application(app: &AppHandle) -> Result<gtk::Application, String> {+ use gtk::prelude::*;+ CapWindowId::Main+ .get(app)+ .ok_or("Main recording window disappeared")?+ .gtk_window()+ .map_err(|error| error.to_string())?+ .application()+ .ok_or("Recording GTK application disappeared".into())+}++#[cfg(target_os = "linux")]+fn wayland_window_label(app: &AppHandle, native: >k::Window) -> Option<String> {+ use gtk::prelude::*;+ app.webview_windows()+ .into_iter()+ .find_map(|(label, window)| {+ window+ .gtk_window()+ .ok()+ .filter(|window| window.upcast_ref::<gtk::Window>() == native)+ .map(|_| label)+ })+}++#[cfg(target_os = "linux")]+fn remember_wayland_window(+ app: &AppHandle,+ generation: u32,+ window: >k::Window,+ during_stop: bool,+) {+ use gtk::prelude::*;+ let label = wayland_window_label(app, window);+ WAYLAND_CAPTURE_WINDOWS.with_borrow_mut(|windows| {+ let windows = windows.entry(generation).or_default();+ if let Some(saved) = windows.iter_mut().find(|saved| saved.window == *window) {+ if during_stop {+ saved.requested_during_stop = true;+ }+ } else {+ windows.push(RetainedWaylandWindow {+ window: window.clone(),+ label,+ visible: window.is_visible(),+ requested_during_stop: during_stop,+ });+ }+ });+}++#[cfg(target_os = "linux")]+fn guard_wayland_window(app: &AppHandle, window: >k::Window) {+ use gtk::prelude::*;+ let already_guarded = WAYLAND_GUARDED_WINDOWS.with_borrow_mut(|windows| {+ windows.retain(|window| window.upgrade().is_some());+ if windows+ .iter()+ .any(|saved| saved.upgrade().as_ref() == Some(window))+ {+ true+ } else {+ windows.push(window.downgrade());+ false+ }+ });+ if already_guarded {+ return;+ }+ let app = app.clone();+ window.connect_map(move |window| {+ let blocked = {+ let state = app.state::<State>();+ let inner = state.inner.lock().unwrap();+ inner+ .lease+ .as_ref()+ .filter(|lease| lease.wayland && wayland_blocks_mapping(lease.phase))+ .map(|lease| (lease.generation, lease.phase == Phase::Stopping))+ };+ if let Some((generation, during_stop)) = blocked {+ remember_wayland_window(&app, generation, window, during_stop);+ // GTK's map default handler sends an empty Wayland commit with updates frozen+ // until initial configure. This synchronous handler unmaps before that dispatch.+ window.hide();+ }+ });+}++#[cfg(target_os = "linux")]+fn install_wayland_window_guard(app: &AppHandle) -> Result<(), String> {+ use gtk::prelude::*;+ let application = wayland_application(app)?;+ let installed = WAYLAND_GUARD_APPLICATION+ .with_borrow(|saved| saved.as_ref().and_then(gtk::glib::WeakRef::upgrade));+ if let Some(installed) = installed {+ if installed != application {+ return Err("Recording GTK application identity changed".into());+ }+ return Ok(());+ }+ let handle = app.clone();+ application.connect_window_added(move |_, window| guard_wayland_window(&handle, window));+ for window in application.windows() {+ guard_wayland_window(app, &window);+ }+ WAYLAND_GUARD_APPLICATION.with_borrow_mut(|saved| *saved = Some(application.downgrade()));+ Ok(())+}++#[cfg(target_os = "linux")]+fn remember_wayland_windows(app: &AppHandle, generation: u32) -> Result<(), String> {+ use gtk::prelude::*;+ for window in wayland_application(app)?.windows() {+ remember_wayland_window(app, generation, &window, false);+ }+ Ok(())+}++#[cfg(target_os = "linux")]+fn hide_wayland_windows(app: &AppHandle, generation: u32) -> Result<(), String> {+ use gtk::prelude::*;+ remember_wayland_windows(app, generation)?;+ for window in wayland_application(app)?.windows() {+ window.hide();+ if window.is_visible() || window.is_mapped() {+ return Err("GTK could not hide a Cap window".into());+ }+ }+ Ok(())+}++#[cfg(target_os = "linux")]+pub(crate) fn admit_wayland_window_creation(app: &AppHandle) -> Result<(), String> {+ let state = app.state::<State>();+ let inner = state.inner.lock().unwrap();+ if inner.lease.as_ref().is_some_and(|lease| {+ lease.wayland && wayland_blocks_mapping(lease.phase) && lease.phase != Phase::Stopping+ }) {+ return Err("Pause or stop recording before opening another Cap window".into());+ }+ Ok(())+}++#[cfg(target_os = "linux")]+fn wayland_restore_plan(+ app: &AppHandle,+ generation: u32,+ require_inputs: bool,+) -> Result<Vec<(RetainedWaylandWindow, bool)>, String> {+ use gtk::prelude::*;+ let saved_main = {+ let state = app.state::<State>();+ let inner = state.inner.lock().unwrap();+ let lease = inner+ .lease+ .as_ref()+ .filter(|lease| lease.generation == generation && lease.phase == Phase::Restoring)+ .ok_or("Wayland restoration was superseded")?;+ lease+ .windows+ .iter()+ .find(|window| window.label == CapWindowId::Main.label())+ .cloned()+ };+ let requested = if require_inputs {+ Some(+ app.state::<crate::RequestedInputsState>()+ .ready_snapshot()?,+ )+ } else {+ None+ };+ let retained = WAYLAND_CAPTURE_WINDOWS+ .with_borrow(|windows| windows.get(&generation).cloned())+ .ok_or("Retained Wayland windows disappeared")?;+ let application = WAYLAND_GUARD_APPLICATION+ .with_borrow(|saved| saved.as_ref().and_then(gtk::glib::WeakRef::upgrade))+ .ok_or("Retained GTK application disappeared")?;+ let current = application.windows();+ let mut result = Vec::new();+ for mut saved in retained {+ let label = wayland_window_label(app, &saved.window);+ let label_changed = saved.label.is_some() && saved.label != label;+ if saved.label.is_none() {+ saved.label = label;+ }+ let camera = saved+ .label+ .as_deref()+ .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Camera)));+ let editor = saved+ .label+ .as_deref()+ .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Editor { .. })));+ let mut wanted = (saved.visible || (editor && saved.requested_during_stop))+ && restore_floating_window(saved.label.as_deref())+ && (!camera+ || requested+ .as_ref()+ .is_some_and(|snapshot| snapshot.camera.value.is_some()));+ if saved.label.as_deref() == Some("main") {+ wanted = saved_main.as_ref().is_some_and(|saved| saved.visible);+ }+ if wanted && label_changed {+ return Err("A retained Cap window changed identity".into());+ }+ if wanted && !current.contains(&saved.window) {+ return Err("A retained Cap window disappeared before restoration".into());+ }+ result.push((saved, wanted));+ }+ if requested.as_ref().is_some_and(|requested| {+ !app.state::<crate::RequestedInputsState>()+ .is_current(requested)+ }) {+ return Err("Requested inputs changed during Wayland restoration".into());+ }+ Ok(result)+}++#[cfg(target_os = "linux")]+fn restore_wayland_windows(+ app: &AppHandle,+ generation: u32,+ main_only: bool,+) -> Result<(), String> {+ use gtk::prelude::*;+ for (saved, wanted) in wayland_restore_plan(app, generation, !main_only)? {+ if (saved.label.as_deref() == Some("main")) != main_only {+ continue;+ }+ if wanted {+ saved.window.show();+ if saved.requested_during_stop+ && saved+ .label+ .as_deref()+ .is_some_and(|label| matches!(label.parse(), Ok(CapWindowId::Editor { .. })))+ {+ saved.window.present();+ }+ } else {+ saved.window.hide();+ }+ if saved.window.is_visible() != wanted || (!wanted && saved.window.is_mapped()) {+ return Err("GTK did not acknowledge Cap window restoration".into());+ }+ }+ Ok(())+}diff --git a/apps/desktop/src-tauri/src/deeplink_actions.rs b/apps/desktop/src-tauri/src/deeplink_actions.rsindex 6eb7f4c89..7be4674e3 100644--- a/apps/desktop/src-tauri/src/deeplink_actions.rs+++ b/apps/desktop/src-tauri/src/deeplink_actions.rs@@ -195,7 +195,7 @@ impl DeepLinkAction {let state = app.state::<ArcLock<App>>();crate::set_camera_input(app.clone(), state.clone(), camera, None).await?;- crate::set_mic_input(state.clone(), mic_label).await?;+ crate::set_mic_input(app.clone(), state.clone(), mic_label).await?;let capture_target: ScreenCaptureTarget = match capture_mode {CaptureMode::Screen(name) => cap_recording::screen_capture::list_displays()diff --git a/apps/desktop/src-tauri/src/gpui_app.rs b/apps/desktop/src-tauri/src/gpui_app.rsindex 091479497..954427234 100644--- a/apps/desktop/src-tauri/src/gpui_app.rs+++ b/apps/desktop/src-tauri/src/gpui_app.rs@@ -607,9 +607,18 @@ fn activate_instance(pid: u32) {}}-#[cfg(not(any(target_os = "macos", windows)))]+#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]fn activate_instance(_pid: u32) {}+#[cfg(any(target_os = "linux", test))]+fn launch_linux_activation(+ path: Option<&std::path::Path>,+ launch: impl FnOnce(&std::path::Path, &[String]) -> Result<(), String>,+) -> Result<(), String> {+ let path = path.ok_or_else(|| "Cap GPUI isn't included in this build".to_string())?;+ launch(path, &[])+}+fn write_handoff_marker() {let path = handoff_marker();if let Some(parent) = path.parent() {@@ -717,8 +726,16 @@ pub async fn switch_to_gpui_app(match running_instance_pid() {Some(pid) => {- info!(pid, "Cap GPUI is already running; bringing it forward");+ #[cfg(target_os = "linux")]+ if let Err(error) = launch_linux_activation(Some(&path), spawn_detached) {+ if !own_store_is_shared(&app) {+ write_shared_store_flag(false);+ }+ return Err(error);+ }+ #[cfg(not(target_os = "linux"))]activate_instance(pid);+ info!(pid, "Cap GPUI is already running; requested its controls");}None => {write_handoff_marker();@@ -740,9 +757,9 @@ pub async fn switch_to_gpui_app(/// Whether this app should hand over to `cap-gpui` instead of starting.////// `true` means the caller must exit before any window is created.-pub fn redirect_at_startup_if_enabled(app: &AppHandle) -> bool {+pub fn redirect_at_startup_if_enabled(app: &AppHandle) -> Result<bool, String> {let update_handoff = handle_update_handoff(app);- let redirect = !update_handoff && redirect_decision(app);+ let redirect = !update_handoff && redirect_decision(app)?;if !redirect {// Staying up IS the readiness signal the waiting `cap-gpui` needs --// and the wait can begin while this app is ALREADY running (switching@@ -757,10 +774,10 @@ pub fn redirect_at_startup_if_enabled(app: &AppHandle) -> bool {}});}- redirect+ Ok(redirect)}-fn redirect_decision(app: &AppHandle) -> bool {+fn redirect_decision(app: &AppHandle) -> Result<bool, String> {let own = GeneralSettingsStore::get(app).ok().flatten()@@ -784,20 +801,23 @@ fn redirect_decision(app: &AppHandle) -> bool {warn!(%error, "could not reconcile the Cap GPUI setting");}}- return false;+ return Ok(false);}// The marker exists throughout a live session. Check the process first so// reopening Cap does not mistake a running native app for a crashed one.if let Some(pid) = running_instance_pid() {- info!(pid, "Cap GPUI is already running; handing over to it");#[cfg(any(target_os = "macos", windows))]{let args = std::env::args().skip(1).collect::<Vec<_>>();forward_deep_links_to_gpui(pid, &args);}+ #[cfg(target_os = "linux")]+ launch_linux_activation(binary_path(app).as_deref(), spawn_detached)?;+ #[cfg(not(target_os = "linux"))]activate_instance(pid);- return true;+ info!(pid, "Cap GPUI is already running; requested its controls");+ return Ok(true);}let marker = handoff_marker();@@ -817,12 +837,12 @@ fn redirect_decision(app: &AppHandle) -> bool {"The native Cap app exited unexpectedly last time, so the classic app has been restored.",).show(|_| {});- return false;+ return Ok(false);}let Some(path) = binary_path(app) else {warn!("Cap GPUI is enabled but its binary was not found; starting this app instead");- return false;+ return Ok(false);};write_handoff_marker();@@ -837,9 +857,9 @@ fn redirect_decision(app: &AppHandle) -> bool {if let Err(error) = spawn_detached(&path, &args) {warn!("{error}");let _ = std::fs::remove_file(handoff_marker());- return false;+ return Ok(false);}- true+ Ok(true)}#[cfg(test)]@@ -850,6 +870,40 @@ mod tests {is_gpui_process_image, parse_gpui_forwarding_endpoint, parse_update_handoff,};+ #[test]+ fn linux_activation_launches_the_resolved_binary_once_without_arguments() {+ let path = std::path::Path::new("/opt/cap/cap-gpui");+ let mut launches = 0;+ super::launch_linux_activation(Some(path), |selected, args| {+ launches += 1;+ assert_eq!(selected, path);+ assert!(args.is_empty());+ Ok(())+ })+ .unwrap();+ assert_eq!(launches, 1);+ }++ #[test]+ fn linux_activation_requires_a_resolved_binary_before_launch() {+ let result = super::launch_linux_activation(None, |_, _| {+ panic!("a missing GPUI binary must not be launched")+ });+ assert_eq!(result.unwrap_err(), "Cap GPUI isn't included in this build");+ }++ #[test]+ fn linux_activation_preserves_launch_failure() {+ let path = std::path::Path::new("/opt/cap/cap-gpui");+ let result = super::launch_linux_activation(Some(path), |_, _| {+ Err("Failed to launch Cap GPUI: permission denied".into())+ });+ assert_eq!(+ result.unwrap_err(),+ "Failed to launch Cap GPUI: permission denied"+ );+ }+#[test]fn startup_redirect_exits_once_when_no_open_event_arrives() {let state = StartupRedirectState::default();diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rsindex 2c9a6eed1..950394e62 100644--- a/apps/desktop/src-tauri/src/hotkeys.rs+++ b/apps/desktop/src-tauri/src/hotkeys.rs@@ -10,6 +10,7 @@ use global_hotkey::HotKeyState;use serde::{Deserialize, Serialize};use specta::Type;use std::collections::HashMap;+use std::future::Future;use std::sync::Mutex;use tauri::{AppHandle, Manager};use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};@@ -90,6 +91,49 @@ pub struct OnEscapePress;pub type HotkeysState = Mutex<HotkeysStore>;+fn clean_capture_shortcut() -> Shortcut {+ Shortcut::new(Some(Modifiers::CONTROL | Modifiers::SHIFT), Code::F9)+}++fn existing_clean_capture_stop(store: &HotkeysStore) -> Result<bool, String> {+ let shortcut = clean_capture_shortcut();+ let mut existing_stop = false;+ for (action, hotkey) in &store.hotkeys {+ if Shortcut::from(*hotkey) == shortcut {+ if !matches!(action, HotkeyAction::StopRecording) {+ return Err("Ctrl+Shift+F9 is assigned to another Cap action. Change that shortcut before starting clean Studio capture.".into());+ }+ existing_stop = true;+ }+ }+ Ok(existing_stop)+}++pub(crate) fn reserve_clean_capture_stop(app: &AppHandle) -> Result<bool, String> {+ let shortcut = clean_capture_shortcut();+ let state = app.state::<HotkeysState>();+ let store = state.lock().unwrap();+ let existing_stop = existing_clean_capture_stop(&store)?;+ let shortcuts = app.global_shortcut();+ if shortcuts.is_registered(shortcut) {+ return if existing_stop {+ Ok(false)+ } else {+ Err("Ctrl+Shift+F9 is already reserved. Release it before starting clean Studio capture.".into())+ };+ }+ shortcuts.register(shortcut).map_err(|error| {+ format!("Cannot reserve Ctrl+Shift+F9 to stop recording: {error}. Change the conflicting system shortcut and try again.")+ })?;+ Ok(true)+}++pub(crate) fn release_clean_capture_stop(app: &AppHandle, owned: bool) {+ if owned && let Err(error) = app.global_shortcut().unregister(clean_capture_shortcut()) {+ tracing::warn!(%error, "Could not release temporary recording shortcut");+ }+}+const RECORDING_START_SAFETY_STORE_KEY: &str = "recording_start_safety";#[derive(Deserialize)]@@ -176,10 +220,26 @@ async fn start_recording_from_hotkey(Ok(())}+fn spawn_shortcut_task<F>(task: F)+where+ F: Future + Send + 'static,+ F::Output: Send + 'static,+{+ drop(tauri::async_runtime::spawn(task));+}+pub fn init(app: &AppHandle) {app.plugin(tauri_plugin_global_shortcut::Builder::new().with_handler(|app, shortcut, event| {+ if *shortcut == clean_capture_shortcut()+ && crate::clean_capture::handle_shortcut(+ app,+ event.state() == HotKeyState::Pressed,+ )+ {+ return;+ }if !matches!(event.state(), HotKeyState::Pressed) {return;}@@ -190,7 +250,7 @@ pub fn init(app: &AppHandle) {if shortcut.key == Code::Comma && shortcut.mods == Modifiers::META {let app = app.clone();- tokio::spawn(async move {+ spawn_shortcut_task(async move {let _ = ShowCapWindow::Settings { page: None }.show(&app).await;});}@@ -200,7 +260,7 @@ pub fn init(app: &AppHandle) {for (action, hotkey) in &store.hotkeys {if &Shortcut::from(*hotkey) == shortcut {- tokio::spawn(handle_hotkey(app.clone(), *action));+ spawn_shortcut_task(handle_hotkey(app.clone(), *action));}}})@@ -343,6 +403,9 @@ pub fn set_hotkey(app: AppHandle, action: HotkeyAction, hotkey: Option<Hotkey>)let global_shortcut = app.global_shortcut();let state = app.state::<HotkeysState>();let mut store = state.lock().unwrap();+ if crate::clean_capture::phase(&app).is_some() {+ return Err(());+ }let prev = store.hotkeys.get(&action).cloned();@@ -365,9 +428,314 @@ pub fn set_hotkey(app: AppHandle, action: HotkeyAction, hotkey: Option<Hotkey>)Ok(())}+#[cfg(target_os = "linux")]+pub(crate) struct WaylandStop {+ generation: u32,+ cancel: tokio::sync::watch::Sender<bool>,+ task: Option<tauri::async_runtime::JoinHandle<Result<(), String>>>,+ completed: Option<Result<(), String>>,+}++#[cfg(target_os = "linux")]+pub(crate) async fn reserve_wayland_stop(app: &AppHandle, generation: u32) -> Result<(), String> {+ let state = app.state::<crate::clean_capture::State>();+ let mut owned = state.portal_stop.lock().await;+ if owned.is_some() {+ return Err("Previous Wayland Stop session has not closed".into());+ }+ let (cancel, receiver) = tokio::sync::watch::channel(false);+ let handle = app.clone();+ let task = tauri::async_runtime::spawn(async move {+ if run_wayland_tray(&handle, generation, receiver.clone()).await? {+ Ok(())+ } else {+ run_wayland_stop(&handle, generation, receiver).await+ }+ });+ *owned = Some(WaylandStop {+ generation,+ cancel,+ task: Some(task),+ completed: None,+ });+ Ok(())+}++#[cfg(target_os = "linux")]+async fn run_wayland_stop(+ app: &AppHandle,+ generation: u32,+ mut cancel: tokio::sync::watch::Receiver<bool>,+) -> Result<(), String> {+ use ashpd::desktop::global_shortcuts::{GlobalShortcuts, NewShortcut};+ use futures::StreamExt;+ let portal = tokio::select! {+ _ = cancel.changed() => return Ok(()),+ result = GlobalShortcuts::new() => match result {+ Ok(portal) => portal,+ Err(error) => { report_wayland_stop_loss(app, generation, &error.to_string()); return Ok(()); }+ },+ };+ if *cancel.borrow() {+ return Ok(());+ }+ // Keep session creation owned even if Stop arrives while the portal replies;+ // dropping CreateSession could lose the only handle needed to close it.+ let session = match portal.create_session().await {+ Ok(session) => session,+ Err(error) => {+ report_wayland_stop_loss(app, generation, &error.to_string());+ return Ok(());+ }+ };+ let result = async {+ let session_path = serde_json::to_value(&session).map_err(|error| error.to_string())?;+ let session_path = session_path+ .as_str()+ .ok_or("Invalid Stop session identity")?;+ let id = format!("cap-clean-stop-{generation}");+ let mut activated = portal+ .receive_activated()+ .await+ .map_err(|error| error.to_string())?;+ let mut deactivated = portal+ .receive_deactivated()+ .await+ .map_err(|error| error.to_string())?;+ let mut closed = session+ .receive_closed()+ .await+ .map_err(|error| error.to_string())?;+ let bound = portal+ .bind_shortcuts(+ &session,+ &[NewShortcut::new(&id, "Start or stop Cap clean recording")+ .preferred_trigger(Some("CTRL+SHIFT+F9"))],+ None,+ )+ .await+ .map_err(|error| error.to_string())?+ .response()+ .map_err(|error| error.to_string())?;+ let shortcut = bound+ .shortcuts()+ .iter()+ .find(|shortcut| shortcut.id() == id)+ .ok_or("Stop shortcut was not granted")?;+ crate::clean_capture::describe_wayland_stop(+ app,+ generation,+ format!("{} (desktop shortcut)", shortcut.trigger_description()),+ );+ loop {+ tokio::select! {+ event = activated.next() => match event {+ Some(event) if event.session_handle().as_str() == session_path && event.shortcut_id() == id => {+ crate::clean_capture::handle_wayland_stop(app, generation, crate::clean_capture::StopRoute::Portal, true);+ }+ Some(_) => {}+ None => return Err("Stop shortcut event stream closed".into()),+ },+ event = deactivated.next() => match event {+ Some(event) if event.session_handle().as_str() == session_path && event.shortcut_id() == id => {+ crate::clean_capture::handle_wayland_stop(app, generation, crate::clean_capture::StopRoute::Portal, false);+ }+ Some(_) => {}+ None => return Err("Stop shortcut event stream closed".into()),+ },+ _ = closed.next() => return Err("Stop shortcut session was revoked".into()),+ }+ }+ };+ let result: Result<(), String> = if *cancel.borrow() {+ Ok(())+ } else {+ tokio::select! {+ _ = cancel.changed() => Ok(()),+ result = result => result,+ }+ };+ if let Err(error) = &result {+ report_wayland_stop_loss(app, generation, error);+ }+ tokio::time::timeout(std::time::Duration::from_secs(2), session.close())+ .await+ .map_err(|_| "Stop session close timed out".to_string())?+ .map_err(|error| error.to_string())?;+ Ok(())+}++#[cfg(target_os = "linux")]+fn report_wayland_stop_loss(app: &AppHandle, generation: u32, error: &str) {+ crate::clean_capture::wayland_stop_lost(+ app,+ generation,+ crate::clean_capture::StopRoute::Portal,+ error.to_string(),+ );+}++#[cfg(target_os = "linux")]+pub(crate) async fn release_wayland_stop(app: &AppHandle, generation: u32) -> Result<(), String> {+ let state = app.state::<crate::clean_capture::State>();+ let mut owned = state.portal_stop.lock().await;+ let Some(stop) = owned.as_mut().filter(|stop| stop.generation == generation) else {+ return Ok(());+ };+ if let Some(result) = &stop.completed {+ return result.clone();+ }+ let _ = stop.cancel.send(true);+ let task = stop+ .task+ .as_mut()+ .ok_or("Stop session worker ownership was lost")?;+ let joined = tokio::time::timeout(std::time::Duration::from_secs(3), task)+ .await+ .map_err(|_| "Stop session worker has not joined".to_string())?;+ let _finished = stop.task.take();+ let result = joined+ .map_err(|error| error.to_string())+ .and_then(|result| result);+ stop.completed = Some(result.clone());+ if result.is_ok() {+ let _released = owned.take();+ }+ result+}++#[cfg(target_os = "linux")]+async fn run_wayland_tray(+ app: &AppHandle,+ generation: u32,+ mut cancel: tokio::sync::watch::Receiver<bool>,+) -> Result<bool, String> {+ use cap_utils::linux_recording_stop::{StopTray, StopTrayEvent};+ let icon = match crate::tray::clean_stop_icon() {+ Ok(icon) => icon,+ Err(error) => {+ crate::clean_capture::wayland_stop_lost(+ app,+ generation,+ crate::clean_capture::StopRoute::Tray,+ error,+ );+ return Ok(false);+ }+ };+ let tray = match StopTray::open(u64::from(generation), icon).await {+ Ok(tray) => tray,+ Err(error) => {+ let can_fallback = error.can_fallback();+ let message = error.to_string();+ crate::clean_capture::wayland_stop_lost(+ app,+ generation,+ crate::clean_capture::StopRoute::Tray,+ message.clone(),+ );+ if !can_fallback {+ crate::clean_capture::wayland_stop_lost(+ app,+ generation,+ crate::clean_capture::StopRoute::Portal,+ message.clone(),+ );+ return Err(message);+ }+ return Ok(false);+ }+ };+ let events = tray.events();+ let mut used = false;+ let mut cancelled = false;+ loop {+ tokio::select! {+ _ = cancel.changed() => { cancelled = true; break; },+ event = events.recv_async() => match event {+ Ok(StopTrayEvent::Activated { generation: received }) if received == u64::from(generation) => {+ used = true;+ crate::clean_capture::handle_wayland_stop(app, generation, crate::clean_capture::StopRoute::Tray, true);+ crate::clean_capture::handle_wayland_stop(app, generation, crate::clean_capture::StopRoute::Tray, false);+ }+ Ok(StopTrayEvent::Unavailable { generation: received }) if received == u64::from(generation) => {+ crate::clean_capture::wayland_stop_lost(app, generation, crate::clean_capture::StopRoute::Tray, "The Stop tray host is unavailable".into());+ break;+ }+ Ok(_) => {}+ Err(_) => {+ crate::clean_capture::wayland_stop_lost(app, generation, crate::clean_capture::StopRoute::Tray, "The Stop tray event stream closed".into());+ break;+ }+ }+ }+ }+ tray.close().await?;+ Ok(used || cancelled)+}+#[cfg(test)]mod tests {- use super::should_confirm_without_microphone;+ use super::{should_confirm_without_microphone, spawn_shortcut_task};+ use std::time::Duration;++ #[test]+ fn clean_capture_reuses_only_an_existing_stop_binding() {+ let hotkey = super::Hotkey {+ code: super::Code::F9,+ meta: false,+ ctrl: true,+ alt: false,+ shift: true,+ };+ let mut store = super::HotkeysStore::default();+ assert!(!super::existing_clean_capture_stop(&store).unwrap());+ store+ .hotkeys+ .insert(super::HotkeyAction::StopRecording, hotkey);+ assert!(super::existing_clean_capture_stop(&store).unwrap());+ store+ .hotkeys+ .insert(super::HotkeyAction::StartStudioRecording, hotkey);+ assert!(super::existing_clean_capture_stop(&store).is_err());+ }++ #[test]+ fn shortcut_dispatch_runs_from_thread_without_tokio_runtime() {+ let (sent, received) = std::sync::mpsc::channel();+ let caller = std::thread::spawn(move || {+ assert!(tokio::runtime::Handle::try_current().is_err());+ let caller_id = std::thread::current().id();+ spawn_shortcut_task(async move {+ assert!(tokio::runtime::Handle::try_current().is_ok());+ tokio::time::sleep(Duration::from_millis(1)).await;+ sent.send((caller_id, std::thread::current().id())).unwrap();+ Ok::<(), String>(())+ });+ });+ caller.join().expect("OS callback thread must not panic");+ let (caller_id, task_id) = received+ .recv_timeout(Duration::from_secs(2))+ .expect("Shortcut action must run on the application runtime");+ assert_ne!(caller_id, task_id);+ }++ #[test]+ fn shortcut_dispatch_keeps_detached_settings_task_alive() {+ let (sent, received) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ assert!(tokio::runtime::Handle::try_current().is_err());+ spawn_shortcut_task(async move {+ tokio::time::sleep(Duration::from_millis(1)).await;+ sent.send(()).unwrap();+ });+ })+ .join()+ .expect("OS callback thread must not panic");+ received+ .recv_timeout(Duration::from_secs(2))+ .expect("Detached settings task must complete");+ }#[test]fn confirms_when_enabled_without_microphone() {diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex e5292a355..1adcdde86 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -11,6 +11,7 @@ mod camera_legacy;#[cfg(target_os = "macos")]mod camera_native;mod captions;+mod clean_capture;mod cli;mod clip_thumbnails;mod crash_sentinel;@@ -27,6 +28,7 @@ mod gpui_app;mod hotkeys;mod http_client;mod import;+pub mod linux_instant_camera;mod logging;mod notifications;mod panel_manager;@@ -196,6 +198,38 @@ fn scaled_editor_preview_dimension(mod tests {use super::*;+ #[test]+ fn tauri_event_loop_runs_once_on_its_calling_thread() {+ let thread = std::thread::current().id();+ let calls = std::cell::Cell::new(0);+ let result = run_tauri_event_loop(|| {+ assert_eq!(std::thread::current().id(), thread);+ calls.set(calls.get() + 1);+ 42+ });+ assert_eq!(calls.get(), 1);+ assert_eq!(result, 42);+ }++ #[cfg(target_os = "linux")]+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn linux_tauri_event_loop_allows_blocking_plugin_setup_and_shutdown() {+ let thread = std::thread::current().id();+ run_tauri_event_loop(|| {+ assert_eq!(std::thread::current().id(), thread);+ let plugin_runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(1)+ .enable_all()+ .build()+ .unwrap();+ assert_eq!(plugin_runtime.block_on(async { 1 }), 1);+ let callback = tokio::spawn(async { 2 });+ assert_eq!(plugin_runtime.block_on(callback).unwrap(), 2);+ assert_eq!(plugin_runtime.block_on(async { 3 }), 3);+ });+ assert_eq!(tokio::spawn(async { 4 }).await.unwrap(), 4);+ }+#[test]fn default_editor_preview_resolution_matches_frontend_defaults() {assert_eq!(default_editor_preview_resolution(), XY::new(1248, 702));@@ -735,11 +769,203 @@ pub enum RecordingState {Active(InProgressRecording),}+#[derive(Clone)]+pub(crate) struct RequestedInput<T> {+ value: Option<T>,+ revision: u64,+ pending: bool,+ error: Option<String>,+}++impl<T: Clone> RequestedInput<T> {+ fn new(value: Option<T>) -> Self {+ Self {+ value,+ revision: 0,+ pending: false,+ error: None,+ }+ }++ fn begin(&mut self, value: Option<T>) -> u64 {+ self.value = value;+ self.revision = self.revision.wrapping_add(1);+ self.pending = true;+ self.error = None;+ self.revision+ }++ fn finish(&mut self, revision: u64, result: &Result<(), String>) {+ if self.revision == revision {+ self.pending = false;+ self.error = result.as_ref().err().cloned();+ }+ }++ fn prepare_restore(&mut self, revision: u64) -> bool {+ if self.revision != revision || self.pending {+ return false;+ }+ self.pending = true;+ self.error = None;+ true+ }++ fn validate(&self, kind: &str) -> Result<(), String> {+ if self.pending {+ return Err(format!(+ "The requested {kind} is still being configured. Wait before recording."+ ));+ }+ if let Some(error) = &self.error {+ return Err(format!(+ "The requested {kind} could not be configured: {error}. Select it again or choose another input before recording."+ ));+ }+ Ok(())+ }+}++#[derive(Clone)]+pub(crate) struct RequestedInputs {+ microphone: RequestedInput<String>,+ camera: RequestedInput<DeviceOrModelID>,+}++pub(crate) struct RequestedInputsState {+ inner: Arc<std::sync::Mutex<RequestedInputs>>,+ operation: Mutex<()>,+}++impl RequestedInputsState {+ fn new(microphone: Option<String>, camera: Option<DeviceOrModelID>) -> Self {+ Self {+ inner: Arc::new(std::sync::Mutex::new(RequestedInputs {+ microphone: RequestedInput::new(microphone),+ camera: RequestedInput::new(camera),+ })),+ operation: Mutex::new(()),+ }+ }++ pub(crate) fn snapshot(&self) -> RequestedInputs {+ self.inner.lock().unwrap().clone()+ }++ pub(crate) fn ready_snapshot(&self) -> Result<RequestedInputs, String> {+ let snapshot = self.snapshot();+ snapshot.microphone.validate("microphone")?;+ snapshot.camera.validate("camera")?;+ Ok(snapshot)+ }++ pub(crate) fn ensure_ready_for_resume(&self) -> Result<(), String> {+ self.ready_snapshot().map(|_| ()).map_err(|error| {+ format!("Cannot resume recording: {error} Finish configuring or reselect the requested inputs before resuming.")+ })+ }++ pub(crate) fn try_resume_guard(&self) -> Result<tokio::sync::MutexGuard<'_, ()>, String> {+ let guard = self.operation.try_lock().map_err(|_| {+ "Input change in progress. Finish configuring or reselect the requested inputs before resuming.".to_string()+ })?;+ self.ensure_ready_for_resume()?;+ Ok(guard)+ }++ pub(crate) fn is_current(&self, snapshot: &RequestedInputs) -> bool {+ let current = self.inner.lock().unwrap();+ current.microphone.revision == snapshot.microphone.revision+ && current.camera.revision == snapshot.camera.revision+ }++ fn mic_is_current(&self, revision: u64) -> bool {+ self.inner.lock().unwrap().microphone.revision == revision+ }++ fn camera_is_current(&self, revision: u64) -> bool {+ self.inner.lock().unwrap().camera.revision == revision+ }++ fn publish_mic_if_current(&self, revision: u64, publish: impl FnOnce()) -> bool {+ let current = self.inner.lock().unwrap();+ if current.microphone.revision != revision {+ return false;+ }+ publish();+ true+ }++ pub(crate) fn publish_camera_if_current(&self, revision: u64, publish: impl FnOnce()) -> bool {+ let current = self.inner.lock().unwrap();+ if current.camera.revision != revision {+ return false;+ }+ publish();+ true+ }++ pub(crate) fn publish_if_current(+ &self,+ snapshot: &RequestedInputs,+ publish: impl FnOnce(),+ ) -> bool {+ let current = self.inner.lock().unwrap();+ if current.microphone.revision != snapshot.microphone.revision+ || current.camera.revision != snapshot.camera.revision+ {+ return false;+ }+ publish();+ true+ }+}++#[derive(Default)]+struct AppliedMicrophoneInput {+ valid: bool,+ generation: u64,+}++impl AppliedMicrophoneInput {+ fn prepare_change(+ &mut self,+ active: bool,+ requested: Option<&str>,+ selected: Option<&str>,+ ) -> bool {+ if active && self.valid && requested.is_some() && requested == selected {+ return false;+ }+ self.invalidate();+ true+ }++ fn invalidate(&mut self) {+ self.valid = false;+ self.generation = self.generation.wrapping_add(1);+ }++ fn confirm_if_current(&mut self, generation: u64) -> bool {+ if self.generation != generation {+ return false;+ }+ self.confirm();+ true+ }++ fn confirm(&mut self) {+ self.valid = true;+ }+}+pub struct App {#[deprecated = "can be removed when native camera preview is ready"]camera_ws_port: u16,#[deprecated = "can be removed when native camera preview is ready"]camera_ws_sender: flume::Sender<cap_recording::FFmpegVideoFrame>,+ #[cfg(target_os = "linux")]+ pub camera_processing: linux_instant_camera::ProcessingFactory,camera_preview: CameraPreviewManager,camera_preview_state_tx: tokio::sync::watch::Sender<CameraPreviewState>,handle: AppHandle,@@ -748,6 +974,7 @@ pub struct App {mic_feed: ActorRef<feeds::microphone::MicrophoneFeed>,mic_meter_sender: flume::Sender<microphone::MicrophoneSamples>,selected_mic_label: Option<String>,+ applied_mic_input: AppliedMicrophoneInput,selected_camera_id: Option<DeviceOrModelID>,camera_in_use: bool,camera_cleanup_done: bool,@@ -884,6 +1111,12 @@ impl App {mode: RecordingMode,target: ScreenCaptureTarget,) -> Result<(), String> {+ #[cfg(target_os = "linux")]+ if mode != RecordingMode::Instant+ && recording::linux_instant::current(&self.handle).is_some()+ {+ return Err("Finish the pending Instant cleanup before recording".into());+ }if !matches!(self.recording_state, RecordingState::None) {return Err("Recording already in progress".to_string());}@@ -900,6 +1133,10 @@ impl App {}pub fn clear_pending_recording(&mut self) -> bool {+ #[cfg(target_os = "linux")]+ if recording::linux_instant::blocks_cleanup(&self.handle) {+ return false;+ }if !matches!(self.recording_state, RecordingState::Pending { .. }) {return false;}@@ -917,6 +1154,10 @@ impl App {}pub fn clear_current_recording(&mut self) -> Option<InProgressRecording> {+ #[cfg(target_os = "linux")]+ if recording::linux_instant::blocks_cleanup(&self.handle) {+ return None;+ }let previous = std::mem::replace(&mut self.recording_state, RecordingState::None);match previous {RecordingState::Active(recording) => {@@ -932,6 +1173,10 @@ impl App {}pub fn clear_recording_state(&mut self) -> Option<InProgressRecording> {+ #[cfg(target_os = "linux")]+ if recording::linux_instant::blocks_cleanup(&self.handle) {+ return None;+ }let previous = std::mem::replace(&mut self.recording_state, RecordingState::None);self.close_occluder_windows();crate::windows::apply_content_protection(&self.handle, false);@@ -964,6 +1209,7 @@ impl App {}async fn restart_mic_feed(&mut self) -> Result<(), String> {+ self.applied_mic_input.invalidate();info!("Restarting microphone feed after actor shutdown");let (error_tx, error_rx) = flume::bounded(1);@@ -1042,9 +1288,13 @@ impl App {pub fn is_recording_active_or_pending(&self) -> bool {!matches!(self.recording_state, RecordingState::None)+ || clean_capture::blocks_idle_cleanup(&self.handle)}async fn handle_input_disconnect(&mut self, kind: RecordingInputKind) -> Result<(), String> {+ if matches!(kind, RecordingInputKind::Microphone) {+ self.applied_mic_input.invalidate();+ }if !self.disconnected_inputs.insert(kind) {return Ok(());}@@ -1105,6 +1355,7 @@ impl App {}async fn ensure_selected_mic_ready(&mut self) -> Result<(), String> {+ self.applied_mic_input.invalidate();self.ensure_mic_feed_alive().await?;if let Some(label) = self.selected_mic_label.clone() {@@ -1142,123 +1393,315 @@ impl App {#[tauri::command]#[specta::specta]-#[instrument(skip(state))]-async fn set_mic_input(state: MutableState<'_, App>, label: Option<String>) -> Result<(), String> {- let desired_label = label;+#[instrument(skip(app_handle, state))]+async fn set_mic_input(+ app_handle: AppHandle,+ state: MutableState<'_, App>,+ label: Option<String>,+) -> Result<(), String> {+ let requested = app_handle.state::<RequestedInputsState>();+ let revision = requested+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(label.clone());+ let _operation = requested.operation.lock().await;+ if !requested.mic_is_current(revision) {+ return Err("Microphone selection was superseded by a newer request".into());+ }+ let result = apply_mic_input(&app_handle, state, label, revision).await;+ requested+ .inner+ .lock()+ .unwrap()+ .microphone+ .finish(revision, &result);+ result+}++async fn finish_microphone_input_change(+ change: impl std::future::Future<Output = Result<(), String>>,+ is_current: impl FnOnce() -> bool,+ attach: impl std::future::Future<Output = Result<(), String>>,+) -> Result<(), String> {+ change.await?;+ if !is_current() {+ return Err("Microphone selection was superseded by a newer request".into());+ }+ attach.await+}++const MICROPHONE_UNLOCK_TIMEOUT: Duration = Duration::from_millis(500);+const MICROPHONE_UNLOCK_RETRY: Duration = Duration::from_millis(50);+const MICROPHONE_CHANGE_TIMEOUT: Duration = Duration::from_millis(1500);++enum MicrophoneRemovalError {+ Locked,+ Failed(String),+}++async fn wait_for_microphone_removal<F>(mut remove: impl FnMut() -> F) -> Result<(), String>+where+ F: std::future::Future<Output = Result<(), MicrophoneRemovalError>>,+{+ let deadline = tokio::time::Instant::now() + MICROPHONE_UNLOCK_TIMEOUT;+ loop {+ if tokio::time::Instant::now() >= deadline {+ return Err("The microphone is still in use. Stop recording and try again.".into());+ }+ match tokio::time::timeout_at(deadline, remove()).await {+ Ok(Ok(())) => return Ok(()),+ Ok(Err(MicrophoneRemovalError::Failed(error))) => return Err(error),+ Ok(Err(MicrophoneRemovalError::Locked)) => {}+ Err(_) => {+ return Err(+ "Timed out waiting for the microphone to close. Stop recording and try again."+ .into(),+ );+ }+ }+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());+ if remaining.is_zero() {+ return Err("The microphone is still in use. Stop recording and try again.".into());+ }+ tokio::time::sleep(remaining.min(MICROPHONE_UNLOCK_RETRY)).await;+ }+}- let (mic_feed, studio_handle, previous_label, app_handle) = {+async fn remove_microphone_input(feed: &ActorRef<MicrophoneFeed>) -> Result<(), String> {+ wait_for_microphone_removal(|| async {+ match feed.ask(microphone::RemoveInput).await {+ Ok(()) => Ok(()),+ Err(kameo::error::SendError::HandlerError(microphone::FeedLockedError)) => {+ Err(MicrophoneRemovalError::Locked)+ }+ Err(error) => Err(MicrophoneRemovalError::Failed(error.to_string())),+ }+ })+ .await+}++async fn acknowledge_studio_microphone(+ acknowledgement: impl std::future::Future<Output = Result<(), String>>,+ update_ownership: impl std::future::Future<Output = Result<(), String>>,+ action: &str,+) -> Result<(), String> {+ tokio::time::timeout(MICROPHONE_UNLOCK_TIMEOUT, acknowledgement)+ .await+ .map_err(|_| {+ format!("Timed out {action} the Studio microphone. Stop recording and try again.")+ })??;+ update_ownership.await+}++fn replace_owned_microphone<T>(+ owner: &std::path::Path,+ current: Option<(&std::path::Path, &mut Option<T>)>,+ replacement: Option<T>,+) -> Result<(), String> {+ let Some((current_owner, slot)) = current else {+ return Err("The Studio recording stopped while changing microphone input.".into());+ };+ if current_owner != owner {+ return Err("The Studio recording changed while changing microphone input.".into());+ }+ *slot = replacement;+ Ok(())+}++fn studio_microphone_owner_matches(app: &App, owner: &std::path::Path) -> bool {+ matches!(app.current_recording(), Some(InProgressRecording::Studio { common, .. })+ if common.recording_dir == owner)+}++fn replace_studio_microphone(+ app: &mut App,+ owner: &std::path::Path,+ replacement: Option<Arc<microphone::MicrophoneFeedLock>>,+) -> Result<(), String> {+ let current = match app.current_recording_mut() {+ Some(InProgressRecording::Studio {+ common, mic_feed, ..+ }) => Some((common.recording_dir.as_path(), mic_feed)),+ _ => None,+ };+ replace_owned_microphone(owner, current, replacement)+}++async fn apply_mic_input(+ app_handle: &AppHandle,+ state: MutableState<'_, App>,+ desired_label: Option<String>,+ revision: u64,+) -> Result<(), String> {+ let requested = app_handle.state::<RequestedInputsState>();++ let (mic_feed, studio_handle, app_handle, applied_generation) = {let mut app = state.write().await;+ if !requested.mic_is_current(revision) {+ return Err("Microphone selection was superseded by a newer request".into());+ }app.ensure_mic_feed_alive().await?;+ let selected_label = app.selected_mic_label.clone();+ let active = matches!(app.recording_state, RecordingState::Active(_));+ let needs_change = app.applied_mic_input.prepare_change(+ active,+ desired_label.as_deref(),+ selected_label.as_deref(),+ );- // A selected microphone that isn't connected is an expected state- // (e.g. undocked laptop), not an error: remember the selection so the- // device can be reclaimed when it reappears, and leave the feed empty.if let Some(label) = desired_label.as_ref()- && !matches!(app.recording_state, RecordingState::Active(_))- && find_mic_by_label_or_fuzzy(&MicrophoneFeed::list_names(), label).is_none()+ && !MicrophoneFeed::list_names().contains(label){- info!(- "Selected microphone '{label}' is not connected; keeping selection with no input"- );- app.selected_mic_label = desired_label.clone();- let mic_feed = app.mic_feed.clone();- drop(app);- // Best-effort: the feed may be locked by a recording that is still- // spinning up (Pending), in which case it must keep its input.- if let Err(err) = mic_feed.ask(microphone::RemoveInput).await {- warn!("Failed to release microphone input for absent device: {err}");- }- return Ok(());+ app.applied_mic_input.invalidate();+ return Err(format!(+ "Selected microphone '{label}' is no longer available. Reconnect it or choose another microphone."+ ));}-- if desired_label == app.selected_mic_label {- if desired_label.is_some() && !matches!(app.recording_state, RecordingState::Active(_))- {- app.ensure_selected_mic_ready().await?;- }+ if !needs_change {return Ok(());}let handle = match app.current_recording() {- Some(InProgressRecording::Studio { handle, .. }) => Some(handle.clone()),+ Some(InProgressRecording::Studio { handle, common, .. }) => {+ Some((handle.clone(), common.recording_dir.clone()))+ }_ => None,};- let previous_label = app.selected_mic_label.clone();- app.selected_mic_label = desired_label.clone();-(app.mic_feed.clone(),handle,- previous_label,app.handle.clone(),+ app.applied_mic_input.generation,)};- let has_studio = studio_handle.is_some();-- let apply_result = async {- if let Some(handle) = &studio_handle {- handle.set_mic_feed(None).await.map_err(|e| e.to_string())?;+ let change = async {+ if let Some((handle, owner)) = &studio_handle {+ acknowledge_studio_microphone(+ async {+ handle+ .set_mic_feed(None)+ .await+ .map_err(|error| error.to_string())+ },+ async {+ let mut app = state.write().await;+ replace_studio_microphone(&mut app, owner, None)+ },+ "detaching",+ )+ .await?;+ remove_microphone_input(&mic_feed).await?;}match desired_label.as_ref() {- None => {- let remove_result = mic_feed- .ask(microphone::RemoveInput)- .await- .map_err(|e| e.to_string());-- match remove_result {- Ok(()) => {}- Err(e) if has_studio && e.contains("FeedLocked") => {- info!("Microphone feed locked by recording, deselection applied at studio level");- }- Err(e) => return Err(e),- }- }+ None if studio_handle.is_none() => remove_microphone_input(&mic_feed).await?,+ None => {}Some(label) => {- let settings =- recording_settings::RecordingSettingsStore::microphone_settings_for(- &app_handle,- label,+ if let Some((_, owner)) = &studio_handle+ && !studio_microphone_owner_matches(&*state.read().await, owner)+ {+ return Err(+ "The Studio recording stopped while changing microphone input.".into(),);- mic_feed- .ask(feeds::microphone::SetInput {- label: label.clone(),- settings,- })- .await- .map_err(|e| e.to_string())?- .await- .map_err(|e| e.to_string())?;+ }+ let settings = recording_settings::RecordingSettingsStore::microphone_settings_for(+ &app_handle,+ label,+ );+ tokio::time::timeout(MICROPHONE_CHANGE_TIMEOUT, async {+ mic_feed+ .ask(feeds::microphone::SetInput {+ label: label.clone(),+ settings,+ })+ .await+ .map_err(|error| error.to_string())?+ .await+ .map_err(|error| error.to_string())+ })+ .await+ .map_err(|_| "Timed out configuring the requested microphone. Select it again before recording.".to_string())??;}}- if let Some(handle) = studio_handle- && desired_label.is_some()+ Ok(())+ };+ let attach = async {+ if let Some((handle, owner)) = &studio_handle+ && let Some(label) = desired_label.as_ref(){- let mic_lock = mic_feed- .ask(microphone::Lock)- .await- .map_err(|e| e.to_string())?;- handle- .set_mic_feed(Some(Arc::new(mic_lock)))- .await- .map_err(|e| e.to_string())?;+ let mic_lock =+ tokio::time::timeout(MICROPHONE_UNLOCK_TIMEOUT, mic_feed.ask(microphone::Lock))+ .await+ .map_err(|_| "Timed out locking the requested microphone.".to_string())?+ .map_err(|error| error.to_string())?;+ if mic_lock.device_name() != label {+ return Err(+ "Microphone input changed before Studio could attach it. Select it again."+ .into(),+ );+ }+ let mic_lock = Arc::new(mic_lock);+ acknowledge_studio_microphone(+ async {+ handle+ .set_mic_feed(Some(mic_lock.clone()))+ .await+ .map_err(|error| error.to_string())+ },+ async {+ let mut app = state.write().await;+ replace_studio_microphone(&mut app, owner, Some(mic_lock.clone()))+ },+ "attaching",+ )+ .await?;}- Ok::<(), String>(())+ Ok(())+ };+ let apply_result =+ finish_microphone_input_change(change, || requested.mic_is_current(revision), attach).await;++ if let Some((_, owner)) = &studio_handle+ && !studio_microphone_owner_matches(&*state.read().await, owner)+ {+ remove_microphone_input(&mic_feed).await?;+ return Err("The Studio recording stopped while changing microphone input.".into());}- .await;match apply_result {Ok(()) => {let mut app = state.write().await;- let cleared = app- .disconnected_inputs- .remove(&RecordingInputKind::Microphone);+ if let Some((_, owner)) = &studio_handle+ && !studio_microphone_owner_matches(&app, owner)+ {+ drop(app);+ remove_microphone_input(&mic_feed).await?;+ return Err("The Studio recording stopped while changing microphone input.".into());+ }+ let mut cleared = false;+ let mut confirmed = false;+ if !requested.publish_mic_if_current(revision, || {+ if !app.applied_mic_input.confirm_if_current(applied_generation) {+ return;+ }+ confirmed = true;+ app.selected_mic_label = desired_label;+ cleared = app+ .disconnected_inputs+ .remove(&RecordingInputKind::Microphone);+ }) {+ return Err("Microphone selection was superseded by a newer request".into());+ }+ if !confirmed {+ return Err("Microphone changed or disconnected during setup. Select it again before recording.".into());+ }if cleared {let _ = RecordingEvent::InputRestored {input: RecordingInputKind::Microphone,@@ -1268,13 +1711,7 @@ async fn set_mic_input(state: MutableState<'_, App>, label: Option<String>) -> ROk(())}- Err(err) => {- let mut app = state.write().await;- if app.selected_mic_label == desired_label {- app.selected_mic_label = previous_label;- }- Err(err)- }+ Err(err) => Err(err),}}@@ -1300,9 +1737,35 @@ async fn set_camera_input(id: Option<DeviceOrModelID>,skip_camera_window: Option<bool>,) -> Result<(), String> {+ let requested = app_handle.state::<RequestedInputsState>();+ let revision = requested.inner.lock().unwrap().camera.begin(id.clone());+ let _operation = requested.operation.lock().await;+ if !requested.camera_is_current(revision) {+ return Err("Camera selection was superseded by a newer request".into());+ }+ let result = apply_camera_input(&app_handle, state, id, skip_camera_window, revision).await;+ requested+ .inner+ .lock()+ .unwrap()+ .camera+ .finish(revision, &result);+ result+}++async fn apply_camera_input(+ app_handle: &AppHandle,+ state: MutableState<'_, App>,+ id: Option<DeviceOrModelID>,+ skip_camera_window: Option<bool>,+ revision: u64,+) -> Result<(), String> {+ let requested = app_handle.state::<RequestedInputsState>();let operation_lock = app_handle.state::<CameraWindowOperationLock>();let _operation_guard = operation_lock.lock().await;-+ if !requested.camera_is_current(revision) {+ return Err("Camera selection was superseded by a newer request".into());+ }let app = state.read().await;let camera_feed = app.camera_feed.clone();let studio_handle = match app.current_recording() {@@ -1311,22 +1774,20 @@ async fn set_camera_input(};let current_id = app.selected_camera_id.clone();let camera_in_use = app.camera_in_use;+ let recording_active = matches!(app.recording_state, RecordingState::Active(_));drop(app);let skip_camera_window = skip_camera_window.unwrap_or(false);let camera_window_is_visible = CapWindowId::Camera- .get(&app_handle)+ .get(app_handle).and_then(|window| window.is_visible().ok()).unwrap_or(false);- if id == current_id && camera_in_use && !skip_camera_window {+ if id == current_id && camera_in_use && recording_active && !skip_camera_window {let show_result = if camera_window_is_visible {Ok(())} else {- ShowCapWindow::Camera { centered: false }- .show(&app_handle)- .await- .map(|_| ())+ show_requested_camera_window(app_handle, revision).await};show_result@@ -1336,6 +1797,15 @@ async fn set_camera_input(return Ok(());}+ if let Some(id) = &id+ && !is_camera_available(id)+ {+ return Err(format!(+ "Selected camera '{}' is no longer available. Reconnect it or choose another camera.",+ recording::camera_id_label(id)+ ));+ }+if let Some(handle) = &studio_handle {handle.set_camera_feed(None)@@ -1343,51 +1813,11 @@ async fn set_camera_input(.map_err(|e| e.to_string())?;}- // A selected camera that isn't connected is an expected state (e.g. undocked- // laptop), not an error: tear down like a deselect but remember the selection- // so the device can be reclaimed when it reappears. Running the init/retry- // loop instead would flash the preview window and toast an error on every- // launch and picker-open while the device is away.- if let Some(id) = &id- && !is_camera_available(id)- {- info!(camera = ?id, "Selected camera is not connected; keeping selection with no input");- let shutdown_rx = {- let app = &mut *state.write().await;- app.camera_in_use = false;- app.selected_camera_id = Some(id.clone());- app.camera_cleanup_done = true;- if skip_camera_window {- app.camera_preview.begin_shutdown()- } else {- app.camera_preview.pause();- None- }- };-- // Best-effort: the feed may be locked by a recording that is still- // spinning up (Pending), in which case it must keep its input.- if let Err(err) = camera_feed.ask(feeds::camera::RemoveInput).await {- warn!("Failed to release camera input for absent device: {err}");- }-- if let Some(rx) = shutdown_rx {- let _ = tokio::time::timeout(Duration::from_millis(500), rx).await;- }-- if !skip_camera_window && let Some(window) = CapWindowId::Camera.get(&app_handle) {- let _ = window.hide();- }-- return Ok(());- }-match &id {None => {let shutdown_rx = {let app = &mut *state.write().await;app.camera_in_use = false;- app.selected_camera_id = None;app.camera_cleanup_done = true;if skip_camera_window {app.camera_preview.begin_shutdown()@@ -1406,20 +1836,19 @@ async fn set_camera_input(let _ = tokio::time::timeout(Duration::from_millis(500), rx).await;}- if !skip_camera_window && let Some(window) = CapWindowId::Camera.get(&app_handle) {+ if !skip_camera_window && let Some(window) = CapWindowId::Camera.get(app_handle) {let _ = window.hide();}}Some(id) => {- emit_camera_preview_clear(&app_handle);+ emit_camera_preview_clear(app_handle);let settings =- recording_settings::RecordingSettingsStore::camera_settings_for(&app_handle, id);+ recording_settings::RecordingSettingsStore::camera_settings_for(app_handle, id);let (camera_ws_sender, camera_preview_sender, use_ws_preview) = {let app = &mut *state.write().await;let use_ws_preview = !(camera_window_is_visible&& app.camera_preview.is_initialized()&& !app.camera_preview.is_paused());- app.selected_camera_id = Some(id.clone());app.camera_in_use = true;app.camera_cleanup_done = false;#[allow(deprecated)]@@ -1451,11 +1880,12 @@ async fn set_camera_input(.await.map_err(|e| e.to_string());+ if !requested.camera_is_current(revision) {+ return Err("Camera selection was superseded by a newer request".into());+ }if !showed_camera_window {showed_camera_window = true;- let show_result = ShowCapWindow::Camera { centered: false }- .show(&app_handle)- .await;+ let show_result = show_requested_camera_window(app_handle, revision).await;show_result.map_err(|err| error!("Failed to show camera preview window: {err}")).ok();@@ -1468,15 +1898,12 @@ async fn set_camera_input(match result {Ok(_) => {- emit_camera_preview_clear(&app_handle);+ emit_camera_preview_clear(app_handle);break Ok(());}Err(e) => {if attempts == 1 && !skip_camera_window {- emit_camera_preview_error(- &app_handle,- camera_preview_error_message(&e),- );+ emit_camera_preview_error(app_handle, camera_preview_error_message(&e));}if attempts >= 3 {break Err(format!(@@ -1492,6 +1919,9 @@ async fn set_camera_input(}};+ if !requested.camera_is_current(revision) {+ return Err("Camera selection was superseded by a newer request".into());+ }if let Err(e) = init_result {let message = camera_preview_error_message(&e);let _ = camera_feed.ask(feeds::camera::RemoveInput).await;@@ -1504,20 +1934,23 @@ async fn set_camera_input(let _ = RecordingEvent::InputLost {input: RecordingInputKind::Camera,}- .emit(&app_handle);+ .emit(app_handle);}- emit_camera_preview_error(&app_handle, message.clone());+ emit_camera_preview_error(app_handle, message.clone());let _ = NewNotification {title: "Camera unavailable".to_string(),body: message,is_error: true,}- .emit(&app_handle);- return Ok(());+ .emit(app_handle);+ return Err(e);}}}+ if !requested.camera_is_current(revision) {+ return Err("Camera selection was superseded by a newer request".into());+ }if let Some(handle) = studio_handle&& id.is_some(){@@ -1533,12 +1966,15 @@ async fn set_camera_input({let app = &mut *state.write().await;- app.selected_camera_id = id;- app.camera_in_use = app.selected_camera_id.is_some();- if app.camera_in_use {- app.camera_cleanup_done = false;+ let mut cleared = false;+ if !requested.publish_camera_if_current(revision, || {+ app.selected_camera_id = id;+ app.camera_in_use = app.selected_camera_id.is_some();+ app.camera_cleanup_done = !app.camera_in_use;+ cleared = app.disconnected_inputs.remove(&RecordingInputKind::Camera);+ }) {+ return Err("Camera selection was superseded by a newer request".into());}- let cleared = app.disconnected_inputs.remove(&RecordingInputKind::Camera);if cleared {let _ = RecordingEvent::InputRestored {@@ -1551,6 +1987,97 @@ async fn set_camera_input(Ok(())}+async fn show_requested_camera_window(app: &AppHandle, revision: u64) -> Result<(), String> {+ let requested = app.state::<RequestedInputsState>();+ if !requested.camera_is_current(revision) {+ return Err("Camera selection was superseded by a newer request".into());+ }+ let result = ShowCapWindow::Camera { centered: false }.show(app).await;+ if !requested.camera_is_current(revision) {+ if let Some(window) = CapWindowId::Camera.get(app) {+ let _ = window.hide();+ }+ return Err("Camera selection was superseded by a newer request".into());+ }+ result.map(|_| ()).map_err(|error| error.to_string())+}++pub(crate) async fn restore_requested_inputs(app_handle: &AppHandle) {+ let requested = app_handle.state::<RequestedInputsState>();+ let snapshot = requested.snapshot();+ if snapshot.microphone.pending || snapshot.camera.pending {+ return;+ }+ let _operation = requested.operation.lock().await;+ let state = app_handle.state::<ArcLock<App>>();+ if !requested.is_current(&snapshot) || state.read().await.is_recording_active_or_pending() {+ return;+ }+ if !requested+ .inner+ .lock()+ .unwrap()+ .microphone+ .prepare_restore(snapshot.microphone.revision)+ {+ return;+ }+ let mic_result = apply_mic_input(+ app_handle,+ state.clone(),+ snapshot.microphone.value.clone(),+ snapshot.microphone.revision,+ )+ .await;+ requested+ .inner+ .lock()+ .unwrap()+ .microphone+ .finish(snapshot.microphone.revision, &mic_result);+ if let Err(error) = mic_result {+ warn!(%error, "Failed to restore requested microphone");+ }++ let restore_camera = {+ let state = state.read().await;+ requested.is_current(&snapshot)+ && !state.is_recording_active_or_pending()+ && !state.camera_cleanup_done+ && !state.camera_in_use+ && snapshot.camera.value.is_some()+ };+ if !restore_camera {+ return;+ }+ if !requested+ .inner+ .lock()+ .unwrap()+ .camera+ .prepare_restore(snapshot.camera.revision)+ {+ return;+ }+ let camera_result = apply_camera_input(+ app_handle,+ state,+ snapshot.camera.value,+ Some(false),+ snapshot.camera.revision,+ )+ .await;+ requested+ .inner+ .lock()+ .unwrap()+ .camera+ .finish(snapshot.camera.revision, &camera_result);+ if let Err(error) = camera_result {+ warn!(%error, "Failed to restore requested camera");+ }+}+#[tauri::command]#[specta::specta]#[instrument(skip(app_handle, state))]@@ -2181,6 +2708,7 @@ async fn cleanup_app_resources_for_exit(app: &AppHandle) {};let mut app_state = state.write().await;let camera_shutdown = app_state.camera_preview.begin_shutdown();+ app_state.applied_mic_input.invalidate();app_state.camera_in_use = false;app_state.selected_camera_id = None;(@@ -2272,23 +2800,12 @@ pub async fn request_app_exit(app: AppHandle) {finalize_app_exit(&app, 0);}-pub(crate) fn find_mic_by_label_or_fuzzy(- devices: &[String],- selected_label: &str,-) -> Option<String> {+pub(crate) fn find_mic_by_label(devices: &[String], selected_label: &str) -> Option<String> {if devices.iter().any(|name| name == selected_label) {return Some(selected_label.to_string());}- let selected_lower = selected_label.to_lowercase();-- devices- .iter()- .find(|name| {- let name_lower = name.to_lowercase();- name_lower.contains(&selected_lower) || selected_lower.contains(&name_lower)- })- .cloned()+ None}fn spawn_microphone_watcher(app_handle: AppHandle) {@@ -2324,7 +2841,7 @@ fn spawn_microphone_watcher(app_handle: AppHandle) {) else {break;};- let matched = find_mic_by_label_or_fuzzy(&devices, &selected_label);+ let matched = find_mic_by_label(&devices, &selected_label);if matched.is_none() && !is_marked {let mut app = state.write().await;@@ -2334,20 +2851,9 @@ fn spawn_microphone_watcher(app_handle: AppHandle) {{warn!("Failed to handle mic disconnect: {err}");}- } else if let Some(matched_label) = matched- && is_marked- {+ } else if matched.is_some() && is_marked {let mut app = state.write().await;- if matched_label != selected_label {- info!(- original = selected_label,- matched = matched_label,- "Microphone reconnected with different name (possible Bluetooth profile switch)"- );- app.selected_mic_label = Some(matched_label);- }-if let Err(err) = app.handle_input_restored(RecordingInputKind::Microphone).await@@ -5015,6 +5521,9 @@ fn random_animated_gradient() -> cap_project::AnimatedGradientConfig {fn specta_builder() -> tauri_specta::Builder {tauri_specta::Builder::new().commands(tauri_specta::collect_commands![+ linux_instant_camera::submit_camera_presentation,+ clean_capture::get_clean_capture_state,+ clean_capture::reveal_capture_window,animated_gradient_catalog,random_animated_gradient,set_mic_input,@@ -5185,6 +5694,7 @@ fn specta_builder() -> tauri_specta::Builder {updates::updates_channel_changed,]).events(tauri_specta::collect_events![+ linux_instant_camera::CameraPresentationRequested,RecordingOptionsChanged,NewStudioRecordingAdded,EditorRecordingAdded,@@ -5298,8 +5808,12 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {let (camera_preview_state_tx, camera_preview_state_rx) =tokio::sync::watch::channel(CameraPreviewState::default());- let (camera_tx, camera_ws_port, _shutdown) =- camera_legacy::create_camera_preview_ws(camera_preview_state_rx).await;+ let camera_preview_ws = camera_legacy::create_camera_preview_ws(camera_preview_state_rx).await;+ let camera_tx = camera_preview_ws.sender;+ let camera_ws_port = camera_preview_ws.port;+ let _shutdown = camera_preview_ws.shutdown;+ #[cfg(target_os = "linux")]+ let camera_processing = camera_preview_ws.processing;let camera_ws_sender = camera_tx.clone();let (mic_samples_tx, mic_samples_rx) = flume::bounded(8);@@ -5325,72 +5839,35 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {tauri::async_runtime::set(tokio::runtime::Handle::current());- #[allow(unused_mut)]- let mut builder = tauri::Builder::default();-- // The Linux single-instance plugin establishes its D-Bus connection through a- // blocking zbus call, which panics ("Cannot start a runtime from within a- // runtime") when initialized inside the Tokio runtime that drives the app.- #[cfg(not(target_os = "linux"))]- {- builder = builder.plugin(tauri_plugin_single_instance::init(|app, args, _cwd| {- trace!(arg_count = args.len(), "Single instance invoked");-- if gpui_app::handle_update_handoff(app) {- return;- }-- #[cfg(any(target_os = "macos", windows))]- if gpui_app::forward_deep_links_to_active_gpui(app, &args) {- return;- }-- let action_urls = args- .iter()- .filter(|arg| arg.starts_with("cap-desktop://"))- .filter_map(|arg| tauri::Url::parse(arg).ok())- .collect::<Vec<_>>();- if !action_urls.is_empty() {- deeplink_actions::handle(app, action_urls);- return;+ let builder =+ tauri::Builder::default().plugin(tauri_plugin_single_instance::init(|app, args, _cwd| {+ #[cfg(target_os = "linux")]+ {+ let handle = app.clone();+ if let Err(error) = app.run_on_main_thread(move || {+ handle_single_instance(&handle, args);+ }) {+ warn!(%error, "Could not queue Cap activation");+ }}+ #[cfg(not(target_os = "linux"))]+ handle_single_instance(app, args);+ }));- let Some(cap_file) = args- .iter()- .find(|arg| arg.ends_with(".cap"))- .map(PathBuf::from)- else {+ #[cfg(target_os = "macos")]+ let builder = builder+ .menu(build_macos_app_menu)+ .on_menu_event(|app, event| {+ if event.id() == APP_MENU_QUIT_ID {let app = app.clone();tokio::spawn(async move {- ShowCapWindow::Main {- init_target_mode: None,- }- .show(&app)- .await+ request_app_exit(app).await;});- return;- };-- let _ = open_project_from_path(&cap_file, app.clone());- }));- }-- #[cfg(target_os = "macos")]- {- builder = builder- .menu(build_macos_app_menu)- .on_menu_event(|app, event| {- if event.id() == APP_MENU_QUIT_ID {- let app = app.clone();- tokio::spawn(async move {- request_app_exit(app).await;- });- }- })- .plugin(tauri_nspanel::init());- }+ }+ })+ .plugin(tauri_nspanel::init());- builder+ let builder = builder.plugin(tauri_plugin_shell::init()).plugin(tauri_plugin_dialog::init()).plugin(tauri_plugin_store::Builder::new().build())@@ -5451,7 +5928,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {general_settings::init(&app);// Before anything shows a window or initialises further state: when// the native app owns the session, this one only exists to start it.- if gpui_app::redirect_at_startup_if_enabled(&app) {+ if gpui_app::redirect_at_startup_if_enabled(&app)? {// Nothing is managed yet, so `ExitRequested` would otherwise// spawn a cleanup with no `AppExitState` to guard it. Marking// the exit as already begun takes the plain runtime-exit path.@@ -5480,6 +5957,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {return Ok(());}+ app.manage(clean_capture::State::default());hotkeys::init(&app);configure_camera_blur_recovery(&app, previous_termination);fake_window::init(&app);@@ -5589,9 +6067,19 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {let camera_preview = CameraPreviewManager::new(&app);let camera_session_id_handle = camera_preview.session_id_handle();+ let requested_settings = RecordingSettingsStore::get(&app)?+ .unwrap_or_default();+ app.manage(linux_instant_camera::PresentationBroker::default());+ app.manage(RequestedInputsState::new(+ requested_settings.mic_name,+ requested_settings.camera_id,+ ));+app.manage(Arc::new(RwLock::new(App {camera_ws_port,camera_ws_sender,+ #[cfg(target_os = "linux")]+ camera_processing,handle: app.clone(),camera_preview,camera_preview_state_tx,@@ -5600,6 +6088,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {mic_feed,mic_meter_sender,selected_mic_label: None,+ applied_mic_input: AppliedMicrophoneInput::default(),selected_camera_id: None,camera_in_use: false,camera_cleanup_done: false,@@ -5706,9 +6195,6 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {.flatten().unwrap_or_default();- let _ = set_mic_input(app.state(), settings.mic_name).await;- let _ = set_camera_input(app.clone(), app.state(), settings.camera_id, None).await;-let _ = start_recording(app.clone(), app.state(), {recording::StartRecordingInputs {capture_target: settings.target.unwrap_or_else(|| {@@ -5834,6 +6320,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {}CapWindowId::Main => {api.prevent_close();+ clean_capture::cancel_closed_preflight(app);hide_main_window(app);#[cfg(target_os = "macos")]@@ -5865,6 +6352,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {let (mic_feed, camera_feed) = {let mut app_state = state.write().await;app_state.camera_preview.pause();+ app_state.applied_mic_input.invalidate();(app_state.mic_feed.clone(),app_state.camera_feed.clone(),@@ -5934,10 +6422,11 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {};let feeds = {- let app_state = state.read().await;+ let mut app_state = state.write().await;if app_state.is_recording_active_or_pending() {None} else {+ app_state.applied_mic_input.invalidate();Some((app_state.mic_feed.clone(),app_state.camera_feed.clone(),@@ -6203,23 +6692,89 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {sentry::Level::Error,);}- })- .build(tauri_context)- .expect("error while running tauri application")- .run(move |handle, event| {- let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- handle_run_event(handle, event);- }));+ });- if let Err(panic) = result {- let message = panic_payload_message(&panic);- tracing::error!(panic = %message, "Suppressed panic in Tauri RunEvent handler");- sentry::capture_message(- &format!("Tauri RunEvent panic suppressed: {message}"),- sentry::Level::Error,- );+ run_tauri_event_loop(move || {+ builder+ .build(tauri_context)+ .expect("error while running tauri application")+ .run(move |handle, event| {+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ handle_run_event(handle, event);+ }));++ if let Err(panic) = result {+ let message = panic_payload_message(&panic);+ tracing::error!(panic = %message, "Suppressed panic in Tauri RunEvent handler");+ sentry::capture_message(+ &format!("Tauri RunEvent panic suppressed: {message}"),+ sentry::Level::Error,+ );+ }+ });+ });+}++fn run_tauri_event_loop<R>(run: impl FnOnce() -> R) -> R {+ #[cfg(target_os = "linux")]+ {+ // zbus blocks on its own runtime during plugin setup and shutdown; keep GTK on this thread.+ tokio::task::block_in_place(run)+ }+ #[cfg(not(target_os = "linux"))]+ run()+}++fn handle_single_instance(app: &AppHandle, args: Vec<String>) {+ trace!(arg_count = args.len(), "Single instance invoked");++ #[cfg(target_os = "linux")]+ if app+ .try_state::<AppExitState>()+ .is_some_and(|state| state.is_exiting())+ {+ return;+ }++ if gpui_app::handle_update_handoff(app) {+ return;+ }++ #[cfg(any(target_os = "macos", windows))]+ if gpui_app::forward_deep_links_to_active_gpui(app, &args) {+ return;+ }++ let action_urls = args+ .iter()+ .filter(|arg| arg.starts_with("cap-desktop://"))+ .filter_map(|arg| tauri::Url::parse(arg).ok())+ .collect::<Vec<_>>();+ if !action_urls.is_empty() {+ deeplink_actions::handle(app, action_urls);+ return;+ }++ let Some(cap_file) = args+ .iter()+ .find(|arg| arg.ends_with(".cap"))+ .map(PathBuf::from)+ else {+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ if let Err(error) = (ShowCapWindow::Main {+ init_target_mode: None,+ })+ .show(&app)+ .await+ {+ warn!(%error, "Could not show Cap recording controls");}});+ return;+ };++ let _ = open_project_from_path(&cap_file, app.clone());}pub(crate) fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {@@ -6478,13 +7033,6 @@ where}}-fn show_camera_window_unlocked(app: &AppHandle) {- let app = app.clone();- spawn_on_runtime(async move {- let _ = ShowCapWindow::Camera { centered: false }.show(&app).await;- });-}-#[cfg(target_os = "windows")]fn has_open_editor_window(app: &AppHandle) -> bool {app.webview_windows()@@ -6503,7 +7051,8 @@ fn restore_main_windows_if_no_editors(app: &AppHandle) {if !has_other_editors {if CapWindowId::Settings.get(app).is_none() {if let Some(main) = CapWindowId::Main.get(app) {- let _ = main.show();+ let generation = clean_capture::generation(app);+ let _ = clean_capture::reveal_now(&main, generation);}restore_main_window_inputs(app);@@ -6531,7 +7080,8 @@ fn restore_main_and_target_select_windows(app: &AppHandle) {}}CapWindowId::Main => {- let _ = window.show();+ let generation = clean_capture::generation(app);+ let _ = clean_capture::reveal_now(&window, generation);restore_main_window_inputs(app);}_ => {}@@ -6548,27 +7098,29 @@ fn restore_main_window_inputs(app: &AppHandle) {}fn restore_camera_window(app: &AppHandle) {- let should_restore_camera = app- .try_state::<ArcLock<App>>()- .and_then(|state| {- state- .try_read()- .ok()- .map(|state| state.selected_camera_id.is_some() && !state.camera_cleanup_done)- })- .unwrap_or(false);-- if should_restore_camera {- let app = app.clone();- spawn_on_runtime(async move {- let Some(operation_lock) = app.try_state::<CameraWindowOperationLock>() else {- warn!("Camera window operation lock unavailable during restore");- return;- };- let _operation_guard = operation_lock.lock().await;- let _ = ShowCapWindow::Camera { centered: false }.show(&app).await;- });+ let snapshot = app.state::<RequestedInputsState>().snapshot();+ if snapshot.camera.value.is_none() || snapshot.camera.pending || snapshot.camera.error.is_some()+ {+ return;}+ let app = app.clone();+ spawn_on_runtime(async move {+ let requested = app.state::<RequestedInputsState>();+ let _input_operation = requested.operation.lock().await;+ let operation_lock = app.state::<CameraWindowOperationLock>();+ let _operation_guard = operation_lock.lock().await;+ let state = app.state::<ArcLock<App>>();+ let can_restore = {+ let state = state.read().await;+ requested.is_current(&snapshot)+ && !state.is_recording_active_or_pending()+ && !state.camera_cleanup_done+ && state.selected_camera_id == snapshot.camera.value+ };+ if can_restore {+ let _ = show_requested_camera_window(&app, snapshot.camera.revision).await;+ }+ });}fn close_target_select_overlays(app: &AppHandle) {@@ -6577,6 +7129,26 @@ fn close_target_select_overlays(app: &AppHandle) {#[cfg(target_os = "windows")]fn reopen_main_window(app: &AppHandle) {+ #[cfg(target_os = "linux")]+ if let Some(attempt) = recording::linux_instant::current(app)+ && attempt.has_capture()+ && !attempt.ui_ready()+ {+ let app = app.clone();+ drop(tauri::async_runtime::spawn(async move {+ if recording::linux_instant::control(app.clone(), attempt, false)+ .await+ .is_ok()+ {+ let _ = ShowCapWindow::Main {+ init_target_mode: None,+ }+ .show(&app)+ .await;+ }+ }));+ return;+ }if let Some(main) = CapWindowId::Main.get(app) {let _ = main.show();let _ = main.set_focus();@@ -6593,6 +7165,31 @@ fn reopen_main_window(app: &AppHandle) {}}+#[cfg(target_os = "linux")]+fn instant_upload_may_resume(inner: &RecordingMetaInner) -> bool {+ !matches!(+ inner,+ RecordingMetaInner::Instant(+ InstantRecordingMeta::InProgress { .. } | InstantRecordingMeta::Failed { .. }+ )+ )+}++#[cfg(target_os = "linux")]+fn load_instant_resume_candidate(path: &std::path::Path) -> Result<Option<RecordingMeta>, String> {+ let mut meta = RecordingMeta::load_for_project(path).map_err(|error| error.to_string())?;+ if matches!(+ meta.inner,+ RecordingMetaInner::Instant(InstantRecordingMeta::InProgress { .. })+ ) {+ meta.inner = RecordingMetaInner::Instant(InstantRecordingMeta::Failed {+ error: "Recording crashed".into(),+ });+ meta.save_for_project().map_err(|error| error.to_string())?;+ }+ Ok(instant_upload_may_resume(&meta.inner).then_some(meta))+}+async fn resume_uploads(app: AppHandle) -> Result<(), String> {let mut entries = Vec::new();for recordings_dir in recordings_locations::known_recordings_dirs(&app) {@@ -6606,7 +7203,11 @@ async fn resume_uploads(app: AppHandle) -> Result<(), String> {let path = entry.path();if path.is_dir() && path.extension().and_then(|s| s.to_str()) == Some("cap") {// Load recording meta to check for in-progress recordings- if let Ok(mut meta) = RecordingMeta::load_for_project(&path) {+ #[cfg(target_os = "linux")]+ let candidate = load_instant_resume_candidate(&path);+ #[cfg(not(target_os = "linux"))]+ let candidate = RecordingMeta::load_for_project(&path).map(Some);+ if let Ok(Some(mut meta)) = candidate {let mut needs_save = false;// Check if recording is still marked as in-progress and if so mark as failed@@ -6636,6 +7237,19 @@ async fn resume_uploads(app: AppHandle) -> Result<(), String> {error!("Failed to save recording meta for {path:?}: {err}");}+ #[cfg(target_os = "linux")]+ if !instant_upload_may_resume(&meta.inner) {+ continue;+ }+ #[cfg(target_os = "linux")]+ let required_audio = matches!(+ &meta.inner,+ RecordingMetaInner::Instant(InstantRecordingMeta::Complete {+ sample_rate: Some(_),+ ..+ })+ );+// Handle upload resumptionif let Some(upload_meta) = meta.upload {match upload_meta {@@ -6645,6 +7259,17 @@ async fn resume_uploads(app: AppHandle) -> Result<(), String> {pre_created_video,recording_dir,} => {+ #[cfg(target_os = "linux")]+ if matches!(&meta.inner, RecordingMetaInner::Instant(_)) {+ upload::strict_instant::resume(+ app.clone(),+ recording_dir,+ pre_created_video,+ None,+ required_audio,+ );+ continue;+ }InstantMultipartUpload::spawn(app.clone(),file_path,@@ -6815,6 +7440,17 @@ async fn resume_uploads(app: AppHandle) -> Result<(), String> {scan_and_send(&audio_dir, SegmentMediaType::Audio, &segment_tx);drop(segment_tx);+ #[cfg(target_os = "linux")]+ if matches!(&meta.inner, RecordingMetaInner::Instant(_)) {+ upload::strict_instant::resume(+ app.clone(),+ recording_dir,+ pre_created_video,+ Some(segment_rx),+ required_audio,+ );+ continue;+ }crate::upload::SegmentUploader::spawn(app.clone(),video_id,@@ -6898,6 +7534,11 @@ pub(crate) async fn wait_for_recording_ready(app: &AppHandle, path: &Path) -> Re.await.map_err(|_| "Finalization was cancelled".to_string())?;info!("Recording finalization completed");+ let meta = RecordingMeta::load_for_project(path)+ .map_err(|e| format!("Failed to reload recording meta: {e}"))?;+ if let Some(studio_meta) = meta.studio_meta() {+ studio_meta.ensure_ordinary_media_access(path)?;+ }return Ok(());}@@ -6946,6 +7587,9 @@ pub(crate) async fn wait_for_recording_ready(app: &AppHandle, path: &Path) -> Relet meta = RecordingMeta::load_for_project(path).map_err(|e| format!("Failed to reload recording meta: {e}"))?;+ if let Some(studio_meta) = meta.studio_meta() {+ studio_meta.ensure_ordinary_media_access(path)?;+ }if let Some(studio_meta) = meta.studio_meta()&& recording::needs_fragment_remux(path, studio_meta)@@ -7159,6 +7803,738 @@ fn open_project_from_path(path: &Path, app: AppHandle) -> Result<(), String> {Ok(())}+#[cfg(test)]+mod studio_microphone_ownership_tests {+ use super::{+ MicrophoneRemovalError, RequestedInputsState, acknowledge_studio_microphone,+ replace_owned_microphone, wait_for_microphone_removal,+ };+ use std::{+ path::{Path, PathBuf},+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, AtomicUsize, Ordering},+ },+ time::Duration,+ };+ use tokio::sync::oneshot;++ struct Lock {+ drops: Arc<AtomicUsize>,+ unlock: Option<oneshot::Sender<()>>,+ }++ impl Drop for Lock {+ fn drop(&mut self) {+ self.drops.fetch_add(1, Ordering::SeqCst);+ if let Some(unlock) = self.unlock.take() {+ let _ = unlock.send(());+ }+ }+ }++ #[tokio::test]+ async fn detach_drops_app_lock_after_ack_and_waits_for_unlock_and_removal() {+ let drops = Arc::new(AtomicUsize::new(0));+ let (unlock_tx, unlock_rx) = oneshot::channel();+ let lock = Arc::new(Lock {+ drops: drops.clone(),+ unlock: Some(unlock_tx),+ });+ let app_slot = Mutex::new(Some(lock.clone()));+ let actor_slot = Mutex::new(Some(lock));+ let (ack_tx, ack_rx) = oneshot::channel();+ let unlocked = AtomicBool::new(false);+ let removed = AtomicBool::new(false);+ let attempts = AtomicUsize::new(0);+ let transition = async {+ acknowledge_studio_microphone(+ async {+ ack_rx.await.unwrap();+ drop(actor_slot.lock().unwrap().take());+ Ok(())+ },+ async {+ replace_owned_microphone(+ Path::new("owner"),+ Some((Path::new("owner"), &mut *app_slot.lock().unwrap())),+ None,+ )+ },+ "detaching",+ )+ .await+ .unwrap();+ assert_eq!(drops.load(Ordering::SeqCst), 1);+ wait_for_microphone_removal(|| async {+ attempts.fetch_add(1, Ordering::SeqCst);+ if unlocked.load(Ordering::SeqCst) {+ removed.store(true, Ordering::SeqCst);+ Ok(())+ } else {+ Err(MicrophoneRemovalError::Locked)+ }+ })+ .await+ .unwrap();+ };+ tokio::join!(+ biased;+ transition,+ async {+ assert!(app_slot.lock().unwrap().is_some());+ assert_eq!(drops.load(Ordering::SeqCst), 0);+ ack_tx.send(()).unwrap();+ unlock_rx.await.unwrap();+ assert!(!removed.load(Ordering::SeqCst));+ tokio::time::sleep(Duration::from_millis(10)).await;+ unlocked.store(true, Ordering::SeqCst);+ }+ );+ assert!(removed.load(Ordering::SeqCst));+ assert!(attempts.load(Ordering::SeqCst) >= 2);+ }++ #[tokio::test]+ async fn failed_detach_keeps_app_ownership() {+ let drops = Arc::new(AtomicUsize::new(0));+ let mut slot = Some(Arc::new(Lock {+ drops: drops.clone(),+ unlock: None,+ }));+ let result = acknowledge_studio_microphone(+ async { Err("Pause before changing input".into()) },+ async {+ replace_owned_microphone(+ Path::new("owner"),+ Some((Path::new("owner"), &mut slot)),+ None,+ )+ },+ "detaching",+ )+ .await;+ assert!(result.is_err());+ assert!(slot.is_some());+ assert_eq!(drops.load(Ordering::SeqCst), 0);+ }++ #[tokio::test]+ async fn timed_out_detach_keeps_app_ownership() {+ let mut slot = Some(Arc::new(1));+ let result = acknowledge_studio_microphone(+ std::future::pending(),+ async {+ replace_owned_microphone(+ Path::new("owner"),+ Some((Path::new("owner"), &mut slot)),+ None,+ )+ },+ "detaching",+ )+ .await;+ assert!(result.unwrap_err().contains("Timed out"));+ assert!(slot.is_some());+ }++ #[tokio::test]+ async fn stale_successful_attachment_retains_actual_arc_for_next_request() {+ let requests = RequestedInputsState::new(Some("A".into()), None);+ let revision = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("B".into()));+ let lock = Arc::new(42);+ let actor_slot = Mutex::new(None);+ let app_slot = Mutex::new(None);+ let (tx, rx) = oneshot::channel();+ let (result, ()) = tokio::join!(+ biased;+ acknowledge_studio_microphone(+ async { rx.await.unwrap(); *actor_slot.lock().unwrap() = Some(lock.clone()); Ok(()) },+ async { replace_owned_microphone(Path::new("owner"), Some((Path::new("owner"), &mut *app_slot.lock().unwrap())), Some(lock.clone())) },+ "attaching",+ ),+ async {+ assert!(app_slot.lock().unwrap().is_none());+ let _revision = requests.inner.lock().unwrap().microphone.begin(None);+ tx.send(()).unwrap();+ }+ );+ result.unwrap();+ assert!(!requests.mic_is_current(revision));+ assert!(Arc::ptr_eq(+ app_slot.lock().unwrap().as_ref().unwrap(),+ actor_slot.lock().unwrap().as_ref().unwrap()+ ));+ }++ #[tokio::test]+ async fn failed_attachment_does_not_retain_new_lock() {+ let mut slot: Option<Arc<u32>> = None;+ let result = acknowledge_studio_microphone(+ async { Err("Studio stopped".into()) },+ async {+ replace_owned_microphone(+ Path::new("owner"),+ Some((Path::new("owner"), &mut slot)),+ Some(Arc::new(42)),+ )+ },+ "attaching",+ )+ .await;+ assert!(result.is_err());+ assert!(slot.is_none());+ }++ #[tokio::test]+ async fn stop_or_replacement_during_ack_does_not_overwrite_another_owner() {+ for next_owner in [None, Some(PathBuf::from("new-owner"))] {+ let requests = RequestedInputsState::new(None, None);+ let _operation = requests.operation.lock().await;+ let owner = Mutex::new(Some(PathBuf::from("old-owner")));+ let new_lock = Arc::new(9);+ let slot = Mutex::new(Some(new_lock.clone()));+ let (tx, rx) = oneshot::channel();+ let (result, ()) = tokio::join!(+ biased;+ acknowledge_studio_microphone(+ async { rx.await.unwrap(); Ok(()) },+ async {+ let owner = owner.lock().unwrap();+ let mut slot = slot.lock().unwrap();+ replace_owned_microphone(Path::new("old-owner"), owner.as_deref().map(|owner| (owner, &mut *slot)), Some(Arc::new(42)))+ },+ "attaching",+ ),+ async { *owner.lock().unwrap() = next_owner; tx.send(()).unwrap(); }+ );+ assert!(result.is_err());+ assert!(Arc::ptr_eq(+ slot.lock().unwrap().as_ref().unwrap(),+ &new_lock+ ));+ }+ }++ #[tokio::test]+ async fn locked_input_is_not_reported_removed_at_the_deadline() {+ let result = tokio::time::timeout(+ Duration::from_secs(2),+ wait_for_microphone_removal(|| async { Err(MicrophoneRemovalError::Locked) }),+ )+ .await+ .unwrap();+ assert!(result.is_err());+ }++ #[tokio::test]+ async fn unresponsive_remove_ask_is_bounded() {+ let result = tokio::time::timeout(+ Duration::from_secs(2),+ wait_for_microphone_removal(std::future::pending),+ )+ .await+ .unwrap();+ assert!(result.unwrap_err().contains("Timed out"));+ }++ #[tokio::test]+ async fn pending_microphone_change_blocks_resume() {+ let requests = RequestedInputsState::new(Some("A".into()), None);+ let _revision = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("B".into()));+ let error = requests.try_resume_guard().unwrap_err();+ assert!(error.contains("still being configured"));+ }++ #[tokio::test]+ async fn failed_microphone_change_blocks_resume_until_reselected() {+ let requests = RequestedInputsState::new(Some("A".into()), None);+ let revision = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("B".into()));+ requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .finish(revision, &Err("B unavailable".into()));+ assert!(+ requests+ .try_resume_guard()+ .unwrap_err()+ .contains("B unavailable")+ );+ let none = requests.inner.lock().unwrap().microphone.begin(None);+ requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .finish(none, &Ok(()));+ assert!(requests.try_resume_guard().is_ok());+ }++ #[tokio::test]+ async fn camera_setup_also_blocks_resume() {+ let requests = RequestedInputsState::new(None, None);+ let _revision = requests.inner.lock().unwrap().camera.begin(None);+ assert!(requests.try_resume_guard().unwrap_err().contains("camera"));+ }++ #[tokio::test]+ async fn resume_rejects_busy_operation_without_waiting_for_it() {+ let requests = RequestedInputsState::new(None, None);+ let _operation = requests.operation.lock().await;+ assert!(+ requests+ .try_resume_guard()+ .unwrap_err()+ .contains("Input change in progress")+ );+ }++ #[tokio::test]+ async fn healthy_resume_holds_operation_until_actor_acknowledgement() {+ let requests = RequestedInputsState::new(Some("A".into()), None);+ let (tx, rx) = oneshot::channel();+ tokio::join!(+ biased;+ async {+ let _guard = requests.try_resume_guard().unwrap();+ rx.await.unwrap();+ },+ async {+ assert!(requests.operation.try_lock().is_err());+ tx.send(()).unwrap();+ }+ );+ assert!(requests.operation.try_lock().is_ok());+ }++ #[tokio::test]+ async fn non_lock_failure_is_not_retried() {+ let attempts = AtomicUsize::new(0);+ let result = wait_for_microphone_removal(|| async {+ attempts.fetch_add(1, Ordering::SeqCst);+ Err(MicrophoneRemovalError::Failed("Actor unavailable".into()))+ })+ .await;+ assert_eq!(result.unwrap_err(), "Actor unavailable");+ assert_eq!(attempts.load(Ordering::SeqCst), 1);+ }+}++#[cfg(test)]+mod applied_microphone_tests {+ use super::{AppliedMicrophoneInput, RequestedInputsState, finish_microphone_input_change};+ use std::sync::Mutex;+ use tokio::sync::oneshot;++ #[derive(Default)]+ struct Feed {+ applied: AppliedMicrophoneInput,+ selected: Option<String>,+ actual: Option<String>,+ attached: Option<String>,+ active: bool,+ set_count: usize,+ remove_count: usize,+ detach_count: usize,+ attach_count: usize,+ }++ impl Feed {+ fn healthy_active() -> Self {+ Self {+ applied: AppliedMicrophoneInput {+ valid: true,+ generation: 0,+ },+ selected: Some("A".into()),+ actual: Some("A".into()),+ attached: Some("A".into()),+ active: true,+ ..Default::default()+ }+ }+ }++ async fn apply(+ feed: &Mutex<Feed>,+ requests: &RequestedInputsState,+ label: Option<&str>,+ revision: u64,+ ready: oneshot::Receiver<()>,+ fail: bool,+ ) -> Result<(), String> {+ let generation = {+ let mut feed = feed.lock().unwrap();+ let active = feed.active;+ let selected = feed.selected.clone();+ if !feed+ .applied+ .prepare_change(active, label, selected.as_deref())+ {+ return Ok(());+ }+ feed.applied.generation+ };+ let result = finish_microphone_input_change(+ async {+ {+ let mut feed = feed.lock().unwrap();+ if feed.active {+ feed.detach_count += 1;+ feed.attached = None;+ }+ }+ ready.await.unwrap();+ let mut feed = feed.lock().unwrap();+ if label.is_some() {+ feed.set_count += 1;+ } else {+ feed.remove_count += 1;+ }+ feed.actual = if fail {+ None+ } else {+ label.map(str::to_string)+ };+ if fail {+ Err("Setup failed".into())+ } else {+ Ok(())+ }+ },+ || requests.mic_is_current(revision),+ async {+ let mut feed = feed.lock().unwrap();+ if feed.active && label.is_some() {+ feed.attach_count += 1;+ feed.attached = feed.actual.clone();+ }+ Ok(())+ },+ )+ .await;+ if result.is_ok() {+ let mut confirmed = false;+ requests.publish_mic_if_current(revision, || {+ let mut feed = feed.lock().unwrap();+ if feed.applied.confirm_if_current(generation) {+ feed.selected = label.map(str::to_string);+ confirmed = true;+ }+ });+ if !confirmed {+ return Err("Input changed during setup".into());+ }+ }+ result+ }++ fn ready() -> oneshot::Receiver<()> {+ let (tx, rx) = oneshot::channel();+ tx.send(()).unwrap();+ rx+ }++ #[tokio::test]+ async fn stale_a_then_none_removes_actual_input_even_when_metadata_is_none() {+ let feed = Mutex::new(Feed::default());+ let requests = RequestedInputsState::new(None, None);+ let a = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("A".into()));+ let (tx, rx) = oneshot::channel();+ let (old, none) = tokio::join!(apply(&feed, &requests, Some("A"), a, rx, false), async {+ let none = requests.inner.lock().unwrap().microphone.begin(None);+ tx.send(()).unwrap();+ none+ });+ assert!(old.is_err());+ {+ let feed = feed.lock().unwrap();+ assert_eq!(feed.actual.as_deref(), Some("A"));+ assert!(feed.selected.is_none());+ assert!(!feed.applied.valid);+ }+ apply(&feed, &requests, None, none, ready(), false)+ .await+ .unwrap();+ let feed = feed.lock().unwrap();+ assert!(feed.actual.is_none());+ assert_eq!(feed.remove_count, 1);+ }++ #[tokio::test]+ async fn stale_b_then_a_restores_actual_feed_and_studio_attachment() {+ let feed = Mutex::new(Feed::healthy_active());+ let requests = RequestedInputsState::new(Some("A".into()), None);+ let b = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("B".into()));+ let (tx, rx) = oneshot::channel();+ let (old, a) = tokio::join!(apply(&feed, &requests, Some("B"), b, rx, false), async {+ let a = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("A".into()));+ tx.send(()).unwrap();+ a+ });+ assert!(old.is_err());+ assert!(feed.lock().unwrap().attached.is_none());+ apply(&feed, &requests, Some("A"), a, ready(), false)+ .await+ .unwrap();+ let feed = feed.lock().unwrap();+ assert_eq!(feed.actual.as_deref(), Some("A"));+ assert_eq!(feed.attached.as_deref(), Some("A"));+ assert_eq!(feed.set_count, 2);+ assert_eq!(feed.detach_count, 2);+ assert_eq!(feed.attach_count, 1);+ }++ #[tokio::test]+ async fn failed_b_leaves_dirty_state_and_a_cannot_reuse_metadata() {+ let feed = Mutex::new(Feed::healthy_active());+ let requests = RequestedInputsState::new(Some("A".into()), None);+ let b = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("B".into()));+ assert!(+ apply(&feed, &requests, Some("B"), b, ready(), true)+ .await+ .is_err()+ );+ {+ let feed = feed.lock().unwrap();+ assert_eq!(feed.selected.as_deref(), Some("A"));+ assert!(feed.actual.is_none());+ assert!(feed.attached.is_none());+ assert!(!feed.applied.valid);+ }+ let a = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("A".into()));+ apply(&feed, &requests, Some("A"), a, ready(), false)+ .await+ .unwrap();+ let feed = feed.lock().unwrap();+ assert_eq!(feed.actual.as_deref(), Some("A"));+ assert_eq!(feed.attached.as_deref(), Some("A"));+ assert_eq!(feed.set_count, 2);+ assert_eq!(feed.attach_count, 1);+ }++ #[tokio::test]+ async fn disconnect_during_setup_cannot_restore_validity() {+ let feed = Mutex::new(Feed::healthy_active());+ let requests = RequestedInputsState::new(Some("A".into()), None);+ let b = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("B".into()));+ let (tx, rx) = oneshot::channel();+ let (result, ()) = tokio::join!(+ biased;+ apply(&feed, &requests, Some("B"), b, rx, false),+ async {+ feed.lock().unwrap().applied.invalidate();+ tx.send(()).unwrap();+ }+ );+ assert!(result.is_err());+ let feed = feed.lock().unwrap();+ assert!(!feed.applied.valid);+ assert_eq!(feed.selected.as_deref(), Some("A"));+ }++ #[tokio::test]+ async fn healthy_active_same_input_has_zero_setup_or_detach() {+ let feed = Mutex::new(Feed::healthy_active());+ let requests = RequestedInputsState::new(Some("A".into()), None);+ let a = requests+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("A".into()));+ apply(&feed, &requests, Some("A"), a, ready(), false)+ .await+ .unwrap();+ let feed = feed.lock().unwrap();+ assert_eq!(feed.set_count, 0);+ assert_eq!(feed.detach_count, 0);+ assert_eq!(feed.attach_count, 0);+ assert_eq!(feed.attached.as_deref(), Some("A"));+ }+}++#[cfg(test)]+mod requested_inputs_tests {+ use super::{RequestedInput, RequestedInputsState};++ #[test]+ fn persisted_intent_is_available_before_preview_setup() {+ let state = RequestedInputsState::new(Some("Missing microphone".into()), None);+ let snapshot = state.ready_snapshot().unwrap();+ assert_eq!(+ snapshot.microphone.value.as_deref(),+ Some("Missing microphone")+ );+ assert!(snapshot.camera.value.is_none());+ }++ #[test]+ fn failed_change_retains_requested_device_and_blocks_start() {+ let mut input = RequestedInput::new(Some("A".to_string()));+ let revision = input.begin(Some("B".to_string()));+ input.finish(revision, &Err("B unavailable".into()));+ assert_eq!(input.value.as_deref(), Some("B"));+ assert!(+ input+ .validate("microphone")+ .unwrap_err()+ .contains("B unavailable")+ );+ }++ #[test]+ fn stale_completion_cannot_finish_newer_request() {+ let mut input = RequestedInput::new(None);+ let old = input.begin(Some("A".to_string()));+ let current = input.begin(Some("B".to_string()));+ input.finish(old, &Err("A failed".into()));+ assert!(input.pending);+ assert!(input.error.is_none());+ assert_eq!(input.value.as_deref(), Some("B"));+ input.finish(current, &Ok(()));+ assert!(input.validate("microphone").is_ok());+ }++ #[test]+ fn rapid_requests_preserve_explicit_none() {+ let mut input = RequestedInput::new(None);+ let first = input.begin(Some("A".to_string()));+ let second = input.begin(Some("B".to_string()));+ let none = input.begin(None);+ input.finish(none, &Ok(()));+ input.finish(first, &Ok(()));+ input.finish(second, &Err("B unavailable".into()));+ assert!(input.value.is_none());+ assert!(input.validate("microphone").is_ok());+ }++ #[test]+ fn restore_cannot_replace_newer_or_pending_request() {+ let mut input = RequestedInput::new(Some("A".to_string()));+ let old = input.revision;+ let current = input.begin(None);+ assert!(!input.prepare_restore(old));+ assert!(!input.prepare_restore(current));+ input.finish(current, &Ok(()));+ assert!(input.prepare_restore(current));+ assert!(input.value.is_none());+ }++ #[test]+ fn start_is_blocked_while_setup_is_pending_or_failed() {+ let state = RequestedInputsState::new(None, None);+ let revision = state+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("A".into()));+ assert!(state.ready_snapshot().is_err());+ state+ .inner+ .lock()+ .unwrap()+ .microphone+ .finish(revision, &Err("Unavailable".into()));+ assert!(state.ready_snapshot().is_err());+ let none = state.inner.lock().unwrap().microphone.begin(None);+ state.inner.lock().unwrap().microphone.finish(none, &Ok(()));+ assert!(state.ready_snapshot().is_ok());+ }++ #[test]+ fn changed_request_prevents_recording_publication() {+ let state = RequestedInputsState::new(Some("A".into()), None);+ let snapshot = state.ready_snapshot().unwrap();+ let _revision = state+ .inner+ .lock()+ .unwrap()+ .microphone+ .begin(Some("B".into()));+ let mut published = false;+ assert!(!state.publish_if_current(&snapshot, || published = true));+ assert!(!published);+ }++ #[test]+ fn stale_camera_restore_cannot_publish_runtime_state() {+ let state = RequestedInputsState::new(None, None);+ let revision = state.snapshot().camera.revision;+ let _new_revision = state.inner.lock().unwrap().camera.begin(None);+ let mut published = false;+ assert!(!state.publish_camera_if_current(revision, || published = true));+ assert!(!published);+ }++ #[test]+ fn stale_microphone_completion_cannot_publish_runtime_state() {+ let state = RequestedInputsState::new(None, None);+ let revision = state.snapshot().microphone.revision;+ let _new_revision = state.inner.lock().unwrap().microphone.begin(None);+ let mut published = false;+ assert!(!state.publish_mic_if_current(revision, || published = true));+ assert!(!published);+ }++ #[test]+ fn unchanged_request_can_publish_recording() {+ let state = RequestedInputsState::new(None, None);+ let snapshot = state.ready_snapshot().unwrap();+ let mut published = false;+ assert!(state.publish_if_current(&snapshot, || published = true));+ assert!(published);+ }+}+#[cfg(test)]mod screenshot_share_cache_tests {use super::*;@@ -7206,3 +8582,87 @@ mod typescript_bindings_tests {}}}++#[cfg(all(test, target_os = "linux"))]+mod instant_resume_safety_tests {+ use super::*;+ fn project(tag: &str, inner: InstantRecordingMeta) -> PathBuf {+ static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);+ let path = std::env::temp_dir().join(format!(+ "cap-instant-recovery-{tag}-{}-{}",+ std::process::id(),+ NEXT.fetch_add(1, std::sync::atomic::Ordering::AcqRel)+ ));+ std::fs::create_dir_all(&path).unwrap();+ let meta = RecordingMeta {+ platform: None,+ project_path: path.clone(),+ pretty_name: "Synthetic recovery".into(),+ sharing: None,+ inner: RecordingMetaInner::Instant(inner),+ upload: Some(UploadMeta::SegmentUpload {+ video_id: "synthetic".into(),+ recording_dir: path.clone(),+ pre_created_video: VideoUploadInfo {+ id: "synthetic".into(),+ link: "https://example.invalid/s/synthetic".into(),+ config: cap_project::S3UploadMeta {+ id: "synthetic".into(),+ },+ },+ }),+ };+ meta.save_for_project().unwrap();+ path+ }+ #[test]+ fn crashed_and_failed_projects_never_become_automatic_upload_candidates() {+ for inner in [+ InstantRecordingMeta::InProgress { recording: true },+ InstantRecordingMeta::Failed {+ error: "required audio failed".into(),+ },+ ] {+ let path = project("failed", inner);+ assert!(load_instant_resume_candidate(&path).unwrap().is_none());+ let meta = RecordingMeta::load_for_project(&path).unwrap();+ assert!(matches!(+ meta.inner,+ RecordingMetaInner::Instant(InstantRecordingMeta::Failed { .. })+ ));+ assert!(matches!(+ meta.upload,+ Some(UploadMeta::SegmentUpload { .. })+ ));+ assert!(path.is_dir());+ std::fs::remove_dir_all(path).unwrap();+ }+ }+ #[test]+ fn positively_complete_project_remains_resumable_without_media_deletion() {+ let path = project(+ "complete",+ InstantRecordingMeta::Complete {+ fps: 30,+ sample_rate: Some(48000),+ },+ );+ assert!(load_instant_resume_candidate(&path).unwrap().is_some());+ assert!(path.is_dir());+ std::fs::remove_dir_all(path).unwrap();+ }+ #[test]+ fn invalid_recovery_metadata_cannot_authorize_upload() {+ let path = project(+ "invalid",+ InstantRecordingMeta::Complete {+ fps: 30,+ sample_rate: None,+ },+ );+ std::fs::write(path.join("recording-meta.json"), b"invalid").unwrap();+ assert!(load_instant_resume_candidate(&path).is_err());+ assert!(path.is_dir());+ std::fs::remove_dir_all(path).unwrap();+ }+}diff --git a/apps/desktop/src-tauri/src/linux_instant_camera.rs b/apps/desktop/src-tauri/src/linux_instant_camera.rsnew file mode 100644index 000000000..1f2efed7f--- /dev/null+++ b/apps/desktop/src-tauri/src/linux_instant_camera.rs@@ -0,0 +1,1140 @@+use std::{+ sync::{Arc, Mutex},+ time::Duration,+};++use serde::{Deserialize, Serialize};+use specta::Type;+#[cfg(target_os = "linux")]+use std::time::Instant;+use tauri::{AppHandle, Manager, WebviewWindow};+use tauri_specta::Event;++use crate::{camera::CameraPreviewState, windows::CapWindowId};++#[cfg(target_os = "linux")]+use crate::camera::CameraPreviewShape;++#[derive(Clone)]+struct SelectionGuard {+ inputs: Arc<Mutex<crate::RequestedInputs>>,+ revision: u64,+ selected: cap_recording::feeds::camera::DeviceOrModelID,+}++impl SelectionGuard {+ fn current(&self) -> bool {+ let inputs = self.inputs.lock().unwrap();+ inputs.camera.revision == self.revision+ && inputs.camera.value.as_ref() == Some(&self.selected)+ && !inputs.camera.pending+ && inputs.camera.error.is_none()+ }+}++#[derive(Clone, Debug, Deserialize, Serialize, Type)]+#[serde(rename_all = "camelCase")]+pub struct CameraPresentationInput {+ pub viewport_width: f64,+ pub viewport_height: f64,+ pub left: f64,+ pub top: f64,+ pub width: f64,+ pub height: f64,+ pub radius: f64,+ pub layout_revision: u32,+ pub state: CameraPreviewState,+}++#[derive(Clone, Serialize, Type, Event)]+#[serde(rename_all = "camelCase")]+pub struct CameraPresentationRequested {+ pub nonce: String,+ pub generation: u32,+ pub camera_revision: String,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct PhysicalRect {+ pub x: i32,+ pub y: i32,+ pub width: u32,+ pub height: u32,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct NativeSnapshot {+ id: u64,+ rect: PhysicalRect,+}++impl NativeSnapshot {+ #[cfg(target_os = "linux")]+ fn read(window: &WebviewWindow) -> Result<Self, String> {+ use wgpu::rwh::{HasWindowHandle, RawWindowHandle};+ let id = match window+ .window_handle()+ .map_err(|error| error.to_string())?+ .as_raw()+ {+ RawWindowHandle::Xlib(handle) => handle.window,+ RawWindowHandle::Xcb(handle) => u64::from(handle.window.get()),+ _ => return Err("Camera presentation requires a native X11 window".into()),+ };+ let position = window.inner_position().map_err(|error| error.to_string())?;+ let size = window.inner_size().map_err(|error| error.to_string())?;+ Ok(Self {+ id,+ rect: PhysicalRect {+ x: position.x,+ y: position.y,+ width: size.width,+ height: size.height,+ },+ })+ }++ #[cfg(not(target_os = "linux"))]+ fn read(_window: &WebviewWindow) -> Result<Self, String> {+ Err("Processed camera presentation is only available on Linux X11".into())+ }+}++async fn native_snapshot(window: WebviewWindow) -> Result<NativeSnapshot, String> {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = window.clone();+ window+ .run_on_main_thread(move || {+ let _ = tx.send(NativeSnapshot::read(&handle));+ })+ .map_err(|error| error.to_string())?;+ tokio::time::timeout(Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Camera window geometry timed out".to_string())?+ .map_err(|_| "Camera window geometry was cancelled".to_string())?+}++#[derive(Clone)]+struct PresentationOwner {+ nonce: String,+ generation: u32,+ native: NativeSnapshot,+ selection: SelectionGuard,+ state: tokio::sync::watch::Receiver<CameraPreviewState>,+}++impl PresentationOwner {+ fn validate(+ &self,+ app: &AppHandle,+ native: NativeSnapshot,+ input: &CameraPresentationInput,+ ) -> Result<(), String> {+ if !crate::clean_capture::is_current(app, self.generation)+ || !self.selection.current()+ || self.native != native+ || *self.state.borrow() != input.state+ {+ return Err(+ "Camera selection, appearance, or window changed. Start again to confirm it."+ .into(),+ );+ }+ Ok(())+ }+}++struct PendingPresentation {+ owner: PresentationOwner,+ reply: tokio::sync::oneshot::Sender<Result<CameraPresentationInput, String>>,+}++#[derive(Default)]+pub struct PresentationBroker {+ pending: Arc<Mutex<Option<PendingPresentation>>>,+}++struct PendingGuard {+ pending: Arc<Mutex<Option<PendingPresentation>>>,+ nonce: String,+}++impl Drop for PendingGuard {+ fn drop(&mut self) {+ let mut pending = self.pending.lock().unwrap();+ if pending+ .as_ref()+ .is_some_and(|pending| pending.owner.nonce == self.nonce)+ {+ *pending = None;+ }+ }+}++#[tauri::command]+#[specta::specta]+pub async fn submit_camera_presentation(+ window: WebviewWindow,+ nonce: String,+ input: Option<CameraPresentationInput>,+ error: Option<String>,+) -> Result<(), String> {+ if !cfg!(target_os = "linux")+ || !matches!(+ window.label().parse::<CapWindowId>(),+ Ok(CapWindowId::Camera)+ )+ {+ return Err(+ "Only the current Linux camera window may answer a presentation request".into(),+ );+ }+ let app = window.app_handle();+ let broker = app.state::<PresentationBroker>();+ let owner = broker+ .pending+ .lock()+ .unwrap()+ .as_ref()+ .filter(|pending| pending.owner.nonce == nonce)+ .map(|pending| pending.owner.clone())+ .ok_or("Camera presentation request expired")?;+ let native = native_snapshot(window.clone()).await?;+ if native.id != owner.native.id+ || !crate::clean_capture::is_current(app, owner.generation)+ || !owner.selection.current()+ {+ return Err("Camera presentation owner changed".into());+ }+ let result = match (input, error) {+ (Some(input), None) => owner.validate(app, native, &input).map(|()| input),+ (None, Some(error)) => Err(error),+ _ => return Err("Camera presentation requires either pixels geometry or an error".into()),+ };+ let mut pending = broker.pending.lock().unwrap();+ if pending+ .as_ref()+ .is_none_or(|pending| pending.owner.nonce != nonce)+ {+ return Err("Camera presentation request was superseded".into());+ }+ let _ = pending.take().unwrap().reply.send(result);+ Ok(())+}++#[cfg(target_os = "linux")]+pub struct PreparedPresentation {+ owner: PresentationOwner,+ actor: kameo::actor::ActorRef<cap_recording::feeds::camera::CameraFeed>,+ input: CameraPresentationInput,+ pub presentation: cap_recording::instant_recording::LinuxCameraPresentation,+ pub reference_size: (u32, u32),+ pub processing: cap_recording::instant_recording::LinuxCameraProcessing,+}++#[cfg(target_os = "linux")]+impl PreparedPresentation {+ pub fn validate_before_hide(&self, window: &WebviewWindow) -> Result<(), String> {+ if !matches!(+ window.label().parse::<CapWindowId>(),+ Ok(CapWindowId::Camera)+ ) {+ return Err("Camera presentation window changed".into());+ }+ self.owner.validate(+ window.app_handle(),+ NativeSnapshot::read(window)?,+ &self.input,+ )+ }+}++#[cfg(target_os = "linux")]+pub async fn request_presentation(+ app: &AppHandle,+ generation: u32,+ capture: PhysicalRect,+) -> Result<PreparedPresentation, String> {+ let requested = app.state::<crate::RequestedInputsState>();+ let snapshot = requested.ready_snapshot()?;+ let selected = snapshot+ .camera+ .value+ .clone()+ .ok_or("Select a camera before requesting its presentation")?;+ let selection = SelectionGuard {+ inputs: requested.inner.clone(),+ revision: snapshot.camera.revision,+ selected,+ };+ let window = CapWindowId::Camera+ .get(app)+ .ok_or("Open the selected camera preview before recording")?;+ if !window.is_visible().map_err(|error| error.to_string())? {+ return Err("Open the selected camera preview before recording".into());+ }+ let native = native_snapshot(window.clone()).await?;+ let (actor, state) = {+ let state = app.state::<crate::ArcLock<crate::App>>();+ let state = state.read().await;+ (+ state.camera_feed.clone(),+ state.camera_preview_state_tx.subscribe(),+ )+ };+ if !selection.current() || !crate::clean_capture::is_current(app, generation) {+ return Err("Recording or camera selection changed".into());+ }+ let nonce = uuid::Uuid::new_v4().to_string();+ let owner = PresentationOwner {+ nonce: nonce.clone(),+ generation,+ native,+ selection,+ state,+ };+ let broker = app.state::<PresentationBroker>();+ let (reply, rx) = tokio::sync::oneshot::channel();+ {+ let mut pending = broker.pending.lock().unwrap();+ if pending.is_some() {+ return Err("Camera presentation is already being measured".into());+ }+ *pending = Some(PendingPresentation {+ owner: owner.clone(),+ reply,+ });+ }+ let _guard = PendingGuard {+ pending: broker.pending.clone(),+ nonce: nonce.clone(),+ };+ CameraPresentationRequested {+ nonce,+ generation,+ camera_revision: snapshot.camera.revision.to_string(),+ }+ .emit_to(app, window.label())+ .map_err(|error| error.to_string())?;+ let input = tokio::time::timeout(Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Camera preview did not answer before the presentation deadline".to_string())?+ .map_err(|_| "Camera presentation was cancelled".to_string())??;+ owner.validate(app, native_snapshot(window).await?, &input)?;+ let (presentation, processing) = presentation_from_input(&input, native.rect, capture)?;+ Ok(PreparedPresentation {+ owner,+ actor,+ input,+ presentation,+ reference_size: (capture.width, capture.height),+ processing,+ })+}++#[cfg(target_os = "linux")]+fn processing(+ state: &CameraPreviewState,+) -> cap_recording::instant_recording::LinuxCameraProcessing {+ use cap_recording::instant_recording::{LinuxCameraBlur, LinuxCameraProcessing};+ LinuxCameraProcessing {+ mirrored: state.mirrored,+ blur: match state.background_blur {+ cap_project::BackgroundBlurMode::Off => LinuxCameraBlur::Off,+ cap_project::BackgroundBlurMode::Light => LinuxCameraBlur::Light,+ cap_project::BackgroundBlurMode::Heavy => LinuxCameraBlur::Heavy,+ },+ }+}++#[cfg(target_os = "linux")]+fn presentation_from_input(+ input: &CameraPresentationInput,+ window: PhysicalRect,+ capture: PhysicalRect,+) -> Result<+ (+ cap_recording::instant_recording::LinuxCameraPresentation,+ cap_recording::instant_recording::LinuxCameraProcessing,+ ),+ String,+> {+ use cap_recording::instant_recording::{+ LinuxCameraEffect, LinuxCameraPresentation, LinuxCameraRect, LinuxCameraShape,+ };+ if ![+ input.viewport_width,+ input.viewport_height,+ input.left,+ input.top,+ input.width,+ input.height,+ input.radius,+ ]+ .iter()+ .all(|value| value.is_finite())+ || input.viewport_width <= 0.0+ || input.viewport_height <= 0.0+ || input.width <= 0.0+ || input.height <= 0.0+ || input.left < 0.0+ || input.top < 0.0+ || input.radius < 0.0+ || input.left + input.width > input.viewport_width + 1.0+ || input.top + input.height > input.viewport_height + 1.0+ || window.width == 0+ || window.height == 0+ || !input.state.size.is_finite()+ || !(crate::camera::MIN_CAMERA_SIZE..=crate::camera::MAX_CAMERA_SIZE)+ .contains(&input.state.size)+ {+ return Err("Camera preview has invalid content bounds".into());+ }+ let sx = f64::from(window.width) / input.viewport_width;+ let sy = f64::from(window.height) / input.viewport_height;+ if (sx - sy).abs() > sx.min(sy) * 0.01 {+ return Err("Camera preview has an unsupported physical scale".into());+ }+ let left = f64::from(window.x) + (input.left * sx).round();+ let top = f64::from(window.y) + (input.top * sy).round();+ let right = f64::from(window.x) + ((input.left + input.width) * sx).round();+ let bottom = f64::from(window.y) + ((input.top + input.height) * sy).round();+ let x = left - f64::from(capture.x);+ let y = top - f64::from(capture.y);+ let width = right - left;+ let height = bottom - top;+ if x < 0.0+ || y < 0.0+ || width < 1.0+ || height < 1.0+ || x + width > f64::from(capture.width)+ || y + height > f64::from(capture.height)+ {+ return Err(+ "Move the whole camera preview inside the capture area before recording".into(),+ );+ }+ let width = width as u32;+ let height = height as u32;+ let shape = match input.state.shape {+ CameraPreviewShape::Round if width == height => LinuxCameraShape::Round,+ CameraPreviewShape::Round if width.abs_diff(height) <= 1 => {+ LinuxCameraShape::RoundedRectangle {+ radius_pixels: width.min(height) / 2,+ }+ }+ CameraPreviewShape::Round => return Err("Round camera preview is not square".into()),+ CameraPreviewShape::Square | CameraPreviewShape::Full => {+ LinuxCameraShape::RoundedRectangle {+ radius_pixels: ((input.radius * sx.min(sy)).round() as u32)+ .min(width.min(height) / 2),+ }+ }+ };+ let mut presentation = LinuxCameraPresentation {+ rect: LinuxCameraRect {+ x: x as u32,+ y: y as u32,+ width,+ height,+ },+ shape,+ mirrored: input.state.mirrored,+ effect: LinuxCameraEffect::None,+ };+ presentation+ .validate(capture.width, capture.height)+ .map_err(|error| error.to_string())?;+ if input.state.background_blur != cap_project::BackgroundBlurMode::Off {+ presentation.effect = LinuxCameraEffect::BackgroundBlur;+ }+ Ok((presentation, processing(&input.state)))+}++#[cfg(target_os = "linux")]+mod producer {+ use super::*;+ use cap_recording::{+ FFmpegVideoFrame,+ feeds::camera::{self, CameraFeed, CameraFeedLock},+ instant_recording::{+ LINUX_CAMERA_MAX_MASK_AGE, LinuxCameraBlur, LinuxCameraMaskReceipt,+ LinuxCameraProcessing, LinuxCameraPublisher, LinuxProcessedCameraFrame,+ LinuxProcessedCameraSource,+ },+ };+ use cap_timestamp::Timestamp;+ use kameo::actor::ActorRef;+ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};++ pub struct Reservation(Arc<AtomicBool>);++ impl Reservation {+ pub(super) fn acquire(active: &Arc<AtomicBool>) -> Option<Self> {+ active+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)+ .ok()+ .map(|_| Self(active.clone()))+ }+ }++ impl Drop for Reservation {+ fn drop(&mut self) {+ self.0.store(false, Ordering::Release);+ }+ }++ struct Attachment {+ actor: ActorRef<CameraFeed>,+ sender: flume::Sender<FFmpegVideoFrame>,+ runtime: tokio::runtime::Handle,+ _reservation: Reservation,+ }++ impl Drop for Attachment {+ fn drop(&mut self) {+ let actor = self.actor.clone();+ let sender = self.sender.clone();+ drop(self.runtime.spawn(async move {+ let _ = actor.ask(camera::RemoveSender(sender)).await;+ }));+ }+ }++ #[derive(Clone)]+ pub struct ProcessingFactory {+ commands: flume::Sender<Box<RecordingWork>>,+ reserved: Arc<AtomicBool>,+ generation: Arc<AtomicU64>,+ }++ pub(crate) fn channel() -> (ProcessingFactory, flume::Receiver<Box<RecordingWork>>) {+ let (commands, receiver) = flume::bounded(1);+ (+ ProcessingFactory {+ commands,+ reserved: Arc::new(AtomicBool::new(false)),+ generation: Arc::new(AtomicU64::new(0)),+ },+ receiver,+ )+ }++ impl ProcessingFactory {+ pub async fn subscribe(+ &self,+ feed: Arc<CameraFeedLock>,+ prepared: &PreparedPresentation,+ ) -> anyhow::Result<LinuxProcessedCameraSource> {+ let info = feed.camera_info();+ let matches = match &prepared.owner.selection.selected {+ camera::DeviceOrModelID::DeviceID(id) => info.device_id() == id,+ camera::DeviceOrModelID::ModelID(id) => info.model_id() == Some(id),+ };+ anyhow::ensure!(+ matches && feed.id() == prepared.actor.id(),+ "Processed camera does not match the requested camera lock"+ );+ anyhow::ensure!(+ prepared.owner.selection.current()+ && *prepared.owner.state.borrow() == prepared.input.state,+ "Camera request or appearance changed before recording"+ );+ let reservation = tokio::time::timeout(Duration::from_millis(1500), async {+ loop {+ if let Some(reservation) = Reservation::acquire(&self.reserved) {+ break reservation;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .map_err(|_| {+ anyhow::anyhow!("Previous camera processing has not released its lease")+ })?;+ let (sender, frames) = flume::bounded(2);+ let attachment = Attachment {+ actor: prepared.actor.clone(),+ sender: sender.clone(),+ runtime: tokio::runtime::Handle::current(),+ _reservation: reservation,+ };+ anyhow::ensure!(+ prepared.owner.selection.current(),+ "Camera selection changed while waiting for processing"+ );+ let generation = self.generation.fetch_add(1, Ordering::AcqRel) + 1;+ let not_before = Instant::now();+ let (publisher, mut source) = LinuxProcessedCameraSource::channel(+ feed.clone(),+ prepared.processing,+ generation,+ not_before,+ );+ tokio::time::timeout(+ Duration::from_millis(1500),+ feed.ask(camera::AddSender(sender)),+ )+ .await+ .map_err(|_| anyhow::anyhow!("Camera processing attachment timed out"))?+ .map_err(|error| anyhow::anyhow!("Camera processing attachment failed: {error}"))?;+ let work = RecordingWork {+ frames,+ publisher,+ state: prepared.input.state.clone(),+ selection: prepared.owner.selection.clone(),+ current_state: prepared.owner.state.clone(),+ generation,+ not_before,+ published: AtomicBool::new(false),+ _attachment: attachment,+ };+ tokio::time::timeout(+ Duration::from_millis(1500),+ self.commands.send_async(Box::new(work)),+ )+ .await+ .map_err(|_| anyhow::anyhow!("Camera processing command timed out"))?+ .map_err(|_| anyhow::anyhow!("Camera processing worker disconnected"))?;+ source.wait_ready(Duration::from_secs(10)).await?;+ anyhow::ensure!(+ prepared.owner.selection.current()+ && *prepared.owner.state.borrow() == prepared.input.state,+ "Camera request or appearance changed while processing warmed up"+ );+ Ok(source)+ }+ }++ #[derive(Clone, Debug)]+ pub(crate) struct FrameReceipt {+ pub timestamp: Timestamp,+ pub generation: u64,+ pub processing: LinuxCameraProcessing,+ pub dimensions: (u32, u32),+ pub blur: Option<cap_camera_effects::BlurOutputStatus>,+ }++ pub(crate) struct RecordingWork {+ pub frames: flume::Receiver<FFmpegVideoFrame>,+ publisher: LinuxCameraPublisher,+ pub state: CameraPreviewState,+ selection: SelectionGuard,+ current_state: tokio::sync::watch::Receiver<CameraPreviewState>,+ generation: u64,+ not_before: Instant,+ published: AtomicBool,+ _attachment: Attachment,+ }++ impl RecordingWork {+ pub fn cancelled(&self) -> bool {+ self.publisher.is_cancelled()+ }+ pub fn fail(&self, error: impl Into<String>) {+ self.publisher.fail(error.into());+ }+ pub fn accepts(&self, timestamp: Timestamp) -> Result<bool, String> {+ if !self.selection.current() || *self.current_state.borrow() != self.state {+ return Err("Requested camera or appearance changed during recording".into());+ }+ let Timestamp::Instant(captured) = timestamp else {+ return Err("Camera requires an original monotonic timestamp".into());+ };+ Ok(captured >= self.not_before)+ }+ pub fn receipt(&self, timestamp: Timestamp, dimensions: (u32, u32)) -> FrameReceipt {+ FrameReceipt {+ timestamp,+ generation: self.generation,+ processing: processing(&self.state),+ dimensions,+ blur: None,+ }+ }+ pub fn publish(&self, rgba: &[u8], receipt: FrameReceipt) {+ if self.cancelled() {+ return;+ }+ match self.accepts(receipt.timestamp) {+ Ok(true) => {}+ Ok(false) => return,+ Err(error) => {+ self.fail(error);+ return;+ }+ }+ let now = Instant::now();+ if !self.published.load(Ordering::Acquire)+ && matches!(receipt.timestamp, Timestamp::Instant(captured) if now.saturating_duration_since(captured)>Duration::from_secs(1))+ {+ return;+ }+ let result = make_processed_frame(+ rgba,+ receipt,+ self.generation,+ self.not_before,+ processing(&self.state),+ now,+ );+ match result {+ Ok(Some(frame)) => {+ self.publisher.publish(frame);+ self.published.store(true, Ordering::Release);+ }+ Ok(None) => {}+ Err(error) => self.fail(error),+ }+ }+ }++ pub(crate) fn make_processed_frame(+ rgba: &[u8],+ receipt: FrameReceipt,+ generation: u64,+ not_before: Instant,+ expected: LinuxCameraProcessing,+ now: Instant,+ ) -> Result<Option<LinuxProcessedCameraFrame>, String> {+ if receipt.generation != generation || receipt.processing != expected {+ return Err("Processed camera receipt belongs to another request".into());+ }+ let Timestamp::Instant(captured) = receipt.timestamp else {+ return Err("Processed camera timestamp is not monotonic".into());+ };+ if captured < not_before+ || captured > now+ || now.saturating_duration_since(captured) > Duration::from_secs(1)+ {+ return Err("Processed camera capture timestamp is stale or invalid".into());+ }+ let mask = match (expected.blur, receipt.blur) {+ (LinuxCameraBlur::Off, None) => None,+ (LinuxCameraBlur::Light | LinuxCameraBlur::Heavy, Some(status)) => {+ let mode = if expected.blur == LinuxCameraBlur::Light {+ cap_camera_effects::BlurMode::Light+ } else {+ cap_camera_effects::BlurMode::Heavy+ };+ match status.applied_at(now, LINUX_CAMERA_MAX_MASK_AGE) {+ Ok(applied)+ if applied.mode == mode+ && applied.output_dimensions == receipt.dimensions+ && applied.mask.input_submitted_at >= not_before+ && applied.mask.generation > 0 =>+ {+ Some(LinuxCameraMaskReceipt {+ generation: applied.mask.generation,+ submitted_at: applied.mask.input_submitted_at,+ completed_at: applied.mask.inference_completed_at,+ })+ }+ Err(cap_camera_effects::BlurOutputUnavailable::Pending) => return Ok(None),+ other => {+ return Err(format!("Requested camera blur was not applied: {other:?}"));+ }+ }+ }+ _ => return Err("Requested camera blur has no matching output receipt".into()),+ };+ let (width, height) = receipt.dimensions;+ let row = (width as usize)+ .checked_mul(4)+ .ok_or("Camera row overflow")?;+ let size = row+ .checked_mul(height as usize)+ .ok_or("Camera image overflow")?;+ if width == 0 || height == 0 || rgba.len() != size {+ return Err("Camera pixels do not match their receipt".into());+ }+ let mut bgra = vec![0; size];+ for (source, destination) in rgba.chunks_exact(row).zip(bgra.chunks_exact_mut(row)) {+ for (x, pixel) in destination.chunks_exact_mut(4).enumerate() {+ let source_x = if expected.mirrored {+ width as usize - 1 - x+ } else {+ x+ };+ let source = &source[source_x * 4..source_x * 4 + 4];+ pixel.copy_from_slice(&[source[2], source[1], source[0], source[3]]);+ }+ }+ Ok(Some(LinuxProcessedCameraFrame {+ bgra: Arc::from(bgra),+ dimensions: receipt.dimensions,+ stride: row,+ timestamp: receipt.timestamp,+ generation,+ processing: expected,+ mask,+ }))+ }+}++#[cfg(target_os = "linux")]+pub use producer::ProcessingFactory;+#[cfg(target_os = "linux")]+pub(crate) use producer::{FrameReceipt, RecordingWork, channel as processing_channel};++#[cfg(all(test, target_os = "linux"))]+mod tests {+ use super::*;+ use cap_recording::instant_recording::{LinuxCameraBlur, LinuxCameraProcessing};+ use cap_timestamp::Timestamp;++ fn input() -> CameraPresentationInput {+ CameraPresentationInput {+ viewport_width: 230.0,+ viewport_height: 286.0,+ left: 0.0,+ top: 56.0,+ width: 230.0,+ height: 230.0,+ radius: 115.0,+ layout_revision: 1,+ state: CameraPreviewState::default(),+ }+ }++ #[test]+ fn camera_content_excludes_toolbar_and_preserves_physical_position() {+ let window = PhysicalRect {+ x: -1200,+ y: 100,+ width: 460,+ height: 572,+ };+ let capture = PhysicalRect {+ x: -1920,+ y: 0,+ width: 1920,+ height: 1080,+ };+ let (presentation, _) = presentation_from_input(&input(), window, capture).unwrap();+ assert_eq!(presentation.rect.x, 720);+ assert_eq!(presentation.rect.y, 212);+ assert_eq!(+ (presentation.rect.width, presentation.rect.height),+ (460, 460)+ );+ }++ #[test]+ fn presentation_rejects_outside_capture_ambiguous_scale_and_invalid_geometry() {+ let capture = PhysicalRect {+ x: 0,+ y: 0,+ width: 1920,+ height: 1080,+ };+ assert!(+ presentation_from_input(+ &input(),+ PhysicalRect {+ x: 1800,+ y: 0,+ width: 230,+ height: 286+ },+ capture+ )+ .is_err()+ );+ assert!(+ presentation_from_input(+ &input(),+ PhysicalRect {+ x: 0,+ y: 0,+ width: 460,+ height: 286+ },+ capture+ )+ .is_err()+ );+ let mut invalid = input();+ invalid.width = f64::NAN;+ assert!(+ presentation_from_input(+ &invalid,+ PhysicalRect {+ x: 0,+ y: 0,+ width: 230,+ height: 286+ },+ capture+ )+ .is_err()+ );+ }++ #[test]+ fn full_shape_and_exact_effects_are_not_replaced_by_defaults() {+ let mut input = input();+ input.width = 460.0;+ input.viewport_width = 460.0;+ input.radius = 24.0;+ input.state.shape = CameraPreviewShape::Full;+ input.state.mirrored = true;+ input.state.background_blur = cap_project::BackgroundBlurMode::Heavy;+ let (presentation, processing) = presentation_from_input(+ &input,+ PhysicalRect {+ x: 20,+ y: 30,+ width: 460,+ height: 286,+ },+ PhysicalRect {+ x: 0,+ y: 0,+ width: 1920,+ height: 1080,+ },+ )+ .unwrap();+ assert_eq!(+ presentation.shape,+ cap_recording::instant_recording::LinuxCameraShape::RoundedRectangle {+ radius_pixels: 24+ }+ );+ assert_eq!(presentation.rect.width, 460);+ assert_eq!(+ processing,+ LinuxCameraProcessing {+ mirrored: true,+ blur: LinuxCameraBlur::Heavy+ }+ );+ }++ fn receipt(now: Instant) -> FrameReceipt {+ FrameReceipt {+ timestamp: Timestamp::Instant(now),+ generation: 3,+ processing: LinuxCameraProcessing {+ mirrored: true,+ blur: LinuxCameraBlur::Off,+ },+ dimensions: (2, 1),+ blur: None,+ }+ }++ #[test]+ fn recording_packs_rgba_to_bgra_and_mirrors_already_processed_pixels_once() {+ let now = Instant::now();+ let receipt = receipt(now);+ let expected = receipt.processing;+ let frame = producer::make_processed_frame(+ &[1, 2, 3, 255, 4, 5, 6, 128],+ receipt,+ 3,+ now,+ expected,+ now,+ )+ .unwrap()+ .unwrap();+ assert_eq!(&*frame.bgra, &[6, 5, 4, 128, 3, 2, 1, 255]);+ assert_eq!(frame.generation, 3);+ assert_eq!(frame.dimensions, (2, 1));+ }++ #[test]+ fn recording_rejects_old_generation_old_capture_and_missing_requested_blur() {+ let now = Instant::now();+ let original = receipt(now);+ assert!(+ producer::make_processed_frame(+ &[0; 8],+ original.clone(),+ 4,+ now,+ original.processing,+ now+ )+ .is_err()+ );+ assert!(+ producer::make_processed_frame(+ &[0; 8],+ original.clone(),+ 3,+ now + Duration::from_millis(1),+ original.processing,+ now+ )+ .is_err()+ );+ assert!(+ producer::make_processed_frame(+ &[0; 8],+ original.clone(),+ 3,+ now,+ original.processing,+ now + Duration::from_secs(2)+ )+ .is_err()+ );+ let mut blurred = original;+ blurred.processing.blur = LinuxCameraBlur::Light;+ let expected = blurred.processing;+ assert!(producer::make_processed_frame(&[0; 8], blurred, 3, now, expected, now).is_err());+ }++ #[test]+ fn pending_failed_wrong_mode_and_stale_masks_never_become_recorded_raw_frames() {+ use cap_camera_effects::{+ BlurFailure, BlurMaskReceipt, BlurMaskStatus, BlurMode, BlurOutputStatus,+ };+ let now = Instant::now();+ let mut receipt = receipt(now);+ receipt.processing.blur = LinuxCameraBlur::Heavy;+ let expected = receipt.processing;+ let mut status = BlurOutputStatus {+ mode: BlurMode::Heavy,+ output_sequence: 1,+ output_dimensions: (2, 1),+ mask: BlurMaskStatus::Pending,+ };+ receipt.blur = Some(status.clone());+ assert!(+ producer::make_processed_frame(&[0; 8], receipt.clone(), 3, now, expected, now)+ .unwrap()+ .is_none()+ );+ status.mask = BlurMaskStatus::Failed(BlurFailure::Inference("failed".into()));+ receipt.blur = Some(status.clone());+ assert!(+ producer::make_processed_frame(&[0; 8], receipt.clone(), 3, now, expected, now)+ .is_err()+ );+ status.mask = BlurMaskStatus::Ready(BlurMaskReceipt {+ generation: 1,+ input_submitted_at: now,+ inference_completed_at: now,+ input_dimensions: (2, 1),+ });+ status.mode = BlurMode::Light;+ receipt.blur = Some(status.clone());+ assert!(+ producer::make_processed_frame(&[0; 8], receipt.clone(), 3, now, expected, now)+ .is_err()+ );+ status.mode = BlurMode::Heavy;+ receipt.blur = Some(status);+ assert!(+ producer::make_processed_frame(&[0; 8], receipt.clone(), 3, now, expected, now)+ .unwrap()+ .is_some()+ );+ assert!(+ producer::make_processed_frame(+ &[0; 8],+ receipt,+ 3,+ now,+ expected,+ now + Duration::from_millis(751)+ )+ .is_err()+ );+ }++ #[tokio::test]+ async fn presentation_request_cancellation_only_releases_owned_nonce() {+ let pending = Arc::new(Mutex::new(None));+ let inputs = Arc::new(Mutex::new(crate::RequestedInputs {+ microphone: crate::RequestedInput::new(None),+ camera: crate::RequestedInput::new(Some(+ cap_recording::feeds::camera::DeviceOrModelID::DeviceID("camera-a".into()),+ )),+ }));+ let (_, state) = tokio::sync::watch::channel(CameraPreviewState::default());+ let owner = PresentationOwner {+ nonce: "new".into(),+ generation: 2,+ native: NativeSnapshot {+ id: 1,+ rect: PhysicalRect {+ x: 0,+ y: 0,+ width: 230,+ height: 286,+ },+ },+ selection: SelectionGuard {+ inputs,+ revision: 0,+ selected: cap_recording::feeds::camera::DeviceOrModelID::DeviceID(+ "camera-a".into(),+ ),+ },+ state,+ };+ let (reply, received) = tokio::sync::oneshot::channel();+ *pending.lock().unwrap() = Some(PendingPresentation { owner, reply });+ drop(PendingGuard {+ pending: pending.clone(),+ nonce: "old".into(),+ });+ assert!(pending.lock().unwrap().is_some());+ drop(PendingGuard {+ pending: pending.clone(),+ nonce: "new".into(),+ });+ assert!(received.await.is_err());+ assert!(pending.lock().unwrap().is_none());+ }++ #[test]+ fn camera_request_revision_guard_does_not_rewrite_input_intent() {+ let state = crate::RequestedInputsState::new(+ None,+ Some(cap_recording::feeds::camera::DeviceOrModelID::DeviceID(+ "camera-a".into(),+ )),+ );+ let guard = SelectionGuard {+ inputs: state.inner.clone(),+ revision: 0,+ selected: cap_recording::feeds::camera::DeviceOrModelID::DeviceID("camera-a".into()),+ };+ assert!(guard.current());+ let revision = state.inner.lock().unwrap().camera.begin(None);+ assert!(!guard.current());+ state.inner.lock().unwrap().camera.finish(revision, &Ok(()));+ assert!(!guard.current());+ assert!(state.snapshot().camera.value.is_none());+ }++ #[tokio::test]+ async fn recording_reservation_excludes_another_attempt_until_owned_drop() {+ use std::sync::atomic::{AtomicBool, Ordering};+ let active = Arc::new(AtomicBool::new(false));+ let first = producer::Reservation::acquire(&active).unwrap();+ let next_active = active.clone();+ let (blocked, seen) = tokio::sync::oneshot::channel();+ let (release, ready) = tokio::sync::oneshot::channel();+ let next = tokio::spawn(async move {+ assert!(producer::Reservation::acquire(&next_active).is_none());+ blocked.send(()).unwrap();+ ready.await.unwrap();+ producer::Reservation::acquire(&next_active).unwrap()+ });+ seen.await.unwrap();+ assert!(active.load(Ordering::Acquire));+ drop(first);+ release.send(()).unwrap();+ let next = next.await.unwrap();+ assert!(active.load(Ordering::Acquire));+ drop(next);+ assert!(!active.load(Ordering::Acquire));+ }+}diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex 84fe5ecc0..ac7a169f6 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -9,6 +9,14 @@ use tracing_subscriber::{Layer, layer::SubscriberExt, util::SubscriberInitExt};const TOKIO_WORKER_THREAD_STACK_SIZE: usize = 16 * 1024 * 1024;fn main() {+ #[cfg(target_os = "linux")]+ if let Some(threads) = cap_utils::linux_runtime::llvmpipe_thread_count() {+ // Mesa counts host CPUs inside containers; configure it before spawning threads or bundled children.+ unsafe {+ std::env::set_var("LP_NUM_THREADS", threads.to_string());+ }+ }+#[cfg(target_os = "linux")]if let Some(config) = cap_utils::linux_package::appimage_alsa_config_path() {// Configure ALSA before starting threads or handing off to a bundled child process.diff --git a/apps/desktop/src-tauri/src/power_observer.rs b/apps/desktop/src-tauri/src/power_observer.rsindex 71e354470..4bf8e0b7f 100644--- a/apps/desktop/src-tauri/src/power_observer.rs+++ b/apps/desktop/src-tauri/src/power_observer.rs@@ -1,5 +1,6 @@use std::sync::atomic::{AtomicBool, Ordering};use tauri::AppHandle;+#[cfg(any(target_os = "macos", target_os = "windows"))]use tracing::info;static SYSTEM_ASLEEP: AtomicBool = AtomicBool::new(false);@@ -8,19 +9,23 @@ pub fn is_system_asleep() -> bool {SYSTEM_ASLEEP.load(Ordering::Acquire)}+#[cfg(any(target_os = "macos", target_os = "windows"))]fn mark_sleeping() {SYSTEM_ASLEEP.store(true, Ordering::Release);}+#[cfg(any(target_os = "macos", target_os = "windows"))]fn mark_awake() {SYSTEM_ASLEEP.store(false, Ordering::Release);}+#[cfg(any(target_os = "macos", target_os = "windows"))]pub fn on_system_will_sleep(_app: &AppHandle) {mark_sleeping();info!("System going to sleep");}+#[cfg(any(target_os = "macos", target_os = "windows"))]pub fn on_system_did_wake(app: &AppHandle) {mark_awake();info!("System woke from sleep; scheduling recovery refresh");diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 1e0743a6b..66769212e 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -72,13 +72,16 @@ use crate::{open_external_link,presets::PresetsStore,thumbnails::*,- upload::{InstantMultipartUpload, SegmentUploader, compress_image},+ upload::{SegmentUploader, compress_image},web_api::ManagerExt,windows::{CapWindowId, EditorRecordingTarget, ShowCapWindow, editor_window_for_path, hide_overlay,},};+#[cfg(not(target_os = "linux"))]+use crate::upload::InstantMultipartUpload;+fn recording_stopped_share_url(link: &str) -> String {if link.contains('?') {format!("{link}&recordingStopped=1")@@ -589,15 +592,40 @@ pub struct InProgressRecordingCommon {pub health: Arc<crate::recording_telemetry::RecordingHealthAccumulator>,}+#[cfg(target_os = "linux")]+type InstantUploader = Arc<tokio::sync::Mutex<SegmentUploader>>;+#[cfg(not(target_os = "linux"))]+type InstantUploader = SegmentUploader;++async fn await_instant_upload(+ upload: InstantUploader,+) -> Result<Result<(), AuthedApiError>, String> {+ #[cfg(target_os = "linux")]+ {+ (&mut upload.lock().await.handle)+ .await+ .map_err(|error| error.to_string())+ }+ #[cfg(not(target_os = "linux"))]+ {+ upload.handle.await.map_err(|error| error.to_string())+ }+}+pub struct StopFailureContext {- pub segment_upload: SegmentUploader,+ pub segment_upload: InstantUploader,pub video_upload_info: VideoUploadInfo,}+#[cfg(target_os = "linux")]+type InstantActorHandle = Arc<instant_recording::ActorHandle>;+#[cfg(not(target_os = "linux"))]+type InstantActorHandle = instant_recording::ActorHandle;+pub enum InProgressRecording {Instant {- handle: instant_recording::ActorHandle,- segment_upload: SegmentUploader,+ handle: InstantActorHandle,+ segment_upload: InstantUploader,video_upload_info: VideoUploadInfo,common: InProgressRecordingCommon,mic_feed: Option<Arc<microphone::MicrophoneFeedLock>>,@@ -717,14 +745,38 @@ impl InProgressRecording {pub async fn pause(&self) -> anyhow::Result<()> {match self {- Self::Instant { handle, .. } => handle.pause().await,+ Self::Instant { handle, .. } => {+ #[cfg(target_os = "linux")]+ {+ let _ = handle;+ Err(anyhow!(+ "Instant recordings cannot pause or resume; use Stop"+ ))+ }+ #[cfg(not(target_os = "linux"))]+ {+ handle.pause().await+ }+ }Self::Studio { handle, .. } => handle.pause().await,}}pub async fn resume(&self) -> anyhow::Result<()> {match self {- Self::Instant { handle, .. } => handle.resume().await,+ Self::Instant { handle, .. } => {+ #[cfg(target_os = "linux")]+ {+ let _ = handle;+ Err(anyhow!(+ "Instant recordings cannot pause or resume; use Stop"+ ))+ }+ #[cfg(not(target_os = "linux"))]+ {+ handle.resume().await+ }+ }Self::Studio { handle, .. } => handle.resume().await,}}@@ -755,6 +807,8 @@ impl InProgressRecording {..} => match handle.stop().await {Ok(recording) => Ok(CompletedRecording::Instant {+ #[cfg(target_os = "linux")]+ finalized: false,recording,segment_upload,video_upload_info,@@ -788,7 +842,16 @@ impl InProgressRecording {pub fn take_health_rx(&mut self) -> Option<cap_recording::HealthReceiver> {match self {- Self::Instant { handle, .. } => handle.take_health_rx(),+ Self::Instant { handle, .. } => {+ #[cfg(target_os = "linux")]+ {+ Arc::get_mut(handle).and_then(instant_recording::ActorHandle::take_health_rx)+ }+ #[cfg(not(target_os = "linux"))]+ {+ handle.take_health_rx()+ }+ }Self::Studio { .. } => None,}}@@ -810,9 +873,11 @@ impl InProgressRecording {pub enum CompletedRecording {Instant {+ #[cfg(target_os = "linux")]+ finalized: bool,recording: instant_recording::CompletedRecording,target_name: String,- segment_upload: SegmentUploader,+ segment_upload: InstantUploader,video_upload_info: VideoUploadInfo,},Studio {@@ -1173,13 +1238,43 @@ pub enum RecordingAction {const MICROPHONE_INPUT_PROBE_TIMEOUT: Duration = Duration::from_millis(1500);const CAMERA_INPUT_PROBE_TIMEOUT: Duration = Duration::from_millis(1500);-fn camera_id_label(id: &camera::DeviceOrModelID) -> String {+pub(crate) fn camera_id_label(id: &camera::DeviceOrModelID) -> String {match id {camera::DeviceOrModelID::DeviceID(device_id) => device_id.clone(),camera::DeviceOrModelID::ModelID(model_id) => format!("{model_id:?}"),}}+fn validate_selected_camera_for_start(+ selected_id: Option<&camera::DeviceOrModelID>,+ is_available: impl FnOnce(&camera::DeviceOrModelID) -> bool,+) -> anyhow::Result<()> {+ if let Some(id) = selected_id+ && !is_available(id)+ {+ return Err(anyhow!(+ "Selected camera '{}' is no longer available. Reconnect it or choose another camera before recording.",+ camera_id_label(id)+ ));+ }+ Ok(())+}++fn selected_microphone_for_start(+ selected_label: Option<String>,+ available_names: &[String],+) -> anyhow::Result<Option<String>> {+ let Some(label) = selected_label else {+ return Ok(None);+ };+ if !available_names.contains(&label) {+ return Err(anyhow!(+ "Selected microphone '{label}' is no longer available. Reconnect it or choose another microphone before recording."+ ));+ }+ Ok(Some(label))+}+fn camera_lock_matches_id(lock: &CameraFeedLock, selected_id: &camera::DeviceOrModelID) -> bool {let camera_info = lock.camera_info();match selected_id {@@ -1216,7 +1311,10 @@ async fn lock_initialized_camera() -> anyhow::Result<CameraFeedLock> {let label = camera_id_label(id);match camera_feed.ask(camera::Lock).await {- Ok(lock) => Ok(lock),+ Ok(lock) if camera_lock_matches_id(&lock, id) => Ok(lock),+ Ok(_) => Err(anyhow!(+ "Selected camera '{label}' changed during initialization. Select the camera again before recording."+ )),Err(kameo::error::SendError::HandlerError(camera::LockFeedError::NoInput)) => Err(anyhow!("Selected camera '{label}' did not become ready after initialization")),@@ -1360,7 +1458,10 @@ async fn lock_initialized_microphone(label: &str,) -> anyhow::Result<microphone::MicrophoneFeedLock> {match mic_feed.ask(microphone::Lock).await {- Ok(lock) => Ok(lock),+ Ok(lock) if lock.device_name() == label => Ok(lock),+ Ok(_) => Err(anyhow!(+ "Selected microphone '{label}' changed during initialization. Select the microphone again before recording."+ )),Err(kameo::error::SendError::HandlerError(microphone::LockFeedError::NoInput)) => Err(anyhow!("Selected microphone '{label}' did not become ready after initialization"),),@@ -1495,24 +1596,111 @@ pub async fn start_recording(app: AppHandle,state_mtx: MutableState<'_, App>,inputs: StartRecordingInputs,+) -> Result<RecordingAction, String> {+ #[cfg(target_os = "linux")]+ if inputs.mode != RecordingMode::Instant && linux_instant::current(&app).is_some() {+ return Err("Finish the pending Instant cleanup before recording".into());+ }+ #[cfg(target_os = "linux")]+ if inputs.mode == RecordingMode::Instant && EditorRecordingTarget::current(&app).is_none() {+ return linux_instant::start(app, state_mtx, inputs).await;+ }+ start_recording_inner(app, state_mtx, inputs).await+}++async fn start_recording_inner(+ app: AppHandle,+ state_mtx: MutableState<'_, App>,+ inputs: StartRecordingInputs,) -> Result<RecordingAction, String> {let mut inputs = inputs;- if EditorRecordingTarget::current(&app).is_some() {+ #[cfg(target_os = "linux")]+ let has_instant_owner = linux_instant::current(&app).is_some();+ #[cfg(not(target_os = "linux"))]+ let has_instant_owner = false;+ if EditorRecordingTarget::current(&app).is_some() && !has_instant_owner {inputs.mode = RecordingMode::Studio;}+ let requested_state = app.state::<crate::RequestedInputsState>();+ let requested_inputs = match requested_state.ready_snapshot() {+ Ok(snapshot) => snapshot,+ Err(error) => {+ notify_recording_start_failed(&app, &error);+ return Err(error);+ }+ };+ #[cfg(target_os = "linux")]+ linux_instant::validate_screen_request(&inputs, &requested_inputs).inspect_err(|error| {+ notify_recording_start_failed(&app, error);+ })?;+ let clean_generation = crate::clean_capture::prepare(&app, &inputs, None)+ .await+ .inspect_err(|error| {+ notify_recording_start_failed(&app, error);+ })?;+ let result = start_recording_prepared(+ app.clone(),+ state_mtx.clone(),+ inputs,+ requested_inputs,+ clean_generation,+ )+ .await;+ if !matches!(&result, Ok(RecordingAction::Started))+ && let Some(generation) = clean_generation+ && crate::clean_capture::is_current(&app, generation)+ {+ state_mtx.write().await.clear_pending_recording();+ crate::clean_capture::release(&app, generation, false);+ }+ result+}++async fn start_recording_prepared(+ app: AppHandle,+ state_mtx: MutableState<'_, App>,+ mut inputs: StartRecordingInputs,+ requested_inputs: crate::RequestedInputs,+ clean_generation: Option<u32>,+) -> Result<RecordingAction, String> {+ let requested_state = app.state::<crate::RequestedInputsState>();+ let mut _input_operation = Some(requested_state.operation.lock().await);+ if let Err(error) = requested_state.ready_snapshot() {+ notify_recording_start_failed(&app, &error);+ return Err(error);+ }+ if !requested_state.is_current(&requested_inputs) {+ let error = "Input selection changed before recording could start. Try recording again."+ .to_string();+ notify_recording_start_failed(&app, &error);+ return Err(error);+ }+let is_camera_only = matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly);+ #[cfg(target_os = "linux")]+ linux_instant::validate_inputs(&inputs)?;+if is_camera_only {inputs.capture_system_audio = false;}{let mut app_state = state_mtx.write().await;- if let Err(error) =+ let pending_result = if let Some(generation) = clean_generation {+ if crate::clean_capture::is_current(&app, generation)+ && matches!(app_state.recording_state, RecordingState::Pending { .. })+ {+ Ok(())+ } else {+ Err("Recording preflight was cancelled or superseded".to_string())+ }+ } else {app_state.set_pending_recording(inputs.mode, inputs.capture_target.clone())- {+ };+ if let Err(error) = pending_result {drop(app_state);// Deliberately no clear_pending_recording: the pending/active state that// caused the refusal belongs to another recording and must survive.@@ -1524,6 +1712,10 @@ pub async fn start_recording(}}+ if cfg!(target_os = "linux") && inputs.mode == RecordingMode::Instant {+ drop(_input_operation.take());+ }+let instant_auth = if matches!(inputs.mode, RecordingMode::Instant) {AuthStore::get(&app).ok().flatten()} else {@@ -1621,10 +1813,22 @@ pub async fn start_recording(cap_utils::ensure_unique_filename(&filename, &recordings_base_dir,),|e| e));+ #[cfg(target_os = "linux")]+ if inputs.mode == RecordingMode::Instant+ && let Some(attempt) = linux_instant::current(&app)+ {+ attempt.set_directory(project_file_path.clone());+ if attempt.cancelled() {+ return Err("Instant startup cancelled".into());+ }+ }pending_try!(ensure_dir(&project_file_path), |e| format!("Failed to create recording directory: {e}"));+ if let Some(generation) = clean_generation {+ crate::clean_capture::set_start_directory(&app, generation, project_file_path.clone())?;+ }pending_try!(state_mtx.write()@@ -1754,42 +1958,44 @@ pub async fn start_recording("Failed to save recording meta: {e}"));- match &inputs.capture_target {- ScreenCaptureTarget::Window { id: _id } => {- if let Some(show) = inputs- .capture_target- .display()- .map(|d| ShowCapWindow::WindowCaptureOccluder { screen_id: d.id() })- {- let _ = show.show(&app).await;+ if clean_generation.is_none() {+ match &inputs.capture_target {+ ScreenCaptureTarget::Window { id: _id } => {+ if let Some(show) = inputs+ .capture_target+ .display()+ .map(|d| ShowCapWindow::WindowCaptureOccluder { screen_id: d.id() })+ {+ let _ = show.show(&app).await;+ }}- }- ScreenCaptureTarget::Area { screen, .. } => {- let _ = ShowCapWindow::WindowCaptureOccluder {- screen_id: screen.clone(),+ ScreenCaptureTarget::Area { screen, .. } => {+ let _ = ShowCapWindow::WindowCaptureOccluder {+ screen_id: screen.clone(),+ }+ .show(&app)+ .await;}- .show(&app)- .await;+ _ => {}}- _ => {}}-let countdown = general_settings.and_then(|v| v.recording_countdown);crate::target_select_overlay::close_target_select_overlay_windows(&app);- let _ = ShowCapWindow::InProgressRecording {- countdown,- capture_target: Some(inputs.capture_target.clone()),- }- .show(&app)- .await;+ if clean_generation.is_none() {+ let _ = ShowCapWindow::InProgressRecording {+ countdown,+ capture_target: Some(inputs.capture_target.clone()),+ }+ .show(&app)+ .await;- if let Some(window) = CapWindowId::Main.get(&app) {- let _ = general_settings- .map(|v| v.main_window_recording_start_behaviour)- .unwrap_or_default()- .perform(&window);+ if let Some(window) = CapWindowId::Main.get(&app) {+ let _ = general_settings+ .map(|v| v.main_window_recording_start_behaviour)+ .unwrap_or_default()+ .perform(&window);+ }}-crate::windows::apply_content_protection(&app, true);if let Some(editor_target) = EditorRecordingTarget::current(&app)@@ -1801,15 +2007,35 @@ pub async fn start_recording(if let Some(countdown) = countdown {for t in 0..countdown {+ #[cfg(target_os = "linux")]+ if inputs.mode == RecordingMode::Instant+ && linux_instant::current(&app).is_none_or(|attempt| attempt.cancelled())+ {+ return Err("Instant startup cancelled".into());+ }let _ = RecordingEvent::Countdown {value: countdown - t,}.emit(&app);tokio::time::sleep(Duration::from_secs(1)).await;+ if clean_generation+ .is_some_and(|generation| crate::clean_capture::stop_requested(&app, generation))+ {+ return Err("Recording cancelled".into());+ }}}let (finish_upload_tx, finish_upload_rx) = flume::bounded(1);+ #[cfg(target_os = "linux")]+ drop(finish_upload_rx);++ if _input_operation.is_none() {+ _input_operation = Some(requested_state.operation.lock().await);+ if !requested_state.is_current(&requested_inputs) {+ return Err("Input selection changed during startup".into());+ }+ }debug!("spawning start_recording actor");@@ -1824,41 +2050,24 @@ pub async fn start_recording(let (camera_feed_actor, selected_camera_id, selected_camera_settings) = {let state = state_mtx.read().await;- let selected_camera_settings = state.selected_camera_id.as_ref().and_then(|id| {- crate::recording_settings::RecordingSettingsStore::camera_settings_for(- &state.handle,- id,- )- });+ let selected_camera_settings =+ requested_inputs.camera.value.as_ref().and_then(|id| {+ crate::recording_settings::RecordingSettingsStore::camera_settings_for(+ &state.handle,+ id,+ )+ });(state.camera_feed.clone(),- state.selected_camera_id.clone(),+ requested_inputs.camera.value.clone(),selected_camera_settings,)};- // A remembered camera that isn't connected must not abort the- // recording (camera-only mode excepted, where it's required):- // degrade to no-camera and tell the user once.- let selected_camera_id = match selected_camera_id {- Some(id)- if !matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly)- && !crate::is_camera_available(&id) =>- {- warn!(- camera = %camera_id_label(&id),- "Selected camera is not connected; recording without camera"- );- let _ = crate::NewNotification {- title: "Recording without camera".to_string(),- body: "The selected camera is not connected, so this recording won't include it.".to_string(),- is_error: true,- }- .emit(&app_handle);- None- }- other => other,- };+ validate_selected_camera_for_start(+ selected_camera_id.as_ref(),+ crate::is_camera_available,+ )?;let camera_feed = lock_selected_camera(&camera_feed_actor,@@ -1872,9 +2081,7 @@ pub async fn start_recording("Selected camera locked for recording");- let mut state = state_mtx.write().await;-- state.camera_in_use = camera_feed.is_some();+ let has_camera_feed = camera_feed.is_some();#[cfg(target_os = "macos")]let mut shareable_content = match inputs.capture_target {@@ -1943,43 +2150,35 @@ pub async fn start_recording(let (done_fut, health_rx) = loop {let actor_result: Result<InProgressRecording, anyhow::Error> = async {- // Resolve the remembered microphone against the connected- // devices (fuzzy-matching Bluetooth profile renames like the- // reconnect watcher does). A missing microphone must not- // abort the recording: degrade and tell the user once.- let selected_mic_label = match state.selected_mic_label.clone() {- Some(label) => {- let matched = crate::find_mic_by_label_or_fuzzy(- µphone::MicrophoneFeed::list_names(),- &label,- );- if matched.is_none() {- warn!(- mic = %label,- "Selected microphone is not connected; recording without microphone"- );- let _ = crate::NewNotification {- title: "Recording without microphone".to_string(),- body: format!(- "Microphone '{label}' is not connected, so this recording won't include it."- ),- is_error: true,- }- .emit(&app_handle);- }- matched- }+ if !app_handle+ .state::<crate::RequestedInputsState>()+ .is_current(&requested_inputs)+ {+ return Err(anyhow!(+ "Input selection changed during recording startup. Try recording again."+ ));+ }+ let selected_mic_label = match requested_inputs.microphone.value.clone() {+ Some(label) => selected_microphone_for_start(+ Some(label),+ µphone::MicrophoneFeed::list_names(),+ )?,None => None,};- let selected_mic_settings = selected_mic_label- .as_ref()- .and_then(|label| state.microphone_settings_for_label(label));+ let (mic_actor, selected_mic_settings) = {+ let mut state = state_mtx.write().await;+ let settings = selected_mic_label+ .as_ref()+ .and_then(|label| state.microphone_settings_for_label(label));+ state.applied_mic_input.invalidate();+ (state.mic_feed.clone(), settings)+ };debug!(mic_selected = selected_mic_label.is_some(),"Locking selected microphone for recording");let mic_feed = lock_selected_microphone(- &state.mic_feed,+ &mic_actor,selected_mic_label,selected_mic_settings,)@@ -2060,6 +2259,38 @@ pub async fn start_recording(builder = builder.with_mic_feed(mic_feed);}+ #[cfg(target_os = "linux")]+ let attempt = linux_instant::current(&app_handle)+ .ok_or_else(|| anyhow!("Instant startup owner was lost"))?;+ #[cfg(target_os = "linux")]+ attempt+ .attach(recording_dir.clone(), builder.lifecycle())+ .await+ .map_err(anyhow::Error::msg)?;+ #[cfg(target_os = "linux")]+ {+ let prepared = match clean_generation {+ Some(generation) => linux_instant::prepare_screen_camera(+ &app_handle,+ &attempt,+ generation,+ &inputs,+ &requested_inputs,+ camera_feed.clone(),+ )+ .await+ .map_err(anyhow::Error::msg)?,+ None => None,+ };+ builder = linux_instant::configure_screen_camera(+ builder,+ &inputs.capture_target,+ requested_inputs.camera.value.is_some(),+ prepared,+ )+ .map_err(anyhow::Error::msg)?;+ attempt.checked(Ok(())).map_err(anyhow::Error::msg)?;+ }let handle = builder.build(#[cfg(target_os = "macos")]@@ -2071,27 +2302,53 @@ pub async fn start_recording(e})?;- let segment_rx = handle.take_segment_rx();-- let segment_upload = if let Some(rx) = segment_rx {- SegmentUploader::spawn(- app_handle.clone(),- video_upload_info.id.clone(),- rx,- Some(finish_upload_rx.clone()),- recording_dir.clone(),- video_upload_info.clone(),+ #[cfg(target_os = "linux")]+ let handle = Arc::new(handle);+ #[cfg(target_os = "linux")]+ let segment_upload = {+ let events = handle.take_segment_rx();+ linux_instant::persist_upload_start(+ &recording_dir,+ &video_upload_info,+ events.is_some(),)- } else {- let progressive_upload = InstantMultipartUpload::spawn(- app_handle.clone(),- recording_dir.join("content/output.mp4"),- video_upload_info.clone(),- recording_dir.clone(),- Some(finish_upload_rx.clone()),- );- SegmentUploader {- handle: progressive_upload.handle,+ .map_err(anyhow::Error::msg)?;+ attempt.upload_started();+ Arc::new(tokio::sync::Mutex::new(+ crate::upload::strict_instant::spawn(+ app_handle.clone(),+ recording_dir.clone(),+ video_upload_info.clone(),+ events,+ attempt.upload(),+ inputs.capture_system_audio || mic_feed.is_some(),+ ),+ ))+ };+ #[cfg(not(target_os = "linux"))]+ let segment_upload = {+ let segment_rx = handle.take_segment_rx();++ if let Some(rx) = segment_rx {+ SegmentUploader::spawn(+ app_handle.clone(),+ video_upload_info.id.clone(),+ rx,+ Some(finish_upload_rx.clone()),+ recording_dir.clone(),+ video_upload_info.clone(),+ )+ } else {+ let progressive_upload = InstantMultipartUpload::spawn(+ app_handle.clone(),+ recording_dir.join("content/output.mp4"),+ video_upload_info.clone(),+ recording_dir.clone(),+ Some(finish_upload_rx.clone()),+ );+ SegmentUploader {+ handle: progressive_upload.handle,+ }}};@@ -2113,9 +2370,58 @@ pub async fn start_recording(match actor_result {Ok(mut actor) => {+ let mut state = state_mtx.write().await;+ if clean_generation.is_some_and(|generation| {+ !crate::clean_capture::is_current(&app_handle, generation)+ }) || !matches!(state.recording_state, RecordingState::Pending { .. })+ {+ drop(state);+ let _ = cancel_discarded_recording(&app_handle, actor).await;+ return Err(anyhow!("Recording startup was cancelled or superseded"));+ }+ #[cfg(target_os = "linux")]+ if inputs.mode == RecordingMode::Instant+ && (linux_instant::current(&app_handle).is_none_or(|attempt| {+ attempt.cancelled() || !attempt.owns_directory(&recording_dir)+ }) || clean_generation.is_some_and(|generation| {+ crate::clean_capture::stop_requested(&app_handle, generation)+ }) || !app_handle+ .state::<crate::RequestedInputsState>()+ .is_current(&requested_inputs))+ {+ drop(state);+ let _ = cancel_discarded_recording(&app_handle, actor).await;+ return Err(anyhow!("Instant startup was cancelled"));+ }let done_fut = actor.done_fut();let health_rx = actor.take_health_rx();- state.set_current_recording(actor);+ let mut candidate = Some(actor);+ let published = app_handle+ .state::<crate::RequestedInputsState>()+ .publish_if_current(&requested_inputs, || {+ state.selected_mic_label =+ requested_inputs.microphone.value.clone();+ state.selected_camera_id = requested_inputs.camera.value.clone();+ state.camera_in_use = has_camera_feed;+ state.applied_mic_input.confirm();+ state.set_current_recording(candidate.take().unwrap());+ if let Some(generation) = clean_generation {+ crate::clean_capture::publish(+ &app_handle,+ generation,+ recording_dir.clone(),+ );+ }+ });+ if !published {+ drop(state);+ let _ =+ cancel_discarded_recording(&app_handle, candidate.take().unwrap())+ .await;+ return Err(anyhow!(+ "Input selection changed during recording startup. Try recording again."+ ));+ }break (done_fut, health_rx);}#[cfg(target_os = "macos")]@@ -2127,6 +2433,8 @@ pub async fn start_recording(}Err(err)if mic_restart_attempts < 3+ && !(inputs.mode == RecordingMode::Instant+ && clean_generation.is_some())&& (mic_actor_not_running(&err) || mic_feed_locked(&err)) =>{mic_restart_attempts += 1;@@ -2135,7 +2443,18 @@ pub async fn start_recording(error = %err,"Recovering microphone feed before retrying recording start");- state+ if clean_generation.is_some() {+ if mic_feed_locked(&err) {+ tokio::time::sleep(Duration::from_millis(50)).await;+ continue;+ }+ return Err(anyhow!(+ "The selected microphone stopped during startup. Reselect it before recording: {err:#}"+ ));+ }+ state_mtx+ .write()+ .await.restart_mic_feed().await.map_err(|restart_err| anyhow!(restart_err))?;@@ -2178,6 +2497,21 @@ pub async fn start_recording(}};+ drop(_input_operation);+ if clean_generation+ .is_some_and(|generation| crate::clean_capture::stop_requested(&app, generation))+ {+ #[cfg(target_os = "linux")]+ if inputs.mode == RecordingMode::Instant {+ if let Some(attempt) = linux_instant::current(&app) {+ attempt.cancel();+ }+ return Err("Instant startup cancelled".into());+ }+ Box::pin(stop_recording(app.clone(), state_mtx.clone())).await?;+ return Ok(RecordingAction::Started);+ }+if matches!(inputs.mode, RecordingMode::Studio) {spawn_current_desktop_background_snapshot(project_file_path.clone(),@@ -2194,10 +2528,56 @@ pub async fn start_recording(let app = app.clone();let state_mtx = Arc::clone(&state_mtx);let project_file_path = project_file_path.clone();+ #[cfg(any(target_os = "linux", windows))]+ let instant_watch = inputs.mode == RecordingMode::Instant;async move {fail!("recording::wait_actor_done");let disposition = {let res = actor_done_fut.await;+ #[cfg(target_os = "linux")]+ if instant_watch {+ if let Some(attempt) = linux_instant::current(&app)+ && attempt.owns_directory(&project_file_path)+ && attempt.terminal_needs_cleanup()+ {+ let _ = linux_instant::control(app.clone(), attempt, false).await;+ }+ return;+ }+ #[cfg(target_os = "linux")]+ if !instant_watch {+ let state = state_mtx.read().await;+ if let Some(InProgressRecording::Studio { handle, common, .. }) =+ state.current_recording()+ && common.recording_dir == project_file_path+ && handle.lifecycle().terminal_started()+ {+ return;+ }+ }+ #[cfg(windows)]+ if !instant_watch {+ let state = state_mtx.read().await;+ if let Some(InProgressRecording::Studio { handle, common, .. }) =+ state.current_recording()+ && common.recording_dir == project_file_path+ && handle.terminal_started()+ {+ return;+ }+ }+ if let Some(generation) = clean_generation+ && (crate::clean_capture::owner(&app, &project_file_path) != Some(generation)+ || matches!(+ crate::clean_capture::phase(&app),+ Some(+ crate::clean_capture::Phase::Stopping+ | crate::clean_capture::Phase::Restoring+ )+ ))+ {+ return;+ }info!("recording wait actor done: {:?}", &res);let recording_still_active = matches!(state_mtx.read().await.recording_state,@@ -2212,7 +2592,35 @@ pub async fn start_recording(}ActorDoneDisposition::UnexpectedStop { error }| ActorDoneDisposition::Failed { error } => {+ #[cfg(any(target_os = "linux", windows))]+ if !instant_watch {+ let _ = control_studio_recording(+ &app,+ &state_mtx,+ Some(&project_file_path),+ false,+ Some(error),+ )+ .await;+ return;+ }let mut state = state_mtx.write().await;+ if let Some(generation) = clean_generation+ && (crate::clean_capture::owner(&app, &project_file_path)+ != Some(generation)+ || state.current_recording().is_none_or(|recording| {+ recording.recording_dir() != &project_file_path+ })+ || matches!(+ crate::clean_capture::phase(&app),+ Some(+ crate::clean_capture::Phase::Stopping+ | crate::clean_capture::Phase::Restoring+ )+ ))+ {+ return;+ }let _ = RecordingEvent::Failed {error: error.clone(),@@ -2230,7 +2638,9 @@ pub async fn start_recording(dialog = dialog.parent(&window);}- dialog.blocking_show();+ if crate::clean_capture::phase(&app).is_none() {+ dialog.blocking_show();+ }handle_recording_end(app, Err(error), &mut state, project_file_path).await@@ -2439,6 +2849,9 @@ pub async fn start_recording(#[specta::specta]#[instrument(skip(app, state))]pub async fn pause_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {+ if crate::clean_capture::phase(&app).is_some() {+ return crate::clean_capture::control(&app, false).await;+ }let mut state = state.write().await;if let Some(recording) = state.current_recording_mut() {@@ -2453,7 +2866,14 @@ pub async fn pause_recording(app: AppHandle, state: MutableState<'_, App>) -> Re#[specta::specta]#[instrument(skip(app, state))]pub async fn resume_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {+ let requested = app.state::<crate::RequestedInputsState>();+ let _input_operation = requested.try_resume_guard()?;+ if crate::clean_capture::phase(&app).is_some() {+ requested.ensure_ready_for_resume()?;+ return crate::clean_capture::control(&app, true).await;+ }let mut state = state.write().await;+ requested.ensure_ready_for_resume()?;if let Some(recording) = state.current_recording_mut() {recording.resume().await.map_err(|e| e.to_string())?;@@ -2503,10 +2923,20 @@ pub async fn toggle_pause_recording(app: AppHandle,state: MutableState<'_, App>,) -> Result<(), String> {+ if crate::clean_capture::phase(&app).is_some() {+ if crate::clean_capture::is_paused(&app).await? {+ let requested = app.state::<crate::RequestedInputsState>();+ let _input_operation = requested.try_resume_guard()?;+ return crate::clean_capture::control(&app, true).await;+ }+ return crate::clean_capture::control(&app, false).await;+ }let state = state.read().await;if let Some(recording) = state.current_recording() {if recording.is_paused().await.map_err(|e| e.to_string())? {+ let requested = app.state::<crate::RequestedInputsState>();+ let _input_operation = requested.try_resume_guard()?;recording.resume().await.map_err(|e| e.to_string())?;RecordingEvent::Resumed.emit(&app).ok();} else {@@ -2524,6 +2954,11 @@ async fn handle_spawn_failure(recording_dir: &Path,message: String,) -> Result<(), String> {+ #[cfg(target_os = "linux")]+ if linux_instant::current(app).is_some_and(|attempt| attempt.owns_directory(recording_dir)) {+ notify_recording_start_failed(app, &message);+ return Err(message);+ }error!(recording_dir = %recording_dir.display(),error = %message,@@ -2540,7 +2975,7 @@ async fn handle_spawn_failure(let is_device_not_found =message.contains("no longer available") || message.contains("DeviceNotFound");- if !is_device_not_found {+ if !is_device_not_found && crate::clean_capture::phase(app).is_none() {let mut dialog = MessageDialogBuilder::new(app.dialog().clone(),"An error occurred".to_string(),@@ -2673,21 +3108,41 @@ async fn cancel_discarded_recording(..} => {let video_id = video_upload_info.id;- segment_upload.handle.abort();-- if let Err(err) = handle.cancel().await {- warn!("Failed to cancel instant recording while discarding: {err:#}");+ #[cfg(target_os = "linux")]+ {+ if let Some(attempt) = linux_instant::current(app) {+ attempt.cancel();+ }+ if let Err(error) = handle.cancel().await {+ warn!(%error, "Instant cancellation failed");+ }+ if handle.lifecycle().wait_for_quiescence().await+ != instant_recording::InstantQuiescence::Joined+ {+ return None;+ }+ if let Some(attempt) = linux_instant::current(app)+ && !attempt.upload_cleanup().await+ {+ return None;+ }+ let _ = await_instant_upload(segment_upload).await;}-- match segment_upload.handle.await {- Ok(Ok(())) => {}- Ok(Err(err)) => warn!("Instant upload ended while discarding recording: {err}"),- Err(err) if err.is_cancelled() => {}- Err(err) => {- warn!("Failed to join instant upload while discarding recording: {err}")+ #[cfg(not(target_os = "linux"))]+ {+ segment_upload.handle.abort();+ if let Err(err) = handle.cancel().await {+ warn!("Failed to cancel instant recording while discarding: {err:#}");+ }+ match segment_upload.handle.await {+ Ok(Ok(())) => {}+ Ok(Err(err)) => warn!("Instant upload ended while discarding recording: {err}"),+ Err(err) if err.is_cancelled() => {}+ Err(err) => {+ warn!("Failed to join instant upload while discarding recording: {err}")+ }}}-crate::upload::emit_upload_complete(app, &video_id);Some(video_id)}@@ -2747,65 +3202,355 @@ async fn discard_recording(app: &AppHandle, recording: InProgressRecording) -> Rlocal_delete}-#[tauri::command]-#[specta::specta]-#[instrument(skip(app, state))]-pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {- let mut state = state.write().await;- let recording_pending = matches!(&state.recording_state, RecordingState::Pending { .. });- let Some(current_recording) = state.clear_current_recording() else {- if recording_pending {- debug!("Stop recording requested before recording actor was ready");- return Err("Recording is still starting".to_string());- }- debug!("Stop recording requested without active recording");- return Ok(());- };-- let recording_dir = current_recording.recording_dir().clone();- if let InProgressRecording::Instant {- video_upload_info, ..- } = ¤t_recording- {- let _ = open_external_link(- app.clone(),- recording_stopped_share_url(&video_upload_info.link),- );+#[cfg(target_os = "linux")]+async fn after_studio_join<T, F>(+ stop: impl std::future::Future<Output = studio_recording::StudioStopReport>,+ finish: impl FnOnce(Result<studio_recording::CompletedRecording, String>) -> F,+) -> Result<T, String>+where+ F: std::future::Future<Output = Result<T, String>>,+{+ let report = stop.await;+ if !report.accepted_intent {+ return Err("Another Studio terminal action owns cleanup".into());+ }+ if report.quiescence != studio_recording::StudioQuiescence::Joined {+ return Err("Studio cleanup is unconfirmed; recording and Stop control retained".into());}+ finish(report.result).await+}- let recording_outcome = match current_recording.stop().await {- Ok(completed) => Ok(completed),- Err((e, ctx)) => {- error!("Recording stop failed: {e:#}");- if let Some(ctx) = ctx {- ctx.segment_upload.handle.abort();- crate::upload::emit_upload_complete(&app, &ctx.video_upload_info.id);- }- Err(e.to_string())+#[cfg(target_os = "linux")]+async fn control_studio_recording(+ app: &AppHandle,+ state: &Arc<tokio::sync::RwLock<App>>,+ expected_directory: Option<&Path>,+ discard: bool,+ failure: Option<String>,+) -> Option<Result<(), String>> {+ let (handle, directory, target_name, capture_target, generation) = {+ let state = state.read().await;+ let InProgressRecording::Studio { handle, common, .. } = state.current_recording()? else {+ return None;+ };+ if expected_directory.is_some_and(|expected| expected != common.recording_dir) {+ return Some(Err(+ "Studio terminal operation belongs to an older recording".into(),+ ));}+ (+ handle.clone(),+ common.recording_dir.clone(),+ common.target_name.clone(),+ common.inputs.capture_target.clone(),+ crate::clean_capture::owner(app, &common.recording_dir),+ )};-- handle_recording_end(app, recording_outcome, &mut state, recording_dir).await?;-- Ok(())-}--#[tauri::command]-#[specta::specta]-#[instrument(skip(app, state))]-pub async fn restart_recording(- app: AppHandle,- state: MutableState<'_, App>,-) -> Result<RecordingAction, String> {- let Some(recording) = state.write().await.clear_current_recording() else {- return Err("No recording in progress".to_string());+ let intent = if discard {+ studio_recording::StudioStopIntent::Discard+ } else {+ studio_recording::StudioStopIntent::Preserve};+ let stopping = handle.clone();+ Some(+ after_studio_join(+ async move { stopping.stop_with_intent(intent).await },+ |result| async move {+ let outcome = match failure {+ Some(error) => Err(error),+ None => result,+ };+ if discard && let Err(error) = &outcome {+ return Err(error.clone());+ }+ let mut state = state.write().await;+ let current = match state.current_recording() {+ Some(InProgressRecording::Studio {+ handle: current,+ common,+ ..+ }) => {+ common.recording_dir == directory+ && current.lifecycle().same_attempt(&handle.lifecycle())+ && crate::clean_capture::owner(app, &directory) == generation+ }+ _ => false,+ };+ if !current {+ return Err("Studio terminal completion is stale".into());+ }+ if discard && let Err(error) = remove_recording_dir(&directory).await {+ return Err(error);+ }+ let error = outcome.as_ref().err().cloned();+ let completed = if discard {+ Err("Recording discarded after confirmed capture shutdown".into())+ } else {+ outcome.map(|recording| CompletedRecording::Studio {+ recording,+ target_name,+ capture_target,+ })+ };+ if let Some(error) = &error {+ let _ = RecordingEvent::Failed {+ error: error.clone(),+ }+ .emit(app);+ }+ let cleanup =+ handle_recording_end(app.clone(), completed, &mut state, directory).await;+ match error {+ Some(error) => Err(error),+ None => cleanup,+ }+ },+ )+ .await,+ )+}++#[cfg(windows)]+async fn after_windows_studio_stop<T, F>(+ stop: impl std::future::Future<Output = studio_recording::WindowsStudioStopReport>,+ finish: impl FnOnce(studio_recording::CompletedRecording) -> F,+) -> Result<T, String>+where+ F: std::future::Future<Output = Result<T, String>>,+{+ let report = stop.await;+ if !report.accepted_intent {+ return Err("Another Studio terminal action owns cleanup".into());+ }+ if !report.stop_acknowledged {+ return Err(format!(+ "Studio cleanup is unconfirmed; recording and Stop control retained: {}",+ report+ .result+ .err()+ .unwrap_or_else(|| "terminal acknowledgement missing".into())+ ));+ }+ finish(report.result?).await+}++#[cfg(windows)]+async fn control_studio_recording(+ app: &AppHandle,+ state: &Arc<tokio::sync::RwLock<App>>,+ expected_directory: Option<&Path>,+ discard: bool,+ failure: Option<String>,+) -> Option<Result<(), String>> {+ let (handle, directory, target_name, capture_target, generation) = {+ let state = state.read().await;+ let InProgressRecording::Studio { handle, common, .. } = state.current_recording()? else {+ return None;+ };+ if expected_directory.is_some_and(|expected| expected != common.recording_dir) {+ return Some(Err(+ "Studio terminal operation belongs to an older recording".into(),+ ));+ }+ (+ handle.clone(),+ common.recording_dir.clone(),+ common.target_name.clone(),+ common.inputs.capture_target.clone(),+ crate::clean_capture::owner(app, &common.recording_dir),+ )+ };+ let intent = if discard {+ studio_recording::StudioStopIntent::Discard+ } else {+ studio_recording::StudioStopIntent::Preserve+ };+ let stopping = handle.clone();+ let finishing = handle.clone();+ let result = after_windows_studio_stop(+ async move { stopping.stop_with_intent(intent).await },+ |recording| async move {+ let mut state = state.write().await;+ let current = match state.current_recording() {+ Some(InProgressRecording::Studio {+ handle: current,+ common,+ ..+ }) => {+ common.recording_dir == directory+ && current.same_attempt(&finishing)+ && crate::clean_capture::owner(app, &directory) == generation+ }+ _ => false,+ };+ if !current {+ return Err("Studio terminal completion is stale".into());+ }+ if let Some(error) = failure {+ return Err(error);+ }+ if discard {+ remove_recording_dir(&directory).await?;+ }+ let completed = if discard {+ Err("Recording discarded after Studio stop acknowledgement".into())+ } else {+ Ok(CompletedRecording::Studio {+ recording,+ target_name,+ capture_target,+ })+ };+ handle_recording_end(app.clone(), completed, &mut state, directory).await+ },+ )+ .await;+ if let Err(error) = &result {+ let state = state.read().await;+ if let Some(InProgressRecording::Studio {+ handle: current,+ common,+ ..+ }) = state.current_recording()+ && current.same_attempt(&handle)+ && expected_directory.is_none_or(|expected| expected == common.recording_dir)+ {+ let _ = RecordingEvent::Failed {+ error: error.clone(),+ }+ .emit(app);+ }+ }+ Some(result)+}++#[tauri::command]+#[specta::specta]+#[instrument(skip(app, state))]+pub async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {+ #[cfg(target_os = "linux")]+ if let Some(attempt) = linux_instant::current(&app) {+ return linux_instant::control(app, attempt, false).await;+ }+ if crate::clean_capture::queue_stop(&app) {+ return Ok(());+ }+ #[cfg(any(target_os = "linux", windows))]+ if let Some(result) = control_studio_recording(&app, &state, None, false, None).await {+ return result;+ }+ let mut state = state.write().await;+ let recording_pending = matches!(&state.recording_state, RecordingState::Pending { .. });+ let Some(current_recording) = state.clear_current_recording() else {+ if recording_pending {+ debug!("Stop recording requested before recording actor was ready");+ return Err("Recording is still starting".to_string());+ }+ debug!("Stop recording requested without active recording");+ return Ok(());+ };++ let recording_dir = current_recording.recording_dir().clone();+ if let InProgressRecording::Instant {+ video_upload_info, ..+ } = ¤t_recording+ {+ let _ = open_external_link(+ app.clone(),+ recording_stopped_share_url(&video_upload_info.link),+ );+ }++ let recording_outcome = match current_recording.stop().await {+ Ok(completed) => Ok(completed),+ Err((e, ctx)) => {+ error!("Recording stop failed: {e:#}");+ if let Some(ctx) = ctx {+ #[cfg(not(target_os = "linux"))]+ ctx.segment_upload.handle.abort();+ #[cfg(target_os = "linux")]+ if let Some(attempt) = linux_instant::current(&app) {+ attempt.cancel();+ }+ crate::upload::emit_upload_complete(&app, &ctx.video_upload_info.id);+ }+ Err(e.to_string())+ }+ };++ handle_recording_end(app, recording_outcome, &mut state, recording_dir).await?;++ Ok(())+}++#[tauri::command]+#[specta::specta]+#[instrument(skip(app, state))]+pub async fn restart_recording(+ app: AppHandle,+ state: MutableState<'_, App>,+) -> Result<RecordingAction, String> {+ #[cfg(target_os = "linux")]+ if let Some(attempt) = linux_instant::current(&app) {+ let inputs = state+ .read()+ .await+ .current_recording()+ .ok_or("No recording in progress")?+ .inputs()+ .clone();+ let restore_generation =+ crate::clean_capture::phase(&app).map(|_| crate::clean_capture::generation(&app));+ linux_instant::control(app.clone(), attempt, true).await?;+ if let Some(generation) = restore_generation {+ crate::clean_capture::wait_restored(&app, generation).await?;+ }+ return Box::pin(start_recording(app, state, inputs)).await;+ }+ #[cfg(any(target_os = "linux", windows))]+ {+ let current = {+ let state = state.read().await;+ match state.current_recording() {+ Some(InProgressRecording::Studio { common, .. }) => Some((+ common.inputs.clone(),+ common.recording_dir.clone(),+ crate::clean_capture::owner(&app, &common.recording_dir),+ )),+ _ => None,+ }+ };+ if let Some((inputs, directory, generation)) = current {+ control_studio_recording(&app, &state, Some(&directory), true, None)+ .await+ .ok_or("Studio recording changed before restart")??;+ #[cfg(target_os = "linux")]+ if let Some(generation) = generation {+ crate::clean_capture::wait_restored(&app, generation).await?;+ }+ #[cfg(windows)]+ let _ = generation;+ return Box::pin(start_recording(app, state, inputs)).await;+ }+ }+ if crate::clean_capture::phase(&app) == Some(crate::clean_capture::Phase::Recording) {+ crate::clean_capture::control(&app, false).await?;+ }++ let (recording, clean_generation) = {+ let mut state = state.write().await;+ let recording = state+ .current_recording()+ .ok_or("No recording in progress")?;+ let generation = crate::clean_capture::begin_restart(&app, recording.recording_dir())?;+ (state.clear_current_recording().unwrap(), generation)+ };++ let _ = CurrentRecordingChanged.emit(&app);++ let inputs = recording.inputs().clone();+ let recording_dir = recording.recording_dir().clone();- let _ = CurrentRecordingChanged.emit(&app);-- let inputs = recording.inputs().clone();- let recording_dir = recording.recording_dir().clone();-// Cleanup of the discarded recording must not block or abort the restart:// the old recording is already cancelled at this point, and the new one// writes to a fresh directory.@@ -2822,6 +3567,33 @@ pub async fn restart_recording(warn!("Failed to delete recording files while restarting: {err}");}+ if let Some(generation) = clean_generation {+ let result = async {+ crate::clean_capture::hide(&app, generation).await?;+ let requested = app+ .state::<crate::RequestedInputsState>()+ .ready_snapshot()?;+ crate::clean_capture::prepare(&app, &inputs, Some(generation)).await?;+ state+ .write()+ .await+ .set_pending_recording(inputs.mode, inputs.capture_target.clone())?;+ start_recording_prepared(+ app.clone(),+ state.clone(),+ inputs,+ requested,+ Some(generation),+ )+ .await+ }+ .await;+ if !matches!(&result, Ok(RecordingAction::Started)) {+ state.write().await.clear_pending_recording();+ crate::clean_capture::release(&app, generation, false);+ }+ return result;+ }start_recording(app.clone(), state, inputs).await}@@ -2829,6 +3601,31 @@ pub async fn restart_recording(#[specta::specta]#[instrument(skip(app, state))]pub async fn delete_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<(), String> {+ #[cfg(target_os = "linux")]+ if let Some(attempt) = linux_instant::current(&app) {+ return linux_instant::control(app, attempt, true).await;+ }+ #[cfg(any(target_os = "linux", windows))]+ if let Some(result) = control_studio_recording(&app, &state, None, true, None).await {+ return result;+ }+ if crate::clean_capture::phase(&app) == Some(crate::clean_capture::Phase::Recording) {+ crate::clean_capture::control(&app, false).await?;+ }++ if matches!(+ crate::clean_capture::phase(&app),+ Some(+ crate::clean_capture::Phase::Starting+ | crate::clean_capture::Phase::AwaitingShortcut+ | crate::clean_capture::Phase::Pausing+ | crate::clean_capture::Phase::Resuming+ | crate::clean_capture::Phase::ResumeFailed+ | crate::clean_capture::Phase::Restarting+ )+ ) {+ return Err("Recording is changing state. Use Ctrl+Shift+F9 to stop.".into());+ }let recording_data = {let mut app_state = state.write().await;app_state.clear_current_recording()@@ -2842,7 +3639,18 @@ pub async fn delete_recording(app: AppHandle, state: MutableState<'_, App>) -> Rlet _ = window.hide();}+ let clean_generation = crate::clean_capture::owner(&app, recording.recording_dir());+ if let Some(generation) = clean_generation {+ crate::clean_capture::set_phase(+ &app,+ generation,+ crate::clean_capture::Phase::Stopping,+ );+ }let delete_result = discard_recording(&app, recording).await;+ if let Some(generation) = clean_generation {+ crate::clean_capture::release(&app, generation, false);+ }let settings = GeneralSettingsStore::get(&app).ok()@@ -3082,6 +3890,46 @@ async fn handle_recording_end(app: &mut App,recording_dir: PathBuf,) -> Result<(), String> {+ #[cfg(target_os = "linux")]+ if let Some(InProgressRecording::Studio {+ handle: studio,+ common,+ ..+ }) = app.current_recording()+ && common.recording_dir == recording_dir+ && studio.lifecycle().quiescence() != studio_recording::StudioQuiescence::Joined+ {+ return Err("Studio capture cleanup is unconfirmed; active recording retained".into());+ }+ #[cfg(windows)]+ if let Some(InProgressRecording::Studio {+ handle: studio,+ common,+ ..+ }) = app.current_recording()+ && common.recording_dir == recording_dir+ && !studio.stop_acknowledged()+ {+ return Err("Studio stop is unconfirmed; active recording retained".into());+ }+ #[cfg(target_os = "linux")]+ if linux_instant::current(&handle)+ .is_some_and(|attempt| attempt.owns_directory(&recording_dir) && !attempt.capture_joined())+ {+ return Err("Instant capture cleanup is unconfirmed; recording state retained".into());+ }+ #[cfg(target_os = "linux")]+ let strict_attempt =+ linux_instant::current(&handle).filter(|attempt| attempt.owns_directory(&recording_dir));+ #[cfg(target_os = "linux")]+ let mut recording = match &strict_attempt {+ Some(attempt) => attempt.checked(recording),+ None => recording,+ };+ let clean_generation = crate::clean_capture::owner(&handle, &recording_dir);+ if crate::clean_capture::phase(&handle).is_some() && clean_generation.is_none() {+ return Ok(());+ }let cleared = app.clear_recording_state();if let Some(in_progress) = cleared.as_ref() {@@ -3100,15 +3948,19 @@ async fn handle_recording_end(),}};- let (status, error_class) = match &recording {- Ok(_) => ("stopped", None),- Err(e) => ("failed", Some(classify_error_message(e.as_str()))),- };let drop_rate_pct = 0.0_f64;let dropped_mic_messages = match mic_feed {Some(feed) => feed.dropped_message_count().await,None => 0,};+ #[cfg(target_os = "linux")]+ if let Some(attempt) = &strict_attempt {+ recording = attempt.checked(recording);+ }+ let (status, error_class) = match &recording {+ Ok(_) => ("stopped", None),+ Err(e) => ("failed", Some(classify_error_message(e.as_str()))),+ };crate::telemetry::async_capture_event(&handle,crate::telemetry::AnalyticsEvent::RecordingCompleted {@@ -3146,8 +3998,16 @@ async fn handle_recording_end(..}) = cleared.as_ref(){- info!("Aborting segment upload due to recording failure");+ info!("Ending upload after recording failure");+ #[cfg(not(target_os = "linux"))]segment_upload.handle.abort();+ #[cfg(target_os = "linux")]+ {+ let _ = segment_upload;+ if let Some(attempt) = linux_instant::current(&handle) {+ attempt.upload().deny();+ }+ }crate::upload::emit_upload_complete(&handle, &video_upload_info.id);}@@ -3157,6 +4017,10 @@ async fn handle_recording_end(app.was_camera_only_recording = false;}+ #[cfg(target_os = "linux")]+ if let Some(attempt) = &strict_attempt {+ recording = attempt.checked(recording);+ }let res = match recording {// we delay reporting errors here so that everything else happens firstOk(recording) => Some(handle_recording_finish(&handle, recording).await),@@ -3217,6 +4081,7 @@ async fn handle_recording_end(}app.camera_preview.pause();+ app.applied_mic_input.invalidate();let _ = app.mic_feed.ask(microphone::RemoveInput).await;let _ = app.camera_feed.ask(camera::RemoveInput).await;@@ -3226,13 +4091,19 @@ async fn handle_recording_end(// the main window alone: un-minimizing it here (Windows `Close` behaviour// minimizes; macOS `Minimise` miniaturizes) would restore it on top of the// editor that just opened.- let editor_took_foreground = matches!(&res, Some(Ok(true)));+ let mut editor_took_foreground = matches!(&res, Some(Ok(true)));if let Some(window) = main_window {- if !editor_took_foreground {+ if !editor_took_foreground && clean_generation.is_none() {window.unminimize().ok();}- if let Err(err) = app.ensure_selected_mic_ready().await {+ let requested = handle.state::<crate::RequestedInputsState>().snapshot();+ if clean_generation.is_none()+ && !requested.microphone.pending+ && requested.microphone.error.is_none()+ && requested.microphone.value == app.selected_mic_label+ && let Err(err) = app.ensure_selected_mic_ready().await+ {warn!("Failed to restore microphone preview after recording: {err}");}} else {@@ -3251,12 +4122,16 @@ async fn handle_recording_end(if let Some(editor_path) = EditorRecordingTarget::take(&handle)&& let Some(editor_window) = editor_window_for_path(&handle, &editor_path){+ editor_took_foreground = true;let _ = editor_window.unminimize();let _ = editor_window.show();let _ = editor_window.set_focus();}CurrentRecordingChanged.emit(&handle).ok();+ if let Some(generation) = clean_generation {+ crate::clean_capture::release_after_recording(&handle, generation, editor_took_foreground);+ }if let Some(res) = res {let _editor_took_foreground: bool = res?;@@ -3471,11 +4346,20 @@ async fn handle_recording_finish()}CompletedRecording::Instant {+ #[cfg(target_os = "linux")]+ finalized,recording,segment_upload,video_upload_info,..} => {+ #[cfg(target_os = "linux")]+ if finalized {+ if let Some(attempt) = linux_instant::current(app) {+ attempt.checked(Ok(()))?;+ }+ return Ok(false);+ }if !recording.health.is_uploadable()&& let cap_recording::RecordingHealth::Damaged { ref reason } = recording.health{@@ -3528,8 +4412,7 @@ async fn handle_recording_finish(let recording_dir = recording_dir.clone();async move {- let upload_succeeded = segment_upload- .handle+ let upload_succeeded = await_instant_upload(segment_upload).await.map_err(|e| e.to_string()).and_then(|r| r.map_err(|v| v.to_string()))@@ -4289,6 +5172,64 @@ mod tests {use super::*;use tempfile::tempdir;+ #[test]+ fn requested_microphone_absence_is_an_error_not_an_empty_track() {+ let error = selected_microphone_for_start(Some("Requested mic".into()), &[])+ .unwrap_err()+ .to_string();+ assert!(error.contains("Requested mic"));+ assert!(error.contains("no longer available"));+ assert!(error.contains("Reconnect"));+ }++ #[test]+ fn requested_microphone_requires_exact_name_without_substring_fallback() {+ for names in [+ vec!["Requested mic alternate".into()],+ vec!["mic".into()],+ vec!["requested mic".into()],+ ] {+ assert!(selected_microphone_for_start(Some("Requested mic".into()), &names).is_err());+ }+ assert_eq!(+ selected_microphone_for_start(+ Some("Requested mic".into()),+ &["Requested mic alternate".into(), "Requested mic".into()],+ )+ .unwrap(),+ Some("Requested mic".into())+ );+ }++ #[test]+ fn intentional_no_microphone_is_preserved() {+ assert_eq!(selected_microphone_for_start(None, &[]).unwrap(), None);+ assert_eq!(+ selected_microphone_for_start(None, &["Another mic".into()]).unwrap(),+ None+ );+ }++ #[test]+ fn requested_camera_absence_is_an_error_for_screen_capture_too() {+ let id = camera::DeviceOrModelID::DeviceID("requested-camera".into());+ let error = validate_selected_camera_for_start(Some(&id), |_| false)+ .unwrap_err()+ .to_string();+ assert!(error.contains("requested-camera"));+ assert!(error.contains("no longer available"));+ assert!(error.contains("Reconnect"));+ assert!(validate_selected_camera_for_start(Some(&id), |_| true).is_ok());+ }++ #[test]+ fn intentional_no_camera_does_not_probe_or_choose_another_device() {+ assert!(+ validate_selected_camera_for_start(None, |_| { panic!("No camera was requested") })+ .is_ok()+ );+ }+#[test]fn animated_gradient_default_is_remembered_without_overwriting_explicit_presets() {let library = cap_project::AnimatedGradientLibrary {@@ -4684,3 +5625,1993 @@ mod tests {);}}++#[cfg(target_os = "linux")]+pub(crate) mod linux_instant {+ use super::*;+ use crate::upload::strict_instant::{Control, Permission};+ use std::sync::{+ Mutex,+ atomic::{AtomicBool, Ordering},+ };++ #[derive(Clone)]+ pub struct Attempt(Arc<AttemptInner>);++ struct AttemptInner {+ lifecycle: Mutex<Option<instant_recording::InstantLifecycle>>,+ directory: Mutex<Option<PathBuf>>,+ cancelled: AtomicBool,+ cancel_changed: tokio::sync::watch::Sender<bool>,+ started: tokio::sync::watch::Sender<bool>,+ operation: tokio::sync::Mutex<()>,+ upload: Control,+ permission: Mutex<Option<Permission>>,+ uploading: AtomicBool,+ ui_ready: AtomicBool,+ cleanup_uncertain: AtomicBool,+ upload_result: Mutex<Option<Result<(), String>>>,+ terminal: Mutex<Option<TerminalControl>>,+ }++ #[derive(Clone, Copy)]+ enum ControlSuccess {+ Stopped,+ Discarded,+ }++ #[derive(Clone)]+ struct TerminalControl {+ kind: ControlSuccess,+ result: Result<(), String>,+ }++ impl Attempt {+ fn new() -> Self {+ let (upload, permission) = Control::new();+ let (started, _) = tokio::sync::watch::channel(false);+ Self(Arc::new(AttemptInner {+ lifecycle: Mutex::new(None),+ directory: Mutex::new(None),+ cancelled: AtomicBool::new(false),+ cancel_changed: tokio::sync::watch::channel(false).0,+ started,+ operation: tokio::sync::Mutex::new(()),+ upload,+ ui_ready: AtomicBool::new(false),+ cleanup_uncertain: AtomicBool::new(false),+ upload_result: Mutex::new(None),+ terminal: Mutex::new(None),+ permission: Mutex::new(Some(permission)),+ uploading: AtomicBool::new(false),+ }))+ }++ pub(crate) fn checked<T>(&self, result: Result<T, String>) -> Result<T, String> {+ result.and_then(|value| {+ if self.cancelled() {+ Err("Instant attempt cancelled; local recording retained".into())+ } else {+ Ok(value)+ }+ })+ }++ fn terminal_result(&self, discard: bool) -> Option<Result<(), String>> {+ let mut terminal = self.0.terminal.lock().unwrap();+ let terminal = terminal.as_mut()?;+ terminal.result = self.checked(terminal.result.clone());+ Some(+ terminal+ .result+ .clone()+ .and_then(|()| match (terminal.kind, discard) {+ (ControlSuccess::Stopped, true) => {+ Err("Instant recording was stopped, not discarded".into())+ }+ _ => Ok(()),+ }),+ )+ }++ fn record_terminal(&self, discard: bool, result: Result<(), String>) -> Result<(), String> {+ let result = self.checked(result);+ let kind = if discard {+ ControlSuccess::Discarded+ } else {+ ControlSuccess::Stopped+ };+ let mut terminal = self.0.terminal.lock().unwrap();+ if terminal.is_none() {+ *terminal = Some(TerminalControl { kind, result });+ }+ drop(terminal);+ self.terminal_result(discard).unwrap()+ }++ pub fn control_in_progress(&self) -> bool {+ self.0.operation.try_lock().is_err()+ }+ pub fn terminal_needs_cleanup(&self) -> bool {+ if self.control_in_progress() {+ false+ } else {+ self.cancel();+ true+ }+ }++ fn prepare_control(&self) {+ if self.0.operation.try_lock().is_err() || !*self.0.started.borrow() {+ self.cancel();+ }+ }++ pub fn cancel(&self) {+ self.0.cancelled.store(true, Ordering::Release);+ self.0.cancel_changed.send_replace(true);+ self.0.upload.deny();+ if let Some(lifecycle) = self.lifecycle() {+ lifecycle.cancel();+ }+ }++ pub fn cancelled(&self) -> bool {+ self.0.cancelled.load(Ordering::Acquire)+ }+ pub(crate) async fn while_active<T>(+ &self,+ operation: impl std::future::Future<Output = Result<T, String>>,+ ) -> Result<T, String> {+ self.checked(Ok(()))?;+ let mut changed = self.0.cancel_changed.subscribe();+ tokio::select! {+ biased;+ _ = async {+ while !*changed.borrow_and_update() {+ if changed.changed().await.is_err() { break; }+ }+ } => Err("Instant preparation cancelled".into()),+ result = operation => self.checked(result),+ }+ }++ pub fn upload(&self) -> Control {+ self.0.upload.clone()+ }+ pub fn upload_started(&self) {+ self.0.uploading.store(true, Ordering::Release);+ }+ fn lifecycle(&self) -> Option<instant_recording::InstantLifecycle> {+ self.0.lifecycle.lock().unwrap().clone()+ }+ pub fn owns_directory(&self, directory: &Path) -> bool {+ self.0.directory.lock().unwrap().as_deref() == Some(directory)+ }+ pub fn capture_joined(&self) -> bool {+ self.lifecycle().is_none_or(|lifecycle| {+ lifecycle.quiescence() == instant_recording::InstantQuiescence::Joined+ })+ }+ pub fn has_capture(&self) -> bool {+ self.lifecycle().is_some()+ }+ pub fn ui_ready(&self) -> bool {+ self.0.ui_ready.load(Ordering::Acquire)+ }+ pub fn set_directory(&self, directory: PathBuf) {+ *self.0.directory.lock().unwrap() = Some(directory);+ }+ pub(crate) fn same(&self, other: &Self) -> bool {+ Arc::ptr_eq(&self.0, &other.0)+ }++ pub async fn attach(+ &self,+ directory: PathBuf,+ lifecycle: instant_recording::InstantLifecycle,+ ) -> Result<(), String> {+ if let Some(previous) = self.lifecycle()+ && previous.wait_for_quiescence().await+ != instant_recording::InstantQuiescence::Joined+ {+ lifecycle.cancel();+ return Err("Previous Instant startup cleanup is unconfirmed".into());+ }+ *self.0.directory.lock().unwrap() = Some(directory);+ *self.0.lifecycle.lock().unwrap() = Some(lifecycle.clone());+ if self.cancelled() {+ lifecycle.cancel();+ return Err("Instant startup cancelled".into());+ }+ Ok(())+ }++ async fn capture_cleanup(&self) -> bool {+ match self.lifecycle() {+ Some(lifecycle) => {+ lifecycle.wait_for_quiescence().await+ == instant_recording::InstantQuiescence::Joined+ }+ None => true,+ }+ }++ pub(super) async fn upload_cleanup(&self) -> bool {+ !self.0.uploading.load(Ordering::Acquire) || self.0.upload.joined().await+ }++ async fn join_upload(&self, upload: InstantUploader) -> Result<(), String> {+ if let Some(result) = self.0.upload_result.lock().unwrap().clone() {+ return result;+ }+ let result = await_instant_upload(upload)+ .await+ .and_then(|result| result.map_err(|error| error.to_string()));+ *self.0.upload_result.lock().unwrap() = Some(result.clone());+ result+ }++ async fn wait_started(&self) -> Result<(), String> {+ let mut started = self.0.started.subscribe();+ loop {+ if *started.borrow_and_update() {+ return Ok(());+ }+ started+ .changed()+ .await+ .map_err(|_| "Instant startup owner was lost")?;+ }+ }++ fn authorize(&self) -> Result<(), String> {+ if self.cancelled() {+ return Err("Instant attempt was cancelled".into());+ }+ self.0+ .permission+ .lock()+ .unwrap()+ .take()+ .ok_or("Instant completion permission was consumed")?+ .grant()+ .map_err(|error| error.to_string())+ }+ }++ struct Waiter(Option<Attempt>);+ impl Drop for Waiter {+ fn drop(&mut self) {+ if let Some(attempt) = self.0.take() {+ attempt.cancel();+ }+ }+ }++ pub fn current(app: &AppHandle) -> Option<Attempt> {+ app.try_state::<crate::clean_capture::State>()+ .and_then(|state| state.instant.lock().unwrap().clone())+ }++ fn is_current(app: &AppHandle, attempt: &Attempt) -> bool {+ current(app).is_some_and(|value| value.same(attempt))+ }++ fn release(app: &AppHandle, attempt: &Attempt) {+ let state = app.state::<crate::clean_capture::State>();+ let mut current = state.instant.lock().unwrap();+ if current.as_ref().is_some_and(|value| value.same(attempt)) {+ drop(current.take());+ }+ }++ pub fn blocks_cleanup(app: &AppHandle) -> bool {+ current(app).is_some_and(|attempt| !attempt.capture_joined())+ }++ pub(crate) fn validate_screen_request(+ inputs: &StartRecordingInputs,+ requested: &crate::RequestedInputs,+ ) -> Result<(), String> {+ validate_screen_camera_support(+ inputs,+ requested.camera.value.is_some(),+ std::env::var_os("DISPLAY").is_some()+ && std::env::var_os("WAYLAND_DISPLAY").is_none()+ && std::env::var("XDG_SESSION_TYPE")+ .is_ok_and(|value| value.eq_ignore_ascii_case("x11")),+ )+ }++ fn validate_screen_camera_support(+ inputs: &StartRecordingInputs,+ camera_requested: bool,+ x11: bool,+ ) -> Result<(), String> {+ if inputs.mode != RecordingMode::Instant+ || !camera_requested+ || matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly)+ {+ return Ok(());+ }+ if !matches!(+ inputs.capture_target,+ ScreenCaptureTarget::Display { .. } | ScreenCaptureTarget::Area { .. }+ ) {+ return Err("Instant screen camera is supported for X11 Display and Area only. No camera was omitted.".into());+ }+ if !x11 {+ return Err(+ "Instant camera composition requires an X11 desktop; Wayland is not supported."+ .into(),+ );+ }+ Ok(())+ }++ pub(crate) fn capture_rect(+ target: &ScreenCaptureTarget,+ ) -> Result<crate::linux_instant_camera::PhysicalRect, String> {+ let (display, crop) =+ cap_recording::target_to_display_and_crop(target).map_err(|error| error.to_string())?;+ let position = display+ .raw_handle()+ .physical_position()+ .ok_or("Display physical position unavailable")?;+ let size = display+ .physical_size()+ .ok_or("Display physical size unavailable")?;+ physical_capture_rect(+ (position.x(), position.y(), size.width(), size.height()),+ crop.map(|crop| {+ (+ crop.position().x(),+ crop.position().y(),+ crop.size().width(),+ crop.size().height(),+ )+ }),+ )+ }++ fn physical_capture_rect(+ display: (f64, f64, f64, f64),+ crop: Option<(f64, f64, f64, f64)>,+ ) -> Result<crate::linux_instant_camera::PhysicalRect, String> {+ let (x, y, width, height) = cap_recording::sources::screen_capture::x11_capture_rect(+ display.0, display.1, display.2, display.3, crop,+ )+ .map_err(|error| error.to_string())?;+ Ok(crate::linux_instant_camera::PhysicalRect {+ x,+ y,+ width,+ height,+ })+ }++ pub(crate) struct PreparedScreenCamera {+ pub source: instant_recording::LinuxProcessedCameraSource,+ pub presentation: instant_recording::LinuxCameraPresentation,+ pub reference_size: (u32, u32),+ }++ pub(crate) fn configure_screen_camera(+ builder: instant_recording::ActorBuilder,+ target: &ScreenCaptureTarget,+ camera_requested: bool,+ prepared: Option<PreparedScreenCamera>,+ ) -> Result<instant_recording::ActorBuilder, String> {+ if let Some(prepared) = prepared {+ if !camera_requested || matches!(target, ScreenCaptureTarget::CameraOnly) {+ return Err("Unexpected Instant screen camera preparation".into());+ }+ Ok(builder.with_linux_processed_camera(+ prepared.source,+ prepared.presentation,+ prepared.reference_size,+ ))+ } else if camera_requested && !matches!(target, ScreenCaptureTarget::CameraOnly) {+ Err(+ "Requested Instant screen camera was not prepared; no raw fallback is allowed"+ .into(),+ )+ } else {+ Ok(builder)+ }+ }++ pub(crate) async fn prepare_screen_camera(+ app: &AppHandle,+ attempt: &Attempt,+ generation: u32,+ inputs: &StartRecordingInputs,+ requested: &crate::RequestedInputs,+ camera: Option<Arc<CameraFeedLock>>,+ ) -> Result<Option<PreparedScreenCamera>, String> {+ validate_screen_request(inputs, requested)?;+ if camera.is_some() != requested.camera.value.is_some() {+ return Err("Requested camera lock is missing or unexpected".into());+ }+ let capture = capture_rect(&inputs.capture_target)?;+ let prepared = if let Some(camera) = camera {+ let presentation = attempt+ .while_active(crate::linux_instant_camera::request_presentation(+ app, generation, capture,+ ))+ .await?;+ let state = app.state::<crate::ArcLock<App>>();+ let factory = state.read().await.camera_processing.clone();+ let source = attempt+ .while_active(async {+ factory+ .subscribe(camera, &presentation)+ .await+ .map_err(|error| error.to_string())+ })+ .await?;+ Some((presentation, source))+ } else {+ None+ };+ let (presentation, source) = match prepared {+ Some((presentation, source)) => (Some(presentation), Some(source)),+ None => (None, None),+ };+ let seal = crate::clean_capture::seal_instant(+ app,+ crate::clean_capture::InstantSeal {+ generation,+ attempt: attempt.clone(),+ requested: requested.clone(),+ target: inputs.capture_target.clone(),+ capture,+ presentation,+ },+ )+ .await?;+ match (seal.presentation, source) {+ (Some(presentation), Some(source)) => Ok(Some(PreparedScreenCamera {+ source,+ presentation: presentation.presentation,+ reference_size: presentation.reference_size,+ })),+ (None, None) => Ok(None),+ _ => Err("Instant prepared camera ownership was lost".into()),+ }+ }++ pub fn validate_inputs(inputs: &StartRecordingInputs) -> Result<(), String> {+ if inputs.mode == RecordingMode::Instant+ && matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly)+ && inputs.capture_system_audio+ {+ Err("System audio is not supported for Linux Instant CameraOnly. Disable it before recording.".into())+ } else {+ Ok(())+ }+ }++ pub async fn start(+ app: AppHandle,+ state: MutableState<'_, App>,+ inputs: StartRecordingInputs,+ ) -> Result<RecordingAction, String> {+ validate_inputs(&inputs)?;+ let attempt = Attempt::new();+ {+ let app_state = state.write().await;+ if !matches!(app_state.recording_state, RecordingState::None) {+ return Err("Recording already in progress".into());+ }+ let state = app.state::<crate::clean_capture::State>();+ let mut slot = state.instant.lock().unwrap();+ if slot.is_some() {+ return Err("Finish the previous Instant attempt before recording".into());+ }+ *slot = Some(attempt.clone());+ }+ let work_attempt = attempt.clone();+ let abandoned_attempt = attempt.clone();+ let abandoned_app = app.clone();+ owned_reply(+ attempt,+ async move {+ let attempt = work_attempt;+ let state = app.state::<crate::ArcLock<App>>();+ let result =+ AssertUnwindSafe(start_recording_inner(app.clone(), state.clone(), inputs))+ .catch_unwind()+ .await+ .unwrap_or_else(|panic| {+ Err(format!(+ "Instant startup panicked: {}",+ panic_message(panic)+ ))+ });+ let started =+ matches!(result, Ok(RecordingAction::Started)) && !attempt.cancelled();+ if !started {+ attempt.cancel();+ let joined = attempt.capture_cleanup().await;+ let upload_joined = attempt.upload_cleanup().await;+ if joined && upload_joined && is_current(&app, &attempt) {+ let upload = {+ let state = state.read().await;+ match state.current_recording() {+ Some(InProgressRecording::Instant { segment_upload, .. }) => {+ Some(segment_upload.clone())+ }+ _ => None,+ }+ };+ if let Some(upload) = upload {+ let _ = attempt.join_upload(upload).await;+ }+ attempt.0.ui_ready.store(true, Ordering::Release);+ let directory = attempt.0.directory.lock().unwrap().clone();+ if let Some(directory) = directory {+ let mut state = state.write().await;+ let _ = handle_recording_end(+ app.clone(),+ Err("Instant startup failed or was cancelled".into()),+ &mut state,+ directory,+ )+ .await;+ } else {+ state.write().await.clear_pending_recording();+ }+ let terminal = result.as_ref().err().cloned().unwrap_or_else(|| {+ "Instant startup did not establish a recording".into()+ });+ let _ = attempt.record_terminal(false, Err(terminal));+ release(&app, &attempt);+ }+ }+ attempt.0.started.send_replace(true);+ match result {+ Ok(RecordingAction::Started) if !started => {+ Err("Instant startup cancelled".into())+ }+ result => result,+ }+ },+ async move {+ let _ = execute(abandoned_app, abandoned_attempt, false).await;+ },+ )+ .await+ }++ pub fn control(+ app: AppHandle,+ attempt: Attempt,+ discard: bool,+ ) -> futures::future::BoxFuture<'static, Result<(), String>> {+ Box::pin(async move {+ attempt.prepare_control();+ let worker = attempt.clone();+ owned_reply(+ attempt,+ async move {+ let result = execute(app.clone(), worker, discard).await;+ if let Err(error) = &result {+ let _ = RecordingEvent::Failed {+ error: error.clone(),+ }+ .emit(&app);+ }+ result+ },+ async {},+ )+ .await+ })+ }++ async fn owned_reply<T, F, A>(attempt: Attempt, work: F, abandoned: A) -> Result<T, String>+ where+ T: Send + 'static,+ F: std::future::Future<Output = Result<T, String>> + Send + 'static,+ A: std::future::Future<Output = ()> + Send + 'static,+ {+ let mut waiter = Waiter(Some(attempt.clone()));+ let (reply, result) = tokio::sync::oneshot::channel();+ drop(tauri::async_runtime::spawn(async move {+ let result = match AssertUnwindSafe(work).catch_unwind().await {+ Ok(result) => result,+ Err(panic) => {+ attempt.0.cleanup_uncertain.store(true, Ordering::Release);+ attempt.cancel();+ attempt.0.started.send_replace(true);+ let _ = attempt.upload_cleanup().await;+ Err(format!(+ "Instant owned work panicked; cleanup is unconfirmed: {}",+ panic_message(panic)+ ))+ }+ };+ if result.is_err() {+ attempt.cancel();+ }+ if reply.send(result).is_err() {+ attempt.cancel();+ abandoned.await;+ }+ }));+ let result = result+ .await+ .map_err(|_| "Instant cleanup owner was lost".to_string())?;+ drop(waiter.0.take());+ result+ }++ async fn run_control<F, W>(+ attempt: &Attempt,+ discard: bool,+ current: impl FnOnce() -> bool,+ work: W,+ ) -> Result<(), String>+ where+ F: std::future::Future<Output = Result<(), String>>,+ W: FnOnce() -> F,+ {+ attempt.wait_started().await?;+ let _operation = attempt.0.operation.lock().await;+ if let Some(result) = attempt.terminal_result(discard) {+ return result;+ }+ if !current() {+ return Err("Instant attempt was superseded without a terminal result".into());+ }+ work().await+ }++ async fn complete_local<T, G, L, F, W>(+ attempt: &Attempt,+ outcome: Result<T, String>,+ acquire: L,+ finish: W,+ ) -> Result<(), String>+ where+ L: std::future::Future<Output = G>,+ F: std::future::Future<Output = Result<(), String>>,+ W: FnOnce(G, Result<T, String>) -> F,+ {+ let guard = acquire.await;+ let outcome = attempt.checked(outcome);+ let failure = outcome.as_ref().err().cloned();+ let cleanup = finish(guard, outcome).await;+ attempt.checked(failure.map_or(cleanup, Err))+ }++ async fn execute(app: AppHandle, attempt: Attempt, discard: bool) -> Result<(), String> {+ run_control(+ &attempt,+ discard,+ || is_current(&app, &attempt),+ || execute_current(app.clone(), attempt.clone(), discard),+ )+ .await+ }++ async fn execute_current(+ app: AppHandle,+ attempt: Attempt,+ discard: bool,+ ) -> Result<(), String> {+ if attempt.0.cleanup_uncertain.load(Ordering::Acquire) {+ attempt.cancel();+ return Err("Instant finalization cleanup is unconfirmed; local recording and Stop ownership retained".into());+ }+ let state = app.state::<crate::ArcLock<App>>();+ let (handle, directory, segment_upload, video_upload_info, target_name) = {+ let state = state.read().await;+ match state.current_recording() {+ Some(InProgressRecording::Instant {+ handle,+ common,+ segment_upload,+ video_upload_info,+ ..+ }) if attempt.owns_directory(&common.recording_dir) => (+ handle.clone(),+ common.recording_dir.clone(),+ segment_upload.clone(),+ video_upload_info.clone(),+ common.target_name.clone(),+ ),+ _ => return Err("Instant recording is unavailable; cleanup state retained".into()),+ }+ };+ if discard {+ attempt.upload().deny();+ }+ let stopped = if discard || attempt.cancelled() {+ handle.cancel().await.map(|()| None)+ } else {+ handle.stop().await.map(Some)+ };+ if stopped.is_err() {+ attempt.cancel();+ }+ if !attempt.capture_cleanup().await {+ return Err("Instant capture cleanup is unconfirmed. Local recording retained; use Stop to retry.".into());+ }+ let video_id = video_upload_info.id.clone();+ let share_info = video_upload_info.clone();+ let result = match stopped {+ Ok(Some(recording)) if !attempt.cancelled() => {+ let mut completed = CompletedRecording::Instant {+ recording,+ segment_upload: segment_upload.clone(),+ video_upload_info,+ target_name,+ finalized: false,+ };+ match finalize(&app, &attempt, &mut completed).await {+ Ok(()) => Ok(Some(completed)),+ Err(error) => {+ attempt.cancel();+ let _ = attempt.upload_cleanup().await;+ Err(error)+ }+ }+ }+ result => {+ attempt.upload().deny();+ if !attempt.upload_cleanup().await {+ return Err(+ "Instant upload reader cleanup is unconfirmed; local recording retained"+ .into(),+ );+ }+ match result {+ Ok(None) if discard && !attempt.cancelled() => Ok(None),+ Ok(_) => {+ Err("Instant recording was cancelled; local recording retained".into())+ }+ Err(error) => Err(error.to_string()),+ }+ }+ };+ if !attempt.upload_cleanup().await {+ return Err("Instant upload cleanup is unconfirmed; local recording retained".into());+ }+ let _ = attempt.join_upload(segment_upload.clone()).await;+ let successful_discard = matches!(result, Ok(None));+ let successful_upload = matches!(result, Ok(Some(_)));+ let finish_app = app.clone();+ let finish_attempt = attempt.clone();+ let finish_directory = directory.clone();+ let mut result = complete_local(+ &attempt,+ result,+ state.write(),+ move |mut state, result| async move {+ if !is_current(&finish_app, &finish_attempt)+ || state+ .current_recording()+ .is_none_or(|recording| recording.recording_dir() != &finish_directory)+ {+ return Err("Instant completion no longer owns the recording".into());+ }+ let outcome = match result {+ Ok(Some(completed)) => Ok(completed),+ Ok(None) => Err("Recording discarded".into()),+ Err(error) => Err(error),+ };+ finish_attempt.0.ui_ready.store(true, Ordering::Release);+ handle_recording_end(finish_app, outcome, &mut state, finish_directory).await+ },+ )+ .await;+ if result.is_ok() && successful_upload {+ result = successful_effects(&app, &attempt, &directory, &share_info);+ }+ result = attempt.checked(result);+ if result.is_ok() && successful_discard {+ result = remove_owned_directory(directory.clone(), attempt.clone(), false).await;+ result = attempt.checked(result);+ if result.is_ok() {+ result = delete_remote_instant_video(&app, &video_id).await;+ result = attempt.checked(result);+ }+ } else if result.is_ok() && successful_upload {+ let settings = GeneralSettingsStore::get(&app)+ .ok()+ .flatten()+ .unwrap_or_default();+ result = attempt.checked(result);+ if result.is_ok() && settings.delete_instant_recordings_after_upload {+ result = remove_owned_directory(directory.clone(), attempt.clone(), true).await;+ result = attempt.checked(result);+ }+ }+ result = attempt.checked(result);+ if let Err(error) = &result {+ attempt.cancel();+ persist_terminal_failure(&directory, error).await;+ }+ let result = attempt.record_terminal(discard, result);+ release(&app, &attempt);+ attempt.terminal_result(discard).unwrap_or(result)+ }++ async fn persist_terminal_failure(directory: &Path, error: &str) {+ let directory = directory.to_path_buf();+ let failure = error.to_string();+ let result = tokio::task::spawn_blocking(move || -> Result<(), String> {+ let mut meta =+ RecordingMeta::load_for_project(&directory).map_err(|error| error.to_string())?;+ meta.inner =+ RecordingMetaInner::Instant(InstantRecordingMeta::Failed { error: failure });+ meta.save_for_project().map_err(|error| error.to_string())+ })+ .await;+ if !matches!(&result, Ok(Ok(()))) {+ error!(+ ?result,+ "Failed to persist Instant terminal error; local recording retained"+ );+ }+ }++ struct SuccessEffects<R, U, O, C, S> {+ recording_automation: R,+ upload_automation: U,+ open_link: O,+ copy_link: C,+ sound: S,+ }++ fn dispatch_success_effects<R, U, O, C, S>(+ attempt: &Attempt,+ share_link: &str,+ effects: SuccessEffects<R, U, O, C, S>,+ ) -> Result<(), String>+ where+ R: FnOnce(),+ U: FnOnce(),+ O: FnOnce(String) -> Result<(), String>,+ C: FnOnce(String) -> Result<(), String>,+ S: FnOnce(),+ {+ attempt.checked(Ok(()))?;+ (effects.recording_automation)();+ attempt.checked(Ok(()))?;+ (effects.upload_automation)();+ attempt.checked(Ok(()))?;+ (effects.open_link)(recording_stopped_share_url(share_link))?;+ attempt.checked(Ok(()))?;+ let _ = (effects.copy_link)(share_link.to_string());+ attempt.checked(Ok(()))?;+ (effects.sound)();+ attempt.checked(Ok(()))+ }++ fn successful_effects(+ app: &AppHandle,+ attempt: &Attempt,+ directory: &Path,+ video: &VideoUploadInfo,+ ) -> Result<(), String> {+ use tauri_plugin_clipboard_manager::ClipboardExt;+ dispatch_success_effects(+ attempt,+ &video.link,+ SuccessEffects {+ recording_automation: || {+ crate::automation::run_instant_recording_automations(+ app.clone(),+ directory.to_path_buf(),+ Some(video.link.clone()),+ Some(video.id.clone()),+ )+ },+ upload_automation: || {+ crate::automation::run_upload_completed_automations(+ app.clone(),+ directory.to_path_buf(),+ Some(video.link.clone()),+ Some(video.id.clone()),+ )+ },+ open_link: |link| open_external_link(app.clone(), link),+ copy_link: |link| {+ app.clipboard()+ .write_text(link)+ .map_err(|error| error.to_string())+ },+ sound: || AppSounds::StopRecording.play(),+ },+ )+ }++ async fn remove_owned_directory(+ directory: PathBuf,+ attempt: Attempt,+ uploaded: bool,+ ) -> Result<(), String> {+ if attempt.cancelled() {+ return Err("Instant cleanup cancelled; local recording retained".into());+ }+ let worker = attempt.clone();+ tokio::task::spawn_blocking(move || {+ if worker.cancelled() {+ return Err("Instant cleanup cancelled before deletion".to_string());+ }+ if uploaded {+ worker.upload().check().map_err(|error| error.to_string())?;+ }+ std::fs::remove_dir_all(directory).map_err(|error| error.to_string())+ })+ .await+ .map_err(|error| error.to_string())??;+ if attempt.cancelled() {+ return Err("Instant cleanup cancelled during deletion".into());+ }+ Ok(())+ }++ pub fn persist_upload_start(+ directory: &Path,+ video: &VideoUploadInfo,+ segmented: bool,+ ) -> Result<(), String> {+ let mut meta =+ RecordingMeta::load_for_project(directory).map_err(|error| error.to_string())?;+ meta.upload = Some(if segmented {+ cap_project::UploadMeta::SegmentUpload {+ video_id: video.id.clone(),+ pre_created_video: video.clone(),+ recording_dir: directory.into(),+ }+ } else {+ cap_project::UploadMeta::MultipartUpload {+ video_id: video.id.clone(),+ pre_created_video: video.clone(),+ recording_dir: directory.into(),+ file_path: directory.join("content/output.mp4"),+ }+ });+ meta.save_for_project().map_err(|error| error.to_string())+ }++ async fn finalize(+ app: &AppHandle,+ attempt: &Attempt,+ completed: &mut CompletedRecording,+ ) -> Result<(), String> {+ let CompletedRecording::Instant {+ recording,+ segment_upload,+ video_upload_info,+ finalized,+ ..+ } = completed+ else {+ unreachable!()+ };+ if !recording.health.is_uploadable() {+ return Err("Instant recording output is damaged".into());+ }+ let directory = &recording.project_path;+ let screenshots = directory.join("screenshots");+ std::fs::create_dir_all(&screenshots).map_err(|error| error.to_string())?;+ let screenshot = screenshots.join("display.jpg");+ let source = if matches!(recording.display_source, ScreenCaptureTarget::CameraOnly) {+ directory.join("content/output.mp4")+ } else {+ create_screenshot_source_from_segments(&directory.join("content/display")).await?+ };+ create_screenshot(source, screenshot.clone(), None).await?;+ let bytes = compress_image(screenshot).await?;+ let upload_control = attempt.upload();+ crate::upload::strict_instant::upload_thumbnail(+ app,+ &video_upload_info.id,+ bytes,+ &upload_control,+ )+ .await+ .map_err(|error| error.to_string())?;+ let mut meta =+ RecordingMeta::load_for_project(directory).map_err(|error| error.to_string())?;+ attempt+ .upload()+ .check()+ .map_err(|error| error.to_string())?;+ meta.sharing = Some(SharingMeta {+ link: video_upload_info.link.clone(),+ id: video_upload_info.id.clone(),+ content_hash: None,+ });+ meta.save_for_project().map_err(|error| error.to_string())?;+ attempt.authorize()?;+ attempt.join_upload(segment_upload.clone()).await?;+ if !attempt.upload_cleanup().await {+ return Err("Instant upload cleanup is unconfirmed".into());+ }+ attempt+ .upload()+ .check()+ .map_err(|error| error.to_string())?;+ meta.inner = RecordingMetaInner::Instant(recording.meta.clone());+ meta.upload = Some(cap_project::UploadMeta::Complete);+ meta.save_for_project().map_err(|error| error.to_string())?;+ attempt+ .upload()+ .check()+ .map_err(|error| error.to_string())?;+ *finalized = true;+ Ok(())+ }++ #[cfg(test)]+ mod tests {+ use super::*;+ #[tokio::test]+ async fn preflight_cancel_before_f9_unblocks_start_and_stop_only_after_owned_cleanup() {+ for discard in [false, true] {+ let state = Arc::new(crate::clean_capture::instant_preflight_fixture(7));+ let attempt = Attempt::new();+ let starter = attempt.clone();+ let waiting = state.clone();+ let (polled_tx, polled_rx) = tokio::sync::oneshot::channel();+ let (cancelled_tx, cancelled_rx) = tokio::sync::oneshot::channel();+ let (cleanup_tx, cleanup_rx) = tokio::sync::oneshot::channel();+ let startup = tokio::spawn(async move {+ polled_tx.send(()).unwrap();+ let error = crate::clean_capture::await_instant_shortcut(&waiting, 7, &starter)+ .await+ .unwrap_err();+ cancelled_tx.send(()).unwrap();+ cleanup_rx.await.unwrap();+ assert!(starter.capture_cleanup().await);+ assert!(starter.upload_cleanup().await);+ let result = starter.record_terminal(false, Err(error));+ starter.0.started.send_replace(true);+ result+ });+ polled_rx.await.unwrap();+ attempt.prepare_control();+ let controller = attempt.clone();+ let stop = tokio::spawn(async move {+ run_control(+ &controller,+ discard,+ || true,+ || async { panic!("cancelled preflight has no active actor to finalize") },+ )+ .await+ });+ tokio::time::timeout(std::time::Duration::from_secs(2), cancelled_rx)+ .await+ .expect("Cancel must wake preflight without F9")+ .unwrap();+ assert!(!stop.is_finished());+ assert!(!*attempt.0.started.borrow());+ assert!(!attempt.ui_ready());+ cleanup_tx.send(()).unwrap();+ let startup_error = startup.await.unwrap().unwrap_err();+ assert_eq!(stop.await.unwrap().unwrap_err(), startup_error);+ assert!(attempt.upload().check().is_err());+ }+ }++ #[tokio::test]+ async fn preflight_cancelled_before_wait_poll_does_not_need_state_notification() {+ let state = crate::clean_capture::instant_preflight_fixture(7);+ let attempt = Attempt::new();+ attempt.cancel();+ assert!(+ tokio::time::timeout(+ std::time::Duration::from_secs(2),+ crate::clean_capture::await_instant_shortcut(&state, 7, &attempt),+ )+ .await+ .expect("pre-cancelled wait must return")+ .is_err()+ );+ }++ #[tokio::test]+ async fn preflight_command_waiter_drop_wakes_shortcut_wait_without_aborting_cleanup() {+ let state = Arc::new(crate::clean_capture::instant_preflight_fixture(7));+ let attempt = Attempt::new();+ let waiter = Waiter(Some(attempt.clone()));+ let owner = attempt.clone();+ let (polled_tx, polled_rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(async move {+ polled_tx.send(()).unwrap();+ crate::clean_capture::await_instant_shortcut(&state, 7, &owner).await+ });+ polled_rx.await.unwrap();+ drop(waiter);+ assert!(+ tokio::time::timeout(std::time::Duration::from_secs(2), task)+ .await+ .expect("dropped command must wake preflight")+ .unwrap()+ .is_err()+ );+ assert!(attempt.capture_cleanup().await);+ assert!(attempt.upload_cleanup().await);+ assert!(attempt.authorize().is_err());+ }++ #[tokio::test]+ async fn preflight_cancel_wins_when_f9_and_cancel_are_ready_together() {+ let state = Arc::new(crate::clean_capture::instant_preflight_fixture(7));+ let attempt = Attempt::new();+ let owner = attempt.clone();+ let waiting = state.clone();+ let (polled_tx, polled_rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(async move {+ polled_tx.send(()).unwrap();+ crate::clean_capture::await_instant_shortcut(&waiting, 7, &owner).await+ });+ polled_rx.await.unwrap();+ crate::clean_capture::deliver_preflight_shortcut(&state);+ attempt.cancel();+ assert!(task.await.unwrap().is_err());+ }++ #[tokio::test]+ async fn preflight_actual_shortcut_wait_preserves_success_and_rejects_wrong_generation() {+ let state = Arc::new(crate::clean_capture::instant_preflight_fixture(7));+ assert!(+ crate::clean_capture::wait_for_shortcut(&state, 8)+ .await+ .is_err()+ );+ let waiting = state.clone();+ let task =+ tokio::spawn(+ async move { crate::clean_capture::wait_for_shortcut(&waiting, 7).await },+ );+ crate::clean_capture::deliver_preflight_shortcut(&state);+ task.await.unwrap().unwrap();+ }++ #[test]+ fn instant_physical_capture_reference_matches_negative_origin_fractional_crop_and_even_rounding()+ {+ assert_eq!(+ physical_capture_rect(+ (-1920.0, 0.0, 1920.0, 1080.0),+ Some((10.25, 20.75, 301.25, 199.5))+ )+ .unwrap(),+ crate::linux_instant_camera::PhysicalRect {+ x: -1910,+ y: 20,+ width: 302,+ height: 200+ },+ );+ assert_eq!(+ physical_capture_rect((0.0, -1080.0, 1919.0, 1079.0), None).unwrap(),+ crate::linux_instant_camera::PhysicalRect {+ x: 0,+ y: -1080,+ width: 1918,+ height: 1078+ },+ );+ }++ #[test]+ fn instant_physical_capture_reference_clamps_and_rejects_invalid_geometry() {+ assert_eq!(+ physical_capture_rect(+ (0.0, 0.0, 1920.0, 1080.0),+ Some((-50.0, -10.0, 3000.0, 2000.0))+ )+ .unwrap(),+ crate::linux_instant_camera::PhysicalRect {+ x: 0,+ y: 0,+ width: 1920,+ height: 1080+ },+ );+ assert!(physical_capture_rect((f64::NAN, 0.0, 1920.0, 1080.0), None).is_err());+ }++ struct PreparationLease(std::sync::Arc<std::sync::atomic::AtomicBool>);+ impl Drop for PreparationLease {+ fn drop(&mut self) {+ self.0.store(true, Ordering::SeqCst);+ }+ }++ #[tokio::test]+ async fn instant_preparation_cancel_wakes_pending_first_frame_and_drops_source_reservation()+ {+ let attempt = Attempt::new();+ let dropped = Arc::new(AtomicBool::new(false));+ let source = PreparationLease(dropped.clone());+ let owner = attempt.clone();+ let (tx, rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn(async move {+ owner+ .while_active(async move {+ let _source = source;+ tx.send(()).unwrap();+ std::future::pending::<Result<(), String>>().await+ })+ .await+ });+ rx.await.unwrap();+ attempt.cancel();+ assert!(task.await.unwrap().is_err());+ assert!(dropped.load(Ordering::SeqCst));+ assert!(!attempt.has_capture());+ assert!(attempt.upload().check().is_err());+ }++ #[tokio::test]+ async fn instant_preparation_cancel_before_poll_never_requests_or_hides_preview() {+ let attempt = Attempt::new();+ attempt.cancel();+ let result: Result<(), String> = attempt+ .while_active(async {+ panic!("cancelled preparation must not contact the preview or hide windows")+ })+ .await;+ assert!(result.is_err());+ }++ #[tokio::test]+ async fn instant_preparation_rechecks_cancel_after_first_frame_arrives() {+ let attempt = Attempt::new();+ let owner = attempt.clone();+ let result = attempt+ .while_active(async move {+ owner.cancel();+ Ok(7)+ })+ .await;+ assert!(result.is_err());+ }++ #[tokio::test]+ async fn instant_preparation_preserves_fresh_source_and_failure_identity() {+ let attempt = Attempt::new();+ assert_eq!(attempt.while_active(async { Ok(7) }).await.unwrap(), 7);+ let result: Result<(), String> = attempt+ .while_active(async { Err("first mask unavailable".into()) })+ .await;+ assert_eq!(result.unwrap_err(), "first mask unavailable");+ assert!(!attempt.cancelled());+ }++ #[tokio::test]+ async fn instant_builder_rejects_unprepared_screen_camera_and_joins_unused_attempt() {+ let target = ScreenCaptureTarget::Window {+ id: "1".parse().unwrap(),+ };+ let builder = instant_recording::Actor::builder(+ PathBuf::from("unused-activation-test"),+ target.clone(),+ );+ let lifecycle = builder.lifecycle();+ assert!(configure_screen_camera(builder, &target, true, None).is_err());+ assert_eq!(+ lifecycle.wait_for_quiescence().await,+ instant_recording::InstantQuiescence::Joined+ );+ }++ #[tokio::test]+ async fn instant_builder_preserves_camera_only_and_unselected_camera_paths() {+ for (target, requested) in [+ (ScreenCaptureTarget::CameraOnly, true),+ (+ ScreenCaptureTarget::Window {+ id: "1".parse().unwrap(),+ },+ false,+ ),+ ] {+ let builder = instant_recording::Actor::builder(+ PathBuf::from("unused-activation-test"),+ target.clone(),+ );+ let lifecycle = builder.lifecycle();+ drop(configure_screen_camera(builder, &target, requested, None).unwrap());+ assert_eq!(+ lifecycle.wait_for_quiescence().await,+ instant_recording::InstantQuiescence::Joined+ );+ }+ }++ #[test]+ fn instant_screen_camera_support_rejects_window_wayland_and_preserves_studio() {+ let mut inputs = StartRecordingInputs {+ capture_target: ScreenCaptureTarget::Window {+ id: "1".parse().unwrap(),+ },+ capture_system_audio: false,+ mode: RecordingMode::Instant,+ organization_id: None,+ };+ assert!(validate_screen_camera_support(&inputs, true, true).is_err());+ assert!(validate_screen_camera_support(&inputs, false, false).is_ok());+ inputs.capture_target = ScreenCaptureTarget::Display {+ id: "1".parse().unwrap(),+ };+ assert!(validate_screen_camera_support(&inputs, true, true).is_ok());+ assert!(validate_screen_camera_support(&inputs, true, false).is_err());+ inputs.mode = RecordingMode::Studio;+ assert!(validate_screen_camera_support(&inputs, true, false).is_ok());+ inputs.mode = RecordingMode::Instant;+ inputs.capture_target = ScreenCaptureTarget::CameraOnly;+ assert!(validate_screen_camera_support(&inputs, true, false).is_ok());+ }++ #[tokio::test]+ async fn owned_waiter_drop_cancels_without_aborting_cleanup() {+ let attempt = Attempt::new();+ let (release, released) = tokio::sync::oneshot::channel();+ let (finished, finished_rx) = tokio::sync::oneshot::channel();+ let cleaned = Arc::new(AtomicBool::new(false));+ let worker_cleaned = cleaned.clone();+ let mut waiter = Box::pin(owned_reply(+ attempt.clone(),+ async move {+ released.await.unwrap();+ worker_cleaned.store(true, Ordering::Release);+ Ok(())+ },+ async move {+ finished.send(()).unwrap();+ },+ ));+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut waiter)+ .await+ .is_err()+ );+ drop(waiter);+ assert!(attempt.cancelled());+ assert!(!cleaned.load(Ordering::Acquire));+ release.send(()).unwrap();+ tokio::time::timeout(Duration::from_secs(1), finished_rx)+ .await+ .unwrap()+ .unwrap();+ assert!(cleaned.load(Ordering::Acquire));+ }+ #[tokio::test]+ async fn owned_work_failure_returns_error_without_success_or_permission() {+ let attempt = Attempt::new();+ let result: Result<(), _> = owned_reply(+ attempt.clone(),+ async { Err("required output failed".into()) },+ async {},+ )+ .await;+ assert!(result.is_err());+ assert!(!attempt.ui_ready());+ attempt.cancel();+ assert!(attempt.authorize().is_err());+ }+ #[tokio::test]+ async fn owned_work_panic_retains_unconfirmed_cleanup() {+ let attempt = Attempt::new();+ let result: Result<(), _> = owned_reply(+ attempt.clone(),+ async { panic!("failed finalization owner") },+ async {},+ )+ .await;+ assert!(result.unwrap_err().contains("unconfirmed"));+ assert!(attempt.0.cleanup_uncertain.load(Ordering::Acquire));+ assert!(attempt.cancelled());+ assert!(!attempt.ui_ready());+ }+ #[tokio::test]+ async fn cancel_before_builder_poll_joins_unused_core_lifecycle() {+ let attempt = Attempt::new();+ let builder = instant_recording::Actor::builder(+ PathBuf::from("unused-synthetic.cap"),+ ScreenCaptureTarget::CameraOnly,+ );+ attempt+ .attach(PathBuf::from("unused-synthetic.cap"), builder.lifecycle())+ .await+ .unwrap();+ attempt.cancel();+ drop(builder);+ assert!(attempt.capture_cleanup().await);+ assert!(attempt.cancelled());+ assert!(attempt.authorize().is_err());+ }+ #[tokio::test]+ async fn stop_retry_signals_cancellation_before_waiting_for_operation_lock() {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ let active = attempt.0.operation.lock().await;+ attempt.prepare_control();+ assert!(attempt.cancelled());+ assert!(attempt.upload().check().is_err());+ drop(active);+ }+ #[test]+ fn explicit_camera_only_system_audio_request_is_rejected_before_normalization() {+ let mut inputs = StartRecordingInputs {+ capture_target: ScreenCaptureTarget::CameraOnly,+ capture_system_audio: true,+ mode: RecordingMode::Instant,+ organization_id: None,+ };+ assert!(validate_inputs(&inputs).is_err());+ assert!(inputs.capture_system_audio);+ inputs.capture_system_audio = false;+ assert!(validate_inputs(&inputs).is_ok());+ inputs.capture_system_audio = true;+ inputs.mode = RecordingMode::Studio;+ assert!(validate_inputs(&inputs).is_ok());+ }+ #[tokio::test]+ async fn terminal_observer_does_not_revoke_an_owned_successful_stop() {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ let active = attempt.0.operation.lock().await;+ assert!(!attempt.terminal_needs_cleanup());+ assert!(!attempt.cancelled());+ drop(active);+ assert!(attempt.terminal_needs_cleanup());+ assert!(attempt.cancelled());+ }+ #[tokio::test]+ async fn local_completion_rechecks_after_held_app_lock_before_success_or_delete() {+ for delete_after_upload in [false, true] {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ let state = tokio::sync::RwLock::new(Vec::new());+ let held = state.read().await;+ let deleted = AtomicBool::new(false);+ let shared = AtomicBool::new(false);+ let future = run_control(+ &attempt,+ false,+ || true,+ || async {+ let result = complete_local(+ &attempt,+ Ok(()),+ state.write(),+ |mut state, result| async move {+ state.push(result.is_ok());+ Ok(())+ },+ )+ .await;+ if result.is_ok() {+ shared.store(true, Ordering::Release);+ if delete_after_upload {+ deleted.store(true, Ordering::Release);+ }+ }+ attempt.record_terminal(false, result)+ },+ );+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ attempt.prepare_control();+ drop(held);+ assert!(future.await.is_err());+ assert_eq!(*state.read().await, vec![false]);+ assert!(!deleted.load(Ordering::Acquire));+ assert!(!shared.load(Ordering::Acquire));+ }+ }++ #[tokio::test]+ async fn local_completion_rechecks_after_owned_cleanup_await() {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ let state = tokio::sync::RwLock::new(false);+ let (release, released) = tokio::sync::oneshot::channel();+ let (entered, entering) = tokio::sync::oneshot::channel();+ let shared = AtomicBool::new(false);+ let future = run_control(+ &attempt,+ false,+ || true,+ || async {+ let result = complete_local(+ &attempt,+ Ok(()),+ state.write(),+ |mut state, result| async move {+ assert!(result.is_ok());+ entered.send(()).unwrap();+ released.await.unwrap();+ *state = true;+ Ok(())+ },+ )+ .await;+ if result.is_ok() {+ shared.store(true, Ordering::Release);+ }+ attempt.record_terminal(false, result)+ },+ );+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ entering.await.unwrap();+ attempt.prepare_control();+ release.send(()).unwrap();+ assert!(future.await.is_err());+ assert!(*state.read().await);+ assert!(!shared.load(Ordering::Acquire));+ }++ #[tokio::test]+ async fn queued_stop_and_discard_replay_first_joined_error() {+ for queued_discard in [false, true] {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ let current = AtomicBool::new(true);+ let state = tokio::sync::RwLock::new(());+ let (release, released) = tokio::sync::oneshot::channel();+ let first = run_control(+ &attempt,+ false,+ || current.load(Ordering::Acquire),+ || async {+ released.await.unwrap();+ let result = complete_local(+ &attempt,+ Err::<(), _>("required audio failed".into()),+ state.write(),+ |_, result| async move {+ assert_eq!(result.unwrap_err(), "required audio failed");+ Err("later cleanup error".into())+ },+ )+ .await;+ attempt.0.ui_ready.store(true, Ordering::Release);+ let result = attempt.record_terminal(false, result);+ current.store(false, Ordering::Release);+ result+ },+ );+ tokio::pin!(first);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut first)+ .await+ .is_err()+ );+ attempt.prepare_control();+ let second = run_control(+ &attempt,+ queued_discard,+ || current.load(Ordering::Acquire),+ || async { panic!("queued control must not finalize or delete again") },+ );+ tokio::pin!(second);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut second)+ .await+ .is_err()+ );+ release.send(()).unwrap();+ assert_eq!(first.await.unwrap_err(), "required audio failed");+ assert_eq!(second.await.unwrap_err(), "required audio failed");+ }+ }++ #[tokio::test]+ async fn successful_stop_is_idempotent_but_is_not_successful_discard() {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ run_control(+ &attempt,+ false,+ || true,+ || async { attempt.record_terminal(false, Ok(())) },+ )+ .await+ .unwrap();+ run_control(+ &attempt,+ false,+ || false,+ || async { panic!("already finished") },+ )+ .await+ .unwrap();+ let result = run_control(+ &attempt,+ true,+ || false,+ || async { panic!("must not delete") },+ )+ .await;+ assert!(result.unwrap_err().contains("not discarded"));+ run_control(+ &attempt,+ false,+ || false,+ || async { panic!("already finished") },+ )+ .await+ .unwrap();+ }++ #[tokio::test]+ async fn uncertain_cleanup_and_unrelated_generation_never_replay_ui_ready_success() {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ attempt.0.ui_ready.store(true, Ordering::Release);+ for _ in 0..2 {+ assert_eq!(+ run_control(+ &attempt,+ false,+ || true,+ || async { Err("cleanup unconfirmed".into()) }+ )+ .await+ .unwrap_err(),+ "cleanup unconfirmed"+ );+ }+ assert!(attempt.0.terminal.lock().unwrap().is_none());+ let result = run_control(+ &attempt,+ false,+ || false,+ || async { panic!("stale generation must not execute") },+ )+ .await;+ assert!(result.unwrap_err().contains("superseded"));+ }++ #[tokio::test]+ async fn terminal_failure_persists_failed_metadata_and_keeps_local_media() {+ let path =+ std::env::temp_dir().join(format!("cap-instant-terminal-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&path).unwrap();+ let media = path.join("synthetic-bytes");+ std::fs::write(&media, b"preserve").unwrap();+ RecordingMeta {+ platform: None,+ project_path: path.clone(),+ pretty_name: "Synthetic terminal failure".into(),+ sharing: None,+ inner: RecordingMetaInner::Instant(InstantRecordingMeta::InProgress {+ recording: false,+ }),+ upload: Some(cap_project::UploadMeta::Complete),+ }+ .save_for_project()+ .unwrap();+ persist_terminal_failure(&path, "late cancellation").await;+ let meta = RecordingMeta::load_for_project(&path).unwrap();+ assert!(+ matches!(meta.inner, RecordingMetaInner::Instant(InstantRecordingMeta::Failed { error }) if error == "late cancellation")+ );+ assert_eq!(std::fs::read(&media).unwrap(), b"preserve");+ std::fs::remove_dir_all(path).unwrap();+ }+ fn synthetic_success_effects(+ attempt: &Attempt,+ copies: &Mutex<Vec<String>>,+ cancel_before_copy: bool,+ clipboard_error: bool,+ ) -> Result<(), String> {+ dispatch_success_effects(+ attempt,+ "https://example.invalid/s/fixture?existing=1",+ SuccessEffects {+ recording_automation: || {},+ upload_automation: || {},+ open_link: |_| {+ if cancel_before_copy {+ attempt.cancel();+ }+ Ok(())+ },+ copy_link: |link| {+ copies.lock().unwrap().push(link);+ if clipboard_error {+ Err("synthetic clipboard unavailable".into())+ } else {+ Ok(())+ }+ },+ sound: || {},+ },+ )+ }++ async fn finish_synthetic_control(+ attempt: &Attempt,+ state: &tokio::sync::RwLock<()>,+ copies: &Mutex<Vec<String>>,+ outcome: Result<Option<()>, String>,+ discard: bool,+ ) -> Result<(), String> {+ let successful_upload = matches!(outcome, Ok(Some(())));+ let mut result =+ complete_local(attempt, outcome, state.write(), |_, _| async { Ok(()) }).await;+ if result.is_ok() && successful_upload {+ result = synthetic_success_effects(attempt, copies, false, false);+ }+ attempt.record_terminal(discard, result)+ }++ #[tokio::test]+ async fn normal_instant_success_copies_original_link_once_without_auto_open_and_not_on_replay()+ {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ let state = tokio::sync::RwLock::new(());+ let copies = Mutex::new(Vec::new());+ run_control(+ &attempt,+ false,+ || true,+ || finish_synthetic_control(&attempt, &state, &copies, Ok(Some(())), false),+ )+ .await+ .unwrap();+ run_control(+ &attempt,+ false,+ || false,+ || async { panic!("successful replay must not dispatch effects") },+ )+ .await+ .unwrap();+ assert_eq!(+ *copies.lock().unwrap(),+ vec!["https://example.invalid/s/fixture?existing=1"]+ );+ }++ #[tokio::test]+ async fn failed_and_discarded_controls_never_copy_share_link() {+ for (outcome, discard) in [+ (Err("required source failed".into()), false),+ (Ok(None), true),+ ] {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ let state = tokio::sync::RwLock::new(());+ let copies = Mutex::new(Vec::new());+ let result = run_control(+ &attempt,+ discard,+ || true,+ || finish_synthetic_control(&attempt, &state, &copies, outcome, discard),+ )+ .await;+ assert_eq!(result.is_ok(), discard);+ assert!(copies.lock().unwrap().is_empty());+ }+ }++ #[tokio::test]+ async fn cancelled_held_local_completion_and_queued_replay_never_copy_link() {+ let attempt = Attempt::new();+ attempt.0.started.send_replace(true);+ let state = tokio::sync::RwLock::new(());+ let held = state.read().await;+ let copies = Mutex::new(Vec::new());+ let first = run_control(+ &attempt,+ false,+ || true,+ || finish_synthetic_control(&attempt, &state, &copies, Ok(Some(())), false),+ );+ tokio::pin!(first);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut first)+ .await+ .is_err()+ );+ attempt.prepare_control();+ let second = run_control(+ &attempt,+ false,+ || false,+ || async { panic!("cancelled replay must not dispatch effects") },+ );+ tokio::pin!(second);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut second)+ .await+ .is_err()+ );+ drop(held);+ assert!(first.await.is_err());+ assert!(second.await.is_err());+ assert!(copies.lock().unwrap().is_empty());+ }++ #[test]+ fn clipboard_boundary_rechecks_revocation_and_preserves_nonfatal_clipboard_error_policy() {+ let cancelled = Attempt::new();+ let cancelled_copies = Mutex::new(Vec::new());+ assert!(synthetic_success_effects(&cancelled, &cancelled_copies, true, false).is_err());+ assert!(cancelled_copies.lock().unwrap().is_empty());+ let healthy = Attempt::new();+ let attempted_copies = Mutex::new(Vec::new());+ synthetic_success_effects(&healthy, &attempted_copies, false, true).unwrap();+ assert_eq!(attempted_copies.lock().unwrap().len(), 1);+ }+ }+}++#[cfg(all(test, target_os = "linux"))]+mod studio_joined_completion_tests {+ use super::*;+ use std::sync::atomic::{AtomicUsize, Ordering};++ #[tokio::test]+ async fn unconfirmed_stop_never_enters_local_completion() {+ let effects = AtomicUsize::new(0);+ let result = after_studio_join(+ async {+ studio_recording::StudioStopReport {+ accepted_intent: true,+ quiescence: studio_recording::StudioQuiescence::Unconfirmed,+ result: Err("source stop unknown".into()),+ }+ },+ |_| async {+ effects.fetch_add(1, Ordering::SeqCst);+ Ok(())+ },+ )+ .await;+ assert!(result.is_err());+ assert_eq!(effects.load(Ordering::SeqCst), 0);+ }++ #[tokio::test]+ async fn losing_preserve_cannot_finish_while_discard_local_cleanup_is_waiting() {+ let effects = Arc::new(AtomicUsize::new(0));+ let (entered, entry) = tokio::sync::oneshot::channel();+ let (release, released) = tokio::sync::oneshot::channel();+ let owner = tokio::spawn({+ let effects = effects.clone();+ async move {+ after_studio_join(+ async {+ studio_recording::StudioStopReport {+ accepted_intent: true,+ quiescence: studio_recording::StudioQuiescence::Joined,+ result: Ok(studio_recording::CompletedRecording {+ project_path: std::path::PathBuf::from("synthetic.cap"),+ meta: cap_project::StudioRecordingMeta::MultipleSegments {+ inner: cap_project::MultipleSegments {+ segments: Vec::new(),+ cursors: Default::default(),+ status: Some(cap_project::StudioRecordingStatus::Complete),+ },+ },+ cursor_data: Default::default(),+ }),+ }+ },+ |_| async move {+ entered.send(()).unwrap();+ released.await.unwrap();+ effects.fetch_add(1, Ordering::SeqCst);+ Ok(())+ },+ )+ .await+ }+ });+ entry.await.unwrap();+ let losing = after_studio_join(+ async {+ studio_recording::StudioStopReport {+ accepted_intent: false,+ quiescence: studio_recording::StudioQuiescence::Joined,+ result: Err("different terminal action owns attempt".into()),+ }+ },+ |_| async {+ effects.fetch_add(100, Ordering::SeqCst);+ Ok(())+ },+ )+ .await;+ assert!(losing.is_err());+ assert!(!owner.is_finished());+ assert_eq!(effects.load(Ordering::SeqCst), 0);+ release.send(()).unwrap();+ owner.await.unwrap().unwrap();+ assert_eq!(effects.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn joined_failure_waits_for_app_lock_without_turning_into_success() {+ let app_lock = Arc::new(tokio::sync::RwLock::new(()));+ let held = app_lock.clone().write_owned().await;+ let effects = Arc::new(AtomicUsize::new(0));+ let (joined_tx, joined_rx) = tokio::sync::oneshot::channel();+ let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();+ let task = tokio::spawn({+ let effects = effects.clone();+ async move {+ after_studio_join(+ async {+ joined_rx.await.unwrap();+ studio_recording::StudioStopReport {+ accepted_intent: true,+ quiescence: studio_recording::StudioQuiescence::Joined,+ result: Err("requested microphone failed".into()),+ }+ },+ |result| async move {+ let _ = entered_tx.send(());+ let _state = app_lock.write().await;+ effects.fetch_add(1, Ordering::SeqCst);+ result.map(|_| ())+ },+ )+ .await+ }+ });+ assert_eq!(effects.load(Ordering::SeqCst), 0);+ joined_tx.send(()).unwrap();+ entered_rx.await.unwrap();+ assert!(!task.is_finished());+ assert_eq!(effects.load(Ordering::SeqCst), 0);+ drop(held);+ assert!(task.await.unwrap().is_err());+ assert_eq!(effects.load(Ordering::SeqCst), 1);+ }+}++#[cfg(all(test, windows))]+mod windows_studio_control_tests {+ use super::*;++ #[tokio::test]+ async fn studio_unconfirmed_or_losing_stop_cannot_restore_or_delete() {+ for (accepted_intent, stop_acknowledged) in [(true, false), (false, true), (false, false)] {+ let effects = std::sync::atomic::AtomicUsize::new(0);+ let result = after_windows_studio_stop(+ async {+ studio_recording::WindowsStudioStopReport {+ accepted_intent,+ stop_acknowledged,+ result: Err("encoder join unconfirmed".into()),+ }+ },+ |_| async {+ effects.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Ok(())+ },+ )+ .await;+ assert!(result.is_err());+ assert_eq!(effects.load(std::sync::atomic::Ordering::SeqCst), 0);+ }+ }+}diff --git a/apps/desktop/src-tauri/src/screenshot_editor.rs b/apps/desktop/src-tauri/src/screenshot_editor.rsindex 222da938b..c573782b9 100644--- a/apps/desktop/src-tauri/src/screenshot_editor.rs+++ b/apps/desktop/src-tauri/src/screenshot_editor.rs@@ -1142,7 +1142,11 @@ async fn recognize_screenshot_ocr_image(#[cfg(not(any(target_os = "macos", target_os = "windows")))]async fn recognize_screenshot_ocr_image(- _image: ScreenshotOcrImage,+ ScreenshotOcrImage {+ bgra: _bgra,+ width: _width,+ height: _height,+ }: ScreenshotOcrImage,) -> Result<ScreenshotOcrResult, String> {Err("OCR is only available on macOS and Windows".to_string())}diff --git a/apps/desktop/src-tauri/src/target_select_overlay.rs b/apps/desktop/src-tauri/src/target_select_overlay.rsindex f48963b39..a1c2212aa 100644--- a/apps/desktop/src-tauri/src/target_select_overlay.rs+++ b/apps/desktop/src-tauri/src/target_select_overlay.rs@@ -13,7 +13,7 @@ use crate::{App, ArcLock, general_settings,recording_settings::RecordingTargetMode,window_exclusion::WindowExclusion,- windows::{CapWindowId, ShowCapWindow, hide_overlay, show_overlay},+ windows::{CapWindowId, ShowCapWindow, hide_overlay},};use scap_targets::{Display, DisplayId, Window, WindowId,@@ -59,6 +59,12 @@ pub async fn open_target_select_overlays(specific_display_id: Option<String>,target_mode: Option<RecordingTargetMode>,) -> Result<(), String> {+ let reveal_generation = crate::clean_capture::generation(&app);+ if crate::clean_capture::phase(&app).is_some() {+ return Err(+ "Close or finish clean Studio recording before opening the target picker".into(),+ );+ }let start = Instant::now();let resolved_specific_display_id = specific_display_id.as_ref().map(|id_str| {@@ -112,10 +118,10 @@ pub async fn open_target_select_overlays(.get(&app);if let Some(window) = existing_window {- show_overlay(&window);+ crate::clean_capture::schedule_overlay_reveal(&window, reveal_generation, false);if should_focus {- focus_target_select_overlay(&window);+ focus_target_select_overlay(&window, reveal_generation);}state.spawn(display_id, window.clone());@@ -127,7 +133,7 @@ pub async fn open_target_select_overlays(.show(&app).await{- finish_created_target_select_overlay(&window, should_focus);+ finish_created_target_select_overlay(&window, should_focus, reveal_generation);}} else {let app_clone = app.clone();@@ -140,7 +146,7 @@ pub async fn open_target_select_overlays(.show(&app_clone).await{- finish_created_target_select_overlay(&window, should_focus);+ finish_created_target_select_overlay(&window, should_focus, reveal_generation);}});}@@ -152,7 +158,7 @@ pub async fn open_target_select_overlays(.get(&app);if let Some(window) = focus_window {- focus_target_select_overlay(&window);+ focus_target_select_overlay(&window, reveal_generation);}let window_exclusions = general_settings::GeneralSettingsStore::get(&app)@@ -215,25 +221,26 @@ pub async fn open_target_select_overlays(Ok(())}-fn finish_created_target_select_overlay(window: &WebviewWindow, should_focus: bool) {+fn finish_created_target_select_overlay(+ window: &WebviewWindow,+ should_focus: bool,+ reveal_generation: u32,+) {#[cfg(target_os = "macos")]- let _ = (window, should_focus);+ let _ = (window, should_focus, reveal_generation);#[cfg(not(target_os = "macos"))]{- window.show().ok();- if should_focus {- focus_target_select_overlay(window);- }+ crate::clean_capture::schedule_overlay_reveal(window, reveal_generation, should_focus);}}-fn focus_target_select_overlay(window: &WebviewWindow) {+fn focus_target_select_overlay(window: &WebviewWindow, reveal_generation: u32) {#[cfg(target_os = "macos")]- let _ = window;+ let _ = (window, reveal_generation);#[cfg(not(target_os = "macos"))]- window.set_focus().ok();+ crate::clean_capture::schedule_overlay_focus(window, reveal_generation);}fn should_skip_window(window: &Window, exclusions: &[WindowExclusion]) -> bool {@@ -378,7 +385,10 @@ pub async fn display_information(display_id: &str) -> Result<DisplayInformation,#[tauri::command]#[instrument]pub async fn focus_window(window_id: WindowId) -> Result<(), String> {+ #[cfg(any(target_os = "macos", target_os = "windows"))]let window = Window::from_id(&window_id).ok_or("Window not found")?;+ #[cfg(not(any(target_os = "macos", target_os = "windows")))]+ Window::from_id(&window_id).ok_or("Window not found")?;#[cfg(target_os = "macos")]{@@ -459,6 +469,8 @@ impl WindowFocusManager {pub fn spawn(&self, id: &DisplayId, window: WebviewWindow) {let display_id = id.clone();let task_id = id.to_string();+ #[cfg(windows)]+ let reveal_generation = crate::clean_capture::generation(window.app_handle());let handle = tokio::spawn(async move {let app = window.app_handle();let mut main_window_was_seen = false;@@ -505,7 +517,11 @@ impl WindowFocusManager {overlay_focused || cap_main.is_focused().ok().unwrap_or_default();if !should_refocus {- window.set_focus().ok();+ crate::clean_capture::schedule_overlay_reveal(+ &window,+ reveal_generation,+ true,+ );}}diff --git a/apps/desktop/src-tauri/src/tray.rs b/apps/desktop/src-tauri/src/tray.rsindex 4d0d8f7e3..e7c16babc 100644--- a/apps/desktop/src-tauri/src/tray.rs+++ b/apps/desktop/src-tauri/src/tray.rs@@ -32,7 +32,6 @@ const THUMBNAIL_SIZE: u32 = 32;#[cfg(target_os = "linux")]#[derive(Clone, Copy)]enum LinuxTrayIcon {- Default,Instant,Screenshot,Studio,@@ -43,7 +42,6 @@ enum LinuxTrayIcon {impl LinuxTrayIcon {fn name(self) -> &'static str {match self {- Self::Default => "so.cap.desktop-tray-default-symbolic",Self::Instant => "so.cap.desktop-tray-instant-symbolic",Self::Screenshot => "so.cap.desktop-tray-screenshot-symbolic",Self::Studio => "so.cap.desktop-tray-studio-symbolic",@@ -53,9 +51,6 @@ impl LinuxTrayIcon {fn svg(self) -> &'static str {match self {- Self::Default => {- include_str!("../icons/linux/so.cap.desktop-tray-default-symbolic.svg")- }Self::Instant => {include_str!("../icons/linux/so.cap.desktop-tray-instant-symbolic.svg")}@@ -787,7 +782,7 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {move |app: &AppHandle, event| match TrayItem::try_from(event.id) {Ok(TrayItem::OpenCap) => {let app = app.clone();- tokio::spawn(async move {+ tauri::async_runtime::spawn(async move {let _ = ShowCapWindow::Main {init_target_mode: None,}@@ -1123,3 +1118,37 @@ pub fn create_tray(app: &AppHandle) -> tauri::Result<()> {Ok(())}++#[cfg(target_os = "linux")]+pub(crate) fn clean_stop_icon() -> Result<cap_utils::linux_recording_stop::StopTrayIcon, String> {+ let image = image::load_from_memory(include_bytes!("../icons/tray-stop-icon.png"))+ .map_err(|error| error.to_string())?+ .resize_exact(32, 32, image::imageops::FilterType::Triangle)+ .into_rgba8();+ cap_utils::linux_recording_stop::StopTrayIcon::from_rgba(32, 32, image.as_raw())+}++#[cfg(target_os = "linux")]+pub(crate) async fn set_clean_stop_mode(+ app: &AppHandle,+ generation: u32,+ active: bool,+) -> Result<(), String> {+ let (tx, rx) = tokio::sync::oneshot::channel();+ let handle = app.clone();+ app.run_on_main_thread(move || {+ let result = if crate::clean_capture::wayland_generation(&handle) != Some(generation) {+ Err("Recording tray transition was superseded".to_string())+ } else if let Some(tray) = handle.tray_by_id("tray") {+ tray.set_visible(!active).map_err(|error| error.to_string())+ } else {+ Ok(())+ };+ let _ = tx.send(result);+ })+ .map_err(|error| error.to_string())?;+ tokio::time::timeout(std::time::Duration::from_secs(2), rx)+ .await+ .map_err(|_| "Recording tray transition timed out".to_string())?+ .map_err(|_| "Recording tray transition was lost".to_string())?+}diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 95f5827ed..5782b04ce 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -554,6 +554,7 @@ pub async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {}pub struct InstantMultipartUpload {+ #[cfg(not(target_os = "linux"))]pub handle: tokio::task::JoinHandle<Result<(), AuthedApiError>>,}@@ -567,39 +568,43 @@ impl InstantMultipartUpload {recording_dir: PathBuf,realtime_upload_done: Option<Receiver<()>>,) -> Self {- Self {- handle: spawn_actor(async move {- let start = Instant::now();- let result = Self::run(- app.clone(),- file_path.clone(),- pre_created_video,- recording_dir,- realtime_upload_done,- )- .await;- async_capture_event(- &app,- match &result {- Ok(meta) => AnalyticsEvent::MultipartUploadComplete {- duration: start.elapsed(),- length: meta- .as_ref()- .map(|v| Duration::from_secs(v.duration_in_secs as u64))- .unwrap_or_default(),- size: std::fs::metadata(file_path)- .map(|m| ((m.len() as f64) / 1_000_000.0) as u64)- .unwrap_or_default(),- },- Err(err) => AnalyticsEvent::MultipartUploadFailed {- duration: start.elapsed(),- error: err.to_string(),- },+ let handle = spawn_actor(async move {+ let start = Instant::now();+ let result = Self::run(+ app.clone(),+ file_path.clone(),+ pre_created_video,+ recording_dir,+ realtime_upload_done,+ )+ .await;+ async_capture_event(+ &app,+ match &result {+ Ok(meta) => AnalyticsEvent::MultipartUploadComplete {+ duration: start.elapsed(),+ length: meta+ .as_ref()+ .map(|v| Duration::from_secs(v.duration_in_secs as u64))+ .unwrap_or_default(),+ size: std::fs::metadata(file_path)+ .map(|m| ((m.len() as f64) / 1_000_000.0) as u64)+ .unwrap_or_default(),},- );+ Err(err) => AnalyticsEvent::MultipartUploadFailed {+ duration: start.elapsed(),+ error: err.to_string(),+ },+ },+ );- result.map(|_| ())- }),+ result.map(|_| ())+ });+ #[cfg(target_os = "linux")]+ drop(handle);+ Self {+ #[cfg(not(target_os = "linux"))]+ handle,}}@@ -3221,3 +3226,1216 @@ mod tests {);}}++#[cfg(target_os = "linux")]+pub(crate) mod strict_instant {+ use super::*;+ use cap_enc_ffmpeg::segmented_stream::{SegmentCompletedEvent, SegmentMediaType};+ use futures::{FutureExt as _, stream::FuturesUnordered};+ use std::{future::Future, panic::AssertUnwindSafe, sync::atomic::AtomicBool};++ #[derive(Clone)]+ pub struct Control(Arc<ControlInner>);++ struct ControlInner {+ decision: tokio::sync::watch::Sender<u8>,+ cleanup: tokio::sync::watch::Sender<Option<bool>>,+ }++ pub struct Permission {+ control: Control,+ granted: bool,+ }++ impl Control {+ pub fn new() -> (Self, Permission) {+ let (decision, _) = tokio::sync::watch::channel(0);+ let (cleanup, _) = tokio::sync::watch::channel(None);+ let control = Self(Arc::new(ControlInner { decision, cleanup }));+ (+ control.clone(),+ Permission {+ control,+ granted: false,+ },+ )+ }++ pub fn deny(&self) {+ self.0.decision.send_replace(2);+ }++ pub fn check(&self) -> Result<(), AuthedApiError> {+ if *self.0.decision.borrow() == 2 {+ Err("Instant upload authorization revoked".to_string().into())+ } else {+ Ok(())+ }+ }++ pub async fn step<T, F>(&self, step: impl FnOnce() -> F) -> Result<T, AuthedApiError>+ where+ F: Future<Output = Result<T, AuthedApiError>>,+ {+ self.check()?;+ let result = step().await;+ self.check()?;+ result+ }++ async fn complete<T, F>(&self, complete: impl FnOnce() -> F) -> Result<(), AuthedApiError>+ where+ F: Future<Output = Result<T, AuthedApiError>>,+ {+ self.step(complete).await.map(drop)+ }++ async fn permission(&self) -> Result<(), AuthedApiError> {+ let mut decision = self.0.decision.subscribe();+ loop {+ let value = *decision.borrow_and_update();+ match value {+ 1 => return self.check(),+ 2 => return Err("Instant completion was denied".to_string().into()),+ _ => decision+ .changed()+ .await+ .map_err(|_| "Instant authorization owner lost")?,+ }+ }+ }++ async fn cancelled(&self) {+ let mut decision = self.0.decision.subscribe();+ loop {+ if *decision.borrow_and_update() == 2 {+ return;+ }+ if decision.changed().await.is_err() {+ return;+ }+ }+ }++ pub async fn joined(&self) -> bool {+ let mut cleanup = self.0.cleanup.subscribe();+ loop {+ let state = *cleanup.borrow_and_update();+ if let Some(joined) = state {+ return joined;+ }+ if cleanup.changed().await.is_err() {+ return false;+ }+ }+ }+ }++ impl Permission {+ pub fn grant(mut self) -> Result<(), AuthedApiError> {+ let changed = self.control.0.decision.send_if_modified(|state| {+ if *state != 0 {+ return false;+ }+ *state = 1;+ true+ });+ if !changed {+ return Err("Instant completion permission is no longer valid"+ .to_string()+ .into());+ }+ self.granted = true;+ self.control.check()+ }+ }++ impl Drop for Permission {+ fn drop(&mut self) {+ if !self.granted {+ self.control.deny();+ }+ }+ }++ struct WorkerGuard(Control);+ impl Drop for WorkerGuard {+ fn drop(&mut self) {+ let missing = self.0.0.cleanup.borrow().is_none();+ if missing {+ self.0.deny();+ let _ = self.0.0.cleanup.send_replace(Some(false));+ }+ }+ }++ struct Bridge {+ events: tokio::sync::mpsc::Receiver<SegmentCompletedEvent>,+ stop: Arc<AtomicBool>,+ thread: Option<std::thread::JoinHandle<()>>,+ }++ impl Bridge {+ fn new(+ source: std::sync::mpsc::Receiver<SegmentCompletedEvent>,+ ) -> Result<Self, AuthedApiError> {+ let (sender, events) = tokio::sync::mpsc::channel(12);+ let stop = Arc::new(AtomicBool::new(false));+ let stop_thread = stop.clone();+ let thread = std::thread::Builder::new()+ .name("strict-instant-events".into())+ .spawn(move || {+ while !stop_thread.load(Ordering::Acquire) {+ match source.recv_timeout(Duration::from_millis(100)) {+ Ok(event) => {+ if sender.blocking_send(event).is_err() {+ break;+ }+ }+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,+ }+ }+ })+ .map_err(|error| format!("Starting owned Instant event bridge: {error}"))?;+ Ok(Self {+ events,+ stop,+ thread: Some(thread),+ })+ }++ async fn finish(mut self) -> bool {+ self.events.close();+ self.stop.store(true, Ordering::Release);+ let thread = self.thread.take().unwrap();+ tokio::task::spawn_blocking(move || thread.join().is_ok())+ .await+ .unwrap_or(false)+ }+ }++ impl Drop for Bridge {+ fn drop(&mut self) {+ self.events.close();+ self.stop.store(true, Ordering::Release);+ if let Some(thread) = self.thread.take() {+ drop(tokio::task::spawn_blocking(move || thread.join()));+ }+ }+ }++ trait Transport: Send + Sync {+ fn put(+ &self,+ path: &str,+ bytes: Bytes,+ ) -> impl Future<Output = Result<(), AuthedApiError>> + Send;+ fn complete(&self) -> impl Future<Output = Result<(), AuthedApiError>> + Send;+ }++ struct LiveTransport<'a> {+ app: &'a AppHandle,+ video_id: &'a str,+ control: &'a Control,+ }++ impl Transport for LiveTransport<'_> {+ async fn put(&self, path: &str, bytes: Bytes) -> Result<(), AuthedApiError> {+ let mut failure = None;+ for attempt in 0..3 {+ if attempt > 0 {+ self.control+ .step(|| async {+ tokio::time::sleep(Duration::from_millis(500u64 << (attempt - 1)))+ .await;+ Ok(())+ })+ .await?;+ }+ let target = self+ .control+ .step(|| {+ api::upload_signed(+ self.app,+ PresignedS3PutRequest {+ video_id: self.video_id.into(),+ subpath: path.into(),+ method: PresignedS3PutRequestMethod::Put,+ meta: None,+ },+ )+ })+ .await?;+ let size = bytes.len() as u64;+ let mut request = self+ .app+ .state::<HttpClient>()+ .put(&target.url)+ .header("Content-Length", size)+ .header("Content-Type", content_type_for_upload_subpath(path))+ .timeout(Duration::from_secs(5 * 60))+ .body(bytes.clone());+ for (name, value) in target.headers {+ if !name.eq_ignore_ascii_case("content-length") {+ request = request.header(name, value);+ }+ }+ let result = self+ .control+ .step(|| async {+ let response =+ with_drive_content_range(request, &target.url, 0, size, size)+ .send()+ .await+ .map_err(AuthedApiError::from)?;+ if !response.status().is_success() {+ return Err(format!("Instant PUT failed: {}", response.status()).into());+ }+ Ok(())+ })+ .await;+ match result {+ Ok(()) => return Ok(()),+ Err(error) => {+ let network = matches!(&error, AuthedApiError::Timeout)+ || matches!(&error, AuthedApiError::Request(error) if is_reqwest_network_error(error));+ failure = Some(error);+ self.control.check()?;+ if network && attempt < 2 {+ network_recovery(self.app, self.control).await?;+ }+ }+ }+ self.control.check()?;+ }+ Err(failure.unwrap())+ }++ async fn complete(&self) -> Result<(), AuthedApiError> {+ let mut failure = None;+ for attempt in 0..3 {+ if attempt > 0 {+ self.control+ .step(|| async {+ tokio::time::sleep(Duration::from_millis(1000u64 << (attempt - 1)))+ .await;+ Ok(())+ })+ .await?;+ }+ match self+ .control+ .step(|| api::signal_recording_complete(self.app, self.video_id))+ .await+ {+ Ok(()) => return Ok(()),+ Err(error) => failure = Some(error),+ }+ self.control.check()?;+ }+ Err(failure.unwrap())+ }+ }++ fn event_path(event: &SegmentCompletedEvent) -> String {+ let media = match event.media_type {+ SegmentMediaType::Video => "video",+ SegmentMediaType::Audio => "audio",+ };+ if event.is_init {+ format!("segments/{media}/init.mp4")+ } else {+ format!("segments/{media}/segment_{:03}.m4s", event.index)+ }+ }++ async fn segment(+ transport: &impl Transport,+ control: &Control,+ event: SegmentCompletedEvent,+ ) -> Result<SegmentCompletedEvent, AuthedApiError> {+ control.check()?;+ let path = event_path(&event);+ let bytes = control+ .step(|| SegmentUploader::read_segment_data(&event.path, &path, event.file_size))+ .await?;+ if bytes.is_empty() || (event.file_size > 0 && (bytes.len() as u64) < event.file_size) {+ return Err(format!("Required Instant segment is incomplete: {path}").into());+ }+ control.step(|| transport.put(&path, bytes)).await?;+ Ok(event)+ }++ async fn segments(+ transport: &impl Transport,+ control: &Control,+ events: &mut tokio::sync::mpsc::Receiver<SegmentCompletedEvent>,+ required_audio: bool,+ ) -> Result<(), AuthedApiError> {+ let mut uploads = FuturesUnordered::new();+ let mut state = SegmentUploadState::new();+ let mut closed = false;+ let mut failure = None;+ let mut manifest_at = Instant::now();+ while !closed || !uploads.is_empty() {+ tokio::select! {+ _ = control.cancelled(), if failure.is_none() => { failure = Some("Instant upload cancelled".to_string().into()); closed = true; events.close(); }+ event = events.recv(), if !closed && uploads.len() < 6 => {+ match event { Some(event) => uploads.push(segment(transport, control, event)), None => closed = true }+ }+ Some(result) = uploads.next(), if !uploads.is_empty() => {+ match result {+ Ok(event) => {+ match (event.is_init, event.media_type) {+ (true, SegmentMediaType::Video) => state.video_init_uploaded = true,+ (true, SegmentMediaType::Audio) => state.audio_init_uploaded = true,+ (false, SegmentMediaType::Video) => { let _ = state.uploaded_video_segments.insert(event.index, event.duration); }+ (false, SegmentMediaType::Audio) => { let _ = state.uploaded_audio_segments.insert(event.index, event.duration); }+ }+ if failure.is_none() && manifest_at.elapsed() >= Duration::from_secs(1) {+ let manifest = serde_json::to_vec(&state.to_manifest()).map_err(|error| error.to_string());+ let result = match manifest { Ok(bytes) => control.step(|| transport.put("segments/manifest.json", bytes.into())).await, Err(error) => Err(error.into()) };+ if let Err(error) = result { failure = Some(error); closed = true; events.close(); }+ manifest_at = Instant::now();+ }+ }+ Err(error) => { failure = Some(error); closed = true; events.close(); }+ }+ }+ }+ if failure.is_some() {+ control.deny();+ closed = true;+ events.close();+ }+ }+ if let Some(error) = failure {+ return Err(error);+ }+ control.permission().await?;+ let manifest = state.to_complete_manifest();+ if !manifest.has_video_content()+ || (required_audio+ && (!state.audio_init_uploaded || state.uploaded_audio_segments.is_empty()))+ {+ return Err("Required Instant media track is missing".to_string().into());+ }+ let bytes = serde_json::to_vec(&manifest).map_err(|error| error.to_string())?;+ control+ .step(|| transport.put("segments/manifest.json", bytes.into()))+ .await?;+ control.step(|| transport.complete()).await+ }++ pub fn spawn(+ app: AppHandle,+ recording_dir: PathBuf,+ video: VideoUploadInfo,+ events: Option<std::sync::mpsc::Receiver<SegmentCompletedEvent>>,+ control: Control,+ required_audio: bool,+ ) -> SegmentUploader {+ SegmentUploader {+ handle: spawn_actor(async move {+ let _owner = WorkerGuard(control.clone());+ let _active = ActiveUploadGuard::new(&ACTIVE_UPLOADS);+ let result = if let Some(events) = events {+ match Bridge::new(events) {+ Ok(mut bridge) => {+ let transport = LiveTransport {+ app: &app,+ video_id: &video.id,+ control: &control,+ };+ let result = AssertUnwindSafe(segments(+ &transport,+ &control,+ &mut bridge.events,+ required_audio,+ ))+ .catch_unwind()+ .await;+ let joined = bridge.finish().await;+ let _ = control+ .0+ .cleanup+ .send_replace(Some(joined && result.is_ok()));+ match result {+ Ok(result) if joined => result,+ _ => {+ Err("Instant upload cleanup is unconfirmed".to_string().into())+ }+ }+ }+ Err(error) => {+ let _ = control.0.cleanup.send_replace(Some(true));+ Err(error)+ }+ }+ } else {+ let result =+ AssertUnwindSafe(multipart(&app, &recording_dir, &video, &control))+ .catch_unwind()+ .await;+ let _ = control.0.cleanup.send_replace(Some(result.is_ok()));+ result.unwrap_or_else(|_| {+ Err("Instant multipart cleanup is unconfirmed"+ .to_string()+ .into())+ })+ };+ if result.is_err() {+ control.deny();+ }+ result+ }),+ }+ }++ async fn network_recovery(app: &AppHandle, control: &Control) -> Result<(), AuthedApiError> {+ let started = Instant::now();+ let mut delay = CONNECTIVITY_PROBE_INITIAL_DELAY;+ while started.elapsed() <= NETWORK_RECOVERY_TIMEOUT {+ control+ .step(|| async {+ tokio::time::sleep(delay).await;+ Ok(())+ })+ .await?;+ if control+ .step(|| async { Ok(probe_connectivity(app).await) })+ .await?+ {+ return Ok(());+ }+ delay = (delay * 2).min(CONNECTIVITY_PROBE_MAX_DELAY);+ }+ Err("Instant upload network recovery timed out"+ .to_string()+ .into())+ }++ struct MultipartTarget<'a> {+ app: &'a AppHandle,+ video_id: &'a str,+ upload_id: &'a str,+ control: &'a Control,+ use_md5: bool,+ }++ async fn part(+ target: &MultipartTarget<'_>,+ chunk: Chunk,+ ) -> Result<UploadedPart, AuthedApiError> {+ let size = chunk.chunk.len();+ let md5_sum = target+ .use_md5+ .then(|| base64::encode(md5::compute(&chunk.chunk).0));+ for attempt in 0..2 {+ let url = target+ .control+ .step(|| {+ api::upload_multipart_presign_part(+ target.app,+ target.video_id,+ target.upload_id,+ chunk.part_number,+ md5_sum.as_deref(),+ )+ })+ .await?;+ let mut request = target+ .app+ .state::<HttpClient>()+ .put(&url)+ .header("Content-Length", size)+ .timeout(Duration::from_secs(5 * 60))+ .body(chunk.chunk.clone());+ if let Some(md5_sum) = &md5_sum {+ request = request.header("Content-MD5", md5_sum);+ }+ let request = with_drive_content_range(+ request,+ &url,+ chunk.offset,+ size as u64,+ chunk.total_size,+ );+ let sent = target+ .control+ .step(|| async { Ok(request.send().await) })+ .await?;+ let response = match sent {+ Ok(response) => response,+ Err(error) if attempt == 0 && is_reqwest_network_error(&error) => {+ network_recovery(target.app, target.control).await?;+ continue;+ }+ Err(error) => return Err(error.to_string().into()),+ };+ if !is_upload_response_accepted(+ &url,+ response.status(),+ chunk.offset,+ size as u64,+ chunk.total_size,+ ) {+ return Err(format!("Instant multipart part failed: {}", response.status()).into());+ }+ let etag = response+ .headers()+ .get("ETag")+ .and_then(|value| value.to_str().ok())+ .map(|value| value.trim_matches('"').to_string())+ .or_else(|| {+ is_google_drive_resumable_url(&url)+ .then(|| format!("drive-{}", chunk.part_number))+ })+ .ok_or_else(|| {+ format!(+ "Instant multipart part {} is missing ETag",+ chunk.part_number+ )+ })?;+ target.control.check()?;+ return Ok(UploadedPart {+ part_number: chunk.part_number,+ etag,+ size,+ total_size: chunk.total_size,+ });+ }+ Err("Instant multipart retries exhausted".to_string().into())+ }++ async fn multipart(+ app: &AppHandle,+ directory: &Path,+ video: &VideoUploadInfo,+ control: &Control,+ ) -> Result<(), AuthedApiError> {+ let upload = control+ .step(|| api::upload_multipart_initiate(app, &video.id))+ .await?;+ let concurrency = if is_google_drive_upload(upload.provider.as_deref(), &upload.upload_id) {+ 1+ } else {+ 5+ };+ let target = MultipartTarget {+ app,+ video_id: &video.id,+ upload_id: &upload.upload_id,+ control,+ use_md5: app.is_server_url_custom().await,+ };+ let path = directory.join("content/output.mp4");+ let stream = strict_chunks(path.clone(), control.clone());+ let parts = transfer_parts(&path, stream, &target, control, concurrency).await?;+ let metadata = tokio::task::spawn_blocking(move || build_video_meta(&path))+ .await+ .map_err(|error| error.to_string())??;+ control+ .complete(|| {+ api::upload_multipart_complete(+ app,+ &video.id,+ &upload.upload_id,+ &parts,+ Some(metadata),+ )+ })+ .await+ }++ fn strict_chunks(path: PathBuf, control: Control) -> impl Stream<Item = io::Result<Chunk>> {+ try_stream! {+ let started = Instant::now();+ let mut file = loop {+ control.check().map_err(io::Error::other)?;+ let opened = File::open(&path).await;+ control.check().map_err(io::Error::other)?;+ match opened {+ Ok(file) => break file,+ Err(error) if started.elapsed() >= Duration::from_secs(20) => Err(error)?,+ Err(_) => tokio::time::sleep(Duration::from_millis(100)).await,+ }+ };+ let mut offset = 0u64;+ let mut number = 1;+ let mut first_size = None;+ let mut buffer = vec![0; MAX_CHUNK_SIZE as usize];+ loop {+ control.check().map_err(io::Error::other)?;+ let done = *control.0.decision.borrow() == 1;+ let size = file.metadata().await?.len();+ control.check().map_err(io::Error::other)?;+ let available = size.saturating_sub(offset);+ if available >= MIN_CHUNK_SIZE || (done && available > 0) {+ let count = available.min(MAX_CHUNK_SIZE) as usize;+ file.seek(std::io::SeekFrom::Start(offset)).await?;+ control.check().map_err(io::Error::other)?;+ file.read_exact(&mut buffer[..count]).await?;+ control.check().map_err(io::Error::other)?;+ if offset == 0 { first_size = Some(count); }+ yield Chunk { total_size: size, part_number: number, offset, chunk: Bytes::copy_from_slice(&buffer[..count]) };+ offset += count as u64; number += 1;+ } else if done && available == 0 {+ if let Some(count) = first_size {+ file.seek(std::io::SeekFrom::Start(0)).await?;+ control.check().map_err(io::Error::other)?;+ file.read_exact(&mut buffer[..count]).await?;+ control.check().map_err(io::Error::other)?;+ yield Chunk { total_size: size, part_number: 1, offset: 0, chunk: Bytes::copy_from_slice(&buffer[..count]) };+ }+ break;+ } else {+ tokio::select! { _ = tokio::time::sleep(Duration::from_millis(100)) => {}, _ = control.cancelled() => {} }+ }+ }+ }+ }++ trait PartTransport: Send + Sync {+ fn send(+ &self,+ chunk: Chunk,+ ) -> impl Future<Output = Result<UploadedPart, AuthedApiError>> + Send;+ }+ impl PartTransport for MultipartTarget<'_> {+ async fn send(&self, chunk: Chunk) -> Result<UploadedPart, AuthedApiError> {+ part(self, chunk).await+ }+ }++ async fn transfer_parts(+ path: &Path,+ stream: impl Stream<Item = io::Result<Chunk>>,+ transport: &impl PartTransport,+ control: &Control,+ concurrency: usize,+ ) -> Result<Vec<UploadedPart>, AuthedApiError> {+ let mut chunks = Box::pin(stream);+ let mut pending = futures::stream::FuturesOrdered::new();+ let mut parts = Vec::new();+ let mut failed = Vec::new();+ let mut failure = None;+ let mut closed = false;+ while !closed || !pending.is_empty() {+ tokio::select! {+ _ = control.cancelled(), if failure.is_none() => { failure = Some("Instant multipart cancelled".to_string().into()); }+ chunk = chunks.next(), if !closed && pending.len() < concurrency && failure.is_none() => {+ match chunk {+ Some(Ok(chunk)) => {+ let info = FailedChunkInfo { part_number: chunk.part_number, offset: chunk.offset, chunk_size: chunk.chunk.len(), total_size: chunk.total_size, error: String::new() };+ let target = transport;+ pending.push_back(async move { (info, control.step(|| target.send(chunk)).await) });+ }+ Some(Err(error)) => { failure = Some(error.to_string().into()); closed = true; }+ None => closed = true,+ }+ }+ Some((info, result)) = pending.next(), if !pending.is_empty() => {+ match result { Ok(part) => parts.push(part), Err(error) => { failed.push(info); if control.check().is_err() { failure = Some(error); } } }+ }+ }+ if failure.is_some() {+ control.deny();+ if !closed {+ let _ = chunks.next().await;+ }+ closed = true;+ }+ }+ drop(chunks);+ if let Some(error) = failure {+ return Err(error);+ }+ control.permission().await?;+ for info in failed {+ control.check()?;+ let mut file = File::open(path).await.map_err(|error| error.to_string())?;+ control.check()?;+ file.seek(std::io::SeekFrom::Start(info.offset))+ .await+ .map_err(|error| error.to_string())?;+ control.check()?;+ let mut bytes = vec![0; info.chunk_size];+ file.read_exact(&mut bytes)+ .await+ .map_err(|error| error.to_string())?;+ control.check()?;+ parts.push(+ control+ .step(|| {+ transport.send(Chunk {+ part_number: info.part_number,+ offset: info.offset,+ total_size: info.total_size,+ chunk: bytes.into(),+ })+ })+ .await?,+ );+ }+ let mut deduplicated = HashMap::new();+ for part in parts {+ let _ = deduplicated.insert(part.part_number, part);+ }+ let mut parts: Vec<_> = deduplicated.into_values().collect();+ parts.sort_by_key(|part| part.part_number);+ if parts.is_empty()+ || parts+ .iter()+ .enumerate()+ .any(|(index, part)| part.part_number as usize != index + 1 || part.size == 0)+ {+ return Err("Required Instant multipart data is incomplete"+ .to_string()+ .into());+ }+ Ok(parts)+ }++ pub async fn upload_thumbnail(+ app: &AppHandle,+ video_id: &str,+ bytes: Vec<u8>,+ control: &Control,+ ) -> Result<(), AuthedApiError> {+ let transport = LiveTransport {+ app,+ video_id,+ control,+ };+ control+ .step(|| transport.put("screenshot/screen-capture.jpg", bytes.into()))+ .await+ }++ pub fn resume(+ app: AppHandle,+ directory: PathBuf,+ video: VideoUploadInfo,+ events: Option<std::sync::mpsc::Receiver<SegmentCompletedEvent>>,+ required_audio: bool,+ ) {+ let (control, permission) = Control::new();+ if permission.grant().is_err() {+ return;+ }+ let upload = spawn(+ app.clone(),+ directory.clone(),+ video.clone(),+ events,+ control.clone(),+ required_audio,+ );+ drop(tauri::async_runtime::spawn(async move {+ let result = upload.handle.await;+ if matches!(result, Ok(Ok(()))) && control.joined().await && control.check().is_ok() {+ let result = (|| -> Result<(), String> {+ let mut meta = RecordingMeta::load_for_project(&directory)+ .map_err(|error| error.to_string())?;+ control.check().map_err(|error| error.to_string())?;+ meta.upload = Some(UploadMeta::Complete);+ meta.save_for_project().map_err(|error| error.to_string())?;+ control.check().map_err(|error| error.to_string())+ })();+ if let Err(error) = result {+ error!(%error, "Resumed Instant upload local completion failed");+ }+ }+ emit_upload_complete(&app, &video.id);+ }));+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ #[derive(Default)]+ struct FakeTransport {+ calls: Mutex<Vec<String>>,+ fail_audio: AtomicBool,+ delay_complete: AtomicBool,+ entered: tokio::sync::Notify,+ released: tokio::sync::Notify,+ }+ impl Transport for FakeTransport {+ async fn put(&self, path: &str, _: Bytes) -> Result<(), AuthedApiError> {+ self.calls.lock().unwrap().push(path.into());+ if self.fail_audio.load(Ordering::Acquire) && path.starts_with("segments/audio/") {+ return Err("required audio upload failed".into());+ }+ Ok(())+ }+ async fn complete(&self) -> Result<(), AuthedApiError> {+ self.calls.lock().unwrap().push("Complete".into());+ if self.delay_complete.load(Ordering::Acquire) {+ self.entered.notify_one();+ self.released.notified().await;+ }+ Ok(())+ }+ }+ fn directory(tag: &str) -> PathBuf {+ static NEXT: AtomicUsize = AtomicUsize::new(0);+ let path = std::env::temp_dir().join(format!(+ "cap-strict-upload-{tag}-{}-{}",+ std::process::id(),+ NEXT.fetch_add(1, Ordering::AcqRel)+ ));+ std::fs::create_dir_all(&path).unwrap();+ path+ }+ fn event(path: PathBuf, audio: bool, init: bool) -> SegmentCompletedEvent {+ SegmentCompletedEvent {+ path,+ index: u32::from(!init),+ duration: if init { 0.0 } else { 1.0 },+ file_size: 4,+ is_init: init,+ media_type: if audio {+ SegmentMediaType::Audio+ } else {+ SegmentMediaType::Video+ },+ }+ }+ fn events(path: &Path, audio: bool) -> tokio::sync::mpsc::Receiver<SegmentCompletedEvent> {+ let file = path.join("synthetic-bytes");+ std::fs::write(&file, b"test").unwrap();+ let (sender, receiver) = tokio::sync::mpsc::channel(12);+ for init in [true, false] {+ sender.try_send(event(file.clone(), false, init)).unwrap();+ if audio {+ sender.try_send(event(file.clone(), true, init)).unwrap();+ }+ }+ receiver+ }+ #[tokio::test]+ async fn strict_segment_eof_waits_for_owned_permission() {+ let dir = directory("eof");+ let transport = FakeTransport::default();+ let (control, permission) = Control::new();+ let mut source = events(&dir, false);+ let future = segments(&transport, &control, &mut source, false);+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ assert!(+ !transport+ .calls+ .lock()+ .unwrap()+ .iter()+ .any(|value| value == "Complete")+ );+ permission.grant().unwrap();+ future.await.unwrap();+ assert!(+ transport+ .calls+ .lock()+ .unwrap()+ .iter()+ .any(|value| value == "Complete")+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+ #[tokio::test]+ async fn strict_required_audio_failure_or_absence_never_completes() {+ for present in [false, true] {+ let dir = directory("audio");+ let transport = FakeTransport::default();+ transport.fail_audio.store(present, Ordering::Release);+ let (control, permission) = Control::new();+ permission.grant().unwrap();+ let mut source = events(&dir, present);+ assert!(+ segments(&transport, &control, &mut source, true)+ .await+ .is_err()+ );+ assert!(+ !transport+ .calls+ .lock()+ .unwrap()+ .iter()+ .any(|value| value == "Complete")+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+ }+ #[tokio::test]+ async fn strict_complete_inflight_revocation_rejects_late_success() {+ let dir = directory("late-complete");+ let transport = FakeTransport::default();+ transport.delay_complete.store(true, Ordering::Release);+ let (control, permission) = Control::new();+ permission.grant().unwrap();+ let mut source = events(&dir, false);+ let future = segments(&transport, &control, &mut source, false);+ tokio::pin!(future);+ tokio::select! { _ = transport.entered.notified() => {}, result = &mut future => panic!("Unexpected completion: {result:?}") }+ control.deny();+ transport.released.notify_one();+ assert!(future.await.is_err());+ assert_eq!(+ transport+ .calls+ .lock()+ .unwrap()+ .iter()+ .filter(|value| *value == "Complete")+ .count(),+ 1+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+ #[tokio::test]+ async fn strict_permission_drop_and_old_generation_cannot_complete() {+ let dir = directory("owner-drop");+ let transport = FakeTransport::default();+ let (old, old_permission) = Control::new();+ old.deny();+ assert!(old_permission.grant().is_err());+ let (control, permission) = Control::new();+ let mut source = events(&dir, false);+ let future = segments(&transport, &control, &mut source, false);+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ drop(permission);+ assert!(future.await.is_err());+ assert!(+ !transport+ .calls+ .lock()+ .unwrap()+ .iter()+ .any(|value| value == "Complete")+ );+ std::fs::remove_dir_all(&dir).unwrap();+ }+ #[tokio::test]+ async fn owned_bridge_closes_full_queue_before_actual_thread_join() {+ let (sender, receiver) = std::sync::mpsc::channel();+ for _ in 0..30 {+ sender+ .send(event(PathBuf::from("unused"), false, false))+ .unwrap();+ }+ let bridge = Bridge::new(receiver).unwrap();+ tokio::time::sleep(Duration::from_millis(10)).await;+ assert!(+ tokio::time::timeout(Duration::from_secs(1), bridge.finish())+ .await+ .unwrap()+ );+ assert!(+ sender+ .send(event(PathBuf::from("unused"), false, false))+ .is_err()+ );+ }+ #[derive(Default)]+ struct FakeParts {+ entered: tokio::sync::Notify,+ released: tokio::sync::Notify,+ delayed: AtomicBool,+ calls: AtomicUsize,+ }+ impl PartTransport for FakeParts {+ async fn send(&self, chunk: Chunk) -> Result<UploadedPart, AuthedApiError> {+ self.calls.fetch_add(1, Ordering::AcqRel);+ if self.delayed.load(Ordering::Acquire) {+ self.entered.notify_one();+ self.released.notified().await;+ }+ Ok(UploadedPart {+ part_number: chunk.part_number,+ etag: "synthetic".into(),+ size: chunk.chunk.len(),+ total_size: chunk.total_size,+ })+ }+ }+ fn chunks() -> impl Stream<Item = io::Result<Chunk>> {+ stream::iter([Ok(Chunk {+ total_size: 4,+ part_number: 1,+ offset: 0,+ chunk: Bytes::from_static(b"test"),+ })])+ }+ #[tokio::test]+ async fn strict_multipart_eof_without_permission_does_not_finalize() {+ let transport = FakeParts::default();+ let (control, permission) = Control::new();+ let future = transfer_parts(Path::new("unused"), chunks(), &transport, &control, 5);+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ permission.grant().unwrap();+ assert_eq!(future.await.unwrap().len(), 1);+ }+ #[tokio::test]+ async fn strict_multipart_cancel_drains_inflight_part_before_error() {+ let transport = FakeParts::default();+ transport.delayed.store(true, Ordering::Release);+ let (control, permission) = Control::new();+ permission.grant().unwrap();+ let future = transfer_parts(Path::new("unused"), chunks(), &transport, &control, 5);+ tokio::pin!(future);+ tokio::select! { _ = transport.entered.notified() => {}, result = &mut future => panic!("Unexpected result: {result:?}") }+ control.deny();+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ transport.released.notify_one();+ assert!(future.await.is_err());+ assert_eq!(transport.calls.load(Ordering::Acquire), 1);+ }+ #[tokio::test]+ async fn strict_request_boundary_stops_following_request_after_late_response() {+ let (control, permission) = Control::new();+ let called = AtomicBool::new(false);+ let (reply, response) = tokio::sync::oneshot::channel();+ let future = async {+ control+ .step(|| async {+ response.await.unwrap();+ Ok(())+ })+ .await?;+ control+ .step(|| async {+ called.store(true, Ordering::Release);+ Ok(())+ })+ .await+ };+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(1), &mut future)+ .await+ .is_err()+ );+ drop(permission);+ reply.send(()).unwrap();+ assert!(future.await.is_err());+ assert!(!called.load(Ordering::Acquire));+ }+ #[tokio::test]+ async fn lost_upload_worker_marks_cleanup_unconfirmed_and_wakes_waiter() {+ let (control, _permission) = Control::new();+ let worker = control.clone();+ let task = tokio::spawn(async move {+ let _guard = WorkerGuard(worker);+ panic!("lost uploader");+ });+ assert!(task.await.is_err());+ assert!(+ !tokio::time::timeout(Duration::from_secs(1), control.joined())+ .await+ .unwrap()+ );+ assert!(control.check().is_err());+ }+ #[tokio::test]+ async fn strict_reader_waits_for_permission_then_rewrites_first_part() {+ let dir = directory("reader");+ let path = dir.join("bytes");+ std::fs::write(&path, b"test").unwrap();+ let (control, permission) = Control::new();+ let mut stream = Box::pin(strict_chunks(path, control));+ assert!(+ tokio::time::timeout(Duration::from_millis(10), stream.next())+ .await+ .is_err()+ );+ permission.grant().unwrap();+ let first = stream.next().await.unwrap().unwrap();+ assert_eq!(first.part_number, 1);+ assert_eq!(first.chunk.as_ref(), b"test");+ let rewritten = stream.next().await.unwrap().unwrap();+ assert_eq!(rewritten.part_number, 1);+ assert_eq!(rewritten.chunk.as_ref(), b"test");+ assert!(stream.next().await.is_none());+ drop(stream);+ std::fs::remove_dir_all(dir).unwrap();+ }+ #[tokio::test]+ async fn strict_reader_cancellation_is_error_not_successful_eof() {+ let dir = directory("cancel-reader");+ let path = dir.join("bytes");+ std::fs::write(&path, b"test").unwrap();+ let (control, permission) = Control::new();+ let mut stream = Box::pin(strict_chunks(path, control));+ assert!(+ tokio::time::timeout(Duration::from_millis(10), stream.next())+ .await+ .is_err()+ );+ drop(permission);+ assert!(+ tokio::time::timeout(Duration::from_secs(1), stream.next())+ .await+ .unwrap()+ .unwrap()+ .is_err()+ );+ drop(stream);+ std::fs::remove_dir_all(dir).unwrap();+ }+ #[tokio::test]+ async fn strict_multipart_complete_maps_optional_success_and_retains_errors_and_late_revocation()+ {+ let (control, permission) = Control::new();+ permission.grant().unwrap();+ let result: Result<(), AuthedApiError> = control+ .complete(|| async { Ok(Some("synthetic-location".to_string())) })+ .await;+ result.unwrap();+ assert!(+ control+ .complete(|| async {+ Err::<Option<String>, _>("required completion failed".into())+ })+ .await+ .is_err()+ );+ let (release, released) = tokio::sync::oneshot::channel();+ let future = control.complete(|| async {+ released.await.unwrap();+ Ok(Some("late-location".to_string()))+ });+ tokio::pin!(future);+ assert!(+ tokio::time::timeout(Duration::from_millis(10), &mut future)+ .await+ .is_err()+ );+ control.deny();+ release.send(()).unwrap();+ assert!(future.await.is_err());+ }+ }+}diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex 3fc30b30a..03823274f 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -126,8 +126,8 @@ pub fn hide_overlay(window: &WebviewWindow) {}pub fn show_overlay(window: &WebviewWindow) {- let _ = window.set_ignore_cursor_events(false);- let _ = window.show();+ let generation = crate::clean_capture::generation(window.app_handle());+ crate::clean_capture::schedule_overlay_reveal(window, generation, false);}fn emit_app_event<E>(app: &AppHandle, event: E)@@ -328,6 +328,16 @@ async fn init_native_camera_preview(}pub(crate) async fn ensure_camera_input_active(app_state: &mut App) {+ let app_handle = app_state.handle.clone();+ let requested = app_handle.state::<crate::RequestedInputsState>();+ let snapshot = requested.snapshot();+ if snapshot.camera.pending+ || snapshot.camera.error.is_some()+ || snapshot.camera.value != app_state.selected_camera_id+ || app_state.is_recording_active_or_pending()+ {+ return;+ }if let Some(id) = app_state.selected_camera_id.clone()&& !app_state.camera_in_use{@@ -352,174 +362,15 @@ pub(crate) async fn ensure_camera_input_active(app_state: &mut App) {}}- app_state.camera_in_use = true;- app_state.camera_cleanup_done = false;+ requested.publish_camera_if_current(snapshot.camera.revision, || {+ app_state.camera_in_use = true;+ app_state.camera_cleanup_done = false;+ });}}pub(crate) async fn restore_main_window_inputs(app: &AppHandle) {- let Some(state) = app.try_state::<ArcLock<App>>() else {- warn!("App state unavailable while restoring main window inputs");- return;- };-- let should_restore = state- .try_read()- .map(|state| !state.is_recording_active_or_pending())- .unwrap_or(false);-- if !should_restore {- return;- }-- let settings = crate::recording_settings::RecordingSettingsStore::get(app)- .ok()- .flatten()- .unwrap_or_default();- let stored_camera_id = settings.camera_id.clone();-- if let Err(err) = crate::set_mic_input(state.clone(), settings.mic_name).await {- warn!("Failed to restore microphone input for main window: {err}");- }-- let Some(operation_lock) = app.try_state::<crate::CameraWindowOperationLock>() else {- warn!("CameraWindowOperationLock unavailable while restoring main window inputs");- return;- };- let operation_guard = operation_lock.lock().await;-- let camera_to_restore = state- .try_read()- .map(|s| {- if !s.camera_cleanup_done && !s.camera_in_use {- s.selected_camera_id- .clone()- .or_else(|| stored_camera_id.clone())- } else {- None- }- })- .unwrap_or(None)- // A remembered camera that isn't connected must not run the init/retry- // loop below: it would flash the preview window and toast an error on- // every main-window reveal while the device is away.- .filter(crate::is_camera_available);-- if let Some(camera_id) = camera_to_restore {- emit_camera_preview_clear(app);- let settings =- crate::recording_settings::RecordingSettingsStore::camera_settings_for(app, &camera_id);-- let (camera_feed, camera_ws_sender, native_sender) = {- let app_state = &mut *state.write().await;- app_state.selected_camera_id = Some(camera_id.clone());- app_state.camera_in_use = true;- app_state.camera_cleanup_done = false;- #[allow(deprecated)]- (- app_state.camera_feed.clone(),- app_state.camera_ws_sender.clone(),- app_state.camera_preview.sender(),- )- };-- if let Some(sender) = native_sender {- #[allow(deprecated)]- let _ = camera_feed- .ask(feeds::camera::RemoveSender(camera_ws_sender))- .await;- if let Err(err) = sender.attach(&camera_feed).await {- warn!(error = %err, "Failed to add native preview camera sender");- }- } else {- #[allow(deprecated)]- let _ = camera_feed- .ask(feeds::camera::AddSender(camera_ws_sender))- .await;- }-- let mut showed_camera_window = false;- let mut attempts = 0;- let init_result: Result<(), String> = loop {- attempts += 1;- let request = camera_feed- .ask(feeds::camera::SetInput {- id: camera_id.clone(),- settings,- })- .await- .map_err(|e| e.to_string());-- if !showed_camera_window {- showed_camera_window = true;- crate::show_camera_window_unlocked(app);- }-- match request {- Ok(future) => match future.await {- Ok(_) => {- emit_camera_preview_clear(app);- break Ok(());- }- Err(e) => {- if attempts == 1 {- emit_camera_preview_error(- app,- camera_preview_error_message(&e.to_string()),- );- }- if attempts >= 3 {- break Err(format!(- "Failed to restore camera after {attempts} attempts: {e}"- ));- }- warn!("Camera restore attempt {attempts} failed: {e}. Retrying...");- tokio::time::sleep(Duration::from_millis(500)).await;- }- },- Err(e) => {- if attempts >= 3 {- break Err(e);- }- warn!("Camera restore attempt {attempts} failed: {e}. Retrying...");- tokio::time::sleep(Duration::from_millis(500)).await;- }- }- };-- drop(operation_guard);-- match init_result {- Ok(()) => crate::restore_camera_window(app),- Err(error) => {- let message = camera_preview_error_message(&error);- warn!("Failed to restore camera input for main window: {error}");- let _ = camera_feed.ask(feeds::camera::RemoveInput).await;- let emit_input_lost = {- let app_state = &mut *state.write().await;- app_state.selected_camera_id = None;- app_state.camera_in_use = false;- app_state- .disconnected_inputs- .insert(RecordingInputKind::Camera)- };- crate::show_camera_window_unlocked(app);- if emit_input_lost {- let _ = RecordingEvent::InputLost {- input: RecordingInputKind::Camera,- }- .emit(app);- }- emit_camera_preview_error(app, message.clone());- let _ = NewNotification {- title: "Camera unavailable".to_string(),- body: message,- is_error: true,- }- .emit(app);- }- }- }+ crate::restore_requested_inputs(app).await;}pub(crate) async fn cleanup_camera_window(@@ -1162,7 +1013,23 @@ pub enum ShowCapWindow {}impl ShowCapWindow {- pub async fn show(&self, app: &AppHandle<Wry>) -> tauri::Result<WebviewWindow> {+ pub fn show<'a>(+ &'a self,+ app: &'a AppHandle<Wry>,+ ) -> futures::future::BoxFuture<'a, tauri::Result<WebviewWindow>> {+ Box::pin(self.show_inner(app))+ }++ async fn show_inner(&self, app: &AppHandle<Wry>) -> tauri::Result<WebviewWindow> {+ let reveal_generation = crate::clean_capture::generation(app);+ if matches!(self, Self::Main { .. }) && crate::clean_capture::phase(app).is_some() {+ crate::clean_capture::show_main_controls(app)+ .await+ .map_err(|error| tauri::Error::Io(std::io::Error::other(error)))?;+ }+ #[cfg(target_os = "linux")]+ crate::clean_capture::admit_wayland_window_creation(app)+ .map_err(|error| tauri::Error::Io(std::io::Error::other(error)))?;if let Self::Editor { project_path } = &self {let state = app.state::<EditorWindowIds>();let window_id = {@@ -1239,6 +1106,11 @@ impl ShowCapWindow {}if let Some(window) = self.id(app).get(app) {+ if crate::clean_capture::phase(app)+ .is_some_and(|phase| phase != crate::clean_capture::Phase::Restoring)+ {+ return Ok(window);+ }#[cfg(target_os = "macos")]{use crate::panel_manager::is_window_handle_valid;@@ -1398,8 +1270,13 @@ impl ShowCapWindow {if *centered {center_camera_window(app, &window);}- window.show().ok();- window.set_focus().ok();+ crate::clean_capture::guarded_show(+ window.clone(),+ reveal_generation,+ true,+ false,+ )+ .await?;return Ok(window);}}@@ -1482,8 +1359,8 @@ impl ShowCapWindow {CursorMonitorInfo::get().bottom_center_position(width, height, 120.0)});let _ = window.set_position(logical_point_position(pos_x, pos_y));- window.show().ok();- window.set_focus().ok();+ crate::clean_capture::guarded_show(window.clone(), reveal_generation, true, false)+ .await?;fake_window::spawn_fake_window_listener(app.clone(), window.clone());return Ok(window);}@@ -1536,9 +1413,8 @@ impl ShowCapWindow {recenter_window_if_offscreen(&window);}- window.show().ok();- window.unminimize().ok();- window.set_focus().ok();+ crate::clean_capture::guarded_show(window.clone(), reveal_generation, true, true)+ .await?;if let Self::Settings { .. } = self {ensure_settings_window_bounds(&window);@@ -1686,7 +1562,13 @@ impl ShowCapWindow {}}- window.show().ok();+ crate::clean_capture::guarded_show(+ window.clone(),+ reveal_generation,+ false,+ false,+ )+ .await?;}window@@ -1885,7 +1767,13 @@ impl ShowCapWindow {#[cfg(not(target_os = "macos"))]{- window.show().ok();+ crate::clean_capture::guarded_show(+ window.clone(),+ reveal_generation,+ false,+ false,+ )+ .await?;}window@@ -2239,8 +2127,12 @@ impl ShowCapWindow {window.__CAP__.cameraWsPort = {};window.__CAP__.cameraOnlyMode = {};window.__CAP__.enableNativeCameraPreview = {};+ window.__CAP__.cleanCaptureGeneration = {};",- state.camera_ws_port, centered, enable_native_camera_preview+ state.camera_ws_port,+ centered,+ enable_native_camera_preview,+ reveal_generation)).content_protected(should_protect).transparent(true)@@ -2439,7 +2331,13 @@ impl ShowCapWindow {#[cfg(not(target_os = "macos"))]{- window.show().ok();+ crate::clean_capture::guarded_show(+ window.clone(),+ reveal_generation,+ false,+ false,+ )+ .await?;}drop(state);diff --git a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsxindex 7e71765ed..f36e3146a 100644--- a/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx+++ b/apps/desktop/src/routes/(window-chrome)/new-main/index.tsx@@ -62,14 +62,17 @@ import {} from "~/utils/importMedia";import {createCameraMutation,+ createCleanCaptureQuery,createCurrentRecordingQuery,createLicenseQuery,+ createMicrophoneMutation,getPermissions,listDisplaysWithThumbnails,listRecordings,listScreens,listWindows,listWindowsWithThumbnails,+ revealRecordingWindow,} from "~/utils/queries";import {type CaptureDisplay,@@ -143,18 +146,8 @@ const findCamera = (cameras: CameraWithDetails[], id: DeviceOrModelID) => {});};-// Must stay in sync with find_mic_by_label_or_fuzzy in src-tauri: Bluetooth-// mics can reappear under a slightly different name (profile switch), and the-// backend accepts case-insensitive containment in either direction.-const findMicrophone = (microphones: MicrophoneWithDetails[], name: string) => {- const exact = microphones.find((m) => m.name === name);- if (exact) return exact;- const nameLower = name.toLowerCase();- return microphones.find((m) => {- const deviceLower = m.name.toLowerCase();- return deviceLower.includes(nameLower) || nameLower.includes(deviceLower);- });-};+const findMicrophone = (microphones: MicrophoneWithDetails[], name: string) =>+ microphones.find((microphone) => microphone.name === name);type WindowListItem = Pick<CaptureWindow,@@ -1859,6 +1852,7 @@ function Page() {const queryClient = useQueryClient();const { rawOptions, setOptions } = useRecordingOptions();const currentRecording = createCurrentRecordingQuery();+ const cleanCapture = createCleanCaptureQuery();const [isExpanded, setIsExpanded] = createSignal(false);const [isWindowFocused, setIsWindowFocused] = createSignal(false);const [isWindowResizing, setIsWindowResizing] = createSignal(false);@@ -2056,9 +2050,7 @@ function Page() {dismissal === "screenshot" ||dismissal === "recordingInstant";if (shouldRevealMainWindow && dismissalReveals) {- const currentWindow = getCurrentWindow();- void currentWindow.show();- void currentWindow.setFocus();+ void revealRecordingWindow();}}});@@ -2073,11 +2065,11 @@ function Page() {rawOptions.targetMode != null &&!currentRecording.data)- void getCurrentWindow().show();+ void revealRecordingWindow();});const handleMouseEnter = () => {- getCurrentWindow().setFocus();+ void revealRecordingWindow();};const [displayMenuOpen, setDisplayMenuOpen] = createSignal(false);@@ -2181,9 +2173,7 @@ function Page() {// in a hidden webview and the failure is invisible again.createTauriEventListener(events.recordingEvent, (payload) => {if (payload.variant === "StartFailed") {- const currentWindow = getCurrentWindow();- void currentWindow.show();- void currentWindow.setFocus();+ void revealRecordingWindow();toast.error(payload.error);}});@@ -2474,19 +2464,7 @@ function Page() {closeAllMenuPanels();});- const setMicInput = createMutation(() => ({- mutationFn: async (name: string | null) => {- const previous = rawOptions.micName ?? null;- if (previous !== name) setOptions("micName", name);- try {- await commands.setMicInput(name);- } catch (error) {- if (previous !== name) setOptions("micName", previous);- throw error;- }- },- }));-+ const setMicInput = createMicrophoneMutation();const setCamera = createCameraMutation();createUpdateCheck();@@ -2521,8 +2499,7 @@ function Page() {targetModeSource: null,targetModeDismissal: "cancelled",});- await currentWindow.show();- await currentWindow.setFocus();+ await revealRecordingWindow();setIsWindowFocused(true);void commands.closeTargetSelectOverlays().catch((error) => {console.error("Failed to close target select overlays:", error);@@ -2767,18 +2744,9 @@ function Page() {const previous = micPresence;micPresence = { name, present: !!matched };const reappeared = previous?.present === false && previous.name === name;- if (matched && (reappeared || matched.name !== name)) {- // The feed rejects non-exact labels, so a fuzzy match (Bluetooth- // rename) must be applied under the connected device's name. The- // stored selection converges only after the backend accepts it,- // keeping a failed call from retriggering this effect.- const matchedName = matched.name;+ if (matched && reappeared) {commands- .setMicInput(matchedName)- .then(() => {- if (rawOptions.micName === name && matchedName !== name)- setOptions("micName", matchedName);- })+ .setMicInput(name).catch((error) =>console.error("Failed to restore reconnected microphone:", error),);@@ -3169,6 +3137,7 @@ function Page() {);const startSignInCleanup = listen("start-sign-in", async () => {+ const revealGeneration = (await commands.getCleanCaptureState()).generation;const abort = new AbortController();for (const win of await getAllWebviewWindows()) {if (win.label.startsWith("target-select-overlay")) {@@ -3182,7 +3151,7 @@ function Page() {for (const win of await getAllWebviewWindows()) {if (win.label.startsWith("target-select-overlay")) {await win.setIgnoreCursorEvents(false);- await win.show();+ await commands.revealCaptureWindow(revealGeneration, win.label);}}});@@ -3193,6 +3162,39 @@ function Page() {onMouseEnter={handleMouseEnter}class="flex relative flex-col px-[13px] gap-2 pb-[8px] h-full min-h-0 text-(--text-primary)">+ <Show when={cleanCapture.data?.phase === "awaitingShortcut"}>+ <div+ class="absolute inset-0 z-50 flex flex-col justify-center gap-4 p-5 bg-gray-2"+ role="dialog"+ aria-label={+ cleanCapture.data?.mode === "instant"+ ? "Clean Instant recording"+ : "Clean Studio recording"+ }+ >+ <strong>Record without Cap's preview and controls</strong>+ <p class="text-sm">+ {cleanCapture.data?.mode === "instant"+ ? "Any selected camera will be included in the video with its preview appearance. Cap's preview and controls will hide."+ : "Any selected camera will keep recording as a separate editable track. Cap's preview and controls will hide."}+ </p>+ <p class="text-sm">+ Press <strong>{cleanCapture.data?.shortcut}</strong> to start, then+ use it to stop.{" "}+ {cleanCapture.data?.mode === "instant"+ ? "Open Cap to stop and show controls."+ : "Open Cap to pause and show controls."}+ </p>+ <button+ type="button"+ class="rounded-lg border border-gray-5 px-4 py-2"+ disabled={stopRecording.isPending}+ onClick={() => stopRecording.mutate()}+ >+ Cancel+ </button>+ </div>+ </Show><WindowChromeHeadermaximized={isExpanded()}onMaximize={() => void toggleMainWindowExpanded()}@@ -3300,6 +3302,14 @@ function Page() {</div></div></WindowChromeHeader>+ <Show when={!isActivelyRecording() && cleanCapture.data?.error}>+ <div+ role="alert"+ class="max-h-20 shrink-0 overflow-auto rounded-lg bg-red-3 p-2 text-sm text-red-11"+ >+ {cleanCapture.data?.error}+ </div>+ </Show><Show when={!activeMenu()}><div class="flex items-center justify-between mt-[16px] mb-[6px]"><div class="flex items-center space-x-1">@@ -3516,6 +3526,32 @@ function Page() {<Show when={isActivelyRecording()}><div class="absolute inset-0 z-10 flex flex-col justify-end bg-gray-1/80 px-6 pb-8 backdrop-blur-xs"><div class="pointer-events-auto">+ <Show when={cleanCapture.data?.phase === "paused"}>+ <div class="mb-3 flex items-center justify-between gap-2 rounded-lg bg-gray-3 p-2 text-sm">+ <div class="min-w-0">+ <Show when={cleanCapture.data?.error}>+ <p+ role="alert"+ class="mb-1 max-h-20 overflow-auto text-red-11"+ >+ {cleanCapture.data?.error}+ </p>+ </Show>+ <span>Recording paused. Cap will hide before resuming.</span>+ </div>+ <button+ type="button"+ class="rounded-md border border-gray-5 px-3 py-1"+ onClick={() =>+ void commands+ .resumeRecording()+ .catch((error: unknown) => toast.error(String(error)))+ }+ >+ Resume+ </button>+ </div>+ </Show><buttontype="button"disabled={stopRecording.isPending}diff --git a/apps/desktop/src/routes/camera.tsx b/apps/desktop/src/routes/camera.tsxindex f8e88825f..99b519192 100644--- a/apps/desktop/src/routes/camera.tsx+++ b/apps/desktop/src/routes/camera.tsx@@ -38,10 +38,12 @@ import {normalizeBackgroundBlurMode,} from "~/components/CameraPreviewChrome";import { generalSettingsStore } from "~/store";+import { cameraPresentationInput } from "~/utils/camera-presentation";import { createTauriEventListener } from "~/utils/createEventListener";import {createCameraMutation,createCurrentRecordingQuery,+ revealRecordingWindow,} from "~/utils/queries";import {type CanvasControls,@@ -129,7 +131,7 @@ export default function () {const generalSettings = generalSettingsStore.createQuery();const isNativePreviewEnabled = () => {- if (type() === "windows") return false;+ if (type() === "windows" || type() === "linux") return false;if (generalSettings.isPending) return getNativeCameraPreviewInitialState();return (generalSettings.data?.enableNativeCameraPreview ??@@ -405,13 +407,19 @@ function LegacyCameraPreviewPage(props: {}});+ let layoutRevision = 0;+ let previewStateSync: Promise<unknown> = Promise.resolve();createEffect(() => {- commands.setCameraPreviewState({+ layoutRevision = (layoutRevision + 1) >>> 0;+ previewStateSync = commands.setCameraPreviewState({size: state.size,shape: state.shape,mirrored: state.mirrored,background_blur: normalizeBackgroundBlurMode(state.backgroundBlur),});+ void previewStateSync.catch((error) =>+ console.error("Camera preview state sync failed", error),+ );});const [hasPositioned, setHasPositioned] = createSignal(isCameraOnlyMode());@@ -441,6 +449,7 @@ function LegacyCameraPreviewPage(props: {Math.abs(currentSize.width - rect.width) > 1 ||Math.abs(currentSize.height - rect.height) > 1) {+ layoutRevision = (layoutRevision + 1) >>> 0;setExternalContainerSize({ width: rect.width, height: rect.height });}};@@ -707,9 +716,11 @@ function LegacyCameraPreviewPage(props: {);});if (onMonitor) {- currentWindow.setPosition(new LogicalPosition(saved.x, saved.y));+ await currentWindow.setPosition(+ new LogicalPosition(saved.x, saved.y),+ );} else {- currentWindow.setPosition(+ await currentWindow.setPosition(new LogicalPosition(width + activeMonitor.position.toLogical(scalingFactor).x,height + activeMonitor.position.toLogical(scalingFactor).y,@@ -717,7 +728,7 @@ function LegacyCameraPreviewPage(props: {);}} else {- currentWindow.setPosition(+ await currentWindow.setPosition(new LogicalPosition(width + activeMonitor.position.toLogical(scalingFactor).x,height + activeMonitor.position.toLogical(scalingFactor).y,@@ -771,7 +782,112 @@ function LegacyCameraPreviewPage(props: {},);- onMount(() => getCurrentWindow().show());+ onMount(() => {+ let disposed = false;+ let requestRevision = 0;+ const unlisten = events.cameraPresentationRequested.listen(+ async ({ payload }) => {+ const request = ++requestRevision;+ try {+ if (+ type() !== "linux" ||+ isCameraOnlyMode() ||+ !containerRef ||+ !hasFrame()+ ) {+ throw new Error(+ "Wait for the selected camera preview before recording",+ );+ }+ const sync = previewStateSync;+ await sync;+ const deadline = performance.now() + 900;+ while (_windowSize.loading) {+ if (performance.now() >= deadline)+ throw new Error("Camera layout did not settle");+ await new Promise<void>((resolve) => setTimeout(resolve, 16));+ }+ const measuredRevision = layoutRevision;+ await Promise.race([+ new Promise<void>((resolve) =>+ requestAnimationFrame(() =>+ requestAnimationFrame(() => resolve()),+ ),+ ),+ new Promise<never>((_, reject) =>+ setTimeout(+ () =>+ reject(new Error("Camera window did not render its layout")),+ 500,+ ),+ ),+ ]);+ if (disposed || request !== requestRevision) return;+ if (+ sync !== previewStateSync ||+ measuredRevision !== layoutRevision ||+ _windowSize.loading+ ) {+ throw new Error(+ "Camera appearance changed while measuring; start again",+ );+ }+ const rect = containerRef.getBoundingClientRect();+ const clip = getComputedStyle(containerRef);+ const input = cameraPresentationInput(+ {+ viewportWidth: window.innerWidth,+ viewportHeight: window.innerHeight,+ left: rect.left,+ top: rect.top,+ width: rect.width,+ height: rect.height,+ cornerRadii: [+ clip.borderTopLeftRadius,+ clip.borderTopRightRadius,+ clip.borderBottomRightRadius,+ clip.borderBottomLeftRadius,+ ],+ },+ {+ size: state.size,+ shape: state.shape,+ mirrored: state.mirrored,+ background_blur: normalizeBackgroundBlurMode(+ state.backgroundBlur,+ ),+ },+ measuredRevision,+ );+ await commands.submitCameraPresentation(payload.nonce, input, null);+ } catch (error) {+ if (!disposed && request === requestRevision) {+ await commands+ .submitCameraPresentation(payload.nonce, null, String(error))+ .catch(() => {});+ }+ }+ },+ );+ onCleanup(() => {+ disposed = true;+ requestRevision += 1;+ void unlisten.then((remove) => remove());+ });+ });++ const initialGeneration = (+ window.__CAP__ as { cleanCaptureGeneration?: number } | undefined+ )?.cleanCaptureGeneration;+ const revealGeneration =+ initialGeneration === undefined+ ? commands.getCleanCaptureState().then((state) => state.generation)+ : Promise.resolve(initialGeneration);+ onMount(() => {+ void revealGeneration.then((generation) =>+ revealRecordingWindow(generation),+ );+ });return (<divdiff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsxindex 7afd88628..8c2ec8f4b 100644--- a/apps/desktop/src/routes/in-progress-recording.tsx+++ b/apps/desktop/src/routes/in-progress-recording.tsx@@ -21,7 +21,7 @@ import {onMount,Show,} from "solid-js";-import { createStore, produce } from "solid-js/store";+import { createStore, produce, reconcile } from "solid-js/store";import { TransitionGroup } from "solid-transition-group";import { authStore } from "~/store";import { getCameraWindow } from "~/utils/camera-window";@@ -29,6 +29,7 @@ import { createTauriEventListener } from "~/utils/createEventListener";import {createCurrentRecordingQuery,createOptionsQuery,+ revealRecordingWindow,} from "~/utils/queries";import { handleRecordingResult } from "~/utils/recording";import type {@@ -232,7 +233,7 @@ function InProgressRecordingInner() {setTime(Date.now());setState({ variant: "recording" });if (wasStartingDismissed) {- void getCurrentWindow().show();+ void revealRecordingWindow();}break;}@@ -573,14 +574,16 @@ function InProgressRecordingInner() {const updateMicInput = createMutation(() => ({mutationFn: async (name: string | null) => {if (!startedWithMicrophone && name !== null) return;- const previous = optionsQuery.rawOptions.micName ?? null;- if (previous === name) return;await pauseRecordingForDeviceChange();optionsQuery.setOptions("micName", name);try {await commands.setMicInput(name);} catch (error) {- optionsQuery.setOptions("micName", previous);+ if (+ (optionsQuery.rawOptions.micName ?? null) !== name ||+ String(error).includes("selection was superseded by a newer request")+ )+ return;throw error;}},@@ -589,22 +592,28 @@ function InProgressRecordingInner() {const updateCameraInput = createMutation(() => ({mutationFn: async (camera: CameraInfo | null) => {if (!startedWithCameraInput && camera != null) return;- const selected = optionsQuery.rawOptions.cameraID ?? null;- if (!camera && selected === null) return;- if (camera && cameraMatchesSelection(camera, selected)) return;await pauseRecordingForDeviceChange();const next = cameraInfoToId(camera);- const previous = cloneDeviceOrModelId(selected);- optionsQuery.setOptions("cameraID", next);+ optionsQuery.setOptions("cameraID", reconcile(next));try {await commands.setCameraInput(next, null);- if (!next && cameraWindowOpen()) {+ if (+ !next &&+ optionsQuery.rawOptions.cameraID == null &&+ cameraWindowOpen()+ ) {const cameraWindow = await getCameraWindow();- if (cameraWindow) await cameraWindow.close();+ if (cameraWindow && optionsQuery.rawOptions.cameraID == null)+ await cameraWindow.close();await refreshCameraWindowState();}} catch (error) {- optionsQuery.setOptions("cameraID", previous);+ if (+ JSON.stringify(optionsQuery.rawOptions.cameraID ?? null) !==+ JSON.stringify(next) ||+ String(error).includes("selection was superseded by a newer request")+ )+ return;throw error;}},@@ -1118,11 +1127,3 @@ function cameraInfoToId(camera: CameraInfo | null): DeviceOrModelID | null {if (camera.model_id) return { ModelID: camera.model_id };return { DeviceID: camera.device_id };}--function cloneDeviceOrModelId(- id: DeviceOrModelID | null,-): DeviceOrModelID | null {- if (!id) return null;- if ("DeviceID" in id) return { DeviceID: id.DeviceID };- return { ModelID: id.ModelID };-}diff --git a/apps/desktop/src/routes/target-select-overlay.tsx b/apps/desktop/src/routes/target-select-overlay.tsxindex 772fc3f00..de755f9dd 100644--- a/apps/desktop/src/routes/target-select-overlay.tsx+++ b/apps/desktop/src/routes/target-select-overlay.tsx@@ -4,7 +4,7 @@ import { createEventListener } from "@solid-primitives/event-listener";import { createElementSize } from "@solid-primitives/resize-observer";import { makePersisted } from "@solid-primitives/storage";import { useSearchParams } from "@solidjs/router";-import { createMutation, useQuery } from "@tanstack/solid-query";+import { useQuery } from "@tanstack/solid-query";import {LogicalPosition,type PhysicalPosition,@@ -78,6 +78,7 @@ import { createDevicesQuery } from "~/utils/devices";import { shouldConfirmRecordingWithoutMicrophone } from "~/utils/general-settings";import {createCameraMutation,+ createMicrophoneMutation,createOptionsQuery,createOrganizationsQuery,} from "~/utils/queries";@@ -1875,18 +1876,7 @@ function RecordingControls(props: {const cameras = createMemo(() => devices.data?.cameras ?? []);const mics = createMemo(() => devices.data?.microphones ?? []);const permissions = createMemo(() => devices.data?.permissions);- const setMicInput = createMutation(() => ({- mutationFn: async (name: string | null) => {- const previous = rawOptions.micName ?? null;- if (previous !== name) setOptions("micName", name);- try {- await commands.setMicInput(name);- } catch (error) {- if (previous !== name) setOptions("micName", previous);- throw error;- }- },- }));+ const setMicInput = createMicrophoneMutation();const setCamera = createCameraMutation();onMount(async () => {@@ -1938,7 +1928,10 @@ function RecordingControls(props: {});const startLoading = () =>- devices.isPending || recordingStartSafety.isPending;+ devices.isPending ||+ recordingStartSafety.isPending ||+ setMicInput.isPending ||+ setCamera.isPending;const startDisabled = () => !!props.disabled || startLoading();const startRecording = async (confirmedWithoutMicrophone = false) => {diff --git a/apps/desktop/src/utils/camera-presentation.test.ts b/apps/desktop/src/utils/camera-presentation.test.tsnew file mode 100644index 000000000..79f19666d--- /dev/null+++ b/apps/desktop/src/utils/camera-presentation.test.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from "vitest";+import {+ type CameraPresentationMeasurement,+ cameraPresentationInput,+} from "./camera-presentation";+import type { CameraPreviewState } from "./tauri";++const state: CameraPreviewState = {+ size: 230,+ shape: "round",+ mirrored: true,+ background_blur: "heavy",+};+const measurement: CameraPresentationMeasurement = {+ viewportWidth: 230,+ viewportHeight: 286,+ left: 0,+ top: 56,+ width: 230,+ height: 230,+ cornerRadii: ["9999px", "9999px", "9999px", "9999px"],+};++describe("Linux legacy camera presentation", () => {+ it("measures content below the toolbar and preserves exact requested effects", () => {+ const actual = cameraPresentationInput(measurement, state, 7);+ expect(actual.top).toBe(56);+ expect(actual.height).toBe(230);+ expect(actual.radius).toBe(115);+ expect(actual.state).toEqual(state);+ expect(actual.layoutRevision).toBe(7);+ });++ it("uses actual full-shape dimensions and inner clipping rather than outer radius", () => {+ const actual = cameraPresentationInput(+ {+ ...measurement,+ viewportWidth: 460,+ width: 460,+ cornerRadii: ["24px", "24px", "24px", "24px"],+ },+ { ...state, shape: "full" },+ 8,+ );+ expect(actual.width).toBe(460);+ expect(actual.radius).toBe(24);+ });++ it("keeps fractional CSS coordinates for native physical scaling", () => {+ const actual = cameraPresentationInput(+ {+ ...measurement,+ viewportWidth: 231,+ left: 0.5,+ width: 230.25,+ height: 230.25,+ viewportHeight: 287,+ },+ state,+ 1,+ );+ expect(actual.left).toBe(0.5);+ expect(actual.width).toBe(230.25);+ });++ it("rejects absent, nonfinite, negative or outside content geometry", () => {+ for (const invalid of [+ { width: 0 },+ { left: -1 },+ { top: Number.NaN },+ { width: Number.POSITIVE_INFINITY },+ { top: 100 },+ ]) {+ expect(() =>+ cameraPresentationInput({ ...measurement, ...invalid }, state, 1),+ ).toThrow();+ }+ });++ it("rejects unknown, asymmetric and elliptical clipping", () => {+ for (const cornerRadii of [+ ["calc(2px)", "24px", "24px", "24px"],+ ["12px", "24px", "24px", "24px"],+ ["24px 12px", "24px", "24px", "24px"],+ ] as const) {+ expect(() =>+ cameraPresentationInput({ ...measurement, cornerRadii }, state, 1),+ ).toThrow();+ }+ });++ it("accepts measured percentage circles but rejects a non-square round preview", () => {+ expect(+ cameraPresentationInput(+ { ...measurement, cornerRadii: ["50%", "50%", "50%", "50%"] },+ state,+ 1,+ ).radius,+ ).toBe(115);+ expect(() =>+ cameraPresentationInput({ ...measurement, width: 220 }, state, 1),+ ).toThrow();+ });++ it("does not rewrite stored state or share its mutable object", () => {+ const actual = cameraPresentationInput(measurement, state, 1);+ actual.state.mirrored = false;+ expect(state.mirrored).toBe(true);+ for (const mode of ["off", "light", "heavy"] as const) {+ expect(+ cameraPresentationInput(+ measurement,+ { ...state, background_blur: mode },+ 1,+ ).state.background_blur,+ ).toBe(mode);+ }+ });++ it("rejects invalid layout revisions", () => {+ for (const revision of [-1, 1.5, Number.NaN, 0x1_0000_0000]) {+ expect(() =>+ cameraPresentationInput(measurement, state, revision),+ ).toThrow();+ }+ });+});diff --git a/apps/desktop/src/utils/camera-presentation.ts b/apps/desktop/src/utils/camera-presentation.tsnew file mode 100644index 000000000..fa3a1efd7--- /dev/null+++ b/apps/desktop/src/utils/camera-presentation.ts@@ -0,0 +1,91 @@+import type { CameraPreviewState } from "./tauri";++export type CameraPresentationMeasurement = {+ viewportWidth: number;+ viewportHeight: number;+ left: number;+ top: number;+ width: number;+ height: number;+ cornerRadii: readonly [string, string, string, string];+};++function radiusComponent(value: string, extent: number): number {+ const match = /^([\d.e+-]+)(px|%)$/.exec(value);+ if (!match) throw new Error("Camera clipping radius is unsupported");+ const numeric = Number(match[1]);+ if (!Number.isFinite(numeric) || numeric < 0) {+ throw new Error("Camera clipping radius is invalid");+ }+ return match[2] === "%" ? (numeric * extent) / 100 : numeric;+}++function clippingRadius(value: string, width: number, height: number): number {+ const components = value.trim().split(/\s+/);+ if (components.length < 1 || components.length > 2) {+ throw new Error("Camera clipping radius is unsupported");+ }+ const x = Math.min(radiusComponent(components[0], width), width / 2);+ const y = Math.min(+ radiusComponent(components[1] ?? components[0], height),+ height / 2,+ );+ if (Math.abs(x - y) > 0.5) {+ throw new Error("Elliptical camera corners are unsupported");+ }+ return Math.min(x, y);+}++export function cameraPresentationInput(+ measurement: CameraPresentationMeasurement,+ state: CameraPreviewState,+ layoutRevision: number,+) {+ const {+ viewportWidth,+ viewportHeight,+ left,+ top,+ width,+ height,+ cornerRadii,+ } = measurement;+ if (+ ![viewportWidth, viewportHeight, left, top, width, height].every(+ Number.isFinite,+ ) ||+ viewportWidth <= 0 ||+ viewportHeight <= 0 ||+ width <= 0 ||+ height <= 0 ||+ left < 0 ||+ top < 0 ||+ left + width > viewportWidth + 1 ||+ top + height > viewportHeight + 1 ||+ !Number.isSafeInteger(layoutRevision) ||+ layoutRevision < 0 ||+ layoutRevision > 0xffff_ffff+ ) {+ throw new Error("Camera content is not ready for recording");+ }+ if (state.shape === "round" && Math.abs(width - height) > 1) {+ throw new Error("Round camera content is not square");+ }+ const radii = cornerRadii.map((value) =>+ clippingRadius(value, width, height),+ );+ if (radii.some((value) => Math.abs(value - radii[0]) > 0.5)) {+ throw new Error("Camera corners must use the same clipping radius");+ }+ return {+ viewportWidth,+ viewportHeight,+ left,+ top,+ width,+ height,+ radius: radii[0],+ layoutRevision,+ state: { ...state },+ };+}diff --git a/apps/desktop/src/utils/queries.requested-inputs.test.ts b/apps/desktop/src/utils/queries.requested-inputs.test.tsnew file mode 100644index 000000000..97c961092--- /dev/null+++ b/apps/desktop/src/utils/queries.requested-inputs.test.ts@@ -0,0 +1,571 @@+import { readFileSync } from "node:fs";+import ts from "typescript";+import { beforeEach, describe, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({+ options: {+ micName: null as string | null,+ cameraID: null as { DeviceID: string } | null,+ },+ setMicInput: vi.fn(async (_name: string | null) => {}),+ setCameraInput: vi.fn(+ async (_id: { DeviceID: string } | null, _skip: boolean | null) => {},+ ),+ setFocus: vi.fn(async () => {}),+ getSettings:+ vi.fn<+ () => Promise<{+ micName: string | null;+ cameraId: { DeviceID: string } | null;+ }>+ >(),+}));++vi.mock("@tanstack/solid-query", () => ({+ queryOptions: (value: unknown) => value,+ createQuery: vi.fn(),+ useQuery: vi.fn(),+ useMutation: (+ factory: () => { mutationFn: (value: unknown) => unknown },+ ) => ({+ mutateAsync: factory().mutationFn,+ }),+}));+vi.mock("@solid-primitives/event-listener", () => ({+ createEventListener: vi.fn(),+}));+vi.mock("@solid-primitives/storage", () => ({+ makePersisted: (store: unknown) => store,+}));+vi.mock("solid-js", () => ({+ batch: (action: () => void) => action(),+ createEffect: vi.fn(),+ createMemo: vi.fn(),+ onCleanup: vi.fn(),+}));+vi.mock("@tauri-apps/api/window", () => ({+ getCurrentWindow: () => ({ setFocus: fixture.setFocus }),+}));+vi.mock("solid-js/store", () => ({+ createStore: (initial: Record<string, unknown>) => [+ initial,+ (key: string | object, value: unknown) => {+ if (typeof key === "string") initial[key] = value;+ else Object.assign(initial, key);+ },+ ],+ reconcile: (value: unknown) => value,+}));+vi.mock("~/routes/(window-chrome)/OptionsContext", () => ({+ useRecordingOptions: () => ({+ rawOptions: fixture.options,+ setOptions: (+ key: "micName" | "cameraID",+ value: string | { DeviceID: string } | null,+ ) => {+ if (key === "micName" && (typeof value === "string" || value === null)) {+ fixture.options.micName = value;+ } else if (key === "cameraID" && typeof value !== "string") {+ fixture.options.cameraID = value;+ }+ },+ }),+}));+vi.mock("~/store", () => ({+ authStore: {},+ generalSettingsStore: {},+ recordingSettingsStore: {+ get: fixture.getSettings,+ set: vi.fn(),+ listen: vi.fn(async () => () => {}),+ },+}));+vi.mock("./events", () => ({ createQueryInvalidate: vi.fn() }));+vi.mock("./tauri", () => ({+ commands: {+ setMicInput: fixture.setMicInput,+ setCameraInput: fixture.setCameraInput,+ },+}));+vi.mock("./web-api", () => ({+ orgCustomDomainClient: {},+ protectedHeaders: vi.fn(),+}));++import {+ createCameraMutation,+ createMicrophoneMutation,+ createOptionsQuery,+} from "./queries";++beforeEach(() => {+ vi.resetAllMocks();+ fixture.options.micName = null;+ fixture.options.cameraID = null;+ fixture.setMicInput.mockResolvedValue(undefined);+ fixture.setCameraInput.mockResolvedValue(undefined);+});++describe("requested microphone intent", () => {+ it("keeps a failed A to B request instead of rolling back to A", async () => {+ fixture.options.micName = "A";+ fixture.setMicInput.mockRejectedValueOnce(new Error("Cannot open B"));+ await expect(createMicrophoneMutation().mutateAsync("B")).rejects.toThrow(+ "Cannot open B",+ );+ expect(fixture.options.micName).toBe("B");+ });++ it("does not let an older failed request replace a later None", async () => {+ let rejectOld: (error: Error) => void = () => {};+ fixture.setMicInput.mockImplementationOnce(+ () =>+ new Promise<void>((_, reject) => {+ rejectOld = reject;+ }),+ );+ const mutation = createMicrophoneMutation();+ const old = mutation.mutateAsync("A");+ await mutation.mutateAsync(null);+ rejectOld(new Error("A failed late"));+ await old;+ expect(fixture.options.micName).toBeNull();+ });++ it("ignores superseded duplicate setup without erasing selection", async () => {+ fixture.setMicInput.mockRejectedValueOnce(+ "Microphone selection was superseded by a newer request",+ );+ await createMicrophoneMutation().mutateAsync("A");+ expect(fixture.options.micName).toBe("A");+ });+});++describe("requested camera intent", () => {+ it("retains a persisted selection after initialization failure", async () => {+ fixture.options.cameraID = { DeviceID: "A" };+ fixture.setCameraInput.mockRejectedValueOnce(+ new Error("Failed to initialize camera"),+ );+ await expect(+ createCameraMutation().mutateAsync({ model: { DeviceID: "A" } }),+ ).rejects.toThrow("Failed to initialize camera");+ expect(fixture.options.cameraID).toEqual({ DeviceID: "A" });+ });++ it("keeps a failed new camera request rather than the old camera", async () => {+ fixture.options.cameraID = { DeviceID: "A" };+ fixture.setCameraInput.mockRejectedValueOnce(new Error("DeviceNotFound"));+ await expect(+ createCameraMutation().mutateAsync({ model: { DeviceID: "B" } }),+ ).rejects.toThrow("DeviceNotFound");+ expect(fixture.options.cameraID).toEqual({ DeviceID: "B" });+ });++ it("does not focus or overwrite a newer request when old setup completes", async () => {+ let finishOld: () => void = () => {};+ fixture.setCameraInput.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishOld = resolve;+ }),+ );+ const mutation = createCameraMutation();+ const old = mutation.mutateAsync({ model: { DeviceID: "A" } });+ await mutation.mutateAsync({ model: null });+ finishOld();+ await old;+ expect(fixture.options.cameraID).toBeNull();+ expect(fixture.setFocus).not.toHaveBeenCalled();+ });+});++describe("initial requested input hydration", () => {+ it("does not overwrite rapid A/B/None choices with an older persisted result", async () => {+ vi.stubGlobal("window", {});+ let finish: (settings: {+ micName: string | null;+ cameraId: { DeviceID: string } | null;+ }) => void = () => {};+ fixture.getSettings.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const options = createOptionsQuery();+ options.setOptions("micName", "A");+ options.setOptions("micName", "B");+ options.setOptions("micName", null);+ options.setOptions("cameraID", { DeviceID: "B" });+ options.setOptions("cameraID", null);+ finish({ micName: "Persisted A", cameraId: { DeviceID: "A" } });+ await Promise.resolve();+ expect(options.rawOptions.micName).toBeNull();+ expect(options.rawOptions.cameraID).toBeNull();+ vi.unstubAllGlobals();+ });++ it("still hydrates the input that the user has not changed", async () => {+ vi.stubGlobal("window", {});+ fixture.getSettings.mockResolvedValueOnce({+ micName: "Persisted mic",+ cameraId: { DeviceID: "Persisted camera" },+ });+ const options = createOptionsQuery();+ options.setOptions("micName", null);+ await Promise.resolve();+ expect(options.rawOptions.micName).toBeNull();+ expect(options.rawOptions.cameraID).toEqual({+ DeviceID: "Persisted camera",+ });+ vi.unstubAllGlobals();+ });+});++type PausedCamera = {+ device_id: string;+ model_id: string | null;+ display_name: string;+};+type PausedCameraId = { DeviceID: string } | { ModelID: string } | null;+type PausedOptions = { micName: string | null; cameraID: PausedCameraId };+type PausedMutations = {+ updateMicInput: { mutateAsync(name: string | null): Promise<void> };+ updateCameraInput: {+ mutateAsync(camera: PausedCamera | null): Promise<void>;+ };+};++const pausedRoute = ts.createSourceFile(+ "in-progress-recording.tsx",+ readFileSync(+ new URL("../routes/in-progress-recording.tsx", import.meta.url),+ "utf8",+ ),+ ts.ScriptTarget.ESNext,+ true,+ ts.ScriptKind.TSX,+);+const pausedComponent = pausedRoute.statements.find(+ (statement): statement is ts.FunctionDeclaration =>+ ts.isFunctionDeclaration(statement) &&+ statement.name?.text === "InProgressRecordingInner",+);+const pausedMutationNames = new Set([+ "pauseRecordingForDeviceChange",+ "updateMicInput",+ "updateCameraInput",+]);+const pausedStatements = pausedComponent?.body?.statements.filter(+ (statement) =>+ ts.isVariableStatement(statement) &&+ statement.declarationList.declarations.some(+ (declaration) =>+ ts.isIdentifier(declaration.name) &&+ pausedMutationNames.has(declaration.name.text),+ ),+);+if (pausedStatements?.length !== 3) {+ throw new Error("Paused device mutation source was not found");+}+const pausedHelpers = pausedRoute.statements.filter(+ (statement) =>+ ts.isFunctionDeclaration(statement) &&+ [+ "cameraInfoToId",+ "cameraMatchesSelection",+ "cloneDeviceOrModelId",+ ].includes(statement.name?.text ?? ""),+);+const pausedMutationCode = ts.transpileModule(+ [...pausedStatements, ...pausedHelpers]+ .map((statement) => statement.getText(pausedRoute))+ .join("\n"),+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } },+).outputText;+const createPausedMutations = new Function(+ "createMutation",+ "optionsQuery",+ "commands",+ "state",+ "startedWithMicrophone",+ "startedWithCameraInput",+ "cameraWindowOpen",+ "getCameraWindow",+ "refreshCameraWindowState",+ "reconcile",+ `${pausedMutationCode}\nreturn { updateMicInput, updateCameraInput };`,+) as (...args: unknown[]) => PausedMutations;++const pausedStore =+ await vi.importActual<typeof import("solid-js/store")>("solid-js/store");++function pausedControls() {+ const [options, setOptions] = pausedStore.createStore<PausedOptions>({+ micName: "A",+ cameraID: { DeviceID: "A" },+ });+ const state = { variant: "paused" };+ const commands = {+ pauseRecording: vi.fn(async () => {}),+ setMicInput: vi.fn(async (_name: string | null) => {}),+ setCameraInput: vi.fn(+ async (_id: PausedCameraId, _skip: boolean | null) => {},+ ),+ };+ const close = vi.fn(async () => {});+ const getCameraWindow = vi.fn(async () => ({ close }));+ const refresh = vi.fn(async () => {});+ const mutations = createPausedMutations(+ <T>(factory: () => { mutationFn: (value: T) => Promise<void> }) => ({+ mutateAsync: factory().mutationFn,+ }),+ { rawOptions: options, setOptions },+ commands,+ () => state,+ true,+ true,+ () => true,+ getCameraWindow,+ refresh,+ pausedStore.reconcile,+ );+ return {+ ...mutations,+ options,+ commands,+ state,+ close,+ getCameraWindow,+ refresh,+ };+}++const pausedCamera = (+ id: string,+ model_id: string | null = null,+): PausedCamera => ({+ device_id: id,+ model_id,+ display_name: id,+});++describe("paused recording requested inputs", () => {+ it("keeps failed microphone B visible and sends an explicit A retry", async () => {+ const controls = pausedControls();+ controls.commands.setMicInput.mockRejectedValueOnce(new Error("B failed"));+ await expect(controls.updateMicInput.mutateAsync("B")).rejects.toThrow(+ "B failed",+ );+ expect(controls.options.micName).toBe("B");+ await controls.updateMicInput.mutateAsync("A");+ expect(controls.commands.setMicInput.mock.calls).toEqual([["B"], ["A"]]);+ expect(controls.options.micName).toBe("A");+ });++ it("retries the selected microphone including a failed None request", async () => {+ const controls = pausedControls();+ await controls.updateMicInput.mutateAsync("A");+ controls.commands.setMicInput.mockRejectedValueOnce(+ new Error("None failed"),+ );+ await expect(controls.updateMicInput.mutateAsync(null)).rejects.toThrow(+ "None failed",+ );+ expect(controls.options.micName).toBeNull();+ await controls.updateMicInput.mutateAsync(null);+ expect(controls.commands.setMicInput.mock.calls).toEqual([+ ["A"],+ [null],+ [null],+ ]);+ });++ it("does not overwrite or report an older failed microphone after a later choice", async () => {+ const controls = pausedControls();+ let rejectOld: (error: Error) => void = () => {};+ controls.commands.setMicInput.mockImplementationOnce(+ () =>+ new Promise<void>((_, reject) => {+ rejectOld = reject;+ }),+ );+ const old = controls.updateMicInput.mutateAsync("B");+ await Promise.resolve();+ await controls.updateMicInput.mutateAsync(null);+ rejectOld(new Error("B failed late"));+ await old;+ expect(controls.options.micName).toBeNull();+ });++ it("keeps failed camera B visible and sends an explicit A retry", async () => {+ const controls = pausedControls();+ controls.commands.setCameraInput.mockRejectedValueOnce(+ new Error("B failed"),+ );+ await expect(+ controls.updateCameraInput.mutateAsync(pausedCamera("B")),+ ).rejects.toThrow("B failed");+ expect(controls.options.cameraID).toEqual({ DeviceID: "B" });+ await controls.updateCameraInput.mutateAsync(pausedCamera("A"));+ expect(controls.commands.setCameraInput.mock.calls).toEqual([+ [{ DeviceID: "B" }, null],+ [{ DeviceID: "A" }, null],+ ]);+ expect(controls.options.cameraID).toEqual({ DeviceID: "A" });+ });++ it("retries the selected model camera and preserves its identifier form", async () => {+ const controls = pausedControls();+ controls.options.cameraID = { ModelID: "Model A" };+ await controls.updateCameraInput.mutateAsync(pausedCamera("A", "Model A"));+ expect(controls.commands.setCameraInput).toHaveBeenCalledWith(+ { ModelID: "Model A" },+ null,+ );+ expect(controls.options.cameraID).toEqual({ ModelID: "Model A" });+ });++ it("reconciles identifier variants without retaining a different camera key", async () => {+ const controls = pausedControls();+ controls.commands.setCameraInput.mockRejectedValueOnce(+ new Error("Model B failed"),+ );+ await expect(+ controls.updateCameraInput.mutateAsync(pausedCamera("B", "Model B")),+ ).rejects.toThrow("Model B failed");+ expect(controls.options.cameraID).toEqual({ ModelID: "Model B" });+ await controls.updateCameraInput.mutateAsync(pausedCamera("A"));+ expect(controls.options.cameraID).toEqual({ DeviceID: "A" });+ expect(controls.commands.setCameraInput.mock.calls).toEqual([+ [{ ModelID: "Model B" }, null],+ [{ DeviceID: "A" }, null],+ ]);+ });++ it("does not overwrite or report an older failed camera after a later choice", async () => {+ const controls = pausedControls();+ let rejectOld: (error: Error) => void = () => {};+ controls.commands.setCameraInput.mockImplementationOnce(+ () =>+ new Promise<void>((_, reject) => {+ rejectOld = reject;+ }),+ );+ const old = controls.updateCameraInput.mutateAsync(pausedCamera("B"));+ await Promise.resolve();+ await controls.updateCameraInput.mutateAsync(null);+ rejectOld(new Error("B failed late"));+ await old;+ expect(controls.options.cameraID).toBeNull();+ });++ it("ignores backend supersession without erasing either current request", async () => {+ const controls = pausedControls();+ controls.commands.setMicInput.mockRejectedValueOnce(+ "Microphone selection was superseded by a newer request",+ );+ controls.commands.setCameraInput.mockRejectedValueOnce(+ "Camera selection was superseded by a newer request",+ );+ await controls.updateMicInput.mutateAsync("B");+ await controls.updateCameraInput.mutateAsync(pausedCamera("B"));+ expect(controls.options).toEqual({+ micName: "B",+ cameraID: { DeviceID: "B" },+ });+ });++ it("does not change requested inputs when acknowledged Pause fails", async () => {+ const controls = pausedControls();+ controls.state.variant = "recording";+ controls.commands.pauseRecording.mockRejectedValue(+ new Error("Pause failed"),+ );+ await expect(controls.updateMicInput.mutateAsync("B")).rejects.toThrow(+ "Pause failed",+ );+ await expect(+ controls.updateCameraInput.mutateAsync(pausedCamera("B")),+ ).rejects.toThrow("Pause failed");+ expect(controls.options).toEqual({+ micName: "A",+ cameraID: { DeviceID: "A" },+ });+ expect(controls.commands.setMicInput).not.toHaveBeenCalled();+ expect(controls.commands.setCameraInput).not.toHaveBeenCalled();+ });++ it("waits for acknowledged Pause before storing and sending the requested input", async () => {+ const controls = pausedControls();+ controls.state.variant = "recording";+ let paused: () => void = () => {};+ controls.commands.pauseRecording.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ paused = resolve;+ }),+ );+ const request = controls.updateMicInput.mutateAsync("B");+ expect(controls.options.micName).toBe("A");+ expect(controls.commands.setMicInput).not.toHaveBeenCalled();+ paused();+ await request;+ expect(controls.options.micName).toBe("B");+ expect(controls.state.variant).toBe("recording");+ });++ it("keeps None after camera-window cleanup fails and retries it explicitly", async () => {+ const controls = pausedControls();+ controls.close.mockRejectedValueOnce(new Error("Close failed"));+ await expect(controls.updateCameraInput.mutateAsync(null)).rejects.toThrow(+ "Close failed",+ );+ expect(controls.options.cameraID).toBeNull();+ await controls.updateCameraInput.mutateAsync(null);+ expect(controls.commands.setCameraInput.mock.calls).toEqual([+ [null, null],+ [null, null],+ ]);+ expect(controls.refresh).toHaveBeenCalledTimes(1);+ });++ it("does not close a newer camera after a delayed None completion", async () => {+ const controls = pausedControls();+ let finishOld: () => void = () => {};+ controls.commands.setCameraInput.mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ finishOld = resolve;+ }),+ );+ const old = controls.updateCameraInput.mutateAsync(null);+ await Promise.resolve();+ await controls.updateCameraInput.mutateAsync(pausedCamera("B"));+ finishOld();+ await old;+ expect(controls.options.cameraID).toEqual({ DeviceID: "B" });+ expect(controls.close).not.toHaveBeenCalled();+ });++ it("rechecks the current camera after waiting for the preview window", async () => {+ const controls = pausedControls();+ let finishLookup: (window: { close: typeof controls.close }) => void =+ () => {};+ controls.getCameraWindow.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishLookup = resolve;+ }),+ );+ const old = controls.updateCameraInput.mutateAsync(null);+ await Promise.resolve();+ await Promise.resolve();+ await controls.updateCameraInput.mutateAsync(pausedCamera("B"));+ finishLookup({ close: controls.close });+ await old;+ expect(controls.close).not.toHaveBeenCalled();+ expect(controls.options.cameraID).toEqual({ DeviceID: "B" });+ });+});diff --git a/apps/desktop/src/utils/queries.ts b/apps/desktop/src/utils/queries.tsindex 4118d0cb9..1ba4551cf 100644--- a/apps/desktop/src/utils/queries.ts+++ b/apps/desktop/src/utils/queries.ts@@ -187,8 +187,28 @@ export function createOptionsQuery() {organizationId: null,});+ let microphoneRevision = 0;+ let cameraRevision = 0;+ const markInputChanges = (update: unknown) => {+ if (+ update === "micName" ||+ (typeof update === "object" && update !== null && "micName" in update)+ )+ microphoneRevision++;+ if (+ update === "cameraID" ||+ (typeof update === "object" && update !== null && "cameraID" in update)+ )+ cameraRevision++;+ };createEventListener(window, "storage", (e) => {- if (e.key === PERSIST_KEY) _setState(JSON.parse(e.newValue ?? "{}"));+ if (e.key === PERSIST_KEY) {+ const update: unknown = JSON.parse(e.newValue ?? "{}");+ if (typeof update === "object" && update !== null) {+ markInputChanges(update);+ _setState(update);+ }+ }});let initialized = false;@@ -198,10 +218,10 @@ export function createOptionsQuery() {if (data?.target) {_setState("captureTarget", data.target);}- if (data?.micName !== undefined) {+ if (data?.micName !== undefined && microphoneRevision === 0) {_setState("micName", data.micName);}- if (data?.cameraId !== undefined) {+ if (data?.cameraId !== undefined && cameraRevision === 0) {_setState("cameraID", data.cameraId);}if (data?.mode && data.mode !== _state.mode) {@@ -243,7 +263,29 @@ export function createOptionsQuery() {name: PERSIST_KEY,});- return { rawOptions: state, setOptions: setState };+ const setOptions = new Proxy(setState, {+ apply(target, thisArg, args) {+ markInputChanges(args[0]);+ return Reflect.apply(target, thisArg, args);+ },+ });+ return { rawOptions: state, setOptions };+}++export function createCleanCaptureQuery() {+ const query = createQuery(() => ({+ queryKey: ["cleanCapture"] as const,+ queryFn: () => commands.getCleanCaptureState(),+ refetchOnWindowFocus: true,+ }));+ createQueryInvalidate(query, "currentRecordingChanged");+ return query;+}++export async function revealRecordingWindow(generation?: number) {+ const currentGeneration =+ generation ?? (await commands.getCleanCaptureState()).generation;+ return commands.revealCaptureWindow(currentGeneration, null);}export function createCurrentRecordingQuery() {@@ -285,6 +327,29 @@ export function createLicenseQuery() {return query;}+function inputRequestWasSuperseded(error: unknown) {+ return String(error).includes("selection was superseded by a newer request");+}++export function createMicrophoneMutation() {+ const { setOptions, rawOptions } = useRecordingOptions();+ return useMutation(() => ({+ mutationFn: async (name: string | null) => {+ setOptions("micName", name);+ try {+ await commands.setMicInput(name);+ } catch (error) {+ if (+ (rawOptions.micName ?? null) !== name ||+ inputRequestWasSuperseded(error)+ )+ return;+ throw error;+ }+ },+ }));+}+export function createCameraMutation() {const { setOptions, rawOptions } = useRecordingOptions();@@ -292,36 +357,23 @@ export function createCameraMutation() {model: DeviceOrModelID | null,skipCameraWindow?: boolean,) => {- const before = rawOptions.cameraID ? { ...rawOptions.cameraID } : null;setOptions("cameraID", reconcile(model));- await commands- .setCameraInput(model, skipCameraWindow ?? null)- .catch(async (e) => {- const message =- typeof e === "string"- ? e- : e instanceof Error- ? e.message- : String(e);-- if (- message.includes("DeviceNotFound") ||- message.includes("CameraTimeout") ||- message.includes("Failed to initialize camera")- ) {- setOptions("cameraID", null);- console.warn("Selected camera is unavailable.");- return;- }-- if (JSON.stringify(before) === JSON.stringify(model) || !before) {- setOptions("cameraID", null);- } else setOptions("cameraID", reconcile(before));-- throw e;- });+ try {+ await commands.setCameraInput(model, skipCameraWindow ?? null);+ } catch (error) {+ if (+ JSON.stringify(rawOptions.cameraID ?? null) !== JSON.stringify(model) ||+ inputRequestWasSuperseded(error)+ )+ return;+ throw error;+ }- if (model && !skipCameraWindow) {+ if (+ model &&+ !skipCameraWindow &&+ JSON.stringify(rawOptions.cameraID) === JSON.stringify(model)+ ) {getCurrentWindow().setFocus();}};diff --git a/crates/camera-effects/src/lib.rs b/crates/camera-effects/src/lib.rsindex d5355dab1..1e9df1798 100644--- a/crates/camera-effects/src/lib.rs+++ b/crates/camera-effects/src/lib.rs@@ -61,7 +61,11 @@ const READBACK_READY_ERR: u8 = 2;enum ReadbackState {Idle,- InFlight(Arc<AtomicU8>),+ InFlight {+ status: Arc<AtomicU8>,+ submitted_at: Instant,+ dimensions: (u32, u32),+ },}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -70,6 +74,171 @@ pub enum BlurMode {Heavy,}+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum BlurFailure {+ Inference(String),+ Readback(String),+ InvalidMask {+ expected_samples: usize,+ actual_samples: usize,+ },+ NonFiniteMask,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct BlurMaskReceipt {+ pub generation: u64,+ /// Processing submission time, not the camera's original capture timestamp.+ pub input_submitted_at: Instant,+ pub inference_completed_at: Instant,+ pub input_dimensions: (u32, u32),+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum BlurMaskStatus {+ Pending,+ Ready(BlurMaskReceipt),+ Failed(BlurFailure),+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct BlurOutputStatus {+ pub mode: BlurMode,+ pub output_sequence: u64,+ pub output_dimensions: (u32, u32),+ pub mask: BlurMaskStatus,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct AppliedBlur {+ pub mode: BlurMode,+ pub output_sequence: u64,+ pub output_dimensions: (u32, u32),+ pub mask: BlurMaskReceipt,+ pub mask_age: Duration,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum BlurOutputUnavailable {+ Pending,+ Failed(BlurFailure),+ Stale {+ mask_age: Duration,+ max_mask_age: Duration,+ },+ MaskGeometryMismatch,+ InvalidTimestamp,+}++impl BlurOutputStatus {+ pub fn applied_at(+ &self,+ now: Instant,+ max_mask_age: Duration,+ ) -> Result<AppliedBlur, BlurOutputUnavailable> {+ let mask = match &self.mask {+ BlurMaskStatus::Pending => return Err(BlurOutputUnavailable::Pending),+ BlurMaskStatus::Failed(error) => {+ return Err(BlurOutputUnavailable::Failed(error.clone()));+ }+ BlurMaskStatus::Ready(mask) => *mask,+ };+ if mask.input_dimensions != self.output_dimensions {+ return Err(BlurOutputUnavailable::MaskGeometryMismatch);+ }+ if mask.input_submitted_at > mask.inference_completed_at+ || now < mask.inference_completed_at+ {+ return Err(BlurOutputUnavailable::InvalidTimestamp);+ }+ let mask_age = now.saturating_duration_since(mask.input_submitted_at);+ if mask_age > max_mask_age {+ return Err(BlurOutputUnavailable::Stale {+ mask_age,+ max_mask_age,+ });+ }+ Ok(AppliedBlur {+ mode: self.mode,+ output_sequence: self.output_sequence,+ output_dimensions: self.output_dimensions,+ mask,+ mask_age,+ })+ }+}++struct MaskStatusTracker {+ generation: u64,+ failure_revision: u64,+ status: BlurMaskStatus,+}++impl Default for MaskStatusTracker {+ fn default() -> Self {+ Self {+ generation: 0,+ failure_revision: 0,+ status: BlurMaskStatus::Pending,+ }+ }+}++impl MaskStatusTracker {+ fn reset(&mut self) {+ self.generation = self.generation.wrapping_add(1);+ self.failure_revision = self.failure_revision.wrapping_add(1);+ self.status = BlurMaskStatus::Pending;+ }++ fn fail(&mut self, failure: BlurFailure) {+ self.failure_revision = self.failure_revision.wrapping_add(1);+ self.status = BlurMaskStatus::Failed(failure);+ }++ fn complete(+ &mut self,+ failure_revision: u64,+ submitted_at: Instant,+ dimensions: (u32, u32),+ now: Instant,+ ) {+ if self.failure_revision != failure_revision {+ return;+ }+ self.generation = self.generation.wrapping_add(1);+ self.status = BlurMaskStatus::Ready(BlurMaskReceipt {+ generation: self.generation,+ input_submitted_at: submitted_at,+ inference_completed_at: now,+ input_dimensions: dimensions,+ });+ }+}++fn validate_mask_samples(mask: &[f32], expected_samples: usize) -> Result<(), BlurFailure> {+ if mask.len() < expected_samples {+ return Err(BlurFailure::InvalidMask {+ expected_samples,+ actual_samples: mask.len(),+ });+ }+ if mask+ .iter()+ .take(expected_samples)+ .any(|value| !value.is_finite())+ {+ return Err(BlurFailure::NonFiniteMask);+ }+ Ok(())+}++struct ReadbackFrame {+ pixels: Vec<u8>,+ submitted_at: Instant,+ dimensions: (u32, u32),+}+const SEGMENTATION_SIZE: u32 = 256;const DEFAULT_INFERENCE_INTERVAL: Duration = Duration::from_millis(66);const MASK_GROWTH_ALPHA: f32 = 0.25;@@ -78,6 +247,12 @@ const MASK_STABILITY_EPSILON: f32 = 0.025;const MASK_EDGE_CONTRAST: f32 = 4.0;const INITIAL_MASK_VALUE: f32 = 1.0;+fn reset_mask_buffers(buffers: [&mut [f32]; 4]) {+ for buffer in buffers {+ buffer.fill(INITIAL_MASK_VALUE);+ }+}+pub struct BlurProcessor {model: SegmentationModel,blur_pipeline: BlurPipeline,@@ -95,9 +270,13 @@ pub struct BlurProcessor {readback_bytes_per_row: u32,readback_state: ReadbackState,inference_interval: Duration,+ inference_requested: bool,mask_initialized: bool,mask_dirty: bool,output_generation: u64,+ output_sequence: u64,+ mask_status: MaskStatusTracker,+ last_output_status: Option<BlurOutputStatus>,// Keep last: must drop after every other field (see BlurSessionHandle)._blur_session: BlurSessionHandle,}@@ -264,9 +443,13 @@ impl BlurProcessor {readback_bytes_per_row,readback_state: ReadbackState::Idle,inference_interval: DEFAULT_INFERENCE_INTERVAL,+ inference_requested: false,mask_initialized: false,mask_dirty: true,output_generation: 0,+ output_sequence: 0,+ mask_status: MaskStatusTracker::default(),+ last_output_status: None,_blur_session: blur_session,})}@@ -275,10 +458,34 @@ impl BlurProcessor {self.inference_interval = interval;}+ /// Call between outputs after submitting prior work; discard queued output readbacks too.+ pub fn reset_mask_history(&mut self) {+ if matches!(self.readback_state, ReadbackState::InFlight { .. }) {+ self.readback_buffer.unmap();+ }+ self.readback_state = ReadbackState::Idle;+ reset_mask_buffers([+ &mut self.mask_data,+ &mut self.smoothed_mask,+ &mut self.mask_scratch,+ &mut self.mask_upload,+ ]);+ self.mask_initialized = false;+ self.mask_dirty = true;+ self.inference_requested = true;+ self.mask_status.reset();+ self.last_output_status = None;+ }+pub fn output_generation(&self) -> u64 {self.output_generation}+ /// Describes encoded work; the caller must complete its GPU submission before using the output.+ pub fn output_status(&self) -> Option<BlurOutputStatus> {+ self.last_output_status.clone()+ }+pub fn output_view(&self) -> Option<&wgpu::TextureView> {self.textures.as_ref().map(|t| &t.output_view)}@@ -319,7 +526,8 @@ impl BlurProcessor {self.ensure_textures(device, width, height);let input_view = input_texture.create_view(&Default::default());- if self.last_inference.elapsed() >= self.inference_interval {+ if self.inference_requested || self.last_inference.elapsed() >= self.inference_interval {+ self.inference_requested = false;let mask_updated = self.run_segmentation(device, queue, input_texture);self.last_inference = Instant::now();if mask_updated {@@ -368,6 +576,13 @@ impl BlurProcessor {&textures.mask_view,&textures.output_view,);+ self.output_sequence = self.output_sequence.wrapping_add(1);+ self.last_output_status = Some(BlurOutputStatus {+ mode,+ output_sequence: self.output_sequence,+ output_dimensions: (width, height),+ mask: self.mask_status.status.clone(),+ });}pub fn process_returning_output(&mut self) -> Option<&wgpu::Texture> {@@ -444,15 +659,20 @@ impl BlurProcessor {queue: &wgpu::Queue,input_texture: &wgpu::Texture,) -> bool {+ let failure_revision = self.mask_status.failure_revision;let rgba_256 =match self.readback_downsampled(device, queue, input_texture, !self.mask_initialized) {Some(data) => data,None => return false,};- match self.model.run_inference(&rgba_256) {+ match self.model.run_inference(&rgba_256.pixels) {Ok(new_mask) => {let pixel_count = (SEGMENTATION_SIZE * SEGMENTATION_SIZE) as usize;+ let mask_validation = validate_mask_samples(new_mask, pixel_count);+ if let Err(error) = &mask_validation {+ self.mask_status.fail(error.clone());+ }if new_mask.len() >= pixel_count {for (i, &raw) in new_mask.iter().take(pixel_count).enumerate() {let v = refine_mask_value(raw);@@ -465,12 +685,26 @@ impl BlurProcessor {self.mask_data.copy_from_slice(&self.smoothed_mask[..pixel_count]);self.mask_initialized = true;+ let smoothed_validation = validate_mask_samples(&self.mask_data, pixel_count);+ if let Err(error) = &smoothed_validation {+ self.mask_status.fail(error.clone());+ }+ if mask_validation.is_ok() && smoothed_validation.is_ok() {+ self.mask_status.complete(+ failure_revision,+ rgba_256.submitted_at,+ rgba_256.dimensions,+ Instant::now(),+ );+ }return true;}false}Err(e) => {tracing::warn!("Segmentation inference failed: {e:#}");+ self.mask_status+ .fail(BlurFailure::Inference(format!("{e:#}")));false}}@@ -482,7 +716,7 @@ impl BlurProcessor {queue: &wgpu::Queue,input_texture: &wgpu::Texture,wait_for_result: bool,- ) -> Option<Vec<u8>> {+ ) -> Option<ReadbackFrame> {let mut completed = self.take_completed_readback(device, wgpu::PollType::Poll);if matches!(self.readback_state, ReadbackState::Idle) {@@ -550,6 +784,7 @@ impl BlurProcessor {},);+ let submitted_at = Instant::now();queue.submit(std::iter::once(encoder.finish()));let status = Arc::new(AtomicU8::new(READBACK_PENDING));@@ -565,7 +800,11 @@ impl BlurProcessor {status_cb.store(code, Ordering::Release);});- self.readback_state = ReadbackState::InFlight(status);+ self.readback_state = ReadbackState::InFlight {+ status,+ submitted_at,+ dimensions: (input_texture.width(), input_texture.height()),+ };if wait_for_result {completed = self@@ -581,9 +820,20 @@ impl BlurProcessor {&mut self,device: &wgpu::Device,poll_type: wgpu::PollType,- ) -> Option<Vec<u8>> {- if let ReadbackState::InFlight(status) = &self.readback_state {- let _ = device.poll(poll_type);+ ) -> Option<ReadbackFrame> {+ if let ReadbackState::InFlight {+ status,+ submitted_at,+ dimensions,+ } = &self.readback_state+ {+ let submitted_at = *submitted_at;+ let dimensions = *dimensions;+ if let Err(error) = device.poll(poll_type) {+ self.mask_status.fail(BlurFailure::Readback(format!(+ "GPU polling failed: {error}"+ )));+ }match status.load(Ordering::Acquire) {READBACK_READY_OK => {let slice = self.readback_buffer.slice(..);@@ -598,10 +848,17 @@ impl BlurProcessor {drop(data);self.readback_buffer.unmap();self.readback_state = ReadbackState::Idle;- Some(out)+ Some(ReadbackFrame {+ pixels: out,+ submitted_at,+ dimensions,+ })}READBACK_READY_ERR => {self.readback_state = ReadbackState::Idle;+ self.mask_status.fail(BlurFailure::Readback(+ "GPU mask readback failed".to_string(),+ ));None}_ => None,@@ -730,3 +987,218 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {return textureSample(src_tex, src_sampler, in.uv);}";++#[cfg(test)]+mod blur_status_tests {+ use super::*;++ #[test]+ fn reset_invalidates_ready_and_failed_masks_until_new_inference() {+ let now = Instant::now();+ let mut tracker = MaskStatusTracker::default();+ tracker.complete(0, now, (640, 480), now);+ let previous_generation = tracker.generation;+ tracker.reset();+ assert_eq!(tracker.status, BlurMaskStatus::Pending);+ assert!(tracker.generation > previous_generation);+ tracker.complete(0, now, (640, 480), now);+ assert_eq!(tracker.status, BlurMaskStatus::Pending);+ tracker.complete(tracker.failure_revision, now, (640, 480), now);+ assert!(matches!(tracker.status, BlurMaskStatus::Ready(_)));+ tracker.fail(BlurFailure::NonFiniteMask);+ tracker.reset();+ assert_eq!(tracker.status, BlurMaskStatus::Pending);+ }++ #[test]+ fn reset_erases_smoothing_without_reallocating_cpu_buffers() {+ let mut data = vec![0.0, 0.5, f32::NAN];+ let mut smoothed = vec![0.2, 0.8];+ let mut scratch = vec![f32::INFINITY, 0.4];+ let mut upload = vec![0.1];+ let pointers = [+ data.as_ptr(),+ smoothed.as_ptr(),+ scratch.as_ptr(),+ upload.as_ptr(),+ ];+ reset_mask_buffers([&mut data, &mut smoothed, &mut scratch, &mut upload]);+ for (index, buffer) in [&data, &smoothed, &scratch, &upload]+ .into_iter()+ .enumerate()+ {+ assert_eq!(buffer.as_ptr(), pointers[index]);+ assert!(buffer.iter().all(|value| *value == INITIAL_MASK_VALUE));+ }+ }++ const DIMS: (u32, u32) = (640, 360);+ const MAX_AGE: Duration = Duration::from_millis(300);++ fn output(tracker: &MaskStatusTracker, mode: BlurMode, sequence: u64) -> BlurOutputStatus {+ BlurOutputStatus {+ mode,+ output_sequence: sequence,+ output_dimensions: DIMS,+ mask: tracker.status.clone(),+ }+ }++ #[test]+ fn initial_default_mask_is_pending_not_applied() {+ let tracker = MaskStatusTracker::default();+ assert_eq!(INITIAL_MASK_VALUE, 1.0);+ assert_eq!(+ output(&tracker, BlurMode::Heavy, 1).applied_at(Instant::now(), MAX_AGE),+ Err(BlurOutputUnavailable::Pending)+ );+ }++ #[test]+ fn successful_mask_binds_exact_output_mode_sequence_and_generation() {+ let start = Instant::now();+ let completed = start + Duration::from_millis(20);+ let mut tracker = MaskStatusTracker::default();+ tracker.complete(0, start, DIMS, completed);+ for (mode, sequence) in [(BlurMode::Light, 3), (BlurMode::Heavy, 4)] {+ let applied = output(&tracker, mode, sequence)+ .applied_at(completed, MAX_AGE)+ .unwrap();+ assert_eq!(applied.mode, mode);+ assert_eq!(applied.output_sequence, sequence);+ assert_eq!(applied.output_dimensions, DIMS);+ assert_eq!(applied.mask.generation, 1);+ assert_eq!(applied.mask.input_submitted_at, start);+ assert_eq!(applied.mask.inference_completed_at, completed);+ }+ tracker.complete(0, completed, DIMS, completed);+ assert_eq!(+ output(&tracker, BlurMode::Light, 5)+ .applied_at(completed, MAX_AGE)+ .unwrap()+ .mask+ .generation,+ 2+ );+ }++ #[test]+ fn reused_mask_expires_from_input_submission_not_inference_completion() {+ let start = Instant::now();+ let completed = start + Duration::from_millis(290);+ let mut tracker = MaskStatusTracker::default();+ tracker.complete(0, start, DIMS, completed);+ let status = output(&tracker, BlurMode::Light, 2);+ let boundary = status.applied_at(start + MAX_AGE, MAX_AGE).unwrap();+ assert_eq!(boundary.mask_age, MAX_AGE);+ assert_eq!(boundary.mask.generation, 1);+ let expired_age = MAX_AGE + Duration::from_millis(1);+ assert_eq!(+ status.applied_at(start + expired_age, MAX_AGE),+ Err(BlurOutputUnavailable::Stale {+ mask_age: expired_age,+ max_mask_age: MAX_AGE,+ })+ );+ }++ #[test]+ fn inference_and_readback_failures_invalidate_previous_valid_mask() {+ let now = Instant::now();+ for failure in [+ BlurFailure::Inference("inference failed".into()),+ BlurFailure::Readback("readback failed".into()),+ BlurFailure::InvalidMask {+ expected_samples: 4,+ actual_samples: 2,+ },+ BlurFailure::NonFiniteMask,+ ] {+ let mut tracker = MaskStatusTracker::default();+ tracker.complete(0, now, DIMS, now);+ tracker.fail(failure.clone());+ assert_eq!(+ output(&tracker, BlurMode::Heavy, 2).applied_at(now, MAX_AGE),+ Err(BlurOutputUnavailable::Failed(failure))+ );+ }+ }++ #[test]+ fn completed_old_readback_cannot_hide_new_readback_failure() {+ let now = Instant::now();+ let mut tracker = MaskStatusTracker::default();+ let revision = tracker.failure_revision;+ let failure = BlurFailure::Readback("poll failed".into());+ tracker.fail(failure.clone());+ tracker.complete(revision, now, DIMS, now);+ assert_eq!(tracker.status, BlurMaskStatus::Failed(failure));+ assert_eq!(tracker.generation, 0);+ tracker.complete(tracker.failure_revision, now, DIMS, now);+ assert!(+ output(&tracker, BlurMode::Heavy, 3)+ .applied_at(now, MAX_AGE)+ .is_ok()+ );+ assert_eq!(tracker.generation, 1);+ }++ #[test]+ fn resized_output_cannot_claim_old_geometry_mask() {+ let now = Instant::now();+ let mut tracker = MaskStatusTracker::default();+ tracker.complete(0, now, DIMS, now);+ let mut status = output(&tracker, BlurMode::Heavy, 1);+ status.output_dimensions = (320, 180);+ assert_eq!(+ status.applied_at(now, MAX_AGE),+ Err(BlurOutputUnavailable::MaskGeometryMismatch)+ );+ }++ #[test]+ fn future_or_inverted_mask_timestamps_are_rejected() {+ let now = Instant::now();+ let later = now + Duration::from_millis(1);+ for (submitted, completed) in [(later, now), (now, later)] {+ let mut tracker = MaskStatusTracker::default();+ tracker.complete(0, submitted, DIMS, completed);+ assert_eq!(+ output(&tracker, BlurMode::Light, 1).applied_at(now, MAX_AGE),+ Err(BlurOutputUnavailable::InvalidTimestamp)+ );+ }+ }++ #[test]+ fn invalid_masks_fail_but_real_uniform_segmentation_is_valid() {+ assert_eq!(+ validate_mask_samples(&[1.0], 2),+ Err(BlurFailure::InvalidMask {+ expected_samples: 2,+ actual_samples: 1,+ })+ );+ for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ assert_eq!(+ validate_mask_samples(&[0.5, value], 2),+ Err(BlurFailure::NonFiniteMask)+ );+ }+ for mask in [[0.0; 2], [1.0; 2]] {+ assert_eq!(validate_mask_samples(&mask, 2), Ok(()));+ }+ assert_eq!(validate_mask_samples(&[0.0, 1.0, f32::NAN], 2), Ok(()));+ }++ #[test]+ fn valid_new_inference_cannot_certify_nan_contaminated_smoothed_mask() {+ let next = refine_mask_value(0.5);+ assert_eq!(validate_mask_samples(&[next], 1), Ok(()));+ let smoothed = smooth_mask_value(f32::NAN, next);+ assert_eq!(+ validate_mask_samples(&[smoothed], 1),+ Err(BlurFailure::NonFiniteMask)+ );+ }+}diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex e75b7cd4e..77121a107 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -230,6 +230,8 @@ impl EditorInstance {return Err("Cannot edit non-studio recordings".to_string());};+ meta.ensure_ordinary_media_access(&project_path)?;+let segment_count = match meta.as_ref() {StudioRecordingMeta::SingleSegment { .. } => 1,StudioRecordingMeta::MultipleSegments { inner } => inner.segments.len(),diff --git a/crates/enc-ffmpeg/src/base.rs b/crates/enc-ffmpeg/src/base.rsindex 2edb1226f..ace6701de 100644--- a/crates/enc-ffmpeg/src/base.rs+++ b/crates/enc-ffmpeg/src/base.rs@@ -119,7 +119,7 @@ impl EncoderBase {output: &mut format::context::Output,encoder: &mut encoder::encoder::Encoder,) -> Result<(), ffmpeg::Error> {- while encoder.receive_packet(&mut self.packet).is_ok() {+ while packet_available(encoder.receive_packet(&mut self.packet))? {self.packet.set_stream(self.stream_index);self.packet.rescale_ts(encoder.time_base(),@@ -195,6 +195,15 @@ impl EncoderBase {}}+fn packet_available(result: Result<(), ffmpeg::Error>) -> Result<bool, ffmpeg::Error> {+ match result {+ Ok(()) => Ok(true),+ Err(ffmpeg::Error::Eof) => Ok(false),+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::error::EAGAIN => Ok(false),+ Err(error) => Err(error),+ }+}+fn nominal_packet_duration(time_base: Rational, frame_rate: Rational) -> Option<i64> {let time_base_num = time_base.numerator();let time_base_den = time_base.denominator();@@ -249,4 +258,109 @@ mod tests {assert_eq!(normalize_input_pts(90_000, Some(100_000)), 100_001);assert_eq!(normalize_input_pts(100_000, Some(100_000)), 100_001);}++ #[test]+ fn receive_success_exposes_one_packet() {+ assert_eq!(packet_available(Ok(())), Ok(true));+ }++ #[test]+ fn receive_eof_finishes_packet_drain() {+ assert_eq!(packet_available(Err(ffmpeg::Error::Eof)), Ok(false));+ }++ #[test]+ fn receive_eagain_requests_more_input_without_error() {+ assert_eq!(+ packet_available(Err(ffmpeg::Error::Other {+ errno: ffmpeg::error::EAGAIN,+ })),+ Ok(false)+ );+ }++ #[test]+ fn unexpected_receive_errors_keep_their_exact_error() {+ for error in [+ ffmpeg::Error::InvalidData,+ ffmpeg::Error::Bug,+ ffmpeg::Error::External,+ ffmpeg::Error::Exit,+ ffmpeg::Error::Other {+ errno: ffmpeg::error::EINVAL,+ },+ ffmpeg::Error::Other {+ errno: ffmpeg::error::EIO,+ },+ ffmpeg::Error::Other {+ errno: ffmpeg::error::ENOMEM,+ },+ ffmpeg::Error::Other {+ errno: ffmpeg::error::EINTR,+ },+ ] {+ assert_eq!(packet_available(Err(error)), Err(error));+ }+ }++ #[test]+ fn receive_failure_after_output_does_not_read_another_packet() {+ let mut results = [Ok(()), Err(ffmpeg::Error::InvalidData), Ok(())].into_iter();+ let mut processed = 0;+ let outcome = (|| {+ while packet_available(results.next().unwrap())? {+ processed += 1;+ }+ Ok::<(), ffmpeg::Error>(())+ })();+ assert_eq!(outcome, Err(ffmpeg::Error::InvalidData));+ assert_eq!(processed, 1);+ assert_eq!(results.next(), Some(Ok(())));+ }++ #[test]+ fn normal_receive_states_do_not_consume_next_input_opportunity() {+ for terminal in [+ ffmpeg::Error::Eof,+ ffmpeg::Error::Other {+ errno: ffmpeg::error::EAGAIN,+ },+ ] {+ let mut results = [Ok(()), Err(terminal), Ok(())].into_iter();+ let mut processed = 0;+ while packet_available(results.next().unwrap()).unwrap() {+ processed += 1;+ }+ assert_eq!(processed, 1);+ assert_eq!(results.next(), Some(Ok(())));+ }+ }++ #[test]+ fn actual_unopened_encoder_receive_is_not_success_and_keeps_held_packet() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("unopened.mp4");+ let mut output = format::output_as(&path, "mp4").unwrap();+ let mut encoder = ffmpeg::codec::context::Context::new().encoder();+ let mut base = EncoderBase::new(0);+ let mut previous = Packet::copy(b"held-packet");+ previous.set_pts(Some(42));+ previous.set_dts(Some(40));+ previous.set_duration(1024);+ base.held_packet = Some((previous, true));+ let error = base.process_packets(&mut output, &mut encoder).unwrap_err();+ assert_eq!(+ error,+ ffmpeg::Error::Other {+ errno: ffmpeg::error::EINVAL+ }+ );+ let (previous, synthesized) = base.held_packet.as_ref().unwrap();+ assert_eq!(previous.data(), Some(b"held-packet".as_slice()));+ assert_eq!(previous.pts(), Some(42));+ assert_eq!(previous.dts(), Some(40));+ assert_eq!(previous.duration(), 1024);+ assert!(*synthesized);+ assert!(path.exists());+ }}diff --git a/crates/enc-ffmpeg/src/mux/dash_audio.rs b/crates/enc-ffmpeg/src/mux/dash_audio.rsindex 5e5b0f4cb..4bff4b82d 100644--- a/crates/enc-ffmpeg/src/mux/dash_audio.rs+++ b/crates/enc-ffmpeg/src/mux/dash_audio.rs@@ -1,3 +1,4 @@+use super::fragment_metadata::read_fragment_metadata;use crate::audio::aac::{AACEncoder, AACEncoderError};use crate::mux::segmented_stream::{SegmentCompletedEvent, SegmentMediaType};use cap_media_info::AudioInfo;@@ -49,17 +50,13 @@ pub struct DashAudioSegmentEncoder {base_path: PathBuf,encoder: AACEncoder,output: format::context::Output,+ initial_padding: Duration,current_index: u32,- segment_duration: Duration,- segment_start_time: Option<Duration>,- last_frame_timestamp: Option<Duration>,- frames_in_segment: u32,completed_segments: Vec<AudioSegmentInfo>,- pending_segment_indices: Vec<(u32, Duration)>,- frames_since_pending_flush: u32,+ frames_since_segment_scan: u32,segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,init_notified: bool,@@ -173,6 +170,20 @@ impl DashAudioSegmentEncoder {}let encoder = AACEncoder::init(audio_config, &mut output)?;+ let parameters = output+ .stream(0)+ .ok_or(ffmpeg::Error::StreamNotFound)?+ .parameters();+ let initial_padding = unsafe {+ let parameters = &*parameters.as_ptr();+ if parameters.initial_padding > 0 && parameters.sample_rate > 0 {+ Duration::from_secs_f64(+ f64::from(parameters.initial_padding) / f64::from(parameters.sample_rate),+ )+ } else {+ Duration::ZERO+ }+ };output.write_header()?;@@ -190,14 +201,10 @@ impl DashAudioSegmentEncoder {base_path,encoder,output,+ initial_padding,current_index: 1,- segment_duration: config.segment_duration,- segment_start_time: None,- last_frame_timestamp: None,- frames_in_segment: 0,completed_segments: Vec::new(),- pending_segment_indices: Vec::new(),- frames_since_pending_flush: 0,+ frames_since_segment_scan: 0,segment_tx: None,init_notified: false,};@@ -245,176 +252,65 @@ impl DashAudioSegmentEncoder {frame: frame::Audio,timestamp: Duration,) -> Result<(), QueueFrameError> {- let is_first_frame = self.segment_start_time.is_none();- let segment_start = match self.segment_start_time {- Some(start) => start,- None => {- self.segment_start_time = Some(timestamp);- timestamp- }- };-- self.last_frame_timestamp = Some(timestamp);-self.encoder.send_frame(frame, timestamp, &mut self.output)?;- self.frames_in_segment += 1;-- if is_first_frame {- self.try_notify_init_segment();- }- if !self.pending_segment_indices.is_empty() {- self.frames_since_pending_flush += 1;- if self.frames_since_pending_flush >= 10 {- self.frames_since_pending_flush = 0;- self.flush_pending_segments();- }- }+ self.try_notify_init_segment();- let elapsed_in_segment = timestamp.saturating_sub(segment_start);- if elapsed_in_segment >= self.segment_duration {- self.on_segment_boundary(self.current_index, timestamp);+ self.frames_since_segment_scan += 1;+ if self.frames_since_segment_scan >= 10 {+ self.frames_since_segment_scan = 0;+ self.flush_pending_segments();}Ok(())}- fn on_segment_boundary(&mut self, completed_index: u32, timestamp: Duration) {- self.try_notify_init_segment();-- let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);- let segment_duration = timestamp.saturating_sub(segment_start);-- let segment_path = self- .base_path- .join(format!("segment_{completed_index:03}.m4s"));-- tracing::debug!(- segment_index = completed_index,- duration_secs = segment_duration.as_secs_f64(),- frames = self.frames_in_segment,- "Audio segment boundary reached (time-based)"- );-- self.current_index = completed_index + 1;- self.segment_start_time = Some(timestamp);- self.frames_in_segment = 0;-- let tmp_path = self- .base_path- .join(format!("segment_{completed_index:03}.m4s.tmp"));-- let (resolved_path, file_size) = if segment_path.exists() {- let size = std::fs::metadata(&segment_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (segment_path.clone(), size)- } else if tmp_path.exists() {- let size = std::fs::metadata(&tmp_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (tmp_path, size)- } else {- (segment_path.clone(), 0)- };-- let file_found = resolved_path.exists();-- if file_found && file_size > 0 {- self.completed_segments.push(AudioSegmentInfo {- path: segment_path.clone(),- index: completed_index,- duration: segment_duration,- file_size: Some(file_size),- });-- self.write_in_progress_manifest();-- self.notify_segment(SegmentCompletedEvent {- path: resolved_path,- index: completed_index,- duration: segment_duration.as_secs_f64(),- file_size,- is_init: false,- media_type: SegmentMediaType::Audio,- });- } else {- tracing::debug!(- segment_index = completed_index,- file_exists = file_found,- file_size,- "Segment file not ready yet, deferring notification"- );- self.pending_segment_indices- .push((completed_index, segment_duration));- self.write_in_progress_manifest();- }- }-fn flush_pending_segments(&mut self) {- if self.pending_segment_indices.is_empty() {- return;- }-- let mut still_pending = Vec::new();-- for (index, duration) in std::mem::take(&mut self.pending_segment_indices) {+ let first_index = self.current_index;+ loop {+ let index = self.current_index;let segment_path = self.base_path.join(format!("segment_{index:03}.m4s"));- let tmp_path = self.base_path.join(format!("segment_{index:03}.m4s.tmp"));-- let (resolved_path, file_size) = if segment_path.exists() {- let size = std::fs::metadata(&segment_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (segment_path.clone(), size)- } else if tmp_path.exists() {- let size = std::fs::metadata(&tmp_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (tmp_path, size)- } else {- still_pending.push((index, duration));- continue;+ let metadata = match read_fragment_metadata(&segment_path) {+ Ok(metadata) => metadata,+ Err(error) => {+ if error.kind() != std::io::ErrorKind::NotFound {+ tracing::debug!(index, %error, "Waiting for finalized segment media");+ }+ break;+ }};-- if file_size == 0 {- still_pending.push((index, duration));- continue;- }-- tracing::debug!(- segment_index = index,- file_size,- "Flushing previously pending segment"- );+ let duration = self.presentation_duration(index, metadata.duration);self.completed_segments.push(AudioSegmentInfo {- path: segment_path,+ path: segment_path.clone(),index,duration,- file_size: Some(file_size),+ file_size: Some(metadata.file_size),});-self.notify_segment(SegmentCompletedEvent {- path: resolved_path,+ path: segment_path,index,duration: duration.as_secs_f64(),- file_size,+ file_size: metadata.file_size,is_init: false,media_type: SegmentMediaType::Audio,});+ self.current_index += 1;}- if !still_pending.is_empty() {+ if self.current_index != first_index {self.write_in_progress_manifest();}+ }- self.pending_segment_indices = still_pending;+ fn presentation_duration(&self, index: u32, duration: Duration) -> Duration {+ if index == 1 {+ // The first AAC fragment includes encoder priming that DASH excludes from its timeline.+ duration.saturating_sub(self.initial_padding)+ } else {+ duration+ }}fn current_segment_path(&self) -> PathBuf {@@ -472,10 +368,6 @@ impl DashAudioSegmentEncoder {}pub fn finish(&mut self) -> Result<(), FinishError> {- let segment_start = self.segment_start_time;- let last_timestamp = self.last_frame_timestamp;- let frames_before_flush = self.frames_in_segment;-if let Err(e) = self.encoder.flush(&mut self.output) {tracing::warn!("Audio encoder flush warning: {e}");}@@ -488,41 +380,15 @@ impl DashAudioSegmentEncoder {self.finalize_pending_tmp_files();self.flush_pending_segments();- let end_timestamp =- last_timestamp.unwrap_or_else(|| segment_start.unwrap_or(Duration::ZERO));- self.collect_orphaned_segments(segment_start, end_timestamp, frames_before_flush);+ self.collect_orphaned_segments();self.finalize_manifest();Ok(())}- pub fn finish_with_timestamp(&mut self, timestamp: Duration) -> Result<(), FinishError> {- let segment_start = self.segment_start_time;- let frames_before_flush = self.frames_in_segment;-- if let Err(e) = self.encoder.flush(&mut self.output) {- tracing::warn!("Audio encoder flush warning: {e}");- }-- if let Err(e) = self.output.write_trailer() {- tracing::warn!("Audio write_trailer warning: {e}");- }-- self.try_notify_init_segment();- self.finalize_pending_tmp_files();- self.flush_pending_segments();-- let effective_end_timestamp = self- .last_frame_timestamp- .map(|last| last.max(timestamp))- .unwrap_or(timestamp);-- self.collect_orphaned_segments(segment_start, effective_end_timestamp, frames_before_flush);-- self.finalize_manifest();-- Ok(())+ pub fn finish_with_timestamp(&mut self, _timestamp: Duration) -> Result<(), FinishError> {+ self.finish()}fn finalize_pending_tmp_files(&self) {@@ -535,12 +401,11 @@ impl DashAudioSegmentEncoder {if let Some(name) = path.file_name().and_then(|n| n.to_str())&& name.starts_with("segment_")&& name.ends_with(".m4s.tmp")- && let Ok(metadata) = std::fs::metadata(&path)- && metadata.len() > 0+ && let Ok(metadata) = read_fragment_metadata(&path){let final_name = name.trim_end_matches(".tmp");let final_path = self.base_path.join(final_name);- let file_size = metadata.len();+ let file_size = metadata.file_size;match std::fs::rename(&path, &final_path) {Ok(()) => {@@ -564,12 +429,7 @@ impl DashAudioSegmentEncoder {}}- fn collect_orphaned_segments(- &mut self,- segment_start: Option<Duration>,- end_timestamp: Duration,- frames_before_flush: u32,- ) {+ fn collect_orphaned_segments(&mut self) {let completed_indices: std::collections::HashSet<u32> =self.completed_segments.iter().map(|s| s.index).collect();@@ -598,53 +458,29 @@ impl DashAudioSegmentEncoder {orphaned.sort_by_key(|(idx, _)| *idx);for (index, segment_path) in orphaned {- if let Ok(metadata) = std::fs::metadata(&segment_path) {- let file_size = metadata.len();-- if file_size < 100 {- tracing::debug!(- "Skipping tiny unlisted audio segment {} ({} bytes)",- segment_path.display(),- file_size- );+ let metadata = match read_fragment_metadata(&segment_path) {+ Ok(metadata) => metadata,+ Err(error) => {+ tracing::warn!(index, %error, "Cannot finalize invalid segment media");continue;}-- sync_file(&segment_path);-- let duration = if index == self.current_index && frames_before_flush > 0 {- if let Some(start) = segment_start {- end_timestamp.saturating_sub(start)- } else {- self.segment_duration- }- } else {- self.segment_duration- };-- tracing::info!(- "Finalized unlisted audio segment {} with {} bytes, estimated duration {:?}",- segment_path.display(),- file_size,- duration- );-- self.completed_segments.push(AudioSegmentInfo {- path: segment_path.clone(),- index,- duration,- file_size: Some(file_size),- });-- self.notify_segment(SegmentCompletedEvent {- path: segment_path,- index,- duration: duration.as_secs_f64(),- file_size,- is_init: false,- media_type: SegmentMediaType::Audio,- });- }+ };+ let duration = self.presentation_duration(index, metadata.duration);+ sync_file(&segment_path);+ self.completed_segments.push(AudioSegmentInfo {+ path: segment_path.clone(),+ index,+ duration,+ file_size: Some(metadata.file_size),+ });+ self.notify_segment(SegmentCompletedEvent {+ path: segment_path,+ index,+ duration: duration.as_secs_f64(),+ file_size: metadata.file_size,+ is_init: false,+ media_type: SegmentMediaType::Audio,+ });}self.completed_segments.sort_by_key(|s| s.index);@@ -732,6 +568,76 @@ mod tests {frame}+ #[test]+ fn audio_manifest_and_events_match_muxer_timeline() {+ ffmpeg::init().unwrap();+ let temp = tempfile::tempdir().unwrap();+ let base_path = temp.path().to_path_buf();+ let mut encoder = DashAudioSegmentEncoder::init(+ base_path.clone(),+ test_audio_info(),+ DashAudioSegmentEncoderConfig {+ segment_duration: Duration::from_secs(1),+ },+ )+ .unwrap();+ let (tx, rx) = mpsc::channel();+ encoder.set_segment_callback(tx);+ let mut events = Vec::new();+ for i in 0..117 {+ encoder+ .queue_frame(+ create_test_audio_frame(1024, i * 1024),+ Duration::from_secs_f64((i * 1024) as f64 / 48_000.0),+ )+ .unwrap();+ for event in rx.try_iter().filter(|event| !event.is_init) {+ assert_eq!(event.path.extension().unwrap(), "m4s");+ assert_eq!(+ event.file_size,+ std::fs::metadata(&event.path).unwrap().len()+ );+ events.push(event);+ }+ }+ encoder+ .finish_with_timestamp(Duration::from_secs(9))+ .unwrap();+ events.extend(rx.try_iter().filter(|event| !event.is_init));+ let manifest: serde_json::Value =+ serde_json::from_slice(&std::fs::read(base_path.join("manifest.json")).unwrap())+ .unwrap();+ let segments = manifest["segments"].as_array().unwrap();+ let mpd = std::fs::read_to_string(base_path.join("dash_manifest.mpd")).unwrap();+ let attribute = |text: &str, key: &str| -> Option<u64> {+ text.split_once(&format!("{key}=\""))?+ .1+ .split('"')+ .next()?+ .parse()+ .ok()+ };+ let timescale = attribute(&mpd, "timescale").unwrap() as f64;+ let mut durations = Vec::new();+ for line in mpd+ .lines()+ .map(str::trim)+ .filter(|line| line.starts_with("<S "))+ {+ let duration = attribute(line, "d").unwrap() as f64 / timescale;+ let repeat_count = attribute(line, "r").unwrap_or(0);+ durations.extend(std::iter::repeat_n(duration, repeat_count as usize + 1));+ }+ assert_eq!(events.len(), segments.len());+ assert_eq!(events.len(), durations.len());+ assert!(events.len() >= 3);+ for (event, (segment, duration)) in events.iter().zip(segments.iter().zip(durations)) {+ assert!((event.duration - duration).abs() < 1e-6);+ assert!((segment["duration"].as_f64().unwrap() - duration).abs() < 1e-6);+ }+ assert!((manifest["total_duration"].as_f64().unwrap() - 2.496).abs() < 1e-6);+ }+#[test]fn dash_audio_encoder_creates_init_segment() {ffmpeg::init().ok();diff --git a/crates/enc-ffmpeg/src/mux/fragment_manifest.rs b/crates/enc-ffmpeg/src/mux/fragment_manifest.rsindex d5b0f8e9d..e78951ffe 100644--- a/crates/enc-ffmpeg/src/mux/fragment_manifest.rs+++ b/crates/enc-ffmpeg/src/mux/fragment_manifest.rs@@ -1,3 +1,4 @@+use super::fragment_metadata::read_fragment_metadata;use cap_media_info::VideoInfo;use serde::Serialize;use std::{@@ -11,7 +12,6 @@ use crate::mux::segmented_stream::{SegmentCompletedEvent, SegmentMediaType, Videconst INIT_SEGMENT_NAME: &str = "init.mp4";const MANIFEST_VERSION: u32 = 5;const MANIFEST_TYPE: &str = "m4s_segments";-const PENDING_FLUSH_INTERVAL: u32 = 10;fn atomic_write_json<T: Serialize>(path: &Path, data: &T) -> std::io::Result<()> {let temp_path = path.with_extension("json.tmp");@@ -85,12 +85,8 @@ pub struct FragmentManifestTracker {base_path: PathBuf,segment_duration: Duration,current_index: u32,- segment_start_time: Option<Duration>,- last_frame_timestamp: Option<Duration>,- frames_in_segment: u32,completed_segments: Vec<VideoSegmentInfo>,- pending_segment_indices: Vec<(u32, Duration)>,- frames_since_pending_flush: u32,+ frames_since_segment_scan: u32,codec_info: CodecInfo,segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,init_notified: bool,@@ -111,12 +107,8 @@ impl FragmentManifestTracker {base_path,segment_duration,current_index: 1,- segment_start_time: None,- last_frame_timestamp: None,- frames_in_segment: 0,completed_segments: Vec::new(),- pending_segment_indices: Vec::new(),- frames_since_pending_flush: 0,+ frames_since_segment_scan: 0,codec_info,segment_tx: None,init_notified: false,@@ -152,34 +144,13 @@ impl FragmentManifestTracker {self.write_in_progress_manifest();}- pub fn on_frame(&mut self, timestamp: Duration) {- let is_first_frame = self.segment_start_time.is_none();- let segment_start = match self.segment_start_time {- Some(start) => start,- None => {- self.segment_start_time = Some(timestamp);- timestamp- }- };-- self.last_frame_timestamp = Some(timestamp);- self.frames_in_segment += 1;-- if is_first_frame {- self.try_notify_init_segment();- }-- if !self.pending_segment_indices.is_empty() {- self.frames_since_pending_flush += 1;- if self.frames_since_pending_flush >= PENDING_FLUSH_INTERVAL {- self.frames_since_pending_flush = 0;- self.flush_pending_segments();- }- }+ pub fn on_frame(&mut self, _timestamp: Duration) {+ self.try_notify_init_segment();- let elapsed_in_segment = timestamp.saturating_sub(segment_start);- if elapsed_in_segment >= self.segment_duration {- self.on_segment_boundary(self.current_index, timestamp);+ self.frames_since_segment_scan += 1;+ if self.frames_since_segment_scan >= 10 {+ self.frames_since_segment_scan = 0;+ self.flush_pending_segments();}}@@ -211,139 +182,39 @@ impl FragmentManifestTracker {}}- fn on_segment_boundary(&mut self, completed_index: u32, timestamp: Duration) {- self.try_notify_init_segment();-- let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);- let segment_duration = timestamp.saturating_sub(segment_start);-- let segment_path = self- .base_path- .join(format!("segment_{completed_index:03}.m4s"));-- tracing::debug!(- segment_index = completed_index,- duration_secs = segment_duration.as_secs_f64(),- frames = self.frames_in_segment,- "Fragment manifest boundary reached (time-based)"- );-- self.current_index = completed_index + 1;- self.segment_start_time = Some(timestamp);- self.frames_in_segment = 0;-- let tmp_path = self- .base_path- .join(format!("segment_{completed_index:03}.m4s.tmp"));-- let (resolved_path, file_size) = if segment_path.exists() {- let size = std::fs::metadata(&segment_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (segment_path.clone(), size)- } else if tmp_path.exists() {- let size = std::fs::metadata(&tmp_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (tmp_path, size)- } else {- (segment_path.clone(), 0)- };-- if resolved_path.exists() && file_size > 0 {- self.completed_segments.push(VideoSegmentInfo {- path: segment_path.clone(),- index: completed_index,- duration: segment_duration,- file_size: Some(file_size),- });-- self.write_in_progress_manifest();-- self.notify_segment(SegmentCompletedEvent {- path: resolved_path,- index: completed_index,- duration: segment_duration.as_secs_f64(),- file_size,- is_init: false,- media_type: SegmentMediaType::Video,- });- } else {- tracing::debug!(- segment_index = completed_index,- file_size,- "Segment file not ready yet, deferring notification"- );- self.pending_segment_indices- .push((completed_index, segment_duration));- self.write_in_progress_manifest();- }- }-pub fn flush_pending_segments(&mut self) {- if self.pending_segment_indices.is_empty() {- return;- }-- let taken = std::mem::take(&mut self.pending_segment_indices);- let taken_len = taken.len();- let mut still_pending = Vec::new();-- for (index, duration) in taken {+ let first_index = self.current_index;+ loop {+ let index = self.current_index;let segment_path = self.base_path.join(format!("segment_{index:03}.m4s"));- let tmp_path = self.base_path.join(format!("segment_{index:03}.m4s.tmp"));-- let (resolved_path, file_size) = if segment_path.exists() {- let size = std::fs::metadata(&segment_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (segment_path.clone(), size)- } else if tmp_path.exists() {- let size = std::fs::metadata(&tmp_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (tmp_path, size)- } else {- still_pending.push((index, duration));- continue;+ let metadata = match read_fragment_metadata(&segment_path) {+ Ok(metadata) => metadata,+ Err(error) => {+ if error.kind() != std::io::ErrorKind::NotFound {+ tracing::debug!(index, %error, "Waiting for finalized segment media");+ }+ break;+ }};- if file_size == 0 {- still_pending.push((index, duration));- continue;- }-- tracing::debug!(- segment_index = index,- file_size,- "Flushing previously pending segment"- );-self.completed_segments.push(VideoSegmentInfo {- path: segment_path,+ path: segment_path.clone(),index,- duration,- file_size: Some(file_size),+ duration: metadata.duration,+ file_size: Some(metadata.file_size),});-self.notify_segment(SegmentCompletedEvent {- path: resolved_path,+ path: segment_path,index,- duration: duration.as_secs_f64(),- file_size,+ duration: metadata.duration.as_secs_f64(),+ file_size: metadata.file_size,is_init: false,media_type: SegmentMediaType::Video,});+ self.current_index += 1;}- let flushed_any = still_pending.len() < taken_len;- self.pending_segment_indices = still_pending;-- if flushed_any {+ if self.current_index != first_index {self.write_in_progress_manifest();}}@@ -403,17 +274,11 @@ impl FragmentManifestTracker {}}- pub fn finalize(&mut self, end_timestamp: Duration) {- let segment_start = self.segment_start_time;- let frames_before_flush = self.frames_in_segment;- let effective_end_timestamp = self- .last_frame_timestamp- .map(|last| last.max(end_timestamp))- .unwrap_or(end_timestamp);-+ pub fn finalize(&mut self, _end_timestamp: Duration) {+ self.try_notify_init_segment();self.finalize_pending_tmp_files();self.flush_pending_segments();- self.collect_orphaned_segments(segment_start, effective_end_timestamp, frames_before_flush);+ self.collect_orphaned_segments();self.finalize_manifest();}@@ -427,12 +292,11 @@ impl FragmentManifestTracker {if let Some(name) = path.file_name().and_then(|n| n.to_str())&& name.starts_with("segment_")&& name.ends_with(".m4s.tmp")- && let Ok(metadata) = std::fs::metadata(&path)- && metadata.len() > 0+ && let Ok(metadata) = read_fragment_metadata(&path){let final_name = name.trim_end_matches(".tmp");let final_path = self.base_path.join(final_name);- let file_size = metadata.len();+ let file_size = metadata.file_size;let rename_result = Self::rename_with_retry(&path, &final_path);match rename_result {@@ -489,12 +353,7 @@ impl FragmentManifestTracker {std::fs::rename(from, to)}- fn collect_orphaned_segments(- &mut self,- segment_start: Option<Duration>,- end_timestamp: Duration,- frames_before_flush: u32,- ) {+ fn collect_orphaned_segments(&mut self) {let completed_indices: std::collections::HashSet<u32> =self.completed_segments.iter().map(|s| s.index).collect();@@ -523,52 +382,28 @@ impl FragmentManifestTracker {orphaned.sort_by_key(|(idx, _)| *idx);for (index, segment_path) in orphaned {- if let Ok(metadata) = std::fs::metadata(&segment_path) {- let file_size = metadata.len();- if file_size < 100 {- tracing::debug!(- "Skipping tiny unlisted segment {} ({} bytes)",- segment_path.display(),- file_size- );+ let metadata = match read_fragment_metadata(&segment_path) {+ Ok(metadata) => metadata,+ Err(error) => {+ tracing::warn!(index, %error, "Cannot finalize invalid segment media");continue;}-- sync_file(&segment_path);-- let duration = if index == self.current_index && frames_before_flush > 0 {- if let Some(start) = segment_start {- end_timestamp.saturating_sub(start)- } else {- self.segment_duration- }- } else {- self.segment_duration- };-- tracing::info!(- "Finalized unlisted segment {} with {} bytes, estimated duration {:?}",- segment_path.display(),- file_size,- duration- );-- self.completed_segments.push(VideoSegmentInfo {- path: segment_path.clone(),- index,- duration,- file_size: Some(file_size),- });-- self.notify_segment(SegmentCompletedEvent {- path: segment_path,- index,- duration: duration.as_secs_f64(),- file_size,- is_init: false,- media_type: SegmentMediaType::Video,- });- }+ };+ sync_file(&segment_path);+ self.completed_segments.push(VideoSegmentInfo {+ path: segment_path.clone(),+ index,+ duration: metadata.duration,+ file_size: Some(metadata.file_size),+ });+ self.notify_segment(SegmentCompletedEvent {+ path: segment_path,+ index,+ duration: metadata.duration.as_secs_f64(),+ file_size: metadata.file_size,+ is_init: false,+ media_type: SegmentMediaType::Video,+ });}self.completed_segments.sort_by_key(|s| s.index);@@ -671,7 +506,7 @@ mod tests {}#[test]- fn tracker_advances_segments_on_boundary() {+ fn tracker_does_not_invent_segments_from_capture_timestamps() {let temp = tempfile::tempdir().unwrap();let base = temp.path().to_path_buf();@@ -686,9 +521,66 @@ mod tests {tracker.on_frame(Duration::from_millis(i * 15));}- assert!(- tracker.current_index() >= 2,- "expected at least one boundary crossed"- );+ assert_eq!(tracker.current_index(), 1);+ }++ #[test]+ fn tracker_waits_for_finalized_files_and_uses_media_duration() {+ let temp = tempfile::tempdir().unwrap();+ let base = temp.path().to_path_buf();+ let mut tracker =+ FragmentManifestTracker::new(base.clone(), &test_video_info(), Duration::from_secs(2));+ let (tx, rx) = std::sync::mpsc::channel();+ tracker.set_segment_callback(tx);+ let bytes = crate::mux::fragment_metadata::tests::fragment(1, 90_000, &[360_070]);+ let temporary = base.join("segment_001.m4s.tmp");+ let finalized = base.join("segment_001.m4s");+ std::fs::write(&temporary, &bytes).unwrap();++ tracker.on_frame(Duration::ZERO);+ tracker.on_frame(Duration::from_secs(2));+ for i in 1..=20 {+ tracker.on_frame(Duration::from_millis(2000 + i * 33));+ }+ assert!(rx.try_recv().is_err());+ assert!(tracker.completed_segments().is_empty());++ std::fs::rename(&temporary, &finalized).unwrap();+ for i in 21..=30 {+ tracker.on_frame(Duration::from_millis(2000 + i * 33));+ }+ let event = rx.try_recv().unwrap();+ assert_eq!(event.path, finalized);+ assert_eq!(event.file_size, bytes.len() as u64);+ assert!((event.duration - 4.000_777_777).abs() < 1e-9);++ tracker.finalize(Duration::from_secs(3));+ assert!(rx.try_recv().is_err());+ let manifest: serde_json::Value =+ serde_json::from_slice(&std::fs::read(base.join("manifest.json")).unwrap()).unwrap();+ assert_eq!(manifest["segments"][0]["duration"], event.duration);+ assert_eq!(manifest["total_duration"], event.duration);+ }++ #[test]+ fn tracker_finalizes_actual_tail_without_publishing_truncated_files() {+ let temp = tempfile::tempdir().unwrap();+ let base = temp.path().to_path_buf();+ let mut tracker =+ FragmentManifestTracker::new(base.clone(), &test_video_info(), Duration::from_secs(2));+ let (tx, rx) = std::sync::mpsc::channel();+ tracker.set_segment_callback(tx);+ tracker.on_frame(Duration::ZERO);+ let bytes = crate::mux::fragment_metadata::tests::fragment(1, 90_000, &[155_815]);+ std::fs::write(base.join("segment_001.m4s.tmp"), &bytes).unwrap();+ std::fs::write(base.join("segment_002.m4s.tmp"), &bytes[..80]).unwrap();+ tracker.finalize(Duration::from_secs(10));++ let events: Vec<_> = rx.try_iter().collect();+ assert_eq!(events.len(), 1);+ assert_eq!(events[0].index, 1);+ assert!((events[0].duration - 1.731_277_777).abs() < 1e-9);+ assert!(!base.join("segment_002.m4s").exists());+ assert_eq!(tracker.completed_segments().len(), 1);}}diff --git a/crates/enc-ffmpeg/src/mux/fragment_metadata.rs b/crates/enc-ffmpeg/src/mux/fragment_metadata.rsnew file mode 100644index 000000000..d9b3159a2--- /dev/null+++ b/crates/enc-ffmpeg/src/mux/fragment_metadata.rs@@ -0,0 +1,219 @@+use std::{+ fs::File,+ io::{self, Read, Seek, SeekFrom},+ path::Path,+ time::Duration,+};++pub(super) struct FragmentMetadata {+ pub duration: Duration,+ pub file_size: u64,+}++pub(super) fn read_fragment_metadata(path: &Path) -> io::Result<FragmentMetadata> {+ let mut file = File::open(path)?;+ let file_size = file.metadata()?.len();+ read_metadata(&mut file, file_size)+}++fn invalid_fragment(message: &'static str) -> io::Error {+ io::Error::new(io::ErrorKind::InvalidData, message)+}++fn read_u32(reader: &mut impl Read) -> io::Result<u32> {+ let mut bytes = [0; 4];+ reader.read_exact(&mut bytes)?;+ Ok(u32::from_be_bytes(bytes))+}++fn read_u64(reader: &mut impl Read) -> io::Result<u64> {+ let mut bytes = [0; 8];+ reader.read_exact(&mut bytes)?;+ Ok(u64::from_be_bytes(bytes))+}++fn read_metadata(reader: &mut (impl Read + Seek), file_size: u64) -> io::Result<FragmentMetadata> {+ let mut offset = 0;+ let mut duration = None;+ let mut has_movie_fragment = false;+ let mut has_media_data = false;++ while offset < file_size {+ if file_size - offset < 8 {+ return Err(invalid_fragment("Truncated fragment box header"));+ }++ reader.seek(SeekFrom::Start(offset))?;+ let size = read_u32(reader)?;+ let mut kind = [0; 4];+ reader.read_exact(&mut kind)?;+ let (size, header_size) = match size {+ 0 => (file_size - offset, 8),+ 1 => (read_u64(reader)?, 16),+ size => (u64::from(size), 8),+ };+ if size < header_size || size > file_size - offset {+ return Err(invalid_fragment("Invalid fragment box size"));+ }++ if kind == *b"sidx" {+ if duration.is_some() {+ return Err(invalid_fragment("Multiple segment indexes in one fragment"));+ }+ // DASH cuts at encoded keyframes, which can differ from capture-time boundaries.+ let (indexed_duration, referenced_bytes) =+ read_segment_index(&mut (&mut *reader).take(size - header_size))?;+ if referenced_bytes > file_size - offset - size {+ return Err(invalid_fragment(+ "Segment index references incomplete media",+ ));+ }+ duration = Some(indexed_duration);+ } else if kind == *b"moof" {+ has_movie_fragment = true;+ } else if kind == *b"mdat" {+ has_media_data = size > header_size;+ }++ offset += size;+ }++ if !has_movie_fragment || !has_media_data {+ return Err(invalid_fragment("Fragment media is missing"));+ }++ Ok(FragmentMetadata {+ duration: duration.ok_or_else(|| invalid_fragment("Fragment segment index is missing"))?,+ file_size,+ })+}++fn read_segment_index(reader: &mut impl Read) -> io::Result<(Duration, u64)> {+ let version = read_u32(reader)? >> 24;+ let _reference_id = read_u32(reader)?;+ let timescale = u64::from(read_u32(reader)?);+ if timescale == 0 {+ return Err(invalid_fragment("Segment index timescale is zero"));+ }++ let mut referenced_bytes = match version {+ 0 => {+ let _earliest_presentation_time = read_u32(reader)?;+ u64::from(read_u32(reader)?)+ }+ 1 => {+ let _earliest_presentation_time = read_u64(reader)?;+ read_u64(reader)?+ }+ _ => return Err(invalid_fragment("Unsupported segment index version")),+ };+ let reference_count = read_u32(reader)? & 0xffff;+ let mut duration_ticks = 0_u64;+ for _ in 0..reference_count {+ let reference = read_u32(reader)?;+ if reference & 0x8000_0000 != 0 {+ return Err(invalid_fragment("Nested segment index is unsupported"));+ }+ referenced_bytes = referenced_bytes+ .checked_add(u64::from(reference))+ .ok_or_else(|| invalid_fragment("Segment index size overflow"))?;+ duration_ticks += u64::from(read_u32(reader)?);+ let _access_point = read_u32(reader)?;+ }+ if duration_ticks == 0 {+ return Err(invalid_fragment("Segment index duration is zero"));+ }++ let duration = Duration::new(+ duration_ticks / timescale,+ ((duration_ticks % timescale) * 1_000_000_000 / timescale) as u32,+ );+ Ok((duration, referenced_bytes))+}++#[cfg(test)]+pub(super) mod tests {+ use super::*;+ use std::io::Cursor;++ fn mp4_box(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {+ let mut bytes = ((payload.len() + 8) as u32).to_be_bytes().to_vec();+ bytes.extend(kind);+ bytes.extend(payload);+ bytes+ }++ pub(crate) fn fragment(version: u8, timescale: u32, durations: &[u32]) -> Vec<u8> {+ let mut payload = (u32::from(version) << 24).to_be_bytes().to_vec();+ payload.extend(1_u32.to_be_bytes());+ payload.extend(timescale.to_be_bytes());+ payload.extend(vec![0; if version == 0 { 8 } else { 16 }]);+ payload.extend((durations.len() as u32).to_be_bytes());+ for duration in durations {+ payload.extend(32_u32.to_be_bytes());+ payload.extend(duration.to_be_bytes());+ payload.extend(0x8000_0000_u32.to_be_bytes());+ }+ let mut bytes = mp4_box(b"styp", &[0; 16]);+ bytes.extend(mp4_box(b"sidx", &payload));+ for _ in durations {+ bytes.extend(mp4_box(b"moof", &[0; 8]));+ bytes.extend(mp4_box(b"mdat", &[0; 8]));+ }+ bytes+ }++ fn parse(bytes: &[u8]) -> io::Result<FragmentMetadata> {+ read_metadata(&mut Cursor::new(bytes), bytes.len() as u64)+ }++ #[test]+ fn reads_both_segment_index_versions_and_multiple_references() {+ for version in [0, 1] {+ let bytes = fragment(version, 90_000, &[180_000, 360_070]);+ let metadata = parse(&bytes).unwrap();+ assert_eq!(metadata.file_size, bytes.len() as u64);+ assert_eq!(metadata.duration, Duration::new(6, 777_777));+ }+ }++ #[test]+ fn reads_audio_timescale_without_rounding_to_segment_target() {+ let bytes = fragment(1, 48_000, &[97_280]);+ assert_eq!(+ parse(&bytes).unwrap().duration,+ Duration::new(2, 26_666_666)+ );+ }++ #[test]+ fn skips_extended_size_boxes() {+ let mut bytes = 1_u32.to_be_bytes().to_vec();+ bytes.extend(b"free");+ bytes.extend(24_u64.to_be_bytes());+ bytes.extend([0; 8]);+ bytes.extend(fragment(1, 30, &[60]));+ assert_eq!(parse(&bytes).unwrap().duration, Duration::from_secs(2));+ }++ #[test]+ fn rejects_truncated_media_even_when_segment_index_is_complete() {+ let bytes = fragment(1, 30, &[60]);+ for length in 0..bytes.len() {+ assert!(parse(&bytes[..length]).is_err(), "length {length}");+ }+ }++ #[test]+ fn rejects_invalid_segment_indexes() {+ for bytes in [+ fragment(2, 30, &[60]),+ fragment(1, 0, &[60]),+ fragment(1, 30, &[0]),+ fragment(1, 30, &[]),+ mp4_box(b"mdat", &[0; 32]),+ ] {+ assert!(parse(&bytes).is_err());+ }+ }+}diff --git a/crates/enc-ffmpeg/src/mux/fragmented_audio.rs b/crates/enc-ffmpeg/src/mux/fragmented_audio.rsindex 5e1639f33..1203ad72c 100644--- a/crates/enc-ffmpeg/src/mux/fragmented_audio.rs+++ b/crates/enc-ffmpeg/src/mux/fragmented_audio.rs@@ -29,6 +29,40 @@ pub enum FinishError {WriteTrailerFailed(ffmpeg::Error),}+fn option_result(value: i32) -> Result<(), ffmpeg::Error> {+ if value < 0 {+ Err(ffmpeg::Error::from(value))+ } else {+ Ok(())+ }+}++fn configure_fragmentation(output: &mut format::context::Output) -> Result<(), ffmpeg::Error> {+ // Audio-only streams cannot trigger frag_keyframe. Fragment cuts and AVIO+ // flushes are separate requirements for exposing bytes before finalization.+ unsafe {+ let context = output.as_mut_ptr();+ option_result(ffmpeg::ffi::av_opt_set(+ (*context).priv_data,+ c"movflags".as_ptr(),+ c"frag_keyframe+empty_moov+default_base_moof+skip_trailer".as_ptr(),+ 0,+ ))?;+ option_result(ffmpeg::ffi::av_opt_set_int(+ (*context).priv_data,+ c"frag_duration".as_ptr(),+ 2_000_000,+ 0,+ ))?;+ option_result(ffmpeg::ffi::av_opt_set_int(+ context.cast(),+ c"flush_packets".as_ptr(),+ 1,+ 0,+ ))+ }+}+impl FragmentedAudioFile {pub fn init(mut output_path: PathBuf, audio_config: AudioInfo) -> Result<Self, InitError> {output_path.set_extension("m4a");@@ -39,14 +73,7 @@ impl FragmentedAudioFile {let mut output = format::output_as(&output_path, "mp4")?;- unsafe {- let opts = output.as_mut_ptr();- let key = std::ffi::CString::new("movflags").unwrap();- let value =- std::ffi::CString::new("frag_keyframe+empty_moov+default_base_moof+skip_trailer")- .unwrap();- ffmpeg::ffi::av_opt_set((*opts).priv_data, key.as_ptr(), value.as_ptr(), 0);- }+ configure_fragmentation(&mut output)?;let encoder = AACEncoder::init(audio_config, &mut output)?;@@ -87,27 +114,213 @@ impl FragmentedAudioFile {self.finished = true;- if self.has_frames {- if let Err(flush_err) = self.encoder.flush(&mut self.output) {- tracing::warn!(- "Audio encoder flush reported a non-fatal error (fragments on disk are valid): {flush_err}"- );- }- if let Err(trailer_err) = self.output.write_trailer() {- tracing::warn!(- "Audio fragmented MP4 write_trailer reported a non-fatal error (fragments on disk are valid, file remains playable): {trailer_err}"- );- }- Ok(Ok(()))+ let flush_result = if self.has_frames {+ self.encoder.flush(&mut self.output)} else {- let _ = self.output.write_trailer();- Ok(Ok(()))- }+ Ok(())+ };+ let trailer_result = self.output.write_trailer();+ finish_result(flush_result, trailer_result)}}+fn finish_result(+ flush_result: Result<(), ffmpeg::Error>,+ trailer_result: Result<(), ffmpeg::Error>,+) -> Result<Result<(), ffmpeg::Error>, FinishError> {+ trailer_result.map_err(FinishError::WriteTrailerFailed)?;+ Ok(flush_result)+}+impl Drop for FragmentedAudioFile {fn drop(&mut self) {let _ = self.finish_with_timestamp(Duration::ZERO);}}++#[cfg(test)]+mod publication_tests {+ use super::*;+ use ffmpeg::{ChannelLayout, format::Sample, format::sample::Type};+ use std::ffi::CStr;++ fn value(output: &mut format::context::Output, name: &CStr, private: bool) -> i64 {+ unsafe {+ let context = output.as_mut_ptr();+ let target = if private {+ (*context).priv_data+ } else {+ context.cast()+ };+ let mut result = 0;+ assert_eq!(+ ffmpeg::ffi::av_opt_get_int(target, name.as_ptr(), 0, &mut result),+ 0+ );+ result+ }+ }++ fn queue_tone(output: &mut FragmentedAudioFile, blocks: i64) {+ for block in 0..blocks {+ let mut frame =+ ffmpeg::frame::Audio::new(Sample::F32(Type::Packed), 1024, ChannelLayout::MONO);+ frame.set_rate(48_000);+ for (index, value) in frame.data_mut(0)[..1024 * 4]+ .chunks_exact_mut(4)+ .enumerate()+ {+ let position = (block * 1024) as f32 + index as f32;+ let sample = 0.125 * (position * 880.0 * std::f32::consts::TAU / 48_000.0).sin();+ value.copy_from_slice(&sample.to_ne_bytes());+ }+ output+ .queue_frame(+ frame,+ Duration::from_secs_f64(block as f64 * 1024.0 / 48_000.0),+ )+ .unwrap();+ }+ }++ #[test]+ fn fragmented_audio_sets_both_publication_options() {+ let directory = tempfile::tempdir().unwrap();+ let mut output = format::output_as(&directory.path().join("options.m4a"), "mp4").unwrap();+ configure_fragmentation(&mut output).unwrap();+ assert_eq!(value(&mut output, c"frag_duration", true), 2_000_000);+ assert_eq!(value(&mut output, c"flush_packets", false), 1);+ assert_ne!(value(&mut output, c"movflags", true), 0);+ }++ #[test]+ fn fragmented_audio_rejects_unsupported_mux_options() {+ let directory = tempfile::tempdir().unwrap();+ let mut output = format::output_as(&directory.path().join("wrong.ogg"), "ogg").unwrap();+ assert!(configure_fragmentation(&mut output).is_err());+ }++ #[test]+ fn fragmented_audio_option_errors_are_not_ignored() {+ assert!(option_result(0).is_ok());+ assert!(option_result(-22).is_err());+ assert!(option_result(ffmpeg::ffi::AVERROR_OPTION_NOT_FOUND).is_err());+ }++ #[test]+ fn fragmented_audio_exposes_packets_before_finish() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("before-finish.m4a");+ let info = AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 1);+ let mut output = FragmentedAudioFile::init(path.clone(), info).unwrap();+ queue_tone(&mut output, 120);+ let mut input = format::input(&path).unwrap();+ assert!(input.packets().next().is_some());+ drop(input);+ output.finish().unwrap().unwrap();+ }++ #[test]+ fn short_fragmented_audio_remains_readable_after_finish() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("short.m4a");+ let info = AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 1);+ let mut output = FragmentedAudioFile::init(path.clone(), info).unwrap();+ queue_tone(&mut output, 10);+ output.finish().unwrap().unwrap();+ let mut input = format::input(&path).unwrap();+ assert!(input.packets().next().is_some());+ }++ #[test]+ fn fragmented_audio_terminal_success_requires_both_stages() {+ assert!(matches!(finish_result(Ok(()), Ok(())), Ok(Ok(()))));+ }++ #[test]+ fn fragmented_audio_preserves_encoder_flush_failure() {+ assert!(matches!(+ finish_result(Err(ffmpeg::Error::InvalidData), Ok(())),+ Ok(Err(ffmpeg::Error::InvalidData))+ ));+ }++ #[test]+ fn fragmented_audio_reports_trailer_failure() {+ assert!(matches!(+ finish_result(Ok(()), Err(ffmpeg::Error::InvalidData)),+ Err(FinishError::WriteTrailerFailed(ffmpeg::Error::InvalidData))+ ));+ }++ #[test]+ fn fragmented_audio_reports_trailer_failure_after_failed_flush() {+ assert!(matches!(+ finish_result(Err(ffmpeg::Error::InvalidData), Err(ffmpeg::Error::Bug)),+ Err(FinishError::WriteTrailerFailed(ffmpeg::Error::Bug))+ ));+ }++ #[test]+ fn fragmented_audio_does_not_assume_reported_eof_is_benign() {+ assert!(matches!(+ finish_result(Err(ffmpeg::Error::Eof), Ok(())),+ Ok(Err(ffmpeg::Error::Eof))+ ));+ assert!(matches!(+ finish_result(Ok(()), Err(ffmpeg::Error::Eof)),+ Err(FinishError::WriteTrailerFailed(ffmpeg::Error::Eof))+ ));+ }++ #[test]+ fn fragmented_audio_empty_track_without_io_error_can_finish() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("empty-finish.m4a");+ let info = AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 1);+ let mut output = FragmentedAudioFile::init(path, info).unwrap();+ output.finish().unwrap().unwrap();+ }++ fn set_output_error(output: &mut FragmentedAudioFile) {+ unsafe {+ let context = output.output.as_mut_ptr();+ assert!(!(*context).pb.is_null());+ (*(*context).pb).error = ffmpeg::Error::Other {+ errno: ffmpeg::error::EIO,+ }+ .into();+ }+ }++ #[test]+ fn fragmented_audio_sticky_io_error_cannot_report_terminal_success() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("failed-finish.m4a");+ let info = AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 1);+ let mut output = FragmentedAudioFile::init(path.clone(), info).unwrap();+ queue_tone(&mut output, 120);+ let prefix = std::fs::read(&path).unwrap();+ assert!(!prefix.is_empty());+ set_output_error(&mut output);+ assert!(!matches!(output.finish(), Ok(Ok(()))));+ assert!(matches!(output.finish(), Err(FinishError::AlreadyFinished)));+ drop(output);+ assert!(std::fs::read(&path).unwrap().starts_with(&prefix));+ }++ #[test]+ fn fragmented_audio_empty_track_trailer_error_is_reported() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("empty-failed-finish.m4a");+ let info = AudioInfo::new_raw(Sample::F32(Type::Packed), 48_000, 1);+ let mut output = FragmentedAudioFile::init(path.clone(), info).unwrap();+ set_output_error(&mut output);+ assert!(matches!(+ output.finish(),+ Err(FinishError::WriteTrailerFailed(_))+ ));+ drop(output);+ assert!(path.exists());+ }+}diff --git a/crates/enc-ffmpeg/src/mux/mod.rs b/crates/enc-ffmpeg/src/mux/mod.rsindex 962da146b..86d58a9c0 100644--- a/crates/enc-ffmpeg/src/mux/mod.rs+++ b/crates/enc-ffmpeg/src/mux/mod.rs@@ -1,5 +1,6 @@pub mod dash_audio;pub mod fragment_manifest;+mod fragment_metadata;pub mod fragmented_audio;pub mod fragmented_mp4;pub mod mov;diff --git a/crates/enc-ffmpeg/src/mux/segmented_stream.rs b/crates/enc-ffmpeg/src/mux/segmented_stream.rsindex 419544b54..b35aba5ca 100644--- a/crates/enc-ffmpeg/src/mux/segmented_stream.rs+++ b/crates/enc-ffmpeg/src/mux/segmented_stream.rs@@ -1,3 +1,4 @@+use super::fragment_metadata::read_fragment_metadata;use cap_media_info::VideoInfo;use ffmpeg::{format, frame};use serde::Serialize;@@ -81,14 +82,10 @@ pub struct SegmentedVideoEncoder {current_index: u32,segment_duration: Duration,- segment_start_time: Option<Duration>,- last_frame_timestamp: Option<Duration>,- frames_in_segment: u32,completed_segments: Vec<VideoSegmentInfo>,- pending_segment_indices: Vec<(u32, Duration)>,- frames_since_pending_flush: u32,+ frames_since_segment_scan: u32,codec_info: CodecInfo,@@ -304,12 +301,8 @@ impl SegmentedVideoEncoder {output,current_index: 1,segment_duration: config.segment_duration,- segment_start_time: None,- last_frame_timestamp: None,- frames_in_segment: 0,completed_segments: Vec::new(),- pending_segment_indices: Vec::new(),- frames_since_pending_flush: 0,+ frames_since_segment_scan: 0,codec_info,disk_space_callback: None,segment_tx: None,@@ -379,40 +372,22 @@ impl SegmentedVideoEncoder {frame: frame::Video,timestamp: Duration,) -> Result<(), QueueFrameError> {- let segment_start = match self.segment_start_time {- Some(start) => start,- None => {- self.segment_start_time = Some(timestamp);- timestamp- }- };-- self.last_frame_timestamp = Some(timestamp);-// Encode with the frame's real capture-derived timestamp. The encoder// anchors pts at the first frame, so capture gaps (static content,// stream restarts, dropped frames) stay in the timeline instead of// compressing it and drifting video ahead of audio.self.encoder.queue_frame(frame, timestamp, &mut self.output)?;- self.frames_in_segment += 1;// The encoder holds one packet back to stamp real durations, so the// init segment materializes a frame later than the first queue call;// keep trying until it lands (no-op once notified).self.try_notify_init_segment();- if !self.pending_segment_indices.is_empty() {- self.frames_since_pending_flush += 1;- if self.frames_since_pending_flush >= 10 {- self.frames_since_pending_flush = 0;- self.flush_pending_segments();- }- }-- let elapsed_in_segment = timestamp.saturating_sub(segment_start);- if elapsed_in_segment >= self.segment_duration {- self.on_segment_boundary(self.current_index, timestamp);+ self.frames_since_segment_scan += 1;+ if self.frames_since_segment_scan >= 10 {+ self.frames_since_segment_scan = 0;+ self.flush_pending_segments();}Ok(())@@ -426,142 +401,39 @@ impl SegmentedVideoEncoder {}}- fn on_segment_boundary(&mut self, completed_index: u32, timestamp: Duration) {- self.try_notify_init_segment();-- let segment_start = self.segment_start_time.unwrap_or(Duration::ZERO);- let segment_duration = timestamp.saturating_sub(segment_start);-- let segment_path = self- .base_path- .join(format!("segment_{completed_index:03}.m4s"));-- tracing::debug!(- segment_index = completed_index,- duration_secs = segment_duration.as_secs_f64(),- frames = self.frames_in_segment,- "Segment boundary reached (time-based)"- );-- self.current_index = completed_index + 1;- self.segment_start_time = Some(timestamp);- self.frames_in_segment = 0;-- let tmp_path = self- .base_path- .join(format!("segment_{completed_index:03}.m4s.tmp"));-- let (resolved_path, file_size) = if segment_path.exists() {- let size = std::fs::metadata(&segment_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (segment_path.clone(), size)- } else if tmp_path.exists() {- let size = std::fs::metadata(&tmp_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (tmp_path, size)- } else {- (segment_path.clone(), 0)- };-- let file_found = resolved_path.exists();-- if file_found && file_size > 0 {- self.completed_segments.push(VideoSegmentInfo {- path: segment_path.clone(),- index: completed_index,- duration: segment_duration,- file_size: Some(file_size),- });-- self.write_in_progress_manifest();-- self.notify_segment(SegmentCompletedEvent {- path: resolved_path,- index: completed_index,- duration: segment_duration.as_secs_f64(),- file_size,- is_init: false,- media_type: SegmentMediaType::Video,- });- } else {- tracing::debug!(- segment_index = completed_index,- file_exists = file_found,- file_size,- "Segment file not ready yet, deferring notification"- );- self.pending_segment_indices- .push((completed_index, segment_duration));- self.write_in_progress_manifest();- }- }-fn flush_pending_segments(&mut self) {- if self.pending_segment_indices.is_empty() {- return;- }-- let taken = std::mem::take(&mut self.pending_segment_indices);- let taken_len = taken.len();- let mut still_pending = Vec::new();-- for (index, duration) in taken {+ let first_index = self.current_index;+ loop {+ let index = self.current_index;let segment_path = self.base_path.join(format!("segment_{index:03}.m4s"));- let tmp_path = self.base_path.join(format!("segment_{index:03}.m4s.tmp"));-- let (resolved_path, file_size) = if segment_path.exists() {- let size = std::fs::metadata(&segment_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (segment_path.clone(), size)- } else if tmp_path.exists() {- let size = std::fs::metadata(&tmp_path)- .ok()- .map(|m| m.len())- .unwrap_or(0);- (tmp_path, size)- } else {- still_pending.push((index, duration));- continue;+ let metadata = match read_fragment_metadata(&segment_path) {+ Ok(metadata) => metadata,+ Err(error) => {+ if error.kind() != std::io::ErrorKind::NotFound {+ tracing::debug!(index, %error, "Waiting for finalized segment media");+ }+ break;+ }};- if file_size == 0 {- still_pending.push((index, duration));- continue;- }-- tracing::debug!(- segment_index = index,- file_size,- "Flushing previously pending segment"- );-self.completed_segments.push(VideoSegmentInfo {- path: segment_path,+ path: segment_path.clone(),index,- duration,- file_size: Some(file_size),+ duration: metadata.duration,+ file_size: Some(metadata.file_size),});-self.notify_segment(SegmentCompletedEvent {- path: resolved_path,+ path: segment_path,index,- duration: duration.as_secs_f64(),- file_size,+ duration: metadata.duration.as_secs_f64(),+ file_size: metadata.file_size,is_init: false,media_type: SegmentMediaType::Video,});+ self.current_index += 1;}- let flushed_any = still_pending.len() < taken_len;- self.pending_segment_indices = still_pending;-- if flushed_any {+ if self.current_index != first_index {self.write_in_progress_manifest();}}@@ -622,10 +494,6 @@ impl SegmentedVideoEncoder {}pub fn finish(&mut self) -> Result<(), FinishError> {- let segment_start = self.segment_start_time;- let last_timestamp = self.last_frame_timestamp;- let frames_before_flush = self.frames_in_segment;-if let Err(e) = self.encoder.flush(&mut self.output) {tracing::warn!("Video encoder flush warning: {e}");}@@ -638,41 +506,15 @@ impl SegmentedVideoEncoder {self.finalize_pending_tmp_files();self.flush_pending_segments();- let end_timestamp =- last_timestamp.unwrap_or_else(|| segment_start.unwrap_or(Duration::ZERO));- self.collect_orphaned_segments(segment_start, end_timestamp, frames_before_flush);+ self.collect_orphaned_segments();self.finalize_manifest();Ok(())}- pub fn finish_with_timestamp(&mut self, timestamp: Duration) -> Result<(), FinishError> {- let segment_start = self.segment_start_time;- let frames_before_flush = self.frames_in_segment;-- if let Err(e) = self.encoder.flush(&mut self.output) {- tracing::warn!("Video encoder flush warning: {e}");- }-- if let Err(e) = self.output.write_trailer() {- tracing::warn!("Video write_trailer warning: {e}");- }-- self.try_notify_init_segment();- self.finalize_pending_tmp_files();- self.flush_pending_segments();-- let effective_end_timestamp = self- .last_frame_timestamp- .map(|last| last.max(timestamp))- .unwrap_or(timestamp);-- self.collect_orphaned_segments(segment_start, effective_end_timestamp, frames_before_flush);-- self.finalize_manifest();-- Ok(())+ pub fn finish_with_timestamp(&mut self, _timestamp: Duration) -> Result<(), FinishError> {+ self.finish()}fn finalize_pending_tmp_files(&self) {@@ -685,12 +527,11 @@ impl SegmentedVideoEncoder {if let Some(name) = path.file_name().and_then(|n| n.to_str())&& name.starts_with("segment_")&& name.ends_with(".m4s.tmp")- && let Ok(metadata) = std::fs::metadata(&path)- && metadata.len() > 0+ && let Ok(metadata) = read_fragment_metadata(&path){let final_name = name.trim_end_matches(".tmp");let final_path = self.base_path.join(final_name);- let file_size = metadata.len();+ let file_size = metadata.file_size;let rename_result = Self::rename_with_retry(&path, &final_path);@@ -753,12 +594,7 @@ impl SegmentedVideoEncoder {std::fs::rename(from, to)}- fn collect_orphaned_segments(- &mut self,- segment_start: Option<Duration>,- end_timestamp: Duration,- frames_before_flush: u32,- ) {+ fn collect_orphaned_segments(&mut self) {let completed_indices: std::collections::HashSet<u32> =self.completed_segments.iter().map(|s| s.index).collect();@@ -787,53 +623,28 @@ impl SegmentedVideoEncoder {orphaned.sort_by_key(|(idx, _)| *idx);for (index, segment_path) in orphaned {- if let Ok(metadata) = std::fs::metadata(&segment_path) {- let file_size = metadata.len();-- if file_size < 100 {- tracing::debug!(- "Skipping tiny unlisted segment {} ({} bytes)",- segment_path.display(),- file_size- );+ let metadata = match read_fragment_metadata(&segment_path) {+ Ok(metadata) => metadata,+ Err(error) => {+ tracing::warn!(index, %error, "Cannot finalize invalid segment media");continue;}-- sync_file(&segment_path);-- let duration = if index == self.current_index && frames_before_flush > 0 {- if let Some(start) = segment_start {- end_timestamp.saturating_sub(start)- } else {- self.segment_duration- }- } else {- self.segment_duration- };-- tracing::info!(- "Finalized unlisted segment {} with {} bytes, estimated duration {:?}",- segment_path.display(),- file_size,- duration- );-- self.completed_segments.push(VideoSegmentInfo {- path: segment_path.clone(),- index,- duration,- file_size: Some(file_size),- });-- self.notify_segment(SegmentCompletedEvent {- path: segment_path,- index,- duration: duration.as_secs_f64(),- file_size,- is_init: false,- media_type: SegmentMediaType::Video,- });- }+ };+ sync_file(&segment_path);+ self.completed_segments.push(VideoSegmentInfo {+ path: segment_path.clone(),+ index,+ duration: metadata.duration,+ file_size: Some(metadata.file_size),+ });+ self.notify_segment(SegmentCompletedEvent {+ path: segment_path,+ index,+ duration: metadata.duration.as_secs_f64(),+ file_size: metadata.file_size,+ is_init: false,+ media_type: SegmentMediaType::Video,+ });}self.completed_segments.sort_by_key(|s| s.index);@@ -962,6 +773,69 @@ mod tests {frame}+ #[test]+ fn video_manifest_and_events_match_muxer_playlist() {+ ffmpeg::init().unwrap();+ let temp = tempfile::tempdir().unwrap();+ let base_path = temp.path().to_path_buf();+ let mut encoder = SegmentedVideoEncoder::init(+ base_path.clone(),+ test_video_info(),+ SegmentedVideoEncoderConfig::default(),+ )+ .unwrap();+ let (tx, rx) = mpsc::channel();+ encoder.set_segment_callback(tx);+ let mut snapshots = Vec::new();+ for i in 0..200 {+ encoder+ .queue_frame(+ create_test_frame(320, 240),+ Duration::from_micros(i * 33_320),+ )+ .unwrap();+ for event in rx.try_iter().filter(|event| !event.is_init) {+ assert_eq!(event.path.extension().unwrap(), "m4s");+ let bytes = std::fs::read(&event.path).unwrap();+ snapshots.push((event, bytes));+ }+ }+ encoder+ .finish_with_timestamp(Duration::from_secs(9))+ .unwrap();+ for event in rx.try_iter().filter(|event| !event.is_init) {+ let bytes = std::fs::read(&event.path).unwrap();+ snapshots.push((event, bytes));+ }++ let playlist = std::fs::read_to_string(base_path.join("media_0.m3u8")).unwrap();+ let durations: Vec<f64> = playlist+ .lines()+ .filter_map(|line| line.strip_prefix("#EXTINF:"))+ .map(|line| line.trim_end_matches(',').parse().unwrap())+ .collect();+ let manifest: serde_json::Value =+ serde_json::from_slice(&std::fs::read(base_path.join("manifest.json")).unwrap())+ .unwrap();+ let segments = manifest["segments"].as_array().unwrap();+ assert!(durations.len() >= 2);+ assert_eq!(snapshots.len(), durations.len());+ assert_eq!(segments.len(), durations.len());+ for ((event, bytes), (segment, duration)) in+ snapshots.iter().zip(segments.iter().zip(&durations))+ {+ assert_eq!(*bytes, std::fs::read(&event.path).unwrap());+ assert_eq!(event.file_size, bytes.len() as u64);+ assert_eq!(event.index, segment["index"].as_u64().unwrap() as u32);+ assert!((event.duration - duration).abs() <= 1e-6);+ assert!((segment["duration"].as_f64().unwrap() - duration).abs() <= 1e-6);+ }+ assert!(+ (manifest["total_duration"].as_f64().unwrap() - durations.iter().sum::<f64>()).abs()+ <= 1e-5+ );+ }+#[test]fn segment_callback_fires_for_init_segment() {ffmpeg::init().ok();diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rsindex fd2cb1abd..d02b48e81 100644--- a/crates/enc-ffmpeg/src/video/h264.rs+++ b/crates/enc-ffmpeg/src/video/h264.rs@@ -51,6 +51,8 @@ pub enum H264EncoderError {FFmpeg(#[from] ffmpeg::Error),#[error("Codec not found")]CodecNotFound,+ #[error("Failed to configure RGB conversion for BT.709 limited-range video: {0}")]+ ColorConversion(ffmpeg::Error),#[error("Pixel format {0:?} not supported")]PixFmtNotSupported(Pixel),#[error("Invalid output dimensions {width}x{height}; expected non-zero even width and height")]@@ -617,6 +619,44 @@ pub(crate) fn open_video_encoder_with_flags()}+fn is_rgb(format: format::Pixel) -> bool {+ format.descriptor().is_some_and(|descriptor| unsafe {+ (*descriptor.as_ptr()).flags & ffmpeg::ffi::AV_PIX_FMT_FLAG_RGB as u64 != 0+ })+}++fn configure_rgb_converter(+ converter: &mut ffmpeg::software::scaling::Context,+ input: format::Pixel,+ output: format::Pixel,+) -> Result<(), H264EncoderError> {+ if !is_rgb(input) || is_rgb(output) {+ return Ok(());+ }++ // swscale defaults to BT.601 even though the encoder declares BT.709.+ // RGB input is full range; the encoded YUV contract below is limited range.+ let result = unsafe {+ let coefficients = ffmpeg::ffi::sws_getCoefficients(ffmpeg::ffi::SWS_CS_ITU709);+ ffmpeg::ffi::sws_setColorspaceDetails(+ converter.as_mut_ptr(),+ coefficients,+ 1,+ coefficients,+ 0,+ 0,+ 1 << 16,+ 1 << 16,+ )+ };+ if result < 0 {+ return Err(H264EncoderError::ColorConversion(ffmpeg::Error::from(+ result,+ )));+ }+ Ok(())+}+#[allow(clippy::too_many_arguments)]fn open_video_encoder_inner(codec: Codec,@@ -699,7 +739,8 @@ fn open_video_encoder_inner(output_height,flags,) {- Ok(context) => {+ Ok(mut context) => {+ configure_rgb_converter(&mut context, input_config.pixel_format, output_format)?;debug!(encoder = %codec.name(),src_format = ?input_config.pixel_format,@@ -1720,3 +1761,309 @@ mod self_test_tests {.expect("real NVIDIA hardware preserves neutral gray through encode and decode");}}++#[cfg(test)]+mod rgb_color_tests {+ use super::*;++ const COLORS: [[u8; 3]; 6] = [+ [255, 0, 0],+ [0, 255, 0],+ [0, 0, 255],+ [0, 0, 0],+ [255, 255, 255],+ [128, 128, 128],+ ];++ fn open(input: format::Pixel, scale: u32, external: bool) -> OpenedVideoEncoder {+ ffmpeg::init().unwrap();+ let config = VideoInfo::from_raw_ffmpeg(input, 192, 64, 30);+ let mut options = Dictionary::new();+ options.set("preset", "ultrafast");+ options.set("tune", "zerolatency");+ options.set("crf", "18");+ open_video_encoder(+ encoder::find_by_name("libx264").expect("libx264 available"),+ options,+ &config,+ 192 / scale,+ 64 / scale,+ 0.3,+ external,+ Some(18),+ )+ .unwrap()+ }++ fn rgb_bars(format: format::Pixel) -> frame::Video {+ let mut frame = frame::Video::new(format, 192, 64);+ let stride = frame.stride(0);+ let channels = if format == format::Pixel::RGB24 { 3 } else { 4 };+ for y in 0..64 {+ for x in 0..192 {+ let [red, green, blue] = COLORS[x / 32];+ let offset = y * stride + x * channels;+ let bytes = frame.data_mut(0);+ match format {+ format::Pixel::RGB24 => {+ bytes[offset..offset + 3].copy_from_slice(&[red, green, blue]);+ }+ format::Pixel::RGBA => {+ bytes[offset..offset + 4].copy_from_slice(&[red, green, blue, 255]);+ }+ format::Pixel::BGRA | format::Pixel::BGRZ => {+ bytes[offset..offset + 4].copy_from_slice(&[blue, green, red, 255]);+ }+ _ => panic!("unexpected test RGB format"),+ }+ }+ }+ frame+ }++ fn receive_packets(encoder: &mut encoder::Video, packets: &mut Vec<ffmpeg::Packet>) {+ loop {+ let mut packet = ffmpeg::Packet::empty();+ match encoder.receive_packet(&mut packet) {+ Ok(()) => packets.push(packet),+ Err(ffmpeg::Error::Eof) => break,+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => break,+ Err(error) => panic!("receive encoded packet: {error}"),+ }+ }+ }++ fn receive_frames(decoder: &mut ffmpeg::decoder::Video, frames: &mut Vec<frame::Video>) {+ loop {+ let mut frame = frame::Video::empty();+ match decoder.receive_frame(&mut frame) {+ Ok(()) => frames.push(frame),+ Err(ffmpeg::Error::Eof) => break,+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => break,+ Err(error) => panic!("receive decoded frame: {error}"),+ }+ }+ }++ fn decoded_rgb(opened: &mut OpenedVideoEncoder, input: &frame::Video) -> frame::Video {+ let mut yuv = frame::Video::empty();+ opened+ .converter+ .as_mut()+ .unwrap()+ .run(input, &mut yuv)+ .unwrap();+ assert_eq!(yuv.format(), format::Pixel::YUV420P);+ let expected_luma = [63u8, 173, 32, 16, 235, 126];+ for (index, expected) in expected_luma.into_iter().enumerate() {+ let x = (index * 2 + 1) * yuv.width() as usize / 12;+ let y = yuv.height() as usize / 2;+ let actual = yuv.data(0)[y * yuv.stride(0) + x];+ assert!(+ actual.abs_diff(expected) <= 2,+ "limited BT709 luma patch {index}: {actual} vs {expected}"+ );+ }+ yuv.set_pts(Some(0));+ opened.encoder.send_frame(&yuv).unwrap();+ let mut packets = Vec::new();+ receive_packets(&mut opened.encoder, &mut packets);+ opened.encoder.send_eof().unwrap();+ receive_packets(&mut opened.encoder, &mut packets);+ assert!(!packets.is_empty());++ let codec = ffmpeg::decoder::find(ffmpeg::codec::Id::H264).unwrap();+ let mut decoder = context::Context::new_with_codec(codec)+ .decoder()+ .video()+ .unwrap();+ let mut frames = Vec::new();+ for packet in packets {+ decoder.send_packet(&packet).unwrap();+ receive_frames(&mut decoder, &mut frames);+ }+ decoder.send_eof().unwrap();+ receive_frames(&mut decoder, &mut frames);+ assert_eq!(frames.len(), 1);+ let decoded = frames.pop().unwrap();+ assert_eq!(decoded.color_space(), color::Space::BT709);+ assert_eq!(decoded.color_range(), color::Range::MPEG);+ let mut converter = ffmpeg::software::scaling::Context::get(+ decoded.format(),+ decoded.width(),+ decoded.height(),+ format::Pixel::RGB24,+ decoded.width(),+ decoded.height(),+ ffmpeg::software::scaling::Flags::BILINEAR,+ )+ .unwrap();+ unsafe {+ let coefficients = ffmpeg::ffi::sws_getCoefficients(ffmpeg::ffi::SWS_CS_ITU709);+ assert!(+ ffmpeg::ffi::sws_setColorspaceDetails(+ converter.as_mut_ptr(),+ coefficients,+ 0,+ coefficients,+ 1,+ 0,+ 1 << 16,+ 1 << 16,+ ) >= 0+ );+ }+ let mut rgb = frame::Video::empty();+ converter.run(&decoded, &mut rgb).unwrap();+ rgb+ }++ #[test]+ fn rgb_software_conversion_matches_declared_bt709_through_encode_decode() {+ for format in [+ format::Pixel::RGB24,+ format::Pixel::RGBA,+ format::Pixel::BGRA,+ format::Pixel::BGRZ,+ ] {+ for scale in [1, 2] {+ let mut opened = open(format, scale, false);+ let decoded = decoded_rgb(&mut opened, &rgb_bars(format));+ for (index, expected) in COLORS.iter().enumerate() {+ let x = (index * 2 + 1) * decoded.width() as usize / 12;+ let y = decoded.height() as usize / 2;+ let offset = y * decoded.stride(0) + x * 3;+ for (actual, expected) in+ decoded.data(0)[offset..offset + 3].iter().zip(expected)+ {+ assert!(+ actual.abs_diff(*expected) <= 4,+ "RGB round trip {format:?} scale {scale} patch {index}: {actual} vs {expected}"+ );+ }+ }+ }+ }+ }++ #[test]+ fn external_rgb_conversion_still_skips_internal_scaler() {+ let opened = open(format::Pixel::BGRA, 1, true);+ assert_eq!(opened.output_format, format::Pixel::YUV420P);+ assert!(opened.converter.is_none());+ assert!(opened.converted_frame_pool.is_none());+ }++ #[test]+ fn rgb_software_nv12_conversion_uses_bt709_limited_luma() {+ ffmpeg::init().unwrap();+ let mut converter = ffmpeg::software::scaling::Context::get(+ format::Pixel::BGRA,+ 192,+ 64,+ format::Pixel::NV12,+ 192,+ 64,+ ffmpeg::software::scaling::Flags::FAST_BILINEAR,+ )+ .unwrap();+ configure_rgb_converter(&mut converter, format::Pixel::BGRA, format::Pixel::NV12).unwrap();+ let mut output = frame::Video::empty();+ converter+ .run(&rgb_bars(format::Pixel::BGRA), &mut output)+ .unwrap();+ for (index, expected) in [63u8, 173, 32, 16, 235, 126].into_iter().enumerate() {+ let actual = output.data(0)[32 * output.stride(0) + index * 32 + 16];+ assert!(actual.abs_diff(expected) <= 2);+ }+ }++ #[test]+ fn rgb_to_rgb_conversion_preserves_channel_values() {+ ffmpeg::init().unwrap();+ let mut converter = ffmpeg::software::scaling::Context::get(+ format::Pixel::BGRA,+ 192,+ 64,+ format::Pixel::RGB24,+ 192,+ 64,+ ffmpeg::software::scaling::Flags::FAST_BILINEAR,+ )+ .unwrap();+ configure_rgb_converter(&mut converter, format::Pixel::BGRA, format::Pixel::RGB24).unwrap();+ let mut output = frame::Video::empty();+ converter+ .run(&rgb_bars(format::Pixel::BGRA), &mut output)+ .unwrap();+ for (index, expected) in COLORS.iter().enumerate() {+ let offset = 32 * output.stride(0) + (index * 32 + 16) * 3;+ assert_eq!(&output.data(0)[offset..offset + 3], expected);+ }+ }++ #[test]+ fn existing_yuv_input_selection_and_scaling_are_unchanged() {+ let opened = open(format::Pixel::YUV420P, 1, false);+ assert_eq!(opened.output_format, format::Pixel::YUV420P);+ assert!(opened.converter.is_none());+ let mut scaled = open(format::Pixel::YUV420P, 2, false);+ assert_eq!(scaled.output_format, format::Pixel::YUV420P);+ let mut original = ffmpeg::software::scaling::Context::get(+ format::Pixel::YUV420P,+ 192,+ 64,+ format::Pixel::YUV420P,+ 96,+ 32,+ ffmpeg::software::scaling::Flags::BICUBIC,+ )+ .unwrap();+ let mut input = frame::Video::new(format::Pixel::YUV420P, 192, 64);+ for plane in 0..input.planes() {+ for (index, byte) in input.data_mut(plane).iter_mut().enumerate() {+ *byte = ((index + plane * 37) % 256) as u8;+ }+ }+ let mut expected = frame::Video::empty();+ let mut actual = frame::Video::empty();+ original.run(&input, &mut expected).unwrap();+ scaled+ .converter+ .as_mut()+ .unwrap()+ .run(&input, &mut actual)+ .unwrap();+ for plane in 0..actual.planes() {+ let width = actual.plane_width(plane) as usize;+ for row in 0..actual.plane_height(plane) as usize {+ let actual_offset = row * actual.stride(plane);+ let expected_offset = row * expected.stride(plane);+ assert_eq!(+ &actual.data(plane)[actual_offset..actual_offset + width],+ &expected.data(plane)[expected_offset..expected_offset + width],+ );+ }+ }+ }++ #[test]+ fn rgb_classification_does_not_treat_yuv_or_hardware_as_rgb() {+ for format in [+ format::Pixel::RGB24,+ format::Pixel::BGRA,+ format::Pixel::BGRZ,+ ] {+ assert!(is_rgb(format));+ }+ for format in [+ format::Pixel::YUV420P,+ format::Pixel::NV12,+ format::Pixel::GRAY8,+ format::Pixel::CUDA,+ format::Pixel::None,+ ] {+ assert!(!is_rgb(format));+ }+ }+}diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rsindex 216ee8b07..dee6d2f31 100644--- a/crates/project/src/meta.rs+++ b/crates/project/src/meta.rs@@ -367,6 +367,46 @@ impl StudioRecordingMeta {}}+ pub fn ensure_ordinary_media_access(&self, project_path: &Path) -> Result<(), String> {+ if let StudioRecordingStatus::Failed { error } = self.status() {+ return Err(format!(+ "This recording failed: {error}. Its original files are preserved and may contain incomplete tracks. Open the recording folder to inspect them."+ ));+ }++ let path = project_path.join("recording-diagnostics.json");+ let raw = match std::fs::read(&path) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) => {+ return Err(format!(+ "Cannot verify preserved recording diagnostics: {error}. Original files are unchanged."+ ));+ }+ };+ let diagnostics: serde_json::Value = serde_json::from_slice(&raw).map_err(|error| {+ format!("Cannot verify preserved recording diagnostics: {error}. Original files are unchanged.")+ })?;+ let failed = diagnostics+ .get("segments")+ .and_then(serde_json::Value::as_array)+ .is_none_or(|segments| {+ segments.iter().any(|segment| {+ segment+ .get("trackFailures")+ .and_then(serde_json::Value::as_array)+ .is_none_or(|failures| !failures.is_empty())+ })+ });+ if failed {+ return Err(+ "This recording retains a requested-track failure or incomplete diagnostics. Its original files are preserved. Open the recording folder to inspect them."+ .into(),+ );+ }+ Ok(())+ }+pub fn camera_path(&self) -> Option<RelativePathBuf> {match self {Self::SingleSegment { segment } => segment.camera.as_ref().map(|c| c.path.clone()),@@ -914,3 +954,129 @@ mod display_notch_tests {assert_eq!(studio(&meta).display_notch(), None);}}++#[cfg(test)]+mod ordinary_media_access_tests {+ use super::{Cursors, MultipleSegments, StudioRecordingMeta, StudioRecordingStatus};++ fn studio(status: Option<StudioRecordingStatus>) -> StudioRecordingMeta {+ StudioRecordingMeta::MultipleSegments {+ inner: MultipleSegments {+ segments: Vec::new(),+ cursors: Cursors::default(),+ status,+ },+ }+ }++ fn check_diagnostics(raw: &[u8], expected_ok: bool) {+ let project = tempfile::tempdir().unwrap();+ let diagnostics = project.path().join("recording-diagnostics.json");+ let media = project.path().join("surviving-track.bin");+ let config = project.path().join("project-config.json");+ std::fs::write(&diagnostics, raw).unwrap();+ std::fs::write(&media, b"incomplete original media").unwrap();+ std::fs::write(&config, b"original config").unwrap();+ let meta = studio(Some(StudioRecordingStatus::Complete));+ let before = serde_json::to_vec(&meta).unwrap();+ assert_eq!(+ meta.ensure_ordinary_media_access(project.path()).is_ok(),+ expected_ok+ );+ assert_eq!(std::fs::read(diagnostics).unwrap(), raw);+ assert_eq!(std::fs::read(media).unwrap(), b"incomplete original media");+ assert_eq!(std::fs::read(config).unwrap(), b"original config");+ assert_eq!(serde_json::to_vec(&meta).unwrap(), before);+ }++ #[test]+ fn failed_status_refuses_without_changing_metadata_or_media() {+ let project = tempfile::tempdir().unwrap();+ let media = project.path().join("raw.bin");+ std::fs::write(&media, b"retained").unwrap();+ let meta = studio(Some(StudioRecordingStatus::Failed {+ error: "microphone lost".into(),+ }));+ let before = serde_json::to_vec(&meta).unwrap();+ let error = meta+ .ensure_ordinary_media_access(project.path())+ .unwrap_err();+ assert!(error.contains("microphone lost"));+ assert!(!error.contains("may need to be recovered"));+ assert_eq!(serde_json::to_vec(&meta).unwrap(), before);+ assert_eq!(std::fs::read(media).unwrap(), b"retained");+ }++ #[test]+ fn absent_diagnostics_preserves_legacy_and_existing_status_policy() {+ let project = tempfile::tempdir().unwrap();+ for status in [+ None,+ Some(StudioRecordingStatus::Complete),+ Some(StudioRecordingStatus::InProgress),+ Some(StudioRecordingStatus::NeedsRemux),+ ] {+ assert!(+ studio(status)+ .ensure_ordinary_media_access(project.path())+ .is_ok()+ );+ }+ }++ #[test]+ fn legacy_single_segment_without_diagnostics_remains_allowed() {+ let project = tempfile::tempdir().unwrap();+ let meta: StudioRecordingMeta =+ serde_json::from_str(r#"{"display":{"path":"content/display.mp4"}}"#).unwrap();+ assert!(meta.ensure_ordinary_media_access(project.path()).is_ok());+ }++ #[test]+ fn clean_track_diagnostics_remain_allowed() {+ check_diagnostics(br#"{"segments":[{"trackFailures":[]}]}"#, true);+ }++ #[test]+ fn retained_failure_refuses_even_if_status_is_complete() {+ check_diagnostics(+ br#"{"segments":[{"trackFailures":["system audio lost"]}]}"#,+ false,+ );+ }++ #[test]+ fn malformed_diagnostics_refuse_without_modification() {+ check_diagnostics(b"{", false);+ }++ #[test]+ fn incomplete_diagnostic_schema_refuses_without_modification() {+ for raw in [+ b"{}".as_slice(),+ br#"{"segments":[{}]}"#,+ br#"{"segments":null}"#,+ br#"{"segments":[{"trackFailures":null}]}"#,+ ] {+ check_diagnostics(raw, false);+ }+ }++ #[test]+ fn empty_segment_diagnostics_preserve_existing_recovery_policy() {+ check_diagnostics(br#"{"segments":[]}"#, true);+ }++ #[test]+ fn diagnostics_read_error_refuses_without_changing_directory() {+ let project = tempfile::tempdir().unwrap();+ let diagnostics = project.path().join("recording-diagnostics.json");+ std::fs::create_dir(&diagnostics).unwrap();+ assert!(+ studio(None)+ .ensure_ordinary_media_access(project.path())+ .is_err()+ );+ assert!(diagnostics.is_dir());+ }+}diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rsindex aeeacc018..fec8000a1 100644--- a/crates/recording/src/cursor.rs+++ b/crates/recording/src/cursor.rs@@ -328,8 +328,14 @@ pub fn spawn_cursor_recorder(let (tx, rx) = oneshot::channel();let (stop_wakeup_tx, stop_wakeup_rx) = std::sync::mpsc::channel();+ let scope = crate::output_pipeline::PipelineBuildScope::current();+ if let Some(scope) = &scope {+ scope.register_token(stop_token.clone());+ }+ let completion = scope.map(|scope| scope.task_completion());let stop_token_child = stop_token.child_token();let thread = std::thread::spawn(move || {+ let _completion = completion;let crop_bounds = target.crop_bounds;let display = target.display;#[cfg(target_os = "linux")]diff --git a/crates/recording/src/diagnostics.rs b/crates/recording/src/diagnostics.rsindex aa53ff252..23a759cdf 100644--- a/crates/recording/src/diagnostics.rs+++ b/crates/recording/src/diagnostics.rs@@ -585,7 +585,7 @@ pub fn collect_recent_recordings(}).collect();- candidates.sort_by(|a, b| b.0.cmp(&a.0));+ candidates.sort_by_key(|candidate| std::cmp::Reverse(candidate.0));candidates.into_iter().take(limit)diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rsindex 0bbf4c887..97af69b19 100644--- a/crates/recording/src/feeds/camera.rs+++ b/crates/recording/src/feeds/camera.rs@@ -1520,10 +1520,14 @@ impl Message<Lock> for CameraFeed {LockFeedError::InitializeFailed(SetInputError::Timeout(err.to_string()))})??;- if state.handle_input_connected(data)- && let Some(attached) = &mut state.attached- {- attached.finalize_pending_release();+ if state.handle_input_connected(data) {+ if let Some(attached) = &mut state.attached {+ attached.finalize_pending_release();+ }++ for tx in self.on_ready.drain(..) {+ let _ = tx.send(());+ }}}@@ -1563,7 +1567,7 @@ impl Message<Lock> for CameraFeed {}impl Message<InputConnected> for CameraFeed {- type Reply = Result<(), FeedLockedError>;+ type Reply = ();async fn handle(&mut self,@@ -1572,7 +1576,10 @@ impl Message<InputConnected> for CameraFeed {) -> Self::Reply {trace!("CameraFeed.InputConnected");- let state = self.state.try_as_open()?;+ // Lock can consume this connection before the notification reaches the mailbox.+ let Ok(state) = self.state.try_as_open() else {+ return;+ };if state.handle_input_connected(msg) {if let Some(attached) = &mut state.attached {@@ -1583,13 +1590,11 @@ impl Message<InputConnected> for CameraFeed {tx.send(()).ok();}}-- Ok(())}}impl Message<InputConnectFailed> for CameraFeed {- type Reply = Result<(), FeedLockedError>;+ type Reply = ();async fn handle(&mut self,@@ -1598,7 +1603,9 @@ impl Message<InputConnectFailed> for CameraFeed {) -> Self::Reply {trace!("CameraFeed.InputConnectFailed");- let state = self.state.try_as_open()?;+ let Ok(state) = self.state.try_as_open() else {+ return;+ };let should_clear = state.connecting.as_ref().is_some_and(|connecting| {connecting.id == msg.id && connecting.generation == msg.generation@@ -1613,8 +1620,6 @@ impl Message<InputConnectFailed> for CameraFeed {tx.send(()).ok();}}-- Ok(())}}@@ -1699,3 +1704,95 @@ impl Message<Unlock> for CameraFeed {});}}++#[cfg(test)]+mod tests {+ use super::*;++ async fn locked_test_camera() -> (+ ActorRef<CameraFeed>,+ CameraFeedLock,+ InputConnected,+ oneshot::Receiver<()>,+ ) {+ let (done_tx, _done_rx) = mpsc::sync_channel(1);+ let connection = InputConnected {+ id: DeviceOrModelID::DeviceID("test-camera".to_string()),+ generation: 1,+ done_tx: done_tx.clone(),+ camera_info: serde_json::from_value(serde_json::json!({+ "device_id": "test-camera",+ "model_id": null,+ "display_name": "Test camera"+ }))+ .unwrap(),+ video_info: VideoInfo::from_raw_ffmpeg(ffmpeg::format::Pixel::BGRA, 16, 16, 30),+ };+ let (ready_tx, ready_rx) = oneshot::channel();+ let camera = CameraFeed {+ setup_generation: 1,+ state: State::Open(OpenState {+ connecting: Some(ConnectingState {+ id: connection.id.clone(),+ generation: connection.generation,+ ready: futures::future::ready(Ok(connection.clone())).boxed(),+ done_tx,+ }),+ attached: None,+ }),+ on_ready: vec![ready_tx],+ ..CameraFeed::default()+ };+ let feed = CameraFeed::spawn(camera);+ let lock = feed.ask(Lock).await.unwrap();+ (feed, lock, connection, ready_rx)+ }++ #[tokio::test]+ async fn camera_late_connection_notification_keeps_locked_feed_alive() {+ let (feed, lock, connection, _ready) = locked_test_camera().await;+ feed.tell(connection).await.unwrap();+ let (sender, _receiver) = flume::bounded(1);+ let result = feed.ask(AddSender(sender)).await;+ drop(lock);+ feed.kill();+ feed.wait_for_stop().await;+ assert!(+ result.is_ok(),+ "late connection notification stopped the feed: {result:?}"+ );+ }++ #[tokio::test]+ async fn camera_late_failure_notification_keeps_locked_feed_alive() {+ let (feed, lock, connection, _ready) = locked_test_camera().await;+ feed.tell(InputConnectFailed {+ id: connection.id,+ generation: connection.generation,+ })+ .await+ .unwrap();+ let (sender, _receiver) = flume::bounded(1);+ let result = feed.ask(AddSender(sender)).await;+ drop(lock);+ feed.kill();+ feed.wait_for_stop().await;+ assert!(+ result.is_ok(),+ "late failure notification stopped the feed: {result:?}"+ );+ }++ #[tokio::test]+ async fn camera_lock_notifies_waiters_when_it_consumes_the_connection() {+ let (feed, lock, _connection, mut ready) = locked_test_camera().await;+ let result = ready.try_recv();+ drop(lock);+ feed.kill();+ feed.wait_for_stop().await;+ assert!(+ result.is_ok(),+ "camera readiness was not delivered: {result:?}"+ );+ }+}diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rsindex 88af297b3..16ca756f3 100644--- a/crates/recording/src/feeds/microphone.rs+++ b/crates/recording/src/feeds/microphone.rs@@ -47,6 +47,51 @@ const STANDARD_SAMPLE_RATES: [u32; 13] = [192_000,];+#[cfg(target_os = "linux")]+fn audio_follows_confirmed_route(+ callback_received: Instant,+ capture_delay: Option<Duration>,+ route_required: bool,+ routed_at: Option<cap_timestamp::Timestamps>,+) -> bool {+ !route_required+ || capture_delay+ .and_then(|delay| callback_received.checked_sub(delay))+ .zip(routed_at)+ .is_some_and(|(captured_at, routed_at)| captured_at >= routed_at.instant())+}++#[cfg(target_os = "linux")]+fn cancellable_system_stream_ready(+ ready: StreamReadyFuture,+ cancel: tokio_util::sync::CancellationToken,+) -> StreamReadyFuture {+ async move {+ tokio::select! {+ biased;+ _ = cancel.cancelled() => Err(SetInputError::BuildStream("System audio reconnect cancelled".into())),+ result = ready => result,+ }+ }.boxed()+}++fn microphone_stream_error_handler(+ error_sender: flume::Sender<StreamError>,+ mut on_first_error: impl FnMut() + Send + 'static,+) -> impl FnMut(StreamError) + Send + 'static {+ let mut logged = false;+ move |error| {+ if !logged {+ error!("Microphone stream error: {error}");+ logged = true;+ on_first_error();+ }+ if error_sender.is_empty() {+ let _ = error_sender.try_send(error);+ }+ }+}+#[derive(serde::Serialize, serde::Deserialize, specta::Type, Clone, Copy, Debug, PartialEq, Eq, Default,)]@@ -58,6 +103,8 @@ pub struct MicrophoneDeviceSettings {#[derive(Clone)]pub struct MicrophoneSamples {+ #[cfg(any(target_os = "linux", windows))]+ pub(crate) stream_id: u32,pub data: Vec<u8>,pub format: SampleFormat,pub sample_rate: u32,@@ -384,8 +431,390 @@ fn enqueue_microphone_samples(}}+#[cfg(any(target_os = "linux", windows))]+struct StreamHealth {+ id: u32,+ failed: AtomicBool,+}++#[cfg(any(target_os = "linux", windows))]+impl StreamHealth {+ fn new(id: u32) -> Self {+ Self {+ id,+ failed: AtomicBool::new(false),+ }+ }+}++#[cfg(target_os = "linux")]+#[derive(Clone)]+pub(crate) struct RecordingSourceHealth(Arc<std::sync::Mutex<RecordingSourceHealthState>>);++#[cfg(target_os = "linux")]+struct RecordingSourceHealthState {+ generation: u64,+ current: Arc<StreamHealth>,+ pending: Option<Arc<StreamHealth>>,+ recovery_origin: Option<u32>,+ terminal: Option<String>,+}++#[cfg(target_os = "linux")]+impl RecordingSourceHealth {+ fn new(generation: u64, current: Arc<StreamHealth>) -> Self {+ Self(Arc::new(std::sync::Mutex::new(+ RecordingSourceHealthState {+ generation,+ current,+ pending: None,+ recovery_origin: None,+ terminal: None,+ },+ )))+ }++ #[cfg(test)]+ pub(crate) fn test_healthy(id: u32) -> Self {+ Self::new(1, Arc::new(StreamHealth::new(id)))+ }++ #[cfg(test)]+ pub(crate) fn test_backend_failure(&self) {+ self.0+ .lock()+ .unwrap()+ .current+ .failed+ .store(true, Ordering::Release);+ }++ fn observe_ready(+ &self,+ generation: u64,+ id: u32,+ ready: StreamReadyFuture,+ ) -> StreamReadyFuture {+ let health = self.clone();+ ready+ .map(move |result| {+ if let Err(error) = &result {+ health.fail_reconnect(+ generation,+ id,+ format!("Requested audio stream rebuild failed: {error}"),+ );+ }+ result+ })+ .boxed()+ }++ fn begin_reconnect(&self, generation: u64, pending: Arc<StreamHealth>) {+ let mut state = self.0.lock().unwrap();+ if state.generation == generation && state.terminal.is_none() {+ state.pending = Some(pending);+ }+ }++ fn expects_reconnect(&self, generation: u64, id: u32) -> bool {+ let state = self.0.lock().unwrap();+ state.generation == generation+ && state.terminal.is_none()+ && state+ .pending+ .as_ref()+ .is_some_and(|pending| pending.id == id)+ }++ fn commit_reconnect(&self, generation: u64, id: u32) {+ let mut state = self.0.lock().unwrap();+ if state.generation != generation || state.terminal.is_some() {+ return;+ }+ let Some(pending) = state+ .pending+ .as_ref()+ .filter(|pending| pending.id == id)+ .cloned()+ else {+ return;+ };+ if pending.failed.load(Ordering::Acquire) {+ state.terminal = Some("Replacement audio stream failed before acceptance".into());+ return;+ }+ if state.current.failed.load(Ordering::Acquire) || state.recovery_origin.is_some() {+ state.recovery_origin = Some(state.current.id);+ }+ state.current = pending;+ state.pending = None;+ }++ fn fail_current(&self, generation: u64, id: u32, error: String) {+ let mut state = self.0.lock().unwrap();+ if state.generation == generation && state.current.id == id {+ state.terminal.get_or_insert(error);+ }+ }++ fn fail_reconnect(&self, generation: u64, id: u32, error: String) {+ let mut state = self.0.lock().unwrap();+ if state.generation == generation+ && state+ .pending+ .as_ref()+ .is_some_and(|pending| pending.id == id)+ {+ state.terminal.get_or_insert(error);+ }+ }++ pub(crate) fn fail(&self, error: String) {+ self.0.lock().unwrap().terminal.get_or_insert(error);+ }++ pub(crate) fn terminal_error(&self) -> Option<String> {+ self.0.lock().unwrap().terminal.clone()+ }++ pub(crate) fn frame_is_current(&self, id: u32) -> bool {+ let mut state = self.0.lock().unwrap();+ if state.current.id != id || state.terminal.is_some() {+ return false;+ }+ if state.current.failed.load(Ordering::Acquire) {+ state.terminal =+ Some("Requested audio backend failed while continuing to deliver samples".into());+ return false;+ }+ true+ }++ pub(crate) fn accepted_frame(&self, id: u32) {+ let mut state = self.0.lock().unwrap();+ if state.current.id == id+ && state.terminal.is_none()+ && !state.current.failed.load(Ordering::Acquire)+ && state.recovery_origin.is_some_and(|origin| origin != id)+ {+ state.recovery_origin = None;+ }+ }++ pub(crate) fn stop_error(&self) -> Option<String> {+ let state = self.0.lock().unwrap();+ state.terminal.clone().or_else(|| {+ (state.current.failed.load(Ordering::Acquire)+ || state+ .pending+ .as_ref()+ .is_some_and(|pending| pending.failed.load(Ordering::Acquire))+ || state.recovery_origin.is_some())+ .then(|| "Requested audio stream has an unresolved backend failure at Stop".into())+ })+ }+}++#[cfg(windows)]+pub(crate) struct RecordingSubscription {+ generation: u64,+ cancel: tokio_util::sync::CancellationToken,+ state: std::sync::Mutex<RecordingSubscriptionState>,+}++#[cfg(windows)]+#[derive(Default)]+struct RecordingSubscriptionState {+ current: Option<Arc<StreamHealth>>,+ pending: Option<Arc<StreamHealth>>,+ retired: bool,+ failure: Option<String>,+}++#[cfg(windows)]+impl RecordingSubscription {+ fn new(generation: u64, cancel: tokio_util::sync::CancellationToken) -> Arc<Self> {+ Arc::new(Self {+ generation,+ cancel,+ state: std::sync::Mutex::new(RecordingSubscriptionState::default()),+ })+ }++ fn active(&self) -> bool {+ let state = self.state.lock().unwrap();+ !state.retired && !self.cancel.is_cancelled()+ }++ pub(crate) fn error(&self) -> Option<String> {+ let mut state = self.state.lock().unwrap();+ if !state.retired+ && state.failure.is_none()+ && (state+ .current+ .as_ref()+ .is_some_and(|stream| stream.failed.load(Ordering::Acquire))+ || state+ .pending+ .as_ref()+ .is_some_and(|stream| stream.failed.load(Ordering::Acquire)))+ {+ state.failure = Some("Requested microphone backend failed".into());+ }+ state.failure.clone()+ }++ pub(crate) fn accepts_frame(&self, id: u32) -> bool {+ let state = self.state.lock().unwrap();+ !state.retired+ && !self.cancel.is_cancelled()+ && state.failure.is_none()+ && state+ .current+ .as_ref()+ .is_some_and(|stream| stream.id == id && !stream.failed.load(Ordering::Acquire))+ }++ pub(crate) fn retire(&self) -> Option<String> {+ let mut state = self.state.lock().unwrap();+ if !state.retired+ && state.failure.is_none()+ && (state+ .current+ .as_ref()+ .is_some_and(|stream| stream.failed.load(Ordering::Acquire))+ || state+ .pending+ .as_ref()+ .is_some_and(|stream| stream.failed.load(Ordering::Acquire)))+ {+ state.failure = Some("Requested microphone backend failed at Stop".into());+ }+ state.retired = true;+ let error = state.failure.clone();+ drop(state);+ self.cancel.cancel();+ error+ }++ fn begin_reconnect(&self, health: Arc<StreamHealth>) {+ let mut state = self.state.lock().unwrap();+ if !state.retired && !self.cancel.is_cancelled() {+ state.pending = Some(health);+ }+ }++ fn commit_reconnect(&self, id: u32) {+ let mut state = self.state.lock().unwrap();+ if !state.retired+ && state.failure.is_none()+ && state+ .current+ .as_ref()+ .is_some_and(|current| current.failed.load(Ordering::Acquire))+ {+ state.failure =+ Some("Requested microphone backend failed before replacement acceptance".into());+ }+ if state.retired || self.cancel.is_cancelled() || state.failure.is_some() {+ return;+ }+ if let Some(pending) = state.pending.take() {+ if pending.id == id && !pending.failed.load(Ordering::Acquire) {+ state.current = Some(pending);+ } else {+ state.pending = Some(pending);+ }+ }+ }++ fn fail_reconnect(&self, id: u32, error: String) {+ let mut state = self.state.lock().unwrap();+ if !state.retired+ && !self.cancel.is_cancelled()+ && state+ .pending+ .as_ref()+ .is_some_and(|pending| pending.id == id)+ {+ state.failure.get_or_insert(error);+ }+ }+}++#[cfg(windows)]+struct StreamExitHealth {+ health: Arc<StreamHealth>,+ expected: bool,+}++#[cfg(windows)]+impl Drop for StreamExitHealth {+ fn drop(&mut self) {+ if !self.expected {+ self.health.failed.store(true, Ordering::Release);+ }+ }+}++#[cfg(windows)]+struct WindowsReconnect {+ selection_generation: u64,+ generation: u64,+ previous_id: u32,+ id: u32,+ label: String,+ ready: futures::future::Shared<StreamReadyFuture>,+ done_tx: SyncSender<()>,+}++#[cfg(windows)]+impl WindowsReconnect {+ fn identity(&self) -> (u64, u32, u32) {+ (self.generation, self.previous_id, self.id)+ }+ fn connecting(&self) -> ConnectingState {+ let id = self.id;+ let label = self.label.clone();+ let done_tx = self.done_tx.clone();+ ConnectingState {+ id,+ ready: self+ .ready+ .clone()+ .map(move |result| {+ result.map(|(config, buffer_size_frames)| InputConnected {+ id,+ label,+ config,+ buffer_size_frames,+ done_tx,+ })+ })+ .boxed(),+ }+ }+}+#[derive(Actor)]pub struct MicrophoneFeed {+ #[cfg(windows)]+ selection_generation: u64,+ #[cfg(windows)]+ recording_reconnect: Option<WindowsReconnect>,+ #[cfg(any(target_os = "linux", windows))]+ stream_health: std::collections::HashMap<u32, Arc<StreamHealth>>,+ #[cfg(target_os = "linux")]+ recording_health: Option<RecordingSourceHealth>,+ #[cfg(target_os = "linux")]+ pulse_input_role: crate::sources::screen_capture::PulseInputRole,+ #[cfg(target_os = "linux")]+ system_stream_cancel: tokio_util::sync::CancellationToken,+ #[cfg(target_os = "linux")]+ system_failed_input: Option<u32>,+ #[cfg(target_os = "linux")]+ system_reconnect: Option<SystemReconnect>,input_id_counter: u32,lock_generation: u64,state: State,@@ -394,7 +823,25 @@ pub struct MicrophoneFeed {dropped_message_count: Arc<AtomicU64>,}+#[cfg(target_os = "linux")]+struct SystemReconnect {+ previous_id: u32,+ id: u32,+ generation: u64,+ label: String,+ ready: futures::future::Shared<StreamReadyFuture>,+}++impl Drop for MicrophoneFeed {+ fn drop(&mut self) {+ #[cfg(target_os = "linux")]+ self.system_stream_cancel.cancel();+ }+}+struct MicrophoneFeedSender {+ #[cfg(windows)]+ subscription: Option<Arc<RecordingSubscription>>,sender: flume::Sender<MicrophoneSamples>,health_tx: Option<HealthSender>,label: Option<String>,@@ -405,6 +852,8 @@ struct MicrophoneFeedSender {impl MicrophoneFeedSender {fn new(sender: flume::Sender<MicrophoneSamples>) -> Self {Self {+ #[cfg(windows)]+ subscription: None,sender,health_tx: None,label: None,@@ -419,6 +868,8 @@ impl MicrophoneFeedSender {label: String,) -> Self {Self {+ #[cfg(windows)]+ subscription: None,sender,health_tx: Some(health_tx),label: Some(label),@@ -603,6 +1054,22 @@ fn list_input_device_names() -> Vec<String> {impl MicrophoneFeed {pub fn new(error_sender: flume::Sender<StreamError>) -> Self {Self {+ #[cfg(target_os = "linux")]+ pulse_input_role: crate::sources::screen_capture::PulseInputRole::Microphone,+ #[cfg(target_os = "linux")]+ system_stream_cancel: tokio_util::sync::CancellationToken::new(),+ #[cfg(target_os = "linux")]+ system_failed_input: None,+ #[cfg(target_os = "linux")]+ system_reconnect: None,+ #[cfg(any(target_os = "linux", windows))]+ stream_health: std::collections::HashMap::new(),+ #[cfg(target_os = "linux")]+ recording_health: None,+ #[cfg(windows)]+ recording_reconnect: None,+ #[cfg(windows)]+ selection_generation: 0,input_id_counter: 0,lock_generation: 0,state: State::Open(OpenState {@@ -615,6 +1082,13 @@ impl MicrophoneFeed {}}+ #[cfg(target_os = "linux")]+ pub(crate) fn new_system_audio(error_sender: flume::Sender<StreamError>) -> Self {+ let mut feed = Self::new(error_sender);+ feed.pulse_input_role = crate::sources::screen_capture::PulseInputRole::SystemAudio;+ feed+ }+pub fn default_device() -> Option<(String, Device, SupportedStreamConfig)> {let host = cpal::default_host();host.default_input_device()@@ -658,6 +1132,12 @@ impl MicrophoneFeed {fn spawn_input_stream(params: StreamSpawnParams) -> (StreamReadyFuture, SyncSender<()>) {let StreamSpawnParams {+ #[cfg(any(target_os = "linux", windows))]+ health,+ #[cfg(target_os = "linux")]+ pulse_input_role,+ #[cfg(target_os = "linux")]+ system_stream_cancel,id,label,device,@@ -693,6 +1173,11 @@ impl MicrophoneFeed {let error_sender = error_sender.clone();let dropped_message_count = dropped_message_count.clone();move || {+ #[cfg(windows)]+ let mut exit_health = StreamExitHealth {+ health: health.clone(),+ expected: false,+ };let device_name_for_log = device.name().ok();if let Some(ref name) = device_name_for_log {@@ -734,6 +1219,10 @@ impl MicrophoneFeed {let mut sample_rate_estimator =CallbackSampleRateEstimator::new(callback_sample_rate);let mut pending_samples = VecDeque::new();+ #[cfg(windows)]+ let mut capture_clock = crate::sources::capture_clock::CaptureClock::new(+ cap_timestamp::Timestamps::now(),+ );let latency_info = estimate_input_latency(callback_sample_rate,@@ -753,13 +1242,45 @@ impl MicrophoneFeed {);}+ #[cfg(target_os = "linux")]+ let input_route = match crate::sources::screen_capture::PulseInputRoute::prepare(+ &label,+ pulse_input_role,+ ) {+ Ok(route) => route,+ Err(error) => {+ let _ = ready_tx.send(Err(SetInputError::BuildStream(format!(+ "Could not prepare the Linux audio input route: {error}"+ ))));+ return;+ }+ };+ #[cfg(target_os = "linux")]+ let input_callback_observed = Arc::new(AtomicBool::new(false));+ #[cfg(target_os = "linux")]+ let route_required = input_route.is_some();+ #[cfg(target_os = "linux")]+ let routed_at = Arc::new(std::sync::OnceLock::<cap_timestamp::Timestamps>::new());+let stream = match device.build_input_stream_raw(&stream_config,sample_format,{let actor_ref = actor_ref.clone();+ #[cfg(target_os = "linux")]+ let input_callback_observed = input_callback_observed.clone();+ #[cfg(target_os = "linux")]+ let routed_at = routed_at.clone();+ #[cfg(target_os = "linux")]+ let system_stream_cancel = system_stream_cancel.clone();let mut callback_count = 0u64;move |data, info| {+ #[cfg(target_os = "linux")]+ if system_stream_cancel.is_cancelled() {+ return;+ }+ #[cfg(target_os = "linux")]+ let callback_received = Instant::now();let frame_count = callback_frame_count(data.bytes().len(),data.sample_format(),@@ -770,6 +1291,8 @@ impl MicrophoneFeed {sample_rate_estimator.sample_rate_for(input_timestamp, frame_count);if callback_count == 0 {+ #[cfg(target_os = "linux")]+ input_callback_observed.store(true, Ordering::Release);info!("🎤 First audio callback - data size: {} bytes, frames: {}, format: {:?}, rate: {}",data.bytes().len(),@@ -780,14 +1303,36 @@ impl MicrophoneFeed {}callback_count += 1;+ let timestamp = Timestamp::from_cpal(input_timestamp.capture);+ #[cfg(target_os = "linux")]+ // Linux Timestamp::from_cpal uses receipt time, so the route gate+ // separately accounts for ALSA buffers without changing A/V compensation.+ if !audio_follows_confirmed_route(+ callback_received,+ input_timestamp.callback.duration_since(&input_timestamp.capture),+ route_required,+ routed_at.get().copied(),+ ) {+ return;+ }+ #[cfg(windows)]+ let timestamp = capture_clock.timestamp(+ timestamp,+ Instant::now(),+ Duration::from_secs_f64(+ frame_count as f64+ / f64::from(effective_sample_rate.sample_rate.max(1)),+ ),+ );let samples = MicrophoneSamples {+ #[cfg(any(target_os = "linux", windows))]+ stream_id: id,data: data.bytes().to_vec(),format: data.sample_format(),sample_rate: effective_sample_rate.sample_rate,channels: callback_channels,info: info.clone(),- timestamp: Timestamp::from_cpal(input_timestamp.capture)- - capture_latency,+ timestamp: timestamp - capture_latency,};if !effective_sample_rate.settled {@@ -825,11 +1370,22 @@ impl MicrophoneFeed {);}},- move |e| {- error!("Microphone stream error: {e}");-- let _ = error_sender.send(e).is_err();- },+ microphone_stream_error_handler(error_sender, {+ #[cfg(target_os = "linux")]+ let actor = actor_ref.clone();+ #[cfg(target_os = "linux")]+ let cancel = system_stream_cancel.clone();+ move || {+ #[cfg(any(target_os = "linux", windows))]+ health.failed.store(true, Ordering::Release);+ #[cfg(target_os = "linux")]+ if pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio+ && !cancel.is_cancelled()+ {+ let _ = actor.tell(SystemInputFailed { id }).try_send();+ }+ }+ }),None,) {Ok(stream) => stream,@@ -844,12 +1400,33 @@ impl MicrophoneFeed {return;}+ #[cfg(target_os = "linux")]+ if let Some(route) = input_route+ && let Err(error) = route.apply(&input_callback_observed, &system_stream_cancel)+ {+ let _ = ready_tx.send(Err(SetInputError::BuildStream(format!(+ "Could not confirm the Linux audio input route: {error}"+ ))));+ return;+ }++ #[cfg(target_os = "linux")]+ let _ = routed_at.set(cap_timestamp::Timestamps::now());+ #[cfg(target_os = "linux")]+ if system_stream_cancel.is_cancelled() {+ return;+ }+let _ = ready_tx.send(Ok(buffer_size_frames));match done_rx.recv() {Ok(_) => debug!("Microphone actor shut down, ending stream"),Err(_) => debug!("Microphone shutdown signal channel closed, ending stream"),}+ #[cfg(windows)]+ {+ exit_health.expected = true;+ }}});@@ -1056,6 +1633,10 @@ fn latency_ms_to_frames(sample_rate: u32, milliseconds: u32) -> u32 {#[derive(Reply)]pub struct MicrophoneFeedLock {+ #[cfg(windows)]+ generation: u64,+ #[cfg(target_os = "linux")]+ source_health: RecordingSourceHealth,actor: ActorRef<MicrophoneFeed>,config: SupportedStreamConfig,audio_info: AudioInfo,@@ -1071,6 +1652,66 @@ pub struct MicrophoneFeedLock {}impl MicrophoneFeedLock {+ #[cfg(windows)]+ pub(crate) fn recording_subscription(+ &self,+ cancel: tokio_util::sync::CancellationToken,+ ) -> Arc<RecordingSubscription> {+ RecordingSubscription::new(self.generation, cancel)+ }++ #[cfg(windows)]+ pub(crate) async fn attach_recording_subscription(+ &self,+ subscription: Arc<RecordingSubscription>,+ sender: flume::Sender<MicrophoneSamples>,+ health_tx: HealthSender,+ label: String,+ ) -> anyhow::Result<()> {+ self.actor+ .ask(AttachRecordingSubscription {+ subscription,+ sender,+ health_tx,+ label,+ })+ .await+ .map_err(|error| anyhow::anyhow!("{error}"))+ }++ #[cfg(windows)]+ pub(crate) async fn detach_recording_subscription(+ &self,+ subscription: Arc<RecordingSubscription>,+ ) -> anyhow::Result<()> {+ self.actor+ .ask(DetachRecordingSubscription(subscription))+ .await+ .map_err(|error| anyhow::anyhow!("{error}"))+ }++ #[cfg(windows)]+ pub(crate) async fn reconnect_recording_subscription(+ &self,+ subscription: Arc<RecordingSubscription>,+ settings: MicrophoneDeviceSettings,+ ) -> Result<BoxFuture<'static, Result<SupportedStreamConfig, SetInputError>>, SetInputError>+ {+ self.actor+ .ask(ReconnectRecordingSubscription {+ subscription,+ label: self.device_name.clone(),+ settings,+ })+ .await+ .map_err(|error| SetInputError::BuildStream(format!("{error}")))+ }++ #[cfg(target_os = "linux")]+ pub(crate) fn source_health(&self) -> RecordingSourceHealth {+ self.source_health.clone()+ }+pub fn config(&self) -> &SupportedStreamConfig {&self.config}@@ -1154,6 +1795,10 @@ struct InputConnected {}struct LockedInputReconnected {+ #[cfg(any(target_os = "linux", windows))]+ previous_id: u32,+ #[cfg(any(target_os = "linux", windows))]+ generation: u64,id: u32,label: String,config: SupportedStreamConfig,@@ -1161,6 +1806,24 @@ struct LockedInputReconnected {done_tx: mpsc::SyncSender<()>,}+#[cfg(target_os = "linux")]+struct SystemInputFailed {+ id: u32,+}++#[cfg(target_os = "linux")]+#[derive(Clone, Copy)]+struct ReconnectSystemInput {+ id: u32,+ generation: u64,+}++#[cfg(target_os = "linux")]+struct SystemReconnectFailed {+ id: u32,+ generation: u64,+}+struct InputConnectFailed {id: u32,}@@ -1185,6 +1848,12 @@ impl StreamLogAction {}struct StreamSpawnParams {+ #[cfg(any(target_os = "linux", windows))]+ health: Arc<StreamHealth>,+ #[cfg(target_os = "linux")]+ pulse_input_role: crate::sources::screen_capture::PulseInputRole,+ #[cfg(target_os = "linux")]+ system_stream_cancel: tokio_util::sync::CancellationToken,id: u32,label: String,device: Device,@@ -1224,6 +1893,17 @@ impl Message<SetInput> for MicrophoneFeed {Result<BoxFuture<'static, Result<SupportedStreamConfig, SetInputError>>, SetInputError>;async fn handle(&mut self, msg: SetInput, ctx: &mut Context<Self, Self::Reply>) -> Self::Reply {+ self.set_input(msg, ctx.actor_ref())+ }+}++impl MicrophoneFeed {+ fn set_input(+ &mut self,+ msg: SetInput,+ actor_ref: ActorRef<Self>,+ ) -> Result<BoxFuture<'static, Result<SupportedStreamConfig, SetInputError>>, SetInputError>+ {trace!("MicrophoneFeed.SetInput('{}')", &msg.label);match &mut self.state {@@ -1238,12 +1918,38 @@ impl Message<SetInput> for MicrophoneFeed {return Err(SetInputError::DeviceNotFound);};+ #[cfg(target_os = "linux")]+ if self.pulse_input_role+ == crate::sources::screen_capture::PulseInputRole::SystemAudio+ {+ self.system_stream_cancel.cancel();+ self.system_stream_cancel = tokio_util::sync::CancellationToken::new();+ }+ #[cfg(windows)]+ {+ self.selection_generation = self.selection_generation.wrapping_add(1);+ self.recording_reconnect = None;+ }let sample_format = config.sample_format();let (stream_config, buffer_size_frames) =stream_config_with_latency(&config, Some(&label));- let actor_ref = ctx.actor_ref();+ let actor_ref = actor_ref.clone();+ #[cfg(any(target_os = "linux", windows))]+ let health = {+ let health = Arc::new(StreamHealth::new(id));+ self.stream_health+ .retain(|key, _| state.attached.as_ref().is_some_and(|v| v.id == *key));+ let _ = self.stream_health.insert(id, health.clone());+ health+ };let (ready_future, done_tx) = Self::spawn_input_stream(StreamSpawnParams {+ #[cfg(any(target_os = "linux", windows))]+ health,+ #[cfg(target_os = "linux")]+ pulse_input_role: self.pulse_input_role,+ #[cfg(target_os = "linux")]+ system_stream_cancel: self.system_stream_cancel.clone(),id,label: label.clone(),device,@@ -1318,10 +2024,43 @@ impl Message<SetInput> for MicrophoneFeed {return Err(SetInputError::Locked(FeedLockedError));}+ #[cfg(windows)]+ if let Some(pending) = &self.recording_reconnect+ && pending.generation == self.lock_generation+ && pending.previous_id == inner.id+ && pending.label == msg.label+ {+ return Ok(pending+ .ready+ .clone()+ .map(|result| result.map(|(config, _)| config))+ .boxed());+ }++ #[cfg(target_os = "linux")]+ if let Some(pending) = &self.system_reconnect+ && pending.generation == self.lock_generation+ && pending.label == msg.label+ {+ return Ok(pending+ .ready+ .clone()+ .map(|result| result.map(|(config, _)| config))+ .boxed());+ }+let label = msg.label.clone();let Some((device, config)) =Self::list_with_settings(msg.settings.as_ref()).swap_remove(&label)else {+ #[cfg(target_os = "linux")]+ if let Some(recording) = &self.recording_health {+ recording.fail_current(+ self.lock_generation,+ inner.id,+ "Requested audio device unavailable during reconnect".into(),+ );+ }return Err(SetInputError::DeviceNotFound);};@@ -1332,10 +2071,40 @@ impl Message<SetInput> for MicrophoneFeed {let new_id = self.input_id_counter;self.input_id_counter += 1;+ #[cfg(any(target_os = "linux", windows))]+ let previous_id = inner.id;+ #[cfg(any(target_os = "linux", windows))]+ let generation = self.lock_generation;+ #[cfg(target_os = "linux")]+ if self.pulse_input_role+ == crate::sources::screen_capture::PulseInputRole::SystemAudio+ {+ self.system_stream_cancel.cancel();+ self.system_stream_cancel = tokio_util::sync::CancellationToken::new();+ }let _ = inner.done_tx.send(());- let actor_ref = ctx.actor_ref();+ #[cfg(any(target_os = "linux", windows))]+ let health = {+ let health = Arc::new(StreamHealth::new(new_id));+ self.stream_health.retain(|key, _| *key == inner.id);+ let _ = self.stream_health.insert(new_id, health.clone());+ #[cfg(target_os = "linux")]+ if let Some(recording) = &self.recording_health {+ recording.begin_reconnect(generation, health.clone());+ }+ health+ };+ let actor_ref = actor_ref.clone();+ #[cfg(windows)]+ let windows_health = health.clone();let (ready_future, done_tx) = Self::spawn_input_stream(StreamSpawnParams {+ #[cfg(any(target_os = "linux", windows))]+ health,+ #[cfg(target_os = "linux")]+ pulse_input_role: self.pulse_input_role,+ #[cfg(target_os = "linux")]+ system_stream_cancel: self.system_stream_cancel.clone(),id: new_id,label: label.clone(),device,@@ -1348,7 +2117,49 @@ impl Message<SetInput> for MicrophoneFeed {dropped_message_count: self.dropped_message_count.clone(),log_action: StreamLogAction::Rebuild,});+ #[cfg(target_os = "linux")]+ let ready_future = if self.pulse_input_role+ == crate::sources::screen_capture::PulseInputRole::SystemAudio+ {+ cancellable_system_stream_ready(ready_future, self.system_stream_cancel.clone())+ } else {+ ready_future+ };+ #[cfg(target_os = "linux")]+ let ready_future = if let Some(health) = &self.recording_health {+ health.observe_ready(generation, new_id, ready_future)+ } else {+ ready_future+ };let ready = ready_future.shared();+ #[cfg(windows)]+ {+ self.accept_windows_reconnect(+ WindowsReconnect {+ selection_generation: self.selection_generation,+ generation,+ previous_id,+ id: new_id,+ label: label.clone(),+ ready: ready.clone(),+ done_tx: done_tx.clone(),+ },+ windows_health,+ );+ }++ #[cfg(target_os = "linux")]+ if self.pulse_input_role+ == crate::sources::screen_capture::PulseInputRole::SystemAudio+ {+ self.system_reconnect = Some(SystemReconnect {+ previous_id,+ id: new_id,+ generation,+ label: label.clone(),+ ready: ready.clone(),+ });+ }tokio::spawn({let ready = ready.clone();@@ -1356,16 +2167,41 @@ impl Message<SetInput> for MicrophoneFeed {let done_tx = done_tx.clone();let label = label.clone();async move {- if let Ok((config, buffer_size_frames)) = ready.await {- let _ = actor- .tell(LockedInputReconnected {- id: new_id,- label,- config,- buffer_size_frames,- done_tx,- })- .await;+ match ready.await {+ Ok((config, buffer_size_frames)) => {+ let _ = actor+ .tell(LockedInputReconnected {+ #[cfg(any(target_os = "linux", windows))]+ previous_id,+ #[cfg(any(target_os = "linux", windows))]+ generation,+ id: new_id,+ label,+ config,+ buffer_size_frames,+ done_tx,+ })+ .await;+ }+ Err(_error) => {+ #[cfg(windows)]+ let _ = actor+ .tell(WindowsReconnectFailed {+ generation,+ id: new_id,+ error: format!(+ "Requested microphone rebuild failed: {_error}"+ ),+ })+ .await;+ #[cfg(target_os = "linux")]+ let _ = actor+ .tell(SystemReconnectFailed {+ id: new_id,+ generation,+ })+ .await;+ }}}});@@ -1398,6 +2234,11 @@ impl Message<RemoveInput> for MicrophoneFeed {}};+ #[cfg(windows)]+ {+ self.selection_generation = self.selection_generation.wrapping_add(1);+ self.recording_reconnect = None;+ }state.connecting = None;if let Some(AttachedState { done_tx, .. }) = state.attached.take() {@@ -1429,9 +2270,196 @@ impl Message<RemoveSender> for MicrophoneFeed {}}-impl Message<AddRecordingSender> for MicrophoneFeed {- type Reply = ();-+#[cfg(windows)]+struct AttachRecordingSubscription {+ subscription: Arc<RecordingSubscription>,+ sender: flume::Sender<MicrophoneSamples>,+ health_tx: HealthSender,+ label: String,+}++#[cfg(windows)]+struct DetachRecordingSubscription(Arc<RecordingSubscription>);++#[cfg(windows)]+struct ReconnectRecordingSubscription {+ subscription: Arc<RecordingSubscription>,+ label: String,+ settings: MicrophoneDeviceSettings,+}++#[cfg(windows)]+struct WindowsReconnectFailed {+ generation: u64,+ id: u32,+ error: String,+}++#[cfg(windows)]+impl MicrophoneFeed {+ fn accept_windows_reconnect(&mut self, pending: WindowsReconnect, health: Arc<StreamHealth>) {+ for sender in &self.senders {+ if let Some(subscription) = &sender.subscription {+ subscription.begin_reconnect(health.clone());+ }+ }+ self.recording_reconnect = Some(pending);+ }++ fn subscription_is_current(&self, subscription: &Arc<RecordingSubscription>) -> bool {+ subscription.active()+ && subscription.error().is_none()+ && subscription.generation == self.lock_generation+ && matches!(&self.state, State::Locked { inner, token } if token.strong_count() > 0 && subscription.accepts_frame(inner.id))+ && self.senders.iter().any(|sender| {+ sender+ .subscription+ .as_ref()+ .is_some_and(|current| Arc::ptr_eq(current, subscription))+ })+ }++ fn attach_subscription(&mut self, msg: AttachRecordingSubscription) -> Result<(), String> {+ let State::Locked { inner, token } = &self.state else {+ return Err("Recording microphone lock is no longer current".into());+ };+ if !msg.subscription.active()+ || msg.subscription.generation != self.lock_generation+ || token.strong_count() == 0+ {+ return Err("Recording microphone subscription was retired".into());+ }+ let health = self+ .stream_health+ .get(&inner.id)+ .cloned()+ .ok_or("Current microphone stream health is unavailable")?;+ if health.failed.load(Ordering::Acquire) {+ return Err("Requested microphone backend is already failed".into());+ }+ let pending_health = if let Some(pending) = &self.recording_reconnect {+ if pending.selection_generation != self.selection_generation+ || pending.generation != self.lock_generation+ || pending.previous_id != inner.id+ || pending.label != inner.label+ {+ return Err("Pending microphone replacement is no longer current".into());+ }+ let health = self+ .stream_health+ .get(&pending.id)+ .cloned()+ .ok_or("Pending microphone stream health is unavailable")?;+ if health.failed.load(Ordering::Acquire) {+ return Err("Pending microphone backend is already failed".into());+ }+ Some(health)+ } else {+ None+ };+ let mut state = msg.subscription.state.lock().unwrap();+ if state.retired || msg.subscription.cancel.is_cancelled() || state.current.is_some() {+ return Err("Recording subscription already attached or retired".into());+ }+ state.current = Some(health);+ state.pending = pending_health;+ drop(state);+ let mut sender = MicrophoneFeedSender::recording(msg.sender, msg.health_tx, msg.label);+ sender.subscription = Some(msg.subscription);+ self.senders.push(sender);+ Ok(())+ }++ fn prepare_unlocked_recovery(&mut self) {+ if matches!(&self.state, State::Locked { token, .. } if token.strong_count() == 0) {+ let _ = self.state.try_as_open();+ }+ if let State::Open(state) = &mut self.state+ && state.connecting.is_none()+ && let Some(pending) = &self.recording_reconnect+ && pending.generation == self.lock_generation+ && pending.selection_generation == self.selection_generation+ && state.attached.as_ref().is_some_and(|inner| {+ inner.id == pending.previous_id && inner.label == pending.label+ })+ {+ state.connecting = Some(pending.connecting());+ }+ }+}++#[cfg(windows)]+impl Message<AttachRecordingSubscription> for MicrophoneFeed {+ type Reply = Result<(), String>;+ async fn handle(+ &mut self,+ msg: AttachRecordingSubscription,+ _: &mut Context<Self, Self::Reply>,+ ) -> Self::Reply {+ self.attach_subscription(msg)+ }+}++#[cfg(windows)]+impl Message<DetachRecordingSubscription> for MicrophoneFeed {+ type Reply = ();+ async fn handle(+ &mut self,+ msg: DetachRecordingSubscription,+ _: &mut Context<Self, Self::Reply>,+ ) {+ let _ = msg.0.retire();+ self.senders.retain(|sender| {+ !sender+ .subscription+ .as_ref()+ .is_some_and(|subscription| Arc::ptr_eq(subscription, &msg.0))+ });+ }+}++#[cfg(windows)]+impl Message<ReconnectRecordingSubscription> for MicrophoneFeed {+ type Reply =+ Result<BoxFuture<'static, Result<SupportedStreamConfig, SetInputError>>, SetInputError>;+ async fn handle(+ &mut self,+ msg: ReconnectRecordingSubscription,+ ctx: &mut Context<Self, Self::Reply>,+ ) -> Self::Reply {+ if !self.subscription_is_current(&msg.subscription) {+ return Err(SetInputError::BuildStream(+ "Recording microphone subscription is retired".into(),+ ));+ }+ self.set_input(+ SetInput {+ label: msg.label,+ settings: Some(msg.settings),+ },+ ctx.actor_ref(),+ )+ }+}++#[cfg(windows)]+impl Message<WindowsReconnectFailed> for MicrophoneFeed {+ type Reply = ();+ async fn handle(&mut self, msg: WindowsReconnectFailed, _: &mut Context<Self, Self::Reply>) {+ if self.lock_generation != msg.generation {+ return;+ }+ for sender in &self.senders {+ if let Some(subscription) = &sender.subscription {+ subscription.fail_reconnect(msg.id, msg.error.clone());+ }+ }+ }+}++impl Message<AddRecordingSender> for MicrophoneFeed {+ type Reply = ();+async fn handle(&mut self,msg: AddRecordingSender,@@ -1458,6 +2486,14 @@ impl Message<MicrophoneSamples> for MicrophoneFeed {let stall_emit_interval = Duration::from_secs(5);for (i, sender) in self.senders.iter_mut().enumerate() {+ #[cfg(windows)]+ if sender+ .subscription+ .as_ref()+ .is_some_and(|subscription| !subscription.accepts_frame(msg.stream_id))+ {+ continue;+ }match sender.sender.try_send(msg.clone()) {Ok(()) => sender.reset_stall(),Err(TrySendError::Full(_)) => {@@ -1510,6 +2546,8 @@ impl Message<Lock> for MicrophoneFeed {async fn handle(&mut self, _: Lock, ctx: &mut Context<Self, Self::Reply>) -> Self::Reply {trace!("MicrophoneFeed.Lock");+ #[cfg(windows)]+ self.prepare_unlocked_recovery();let state = self.state.try_as_open()?;@@ -1529,7 +2567,23 @@ impl Message<Lock> for MicrophoneFeed {let device_name = attached.label.clone();self.lock_generation += 1;+ #[cfg(windows)]+ {+ self.recording_reconnect = None;+ }let generation = self.lock_generation;+ #[cfg(target_os = "linux")]+ let source_health = RecordingSourceHealth::new(+ generation,+ self.stream_health+ .get(&attached.id)+ .cloned()+ .unwrap_or_else(|| Arc::new(StreamHealth::new(attached.id))),+ );+ #[cfg(target_os = "linux")]+ {+ self.recording_health = Some(source_health.clone());+ }let token = Arc::new(());let token_weak = Arc::downgrade(&token);@@ -1555,6 +2609,10 @@ impl Message<Lock> for MicrophoneFeed {.with_wireless_transport(latency_info.transport.is_wireless());Ok(MicrophoneFeedLock {+ #[cfg(windows)]+ generation,+ #[cfg(target_os = "linux")]+ source_health,audio_info,actor: ctx.actor_ref(),config,@@ -1580,7 +2638,7 @@ impl Message<GetDroppedMessageCount> for MicrophoneFeed {}impl Message<InputConnected> for MicrophoneFeed {- type Reply = Result<(), FeedLockedError>;+ type Reply = ();async fn handle(&mut self,@@ -1589,16 +2647,17 @@ impl Message<InputConnected> for MicrophoneFeed {) -> Self::Reply {trace!("MicrophoneFeed.InputConnected");- let state = self.state.try_as_open()?;+ // Lock can consume this connection before the notification reaches the mailbox.+ let Ok(state) = self.state.try_as_open() else {+ return;+ };state.handle_input_connected(msg);-- Ok(())}}impl Message<InputConnectFailed> for MicrophoneFeed {- type Reply = Result<(), FeedLockedError>;+ type Reply = ();async fn handle(&mut self,@@ -1607,15 +2666,15 @@ impl Message<InputConnectFailed> for MicrophoneFeed {) -> Self::Reply {trace!("MicrophoneFeed.InputConnectFailed");- let state = self.state.try_as_open()?;+ let Ok(state) = self.state.try_as_open() else {+ return;+ };if let Some(connecting) = &state.connecting&& connecting.id == msg.id{state.connecting = None;}-- Ok(())}}@@ -1627,9 +2686,116 @@ impl Message<LockedInputReconnected> for MicrophoneFeed {msg: LockedInputReconnected,_: &mut Context<Self, Self::Reply>,) -> Self::Reply {+ self.handle_locked_input_reconnected(msg);+ }+}++#[cfg(any(windows, test))]+fn recording_reconnect_is_current(+ current_generation: u64,+ pending: Option<(u64, u32, u32)>,+ current: Option<(u32, &str, bool)>,+ generation: u64,+ previous_id: u32,+ id: u32,+ label: &str,+) -> bool {+ current_generation == generation+ && pending == Some((generation, previous_id, id))+ && current.is_some_and(|(current_id, current_label, locked)| {+ locked && current_id == previous_id && current_label == label+ })+}++impl MicrophoneFeed {+ fn handle_locked_input_reconnected(&mut self, msg: LockedInputReconnected) {+ #[cfg(windows)]+ {+ let current = match &self.state {+ State::Locked { inner, token } => {+ Some((inner.id, inner.label.as_str(), token.strong_count() > 0))+ }+ State::Open(state) => state.attached.as_ref().map(|inner| {+ (+ inner.id,+ inner.label.as_str(),+ state+ .connecting+ .as_ref()+ .is_some_and(|pending| pending.id == msg.id),+ )+ }),+ };+ if !recording_reconnect_is_current(+ self.lock_generation,+ self.recording_reconnect+ .as_ref()+ .filter(|pending| pending.selection_generation == self.selection_generation)+ .map(WindowsReconnect::identity),+ current,+ msg.generation,+ msg.previous_id,+ msg.id,+ &msg.label,+ ) {+ return;+ }+ self.recording_reconnect = None;+ for sender in &self.senders {+ if let Some(subscription) = &sender.subscription {+ subscription.commit_reconnect(msg.id);+ }+ }+ if let State::Open(state) = &mut self.state {+ state.handle_input_connected(InputConnected {+ id: msg.id,+ label: msg.label,+ config: msg.config,+ buffer_size_frames: msg.buffer_size_frames,+ done_tx: msg.done_tx,+ });+ return;+ }+ }+ #[cfg(target_os = "linux")]+ if self.lock_generation != msg.generation+ || !matches!(&self.state, State::Locked { inner, token }+ if inner.id == msg.previous_id && inner.label == msg.label && token.strong_count() > 0)+ || self+ .recording_health+ .as_ref()+ .is_some_and(|health| !health.expects_reconnect(msg.generation, msg.id))+ {+ return;+ }+ #[cfg(target_os = "linux")]+ if self.pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio {+ let current = !self.system_stream_cancel.is_cancelled()+ && matches!(&self.state, State::Locked { inner, token }+ if token.strong_count() > 0 && inner.id == msg.previous_id && inner.label == msg.label);+ if !current+ || self.lock_generation != msg.generation+ || !self.system_reconnect.as_ref().is_some_and(|pending| {+ pending.previous_id == msg.previous_id+ && pending.id == msg.id+ && pending.generation == msg.generation+ })+ {+ return;+ }+ self.system_reconnect = None;+ self.system_failed_input = None;+ }if let State::Locked { inner, .. } = &mut self.state&& inner.label == msg.label{+ #[cfg(target_os = "linux")]+ if msg.generation == self.lock_generation+ && inner.id == msg.previous_id+ && let Some(recording) = &self.recording_health+ {+ recording.commit_reconnect(msg.generation, msg.id);+ }inner.id = msg.id;inner.config = msg.config;inner.buffer_size_frames = msg.buffer_size_frames;@@ -1638,6 +2804,131 @@ impl Message<LockedInputReconnected> for MicrophoneFeed {}}+#[cfg(target_os = "linux")]+impl MicrophoneFeed {+ fn take_system_error_reconnect(&mut self, id: u32) -> Option<ReconnectSystemInput> {+ if self.pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio+ && self.system_reconnect.as_ref().is_some_and(|pending| {+ pending.id == id && pending.generation == self.lock_generation+ })+ {+ if let Some(recording) = &self.recording_health {+ recording.fail_reconnect(+ self.lock_generation,+ id,+ "Replacement audio stream failed before acceptance".into(),+ );+ }+ self.system_failed_input = Some(id);+ self.system_stream_cancel.cancel();+ self.system_reconnect = None;+ return None;+ }+ if self.pulse_input_role != crate::sources::screen_capture::PulseInputRole::SystemAudio+ || self.system_stream_cancel.is_cancelled()+ || self.system_failed_input == Some(id)+ || self.system_reconnect.is_some()+ {+ return None;+ }+ let State::Locked { inner, token } = &self.state else {+ return None;+ };+ if inner.id != id || token.strong_count() == 0 {+ return None;+ }+ self.system_failed_input = Some(id);+ Some(ReconnectSystemInput {+ id,+ generation: self.lock_generation,+ })+ }++ fn system_reconnect_request_is_current(&self, msg: ReconnectSystemInput) -> bool {+ self.pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio+ && self.lock_generation == msg.generation+ && !self.system_stream_cancel.is_cancelled()+ && matches!(&self.state, State::Locked { inner, token }+ if inner.id == msg.id && token.strong_count() > 0)+ }+}++#[cfg(target_os = "linux")]+impl Message<SystemInputFailed> for MicrophoneFeed {+ type Reply = ();++ async fn handle(&mut self, msg: SystemInputFailed, ctx: &mut Context<Self, Self::Reply>) {+ let Some(request) = self.take_system_error_reconnect(msg.id) else {+ return;+ };+ let actor = ctx.actor_ref();+ tokio::spawn(async move {+ match actor.ask(request).await {+ Ok(ready) => match ready.await {+ Ok(_) => info!("System audio recovered after native stream error"),+ Err(error) => warn!(%error, "System audio error recovery did not complete"),+ },+ Err(error) => warn!(%error, "System audio error recovery could not start"),+ }+ });+ }+}++#[cfg(target_os = "linux")]+impl Message<ReconnectSystemInput> for MicrophoneFeed {+ type Reply =+ Result<BoxFuture<'static, Result<SupportedStreamConfig, SetInputError>>, SetInputError>;++ async fn handle(+ &mut self,+ msg: ReconnectSystemInput,+ ctx: &mut Context<Self, Self::Reply>,+ ) -> Self::Reply {+ if !self.system_reconnect_request_is_current(msg) {+ return Err(SetInputError::BuildStream(+ "System audio recovery no longer belongs to the active input".into(),+ ));+ }+ let State::Locked { inner, .. } = &self.state else {+ return Err(SetInputError::Locked(FeedLockedError));+ };+ let request = SetInput {+ label: inner.label.clone(),+ settings: Some(MicrophoneDeviceSettings {+ sample_rate: Some(inner.config.sample_rate().0),+ channels: Some(inner.config.channels()),+ }),+ };+ info!(+ stream_id = msg.id,+ "Recovering system audio after native stream error"+ );+ self.set_input(request, ctx.actor_ref())+ }+}++#[cfg(target_os = "linux")]+impl Message<SystemReconnectFailed> for MicrophoneFeed {+ type Reply = ();++ async fn handle(&mut self, msg: SystemReconnectFailed, _: &mut Context<Self, Self::Reply>) {+ if let Some(recording) = &self.recording_health {+ recording.fail_reconnect(+ msg.generation,+ msg.id,+ "Requested audio stream rebuild failed".into(),+ );+ }+ if self+ .system_reconnect+ .as_ref()+ .is_some_and(|pending| pending.id == msg.id && pending.generation == msg.generation)+ {+ self.system_reconnect = None;+ }+ }+}+impl Message<Unlock> for MicrophoneFeed {type Reply = ();@@ -1652,6 +2943,11 @@ impl Message<Unlock> for MicrophoneFeed {return;}+ #[cfg(target_os = "linux")]+ if self.pulse_input_role == crate::sources::screen_capture::PulseInputRole::SystemAudio {+ self.system_stream_cancel.cancel();+ self.system_reconnect = None;+ }replace_with_or_abort(&mut self.state, |state| {if let State::Locked { inner, .. } = state {State::Open(OpenState {@@ -1662,6 +2958,8 @@ impl Message<Unlock> for MicrophoneFeed {state}});+ #[cfg(windows)]+ self.prepare_unlocked_recovery();}}@@ -1669,6 +2967,446 @@ impl Message<Unlock> for MicrophoneFeed {mod tests {use super::*;+ #[test]+ fn repeated_stream_errors_are_coalesced_while_a_notification_is_pending() {+ let (sender, receiver) = flume::unbounded();+ let mut report = microphone_stream_error_handler(sender, || {});+ for _ in 0..1024 {+ report(StreamError::DeviceNotAvailable);+ }+ assert_eq!(receiver.len(), 1);+ }++ #[test]+ fn stream_error_consumers_can_receive_a_later_recovery_attempt() {+ let (sender, receiver) = flume::bounded(1);+ let mut report = microphone_stream_error_handler(sender, || {});+ report(StreamError::DeviceNotAvailable);+ assert!(receiver.try_recv().is_ok());+ report(StreamError::DeviceNotAvailable);+ assert!(receiver.try_recv().is_ok());+ }++ #[test]+ fn stream_error_callback_never_waits_for_a_receiver() {+ let (sender, receiver) = flume::bounded(0);+ let mut report = microphone_stream_error_handler(sender, || {});+ report(StreamError::DeviceNotAvailable);+ assert!(receiver.is_empty());+ drop(receiver);+ report(StreamError::DeviceNotAvailable);+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn system_audio_feed_retains_its_input_role() {+ let (sender, _receiver) = flume::bounded(1);+ let microphone = MicrophoneFeed::new(sender.clone());+ let system_audio = MicrophoneFeed::new_system_audio(sender);+ assert_eq!(+ microphone.pulse_input_role,+ crate::sources::screen_capture::PulseInputRole::Microphone+ );+ assert_eq!(+ system_audio.pulse_input_role,+ crate::sources::screen_capture::PulseInputRole::SystemAudio+ );+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn routed_audio_waits_until_the_route_is_confirmed() {+ let received = Instant::now();+ assert!(!audio_follows_confirmed_route(+ received,+ Some(Duration::ZERO),+ true,+ None+ ));+ assert!(audio_follows_confirmed_route(received, None, false, None));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn routed_audio_rejects_old_samples_delivered_after_the_route_changed() {+ let routed_at = cap_timestamp::Timestamps::now();+ let received = routed_at.instant() + Duration::from_millis(20);+ assert!(!audio_follows_confirmed_route(+ received,+ Some(Duration::from_millis(40)),+ true,+ Some(routed_at)+ ));+ assert!(audio_follows_confirmed_route(+ received,+ Some(Duration::from_millis(10)),+ true,+ Some(routed_at)+ ));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn routed_audio_rejects_an_unknown_or_unrepresentable_capture_delay() {+ let routed_at = cap_timestamp::Timestamps::now();+ let received = routed_at.instant() + Duration::from_millis(20);+ assert!(!audio_follows_confirmed_route(+ received,+ None,+ true,+ Some(routed_at)+ ));+ assert!(!audio_follows_confirmed_route(+ received,+ Some(Duration::MAX),+ true,+ Some(routed_at)+ ));+ }++ #[cfg(target_os = "linux")]+ fn system_recovery_fixture() -> (MicrophoneFeed, Arc<()>, SupportedStreamConfig) {+ let (sender, _receiver) = flume::bounded(1);+ let mut feed = MicrophoneFeed::new_system_audio(sender);+ let token = Arc::new(());+ let config = SupportedStreamConfig::new(+ 1,+ cpal::SampleRate(48_000),+ cpal::SupportedBufferSize::Unknown,+ SampleFormat::F32,+ );+ let (done_tx, _done_rx) = mpsc::sync_channel(1);+ feed.lock_generation = 11;+ feed.input_id_counter = 8;+ feed.state = State::Locked {+ inner: AttachedState {+ id: 7,+ label: "synthetic-system".into(),+ config: config.clone(),+ buffer_size_frames: None,+ done_tx,+ },+ token: Arc::downgrade(&token),+ };+ (feed, token, config)+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn system_error_schedules_one_reconnect_and_ignores_stale_errors() {+ let (mut feed, _token, _) = system_recovery_fixture();+ assert!(feed.take_system_error_reconnect(6).is_none());+ let request = feed.take_system_error_reconnect(7).unwrap();+ assert_eq!((request.id, request.generation), (7, 11));+ assert!(feed.take_system_error_reconnect(7).is_none());+ assert!(feed.system_reconnect_request_is_current(request));+ feed.lock_generation += 1;+ assert!(!feed.system_reconnect_request_is_current(request));+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn microphone_errors_do_not_enter_system_audio_recovery() {+ let (mut feed, _token, _) = system_recovery_fixture();+ feed.pulse_input_role = crate::sources::screen_capture::PulseInputRole::Microphone;+ assert!(feed.take_system_error_reconnect(7).is_none());+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn watchdog_joins_pending_system_reconnect_without_reopening_device() {+ let (mut feed, _token, config) = system_recovery_fixture();+ let (ready_tx, ready_rx) = oneshot::channel();+ feed.system_reconnect = Some(SystemReconnect {+ previous_id: 7,+ id: 8,+ generation: 11,+ label: "synthetic-system".into(),+ ready: async move { ready_rx.await.unwrap() }.boxed().shared(),+ });+ let actor = MicrophoneFeed::spawn(feed);+ let first = actor+ .ask(SetInput {+ label: "synthetic-system".into(),+ settings: None,+ })+ .await+ .unwrap();+ let second = actor+ .ask(SetInput {+ label: "synthetic-system".into(),+ settings: None,+ })+ .await+ .unwrap();+ ready_tx.send(Ok((config, None))).unwrap();+ assert_eq!(first.await.unwrap().sample_rate(), cpal::SampleRate(48_000));+ assert_eq!(+ second.await.unwrap().sample_rate(),+ cpal::SampleRate(48_000)+ );+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn stale_system_reconnect_completion_cannot_replace_current_input() {+ let (mut feed, _token, config) = system_recovery_fixture();+ feed.system_reconnect = Some(SystemReconnect {+ previous_id: 7,+ id: 8,+ generation: 11,+ label: "synthetic-system".into(),+ ready: futures::future::ready(Ok((config.clone(), None)))+ .boxed()+ .shared(),+ });+ for (previous_id, generation, id) in [(6, 11, 8), (7, 10, 8), (7, 11, 9)] {+ let (done_tx, _done_rx) = mpsc::sync_channel(1);+ feed.handle_locked_input_reconnected(LockedInputReconnected {+ previous_id,+ generation,+ id,+ label: "synthetic-system".into(),+ config: config.clone(),+ buffer_size_frames: None,+ done_tx,+ });+ assert!(matches!(&feed.state, State::Locked { inner, .. } if inner.id==7));+ assert!(feed.system_reconnect.is_some());+ }+ let (done_tx, _done_rx) = mpsc::sync_channel(1);+ feed.handle_locked_input_reconnected(LockedInputReconnected {+ previous_id: 7,+ generation: 11,+ id: 8,+ label: "synthetic-system".into(),+ config,+ buffer_size_frames: None,+ done_tx,+ });+ assert!(matches!(&feed.state, State::Locked { inner, .. } if inner.id==8));+ assert!(feed.system_reconnect.is_none());+ assert!(feed.take_system_error_reconnect(7).is_none());+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn system_unlock_cancels_pending_rebuild_and_rejects_late_completion() {+ let (mut feed, token, config) = system_recovery_fixture();+ let cancel = feed.system_stream_cancel.clone();+ let ready =+ cancellable_system_stream_ready(futures::future::pending().boxed(), cancel.clone())+ .shared();+ feed.system_reconnect = Some(SystemReconnect {+ previous_id: 7,+ id: 8,+ generation: 11,+ label: "synthetic-system".into(),+ ready: ready.clone(),+ });+ let actor = MicrophoneFeed::spawn(feed);+ drop(token);+ actor.tell(Unlock { generation: 11 }).await.unwrap();+ actor.ask(GetDroppedMessageCount).await.unwrap();+ assert!(cancel.is_cancelled());+ assert!(+ tokio::time::timeout(Duration::from_millis(100), ready)+ .await+ .unwrap()+ .is_err()+ );+ let (done_tx, done_rx) = mpsc::sync_channel(1);+ actor+ .tell(LockedInputReconnected {+ previous_id: 7,+ generation: 11,+ id: 8,+ label: "synthetic-system".into(),+ config,+ buffer_size_frames: None,+ done_tx,+ })+ .await+ .unwrap();+ actor.ask(GetDroppedMessageCount).await.unwrap();+ assert!(matches!(+ done_rx.try_recv(),+ Err(mpsc::TryRecvError::Disconnected)+ ));+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn pending_system_stream_error_cancels_ready_and_rejects_completion() {+ let (mut feed, _token, config) = system_recovery_fixture();+ let cancel = feed.system_stream_cancel.clone();+ let ready =+ cancellable_system_stream_ready(futures::future::pending().boxed(), cancel.clone())+ .shared();+ feed.system_reconnect = Some(SystemReconnect {+ previous_id: 7,+ id: 8,+ generation: 11,+ label: "synthetic-system".into(),+ ready: ready.clone(),+ });+ assert!(feed.take_system_error_reconnect(6).is_none());+ assert!(!cancel.is_cancelled());+ assert!(feed.take_system_error_reconnect(8).is_none());+ assert!(cancel.is_cancelled());+ assert!(+ tokio::time::timeout(Duration::from_millis(100), ready)+ .await+ .unwrap()+ .is_err()+ );+ let (done_tx, done_rx) = mpsc::sync_channel(1);+ feed.handle_locked_input_reconnected(LockedInputReconnected {+ previous_id: 7,+ generation: 11,+ id: 8,+ label: "synthetic-system".into(),+ config,+ buffer_size_frames: None,+ done_tx,+ });+ assert!(matches!(&feed.state, State::Locked { inner, .. } if inner.id == 7));+ assert!(matches!(+ done_rx.try_recv(),+ Err(mpsc::TryRecvError::Disconnected)+ ));+ assert!(feed.take_system_error_reconnect(8).is_none());+ assert!(feed.take_system_error_reconnect(7).is_none());+ }++ #[cfg(target_os = "linux")]+ #[tokio::test]+ async fn fault_after_ready_success_retires_cached_reconnect_before_completion() {+ let (mut feed, _token, config) = system_recovery_fixture();+ let ready = futures::future::ready(Ok((config.clone(), None)))+ .boxed()+ .shared();+ ready.clone().await.unwrap();+ feed.system_reconnect = Some(SystemReconnect {+ previous_id: 7,+ id: 8,+ generation: 11,+ label: "synthetic-system".into(),+ ready,+ });+ assert!(feed.take_system_error_reconnect(8).is_none());+ assert!(feed.system_reconnect.is_none());+ let (done_tx, done_rx) = mpsc::sync_channel(1);+ feed.handle_locked_input_reconnected(LockedInputReconnected {+ previous_id: 7,+ generation: 11,+ id: 8,+ label: "synthetic-system".into(),+ config,+ buffer_size_frames: None,+ done_tx,+ });+ assert!(matches!(&feed.state, State::Locked { inner, .. } if inner.id == 7));+ assert!(feed.system_reconnect.is_none());+ assert!(matches!(+ done_rx.try_recv(),+ Err(mpsc::TryRecvError::Disconnected)+ ));+ assert!(feed.take_system_error_reconnect(8).is_none());+ }++ #[cfg(target_os = "linux")]+ #[test]+ fn dropping_system_feed_cancels_stream_and_recovery_work() {+ let (feed, _token, _) = system_recovery_fixture();+ let cancel = feed.system_stream_cancel.clone();+ drop(feed);+ assert!(cancel.is_cancelled());+ }++ #[test]+ fn native_error_notifies_recovery_only_once_per_stream() {+ let (sender, _receiver) = flume::bounded(1);+ let calls = Arc::new(AtomicU64::new(0));+ let observed = calls.clone();+ let mut handler = microphone_stream_error_handler(sender, move || {+ observed.fetch_add(1, Ordering::Relaxed);+ });+ for _ in 0..1024 {+ handler(StreamError::DeviceNotAvailable);+ }+ assert_eq!(calls.load(Ordering::Relaxed), 1);+ }++ async fn locked_test_microphone()+ -> (ActorRef<MicrophoneFeed>, MicrophoneFeedLock, InputConnected) {+ let (error_tx, _error_rx) = flume::bounded(1);+ let (done_tx, _done_rx) = mpsc::sync_channel(1);+ let config = SupportedStreamConfig::new(+ 1,+ cpal::SampleRate(48_000),+ cpal::SupportedBufferSize::Unknown,+ SampleFormat::F32,+ );+ let connection = InputConnected {+ id: 1,+ label: "test microphone".to_string(),+ config: config.clone(),+ buffer_size_frames: Some(480),+ done_tx: done_tx.clone(),+ };+ let mut microphone = MicrophoneFeed::new(error_tx);+ microphone.state = State::Open(OpenState {+ connecting: Some(ConnectingState {+ id: 1,+ ready: futures::future::ready(Ok(InputConnected {+ id: 1,+ label: "test microphone".to_string(),+ config,+ buffer_size_frames: Some(480),+ done_tx,+ }))+ .boxed(),+ }),+ attached: None,+ });+ let feed = MicrophoneFeed::spawn(microphone);+ let lock = feed.ask(Lock).await.unwrap();+ (feed, lock, connection)+ }++ #[tokio::test]+ async fn microphone_late_connection_notification_keeps_locked_feed_alive() {+ let (feed, lock, connection) = locked_test_microphone().await;+ feed.tell(connection).await.unwrap();+ let result = feed.ask(GetDroppedMessageCount).await;+ drop(lock);+ feed.kill();+ feed.wait_for_stop().await;+ assert!(+ result.is_ok(),+ "late connection notification stopped the feed: {result:?}"+ );+ }++ #[tokio::test]+ async fn microphone_late_failure_notification_keeps_locked_feed_alive() {+ let (feed, lock, _connection) = locked_test_microphone().await;+ feed.tell(InputConnectFailed { id: 1 }).await.unwrap();+ let result = feed.ask(GetDroppedMessageCount).await;+ drop(lock);+ feed.kill();+ feed.wait_for_stop().await;+ assert!(+ result.is_ok(),+ "late failure notification stopped the feed: {result:?}"+ );+ }+fn config_range(rate: u32, channels: u16) -> SupportedStreamConfigRange {SupportedStreamConfigRange::new(channels,@@ -1984,3 +3722,721 @@ mod tests {}}}++#[cfg(all(test, target_os = "linux"))]+mod required_recording_health_tests {+ use super::*;++ fn microphone_fixture() -> (+ MicrophoneFeed,+ RecordingSourceHealth,+ SupportedStreamConfig,+ Arc<()>,+ ) {+ let (errors, _) = flume::bounded(1);+ let mut feed = MicrophoneFeed::new(errors);+ let health = RecordingSourceHealth::new(3, Arc::new(StreamHealth::new(7)));+ let config = SupportedStreamConfig::new(+ 1,+ cpal::SampleRate(48_000),+ cpal::SupportedBufferSize::Unknown,+ SampleFormat::F32,+ );+ let token = Arc::new(());+ let (done_tx, _) = mpsc::sync_channel(1);+ feed.lock_generation = 3;+ feed.recording_health = Some(health.clone());+ feed.state = State::Locked {+ inner: AttachedState {+ id: 7,+ label: "synthetic-microphone".into(),+ config: config.clone(),+ buffer_size_frames: None,+ done_tx,+ },+ token: Arc::downgrade(&token),+ };+ (feed, health, config, token)+ }++ fn replacement(+ config: SupportedStreamConfig,+ generation: u64,+ previous_id: u32,+ id: u32,+ ) -> LockedInputReconnected {+ let (done_tx, _) = mpsc::sync_channel(1);+ LockedInputReconnected {+ previous_id,+ generation,+ id,+ label: "synthetic-microphone".into(),+ config,+ buffer_size_frames: None,+ done_tx,+ }+ }++ #[test]+ fn older_microphone_rebuild_cannot_split_actual_input_from_current_health() {+ let (mut feed, health, config, _token) = microphone_fixture();+ health.begin_reconnect(3, Arc::new(StreamHealth::new(8)));+ health.begin_reconnect(3, Arc::new(StreamHealth::new(9)));+ feed.handle_locked_input_reconnected(replacement(config.clone(), 3, 7, 8));+ assert!(matches!(&feed.state, State::Locked { inner, .. } if inner.id == 7));+ assert!(health.frame_is_current(7));+ feed.handle_locked_input_reconnected(replacement(config, 3, 7, 9));+ assert!(matches!(&feed.state, State::Locked { inner, .. } if inner.id == 9));+ assert!(health.frame_is_current(9));+ assert!(!health.frame_is_current(8));+ }++ #[test]+ fn old_lock_or_previous_input_completion_cannot_replace_current_microphone() {+ let (mut feed, health, config, _token) = microphone_fixture();+ health.begin_reconnect(3, Arc::new(StreamHealth::new(8)));+ feed.handle_locked_input_reconnected(replacement(config.clone(), 2, 7, 8));+ feed.handle_locked_input_reconnected(replacement(config, 3, 6, 8));+ assert!(matches!(&feed.state, State::Locked { inner, .. } if inner.id == 7));+ assert!(health.frame_is_current(7));+ assert!(health.expects_reconnect(3, 8));+ }++ #[test]+ fn actual_backend_callback_requires_replacement_frame_before_success() {+ let stream = Arc::new(StreamHealth::new(7));+ let health = RecordingSourceHealth::new(3, stream.clone());+ let (tx, _rx) = flume::bounded(1);+ let mut callback = microphone_stream_error_handler(tx, move || {+ stream.failed.store(true, Ordering::Release);+ });+ callback(StreamError::DeviceNotAvailable);+ assert!(health.terminal_error().is_none());+ assert!(health.stop_error().is_some());+ let replacement = Arc::new(StreamHealth::new(8));+ health.begin_reconnect(3, replacement);+ health.commit_reconnect(3, 8);+ assert!(health.stop_error().is_some());+ assert!(!health.frame_is_current(7));+ health.accepted_frame(7);+ assert!(health.stop_error().is_some());+ assert!(health.frame_is_current(8));+ health.accepted_frame(8);+ assert!(health.stop_error().is_none());+ }++ #[tokio::test]+ async fn pulse_loss_failed_rebuild_is_retained_before_ready_reply() {+ let stream = Arc::new(StreamHealth::new(0));+ let health = RecordingSourceHealth::new(1, stream.clone());+ stream.failed.store(true, Ordering::Release);+ health.begin_reconnect(1, Arc::new(StreamHealth::new(1)));+ let (tx, rx) = tokio::sync::oneshot::channel();+ let ready = health.observe_ready(+ 1,+ 1,+ async move {+ rx.await.unwrap();+ Err(SetInputError::DeviceNotFound)+ }+ .boxed(),+ );+ assert!(health.terminal_error().is_none());+ tx.send(()).unwrap();+ assert!(ready.await.is_err());+ assert!(health.terminal_error().unwrap().contains("DeviceNotFound"));+ health.commit_reconnect(1, 1);+ health.accepted_frame(1);+ assert!(health.stop_error().is_some());+ }++ #[test]+ fn discovery_failure_is_sticky_without_a_silence_threshold() {+ let health = RecordingSourceHealth::test_healthy(7);+ health.fail_current(1, 7, "DeviceNotFound".into());+ health.begin_reconnect(1, Arc::new(StreamHealth::new(8)));+ health.commit_reconnect(1, 8);+ health.accepted_frame(8);+ assert_eq!(health.stop_error().as_deref(), Some("DeviceNotFound"));+ }++ #[test]+ fn stale_generation_and_previous_rebuild_cannot_poison_current_stream() {+ let health = RecordingSourceHealth::new(3, Arc::new(StreamHealth::new(7)));+ health.begin_reconnect(3, Arc::new(StreamHealth::new(8)));+ health.fail_current(2, 7, "stale lock".into());+ health.fail_reconnect(2, 8, "stale lock".into());+ health.fail_reconnect(3, 6, "stale rebuild".into());+ health.commit_reconnect(3, 8);+ health.fail_current(3, 7, "retired stream".into());+ health.fail_reconnect(3, 8, "late old ready error".into());+ assert!(health.stop_error().is_none());+ assert!(health.frame_is_current(8));+ assert!(!health.frame_is_current(7));+ }++ #[test]+ fn failed_pending_stream_cannot_be_committed_as_healthy() {+ let health = RecordingSourceHealth::test_healthy(7);+ let replacement = Arc::new(StreamHealth::new(8));+ health.begin_reconnect(1, replacement.clone());+ replacement.failed.store(true, Ordering::Release);+ health.commit_reconnect(1, 8);+ health.accepted_frame(8);+ assert!(health.terminal_error().is_some());+ }++ #[test]+ fn failed_current_callbacks_cannot_wait_forever_for_a_receive_timeout() {+ let stream = Arc::new(StreamHealth::new(7));+ let health = RecordingSourceHealth::new(3, stream.clone());+ let (tx, _rx) = flume::bounded(1);+ let mut callback = microphone_stream_error_handler(tx, move || {+ stream.failed.store(true, Ordering::Release);+ });+ callback(StreamError::DeviceNotAvailable);+ assert!(health.terminal_error().is_none());+ for _ in 0..128 {+ assert!(!health.frame_is_current(7));+ }+ let error = health.terminal_error().unwrap();+ assert!(error.contains("failed while continuing to deliver samples"));+ assert_eq!(health.stop_error(), Some(error));+ }++ #[test]+ fn failed_retired_callbacks_do_not_poison_a_healthy_current_replacement() {+ let health = RecordingSourceHealth::new(3, Arc::new(StreamHealth::new(7)));+ health.test_backend_failure();+ health.begin_reconnect(3, Arc::new(StreamHealth::new(8)));+ health.commit_reconnect(3, 8);+ for _ in 0..128 {+ assert!(!health.frame_is_current(7));+ }+ assert!(health.terminal_error().is_none());+ assert!(health.frame_is_current(8));+ health.accepted_frame(8);+ assert!(health.stop_error().is_none());+ }++ #[test]+ fn callback_failure_is_not_cleared_by_stale_or_late_rebuild_completion() {+ let (mut feed, health, config, _token) = microphone_fixture();+ health.begin_reconnect(3, Arc::new(StreamHealth::new(8)));+ health.test_backend_failure();+ assert!(!health.frame_is_current(7));+ let error = health.terminal_error();+ for generation in [2, 3] {+ feed.handle_locked_input_reconnected(replacement(config.clone(), generation, 7, 8));+ health.accepted_frame(8);+ assert!(matches!(&feed.state, State::Locked { inner, .. } if inner.id == 7));+ assert!(!health.frame_is_current(8));+ assert_eq!(health.terminal_error(), error);+ assert_eq!(health.stop_error(), error);+ }+ }++ #[test]+ fn healthy_silence_and_ready_without_backend_error_remain_successful() {+ let health = RecordingSourceHealth::test_healthy(7);+ assert!(health.stop_error().is_none());+ health.begin_reconnect(1, Arc::new(StreamHealth::new(8)));+ assert!(health.stop_error().is_none());+ health.commit_reconnect(1, 8);+ health.accepted_frame(8);+ assert!(health.stop_error().is_none());+ }+}++#[cfg(test)]+mod recording_reconnect_ownership_tests {+ use super::recording_reconnect_is_current;++ #[test]+ fn current_requested_reconnect_can_commit() {+ assert!(recording_reconnect_is_current(+ 4,+ Some((4, 10, 11)),+ Some((10, "requested", true)),+ 4,+ 10,+ 11,+ "requested"+ ));+ }++ #[test]+ fn stale_or_superseded_reconnect_cannot_commit() {+ for (generation, previous, replacement) in [(3, 10, 11), (4, 9, 11), (4, 10, 12)] {+ assert!(!recording_reconnect_is_current(+ 4,+ Some((4, 10, 11)),+ Some((10, "requested", true)),+ generation,+ previous,+ replacement,+ "requested"+ ));+ }+ assert!(!recording_reconnect_is_current(+ 4,+ Some((4, 10, 12)),+ Some((10, "requested", true)),+ 4,+ 10,+ 11,+ "requested"+ ));+ }++ #[test]+ fn unlocked_or_different_device_reconnect_cannot_commit() {+ for current in [+ None,+ Some((10, "requested", false)),+ Some((10, "different", true)),+ Some((11, "requested", true)),+ ] {+ assert!(!recording_reconnect_is_current(+ 4,+ Some((4, 10, 11)),+ current,+ 4,+ 10,+ 11,+ "requested"+ ));+ }+ assert!(!recording_reconnect_is_current(+ 4,+ None,+ Some((10, "requested", true)),+ 4,+ 10,+ 11,+ "requested"+ ));+ }+}++#[cfg(all(test, windows))]+mod recording_subscription_tests {+ use super::*;+ use crate::output_pipeline::{+ AudioFrame, AudioMuxer, Muxer, OutputPipeline, TaskPool, new_health_channel,+ };++ fn config() -> SupportedStreamConfig {+ SupportedStreamConfig::new(+ 1,+ cpal::SampleRate(48_000),+ cpal::SupportedBufferSize::Unknown,+ SampleFormat::F32,+ )+ }++ struct SharedFeedProbe {+ native: mpsc::Receiver<()>,+ _preview: flume::Receiver<MicrophoneSamples>,+ }++ impl SharedFeedProbe {+ fn try_recv(&self) -> Result<(), mpsc::TryRecvError> {+ self.native.try_recv()+ }+ }++ fn fixture() -> (MicrophoneFeed, Arc<()>, SharedFeedProbe) {+ let (errors, _errors) = flume::bounded(1);+ let mut feed = MicrophoneFeed::new(errors);+ let token = Arc::new(());+ let (done_tx, done_rx) = mpsc::sync_channel(1);+ feed.lock_generation = 3;+ feed.input_id_counter = 8;+ feed.state = State::Locked {+ inner: AttachedState {+ id: 7,+ label: "requested".into(),+ config: config(),+ buffer_size_frames: None,+ done_tx,+ },+ token: Arc::downgrade(&token),+ };+ let _ = feed.stream_health.insert(7, Arc::new(StreamHealth::new(7)));+ let (preview, preview_rx) = flume::bounded(4);+ feed.senders.push(MicrophoneFeedSender::new(preview));+ (+ feed,+ token,+ SharedFeedProbe {+ native: done_rx,+ _preview: preview_rx,+ },+ )+ }++ fn attach(subscription: Arc<RecordingSubscription>) -> AttachRecordingSubscription {+ let (sender, _receiver) = flume::bounded(4);+ let (health_tx, _health_rx) = new_health_channel();+ AttachRecordingSubscription {+ subscription,+ sender,+ health_tx,+ label: "recording-test".into(),+ }+ }++ fn accepted_recovery(+ feed: &mut MicrophoneFeed,+ id: u32,+ ) -> (LockedInputReconnected, mpsc::Receiver<()>) {+ let generation = feed.lock_generation;+ let previous_id = match &feed.state {+ State::Locked { inner, .. } => inner.id,+ _ => panic!("locked fixture"),+ };+ let health = Arc::new(StreamHealth::new(id));+ let _ = feed.stream_health.insert(id, health.clone());+ let (done_tx, done_rx) = mpsc::sync_channel(1);+ let ready: StreamReadyFuture = futures::future::ready(Ok((config(), None))).boxed();+ feed.accept_windows_reconnect(+ WindowsReconnect {+ selection_generation: feed.selection_generation,+ generation,+ previous_id,+ id,+ label: "requested".into(),+ ready: ready.shared(),+ done_tx: done_tx.clone(),+ },+ health,+ );+ (+ LockedInputReconnected {+ previous_id,+ generation,+ id,+ label: "requested".into(),+ config: config(),+ buffer_size_frames: None,+ done_tx,+ },+ done_rx,+ )+ }++ struct Snapshot;+ impl Message<Snapshot> for MicrophoneFeed {+ type Reply = (u64, u32, Option<u32>, usize, usize, u32);+ async fn handle(&mut self, _: Snapshot, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ let id = match &self.state {+ State::Locked { inner, .. } => inner.id,+ State::Open(state) => state.attached.as_ref().map_or(0, |inner| inner.id),+ };+ (+ self.lock_generation,+ id,+ self.recording_reconnect.as_ref().map(|pending| pending.id),+ self.senders.len(),+ self.senders+ .iter()+ .filter(|sender| sender.subscription.is_some())+ .count(),+ self.input_id_counter,+ )+ }+ }++ #[tokio::test]+ async fn stop_before_dispatch_rejects_rebuild_and_detaches_only_owned_sender() {+ let (feed, _token, native) = fixture();+ let actor = MicrophoneFeed::spawn(feed);+ let subscription =+ RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ actor.ask(attach(subscription.clone())).await.unwrap();+ assert!(subscription.retire().is_none());+ let result = actor+ .ask(ReconnectRecordingSubscription {+ subscription: subscription.clone(),+ label: "requested".into(),+ settings: MicrophoneDeviceSettings::default(),+ })+ .await;+ assert!(result.is_err());+ actor+ .ask(DetachRecordingSubscription(subscription))+ .await+ .unwrap();+ let snapshot = actor.ask(Snapshot).await.unwrap();+ assert_eq!(snapshot, (3, 7, None, 1, 0, 8));+ assert!(matches!(native.try_recv(), Err(mpsc::TryRecvError::Empty)));+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[tokio::test]+ async fn accepted_rebuild_survives_detach_and_unlock_for_shared_preview() {+ let (mut feed, token, _native) = fixture();+ let subscription =+ RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ feed.attach_subscription(attach(subscription.clone()))+ .unwrap();+ let (replacement, native) = accepted_recovery(&mut feed, 8);+ let actor = MicrophoneFeed::spawn(feed);+ assert!(subscription.retire().is_none());+ actor+ .ask(DetachRecordingSubscription(subscription.clone()))+ .await+ .unwrap();+ drop(token);+ actor.ask(Unlock { generation: 3 }).await.unwrap();+ actor.ask(replacement).await.unwrap();+ assert_eq!(actor.ask(Snapshot).await.unwrap(), (3, 8, None, 1, 0, 8));+ assert!(matches!(native.try_recv(), Err(mpsc::TryRecvError::Empty)));+ assert!(!subscription.accepts_frame(7));+ assert!(!subscription.accepts_frame(8));+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[tokio::test]+ async fn old_recovery_cannot_replace_a_newly_connected_user_selection() {+ let (mut feed, token, _old_native) = fixture();+ let (old_callback, old_native) = accepted_recovery(&mut feed, 8);+ let (selected_done, selected_native) = mpsc::sync_channel(1);+ feed.selection_generation = 1;+ let selected_config = config();+ let ready: BoxFuture<'static, Result<InputConnected, SetInputError>> =+ futures::future::pending().boxed();+ feed.state = State::Open(OpenState {+ connecting: Some(ConnectingState { id: 9, ready }),+ attached: None,+ });+ let actor = MicrophoneFeed::spawn(feed);+ drop(token);+ actor+ .ask(InputConnected {+ id: 9,+ label: "latest-user-selection".into(),+ config: selected_config,+ buffer_size_frames: None,+ done_tx: selected_done,+ })+ .await+ .unwrap();+ actor.ask(old_callback).await.unwrap();+ assert_eq!(actor.ask(Snapshot).await.unwrap().1, 9);+ assert!(matches!(+ selected_native.try_recv(),+ Err(mpsc::TryRecvError::Empty)+ ));+ assert!(matches!(+ old_native.try_recv(),+ Err(mpsc::TryRecvError::Empty)+ ));+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[tokio::test]+ async fn resumed_subscription_accepts_current_callback_and_ignores_retired_pcm_health() {+ let (mut feed, _token, _native) = fixture();+ let retired = RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ feed.attach_subscription(attach(retired.clone())).unwrap();+ assert!(retired.retire().is_none());+ let resumed = RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ feed.attach_subscription(attach(resumed.clone())).unwrap();+ let (callback, _replacement_native) = accepted_recovery(&mut feed, 8);+ let old_health = feed.stream_health.get(&7).unwrap().clone();+ let actor = MicrophoneFeed::spawn(feed);+ actor+ .ask(DetachRecordingSubscription(retired.clone()))+ .await+ .unwrap();+ actor.ask(callback).await.unwrap();+ assert!(resumed.accepts_frame(8));+ assert!(!resumed.accepts_frame(7));+ assert!(!retired.accepts_frame(7));+ assert!(!retired.accepts_frame(8));+ old_health.failed.store(true, Ordering::Release);+ actor+ .ask(WindowsReconnectFailed {+ generation: 3,+ id: 7,+ error: "stale callback".into(),+ })+ .await+ .unwrap();+ assert!(resumed.error().is_none());+ assert!(retired.error().is_none());+ assert_eq!(actor.ask(Snapshot).await.unwrap().4, 1);+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[tokio::test]+ async fn resume_after_reconnect_acceptance_adopts_pending_stream_before_callback() {+ let (mut feed, _token, _native) = fixture();+ let retired = RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ feed.attach_subscription(attach(retired.clone())).unwrap();+ let (callback, _replacement_native) = accepted_recovery(&mut feed, 8);+ let actor = MicrophoneFeed::spawn(feed);+ assert!(retired.retire().is_none());+ actor+ .ask(DetachRecordingSubscription(retired.clone()))+ .await+ .unwrap();+ let resumed = RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ actor.ask(attach(resumed.clone())).await.unwrap();+ assert!(resumed.accepts_frame(7));+ assert!(!resumed.accepts_frame(8));+ actor.ask(callback).await.unwrap();+ assert!(resumed.accepts_frame(8));+ assert!(!resumed.accepts_frame(7));+ assert!(!retired.accepts_frame(8));+ assert!(resumed.error().is_none());+ assert_eq!(actor.ask(Snapshot).await.unwrap(), (3, 8, None, 2, 1, 8));+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[tokio::test]+ async fn resume_rejects_pending_replacement_with_stale_actor_identity() {+ for mismatch in 0..4 {+ let (mut feed, _token, _native) = fixture();+ let (_callback, _replacement_native) = accepted_recovery(&mut feed, 8);+ let pending = feed.recording_reconnect.as_mut().unwrap();+ match mismatch {+ 0 => pending.selection_generation += 1,+ 1 => pending.generation += 1,+ 2 => pending.previous_id += 1,+ _ => pending.label = "other-device".into(),+ }+ let actor = MicrophoneFeed::spawn(feed);+ let resumed = RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ assert!(actor.ask(attach(resumed.clone())).await.is_err());+ assert_eq!(actor.ask(Snapshot).await.unwrap().4, 0);+ assert!(!resumed.accepts_frame(7));+ actor.kill();+ actor.wait_for_stop().await;+ }+ }++ #[tokio::test]+ async fn resume_rejects_missing_or_failed_pending_backend_health() {+ for failed in [false, true] {+ let (mut feed, _token, _native) = fixture();+ let (_callback, _replacement_native) = accepted_recovery(&mut feed, 8);+ if failed {+ feed.stream_health+ .get(&8)+ .unwrap()+ .failed+ .store(true, Ordering::Release);+ } else {+ assert!(feed.stream_health.remove(&8).is_some());+ }+ let actor = MicrophoneFeed::spawn(feed);+ let resumed = RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ assert!(actor.ask(attach(resumed.clone())).await.is_err());+ assert_eq!(actor.ask(Snapshot).await.unwrap().4, 0);+ assert!(!resumed.accepts_frame(7));+ actor.kill();+ actor.wait_for_stop().await;+ }+ }++ struct SinkMuxer;+ impl Muxer for SinkMuxer {+ type Config = ();+ async fn setup(+ _: (),+ _: std::path::PathBuf,+ _: Option<cap_media_info::VideoInfo>,+ _: Option<AudioInfo>,+ _: Arc<AtomicBool>,+ _: &mut TaskPool,+ ) -> anyhow::Result<Self> {+ Ok(Self)+ }+ fn finish(&mut self, _: Duration) -> anyhow::Result<anyhow::Result<()>> {+ Ok(Ok(()))+ }+ }+ impl AudioMuxer for SinkMuxer {+ fn send_audio_frame(&mut self, _: AudioFrame, _: Duration) -> anyhow::Result<()> {+ Ok(())+ }+ }++ #[tokio::test]+ async fn actual_microphone_pipeline_stop_detaches_and_propagates_backend_failure() {+ for fail in [false, true] {+ let (feed, token, native) = fixture();+ let health = feed.stream_health.get(&7).unwrap().clone();+ let actor = MicrophoneFeed::spawn(feed);+ let config = config();+ let lock = Arc::new(MicrophoneFeedLock {+ generation: 3,+ actor: actor.clone(),+ audio_info: AudioInfo::from_stream_config_with_buffer(&config, None),+ config,+ buffer_size_frames: None,+ drop_tx: None,+ device_name: "requested".into(),+ recording_muted: Arc::new(AtomicBool::new(false)),+ _token: token,+ });+ let temp = tempfile::tempdir().unwrap();+ let pipeline = OutputPipeline::builder(temp.path().join("unused.ogg"))+ .with_audio_source::<crate::sources::Microphone>(lock.clone())+ .build::<SinkMuxer>(())+ .await+ .unwrap();+ assert_eq!(actor.ask(Snapshot).await.unwrap().4, 1);+ if fail {+ health.failed.store(true, Ordering::Release);+ }+ let stopped = tokio::time::timeout(Duration::from_secs(2), pipeline.stop())+ .await+ .unwrap();+ assert_eq!(stopped.is_ok(), !fail);+ assert_eq!(actor.ask(Snapshot).await.unwrap().4, 0);+ assert_eq!(actor.ask(Snapshot).await.unwrap().3, 1);+ assert!(matches!(native.try_recv(), Err(mpsc::TryRecvError::Empty)));+ drop(lock);+ actor.kill();+ actor.wait_for_stop().await;+ }+ }++ #[test]+ fn unexpected_native_exit_is_sticky_only_for_current_live_subscription() {+ let health = Arc::new(StreamHealth::new(7));+ let subscription =+ RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ subscription.state.lock().unwrap().current = Some(health.clone());+ drop(StreamExitHealth {+ health: health.clone(),+ expected: false,+ });+ assert!(subscription.error().is_some());+ assert!(subscription.retire().is_some());+ let other = RecordingSubscription::new(3, tokio_util::sync::CancellationToken::new());+ let healthy = Arc::new(StreamHealth::new(8));+ other.state.lock().unwrap().current = Some(healthy.clone());+ assert!(other.retire().is_none());+ drop(StreamExitHealth {+ health: healthy.clone(),+ expected: false,+ });+ assert!(other.error().is_none());+ let expected = Arc::new(StreamHealth::new(9));+ drop(StreamExitHealth {+ health: expected.clone(),+ expected: true,+ });+ assert!(!expected.failed.load(Ordering::Acquire));+ }+}diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rsindex c75ca2237..4a936c04b 100644--- a/crates/recording/src/instant_recording.rs+++ b/crates/recording/src/instant_recording.rs@@ -2,6 +2,13 @@use crate::SendableShareableContent;#[cfg(target_os = "linux")]mod linux_camera;+#[cfg(target_os = "linux")]+pub use linux_camera::{+ LINUX_CAMERA_MAX_MASK_AGE, LinuxCameraBlur, LinuxCameraEffect, LinuxCameraMaskReceipt,+ LinuxCameraPresentation, LinuxCameraPresentationError, LinuxCameraProcessing,+ LinuxCameraPublisher, LinuxCameraRect, LinuxCameraShape, LinuxProcessedCameraFrame,+ LinuxProcessedCameraSource,+};use crate::{RecordingBaseInputs,@@ -18,6 +25,8 @@ use cap_media_info::VideoInfo;use cap_project::InstantRecordingMeta;use cap_timestamp::Timestamps;use cap_utils::ensure_dir;+#[cfg(target_os = "linux")]+use futures::FutureExt as _;use kameo::{Actor as _, prelude::*};use std::{path::PathBuf,@@ -26,6 +35,233 @@ use std::{};use tracing::*;+#[cfg(target_os = "linux")]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+/// Joined covers this attempt's capture/output work, not shared preview feeds or physical device shutdown.+pub enum InstantQuiescence {+ Pending,+ Joined,+ Unconfirmed,+}++#[cfg(target_os = "linux")]+#[derive(Clone)]+pub struct InstantLifecycle(Arc<InstantLifecycleInner>);++#[cfg(target_os = "linux")]+struct InstantLifecycleInner {+ scope: output_pipeline::PipelineBuildScope,+ state: tokio::sync::watch::Sender<InstantQuiescence>,+ completion: tokio::sync::watch::Sender<Option<Result<(), output_pipeline::PipelineDoneError>>>,+ error: std::sync::Mutex<Option<String>>,+ runtime: std::sync::Mutex<Option<tokio::runtime::Handle>>,+}++#[cfg(target_os = "linux")]+impl InstantLifecycle {+ fn new() -> Self {+ let (state, _) = tokio::sync::watch::channel(InstantQuiescence::Pending);+ let (completion, _) = tokio::sync::watch::channel(None);+ Self(Arc::new(InstantLifecycleInner {+ scope: output_pipeline::PipelineBuildScope::new_lifetime(),+ state,+ completion,+ error: std::sync::Mutex::new(None),+ runtime: std::sync::Mutex::new(None),+ }))+ }++ /// Cancellation requests shutdown; callers must still await quiescence before revealing or deleting.+ pub fn cancel(&self) {+ self.0.scope.cancel();+ if let Some(report) = self.0.scope.idle_report() {+ self.publish_quiescence(report.quiescent);+ }+ }++ fn publish_quiescence(&self, quiescent: bool) {+ self.0.state.send_if_modified(|state| {+ if *state == InstantQuiescence::Unconfirmed {+ return false;+ }+ let next = if quiescent {+ InstantQuiescence::Joined+ } else {+ InstantQuiescence::Unconfirmed+ };+ let changed = *state != next;+ *state = next;+ changed+ });+ }++ pub fn quiescence(&self) -> InstantQuiescence {+ *self.0.state.borrow()+ }++ pub async fn wait_for_quiescence(&self) -> InstantQuiescence {+ let mut state = self.0.state.subscribe();+ loop {+ let value = *state.borrow_and_update();+ if value != InstantQuiescence::Pending {+ return value;+ }+ if state.changed().await.is_err() {+ return InstantQuiescence::Unconfirmed;+ }+ }+ }++ fn done_fut(&self) -> output_pipeline::DoneFut {+ let mut completion = self.0.completion.subscribe();+ async move {+ loop {+ if let Some(result) = completion.borrow_and_update().clone() {+ return result;+ }+ if completion.changed().await.is_err() {+ return Err(output_pipeline::PipelineDoneError::from_message(+ "Instant completion acknowledgement was lost".into(),+ ));+ }+ }+ }+ .boxed()+ .shared()+ }++ fn complete(+ &self,+ report: output_pipeline::PipelineJoinReport,+ error: Option<String>,+ ) -> anyhow::Result<()> {+ self.publish_quiescence(report.quiescent);+ let quiescent = self.quiescence() == InstantQuiescence::Joined;+ let mut stored = self.0.error.lock().unwrap();+ if stored.is_none() {+ *stored = error.or(report.error).or_else(|| {+ (!quiescent).then(|| "Instant capture quiescence is unconfirmed".into())+ });+ }+ let result = stored.as_ref().map_or(Ok(()), |error| {+ Err(output_pipeline::PipelineDoneError::from_message(+ error.clone(),+ ))+ });+ self.0.completion.send_if_modified(|current| {+ if current.is_none() {+ *current = Some(result.clone());+ true+ } else {+ false+ }+ });+ result.map_err(anyhow::Error::from)+ }++ fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {+ let runtime = self+ .0+ .runtime+ .lock()+ .unwrap()+ .clone()+ .or_else(|| tokio::runtime::Handle::try_current().ok());+ if let Some(runtime) = runtime {+ drop(runtime.spawn(future));+ } else if self.quiescence() == InstantQuiescence::Pending {+ self.0.state.send_replace(InstantQuiescence::Unconfirmed);+ self.0+ .error+ .lock()+ .unwrap()+ .get_or_insert_with(|| "Capture cleanup runtime is unavailable".into());+ }+ }+}++#[cfg(target_os = "linux")]+struct InstantLifetimeOwner {+ lifecycle: InstantLifecycle,+ armed: bool,+}++#[cfg(target_os = "linux")]+impl InstantLifetimeOwner {+ fn new() -> Self {+ Self {+ lifecycle: InstantLifecycle::new(),+ armed: true,+ }+ }++ async fn failed(mut self, error: String) -> InstantQuiescence {+ let report = self.lifecycle.0.scope.cancel_and_join_report().await;+ let _ = self.lifecycle.complete(report, Some(error));+ self.armed = false;+ self.lifecycle.quiescence()+ }+}++#[cfg(target_os = "linux")]+struct CleanupAcknowledgement {+ lifecycle: InstantLifecycle,+ armed: bool,+}++#[cfg(target_os = "linux")]+impl Drop for CleanupAcknowledgement {+ fn drop(&mut self) {+ if self.armed && self.lifecycle.quiescence() == InstantQuiescence::Pending {+ self.lifecycle+ .0+ .state+ .send_replace(InstantQuiescence::Unconfirmed);+ }+ }+}++#[cfg(target_os = "linux")]+impl Drop for InstantLifetimeOwner {+ fn drop(&mut self) {+ if !self.armed || self.lifecycle.quiescence() != InstantQuiescence::Pending {+ return;+ }+ self.lifecycle.0.scope.cancel();+ let message = "Instant recording owner dropped before shutdown acknowledgement".to_string();+ if let Some(report) = self.lifecycle.0.scope.idle_report() {+ let _ = self.lifecycle.complete(report, Some(message));+ return;+ }+ let lifecycle = self.lifecycle.clone();+ let guard = CleanupAcknowledgement {+ lifecycle: lifecycle.clone(),+ armed: true,+ };+ self.lifecycle.spawn(async move {+ let mut guard = guard;+ let report = lifecycle.0.scope.cancel_and_join_report().await;+ let _ = lifecycle.complete(report, Some(message));+ guard.armed = false;+ });+ }+}++#[cfg(target_os = "linux")]+struct BuildWaiter {+ lifecycle: InstantLifecycle,+ armed: bool,+}++#[cfg(target_os = "linux")]+impl Drop for BuildWaiter {+ fn drop(&mut self) {+ if self.armed {+ self.lifecycle.cancel();+ }+ }+}+struct Pipeline {video: OutputPipeline,audio: Option<OutputPipeline>,@@ -50,6 +286,8 @@ enum ActorState {}pub struct ActorHandle {+ #[cfg(target_os = "linux")]+ lifecycle: InstantLifecycle,actor_ref: kameo::actor::ActorRef<Actor>,pub capture_target: ScreenCaptureTarget,done_fut: output_pipeline::DoneFut,@@ -64,6 +302,11 @@ pub struct ActorHandle {}impl ActorHandle {+ #[cfg(target_os = "linux")]+ pub fn lifecycle(&self) -> InstantLifecycle {+ self.lifecycle.clone()+ }+pub async fn stop(&self) -> anyhow::Result<CompletedRecording> {Ok(self.actor_ref.ask(Stop).await?)}@@ -105,6 +348,23 @@ impl ActorHandle {impl Drop for ActorHandle {fn drop(&mut self) {let actor_ref = self.actor_ref.clone();+ #[cfg(target_os = "linux")]+ {+ if self.lifecycle.quiescence() == InstantQuiescence::Joined {+ return;+ }+ if self.lifecycle.quiescence() == InstantQuiescence::Pending {+ self.lifecycle+ .0+ .scope+ .fail_required("Instant handle dropped before shutdown acknowledgement".into());+ }+ self.lifecycle.cancel();+ self.lifecycle.spawn(async move {+ let _ = actor_ref.ask(Cancel).await;+ });+ }+ #[cfg(not(target_os = "linux"))]tokio::spawn(async move {let _ = actor_ref.tell(Stop).await;});@@ -120,10 +380,63 @@ pub struct Actor {state: ActorState,total_pause_duration: std::time::Duration,pause_started_at: Option<f64>,+ terminal_stop_error: Option<String>,+ #[cfg(target_os = "linux")]+ lifetime: InstantLifetimeOwner,}impl Actor {+ #[cfg(target_os = "linux")]+ async fn stop(&mut self) -> anyhow::Result<()> {+ self.lifetime.lifecycle.0.scope.cancel();+ let pipeline = std::mem::replace(&mut self.state, ActorState::Stopped);+ let mut errors = Vec::new();+ if let ActorState::Recording { pipeline, .. } | ActorState::Paused { pipeline, .. } =+ pipeline+ {+ let video = pipeline.video.stop();+ let audio = async {+ match pipeline.audio {+ Some(audio) => audio.stop().await.map(|_| ()),+ None => Ok(()),+ }+ };+ let (video, audio) = tokio::join!(video, audio);+ if let Err(error) = video {+ errors.push(format!("Video pipeline: {error:#}"));+ }+ if let Err(error) = audio {+ errors.push(format!("Audio pipeline: {error:#}"));+ }+ }+ let report = self+ .lifetime+ .lifecycle+ .0+ .scope+ .cancel_and_join_report()+ .await;+ if let Some(error) = &report.error {+ errors.push(error.clone());+ }+ let result = if errors.is_empty() {+ Ok(())+ } else {+ Err(anyhow::anyhow!(errors.join("; ")))+ };+ let result = preserve_terminal_stop_error(&mut self.terminal_stop_error, result);+ let lifecycle_result = self+ .lifetime+ .lifecycle+ .complete(report, self.terminal_stop_error.clone());+ result.and(lifecycle_result)+ }++ #[cfg(not(target_os = "linux"))]async fn stop(&mut self) -> anyhow::Result<()> {+ if let Some(error) = &self.terminal_stop_error {+ return Err(anyhow::anyhow!(error.clone()));+ }let pipeline = replace_with::replace_with_or_abort_and_return(&mut self.state, |state| {(match state {@@ -135,20 +448,39 @@ impl Actor {)});- if let Some(pipeline) = pipeline {- if let Some(audio) = pipeline.audio {- let (audio_res, video_res) = tokio::join!(audio.stop(), pipeline.video.stop());- if let Err(e) = audio_res {- warn!("Audio pipeline stop failed: {e:#}");+ let result = async {+ if let Some(pipeline) = pipeline {+ if let Some(audio) = pipeline.audio {+ let (audio_res, video_res) = tokio::join!(audio.stop(), pipeline.video.stop());+ #[cfg(not(windows))]+ if let Err(e) = audio_res {+ warn!("Audio pipeline stop failed: {e:#}");+ }+ video_res?;+ #[cfg(windows)]+ audio_res?;+ } else {+ pipeline.video.stop().await?;}- video_res?;- } else {- pipeline.video.stop().await?;}+ Ok(())}+ .await;+ preserve_terminal_stop_error(&mut self.terminal_stop_error, result)+ }+}- Ok(())+fn preserve_terminal_stop_error(+ stored: &mut Option<String>,+ result: anyhow::Result<()>,+) -> anyhow::Result<()> {+ if let Some(error) = stored.as_ref() {+ return Err(anyhow::anyhow!(error.clone()));+ }+ if let Err(error) = &result {+ *stored = Some(format!("{error:#}"));}+ result}impl Message<Stop> for Actor {@@ -286,9 +618,19 @@ impl Message<Cancel> for Actor {type Reply = anyhow::Result<()>;async fn handle(&mut self, _: Cancel, _: &mut Context<Self, Self::Reply>) -> Self::Reply {- let _ = self.stop().await;-- Ok(())+ #[cfg(target_os = "linux")]+ {+ self.stop().await+ }+ #[cfg(windows)]+ {+ self.stop().await+ }+ #[cfg(not(any(target_os = "linux", windows)))]+ {+ let _ = self.stop().await;+ Ok(())+ }}}@@ -314,7 +656,7 @@ struct ScreenPipelineInput {source: crate::sources::screen_capture::VideoSourceConfig,info: VideoInfo,#[cfg(target_os = "linux")]- camera_feed: Option<Arc<crate::feeds::camera::CameraFeedLock>>,+ prepared_camera: Option<linux_camera::PreparedCamera>,}async fn create_pipeline(@@ -329,7 +671,7 @@ async fn create_pipeline(source: screen_capture,info: screen_info,#[cfg(target_os = "linux")]- camera_feed,+ prepared_camera,} = screen;let output_resolution = max_output_size.map(|max_output_size| {@@ -369,11 +711,11 @@ async fn create_pipeline(.await?;#[cfg(target_os = "linux")]- let video = if let Some(camera_feed) = camera_feed {+ let video = if let Some(camera) = prepared_camera {OutputPipeline::builder(segments_dir.clone()).with_video::<linux_camera::CameraCompositeSource>(linux_camera::Config {screen_capture,- camera_feed,+ camera,}).with_timestamps(start_time).build::<crate::ffmpeg::SegmentedVideoMuxer>(crate::ffmpeg::SegmentedVideoMuxerConfig {@@ -462,10 +804,18 @@ pub struct ActorBuilder {camera_feed: Option<Arc<crate::feeds::camera::CameraFeedLock>>,#[cfg(target_os = "linux")]composite_camera: bool,+ #[cfg(target_os = "linux")]+ camera_presentation: Option<LinuxCameraPresentation>,+ #[cfg(target_os = "linux")]+ processed_camera: Option<LinuxProcessedCameraSource>,+ #[cfg(target_os = "linux")]+ camera_reference_size: Option<(u32, u32)>,max_output_size: Option<u32>,max_fps: u32,#[cfg(target_os = "macos")]excluded_windows: Vec<scap_targets::WindowId>,+ #[cfg(target_os = "linux")]+ lifetime: InstantLifetimeOwner,}impl ActorBuilder {@@ -478,13 +828,26 @@ impl ActorBuilder {camera_feed: None,#[cfg(target_os = "linux")]composite_camera: false,+ #[cfg(target_os = "linux")]+ camera_presentation: None,+ #[cfg(target_os = "linux")]+ processed_camera: None,+ #[cfg(target_os = "linux")]+ camera_reference_size: None,max_output_size: None,max_fps: crate::defaults::DEFAULT_INSTANT_MODE_FPS,+ #[cfg(target_os = "linux")]+ lifetime: InstantLifetimeOwner::new(),#[cfg(target_os = "macos")]excluded_windows: Vec::new(),}}+ #[cfg(target_os = "linux")]+ pub fn lifecycle(&self) -> InstantLifecycle {+ self.lifetime.lifecycle.clone()+ }+pub fn with_system_audio(mut self, system_audio: bool) -> Self {self.system_audio = system_audio;self@@ -514,6 +877,27 @@ impl ActorBuilder {self}+ #[cfg(target_os = "linux")]+ pub fn with_linux_camera_presentation(mut self, presentation: LinuxCameraPresentation) -> Self {+ self.composite_camera = true;+ self.camera_presentation = Some(presentation);+ self+ }++ #[cfg(target_os = "linux")]+ pub fn with_linux_processed_camera(+ mut self,+ source: LinuxProcessedCameraSource,+ presentation: LinuxCameraPresentation,+ reference_size: (u32, u32),+ ) -> Self {+ self.composite_camera = true;+ self.camera_presentation = Some(presentation);+ self.processed_camera = Some(source);+ self.camera_reference_size = Some(reference_size);+ self+ }+pub fn with_max_fps(mut self, max_fps: u32) -> Self {self.max_fps = max_fps.clamp(1, 120);self@@ -544,7 +928,14 @@ impl ActorBuilder {self.max_output_size,self.max_fps,#[cfg(target_os = "linux")]- self.composite_camera,+ LinuxCameraConfig {+ composite_camera: self.composite_camera,+ camera_presentation: self.camera_presentation,+ processed_camera: self.processed_camera,+ camera_reference_size: self.camera_reference_size,+ },+ #[cfg(target_os = "linux")]+ self.lifetime,).await}@@ -562,19 +953,150 @@ pub async fn spawn_instant_recording_actor(max_output_size,max_fps,#[cfg(target_os = "linux")]- false,+ LinuxCameraConfig::default(),+ #[cfg(target_os = "linux")]+ InstantLifetimeOwner::new(),).await}-#[tracing::instrument("instant_recording", skip_all)]+#[cfg(target_os = "linux")]+#[derive(Default)]+struct LinuxCameraConfig {+ composite_camera: bool,+ camera_presentation: Option<LinuxCameraPresentation>,+ processed_camera: Option<LinuxProcessedCameraSource>,+ camera_reference_size: Option<(u32, u32)>,+}++#[cfg(target_os = "linux")]+async fn run_owned_instant_build<T: Send + 'static>(+ mut owner: InstantLifetimeOwner,+ build: impl Future<Output = anyhow::Result<T>> + Send + 'static,+) -> anyhow::Result<T> {+ let lifecycle = owner.lifecycle.clone();+ *lifecycle.0.runtime.lock().unwrap() = Some(tokio::runtime::Handle::current());+ let scope = lifecycle.0.scope.clone();+ let mut waiter = BuildWaiter {+ lifecycle: lifecycle.clone(),+ armed: true,+ };+ let startup = scope.task_completion();+ let (sender, receiver) = tokio::sync::oneshot::channel();+ drop(tokio::spawn(async move {+ let cancel = scope.cancellation();+ let result = scope.run(async {+ tokio::select! {+ biased;+ _ = cancel.cancelled() => Err(anyhow::anyhow!("Instant recording startup cancelled")),+ result = std::panic::AssertUnwindSafe(build).catch_unwind() => {+ result.unwrap_or_else(|_| Err(anyhow::anyhow!("Instant recording startup panicked")))+ }+ }+ }).await;+ drop(startup);+ let result = match result {+ Ok(value) if !cancel.is_cancelled() => {+ owner.armed = false;+ drop(owner);+ Ok(value)+ }+ result => {+ let message = match result {+ Ok(value) => {+ drop(value);+ "Instant recording startup cancelled".to_string()+ }+ Err(error) => format!("{error:#}"),+ };+ let quiescence = owner.failed(message.clone()).await;+ Err(anyhow::anyhow!(+ "{message}; capture cleanup: {quiescence:?}"+ ))+ }+ };+ let _ = sender.send(result);+ }));+ let result = receiver+ .await+ .context("Instant recording startup acknowledgement lost")?;+ waiter.armed = false;+ result+}++#[cfg(target_os = "linux")]async fn spawn_instant_recording_actor_inner(recording_dir: PathBuf,inputs: RecordingBaseInputs,max_output_size: Option<u32>,max_fps: u32,- #[cfg(target_os = "linux")] composite_camera: bool,+ camera: LinuxCameraConfig,+ owner: InstantLifetimeOwner,) -> anyhow::Result<ActorHandle> {+ let lifecycle = owner.lifecycle.clone();+ run_owned_instant_build(+ owner,+ build_instant_recording_actor(+ recording_dir,+ inputs,+ max_output_size,+ max_fps,+ camera,+ lifecycle,+ ),+ )+ .await+}++#[cfg(not(target_os = "linux"))]+async fn spawn_instant_recording_actor_inner(+ recording_dir: PathBuf,+ inputs: RecordingBaseInputs,+ max_output_size: Option<u32>,+ max_fps: u32,+) -> anyhow::Result<ActorHandle> {+ let startup = build_instant_recording_actor(recording_dir, inputs, max_output_size, max_fps);+ #[cfg(windows)]+ {+ let scope = output_pipeline::PipelineBuildScope::new();+ output_pipeline::finish_windows_pipeline_startup(&scope, startup).await+ }+ #[cfg(not(windows))]+ startup.await+}++#[tracing::instrument("instant_recording", skip_all)]+async fn build_instant_recording_actor(+ recording_dir: PathBuf,+ inputs: RecordingBaseInputs,+ max_output_size: Option<u32>,+ max_fps: u32,+ #[cfg(target_os = "linux")] camera: LinuxCameraConfig,+ #[cfg(target_os = "linux")] lifecycle: InstantLifecycle,+) -> anyhow::Result<ActorHandle> {+ #[cfg(target_os = "linux")]+ anyhow::ensure!(+ !matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly)+ || !inputs.capture_system_audio,+ "System audio is not supported for Linux Instant CameraOnly recordings. Disable system audio or choose a screen target."+ );+ #[cfg(target_os = "linux")]+ let LinuxCameraConfig {+ composite_camera,+ camera_presentation,+ processed_camera,+ camera_reference_size,+ } = camera;+ #[cfg(target_os = "linux")]+ if camera_presentation.is_some() && inputs.camera_feed.is_none() {+ return Err(LinuxCameraPresentationError::MissingCamera.into());+ }+ #[cfg(target_os = "linux")]+ if camera_presentation.is_some()+ && matches!(inputs.capture_target, ScreenCaptureTarget::CameraOnly)+ {+ return Err(LinuxCameraPresentationError::UnsupportedTarget.into());+ }ensure_dir(&recording_dir)?;let timestamps = Timestamps::now();@@ -736,7 +1258,21 @@ async fn spawn_instant_recording_actor_inner(#[cfg(target_os = "linux")]let screen_info = screen_capture.video_info();#[cfg(target_os = "linux")]- let timestamps = Timestamps::now();+ let (prepared_camera, timestamps) = if let Some(camera_feed) =+ inputs.camera_feed.clone().filter(|_| composite_camera)+ {+ let (camera, timestamps) = linux_camera::PreparedCamera::prepare(+ camera_feed,+ camera_presentation,+ processed_camera,+ camera_reference_size,+ screen_info,+ )+ .await?;+ (Some(camera), timestamps)+ } else {+ (None, Timestamps::now())+ };let pipeline = create_pipeline(content_dir.clone(),@@ -744,7 +1280,7 @@ async fn spawn_instant_recording_actor_inner(source: screen_capture,info: screen_info,#[cfg(target_os = "linux")]- camera_feed: inputs.camera_feed.clone().filter(|_| composite_camera),+ prepared_camera,},inputs.mic_feed.clone(),system_audio_source,@@ -765,7 +1301,14 @@ async fn spawn_instant_recording_actor_inner(let segment_rx = pipeline.segment_rx.take();let output_dir = pipeline.segments_dir.clone();+ #[cfg(not(target_os = "linux"))]let done_fut = pipeline.video.done_fut();+ #[cfg(target_os = "linux")]+ let video_done = pipeline.video.done_fut();+ #[cfg(target_os = "linux")]+ let audio_done = pipeline.audio.as_ref().map(OutputPipeline::done_fut);+ #[cfg(target_os = "linux")]+ let done_fut = lifecycle.done_fut();let health_rx = pipeline.video.take_health_rx();let actor_ref = Actor::spawn(Actor {recording_dir,@@ -778,9 +1321,17 @@ async fn spawn_instant_recording_actor_inner(},total_pause_duration: std::time::Duration::ZERO,pause_started_at: None,+ terminal_stop_error: None,+ #[cfg(target_os = "linux")]+ lifetime: InstantLifetimeOwner {+ lifecycle: lifecycle.clone(),+ armed: true,+ },});let actor_handle = ActorHandle {+ #[cfg(target_os = "linux")]+ lifecycle: lifecycle.clone(),actor_ref: actor_ref.clone(),capture_target: inputs.capture_target,done_fut: done_fut.clone(),@@ -788,14 +1339,54 @@ async fn spawn_instant_recording_actor_inner(segment_rx: segment_rx.map(|rx| std::sync::Mutex::new(Some(rx))),};+ #[cfg(not(target_os = "linux"))]tokio::spawn(async move {let _ = done_fut.await;let _ = actor_ref.ask(Stop).await;});+ #[cfg(target_os = "linux")]+ watch_instant_tracks(lifecycle, actor_ref, video_done, audio_done);Ok(actor_handle)}+#[cfg(target_os = "linux")]+fn watch_instant_tracks(+ lifecycle: InstantLifecycle,+ actor_ref: kameo::actor::ActorRef<Actor>,+ video_done: output_pipeline::DoneFut,+ audio_done: Option<output_pipeline::DoneFut>,+) {+ drop(tokio::spawn(async move {+ let cancel = lifecycle.0.scope.cancellation();+ let audio = async {+ match audio_done {+ Some(done) => done.await,+ None => std::future::pending().await,+ }+ };+ let result = tokio::select! {+ _ = cancel.cancelled() => None,+ result = video_done => Some(("Video", result)),+ result = audio => Some(("Audio", result)),+ };+ if let Some((track, result)) = result {+ match result {+ Err(error) => lifecycle+ .0+ .scope+ .fail_required(format!("{track} pipeline failed: {error}")),+ Ok(()) if !cancel.is_cancelled() => lifecycle+ .0+ .scope+ .fail_required(format!("Required {track} pipeline ended before Stop")),+ Ok(()) => {}+ }+ }+ let _ = actor_ref.ask(Cancel).await;+ }));+}+fn current_time_f64() -> f64 {SystemTime::now().duration_since(UNIX_EPOCH)@@ -865,6 +1456,83 @@ fn clamp_size(input: (u32, u32), max: (u32, u32)) -> (u32, u32) {mod tests {use super::*;+ #[cfg(target_os = "linux")]+ #[test]+ fn linux_presentation_builder_preserves_explicit_config_and_cli_default() {+ let request = LinuxCameraPresentation {+ rect: LinuxCameraRect {+ x: 10,+ y: 20,+ width: 40,+ height: 30,+ },+ shape: LinuxCameraShape::RoundedRectangle { radius_pixels: 4 },+ mirrored: true,+ effect: LinuxCameraEffect::None,+ };+ let configured = ActorBuilder::new(PathBuf::new(), ScreenCaptureTarget::CameraOnly)+ .with_linux_camera_presentation(request);+ assert!(configured.composite_camera);+ assert_eq!(configured.camera_presentation, Some(request));+ let default = ActorBuilder::new(PathBuf::new(), ScreenCaptureTarget::CameraOnly)+ .with_linux_camera_composition();+ assert!(default.composite_camera);+ assert!(default.camera_presentation.is_none());+ }++ #[tokio::test]+ async fn actor_retains_terminal_error_after_internal_stop() {+ let mut actor = Actor {+ recording_dir: PathBuf::new(),+ output_dir: PathBuf::new(),+ capture_target: ScreenCaptureTarget::CameraOnly,+ video_info: VideoInfo::from_raw_ffmpeg(ffmpeg::format::Pixel::RGBA, 4, 4, 30),+ state: ActorState::Stopped,+ total_pause_duration: std::time::Duration::ZERO,+ pause_started_at: None,+ terminal_stop_error: Some("Required camera disconnected".to_string()),+ #[cfg(target_os = "linux")]+ lifetime: InstantLifetimeOwner::new(),+ };+ for _ in 0..2 {+ assert!(+ actor+ .stop()+ .await+ .unwrap_err()+ .to_string()+ .contains("Required camera disconnected")+ );+ }+ }++ #[test]+ fn repeated_stop_cannot_turn_pipeline_failure_into_complete() {+ let mut stored = None;+ assert!(+ super::preserve_terminal_stop_error(+ &mut stored,+ Err(anyhow::anyhow!("Required camera disconnected"))+ )+ .is_err()+ );+ assert!(+ super::preserve_terminal_stop_error(&mut stored, Ok(()))+ .unwrap_err()+ .to_string()+ .contains("Required camera disconnected")+ );+ assert!(super::preserve_terminal_stop_error(&mut stored, Ok(())).is_err());+ }++ #[test]+ fn successful_stop_remains_idempotent() {+ let mut stored = None;+ assert!(super::preserve_terminal_stop_error(&mut stored, Ok(())).is_ok());+ assert!(super::preserve_terminal_stop_error(&mut stored, Ok(())).is_ok());+ assert!(stored.is_none());+ }+#[cfg(target_os = "macos")]#[test]fn capture_size_constraint_preserves_instant_output_axis() {@@ -989,3 +1657,1054 @@ mod tests {assert_eq!(result, (1080, 1920));}}++#[cfg(all(test, target_os = "linux"))]+mod quiescence_tests {+ use super::*;+ use crate::output_pipeline::{+ AudioFrame, AudioMuxer, AudioSource, ChannelAudioSource, ChannelAudioSourceConfig,+ ChannelVideoSource, ChannelVideoSourceConfig, Muxer, SetupCtx, TaskPool, VideoFrame,+ VideoMuxer,+ };+ use cap_timestamp::Timestamp;+ use std::{+ sync::{+ Mutex,+ atomic::{AtomicBool, Ordering},+ },+ time::Duration,+ };++ #[derive(Clone, Copy)]+ struct Frame(Timestamp);+ impl VideoFrame for Frame {+ fn timestamp(&self) -> Timestamp {+ self.0+ }+ }++ #[derive(Clone)]+ struct Finalizer {+ entered: Arc<tokio::sync::Notify>,+ release: Arc<Mutex<Option<std::sync::mpsc::Receiver<()>>>>,+ finished: Arc<AtomicBool>,+ fail: bool,+ }+ impl Finalizer {+ fn new(fail: bool) -> Self {+ Self {+ entered: Arc::new(tokio::sync::Notify::new()),+ release: Arc::new(Mutex::new(None)),+ finished: Arc::new(AtomicBool::new(false)),+ fail,+ }+ }+ }+ struct TestMuxer(Finalizer);+ impl Muxer for TestMuxer {+ type Config = Finalizer;+ async fn setup(+ config: Finalizer,+ _: PathBuf,+ _: Option<VideoInfo>,+ _: Option<cap_media_info::AudioInfo>,+ _: Arc<AtomicBool>,+ _: &mut TaskPool,+ ) -> anyhow::Result<Self> {+ Ok(Self(config))+ }+ fn finish(&mut self, _: Duration) -> anyhow::Result<anyhow::Result<()>> {+ self.0.entered.notify_one();+ if let Some(release) = self.0.release.lock().unwrap().take() {+ release.recv().unwrap();+ }+ self.0.finished.store(true, Ordering::Release);+ Ok(if self.0.fail {+ Err(anyhow::anyhow!("required track finalization failed"))+ } else {+ Ok(())+ })+ }+ }+ impl VideoMuxer for TestMuxer {+ type VideoFrame = Frame;+ fn send_video_frame(&mut self, _: Frame, _: Duration) -> anyhow::Result<()> {+ Ok(())+ }+ }+ impl AudioMuxer for TestMuxer {+ fn send_audio_frame(&mut self, _: AudioFrame, _: Duration) -> anyhow::Result<()> {+ Ok(())+ }+ }++ struct Fixture {+ handle: ActorHandle,+ audio_cancel: Option<tokio_util::sync::CancellationToken>,+ _video_sender: flume::Sender<Frame>,+ _audio_sender: Option<futures::channel::mpsc::Sender<AudioFrame>>,+ }++ async fn actor_fixture(+ directory: &std::path::Path,+ video_finish: Finalizer,+ audio_finish: Option<Finalizer>,+ ) -> Fixture {+ let owner = InstantLifetimeOwner::new();+ let lifecycle = owner.lifecycle.clone();+ *lifecycle.0.runtime.lock().unwrap() = Some(tokio::runtime::Handle::current());+ let info = VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 4, 4, 30);+ let timestamps = Timestamps::now();+ let (video_sender, video_receiver) = flume::bounded(4);+ let video = lifecycle+ .0+ .scope+ .run(+ OutputPipeline::builder(directory.join("display"))+ .with_video::<ChannelVideoSource<Frame>>(ChannelVideoSourceConfig::new(+ info,+ video_receiver,+ ))+ .with_timestamps(timestamps)+ .build::<TestMuxer>(video_finish),+ )+ .await+ .unwrap();+ video_sender+ .send(Frame(Timestamp::Instant(timestamps.instant())))+ .unwrap();+ let mut audio_sender = None;+ let audio = if let Some(finalizer) = audio_finish {+ let (mut sender, receiver) = futures::channel::mpsc::channel(4);+ let info = cap_media_info::AudioInfo::new_raw(+ cap_media_info::Sample::F32(cap_media_info::Type::Packed),+ 48_000,+ 2,+ );+ let audio = lifecycle+ .0+ .scope+ .run(+ OutputPipeline::builder(directory.join("audio"))+ .with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(+ info, receiver,+ ))+ .with_timestamps(timestamps)+ .build::<TestMuxer>(finalizer),+ )+ .await+ .unwrap();+ sender+ .try_send(AudioFrame::new(+ info.empty_frame(960),+ Timestamp::Instant(timestamps.instant()),+ ))+ .unwrap();+ audio_sender = Some(sender);+ Some(audio)+ } else {+ None+ };+ let audio_cancel = audio.as_ref().map(OutputPipeline::cancel_token);+ let video_done = video.done_fut();+ let audio_done = audio.as_ref().map(OutputPipeline::done_fut);+ let actor_ref = Actor::spawn(Actor {+ recording_dir: directory.to_path_buf(),+ output_dir: directory.join("display"),+ capture_target: ScreenCaptureTarget::CameraOnly,+ video_info: info,+ state: ActorState::Recording {+ pipeline: Pipeline {+ video,+ audio,+ video_info: info,+ segments_dir: directory.join("display"),+ segment_rx: None,+ },+ segment_start_time: current_time_f64(),+ },+ total_pause_duration: Duration::ZERO,+ pause_started_at: None,+ terminal_stop_error: None,+ lifetime: owner,+ });+ watch_instant_tracks(lifecycle.clone(), actor_ref.clone(), video_done, audio_done);+ Fixture {+ handle: ActorHandle {+ actor_ref,+ capture_target: ScreenCaptureTarget::CameraOnly,+ done_fut: lifecycle.done_fut(),+ health_rx: None,+ segment_rx: None,+ lifecycle,+ },+ audio_cancel,+ _video_sender: video_sender,+ _audio_sender: audio_sender,+ }+ }++ #[derive(Clone, Copy, PartialEq, Eq)]+ enum CombinedFailure {+ None,+ AudioSend,+ AudioTail,+ FlushInner,+ FlushOuter,+ }++ #[derive(Clone)]+ struct CombinedProbe {+ failure: CombinedFailure,+ finalizer: Finalizer,+ attempts: Arc<Mutex<Vec<f32>>>,+ audio_observed: Arc<tokio::sync::Notify>,+ source_stopped: Arc<AtomicBool>,+ }++ impl CombinedProbe {+ fn new(failure: CombinedFailure) -> Self {+ Self {+ failure,+ finalizer: Finalizer::new(failure == CombinedFailure::FlushInner),+ attempts: Arc::new(Mutex::new(Vec::new())),+ audio_observed: Arc::new(tokio::sync::Notify::new()),+ source_stopped: Arc::new(AtomicBool::new(false)),+ }+ }+ }++ struct CombinedMuxer(CombinedProbe);++ impl Muxer for CombinedMuxer {+ type Config = CombinedProbe;++ async fn setup(+ config: Self::Config,+ output: PathBuf,+ _: Option<VideoInfo>,+ _: Option<cap_media_info::AudioInfo>,+ _: Arc<AtomicBool>,+ _: &mut TaskPool,+ ) -> anyhow::Result<Self> {+ std::fs::write(output, b"preserved partial test video")?;+ Ok(Self(config))+ }++ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ let result = TestMuxer(self.0.finalizer.clone()).finish(timestamp);+ if self.0.failure == CombinedFailure::FlushOuter {+ return Err(anyhow::anyhow!("combined audio outer flush failed"));+ }+ result+ }+ }++ impl VideoMuxer for CombinedMuxer {+ type VideoFrame = Frame;++ fn send_video_frame(&mut self, _: Frame, _: Duration) -> anyhow::Result<()> {+ Ok(())+ }+ }++ impl AudioMuxer for CombinedMuxer {+ fn send_audio_frame(&mut self, frame: AudioFrame, _: Duration) -> anyhow::Result<()> {+ let value = f32::from_ne_bytes(frame.inner.data(0)[..4].try_into().unwrap());+ self.0.attempts.lock().unwrap().push(value);+ self.0.audio_observed.notify_one();+ if self.0.failure == CombinedFailure::AudioSend+ || (self.0.failure == CombinedFailure::AudioTail && value == 0.0)+ {+ return Err(anyhow::anyhow!("required combined audio send failed"));+ }+ Ok(())+ }+ }++ struct DirectAudioSource(Arc<AtomicBool>);++ impl AudioSource for DirectAudioSource {+ type Config = (+ tokio::sync::oneshot::Sender<futures::channel::mpsc::Sender<AudioFrame>>,+ Arc<AtomicBool>,+ );++ fn setup(+ config: Self::Config,+ sender: futures::channel::mpsc::Sender<AudioFrame>,+ _: &mut SetupCtx,+ ) -> impl Future<Output = anyhow::Result<Self>> + Send + 'static {+ futures::future::lazy(move |_| {+ config+ .0+ .send(sender)+ .map_err(|_| anyhow::anyhow!("test audio receiver dropped"))?;+ Ok(Self(config.1))+ })+ }++ fn audio_info(&self) -> cap_media_info::AudioInfo {+ combined_audio_info()+ }++ async fn stop(&mut self) -> anyhow::Result<()> {+ self.0.store(true, Ordering::Release);+ Ok(())+ }+ }++ fn combined_audio_info() -> cap_media_info::AudioInfo {+ cap_media_info::AudioInfo::new_raw(+ cap_media_info::Sample::F32(cap_media_info::Type::Packed),+ 48_000,+ 2,+ )+ }++ fn combined_audio_frame(timestamps: Timestamps, value: f32) -> AudioFrame {+ let mut frame = combined_audio_info().empty_frame(960);+ for sample in frame.data_mut(0).chunks_exact_mut(4) {+ sample.copy_from_slice(&value.to_ne_bytes());+ }+ AudioFrame::new(frame, Timestamp::Instant(timestamps.instant()))+ }++ struct CombinedFixture {+ handle: ActorHandle,+ audio: futures::channel::mpsc::Sender<AudioFrame>,+ additional_audio: Vec<futures::channel::mpsc::Sender<AudioFrame>>,+ pipeline_cancel: tokio_util::sync::CancellationToken,+ _video: flume::Sender<Frame>,+ timestamps: Timestamps,+ }++ async fn combined_actor_fixture(+ directory: &std::path::Path,+ probe: CombinedProbe,+ start_video: bool,+ ) -> CombinedFixture {+ combined_actor_fixture_sources(directory, probe, start_video, 1).await+ }++ async fn combined_actor_fixture_sources(+ directory: &std::path::Path,+ probe: CombinedProbe,+ start_video: bool,+ source_count: usize,+ ) -> CombinedFixture {+ let owner = InstantLifetimeOwner::new();+ let lifecycle = owner.lifecycle.clone();+ *lifecycle.0.runtime.lock().unwrap() = Some(tokio::runtime::Handle::current());+ let info = VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 4, 4, 30);+ let timestamps = Timestamps::now();+ let (video_sender, video_receiver) = flume::bounded(4);+ let output = directory.join("output.mp4");+ let mut builder = OutputPipeline::builder(output.clone())+ .with_video::<ChannelVideoSource<Frame>>(ChannelVideoSourceConfig::new(+ info,+ video_receiver,+ ))+ .with_timestamps(timestamps);+ let mut receivers = Vec::new();+ for _ in 0..source_count {+ let (sender, receiver) = tokio::sync::oneshot::channel();+ builder = builder+ .with_audio_source::<DirectAudioSource>((sender, probe.source_stopped.clone()));+ receivers.push(receiver);+ }+ let video = lifecycle+ .0+ .scope+ .run(builder.build::<CombinedMuxer>(probe))+ .await+ .unwrap();+ let mut audio_sources = Vec::new();+ for receiver in receivers {+ audio_sources.push(receiver.await.unwrap());+ }+ let audio = audio_sources.remove(0);+ let pipeline_cancel = video.cancel_token();+ let done = video.done_fut();+ let actor_ref = Actor::spawn(Actor {+ recording_dir: directory.to_path_buf(),+ output_dir: output.clone(),+ capture_target: ScreenCaptureTarget::CameraOnly,+ video_info: info,+ state: ActorState::Recording {+ pipeline: Pipeline {+ video,+ audio: None,+ video_info: info,+ segments_dir: directory.to_path_buf(),+ segment_rx: None,+ },+ segment_start_time: current_time_f64(),+ },+ total_pause_duration: Duration::ZERO,+ pause_started_at: None,+ terminal_stop_error: None,+ lifetime: owner,+ });+ watch_instant_tracks(lifecycle.clone(), actor_ref.clone(), done, None);+ let handle = ActorHandle {+ actor_ref,+ capture_target: ScreenCaptureTarget::CameraOnly,+ done_fut: lifecycle.done_fut(),+ health_rx: None,+ segment_rx: None,+ lifecycle,+ };+ if start_video {+ video_sender+ .send(Frame(Timestamp::Instant(timestamps.instant())))+ .unwrap();+ }+ CombinedFixture {+ handle,+ audio,+ additional_audio: audio_sources,+ pipeline_cancel,+ _video: video_sender,+ timestamps,+ }+ }++ async fn assert_combined_error(+ fixture: &CombinedFixture,+ probe: &CombinedProbe,+ message: &str,+ ) {+ let error = tokio::time::timeout(Duration::from_secs(3), fixture.handle.done_fut())+ .await+ .unwrap()+ .unwrap_err();+ assert!(error.to_string().contains(message), "{error:#}");+ assert_eq!(+ fixture.handle.lifecycle().quiescence(),+ InstantQuiescence::Joined+ );+ assert!(probe.source_stopped.load(Ordering::Acquire));+ assert!(probe.finalizer.finished.load(Ordering::Acquire));+ for _ in 0..2 {+ let error = fixture.handle.stop().await.unwrap_err();+ assert!(error.to_string().contains(message), "{error:#}");+ assert!(fixture.handle.cancel().await.is_err());+ }+ }++ #[tokio::test]+ async fn camera_only_system_request_fails_inside_joined_startup_without_capture() {+ let directory = tempfile::tempdir().unwrap();+ let output = directory.path().join("unsupported.cap");+ let builder =+ Actor::builder(output.clone(), ScreenCaptureTarget::CameraOnly).with_system_audio(true);+ let lifecycle = builder.lifecycle();+ let error = builder+ .build()+ .await+ .err()+ .expect("Unsupported system audio must fail");+ assert!(+ error.to_string().contains("System audio is not supported"),+ "{error:#}"+ );+ assert!(!output.exists());+ assert_eq!(+ lifecycle.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ assert!(+ lifecycle+ .done_fut()+ .await+ .unwrap_err()+ .to_string()+ .contains("System audio is not supported")+ );+ let supported = Actor::builder(+ directory.path().join("camera.cap"),+ ScreenCaptureTarget::CameraOnly,+ );+ let lifecycle = supported.lifecycle();+ let error = supported+ .build()+ .await+ .err()+ .expect("Missing camera must still be validated");+ assert!(+ error+ .to_string()+ .contains("Camera-only recording requires a camera"),+ "{error:#}"+ );+ assert_eq!(+ lifecycle.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ }++ #[tokio::test]+ async fn combined_mixer_errors_wait_for_owned_finalization_and_remain_terminal() {+ for (rate, message) in [+ (0, "filter input failed"),+ (u32::MAX, "filter rebuild failed"),+ ] {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::FlushInner);+ let (release, blocked) = std::sync::mpsc::channel();+ *probe.finalizer.release.lock().unwrap() = Some(blocked);+ let mut fixture =+ combined_actor_fixture_sources(directory.path(), probe.clone(), true, 2).await;+ let mut invalid = combined_audio_frame(fixture.timestamps, 0.25);+ invalid.inner.set_rate(rate);+ fixture.audio.try_send(invalid).unwrap();+ fixture.additional_audio[0]+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ tokio::time::timeout(Duration::from_secs(3), probe.finalizer.entered.notified())+ .await+ .unwrap();+ assert_eq!(+ fixture.handle.lifecycle().quiescence(),+ InstantQuiescence::Pending+ );+ assert!(+ tokio::time::timeout(Duration::from_millis(20), fixture.handle.done_fut())+ .await+ .is_err()+ );+ release.send(()).unwrap();+ assert_combined_error(&fixture, &probe, message).await;+ assert!(directory.path().join("output.mp4").is_file());+ }+ }++ #[tokio::test]+ async fn combined_closed_requested_mixer_input_cannot_complete() {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::FlushInner);+ let (release, blocked) = std::sync::mpsc::channel();+ *probe.finalizer.release.lock().unwrap() = Some(blocked);+ let mut fixture =+ combined_actor_fixture_sources(directory.path(), probe.clone(), true, 2).await;+ drop(fixture.additional_audio.remove(0));+ tokio::time::timeout(Duration::from_secs(3), probe.finalizer.entered.notified())+ .await+ .unwrap();+ assert!(fixture.pipeline_cancel.is_cancelled());+ assert_eq!(+ fixture.handle.lifecycle().quiescence(),+ InstantQuiescence::Pending+ );+ release.send(()).unwrap();+ assert_combined_error(&fixture, &probe, "source 1 closed").await;+ assert!(directory.path().join("output.mp4").is_file());+ }++ #[tokio::test]+ async fn combined_closed_single_audio_input_cannot_complete() {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::FlushInner);+ let (release, blocked) = std::sync::mpsc::channel();+ *probe.finalizer.release.lock().unwrap() = Some(blocked);+ let mut fixture = combined_actor_fixture(directory.path(), probe.clone(), true).await;+ assert!(!fixture.pipeline_cancel.is_cancelled());+ fixture.audio.close_channel();+ tokio::time::timeout(Duration::from_secs(3), probe.finalizer.entered.notified())+ .await+ .unwrap();+ assert!(fixture.pipeline_cancel.is_cancelled());+ assert_eq!(+ fixture.handle.lifecycle().quiescence(),+ InstantQuiescence::Pending+ );+ release.send(()).unwrap();+ assert_combined_error(&fixture, &probe, "Required audio source closed").await;+ assert!(directory.path().join("output.mp4").is_file());+ }++ #[tokio::test(flavor = "current_thread")]+ async fn combined_pipeline_cancellation_precedes_closed_source_error() {+ for source_count in [1, 2] {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::None);+ let mut fixture =+ combined_actor_fixture_sources(directory.path(), probe.clone(), true, source_count)+ .await;+ fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ for source in &mut fixture.additional_audio {+ source+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ }+ tokio::time::timeout(Duration::from_secs(3), probe.audio_observed.notified())+ .await+ .unwrap();+ let actor = fixture.handle.actor_ref.clone();+ let stop = tokio::spawn(async move { actor.ask(Stop).await });+ tokio::time::timeout(Duration::from_secs(3), fixture.pipeline_cancel.cancelled())+ .await+ .unwrap();+ fixture.audio.close_channel();+ fixture.additional_audio.clear();+ tokio::time::timeout(Duration::from_secs(3), stop)+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ fixture.handle.done_fut().await.unwrap();+ assert_eq!(+ fixture.handle.lifecycle().quiescence(),+ InstantQuiescence::Joined+ );+ assert!(probe.finalizer.finished.load(Ordering::Acquire));+ }+ }++ #[tokio::test]+ async fn combined_requested_mixed_audio_success_still_completes() {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::None);+ let mut fixture =+ combined_actor_fixture_sources(directory.path(), probe.clone(), true, 2).await;+ fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ fixture.additional_audio[0]+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ tokio::time::timeout(Duration::from_secs(3), probe.audio_observed.notified())+ .await+ .unwrap();+ tokio::time::timeout(Duration::from_secs(3), fixture.handle.stop())+ .await+ .unwrap()+ .unwrap();+ fixture.handle.done_fut().await.unwrap();+ assert_eq!(+ fixture.handle.lifecycle().quiescence(),+ InstantQuiescence::Joined+ );+ assert!(probe.source_stopped.load(Ordering::Acquire));+ assert!(probe.finalizer.finished.load(Ordering::Acquire));+ assert!(!probe.attempts.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn combined_audio_send_failure_waits_for_finalizer_and_never_completes() {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::AudioSend);+ let (release, blocked) = std::sync::mpsc::channel();+ *probe.finalizer.release.lock().unwrap() = Some(blocked);+ let mut fixture = combined_actor_fixture(directory.path(), probe.clone(), true).await;+ fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ tokio::time::timeout(Duration::from_secs(3), probe.finalizer.entered.notified())+ .await+ .unwrap();+ assert_eq!(+ fixture.handle.lifecycle().quiescence(),+ InstantQuiescence::Pending+ );+ assert!(fixture.handle.done_fut().now_or_never().is_none());+ assert!(probe.source_stopped.load(Ordering::Acquire));+ release.send(()).unwrap();+ assert_combined_error(&fixture, &probe, "required combined audio send failed").await;+ assert_eq!(+ std::fs::read(directory.path().join("output.mp4")).unwrap(),+ b"preserved partial test video"+ );+ }++ #[tokio::test]+ async fn combined_audio_send_error_survives_later_flush_failure() {+ let directory = tempfile::tempdir().unwrap();+ let mut probe = CombinedProbe::new(CombinedFailure::AudioSend);+ probe.finalizer.fail = true;+ let mut fixture = combined_actor_fixture(directory.path(), probe.clone(), true).await;+ fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ assert_combined_error(&fixture, &probe, "required combined audio send failed").await;+ }++ #[tokio::test]+ async fn combined_audio_drain_failure_is_retained_by_actor_stop() {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::AudioSend);+ let mut fixture = combined_actor_fixture(directory.path(), probe.clone(), false).await;+ fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ let mut full = false;+ for _ in 0..256 {+ if let Err(error) = fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.75))+ {+ assert!(error.is_full());+ full = true;+ break;+ }+ }+ assert!(full);+ tokio::time::timeout(+ Duration::from_secs(2),+ futures::future::poll_fn(|cx| fixture.audio.poll_ready(cx)),+ )+ .await+ .unwrap()+ .unwrap();+ assert!(probe.attempts.lock().unwrap().is_empty());+ let error = tokio::time::timeout(Duration::from_secs(3), fixture.handle.stop())+ .await+ .unwrap()+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("required combined audio send failed")+ );+ assert_eq!(*probe.attempts.lock().unwrap(), vec![0.75]);+ assert_combined_error(&fixture, &probe, "required combined audio send failed").await;+ }++ #[tokio::test]+ async fn combined_audio_tail_failure_is_retained_by_actor_stop() {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::AudioTail);+ let mut fixture = combined_actor_fixture(directory.path(), probe.clone(), true).await;+ fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ tokio::time::timeout(Duration::from_secs(2), probe.audio_observed.notified())+ .await+ .unwrap();+ tokio::time::sleep(Duration::from_millis(50)).await;+ let error = fixture.handle.stop().await.unwrap_err();+ assert!(error.to_string().contains("tail padding"), "{error:#}");+ let attempts = probe.attempts.lock().unwrap().clone();+ assert_eq!(attempts.first(), Some(&0.25));+ assert_eq!(attempts.last(), Some(&0.0));+ assert_combined_error(&fixture, &probe, "tail padding").await;+ }++ #[tokio::test]+ async fn combined_audio_flush_failures_never_become_complete() {+ for failure in [CombinedFailure::FlushInner, CombinedFailure::FlushOuter] {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(failure);+ let mut fixture = combined_actor_fixture(directory.path(), probe.clone(), true).await;+ fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ tokio::time::timeout(Duration::from_secs(2), probe.audio_observed.notified())+ .await+ .unwrap();+ assert!(fixture.handle.stop().await.is_err());+ let message = if failure == CombinedFailure::FlushInner {+ "required track finalization failed"+ } else {+ "combined audio outer flush failed"+ };+ assert_combined_error(&fixture, &probe, message).await;+ }+ }++ #[tokio::test]+ async fn combined_requested_audio_success_still_completes() {+ let directory = tempfile::tempdir().unwrap();+ let probe = CombinedProbe::new(CombinedFailure::None);+ let mut fixture = combined_actor_fixture(directory.path(), probe.clone(), true).await;+ fixture+ .audio+ .try_send(combined_audio_frame(fixture.timestamps, 0.25))+ .unwrap();+ tokio::time::timeout(Duration::from_secs(2), probe.audio_observed.notified())+ .await+ .unwrap();+ let completed = fixture.handle.stop().await.unwrap();+ assert!(matches!(+ completed.meta,+ InstantRecordingMeta::Complete { .. }+ ));+ assert!(fixture.handle.done_fut().await.is_ok());+ assert_eq!(+ fixture.handle.lifecycle().quiescence(),+ InstantQuiescence::Joined+ );+ assert!(probe.source_stopped.load(Ordering::Acquire));+ assert!(probe.finalizer.finished.load(Ordering::Acquire));+ }++ #[tokio::test]+ async fn stop_waits_for_actual_blocking_finalization_before_joined_or_complete() {+ let directory = tempfile::tempdir().unwrap();+ let finalizer = Finalizer::new(false);+ let (release, blocked) = std::sync::mpsc::channel();+ *finalizer.release.lock().unwrap() = Some(blocked);+ let fixture = actor_fixture(directory.path(), finalizer.clone(), None).await;+ let handle = &fixture.handle;+ let stopping = handle.stop();+ tokio::pin!(stopping);+ tokio::select! { _ = finalizer.entered.notified() => {}, _ = &mut stopping => panic!("Stop completed before finalizer entry") }+ assert_eq!(handle.lifecycle().quiescence(), InstantQuiescence::Pending);+ assert!(handle.done_fut().now_or_never().is_none());+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut stopping)+ .await+ .is_err()+ );+ release.send(()).unwrap();+ tokio::time::timeout(Duration::from_secs(2), stopping)+ .await+ .unwrap()+ .unwrap();+ assert!(finalizer.finished.load(Ordering::Acquire));+ assert_eq!(handle.lifecycle().quiescence(), InstantQuiescence::Joined);+ assert!(handle.done_fut().await.is_ok());+ }++ #[tokio::test]+ async fn required_audio_error_stops_video_and_stays_error_for_stop_and_cancel() {+ let directory = tempfile::tempdir().unwrap();+ let video = Finalizer::new(false);+ let audio = Finalizer::new(true);+ let fixture = actor_fixture(directory.path(), video.clone(), Some(audio)).await;+ let handle = &fixture.handle;+ fixture.audio_cancel.as_ref().unwrap().cancel();+ let error = tokio::time::timeout(Duration::from_secs(2), handle.done_fut())+ .await+ .unwrap()+ .unwrap_err();+ assert!(error.to_string().contains("finalization failed"));+ assert!(video.finished.load(Ordering::Acquire));+ assert_eq!(handle.lifecycle().quiescence(), InstantQuiescence::Joined);+ assert!(handle.stop().await.is_err());+ assert!(handle.cancel().await.is_err());+ assert!(handle.stop().await.is_err());+ }++ #[tokio::test]+ async fn cancel_waits_for_joined_capture_and_retains_finalization_error() {+ let directory = tempfile::tempdir().unwrap();+ let finalizer = Finalizer::new(true);+ let (release, blocked) = std::sync::mpsc::channel();+ *finalizer.release.lock().unwrap() = Some(blocked);+ let fixture = actor_fixture(directory.path(), finalizer.clone(), None).await;+ let handle = &fixture.handle;+ let cancel = handle.cancel();+ tokio::pin!(cancel);+ tokio::select! { _ = finalizer.entered.notified() => {}, _ = &mut cancel => panic!("Cancel returned before encoder exit") }+ assert_eq!(handle.lifecycle().quiescence(), InstantQuiescence::Pending);+ release.send(()).unwrap();+ assert!(cancel.await.is_err());+ assert!(handle.stop().await.is_err());+ assert_eq!(handle.lifecycle().quiescence(), InstantQuiescence::Joined);+ }++ #[tokio::test]+ async fn dropped_build_waiter_keeps_native_cleanup_owned_until_exit() {+ let owner = InstantLifetimeOwner::new();+ let lifecycle = owner.lifecycle.clone();+ let (started, started_rx) = tokio::sync::oneshot::channel();+ let (release, blocked) = std::sync::mpsc::channel();+ let finished = Arc::new(AtomicBool::new(false));+ let worker_finished = finished.clone();+ let task = tokio::spawn(run_owned_instant_build(owner, async move {+ let mut tasks = TaskPool::default();+ tasks.spawn_thread("instant-build-native", move || {+ started.send(()).unwrap();+ blocked.recv().unwrap();+ worker_finished.store(true, Ordering::Release);+ Ok(())+ });+ std::future::pending::<anyhow::Result<()>>().await+ }));+ started_rx.await.unwrap();+ task.abort();+ assert!(task.await.unwrap_err().is_cancelled());+ assert!(+ tokio::time::timeout(Duration::from_millis(20), lifecycle.wait_for_quiescence())+ .await+ .is_err()+ );+ release.send(()).unwrap();+ assert_eq!(+ tokio::time::timeout(Duration::from_secs(2), lifecycle.wait_for_quiescence())+ .await+ .unwrap(),+ InstantQuiescence::Joined+ );+ assert!(finished.load(Ordering::Acquire));+ assert!(lifecycle.done_fut().await.is_err());+ }++ #[tokio::test]+ async fn build_error_waits_for_partial_native_work_before_returning() {+ let owner = InstantLifetimeOwner::new();+ let lifecycle = owner.lifecycle.clone();+ let (started, started_rx) = tokio::sync::oneshot::channel();+ let (release, blocked) = std::sync::mpsc::channel();+ let mut task = tokio::spawn(run_owned_instant_build(owner, async move {+ let mut tasks = TaskPool::default();+ tasks.spawn_thread("instant-failed-build-native", move || {+ started.send(()).unwrap();+ blocked.recv().unwrap();+ Ok(())+ });+ Err::<(), _>(anyhow::anyhow!("later setup stage failed"))+ }));+ started_rx.await.unwrap();+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut task)+ .await+ .is_err()+ );+ assert_eq!(lifecycle.quiescence(), InstantQuiescence::Pending);+ release.send(()).unwrap();+ assert!(+ task.await+ .unwrap()+ .unwrap_err()+ .to_string()+ .contains("later setup stage failed")+ );+ assert_eq!(lifecycle.quiescence(), InstantQuiescence::Joined);+ }++ #[tokio::test]+ async fn successful_build_disarms_its_startup_owner_without_cancelling_capture() {+ let owner = InstantLifetimeOwner::new();+ let lifecycle = owner.lifecycle.clone();+ let completion = run_owned_instant_build(owner, async {+ Ok(crate::output_pipeline::PipelineBuildScope::current()+ .unwrap()+ .task_completion())+ })+ .await+ .unwrap();+ assert_eq!(lifecycle.quiescence(), InstantQuiescence::Pending);+ assert!(!lifecycle.0.scope.cancellation().is_cancelled());+ drop(completion);+ lifecycle.cancel();+ assert_eq!(+ lifecycle.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ }++ #[tokio::test]+ async fn unused_and_cancelled_before_build_lifetimes_are_joined_without_capture() {+ let builder = Actor::builder(PathBuf::new(), ScreenCaptureTarget::CameraOnly);+ let lifecycle = builder.lifecycle();+ drop(builder);+ assert_eq!(+ lifecycle.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ let builder = Actor::builder(PathBuf::new(), ScreenCaptureTarget::CameraOnly);+ let lifecycle = builder.lifecycle();+ lifecycle.cancel();+ assert_eq!(+ lifecycle.wait_for_quiescence().await,+ InstantQuiescence::Joined+ );+ assert!(builder.build().await.is_err());+ assert_eq!(lifecycle.quiescence(), InstantQuiescence::Joined);+ }+ #[tokio::test]+ async fn dropped_actor_handle_retains_cleanup_until_encoder_has_exited() {+ let directory = tempfile::tempdir().unwrap();+ let finalizer = Finalizer::new(false);+ let (release, blocked) = std::sync::mpsc::channel();+ *finalizer.release.lock().unwrap() = Some(blocked);+ let fixture = actor_fixture(directory.path(), finalizer.clone(), None).await;+ let lifecycle = fixture.handle.lifecycle();+ let done = fixture.handle.done_fut();+ drop(fixture);+ finalizer.entered.notified().await;+ assert_eq!(lifecycle.quiescence(), InstantQuiescence::Pending);+ assert!(done.clone().now_or_never().is_none());+ release.send(()).unwrap();+ assert_eq!(+ tokio::time::timeout(Duration::from_secs(2), lifecycle.wait_for_quiescence())+ .await+ .unwrap(),+ InstantQuiescence::Joined+ );+ assert!(finalizer.finished.load(Ordering::Acquire));+ assert!(done.await.is_err());+ }+ #[tokio::test]+ async fn lost_cleanup_acknowledgement_cannot_be_upgraded_to_joined_success() {+ let lifecycle = InstantLifecycle::new();+ drop(CleanupAcknowledgement {+ lifecycle: lifecycle.clone(),+ armed: true,+ });+ lifecycle.cancel();+ assert_eq!(lifecycle.quiescence(), InstantQuiescence::Unconfirmed);+ let report = lifecycle.0.scope.cancel_and_join_report().await;+ assert!(lifecycle.complete(report, None).is_err());+ assert_eq!(+ lifecycle.wait_for_quiescence().await,+ InstantQuiescence::Unconfirmed+ );+ assert!(lifecycle.done_fut().await.is_err());+ }+}++#[cfg(all(test, windows))]+mod windows_cancel_tests {+ use super::*;++ fn stopped_actor(error: Option<String>) -> Actor {+ Actor {+ recording_dir: PathBuf::new(),+ output_dir: PathBuf::new(),+ capture_target: ScreenCaptureTarget::CameraOnly,+ video_info: VideoInfo::from_raw_ffmpeg(ffmpeg::format::Pixel::RGBA, 4, 4, 30),+ state: ActorState::Stopped,+ total_pause_duration: std::time::Duration::ZERO,+ pause_started_at: None,+ terminal_stop_error: error,+ }+ }++ #[tokio::test]+ async fn cancel_actor_retains_stop_error_instead_of_reporting_success() {+ let actor = Actor::spawn(stopped_actor(Some("stop cleanup failed".into())));+ for _ in 0..2 {+ assert!(+ actor+ .ask(Cancel)+ .await+ .unwrap_err()+ .to_string()+ .contains("stop cleanup failed")+ );+ }+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[tokio::test]+ async fn cancel_of_clean_stopped_actor_succeeds() {+ let actor = Actor::spawn(stopped_actor(None));+ actor.ask(Cancel).await.unwrap();+ actor.kill();+ actor.wait_for_stop().await;+ }+}diff --git a/crates/recording/src/instant_recording/linux_camera.rs b/crates/recording/src/instant_recording/linux_camera.rsindex 5502e874c..585e59718 100644--- a/crates/recording/src/instant_recording/linux_camera.rs+++ b/crates/recording/src/instant_recording/linux_camera.rs@@ -21,15 +21,521 @@ const CAMERA_ATTACH_TIMEOUT: Duration = Duration::from_millis(1500);const CAMERA_STALE_AFTER: Duration = Duration::from_secs(1);const SCREEN_CHANNEL_CAPACITY: usize = 4;+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+/// Coordinates refer to the capture frame before the encoder applies output resizing.+pub struct LinuxCameraRect {+ pub x: u32,+ pub y: u32,+ pub width: u32,+ pub height: u32,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum LinuxCameraShape {+ Round,+ RoundedRectangle { radius_pixels: u32 },+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum LinuxCameraEffect {+ None,+ BackgroundBlur,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct LinuxCameraPresentation {+ pub rect: LinuxCameraRect,+ pub shape: LinuxCameraShape,+ pub mirrored: bool,+ pub effect: LinuxCameraEffect,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum LinuxCameraPresentationError {+ #[error("Camera presentation dimensions must be nonzero")]+ EmptyDimensions,+ #[error("Camera presentation must fit entirely within the capture frame")]+ OutsideCapture,+ #[error("Round camera presentation requires equal width and height")]+ NonSquareCircle,+ #[error("Camera corner radius exceeds half the shorter edge")]+ InvalidRadius,+ #[error("Camera background blur requires a processed camera stream")]+ UnsupportedEffect,+ #[error("Camera presentation requires a selected camera")]+ MissingCamera,+ #[error("Camera presentation requires a screen capture target")]+ UnsupportedTarget,+}++impl LinuxCameraPresentation {+ pub fn validate(self, width: u32, height: u32) -> Result<(), LinuxCameraPresentationError> {+ let rect = self.rect;+ if width == 0 || height == 0 || rect.width == 0 || rect.height == 0 {+ return Err(LinuxCameraPresentationError::EmptyDimensions);+ }+ if rect+ .x+ .checked_add(rect.width)+ .is_none_or(|right| right > width)+ || rect+ .y+ .checked_add(rect.height)+ .is_none_or(|bottom| bottom > height)+ {+ return Err(LinuxCameraPresentationError::OutsideCapture);+ }+ match self.shape {+ LinuxCameraShape::Round if rect.width != rect.height => {+ return Err(LinuxCameraPresentationError::NonSquareCircle);+ }+ LinuxCameraShape::RoundedRectangle { radius_pixels }+ if radius_pixels > rect.width.min(rect.height) / 2 =>+ {+ return Err(LinuxCameraPresentationError::InvalidRadius);+ }+ _ => {}+ }+ if self.effect != LinuxCameraEffect::None {+ return Err(LinuxCameraPresentationError::UnsupportedEffect);+ }+ Ok(())+ }++ pub fn resolve(+ self,+ reference: (u32, u32),+ actual: (u32, u32),+ ) -> Result<Self, LinuxCameraPresentationError> {+ let geometry = Self {+ effect: LinuxCameraEffect::None,+ ..self+ };+ geometry.validate(reference.0, reference.1)?;+ if actual.0 == 0 || actual.1 == 0 {+ return Err(LinuxCameraPresentationError::EmptyDimensions);+ }+ let scale = |value: u32, from: u32, to: u32| -> u32 {+ ((u64::from(value) * u64::from(to) + u64::from(from) / 2) / u64::from(from)) as u32+ };+ let x = scale(self.rect.x, reference.0, actual.0);+ let y = scale(self.rect.y, reference.1, actual.1);+ let right = scale(self.rect.x + self.rect.width, reference.0, actual.0);+ let bottom = scale(self.rect.y + self.rect.height, reference.1, actual.1);+ let shape = match self.shape {+ LinuxCameraShape::Round+ if right.saturating_sub(x).abs_diff(bottom.saturating_sub(y)) == 1 =>+ {+ LinuxCameraShape::RoundedRectangle {+ radius_pixels: right.saturating_sub(x).min(bottom.saturating_sub(y)) / 2,+ }+ }+ LinuxCameraShape::Round => LinuxCameraShape::Round,+ LinuxCameraShape::RoundedRectangle { radius_pixels } => {+ LinuxCameraShape::RoundedRectangle {+ radius_pixels: scale(radius_pixels, reference.0, actual.0).min(scale(+ radius_pixels,+ reference.1,+ actual.1,+ )),+ }+ }+ };+ let result = Self {+ rect: LinuxCameraRect {+ x,+ y,+ width: right.saturating_sub(x),+ height: bottom.saturating_sub(y),+ },+ shape,+ ..self+ };+ Self {+ effect: LinuxCameraEffect::None,+ ..result+ }+ .validate(actual.0, actual.1)?;+ Ok(result)+ }++ fn default_for(width: u32, height: u32) -> Self {+ let (x, y, size) = overlay_rect(width, height);+ Self {+ rect: LinuxCameraRect {+ x: x as u32,+ y: y as u32,+ width: size,+ height: size,+ },+ shape: LinuxCameraShape::RoundedRectangle { radius_pixels: 0 },+ mirrored: false,+ effect: LinuxCameraEffect::None,+ }+ }++ fn radius(self) -> f64 {+ match self.shape {+ LinuxCameraShape::Round => f64::from(self.rect.width) / 2.0,+ LinuxCameraShape::RoundedRectangle { radius_pixels } => f64::from(radius_pixels),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum LinuxCameraBlur {+ Off,+ Light,+ Heavy,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct LinuxCameraProcessing {+ pub mirrored: bool,+ pub blur: LinuxCameraBlur,+}++#[derive(Debug, Clone, Copy)]+pub struct LinuxCameraMaskReceipt {+ pub generation: u64,+ pub submitted_at: Instant,+ pub completed_at: Instant,+}++#[derive(Debug, Clone)]+pub struct LinuxProcessedCameraFrame {+ pub bgra: Arc<[u8]>,+ pub dimensions: (u32, u32),+ pub stride: usize,+ pub timestamp: Timestamp,+ pub generation: u64,+ pub processing: LinuxCameraProcessing,+ pub mask: Option<LinuxCameraMaskReceipt>,+}++pub const LINUX_CAMERA_MAX_MASK_AGE: Duration = Duration::from_millis(750);++#[derive(Clone)]+enum ProcessedCameraState {+ Pending,+ Frame(Arc<LinuxProcessedCameraFrame>),+ Failed(String),+}++pub struct LinuxCameraPublisher {+ state: tokio::sync::watch::Sender<ProcessedCameraState>,+ stop: CancellationToken,+}++impl LinuxCameraPublisher {+ pub fn is_cancelled(&self) -> bool {+ self.stop.is_cancelled()+ }++ pub fn publish(&self, frame: LinuxProcessedCameraFrame) {+ self.state.send_if_modified(|state| {+ if matches!(state, ProcessedCameraState::Failed(_)) {+ return false;+ }+ *state = ProcessedCameraState::Frame(Arc::new(frame));+ true+ });+ }++ pub fn fail(&self, error: String) {+ self.state.send_if_modified(|state| {+ if matches!(state, ProcessedCameraState::Failed(_)) {+ return false;+ }+ *state = ProcessedCameraState::Failed(error);+ true+ });+ }+}++impl Drop for LinuxCameraPublisher {+ fn drop(&mut self) {+ self.fail("Processed camera worker disconnected".to_string());+ }+}++pub struct LinuxProcessedCameraSource {+ reader: ProcessedCameraReader,+ camera_feed: Arc<CameraFeedLock>,+}++struct ProcessedCameraReader {+ state: tokio::sync::watch::Receiver<ProcessedCameraState>,+ processing: LinuxCameraProcessing,+ generation: u64,+ not_before: Instant,+ _stop: tokio_util::sync::DropGuard,+}++fn processed_camera_channel(+ processing: LinuxCameraProcessing,+ generation: u64,+ not_before: Instant,+) -> (LinuxCameraPublisher, ProcessedCameraReader) {+ let stop = CancellationToken::new();+ let (state, receiver) = tokio::sync::watch::channel(ProcessedCameraState::Pending);+ (+ LinuxCameraPublisher {+ state,+ stop: stop.clone(),+ },+ ProcessedCameraReader {+ state: receiver,+ processing,+ generation,+ not_before,+ _stop: stop.drop_guard(),+ },+ )+}++impl LinuxProcessedCameraSource {+ pub fn channel(+ camera_feed: Arc<CameraFeedLock>,+ processing: LinuxCameraProcessing,+ generation: u64,+ not_before: Instant,+ ) -> (LinuxCameraPublisher, Self) {+ let (publisher, reader) = processed_camera_channel(processing, generation, not_before);+ (+ publisher,+ Self {+ reader,+ camera_feed,+ },+ )+ }++ pub async fn wait_ready(&mut self, timeout: Duration) -> anyhow::Result<()> {+ self.reader.wait_ready(timeout).await+ }+}++impl ProcessedCameraReader {+ fn validate_current(&self) -> anyhow::Result<bool> {+ match &*self.state.borrow() {+ ProcessedCameraState::Pending => Ok(false),+ ProcessedCameraState::Failed(error) => Err(anyhow!("{error}")),+ ProcessedCameraState::Frame(frame) => {+ validate_processed_frame(+ frame,+ self.processing,+ self.generation,+ self.not_before,+ Instant::now(),+ )?;+ Ok(true)+ }+ }+ }++ fn current(&mut self) -> anyhow::Result<Option<FFmpegVideoFrame>> {+ let state = self.state.borrow_and_update().clone();+ match state {+ ProcessedCameraState::Pending => Ok(None),+ ProcessedCameraState::Failed(error) => Err(anyhow!("{error}")),+ ProcessedCameraState::Frame(frame) => {+ validate_processed_frame(+ &frame,+ self.processing,+ self.generation,+ self.not_before,+ Instant::now(),+ )?;+ processed_to_ffmpeg(&frame).map(Some)+ }+ }+ }++ pub async fn wait_ready(&mut self, timeout: Duration) -> anyhow::Result<()> {+ tokio::time::timeout(timeout, async {+ loop {+ if self.validate_current()? {+ return Ok(());+ }+ self.state+ .changed()+ .await+ .context("Processed camera worker disconnected")?;+ }+ })+ .await+ .context("Processed camera did not become ready before the startup deadline")?+ }+}++fn validate_processed_frame(+ frame: &LinuxProcessedCameraFrame,+ expected: LinuxCameraProcessing,+ generation: u64,+ not_before: Instant,+ now: Instant,+) -> anyhow::Result<()> {+ anyhow::ensure!(+ frame.generation == generation,+ "Processed camera generation changed"+ );+ anyhow::ensure!(+ frame.processing == expected,+ "Processed camera effects changed"+ );+ let Timestamp::Instant(captured_at) = frame.timestamp else {+ anyhow::bail!("Processed camera requires an original monotonic capture timestamp");+ };+ anyhow::ensure!(+ captured_at >= not_before && captured_at <= now,+ "Processed camera frame predates its source lease or has a future timestamp"+ );+ anyhow::ensure!(+ camera_is_fresh(captured_at, now),+ "Processed camera frame is stale"+ );+ match (expected.blur, frame.mask) {+ (LinuxCameraBlur::Off, None) => {}+ (LinuxCameraBlur::Light | LinuxCameraBlur::Heavy, Some(mask)) => {+ anyhow::ensure!(+ mask.generation > 0+ && mask.submitted_at >= not_before+ && mask.submitted_at <= mask.completed_at+ && mask.completed_at <= now,+ "Processed camera mask has invalid provenance"+ );+ anyhow::ensure!(+ now.saturating_duration_since(mask.submitted_at) <= LINUX_CAMERA_MAX_MASK_AGE,+ "Processed camera blur mask is stale"+ );+ }+ _ => anyhow::bail!("Processed camera blur was not applied as requested"),+ }+ let (width, height) = frame.dimensions;+ let row = usize::try_from(width)+ .ok()+ .and_then(|width| width.checked_mul(4))+ .context("Processed camera row overflow")?;+ let size = frame+ .stride+ .checked_mul(height as usize)+ .context("Processed camera size overflow")?;+ anyhow::ensure!(+ width > 0 && height > 0 && frame.stride >= row && frame.bgra.len() == size,+ "Processed camera has invalid BGRA dimensions or stride"+ );+ Ok(())+}++fn processed_to_ffmpeg(frame: &LinuxProcessedCameraFrame) -> anyhow::Result<FFmpegVideoFrame> {+ let (width, height) = frame.dimensions;+ let mut inner = ffmpeg::frame::Video::new(Pixel::BGRA, width, height);+ let stride = inner.stride(0);+ let row = width as usize * 4;+ for y in 0..height as usize {+ inner.data_mut(0)[y * stride..y * stride + row]+ .copy_from_slice(&frame.bgra[y * frame.stride..y * frame.stride + row]);+ }+ Ok(FFmpegVideoFrame {+ inner,+ timestamp: frame.timestamp,+ })+}+pub(super) struct Config {pub(super) screen_capture: screen_capture::VideoSourceConfig,- pub(super) camera_feed: Arc<CameraFeedLock>,+ pub(super) camera: PreparedCamera,+}++pub(super) struct PreparedCamera {+ camera_feed: Arc<CameraFeedLock>,+ frames: PreparedCameraFrames,+}++struct PreparedCameraFrames {+ receiver: CameraReceiver,+ first: FFmpegVideoFrame,+ presentation: LinuxCameraPresentation,+}++impl PreparedCamera {+ pub(super) async fn prepare(+ camera_feed: Arc<CameraFeedLock>,+ presentation: Option<LinuxCameraPresentation>,+ processed: Option<LinuxProcessedCameraSource>,+ reference_size: Option<(u32, u32)>,+ info: VideoInfo,+ ) -> anyhow::Result<(Self, cap_timestamp::Timestamps)> {+ let mut presentation = presentation+ .unwrap_or_else(|| LinuxCameraPresentation::default_for(info.width, info.height));+ if let Some(reference) = reference_size {+ presentation = presentation.resolve(reference, (info.width, info.height))?;+ }+ let receiver = if let Some(processed) = processed {+ anyhow::ensure!(+ Arc::ptr_eq(&processed.camera_feed, &camera_feed),+ "Processed camera source belongs to a different feed lock"+ );+ anyhow::ensure!(+ presentation.mirrored == processed.reader.processing.mirrored,+ "Processed camera mirror does not match presentation"+ );+ anyhow::ensure!(+ (presentation.effect == LinuxCameraEffect::None)+ == (processed.reader.processing.blur == LinuxCameraBlur::Off),+ "Processed camera blur does not match presentation"+ );+ presentation.mirrored = false;+ presentation.effect = LinuxCameraEffect::None;+ CameraReceiver::Processed(processed.reader)+ } else {+ let (camera_tx, camera_rx) = flume::bounded(1);+ tokio::time::timeout(+ CAMERA_ATTACH_TIMEOUT,+ camera_feed.ask(camera::AddSender(camera_tx)),+ )+ .await+ .context("Camera compositor timed out attaching to feed")?+ .map_err(|error| anyhow!("Camera compositor failed to attach to feed: {error}"))?;+ CameraReceiver::Raw(camera_rx)+ };+ let (frames, timestamps) = prepare_camera_frames(receiver, info, presentation).await?;+ Ok((+ Self {+ camera_feed,+ frames,+ },+ timestamps,+ ))+ }+}++async fn prepare_camera_frames(+ mut receiver: CameraReceiver,+ info: VideoInfo,+ presentation: LinuxCameraPresentation,+) -> anyhow::Result<(PreparedCameraFrames, cap_timestamp::Timestamps)> {+ presentation.validate(info.width, info.height)?;+ let first = receiver.first(&CancellationToken::new()).await?;+ Compositor::new(info, presentation).camera_overlay(&first.inner)?;+ // Separate Instant audio is epoch-anchored; camera readiness must not become head silence.+ let timestamps = cap_timestamp::Timestamps::now();+ Ok((+ PreparedCameraFrames {+ receiver,+ first,+ presentation,+ },+ timestamps,+ ))}pub(super) struct CameraCompositeSource {inner: screen_capture::VideoSource,info: VideoInfo,_camera_feed: Arc<CameraFeedLock>,+ _compositor_stop: tokio_util::sync::DropGuard,}impl VideoSource for CameraCompositeSource {@@ -40,44 +546,44 @@ impl VideoSource for CameraCompositeSource {config: Self::Config,video_tx: mpsc::Sender<Self::Frame>,ctx: &mut SetupCtx,- ) -> anyhow::Result<Self>- where- Self: Sized,- {- let (camera_tx, camera_rx) = flume::bounded(1);- tokio::time::timeout(- CAMERA_ATTACH_TIMEOUT,- config.camera_feed.ask(camera::AddSender(camera_tx)),- )- .await- .map_err(|_| {- anyhow!("Camera compositor timed out attaching to feed after {CAMERA_ATTACH_TIMEOUT:?}")- })?- .map_err(|error| anyhow!("Camera compositor failed to attach to feed: {error}"))?;-+ ) -> anyhow::Result<Self> {+ let stop_token = ctx.stop_token().child_token();+ let compositor_stop = stop_token.clone().drop_guard();+ let info = config.screen_capture.video_info();+ let PreparedCamera {+ camera_feed,+ frames,+ } = config.camera;+ let PreparedCameraFrames {+ receiver: camera_rx,+ first: first_camera,+ presentation,+ } = frames;+ validate_camera_frame(&first_camera, Instant::now())?;let (screen_tx, screen_rx) = mpsc::channel(SCREEN_CHANNEL_CAPACITY);let inner = screen_capture::VideoSource::setup(config.screen_capture, screen_tx, ctx).await.context("screen source setup for camera compositor")?;- let info = inner.video_info();- let stop_token = ctx.stop_token();let health_tx = ctx.health_tx().clone();+ let runtime = tokio::runtime::Handle::current();ctx.tasks().spawn_thread("linux-instant-camera-compositor", move || {+ let _runtime = runtime.enter();compositor_thread(screen_rx,- Some(camera_rx),+ camera_rx,video_tx,stop_token,health_tx,- info,+ Compositor::new(info, presentation),+ first_camera,)});-Ok(Self {inner,info,- _camera_feed: config.camera_feed,+ _camera_feed: camera_feed,+ _compositor_stop: compositor_stop,})}@@ -94,141 +600,153 @@ impl VideoSource for CameraCompositeSource {}}+enum CameraReceiver {+ Raw(flume::Receiver<FFmpegVideoFrame>),+ Processed(ProcessedCameraReader),+}++impl CameraReceiver {+ async fn first(&mut self, stop: &CancellationToken) -> anyhow::Result<FFmpegVideoFrame> {+ match self {+ Self::Raw(rx) => first_camera_frame(rx, stop, CAMERA_ATTACH_TIMEOUT).await,+ Self::Processed(source) => {+ tokio::select! {+ biased;+ _ = stop.cancelled() => anyhow::bail!("Camera compositor startup cancelled"),+ ready = source.wait_ready(CAMERA_ATTACH_TIMEOUT) => ready?,+ }+ source+ .current()?+ .context("Processed camera first frame missing")+ }+ }+ }++ async fn recv(&mut self) -> anyhow::Result<FFmpegVideoFrame> {+ match self {+ Self::Raw(rx) => rx+ .recv_async()+ .await+ .context("Required camera disconnected"),+ Self::Processed(source) => loop {+ source+ .state+ .changed()+ .await+ .context("Processed camera worker disconnected")?;+ if let Some(frame) = source.current()? {+ return Ok(frame);+ }+ },+ }+ }++ fn latest(&mut self) -> anyhow::Result<Option<FFmpegVideoFrame>> {+ match self {+ Self::Raw(rx) => match rx.try_recv() {+ Ok(frame) => Ok(Some(frame)),+ Err(flume::TryRecvError::Empty) => Ok(None),+ Err(flume::TryRecvError::Disconnected) => {+ anyhow::bail!("Required camera disconnected")+ }+ },+ Self::Processed(source) => {+ if source+ .state+ .has_changed()+ .context("Processed camera worker disconnected")?+ {+ source.current()+ } else {+ source.validate_current()?;+ Ok(None)+ }+ }+ }+ }+}++async fn first_camera_frame(+ camera_rx: &flume::Receiver<FFmpegVideoFrame>,+ stop_token: &CancellationToken,+ timeout: Duration,+) -> anyhow::Result<FFmpegVideoFrame> {+ tokio::select! {+ biased;+ _ = stop_token.cancelled() => anyhow::bail!("Camera compositor startup cancelled"),+ received = tokio::time::timeout(timeout, camera_rx.recv_async()) => {+ let frame = received.context("Camera did not deliver its first frame before the startup deadline")?+ .context("Camera disconnected before its first frame")?;+ validate_camera_frame(&frame, Instant::now())?;+ Ok(frame)+ }+ }+}++fn validate_camera_frame(frame: &FFmpegVideoFrame, now: Instant) -> anyhow::Result<()> {+ if frame.inner.width() == 0 || frame.inner.height() == 0 || frame.inner.planes() == 0 {+ anyhow::bail!("Camera delivered an invalid frame");+ }+ if !camera_is_fresh(camera_freshness_anchor(frame, now), now) {+ anyhow::bail!("Camera frame exceeded the freshness deadline");+ }+ Ok(())+}+fn compositor_thread(screen_rx: mpsc::Receiver<FFmpegVideoFrame>,- camera_rx: Option<flume::Receiver<FFmpegVideoFrame>>,+ mut camera_rx: CameraReceiver,mut video_tx: mpsc::Sender<FFmpegVideoFrame>,stop_token: CancellationToken,health_tx: output_pipeline::HealthSender,- info: VideoInfo,+ mut compositor: Compositor,+ first_camera: FFmpegVideoFrame,) -> anyhow::Result<()> {- futures::executor::block_on(async move {+ let result = futures::executor::block_on(async {let mut screen_rx = screen_rx.fuse();- let mut camera_closed = camera_rx.is_none();- let camera_started_at = Instant::now();- let mut camera_seen = camera_rx.is_none();- let mut latest_camera: Option<(FFmpegVideoFrame, Instant)> = None;- let mut compositor = Compositor::new(info);- let mut logged_compose_failure = false;- let mut logged_camera_disconnect = false;- let mut logged_camera_stale = false;-+ let mut latest_camera = first_camera;+ let mut freshness_anchor = camera_freshness_anchor(&latest_camera, Instant::now());loop {- let stop = stop_token.cancelled().fuse();- let active_camera = camera_rx.as_ref().filter(|_| !camera_closed);- let camera = async {- match active_camera {- Some(receiver) => receiver.recv_async().await,- None => std::future::pending().await,- }+ enum Event {+ Stop,+ Stale,+ Camera(anyhow::Result<FFmpegVideoFrame>),+ Screen(Option<FFmpegVideoFrame>),}- .fuse();- let screen = screen_rx.next().fuse();- futures::pin_mut!(stop, camera, screen);-- futures::select! {- _ = stop => break,- camera_result = camera => match camera_result {- Ok(frame) => {- camera_seen = true;- let received_at = Instant::now();- let freshness_anchor = camera_freshness_anchor(&frame, received_at);- latest_camera = Some((frame, freshness_anchor));- }- Err(_) => {- camera_closed = true;- latest_camera = None;- if !logged_camera_disconnect {- tracing::warn!("Camera feed disconnected; continuing with screen-only output");- output_pipeline::emit_health(- &health_tx,- output_pipeline::PipelineHealthEvent::DeviceLost {- subsystem: "camera".to_string(),- },- );- logged_camera_disconnect = true;- }- }- },- screen_result = screen => {- let Some(screen) = screen_result else { break };-- if let Some(camera_rx) = camera_rx.as_ref() {- loop {- match camera_rx.try_recv() {- Ok(frame) => {- camera_seen = true;- let received_at = Instant::now();- let freshness_anchor =- camera_freshness_anchor(&frame, received_at);- latest_camera = Some((frame, freshness_anchor));- }- Err(flume::TryRecvError::Empty) => break,- Err(flume::TryRecvError::Disconnected) => {- camera_closed = true;- latest_camera = None;- if !logged_camera_disconnect {- tracing::warn!("Camera feed disconnected; continuing with screen-only output");- output_pipeline::emit_health(- &health_tx,- output_pipeline::PipelineHealthEvent::DeviceLost {- subsystem: "camera".to_string(),- },- );- logged_camera_disconnect = true;- }- break;- }- }- }- }-- let mut clear_latest_camera = false;- let now = Instant::now();- let camera_is_stale = latest_camera- .as_ref()- .is_some_and(|(_, received_at)| !camera_is_fresh(*received_at, now));- let camera_waiting_for_first_frame = !camera_closed- && !camera_seen- && now.saturating_duration_since(camera_started_at) > CAMERA_STALE_AFTER;- if (camera_is_stale || camera_waiting_for_first_frame) && !logged_camera_stale {- tracing::warn!(- stale_after_ms = CAMERA_STALE_AFTER.as_millis(),- "Camera feed is stale; continuing with screen-only output"- );- output_pipeline::emit_health(- &health_tx,- output_pipeline::PipelineHealthEvent::Stalled {- source: "camera-compositor".to_string(),- waited_ms: CAMERA_STALE_AFTER.as_millis() as u64,- },- );- logged_camera_stale = true;- }- if !camera_is_stale && !camera_waiting_for_first_frame {- logged_camera_stale = false;+ let event = {+ let stop = stop_token.cancelled().fuse();+ let camera = camera_rx.recv().fuse();+ let screen = screen_rx.next().fuse();+ let remaining = CAMERA_STALE_AFTER.saturating_sub(freshness_anchor.elapsed());+ let stale = tokio::time::sleep(remaining).fuse();+ futures::pin_mut!(stop, camera, screen, stale);+ futures::select_biased! {+ _ = stop => Event::Stop,+ _ = stale => Event::Stale,+ result = camera => Event::Camera(result),+ result = screen => Event::Screen(result),+ }+ };+ match event {+ Event::Stop | Event::Screen(None) => break,+ Event::Stale => anyhow::bail!("Required camera stopped delivering fresh frames"),+ Event::Camera(frame) => {+ latest_camera = frame?;+ validate_camera_frame(&latest_camera, Instant::now())?;+ freshness_anchor = camera_freshness_anchor(&latest_camera, Instant::now());+ }+ Event::Screen(Some(screen)) => {+ if let Some(frame) = camera_rx.latest()? {+ latest_camera = frame;+ freshness_anchor = camera_freshness_anchor(&latest_camera, Instant::now());}- let output = match latest_camera- .as_ref()- .filter(|(_, received_at)| camera_is_fresh(*received_at, now))- {- Some((camera, _)) => match compositor.compose(&screen, camera) {- Ok(frame) => frame,- Err(error) => {- clear_latest_camera = true;- if !logged_compose_failure {- tracing::warn!(error = %error, "Camera compositor degraded to screen-only output");- logged_compose_failure = true;- }- screen- }- },- None => screen,- };- if clear_latest_camera {- latest_camera = None;+ validate_camera_frame(&latest_camera, Instant::now())?;+ let output = compositor+ .compose(&screen, &latest_camera)+ .context("Required camera composition failed")?;+ if stop_token.is_cancelled() {+ break;}-if matches!(send_with_stall_budget_futures(&mut video_tx,@@ -240,12 +758,20 @@ fn compositor_thread() {break;}- },+ }}}-Ok(())- })+ });+ if result.is_err() {+ output_pipeline::emit_health(+ &health_tx,+ output_pipeline::PipelineHealthEvent::DeviceLost {+ subsystem: "camera-compositor".to_string(),+ },+ );+ }+ result}fn camera_is_fresh(received_at: Instant, now: Instant) -> bool {@@ -261,15 +787,17 @@ fn camera_freshness_anchor(frame: &FFmpegVideoFrame, received_at: Instant) -> Instruct Compositor {info: VideoInfo,+ presentation: LinuxCameraPresentation,screen_to_rgba: Option<RgbaConverter>,camera_to_rgba: Option<RgbaConverter>,rgba_to_screen: Option<RgbaConverter>,}impl Compositor {- fn new(info: VideoInfo) -> Self {+ fn new(info: VideoInfo, presentation: LinuxCameraPresentation) -> Self {Self {info,+ presentation,screen_to_rgba: None,camera_to_rgba: None,rgba_to_screen: None,@@ -282,14 +810,16 @@ impl Compositor {camera: &FFmpegVideoFrame,) -> anyhow::Result<FFmpegVideoFrame> {let screen_rgba = self.convert_screen(&screen.inner)?;- let rect = overlay_rect(self.info.width, self.info.height);- if rect.2 == 0 {- return Err(anyhow!("screen dimensions are empty"));- }- let camera_rgba = self.convert_camera(&camera.inner, rect.2)?;- let camera_overlay = center_crop_square(&camera_rgba, rect.2)?;+ self.presentation+ .validate(self.info.width, self.info.height)?;+ let camera_overlay = self.camera_overlay(&camera.inner)?;let mut composed = screen_rgba;- blend_rgba(&mut composed, &camera_overlay, rect.0, rect.1)?;+ blend_rgba(+ &mut composed,+ &camera_overlay,+ self.presentation.rect.x as usize,+ self.presentation.rect.y as usize,+ )?;let mut output = self.convert_to_screen(&composed)?;output.set_pts(screen.inner.pts());@@ -299,6 +829,15 @@ impl Compositor {})}+ fn camera_overlay(+ &mut self,+ input: &ffmpeg::frame::Video,+ ) -> anyhow::Result<ffmpeg::frame::Video> {+ let rect = self.presentation.rect;+ let rgba = self.convert_camera(input, rect.width, rect.height)?;+ crop_camera(&rgba, self.presentation)+ }+fn convert_screen(&mut self,input: &ffmpeg::frame::Video,@@ -327,10 +866,11 @@ impl Compositor {fn convert_camera(&mut self,input: &ffmpeg::frame::Video,- size: u32,+ width: u32,+ height: u32,) -> anyhow::Result<ffmpeg::frame::Video> {let (destination_width, destination_height) =- aspect_fill_dimensions(input.width(), input.height(), size)?;+ aspect_fill_dimensions(input.width(), input.height(), width, height)?;let needs_converter = self.camera_to_rgba.as_ref().is_none_or(|converter| {converter.source_format != input.format()|| converter.source_width != input.width()@@ -457,52 +997,76 @@ fn overlay_rect(width: u32, height: u32) -> (usize, usize, u32) {(x as usize, y as usize, size)}-fn aspect_fill_dimensions(width: u32, height: u32, size: u32) -> anyhow::Result<(u32, u32)> {- if width == 0 || height == 0 || size == 0 {+fn aspect_fill_dimensions(+ width: u32,+ height: u32,+ target_width: u32,+ target_height: u32,+) -> anyhow::Result<(u32, u32)> {+ if width == 0 || height == 0 || target_width == 0 || target_height == 0 {return Err(anyhow!("invalid dimensions for camera scaling"));}- if width >= height {- let scaled_width = (u64::from(size) * u64::from(width)).div_ceil(u64::from(height));- Ok((scaled_width.min(u64::from(u32::MAX)) as u32, size))+ if u64::from(width) * u64::from(target_height) >= u64::from(height) * u64::from(target_width) {+ let scaled = (u64::from(target_height) * u64::from(width)).div_ceil(u64::from(height));+ Ok((+ u32::try_from(scaled).context("Camera scaling exceeds supported width")?,+ target_height,+ ))} else {- let scaled_height = (u64::from(size) * u64::from(height)).div_ceil(u64::from(width));- Ok((size, scaled_height.min(u64::from(u32::MAX)) as u32))+ let scaled = (u64::from(target_width) * u64::from(height)).div_ceil(u64::from(width));+ Ok((+ target_width,+ u32::try_from(scaled).context("Camera scaling exceeds supported height")?,+ ))}}-fn center_crop_square(+fn crop_camera(source: &ffmpeg::frame::Video,- size: u32,+ presentation: LinuxCameraPresentation,) -> anyhow::Result<ffmpeg::frame::Video> {- if size == 0 || source.width() == 0 || source.height() == 0 {- return Err(anyhow!("invalid camera dimensions for compositor"));- }- let source_width = source.width() as usize;- let source_height = source.height() as usize;- let crop_size = source_width.min(source_height);- if crop_size < size as usize {- return Err(anyhow!("scaled camera frame is smaller than overlay"));+ let rect = presentation.rect;+ if source.format() != Pixel::RGBA+ || rect.width == 0+ || rect.height == 0+ || source.width() < rect.width+ || source.height() < rect.height+ {+ anyhow::bail!("Scaled camera frame is smaller than its presentation");}- let crop_x = (source_width - size as usize) / 2;- let crop_y = (source_height - size as usize) / 2;- let mut output = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, size, size);+ let crop_x = (source.width() - rect.width) as usize / 2;+ let crop_y = (source.height() - rect.height) as usize / 2;+ let mut output = ffmpeg::frame::Video::new(Pixel::RGBA, rect.width, rect.height);let source_stride = source.stride(0);let output_stride = output.stride(0);let source_data = source.data(0);let output_data = output.data_mut(0);- for y in 0..size as usize {- let source_y = crop_y + y;- for x in 0..size as usize {- let source_x = crop_x + x;- let source_offset = source_y * source_stride + source_x * 4;+ let radius = presentation.radius();+ for y in 0..rect.height as usize {+ for x in 0..rect.width as usize {+ let source_x = crop_x+ + if presentation.mirrored {+ rect.width as usize - 1 - x+ } else {+ x+ };+ let source_offset = (crop_y + y) * source_stride + source_x * 4;let output_offset = y * output_stride + x * 4;- if source_offset + 4 > source_data.len() || output_offset + 4 > output_data.len() {- return Err(anyhow!(- "RGBA camera frame layout is smaller than dimensions"- ));+ let source_pixel = source_data+ .get(source_offset..source_offset + 4)+ .context("RGBA camera frame layout is smaller than dimensions")?;+ let destination = output_data+ .get_mut(output_offset..output_offset + 4)+ .context("RGBA camera output layout is smaller than dimensions")?;+ destination.copy_from_slice(source_pixel);+ if radius > 0.0 {+ let px = x as f64 + 0.5;+ let py = y as f64 + 0.5;+ let dx = px - px.clamp(radius, f64::from(rect.width) - radius);+ let dy = py - py.clamp(radius, f64::from(rect.height) - radius);+ let coverage = (radius + 0.5 - dx.hypot(dy)).clamp(0.0, 1.0);+ destination[3] = (f64::from(destination[3]) * coverage).round() as u8;}- output_data[output_offset..output_offset + 4]- .copy_from_slice(&source_data[source_offset..source_offset + 4]);}}output.set_pts(source.pts());@@ -558,6 +1122,828 @@ mod tests {use super::*;use futures::SinkExt;+ #[tokio::test]+ async fn prepared_camera_epoch_excludes_delayed_raw_readiness() {+ ffmpeg::init().unwrap();+ for delay in [+ Duration::ZERO,+ Duration::from_millis(25),+ Duration::from_millis(800),+ ] {+ let previous_epoch = cap_timestamp::Timestamps::now();+ let (sender, receiver) = flume::bounded(1);+ let prepare = prepare_camera_frames(+ CameraReceiver::Raw(receiver),+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30),+ presentation(4, 4),+ );+ let deliver = async {+ tokio::time::sleep(delay).await;+ let frame = camera_frame();+ let Timestamp::Instant(captured_at) = frame.timestamp else {+ panic!("monotonic fixture")+ };+ sender.send_async(frame).await.unwrap();+ captured_at+ };+ let (prepared, captured_at) = tokio::join!(prepare, deliver);+ let (frames, epoch) = prepared.unwrap();+ assert!(epoch.instant() >= captured_at);+ assert!(+ epoch+ .instant()+ .saturating_duration_since(previous_epoch.instant())+ >= delay+ );+ assert!(+ matches!(frames.first.timestamp, Timestamp::Instant(value) if value == captured_at)+ );+ let marker = Timestamp::Instant(epoch.instant() + Duration::from_millis(250));+ assert_eq!(marker.signed_duration_since_secs(epoch), 0.25);+ assert!(+ marker.signed_duration_since_secs(previous_epoch) >= delay.as_secs_f64() + 0.25+ );+ assert!(!sender.is_disconnected());+ drop(frames);+ assert!(sender.is_disconnected());+ }+ }++ #[tokio::test]+ async fn prepared_camera_epoch_excludes_pending_processed_readiness() {+ ffmpeg::init().unwrap();+ let not_before = Instant::now();+ let processing = processed_frame(not_before, 11).processing;+ let (publisher, reader) = processed_camera_channel(processing, 11, not_before);+ let prepare = prepare_camera_frames(+ CameraReceiver::Processed(reader),+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30),+ presentation(4, 4),+ );+ let deliver = async {+ tokio::time::sleep(Duration::from_millis(25)).await;+ let captured_at = Instant::now();+ publisher.publish(processed_frame(captured_at, 11));+ captured_at+ };+ let (prepared, captured_at) = tokio::join!(prepare, deliver);+ let (frames, epoch) = prepared.unwrap();+ assert!(epoch.instant() >= captured_at);+ assert!(+ matches!(frames.first.timestamp, Timestamp::Instant(value) if value == captured_at)+ );+ let late_audio = Timestamp::Instant(epoch.instant() + Duration::from_millis(2500));+ assert_eq!(late_audio.signed_duration_since_secs(epoch), 2.5);+ assert!(!publisher.is_cancelled());+ drop(frames);+ assert!(publisher.is_cancelled());+ }++ #[tokio::test]+ async fn prepared_camera_failure_returns_no_epoch_and_releases_receiver() {+ ffmpeg::init().unwrap();+ let (sender, receiver) = flume::bounded(1);+ sender+ .send(FFmpegVideoFrame {+ inner: ffmpeg::frame::Video::empty(),+ timestamp: Timestamp::Instant(Instant::now()),+ })+ .unwrap();+ assert!(+ prepare_camera_frames(+ CameraReceiver::Raw(receiver),+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30),+ presentation(4, 4),+ )+ .await+ .is_err()+ );+ assert!(sender.is_disconnected());++ let now = Instant::now();+ let processing = processed_frame(now, 12).processing;+ let (publisher, reader) = processed_camera_channel(processing, 12, now);+ publisher.fail("Required blur failed".to_string());+ let error = prepare_camera_frames(+ CameraReceiver::Processed(reader),+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30),+ presentation(4, 4),+ )+ .await+ .err()+ .unwrap();+ assert!(error.to_string().contains("Required blur failed"));+ assert!(publisher.is_cancelled());+ }++ #[tokio::test]+ async fn cancelled_camera_preparation_releases_raw_and_processed_inputs() {+ let (sender, receiver) = flume::bounded(1);+ let preparation = prepare_camera_frames(+ CameraReceiver::Raw(receiver),+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30),+ presentation(4, 4),+ );+ assert!(+ tokio::time::timeout(Duration::from_millis(20), preparation)+ .await+ .is_err()+ );+ assert!(sender.is_disconnected());++ let now = Instant::now();+ let processing = processed_frame(now, 13).processing;+ let (publisher, reader) = processed_camera_channel(processing, 13, now);+ let preparation = prepare_camera_frames(+ CameraReceiver::Processed(reader),+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30),+ presentation(4, 4),+ );+ assert!(+ tokio::time::timeout(Duration::from_millis(20), preparation)+ .await+ .is_err()+ );+ assert!(publisher.is_cancelled());+ }++ #[tokio::test]+ async fn prepared_camera_rejects_geometry_before_creating_epoch() {+ let (sender, receiver) = flume::bounded(1);+ assert!(+ prepare_camera_frames(+ CameraReceiver::Raw(receiver),+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30),+ presentation(5, 4),+ )+ .await+ .is_err()+ );+ assert!(sender.is_disconnected());+ }++ fn processed_frame(now: Instant, generation: u64) -> LinuxProcessedCameraFrame {+ LinuxProcessedCameraFrame {+ bgra: Arc::from([+ 10, 20, 30, 255, 40, 50, 60, 255, 99, 99, 99, 99, 70, 80, 90, 255, 100, 110, 120,+ 255, 99, 99, 99, 99,+ ]),+ dimensions: (2, 2),+ stride: 12,+ timestamp: Timestamp::Instant(now),+ generation,+ processing: LinuxCameraProcessing {+ mirrored: true,+ blur: LinuxCameraBlur::Off,+ },+ mask: None,+ }+ }++ #[test]+ fn processed_bgra_stride_and_original_timestamp_are_preserved_without_second_mirror() {+ ffmpeg::init().unwrap();+ let now = Instant::now();+ let frame = processed_frame(now, 7);+ validate_processed_frame(&frame, frame.processing, 7, now, now).unwrap();+ let converted = processed_to_ffmpeg(&frame).unwrap();+ assert_eq!(converted.inner.format(), Pixel::BGRA);+ assert_eq!(&converted.inner.data(0)[..8], &frame.bgra[..8]);+ assert_eq!(+ &converted.inner.data(0)[converted.inner.stride(0)..][..8],+ &frame.bgra[12..20]+ );+ assert!(matches!(converted.timestamp, Timestamp::Instant(timestamp) if timestamp == now));+ let mut compositor = Compositor::new(+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 2, 2, 30),+ presentation(2, 2),+ );+ let overlay = compositor.camera_overlay(&converted.inner).unwrap();+ assert_eq!(overlay.format(), Pixel::RGBA);+ assert_eq!(&overlay.data(0)[..8], &[30, 20, 10, 255, 60, 50, 40, 255]);+ assert_eq!(+ &overlay.data(0)[overlay.stride(0)..][..8],+ &[90, 80, 70, 255, 120, 110, 100, 255]+ );+ }++ #[test]+ fn processed_frame_rejects_old_selection_generation_timestamp_and_effects() {+ let now = Instant::now();+ let frame = processed_frame(now, 7);+ assert!(validate_processed_frame(&frame, frame.processing, 8, now, now).is_err());+ assert!(+ validate_processed_frame(+ &frame,+ frame.processing,+ 7,+ now + Duration::from_nanos(1),+ now + Duration::from_nanos(1)+ )+ .is_err()+ );+ assert!(+ validate_processed_frame(+ &frame,+ LinuxCameraProcessing {+ mirrored: false,+ ..frame.processing+ },+ 7,+ now,+ now+ )+ .is_err()+ );+ assert!(+ validate_processed_frame(+ &frame,+ frame.processing,+ 7,+ now,+ now + CAMERA_STALE_AFTER + Duration::from_nanos(1)+ )+ .is_err()+ );+ let mut invalid = frame.clone();+ invalid.stride = 7;+ assert!(validate_processed_frame(&invalid, frame.processing, 7, now, now).is_err());+ invalid = frame.clone();+ invalid.bgra = Arc::from([0u8; 23]);+ assert!(validate_processed_frame(&invalid, frame.processing, 7, now, now).is_err());+ invalid = frame.clone();+ invalid.timestamp = Timestamp::SystemTime(std::time::SystemTime::now());+ assert!(validate_processed_frame(&invalid, frame.processing, 7, now, now).is_err());+ }++ #[test]+ fn processed_blur_requires_exact_mode_and_fresh_real_mask() {+ let now = Instant::now();+ let mut frame = processed_frame(now, 7);+ frame.processing.blur = LinuxCameraBlur::Light;+ assert!(validate_processed_frame(&frame, frame.processing, 7, now, now).is_err());+ frame.mask = Some(LinuxCameraMaskReceipt {+ generation: 1,+ submitted_at: now,+ completed_at: now,+ });+ assert!(validate_processed_frame(&frame, frame.processing, 7, now, now).is_ok());+ assert!(+ validate_processed_frame(+ &frame,+ LinuxCameraProcessing {+ blur: LinuxCameraBlur::Heavy,+ ..frame.processing+ },+ 7,+ now,+ now+ )+ .is_err()+ );+ assert!(+ validate_processed_frame(+ &frame,+ frame.processing,+ 7,+ now,+ now + LINUX_CAMERA_MAX_MASK_AGE + Duration::from_millis(1)+ )+ .is_err()+ );+ frame.mask.as_mut().unwrap().generation = 0;+ assert!(validate_processed_frame(&frame, frame.processing, 7, now, now).is_err());+ }++ #[tokio::test]+ async fn processed_latest_channel_has_sticky_error_and_wakes_waiter() {+ let now = Instant::now();+ let frame = processed_frame(now, 7);+ let (publisher, mut reader) = processed_camera_channel(frame.processing, 7, now);+ assert!(!reader.validate_current().unwrap());+ publisher.publish(frame.clone());+ reader.wait_ready(Duration::from_millis(20)).await.unwrap();+ publisher.fail("inference failed".to_string());+ publisher.publish(frame);+ let error = reader+ .wait_ready(Duration::from_millis(20))+ .await+ .unwrap_err();+ assert!(error.to_string().contains("inference failed"));+ assert!(matches!(+ &*reader.state.borrow(),+ ProcessedCameraState::Failed(_)+ ));+ let (_, mut pending) = processed_camera_channel(reader.processing, 8, now);+ assert!(pending.wait_ready(Duration::from_millis(20)).await.is_err());+ }++ #[tokio::test]+ async fn processed_first_frame_failure_timeout_and_publisher_drop_are_explicit() {+ let now = Instant::now();+ let processing = processed_frame(now, 1).processing;+ let (publisher, mut reader) = processed_camera_channel(processing, 1, now);+ assert!(+ reader+ .wait_ready(Duration::from_millis(1))+ .await+ .unwrap_err()+ .to_string()+ .contains("deadline")+ );+ publisher.fail("first mask inference failed".to_string());+ assert!(+ reader+ .wait_ready(Duration::from_secs(1))+ .await+ .unwrap_err()+ .to_string()+ .contains("first mask")+ );+ let (publisher, mut reader) = processed_camera_channel(processing, 2, now);+ drop(publisher);+ assert!(+ reader+ .wait_ready(Duration::from_secs(1))+ .await+ .unwrap_err()+ .to_string()+ .contains("disconnected")+ );+ }++ #[test]+ fn processed_drop_cancels_only_its_attempt_and_restart_has_fresh_state() {+ let now = Instant::now();+ let processing = processed_frame(now, 1).processing;+ let (old_publisher, old_reader) = processed_camera_channel(processing, 1, now);+ let (new_publisher, new_reader) = processed_camera_channel(processing, 2, now);+ drop(old_reader);+ assert!(old_publisher.is_cancelled());+ assert!(!new_publisher.is_cancelled());+ old_publisher.publish(processed_frame(now, 1));+ assert!(!new_reader.validate_current().unwrap());+ new_publisher.publish(processed_frame(now, 2));+ assert!(new_reader.validate_current().unwrap());+ }++ #[tokio::test]+ async fn processed_required_error_reaches_compositor_completion_without_screen_success() {+ ffmpeg::init().unwrap();+ let now = Instant::now();+ let frame = processed_frame(now, 3);+ let (publisher, reader) = processed_camera_channel(frame.processing, 3, now);+ publisher.publish(frame.clone());+ publisher.fail("required blur stopped".to_string());+ let (mut screen, screen_rx) = mpsc::channel(1);+ let (video_tx, mut output) = mpsc::channel(1);+ let (health_tx, _health_rx) = tokio::sync::mpsc::channel(4);+ let (done_tx, done_rx) = tokio::sync::oneshot::channel();+ let runtime = tokio::runtime::Handle::current();+ std::thread::spawn(move || {+ let _runtime = runtime.enter();+ let result = compositor_thread(+ screen_rx,+ CameraReceiver::Processed(reader),+ video_tx,+ CancellationToken::new(),+ health_tx,+ Compositor::new(+ VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30),+ presentation(2, 2),+ ),+ processed_to_ffmpeg(&frame).unwrap(),+ );+ let _ = done_tx.send(result);+ });+ let _ = screen.send(camera_frame()).await;+ let result = tokio::time::timeout(Duration::from_secs(1), done_rx)+ .await+ .unwrap()+ .unwrap();+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("required blur stopped")+ );+ assert!(output.next().await.is_none());+ }++ #[test]+ fn round_mapping_preserves_one_pixel_nonsquare_footprint_with_maximum_radius() {+ let request = LinuxCameraPresentation {+ rect: LinuxCameraRect {+ x: 0,+ y: 0,+ width: 401,+ height: 401,+ },+ shape: LinuxCameraShape::Round,+ mirrored: false,+ effect: LinuxCameraEffect::None,+ };+ let mapped = request.resolve((801, 600), (800, 600)).unwrap();+ assert_eq!(+ mapped.rect,+ LinuxCameraRect {+ x: 0,+ y: 0,+ width: 400,+ height: 401+ }+ );+ assert_eq!(+ mapped.shape,+ LinuxCameraShape::RoundedRectangle { radius_pixels: 200 }+ );+ assert!(request.resolve((801, 600), (600, 600)).is_err());+ }++ #[test]+ fn presentation_reference_mapping_resolves_odd_capture_dimensions_once() {+ let request = LinuxCameraPresentation {+ rect: LinuxCameraRect {+ x: 11,+ y: 13,+ width: 101,+ height: 81,+ },+ shape: LinuxCameraShape::RoundedRectangle { radius_pixels: 10 },+ mirrored: true,+ effect: LinuxCameraEffect::BackgroundBlur,+ };+ let mapped = request.resolve((801, 601), (800, 600)).unwrap();+ assert_eq!(mapped.rect, request.rect);+ assert_eq!(mapped.effect, LinuxCameraEffect::BackgroundBlur);+ let half = request.resolve((802, 602), (401, 301)).unwrap();+ assert_eq!(+ half.rect,+ LinuxCameraRect {+ x: 6,+ y: 7,+ width: 50,+ height: 40+ }+ );+ assert_eq!(+ half.shape,+ LinuxCameraShape::RoundedRectangle { radius_pixels: 5 }+ );+ assert!(request.resolve((0, 601), (800, 600)).is_err());+ }++ fn presentation(width: u32, height: u32) -> LinuxCameraPresentation {+ LinuxCameraPresentation {+ rect: LinuxCameraRect {+ x: 0,+ y: 0,+ width,+ height,+ },+ shape: LinuxCameraShape::RoundedRectangle { radius_pixels: 0 },+ mirrored: false,+ effect: LinuxCameraEffect::None,+ }+ }++ fn camera_frame() -> FFmpegVideoFrame {+ let mut inner = ffmpeg::frame::Video::new(Pixel::RGBA, 4, 4);+ for pixel in inner.data_mut(0).chunks_exact_mut(4) {+ pixel.copy_from_slice(&[200, 10, 20, 255]);+ }+ FFmpegVideoFrame {+ inner,+ timestamp: Timestamp::Instant(Instant::now()),+ }+ }++ #[test]+ fn presentation_rejects_empty_overflow_outside_shape_radius_and_unsupported_effect() {+ let mut request = presentation(8, 4);+ assert_eq!(request.validate(8, 4), Ok(()));+ request.rect.x = u32::MAX;+ assert_eq!(+ request.validate(8, 4),+ Err(LinuxCameraPresentationError::OutsideCapture)+ );+ request.rect.x = 1;+ assert_eq!(+ request.validate(8, 4),+ Err(LinuxCameraPresentationError::OutsideCapture)+ );+ request.rect.x = 0;+ request.shape = LinuxCameraShape::Round;+ assert_eq!(+ request.validate(8, 4),+ Err(LinuxCameraPresentationError::NonSquareCircle)+ );+ request.shape = LinuxCameraShape::RoundedRectangle { radius_pixels: 3 };+ assert_eq!(+ request.validate(8, 4),+ Err(LinuxCameraPresentationError::InvalidRadius)+ );+ request.shape = LinuxCameraShape::RoundedRectangle { radius_pixels: 2 };+ request.effect = LinuxCameraEffect::BackgroundBlur;+ assert_eq!(+ request.validate(8, 4),+ Err(LinuxCameraPresentationError::UnsupportedEffect)+ );+ request.rect.width = 0;+ assert_eq!(+ request.validate(8, 4),+ Err(LinuxCameraPresentationError::EmptyDimensions)+ );+ }++ #[test]+ fn rectangular_cover_crop_preserves_aspect_and_rejects_scaling_overflow() {+ assert_eq!(+ aspect_fill_dimensions(640, 480, 160, 90).unwrap(),+ (160, 120)+ );+ assert_eq!(+ aspect_fill_dimensions(1920, 1080, 90, 160).unwrap(),+ (285, 160)+ );+ assert!(aspect_fill_dimensions(u32::MAX, 1, 1, u32::MAX).is_err());+ assert!(aspect_fill_dimensions(0, 10, 1, 1).is_err());+ }++ #[test]+ fn mirror_changes_only_presentation_pixels_not_raw_camera() {+ ffmpeg::init().unwrap();+ let mut frame = ffmpeg::frame::Video::new(Pixel::RGBA, 4, 2);+ let stride = frame.stride(0);+ for y in 0..2 {+ for x in 0..4 {+ frame.data_mut(0)[y * stride + x * 4..][..4]+ .copy_from_slice(&[x as u8, y as u8, 3, 255]);+ }+ }+ let before = frame.data(0).to_vec();+ let mut request = presentation(4, 2);+ request.mirrored = true;+ let output = crop_camera(&frame, request).unwrap();+ assert_eq!(&output.data(0)[..4], &[3, 0, 3, 255]);+ assert_eq!(&output.data(0)[12..16], &[0, 0, 3, 255]);+ assert_eq!(frame.data(0), before);+ }++ #[test]+ fn round_and_rounded_rectangle_mask_corners_without_masking_center() {+ ffmpeg::init().unwrap();+ let mut frame = ffmpeg::frame::Video::new(Pixel::RGBA, 8, 8);+ frame.data_mut(0).fill(255);+ for shape in [+ LinuxCameraShape::Round,+ LinuxCameraShape::RoundedRectangle { radius_pixels: 3 },+ ] {+ let output = crop_camera(+ &frame,+ LinuxCameraPresentation {+ shape,+ ..presentation(8, 8)+ },+ )+ .unwrap();+ assert_eq!(output.data(0)[3], 0);+ assert_eq!(output.data(0)[output.stride(0) * 4 + 4 * 4 + 3], 255);+ }+ }++ #[tokio::test]+ async fn first_camera_readiness_requires_fresh_valid_frame() {+ ffmpeg::init().unwrap();+ let (tx, rx) = flume::bounded(1);+ assert!(tx.send(camera_frame()).is_ok());+ assert!(+ first_camera_frame(&rx, &CancellationToken::new(), Duration::from_millis(20))+ .await+ .is_ok()+ );+ let mut stale = camera_frame();+ stale.timestamp =+ Timestamp::Instant(Instant::now().checked_sub(Duration::from_secs(2)).unwrap());+ assert!(tx.send(stale).is_ok());+ assert!(+ first_camera_frame(&rx, &CancellationToken::new(), Duration::from_millis(20))+ .await+ .is_err()+ );+ assert!(+ tx.send(FFmpegVideoFrame {+ inner: ffmpeg::frame::Video::empty(),+ timestamp: Timestamp::Instant(Instant::now()),+ })+ .is_ok()+ );+ assert!(+ first_camera_frame(&rx, &CancellationToken::new(), Duration::from_millis(20))+ .await+ .is_err()+ );+ }++ #[tokio::test]+ async fn first_camera_readiness_times_out_or_reports_disconnect() {+ let (tx, rx) = flume::bounded(1);+ assert!(+ first_camera_frame(&rx, &CancellationToken::new(), Duration::from_millis(10))+ .await+ .err()+ .expect("camera readiness failed")+ .to_string()+ .contains("deadline")+ );+ drop(tx);+ assert!(+ first_camera_frame(&rx, &CancellationToken::new(), Duration::from_millis(20))+ .await+ .err()+ .expect("camera readiness failed")+ .to_string()+ .contains("disconnected")+ );+ }++ #[tokio::test]+ async fn first_camera_readiness_prefers_stop_even_when_frame_ready() {+ ffmpeg::init().unwrap();+ let (tx, rx) = flume::bounded(1);+ assert!(tx.send(camera_frame()).is_ok());+ let cancel = CancellationToken::new();+ cancel.cancel();+ assert!(+ first_camera_frame(&rx, &cancel, Duration::from_secs(1))+ .await+ .err()+ .expect("camera readiness failed")+ .to_string()+ .contains("cancelled")+ );+ assert_eq!(rx.len(), 1);+ }++ struct TestCompositor {+ screen: mpsc::Sender<FFmpegVideoFrame>,+ camera: flume::Sender<FFmpegVideoFrame>,+ output: mpsc::Receiver<FFmpegVideoFrame>,+ done: tokio::sync::oneshot::Receiver<anyhow::Result<()>>,+ stop: CancellationToken,+ }++ fn start_test_compositor(first_camera: FFmpegVideoFrame) -> TestCompositor {+ let (screen, screen_rx) = mpsc::channel(1);+ let (camera, camera_rx) = flume::bounded(1);+ let (video_tx, output) = mpsc::channel(1);+ let (health_tx, _health_rx) = tokio::sync::mpsc::channel(4);+ let (done_tx, done) = tokio::sync::oneshot::channel();+ let stop = CancellationToken::new();+ let thread_stop = stop.clone();+ let runtime = tokio::runtime::Handle::current();+ std::thread::spawn(move || {+ let _runtime = runtime.enter();+ let info = VideoInfo::from_raw_ffmpeg(Pixel::RGBA, 4, 4, 30);+ let result = compositor_thread(+ screen_rx,+ CameraReceiver::Raw(camera_rx),+ video_tx,+ thread_stop,+ health_tx,+ Compositor::new(info, presentation(2, 2)),+ first_camera,+ );+ let _ = done_tx.send(result);+ });+ TestCompositor {+ screen,+ camera,+ output,+ done,+ stop,+ }+ }++ #[tokio::test]+ async fn required_camera_disconnect_fails_without_screen_fallback() {+ ffmpeg::init().unwrap();+ let mut worker = start_test_compositor(camera_frame());+ drop(worker.camera);+ let _ = worker.screen.send(camera_frame()).await;+ assert!(+ tokio::time::timeout(Duration::from_secs(2), worker.done)+ .await+ .unwrap()+ .unwrap()+ .is_err()+ );+ assert!(worker.output.next().await.is_none());+ }++ #[tokio::test]+ async fn stale_camera_fails_even_without_screen_frames() {+ ffmpeg::init().unwrap();+ let mut frame = camera_frame();+ frame.timestamp =+ Timestamp::Instant(Instant::now().checked_sub(Duration::from_secs(2)).unwrap());+ let mut worker = start_test_compositor(frame);+ assert!(+ tokio::time::timeout(Duration::from_secs(2), worker.done)+ .await+ .unwrap()+ .unwrap()+ .is_err()+ );+ assert!(worker.output.next().await.is_none());+ }++ #[tokio::test]+ async fn invalid_screen_composition_fails_without_output() {+ ffmpeg::init().unwrap();+ let mut worker = start_test_compositor(camera_frame());+ worker+ .screen+ .send(FFmpegVideoFrame {+ inner: ffmpeg::frame::Video::empty(),+ timestamp: Timestamp::Instant(Instant::now()),+ })+ .await+ .unwrap();+ assert!(+ tokio::time::timeout(Duration::from_secs(2), worker.done)+ .await+ .unwrap()+ .unwrap()+ .is_err()+ );+ assert!(worker.output.next().await.is_none());+ }++ #[tokio::test]+ async fn invalid_camera_update_fails_without_output() {+ ffmpeg::init().unwrap();+ let mut worker = start_test_compositor(camera_frame());+ assert!(+ worker+ .camera+ .send(FFmpegVideoFrame {+ inner: ffmpeg::frame::Video::empty(),+ timestamp: Timestamp::Instant(Instant::now())+ })+ .is_ok()+ );+ assert!(+ tokio::time::timeout(Duration::from_secs(2), worker.done)+ .await+ .unwrap()+ .unwrap()+ .is_err()+ );+ assert!(worker.output.next().await.is_none());+ }++ #[tokio::test]+ async fn dropping_source_guard_cancels_compositor_without_screen_frames() {+ ffmpeg::init().unwrap();+ let mut worker = start_test_compositor(camera_frame());+ let source_guard = worker.stop.clone().drop_guard();+ drop(source_guard);+ assert!(+ tokio::time::timeout(Duration::from_secs(2), worker.done)+ .await+ .unwrap()+ .unwrap()+ .is_ok()+ );+ assert!(worker.output.next().await.is_none());+ }++ #[tokio::test]+ async fn first_output_contains_camera_and_stop_closes_compositor() {+ ffmpeg::init().unwrap();+ let mut worker = start_test_compositor(camera_frame());+ let mut screen = camera_frame();+ screen.inner.data_mut(0).fill(0);+ screen.inner.set_pts(Some(71));+ worker.screen.send(screen).await.unwrap();+ let output = tokio::time::timeout(Duration::from_secs(2), worker.output.next())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(&output.inner.data(0)[..4], &[200, 10, 20, 255]);+ assert_eq!(output.inner.pts(), Some(71));+ worker.stop.cancel();+ assert!(+ tokio::time::timeout(Duration::from_secs(2), worker.done)+ .await+ .unwrap()+ .unwrap()+ .is_ok()+ );+ assert!(worker.output.next().await.is_none());+ }+#[test]fn camera_freshness_expires_after_one_second() {let now = Instant::now();@@ -599,7 +1985,19 @@ mod tests {let stride = source.stride(0);let center = 2 * stride + 2 * 4;source.data_mut(0)[center..center + 4].copy_from_slice(&[1, 2, 3, 255]);- let cropped = center_crop_square(&source, 2).expect("crop succeeds");+ let cropped = crop_camera(+ &source,+ LinuxCameraPresentation {+ rect: LinuxCameraRect {+ x: 0,+ y: 0,+ width: 2,+ height: 2,+ },+ ..LinuxCameraPresentation::default_for(2, 2)+ },+ )+ .expect("crop succeeds");assert_eq!(&cropped.data(0)[cropped.stride(0)..cropped.stride(0) + 4],&[1, 2, 3, 255]@@ -629,7 +2027,10 @@ mod tests {inner: camera,timestamp,};- let mut compositor = Compositor::new(info);+ let mut compositor = Compositor::new(+ info,+ LinuxCameraPresentation::default_for(info.width, info.height),+ );let output = compositor.compose(&screen_frame, &camera_frame).expect("composition succeeds");@@ -669,7 +2070,10 @@ mod tests {inner: camera,timestamp,};- let mut compositor = Compositor::new(info);+ let mut compositor = Compositor::new(+ info,+ LinuxCameraPresentation::default_for(info.width, info.height),+ );let output = compositor.compose(&screen_frame, &camera_frame).expect("composition succeeds");@@ -679,128 +2083,6 @@ mod tests {assert_ne!(output.inner.data(0)[output.inner.stride(0) * 7 + 7], 16);}- #[tokio::test]- async fn compositor_passes_screen_without_camera_and_closes_on_cancel() {- ffmpeg::init().expect("FFmpeg initializes");- let timestamp = Timestamp::Instant(Instant::now());- let info = VideoInfo::from_raw_ffmpeg(Pixel::BGRA, 4, 4, 30);- let mut inner = ffmpeg::frame::Video::new(Pixel::BGRA, 4, 4);- inner.data_mut(0).fill(17);- inner.set_pts(Some(77));- let expected = inner.data(0).to_vec();- let frame = FFmpegVideoFrame { inner, timestamp };- let (mut screen_tx, screen_rx) = mpsc::channel(1);- let (video_tx, mut video_rx) = mpsc::channel(1);- let (health_tx, _health_rx) = tokio::sync::mpsc::channel(1);- let stop_token = CancellationToken::new();- let _stop_guard = stop_token.clone().drop_guard();- let worker_stop = stop_token.clone();- let (done_tx, done_rx) = std::sync::mpsc::channel();- let worker = std::thread::spawn(move || {- let result = compositor_thread(screen_rx, None, video_tx, worker_stop, health_tx, info);- let _ = done_tx.send(result);- });-- screen_tx.send(frame).await.expect("screen frame sent");- let output = tokio::time::timeout(Duration::from_secs(2), video_rx.next())- .await- .expect("screen-only output arrives promptly")- .expect("screen-only frame emitted");- assert_eq!(output.inner.data(0), expected.as_slice());- assert_eq!(output.inner.pts(), Some(77));- assert!(matches!(- (output.timestamp, timestamp),- (Timestamp::Instant(actual), Timestamp::Instant(expected)) if actual == expected- ));-- stop_token.cancel();- drop(screen_tx);- done_rx- .recv_timeout(Duration::from_secs(2))- .expect("compositor exits promptly")- .expect("compositor stopped");- worker.join().expect("compositor thread joined");- assert!(video_rx.next().await.is_none());- }-- #[tokio::test]- async fn compositor_reports_silent_attached_camera_and_keeps_screen_output() {- ffmpeg::init().expect("FFmpeg initializes");- let timestamp = Timestamp::Instant(Instant::now());- let info = VideoInfo::from_raw_ffmpeg(Pixel::BGRA, 4, 4, 30);- let mut first_inner = ffmpeg::frame::Video::new(Pixel::BGRA, 4, 4);- first_inner.data_mut(0).fill(17);- first_inner.set_pts(Some(77));- let first_frame = FFmpegVideoFrame {- inner: first_inner,- timestamp,- };- let mut second_inner = ffmpeg::frame::Video::new(Pixel::BGRA, 4, 4);- second_inner.data_mut(0).fill(23);- second_inner.set_pts(Some(88));- let second_frame = FFmpegVideoFrame {- inner: second_inner,- timestamp,- };- let (mut screen_tx, screen_rx) = mpsc::channel(1);- let (camera_tx, camera_rx) = flume::bounded(1);- let (video_tx, mut video_rx) = mpsc::channel(1);- let (health_tx, mut health_rx) = tokio::sync::mpsc::channel(4);- let stop_token = CancellationToken::new();- let _stop_guard = stop_token.clone().drop_guard();- let worker_stop = stop_token.clone();- let (done_tx, done_rx) = std::sync::mpsc::channel();- let worker = std::thread::spawn(move || {- let result = compositor_thread(- screen_rx,- Some(camera_rx),- video_tx,- worker_stop,- health_tx,- info,- );- let _ = done_tx.send(result);- });-- screen_tx- .send(first_frame)- .await- .expect("first screen frame sent");- let first_output = tokio::time::timeout(Duration::from_secs(2), video_rx.next())- .await- .expect("first screen-only output arrives promptly")- .expect("first screen-only frame emitted");- assert_eq!(first_output.inner.pts(), Some(77));-- tokio::time::sleep(CAMERA_STALE_AFTER + Duration::from_millis(20)).await;- screen_tx- .send(second_frame)- .await- .expect("second screen frame sent");- let second_output = tokio::time::timeout(Duration::from_secs(2), video_rx.next())- .await- .expect("silent-camera screen output arrives promptly")- .expect("silent-camera screen frame emitted");- assert_eq!(second_output.inner.pts(), Some(88));- assert!(matches!(- tokio::time::timeout(Duration::from_secs(2), health_rx.recv())- .await- .expect("silent camera reports its health promptly"),- Some(output_pipeline::PipelineHealthEvent::Stalled { source, .. })- if source == "camera-compositor"- ));-- stop_token.cancel();- drop(camera_tx);- drop(screen_tx);- done_rx- .recv_timeout(Duration::from_secs(2))- .expect("compositor exits promptly")- .expect("compositor stopped");- worker.join().expect("compositor thread joined");- assert!(video_rx.next().await.is_none());- }-#[test]fn blend_rejects_overlay_outside_screen_bounds() {ffmpeg::init().expect("FFmpeg initializes");diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rsindex 530ca9919..15485e0ee 100644--- a/crates/recording/src/lib.rs+++ b/crates/recording/src/lib.rs@@ -18,6 +18,8 @@ pub mod studio_recording;pub mod sync_calibration;pub mod track_heal;+#[cfg(target_os = "linux")]+pub use capture_pipeline::target_to_display_and_crop;pub use resolution_limits::{H264_MAX_DIMENSION, calculate_gpu_compatible_size};#[cfg(any(test, feature = "test-utils"))]diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rsindex 75b4cbf9c..6ab4c71ee 100644--- a/crates/recording/src/output_pipeline/core.rs+++ b/crates/recording/src/output_pipeline/core.rs@@ -40,6 +40,24 @@ pub(crate) const STALL_POLL_INTERVAL: Duration = Duration::from_micros(500);pub const VIDEO_START_GATE_TIMEOUT: Duration = Duration::from_millis(500);+fn remap_video_timestamp(+ source_clock: &mut SourceClockState,+ master_clock: &MasterClock,+ timestamp: Timestamp,+ frame_duration_ns: u64,+) -> cap_timestamp::SourceClockRemap {+ #[cfg(target_os = "linux")]+ {+ // Nominal cadence snapping accumulates lag for slower continuous sources,+ // then releases it as a >100ms step despite a <50ms source interval.+ source_clock.remap_preserving_cadence(master_clock, timestamp, frame_duration_ns)+ }+ #[cfg(not(target_os = "linux"))]+ {+ source_clock.remap(master_clock, timestamp, frame_duration_ns)+ }+}+pub const AV_START_ALIGNMENT_LIMIT_NS: u64 = 500_000_000;pub(crate) fn frame_timing_log_threshold_ms(video_config: &VideoInfo) -> u128 {@@ -974,7 +992,45 @@ fn duration_to_sample_count(duration: Duration, sample_rate: u32) -> u64 {ns_to_sample_count(ns, sample_rate)}+#[cfg(target_os = "linux")]+#[derive(Default)]+struct CaptureInstantTimeline {+ source_epoch: Duration,+ output_epoch: Duration,+ last_output: Duration,+ last_wall: Option<Duration>,+}++#[cfg(target_os = "linux")]+impl CaptureInstantTimeline {+ fn calculate(+ &mut self,+ source: Duration,+ wall: Duration,+ discontinuity: bool,+ ) -> (Duration, bool) {+ if discontinuity {+ self.source_epoch = source;+ self.output_epoch = self.last_output.saturating_add(+ self.last_wall+ .map(|previous| wall.saturating_sub(previous))+ .unwrap_or_default(),+ );+ }+ let candidate = self+ .output_epoch+ .saturating_add(source.saturating_sub(self.source_epoch));+ let bound = wall.saturating_add(Duration::from_secs_f64(VIDEO_WALL_CLOCK_TOLERANCE_SECS));+ let output = candidate.clamp(self.last_output, bound.max(self.last_output));+ self.last_output = output;+ self.last_wall = Some(wall);+ (output, candidate > bound)+ }+}+struct VideoDriftTracker {+ #[cfg(target_os = "linux")]+ capture_timeline: CaptureInstantTimeline,anchor: Option<(f64, f64)>,capped_frame_count: u64,clamp_warning_logged: bool,@@ -983,6 +1039,8 @@ struct VideoDriftTracker {impl VideoDriftTracker {fn new() -> Self {Self {+ #[cfg(target_os = "linux")]+ capture_timeline: CaptureInstantTimeline::default(),anchor: None,capped_frame_count: 0,clamp_warning_logged: false,@@ -1060,6 +1118,29 @@ impl VideoDriftTracker {self.capped_frame_count}}+fn calculate_video_timestamp(+ tracker: &mut VideoDriftTracker,+ source_timestamp: Timestamp,+ source_duration: Duration,+ wall_elapsed: Duration,+ discontinuity: bool,+) -> Duration {+ #[cfg(target_os = "linux")]+ if matches!(source_timestamp, Timestamp::Instant(_)) {+ // Linux capture stamps the same monotonic clock as the consumer. Arrival+ // latency is not device-clock drift and must not replace capture cadence.+ let (duration, capped) =+ tracker+ .capture_timeline+ .calculate(source_duration, wall_elapsed, discontinuity);+ tracker.capped_frame_count += u64::from(capped);+ return duration;+ }+ #[cfg(not(target_os = "linux"))]+ let _ = (source_timestamp, discontinuity);+ tracker.calculate_timestamp(source_duration, wall_elapsed)+}+const DEFAULT_VIDEO_SOURCE_CHANNEL_CAPACITY: usize = 300;fn get_video_source_channel_capacity() -> usize {@@ -1640,6 +1721,381 @@ impl OutputPipelineBuilder<NoVideo> {}}+#[derive(Clone)]+pub(crate) struct PipelineBuildScope(Arc<PipelineBuildScopeInner>);++type CaptureCompletion = Shared<BoxFuture<'static, Result<(), String>>>;++struct ScopeError {+ message: String,+ uncertain: bool,+}++#[cfg(any(test, target_os = "linux", windows))]+#[derive(Debug)]+pub(crate) struct PipelineJoinReport {+ pub quiescent: bool,+ pub error: Option<String>,+}++struct PipelineBuildScopeInner {+ parent: Option<PipelineBuildScope>,+ strict_lifetime: bool,+ #[cfg(target_os = "linux")]+ required_source_health: bool,+ #[cfg(any(test, target_os = "linux", windows))]+ drain: tokio::sync::Mutex<()>,+ cancelled: CancellationToken,+ committed: AtomicBool,+ tokens: std::sync::Mutex<Vec<CancellationToken>>,+ completions: std::sync::Mutex<Vec<CaptureCompletion>>,+ cleanup_errors: std::sync::Mutex<Vec<ScopeError>>,+}++tokio::task_local! {+ static PIPELINE_BUILD_SCOPE: PipelineBuildScope;+}++pub(crate) struct BuildTaskCompletion {+ parent: Option<Box<BuildTaskCompletion>>,+ sender: Option<oneshot::Sender<()>>,+ scope: Option<PipelineBuildScope>,+}++impl Drop for BuildTaskCompletion {+ fn drop(&mut self) {+ if std::thread::panicking()+ && let Some(scope) = &self.scope+ {+ scope.record_cleanup_error("Capture setup task panicked during owned work".into());+ if scope.requires_joined_stop() {+ scope.cancel();+ }+ }+ if let Some(sender) = self.sender.take() {+ let _ = sender.send(());+ }+ drop(self.parent.take());+ }+}++impl PipelineBuildScope {+ #[cfg(any(test, windows))]+ pub(crate) fn new() -> Self {+ Self::with_lifetime(false)+ }++ #[cfg(any(test, target_os = "linux"))]+ pub(crate) fn new_lifetime() -> Self {+ Self::with_lifetime(true)+ }++ #[cfg(any(test, target_os = "linux", windows))]+ fn with_lifetime(strict_lifetime: bool) -> Self {+ Self::with_lifetime_policy(strict_lifetime, false)+ }++ #[cfg(target_os = "linux")]+ pub(crate) fn new_studio_lifetime() -> Self {+ Self::with_lifetime_policy(true, true)+ }++ #[cfg(any(test, target_os = "linux", windows))]+ fn with_lifetime_policy(strict_lifetime: bool, _required_source_health: bool) -> Self {+ Self(Arc::new(PipelineBuildScopeInner {+ parent: None,+ strict_lifetime,+ #[cfg(target_os = "linux")]+ required_source_health: _required_source_health,+ drain: tokio::sync::Mutex::new(()),+ cancelled: CancellationToken::new(),+ committed: AtomicBool::new(false),+ tokens: std::sync::Mutex::new(Vec::new()),+ completions: std::sync::Mutex::new(Vec::new()),+ cleanup_errors: std::sync::Mutex::new(Vec::new()),+ }))+ }++ #[cfg(target_os = "linux")]+ pub(crate) fn child_transaction(&self) -> Self {+ Self(Arc::new(PipelineBuildScopeInner {+ parent: Some(self.clone()),+ strict_lifetime: self.requires_joined_stop(),+ required_source_health: self.0.required_source_health,+ drain: tokio::sync::Mutex::new(()),+ cancelled: self.cancellation().child_token(),+ committed: AtomicBool::new(false),+ tokens: std::sync::Mutex::new(Vec::new()),+ completions: std::sync::Mutex::new(Vec::new()),+ cleanup_errors: std::sync::Mutex::new(Vec::new()),+ }))+ }++ pub(crate) fn current() -> Option<Self> {+ PIPELINE_BUILD_SCOPE.try_with(Clone::clone).ok()+ }++ pub(crate) async fn run<F: Future>(&self, future: F) -> F::Output {+ PIPELINE_BUILD_SCOPE.scope(self.clone(), future).await+ }++ pub(crate) fn cancellation(&self) -> CancellationToken {+ self.0.cancelled.clone()+ }++ pub(crate) fn register_token(&self, token: CancellationToken) {+ if let Some(parent) = &self.0.parent {+ parent.register_token(token.clone());+ }+ let mut tokens = self.0.tokens.lock().unwrap();+ tokens.retain(|token| !token.is_cancelled());+ if self.0.cancelled.is_cancelled() {+ token.cancel();+ } else if !self.0.committed.load(Ordering::Acquire) {+ tokens.push(token);+ }+ }++ pub(crate) fn task_completion(&self) -> BuildTaskCompletion {+ if self.0.committed.load(Ordering::Acquire) {+ return BuildTaskCompletion {+ parent: self+ .0+ .parent+ .as_ref()+ .map(|parent| Box::new(parent.task_completion())),+ sender: None,+ scope: None,+ };+ }+ let (sender, receiver) = oneshot::channel();+ self.prune_completed();+ self.0.completions.lock().unwrap().push(+ async move {+ receiver+ .await+ .map_err(|_| "Capture work lost its completion acknowledgement".to_string())+ }+ .boxed()+ .shared(),+ );+ BuildTaskCompletion {+ parent: self+ .0+ .parent+ .as_ref()+ .map(|parent| Box::new(parent.task_completion())),+ sender: Some(sender),+ scope: Some(self.clone()),+ }+ }++ pub(crate) fn cancel(&self) {+ let tokens = self.0.tokens.lock().unwrap();+ if self.is_committed() {+ return;+ }+ self.0.cancelled.cancel();+ for token in tokens.iter() {+ token.cancel();+ }+ }++ fn prune_completed(&self) {+ self.0.completions.lock().unwrap().retain(|completion| {+ match completion.clone().now_or_never() {+ None => true,+ Some(Ok(())) => false,+ Some(Err(error)) => {+ self.record_cleanup_error(error);+ false+ }+ }+ });+ }++ #[cfg(any(test, target_os = "linux", windows))]+ pub(crate) async fn cancel_and_join_report(&self) -> PipelineJoinReport {+ self.cancel();+ let _drain = self.0.drain.lock().await;+ loop {+ self.prune_completed();+ let pending = self.0.completions.lock().unwrap().clone();+ if pending.is_empty() {+ break;+ }+ drop(futures::future::join_all(pending).await);+ }+ let errors = self.0.cleanup_errors.lock().unwrap();+ PipelineJoinReport {+ quiescent: !errors.iter().any(|error| error.uncertain),+ error: (!errors.is_empty()).then(|| {+ errors+ .iter()+ .map(|error| error.message.as_str())+ .collect::<Vec<_>>()+ .join("; ")+ }),+ }+ }++ #[cfg(any(test, target_os = "linux"))]+ pub(crate) async fn cancel_and_join(&self) -> Result<(), String> {+ self.cancel_and_join_report()+ .await+ .error+ .map_or(Ok(()), Err)+ }++ #[cfg(target_os = "linux")]+ pub(crate) fn requires_source_health(&self) -> bool {+ self.0.required_source_health+ }++ pub(crate) fn requires_joined_stop(&self) -> bool {+ self.0.strict_lifetime+ }++ #[cfg(any(test, target_os = "linux", windows))]+ pub(crate) fn commit(&self) -> bool {+ let mut tokens = self.0.tokens.lock().unwrap();+ if self.0.cancelled.is_cancelled() {+ return false;+ }+ self.0.committed.store(true, Ordering::Release);+ tokens.clear();+ self.0.completions.lock().unwrap().clear();+ true+ }++ pub(crate) fn is_committed(&self) -> bool {+ self.0.committed.load(Ordering::Acquire)+ }++ fn record_cleanup_error(&self, error: String) {+ if let Some(parent) = &self.0.parent {+ parent.record_cleanup_error(error.clone());+ }+ if !self.0.committed.load(Ordering::Acquire) {+ self.0.cleanup_errors.lock().unwrap().push(ScopeError {+ message: error,+ uncertain: true,+ });+ }+ }++ fn has_recorded_error(&self) -> bool {+ let own_error = !self.0.cleanup_errors.lock().unwrap().is_empty();+ own_error || self.0.parent.as_ref().is_some_and(Self::has_recorded_error)+ }++ pub(crate) fn fail_required(&self, error: String) {+ if self.is_committed()+ && let Some(parent) = &self.0.parent+ {+ parent.fail_required(error);+ return;+ }+ self.record_finalization_error(error);+ self.cancel();+ }++ #[cfg(any(test, target_os = "linux"))]+ pub(crate) fn idle_report(&self) -> Option<PipelineJoinReport> {+ self.prune_completed();+ if !self.0.completions.lock().unwrap().is_empty() {+ return None;+ }+ let errors = self.0.cleanup_errors.lock().unwrap();+ Some(PipelineJoinReport {+ quiescent: !errors.iter().any(|error| error.uncertain),+ error: (!errors.is_empty()).then(|| {+ errors+ .iter()+ .map(|error| error.message.as_str())+ .collect::<Vec<_>>()+ .join("; ")+ }),+ })+ }++ fn record_finalization_error(&self, error: String) {+ if self.is_committed()+ && let Some(parent) = &self.0.parent+ {+ parent.record_finalization_error(error.clone());+ }+ if !self.is_committed() {+ self.0.cleanup_errors.lock().unwrap().push(ScopeError {+ message: error,+ uncertain: !self.requires_joined_stop(),+ });+ }+ }++ pub(crate) fn spawn_cleanup(+ &self,+ future: impl Future<Output = anyhow::Result<()>> + Send + 'static,+ ) {+ let completion = self.task_completion();+ let scope = self.clone();+ drop(tokio::spawn(async move {+ let _completion = completion;+ match std::panic::AssertUnwindSafe(future).catch_unwind().await {+ Ok(Ok(())) => {}+ Ok(Err(error)) => scope.record_cleanup_error(error.to_string()),+ Err(_) => scope.record_cleanup_error("Capture source cleanup panicked".into()),+ }+ }));+ }+}++pub(crate) fn spawn_capture_task<F>(future: F) -> JoinHandle<F::Output>+where+ F: Future + Send + 'static,+ F::Output: Send + 'static,+{+ let scope = PipelineBuildScope::current();+ let completion = scope.as_ref().map(PipelineBuildScope::task_completion);+ tokio::spawn(async move {+ let _completion = completion;+ match scope {+ Some(scope) => scope.run(future).await,+ None => future.await,+ }+ })+}++struct PreparedVideoSource<T: VideoSource> {+ source: Option<T>,+ scope: Option<PipelineBuildScope>,+}++impl<T: VideoSource> PreparedVideoSource<T> {+ fn new(source: T) -> Self {+ Self {+ source: Some(source),+ scope: PipelineBuildScope::current(),+ }+ }++ fn take(&mut self) -> T {+ self.source+ .take()+ .expect("Prepared video source consumed once")+ }+}++impl<T: VideoSource> Drop for PreparedVideoSource<T> {+ fn drop(&mut self) {+ if let Some(scope) = &self.scope+ && let Some(mut source) = self.source.take()+ {+ scope.spawn_cleanup(async move { source.stop().await });+ }+ }+}+#[derive(Default)]pub struct TaskPool(Vec<(&'static str, JoinHandle<anyhow::Result<()>>)>);@@ -1650,8 +2106,8 @@ impl TaskPool {{self.0.push((name,- tokio::spawn(- async {+ spawn_capture_task(+ async move {trace!("Task started");let res = future.await;match &res {@@ -1673,7 +2129,9 @@ impl TaskPool {) {let span = error_span!("", task = name);let (done_tx, done_rx) = oneshot::channel();+ let completion = PipelineBuildScope::current().map(|scope| scope.task_completion());std::thread::spawn(move || {+ let _completion = completion;let _guard = span.enter();trace!("Task started");let _ = done_tx.send(cb());@@ -1690,10 +2148,93 @@ impl TaskPool {}}+#[cfg(any(windows, test))]+struct WindowsStartupGuard {+ scope: PipelineBuildScope,+ armed: bool,+}++#[cfg(any(windows, test))]+impl Drop for WindowsStartupGuard {+ fn drop(&mut self) {+ if self.armed {+ self.scope.cancel();+ let scope = self.scope.clone();+ if let Ok(runtime) = tokio::runtime::Handle::try_current() {+ runtime.spawn(async move {+ let report = scope.cancel_and_join_report().await;+ if let Some(error) = report.error {+ error!(%error, "Dropped Windows startup cleanup failed");+ }+ });+ }+ }+ }+}++#[cfg(any(windows, test))]+pub(crate) async fn finish_windows_pipeline_startup<T>(+ scope: &PipelineBuildScope,+ startup: impl Future<Output = anyhow::Result<T>>,+) -> anyhow::Result<T> {+ let mut guard = WindowsStartupGuard {+ scope: scope.clone(),+ armed: true,+ };+ let result = scope.run(startup).await;+ let pipeline_cancelled = {+ let tokens = scope.0.tokens.lock().unwrap();+ tokens.iter().any(CancellationToken::is_cancelled)+ };+ match result {+ Ok(output) if !pipeline_cancelled && scope.commit() => {+ guard.armed = false;+ Ok(output)+ }+ result => {+ let error = match result {+ Err(error) => error,+ Ok(output) => {+ drop(output);+ anyhow!("Windows capture startup was cancelled")+ }+ };+ let report = scope.cancel_and_join_report().await;+ guard.armed = false;+ match (report.quiescent, report.error) {+ (false, cleanup) => Err(error.context(format!(+ "Capture startup cleanup is unconfirmed: {}",+ cleanup.unwrap_or_default()+ ))),+ (true, Some(cleanup)) => {+ Err(error.context(format!("Capture startup cleanup: {cleanup}")))+ }+ (true, None) => Err(error),+ }+ }+ }+}+impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {pub async fn build<TMuxer: VideoMuxer<VideoFrame = TVideo::Frame> + AudioMuxer>(self,muxer_config: TMuxer::Config,+ ) -> anyhow::Result<OutputPipeline> {+ #[cfg(windows)]+ if PipelineBuildScope::current().is_none() {+ let scope = PipelineBuildScope::new();+ return finish_windows_pipeline_startup(+ &scope,+ self.build_inner::<TMuxer>(muxer_config),+ )+ .await;+ }+ self.build_inner::<TMuxer>(muxer_config).await+ }++ async fn build_inner<TMuxer: VideoMuxer<VideoFrame = TVideo::Frame> + AudioMuxer>(+ self,+ muxer_config: TMuxer::Config,) -> anyhow::Result<OutputPipeline> {let Self {video,@@ -1721,6 +2262,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {setup_video_source::<TVideo>(video.config, &mut setup_ctx).await?;let video_info = video_source.video_info();+ let mut video_source = PreparedVideoSource::new(video_source);let (first_tx, first_rx) = oneshot::channel();let audio = setup_audio_sources(@@ -1748,9 +2290,9 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {let video_start_gate = has_audio_sources.then(VideoStartGate::new);- spawn_video_encoder(+ let video_started = spawn_video_encoder(&mut setup_ctx,- video_source,+ video_source.take(),video_rx,first_tx,build_ctx.stop_token.clone(),@@ -1784,7 +2326,16 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {).await?;+ if let Some(started) = video_started {+ started+ .await+ .context("Video source startup acknowledgement was lost")?+ .map_err(anyhow::Error::msg)?;+ }+Ok(OutputPipeline {+ joined_stop: PipelineBuildScope::current()+ .is_some_and(|scope| scope.requires_joined_stop()),path,first_timestamp_rx: first_rx,video_info: Some(video_info),@@ -1871,6 +2422,8 @@ impl OutputPipelineBuilder<NoVideo> {.await?;Ok(OutputPipeline {+ joined_stop: PipelineBuildScope::current()+ .is_some_and(|scope| scope.requires_joined_stop()),path,first_timestamp_rx: first_rx,stop_token: Some(build_ctx.stop_token.clone().drop_guard()),@@ -1899,6 +2452,9 @@ struct BuildCtx {impl BuildCtx {pub fn new() -> Self {let stop_token = CancellationToken::new();+ if let Some(scope) = PipelineBuildScope::current() {+ scope.register_token(stop_token.clone());+ }let (done_tx, done_rx) = oneshot::channel();let (health_tx, health_rx) = new_health_channel();@@ -1955,7 +2511,12 @@ async fn finish_build();}- tokio::spawn(+ let scope = PipelineBuildScope::current();+ let completion = scope.as_ref().map(PipelineBuildScope::task_completion);+ let drain_owned_tasks = scope.is_some();+ let task_scope = scope.clone();+ tokio::spawn(async move {+ let _completion = completion;async move {let (task_names, task_handles): (Vec<_>, Vec<_>) =setup_ctx.tasks.0.into_iter().unzip();@@ -1967,32 +2528,83 @@ async fn finish_build(.map(|(f, n)| f.map(move |r| (r, n))),);+ let mut first_error = None;while let Some((result, name)) = futures.next().await {- match result {- Err(_) => {- return Err(anyhow::anyhow!("Task {name} failed unexpectedly"));+ let error = match result {+ Err(_) => Some(anyhow::anyhow!("Task {name} failed unexpectedly")),+ Ok(Err(error)) => Some(anyhow::anyhow!("Task {name} failed: {error}")),+ Ok(Ok(())) => None,+ };+ if let Some(error) = error {+ stop_token.cancel();+ if let Some(scope) = &task_scope+ && scope.requires_joined_stop()+ {+ scope.fail_required(format!("Required pipeline task failed: {error:#}"));}- Ok(Err(e)) => {- return Err(anyhow::anyhow!("Task {name} failed: {e}"));+ if !drain_owned_tasks {+ return Err(error);+ }+ if first_error.is_none() {+ first_error = Some(error);}- _ => {}}}- Ok(())+ first_error.map_or(Ok(()), Err)}.then(async move |res| {- let muxer_res = muxer.lock().await.finish(timestamps.instant().elapsed());+ let muxer = muxer.lock_owned().await;+ let muxer_res = match &scope {+ Some(scope) if scope.requires_joined_stop() => {+ finish_muxer_owned(muxer, timestamps.instant().elapsed(), scope).await+ }+ _ => finish_muxer(muxer, timestamps.instant().elapsed()).await,+ };+ if let Some(scope) = &scope {+ match &muxer_res {+ Err(error) | Ok(Err(error)) => {+ scope.record_finalization_error(format!("Muxer cleanup failed: {error:#}"))+ }+ Ok(Ok(())) => {}+ }+ }let _ = done_tx.send(resolve_pipeline_completion(res, muxer_res, &stop_signal));- }),- );+ })+ .await+ });info!("Built pipeline for output {}", path.display());Ok(())}+async fn finish_muxer_owned(+ muxer: futures::lock::OwnedMutexGuard<impl Muxer>,+ timestamp: Duration,+ scope: &PipelineBuildScope,+) -> anyhow::Result<anyhow::Result<()>> {+ let completion = scope.task_completion();+ tokio::task::spawn_blocking(move || {+ let _completion = completion;+ let mut owned_muxer = muxer;+ owned_muxer.finish(timestamp)+ })+ .await+ .context("Muxer finalization task failed")?+}++async fn finish_muxer(+ mut muxer: futures::lock::OwnedMutexGuard<impl Muxer>,+ timestamp: Duration,+) -> anyhow::Result<anyhow::Result<()>> {+ // Encoder joins and trailer writes can stall other tracks' stop and timestamp tasks.+ tokio::task::spawn_blocking(move || muxer.finish(timestamp))+ .await+ .context("Muxer finalization task failed")?+}+fn resolve_pipeline_completion(task_result: anyhow::Result<()>,muxer_result: anyhow::Result<anyhow::Result<()>>,@@ -2108,26 +2720,67 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vmaster_clock: Arc<MasterClock>,video_info: VideoInfo,video_start_gate: Option<VideoStartGate>,-) {+) -> Option<oneshot::Receiver<Result<(), String>>> {let frame_duration_ns = estimate_video_frame_duration_ns(&video_info);+ let (start_tx, started) = if PipelineBuildScope::current().is_some() {+ let (sender, receiver) = oneshot::channel();+ (Some(sender), Some(receiver))+ } else {+ (None, None)+ };setup_ctx.tasks().spawn("capture-video", {let stop_token = stop_token.clone();+ let scope = PipelineBuildScope::current();async move {- video_source.start().await?;-- stop_token.cancelled().await;+ let started = if scope.is_some() {+ tokio::select! {+ biased;+ _ = stop_token.cancelled() => Err(anyhow!("Capture setup cancelled")),+ result = video_source.start() => result,+ }+ } else {+ video_source.start().await+ };+ if let Some(sender) = start_tx {+ let _ = sender.send(started.as_ref().map(|_| ()).map_err(ToString::to_string));+ }+ if started.is_ok() {+ stop_token.cancelled().await;+ } else if scope.is_none() {+ return started;+ }- match tokio::time::timeout(Duration::from_secs(5), video_source.stop()).await {- Ok(Err(e)) => {- error!("Video source stop failed: {e:#}");+ if let Some(scope) = &scope+ && !scope.is_committed()+ {+ if let Err(error) = video_source.stop().await {+ scope.record_cleanup_error(error.to_string());}- Err(_) => {- error!("Video source stop timed out after 5s, proceeding with shutdown");+ } else {+ #[cfg(windows)]+ {+ let stopped = tokio::time::timeout(Duration::from_secs(5), video_source.stop())+ .await+ .map_err(|_| {+ anyhow!("Windows video source shutdown is unconfirmed after 5s")+ })+ .and_then(|result| result);+ started?;+ return stopped;+ }+ #[cfg(not(windows))]+ match tokio::time::timeout(Duration::from_secs(5), video_source.stop()).await {+ Ok(Err(error)) => {+ error!("Video source stop failed: {error:#}");+ }+ Err(_) => {+ error!("Video source stop timed out after 5s, proceeding with shutdown");+ }+ Ok(Ok(())) => {}}- Ok(Ok(())) => {}}- Ok(())+ started}});@@ -2163,7 +2816,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V}let remap =- source_clock.remap(&master_clock, timestamp, frame_duration_ns);+ remap_video_timestamp(&mut source_clock, &master_clock, timestamp, frame_duration_ns);if matches!(remap.outcome, SourceClockOutcome::HardReset) {warn!(source = "video",@@ -2212,13 +2865,20 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vfirst_frame_offset = Some(remap.duration().saturating_sub(total_pause_duration));}- if anomaly_tracker.take_resync_flag() {+ let resynced = anomaly_tracker.take_resync_flag();+ if resynced {info!(raw_duration_ms = raw_duration.as_millis(),"Timeline resync detected (anomaly collapsed jump); wall-clock anchor covers the gap");}- let duration = drift_tracker.calculate_timestamp(raw_duration, wall_clock_elapsed);+ let duration = calculate_video_timestamp(+ &mut drift_tracker,+ timestamp,+ raw_duration,+ wall_clock_elapsed,+ resynced || matches!(remap.outcome, SourceClockOutcome::HardReset),+ );timestamp_span.record(duration);if frame_count.is_multiple_of(300) {@@ -2286,7 +2946,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V}let remap =- source_clock.remap(&master_clock, timestamp, frame_duration_ns);+ remap_video_timestamp(&mut source_clock, &master_clock, timestamp, frame_duration_ns);if matches!(remap.outcome, SourceClockOutcome::HardReset) {anomaly_tracker = TimestampAnomalyTracker::new("video");}@@ -2331,9 +2991,14 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V);}- let _ = anomaly_tracker.take_resync_flag();- let duration =- drift_tracker.calculate_timestamp(raw_duration, wall_clock_elapsed);+ let resynced = anomaly_tracker.take_resync_flag();+ let duration = calculate_video_timestamp(+ &mut drift_tracker,+ timestamp,+ raw_duration,+ wall_clock_elapsed,+ resynced || matches!(remap.outcome, SourceClockOutcome::HardReset),+ );timestamp_span.record(duration);let duplicate = frame.duplicate();@@ -2438,6 +3103,22 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: VOk(())});+ started+}++async fn stop_audio_sources(+ sources: &mut [ErasedAudioSource],+ required_scope: Option<&PipelineBuildScope>,+) {+ for source in sources {+ let result = (source.stop_fn)(source.inner.as_mut()).await;+ let cleanup_scope = source.cleanup_scope.take();+ if let Err(error) = result+ && let Some(scope) = cleanup_scope.as_ref().or(required_scope)+ {+ scope.record_cleanup_error(error.to_string());+ }+ }}struct PreparedAudioSources {@@ -2466,6 +3147,9 @@ impl PreparedAudioSources {let has_wireless_source = self.has_wireless_source;let health_tx = setup_ctx.health_tx().clone();let master_clock = setup_ctx.master_clock().clone();+ let required_scope =+ PipelineBuildScope::current().filter(PipelineBuildScope::requires_joined_stop);+ let allow_audio_degradation = has_video && required_scope.is_none();if audio_anchor == AudioAnchor::PipelineEpoch && video_start_gate.is_some() {warn!(@@ -2502,7 +3186,7 @@ impl PreparedAudioSources {health_tx: &health_tx,shared_pause: &shared_pause,video_start_gate: video_start_gate.as_ref(),- has_video,+ allow_audio_degradation,origin: FrameProcessOrigin::Live,observed_at: Instant::now(),timestamps,@@ -2530,11 +3214,21 @@ impl PreparedAudioSources {Err(e) => return Err(e),}}+ anyhow::ensure!(+ required_scope.is_none() || stop_token.is_cancelled() || audio_degraded,+ "Required audio source closed while capture was active"+ );Ok::<(), anyhow::Error>(())}).await;let was_cancelled = res.is_none();+ let mut audio_error = res.and_then(Result::err);+ if let Some(error) = &audio_error+ && let Some(scope) = &required_scope+ {+ scope.fail_required(format!("Required audio processing failed: {error:#}"));+ }let cancellation_target_elapsed = if was_cancelled && !audio_degraded {Some(timestamps@@ -2564,7 +3258,7 @@ impl PreparedAudioSources {health_tx: &health_tx,shared_pause: &shared_pause,video_start_gate: video_start_gate.as_ref(),- has_video,+ allow_audio_degradation,origin: FrameProcessOrigin::Drain,observed_at: Instant::now(),timestamps,@@ -2589,9 +3283,16 @@ impl PreparedAudioSources {degraded_during_drain = true;break;}- Err(e) => {+ Err(error) => {+ if let Some(scope) = &required_scope {+ scope.fail_required(format!(+ "Required audio drain failed: {error:#}"+ ));+ let _ = audio_error.get_or_insert(error);+ break;+ }warn!(- "mux-audio drain: error processing frame, skipping: {e:#}"+ "mux-audio drain: error processing frame, skipping: {error:#}");skipped += 1;}@@ -2617,8 +3318,16 @@ impl PreparedAudioSources {let final_pause_duration = shared_pause.total_pause_duration();+ if let Some(scope) = &required_scope {+ stop_audio_sources(&mut self.erased_audio_sources, Some(scope)).await;+ }+if let Some(target_elapsed) = cancellation_target_elapsed&& !audio_degraded+ && audio_error.is_none()+ && !required_scope+ .as_ref()+ .is_some_and(PipelineBuildScope::has_recorded_error){// An epoch-anchored track that never received a frame// (e.g. WASAPI loopback with no sound played the whole@@ -2659,7 +3368,7 @@ impl PreparedAudioSources {).await{- if has_video {+ if allow_audio_degradation {warn!(padding_ms = tail_padding.as_millis() as u64,samples = tail_samples,@@ -2675,10 +3384,18 @@ impl PreparedAudioSources {},);} else {- return Err(anyhow!(+ let error = anyhow!("Audio muxer stopped accepting tail padding \after frame {frame_count}: {e}"- ));+ );+ if let Some(scope) = &required_scope {+ scope.fail_required(format!(+ "Required audio tail failed: {error:#}"+ ));+ let _ = audio_error.get_or_insert(error);+ } else {+ return Err(error);+ }}} else {info!(@@ -2718,19 +3435,19 @@ impl PreparedAudioSources {let _ = gap_summary_slot.set(gap_tracker.gap_summary());}- for source in &mut self.erased_audio_sources {- let _ = (source.stop_fn)(source.inner.as_mut()).await;+ if required_scope.is_none() {+ stop_audio_sources(&mut self.erased_audio_sources, None).await;}if !has_video {muxer.lock().await.stop();}- if let Some(Err(e)) = res {- if has_video {- error!("Audio stream ended with error (video continues): {e:#}");+ if let Some(error) = audio_error {+ if allow_audio_degradation {+ error!("Audio stream ended with error (video continues): {error:#}");} else {- return Err(e);+ return Err(error);}}@@ -2761,7 +3478,7 @@ struct AudioFrameProcessContext<'a, TMutex: AudioMuxer> {health_tx: &'a HealthSender,shared_pause: &'a SharedWallClockPause,video_start_gate: Option<&'a VideoStartGate>,- has_video: bool,+ allow_audio_degradation: bool,origin: FrameProcessOrigin,observed_at: Instant,timestamps: Timestamps,@@ -2862,7 +3579,7 @@ async fn process_audio_frame<TMutex: AudioMuxer>().await{- if ctx.has_video {+ if ctx.allow_audio_degradation {warn!("Audio muxer rejected head silence, \degrading to video-only: {e}"@@ -2918,21 +3635,21 @@ async fn process_audio_frame<TMutex: AudioMuxer>(return Ok(AudioFrameOutcome::DropFrame);}- if trim_samples > 0 {- if let Some(trimmed) = trim_audio_frame_front(&frame.inner, trim_samples) {- state- .gap_tracker- .record_overlap(overlap_duration, false, *state.frame_count);- debug!(- frame_count = *state.frame_count,- overlap_ms = overlap_duration.as_millis() as u64,- frame_samples,- trim_samples,- kept_samples = trimmed.samples(),- "Trimmed overlapping audio frame"- );- frame = AudioFrame::new(trimmed, frame.timestamp);- }+ if trim_samples > 0+ && let Some(trimmed) = trim_audio_frame_front(&frame.inner, trim_samples)+ {+ state+ .gap_tracker+ .record_overlap(overlap_duration, false, *state.frame_count);+ debug!(+ frame_count = *state.frame_count,+ overlap_ms = overlap_duration.as_millis() as u64,+ frame_samples,+ trim_samples,+ kept_samples = trimmed.samples(),+ "Trimmed overlapping audio frame"+ );+ frame = AudioFrame::new(trimmed, frame.timestamp);}}@@ -2981,7 +3698,7 @@ async fn process_audio_frame<TMutex: AudioMuxer>().await{- if ctx.has_video {+ if ctx.allow_audio_degradation {warn!(frame_count = *state.frame_count,"Audio muxer rejected silence frame, \@@ -3027,7 +3744,7 @@ async fn process_audio_frame<TMutex: AudioMuxer>(}if let Err(e) = ctx.muxer.lock().await.send_audio_frame(frame, timestamp) {- if ctx.has_video {+ if ctx.allow_audio_degradation {warn!(frame_count = *state.frame_count,"Audio muxer rejected frame, \@@ -3070,10 +3787,15 @@ async fn setup_audio_sources(erased_audio_sources.push(source);info} else {+ let required_scope =+ PipelineBuildScope::current().filter(PipelineBuildScope::requires_joined_stop);let mut audio_mixer = AudioMixer::builder().with_timestamps(timestamps).with_master_clock(setup_ctx.master_clock().clone()).with_health_tx(setup_ctx.health_tx().clone());+ if required_scope.is_some() {+ audio_mixer = audio_mixer.with_required_inputs(stop_token.clone());+ }let stop_flag = Arc::new(AtomicBool::new(false));let (ready_tx, ready_rx) = oneshot::channel::<anyhow::Result<()>>();@@ -3090,15 +3812,18 @@ async fn setup_audio_sources(move || {#[cfg(windows)]let _mmcss = cap_mediafoundation_utils::MmcssAudioHandle::register_audio();- audio_mixer.run(audio_tx, ready_tx, stop_flag);- Ok(())- }+ let result = audio_mixer.run(audio_tx, ready_tx, stop_flag);+ if let Some(scope) = required_scope {+ if let Err(error) = &result {+ scope.fail_required(format!("Required audio mixer failed: {error:#}"));+ }+ result+ } else {+ Ok(())+ }+ }});- ready_rx- .await- .map_err(|_| anyhow::format_err!("Audio mixer crashed"))??;-setup_ctx.tasks().spawn("audio-mixer-stop",stop_token.child_token().cancelled_owned().map(move |_| {@@ -3107,6 +3832,10 @@ async fn setup_audio_sources(}),);+ ready_rx+ .await+ .map_err(|_| anyhow::format_err!("Audio mixer crashed"))??;+AudioMixer::INFO};@@ -3129,6 +3858,7 @@ async fn setup_audio_sources(pub type DoneFut = Shared<BoxFuture<'static, Result<(), PipelineDoneError>>>;pub struct OutputPipeline {+ joined_stop: bool,path: PathBuf,pub first_timestamp_rx: oneshot::Receiver<Timestamp>,video_info: Option<VideoInfo>,@@ -3188,6 +3918,11 @@ impl std::error::Error for PipelineDoneError {}impl PipelineDoneError {+ #[cfg(any(target_os = "linux", windows))]+ pub(crate) fn from_message(message: String) -> Self {+ Self(Arc::new(anyhow!(message)))+ }+pub fn is_caused_by<T>(&self) -> boolwhereT: std::error::Error + 'static,@@ -3206,15 +3941,22 @@ impl OutputPipeline {pub async fn stop(mut self) -> anyhow::Result<FinishedOutputPipeline> {drop(self.stop_token.take());- const PIPELINE_STOP_TIMEOUT: Duration = Duration::from_secs(10);- match tokio::time::timeout(PIPELINE_STOP_TIMEOUT, self.done_fut.clone()).await {- Ok(Err(error)) if error.is_caused_by::<PipelineStoppedByUser>() => {}- Ok(res) => res?,- Err(_) => {- return Err(anyhow!(- "Pipeline stop timed out after {}s — tasks may still be running",- PIPELINE_STOP_TIMEOUT.as_secs()- ));+ if self.joined_stop {+ match self.done_fut.clone().await {+ Err(error) if error.is_caused_by::<PipelineStoppedByUser>() => {}+ result => result?,+ }+ } else {+ const PIPELINE_STOP_TIMEOUT: Duration = Duration::from_secs(10);+ match tokio::time::timeout(PIPELINE_STOP_TIMEOUT, self.done_fut.clone()).await {+ Ok(Err(error)) if error.is_caused_by::<PipelineStoppedByUser>() => {}+ Ok(res) => res?,+ Err(_) => {+ return Err(anyhow!(+ "Pipeline stop timed out after {}s — tasks may still be running",+ PIPELINE_STOP_TIMEOUT.as_secs()+ ));+ }}}@@ -3301,9 +4043,20 @@ impl<TVideoFrame: VideoFrame> VideoSource for ChannelVideoSource<TVideoFrame> {whereSelf: Sized,{- tokio::spawn(async move {- while let Ok(frame) = config.rx.recv_async().await {- let _ = video_tx.send(frame).await;+ let cancellation = PipelineBuildScope::current().map(|scope| scope.cancellation());+ spawn_capture_task(async move {+ let forward = async move {+ while let Ok(frame) = config.rx.recv_async().await {+ let _ = video_tx.send(frame).await;+ }+ };+ if let Some(cancellation) = cancellation {+ tokio::select! {+ _ = cancellation.cancelled() => {}+ _ = forward => {}+ }+ } else {+ forward.await;}});@@ -3338,9 +4091,20 @@ impl AudioSource for ChannelAudioSource {mut tx: mpsc::Sender<AudioFrame>,_: &mut SetupCtx,) -> impl Future<Output = anyhow::Result<Self>> + 'static {- tokio::spawn(async move {- while let Some(frame) = config.rx.next().await {- let _ = tx.send(frame).await;+ let cancellation = PipelineBuildScope::current().map(|scope| scope.cancellation());+ spawn_capture_task(async move {+ let forward = async move {+ while let Some(frame) = config.rx.next().await {+ let _ = tx.send(frame).await;+ }+ };+ if let Some(cancellation) = cancellation {+ tokio::select! {+ _ = cancellation.cancelled() => {}+ _ = forward => {}+ }+ } else {+ forward.await;}});@@ -3395,6 +4159,7 @@ pub trait VideoSource: Send + 'static {}struct ErasedAudioSource {+ cleanup_scope: Option<PipelineBuildScope>,inner: Box<dyn Any + Send>,audio_info: AudioInfo,start_fn: fn(&mut dyn Any) -> BoxFuture<'_, anyhow::Result<()>>,@@ -3404,6 +4169,7 @@ struct ErasedAudioSource {impl ErasedAudioSource {pub fn new<TAudio: AudioSource>(source: TAudio) -> Self {Self {+ cleanup_scope: PipelineBuildScope::current(),audio_info: source.audio_info(),start_fn: |raw| {raw.downcast_mut::<TAudio>()@@ -3422,6 +4188,16 @@ impl ErasedAudioSource {}}+impl Drop for ErasedAudioSource {+ fn drop(&mut self) {+ if let Some(scope) = self.cleanup_scope.take() {+ let mut inner = std::mem::replace(&mut self.inner, Box::new(()));+ let stop = self.stop_fn;+ scope.spawn_cleanup(async move { stop(inner.as_mut()).await });+ }+ }+}+pub trait AudioSource: Send + 'static {type Config: Send;@@ -3494,6 +4270,148 @@ pub trait VideoMuxer: Muxer {mod tests {use super::*;+ #[cfg(target_os = "linux")]+ mod video_cadence {+ use super::*;++ fn chain(samples: &[(u64, u64)], nominal: u64) -> Vec<Duration> {+ let timestamps = Timestamps::now();+ let master = MasterClock::new(timestamps, 48_000);+ let mut source = SourceClockState::new("video-cadence");+ let mut anomaly = TimestampAnomalyTracker::new("video-cadence");+ let mut drift = VideoDriftTracker::new();+ samples+ .iter()+ .map(|&(elapsed, paused)| {+ let remap = remap_video_timestamp(+ &mut source,+ &master,+ Timestamp::Instant(timestamps.instant() + Duration::from_nanos(elapsed)),+ nominal,+ );+ let content = remap+ .duration()+ .saturating_sub(Duration::from_nanos(paused));+ let wall =+ Duration::from_nanos(elapsed).saturating_sub(Duration::from_nanos(paused));+ let adjusted = anomaly+ .process_timestamp(+ Timestamp::Instant(timestamps.instant() + content),+ timestamps,+ wall,+ )+ .unwrap();+ calculate_video_timestamp(+ &mut drift,+ Timestamp::Instant(timestamps.instant() + Duration::from_nanos(elapsed)),+ adjusted,+ wall,+ anomaly.take_resync_flag()+ || matches!(remap.outcome, SourceClockOutcome::HardReset),+ )+ })+ .collect()+ }++ #[tokio::test]+ async fn first_video_gate_keeps_existing_audio_anchor() {+ let timestamps = Timestamps::now();+ let master = MasterClock::new(timestamps, 48_000);+ let timestamp = Timestamp::Instant(timestamps.instant() + Duration::from_millis(50));+ let mut video = SourceClockState::new("video");+ let mut legacy = SourceClockState::new("legacy");+ let first = remap_video_timestamp(&mut video, &master, timestamp, 33_333_333);+ let original = legacy.remap(&master, timestamp, 33_333_333);+ let gate = VideoStartGate::new();+ gate.publish(first.master_ns);+ assert_eq!(+ gate.wait_with_timeout(VIDEO_START_GATE_TIMEOUT).await,+ Some(original.master_ns)+ );+ }++ #[test]+ fn recorded_gap_stays_below_fifty_ms_through_video_chain() {+ let samples = [+ 46154413, 65568721, 110897087, 132556133, 194257322, 210630064, 295866539,+ 331422825, 358539718, 391572010, 419586633, 463879066, 472447881, 513265949,+ 553800082, 612231200, 659399095,+ ]+ .map(|raw| (raw, 0));+ let output = chain(&samples, 33_333_333);+ assert_eq!(output[0], Duration::ZERO);+ let gap = output[16].saturating_sub(output[15]);+ assert!(gap.as_nanos().abs_diff(47_167_895) <= 2);+ assert!(gap < Duration::from_millis(50));+ }++ #[test]+ fn per_frame_cadence_survives_full_video_chain() {+ for nominal in [24, 30, 60] {+ for actual in [10, 15, 20, 24, 25, 30, 48, 60, 90, 120, 240, 500, 1000] {+ let samples: Vec<_> = (0..(actual * 5))+ .map(|frame| (frame * 1_000_000_000 / actual, 0))+ .collect();+ let output = chain(&samples, 1_000_000_000 / nominal);+ for (source, mapped) in samples.windows(2).zip(output.windows(2)) {+ let expected = source[1].0 - source[0].0;+ assert!(mapped[1] >= mapped[0]);+ assert!(+ mapped[1]+ .saturating_sub(mapped[0])+ .as_nanos()+ .abs_diff(u128::from(expected))+ <= 2+ );+ }+ }+ }+ }++ #[test]+ fn pause_subtraction_preserves_first_anchor_and_resumed_cadence() {+ let samples = [+ (40_000_000, 0),+ (73_000_000, 0),+ (106_000_000, 0),+ (439_000_000, 300_000_000),+ (472_000_000, 300_000_000),+ ];+ let output = chain(&samples, 33_333_333);+ assert_eq!(output[0], Duration::ZERO);+ for pair in output.windows(2) {+ assert!(+ pair[1]+ .saturating_sub(pair[0])+ .as_nanos()+ .abs_diff(33_000_000)+ <= 2+ );+ }+ }++ #[test]+ fn backward_input_and_real_gap_do_not_manufacture_cadence() {+ let samples = [+ (0, 0),+ (100_000_000, 0),+ (90_000_000, 0),+ (110_000_000, 0),+ (510_000_000, 0),+ ];+ let output = chain(&samples, 33_333_333);+ assert!(output.windows(2).all(|pair| pair[1] >= pair[0]));+ assert_eq!(output[2], output[1]);+ assert!(+ output[4]+ .saturating_sub(output[3])+ .as_nanos()+ .abs_diff(400_000_000)+ <= 2+ );+ }+ }+mod shared_pause_state {use super::*;@@ -3869,6 +4787,469 @@ mod tests {}}+ #[cfg(target_os = "linux")]+ mod capture_instant_timeline {+ use super::*;++ fn ns(value: u64) -> Duration {+ Duration::from_nanos(value)+ }++ fn frame_timestamp() -> Timestamp {+ Timestamp::Instant(Instant::now())+ }++ fn calculate(+ tracker: &mut VideoDriftTracker,+ source: u64,+ wall: u64,+ discontinuity: bool,+ ) -> Duration {+ calculate_video_timestamp(+ tracker,+ frame_timestamp(),+ ns(source),+ ns(wall),+ discontinuity,+ )+ }++ #[test]+ fn native_ordinal_133_preserves_capture_interval_after_warmup() {+ let samples: &[(u64, u64)] = &[+ (0, 95682793),+ (27114964, 147244255),+ (60160557, 199388240),+ (123221877, 206342290),+ (152789024, 239281720),+ (232599956, 333259377),+ (295278757, 372096844),+ (327645815, 404019663),+ (346693336, 438355353),+ (390125563, 463239050),+ (461444811, 523692693),+ (496175220, 556146493),+ (522173230, 573227922),+ (547810413, 613717485),+ (599483227, 662648900),+ (622143716, 683799166),+ (653322178, 704266328),+ (677965580, 729287177),+ (743925832, 817289105),+ (765119259, 835720492),+ (800035952, 861270203),+ (854691131, 952278456),+ (892577468, 977307886),+ (925267593, 999309140),+ (949152808, 1017310478),+ (1006483464, 1066060480),+ (1030563143, 1100737517),+ (1087435730, 1144289057),+ (1101814640, 1191294860),+ (1142833915, 1217268250),+ (1171564664, 1225892757),+ (1215798278, 1296271844),+ (1276981397, 1341417948),+ (1309165232, 1364655229),+ (1329230154, 1404836225),+ (1393693885, 1475283205),+ (1406446130, 1493856875),+ (1460256350, 1512827414),+ (1486213959, 1542133916),+ (1512645240, 1560280748),+ (1571202683, 1644421532),+ (1613713459, 1673917608),+ (1642606942, 1718293675),+ (1678478526, 1745523622),+ (1696749980, 1748250721),+ (1761742242, 1823933723),+ (1822251806, 1904273466),+ (1860994502, 1939526586),+ (1888123407, 1977284880),+ (1907059505, 2000275786),+ (1946012225, 2020717947),+ (2031233403, 2100269282),+ (2064926440, 2124618968),+ (2091112984, 2161949543),+ (2122543422, 2178547351),+ (2144113787, 2253263992),+ (2185788866, 2271275250),+ (2230450579, 2283847141),+ (2269112003, 2323081597),+ (2307122953, 2381987888),+ (2335732840, 2430652777),+ (2390476690, 2467268307),+ (2415113492, 2477456286),+ (2440965369, 2511142223),+ (2477442026, 2538265428),+ (2513422432, 2567814576),+ (2532149686, 2596242329),+ (2570516834, 2627255178),+ (2630242342, 2715605554),+ (2655671601, 2739268745),+ (2679498415, 2751284594),+ (2729143936, 2809405467),+ (2774166027, 2841336826),+ (2793740769, 2860534471),+ (2870112077, 2959054426),+ (2932352250, 2994701925),+ (2978563457, 3054888123),+ (3004195190, 3069118210),+ (3031165202, 3114242144),+ (3073116317, 3127275405),+ (3087138649, 3142267139),+ (3136511014, 3203722494),+ (3170114549, 3239271471),+ (3201140428, 3283541426),+ (3246395395, 3349166652),+ (3254900458, 3377959113),+ (3309141978, 3390760579),+ (3340957325, 3413324226),+ (3358433092, 3437863406),+ (3409109695, 3474602578),+ (3440375930, 3500357634),+ (3507039168, 3556797691),+ (3529418791, 3606586485),+ (3562327660, 3632263159),+ (3612599725, 3684279992),+ (3652098487, 3724271064),+ (3666758543, 3740864232),+ (3698771254, 3759100796),+ (3745137884, 3814431649),+ (3781807025, 3861222329),+ (3828330689, 3909337637),+ (3849757551, 3924938763),+ (3875883585, 3969996566),+ (3927426507, 3987524084),+ (3996114899, 4070341220),+ (4043707826, 4125770086),+ (4067699962, 4148199310),+ (4111763603, 4188502299),+ (4128373672, 4201374747),+ (4213094350, 4262705540),+ (4252122591, 4304026062),+ (4268685089, 4320207471),+ (4324275768, 4374900381),+ (4344114556, 4432277358),+ (4381189566, 4463689246),+ (4405543372, 4512288595),+ (4448678652, 4528149937),+ (4475884119, 4553694878),+ (4514765008, 4567665839),+ (4546595365, 4604550715),+ (4612707041, 4701234411),+ (4658496569, 4724579455),+ (4667576795, 4748274576),+ (4719807141, 4774989832),+ (4753114760, 4814929274),+ (4780462090, 4838286948),+ (4803455396, 4862250995),+ (4862109561, 4930871675),+ (4905776243, 4989576641),+ (4948579797, 5024259800),+ (4958297956, 5067454972),+ (5002307326, 5082842023),+ (5075126037, 5195619816),+ (5101227820, 5233440232),+ (5130159594, 5245275488),+ (5160109270, 5285294841),+ (5192822186, 5312331994),+ (5237848647, 5334840270),+ (5258351260, 5361280670),+ (5293070059, 5378075643),+ (5334731567, 5400524067),+ (5386212938, 5444750921),+ (5405893663, 5479289486),+ (5453122582, 5510267564),+ (5507043685, 5571672489),+ (5546518086, 5626289808),+ (5573929588, 5641292811),+ (5608114445, 5680287162),+ (5674838485, 5733649014),+ (5701931439, 5768001895),+ (5736228699, 5791201955),+ (5752422158, 5803592483),+ (5808328595, 5864060157),+ (5837780620, 5903265543),+ (5875250638, 5936343426),+ (5927795302, 5978633579),+ (5955926529, 6015670768),+ (5997998796, 6071906271),+ (6008695527, 6083528852),+ (6066479624, 6138095519),+ (6082278355, 6147868400),+ (6138774393, 6198932651),+ (6163215591, 6221301584),+ (6232385643, 6308320581),+ (6272067069, 6330646713),+ (6303203431, 6390131086),+ ];+ let mut candidate = VideoDriftTracker::new();+ let mut legacy = VideoDriftTracker::new();+ let mut corrected = Vec::new();+ let mut previous = Vec::new();+ for &(source, wall) in samples {+ corrected.push(calculate(&mut candidate, source, wall, false));+ previous.push(legacy.calculate_timestamp(ns(source), ns(wall)));+ }+ assert_eq!(previous[132].saturating_sub(previous[131]), ns(112_777_793));+ assert_eq!(+ corrected[132].saturating_sub(corrected[131]),+ ns(72_818_711)+ );+ for (sample, output) in samples.windows(2).zip(corrected.windows(2)) {+ assert_eq!(+ output[1].saturating_sub(output[0]),+ ns(sample[1].0 - sample[0].0)+ );+ }+ }++ #[test]+ fn slower_and_faster_capture_ignore_consumer_arrival_jitter() {+ for actual_fps in [10u64, 15, 20, 24, 25, 30, 48, 60, 90, 120, 240, 500, 1000] {+ let mut tracker = VideoDriftTracker::new();+ let mut previous = Duration::ZERO;+ for frame in 0..actual_fps * 6 {+ let source = frame * 1_000_000_000 / actual_fps;+ let delay = if frame % 7 == 0 {+ 120_000_000+ } else {+ 10_000_000+ };+ let output = calculate(&mut tracker, source, source + delay, false);+ assert_eq!(output, ns(source));+ assert!(output >= previous);+ previous = output;+ }+ }+ }++ #[test]+ fn duplicate_and_backstep_do_not_advance_output() {+ let mut tracker = VideoDriftTracker::new();+ for (source, wall, expected) in [+ (0, 50, 0),+ (3000, 3050, 3000),+ (3000, 3150, 3000),+ (2990, 3200, 3000),+ (3033, 3300, 3033),+ ] {+ assert_eq!(+ calculate(&mut tracker, source * 1_000_000, wall * 1_000_000, false),+ ns(expected * 1_000_000)+ );+ }+ }++ #[test]+ fn actual_long_gap_survives_anomaly_tracker_with_bunched_arrivals() {+ let timestamps = Timestamps::now();+ let mut anomaly = TimestampAnomalyTracker::new("capture-gap");+ let mut drift = VideoDriftTracker::new();+ for (source, wall) in [(0, 100), (3000, 7100), (7000, 7101), (7033, 7200)] {+ let timestamp =+ Timestamp::Instant(timestamps.instant() + Duration::from_millis(source));+ let validated = anomaly+ .process_timestamp(timestamp, timestamps, Duration::from_millis(wall))+ .unwrap();+ assert!(!anomaly.take_resync_flag());+ assert_eq!(+ calculate_video_timestamp(+ &mut drift,+ timestamp,+ validated,+ Duration::from_millis(wall),+ false+ ),+ Duration::from_millis(source)+ );+ }+ }++ #[test]+ fn hard_reset_reanchors_once_then_preserves_source_intervals() {+ let epoch = Timestamps::now();+ let mut anomaly = TimestampAnomalyTracker::new("reset");+ let mut tracker = VideoDriftTracker::new();+ for (source, wall, expected, outcome) in [+ (0u64, 50u64, 0u64, SourceClockOutcome::Trusted),+ (3000, 3050, 3000, SourceClockOutcome::Trusted),+ (6050, 6050, 6000, SourceClockOutcome::HardReset),+ (6083, 6250, 6033, SourceClockOutcome::Trusted),+ (6116, 6260, 6066, SourceClockOutcome::Trusted),+ ] {+ if matches!(outcome, SourceClockOutcome::HardReset) {+ anomaly = TimestampAnomalyTracker::new("reset");+ }+ let timestamp = Timestamp::Instant(epoch.instant() + Duration::from_millis(source));+ let wall = Duration::from_millis(wall);+ let validated = anomaly.process_timestamp(timestamp, epoch, wall).unwrap();+ let discontinuity =+ anomaly.take_resync_flag() || matches!(outcome, SourceClockOutcome::HardReset);+ let output = calculate_video_timestamp(+ &mut tracker,+ timestamp,+ validated,+ wall,+ discontinuity,+ );+ assert!(+ output.abs_diff(Duration::from_millis(expected)) <= Duration::from_nanos(2)+ );+ }+ }++ #[test]+ fn anomaly_resync_retains_prior_output_and_resumes_content_clock() {+ let epoch = Timestamps::now();+ let mut anomaly = TimestampAnomalyTracker::new("resync");+ let mut tracker = VideoDriftTracker::new();+ for (source, wall, expected, resynced) in [+ (0u64, 50u64, 0u64, false),+ (3000, 3050, 3000, false),+ (10_000, 3090, 3040, true),+ (10_033, 3250, 3073, false),+ ] {+ let timestamp = Timestamp::Instant(epoch.instant() + Duration::from_millis(source));+ let wall = Duration::from_millis(wall);+ let validated = anomaly.process_timestamp(timestamp, epoch, wall).unwrap();+ let actual_resync = anomaly.take_resync_flag();+ assert_eq!(actual_resync, resynced);+ let output = calculate_video_timestamp(+ &mut tracker,+ timestamp,+ validated,+ wall,+ actual_resync,+ );+ assert!(+ output.abs_diff(Duration::from_millis(expected)) <= Duration::from_nanos(2)+ );+ }+ }++ #[test]+ fn initial_discontinuity_does_not_inject_startup_wait() {+ let mut tracker = VideoDriftTracker::new();+ assert_eq!(+ calculate(&mut tracker, 0, 30_000_000_000, true),+ Duration::ZERO+ );+ assert_eq!(+ calculate(&mut tracker, 33_000_000, 30_200_000_000, false),+ ns(33_000_000)+ );+ }++ #[test]+ fn pause_is_excised_before_both_clocks_and_recovery() {+ let mut tracker = VideoDriftTracker::new();+ for (source, wall, paused, expected) in [+ (0u64, 50u64, 0u64, 0u64),+ (3000, 3050, 0, 3000),+ (6033, 6200, 3000, 3033),+ (6066, 6300, 3000, 3066),+ ] {+ let source =+ Duration::from_millis(source).saturating_sub(Duration::from_millis(paused));+ let wall =+ Duration::from_millis(wall).saturating_sub(Duration::from_millis(paused));+ assert_eq!(+ calculate_video_timestamp(&mut tracker, frame_timestamp(), source, wall, false),+ Duration::from_millis(expected)+ );+ }+ }++ #[test]+ fn new_studio_segment_has_no_previous_epoch_floor() {+ let mut old = VideoDriftTracker::new();+ calculate(&mut old, 9_000_000_000, 9_050_000_000, false);+ let mut resumed = VideoDriftTracker::new();+ assert_eq!(+ calculate(&mut resumed, 0, 250_000_000, false),+ Duration::ZERO+ );+ assert_eq!(+ calculate(&mut resumed, 33_000_000, 450_000_000, false),+ ns(33_000_000)+ );+ }++ #[test]+ fn non_instant_clock_keeps_legacy_device_drift_correction() {+ let mut policy = VideoDriftTracker::new();+ let mut original = VideoDriftTracker::new();+ for (source, wall) in [(2.0, 2.0), (10.1, 10.0), (60.3, 60.0)] {+ let source = Duration::from_secs_f64(source);+ let wall = Duration::from_secs_f64(wall);+ let actual = calculate_video_timestamp(+ &mut policy,+ Timestamp::SystemTime(std::time::SystemTime::now()),+ source,+ wall,+ false,+ );+ assert_eq!(actual, original.calculate_timestamp(source, wall));+ }+ }++ #[test]+ fn source_bound_and_previous_floor_survive_future_clock_glitch() {+ let mut tracker = VideoDriftTracker::new();+ let wall = Duration::from_secs(1);+ let bound =+ wall.saturating_add(Duration::from_secs_f64(VIDEO_WALL_CLOCK_TOLERANCE_SECS));+ let capped = calculate(&mut tracker, 100_000_000_000, 1_000_000_000, false);+ assert_eq!(capped, bound);+ assert_eq!(calculate(&mut tracker, 0, 900_000_000, false), bound);+ assert!(tracker.capped_frame_count() > 0);+ }++ #[test]+ fn audio_sample_clock_does_not_follow_video_arrival_jitter() {+ let mut video = VideoDriftTracker::new();+ let mut audio = AudioTimestampGenerator::new(48_000);+ for frame in 0..180u64 {+ let source = Duration::from_nanos(frame * 1_000_000_000 / 30);+ let wall = source.saturating_add(Duration::from_millis(if frame % 3 == 0 {+ 180+ } else {+ 50+ }));+ let pts =+ calculate_video_timestamp(&mut video, frame_timestamp(), source, wall, false);+ let audio_pts = audio.next_timestamp(1600);+ assert!(pts.abs_diff(audio_pts) <= Duration::from_nanos(1));+ }+ }++ #[test]+ fn drain_uses_same_content_timeline_not_drain_arrival() {+ let mut tracker = VideoDriftTracker::new();+ calculate(&mut tracker, 3_000_000_000, 3_050_000_000, false);+ assert_eq!(+ calculate(&mut tracker, 3_033_000_000, 4_000_000_000, false),+ ns(3_033_000_000)+ );+ assert_eq!(+ calculate(&mut tracker, 3_066_000_000, 4_001_000_000, false),+ ns(3_066_000_000)+ );+ }++ #[test]+ fn static_last_frame_tail_still_covers_stop_content_time() {+ let mut tracker = VideoDriftTracker::new();+ let last = calculate(&mut tracker, 3_000_000_000, 3_050_000_000, false);+ assert_eq!(+ static_video_tail_timestamp(last, ns(7_000_000_000), ns(33_333_333)),+ Some(ns(6_966_666_667))+ );+ }+ }+mod video_drift_tracker {use super::*;@@ -4056,7 +5437,12 @@ mod tests {last_elapsed = elapsed;let frame_ts = Timestamp::Instant(start + elapsed);- let remap = source_clock.remap(&master_clock, frame_ts, nominal_frame_duration_ns);+ let remap = remap_video_timestamp(+ &mut source_clock,+ &master_clock,+ frame_ts,+ nominal_frame_duration_ns,+ );let remapped_ts = Timestamp::Instant(timestamps.instant() + remap.duration());let raw_duration = anomaly_tracker@@ -4783,6 +6169,149 @@ mod tests {mod finish_build {use super::*;+ enum FinishOutcome {+ Success,+ InnerError,+ OuterError,+ Panic,+ }++ struct FinishProbe {+ calls: Arc<std::sync::Mutex<Vec<Duration>>>,+ outcome: FinishOutcome,+ blocking: Option<(+ tokio::sync::oneshot::Sender<()>,+ std::sync::mpsc::Receiver<()>,+ )>,+ }++ impl FinishProbe {+ fn new(outcome: FinishOutcome) -> Self {+ Self {+ calls: Arc::new(std::sync::Mutex::new(Vec::new())),+ outcome,+ blocking: None,+ }+ }+ }++ impl Muxer for FinishProbe {+ type Config = Self;++ fn setup(+ config: Self::Config,+ _output_path: PathBuf,+ _video_config: Option<VideoInfo>,+ _audio_config: Option<AudioInfo>,+ _pause_flag: Arc<AtomicBool>,+ _tasks: &mut TaskPool,+ ) -> impl Future<Output = anyhow::Result<Self>> + Send {+ std::future::ready(Ok(config))+ }++ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ self.calls.lock().unwrap().push(timestamp);+ if let Some((entered, release)) = self.blocking.take() {+ entered+ .send(())+ .map_err(|_| anyhow!("finish observer dropped"))?;+ release+ .recv_timeout(Duration::from_secs(3))+ .context("finish release timed out")?;+ }+ match self.outcome {+ FinishOutcome::Success => Ok(Ok(())),+ FinishOutcome::InnerError => Ok(Err(anyhow!("inner finish failure"))),+ FinishOutcome::OuterError => Err(anyhow!("outer finish failure")),+ FinishOutcome::Panic => panic!("finish panic"),+ }+ }+ }++ async fn finish_probe(outcome: FinishOutcome) -> anyhow::Result<anyhow::Result<()>> {+ let muxer = Arc::new(Mutex::new(FinishProbe::new(outcome)));+ finish_muxer(muxer.lock_owned().await, Duration::from_secs(7)).await+ }++ #[tokio::test(flavor = "current_thread")]+ async fn blocking_finish_keeps_runtime_responsive() {+ let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();+ let (release_tx, release_rx) = std::sync::mpsc::channel();+ let mut probe = FinishProbe::new(FinishOutcome::Success);+ probe.blocking = Some((entered_tx, release_rx));+ let muxer = Arc::new(Mutex::new(probe));+ let guard = muxer.lock_owned().await;+ let finishing = tokio::spawn(finish_muxer(guard, Duration::from_secs(7)));++ tokio::time::timeout(Duration::from_secs(1), entered_rx)+ .await+ .unwrap()+ .unwrap();+ tokio::time::timeout(Duration::from_millis(100), async {+ tokio::time::sleep(Duration::from_millis(1)).await;+ assert!(!finishing.is_finished());+ release_tx.send(()).unwrap();+ })+ .await+ .unwrap();+ finishing.await.unwrap().unwrap().unwrap();+ }++ #[tokio::test]+ async fn blocking_finish_runs_once_with_the_captured_timestamp() {+ let probe = FinishProbe::new(FinishOutcome::Success);+ let calls = probe.calls.clone();+ let muxer = Arc::new(Mutex::new(probe));+ let timestamp = Duration::from_nanos(7_123_456_789);+ finish_muxer(muxer.lock_owned().await, timestamp)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(*calls.lock().unwrap(), vec![timestamp]);+ }++ #[tokio::test]+ async fn blocking_finish_success_completes_pipeline() {+ resolve_pipeline_completion(+ Ok(()),+ finish_probe(FinishOutcome::Success).await,+ &PipelineStopSignal::default(),+ )+ .unwrap();+ }++ #[tokio::test]+ async fn blocking_finish_preserves_inner_failure() {+ let result = finish_probe(FinishOutcome::InnerError).await;+ assert!(result.is_ok());+ let error = resolve_pipeline_completion(Ok(()), result, &PipelineStopSignal::default())+ .unwrap_err();+ assert!(error.to_string().contains("inner finish failure"));+ }++ #[tokio::test]+ async fn blocking_finish_preserves_outer_failure() {+ let result = finish_probe(FinishOutcome::OuterError).await;+ assert!(result.is_err());+ let error = resolve_pipeline_completion(Ok(()), result, &PipelineStopSignal::default())+ .unwrap_err();+ assert!(error.to_string().contains("outer finish failure"));+ }++ #[tokio::test]+ async fn blocking_finish_panic_is_a_pipeline_failure() {+ let result = finish_probe(FinishOutcome::Panic).await;+ assert!(result.is_err());+ let error = resolve_pipeline_completion(Ok(()), result, &PipelineStopSignal::default())+ .unwrap_err();+ assert!(error.to_string().contains("Muxer finalization task failed"));+ assert!(+ error+ .chain()+ .any(|cause| cause.is::<tokio::task::JoinError>())+ );+ }+#[test]fn treats_inner_muxer_finish_error_as_failure() {let result = resolve_pipeline_completion(@@ -5925,7 +7454,7 @@ mod tests {health_tx: &self.health_tx,shared_pause: &self.shared_pause,video_start_gate: None,- has_video: true,+ allow_audio_degradation: true,origin: FrameProcessOrigin::Live,observed_at,timestamps: self.timestamps,@@ -6430,5 +7959,1235 @@ mod tests {None);}+ #[cfg(target_os = "linux")]+ mod configured_audio_tail {+ use super::*;++ #[derive(Clone, Debug)]+ struct ObservedFrame {+ samples: usize,+ timestamp: Duration,+ pcm: Vec<f32>,+ }++ #[derive(Clone, Default)]+ struct Observation {+ frames: Arc<std::sync::Mutex<Vec<ObservedFrame>>>,+ events: Arc<std::sync::Mutex<Vec<&'static str>>>,+ first_frame: Arc<tokio::sync::Notify>,+ }++ struct ObservedMuxer(Observation);++ impl Muxer for ObservedMuxer {+ type Config = Observation;++ 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> {+ Ok(Self(config))+ }++ fn stop(&mut self) {+ self.0.events.lock().unwrap().push("mux-stop");+ }++ fn finish(&mut self, _timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ Ok(Ok(()))+ }+ }++ impl AudioMuxer for ObservedMuxer {+ fn send_audio_frame(+ &mut self,+ frame: AudioFrame,+ timestamp: Duration,+ ) -> anyhow::Result<()> {+ let count = frame.inner.samples() * TEST_CHANNELS;+ let pcm = frame.inner.data(0)[..count * size_of::<f32>()]+ .chunks_exact(size_of::<f32>())+ .map(|bytes| f32::from_ne_bytes(bytes.try_into().unwrap()))+ .collect::<Vec<_>>();+ let silent = pcm.iter().all(|sample| *sample == 0.0);+ self.0.events.lock().unwrap().push(if silent {+ "silence"+ } else {+ "real-audio"+ });+ self.0.frames.lock().unwrap().push(ObservedFrame {+ samples: frame.inner.samples(),+ timestamp,+ pcm,+ });+ self.0.first_frame.notify_one();+ Ok(())+ }+ }++ struct StopReportingSource {+ info: AudioInfo,+ observation: Observation,+ failure_scope: Option<PipelineBuildScope>,+ return_stop_error: bool,+ }++ impl AudioSource for StopReportingSource {+ type Config = Self;++ fn setup(+ config: Self::Config,+ _tx: mpsc::Sender<AudioFrame>,+ _ctx: &mut SetupCtx,+ ) -> impl Future<Output = anyhow::Result<Self>> + Send + 'static {+ future::ready(Ok(config))+ }++ fn audio_info(&self) -> AudioInfo {+ self.info+ }++ async fn stop(&mut self) -> anyhow::Result<()> {+ self.observation.events.lock().unwrap().push("source-stop");+ if let Some(scope) = &self.failure_scope {+ self.observation.events.lock().unwrap().push("source-error");+ scope.fail_required(+ "Backend failure first observed during source Stop".into(),+ );+ }+ if self.return_stop_error {+ self.observation.events.lock().unwrap().push("source-error");+ return Err(anyhow!("Cleanup failed during source Stop"));+ }+ Ok(())+ }+ }++ #[derive(Clone, Copy)]+ enum StopCause {+ Healthy,+ LegacyHealthy,+ CurrentSource,+ SiblingSource,+ FirstReportedAtSourceStop,+ MissingCleanupScopeStopError,+ }++ async fn reach_tail_target(timestamps: Timestamps) {+ let target = timestamps.instant() + Duration::from_millis(100);+ while Instant::now() < target {+ tokio::time::sleep_until(tokio::time::Instant::from_std(target)).await;+ }+ }++ async fn configure_case(+ cause: StopCause,+ queued_before_cancel: bool,+ ) -> (Observation, PipelineJoinReport) {+ let parent = if matches!(cause, StopCause::LegacyHealthy) {+ PipelineBuildScope::new()+ } else {+ PipelineBuildScope::new_studio_lifetime()+ };+ let scope = parent.child_transaction();+ let sibling = parent.child_transaction();+ let stop = CancellationToken::new();+ scope.register_token(stop.clone());+ assert!(scope.commit());+ assert!(sibling.commit());+ let info = test_audio_info();+ let timestamps = Timestamps::now();+ let clock = MasterClock::new(timestamps, TEST_SAMPLE_RATE);+ let (health_tx, _health_rx) = new_health_channel();+ let mut context = SetupCtx::new(+ health_tx,+ clock,+ stop.clone(),+ PipelineStopSignal::default(),+ );+ let observation = Observation::default();+ let muxer = Arc::new(Mutex::new(ObservedMuxer(observation.clone())));+ let (mut sender, receiver) = mpsc::channel(4);+ sender+ .try_send(AudioFrame::new(+ make_test_frame(&info, 480, 0.25),+ Timestamp::Instant(timestamps.instant()),+ ))+ .unwrap();+ if queued_before_cancel {+ sender+ .try_send(AudioFrame::new(+ make_test_frame(&info, 480, 0.5),+ Timestamp::Instant(timestamps.instant() + Duration::from_millis(10)),+ ))+ .unwrap();+ scope.fail_required("Known source failure before queued drain".into());+ assert!(stop.is_cancelled());+ reach_tail_target(timestamps).await;+ }+ let observed = observation.clone();+ let stop_failure =+ matches!(cause, StopCause::FirstReportedAtSourceStop).then(|| scope.clone());+ scope+ .run(async {+ let source = StopReportingSource {+ info,+ observation: observed,+ failure_scope: stop_failure,+ return_stop_error: matches!(+ cause,+ StopCause::MissingCleanupScopeStopError+ ),+ };+ let mut source = ErasedAudioSource::new(source);+ if matches!(cause, StopCause::MissingCleanupScopeStopError) {+ source.cleanup_scope = None;+ }+ PreparedAudioSources {+ audio_info: info,+ audio_rx: receiver,+ erased_audio_sources: vec![source],+ has_wireless_source: false,+ }+ .configure(+ &mut context,+ muxer,+ stop.clone(),+ timestamps,+ None,+ SharedWallClockPause::new(Arc::new(AtomicBool::new(false))),+ false,+ None,+ Arc::new(OnceLock::new()),+ AudioAnchor::FirstFrame,+ );+ })+ .await;+ if !queued_before_cancel {+ tokio::time::timeout(+ Duration::from_secs(1),+ observation.first_frame.notified(),+ )+ .await+ .unwrap();+ reach_tail_target(timestamps).await;+ match cause {+ StopCause::Healthy+ | StopCause::LegacyHealthy+ | StopCause::FirstReportedAtSourceStop+ | StopCause::MissingCleanupScopeStopError => parent.cancel(),+ StopCause::CurrentSource => {+ scope.fail_required("Current source failed".into())+ }+ StopCause::SiblingSource => {+ sibling.fail_required("Sibling source failed".into())+ }+ }+ }+ assert!(stop.is_cancelled());+ let tasks = std::mem::take(&mut context.tasks.0);+ assert_eq!(tasks.len(), 1);+ for (name, task) in tasks {+ assert_eq!(name, "mux-audio");+ tokio::time::timeout(Duration::from_secs(1), task)+ .await+ .unwrap()+ .unwrap()+ .unwrap();+ }+ drop(sender);+ let report =+ tokio::time::timeout(Duration::from_secs(1), parent.cancel_and_join_report())+ .await+ .unwrap();+ assert_eq!(+ report.quiescent,+ !matches!(cause, StopCause::MissingCleanupScopeStopError),+ );+ assert_eq!(+ observation+ .events+ .lock()+ .unwrap()+ .iter()+ .filter(|event| **event == "source-stop")+ .count(),+ 1+ );+ (observation, report)+ }++ fn assert_only_real(observation: &Observation, expected: &[f32]) {+ let frames = observation.frames.lock().unwrap();+ assert_eq!(frames.len(), expected.len());+ for (index, (frame, value)) in frames.iter().zip(expected).enumerate() {+ assert_eq!(frame.samples, 480);+ assert!(frame.pcm.iter().all(|sample| sample == value));+ assert_eq!(frame.timestamp, Duration::from_millis(index as u64 * 10));+ }+ assert!(!observation.events.lock().unwrap().contains(&"silence"));+ }++ #[tokio::test(flavor = "current_thread")]+ async fn healthy_stop_still_muxes_tail_silence_after_actual_pcm() {+ for cause in [StopCause::Healthy, StopCause::LegacyHealthy] {+ let (observed, report) = configure_case(cause, false).await;+ assert!(report.error.is_none());+ let frames = observed.frames.lock().unwrap();+ assert!(frames.len() >= 2);+ assert_eq!(frames[0].samples, 480);+ assert!(frames[0].pcm.iter().all(|sample| *sample == 0.25));+ assert!(+ frames[1..]+ .iter()+ .all(|frame| frame.pcm.iter().all(|sample| *sample == 0.0))+ );+ assert!(frames[1..].iter().map(|frame| frame.samples).sum::<usize>() >= 4320);+ assert_eq!(frames[1].timestamp, Duration::from_millis(10));+ let events = observed.events.lock().unwrap();+ let stopped = events+ .iter()+ .position(|event| *event == "source-stop")+ .unwrap();+ let padding = events.iter().position(|event| *event == "silence").unwrap();+ assert_eq!(stopped < padding, matches!(cause, StopCause::Healthy));+ }+ }++ #[tokio::test(flavor = "current_thread")]+ async fn committed_current_source_failure_prevents_muxed_tail_silence() {+ let (observed, report) = configure_case(StopCause::CurrentSource, false).await;+ assert!(report.error.unwrap().contains("Current source failed"));+ assert_only_real(&observed, &[0.25]);+ }++ #[tokio::test(flavor = "current_thread")]+ async fn committed_sibling_failure_prevents_muxed_tail_silence() {+ let (observed, report) = configure_case(StopCause::SiblingSource, false).await;+ assert!(report.error.unwrap().contains("Sibling source failed"));+ assert_only_real(&observed, &[0.25]);+ }++ #[tokio::test(flavor = "current_thread")]+ async fn failure_cancellation_drains_every_queued_real_frame_without_tail() {+ let (observed, report) = configure_case(StopCause::CurrentSource, true).await;+ assert!(report.error.unwrap().contains("Known source failure"));+ assert_only_real(&observed, &[0.25, 0.5]);+ }++ #[tokio::test(flavor = "current_thread")]+ async fn source_stop_failure_is_recorded_before_padding_decision() {+ for cause in [+ StopCause::FirstReportedAtSourceStop,+ StopCause::MissingCleanupScopeStopError,+ ] {+ let (observed, report) = configure_case(cause, false).await;+ assert!(report.error.unwrap().contains("during source Stop"));+ assert_only_real(&observed, &[0.25]);+ let events = observed.events.lock().unwrap();+ let failure = events+ .iter()+ .position(|event| *event == "source-error")+ .unwrap();+ let mux_stop = events+ .iter()+ .position(|event| *event == "mux-stop")+ .unwrap();+ assert!(failure < mux_stop);+ }+ }+ }+ }+}++#[cfg(test)]+mod build_scope_tests {+ use super::*;+ use std::sync::atomic::AtomicUsize;++ #[derive(Clone, Copy, PartialEq, Eq)]+ enum FailureStage {+ VideoSetup,+ AudioSetup,+ AudioStart,+ MuxerSetup,+ MuxerPending,+ VideoStart,+ #[cfg(windows)]+ VideoStop,+ None,+ }++ #[derive(Clone)]+ struct Probe {+ stage: FailureStage,+ cancel: CancellationToken,+ alive: Arc<AtomicUsize>,+ stopped: Arc<AtomicUsize>,+ finished: Arc<AtomicUsize>,+ setup_pending: Arc<tokio::sync::Notify>,+ }++ impl Probe {+ fn new(stage: FailureStage, scope: &PipelineBuildScope) -> Self {+ Self {+ stage,+ cancel: scope.cancellation(),+ alive: Arc::new(AtomicUsize::new(0)),+ stopped: Arc::new(AtomicUsize::new(0)),+ finished: Arc::new(AtomicUsize::new(0)),+ setup_pending: Arc::new(tokio::sync::Notify::new()),+ }+ }++ fn task(&self, tasks: &mut TaskPool) {+ self.alive.fetch_add(1, Ordering::AcqRel);+ let probe = self.clone();+ tasks.spawn("resume-owned-setup", async move {+ probe.cancel.cancelled().await;+ probe.alive.fetch_sub(1, Ordering::AcqRel);+ Ok(())+ });+ }+ }++ #[derive(Clone, Copy)]+ struct Frame(Timestamp);++ impl VideoFrame for Frame {+ fn timestamp(&self) -> Timestamp {+ self.0+ }+ }++ struct Video {+ probe: Probe,+ sender: Option<mpsc::Sender<Frame>>,+ }++ impl VideoSource for Video {+ type Config = Probe;+ type Frame = Frame;++ async fn setup(+ probe: Probe,+ sender: mpsc::Sender<Frame>,+ ctx: &mut SetupCtx,+ ) -> anyhow::Result<Self> {+ probe.task(ctx.tasks());+ if probe.stage == FailureStage::VideoSetup {+ anyhow::bail!("video setup fault");+ }+ Ok(Self {+ probe,+ sender: Some(sender),+ })+ }++ fn video_info(&self) -> VideoInfo {+ VideoInfo::from_raw(cap_media_info::RawVideoFormat::Bgra, 16, 16, 30)+ }++ fn start(&mut self) -> BoxFuture<'_, anyhow::Result<()>> {+ async move {+ if self.probe.stage == FailureStage::VideoStart {+ anyhow::bail!("video start fault");+ }+ Ok(())+ }+ .boxed()+ }++ fn stop(&mut self) -> BoxFuture<'_, anyhow::Result<()>> {+ async move {+ self.probe.stopped.fetch_add(1, Ordering::AcqRel);+ drop(self.sender.take());+ #[cfg(windows)]+ if self.probe.stage == FailureStage::VideoStop {+ anyhow::bail!("video stop fault");+ }+ Ok(())+ }+ .boxed()+ }+ }++ struct Audio {+ probe: Probe,+ sender: Option<mpsc::Sender<AudioFrame>>,+ }++ impl AudioSource for Audio {+ type Config = Probe;++ fn setup(+ probe: Probe,+ sender: mpsc::Sender<AudioFrame>,+ ctx: &mut SetupCtx,+ ) -> impl Future<Output = anyhow::Result<Self>> + Send + 'static {+ probe.task(ctx.tasks());+ let result = if probe.stage == FailureStage::AudioSetup {+ Err(anyhow!("audio setup fault"))+ } else {+ Ok(Self {+ probe,+ sender: Some(sender),+ })+ };+ future::ready(result)+ }++ fn audio_info(&self) -> AudioInfo {+ AudioInfo::new_raw(+ cap_media_info::Sample::F32(cap_media_info::Type::Packed),+ 48_000,+ 2,+ )+ }++ async fn start(&mut self) -> anyhow::Result<()> {+ if self.probe.stage == FailureStage::AudioStart {+ anyhow::bail!("audio start fault");+ }+ Ok(())+ }++ async fn stop(&mut self) -> anyhow::Result<()> {+ self.probe.stopped.fetch_add(1, Ordering::AcqRel);+ drop(self.sender.take());+ Ok(())+ }+ }++ struct Encoder(Probe);++ impl Muxer for Encoder {+ type Config = Probe;++ async fn setup(+ probe: Probe,+ _: PathBuf,+ _: Option<VideoInfo>,+ _: Option<AudioInfo>,+ _: Arc<AtomicBool>,+ tasks: &mut TaskPool,+ ) -> anyhow::Result<Self> {+ probe.task(tasks);+ if probe.stage == FailureStage::MuxerSetup {+ anyhow::bail!("muxer setup fault");+ }+ if probe.stage == FailureStage::MuxerPending {+ probe.setup_pending.notify_one();+ std::future::pending::<()>().await;+ }+ Ok(Self(probe))+ }++ fn finish(&mut self, _: Duration) -> anyhow::Result<anyhow::Result<()>> {+ self.0.finished.fetch_add(1, Ordering::AcqRel);+ Ok(Ok(()))+ }+ }++ impl VideoMuxer for Encoder {+ type VideoFrame = Frame;+ fn send_video_frame(&mut self, _: Frame, _: Duration) -> anyhow::Result<()> {+ Ok(())+ }+ }++ impl AudioMuxer for Encoder {+ fn send_audio_frame(&mut self, _: AudioFrame, _: Duration) -> anyhow::Result<()> {+ Ok(())+ }+ }++ #[tokio::test]+ async fn windows_failed_audio_setup_joins_workers_using_the_pipeline_stop_token() {+ let scope = PipelineBuildScope::new();+ let exited = Arc::new(AtomicUsize::new(0));+ let observed = exited.clone();+ let result = tokio::time::timeout(+ Duration::from_secs(2),+ finish_windows_pipeline_startup(&scope, async move {+ let build = BuildCtx::new();+ let mut setup = SetupCtx::new(+ build.health_tx.clone(),+ MasterClock::new(Timestamps::now(), 48_000),+ build.stop_token.clone(),+ build.stop_signal.clone(),+ );+ let cancel = setup.stop_token().child_token();+ setup.tasks().spawn("system-audio", {+ let cancel = cancel.clone();+ let exited = observed.clone();+ async move {+ cancel.cancelled().await;+ exited.fetch_add(1, Ordering::AcqRel);+ Ok(())+ }+ });+ let runtime = tokio::runtime::Handle::current();+ setup.tasks().spawn_thread("system-audio-watcher", move || {+ runtime.block_on(cancel.cancelled());+ observed.fetch_add(1, Ordering::AcqRel);+ Ok(())+ });+ Err::<(), _>(anyhow!("initial loopback creation failed"))+ }),+ )+ .await+ .unwrap();+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("initial loopback creation failed")+ );+ assert_eq!(exited.load(Ordering::Acquire), 2);+ }++ #[cfg(windows)]+ #[tokio::test]+ async fn windows_committed_pipeline_propagates_source_stop_failure() {+ let scope = PipelineBuildScope::new();+ let probe = Probe::new(FailureStage::VideoStop, &scope);+ let directory = tempfile::tempdir().unwrap();+ let pipeline = finish_windows_pipeline_startup(+ &scope,+ OutputPipeline::builder(directory.path().join("stop-fault.mp4"))+ .with_video::<Video>(probe.clone())+ .build::<Encoder>(probe.clone()),+ )+ .await+ .unwrap();+ probe.cancel.cancel();+ let error = pipeline.stop().await.unwrap_err();+ assert!(format!("{error:#}").contains("video stop fault"));+ assert_eq!(probe.alive.load(Ordering::Acquire), 0);+ }++ #[tokio::test]+ async fn windows_startup_failure_joins_actual_pipeline_tasks_before_return() {+ for stage in [+ FailureStage::VideoSetup,+ FailureStage::AudioSetup,+ FailureStage::MuxerSetup,+ FailureStage::VideoStart,+ ] {+ let scope = PipelineBuildScope::new();+ let probe = Probe::new(stage, &scope);+ let directory = tempfile::tempdir().unwrap();+ let result = tokio::time::timeout(+ Duration::from_secs(3),+ finish_windows_pipeline_startup(+ &scope,+ OutputPipeline::builder(directory.path().join("unused.mp4"))+ .with_video::<Video>(probe.clone())+ .with_audio_source::<Audio>(probe.clone())+ .build::<Encoder>(probe.clone()),+ ),+ )+ .await+ .unwrap();+ assert!(result.is_err());+ assert_eq!(probe.alive.load(Ordering::Acquire), 0);+ assert!(!scope.is_committed());+ }+ }++ #[tokio::test]+ async fn late_requested_track_failure_joins_the_started_screen() {+ for stage in [+ FailureStage::VideoSetup,+ FailureStage::AudioSetup,+ FailureStage::AudioStart,+ ] {+ let scope = PipelineBuildScope::new();+ let screen = Probe::new(FailureStage::None, &scope);+ let requested = Probe::new(stage, &scope);+ let directory = tempfile::tempdir().unwrap();+ let result = finish_windows_pipeline_startup(&scope, async {+ let _screen = OutputPipeline::builder(directory.path().join("screen.mp4"))+ .with_video::<Video>(screen.clone())+ .build::<Encoder>(screen.clone())+ .await?;+ if stage == FailureStage::VideoSetup {+ OutputPipeline::builder(directory.path().join("camera.mp4"))+ .with_video::<Video>(requested.clone())+ .build::<Encoder>(requested.clone())+ .await?;+ } else {+ OutputPipeline::builder(directory.path().join("audio.mp4"))+ .with_audio_source::<Audio>(requested.clone())+ .build::<Encoder>(requested.clone())+ .await?;+ }+ Ok(())+ })+ .await;+ assert!(result.is_err());+ assert_eq!(screen.alive.load(Ordering::Acquire), 0);+ assert_eq!(requested.alive.load(Ordering::Acquire), 0);+ assert_eq!(screen.stopped.load(Ordering::Acquire), 1);+ assert!(!scope.is_committed());+ }+ }++ #[tokio::test]+ async fn dropped_windows_startup_cancels_owned_work() {+ let scope = PipelineBuildScope::new();+ let entered = Arc::new(tokio::sync::Notify::new());+ let ready = entered.clone();+ let owned = scope.clone();+ let task = tokio::spawn(async move {+ finish_windows_pipeline_startup(&owned, async {+ ready.notify_one();+ std::future::pending::<anyhow::Result<()>>().await+ })+ .await+ });+ entered.notified().await;+ task.abort();+ assert!(task.await.unwrap_err().is_cancelled());+ assert!(scope.cancellation().is_cancelled());+ assert!(!scope.is_committed());+ }++ #[tokio::test]+ async fn windows_startup_success_commits_the_actual_pipeline() {+ let scope = PipelineBuildScope::new();+ let probe = Probe::new(FailureStage::None, &scope);+ let directory = tempfile::tempdir().unwrap();+ let pipeline = finish_windows_pipeline_startup(+ &scope,+ OutputPipeline::builder(directory.path().join("unused.mp4"))+ .with_video::<Video>(probe.clone())+ .build::<Encoder>(probe.clone()),+ )+ .await+ .unwrap();+ assert!(scope.is_committed());+ probe.cancel.cancel();+ pipeline.stop().await.unwrap();+ assert_eq!(probe.alive.load(Ordering::Acquire), 0);+ assert_eq!(probe.stopped.load(Ordering::Acquire), 1);+ }++ #[tokio::test]+ async fn windows_failed_startup_does_not_finish_before_held_cleanup() {+ let scope = PipelineBuildScope::new();+ let (release, hold) = oneshot::channel();+ let (entered, ready) = oneshot::channel();+ let scoped = scope.clone();+ let task = tokio::spawn(async move {+ finish_windows_pipeline_startup(&scoped, async {+ let completion = PipelineBuildScope::current().unwrap().task_completion();+ tokio::spawn(async move {+ let _completion = completion;+ let _ = entered.send(());+ let _ = hold.await;+ });+ Err::<(), _>(anyhow!("StartCapture failed"))+ })+ .await+ });+ ready.await.unwrap();+ assert!(!task.is_finished());+ release.send(()).unwrap();+ let error = task.await.unwrap().unwrap_err();+ assert!(format!("{error:#}").contains("StartCapture failed"));+ }++ #[tokio::test]+ async fn windows_pipeline_failure_before_actor_return_cannot_commit() {+ let scope = PipelineBuildScope::new();+ let token = CancellationToken::new();+ scope.register_token(token.clone());+ let result = finish_windows_pipeline_startup(&scope, async {+ token.cancel();+ Ok(())+ })+ .await;+ assert!(result.is_err());+ assert!(!scope.is_committed());+ }++ #[tokio::test]+ async fn windows_cancelled_startup_never_commits_success() {+ let scope = PipelineBuildScope::new();+ scope.cancel();+ assert!(+ finish_windows_pipeline_startup(&scope, async { Ok(()) })+ .await+ .is_err()+ );+ assert!(!scope.is_committed());+ }++ #[tokio::test]+ async fn failed_build_stages_join_owned_tasks_and_stop_prepared_sources() {+ for (stage, stops) in [+ (FailureStage::VideoSetup, 0),+ (FailureStage::AudioSetup, 1),+ (FailureStage::AudioStart, 2),+ (FailureStage::MuxerSetup, 2),+ (FailureStage::VideoStart, 2),+ ] {+ let scope = PipelineBuildScope::new();+ let probe = Probe::new(stage, &scope);+ let directory = tempfile::tempdir().unwrap();+ let built = scope+ .run(+ OutputPipeline::builder(directory.path().join("unused.mp4"))+ .with_video::<Video>(probe.clone())+ .with_audio_source::<Audio>(probe.clone())+ .build::<Encoder>(probe.clone()),+ )+ .await;+ assert!(built.is_err());+ tokio::time::timeout(Duration::from_secs(2), scope.cancel_and_join())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(probe.alive.load(Ordering::Acquire), 0);+ assert_eq!(probe.stopped.load(Ordering::Acquire), stops);+ if stage == FailureStage::VideoStart {+ assert_eq!(probe.finished.load(Ordering::Acquire), 1);+ }+ }+ }++ #[tokio::test]+ async fn later_track_failure_joins_already_built_capture_and_finalization() {+ let scope = PipelineBuildScope::new();+ let probe = Probe::new(FailureStage::None, &scope);+ let directory = tempfile::tempdir().unwrap();+ let built = scope+ .run(+ OutputPipeline::builder(directory.path().join("unused.mp4"))+ .with_video::<Video>(probe.clone())+ .with_audio_source::<Audio>(probe.clone())+ .build::<Encoder>(probe.clone()),+ )+ .await+ .unwrap();+ drop(built);+ tokio::time::timeout(Duration::from_secs(2), scope.cancel_and_join())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(probe.alive.load(Ordering::Acquire), 0);+ assert_eq!(probe.stopped.load(Ordering::Acquire), 2);+ assert_eq!(probe.finished.load(Ordering::Acquire), 1);+ }++ #[tokio::test]+ async fn cancellation_waits_for_actual_native_thread_exit() {+ let scope = PipelineBuildScope::new();+ let (release, wait) = std::sync::mpsc::channel();+ let exited = Arc::new(AtomicBool::new(false));+ scope+ .run(async {+ let mut tasks = TaskPool::default();+ let exited = exited.clone();+ tasks.spawn_thread("owned-native-setup", move || {+ wait.recv().unwrap();+ exited.store(true, Ordering::Release);+ Ok(())+ });+ drop(tasks);+ })+ .await;+ let cleanup = scope.cancel_and_join();+ tokio::pin!(cleanup);+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut cleanup)+ .await+ .is_err()+ );+ assert!(!exited.load(Ordering::Acquire));+ release.send(()).unwrap();+ tokio::time::timeout(Duration::from_secs(2), cleanup)+ .await+ .unwrap()+ .unwrap();+ assert!(exited.load(Ordering::Acquire));+ }++ #[tokio::test]+ async fn cleanup_errors_cannot_report_quiescent_success() {+ let scope = PipelineBuildScope::new();+ scope.spawn_cleanup(async { Err(anyhow!("native stop refused")) });+ assert!(+ scope+ .cancel_and_join()+ .await+ .unwrap_err()+ .contains("native stop refused")+ );+ }++ #[tokio::test]+ async fn task_error_does_not_detach_other_owned_cleanup() {+ let scope = PipelineBuildScope::new();+ let (release, wait) = std::sync::mpsc::channel();+ scope+ .run(async {+ let mut tasks = TaskPool::default();+ tasks.spawn("failure", async { Err(anyhow!("setup fault")) });+ tasks.spawn_thread("slow-cleanup", move || {+ wait.recv().unwrap();+ Ok(())+ });+ drop(tasks);+ })+ .await;+ let cleanup = scope.cancel_and_join();+ tokio::pin!(cleanup);+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut cleanup)+ .await+ .is_err()+ );+ release.send(()).unwrap();+ tokio::time::timeout(Duration::from_secs(2), cleanup)+ .await+ .unwrap()+ .unwrap();+ }+ #[tokio::test]+ async fn cancelled_build_drops_prepared_sources_and_joins_partial_muxer_work() {+ let scope = PipelineBuildScope::new();+ let probe = Probe::new(FailureStage::MuxerPending, &scope);+ let directory = tempfile::tempdir().unwrap();+ let mut build = Box::pin(+ scope.run(+ OutputPipeline::builder(directory.path().join("discarded.mp4"))+ .with_video::<Video>(probe.clone())+ .with_audio_source::<Audio>(probe.clone())+ .build::<Encoder>(probe.clone()),+ ),+ );+ tokio::select! {+ _ = probe.setup_pending.notified() => {},+ _ = &mut build => panic!("Muxer should remain pending"),+ }+ drop(build);+ tokio::time::timeout(Duration::from_secs(2), scope.cancel_and_join())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(probe.alive.load(Ordering::Acquire), 0);+ assert_eq!(probe.stopped.load(Ordering::Acquire), 2);+ assert_eq!(probe.finished.load(Ordering::Acquire), 0);+ }++ #[tokio::test]+ async fn committed_scope_ignores_late_waiter_cancellation() {+ let scope = PipelineBuildScope::new();+ let native_stop = CancellationToken::new();+ scope.register_token(native_stop.clone());+ assert!(scope.commit());+ scope.cancel();+ assert!(!native_stop.is_cancelled());+ assert!(!scope.cancellation().is_cancelled());+ let cancelled = PipelineBuildScope::new();+ cancelled.cancel();+ assert!(!cancelled.commit());+ }++ #[tokio::test]+ async fn scoped_child_registration_is_joined_after_parent_exits() {+ let scope = PipelineBuildScope::new();+ let child_started = Arc::new(tokio::sync::Notify::new());+ let child_release = Arc::new(tokio::sync::Notify::new());+ scope+ .run(async {+ let child_started = child_started.clone();+ let child_release = child_release.clone();+ drop(spawn_capture_task(async move {+ drop(spawn_capture_task(async move {+ child_started.notify_one();+ child_release.notified().await;+ }));+ }));+ })+ .await;+ child_started.notified().await;+ let joining = scope.cancel_and_join();+ tokio::pin!(joining);+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut joining)+ .await+ .is_err()+ );+ child_release.notify_one();+ tokio::time::timeout(Duration::from_secs(2), joining)+ .await+ .unwrap()+ .unwrap();+ }+}++#[cfg(test)]+mod lifetime_scope_tests {+ use super::*;++ #[test]+ fn healthy_stop_remains_eligible_for_audio_tail_padding() {+ let scope = PipelineBuildScope::new_lifetime();+ scope.cancel();+ assert!(!scope.has_recorded_error());+ }++ #[test]+ fn required_source_failure_disallows_audio_tail_padding() {+ let scope = PipelineBuildScope::new_lifetime();+ scope.fail_required("Requested microphone ended".into());+ assert!(scope.cancellation().is_cancelled());+ assert!(scope.has_recorded_error());+ }++ #[test]+ fn uncertain_cleanup_disallows_audio_tail_padding() {+ let scope = PipelineBuildScope::new_lifetime();+ scope.record_cleanup_error("Source completion missing".into());+ assert!(scope.has_recorded_error());+ }++ #[tokio::test]+ async fn interrupted_join_keeps_actual_work_registered_for_next_waiter() {+ let scope = PipelineBuildScope::new_lifetime();+ let completion = scope.task_completion();+ let first_scope = scope.clone();+ let first = tokio::spawn(async move { first_scope.cancel_and_join_report().await });+ tokio::task::yield_now().await;+ first.abort();+ assert!(first.await.unwrap_err().is_cancelled());+ let joining = scope.cancel_and_join_report();+ tokio::pin!(joining);+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut joining)+ .await+ .is_err()+ );+ drop(completion);+ let report = joining.await;+ assert!(report.quiescent);+ assert!(report.error.is_none());+ }++ #[tokio::test]+ async fn concurrent_joiners_cannot_consume_each_others_acknowledgements() {+ let scope = PipelineBuildScope::new_lifetime();+ let completion = scope.task_completion();+ let joining = async {+ tokio::join!(+ scope.cancel_and_join_report(),+ scope.cancel_and_join_report()+ )+ };+ tokio::pin!(joining);+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut joining)+ .await+ .is_err()+ );+ drop(completion);+ let (first, second) = joining.await;+ assert!(first.quiescent && second.quiescent);+ }++ #[tokio::test]+ async fn lifetime_registry_prunes_completed_generations() {+ let scope = PipelineBuildScope::new_lifetime();+ for _ in 0..1024 {+ drop(scope.task_completion());+ }+ assert_eq!(scope.0.completions.lock().unwrap().len(), 1);+ assert!(scope.cancel_and_join_report().await.quiescent);+ assert!(scope.0.completions.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn lost_acknowledgement_is_unconfirmed_but_joined_finalization_error_is_not() {+ let scope = PipelineBuildScope::new_lifetime();+ let mut completion = scope.task_completion();+ drop(completion.sender.take());+ drop(completion);+ let report = scope.cancel_and_join_report().await;+ assert!(!report.quiescent);+ assert!(report.error.unwrap().contains("lost its completion"));++ let joined = PipelineBuildScope::new_lifetime();+ joined.record_finalization_error("encoder finish failed".into());+ let report = joined.cancel_and_join_report().await;+ assert!(report.quiescent);+ assert!(report.error.unwrap().contains("encoder finish failed"));++ let studio = PipelineBuildScope::new();+ studio.record_finalization_error("encoder finish failed".into());+ assert!(!studio.cancel_and_join_report().await.quiescent);+ }++ struct BlockingFinalizer {+ release: std::sync::mpsc::Receiver<()>,+ started: Option<oneshot::Sender<()>>,+ }+ impl Muxer for BlockingFinalizer {+ type Config = Self;+ async fn setup(+ config: Self::Config,+ _: PathBuf,+ _: Option<VideoInfo>,+ _: Option<AudioInfo>,+ _: Arc<AtomicBool>,+ _: &mut TaskPool,+ ) -> anyhow::Result<Self> {+ Ok(config)+ }+ fn finish(&mut self, _: Duration) -> anyhow::Result<anyhow::Result<()>> {+ self.started.take().unwrap().send(()).unwrap();+ self.release.recv().unwrap();+ Ok(Ok(()))+ }+ }++ #[tokio::test]+ async fn aborted_finalizer_waiter_does_not_acknowledge_running_blocking_body() {+ let scope = PipelineBuildScope::new_lifetime();+ let (release, blocked) = std::sync::mpsc::channel();+ let (started, entered) = oneshot::channel();+ let muxer = Arc::new(futures::lock::Mutex::new(BlockingFinalizer {+ release: blocked,+ started: Some(started),+ }));+ let worker_scope = scope.clone();+ let waiter = tokio::spawn(async move {+ finish_muxer_owned(muxer.lock_owned().await, Duration::ZERO, &worker_scope).await+ });+ entered.await.unwrap();+ assert_eq!(scope.0.completions.lock().unwrap().len(), 1);+ waiter.abort();+ assert!(waiter.await.unwrap_err().is_cancelled());+ let joining = scope.cancel_and_join_report();+ tokio::pin!(joining);+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut joining)+ .await+ .is_err()+ );+ release.send(()).unwrap();+ assert!(joining.await.quiescent);+ }+}++#[cfg(all(test, target_os = "linux"))]+mod studio_parent_lifetime_tests {+ use super::*;++ #[test]+ fn committed_source_failure_disallows_sibling_audio_tail_padding() {+ let parent = PipelineBuildScope::new_lifetime();+ let source = parent.child_transaction();+ let sibling = parent.child_transaction();+ assert!(source.commit());+ assert!(sibling.commit());+ source.fail_required("Requested microphone ended".into());+ assert!(source.has_recorded_error());+ assert!(parent.has_recorded_error());+ assert!(sibling.has_recorded_error());+ }++ #[test]+ fn discarded_transaction_does_not_disable_healthy_parent_audio_padding() {+ let parent = PipelineBuildScope::new_lifetime();+ let discarded = parent.child_transaction();+ discarded.record_finalization_error("Abandoned setup failed".into());+ discarded.cancel();+ assert!(discarded.has_recorded_error());+ assert!(!parent.has_recorded_error());+ }++ #[tokio::test]+ async fn committed_transaction_keeps_actual_writer_owned_by_parent() {+ let parent = PipelineBuildScope::new_lifetime();+ let child = parent.child_transaction();+ let (started_tx, started_rx) = oneshot::channel();+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();+ child+ .run(async {+ let mut tasks = TaskPool::default();+ tasks.spawn_thread("studio-test-writer", move || {+ let _ = started_tx.send(());+ release_rx.blocking_recv().map_err(anyhow::Error::from)?;+ Ok(())+ });+ })+ .await;+ started_rx.await.unwrap();+ assert!(child.commit());+ let joining = tokio::spawn({+ let parent = parent.clone();+ async move { parent.cancel_and_join_report().await }+ });+ tokio::task::yield_now().await;+ assert!(!joining.is_finished());+ release_tx.send(()).unwrap();+ assert!(joining.await.unwrap().quiescent);+ }++ #[tokio::test]+ async fn committed_transaction_tokens_still_receive_parent_stop() {+ let parent = PipelineBuildScope::new_lifetime();+ let child = parent.child_transaction();+ let token = CancellationToken::new();+ child.register_token(token.clone());+ assert!(child.commit());+ child.cancel();+ assert!(!token.is_cancelled());+ parent.cancel();+ assert!(token.is_cancelled());+ }++ #[tokio::test]+ async fn discarded_transaction_does_not_cancel_healthy_parent() {+ let parent = PipelineBuildScope::new_lifetime();+ let child = parent.child_transaction();+ child.cancel();+ assert!(!parent.cancellation().is_cancelled());+ assert!(child.cancel_and_join_report().await.quiescent);+ }++ #[tokio::test]+ async fn caught_cleanup_failure_after_commit_remains_parent_uncertainty() {+ let parent = PipelineBuildScope::new_lifetime();+ let child = parent.child_transaction();+ assert!(child.commit());+ child.spawn_cleanup(async { Err(anyhow!("native source stop failed")) });+ let report = parent.cancel_and_join_report().await;+ assert!(!report.quiescent);+ assert!(report.error.unwrap().contains("native source stop failed"));+ }++ #[tokio::test]+ async fn panic_in_committed_child_is_not_a_joined_parent_acknowledgement() {+ let parent = PipelineBuildScope::new_lifetime();+ let child = parent.child_transaction();+ let completion = child.task_completion();+ assert!(child.commit());+ let task = tokio::spawn(async move {+ let _completion = completion;+ panic!("owned writer panic");+ });+ assert!(task.await.is_err());+ let report = parent.cancel_and_join_report().await;+ assert!(!report.quiescent);+ assert!(report.error.is_some());}}diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rsindex f2527586e..f9d05d212 100644--- a/crates/recording/src/output_pipeline/ffmpeg.rs+++ b/crates/recording/src/output_pipeline/ffmpeg.rs@@ -1,7 +1,8 @@use crate::{SharedPauseState, TaskPool,output_pipeline::{- AudioFrame, AudioMuxer, Muxer, VideoFrame, VideoMuxer, frame_timing_log_threshold_ms,+ AudioFrame, AudioMuxer, Muxer, STALL_BUDGET_MS, VideoFrame, VideoMuxer,+ frame_timing_log_threshold_ms,},};use anyhow::{Context, anyhow};@@ -19,11 +20,7 @@ use cap_media_info::{AudioInfo, VideoInfo};use cap_timestamp::Timestamp;use std::{path::PathBuf,- sync::{- Arc, Mutex,- atomic::AtomicBool,- mpsc::{SyncSender, sync_channel},- },+ sync::{Arc, Mutex, atomic::AtomicBool, mpsc::sync_channel},thread::JoinHandle,time::Duration,};@@ -411,8 +408,23 @@ impl FrameDropTracker {}}+fn send_segmented_frame<T>(+ sender: &flume::Sender<T>,+ frame: T,+ frame_drops: &mut FrameDropTracker,+) -> anyhow::Result<()> {+ match sender.send_timeout(frame, Duration::from_millis(STALL_BUDGET_MS)) {+ Ok(()) => frame_drops.record_frame(),+ Err(flume::SendTimeoutError::Timeout(_)) => frame_drops.record_drop(),+ Err(flume::SendTimeoutError::Disconnected(_)) => {+ return Err(anyhow!("Segmented encoder channel disconnected"));+ }+ }+ Ok(())+}+struct SegmentedEncoderState {- video_tx: SyncSender<Option<(ffmpeg::frame::Video, Duration)>>,+ video_tx: flume::Sender<Option<(ffmpeg::frame::Video, Duration)>>,encoder: Arc<Mutex<SegmentedVideoEncoder>>,encoder_handle: Option<JoinHandle<anyhow::Result<()>>>,}@@ -428,6 +440,7 @@ pub struct SegmentedVideoMuxer {pause: SharedPauseState,frame_drops: FrameDropTracker,started: bool,+ strict_finish: bool,}pub struct SegmentedVideoMuxerConfig {@@ -485,10 +498,18 @@ impl Muxer for SegmentedVideoMuxer {pause,frame_drops: FrameDropTracker::new(),started: false,+ strict_finish: super::core::PipelineBuildScope::current()+ .is_some_and(|scope| scope.requires_joined_stop()),})}fn stop(&mut self) {+ if self.strict_finish {+ if let Some(state) = &self.state {+ let _ = state.video_tx.try_send(None);+ }+ return;+ }if let Some(state) = &self.state&& let Err(e) = state.video_tx.send(None){@@ -497,6 +518,9 @@ impl Muxer for SegmentedVideoMuxer {}fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ if self.strict_finish {+ return Ok(self.finish_joined(timestamp));+ }if let Some(mut state) = self.state.take() {if let Err(e) = state.video_tx.send(None) {trace!("Segmented encoder channel already closed during finish: {e}");@@ -576,7 +600,37 @@ impl Muxer for SegmentedVideoMuxer {}}+fn join_segmented_encoder(handle: Option<JoinHandle<anyhow::Result<()>>>) -> anyhow::Result<()> {+ match handle {+ Some(handle) => handle+ .join()+ .unwrap_or_else(|_| Err(anyhow!("Segmented encoder thread panicked"))),+ None => Ok(()),+ }+}+impl SegmentedVideoMuxer {+ fn finish_joined(&mut self, timestamp: Duration) -> anyhow::Result<()> {+ let Some(mut state) = self.state.take() else {+ return Ok(());+ };+ let _ = state.video_tx.send(None);+ let thread_error = join_segmented_encoder(state.encoder_handle.take()).err();+ let finish_error = match state.encoder.lock() {+ Ok(mut encoder) => encoder+ .finish_with_timestamp(timestamp)+ .map_err(anyhow::Error::from)+ .err(),+ Err(_) => Some(anyhow!("Segmented encoder state is poisoned")),+ };+ self.frame_drops.report_final_stats();+ match (thread_error, finish_error) {+ (None, None) => Ok(()),+ (Some(error), None) | (None, Some(error)) => Err(error),+ (Some(worker), Some(finish)) => Err(anyhow!("{worker:#}; finalization: {finish:#}")),+ }+ }+fn start_encoder(&mut self) -> anyhow::Result<()> {let buffer_size = get_muxer_buffer_size();debug!(@@ -585,7 +639,7 @@ impl SegmentedVideoMuxer {);let (video_tx, video_rx) =- sync_channel::<Option<(ffmpeg::frame::Video, Duration)>>(buffer_size);+ flume::bounded::<Option<(ffmpeg::frame::Video, Duration)>>(buffer_size);let (ready_tx, ready_rx) = sync_channel::<anyhow::Result<()>>(1);let encoder_config = SegmentedVideoEncoderConfig {@@ -605,72 +659,84 @@ impl SegmentedVideoMuxer {let encoder = Arc::new(Mutex::new(encoder));let encoder_clone = encoder.clone();+ let strict_scope =+ super::core::PipelineBuildScope::current().filter(|scope| scope.requires_joined_stop());+ let build_completion =+ super::core::PipelineBuildScope::current().map(|scope| scope.task_completion());let encoder_handle = std::thread::Builder::new().name("segmented-video-encoder".to_string()).spawn(move || {- if ready_tx.send(Ok(())).is_err() {- return Err(anyhow!("Failed to send ready signal - receiver dropped"));- }+ let _build_completion = build_completion;+ (move || {+ if ready_tx.send(Ok(())).is_err() {+ return Err(anyhow!("Failed to send ready signal - receiver dropped"));+ }++ let mut slow_encode_count = 0u32;+ let mut encode_error_count = 0u32;+ let mut total_frames = 0u64;++ while let Ok(Some((frame, timestamp))) = video_rx.recv() {+ let encode_start = std::time::Instant::now();- let mut slow_encode_count = 0u32;- let mut encode_error_count = 0u32;- let mut total_frames = 0u64;-- while let Ok(Some((frame, timestamp))) = video_rx.recv() {- let encode_start = std::time::Instant::now();-- if let Ok(mut encoder) = encoder_clone.lock()- && let Err(e) = encoder.queue_frame(frame, timestamp)- {- encode_error_count += 1;- if encode_error_count <= 3 {- warn!("Failed to encode frame: {e}");- } else if encode_error_count == 4 {- warn!("Suppressing further encode errors (too many failures)");+ if let Ok(mut encoder) = encoder_clone.lock()+ && let Err(e) = encoder.queue_frame(frame, timestamp)+ {+ if let Some(scope) = &strict_scope {+ scope+ .fail_required(format!("Segmented video encoding failed: {e}"));+ return Err(anyhow!("Segmented video encoding failed: {e}"));+ }+ encode_error_count += 1;+ if encode_error_count <= 3 {+ warn!("Failed to encode frame: {e}");+ } else if encode_error_count == 4 {+ warn!("Suppressing further encode errors (too many failures)");+ }}- }- let encode_elapsed_ms = encode_start.elapsed().as_millis();-- if encode_elapsed_ms > slow_threshold_ms {- slow_encode_count += 1;- if slow_encode_count <= 5 || slow_encode_count.is_multiple_of(100) {- debug!(- elapsed_ms = encode_elapsed_ms,- count = slow_encode_count,- "encoder.queue_frame exceeded {}ms threshold",- slow_threshold_ms- );+ let encode_elapsed_ms = encode_start.elapsed().as_millis();++ if encode_elapsed_ms > slow_threshold_ms {+ slow_encode_count += 1;+ if slow_encode_count <= 5 || slow_encode_count.is_multiple_of(100) {+ debug!(+ elapsed_ms = encode_elapsed_ms,+ count = slow_encode_count,+ "encoder.queue_frame exceeded {}ms threshold",+ slow_threshold_ms+ );+ }}- }- total_frames += 1;- }+ total_frames += 1;+ }- if total_frames > 0 {- debug!(- total_frames = total_frames,- slow_encodes = slow_encode_count,- encode_errors = encode_error_count,- slow_encode_pct = format!(- "{:.1}%",- 100.0 * slow_encode_count as f64 / total_frames as f64- ),- "Segmented encoder timing summary"- );- }+ if total_frames > 0 {+ debug!(+ total_frames = total_frames,+ slow_encodes = slow_encode_count,+ encode_errors = encode_error_count,+ slow_encode_pct = format!(+ "{:.1}%",+ 100.0 * slow_encode_count as f64 / total_frames as f64+ ),+ "Segmented encoder timing summary"+ );+ }- if encode_error_count > 0 {- warn!(- encode_errors = encode_error_count,- total_frames = total_frames,- "Encoder finished with {} encode errors out of {} frames",- encode_error_count,- total_frames- );- }+ if encode_error_count > 0 {+ warn!(+ encode_errors = encode_error_count,+ total_frames = total_frames,+ "Encoder finished with {} encode errors out of {} frames",+ encode_error_count,+ total_frames+ );+ }- Ok(())+ Ok(())+ })()})?;ready_rx@@ -711,22 +777,11 @@ impl VideoMuxer for SegmentedVideoMuxer {}if let Some(state) = &self.state {- match state- .video_tx- .try_send(Some((frame.inner, adjusted_timestamp)))- {- Ok(()) => {- self.frame_drops.record_frame();- }- Err(e) => match e {- std::sync::mpsc::TrySendError::Full(_) => {- self.frame_drops.record_drop();- }- std::sync::mpsc::TrySendError::Disconnected(_) => {- trace!("Segmented encoder channel disconnected");- }- },- }+ send_segmented_frame(+ &state.video_tx,+ Some((frame.inner, adjusted_timestamp)),+ &mut self.frame_drops,+ )?;}Ok(())@@ -823,10 +878,54 @@ impl AudioMuxer for DashSegmentedAudioMuxer {#[cfg(test)]mod tests {- use super::{FFmpegVideoFrame, VideoFrame};+ use super::{FFmpegVideoFrame, FrameDropTracker, VideoFrame, send_segmented_frame};use cap_timestamp::Timestamp;use std::time::Instant;+ #[test]+ fn segmented_encoder_preserves_frames_when_a_full_queue_recovers() {+ let (sender, receiver) = flume::bounded(1);+ sender.send(1).unwrap();+ let consumer = std::thread::spawn(move || {+ std::thread::sleep(std::time::Duration::from_millis(10));+ assert_eq!(receiver.recv().unwrap(), 1);+ receiver.recv_timeout(std::time::Duration::from_millis(200))+ });+ let mut drops = FrameDropTracker::new();++ send_segmented_frame(&sender, 2, &mut drops).unwrap();++ assert_eq!(consumer.join().unwrap().unwrap(), 2);+ assert_eq!(drops.total_frames, 1);+ assert_eq!(drops.total_drops, 0);+ }++ #[test]+ fn segmented_encoder_bounds_waiting_for_a_stalled_queue() {+ let (sender, _receiver) = flume::bounded(1);+ sender.send(1).unwrap();+ let mut drops = FrameDropTracker::new();+ let started = std::time::Instant::now();++ send_segmented_frame(&sender, 2, &mut drops).unwrap();++ assert!(started.elapsed() >= std::time::Duration::from_millis(50));+ assert!(started.elapsed() < std::time::Duration::from_secs(1));+ assert_eq!(drops.total_frames, 0);+ assert_eq!(drops.total_drops, 1);+ }++ #[test]+ fn segmented_encoder_reports_disconnected_queue() {+ let (sender, receiver) = flume::bounded(1);+ drop(receiver);+ let mut drops = FrameDropTracker::new();++ assert!(send_segmented_frame(&sender, 2, &mut drops).is_err());+ assert_eq!(drops.total_frames, 0);+ assert_eq!(drops.total_drops, 0);+ }+#[test]fn duplicated_video_frame_reuses_reference_counted_pixel_storage() {let timestamp = Instant::now();@@ -859,4 +958,39 @@ mod tests {let retained = unsafe { (*duplicate.inner.as_ptr()).buf[0] };assert_eq!(unsafe { ffmpeg::ffi::av_buffer_get_ref_count(retained) }, 1);}+ #[tokio::test]+ async fn strict_encoder_join_waits_for_actual_thread_without_blocking_runtime() {+ let (release, blocked) = std::sync::mpsc::channel();+ let thread = std::thread::spawn(move || {+ blocked.recv().unwrap();+ Err(anyhow::anyhow!("encoder queue failed"))+ });+ let mut joining =+ tokio::task::spawn_blocking(move || super::join_segmented_encoder(Some(thread)));+ assert!(+ tokio::time::timeout(std::time::Duration::from_millis(20), &mut joining)+ .await+ .is_err()+ );+ release.send(()).unwrap();+ assert!(+ joining+ .await+ .unwrap()+ .unwrap_err()+ .to_string()+ .contains("encoder queue failed")+ );+ }++ #[test]+ fn strict_encoder_join_retains_thread_panic() {+ let thread = std::thread::spawn(|| -> anyhow::Result<()> { panic!("encoder fault") });+ assert!(+ super::join_segmented_encoder(Some(thread))+ .unwrap_err()+ .to_string()+ .contains("panicked")+ );+ }}diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rsindex 60e92c15d..a84db12b3 100644--- a/crates/recording/src/recovery.rs+++ b/crates/recording/src/recovery.rs@@ -77,13 +77,6 @@ impl RecoveryPurpose {Self::Finalize => "Created project configuration with timeline for finalized recording",}}-- fn track_action(self) -> &'static str {- match self {- Self::Recover => "recovery",- Self::Finalize => "finalization",- }- }}#[derive(Debug, thiserror::Error)]@@ -102,6 +95,10 @@ pub enum RecoveryError {NoRecoverableSegments,#[error("Meta save failed")]MetaSave,+ #[error("Requested recording track failed; partial media preserved: {0}")]+ RequiredTrackFailure(String),+ #[error("Recovery validation failed; original recording preserved: {0}")]+ Validation(String),#[error("Recovered video is not playable: {0}")]UnplayableVideo(String),}@@ -111,11 +108,46 @@ pub struct RecoveryManager;const EXPORT_SEEK_PROBE_SAMPLE_COUNT: usize = 8;impl RecoveryManager {+ fn require_no_track_failure(project_path: &Path) -> Result<(), RecoveryError> {+ if let Ok(meta) = RecordingMeta::load_for_project(project_path)+ && let Some(studio) = meta.studio_meta()+ && let StudioRecordingStatus::Failed { error } = studio.status()+ {+ return Err(RecoveryError::RequiredTrackFailure(error));+ }+ let path = project_path.join("recording-diagnostics.json");+ let raw = match std::fs::read(&path) {+ Ok(raw) => raw,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error.into()),+ };+ let diagnostics: serde_json::Value = serde_json::from_slice(&raw)?;+ let failed = diagnostics+ .get("segments")+ .and_then(serde_json::Value::as_array)+ .is_none_or(|segments| {+ segments.iter().any(|segment| {+ segment+ .get("trackFailures")+ .and_then(serde_json::Value::as_array)+ .is_none_or(|failures| !failures.is_empty())+ })+ });+ if failed {+ return Err(RecoveryError::RequiredTrackFailure(+ "recording diagnostics retain a required-track failure".into(),+ ));+ }+ Ok(())+ }+pub fn inspect_recording(project_path: &Path) -> Option<IncompleteRecording> {if !project_path.is_dir() {return None;}+ let _lock = RecoveryLock::acquire(project_path).ok()?;+if !project_path.join("recording-meta.json").exists() {return None;}@@ -130,6 +162,8 @@ impl RecoveryManager {return None;}+ let _lock = RecoveryLock::acquire(project_path).ok()?;+if !project_path.join("recording-meta.json").exists() {return None;}@@ -146,7 +180,19 @@ impl RecoveryManager {}pub fn remux_if_needed(project_path: &Path) -> Result<bool, RecoveryError> {- let Some(incomplete) = Self::find_incomplete_single(project_path) else {+ if !project_path.is_dir() {+ return Ok(false);+ }+ let incomplete = {+ let _lock = RecoveryLock::acquire(project_path)?;+ let Ok(meta) = RecordingMeta::load_for_project(project_path) else {+ return Ok(false);+ };+ meta.studio_meta()+ .filter(|studio| Self::should_check_for_recovery(&studio.status()))+ .and_then(|_| Self::analyze_incomplete(project_path, &meta))+ };+ let Some(incomplete) = incomplete else {return Ok(false);};@@ -175,6 +221,10 @@ impl RecoveryManager {continue;}+ let Ok(_lock) = RecoveryLock::acquire(&path) else {+ continue;+ };+let Ok(meta) = RecordingMeta::load_for_project(&path) else {continue;};@@ -356,7 +406,7 @@ impl RecoveryManager {let init_segment = manifest.get("init_segment").and_then(|i| i.as_str())- .map(|name| dir.join(name))+ .and_then(|name| recovery_child_path(dir, name)).filter(|p| p.exists());manifest_init_segment = init_segment.clone();@@ -380,7 +430,7 @@ impl RecoveryManager {}).filter_map(|f| {let path_str = f.get("path").and_then(|p| p.as_str())?;- let path = dir.join(path_str);+ let path = recovery_child_path(dir, path_str)?;if !path.exists() {return None;}@@ -443,7 +493,7 @@ impl RecoveryManager {let listed: std::collections::HashSet<_> = entries.iter().filter_map(|entry| entry.get("path").and_then(|path| path.as_str()))- .map(|path| dir.join(path))+ .filter_map(|path| recovery_child_path(dir, path)).collect();result.extend(Self::probe_m4s_fragments_with_init(dir).into_iter().filter(|path| {@@ -836,6 +886,208 @@ impl RecoveryManager {recording: &IncompleteRecording,purpose: RecoveryPurpose,) -> Result<RecoveredRecording, RecoveryError> {+ Self::require_no_track_failure(&recording.project_path)?;+ let project = &recording.project_path;+ let _lock = RecoveryLock::acquire(project)?;+ let before = recovery_snapshot(project)?;+ let current = RecordingMeta::load_for_project(project)+ .map_err(|error| RecoveryError::Validation(error.to_string()))?;+ if serde_json::to_value(¤t)? != serde_json::to_value(&recording.meta)? {+ return Err(RecoveryError::Validation(+ "Recording metadata changed".into(),+ ));+ }+ Self::require_recoverable_tracks(recording)?;+ let workspace = project.join(format!(".recovery-{}", uuid::Uuid::new_v4()));+ create_private_recovery_dir(&workspace)?;+ let staged = workspace.join("staged");+ create_private_recovery_dir(&staged)?;+ let prepared = (|| {+ for name in RECOVERY_INPUTS {+ let source = project.join(name);+ if source.try_exists()? {+ copy_recovery_input(&source, &staged.join(name))?;+ }+ }+ if recovery_snapshot(&staged)? != before || recovery_snapshot(project)? != before {+ return Err(RecoveryError::Validation(+ "Recording changed while copying".into(),+ ));+ }+ validate_recovery_manifests(&staged.join("content"))?;+ let staged_meta = RecordingMeta::load_for_project(&staged)+ .map_err(|error| RecoveryError::Validation(error.to_string()))?;+ let staged_recording = Self::analyze_incomplete(&staged, &staged_meta)+ .ok_or(RecoveryError::NoRecoverableSegments)?;+ Self::require_recoverable_tracks(&staged_recording)?;+ Self::require_local_fragments(&staged_recording)?;+ Self::validate_staged_inputs(&staged_recording)?;+ let recovered = Self::finalize_staged(&staged_recording, purpose)?;+ let config = ProjectConfiguration::load(&staged)?;+ config+ .validate()+ .map_err(|error| RecoveryError::Validation(error.to_string()))?;+ let persisted = RecordingMeta::load_for_project(&staged)+ .map_err(|error| RecoveryError::Validation(error.to_string()))?;+ if serde_json::to_value(persisted.studio_meta())?+ != serde_json::to_value(&recovered.meta)?+ {+ return Err(RecoveryError::Validation("Staged metadata mismatch".into()));+ }+ sync_recovery_input(&staged)?;+ Self::require_no_track_failure(project)?;+ if recovery_snapshot(project)? != before {+ return Err(RecoveryError::Validation(+ "Recording changed before publication".into(),+ ));+ }+ Ok(recovered.meta)+ })();+ let meta = match prepared {+ Ok(meta) => meta,+ Err(error) => {+ let _ = std::fs::remove_dir_all(&workspace);+ return Err(error);+ }+ };+ publish_recovery(project, &workspace)?;+ finalization_info!(path = %workspace.display(), "Recovered recording retains original media backup");+ Ok(RecoveredRecording {+ project_path: project.clone(),+ meta,+ })+ }++ fn validate_staged_inputs(recording: &IncompleteRecording) -> Result<(), RecoveryError> {+ for segment in &recording.recoverable_segments {+ validate_recovery_video_inputs(+ &segment.display_fragments,+ segment.display_init_segment.as_deref(),+ &recording.project_path,+ )?;+ let display_dir = recording.project_path.join(format!(+ "content/segments/segment-{}/display",+ segment.index+ ));+ for (_, init, fragments) in Self::collect_respawn_groups(&display_dir, None) {+ validate_recovery_video_inputs(&fragments, Some(&init), &recording.project_path)?;+ }+ if let Some(fragments) = &segment.camera_fragments {+ validate_recovery_video_inputs(+ fragments,+ segment.camera_init_segment.as_deref(),+ &recording.project_path,+ )?;+ }+ for path in segment+ .mic_fragments+ .iter()+ .flatten()+ .chain(segment.system_audio_fragments.iter().flatten())+ {+ validate_recovered_track(path, ffmpeg::media::Type::Audio)?;+ }+ }+ Ok(())+ }++ fn require_local_fragments(recording: &IncompleteRecording) -> Result<(), RecoveryError> {+ let content = recording.project_path.join("content").canonicalize()?;+ for segment in &recording.recoverable_segments {+ for path in segment+ .display_fragments+ .iter()+ .chain(segment.display_init_segment.iter())+ .chain(segment.camera_fragments.iter().flatten())+ .chain(segment.camera_init_segment.iter())+ .chain(segment.mic_fragments.iter().flatten())+ .chain(segment.system_audio_fragments.iter().flatten())+ {+ if !path.canonicalize()?.starts_with(&content) {+ return Err(RecoveryError::Validation(+ "Fragment escapes recording content".into(),+ ));+ }+ }+ }+ Ok(())+ }++ fn require_recoverable_tracks(recording: &IncompleteRecording) -> Result<(), RecoveryError> {+ let Some(StudioRecordingMeta::MultipleSegments { inner }) = recording.meta.studio_meta()+ else {+ return Err(RecoveryError::Validation(+ "Recovery requires segmented Studio metadata".into(),+ ));+ };+ let mut indexes = std::collections::BTreeSet::new();+ for segment in &recording.recoverable_segments {+ if !indexes.insert(segment.index) || segment.display_fragments.is_empty() {+ return Err(RecoveryError::Validation(+ "Missing or duplicate display segment".into(),+ ));+ }+ let original = inner.segments.get(segment.index as usize);+ let dir = recording+ .project_path+ .join(format!("content/segments/segment-{}", segment.index));+ for (name, known, fragments) in [+ (+ "camera",+ original.is_some_and(|s| s.camera.is_some()),+ segment.camera_fragments.as_ref(),+ ),+ (+ "audio-input",+ original.is_some_and(|s| s.mic.is_some()),+ segment.mic_fragments.as_ref(),+ ),+ (+ "system_audio",+ original.is_some_and(|s| s.system_audio.is_some()),+ segment.system_audio_fragments.as_ref(),+ ),+ ] {+ let present = ["", ".mp4", ".m4a", ".ogg", ".mp3"]+ .iter()+ .any(|suffix| dir.join(format!("{name}{suffix}")).exists());+ if (known || present) && fragments.is_none_or(Vec::is_empty) {+ return Err(RecoveryError::Validation(format!(+ "Missing or invalid {name} in segment {}",+ segment.index+ )));+ }+ }+ }+ for index in 0..inner.segments.len() {+ if !indexes.contains(&(index as u32)) {+ return Err(RecoveryError::Validation(format!(+ "Missing display segment {index}"+ )));+ }+ }+ for entry in std::fs::read_dir(recording.project_path.join("content/segments"))? {+ let entry = entry?;+ if let Some(index) = entry+ .file_name()+ .to_str()+ .and_then(|name| name.strip_prefix("segment-"))+ .and_then(|value| value.parse::<u32>().ok())+ && !indexes.contains(&index)+ {+ return Err(RecoveryError::Validation(format!(+ "Unrecoverable display segment {index}"+ )));+ }+ }+ Ok(())+ }++ fn finalize_staged(+ recording: &IncompleteRecording,+ purpose: RecoveryPurpose,+ ) -> Result<RecoveredRecording, RecoveryError> {+ Self::require_no_track_failure(&recording.project_path)?;if recording.recoverable_segments.is_empty() {return Err(RecoveryError::NoRecoverableSegments);}@@ -908,78 +1160,22 @@ impl RecoveryManager {if let Some(camera_frags) = &segment.camera_fragments {let camera_output = segment_dir.join("camera.mp4");- let camera_dir = segment_dir.join("camera");-if camera_frags.len() == 1 && segment.camera_init_segment.is_none() {- let source = &camera_frags[0];- if source != &camera_output {- finalization_info!("Moving single camera fragment to {:?}", camera_output);- std::fs::rename(source, &camera_output)?;- }- match Self::validate_required_video(&camera_output, "camera") {- Ok(()) => {- if camera_dir.exists()- && let Err(e) = std::fs::remove_dir_all(&camera_dir)- {- debug!("Failed to clean up camera dir {:?}: {e}", camera_dir);- }- }- Err(e) => {- warn!(- "Camera video validation failed for {:?}: {}",- camera_output, e- );- if let Err(remove_err) = std::fs::remove_file(&camera_output) {- debug!(- "Failed to remove invalid camera video {:?}: {remove_err}",- camera_output- );- }- }+ if camera_frags[0] != camera_output {+ std::fs::rename(&camera_frags[0], &camera_output)?;}- } else if !camera_frags.is_empty() {- let camera_ok = match Self::finalize_fragments_to_progressive_mp4(+ Self::validate_required_video(&camera_output, "camera")?;+ } else {+ Self::finalize_fragments_to_progressive_mp4(camera_frags,segment.camera_init_segment.as_deref(),&camera_output,"camera",- ) {- Ok(()) => true,- Err(err) => {- warn!(- "Camera track {} failed for {:?}: {err}. Preserving fragments for retry.",- purpose.track_action(),- camera_output- );- if let Err(e) = std::fs::remove_file(&camera_output)- && e.kind() != std::io::ErrorKind::NotFound- {- debug!(- "Failed to remove invalid camera output {:?}: {e}",- camera_output- );- }- false- }- };-- if camera_ok {- for fragment in camera_frags {- if let Err(e) = std::fs::remove_file(fragment) {- debug!("Failed to remove camera fragment {:?}: {e}", fragment);- }- }- if let Some(init_path) = &segment.camera_init_segment- && let Err(e) = std::fs::remove_file(init_path)- {- debug!("Failed to remove camera init segment {:?}: {e}", init_path);- }- if camera_dir.exists()- && let Err(e) = std::fs::remove_dir_all(&camera_dir)- {- debug!("Failed to clean up camera dir {:?}: {e}", camera_dir);- }- }+ )?;+ }+ let camera_dir = segment_dir.join("camera");+ if camera_dir.exists() {+ std::fs::remove_dir_all(camera_dir)?;}}@@ -1087,6 +1283,33 @@ impl RecoveryManager {}}+ for segment in &recording.recoverable_segments {+ let dir = recording+ .project_path+ .join(format!("content/segments/segment-{}", segment.index));+ validate_recovered_track(&dir.join("display.mp4"), ffmpeg::media::Type::Video)?;+ for (fragments, name, kind) in [+ (+ segment.camera_fragments.as_ref(),+ "camera.mp4",+ ffmpeg::media::Type::Video,+ ),+ (+ segment.mic_fragments.as_ref(),+ "audio-input.ogg",+ ffmpeg::media::Type::Audio,+ ),+ (+ segment.system_audio_fragments.as_ref(),+ "system_audio.ogg",+ ffmpeg::media::Type::Audio,+ ),+ ] {+ if fragments.is_some() {+ validate_recovered_track(&dir.join(name), kind)?;+ }+ }+ }let meta = Self::build_recovered_meta(recording)?;let mut recording_meta = recording.meta.clone();@@ -1120,6 +1343,122 @@ impl RecoveryManager {display_dir: &Path,audio_dir: &Path,output: &Path,+ ) -> Result<PathBuf, RecoveryError> {+ let content = output+ .parent()+ .ok_or_else(|| RecoveryError::Validation("Instant output has no parent".into()))?;+ if display_dir.parent() != Some(content) || audio_dir.parent() != Some(content) {+ return Err(RecoveryError::Validation(+ "Instant tracks must share the output directory".into(),+ ));+ }+ let project = content+ .parent()+ .ok_or_else(|| RecoveryError::Validation("Instant content has no project".into()))?;+ if content.file_name().is_none_or(|name| name != "content") {+ return Err(RecoveryError::Validation(+ "Instant tracks must be in project content".into(),+ ));+ }+ Self::require_no_track_failure(project)?;+ let _lock = RecoveryLock::acquire(project)?;+ let before = recovery_snapshot(project)?;+ let mut expected_audio = audio_dir.try_exists()?;+ if project.join("recording-meta.json").try_exists()? {+ let meta = RecordingMeta::load_for_project(project)+ .map_err(|error| RecoveryError::Validation(error.to_string()))?;+ match meta.inner {+ RecordingMetaInner::Instant(cap_project::InstantRecordingMeta::Failed {+ error,+ }) => {+ return Err(RecoveryError::RequiredTrackFailure(error));+ }+ RecordingMetaInner::Instant(cap_project::InstantRecordingMeta::Complete {+ sample_rate,+ ..+ }) => {+ expected_audio |= sample_rate.is_some();+ }+ RecordingMetaInner::Instant(_) => {}+ _ => {+ return Err(RecoveryError::Validation(+ "Instant output requires Instant metadata".into(),+ ));+ }+ }+ }+ let workspace = project.join(format!(".recovery-{}", uuid::Uuid::new_v4()));+ create_private_recovery_dir(&workspace)?;+ let staged = workspace.join("content");+ let result = (|| {+ copy_recovery_input(content, &staged)?;+ validate_recovery_manifests(&staged)?;+ let display = staged.join(+ display_dir+ .file_name()+ .ok_or_else(|| RecoveryError::Validation("Missing display name".into()))?,+ );+ let audio = staged.join(+ audio_dir+ .file_name()+ .ok_or_else(|| RecoveryError::Validation("Missing audio name".into()))?,+ );+ let final_output = staged.join(+ output+ .file_name()+ .ok_or_else(|| RecoveryError::Validation("Missing output name".into()))?,+ );+ if final_output.is_file()+ && let Ok(input) = ffmpeg::format::input(&final_output)+ {+ expected_audio |= input.streams().best(ffmpeg::media::Type::Audio).is_some();+ }+ if expected_audio && !audio.is_dir() {+ return Err(RecoveryError::Validation(+ "Missing required Instant audio".into(),+ ));+ }+ Self::rescue_pending_tmp_fragments(&display, None);+ let video = Self::find_complete_fragments_with_init(&display);+ validate_recovery_video_inputs(+ &video.fragments,+ video.init_segment.as_deref(),+ &workspace,+ )?;+ Self::finalize_instant_staged(&display, &audio, &final_output)?;+ validate_recovered_track(&final_output, ffmpeg::media::Type::Video)?;+ if expected_audio {+ validate_recovered_track(&final_output, ffmpeg::media::Type::Audio)?;+ }+ sync_recovery_input(&final_output)?;+ Self::require_no_track_failure(project)?;+ if recovery_snapshot(project)? != before {+ return Err(RecoveryError::Validation(+ "Instant recording changed during finalization".into(),+ ));+ }+ if output.try_exists()? {+ copy_recovery_input(output, &workspace.join("original-output.mp4"))?;+ }+ std::fs::rename(&final_output, output)?;+ Ok(output.to_path_buf())+ })();+ match result {+ Ok(output) => {+ std::fs::remove_dir_all(&workspace)?;+ Ok(output)+ }+ Err(error) => {+ let _ = std::fs::remove_dir_all(&workspace);+ Err(error)+ }+ }+ }++ fn finalize_instant_staged(+ display_dir: &Path,+ audio_dir: &Path,+ output: &Path,) -> Result<PathBuf, RecoveryError> {if !audio_dir.exists() {return Self::finalize_to_progressive_mp4(display_dir, output);@@ -1128,10 +1467,18 @@ impl RecoveryManager {Self::rescue_pending_tmp_fragments(audio_dir, None);let audio_info = Self::find_complete_fragments_with_init(audio_dir);if audio_info.fragments.is_empty() {- return Self::finalize_to_progressive_mp4(display_dir, output);+ return Err(RecoveryError::Validation(+ "Required Instant audio has no recoverable fragments".into(),+ ));}let parent = output.parent().unwrap_or_else(|| Path::new("."));+ validate_recovery_track_inputs(+ &audio_info.fragments,+ audio_info.init_segment.as_deref(),+ parent,+ ffmpeg::media::Type::Audio,+ )?;std::fs::create_dir_all(parent)?;let stem = output.file_stem()@@ -1209,23 +1556,14 @@ impl RecoveryManager {for (n, init, fragments) in respawn_groups {let group_tmp = parent.join(format!("{stem}.respawn-{n}.mp4"));- match Self::finalize_fragments_to_progressive_mp4(+ Self::finalize_fragments_to_progressive_mp4(&fragments,Some(init.as_path()),&group_tmp,&format!("display respawn-{n}"),- ) {- Ok(()) => {- temp_paths.push(group_tmp.clone());- group_outputs.push(group_tmp);- }- Err(err) => {- warn!(- "Respawn-{} group remux failed; skipping those fragments: {err}",- n- );- }- }+ )?;+ temp_paths.push(group_tmp.clone());+ group_outputs.push(group_tmp);}let concat_result = if group_outputs.len() == 1 {@@ -1382,9 +1720,6 @@ impl RecoveryManager {let display_path = segment_dir.join("display.mp4");let fps = get_video_fps(&display_path).unwrap_or(30);- let camera_path = segment_dir.join("camera.mp4");- let mic_path = segment_dir.join("audio-input.ogg");- let system_audio_path = segment_dir.join("system_audio.ogg");let cursor_path = segment_dir.join("cursor.json");let keyboard_path = {let binary = segment_dir.join(cap_project::KEYBOARD_EVENTS_FILE_NAME);@@ -1408,7 +1743,7 @@ impl RecoveryManager {start_time: display_start_time,device_id: original_segment.and_then(|s| s.display.device_id.clone()),},- camera: if camera_path.exists() {+ camera: if seg.camera_fragments.is_some() {Some(VideoMeta {path: RelativePathBuf::from(format!("{segment_base}/camera.mp4")),fps: original_segment@@ -1428,7 +1763,7 @@ impl RecoveryManager {None},mic: {- if valid_recovered_audio(&mic_path) {+ if seg.mic_fragments.is_some() {Some(AudioMeta {path: RelativePathBuf::from(format!("{segment_base}/audio-input.ogg"@@ -1448,7 +1783,7 @@ impl RecoveryManager {}},system_audio: {- if valid_recovered_audio(&system_audio_path) {+ if seg.system_audio_fragments.is_some() {Some(AudioMeta {path: RelativePathBuf::from(format!("{segment_base}/system_audio.ogg"@@ -1541,12 +1876,20 @@ impl RecoveryManager {}).collect();- if timeline_segments.is_empty() {+ if timeline_segments.len() != inner.segments.len() || timeline_segments.is_empty() {warn!("No valid timeline segments could be created");- return Ok(());+ return Err(RecoveryError::Validation(+ "No valid recovery timeline".into(),+ ));}- let mut config = ProjectConfiguration::load(&recording.project_path).unwrap_or_default();+ let mut config = match ProjectConfiguration::load(&recording.project_path) {+ Ok(config) => config,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ ProjectConfiguration::default()+ }+ Err(error) => return Err(error.into()),+ };config.timeline = Some(TimelineConfiguration {segments: timeline_segments,@@ -1690,78 +2033,910 @@ impl RecoveryManager {}}-fn start_time_or_display_fallback(- original_time: Option<f64>,- display_start_time: Option<f64>,-) -> Option<f64> {- original_time.or(display_start_time)+fn create_private_recovery_dir(path: &Path) -> std::io::Result<()> {+ let builder = std::fs::DirBuilder::new();+ #[cfg(unix)]+ let builder = {+ use std::os::unix::fs::DirBuilderExt;+ let mut builder = builder;+ builder.mode(0o700);+ builder+ };+ builder.create(path)}-fn valid_recovered_audio(path: &Path) -> bool {- path.is_file() && probe_media_valid(path)+fn recovery_child_path(dir: &Path, name: &str) -> Option<PathBuf> {+ let child = Path::new(name);+ if child.as_os_str().is_empty()+ || !child+ .components()+ .all(|component| matches!(component, std::path::Component::Normal(_)))+ {+ return None;+ }+ Some(dir.join(child))}-fn replace_file(src: &Path, dst: &Path) -> Result<(), RecoveryError> {- if dst.exists() {- std::fs::remove_file(dst).map_err(RecoveryError::Io)?;+fn validate_recovery_manifests(dir: &Path) -> Result<(), RecoveryError> {+ for entry in std::fs::read_dir(dir)? {+ let path = entry?.path();+ if path.is_dir() {+ validate_recovery_manifests(&path)?;+ } else if path.file_name().is_some_and(|name| name == "manifest.json") {+ let raw = std::fs::read(&path)?;+ let Ok(manifest) = serde_json::from_slice::<serde_json::Value>(&raw) else {+ continue;+ };+ let parent = path+ .parent()+ .ok_or_else(|| RecoveryError::Validation("Manifest has no parent".into()))?;+ if let Some(init) = manifest+ .get("init_segment")+ .and_then(serde_json::Value::as_str)+ {+ let init = recovery_child_path(parent, init)+ .ok_or_else(|| RecoveryError::Validation("Invalid init path".into()))?;+ if !init.is_file() {+ return Err(RecoveryError::Validation(+ "Missing declared init segment".into(),+ ));+ }+ }+ for fragment in manifest+ .get("segments")+ .or_else(|| manifest.get("fragments"))+ .and_then(serde_json::Value::as_array)+ .into_iter()+ .flatten()+ {+ let Some(name) = fragment.get("path").and_then(serde_json::Value::as_str) else {+ continue;+ };+ let path = recovery_child_path(parent, name).ok_or_else(|| {+ RecoveryError::Validation("Invalid manifest fragment path".into())+ })?;+ if fragment+ .get("is_complete")+ .and_then(serde_json::Value::as_bool)+ != Some(true)+ {+ continue;+ }+ let metadata = path.symlink_metadata()?;+ if !metadata.is_file()+ || fragment+ .get("file_size")+ .and_then(serde_json::Value::as_u64)+ .is_some_and(|size| size != metadata.len())+ || (path.extension().is_some_and(|ext| ext == "m4s")+ && !RecoveryManager::is_m4s_complete(&path))+ {+ return Err(RecoveryError::Validation(format!(+ "Invalid declared complete fragment: {}",+ path.display()+ )));+ }+ }+ }}+ Ok(())+}- std::fs::rename(src, dst).map_err(RecoveryError::Io)+fn validate_recovery_video_inputs(+ fragments: &[PathBuf],+ init: Option<&Path>,+ workspace: &Path,+) -> Result<(), RecoveryError> {+ validate_recovery_track_inputs(fragments, init, workspace, ffmpeg::media::Type::Video)}-#[cfg(test)]-mod tests {- use super::{- RecoveryManager, replace_file, start_time_or_display_fallback, valid_recovered_audio,- };- use std::fs;- use tempfile::tempdir;+fn validate_recovery_track_inputs(+ fragments: &[PathBuf],+ init: Option<&Path>,+ workspace: &Path,+ kind: ffmpeg::media::Type,+) -> Result<(), RecoveryError> {+ if fragments.is_empty() {+ return Err(RecoveryError::NoRecoverableSegments);+ }+ if let Some(init) = init {+ let path = workspace.join(format!(".validate-{}.mp4", uuid::Uuid::new_v4()));+ let mut output = std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&path)?;+ for source in std::iter::once(init).chain(fragments.iter().map(PathBuf::as_path)) {+ std::io::copy(&mut std::fs::File::open(source)?, &mut output)?;+ }+ output.sync_all()?;+ drop(output);+ validate_recovered_track(&path, kind)?;+ std::fs::remove_file(path)?;+ } else {+ for path in fragments {+ validate_recovered_track(path, kind)?;+ }+ }+ Ok(())+}- fn complete_m4s_fragment() -> Vec<u8> {- let mut fragment = Vec::new();- for name in [b"moof", b"mdat"] {- fragment.extend_from_slice(&72u32.to_be_bytes());- fragment.extend_from_slice(name);- fragment.extend_from_slice(&[0; 64]);+const RECOVERY_INPUTS: [&str; 4] = [+ "content",+ "recording-meta.json",+ "project-config.json",+ "recording-diagnostics.json",+];++struct RecoveryLock {+ _file: std::fs::File,+}++impl RecoveryLock {+ fn acquire(project: &Path) -> Result<Self, RecoveryError> {+ reject_recovery_link(&project.symlink_metadata()?)?;+ let path = project.join(".recovery.lock");+ let mut options = std::fs::OpenOptions::new();+ options.read(true).write(true).create(true).truncate(false);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);}- fragment+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;+ options+ .share_mode(0)+ .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);+ }+ let file = options.open(&path)?;+ let metadata = file.metadata()?;+ reject_recovery_link(&metadata)?;+ if !metadata.is_file() || metadata.len() != 0 {+ return Err(RecoveryError::Validation(+ "Invalid recovery lock file".into(),+ ));+ }+ #[cfg(unix)]+ {+ use std::os::fd::AsRawFd;+ use std::os::unix::fs::MetadataExt;+ if metadata.nlink() != 1 || metadata.uid() != unsafe { libc::geteuid() } {+ return Err(RecoveryError::Validation(+ "Recovery lock is not exclusively owned".into(),+ ));+ }+ if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {+ return Err(std::io::Error::last_os_error().into());+ }+ }+ let lock = Self { _file: file };+ if let Err(error) = reconcile_recovery_publication(project) {+ warn!(path = %project.display(), %error, "Interrupted recovery publication requires attention; all files retained");+ return Err(error);+ }+ Ok(lock)}+}- #[test]- fn recovery_includes_complete_fragments_missing_from_the_last_manifest() {- let dir = tempdir().unwrap();- let fragment = complete_m4s_fragment();- fs::write(dir.path().join("init.mp4"), [0; 128]).unwrap();- for name in [- "segment_001.m4s",- "segment_002.m4s",- "segment_999.m4s",- "segment_1000.m4s",- ] {- fs::write(dir.path().join(name), &fragment).unwrap();+fn reject_recovery_link(metadata: &std::fs::Metadata) -> Result<(), RecoveryError> {+ #[cfg(windows)]+ {+ use std::os::windows::fs::MetadataExt;+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;+ if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {+ return Err(RecoveryError::Validation(+ "Recovery input is a reparse point".into(),+ ));}- fs::write(- dir.path().join("segment_1001.m4s"),- &fragment[..fragment.len() - 1],- )- .unwrap();- let manifest = serde_json::to_vec(&serde_json::json!({- "version": 5,- "type": "m4s_segments",- "init_segment": "init.mp4",- "segments": [- {"path": "segment_001.m4s", "is_complete": true, "file_size": fragment.len()},- {"path": "segment_002.m4s", "is_complete": true, "file_size": fragment.len() + 1}- ]- }))- .unwrap();- fs::write(dir.path().join("manifest.json"), &manifest).unwrap();+ }+ if metadata.file_type().is_symlink() {+ return Err(RecoveryError::Validation(+ "Recovery input is a symbolic link".into(),+ ));+ }+ Ok(())+}- let recovered = RecoveryManager::find_complete_fragments_with_init(dir.path());- assert_eq!(- recovered.fragments,- ["segment_001.m4s", "segment_999.m4s", "segment_1000.m4s"]- .map(|name| dir.path().join(name))+fn copy_recovery_input(source: &Path, destination: &Path) -> Result<(), RecoveryError> {+ let metadata = source.symlink_metadata()?;+ reject_recovery_link(&metadata)?;+ if metadata.is_dir() {+ std::fs::create_dir(destination)?;+ for entry in std::fs::read_dir(source)? {+ let entry = entry?;+ copy_recovery_input(&entry.path(), &destination.join(entry.file_name()))?;+ }+ } else if metadata.is_file() {+ let mut input = std::fs::File::open(source)?;+ let mut output = std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(destination)?;+ std::io::copy(&mut input, &mut output)?;+ output.sync_all()?;+ } else {+ return Err(RecoveryError::Validation(format!(+ "Unsupported recovery input: {}",+ source.display()+ )));+ }+ Ok(())+}++fn recovery_snapshot(+ project: &Path,+) -> Result<std::collections::BTreeMap<PathBuf, Option<Vec<u8>>>, RecoveryError> {+ use sha2::Digest;+ fn visit(+ root: &Path,+ path: &Path,+ entries: &mut std::collections::BTreeMap<PathBuf, Option<Vec<u8>>>,+ ) -> Result<(), RecoveryError> {+ let metadata = path.symlink_metadata()?;+ reject_recovery_link(&metadata)?;+ let relative = path+ .strip_prefix(root)+ .map_err(|error| RecoveryError::Validation(error.to_string()))?+ .to_path_buf();+ if metadata.is_dir() {+ let _ = entries.insert(relative, None);+ for entry in std::fs::read_dir(path)? {+ visit(root, &entry?.path(), entries)?;+ }+ } else if metadata.is_file() {+ let mut digest = sha2::Sha256::new();+ use std::io::Read;+ let mut input = std::fs::File::open(path)?;+ let mut buffer = [0_u8; 65536];+ loop {+ let count = input.read(&mut buffer)?;+ if count == 0 {+ break;+ }+ digest.update(&buffer[..count]);+ }+ let _ = entries.insert(relative, Some(digest.finalize().to_vec()));+ } else {+ return Err(RecoveryError::Validation(format!(+ "Unsupported recovery input: {}",+ path.display()+ )));+ }+ Ok(())+ }+ let mut entries = std::collections::BTreeMap::new();+ for name in RECOVERY_INPUTS {+ let path = project.join(name);+ match path.symlink_metadata() {+ Ok(_) => visit(project, &path, &mut entries)?,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(error.into()),+ }+ }+ Ok(entries)+}++fn sync_recovery_input(path: &Path) -> Result<(), RecoveryError> {+ if path.is_dir() {+ for entry in std::fs::read_dir(path)? {+ sync_recovery_input(&entry?.path())?;+ }+ } else {+ std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .open(path)?+ .sync_all()?;+ }+ Ok(())+}++const RECOVERY_PUBLICATION: &str = ".recovery-publication.json";+const RECOVERY_PUBLICATION_RECEIPT: &str = "publication-receipt.json";+const RECOVERY_PUBLICATION_MAX_BYTES: u64 = 8192;++#[derive(serde::Serialize, serde::Deserialize)]+#[serde(deny_unknown_fields)]+struct RecoveryPublication {+ version: u32,+ project: PathBuf,+ workspace: String,+ original: RecoveryPublicationState,+ staged: RecoveryPublicationState,+}++#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq)]+#[serde(deny_unknown_fields)]+struct RecoveryPublicationState {+ segments: Option<[u8; 32]>,+ meta: Option<[u8; 32]>,+ config: Option<[u8; 32]>,+}++fn open_recovery_publication_file(path: &Path) -> std::io::Result<std::fs::File> {+ let mut options = std::fs::OpenOptions::new();+ options.read(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK);+ }+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ options.custom_flags(0x0020_0000);+ }+ let file = options.open(path)?;+ let metadata = file.metadata()?;+ if !metadata.is_file() || reject_recovery_link(&metadata).is_err() {+ return Err(std::io::Error::other("Invalid recovery publication file"));+ }+ Ok(file)+}++fn recovery_publication_file_digest(path: &Path) -> Result<Option<[u8; 32]>, RecoveryError> {+ use sha2::Digest;+ use std::io::Read;+ let mut file = match open_recovery_publication_file(path) {+ Ok(file) => file,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(error.into()),+ };+ let mut digest = sha2::Sha256::new();+ let mut buffer = [0_u8; 65536];+ loop {+ let count = file.read(&mut buffer)?;+ if count == 0 {+ break;+ }+ digest.update(&buffer[..count]);+ }+ Ok(Some(digest.finalize().into()))+}++fn recovery_publication_segments_stamp(path: &Path) -> Result<Option<[u8; 32]>, RecoveryError> {+ // These stamps locate the interrupted rename; ordinary recovery still validates media content.+ use sha2::Digest;+ #[derive(serde::Serialize)]+ struct Entry {+ directory: bool,+ size: u64,+ modified: Duration,+ created: Option<Duration>,+ #[cfg(unix)]+ identity: (u64, u64),+ }+ fn visit(+ root: &Path,+ path: &Path,+ entries: &mut std::collections::BTreeMap<PathBuf, Entry>,+ ) -> Result<(), RecoveryError> {+ let metadata = path.symlink_metadata()?;+ reject_recovery_link(&metadata)?;+ if !metadata.is_file() && !metadata.is_dir() {+ return Err(RecoveryError::Validation(+ "Invalid publication tree entry".into(),+ ));+ }+ #[cfg(unix)]+ use std::os::unix::fs::MetadataExt;+ let _ = entries.insert(+ path.strip_prefix(root)+ .map_err(|error| RecoveryError::Validation(error.to_string()))?+ .to_path_buf(),+ Entry {+ directory: metadata.is_dir(),+ size: metadata.len(),+ modified: metadata+ .modified()?+ .duration_since(std::time::UNIX_EPOCH)+ .map_err(|error| RecoveryError::Validation(error.to_string()))?,+ created: metadata+ .created()+ .ok()+ .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()),+ #[cfg(unix)]+ identity: (metadata.dev(), metadata.ino()),+ },+ );+ if metadata.is_dir() {+ for entry in std::fs::read_dir(path)? {+ visit(root, &entry?.path(), entries)?;+ }+ }+ Ok(())+ }+ match path.symlink_metadata() {+ Ok(metadata) => {+ reject_recovery_link(&metadata)?;+ if !metadata.is_dir() {+ return Err(RecoveryError::Validation(+ "Publication segments are not a directory".into(),+ ));+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),+ Err(error) => return Err(error.into()),+ }+ let mut entries = std::collections::BTreeMap::new();+ visit(path, path, &mut entries)?;+ Ok(Some(+ sha2::Sha256::digest(serde_json::to_vec(&entries)?).into(),+ ))+}++fn recovery_publication_state(project: &Path) -> Result<RecoveryPublicationState, RecoveryError> {+ for path in [project.to_path_buf(), project.join("content")] {+ let metadata = path.symlink_metadata()?;+ reject_recovery_link(&metadata)?;+ if !metadata.is_dir() {+ return Err(RecoveryError::Validation(+ "Invalid publication directory".into(),+ ));+ }+ }+ Ok(RecoveryPublicationState {+ segments: recovery_publication_segments_stamp(&project.join("content/segments"))?,+ meta: recovery_publication_file_digest(&project.join("recording-meta.json"))?,+ config: recovery_publication_file_digest(&project.join("project-config.json"))?,+ })+}++fn recovery_publication_workspace(project: &Path, name: &str) -> Result<PathBuf, RecoveryError> {+ let id = name+ .strip_prefix(".recovery-")+ .and_then(|value| uuid::Uuid::parse_str(value).ok())+ .filter(|id| name == format!(".recovery-{id}"))+ .ok_or_else(|| {+ RecoveryError::Validation("Invalid publication workspace generation".into())+ })?;+ let workspace = project.join(format!(".recovery-{id}"));+ let metadata = workspace.symlink_metadata()?;+ reject_recovery_link(&metadata)?;+ if !metadata.is_dir() {+ return Err(RecoveryError::Validation(+ "Invalid publication workspace".into(),+ ));+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ if metadata.uid() != unsafe { libc::geteuid() } || metadata.mode() & 0o077 != 0 {+ return Err(RecoveryError::Validation(+ "Publication workspace is not privately owned".into(),+ ));+ }+ }+ Ok(workspace)+}++fn read_recovery_publication(path: &Path) -> std::io::Result<Vec<u8>> {+ use std::io::Read;+ let file = open_recovery_publication_file(path)?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::MetadataExt;+ let metadata = file.metadata()?;+ if metadata.nlink() != 1+ || metadata.uid() != unsafe { libc::geteuid() }+ || metadata.mode() & 0o077 != 0+ {+ return Err(std::io::Error::other(+ "Recovery publication receipt is not privately owned",+ ));+ }+ }+ let mut bytes = Vec::new();+ file.take(RECOVERY_PUBLICATION_MAX_BYTES + 1)+ .read_to_end(&mut bytes)?;+ if bytes.len() as u64 > RECOVERY_PUBLICATION_MAX_BYTES {+ return Err(std::io::Error::other(+ "Recovery publication receipt is too large",+ ));+ }+ Ok(bytes)+}++fn finish_recovery_publication(+ project: &Path,+ workspace: &Path,+ bytes: &[u8],+) -> Result<(), RecoveryError> {+ if read_recovery_publication(&project.join(RECOVERY_PUBLICATION))? != bytes+ || read_recovery_publication(&workspace.join(RECOVERY_PUBLICATION_RECEIPT))? != bytes+ {+ return Err(RecoveryError::Validation(+ "Publication receipt changed; evidence retained".into(),+ ));+ }+ std::fs::remove_file(project.join(RECOVERY_PUBLICATION))?;+ Ok(())+}++fn begin_recovery_publication(project: &Path, workspace: &Path) -> Result<Vec<u8>, RecoveryError> {+ use std::io::Write;+ let name = workspace+ .file_name()+ .and_then(|name| name.to_str())+ .ok_or_else(|| {+ RecoveryError::Validation("Missing publication workspace generation".into())+ })?;+ if workspace != recovery_publication_workspace(project, name)?.as_path() {+ return Err(RecoveryError::Validation(+ "Publication workspace is outside the project".into(),+ ));+ }+ let receipt = RecoveryPublication {+ version: 1,+ project: project.canonicalize()?,+ workspace: name.into(),+ original: recovery_publication_state(project)?,+ staged: recovery_publication_state(&workspace.join("staged"))?,+ };+ if receipt.original.segments.is_none()+ || receipt.original.meta.is_none()+ || receipt.staged.segments.is_none()+ || receipt.staged.meta.is_none()+ || receipt.staged.config.is_none()+ {+ return Err(RecoveryError::Validation(+ "Incomplete recovery publication".into(),+ ));+ }+ let bytes = serde_json::to_vec(&receipt)?;+ if bytes.len() as u64 > RECOVERY_PUBLICATION_MAX_BYTES {+ return Err(RecoveryError::Validation(+ "Recovery publication receipt is too large".into(),+ ));+ }+ for path in [+ workspace.join(RECOVERY_PUBLICATION_RECEIPT),+ project.join(RECOVERY_PUBLICATION),+ ] {+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC);+ }+ let mut file = options.open(path)?;+ file.write_all(&bytes)?;+ file.sync_all()?;+ }+ Ok(bytes)+}++fn reconcile_recovery_publication(project: &Path) -> Result<(), RecoveryError> {+ let bytes = match read_recovery_publication(&project.join(RECOVERY_PUBLICATION)) {+ Ok(bytes) => bytes,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ if !project.join("content/segments").try_exists()?+ && RecordingMeta::load_for_project(project)+ .ok()+ .is_some_and(|meta| meta.studio_meta().is_some())+ {+ for entry in std::fs::read_dir(project)? {+ if entry?+ .file_name()+ .to_string_lossy()+ .starts_with(".recovery-")+ {+ return Err(RecoveryError::Validation("Missing segments with an unbound recovery workspace; evidence retained".into()));+ }+ }+ }+ return Ok(());+ }+ Err(error) => return Err(error.into()),+ };+ let receipt: RecoveryPublication = serde_json::from_slice(&bytes)?;+ if receipt.version != 1+ || receipt.project != project.canonicalize()?+ || receipt.original.meta.is_none()+ || receipt.original.segments.is_none()+ || receipt.staged.meta.is_none()+ || receipt.staged.segments.is_none()+ || receipt.staged.config.is_none()+ {+ return Err(RecoveryError::Validation(+ "Invalid publication identity; evidence retained".into(),+ ));+ }+ let workspace = recovery_publication_workspace(project, &receipt.workspace)?;+ if read_recovery_publication(&workspace.join(RECOVERY_PUBLICATION_RECEIPT))? != bytes {+ return Err(RecoveryError::Validation(+ "Publication generation does not match its workspace".into(),+ ));+ }+ let current = recovery_publication_state(project)?;+ let staged = recovery_publication_state(&workspace.join("staged"))?;+ let backup = recovery_publication_segments_stamp(&workspace.join("original-segments"))?;+ let backup_config =+ recovery_publication_file_digest(&workspace.join("original-project-config.json"))?;+ if recovery_publication_file_digest(&workspace.join("original-recording-meta.json"))?+ != receipt.original.meta+ {+ return Err(RecoveryError::Validation(+ "Original publication metadata changed".into(),+ ));+ }+ let config_rolled_back = current.meta == receipt.original.meta+ && current.config == receipt.original.config+ && staged.meta == receipt.staged.meta+ && staged.config.is_none()+ && backup_config.is_none();+ let before_move = (current == receipt.original+ && staged == receipt.staged+ && backup.is_none()+ && (backup_config == receipt.original.config || backup_config.is_none()))+ || (config_rolled_back+ && current == receipt.original+ && staged.segments == receipt.staged.segments+ && backup.is_none());+ let missing_segments = (current.segments.is_none()+ && current.meta == receipt.original.meta+ && current.config == receipt.original.config+ && staged == receipt.staged+ && backup == receipt.original.segments+ && backup_config == receipt.original.config)+ || (config_rolled_back+ && current.segments.is_none()+ && staged.segments == receipt.staged.segments+ && backup == receipt.original.segments);+ let installed_segments = (current.segments == receipt.staged.segments+ && current.meta == receipt.original.meta+ && backup == receipt.original.segments+ && backup_config == receipt.original.config+ && staged.segments.is_none()+ && staged.meta == receipt.staged.meta+ && ((current.config == receipt.original.config && staged.config == receipt.staged.config)+ || (current.config == receipt.staged.config && staged.config.is_none())))+ || (config_rolled_back+ && current.segments == receipt.staged.segments+ && staged.segments.is_none()+ && backup == receipt.original.segments);+ let committed = current == receipt.staged+ && backup == receipt.original.segments+ && backup_config == receipt.original.config+ && staged.segments.is_none()+ && staged.meta.is_none()+ && staged.config.is_none();+ if missing_segments {+ let destination = project.join("content/segments");+ match destination.symlink_metadata() {+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Ok(_) => {+ return Err(RecoveryError::Validation(+ "Canonical segments appeared during reconciliation".into(),+ ));+ }+ Err(error) => return Err(error.into()),+ }+ std::fs::rename(workspace.join("original-segments"), destination)?;+ if recovery_publication_state(project)? != receipt.original {+ return Err(RecoveryError::Validation(+ "Restored publication state changed; evidence retained".into(),+ ));+ }+ } else if !before_move && !installed_segments && !committed {+ return Err(RecoveryError::Validation(+ "Conflicting recovery publication state; all files retained".into(),+ ));+ }+ finish_recovery_publication(project, &workspace, &bytes)+}++fn publish_recovery(project: &Path, workspace: &Path) -> Result<(), RecoveryError> {+ publish_recovery_with(project, workspace, rename_recovery_path)+}++fn rename_recovery_path(source: &Path, destination: &Path) -> std::io::Result<()> {+ std::fs::rename(source, destination)+}++fn publish_recovery_with(+ project: &Path,+ workspace: &Path,+ mut rename: impl FnMut(&Path, &Path) -> std::io::Result<()>,+) -> Result<(), RecoveryError> {+ let staged = workspace.join("staged");+ let original_segments = project.join("content/segments");+ let backup_segments = workspace.join("original-segments");+ let config = project.join("project-config.json");+ let backup_config = workspace.join("original-project-config.json");+ let had_config = config.try_exists()?;+ if had_config {+ copy_recovery_input(&config, &backup_config)?;+ }+ copy_recovery_input(+ &project.join("recording-meta.json"),+ &workspace.join("original-recording-meta.json"),+ )?;+ let publication = begin_recovery_publication(project, workspace)?;+ if let Err(error) = rename(&original_segments, &backup_segments) {+ finish_recovery_publication(project, workspace, &publication)?;+ return Err(error.into());+ }+ let mut segments_published = false;+ let mut config_published = false;+ let result = (|| {+ rename(&staged.join("content/segments"), &original_segments)?;+ segments_published = true;+ rename(&staged.join("project-config.json"), &config)?;+ config_published = true;+ rename(+ &staged.join("recording-meta.json"),+ &project.join("recording-meta.json"),+ )?;+ Ok::<_, std::io::Error>(())+ })();+ if let Err(error) = result {+ let rollback = (|| {+ if config_published {+ if had_config {+ rename(&backup_config, &config)?;+ } else {+ std::fs::remove_file(&config)?;+ }+ }+ if segments_published {+ rename(&original_segments, &staged.join("content/segments"))?;+ }+ rename(&backup_segments, &original_segments)?;+ Ok::<_, std::io::Error>(())+ })();+ if let Err(rollback_error) = rollback {+ return Err(RecoveryError::Validation(format!(+ "Publication failed: {error}; rollback failed: {rollback_error}; original media and metadata retained at {}",+ workspace.display()+ )));+ }+ finish_recovery_publication(project, workspace, &publication)?;+ return Err(error.into());+ }+ finish_recovery_publication(project, workspace, &publication)?;+ Ok(())+}++fn validate_recovered_track(path: &Path, kind: ffmpeg::media::Type) -> Result<(), RecoveryError> {+ let validate = || -> Result<(), String> {+ let mut input = ffmpeg::format::input(path).map_err(|error| error.to_string())?;+ let stream = input+ .streams()+ .best(kind)+ .ok_or_else(|| format!("Missing {kind:?} stream"))?;+ let index = stream.index();+ let context = ffmpeg::codec::Context::from_parameters(stream.parameters())+ .map_err(|error| error.to_string())?;+ let codec =+ ffmpeg::decoder::find(context.id()).ok_or_else(|| "Decoder unavailable".to_string())?;+ let mut decoder = context.decoder();+ decoder.check(ffmpeg::codec::decoder::Check::EXPLODE | ffmpeg::codec::decoder::Check::CRC);+ let mut decoder = decoder.open_as(codec).map_err(|error| error.to_string())?;+ let mut frame = unsafe { ffmpeg::Frame::empty() };+ let mut decoded = false;+ loop {+ let mut packet = ffmpeg::Packet::empty();+ match packet.read(&mut input) {+ Ok(()) => {}+ Err(ffmpeg::Error::Eof) => break,+ Err(error) => return Err(error.to_string()),+ }+ if packet.stream() != index {+ continue;+ }+ if packet.is_corrupt() {+ return Err("Corrupt packet".into());+ }+ decoder+ .send_packet(&packet)+ .map_err(|error| error.to_string())?;+ loop {+ match decoder.receive_frame(&mut frame) {+ Ok(()) if !frame.is_corrupt() => decoded = true,+ Ok(()) => return Err("Corrupt decoded frame".into()),+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => break,+ Err(error) => return Err(error.to_string()),+ }+ }+ }+ decoder.send_eof().map_err(|error| error.to_string())?;+ loop {+ match decoder.receive_frame(&mut frame) {+ Ok(()) if !frame.is_corrupt() => decoded = true,+ Ok(()) => return Err("Corrupt decoded frame".into()),+ Err(ffmpeg::Error::Eof) => break,+ Err(error) => return Err(error.to_string()),+ }+ }+ if !decoded {+ return Err("Track contains no decoded frames".into());+ }+ Ok(())+ };+ validate().map_err(|error| RecoveryError::Validation(format!("{}: {error}", path.display())))+}++fn start_time_or_display_fallback(+ original_time: Option<f64>,+ display_start_time: Option<f64>,+) -> Option<f64> {+ original_time.or(display_start_time)+}++#[cfg(test)]+fn valid_recovered_audio(path: &Path) -> bool {+ path.is_file() && validate_recovered_track(path, ffmpeg::media::Type::Audio).is_ok()+}++fn replace_file(src: &Path, dst: &Path) -> Result<(), RecoveryError> {+ if dst.exists() {+ std::fs::remove_file(dst).map_err(RecoveryError::Io)?;+ }++ std::fs::rename(src, dst).map_err(RecoveryError::Io)+}++#[cfg(test)]+mod tests {+ use super::{+ RecoveryManager, replace_file, start_time_or_display_fallback, valid_recovered_audio,+ };+ use std::fs;+ use tempfile::tempdir;++ fn complete_m4s_fragment() -> Vec<u8> {+ let mut fragment = Vec::new();+ for name in [b"moof", b"mdat"] {+ fragment.extend_from_slice(&72u32.to_be_bytes());+ fragment.extend_from_slice(name);+ fragment.extend_from_slice(&[0; 64]);+ }+ fragment+ }++ #[test]+ fn recovery_includes_complete_fragments_missing_from_the_last_manifest() {+ let dir = tempdir().unwrap();+ let fragment = complete_m4s_fragment();+ fs::write(dir.path().join("init.mp4"), [0; 128]).unwrap();+ for name in [+ "segment_001.m4s",+ "segment_002.m4s",+ "segment_999.m4s",+ "segment_1000.m4s",+ ] {+ fs::write(dir.path().join(name), &fragment).unwrap();+ }+ fs::write(+ dir.path().join("segment_1001.m4s"),+ &fragment[..fragment.len() - 1],+ )+ .unwrap();+ let manifest = serde_json::to_vec(&serde_json::json!({+ "version": 5,+ "type": "m4s_segments",+ "init_segment": "init.mp4",+ "segments": [+ {"path": "segment_001.m4s", "is_complete": true, "file_size": fragment.len()},+ {"path": "segment_002.m4s", "is_complete": true, "file_size": fragment.len() + 1}+ ]+ }))+ .unwrap();+ fs::write(dir.path().join("manifest.json"), &manifest).unwrap();++ let recovered = RecoveryManager::find_complete_fragments_with_init(dir.path());+ assert_eq!(+ recovered.fragments,+ ["segment_001.m4s", "segment_999.m4s", "segment_1000.m4s"]+ .map(|name| dir.path().join(name)));assert_eq!(fs::read(dir.path().join("manifest.json")).unwrap(),@@ -1937,3 +3112,819 @@ mod tests {assert_eq!(start_time_or_display_fallback(None, None), None);}}++#[cfg(test)]+mod required_track_failure_recovery_tests {+ use super::*;++ #[test]+ fn diagnostics_failure_blocks_recovery_without_modifying_partial_media() {+ let directory = tempfile::tempdir().unwrap();+ let media = directory.path().join("partial.m4a");+ std::fs::write(&media, b"preserved").unwrap();+ std::fs::write(directory.path().join("recording-diagnostics.json"),+ br#"{"version":1,"segments":[{"trackFailures":[{"track":"microphone","stage":"runtime","error":"failed"}]}]}"#).unwrap();+ assert!(RecoveryManager::require_no_track_failure(directory.path()).is_err());+ assert_eq!(std::fs::read(media).unwrap(), b"preserved");+ }++ #[test]+ fn unknown_or_unreadable_diagnostics_cannot_authorize_recovery() {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("recording-diagnostics.json");+ for raw in [b"not-json".as_slice(), b"{}".as_slice()] {+ std::fs::write(&path, raw).unwrap();+ assert!(RecoveryManager::require_no_track_failure(directory.path()).is_err());+ }+ std::fs::remove_file(&path).unwrap();+ std::fs::create_dir(&path).unwrap();+ assert!(RecoveryManager::require_no_track_failure(directory.path()).is_err());+ }++ #[test]+ fn recording_without_failure_diagnostics_remains_eligible() {+ let directory = tempfile::tempdir().unwrap();+ assert!(RecoveryManager::require_no_track_failure(directory.path()).is_ok());+ }+}++#[cfg(test)]+mod transactional_recovery_tests {+ use super::*;++ fn publication_fixture() -> (tempfile::TempDir, PathBuf, PathBuf) {+ let temporary = tempfile::tempdir().unwrap();+ let project = temporary.path().join("project");+ let workspace = project.join(format!(".recovery-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(project.join("content/segments")).unwrap();+ create_private_recovery_dir(&workspace).unwrap();+ std::fs::create_dir_all(workspace.join("staged/content/segments")).unwrap();+ std::fs::write(project.join("content/segments/raw.m4s"), b"original raw").unwrap();+ std::fs::write(project.join("recording-meta.json"), b"original status").unwrap();+ std::fs::write(project.join("project-config.json"), b"original config").unwrap();+ std::fs::write(+ workspace.join("staged/content/segments/display.mp4"),+ b"validated output",+ )+ .unwrap();+ std::fs::write(workspace.join("staged/recording-meta.json"), b"complete").unwrap();+ std::fs::write(+ workspace.join("staged/project-config.json"),+ b"validated config",+ )+ .unwrap();+ (temporary, project, workspace)+ }++ fn interrupt_publication(project: &Path, workspace: &Path, after: usize) {+ let _lock = RecoveryLock::acquire(project).unwrap();+ let mut calls = 0;+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ publish_recovery_with(project, workspace, |source, destination| {+ assert_ne!(after, 0, "interrupted before the first rename");+ std::fs::rename(source, destination)?;+ calls += 1;+ assert_ne!(calls, after, "interrupted after publication rename");+ Ok(())+ })+ }));+ assert!(result.is_err());+ assert!(project.join(RECOVERY_PUBLICATION).is_file());+ assert!(workspace.join(RECOVERY_PUBLICATION_RECEIPT).is_file());+ }++ fn scannable_publication_fixture() -> (tempfile::TempDir, PathBuf, PathBuf) {+ let (temporary, project, workspace) = publication_fixture();+ let meta = RecordingMeta {+ platform: None,+ project_path: project.clone(),+ pretty_name: "Interrupted publication".into(),+ sharing: None,+ upload: None,+ inner: RecordingMetaInner::Studio(Box::new(StudioRecordingMeta::MultipleSegments {+ inner: MultipleSegments {+ segments: Vec::new(),+ cursors: Cursors::default(),+ status: Some(StudioRecordingStatus::NeedsRemux),+ },+ })),+ };+ meta.save_for_project().unwrap();+ let display = project.join("content/segments/segment-0/display");+ std::fs::create_dir_all(&display).unwrap();+ std::fs::write(display.join("init.mp4"), [0; 128]).unwrap();+ let mut fragment = Vec::new();+ for kind in [b"moof", b"mdat"] {+ fragment.extend_from_slice(&72_u32.to_be_bytes());+ fragment.extend_from_slice(kind);+ fragment.extend_from_slice(&[0; 64]);+ }+ std::fs::write(display.join("segment_001.m4s"), fragment).unwrap();+ let staged_segment = workspace.join("staged/content/segments/segment-0");+ std::fs::create_dir_all(&staged_segment).unwrap();+ copy_recovery_input(&display, &staged_segment.join("display")).unwrap();+ (temporary, project, workspace)+ }++ fn interrupt_publication_rollback(+ project: &Path,+ workspace: &Path,+ failure: usize,+ interruption: usize,+ before_rename: bool,+ ) {+ let _lock = RecoveryLock::acquire(project).unwrap();+ let mut calls = 0;+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ publish_recovery_with(project, workspace, |source, destination| {+ calls += 1;+ if calls == failure {+ return Err(std::io::Error::other("injected publication rename failure"));+ }+ assert!(+ !before_rename || calls != interruption,+ "interrupted before rollback rename"+ );+ std::fs::rename(source, destination)?;+ assert!(+ before_rename || calls != interruption,+ "interrupted after rollback rename"+ );+ Ok(())+ })+ }));+ assert!(result.is_err());+ assert_eq!(calls, interruption);+ assert!(project.join(RECOVERY_PUBLICATION).is_file());+ }++ #[test]+ fn interrupted_rollback_reconciles_and_relaunches_at_every_rename_boundary() {+ use sha2::Digest;++ for had_config in [false, true] {+ for failure in 2..=4 {+ let last_rollback = match failure {+ 2 => 3,+ 3 => 5,+ 4 if had_config => 7,+ 4 => 6,+ _ => unreachable!(),+ };+ for interruption in (failure + 1)..=last_rollback {+ for before_rename in [false, true] {+ let (temporary, project, workspace) = scannable_publication_fixture();+ if !had_config {+ std::fs::remove_file(project.join("project-config.json")).unwrap();+ }+ let original = recovery_snapshot(&project).unwrap();+ let original_state = recovery_publication_state(&project).unwrap();+ let staged_state =+ recovery_publication_state(&workspace.join("staged")).unwrap();+ interrupt_publication_rollback(+ &project,+ &workspace,+ failure,+ interruption,+ before_rename,+ );+ let lock = RecoveryLock::acquire(&project).unwrap();+ let current = recovery_publication_state(&project).unwrap();+ assert_eq!(current.meta, original_state.meta);+ assert!(+ current.segments == original_state.segments+ || current.segments == staged_state.segments+ );+ let raw = if project.join("content/segments/raw.m4s").is_file() {+ project.join("content/segments")+ } else {+ workspace.join("original-segments")+ };+ for (path, bytes) in &original {+ if let (Ok(relative), Some(bytes)) =+ (path.strip_prefix("content/segments"), bytes)+ {+ let actual_digest = sha2::Sha256::digest(+ std::fs::read(raw.join(relative)).unwrap(),+ )+ .to_vec();+ assert_eq!(&actual_digest, bytes);+ }+ }+ assert!(!project.join(RECOVERY_PUBLICATION).exists());+ assert!(workspace.join(RECOVERY_PUBLICATION_RECEIPT).is_file());+ drop(lock);+ let before_scan = recovery_snapshot(&project).unwrap();+ let found = RecoveryManager::find_incomplete(temporary.path());+ assert_eq!(found.len(), 1);+ assert!(matches!(+ found[0].meta.studio_meta().unwrap().status(),+ StudioRecordingStatus::NeedsRemux+ ));+ assert_eq!(recovery_snapshot(&project).unwrap(), before_scan);+ let _lock = RecoveryLock::acquire(&project).unwrap();+ assert_eq!(recovery_snapshot(&project).unwrap(), before_scan);+ }+ }+ }+ }+ }++ #[test]+ fn fully_restored_rollback_finishes_its_journal_without_changing_originals() {+ for had_config in [false, true] {+ let (temporary, project, workspace) = scannable_publication_fixture();+ if !had_config {+ std::fs::remove_file(project.join("project-config.json")).unwrap();+ }+ let original = recovery_snapshot(&project).unwrap();+ interrupt_publication_rollback(+ &project,+ &workspace,+ 4,+ if had_config { 7 } else { 6 },+ false,+ );+ assert_eq!(recovery_snapshot(&project).unwrap(), original);+ assert!(!workspace.join("original-segments").exists());+ assert!(!workspace.join("original-project-config.json").exists());+ assert!(!workspace.join("staged/project-config.json").exists());+ assert_eq!(RecoveryManager::find_incomplete(temporary.path()).len(), 1);+ assert_eq!(recovery_snapshot(&project).unwrap(), original);+ assert!(!project.join(RECOVERY_PUBLICATION).exists());+ assert!(workspace.join(RECOVERY_PUBLICATION_RECEIPT).is_file());+ assert!(RecoveryManager::inspect_recording(&project).is_some());+ assert!(RecoveryManager::find_incomplete_single(&project).is_some());+ assert_eq!(recovery_snapshot(&project).unwrap(), original);+ }+ }++ #[test]+ fn rollback_layout_still_refuses_conflicts_and_changed_generation_evidence() {+ for had_config in [false, true] {+ for changed in ["canonical", "metadata", "config", "staged", "receipt"] {+ let (temporary, project, workspace) = scannable_publication_fixture();+ if !had_config {+ std::fs::remove_file(project.join("project-config.json")).unwrap();+ }+ interrupt_publication_rollback(+ &project,+ &workspace,+ 4,+ if had_config { 6 } else { 5 },+ false,+ );+ match changed {+ "canonical" => {+ std::fs::create_dir(project.join("content/segments")).unwrap();+ std::fs::write(project.join("content/segments/unrelated"), b"unrelated")+ .unwrap();+ }+ "metadata" => {+ let mut meta = RecordingMeta::load_for_project(&project).unwrap();+ meta.pretty_name = "Different recording generation".into();+ meta.save_for_project().unwrap();+ }+ "config" => std::fs::write(+ project.join("project-config.json"),+ b"different configuration",+ )+ .unwrap(),+ "staged" => std::fs::write(+ workspace.join("staged/content/segments/display.mp4"),+ b"different staged data",+ )+ .unwrap(),+ "receipt" => std::fs::write(+ workspace.join(RECOVERY_PUBLICATION_RECEIPT),+ b"different receipt",+ )+ .unwrap(),+ _ => unreachable!(),+ }+ let before = recovery_snapshot(&project).unwrap();+ assert!(RecoveryLock::acquire(&project).is_err());+ assert!(RecoveryManager::find_incomplete(temporary.path()).is_empty());+ assert_eq!(recovery_snapshot(&project).unwrap(), before);+ assert_eq!(+ std::fs::read(workspace.join("original-segments/raw.m4s")).unwrap(),+ b"original raw"+ );+ assert!(project.join(RECOVERY_PUBLICATION).is_file());+ assert!(matches!(+ RecordingMeta::load_for_project(&project)+ .unwrap()+ .studio_meta()+ .unwrap()+ .status(),+ StudioRecordingStatus::NeedsRemux+ ));+ }+ }+ }++ #[test]+ fn interrupted_publication_reconciles_every_completed_rename_without_inventing_status() {+ for after in 0..=4 {+ let (_temporary, project, workspace) = publication_fixture();+ let original = recovery_snapshot(&project).unwrap();+ interrupt_publication(&project, &workspace, after);+ let _lock = RecoveryLock::acquire(&project).unwrap();+ assert!(!project.join(RECOVERY_PUBLICATION).exists());+ assert!(workspace.join(RECOVERY_PUBLICATION_RECEIPT).is_file());+ if after <= 1 {+ assert_eq!(recovery_snapshot(&project).unwrap(), original);+ } else {+ assert_eq!(+ std::fs::read(project.join("content/segments/display.mp4")).unwrap(),+ b"validated output"+ );+ assert_eq!(+ std::fs::read(workspace.join("original-segments/raw.m4s")).unwrap(),+ b"original raw"+ );+ }+ assert_eq!(+ std::fs::read(project.join("recording-meta.json")).unwrap(),+ if after < 4 {+ &b"original status"[..]+ } else {+ &b"complete"[..]+ }+ );+ }+ }++ #[test]+ fn relaunch_scan_restores_first_rename_and_keeps_recording_recoverable() {+ let (temporary, project, workspace) = scannable_publication_fixture();+ let original = recovery_snapshot(&project).unwrap();+ interrupt_publication(&project, &workspace, 1);+ assert!(!project.join("content/segments").exists());+ let found = RecoveryManager::find_incomplete(temporary.path());+ assert_eq!(found.len(), 1);+ assert_eq!(found[0].project_path, project);+ assert!(matches!(+ found[0].meta.studio_meta().unwrap().status(),+ StudioRecordingStatus::NeedsRemux+ ));+ assert_eq!(recovery_snapshot(&project).unwrap(), original);+ assert!(RecoveryManager::inspect_recording(&project).is_some());+ assert!(RecoveryManager::find_incomplete_single(&project).is_some());+ }++ #[test]+ fn relaunch_after_segments_install_retains_canonical_data_and_original_status() {+ for after in [2, 3] {+ let (temporary, project, workspace) = scannable_publication_fixture();+ let original_meta = std::fs::read(project.join("recording-meta.json")).unwrap();+ interrupt_publication(&project, &workspace, after);+ let before_scan = recovery_snapshot(&project).unwrap();+ assert_eq!(RecoveryManager::find_incomplete(temporary.path()).len(), 1);+ assert_eq!(recovery_snapshot(&project).unwrap(), before_scan);+ assert_eq!(+ std::fs::read(project.join("recording-meta.json")).unwrap(),+ original_meta+ );+ assert!(workspace.join("original-segments/raw.m4s").is_file());+ assert!(workspace.join(RECOVERY_PUBLICATION_RECEIPT).is_file());+ }+ }++ #[test]+ fn interrupted_restoration_is_idempotent_and_receipt_generation_must_match() {+ let (_temporary, project, workspace) = publication_fixture();+ let original = recovery_snapshot(&project).unwrap();+ interrupt_publication(&project, &workspace, 1);+ std::fs::rename(+ workspace.join("original-segments"),+ project.join("content/segments"),+ )+ .unwrap();+ let receipt = workspace.join(RECOVERY_PUBLICATION_RECEIPT);+ let bytes = std::fs::read(&receipt).unwrap();+ std::fs::write(&receipt, b"different generation").unwrap();+ assert!(RecoveryLock::acquire(&project).is_err());+ assert_eq!(recovery_snapshot(&project).unwrap(), original);+ assert!(project.join(RECOVERY_PUBLICATION).is_file());+ std::fs::write(receipt, bytes).unwrap();+ let _lock = RecoveryLock::acquire(&project).unwrap();+ assert_eq!(recovery_snapshot(&project).unwrap(), original);+ assert!(!project.join(RECOVERY_PUBLICATION).exists());+ }++ #[test]+ fn interrupted_publication_without_original_config_preserves_that_state() {+ for after in 0..=3 {+ let (_temporary, project, workspace) = publication_fixture();+ std::fs::remove_file(project.join("project-config.json")).unwrap();+ interrupt_publication(&project, &workspace, after);+ let _lock = RecoveryLock::acquire(&project).unwrap();+ assert_eq!(project.join("project-config.json").exists(), after == 3);+ assert_eq!(+ std::fs::read(project.join("recording-meta.json")).unwrap(),+ b"original status"+ );+ }+ }++ #[test]+ fn interrupted_publication_never_overwrites_conflicting_canonical_segments() {+ for conflicting_file in [false, true] {+ let (_temporary, project, workspace) = publication_fixture();+ interrupt_publication(&project, &workspace, 1);+ std::fs::create_dir(project.join("content/segments")).unwrap();+ if conflicting_file {+ std::fs::write(project.join("content/segments/unrelated"), b"unrelated").unwrap();+ }+ let before = recovery_snapshot(&project).unwrap();+ assert!(RecoveryLock::acquire(&project).is_err());+ assert_eq!(recovery_snapshot(&project).unwrap(), before);+ assert_eq!(+ std::fs::read(workspace.join("original-segments/raw.m4s")).unwrap(),+ b"original raw"+ );+ assert!(project.join(RECOVERY_PUBLICATION).is_file());+ }+ }++ #[test]+ fn stale_publication_metadata_or_tree_keeps_evidence_and_does_not_mark_failed() {+ for changed in ["recording-meta.json", "original-segments/raw.m4s"] {+ let (temporary, project, workspace) = scannable_publication_fixture();+ interrupt_publication(&project, &workspace, 1);+ let target = if changed == "recording-meta.json" {+ let mut meta = RecordingMeta::load_for_project(&project).unwrap();+ meta.pretty_name = "A later recording generation".into();+ meta.save_for_project().unwrap();+ project.join(changed)+ } else {+ let target = workspace.join(changed);+ std::fs::write(&target, b"changed raw bytes").unwrap();+ target+ };+ let bytes = std::fs::read(&target).unwrap();+ assert!(RecoveryLock::acquire(&project).is_err());+ assert!(RecoveryManager::find_incomplete(temporary.path()).is_empty());+ assert_eq!(std::fs::read(target).unwrap(), bytes);+ assert!(matches!(+ RecordingMeta::load_for_project(&project)+ .unwrap()+ .studio_meta()+ .unwrap()+ .status(),+ StudioRecordingStatus::NeedsRemux+ ));+ assert!(!project.join("content/segments").exists());+ assert!(project.join(RECOVERY_PUBLICATION).is_file());+ }+ }++ #[test]+ fn invalid_or_wrong_generation_receipts_cannot_select_a_workspace() {+ for value in [+ "invalid-json",+ "version",+ "generation",+ "project",+ "escape",+ "oversized",+ ] {+ let (_temporary, project, workspace) = publication_fixture();+ interrupt_publication(&project, &workspace, 1);+ let path = project.join(RECOVERY_PUBLICATION);+ let mut receipt: RecoveryPublication =+ serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ let bytes = match value {+ "invalid-json" => b"{".to_vec(),+ "oversized" => vec![0; RECOVERY_PUBLICATION_MAX_BYTES as usize + 1],+ _ => {+ match value {+ "version" => receipt.version = 2,+ "generation" => {+ receipt.workspace = format!(".recovery-{}", uuid::Uuid::new_v4())+ }+ "project" => receipt.project = project.join("other"),+ "escape" => receipt.workspace = "../outside".into(),+ _ => unreachable!(),+ }+ serde_json::to_vec(&receipt).unwrap()+ }+ };+ std::fs::write(&path, &bytes).unwrap();+ assert!(RecoveryLock::acquire(&project).is_err());+ assert_eq!(std::fs::read(path).unwrap(), bytes);+ assert_eq!(+ std::fs::read(workspace.join("original-segments/raw.m4s")).unwrap(),+ b"original raw"+ );+ assert!(!project.join("content/segments").exists());+ }+ }++ #[test]+ fn legacy_workspaces_without_receipts_are_not_guessed_or_deleted() {+ let (temporary, project, workspace) = scannable_publication_fixture();+ assert_eq!(RecoveryManager::find_incomplete(temporary.path()).len(), 1);+ std::fs::rename(+ project.join("content/segments"),+ workspace.join("original-segments"),+ )+ .unwrap();+ let original_meta = std::fs::read(project.join("recording-meta.json")).unwrap();+ assert!(RecoveryManager::find_incomplete(temporary.path()).is_empty());+ assert_eq!(+ std::fs::read(project.join("recording-meta.json")).unwrap(),+ original_meta+ );+ assert!(workspace.join("original-segments/raw.m4s").is_file());+ }++ #[cfg(unix)]+ #[test]+ fn publication_reconciliation_refuses_symlinked_receipts_and_workspace_entries() {+ use std::os::unix::fs::symlink;+ for target in ["receipt", "workspace", "segments", "metadata", "content"] {+ let (temporary, project, workspace) = publication_fixture();+ interrupt_publication(&project, &workspace, 1);+ let source = match target {+ "receipt" => project.join(RECOVERY_PUBLICATION),+ "workspace" => workspace.clone(),+ "segments" => workspace.join("original-segments"),+ "metadata" => workspace.join("original-recording-meta.json"),+ "content" => project.join("content"),+ _ => unreachable!(),+ };+ let outside = temporary.path().join("outside");+ std::fs::rename(&source, &outside).unwrap();+ symlink(&outside, &source).unwrap();+ assert!(RecoveryLock::acquire(&project).is_err());+ assert!(source.symlink_metadata().unwrap().file_type().is_symlink());+ assert!(outside.exists());+ }+ }++ #[test]+ fn recovery_publication_rolls_back_each_failed_rename() {+ for failure in 1..=4 {+ let (_temporary, project, workspace) = publication_fixture();+ let before = recovery_snapshot(&project).unwrap();+ let mut calls = 0;+ let result = publish_recovery_with(&project, &workspace, |source, destination| {+ calls += 1;+ if calls == failure {+ return Err(std::io::Error::other("injected publication failure"));+ }+ std::fs::rename(source, destination)+ });+ assert!(result.is_err());+ assert_eq!(recovery_snapshot(&project).unwrap(), before);+ assert_eq!(+ std::fs::read(project.join("recording-meta.json")).unwrap(),+ b"original status"+ );+ }+ }++ #[test]+ fn recovery_scan_cannot_mark_failed_during_publication_rollback() {+ let (temporary, project, workspace) = publication_fixture();+ let meta = RecordingMeta {+ platform: None,+ project_path: project.clone(),+ pretty_name: "Publication scan race".into(),+ sharing: None,+ upload: None,+ inner: RecordingMetaInner::Studio(Box::new(StudioRecordingMeta::MultipleSegments {+ inner: MultipleSegments {+ segments: Vec::new(),+ cursors: Cursors::default(),+ status: Some(StudioRecordingStatus::NeedsRemux),+ },+ })),+ };+ meta.save_for_project().unwrap();+ let before = recovery_snapshot(&project).unwrap();+ let _lock = RecoveryLock::acquire(&project).unwrap();+ let mut calls = 0;+ let result = publish_recovery_with(&project, &workspace, |source, destination| {+ calls += 1;+ if calls == 2 {+ assert!(!project.join("content/segments").exists());+ assert!(RecoveryManager::find_incomplete(temporary.path()).is_empty());+ return Err(std::io::Error::other("injected install failure after scan"));+ }+ std::fs::rename(source, destination)+ });+ assert!(result.is_err());+ assert_eq!(recovery_snapshot(&project).unwrap(), before);+ let meta = RecordingMeta::load_for_project(&project).unwrap();+ assert!(matches!(+ meta.studio_meta().unwrap().status(),+ StudioRecordingStatus::NeedsRemux+ ));+ }++ #[test]+ fn recovery_rollback_failure_retains_original_raw_and_status() {+ let (_temporary, project, workspace) = publication_fixture();+ let mut calls = 0;+ let result = publish_recovery_with(&project, &workspace, |source, destination| {+ calls += 1;+ if calls == 4 || calls == 6 {+ return Err(std::io::Error::other(+ "injected rename and rollback failure",+ ));+ }+ std::fs::rename(source, destination)+ });+ assert!(result.unwrap_err().to_string().contains("rollback failed"));+ assert_eq!(+ std::fs::read(workspace.join("original-segments/raw.m4s")).unwrap(),+ b"original raw"+ );+ assert_eq!(+ std::fs::read(project.join("recording-meta.json")).unwrap(),+ b"original status"+ );+ assert_eq!(+ std::fs::read(workspace.join("original-recording-meta.json")).unwrap(),+ b"original status"+ );+ }++ #[test]+ fn recovery_publication_commits_metadata_last_and_retains_backup_until_success() {+ let (_temporary, project, workspace) = publication_fixture();+ let mut calls = 0;+ publish_recovery_with(&project, &workspace, |source, destination| {+ calls += 1;+ assert_eq!(+ std::fs::read(project.join("recording-meta.json")).unwrap(),+ b"original status"+ );+ if calls > 1 {+ assert_eq!(+ std::fs::read(workspace.join("original-segments/raw.m4s")).unwrap(),+ b"original raw"+ );+ }+ if calls == 4 {+ assert_eq!(destination, project.join("recording-meta.json"));+ }+ std::fs::rename(source, destination)+ })+ .unwrap();+ assert_eq!(calls, 4);+ assert_eq!(+ std::fs::read(project.join("recording-meta.json")).unwrap(),+ b"complete"+ );+ assert!(workspace.join("original-segments/raw.m4s").is_file());+ assert!(project.join("content/segments/display.mp4").is_file());+ }++ #[test]+ fn recovery_copy_refuses_existing_destination_and_preserves_source() {+ let dir = tempfile::tempdir().unwrap();+ let source = dir.path().join("raw");+ let destination = dir.path().join("occupied");+ std::fs::write(&source, b"original").unwrap();+ std::fs::write(&destination, b"existing").unwrap();+ assert!(copy_recovery_input(&source, &destination).is_err());+ assert_eq!(std::fs::read(&source).unwrap(), b"original");+ assert_eq!(std::fs::read(&destination).unwrap(), b"existing");+ }++ #[test]+ fn recovery_lock_refuses_concurrent_attempt_without_touching_first_lock() {+ let dir = tempfile::tempdir().unwrap();+ let lock = RecoveryLock::acquire(dir.path()).unwrap();+ assert!(RecoveryLock::acquire(dir.path()).is_err());+ assert!(dir.path().join(".recovery.lock").exists());+ drop(lock);+ assert!(dir.path().join(".recovery.lock").exists());+ let reacquired = RecoveryLock::acquire(dir.path()).unwrap();+ drop(reacquired);+ }++ #[test]+ fn recovery_manifest_paths_cannot_escape_the_track_directory() {+ let dir = Path::new("content/segments/segment-0/display");+ for name in [+ "",+ "../original.mp4",+ "/outside.mp4",+ "nested/../../outside.mp4",+ ] {+ assert!(recovery_child_path(dir, name).is_none());+ }+ assert_eq!(+ recovery_child_path(dir, "segment_0.m4s"),+ Some(dir.join("segment_0.m4s"))+ );+ }++ #[cfg(unix)]+ #[test]+ fn recovery_rejects_symlinks_and_creates_private_workspace() {+ use std::os::unix::fs::{PermissionsExt, symlink};+ let dir = tempfile::tempdir().unwrap();+ let outside = dir.path().join("outside");+ std::fs::write(&outside, b"outside").unwrap();+ let project = dir.path().join("project");+ create_private_recovery_dir(&project).unwrap();+ assert_eq!(+ std::fs::metadata(&project).unwrap().permissions().mode() & 0o777,+ 0o700+ );+ symlink(&outside, project.join("content")).unwrap();+ assert!(recovery_snapshot(&project).is_err());+ assert!(copy_recovery_input(&project.join("content"), &project.join("copy")).is_err());+ assert_eq!(std::fs::read(&outside).unwrap(), b"outside");+ }+ #[test]+ fn recovery_declared_complete_missing_or_corrupt_fragment_is_not_skipped() {+ let dir = tempfile::tempdir().unwrap();+ let manifest = dir.path().join("manifest.json");+ std::fs::write(+ &manifest,+ br#"{"fragments":[{"path":"missing.mp4","is_complete":true,"file_size":10}]}"#,+ )+ .unwrap();+ assert!(validate_recovery_manifests(dir.path()).is_err());+ std::fs::write(dir.path().join("missing.mp4"), b"short").unwrap();+ assert!(validate_recovery_manifests(dir.path()).is_err());+ std::fs::write(+ &manifest,+ br#"{"init_segment":"../outside.mp4","fragments":[]}"#,+ )+ .unwrap();+ assert!(validate_recovery_manifests(dir.path()).is_err());+ }++ #[test]+ fn recovery_source_snapshot_detects_bytes_and_whole_segment_changes() {+ let (_temporary, project, _workspace) = publication_fixture();+ let before = recovery_snapshot(&project).unwrap();+ std::fs::write(project.join("content/segments/raw.m4s"), b"different raw").unwrap();+ assert_ne!(recovery_snapshot(&project).unwrap(), before);+ std::fs::write(project.join("content/segments/raw.m4s"), b"original raw").unwrap();+ assert_eq!(recovery_snapshot(&project).unwrap(), before);+ std::fs::create_dir(project.join("content/segments/segment-1")).unwrap();+ assert_ne!(recovery_snapshot(&project).unwrap(), before);+ }+ #[test]+ fn recovery_lock_child_probe() {+ let Some(path) = std::env::var_os("CAP_RECOVERY_LOCK_CHILD") else {+ return;+ };+ let project = PathBuf::from(path);+ let _lock = RecoveryLock::acquire(&project).unwrap();+ std::fs::write(project.join("child-ready"), b"ready").unwrap();+ std::thread::sleep(Duration::from_secs(10));+ }++ #[test]+ fn recovery_kernel_lock_releases_after_child_process_death() {+ struct Child(std::process::Child);+ impl Drop for Child {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+ }+ let directory = tempfile::tempdir().unwrap();+ let mut child = Child(+ std::process::Command::new(std::env::current_exe().unwrap())+ .args([+ "--exact",+ "recovery::transactional_recovery_tests::recovery_lock_child_probe",+ "--nocapture",+ ])+ .env("CAP_RECOVERY_LOCK_CHILD", directory.path())+ .stdout(std::process::Stdio::null())+ .spawn()+ .unwrap(),+ );+ let deadline = std::time::Instant::now() + Duration::from_secs(5);+ while !directory.path().join("child-ready").exists() && std::time::Instant::now() < deadline+ {+ assert!(+ child.0.try_wait().unwrap().is_none(),+ "lock probe exited before acquisition"+ );+ std::thread::sleep(Duration::from_millis(10));+ }+ assert!(directory.path().join("child-ready").exists());+ assert!(RecoveryLock::acquire(directory.path()).is_err());+ child.0.kill().unwrap();+ child.0.wait().unwrap();+ let recovered = RecoveryLock::acquire(directory.path()).unwrap();+ assert_eq!(+ std::fs::read(directory.path().join(".recovery.lock")).unwrap(),+ b""+ );+ drop(recovered);+ }+}diff --git a/crates/recording/src/sources/audio_mixer.rs b/crates/recording/src/sources/audio_mixer.rsindex 159587ba7..f4d0b8cce 100644--- a/crates/recording/src/sources/audio_mixer.rs+++ b/crates/recording/src/sources/audio_mixer.rs@@ -1,3 +1,4 @@+use anyhow::Context as _;use cap_media_info::AudioInfo;use cap_timestamp::{MasterClock, SourceClockOutcome, SourceClockState, Timestamp, Timestamps};use futures::channel::{mpsc, oneshot};@@ -10,6 +11,7 @@ use std::{},time::Duration,};+use tokio_util::sync::CancellationToken;use tracing::{debug, info, warn};use crate::output_pipeline::{AudioFrame, HealthSender, PipelineHealthEvent, emit_health};@@ -43,6 +45,7 @@ pub struct AudioMixerBuilder {timestamps: Option<Timestamps>,master_clock: Option<Arc<MasterClock>>,health_tx: Option<HealthSender>,+ required_stop: Option<CancellationToken>,}impl Default for AudioMixerBuilder {@@ -58,6 +61,7 @@ impl AudioMixerBuilder {timestamps: None,master_clock: None,health_tx: None,+ required_stop: None,}}@@ -76,6 +80,11 @@ impl AudioMixerBuilder {self}+ pub(crate) fn with_required_inputs(mut self, stop: CancellationToken) -> Self {+ self.required_stop = Some(stop);+ self+ }+pub fn has_sources(&self) -> bool {!self.sources.is_empty()}@@ -129,6 +138,7 @@ impl AudioMixerBuilder {master_clock,buffering: MixerBufferingTracker::new(),health_tx: self.health_tx,+ required_stop: self.required_stop,})}@@ -137,22 +147,28 @@ impl AudioMixerBuilder {output: mpsc::Sender<AudioFrame>,ready_tx: oneshot::Sender<anyhow::Result<()>>,stop_flag: Arc<AtomicBool>,- ) {+ ) -> anyhow::Result<()> {let start = Timestamps::now();let mut mixer = match self.build(output) {Ok(mixer) => mixer,Err(e) => {tracing::error!("Failed to build audio mixer: {}", e);- let _ = ready_tx.send(Err(e.into()));- return;+ let message = format!("Failed to build audio mixer: {e}");+ let _ = ready_tx.send(Err(anyhow::anyhow!(message.clone())));+ return Err(anyhow::anyhow!(message));}};let _ = ready_tx.send(Ok(()));loop {- if stop_flag.load(Ordering::Relaxed) {+ if stop_flag.load(Ordering::Relaxed)+ || mixer+ .required_stop+ .as_ref()+ .is_some_and(CancellationToken::is_cancelled)+ {info!("Mixer stop flag triggered");break;}@@ -165,13 +181,14 @@ impl AudioMixerBuilder {#[cfg(not(any(target_os = "macos", windows)))]let now = Timestamp::Instant(Instant::now());- if let Err(()) = mixer.tick(start, now) {- info!("Mixer tick errored");+ if !mixer.tick(start, now)? {+ info!("Mixer output closed");break;}std::thread::sleep(Duration::from_millis(5));}+ Ok(())}}@@ -193,6 +210,7 @@ pub struct AudioMixer {master_clock: Arc<MasterClock>,buffering: MixerBufferingTracker,health_tx: Option<HealthSender>,+ required_stop: Option<CancellationToken>,}#[derive(Debug, Clone)]@@ -377,7 +395,7 @@ impl AudioMixer {index: usize,old_info: AudioInfo,new_info: AudioInfo,- ) {+ ) -> anyhow::Result<()> {let label = self.sources.get(index)@@ -428,8 +446,14 @@ impl AudioMixer {error = %e,"AudioMixer: failed to rebuild filter graph after source format change");+ if self.required_stop.is_some() {+ return Err(e).with_context(|| {+ format!("Audio mixer source {index} filter rebuild failed")+ });+ }}}+ Ok(())}fn force_reset_source(&mut self, source_label: &'static str, starvation_ms: u64) {@@ -470,18 +494,30 @@ impl AudioMixer {start_timestamp + Duration::from_nanos(clamped)}- fn buffer_sources(&mut self, now: Timestamp) {+ fn buffer_sources(&mut self, now: Timestamp) -> anyhow::Result<()> {let mut format_change: Option<(usize, AudioInfo, AudioInfo)> = None;let clock_anchor = self.master_clock.timestamps().instant();for (index, source) in self.sources.iter_mut().enumerate() {let rate = source.info.rate();let buffer_timeout = source.buffer_timeout;- while let Ok(Some(AudioFrame {- inner: frame,- timestamp: raw_timestamp,- })) = source.rx.try_next()- {+ loop {+ let AudioFrame {+ inner: frame,+ timestamp: raw_timestamp,+ } = match source.rx.try_next() {+ Ok(Some(frame)) => frame,+ Ok(None) => {+ anyhow::ensure!(+ self.required_stop+ .as_ref()+ .is_none_or(|stop| stop.is_cancelled()),+ "Required audio mixer source {index} closed while capture was active"+ );+ break;+ }+ Err(_) => break,+ };source.last_input_timestamp = Some(raw_timestamp);if format_change.is_none()@@ -575,7 +611,7 @@ impl AudioMixer {}if let Some((index, old_info, new_info)) = format_change {- self.handle_source_format_change(index, old_info, new_info);+ self.handle_source_format_change(index, old_info, new_info)?;}if self.start_timestamp.is_none() {@@ -637,13 +673,25 @@ impl AudioMixer {}}}+ Ok(())}- fn tick(&mut self, _start: Timestamps, now: Timestamp) -> Result<(), ()> {- self.buffer_sources(now);+ fn tick(&mut self, _start: Timestamps, now: Timestamp) -> anyhow::Result<bool> {+ self.tick_with_output(now, |sink, frame| sink.sink().frame(frame))+ }++ fn tick_with_output(+ &mut self,+ now: Timestamp,+ mut read: impl FnMut(+ &mut ffmpeg::filter::Context,+ &mut ffmpeg::frame::Audio,+ ) -> Result<(), ffmpeg::Error>,+ ) -> anyhow::Result<bool> {+ self.buffer_sources(now)?;let Some(start_timestamp) = self.start_timestamp else {- return Ok(());+ return Ok(true);};let wall_now = Instant::now();@@ -662,12 +710,33 @@ impl AudioMixer {for (i, source) in self.sources.iter_mut().enumerate() {for buffer in source.buffer.drain(..) {- let _ = self.abuffers[i].source().add(&buffer.inner);+ let result = self.abuffers[i].source().add(&buffer.inner);+ if self.required_stop.is_some() {+ result+ .with_context(|| format!("Audio mixer source {i} filter input failed"))?;+ }}}let mut filtered = ffmpeg::frame::Audio::empty();- while self.abuffersink.sink().frame(&mut filtered).is_ok() {+ loop {+ match read(&mut self.abuffersink, &mut filtered) {+ Ok(()) => {}+ Err(ffmpeg::Error::Eof) => {+ anyhow::ensure!(+ self.required_stop+ .as_ref()+ .is_none_or(|stop| stop.is_cancelled()),+ "Required audio mixer filter ended while capture was active"+ );+ break;+ }+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::error::EAGAIN => break,+ Err(error) if self.required_stop.is_some() => {+ return Err(error).context("Audio mixer filter output failed");+ }+ Err(_) => break,+ }let output_rate_i32 = Self::INFO.rate();filtered.set_rate(output_rate_i32 as u32);@@ -684,7 +753,7 @@ impl AudioMixer {frame = err.into_inner();std::thread::sleep(Duration::from_millis(1));}- Err(_) => return Err(()),+ Err(_) => return Ok(false),}}@@ -694,7 +763,7 @@ impl AudioMixer {self.last_tick = Some(now);- Ok(())+ Ok(true)}pub fn builder() -> AudioMixerBuilder {@@ -940,6 +1009,207 @@ mod test {assert_eq!(samples[4], samples[5]);}+ fn mixer_fixture(+ strict: bool,+ ) -> (+ AudioMixer,+ Vec<mpsc::Sender<AudioFrame>>,+ mpsc::Receiver<AudioFrame>,+ ) {+ let (output, receiver) = mpsc::channel(4);+ let mut builder = AudioMixerBuilder::new();+ if strict {+ builder = builder.with_required_inputs(CancellationToken::new());+ }+ let mut senders = Vec::new();+ for _ in 0..2 {+ let (sender, receiver) = mpsc::channel(4);+ builder.add_source(SOURCE_INFO, receiver);+ senders.push(sender);+ }+ (builder.build(output).unwrap(), senders, receiver)+ }++ fn mixer_frame(now: Timestamp) -> AudioFrame {+ AudioFrame::new(SOURCE_INFO.wrap_frame(&[128, 255, 128, 1]), now)+ }++ #[test]+ fn strict_mixer_input_error_is_not_silent_but_legacy_still_degrades() {+ for strict in [false, true] {+ let (mut mixer, mut sources, _output) = mixer_fixture(strict);+ let now = Timestamp::Instant(mixer.timestamps.instant());+ let mut invalid = mixer_frame(now);+ invalid.inner.set_rate(0);+ sources[0].try_send(invalid).unwrap();+ sources[1].try_send(mixer_frame(now)).unwrap();+ let result = mixer.tick(mixer.timestamps, now);+ if strict {+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("source 0 filter input failed")+ );+ } else {+ assert!(result.unwrap());+ }+ }+ }++ #[test]+ fn strict_mixer_rebuild_error_propagates_from_actual_graph() {+ for strict in [false, true] {+ let (mut mixer, mut sources, _output) = mixer_fixture(strict);+ let now = Timestamp::Instant(mixer.timestamps.instant());+ let mut invalid = mixer_frame(now);+ invalid.inner.set_rate(u32::MAX);+ sources[0].try_send(invalid).unwrap();+ sources[1].try_send(mixer_frame(now)).unwrap();+ let result = mixer.tick(mixer.timestamps, now);+ if strict {+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("source 0 filter rebuild failed")+ );+ } else {+ assert!(result.unwrap());+ }+ }+ }++ #[test]+ fn strict_mixer_real_empty_and_eof_reads_are_not_errors() {+ let (mut mixer, _sources, _output) = mixer_fixture(true);+ let now = Timestamp::Instant(mixer.timestamps.instant());+ mixer.start_timestamp = Some(now);+ let mut observed_empty = false;+ assert!(mixer.tick_with_output(now, |sink, frame| {+ let result = sink.sink().frame(frame);+ observed_empty = matches!(result, Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::error::EAGAIN);+ result+ }).unwrap());+ assert!(observed_empty);+ for source in &mut mixer.abuffers {+ source.source().flush().unwrap();+ }+ assert!(+ mixer+ .tick(mixer.timestamps, now)+ .unwrap_err()+ .to_string()+ .contains("filter ended")+ );+ mixer.required_stop.as_ref().unwrap().cancel();+ let mut observed_eof = false;+ assert!(+ mixer+ .tick_with_output(now, |sink, frame| {+ let result = sink.sink().frame(frame);+ observed_eof = matches!(result, Err(ffmpeg::Error::Eof));+ result+ })+ .unwrap()+ );+ assert!(observed_eof);+ }++ #[test]+ fn strict_mixer_output_failure_uses_the_real_drain_loop() {+ for strict in [false, true] {+ let (mut mixer, mut sources, _output) = mixer_fixture(strict);+ let now = Timestamp::Instant(mixer.timestamps.instant());+ for source in &mut sources {+ source.try_send(mixer_frame(now)).unwrap();+ }+ let mut decoded = false;+ let result = mixer.tick_with_output(now, |sink, frame| {+ sink.sink().frame(frame)?;+ decoded = true;+ Err(ffmpeg::Error::InvalidData)+ });+ assert!(decoded);+ if strict {+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("filter output failed")+ );+ } else {+ assert!(result.unwrap());+ }+ }+ }++ #[test]+ fn strict_mixer_distinguishes_open_empty_and_closed_requested_inputs() {+ for strict in [false, true] {+ let (mut mixer, mut sources, _output) = mixer_fixture(strict);+ let now = Timestamp::Instant(mixer.timestamps.instant());+ assert!(mixer.tick(mixer.timestamps, now).unwrap());+ drop(sources.remove(0));+ let result = mixer.tick(mixer.timestamps, now);+ if strict {+ assert!(result.unwrap_err().to_string().contains("source 0 closed"));+ } else {+ assert!(result.unwrap());+ }+ }+ }++ #[test]+ fn required_mixer_stop_token_precedes_async_stop_flag_and_input_close() {+ let (mut mixer, sources, _output) = mixer_fixture(true);+ let now = Timestamp::Instant(mixer.timestamps.instant());+ mixer.required_stop.as_ref().unwrap().cancel();+ drop(sources);+ assert!(mixer.tick(mixer.timestamps, now).unwrap());+ let stop = CancellationToken::new();+ let stop_flag = Arc::new(AtomicBool::new(false));+ let mut builder = AudioMixerBuilder::new().with_required_inputs(stop.clone());+ for _ in 0..2 {+ let (sender, receiver) = mpsc::channel(4);+ builder.add_source(SOURCE_INFO, receiver);+ drop(sender);+ }+ let (output, _receiver) = mpsc::channel(4);+ let (ready, _ready_rx) = oneshot::channel();+ stop.cancel();+ let flag = stop_flag.clone();+ let (complete, completed) = std::sync::mpsc::channel();+ let worker = std::thread::spawn(move || {+ let _ = complete.send(builder.run(output, ready, flag));+ });+ let result = completed.recv_timeout(Duration::from_secs(1));+ if result.is_err() {+ stop_flag.store(true, Ordering::Release);+ }+ worker.join().unwrap();+ result.unwrap().unwrap();+ assert!(!stop_flag.load(Ordering::Acquire));+ }++ #[test]+ fn strict_mixer_valid_output_and_closed_consumer_remain_clean() {+ for close_output in [false, true] {+ let (mut mixer, mut sources, mut output) = mixer_fixture(true);+ let now = Timestamp::Instant(mixer.timestamps.instant());+ for source in &mut sources {+ source.try_send(mixer_frame(now)).unwrap();+ }+ if close_output {+ output.close();+ }+ assert_eq!(mixer.tick(mixer.timestamps, now).unwrap(), !close_output);+ if !close_output {+ assert!(output.try_next().unwrap().is_some());+ }+ }+ }+mod buffering_tracker {use super::*;use crate::output_pipeline::{HealthReceiver, HealthSender};@@ -1121,7 +1391,9 @@ mod test {.await.unwrap();- mixer.buffer_sources(Timestamp::Instant(start.instant()));+ mixer+ .buffer_sources(Timestamp::Instant(start.instant()))+ .unwrap();assert_eq!(mixer.sources[0].buffer.len(), 1);assert!(mixer.sources[0].rx.try_next().is_err());@@ -1151,7 +1423,9 @@ mod test {.await.unwrap();- mixer.buffer_sources(Timestamp::Instant(mixer.timestamps.instant()));+ mixer+ .buffer_sources(Timestamp::Instant(mixer.timestamps.instant()))+ .unwrap();let source = &mut mixer.sources[0];@@ -1183,7 +1457,9 @@ mod test {.await.unwrap();- mixer.buffer_sources(Timestamp::Instant(start.instant()));+ mixer+ .buffer_sources(Timestamp::Instant(start.instant()))+ .unwrap();let source = &mut mixer.sources[0];@@ -1215,7 +1491,9 @@ mod test {.await.unwrap();- mixer.buffer_sources(Timestamp::Instant(start.instant()));+ mixer+ .buffer_sources(Timestamp::Instant(start.instant()))+ .unwrap();mixer.sources[0].buffer.clear();@@ -1226,7 +1504,9 @@ mod test {.await.unwrap();- mixer.buffer_sources(Timestamp::Instant(start.instant() + ONE_SECOND));+ mixer+ .buffer_sources(Timestamp::Instant(start.instant() + ONE_SECOND))+ .unwrap();let source = &mut mixer.sources[0];@@ -1261,7 +1541,9 @@ mod test {.await.unwrap();}- mixer.buffer_sources(Timestamp::Instant(start.instant() + ONE_SECOND));+ mixer+ .buffer_sources(Timestamp::Instant(start.instant() + ONE_SECOND))+ .unwrap();let initial_len = mixer.sources[0].buffer.len();assert!(initial_len >= 4,@@ -1276,7 +1558,7 @@ mod test {)).await.unwrap();- mixer.buffer_sources(far_future);+ mixer.buffer_sources(far_future).unwrap();let post_reset_len = mixer.sources[0].buffer.len();assert_eq!(diff --git a/crates/recording/src/sources/camera.rs b/crates/recording/src/sources/camera.rsindex 7470c6505..5a6ee33e4 100644--- a/crates/recording/src/sources/camera.rs+++ b/crates/recording/src/sources/camera.rs@@ -103,7 +103,7 @@ impl VideoSource for Camera {let scaled_frame_count = Arc::new(AtomicU64::new(0));let scaled_count_clone = scaled_frame_count.clone();- tokio::spawn(async move {+ crate::output_pipeline::spawn_capture_task(async move {tracing::debug!(original_width,original_height,diff --git a/crates/recording/src/sources/capture_clock.rs b/crates/recording/src/sources/capture_clock.rsnew file mode 100644index 000000000..433299293--- /dev/null+++ b/crates/recording/src/sources/capture_clock.rs@@ -0,0 +1,171 @@+use cap_timestamp::{Timestamp, Timestamps};+use std::time::{Duration, Instant};++const MAX_CAPTURE_CLOCK_SKEW: Duration = Duration::from_secs(5);++pub(crate) struct CaptureClock {+ reference: Timestamps,+ anchor: Option<(f64, Instant)>,+}++impl CaptureClock {+ pub(crate) fn new(reference: Timestamps) -> Self {+ Self {+ reference,+ anchor: None,+ }+ }++ pub(crate) fn timestamp(+ &mut self,+ captured: Timestamp,+ observed: Instant,+ buffer_duration: Duration,+ ) -> Timestamp {+ let source_seconds = captured.signed_duration_since_secs(self.reference);+ let observed_seconds = observed+ .saturating_duration_since(self.reference.instant())+ .as_secs_f64();++ if let Some((source_anchor, mapped_anchor)) = self.anchor {+ if let Ok(elapsed) = Duration::try_from_secs_f64(source_seconds - source_anchor)+ && let Some(mapped) = mapped_anchor.checked_add(elapsed)+ && mapped+ .saturating_duration_since(observed)+ .max(observed.saturating_duration_since(mapped))+ <= MAX_CAPTURE_CLOCK_SKEW+ {+ return Timestamp::Instant(mapped);+ }+ } else if (source_seconds - observed_seconds).abs() <= MAX_CAPTURE_CLOCK_SKEW.as_secs_f64()+ {+ return captured;+ } else {+ tracing::warn!(+ source_seconds,+ observed_seconds,+ "Device audio clock is outside the capture window; rebasing its timestamps"+ );+ }++ let mapped = observed.checked_sub(buffer_duration).unwrap_or(observed);+ self.anchor = Some((source_seconds, mapped));+ Timestamp::Instant(mapped)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn source_before(reference: Timestamps, seconds: u64) -> Timestamp {+ Timestamp::SystemTime(+ reference+ .system_time()+ .checked_sub(Duration::from_secs(seconds))+ .unwrap(),+ )+ }++ fn elapsed(timestamp: Timestamp, reference: Timestamps) -> Duration {+ timestamp.checked_duration_since(reference).unwrap()+ }++ #[test]+ fn valid_capture_latency_is_preserved() {+ let reference = Timestamps::now();+ let mut clock = CaptureClock::new(reference);+ let captured = Timestamp::Instant(reference.instant() + Duration::from_millis(20));+ let result = clock.timestamp(+ captured,+ reference.instant() + Duration::from_millis(80),+ Duration::from_millis(10),+ );++ assert_eq!(elapsed(result, reference), Duration::from_millis(20));+ assert!(clock.anchor.is_none());+ }++ #[test]+ fn invalid_device_epoch_preserves_a_continuous_audio_timeline() {+ let reference = Timestamps::now();+ let mut clock = CaptureClock::new(reference);+ let source = source_before(reference, 2_223_687_539);++ for packet in 0..1_000 {+ let offset = Duration::from_millis(packet * 10);+ let result = clock.timestamp(+ source + offset,+ reference.instant() + Duration::from_millis(100) + offset,+ Duration::from_millis(10),+ );+ let expected = Duration::from_millis(90) + offset;+ let actual = elapsed(result, reference);+ assert!(actual.abs_diff(expected) < Duration::from_micros(2));+ }+ assert!(clock.anchor.is_some());+ }++ #[test]+ fn rebased_clock_preserves_delayed_packets_and_capture_gaps() {+ let reference = Timestamps::now();+ let mut clock = CaptureClock::new(reference);+ let source = source_before(reference, 60);+ let first = clock.timestamp(+ source,+ reference.instant() + Duration::from_millis(100),+ Duration::from_millis(10),+ );+ let delayed = clock.timestamp(+ source + Duration::from_millis(10),+ reference.instant() + Duration::from_millis(600),+ Duration::from_millis(10),+ );+ let resumed = clock.timestamp(+ source + Duration::from_secs(10),+ reference.instant() + Duration::from_millis(10_100),+ Duration::from_millis(10),+ );++ assert_eq!(elapsed(first, reference), Duration::from_millis(90));+ assert!(+ elapsed(delayed, reference).abs_diff(Duration::from_millis(100))+ < Duration::from_micros(1)+ );+ assert!(+ elapsed(resumed, reference).abs_diff(Duration::from_millis(10_090))+ < Duration::from_micros(1)+ );+ }++ #[test]+ fn a_clock_reset_reanchors_without_retaining_an_invalid_epoch() {+ let reference = Timestamps::now();+ let mut clock = CaptureClock::new(reference);+ let _ = clock.timestamp(+ source_before(reference, 60),+ reference.instant() + Duration::from_millis(100),+ Duration::from_millis(10),+ );+ let reset = clock.timestamp(+ source_before(reference, 120),+ reference.instant() + Duration::from_millis(200),+ Duration::from_millis(10),+ );++ assert_eq!(elapsed(reset, reference), Duration::from_millis(190));+ }++ #[test]+ fn future_device_epoch_is_rebased() {+ let reference = Timestamps::now();+ let mut clock = CaptureClock::new(reference);+ let result = clock.timestamp(+ Timestamp::SystemTime(reference.system_time() + Duration::from_secs(60)),+ reference.instant() + Duration::from_millis(100),+ Duration::from_millis(10),+ );++ assert_eq!(elapsed(result, reference), Duration::from_millis(90));+ }+}diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rsindex c81d3cc9a..a81ea9da8 100644--- a/crates/recording/src/sources/microphone.rs+++ b/crates/recording/src/sources/microphone.rs@@ -40,7 +40,48 @@ fn should_fabricate_stall_silence(stall_duration: Duration, keepalive_after: Durstall_duration >= keepalive_after}+struct ReconnectAttemptGuard(Arc<AtomicBool>);++impl Drop for ReconnectAttemptGuard {+ fn drop(&mut self) {+ self.0.store(false, Ordering::Relaxed);+ }+}++async fn complete_reconnect_attempt<T>(+ in_flight: Arc<AtomicBool>,+ cancel: CancellationToken,+ work: impl Future<Output = T>,+) -> Option<T> {+ let _attempt = ReconnectAttemptGuard(in_flight);+ tokio::select! {+ biased;+ _ = cancel.cancelled() => None,+ result = work => Some(result),+ }+}++fn reconnect_is_due(stall: Duration, backoff: Duration, in_flight: bool) -> bool {+ !in_flight && stall >= backoff+}++fn reset_reconnect_after_frame(+ in_flight: &AtomicBool,+ attempts: &mut u32,+ next_reconnect_after: &mut Duration,+) {+ in_flight.store(false, Ordering::Relaxed);+ *attempts = 0;+ *next_reconnect_after = MIC_RECONNECT_AFTER;+}+pub struct Microphone {+ #[cfg(windows)]+ capture_scope: crate::output_pipeline::PipelineBuildScope,+ #[cfg(windows)]+ subscription: Arc<microphone::RecordingSubscription>,+ #[cfg(target_os = "linux")]+ required_health: Option<RequiredMicrophoneHealth>,info: AudioInfo,_lock: Arc<MicrophoneFeedLock>,cancel: CancellationToken,@@ -53,6 +94,10 @@ pub struct Microphone {// the rest of the process.impl Drop for Microphone {fn drop(&mut self) {+ #[cfg(windows)]+ if let Some(error) = self.subscription.retire() {+ self.capture_scope.fail_required(error);+ }self.cancel.cancel();}}@@ -167,6 +212,44 @@ impl MicResampler {}}+#[cfg(target_os = "linux")]+#[derive(Clone)]+struct RequiredMicrophoneHealth {+ source: microphone::RecordingSourceHealth,+ scope: crate::output_pipeline::PipelineBuildScope,+}++#[cfg(target_os = "linux")]+impl RequiredMicrophoneHealth {+ fn check_terminal(&self) -> bool {+ if let Some(error) = self.source.terminal_error() {+ self.scope.fail_required(error);+ true+ } else {+ false+ }+ }++ fn accepts_frame(&self, id: u32) -> bool {+ let current = self.source.frame_is_current(id);+ if !current {+ self.check_terminal();+ }+ current+ }++ fn fail(&self, error: String) {+ self.source.fail(error);+ self.check_terminal();+ }++ fn stop(&self) {+ if let Some(error) = self.source.stop_error() {+ self.scope.fail_required(error);+ }+ }+}+impl AudioSource for Microphone {type Config = Arc<MicrophoneFeedLock>;@@ -180,7 +263,36 @@ impl AudioSource for Microphone {Self: Sized,{let health_tx = ctx.health_tx().clone();- async move {+ #[cfg(windows)]+ let capture_scope = crate::output_pipeline::PipelineBuildScope::new();+ #[cfg(windows)]+ let source_cancel = ctx.stop_token().child_token();+ #[cfg(windows)]+ let subscription = feed_lock.recording_subscription(source_cancel.clone());+ #[cfg(windows)]+ {+ capture_scope.register_token(source_cancel.clone());+ let scope = capture_scope.clone();+ let cancel = source_cancel.clone();+ let subscription = subscription.clone();+ let feed = feed_lock.clone();+ ctx.tasks().spawn("microphone-owned-producers", async move {+ cancel.cancelled().await;+ finish_recording_subscription(&scope, &feed, subscription).await+ });+ }+ #[cfg(target_os = "linux")]+ let required_health = crate::output_pipeline::PipelineBuildScope::current()+ .filter(crate::output_pipeline::PipelineBuildScope::requires_source_health)+ .map(|scope| RequiredMicrophoneHealth {+ source: feed_lock.source_health(),+ scope,+ });+ #[cfg(windows)]+ let setup_scope = capture_scope.clone();+ #[cfg(windows)]+ let setup_cancel = source_cancel.clone().drop_guard();+ let setup = async move {let source_info = feed_lock.audio_info();let audio_info = source_info.with_max_channels(MICROPHONE_TARGET_CHANNELS)@@ -193,7 +305,10 @@ impl AudioSource for Microphone {sample_rate: Some(source_info.sample_rate),channels: u16::try_from(source_info.channels).ok(),};+ #[cfg(not(windows))]let cancel = CancellationToken::new();+ #[cfg(windows)]+ let cancel = source_cancel;let (tx, rx) = flume::bounded(128);let send_timeout = if is_wireless {@@ -202,6 +317,16 @@ impl AudioSource for Microphone {Duration::from_millis(5)};+ #[cfg(windows)]+ feed_lock+ .attach_recording_subscription(+ subscription.clone(),+ tx,+ health_tx.clone(),+ "microphone-feed:recording".into(),+ )+ .await?;+ #[cfg(not(windows))]feed_lock.ask(microphone::AddRecordingSender {sender: tx,@@ -240,15 +365,22 @@ impl AudioSource for Microphone {let recording_muted = feed_lock.recording_muted_handle();- tokio::spawn({+ crate::output_pipeline::spawn_capture_task({let frame_counter = mic_frame_counter.clone();let drop_counter = mic_drop_counter.clone();let silence_counter = mic_silence_counter.clone();let feed_lock = feed_lock.clone();+ #[cfg(not(windows))]let device_name = device_name.clone();let health_tx = health_tx.clone();let cancel = cancel.clone();let recording_muted = recording_muted.clone();+ #[cfg(windows)]+ let capture_scope = capture_scope.clone();+ #[cfg(windows)]+ let subscription = subscription.clone();+ #[cfg(target_os = "linux")]+ let required_health = required_health.clone();async move {let mut resampler: Option<MicResampler> = None;let mut silence_mode = false;@@ -261,6 +393,18 @@ impl AudioSource for Microphone {let mut logged_current_source: Option<(u32, u16, SampleFormat)> = None;loop {+ #[cfg(windows)]+ if let Some(error) = subscription.error() {+ capture_scope.fail_required(error);+ break;+ }+ #[cfg(target_os = "linux")]+ if required_health+ .as_ref()+ .is_some_and(RequiredMicrophoneHealth::check_terminal)+ {+ break;+ }let recv_result = tokio::select! {biased;_ = cancel.cancelled() => break,@@ -268,6 +412,17 @@ impl AudioSource for Microphone {};match recv_result {Ok(Ok(frame)) => {+ #[cfg(windows)]+ if !subscription.accepts_frame(frame.stream_id) {+ continue;+ }+ #[cfg(target_os = "linux")]+ if required_health+ .as_ref()+ .is_some_and(|health| !health.accepts_frame(frame.stream_id))+ {+ continue;+ }if silence_mode {let stall_ms =silence_start.map(|s| s.elapsed().as_millis()).unwrap_or(0);@@ -277,9 +432,11 @@ impl AudioSource for Microphone {);silence_mode = false;silence_start = None;- reconnect_in_flight.store(false, Ordering::Relaxed);- reconnect_attempts = 0;- next_reconnect_after = MIC_RECONNECT_AFTER;+ reset_reconnect_after_frame(+ &reconnect_in_flight,+ &mut reconnect_attempts,+ &mut next_reconnect_after,+ );emit_health(&health_tx, PipelineHealthEvent::SourceRestarted);}@@ -368,6 +525,12 @@ impl AudioSource for Microphone {.await{Ok(Ok(())) => {+ #[cfg(target_os = "linux")]+ if sample_count > 0+ && let Some(health) = &required_health+ {+ health.source.accepted_frame(frame.stream_id);+ }frame_counter.fetch_add(1, Ordering::Relaxed);}_ => {@@ -377,6 +540,18 @@ impl AudioSource for Microphone {}Ok(Err(_)) => {debug!("Microphone feed channel closed");+ #[cfg(windows)]+ if !cancel.is_cancelled() {+ capture_scope.fail_required(+ "Requested microphone feed closed before Stop".into(),+ );+ }+ #[cfg(target_os = "linux")]+ if !cancel.is_cancelled()+ && let Some(health) = &required_health+ {+ health.fail("Requested audio feed closed before Stop".into());+ }break;}Err(_) => {@@ -394,9 +569,11 @@ impl AudioSource for Microphone {silence_mode = true;}- if !reconnect_in_flight.load(Ordering::Relaxed)- && stall_duration >= next_reconnect_after- {+ if reconnect_is_due(+ stall_duration,+ next_reconnect_after,+ reconnect_in_flight.load(Ordering::Relaxed),+ ) {reconnect_attempts += 1;warn!(attempt = reconnect_attempts,@@ -408,32 +585,57 @@ impl AudioSource for Microphone {reconnect_in_flight.store(true, Ordering::Relaxed);let feed = feed_lock.clone();+ #[cfg(not(windows))]let name = device_name.clone();let in_flight = reconnect_in_flight.clone();- tokio::spawn(async move {- let ready = match feed- .ask(microphone::SetInput {- label: name,- settings: Some(reconnect_settings),- })- .await- {- Ok(r) => r,- Err(e) => {- warn!("Microphone reconnect failed: {e}");- in_flight.store(false, Ordering::Relaxed);- return;- }- };- match ready.await {- Ok(_) => {- info!("Microphone reconnect stream ready")- }- Err(e) => {- warn!("Microphone reconnect stream failed: {e}");- in_flight.store(false, Ordering::Relaxed);- }- }+ let attempt_cancel = cancel.clone();+ #[cfg(windows)]+ let capture_scope = capture_scope.clone();+ #[cfg(windows)]+ let subscription = subscription.clone();+ #[cfg(target_os = "linux")]+ let required_health = required_health.clone();+ crate::output_pipeline::spawn_capture_task(async move {+ let _ = complete_reconnect_attempt(+ in_flight,+ attempt_cancel,+ async move {+ #[cfg(windows)]+ let reconnect = feed.reconnect_recording_subscription(subscription, reconnect_settings).await;+ #[cfg(not(windows))]+ let reconnect = feed.ask(microphone::SetInput {+ label: name, settings: Some(reconnect_settings),+ }).await;+ let ready = match reconnect {+ Ok(r) => r,+ Err(e) => {+ warn!("Microphone reconnect failed: {e}");+ #[cfg(windows)]+ capture_scope.fail_required(format!(+ "Requested microphone reconnect failed: {e}"+ ));+ #[cfg(target_os = "linux")]+ if let Some(health) = &required_health {+ health.fail(format!("Requested audio reconnect failed: {e}"));+ }+ return;+ }+ };+ match ready.await {+ Ok(_) => {+ info!("Microphone reconnect stream ready")+ }+ Err(e) => {+ warn!("Microphone reconnect stream failed: {e}");+ #[cfg(windows)]+ capture_scope.fail_required(format!(+ "Requested microphone reconnect stream failed: {e}"+ ));+ }+ }+ },+ )+ .await;});next_reconnect_after =@@ -478,7 +680,7 @@ impl AudioSource for Microphone {}});- tokio::spawn({+ crate::output_pipeline::spawn_capture_task({let cancel = cancel.clone();let health_tx = health_tx.clone();async move {@@ -578,11 +780,27 @@ impl AudioSource for Microphone {}});+ #[cfg(windows)]+ drop(setup_cancel.disarm());Ok(Self {+ #[cfg(windows)]+ capture_scope,+ #[cfg(windows)]+ subscription,info: audio_info,_lock: feed_lock,+ #[cfg(target_os = "linux")]+ required_health,cancel,})+ };+ #[cfg(windows)]+ {+ async move { setup_scope.run(setup).await }+ }+ #[cfg(not(windows))]+ {+ setup}}@@ -591,9 +809,62 @@ impl AudioSource for Microphone {}fn stop(&mut self) -> impl Future<Output = anyhow::Result<()>> + Send {+ #[cfg(target_os = "linux")]+ if let Some(health) = &self.required_health {+ health.stop();+ }+ #[cfg(windows)]+ if let Some(error) = self.subscription.retire() {+ self.capture_scope.fail_required(error);+ }self.cancel.cancel();- async { Ok(()) }+ #[cfg(windows)]+ let scope = self.capture_scope.clone();+ #[cfg(windows)]+ let feed = self._lock.clone();+ #[cfg(windows)]+ let subscription = self.subscription.clone();+ async move {+ #[cfg(windows)]+ {+ finish_recording_subscription(&scope, &feed, subscription).await+ }+ #[cfg(not(windows))]+ {+ Ok(())+ }+ }+ }+}++#[cfg(windows)]+async fn finish_recording_subscription(+ scope: &crate::output_pipeline::PipelineBuildScope,+ feed: µphone::MicrophoneFeedLock,+ subscription: Arc<microphone::RecordingSubscription>,+) -> anyhow::Result<()> {+ if let Some(error) = subscription.retire() {+ scope.fail_required(error);+ }+ let detached = feed.detach_recording_subscription(subscription).await;+ let joined = microphone_producers_join(scope).await;+ detached?;+ joined+}++#[cfg(any(windows, test))]+async fn microphone_producers_join(+ scope: &crate::output_pipeline::PipelineBuildScope,+) -> anyhow::Result<()> {+ let report = scope.cancel_and_join_report().await;+ if let Some(error) = report.error {+ anyhow::bail!(error);}+ anyhow::ensure!(+ report.quiescent,+ "Microphone producers did not confirm quiescence"+ );+ Ok(())}fn create_silence_frame(info: &AudioInfo, sample_count: usize) -> ffmpeg::frame::Audio {@@ -624,6 +895,110 @@ mod tests {use super::*;use cap_media_info::{Sample, Type};+ #[tokio::test]+ async fn ready_success_without_frames_retries_only_after_existing_backoff() {+ let in_flight = Arc::new(AtomicBool::new(true));+ let result =+ complete_reconnect_attempt(in_flight.clone(), CancellationToken::new(), async {+ Ok::<_, ()>(())+ })+ .await;+ assert_eq!(result, Some(Ok(())));+ assert!(!in_flight.load(Ordering::Relaxed));+ let next_backoff = MIC_RECONNECT_AFTER * 2;+ assert!(!reconnect_is_due(+ Duration::from_millis(3999),+ next_backoff,+ in_flight.load(Ordering::Relaxed)+ ));+ assert!(reconnect_is_due(+ Duration::from_secs(4),+ next_backoff,+ in_flight.load(Ordering::Relaxed)+ ));+ }++ #[tokio::test]+ async fn ready_failure_releases_in_flight_without_skipping_backoff() {+ let in_flight = Arc::new(AtomicBool::new(true));+ let result =+ complete_reconnect_attempt(in_flight.clone(), CancellationToken::new(), async {+ Err::<(), _>("failed")+ })+ .await;+ assert_eq!(result, Some(Err("failed")));+ assert!(!in_flight.load(Ordering::Relaxed));+ assert!(!reconnect_is_due(+ Duration::from_secs(2),+ Duration::from_secs(4),+ false+ ));+ }++ #[test]+ fn real_frame_resets_reconnect_attempts_and_original_delay() {+ let in_flight = AtomicBool::new(true);+ let mut attempts = 3;+ let mut delay = Duration::from_secs(16);+ reset_reconnect_after_frame(&in_flight, &mut attempts, &mut delay);+ assert!(!in_flight.load(Ordering::Relaxed));+ assert_eq!(attempts, 0);+ assert_eq!(delay, MIC_RECONNECT_AFTER);+ assert!(!reconnect_is_due(Duration::from_millis(1999), delay, false));+ assert!(reconnect_is_due(Duration::from_secs(2), delay, false));+ }++ #[tokio::test]+ async fn stop_cancels_pending_reconnect_and_releases_in_flight() {+ let in_flight = Arc::new(AtomicBool::new(true));+ let cancel = CancellationToken::new();+ let (started_tx, started_rx) = tokio::sync::oneshot::channel();+ let attempt = tokio::spawn(complete_reconnect_attempt(+ in_flight.clone(),+ cancel.clone(),+ async {+ started_tx.send(()).unwrap();+ std::future::pending::<()>().await;+ },+ ));+ started_rx.await.unwrap();+ cancel.cancel();+ assert_eq!(+ tokio::time::timeout(Duration::from_secs(1), attempt)+ .await+ .unwrap()+ .unwrap(),+ None+ );+ assert!(!in_flight.load(Ordering::Relaxed));+ }++ #[tokio::test]+ async fn already_stopped_source_does_not_dispatch_reconnect() {+ let in_flight = Arc::new(AtomicBool::new(true));+ let cancel = CancellationToken::new();+ cancel.cancel();+ let result: Option<()> = complete_reconnect_attempt(in_flight.clone(), cancel, async {+ panic!("stopped source dispatched a reconnect")+ })+ .await;+ assert_eq!(result, None);+ assert!(!in_flight.load(Ordering::Relaxed));+ }++ #[tokio::test]+ async fn dropped_reconnect_future_releases_in_flight() {+ let in_flight = Arc::new(AtomicBool::new(true));+ let mut attempt = Box::pin(complete_reconnect_attempt(+ in_flight.clone(),+ CancellationToken::new(),+ std::future::pending::<()>(),+ ));+ assert!(futures::poll!(attempt.as_mut()).is_pending());+ drop(attempt);+ assert!(!in_flight.load(Ordering::Relaxed));+ }+#[test]fn transient_stall_does_not_fabricate_silence() {// The repro's worst mic stall was 293ms; none of its sub-second late-delivery@@ -962,3 +1337,235 @@ mod tests {assert!(prev.is_some(), "resampler produced no frames");}}++#[cfg(all(test, target_os = "linux"))]+mod required_source_outcome_tests {+ use super::*;+ use crate::output_pipeline::PipelineBuildScope;++ #[tokio::test]+ async fn continuing_failed_callbacks_cancel_before_receive_timeout_and_join_owned_work() {+ let scope = PipelineBuildScope::new_studio_lifetime();+ let cancel = CancellationToken::new();+ scope.register_token(cancel.clone());+ let health = RequiredMicrophoneHealth {+ source: microphone::RecordingSourceHealth::test_healthy(7),+ scope: scope.clone(),+ };+ let (sender, receiver) = flume::bounded(128);+ for _ in 0..128 {+ sender.try_send(7).unwrap();+ }+ health.source.test_backend_failure();+ assert!(!health.check_terminal());+ let completion = scope.task_completion();+ let (release, released) = tokio::sync::oneshot::channel();+ let writer = tokio::spawn(async move {+ let _completion = completion;+ released.await.unwrap();+ });+ assert!(!health.accepts_frame(receiver.try_recv().unwrap()));+ assert_eq!(receiver.len(), 127);+ assert!(cancel.is_cancelled());+ health.stop();+ let joined = tokio::spawn(async move { scope.cancel_and_join_report().await });+ tokio::task::yield_now().await;+ assert!(!joined.is_finished());+ release.send(()).unwrap();+ writer.await.unwrap();+ let report = joined.await.unwrap();+ assert!(report.quiescent);+ assert!(+ report+ .error+ .unwrap()+ .contains("failed while continuing to deliver samples")+ );+ }++ #[tokio::test]+ async fn healthy_and_stale_callbacks_preserve_successful_required_source_stop() {+ let scope = PipelineBuildScope::new_studio_lifetime();+ let cancel = CancellationToken::new();+ scope.register_token(cancel.clone());+ let health = RequiredMicrophoneHealth {+ source: microphone::RecordingSourceHealth::test_healthy(7),+ scope: scope.clone(),+ };+ for _ in 0..128 {+ assert!(health.accepts_frame(7));+ assert!(!health.accepts_frame(6));+ }+ assert!(!health.check_terminal());+ assert!(!cancel.is_cancelled());+ health.stop();+ let report = scope.cancel_and_join_report().await;+ assert!(report.quiescent);+ assert!(report.error.is_none());+ }++ #[tokio::test]+ async fn continued_backend_error_in_committed_resume_cancels_parent_attempt() {+ let parent = PipelineBuildScope::new_studio_lifetime();+ let child = parent.child_transaction();+ let cancel = CancellationToken::new();+ child.register_token(cancel.clone());+ assert!(child.commit());+ let health = RequiredMicrophoneHealth {+ source: microphone::RecordingSourceHealth::test_healthy(8),+ scope: child,+ };+ health.source.test_backend_failure();+ assert!(!health.accepts_frame(8));+ assert!(cancel.is_cancelled());+ health.stop();+ let report = parent.cancel_and_join_report().await;+ assert!(report.quiescent);+ assert!(+ report+ .error+ .unwrap()+ .contains("failed while continuing to deliver samples")+ );+ }++ #[tokio::test]+ async fn confirmed_audio_failure_cancels_siblings_but_waits_for_owned_writer() {+ let scope = PipelineBuildScope::new_studio_lifetime();+ let cancel = CancellationToken::new();+ scope.register_token(cancel.clone());+ let completion = scope.task_completion();+ let health = RequiredMicrophoneHealth {+ source: microphone::RecordingSourceHealth::test_healthy(0),+ scope: scope.clone(),+ };+ let (release, released) = tokio::sync::oneshot::channel();+ let writer = tokio::spawn(async move {+ let _completion = completion;+ released.await.unwrap();+ });+ health.fail("DeviceNotFound after confirmed Pulse loss".into());+ assert!(cancel.is_cancelled());+ health.stop();+ let joined = tokio::spawn(async move { scope.cancel_and_join_report().await });+ tokio::task::yield_now().await;+ assert!(!joined.is_finished());+ release.send(()).unwrap();+ writer.await.unwrap();+ let report = joined.await.unwrap();+ assert!(report.quiescent);+ assert!(report.error.unwrap().contains("DeviceNotFound"));+ }++ #[tokio::test]+ async fn feed_eof_cannot_be_a_successful_required_source_stop() {+ let scope = PipelineBuildScope::new_studio_lifetime();+ let health = RequiredMicrophoneHealth {+ source: microphone::RecordingSourceHealth::test_healthy(7),+ scope: scope.clone(),+ };+ health.fail("Requested audio feed closed before Stop".into());+ health.stop();+ let report = scope.cancel_and_join_report().await;+ assert!(report.quiescent);+ assert!(report.error.unwrap().contains("closed before Stop"));+ }++ #[tokio::test]+ async fn healthy_required_source_stop_does_not_invent_failure() {+ let scope = PipelineBuildScope::new_studio_lifetime();+ let health = RequiredMicrophoneHealth {+ source: microphone::RecordingSourceHealth::test_healthy(7),+ scope: scope.clone(),+ };+ assert!(!health.check_terminal());+ health.stop();+ let report = scope.cancel_and_join_report().await;+ assert!(report.quiescent);+ assert!(report.error.is_none());+ assert!(!PipelineBuildScope::new_lifetime().requires_source_health());+ }++ #[tokio::test]+ async fn committed_resume_audio_failure_still_cancels_parent_attempt() {+ let parent = PipelineBuildScope::new_studio_lifetime();+ let child = parent.child_transaction();+ assert!(child.requires_source_health());+ let cancel = CancellationToken::new();+ child.register_token(cancel.clone());+ assert!(child.commit());+ let health = RequiredMicrophoneHealth {+ source: microphone::RecordingSourceHealth::test_healthy(8),+ scope: child,+ };+ health.fail("current replacement failed".into());+ assert!(cancel.is_cancelled());+ let report = parent.cancel_and_join_report().await;+ assert!(report.quiescent);+ assert!(report.error.is_some());+ }+}++#[cfg(test)]+mod owned_microphone_tests {+ use super::*;+ use crate::output_pipeline::{PipelineBuildScope, spawn_capture_task};++ #[tokio::test]+ async fn microphone_stop_waits_for_nested_producer_acknowledgement() {+ let scope = PipelineBuildScope::new();+ let cancel = CancellationToken::new();+ scope.register_token(cancel.clone());+ let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();+ scope+ .run(async move {+ drop(spawn_capture_task(async move {+ drop(spawn_capture_task(async move {+ let _ = ready_tx.send(());+ cancel.cancelled().await;+ release_rx.await.unwrap();+ }));+ }));+ })+ .await;+ ready_rx.await.unwrap();+ let stop = tokio::spawn(async move { microphone_producers_join(&scope).await });+ tokio::task::yield_now().await;+ assert!(!stop.is_finished());+ release_tx.send(()).unwrap();+ stop.await.unwrap().unwrap();+ }++ #[tokio::test]+ async fn microphone_producer_panic_is_not_successful_stop() {+ let scope = PipelineBuildScope::new();+ let mut task = None;+ scope+ .run(async {+ task = Some(spawn_capture_task(async {+ panic!("synthetic microphone producer panic")+ }));+ })+ .await;+ assert!(task.unwrap().await.is_err());+ assert!(microphone_producers_join(&scope).await.is_err());+ }++ #[tokio::test]+ async fn microphone_terminal_error_is_sticky_after_producers_exit() {+ let scope = PipelineBuildScope::new();+ scope.fail_required("Requested microphone reconnect failed: DeviceNotFound".into());+ assert!(microphone_producers_join(&scope).await.is_err());+ assert!(microphone_producers_join(&scope).await.is_err());+ }++ #[tokio::test]+ async fn unpolled_microphone_setup_drop_cancels_registered_completion() {+ let cancel = CancellationToken::new();+ let guard = cancel.clone().drop_guard();+ let setup = async move { drop(guard.disarm()) };+ drop(setup);+ assert!(cancel.is_cancelled());+ }+}diff --git a/crates/recording/src/sources/mod.rs b/crates/recording/src/sources/mod.rsindex 686ac8af1..c70a3caec 100644--- a/crates/recording/src/sources/mod.rs+++ b/crates/recording/src/sources/mod.rs@@ -1,5 +1,7 @@pub mod audio_mixer;pub mod camera;+#[cfg(any(windows, test))]+pub(crate) mod capture_clock;pub mod microphone;pub mod native_camera;pub mod screen_capture;diff --git a/crates/recording/src/sources/native_camera.rs b/crates/recording/src/sources/native_camera.rsindex c346db814..abb50eff2 100644--- a/crates/recording/src/sources/native_camera.rs+++ b/crates/recording/src/sources/native_camera.rs@@ -20,6 +20,100 @@ pub struct NativeCamera {stopped: Arc<AtomicBool>,}+async fn forward_native_frames<T: Send + 'static>(+ rx: flume::Receiver<T>,+ video_tx: mpsc::Sender<T>,+ stop_rx: oneshot::Receiver<()>,+ stopped: Arc<AtomicBool>,+ required: bool,+) -> anyhow::Result<()> {+ tracing::debug!("Native camera source task started");+ let mut frame_count: u64 = 0;+ let mut sent_count: u64 = 0;+ let mut dropped_count: u64 = 0;+ let start = std::time::Instant::now();+ let mut video_tx = video_tx;+ let mut stop_rx = stop_rx.fuse();++ loop {+ if stopped.load(Ordering::Relaxed) {+ tracing::debug!("Native camera source: stop flag set, exiting");+ break;+ }++ tokio::select! {+ biased;+ _ = &mut stop_rx => {+ tracing::debug!("Native camera source: received stop signal");+ break;+ }+ result = rx.recv_async() => {+ match result {+ Ok(frame) => {+ frame_count += 1;+ match video_tx.try_send(frame) {+ Ok(()) => {+ sent_count += 1;+ if sent_count.is_multiple_of(30) {+ tracing::debug!(+ "Native camera source: sent {} frames, dropped {} in {:?}",+ sent_count,+ dropped_count,+ start.elapsed()+ );+ }+ }+ Err(e) => {+ if e.is_full() {+ dropped_count += 1;+ if dropped_count.is_multiple_of(30) {+ tracing::warn!(+ "Native camera source: encoder can't keep up, dropped {} frames so far",+ dropped_count+ );+ }+ } else if e.is_disconnected() {+ tracing::debug!(+ "Native camera source: pipeline closed after {} sent, {} dropped",+ sent_count,+ dropped_count+ );+ if required && !stopped.load(Ordering::Acquire) {+ return Err(anyhow!("Native camera encoder disconnected before Stop"));+ }+ break;+ }+ }+ }+ }+ Err(e) => {+ tracing::debug!(+ "Native camera feed disconnected (rx closed) after {} frames in {:?}: {e}",+ frame_count,+ start.elapsed()+ );+ if required && !stopped.load(Ordering::Acquire) {+ return Err(anyhow!("Native camera feed disconnected before Stop: {e}"));+ }+ break;+ }+ }+ }+ }+ }++ drop(video_tx);++ tracing::info!(+ "Native camera source finished: {} received, {} sent, {} dropped in {:?}",+ frame_count,+ sent_count,+ dropped_count,+ start.elapsed()+ );+ Ok(())+}+impl VideoSource for NativeCamera {type Config = Arc<CameraFeedLock>;type Frame = NativeCameraFrame;@@ -27,7 +121,7 @@ impl VideoSource for NativeCamera {async fn setup(feed_lock: Self::Config,video_tx: mpsc::Sender<Self::Frame>,- _: &mut SetupCtx,+ _ctx: &mut SetupCtx,) -> anyhow::Result<Self>whereSelf: Sized,@@ -46,86 +140,11 @@ impl VideoSource for NativeCamera {let stopped = Arc::new(AtomicBool::new(false));let stopped_clone = stopped.clone();- tokio::spawn(async move {- tracing::debug!("Native camera source task started");- let mut frame_count: u64 = 0;- let mut sent_count: u64 = 0;- let mut dropped_count: u64 = 0;- let start = std::time::Instant::now();- let mut video_tx = video_tx;- let mut stop_rx = stop_rx.fuse();-- loop {- if stopped_clone.load(Ordering::Relaxed) {- tracing::debug!("Native camera source: stop flag set, exiting");- break;- }-- tokio::select! {- biased;- _ = &mut stop_rx => {- tracing::debug!("Native camera source: received stop signal");- break;- }- result = rx.recv_async() => {- match result {- Ok(frame) => {- frame_count += 1;- match video_tx.try_send(frame) {- Ok(()) => {- sent_count += 1;- if sent_count.is_multiple_of(30) {- tracing::debug!(- "Native camera source: sent {} frames, dropped {} in {:?}",- sent_count,- dropped_count,- start.elapsed()- );- }- }- Err(e) => {- if e.is_full() {- dropped_count += 1;- if dropped_count.is_multiple_of(30) {- tracing::warn!(- "Native camera source: encoder can't keep up, dropped {} frames so far",- dropped_count- );- }- } else if e.is_disconnected() {- tracing::debug!(- "Native camera source: pipeline closed after {} sent, {} dropped",- sent_count,- dropped_count- );- break;- }- }- }- }- Err(e) => {- tracing::debug!(- "Native camera feed disconnected (rx closed) after {} frames in {:?}: {e}",- frame_count,- start.elapsed()- );- break;- }- }- }- }- }-- drop(video_tx);-- tracing::info!(- "Native camera source finished: {} received, {} sent, {} dropped in {:?}",- frame_count,- sent_count,- dropped_count,- start.elapsed()- );- });+ let task = forward_native_frames(rx, video_tx, stop_rx, stopped_clone, cfg!(windows));+ #[cfg(windows)]+ _ctx.tasks().spawn("native-camera", task);+ #[cfg(not(windows))]+ drop(tokio::spawn(task));Ok(Self {feed_lock,@@ -150,3 +169,110 @@ impl VideoSource for NativeCamera {.boxed()}}++#[cfg(test)]+mod forwarding_tests {+ use super::*;+ use futures::StreamExt;++ #[tokio::test]+ async fn required_native_camera_eof_is_not_success() {+ let (sender, receiver) = flume::bounded::<u8>(1);+ let (video, _frames) = mpsc::channel(1);+ let (_stop, stopped) = oneshot::channel();+ drop(sender);+ let result = forward_native_frames(+ receiver,+ video,+ stopped,+ Arc::new(AtomicBool::new(false)),+ true,+ )+ .await;+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("feed disconnected before Stop")+ );+ }++ #[tokio::test]+ async fn native_camera_stop_precedes_ready_eof() {+ let (sender, receiver) = flume::bounded::<u8>(1);+ let (video, mut frames) = mpsc::channel(1);+ let (stop, stopped) = oneshot::channel();+ stop.send(()).unwrap();+ drop(sender);+ forward_native_frames(+ receiver,+ video,+ stopped,+ Arc::new(AtomicBool::new(false)),+ true,+ )+ .await+ .unwrap();+ assert!(frames.next().await.is_none());+ }++ #[tokio::test]+ async fn joined_native_camera_forwarder_has_closed_its_output() {+ let (sender, receiver) = flume::bounded(1);+ let (video, mut frames) = mpsc::channel(1);+ let (stop, stopped) = oneshot::channel();+ let task = tokio::spawn(forward_native_frames(+ receiver,+ video,+ stopped,+ Arc::new(AtomicBool::new(false)),+ true,+ ));+ sender.send_async(17_u8).await.unwrap();+ assert_eq!(frames.next().await, Some(17));+ stop.send(()).unwrap();+ task.await.unwrap().unwrap();+ assert!(frames.next().await.is_none());+ assert!(sender.send_async(18).await.is_err());+ }++ #[tokio::test]+ async fn native_camera_encoder_disconnect_is_required_failure() {+ let (sender, receiver) = flume::bounded(1);+ let (video, frames) = mpsc::channel(1);+ let (_stop, stopped) = oneshot::channel();+ drop(frames);+ sender.send_async(17_u8).await.unwrap();+ let result = forward_native_frames(+ receiver,+ video,+ stopped,+ Arc::new(AtomicBool::new(false)),+ true,+ )+ .await;+ assert!(+ result+ .unwrap_err()+ .to_string()+ .contains("encoder disconnected before Stop")+ );+ }++ #[tokio::test]+ async fn legacy_native_camera_eof_remains_success() {+ let (sender, receiver) = flume::bounded::<u8>(1);+ let (video, _frames) = mpsc::channel(1);+ let (_stop, stopped) = oneshot::channel();+ drop(sender);+ forward_native_frames(+ receiver,+ video,+ stopped,+ Arc::new(AtomicBool::new(false)),+ false,+ )+ .await+ .unwrap();+ }+}diff --git a/crates/recording/src/sources/screen_capture/linux.rs b/crates/recording/src/sources/screen_capture/linux.rsindex fee1e5bef..5fe6fc919 100644--- a/crates/recording/src/sources/screen_capture/linux.rs+++ b/crates/recording/src/sources/screen_capture/linux.rs@@ -12,8 +12,8 @@ use ashpd::desktop::{screencast::{CursorMode, Screencast, SourceType, Stream as PortalStream},};use cap_timestamp::Timestamp;-use futures::channel::mpsc;-use kameo::Actor as _;+use futures::{Stream, StreamExt, channel::mpsc};+use kameo::{Actor as _, actor::ActorRef};use pipewire as pw;use pw::{properties::properties, spa};use std::{@@ -175,7 +175,7 @@ impl ScreenCaptureConfig<X11Capture> {}}-pub(crate) fn x11_capture_rect(+pub fn x11_capture_rect(display_x: f64,display_y: f64,display_width: f64,@@ -867,10 +867,43 @@ pub struct SystemAudioSourceConfig {feed_lock: Arc<MicrophoneFeedLock>,device_name: String,monitor_route: Option<PactlMonitorRoute>,+ feed: OwnedSystemAudioFeed,}pub struct SystemAudioSource {inner: crate::sources::Microphone,+ monitor_route: Option<PactlMonitorRoute>,+ feed: OwnedSystemAudioFeed,+}++struct OwnedSystemAudioFeed {+ actor: ActorRef<MicrophoneFeed>,+ build_scope: Option<crate::output_pipeline::PipelineBuildScope>,+ stopped: bool,+}++impl Drop for OwnedSystemAudioFeed {+ fn drop(&mut self) {+ if self.stopped {+ return;+ }+ self.actor.kill();+ if let Some(scope) = &self.build_scope+ && !scope.is_committed()+ {+ let feed = self.actor.clone();+ scope.spawn_cleanup(async move {+ feed.wait_for_stop().await;+ Ok(())+ });+ }+ }+}++impl Drop for SystemAudioSource {+ fn drop(&mut self) {+ drop(self.monitor_route.take());+ }}struct PactlMonitorRoute {@@ -879,9 +912,386 @@ struct PactlMonitorRoute {default_source: Option<String>,default_source_index: Option<u32>,source_output: u32,+ original_source: u32,previous_process_source_outputs: Vec<PactlSourceOutput>,}+impl Drop for PactlMonitorRoute {+ fn drop(&mut self) {+ let restore = || -> anyhow::Result<()> {+ let outputs = current_process_source_outputs()?;+ let Some(output) = outputs+ .iter()+ .find(|output| output.id == self.source_output)+ else {+ return Ok(());+ };+ if output.source != self.monitor_source_index {+ return Ok(());+ }+ let destination = previous_source_destination(+ self.original_source,+ self.monitor_source_index,+ &self.monitor_source,+ self.default_source.as_deref(),+ );+ if destination != self.monitor_source_index.to_string() {+ move_pactl_source_output(self.source_output, &destination)?;+ }+ Ok(())+ };+ if let Err(error) = restore() {+ tracing::warn!(%error, "Could not restore the Linux system-audio input route");+ }+ }+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(crate) enum PulseInputRole {+ #[default]+ Microphone,+ SystemAudio,+}++mod alsa_input_backend {+ use anyhow::{Context as _, anyhow, bail, ensure};+ use std::ffi::{CStr, CString, c_char, c_int, c_void};++ #[link(name = "asound")]+ unsafe extern "C" {+ fn snd_config_update_ref(config: *mut *mut c_void) -> c_int;+ fn snd_config_unref(config: *mut c_void);+ fn snd_config_delete(config: *mut c_void) -> c_int;+ fn snd_config_search_definition(+ config: *mut c_void,+ base: *const c_char,+ name: *const c_char,+ result: *mut *mut c_void,+ ) -> c_int;+ fn snd_config_search(+ config: *mut c_void,+ key: *const c_char,+ result: *mut *mut c_void,+ ) -> c_int;+ fn snd_config_get_string(config: *const c_void, result: *mut *const c_char) -> c_int;+ #[cfg(test)]+ fn snd_config_load_string(+ config: *mut *mut c_void,+ text: *const c_char,+ size: usize,+ ) -> c_int;+ }++ struct Config {+ raw: *mut c_void,+ shared: bool,+ }++ impl Drop for Config {+ fn drop(&mut self) {+ unsafe {+ if self.shared {+ snd_config_unref(self.raw);+ } else {+ let _ = snd_config_delete(self.raw);+ }+ }+ }+ }++ fn definition(root: *mut c_void, base: &CStr, name: &CStr) -> anyhow::Result<Config> {+ let mut raw = std::ptr::null_mut();+ let status =+ unsafe { snd_config_search_definition(root, base.as_ptr(), name.as_ptr(), &mut raw) };+ ensure!(+ status >= 0 && !raw.is_null(),+ "Could not resolve ALSA input configuration {name:?}: {status}"+ );+ Ok(Config { raw, shared: false })+ }++ fn child(config: *mut c_void, key: &CStr) -> Option<*mut c_void> {+ let mut raw = std::ptr::null_mut();+ let status = unsafe { snd_config_search(config, key.as_ptr(), &mut raw) };+ (status >= 0 && !raw.is_null()).then_some(raw)+ }++ fn string(config: *mut c_void) -> Option<CString> {+ let mut value = std::ptr::null();+ let status = unsafe { snd_config_get_string(config, &mut value) };+ if status < 0 || value.is_null() {+ return None;+ }+ Some(unsafe { CStr::from_ptr(value) }.to_owned())+ }++ fn nested_pcm(+ root: *mut c_void,+ node: *mut c_void,+ key: &CStr,+ depth: usize,+ ) -> anyhow::Result<bool> {+ let node = child(node, key).context("ALSA input slave is missing")?;+ let named = string(node)+ .map(|name| definition(root, c"pcm_slave", &name))+ .transpose()?;+ let slave = named.as_ref().map_or(node, |config| config.raw);+ let pcm = child(slave, c"pcm").context("ALSA input slave PCM is missing")?;+ node_uses_pulse(root, pcm, depth + 1)+ }++ fn node_uses_pulse(root: *mut c_void, node: *mut c_void, depth: usize) -> anyhow::Result<bool> {+ ensure!(+ depth < 32,+ "ALSA input configuration exceeds the alias depth limit"+ );+ if let Some(name) = string(node) {+ let resolved = definition(root, c"pcm", &name)?;+ return node_uses_pulse(root, resolved.raw, depth + 1);+ }+ let kind = child(node, c"type")+ .and_then(string)+ .context("ALSA input plugin type is missing")?;+ match kind.as_bytes() {+ b"pulse" => Ok(true),+ b"asym" => nested_pcm(root, node, c"capture", depth),+ b"file" if child(node, c"infile").is_some() => Ok(false),+ b"plug" | b"rate" | b"route" | b"linear" | b"lfloat" | b"copy" | b"softvol"+ | b"dsnoop" | b"mmap_emul" | b"file" => nested_pcm(root, node, c"slave", depth),+ _ if child(node, c"slave").is_some() => nested_pcm(root, node, c"slave", depth),+ b"multi" => {+ bail!("ALSA input has multiple backends; cannot identify a single Pulse route")+ }+ _ => Ok(false),+ }+ }++ pub(super) fn uses_pulse(device_name: &str) -> anyhow::Result<bool> {+ let name = CString::new(device_name).context("Invalid ALSA input name")?;+ let mut raw = std::ptr::null_mut();+ let status = unsafe { snd_config_update_ref(&mut raw) };+ if status < 0 || raw.is_null() {+ return Err(anyhow!("Could not read ALSA input configuration: {status}"));+ }+ let root = Config { raw, shared: true };+ let input = definition(root.raw, c"pcm", &name)?;+ node_uses_pulse(root.raw, input.raw, 0)+ }++ #[cfg(test)]+ mod tests {+ use super::*;++ fn configured_input_uses_pulse(text: &str) -> anyhow::Result<bool> {+ let text = CString::new(text)?;+ let mut raw = std::ptr::null_mut();+ let status =+ unsafe { snd_config_load_string(&mut raw, text.as_ptr(), text.as_bytes().len()) };+ ensure!(+ status >= 0 && !raw.is_null(),+ "ALSA test configuration failed: {status}"+ );+ let root = Config { raw, shared: false };+ let input = definition(root.raw, c"pcm", c"default")?;+ node_uses_pulse(root.raw, input.raw, 0)+ }++ #[test]+ fn direct_default_is_not_mistaken_for_pulse() {+ assert!(!configured_input_uses_pulse("pcm.default { type hw card 0 }").unwrap());+ assert!(!configured_input_uses_pulse("pcm.default { type custom_hardware }").unwrap());+ }++ #[test]+ fn pulse_default_aliases_and_plug_chains_are_detected() {+ assert!(+ configured_input_uses_pulse(+ "pcm.default pulse_input\npcm.pulse_input { type pulse }"+ )+ .unwrap()+ );+ assert!(configured_input_uses_pulse("pcm.default { type plug slave.pcm inner }\npcm.inner { type rate slave.pcm { type pulse } }").unwrap());+ }++ #[test]+ fn asymmetric_default_checks_capture_instead_of_playback() {+ assert!(!configured_input_uses_pulse("pcm.default { type asym playback.pcm { type pulse } capture.pcm { type hw card 0 } }").unwrap());+ assert!(configured_input_uses_pulse("pcm.default { type asym playback.pcm { type hw card 0 } capture.pcm { type pulse } }").unwrap());+ }++ #[test]+ fn named_slaves_and_file_inputs_keep_their_capture_backend() {+ assert!(configured_input_uses_pulse("pcm.default { type plug slave captured }\npcm_slave.captured { pcm { type pulse } }").unwrap());+ assert!(!configured_input_uses_pulse("pcm.default { type plug slave.pcm { type file infile synthetic.raw slave.pcm { type null } } }").unwrap());+ }++ #[test]+ fn malformed_or_ambiguous_inputs_do_not_claim_a_pulse_route() {+ for wrapper in [+ "plug",+ "rate",+ "route",+ "linear",+ "lfloat",+ "copy",+ "softvol",+ "dsnoop",+ "mmap_emul",+ "file",+ ] {+ assert!(+ configured_input_uses_pulse(&format!("pcm.default {{ type {wrapper} }}"))+ .is_err()+ );+ }+ assert!(configured_input_uses_pulse("pcm.default { type multi }").is_err());+ }+ }+}++pub(crate) struct PulseInputRoute {+ source: String,+ source_index: u32,+ previous_outputs: Vec<PactlSourceOutput>,+}++impl PulseInputRoute {+ pub(crate) fn prepare(device_name: &str, role: PulseInputRole) -> anyhow::Result<Option<Self>> {+ if !uses_default_pulse_input(device_name) {+ return Ok(None);+ }+ let default_source = pactl_default_source();+ if default_source.is_none() && role == PulseInputRole::Microphone {+ return Ok(None);+ }+ if !alsa_input_backend::uses_pulse(device_name)? {+ anyhow::ensure!(+ role != PulseInputRole::SystemAudio,+ "The selected ALSA input is not a Pulse system-audio monitor"+ );+ return Ok(None);+ }+ let default_sink = pactl_default_sink();+ let sources = Command::new("pactl")+ .args(["list", "short", "sources"])+ .output()+ .context("inspect the default PulseAudio/PipeWire input")?;+ if !sources.status.success() {+ anyhow::ensure!(+ role != PulseInputRole::SystemAudio,+ "Could not inspect Linux system-audio monitor sources"+ );+ return Ok(None);+ }+ let Some((source_index, source)) = pulse_input_route_destination(+ &String::from_utf8_lossy(&sources.stdout),+ role,+ default_source.as_deref(),+ default_sink.as_deref(),+ ) else {+ anyhow::ensure!(+ role != PulseInputRole::SystemAudio,+ "No Linux system-audio monitor source is available"+ );+ return Ok(None);+ };+ Ok(Some(Self {+ source,+ source_index,+ previous_outputs: current_process_source_outputs()?,+ }))+ }++ pub(crate) fn apply(+ self,+ input_callback_observed: &AtomicBool,+ cancel: &CancellationToken,+ ) -> anyhow::Result<()> {+ let output = wait_for_started_source_output(+ &self.previous_outputs,+ input_callback_observed,+ cancel,+ current_process_source_outputs,+ )?;+ if output.source != self.source_index {+ // Pulse remembers the generic ALSA application's last route, including speaker capture.+ move_pactl_source_output(output.id, &self.source)?;+ }+ Ok(())+ }+}++fn pulse_input_route_destination(+ sources: &str,+ role: PulseInputRole,+ default_source: Option<&str>,+ default_sink: Option<&str>,+) -> Option<(u32, String)> {+ match role {+ PulseInputRole::Microphone => {+ let source = default_source?;+ Some((pactl_source_index(sources, source)?, source.to_string()))+ }+ PulseInputRole::SystemAudio => sources+ .lines()+ .filter_map(|line| {+ let mut fields = line.split_whitespace();+ let index = fields.next()?.parse::<u32>().ok()?;+ let name = fields.next()?;+ let rank = pactl_monitor_preference(name, default_sink)?;+ Some((rank, name.to_ascii_lowercase(), index, name.to_string()))+ })+ .min()+ .map(|(_, _, index, name)| (index, name)),+ }+}++fn wait_for_started_source_output(+ previous_outputs: &[PactlSourceOutput],+ input_callback_observed: &AtomicBool,+ cancel: &CancellationToken,+ mut current_outputs: impl FnMut() -> anyhow::Result<Vec<PactlSourceOutput>>,+) -> anyhow::Result<PactlSourceOutput> {+ let started = Instant::now();+ while started.elapsed() < Duration::from_secs(3) {+ anyhow::ensure!(+ !cancel.is_cancelled(),+ "Linux input route confirmation cancelled"+ );+ let has_captured_audio = input_callback_observed.load(Ordering::Acquire);+ let outputs = current_outputs()?;+ if let Some(id) =+ started_input_source_output(previous_outputs, &outputs, has_captured_audio)?+ {+ return outputs+ .into_iter()+ .find(|output| output.id == id)+ .ok_or_else(|| anyhow!("The started PulseAudio/PipeWire input disappeared"));+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ bail!("The PulseAudio/PipeWire input did not start delivering audio within three seconds")+}++fn started_input_source_output(+ previous: &[PactlSourceOutput],+ current: &[PactlSourceOutput],+ input_callback_observed: bool,+) -> anyhow::Result<Option<u32>> {+ if !input_callback_observed+ || !current+ .iter()+ .any(|output| !previous.iter().any(|previous| previous.id == output.id))+ {+ return Ok(None);+ }+ newly_created_source_output(previous, current).map(Some)+}++fn uses_default_pulse_input(device_name: &str) -> bool {+ device_name.eq_ignore_ascii_case("default") || device_name.eq_ignore_ascii_case("pulse")+}+impl AudioSource for SystemAudioSource {type Config = SystemAudioSourceConfig;@@ -900,11 +1310,15 @@ impl AudioSource for SystemAudioSource {.await.with_context(|| format!("set up Linux system audio source '{device_name}'"))?;- if let Some(route) = config.monitor_route {- apply_pactl_monitor_route(&route)?;+ if let Some(route) = config.monitor_route.as_ref() {+ apply_pactl_monitor_route(route)?;}- Ok(Self { inner })+ Ok(Self {+ inner,+ monitor_route: config.monitor_route,+ feed: config.feed,+ })}}@@ -912,67 +1326,125 @@ impl AudioSource for SystemAudioSource {self.inner.audio_info()}- fn stop(&mut self) -> impl std::future::Future<Output = anyhow::Result<()>> + Send {- self.inner.stop()+ async fn stop(&mut self) -> anyhow::Result<()> {+ drop(self.monitor_route.take());+ self.inner.stop().await?;+ self.feed.actor.kill();+ self.feed.actor.wait_for_stop().await;+ self.feed.stopped = true;+ Ok(())}}async fn create_system_audio_source_config() -> anyhow::Result<SystemAudioSourceConfig> {- let selected = select_system_audio_monitor()?;-let (error_tx, _error_rx) = flume::bounded(16);- let feed = MicrophoneFeed::spawn(MicrophoneFeed::new(error_tx));- feed.ask(microphone::SetInput {- label: selected.device_name.clone(),- settings: None,- })- .await- .map_err(|e| anyhow!("Failed to set Linux system audio input: {e}"))?- .await- .with_context(|| {- format!(- "Linux system audio input '{}' failed to connect",- selected.device_name- )- })?;+ let feed = MicrophoneFeed::spawn(MicrophoneFeed::new_system_audio(error_tx));+ let owned_feed = OwnedSystemAudioFeed {+ actor: feed.clone(),+ build_scope: crate::output_pipeline::PipelineBuildScope::current(),+ stopped: false,+ };+ let (device_name, monitor_route) = retry_system_audio_connection(+ || async {+ let selected = select_system_audio_monitor()?;+ let device_name = selected.device_name.clone();+ feed.ask(microphone::SetInput {+ label: device_name.clone(),+ settings: None,+ })+ .await+ .map_err(|e| anyhow!("Failed to set Linux system audio input: {e}"))?+ .await+ .with_context(|| {+ format!("Linux system audio input '{device_name}' failed to connect")+ })?;- tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ tokio::time::sleep(Duration::from_millis(100)).await;++ let route = selected.into_monitor_route()?;+ if let Some(route) = route.as_ref() {+ apply_pactl_monitor_route(route)?;+ }+ let routed_at = cap_timestamp::Timestamps::now();+ let (sender, receiver) = flume::bounded(1);+ feed.ask(microphone::AddSender(sender.clone()))+ .await+ .map_err(|e| anyhow!("Failed to observe Linux system audio startup: {e}"))?;+ let ready = wait_for_audio_after_route(+ receiver.stream().map(|samples| samples.timestamp),+ routed_at,+ )+ .await;+ feed.ask(microphone::RemoveSender(sender))+ .await+ .map_err(|e| {+ anyhow!("Failed to detach the Linux system audio startup observer: {e}")+ })?;+ ready?;+ Ok((device_name, route))+ },+ || async {+ feed.ask(microphone::RemoveInput)+ .await+ .map_err(|e| anyhow!("Failed to close the unrouted Linux system audio input: {e}"))+ },+ )+ .await?;let lock = feed.ask(microphone::Lock).await.map_err(|e| anyhow!("Failed to lock Linux system audio input: {e}"))?;- let monitor_route = if let Some(monitor_source) = selected.monitor_source {- let current_source_outputs = current_process_source_outputs()?;- let source_output = newly_created_source_output(- &selected.previous_process_source_outputs,- ¤t_source_outputs,- )?;-- Some(PactlMonitorRoute {- monitor_source,- monitor_source_index: selected.monitor_source_index.ok_or_else(|| {- anyhow!("PulseAudio/PipeWire monitor source has no routing index")- })?,- default_source: selected.default_source,- default_source_index: selected.default_source_index,- source_output,- previous_process_source_outputs: selected.previous_process_source_outputs,- })- } else {- None- };-- if let Some(route) = monitor_route.as_ref() {- apply_pactl_monitor_route(route)?;- }-Ok(SystemAudioSourceConfig {feed_lock: Arc::new(lock),- device_name: selected.device_name,+ device_name,monitor_route,+ feed: owned_feed,+ })+}++async fn wait_for_audio_after_route(+ timestamps: impl Stream<Item = Timestamp>,+ routed_at: cap_timestamp::Timestamps,+) -> anyhow::Result<()> {+ futures::pin_mut!(timestamps);+ tokio::time::timeout(Duration::from_secs(3), async {+ while let Some(timestamp) = timestamps.next().await {+ if timestamp.checked_duration_since(routed_at).is_some() {+ return Ok(());+ }+ }+ bail!("Linux system audio input closed before delivering routed audio")})+ .await+ .context("Linux system audio input did not resume after routing within three seconds")?+}++async fn retry_system_audio_connection<T, ConnectFuture, DisconnectFuture>(+ mut connect: impl FnMut() -> ConnectFuture,+ mut disconnect: impl FnMut() -> DisconnectFuture,+) -> anyhow::Result<T>+where+ ConnectFuture: std::future::Future<Output = anyhow::Result<T>>,+ DisconnectFuture: std::future::Future<Output = anyhow::Result<()>>,+{+ let mut remaining_retries = 2;+ loop {+ match connect().await {+ Ok(input) => return Ok(input),+ Err(error) => {+ disconnect().await?;+ if remaining_retries == 0 {+ return Err(error)+ .context("Linux system audio could not reach the output monitor");+ }+ remaining_retries -= 1;+ tracing::warn!(%error, remaining_retries, "Reconnecting the Linux system-audio input after routing failed");+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ }+ }}struct SelectedSystemAudioInput {@@ -984,6 +1456,36 @@ struct SelectedSystemAudioInput {previous_process_source_outputs: Vec<PactlSourceOutput>,}+impl SelectedSystemAudioInput {+ fn into_monitor_route(self) -> anyhow::Result<Option<PactlMonitorRoute>> {+ let Some(monitor_source) = self.monitor_source else {+ return Ok(None);+ };+ let current_source_outputs = current_process_source_outputs()?;+ let source_output = newly_created_source_output(+ &self.previous_process_source_outputs,+ ¤t_source_outputs,+ )?;+ let original_source = current_source_outputs+ .iter()+ .find(|output| output.id == source_output)+ .ok_or_else(|| anyhow!("PulseAudio/PipeWire system-audio stream disappeared"))?+ .source;++ Ok(Some(PactlMonitorRoute {+ monitor_source,+ monitor_source_index: self.monitor_source_index.ok_or_else(|| {+ anyhow!("PulseAudio/PipeWire monitor source has no routing index")+ })?,+ default_source: self.default_source,+ default_source_index: self.default_source_index,+ source_output,+ original_source,+ previous_process_source_outputs: self.previous_process_source_outputs,+ }))+ }+}+#[derive(Debug, PartialEq, Eq)]struct PactlSourceOutput {id: u32,@@ -1253,18 +1755,59 @@ fn newly_created_source_output(}fn move_pactl_source_output(source_output: u32, source: &str) -> anyhow::Result<()> {+ let source_index = match source.parse::<u32>() {+ Ok(index) => index,+ Err(_) => {+ let sources = Command::new("pactl")+ .args(["list", "short", "sources"])+ .output()+ .context("resolve PulseAudio/PipeWire routing destination")?;+ if !sources.status.success() {+ bail!("Could not inspect PulseAudio/PipeWire routing destinations");+ }+ pactl_source_index(&String::from_utf8_lossy(&sources.stdout), source).ok_or_else(+ || anyhow!("PulseAudio/PipeWire routing destination '{source}' disappeared"),+ )?+ }+ };let status = Command::new("pactl").args(["move-source-output", &source_output.to_string(), source]).status().context("move PulseAudio/PipeWire system-audio stream")?;- if status.success() {- Ok(())- } else {+ if !status.success() {bail!("Could not route PulseAudio/PipeWire system-audio stream {source_output} to '{source}'"- )+ );+ }++ for _ in 0..10 {+ if source_output_route_matches(+ ¤t_process_source_outputs()?,+ source_output,+ source_index,+ )? {+ return Ok(());+ }+ std::thread::sleep(Duration::from_millis(20));}+ bail!(+ "PulseAudio/PipeWire acknowledged routing stream {source_output} to '{source}', but the input did not change"+ )+}++fn source_output_route_matches(+ outputs: &[PactlSourceOutput],+ source_output: u32,+ source_index: u32,+) -> anyhow::Result<bool> {+ outputs+ .iter()+ .find(|output| output.id == source_output)+ .map(|output| output.source == source_index)+ .ok_or_else(|| {+ anyhow!("PulseAudio/PipeWire stream {source_output} disappeared while routing")+ })}fn pulse_cpal_device_name(available_devices: &[String]) -> Option<String> {@@ -1857,9 +2400,86 @@ fn x11_source_pixel(#[cfg(test)]mod system_audio_tests {use super::{- PactlSourceOutput, newly_created_source_output, pactl_monitor_preference,- pactl_source_index, preferred_system_audio_device, previous_source_destination,- process_source_output_ids, source_output_needs_move,+ OwnedSystemAudioFeed, PactlSourceOutput, PulseInputRole, newly_created_source_output,+ pactl_monitor_preference, pactl_source_index, preferred_system_audio_device,+ previous_source_destination, process_source_output_ids, pulse_input_route_destination,+ retry_system_audio_connection, source_output_needs_move, source_output_route_matches,+ started_input_source_output, uses_default_pulse_input, wait_for_audio_after_route,+ wait_for_started_source_output,+ };+ use tokio_util::sync::CancellationToken;++ #[test]+ fn cancelled_system_route_does_not_probe_or_publish_a_stream() {+ let cancel = CancellationToken::new();+ cancel.cancel();+ let observed = std::sync::atomic::AtomicBool::new(true);+ let result = wait_for_started_source_output(&[], &observed, &cancel, || {+ panic!("cancelled route must not inspect Pulse")+ });+ assert!(result.is_err());+ }++ #[test]+ fn system_audio_reconnect_selects_output_monitor_instead_of_default_microphone() {+ let sources = "1\tmicrophone\n2\tother.monitor\n3\tspeakers.monitor\n";+ assert_eq!(+ pulse_input_route_destination(+ sources,+ PulseInputRole::SystemAudio,+ Some("microphone"),+ Some("speakers")+ ),+ Some((3, "speakers.monitor".to_string()))+ );+ }++ #[test]+ fn microphone_reconnect_retains_default_microphone_instead_of_output_monitor() {+ let sources = "1\tmicrophone\n2\tspeakers.monitor\n";+ assert_eq!(+ pulse_input_route_destination(+ sources,+ PulseInputRole::Microphone,+ Some("microphone"),+ Some("speakers")+ ),+ Some((1, "microphone".to_string()))+ );+ }++ #[test]+ fn system_audio_reconnect_does_not_fall_back_to_a_microphone() {+ assert_eq!(+ pulse_input_route_destination(+ "1\tmicrophone\n",+ PulseInputRole::SystemAudio,+ Some("microphone"),+ Some("speakers")+ ),+ None+ );+ }++ #[test]+ fn system_audio_reconnect_follows_the_current_default_output() {+ let sources = "1\tmicrophone\n2\told.monitor\n3\tnew.monitor\n";+ assert_eq!(+ pulse_input_route_destination(+ sources,+ PulseInputRole::SystemAudio,+ Some("microphone"),+ Some("new")+ ),+ Some((3, "new.monitor".to_string()))+ );+ }+ use crate::feeds::microphone::MicrophoneFeed;+ use cap_timestamp::{Timestamp, Timestamps};+ use kameo::Actor as _;+ use std::{+ sync::atomic::{AtomicBool, AtomicUsize, Ordering},+ time::{Duration, Instant},};#[test]@@ -1948,6 +2568,185 @@ mod system_audio_tests {assert!(newly_created_source_output(&previous, &ambiguous).is_err());}+ #[test]+ fn default_input_waits_for_capture_instead_of_selecting_a_probe_stream() {+ let previous = [PactlSourceOutput { id: 11, source: 3 }];+ let probing = [+ PactlSourceOutput { id: 11, source: 3 },+ PactlSourceOutput { id: 12, source: 3 },+ ];+ let capturing = [+ PactlSourceOutput { id: 11, source: 3 },+ PactlSourceOutput { id: 13, source: 2 },+ ];++ assert_eq!(+ started_input_source_output(&previous, &probing, false).unwrap(),+ None+ );+ assert_eq!(+ started_input_source_output(&previous, &capturing, true).unwrap(),+ Some(13)+ );+ assert_eq!(+ started_input_source_output(&previous, &previous, true).unwrap(),+ None+ );+ }++ #[test]+ fn pulse_input_accepts_a_buffered_first_callback() {+ let observed = AtomicBool::new(false);+ std::thread::scope(|scope| {+ let callback = scope.spawn(|| {+ std::thread::sleep(Duration::from_millis(650));+ observed.store(true, Ordering::Release);+ });+ let output =+ wait_for_started_source_output(&[], &observed, &CancellationToken::new(), || {+ Ok(vec![PactlSourceOutput { id: 12, source: 3 }])+ });+ callback.join().unwrap();+ assert_eq!(output.unwrap(), PactlSourceOutput { id: 12, source: 3 });+ });+ }++ #[tokio::test]+ async fn system_audio_retries_initial_input_connection_failures() {+ let attempts = AtomicUsize::new(0);+ let closed = AtomicUsize::new(0);+ let input = retry_system_audio_connection(+ || {+ let attempt = attempts.fetch_add(1, Ordering::Relaxed);+ assert_eq!(closed.load(Ordering::Relaxed), attempt);+ std::future::ready(if attempt == 0 {+ Err(anyhow::anyhow!("Default input route was not applied"))+ } else {+ Ok(42)+ })+ },+ || {+ closed.fetch_add(1, Ordering::Relaxed);+ std::future::ready(Ok(()))+ },+ )+ .await+ .unwrap();++ assert_eq!(input, 42);+ assert_eq!(attempts.load(Ordering::Relaxed), 2);+ assert_eq!(closed.load(Ordering::Relaxed), 1);+ }++ #[tokio::test]+ async fn system_audio_connection_retries_are_bounded_and_close_the_final_input() {+ let attempts = AtomicUsize::new(0);+ let closed = AtomicUsize::new(0);+ let result = retry_system_audio_connection(+ || {+ attempts.fetch_add(1, Ordering::Relaxed);+ std::future::ready(Err::<(), _>(anyhow::anyhow!("Input route was not applied")))+ },+ || {+ closed.fetch_add(1, Ordering::Relaxed);+ std::future::ready(Ok(()))+ },+ )+ .await;++ assert!(result.is_err());+ assert_eq!(attempts.load(Ordering::Relaxed), 3);+ assert_eq!(closed.load(Ordering::Relaxed), 3);+ }++ #[tokio::test]+ async fn system_audio_does_not_reconnect_when_the_previous_input_cannot_close() {+ let attempts = AtomicUsize::new(0);+ let result = retry_system_audio_connection(+ || {+ attempts.fetch_add(1, Ordering::Relaxed);+ std::future::ready(Err::<(), _>(anyhow::anyhow!("Input route was not applied")))+ },+ || std::future::ready(Err(anyhow::anyhow!("Input is still locked"))),+ )+ .await;++ assert_eq!(result.unwrap_err().to_string(), "Input is still locked");+ assert_eq!(attempts.load(Ordering::Relaxed), 1);+ }++ #[tokio::test]+ async fn system_audio_waits_for_samples_captured_after_the_route_change() {+ let routed_at = Timestamps::now();+ let (sender, receiver) = flume::bounded(2);+ sender+ .send(Timestamp::Instant(+ routed_at+ .instant()+ .checked_sub(Duration::from_millis(100))+ .unwrap(),+ ))+ .unwrap();+ let ready = wait_for_audio_after_route(receiver.stream(), routed_at);+ tokio::pin!(ready);+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut ready)+ .await+ .is_err()+ );+ sender.send(Timestamp::Instant(Instant::now())).unwrap();+ ready.await.unwrap();+ }++ #[tokio::test]+ async fn system_audio_readiness_rejects_a_closed_input() {+ let result = wait_for_audio_after_route(futures::stream::empty(), Timestamps::now()).await;+ assert!(result.is_err());+ }++ #[tokio::test]+ async fn system_audio_releases_its_feed_even_when_other_references_remain() {+ let (error_tx, _error_rx) = flume::bounded(1);+ let feed = MicrophoneFeed::spawn(MicrophoneFeed::new(error_tx));+ feed.wait_for_startup().await;+ assert!(feed.is_alive());++ let owned = OwnedSystemAudioFeed {+ actor: feed.clone(),+ build_scope: None,+ stopped: false,+ };+ drop(owned);++ tokio::time::timeout(Duration::from_secs(1), feed.wait_for_stop())+ .await+ .unwrap();+ assert!(!feed.is_alive());+ }++ #[tokio::test]+ async fn failed_resume_scope_joins_its_private_system_audio_actor_shutdown() {+ let (error_tx, _error_rx) = flume::bounded(1);+ let feed = MicrophoneFeed::spawn(MicrophoneFeed::new(error_tx));+ feed.wait_for_startup().await;+ let scope = crate::output_pipeline::PipelineBuildScope::new();+ let owned = scope+ .run(async {+ OwnedSystemAudioFeed {+ actor: feed.clone(),+ build_scope: crate::output_pipeline::PipelineBuildScope::current(),+ stopped: false,+ }+ })+ .await;+ drop(owned);+ tokio::time::timeout(Duration::from_secs(1), scope.cancel_and_join())+ .await+ .unwrap()+ .unwrap();+ assert!(!feed.is_alive());+ }+#[test]fn remembered_monitor_input_returns_to_selected_microphone() {assert_eq!(@@ -1978,6 +2777,33 @@ mod system_audio_tests {assert_eq!(pactl_source_index(sources, "microphone.monitor"), Some(3));assert_eq!(pactl_source_index(sources, "missing.monitor"), None);}++ #[test]+ fn routing_acknowledgement_requires_the_requested_source() {+ let unchanged = [PactlSourceOutput {+ id: 1128,+ source: 61,+ }];+ let routed = [PactlSourceOutput {+ id: 1128,+ source: 47,+ }];++ assert!(!source_output_route_matches(&unchanged, 1128, 47).unwrap());+ assert!(source_output_route_matches(&routed, 1128, 47).unwrap());+ assert!(source_output_route_matches(&[], 1128, 47).is_err());+ assert!(source_output_route_matches(&routed, 1129, 47).is_err());+ }++ #[test]+ fn only_generic_pulse_devices_follow_the_default_input() {+ assert!(uses_default_pulse_input("default"));+ assert!(uses_default_pulse_input("PULSE"));+ assert!(!uses_default_pulse_input("USB Microphone"));+ assert!(!uses_default_pulse_input("desktop.monitor"));+ assert!(!uses_default_pulse_input("hw:1,0"));+ assert!(!uses_default_pulse_input("pipewire"));+ }}#[cfg(test)]diff --git a/crates/recording/src/sources/screen_capture/windows.rs b/crates/recording/src/sources/screen_capture/windows.rsindex a1f8f5171..3168d7601 100644--- a/crates/recording/src/sources/screen_capture/windows.rs+++ b/crates/recording/src/sources/screen_capture/windows.rs@@ -422,6 +422,31 @@ pub struct VideoSourceConfig {pub struct VideoSource {video_info: VideoInfo,ctrl_tx: std::sync::mpsc::SyncSender<VideoControl>,+ first_frame: Option<oneshot::Receiver<Result<(), String>>>,+}++#[derive(Clone)]+struct FirstScreenFrame(Arc<Mutex<Option<oneshot::Sender<Result<(), String>>>>>);++impl FirstScreenFrame {+ fn complete(&self, result: Result<(), String>) {+ if let Ok(mut sender) = self.0.lock()+ && let Some(sender) = sender.take()+ {+ let _ = sender.send(result);+ }+ }+}++async fn wait_for_first_screen_frame(+ receiver: oneshot::Receiver<Result<(), String>>,+ timeout: Duration,+) -> anyhow::Result<()> {+ tokio::time::timeout(timeout, receiver)+ .await+ .map_err(|_| anyhow!("Windows screen capture produced no accepted frame within 5s"))?+ .map_err(|_| anyhow!("Windows screen capture closed before its first frame"))?+ .map_err(anyhow::Error::msg)}enum VideoControl {@@ -477,6 +502,7 @@ struct CreateCapturerParams<'a> {scaling_logged: Arc<AtomicBool>,scaled_frame_count: Arc<AtomicU32>,stall_health_tx: output_pipeline::HealthSender,+ first_frame: FirstScreenFrame,}fn create_d3d_capturer(@@ -504,8 +530,13 @@ fn create_d3d_capturer(let scaling_logged = params.scaling_logged.clone();let scaled_frame_count = params.scaled_frame_count.clone();let stall_health_tx = params.stall_health_tx.clone();+ let first_frame = params.first_frame.clone();move |frame| {+ let result = (|| {let capture_time = frame.inner().SystemRelativeTime()?;+ if frame.width() == 0 || frame.height() == 0 {+ return Err(windows::core::Error::new(windows::Win32::Foundation::E_INVALIDARG, "Empty screen frame"));+ }// WGC delivers a frame per screen update — up to the monitor// refresh rate on systems without MinUpdateInterval support —@@ -518,9 +549,9 @@ fn create_d3d_capturer(return Ok(());}- let timestamp = Timestamp::PerformanceCounter(PerformanceCounterTimestamp::new(- capture_time.Duration,- ));+ let timestamp = Timestamp::PerformanceCounter(+ PerformanceCounterTimestamp::from_100ns(capture_time.Duration),+ );let frame_width = frame.width();let frame_height = frame.height();@@ -582,6 +613,7 @@ fn create_d3d_capturer() {output_pipeline::StallSendOutcome::Sent => {video_frame_counter.fetch_add(1, atomic::Ordering::Relaxed);+ first_frame.complete(Ok(()));}output_pipeline::StallSendOutcome::StalledAndDropped { .. }| output_pipeline::StallSendOutcome::Disconnected => {@@ -589,9 +621,15 @@ fn create_d3d_capturer(}}Ok(())+ })();+ if let Err(error) = &result {+ first_frame.complete(Err(format!("Windows first screen frame failed: {error}")));+ }+ result}},{+ let first_frame = params.first_frame.clone();let mut err_tx = error_tx.clone();let device_for_callback = params.d3d_device.clone();move || {@@ -603,6 +641,7 @@ fn create_d3d_capturer(CaptureClosureKind::TargetLost => "capture target lost".to_string(),CaptureClosureKind::Transient => "capture closed".to_string(),};+ first_frame.complete(Err(message.clone()));drop(err_tx.try_send(CaptureClosureEvent { kind, message }));Ok(())}@@ -633,6 +672,8 @@ impl output_pipeline::VideoSource for VideoSource {let (ctrl_tx, ctrl_rx) = std::sync::mpsc::sync_channel::<VideoControl>(4);let monitor_ctrl_tx = ctrl_tx.clone();+ let (first_tx, first_rx) = oneshot::channel();+ let first_frame = FirstScreenFrame(Arc::new(Mutex::new(Some(first_tx))));let tokio_rt = tokio::runtime::Handle::current();let restart_counter: Arc<AtomicU32> = Arc::new(AtomicU32::new(0));@@ -693,6 +734,7 @@ impl output_pipeline::VideoSource for VideoSource {scaling_logged: scaling_logged.clone(),scaled_frame_count: scaled_frame_count.clone(),stall_health_tx: stats_health_tx.clone(),+ first_frame: first_frame.clone(),}};}@@ -966,6 +1008,7 @@ impl output_pipeline::VideoSource for VideoSource {Ok(Self {video_info,ctrl_tx,+ first_frame: Some(first_rx),})}@@ -977,9 +1020,20 @@ impl output_pipeline::VideoSource for VideoSource {let (tx, rx) = oneshot::channel();let _ = self.ctrl_tx.send(VideoControl::Start(tx));- async {- rx.await??;- Ok(())+ let first_frame = self.first_frame.take();+ async move {+ tokio::time::timeout(Duration::from_secs(5), async move {+ rx.await??;+ wait_for_first_screen_frame(+ first_frame.ok_or_else(|| anyhow!("Windows screen source already started"))?,+ Duration::from_secs(5),+ )+ .await+ })+ .await+ .map_err(|_| {+ anyhow!("Windows screen startup did not acknowledge an accepted frame within 5s")+ })?}.boxed()}@@ -1118,6 +1172,8 @@ fn create_system_audio_capturer(let device_info = Direct3DCapture::audio_info();let target_info = crate::sources::audio_mixer::AudioMixer::INFO;let device_differs_from_target = !device_info.matches_format(&target_info);+ let mut capture_clock =+ crate::sources::capture_clock::CaptureClock::new(cap_timestamp::Timestamps::now());let mut resampler = if device_differs_from_target {info!(@@ -1154,7 +1210,16 @@ fn create_system_audio_capturer(}});- let timestamp = Timestamp::from_cpal(info.timestamp().capture);+ let buffer_duration = Duration::from_secs_f64(+ data.len() as f64+ / f64::from(config.channels.max(1))+ / f64::from(config.sample_rate.0.max(1)),+ );+ let timestamp = capture_clock.timestamp(+ Timestamp::from_cpal(info.timestamp().capture),+ std::time::Instant::now(),+ buffer_duration,+ );let raw_frame = data.as_ffmpeg(config);let frame = if let Some(ref mut ctx) = resampler {@@ -1210,7 +1275,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {whereSelf: Sized,{- let cancel_token = CancellationToken::new();+ let cancel_token = ctx.stop_token().child_token();ctx.tasks().spawn("system-audio", {let cancel = cancel_token.clone();@@ -1249,6 +1314,7 @@ impl output_pipeline::AudioSource for SystemAudioSource {}));let stall_health_tx_for_watcher = ctx.health_tx().clone();+ let runtime = tokio::runtime::Handle::current();ctx.tasks().spawn_thread("system-audio-watcher", {let state = state.clone();let mut watcher_tx = tx.clone();@@ -1267,9 +1333,12 @@ impl output_pipeline::AudioSource for SystemAudioSource {.ceil() as usize;loop {- std::thread::sleep(DEVICE_POLL_INTERVAL);-- if cancel.is_cancelled() {+ if runtime+ .block_on(async {+ tokio::time::timeout(DEVICE_POLL_INTERVAL, cancel.cancelled()).await+ })+ .is_ok()+ {break;}@@ -1474,3 +1543,56 @@ impl output_pipeline::AudioSource for SystemAudioSource {async { Ok(()) }}}++#[cfg(test)]+mod first_screen_frame_tests {+ use super::*;++ fn signal() -> (FirstScreenFrame, oneshot::Receiver<Result<(), String>>) {+ let (sender, receiver) = oneshot::channel();+ (+ FirstScreenFrame(Arc::new(Mutex::new(Some(sender)))),+ receiver,+ )+ }++ #[tokio::test]+ async fn accepted_frame_acknowledges_startup_once() {+ let (signal, receiver) = signal();+ signal.complete(Ok(()));+ signal.complete(Err("later close".into()));+ wait_for_first_screen_frame(receiver, Duration::from_millis(20))+ .await+ .unwrap();+ }++ #[tokio::test]+ async fn early_closed_source_cannot_become_ready_on_a_late_frame() {+ let (signal, receiver) = signal();+ signal.complete(Err("capture target lost".into()));+ signal.complete(Ok(()));+ let error = wait_for_first_screen_frame(receiver, Duration::from_millis(20))+ .await+ .unwrap_err();+ assert!(error.to_string().contains("capture target lost"));+ }++ #[tokio::test]+ async fn no_accepted_screen_frame_is_a_startup_error() {+ let (_signal, receiver) = signal();+ let error = wait_for_first_screen_frame(receiver, Duration::from_millis(1))+ .await+ .unwrap_err();+ assert!(error.to_string().contains("no accepted frame"));+ }++ #[tokio::test]+ async fn dropped_capture_thread_is_not_startup_success() {+ let (signal, receiver) = signal();+ drop(signal);+ let error = wait_for_first_screen_frame(receiver, Duration::from_millis(20))+ .await+ .unwrap_err();+ assert!(error.to_string().contains("closed before its first frame"));+ }+}diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 909f23369..e3dde9e78 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -83,8 +83,169 @@ enum ActorState {},}+#[cfg(target_os = "linux")]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StudioQuiescence {+ Pending,+ Joined,+ Unconfirmed,+}++#[cfg(any(target_os = "linux", windows))]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StudioStopIntent {+ Preserve,+ Discard,+}++#[cfg(target_os = "linux")]+#[derive(Clone)]+pub struct StudioStopReport {+ pub accepted_intent: bool,+ pub quiescence: StudioQuiescence,+ pub result: Result<CompletedRecording, String>,+}++#[cfg(target_os = "linux")]+#[derive(Clone)]+pub struct StudioLifecycle(Arc<StudioLifecycleInner>);++#[cfg(target_os = "linux")]+struct StudioLifecycleInner {+ scope: crate::output_pipeline::PipelineBuildScope,+ state: watch::Sender<StudioQuiescence>,+ failure: std::sync::Mutex<Option<String>>,+ terminal: tokio::sync::Mutex<Option<(StudioStopIntent, StudioStopReport)>>,+ terminal_started: std::sync::atomic::AtomicBool,+ runtime: std::sync::Mutex<Option<tokio::runtime::Handle>>,+}++#[cfg(target_os = "linux")]+impl StudioLifecycle {+ fn new() -> Self {+ let (state, _) = watch::channel(StudioQuiescence::Pending);+ Self(Arc::new(StudioLifecycleInner {+ scope: crate::output_pipeline::PipelineBuildScope::new_studio_lifetime(),+ state,+ failure: std::sync::Mutex::new(None),+ terminal: tokio::sync::Mutex::new(None),+ terminal_started: std::sync::atomic::AtomicBool::new(false),+ runtime: std::sync::Mutex::new(tokio::runtime::Handle::try_current().ok()),+ }))+ }++ fn fail(&self, error: String) {+ self.0.failure.lock().unwrap().get_or_insert(error);+ }++ fn failure(&self) -> Option<String> {+ self.0.failure.lock().unwrap().clone()+ }++ pub fn quiescence(&self) -> StudioQuiescence {+ *self.0.state.borrow()+ }++ pub fn terminal_started(&self) -> bool {+ self.0+ .terminal_started+ .load(std::sync::atomic::Ordering::Acquire)+ }++ pub fn same_attempt(&self, other: &Self) -> bool {+ Arc::ptr_eq(&self.0, &other.0)+ }++ pub fn cancel(&self) {+ self.0.scope.cancel();+ }++ pub async fn wait_for_quiescence(&self) -> StudioQuiescence {+ let mut state = self.0.state.subscribe();+ loop {+ let value = *state.borrow_and_update();+ if value != StudioQuiescence::Pending {+ return value;+ }+ if state.changed().await.is_err() {+ return StudioQuiescence::Unconfirmed;+ }+ }+ }++ async fn join(&self) -> StudioQuiescence {+ let report = self.0.scope.cancel_and_join_report().await;+ if let Some(error) = report.error {+ self.fail(error);+ }+ let state = if report.quiescent {+ StudioQuiescence::Joined+ } else {+ StudioQuiescence::Unconfirmed+ };+ self.0.state.send_if_modified(|current| {+ if *current == StudioQuiescence::Unconfirmed {+ return false;+ }+ *current = state;+ true+ });+ self.quiescence()+ }+}++#[cfg(target_os = "linux")]+struct StudioLifetimeOwner {+ lifecycle: StudioLifecycle,+ armed: bool,+}++#[cfg(target_os = "linux")]+impl Drop for StudioLifetimeOwner {+ fn drop(&mut self) {+ if !self.armed {+ return;+ }+ self.lifecycle.cancel();+ let lifecycle = self.lifecycle.clone();+ let runtime = lifecycle.0.runtime.lock().unwrap().clone();+ if let Some(runtime) = runtime {+ drop(runtime.spawn(async move {+ lifecycle.join().await;+ }));+ } else {+ lifecycle+ .0+ .state+ .send_replace(StudioQuiescence::Unconfirmed);+ }+ }+}++#[cfg(windows)]+#[derive(Clone)]+pub struct WindowsStudioStopReport {+ pub accepted_intent: bool,+ pub stop_acknowledged: bool,+ pub result: Result<CompletedRecording, String>,+}++#[cfg(windows)]+#[derive(Default)]+struct WindowsStudioTerminal {+ result: tokio::sync::Mutex<Option<(StudioStopIntent, WindowsStudioStopReport)>>,+ started: std::sync::atomic::AtomicBool,+ acknowledged: std::sync::atomic::AtomicBool,+}+#[derive(Clone)]pub struct ActorHandle {+ #[cfg(target_os = "linux")]+ lifecycle: StudioLifecycle,+ #[cfg(any(target_os = "linux", windows))]+ recording_dir: PathBuf,+ #[cfg(windows)]+ terminal: Arc<WindowsStudioTerminal>,actor_ref: kameo::actor::ActorRef<Actor>,pub capture_target: screen_capture::ScreenCaptureTarget,done_fut: DoneFut,@@ -93,9 +254,19 @@ pub struct ActorHandle {#[derive(kameo::Actor)]pub struct Actor {+ #[cfg(target_os = "linux")]+ lifetime: StudioLifetimeOwner,recording_dir: PathBuf,state: Option<ActorState>,+ #[cfg(windows)]+ cancel_error: Option<String>,segment_factory: SegmentPipelineFactory,+ #[cfg(target_os = "linux")]+ resume_attempt: Option<ResumeAttempt>,+ #[cfg(target_os = "linux")]+ resume_generation: u64,+ #[cfg(target_os = "linux")]+ resume_cleanup_error: Option<String>,segments: Vec<RecordingSegment>,completion_tx: watch::Sender<Option<Result<(), PipelineDoneError>>>,// Resolved once at recording start: the display can be disconnected, or its@@ -104,6 +275,38 @@ pub struct Actor {}impl Actor {+ #[cfg(target_os = "linux")]+ async fn cancel_resume(&mut self) -> anyhow::Result<()> {+ if let Some(mut attempt) = self.resume_attempt.take() {+ attempt.scope.cancel();+ let finished = attempt.finished.clone().await;+ let result = attempt.result.lock().unwrap().take();+ let cleanup = match result {+ Some(Err(error)) if error.quiescent => Ok(()),+ Some(Err(error)) => {+ let cleanup = attempt.scope.cancel_and_join().await;+ Err(cleanup.err().map_or(error.message.clone(), |cleanup| {+ format!("{}; {cleanup}", error.message)+ }))+ }+ result => {+ discard_resume_pipeline(+ result.and_then(Result::ok),+ &attempt.scope,+ &attempt.directory,+ )+ .await+ }+ };+ attempt.reply(Err("Recording resume was cancelled".into()));+ self.resume_cleanup_error = cleanup.err().or_else(|| finished.err());+ }+ if let Some(error) = &self.resume_cleanup_error {+ bail!("Resume cleanup is unconfirmed: {error}");+ }+ Ok(())+ }+async fn stop_pipeline(&mut self,pipeline: Pipeline,@@ -111,15 +314,31 @@ impl Actor {) -> anyhow::Result<(Cursors, u32)> {tracing::info!("pipeline shutting down");- let mut pipeline = pipeline.stop().await?;+ let stopped = pipeline.stop().await;+ #[cfg(windows)]+ let stopped = stopped.map_err(|error| self.preserve_windows_stop_failure(error));+ let mut pipeline = stopped?;tracing::info!("pipeline shutdown");let segment_stop_time = current_time_f64();- let cursors = if let Some(cursor) = pipeline.cursor.as_mut()- && let Ok(res) = cursor.actor.rx.clone().await- {+ let cursor_result = if let Some(cursor) = pipeline.cursor.as_mut() {+ match cursor.actor.rx.clone().await {+ Ok(result) => Some((cursor, result)),+ Err(_error) => {+ #[cfg(windows)]+ return Err(self.preserve_windows_stop_failure(anyhow!(+ "Cursor shutdown acknowledgement failed: {_error}"+ )));+ #[cfg(not(windows))]+ None+ }+ }+ } else {+ None+ };+ let cursors = if let Some((cursor, res)) = cursor_result {if let Some(output_path) = cursor.output_path.as_ref() {std::fs::write(output_path,@@ -159,6 +378,29 @@ impl Actor {Ok(cursors)}+ #[cfg(windows)]+ fn windows_failure(&self) -> Option<String> {+ self.cancel_error.clone().or_else(|| {+ self.completion_tx+ .borrow()+ .as_ref()+ .and_then(|result| result.as_ref().err().map(ToString::to_string))+ })+ }++ #[cfg(windows)]+ fn preserve_windows_stop_failure(&mut self, error: anyhow::Error) -> anyhow::Error {+ let error = match persist_failed_recording(&self.recording_dir, &format!("{error:#}")) {+ Ok(()) => error,+ Err(persist) => error.context(format!(+ "Could not persist failed Studio metadata: {persist:#}"+ )),+ };+ self.cancel_error+ .get_or_insert_with(|| format!("{error:#}"));+ error+ }+fn notify_completion_ok(&self) {if self.completion_tx.borrow().is_none() {let _ = self.completion_tx.send(Some(Ok(())));@@ -170,6 +412,8 @@ impl Message<Stop> for Actor {type Reply = anyhow::Result<CompletedRecording>;async fn handle(&mut self, _: Stop, ctx: &mut Context<Self, Self::Reply>) -> Self::Reply {+ #[cfg(target_os = "linux")]+ self.cancel_resume().await?;let cursors = match self.state.take() {Some(ActorState::Recording {pipeline,@@ -191,12 +435,25 @@ impl Message<Stop> for Actor {ctx.actor_ref().stop_gracefully().await?;+ #[cfg(target_os = "linux")]+ let known_failure = {+ if self.lifetime.lifecycle.join().await != StudioQuiescence::Joined {+ bail!("Studio capture cleanup is unconfirmed; recording preserved");+ }+ self.lifetime.lifecycle.failure()+ };+ #[cfg(windows)]+ let known_failure = self.windows_failure();+ #[cfg(not(any(target_os = "linux", windows)))]+ let known_failure = None;+let recording = stop_recording(self.recording_dir.clone(),std::mem::take(&mut self.segments),cursors,self.segment_factory.fragmented,self.display_notch,+ known_failure,).await?;@@ -212,6 +469,8 @@ impl Message<Pause> for Actor {type Reply = anyhow::Result<()>;async fn handle(&mut self, _: Pause, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ #[cfg(target_os = "linux")]+ self.cancel_resume().await?;self.state = match self.state.take() {Some(ActorState::Recording {pipeline,@@ -237,8 +496,295 @@ impl Message<Pause> for Actor {}}+#[cfg(target_os = "linux")]+type ResumeCompletion =+ futures::future::Shared<futures::future::BoxFuture<'static, Result<(), String>>>;++#[cfg(target_os = "linux")]+struct ResumeBuildError {+ message: String,+ quiescent: bool,+}++#[cfg(target_os = "linux")]+struct ResumeAttempt {+ generation: u64,+ scope: crate::output_pipeline::PipelineBuildScope,+ directory: PathBuf,+ result: Arc<std::sync::Mutex<Option<Result<Pipeline, ResumeBuildError>>>>,+ finished: ResumeCompletion,+ ready: ResumeCompletion,+ reply: Option<tokio::sync::oneshot::Sender<Result<(), String>>>,+}++#[cfg(target_os = "linux")]+struct ResumeWaiterGuard(crate::output_pipeline::PipelineBuildScope);++#[cfg(target_os = "linux")]+impl Drop for ResumeWaiterGuard {+ fn drop(&mut self) {+ self.0.cancel();+ }+}++#[cfg(target_os = "linux")]+impl ResumeAttempt {+ fn ready_future(&self) -> futures::future::BoxFuture<'static, anyhow::Result<()>> {+ let ready = self.ready.clone();+ let cancellation = ResumeWaiterGuard(self.scope.clone());+ async move {+ let _cancellation = cancellation;+ ready.await.map_err(anyhow::Error::msg)+ }+ .boxed()+ }++ fn reply(&mut self, result: Result<(), String>) {+ if let Some(reply) = self.reply.take() {+ let _ = reply.send(result);+ }+ }+}++#[cfg(target_os = "linux")]+async fn discard_resume_pipeline(+ pipeline: Option<Pipeline>,+ scope: &crate::output_pipeline::PipelineBuildScope,+ directory: &Path,+) -> Result<(), String> {+ scope.cancel();+ let mut cursor_error = None;+ if let Some(mut pipeline) = pipeline {+ if let Some(mut cursor) = pipeline.cursor.take() {+ cursor_error = tokio::task::spawn_blocking(move || cursor.actor.stop())+ .await+ .err()+ .map(|error| format!("Cursor setup cleanup failed: {error}"));+ }+ drop(pipeline);+ }+ scope.cancel_and_join().await?;+ if let Some(error) = cursor_error {+ return Err(error);+ }+ match tokio::fs::remove_dir_all(directory).await {+ Ok(()) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(error) => Err(format!(+ "Failed to remove discarded resume segment: {error}"+ )),+ }+}++#[cfg(target_os = "linux")]+async fn prepare_resume_pipeline(+ factory: &mut SegmentPipelineFactory,+ cursors: Cursors,+ next_cursor_id: u32,+ scope: &crate::output_pipeline::PipelineBuildScope,+ directory: &Path,+) -> Result<Pipeline, ResumeBuildError> {+ let cancellation = scope.cancellation();+ let prepared = scope.run(async {+ tokio::select! {+ biased;+ _ = cancellation.cancelled() => Err("Recording resume was cancelled".to_string()),+ result = std::panic::AssertUnwindSafe(factory.prepare_next(cursors, next_cursor_id)).catch_unwind() => {+ match result {+ Ok(result) => result.map_err(|error| format!("{error:#}")),+ Err(_) => Err("Recording resume setup panicked".to_string()),+ }+ }+ }+ }).await;+ let (pipeline, message) = match prepared {+ Ok(pipeline) if !cancellation.is_cancelled() => return Ok(pipeline),+ Ok(pipeline) => (Some(pipeline), "Recording resume was cancelled".to_string()),+ Err(message) => (None, message),+ };+ let cleanup = discard_resume_pipeline(pipeline, scope, directory).await;+ Err(ResumeBuildError {+ message: cleanup.as_ref().err().map_or(message.clone(), |cleanup| {+ format!("{message}; cleanup unconfirmed: {cleanup}")+ }),+ quiescent: cleanup.is_ok(),+ })+}++#[cfg(target_os = "linux")]+struct ResumeFinished(u64);++#[cfg(target_os = "linux")]+impl Message<ResumeFinished> for Actor {+ type Reply = ();++ async fn handle(&mut self, msg: ResumeFinished, _: &mut Context<Self, Self::Reply>) {+ if self+ .resume_attempt+ .as_ref()+ .is_none_or(|attempt| attempt.generation != msg.0)+ {+ return;+ }+ let mut attempt = self.resume_attempt.take().unwrap();+ let result = attempt.result.lock().unwrap().take();+ match result {+ Some(Ok(mut pipeline)) if !attempt.scope.cancellation().is_cancelled() => {+ if let Some(error) = pipeline.completed_before_resume() {+ let cleanup =+ discard_resume_pipeline(Some(pipeline), &attempt.scope, &attempt.directory)+ .await;+ self.resume_cleanup_error = cleanup.err();+ attempt.reply(Err(error));+ return;+ }+ if let Some(ActorState::Paused { next_index, .. }) = self.state.as_ref()+ && attempt.scope.commit()+ {+ let index = *next_index;+ self.segment_factory.commit_next(&mut pipeline);+ self.state = Some(ActorState::Recording {+ pipeline,+ index,+ segment_start_time: current_time_f64(),+ segment_start_instant: Instant::now(),+ });+ attempt.reply(Ok(()));+ } else {+ let cleanup =+ discard_resume_pipeline(Some(pipeline), &attempt.scope, &attempt.directory)+ .await;+ self.resume_cleanup_error = cleanup.err();+ attempt.reply(Err("Recording changed during resume".into()));+ }+ }+ Some(Err(error)) => {+ if !error.quiescent {+ self.resume_cleanup_error = Some(error.message.clone());+ }+ attempt.reply(Err(error.message));+ }+ result => {+ let pipeline = result.and_then(Result::ok);+ let cleanup =+ discard_resume_pipeline(pipeline, &attempt.scope, &attempt.directory).await;+ self.resume_cleanup_error = cleanup.err();+ attempt.reply(Err("Recording resume was cancelled".into()));+ }+ }+ }+}+struct Resume;+#[cfg(target_os = "linux")]+impl Message<Resume> for Actor {+ type Reply = anyhow::Result<futures::future::BoxFuture<'static, anyhow::Result<()>>>;++ async fn handle(&mut self, _: Resume, ctx: &mut Context<Self, Self::Reply>) -> Self::Reply {+ if self+ .completion_tx+ .borrow()+ .as_ref()+ .is_some_and(Result::is_err)+ {+ bail!("A requested recording track failed; stop and preserve this recording");+ }+ if let Some(error) = &self.resume_cleanup_error {+ bail!("Previous resume cleanup is unconfirmed: {error}");+ }+ if let Some(attempt) = &self.resume_attempt {+ return Ok(attempt.ready_future());+ }+ let (cursors, next_cursor_id) = match &self.state {+ Some(ActorState::Paused {+ cursors,+ next_cursor_id,+ ..+ }) => (cursors.clone(), *next_cursor_id),+ Some(ActorState::Recording { .. }) => return Ok(async { Ok(()) }.boxed()),+ None => bail!("Recording is no longer active"),+ };+ let mut factory = self.segment_factory.clone();+ let directory = factory+ .segments_dir+ .join(format!("segment-{}", factory.index));+ if directory.try_exists()? {+ bail!(+ "Resume segment directory already exists; stop and recover the recording before retrying"+ );+ }+ self.resume_generation = self.resume_generation.wrapping_add(1);+ let generation = self.resume_generation;+ let scope = self.lifetime.lifecycle.0.scope.child_transaction();+ let lifetime_completion = self.lifetime.lifecycle.0.scope.task_completion();+ let result = Arc::new(std::sync::Mutex::new(None));+ let (finished_tx, finished_rx) = tokio::sync::oneshot::channel();+ let (reply, ready) = tokio::sync::oneshot::channel();+ let attempt = ResumeAttempt {+ generation,+ scope: scope.clone(),+ directory: directory.clone(),+ result: result.clone(),+ finished: async move {+ finished_rx+ .await+ .map_err(|_| "Resume setup task exited unexpectedly".to_string())+ }+ .boxed()+ .shared(),+ ready: async move {+ ready+ .await+ .map_err(|_| "Resume acknowledgement was lost".to_string())?+ }+ .boxed()+ .shared(),+ reply: Some(reply),+ };+ let ready = attempt.ready_future();+ self.resume_attempt = Some(attempt);+ let actor = ctx.actor_ref().clone();+ drop(tokio::spawn(async move {+ let prepared = std::panic::AssertUnwindSafe(prepare_resume_pipeline(+ &mut factory,+ cursors,+ next_cursor_id,+ &scope,+ &directory,+ ))+ .catch_unwind()+ .await+ .unwrap_or_else(|_| {+ scope.cancel();+ Err(ResumeBuildError {+ message: "Resume setup or cleanup panicked; capture quiescence is unconfirmed"+ .into(),+ quiescent: false,+ })+ });+ *result.lock().unwrap() = Some(prepared);+ let _ = finished_tx.send(());+ let _ = notify_after_capture_publication(+ lifetime_completion,+ actor.tell(ResumeFinished(generation)),+ )+ .await;+ }));+ Ok(ready)+ }+}++#[cfg(target_os = "linux")]+async fn notify_after_capture_publication<T>(+ completion: crate::output_pipeline::BuildTaskCompletion,+ notification: impl std::future::IntoFuture<Output = T>,+) -> T {+ drop(completion);+ notification.await+}++#[cfg(not(target_os = "linux"))]impl Message<Resume> for Actor {type Reply = anyhow::Result<()>;@@ -252,7 +798,10 @@ impl Message<Resume> for Actor {let pipeline = self.segment_factory.create_next(cursors, next_cursor_id)- .await?;+ .await;+ #[cfg(windows)]+ let pipeline = pipeline.map_err(|error| self.preserve_windows_stop_failure(error));+ let pipeline = pipeline?;let new_segment_start_time = current_time_f64();@@ -276,14 +825,33 @@ impl Message<Cancel> for Actor {type Reply = anyhow::Result<()>;async fn handle(&mut self, _: Cancel, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ #[cfg(target_os = "linux")]+ self.cancel_resume().await?;+ #[cfg(windows)]+ if let Some(error) = &self.cancel_error {+ bail!("Previous capture cancellation failed: {error}");+ }if let Some(ActorState::Recording { pipeline, .. }) = self.state.take() {if let Err(e) = pipeline.stop().await {+ #[cfg(windows)]+ {+ return Err(self.preserve_windows_stop_failure(e));+ }+ #[cfg(not(windows))]warn!("Pipeline stop error during cancel: {e:#}");}+ #[cfg(windows)]+ if let Some(error) = self.windows_failure() {+ return Err(self.preserve_windows_stop_failure(anyhow!(error)));+ }self.notify_completion_ok();}+ #[cfg(windows)]+ if let Some(error) = self.windows_failure() {+ return Err(self.preserve_windows_stop_failure(anyhow!(error)));+ }Ok(())}}@@ -296,6 +864,10 @@ impl Message<SetMicFeed> for Actor {type Reply = anyhow::Result<()>;async fn handle(&mut self, msg: SetMicFeed, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ #[cfg(target_os = "linux")]+ if self.resume_attempt.is_some() || self.resume_cleanup_error.is_some() {+ bail!("Recording resume or its cleanup is still pending");+ }match self.state.as_ref() {Some(ActorState::Recording { .. }) => {bail!("Pause the recording before changing microphone input")@@ -321,6 +893,10 @@ impl Message<SetCameraFeed> for Actor {msg: SetCameraFeed,_: &mut Context<Self, Self::Reply>,) -> Self::Reply {+ #[cfg(target_os = "linux")]+ if self.resume_attempt.is_some() || self.resume_cleanup_error.is_some() {+ bail!("Recording resume or its cleanup is still pending");+ }match self.state.as_ref() {Some(ActorState::Recording { .. }) => {bail!("Pause the recording before changing camera input")@@ -340,6 +916,10 @@ impl Message<IsPaused> for Actor {type Reply = bool;async fn handle(&mut self, _: IsPaused, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ #[cfg(target_os = "linux")]+ if self.resume_attempt.is_some() || self.resume_cleanup_error.is_some() {+ return false;+ }matches!(self.state, Some(ActorState::Paused { .. }))}}@@ -367,6 +947,8 @@ struct Pipeline {pub cursor: Option<CursorPipeline>,pub track_failures: SharedTrackFailures,pub watcher_task: Option<JoinHandle<()>>,+ #[cfg(any(target_os = "linux", windows))]+ stopping: Arc<std::sync::atomic::AtomicBool>,}struct FinishedPipeline {@@ -522,15 +1104,38 @@ fn write_recording_failure_diagnostics(}impl Pipeline {+ #[cfg(target_os = "linux")]+ fn completed_before_resume(&self) -> Option<String> {+ [+ ("display", Some(&self.screen)),+ ("microphone", self.microphone.as_ref()),+ ("camera", self.camera.as_ref()),+ ("system audio", self.system_audio.as_ref()),+ ]+ .into_iter()+ .find_map(|(track, pipeline)| {+ pipeline+ .and_then(|pipeline| pipeline.done_fut().now_or_never())+ .map(|result| match result {+ Ok(()) => format!("{track} capture ended before resume was committed"),+ Err(error) => {+ format!("{track} capture failed before resume was committed: {error}")+ }+ })+ })+ }+pub async fn stop(mut self) -> anyhow::Result<FinishedPipeline> {- let (microphone, camera, system_audio) = futures::join!(+ #[cfg(any(target_os = "linux", windows))]+ self.stopping+ .store(true, std::sync::atomic::Ordering::Release);+ let (screen, microphone, camera, system_audio) = futures::join!(+ self.screen.stop(),OptionFuture::from(self.microphone.map(|s| s.stop())),OptionFuture::from(self.camera.map(|s| s.stop())),OptionFuture::from(self.system_audio.map(|s| s.stop())));- let screen = self.screen.stop().await;-if let Some(cursor) = self.cursor.as_mut() {cursor.actor.stop();}@@ -539,6 +1144,40 @@ impl Pipeline {&& let Err(error) = watcher_task.await{warn!(error = %error, "Studio recording watcher task ended unexpectedly");+ #[cfg(any(target_os = "linux", windows))]+ return Err(anyhow!(+ "Studio recording watcher acknowledgement failed: {error}"+ ));+ }++ #[cfg(windows)]+ {+ let errors = [+ ("display", screen.as_ref().err()),+ (+ "microphone",+ microphone.as_ref().and_then(|result| result.as_ref().err()),+ ),+ (+ "camera",+ camera.as_ref().and_then(|result| result.as_ref().err()),+ ),+ (+ "system audio",+ system_audio+ .as_ref()+ .and_then(|result| result.as_ref().err()),+ ),+ ]+ .into_iter()+ .filter_map(|(track, error)| error.map(|error| format!("{track}: {error:#}")))+ .collect::<Vec<_>>();+ if !errors.is_empty() {+ bail!(+ "Requested Studio track stop failed; capture cleanup is unconfirmed: {}",+ errors.join("; ")+ );+ }}Ok(FinishedPipeline {@@ -604,6 +1243,7 @@ impl Pipeline {}// Ensure non-video pipelines stop promptly when the video pipeline completes+ #[cfg(not(any(target_os = "linux", windows)))]{let mic_cancel = self.microphone.as_ref().map(|p| p.cancel_token());let cam_cancel = self.camera.as_ref().map(|p| p.cancel_token());@@ -625,14 +1265,54 @@ impl Pipeline {});}+ #[cfg(any(target_os = "linux", windows))]+ let cancel_tokens = [+ Some(self.screen.cancel_token()),+ self.microphone.as_ref().map(OutputPipeline::cancel_token),+ self.camera.as_ref().map(OutputPipeline::cancel_token),+ self.system_audio.as_ref().map(OutputPipeline::cancel_token),+ ]+ .into_iter()+ .flatten()+ .collect::<Vec<_>>();+ #[cfg(any(target_os = "linux", windows))]+ let stopping = self.stopping.clone();let track_failures = self.track_failures.clone();self.watcher_task = Some(tokio::spawn(async move {while let Some((track, required, res)) = futures.next().await {+ #[cfg(any(target_os = "linux", windows))]+ let res = match res {+ Ok(()) if !stopping.load(std::sync::atomic::Ordering::Acquire) => {+ Err(PipelineDoneError::from_message(format!(+ "Requested {track:?} track ended before Stop"+ )))+ }+ result => result,+ };if let Err(err) = res {+ let required = required || cfg!(any(target_os = "linux", windows));if required {- if completion_tx.borrow().is_none() {- let _ = completion_tx.send(Some(Err(err)));+ record_track_failure(+ &track_failures,+ track,+ TrackFailureStage::Runtime,+ err.to_string(),+ );+ #[cfg(any(target_os = "linux", windows))]+ {+ stopping.store(true, std::sync::atomic::Ordering::Release);+ for token in &cancel_tokens {+ token.cancel();+ }}+ completion_tx.send_if_modified(|current| {+ if current.is_none() {+ *current = Some(Err(err.clone()));+ true+ } else {+ false+ }+ });} else {warn!(?track, error = %err, "Optional recording track failed during runtime");record_track_failure(@@ -656,36 +1336,226 @@ struct CursorPipeline {impl ActorHandle {pub async fn stop(&self) -> anyhow::Result<CompletedRecording> {- Ok(self.actor_ref.ask(Stop).await?)+ #[cfg(target_os = "linux")]+ {+ let report = self.stop_with_report().await;+ if !report.accepted_intent || report.quiescence != StudioQuiescence::Joined {+ bail!("Studio capture cleanup is unconfirmed; local recording preserved");+ }+ report.result.map_err(anyhow::Error::msg)+ }+ #[cfg(windows)]+ {+ let report = self.stop_with_intent(StudioStopIntent::Preserve).await;+ if !report.accepted_intent || !report.stop_acknowledged {+ bail!(+ "Studio stop is unconfirmed: {}",+ report+ .result+ .err()+ .unwrap_or_else(|| "terminal acknowledgement missing".into())+ );+ }+ report.result.map_err(anyhow::Error::msg)+ }+ #[cfg(not(any(target_os = "linux", windows)))]+ {+ Ok(self.actor_ref.ask(Stop).await?)+ }}- pub fn done_fut(&self) -> DoneFut {- self.done_fut.clone()+ #[cfg(target_os = "linux")]+ pub fn lifecycle(&self) -> StudioLifecycle {+ self.lifecycle.clone()}- pub async fn pause(&self) -> anyhow::Result<()> {- Ok(self.actor_ref.ask(Pause).await?)+ #[cfg(target_os = "linux")]+ pub async fn stop_with_report(&self) -> StudioStopReport {+ self.stop_with_intent(StudioStopIntent::Preserve).await}- pub async fn resume(&self) -> anyhow::Result<()> {- Ok(self.actor_ref.ask(Resume).await?)+ #[cfg(target_os = "linux")]+ pub async fn stop_with_intent(&self, intent: StudioStopIntent) -> StudioStopReport {+ let lifecycle = self.lifecycle.clone();+ let actor = self.actor_ref.clone();+ let recording_dir = self.recording_dir.clone();+ let (sender, receiver) = tokio::sync::oneshot::channel();+ drop(tokio::spawn(async move {+ let mut terminal = lifecycle.0.terminal.lock().await;+ let report = match terminal.as_ref() {+ Some((previous, report)) if *previous == intent => report.clone(),+ Some((_, report)) => StudioStopReport {+ accepted_intent: false,+ quiescence: report.quiescence,+ result: Err(+ "A different Studio terminal action already owns this attempt".into(),+ ),+ },+ None => {+ lifecycle+ .0+ .terminal_started+ .store(true, std::sync::atomic::Ordering::Release);+ let result = actor.ask(Stop).await.map_err(|error| format!("{error:#}"));+ if let Err(error) = &result {+ lifecycle.fail(error.clone());+ }+ let quiescence = lifecycle.join().await;+ let result = match lifecycle.failure() {+ Some(error) => {+ if let Err(persist_error) =+ persist_failed_recording(&recording_dir, &error)+ {+ Err(format!(+ "{error}; failed to persist failure metadata: {persist_error:#}"+ ))+ } else {+ Err(error)+ }+ }+ None => result,+ };+ let report = StudioStopReport {+ accepted_intent: true,+ quiescence,+ result,+ };+ *terminal = Some((intent, report.clone()));+ report+ }+ };+ let _ = sender.send(report);+ }));+ receiver.await.unwrap_or_else(|_| StudioStopReport {+ accepted_intent: false,+ quiescence: StudioQuiescence::Unconfirmed,+ result: Err("Studio terminal cleanup acknowledgement lost".into()),+ })}- pub async fn cancel(&self) -> anyhow::Result<()> {- Ok(self.actor_ref.ask(Cancel).await?)+ #[cfg(windows)]+ pub fn same_attempt(&self, other: &Self) -> bool {+ Arc::ptr_eq(&self.terminal, &other.terminal)}- pub async fn set_mic_feed(- &self,- mic_feed: Option<Arc<MicrophoneFeedLock>>,- ) -> anyhow::Result<()> {- Ok(self.actor_ref.ask(SetMicFeed { mic_feed }).await?)+ #[cfg(windows)]+ pub fn terminal_started(&self) -> bool {+ self.terminal+ .started+ .load(std::sync::atomic::Ordering::Acquire)}- pub async fn set_camera_feed(- &self,- camera_feed: Option<Arc<CameraFeedLock>>,- ) -> anyhow::Result<()> {+ #[cfg(windows)]+ pub fn stop_acknowledged(&self) -> bool {+ self.terminal+ .acknowledged+ .load(std::sync::atomic::Ordering::Acquire)+ }++ #[cfg(windows)]+ pub async fn stop_with_intent(&self, intent: StudioStopIntent) -> WindowsStudioStopReport {+ let terminal = self.terminal.clone();+ let actor = self.actor_ref.clone();+ let recording_dir = self.recording_dir.clone();+ let (sender, receiver) = tokio::sync::oneshot::channel();+ drop(tokio::spawn(async move {+ let mut cached = terminal.result.lock().await;+ let report = match cached.as_ref() {+ Some((previous, report)) if *previous == intent => report.clone(),+ Some((_, report)) => WindowsStudioStopReport {+ accepted_intent: false,+ stop_acknowledged: report.stop_acknowledged,+ result: Err("Another Studio terminal action owns this attempt".into()),+ },+ None => {+ terminal+ .started+ .store(true, std::sync::atomic::Ordering::Release);+ let result = actor.ask(Stop).await.map_err(|error| format!("{error:#}"));+ let result = match result {+ Err(error) => match persist_failed_recording(&recording_dir, &error) {+ Ok(()) => Err(error),+ Err(persist) => Err(format!(+ "{error}; failed to preserve Failed metadata: {persist:#}"+ )),+ },+ result => result,+ };+ let report = WindowsStudioStopReport {+ accepted_intent: true,+ stop_acknowledged: result.is_ok(),+ result,+ };+ terminal.acknowledged.store(+ report.stop_acknowledged,+ std::sync::atomic::Ordering::Release,+ );+ *cached = Some((intent, report.clone()));+ report+ }+ };+ let _ = sender.send(report);+ }));+ receiver.await.unwrap_or_else(|_| WindowsStudioStopReport {+ accepted_intent: false,+ stop_acknowledged: false,+ result: Err("Studio terminal acknowledgement lost; local files preserved".into()),+ })+ }++ pub fn done_fut(&self) -> DoneFut {+ self.done_fut.clone()+ }++ pub async fn pause(&self) -> anyhow::Result<()> {+ #[cfg(windows)]+ if self.terminal_started() {+ bail!("Studio terminal cleanup already owns this attempt");+ }+ Ok(self.actor_ref.ask(Pause).await?)+ }++ pub async fn resume(&self) -> anyhow::Result<()> {+ #[cfg(windows)]+ if self.terminal_started() {+ bail!("Studio terminal cleanup already owns this attempt");+ }+ #[cfg(target_os = "linux")]+ {+ self.actor_ref.ask(Resume).await?.await+ }+ #[cfg(not(target_os = "linux"))]+ {+ Ok(self.actor_ref.ask(Resume).await?)+ }+ }++ pub async fn cancel(&self) -> anyhow::Result<()> {+ #[cfg(target_os = "linux")]+ {+ let report = self.stop_with_intent(StudioStopIntent::Discard).await;+ if !report.accepted_intent || report.quiescence != StudioQuiescence::Joined {+ bail!("Studio cancellation cleanup is unconfirmed");+ }+ report.result.map(|_| ()).map_err(anyhow::Error::msg)+ }+ #[cfg(not(target_os = "linux"))]+ {+ Ok(self.actor_ref.ask(Cancel).await?)+ }+ }++ pub async fn set_mic_feed(+ &self,+ mic_feed: Option<Arc<MicrophoneFeedLock>>,+ ) -> anyhow::Result<()> {+ Ok(self.actor_ref.ask(SetMicFeed { mic_feed }).await?)+ }++ pub async fn set_camera_feed(+ &self,+ camera_feed: Option<Arc<CameraFeedLock>>,+ ) -> anyhow::Result<()> {Ok(self.actor_ref.ask(SetCameraFeed { camera_feed }).await?)}@@ -704,6 +1574,8 @@ impl Actor {}pub struct ActorBuilder {+ #[cfg(target_os = "linux")]+ lifetime: StudioLifetimeOwner,output_path: PathBuf,capture_target: screen_capture::ScreenCaptureTarget,system_audio: bool,@@ -722,6 +1594,11 @@ pub struct ActorBuilder {impl ActorBuilder {pub fn new(output: PathBuf, capture_target: screen_capture::ScreenCaptureTarget) -> Self {Self {+ #[cfg(target_os = "linux")]+ lifetime: StudioLifetimeOwner {+ lifecycle: StudioLifecycle::new(),+ armed: true,+ },output_path: output,capture_target,system_audio: false,@@ -789,11 +1666,26 @@ impl ActorBuilder {self}+ #[cfg(target_os = "linux")]+ pub fn lifecycle(&self) -> StudioLifecycle {+ self.lifetime.lifecycle.clone()+ }+pub async fn build(self,#[cfg(target_os = "macos")] shareable_content: Option<SendableShareableContent>,) -> anyhow::Result<ActorHandle> {- spawn_studio_recording_actor(+ #[cfg(any(target_os = "linux", windows))]+ let recording_dir = self.output_path.clone();+ #[cfg(target_os = "linux")]+ let lifecycle = self.lifetime.lifecycle.clone();+ #[cfg(target_os = "linux")]+ {+ *lifecycle.0.runtime.lock().unwrap() = Some(tokio::runtime::Handle::current());+ }+ let startup = spawn_studio_recording_actor(+ #[cfg(target_os = "linux")]+ self.lifetime,self.output_path,RecordingBaseInputs {capture_target: self.capture_target,@@ -811,14 +1703,48 @@ impl ActorBuilder {self.use_oop_muxer,self.max_fps,self.quality,- )- .await+ );+ #[cfg(windows)]+ {+ let scope = crate::output_pipeline::PipelineBuildScope::new();+ let result =+ crate::output_pipeline::finish_windows_pipeline_startup(&scope, startup).await;+ match result {+ Err(error) if recording_dir.join("recording-meta.json").exists() => {+ match persist_failed_recording(&recording_dir, &format!("{error:#}")) {+ Ok(()) => Err(error),+ Err(persist) => Err(error.context(format!(+ "Could not preserve failed Studio startup: {persist:#}"+ ))),+ }+ }+ result => result,+ }+ }+ #[cfg(target_os = "linux")]+ {+ let result = lifecycle.0.scope.run(startup).await;+ if let Err(error) = &result {+ lifecycle.fail(format!("{error:#}"));+ lifecycle.join().await;+ if recording_dir.join("recording-meta.json").exists()+ && let Err(persist_error) =+ persist_failed_recording(&recording_dir, &format!("{error:#}"))+ {+ warn!(%persist_error, "Failed to persist Studio startup failure");+ }+ }+ result+ }+ #[cfg(not(any(windows, target_os = "linux")))]+ startup.await}}#[tracing::instrument("studio_recording", skip_all)]#[allow(clippy::too_many_arguments)]async fn spawn_studio_recording_actor(+ #[cfg(target_os = "linux")] lifetime: StudioLifetimeOwner,recording_dir: PathBuf,base_inputs: RecordingBaseInputs,custom_cursor_capture: bool,@@ -849,6 +1775,8 @@ async fn spawn_studio_recording_actor(debug!("mic audio info: {:#?}", mic_feed.audio_info());};+ #[cfg(target_os = "linux")]+ let lifecycle = lifetime.lifecycle.clone();let mut segment_pipeline_factory = SegmentPipelineFactory::new(segments_dir,cursors_dir,@@ -862,7 +1790,7 @@ async fn spawn_studio_recording_actor(completion_tx.clone(),);- if fragmented {+ if fragmented || cfg!(any(target_os = "linux", windows)) {write_in_progress_meta(&recording_dir)?;}@@ -879,7 +1807,13 @@ async fn spawn_studio_recording_actor(let base_inputs = base_inputs.clone();+ #[cfg(any(target_os = "linux", windows))]+ let actor_recording_dir = recording_dir.clone();let actor_ref = Actor::spawn(Actor {+ #[cfg(target_os = "linux")]+ lifetime,+ #[cfg(windows)]+ cancel_error: None,recording_dir,state: Some(ActorState::Recording {pipeline,@@ -889,18 +1823,31 @@ async fn spawn_studio_recording_actor(segment_start_instant: Instant::now(),}),segment_factory: segment_pipeline_factory,+ #[cfg(target_os = "linux")]+ resume_attempt: None,+ #[cfg(target_os = "linux")]+ resume_generation: 0,+ #[cfg(target_os = "linux")]+ resume_cleanup_error: None,segments: Vec::new(),completion_tx: completion_tx.clone(),display_notch: crate::capture_pipeline::resolve_display_notch(&base_inputs.capture_target),});Ok(ActorHandle {+ #[cfg(target_os = "linux")]+ lifecycle,+ #[cfg(any(target_os = "linux", windows))]+ recording_dir: actor_recording_dir,+ #[cfg(windows)]+ terminal: Arc::new(WindowsStudioTerminal::default()),actor_ref,capture_target: base_inputs.capture_target,done_fut,})}+#[derive(Clone)]pub struct CompletedRecording {pub project_path: PathBuf,pub meta: StudioRecordingMeta,@@ -926,7 +1873,8 @@ async fn stop_recording(cursors: Cursors,fragmented: bool,display_notch: Option<cap_project::DisplayNotch>,-) -> Result<CompletedRecording, RecordingError> {+ known_failure: Option<String>,+) -> anyhow::Result<CompletedRecording> {use cap_project::*;use cap_timestamp::{AUDIO_OUTPUT_FRAMES, DEFAULT_SAMPLE_RATE};@@ -1017,7 +1965,7 @@ async fn stop_recording(// what un-edited recordings use.let display_media_duration = match s.pipeline.screen.video_timestamp_span {Some((first, last)) if display_fps > 0 => {- (last - first).as_secs_f64() + 1.0 / f64::from(display_fps)+ last.saturating_sub(first).as_secs_f64() + 1.0 / f64::from(display_fps)}_ if display_fps > 0 => {s.pipeline.screen.video_frame_count as f64 / f64::from(display_fps)@@ -1155,7 +2103,20 @@ async fn stop_recording(false};- let status = if needs_remux {+ let required_track_failure = known_failure.or_else(|| {+ segment_failure_diagnostics.first().map(|segment| {+ let failure = &segment.track_failures[0];+ format!(+ "Requested {:?} track failed in segment {}: {}",+ failure.track, segment.segment_index, failure.error+ )+ })+ });+ let status = if let Some(error) = required_track_failure.as_ref() {+ Some(StudioRecordingStatus::Failed {+ error: error.clone(),+ })+ } else if needs_remux {Some(StudioRecordingStatus::NeedsRemux)} else {Some(StudioRecordingStatus::Complete)@@ -1184,7 +2145,17 @@ async fn stop_recording(},};- persist_final_recording_meta(&recording_dir, &meta);+ if let Some(diagnostics) = build_recording_failure_diagnostics(&segment_failure_diagnostics)+ && let Err(error) = write_recording_failure_diagnostics(&recording_dir, &diagnostics)+ {+ warn!(+ error = %error,+ path = %recording_dir.join("recording-diagnostics.json").display(),+ "Failed to persist recording diagnostics sidecar"+ );+ }++ persist_final_recording_meta(&recording_dir, &meta)?;let mut project_config = cap_project::ProjectConfiguration::default();if !timeline_segments.is_empty() {@@ -1208,14 +2179,8 @@ async fn stop_recording(.write(&recording_dir).map_err(RecordingError::from)?;- if let Some(diagnostics) = build_recording_failure_diagnostics(&segment_failure_diagnostics)- && let Err(error) = write_recording_failure_diagnostics(&recording_dir, &diagnostics)- {- warn!(- error = %error,- path = %recording_dir.join("recording-diagnostics.json").display(),- "Failed to persist recording diagnostics sidecar"- );+ if let Some(error) = required_track_failure {+ bail!(error);}Ok(CompletedRecording {@@ -1227,7 +2192,17 @@ async fn stop_recording(})}+#[cfg(all(test, target_os = "linux"))]+type ResumeTestFactory = Arc<+ dyn Fn(Cursors, u32) -> futures::future::BoxFuture<'static, anyhow::Result<Pipeline>>+ + Send+ + Sync,+>;++#[derive(Clone)]struct SegmentPipelineFactory {+ #[cfg(all(test, target_os = "linux"))]+ prepare_override: Option<ResumeTestFactory>,segments_dir: PathBuf,cursors_dir: PathBuf,base_inputs: RecordingBaseInputs,@@ -1258,6 +2233,8 @@ impl SegmentPipelineFactory {completion_tx: watch::Sender<Option<Result<(), PipelineDoneError>>>,) -> Self {Self {+ #[cfg(all(test, target_os = "linux"))]+ prepare_override: None,segments_dir,cursors_dir,base_inputs,@@ -1274,6 +2251,55 @@ impl SegmentPipelineFactory {}}+ #[cfg(target_os = "linux")]+ pub async fn create_next(+ &mut self,+ cursors: Cursors,+ next_cursors_id: u32,+ ) -> anyhow::Result<Pipeline> {+ let mut pipeline = self.prepare_next(cursors, next_cursors_id).await?;+ self.commit_next(&mut pipeline);+ Ok(pipeline)+ }++ #[cfg(target_os = "linux")]+ async fn prepare_next(+ &mut self,+ cursors: Cursors,+ next_cursors_id: u32,+ ) -> anyhow::Result<Pipeline> {+ #[cfg(test)]+ if let Some(prepare) = &self.prepare_override {+ return prepare(cursors, next_cursors_id).await;+ }+ let segment_start_time = Timestamps::now();+ create_segment_pipeline(+ &self.segments_dir,+ &self.cursors_dir,+ self.index,+ self.base_inputs.clone(),+ cursors,+ next_cursors_id,+ self.custom_cursor_capture,+ self.keyboard_capture,+ self.fragmented,+ self.use_oop_muxer,+ self.max_fps,+ self.quality,+ segment_start_time,+ #[cfg(windows)]+ self.encoder_preferences.clone(),+ )+ .await+ }++ #[cfg(target_os = "linux")]+ fn commit_next(&mut self, pipeline: &mut Pipeline) {+ self.index += 1;+ pipeline.spawn_watcher(self.completion_tx.clone());+ }++ #[cfg(not(target_os = "linux"))]pub async fn create_next(&mut self,cursors: Cursors,@@ -1339,6 +2365,11 @@ fn completion_rx_to_done_fut(}if rx.changed().await.is_err() {+ #[cfg(target_os = "linux")]+ return Err(PipelineDoneError::from_message(+ "Studio completion acknowledgement was lost".into(),+ ));+ #[cfg(not(target_os = "linux"))]return Ok(());}}@@ -1772,6 +2803,8 @@ async fn create_segment_pipeline(system_audio,track_failures: Arc::new(std::sync::Mutex::new(Vec::new())),watcher_task: None,+ #[cfg(any(target_os = "linux", windows))]+ stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)),})}@@ -1787,7 +2820,27 @@ fn current_time_f64() -> f64 {.as_secs_f64()}-fn persist_final_recording_meta(recording_dir: &Path, studio_meta: &StudioRecordingMeta) {+#[cfg(any(target_os = "linux", windows))]+fn persist_failed_recording(recording_dir: &Path, error: &str) -> anyhow::Result<()> {+ let mut meta = RecordingMeta::load_for_project(recording_dir)+ .map_err(|error| anyhow!("load failed Studio recording metadata: {error}"))?;+ let RecordingMetaInner::Studio(studio) = &mut meta.inner else {+ bail!("Failed Studio recording has incompatible metadata");+ };+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {+ bail!("Failed Studio recording has incompatible segment metadata");+ };+ inner.status = Some(StudioRecordingStatus::Failed {+ error: error.to_string(),+ });+ meta.save_for_project()+ .context("persist failed Studio metadata")+}++fn persist_final_recording_meta(+ recording_dir: &Path,+ studio_meta: &StudioRecordingMeta,+) -> anyhow::Result<()> {use chrono::Local;let pretty_name = Local::now().format("Cap %Y-%m-%d at %H.%M.%S").to_string();@@ -1800,13 +2853,9 @@ fn persist_final_recording_meta(recording_dir: &Path, studio_meta: &StudioRecordupload: None,};- if let Err(err) = recording_meta.save_for_project() {- warn!(- error = ?err,- path = %recording_dir.join("recording-meta.json").display(),- "Failed to persist final recording meta; downstream consumers may see in-progress state"- );- }+ recording_meta+ .save_for_project()+ .context("persist final recording metadata")}fn write_in_progress_meta(recording_dir: &Path) -> anyhow::Result<()> {@@ -1837,10 +2886,697 @@ fn write_in_progress_meta(recording_dir: &Path) -> anyhow::Result<()> {mod tests {use super::*;use crate::output_pipeline::{- AudioMuxer, ChannelAudioSource, ChannelAudioSourceConfig, ChannelVideoSource,- ChannelVideoSourceConfig, Muxer, TaskPool, VideoFrame, VideoMuxer,+ AudioMuxer, AudioSource, ChannelAudioSource, ChannelAudioSourceConfig, ChannelVideoSource,+ ChannelVideoSourceConfig, Muxer, SetupCtx, TaskPool, VideoFrame, VideoMuxer,};+ #[cfg(target_os = "linux")]+ mod resume_transaction_tests {+ use super::*;+ struct ResumeStateSnapshot;++ impl Message<ResumeStateSnapshot> for Actor {+ type Reply = (bool, u32, u32, usize, usize, u32);++ async fn handle(+ &mut self,+ _: ResumeStateSnapshot,+ _: &mut Context<Self, Self::Reply>,+ ) -> Self::Reply {+ let (paused, index, cursor_id, cursors) = match &self.state {+ Some(ActorState::Paused {+ next_index,+ next_cursor_id,+ cursors,+ }) => (true, *next_index, *next_cursor_id, cursors.len()),+ _ => (false, 0, 0, 0),+ };+ (+ paused,+ index,+ cursor_id,+ cursors,+ self.segments.len(),+ self.segment_factory.index,+ )+ }+ }++ fn paused_resume_actor(path: &Path, prepare: ResumeTestFactory) -> ActorHandle {+ let (completion_tx, completion_rx) = watch::channel(None);+ let target = screen_capture::ScreenCaptureTarget::CameraOnly;+ let mut factory = SegmentPipelineFactory::new(+ path.join("content/segments"),+ path.join("content/cursors"),+ RecordingBaseInputs {+ capture_target: target.clone(),+ capture_system_audio: false,+ mic_feed: None,+ camera_feed: None,+ #[cfg(target_os = "macos")]+ shareable_content: None,+ #[cfg(target_os = "macos")]+ excluded_windows: Vec::new(),+ },+ false,+ false,+ false,+ false,+ 30,+ crate::StudioQuality::Balanced,+ completion_tx.clone(),+ );+ factory.index = 1;+ factory.prepare_override = Some(prepare);+ let cursors = [(+ 17,+ crate::cursor::Cursor {+ id: 12,+ file_name: "retained.png".into(),+ hotspot: cap_project::XY { x: 0.25, y: 0.75 },+ shape: None,+ },+ )]+ .into_iter()+ .collect();+ let start_time = Timestamps::now();+ let prior_segment = RecordingSegment {+ start: 0.0,+ end: 1.0,+ camera_device_id: None,+ mic_device_id: None,+ pipeline: FinishedPipeline {+ start_time,+ screen: FinishedOutputPipeline {+ path: path.join("content/segments/segment-0/display.mp4"),+ first_timestamp: Timestamp::Instant(start_time.instant()),+ video_info: Some(test_video_info()),+ video_frame_count: 30,+ video_timestamp_span: Some((Duration::ZERO, Duration::from_millis(967))),+ audio_gap_summary: None,+ },+ microphone: None,+ camera: None,+ system_audio: None,+ cursor: None,+ track_failures: Vec::new(),+ },+ };+ let lifecycle = StudioLifecycle::new();+ ActorHandle {+ lifecycle: lifecycle.clone(),+ recording_dir: path.to_path_buf(),+ actor_ref: Actor::spawn(Actor {+ lifetime: StudioLifetimeOwner {+ lifecycle,+ armed: true,+ },+ recording_dir: path.to_path_buf(),+ state: Some(ActorState::Paused {+ next_index: 1,+ cursors,+ next_cursor_id: 13,+ }),+ segment_factory: factory,+ resume_attempt: None,+ resume_generation: 0,+ resume_cleanup_error: None,+ segments: vec![prior_segment],+ completion_tx,+ display_notch: None,+ }),+ capture_target: target,+ done_fut: completion_rx_to_done_fut(completion_rx),+ }+ }++ #[tokio::test]+ async fn dropped_stop_waiter_does_not_abort_owned_studio_shutdown() {+ let directory = tempfile::tempdir().unwrap();+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new(|_, _| async { Err(anyhow!("not resumed")) }.boxed()),+ );+ let scope = handle.lifecycle.0.scope.clone();+ let (release_tx, release_rx) = tokio::sync::oneshot::channel();+ let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();+ scope+ .run(async {+ let completion = scope.task_completion();+ drop(tokio::spawn(async move {+ let _completion = completion;+ let _ = entered_tx.send(());+ let _ = release_rx.await;+ }));+ })+ .await;+ entered_rx.await.unwrap();+ let waiter = tokio::spawn({+ let handle = handle.clone();+ async move { handle.stop_with_report().await }+ });+ tokio::task::yield_now().await;+ waiter.abort();+ assert_eq!(handle.lifecycle.quiescence(), StudioQuiescence::Pending);+ release_tx.send(()).unwrap();+ let report = handle.stop_with_report().await;+ assert_eq!(report.quiescence, StudioQuiescence::Joined);+ assert!(report.result.is_ok());+ let replay = handle.stop_with_report().await;+ assert!(replay.result.is_ok());+ }++ #[tokio::test]+ async fn queued_discard_cannot_replay_a_successful_preserving_stop() {+ let directory = tempfile::tempdir().unwrap();+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new(|_, _| async { Err(anyhow!("not resumed")) }.boxed()),+ );+ let first = handle.stop_with_report().await;+ assert_eq!(first.quiescence, StudioQuiescence::Joined);+ assert!(first.result.is_ok());+ let discarded = handle.stop_with_intent(StudioStopIntent::Discard).await;+ assert_eq!(discarded.quiescence, StudioQuiescence::Joined);+ assert!(discarded.result.is_err());+ assert!(!discarded.accepted_intent);+ assert!(directory.path().join("recording-meta.json").exists());+ }++ #[tokio::test]+ async fn queued_preserve_cannot_take_a_successful_discard_terminal_action() {+ let directory = tempfile::tempdir().unwrap();+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new(|_, _| async { Err(anyhow!("not resumed")) }.boxed()),+ );+ let first = handle.stop_with_intent(StudioStopIntent::Discard).await;+ assert!(first.accepted_intent);+ assert_eq!(first.quiescence, StudioQuiescence::Joined);+ assert!(first.result.is_ok());+ let preserving = handle.stop_with_report().await;+ assert!(!preserving.accepted_intent);+ assert_eq!(preserving.quiescence, StudioQuiescence::Joined);+ assert!(preserving.result.is_err());+ }++ #[derive(kameo::Actor)]+ struct BlockedCompletionMailbox {+ entered: Option<tokio::sync::oneshot::Sender<()>>,+ release: Option<tokio::sync::oneshot::Receiver<()>>,+ }++ impl Message<u8> for BlockedCompletionMailbox {+ type Reply = ();++ async fn handle(&mut self, message: u8, _: &mut Context<Self, Self::Reply>) {+ if message == 0 {+ self.entered.take().unwrap().send(()).unwrap();+ self.release.take().unwrap().await.unwrap();+ }+ }+ }++ #[tokio::test]+ async fn full_actor_mailbox_cannot_retain_published_capture_completion() {+ let (entered, entry) = tokio::sync::oneshot::channel();+ let (release, released) = tokio::sync::oneshot::channel();+ let actor = BlockedCompletionMailbox::spawn(BlockedCompletionMailbox {+ entered: Some(entered),+ release: Some(released),+ });+ actor.tell(0u8).await.unwrap();+ entry.await.unwrap();+ for _ in 0..64 {+ actor.tell(1u8).try_send().unwrap();+ }+ let scope = crate::output_pipeline::PipelineBuildScope::new_studio_lifetime();+ let completion = scope.task_completion();+ let notifying = tokio::spawn({+ let actor = actor.clone();+ async move { notify_after_capture_publication(completion, actor.tell(2u8)).await }+ });+ let report =+ tokio::time::timeout(Duration::from_secs(1), scope.cancel_and_join_report())+ .await+ .unwrap();+ assert!(report.quiescent);+ assert!(!notifying.is_finished());+ release.send(()).unwrap();+ notifying.await.unwrap().unwrap();+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[tokio::test]+ async fn source_stop_scope_failure_is_failed_before_actor_completion() {+ let directory = tempfile::tempdir().unwrap();+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new(|_, _| async { Err(anyhow!("not resumed")) }.boxed()),+ );+ handle+ .lifecycle+ .0+ .scope+ .fail_required("unresolved backend error at source Stop".into());+ let report = handle.stop_with_report().await;+ assert!(report.accepted_intent);+ assert_eq!(report.quiescence, StudioQuiescence::Joined);+ assert!(report.result.is_err());+ assert!(handle.done_fut().await.is_err());+ let meta = RecordingMeta::load_for_project(directory.path()).unwrap();+ assert!(matches!(+ meta.studio_meta().unwrap().status(),+ StudioRecordingStatus::Failed { .. }+ ));+ }++ #[tokio::test]+ async fn joined_studio_failure_remains_error_for_queued_stop() {+ let directory = tempfile::tempdir().unwrap();+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new(|_, _| async { Err(anyhow!("not resumed")) }.boxed()),+ );+ handle.lifecycle.fail("requested microphone failed".into());+ let (first, second) =+ futures::join!(handle.stop_with_report(), handle.stop_with_report());+ for report in [first, second] {+ assert_eq!(report.quiescence, StudioQuiescence::Joined);+ assert!(+ report+ .result+ .err()+ .unwrap()+ .contains("requested microphone failed")+ );+ }+ let meta = RecordingMeta::load_for_project(directory.path()).unwrap();+ assert!(matches!(+ meta.studio_meta().unwrap().status(),+ StudioRecordingStatus::Failed { .. }+ ));+ }++ #[tokio::test]+ async fn resume_failure_waits_for_owned_cleanup_and_preserves_paused_cursor_state() {+ let directory = tempfile::tempdir().unwrap();+ let started = Arc::new(tokio::sync::Notify::new());+ let release = Arc::new(tokio::sync::Notify::new());+ let stopped = Arc::new(std::sync::atomic::AtomicBool::new(false));+ let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new({+ let started = started.clone();+ let release = release.clone();+ let stopped = stopped.clone();+ let calls = calls.clone();+ move |cursors, next_id| {+ assert_eq!(next_id, 13);+ assert_eq!(cursors[&17].id, 12);+ let started = started.clone();+ let release = release.clone();+ let stopped = stopped.clone();+ let calls = calls.clone();+ async move {+ if calls.fetch_add(1, std::sync::atomic::Ordering::AcqRel) == 0 {+ drop(crate::output_pipeline::spawn_capture_task(async move {+ started.notify_one();+ release.notified().await;+ stopped.store(true, std::sync::atomic::Ordering::Release);+ }));+ }+ bail!("late segment setup failure")+ }+ .boxed()+ }+ }),+ );+ let ready = handle.actor_ref.ask(Resume).await.unwrap();+ started.notified().await;+ assert!(!handle.is_paused().await.unwrap());+ tokio::pin!(ready);+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut ready)+ .await+ .is_err()+ );+ assert!(handle.done_fut().now_or_never().is_none());+ release.notify_one();+ assert!(ready.await.is_err());+ assert!(stopped.load(std::sync::atomic::Ordering::Acquire));+ assert!(handle.is_paused().await.unwrap());+ assert_eq!(+ handle.actor_ref.ask(ResumeStateSnapshot).await.unwrap(),+ (true, 1, 13, 1, 1, 1)+ );+ assert!(handle.resume().await.is_err());+ assert_eq!(calls.load(std::sync::atomic::Ordering::Acquire), 2);+ assert_eq!(+ handle.actor_ref.ask(ResumeStateSnapshot).await.unwrap(),+ (true, 1, 13, 1, 1, 1)+ );+ handle.actor_ref.stop_gracefully().await.unwrap();+ }++ #[tokio::test]+ async fn stop_cancels_pending_resume_and_joins_before_finalizing_only_prior_segments() {+ let directory = tempfile::tempdir().unwrap();+ let started = Arc::new(tokio::sync::Notify::new());+ let cancelled = Arc::new(tokio::sync::Notify::new());+ let release = Arc::new(tokio::sync::Notify::new());+ let failed_dir = directory.path().join("content/segments/segment-1");+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new({+ let started = started.clone();+ let cancelled = cancelled.clone();+ let release = release.clone();+ let failed_dir = failed_dir.clone();+ move |_, _| {+ let started = started.clone();+ let cancelled = cancelled.clone();+ let release = release.clone();+ let failed_dir = failed_dir.clone();+ async move {+ tokio::fs::create_dir_all(&failed_dir).await.unwrap();+ let scope =+ crate::output_pipeline::PipelineBuildScope::current().unwrap();+ drop(crate::output_pipeline::spawn_capture_task(async move {+ scope.cancellation().cancelled().await;+ cancelled.notify_one();+ release.notified().await;+ }));+ started.notify_one();+ std::future::pending::<anyhow::Result<Pipeline>>().await+ }+ .boxed()+ }+ }),+ );+ let ready = handle.actor_ref.ask(Resume).await.unwrap();+ started.notified().await;+ let stopping = handle.stop();+ tokio::pin!(stopping);+ tokio::select! {+ _ = cancelled.notified() => {},+ _ = &mut stopping => panic!("Stop acknowledged before setup cleanup"),+ _ = tokio::time::sleep(Duration::from_secs(2)) => panic!("Stop did not reach pending resume"),+ }+ assert!(+ tokio::time::timeout(Duration::from_millis(20), &mut stopping)+ .await+ .is_err()+ );+ assert!(handle.done_fut().now_or_never().is_none());+ release.notify_one();+ let completed = tokio::time::timeout(Duration::from_secs(2), stopping)+ .await+ .unwrap()+ .unwrap();+ assert!(ready.await.is_err());+ let StudioRecordingMeta::MultipleSegments { inner } = completed.meta else {+ panic!("wrong metadata")+ };+ assert_eq!(inner.segments.len(), 1);+ assert_eq!(+ inner.segments[0].display.path.as_str(),+ "content/segments/segment-0/display.mp4"+ );+ assert!(!failed_dir.exists());+ }++ #[tokio::test]+ async fn dropped_resume_waiter_cancels_owned_setup_without_late_commit() {+ let directory = tempfile::tempdir().unwrap();+ let started = Arc::new(tokio::sync::Notify::new());+ let finished = Arc::new(tokio::sync::Notify::new());+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new({+ let started = started.clone();+ let finished = finished.clone();+ move |_, _| {+ let started = started.clone();+ let finished = finished.clone();+ async move {+ let scope =+ crate::output_pipeline::PipelineBuildScope::current().unwrap();+ drop(crate::output_pipeline::spawn_capture_task(async move {+ scope.cancellation().cancelled().await;+ finished.notify_one();+ }));+ started.notify_one();+ std::future::pending::<anyhow::Result<Pipeline>>().await+ }+ .boxed()+ }+ }),+ );+ let ready = handle.actor_ref.ask(Resume).await.unwrap();+ started.notified().await;+ drop(ready);+ tokio::time::timeout(Duration::from_secs(2), finished.notified())+ .await+ .unwrap();+ tokio::time::timeout(Duration::from_secs(2), async {+ while !handle.is_paused().await.unwrap() {+ tokio::task::yield_now().await;+ }+ })+ .await+ .unwrap();+ handle.actor_ref.tell(ResumeFinished(0)).await.unwrap();+ assert_eq!(+ handle.actor_ref.ask(ResumeStateSnapshot).await.unwrap(),+ (true, 1, 13, 1, 1, 1)+ );+ assert!(handle.done_fut().now_or_never().is_none());+ handle.actor_ref.stop_gracefully().await.unwrap();+ }++ #[tokio::test]+ async fn unconfirmed_resume_cleanup_never_acknowledges_paused_retry_or_complete() {+ let directory = tempfile::tempdir().unwrap();+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new(|_, _| {+ async {+ crate::output_pipeline::PipelineBuildScope::current()+ .unwrap()+ .spawn_cleanup(async { bail!("native stop failed") });+ bail!("setup failed")+ }+ .boxed()+ }),+ );+ assert!(handle.resume().await.is_err());+ assert!(!handle.is_paused().await.unwrap());+ assert!(handle.resume().await.is_err());+ assert!(handle.stop().await.is_err());+ assert!(handle.done_fut().now_or_never().is_none());+ assert_eq!(+ handle.actor_ref.ask(ResumeStateSnapshot).await.unwrap(),+ (true, 1, 13, 1, 1, 1)+ );+ handle.actor_ref.stop_gracefully().await.unwrap();+ }++ struct ResumeVideo {+ sender: Option<futures::channel::mpsc::Sender<TestVideoFrame>>,+ }++ impl crate::output_pipeline::VideoSource for ResumeVideo {+ type Config = Arc<std::sync::Mutex<Option<tokio_util::sync::CancellationToken>>>;+ type Frame = TestVideoFrame;++ async fn setup(+ stop: Self::Config,+ sender: futures::channel::mpsc::Sender<Self::Frame>,+ ctx: &mut SetupCtx,+ ) -> anyhow::Result<Self> {+ *stop.lock().unwrap() = Some(ctx.stop_token());+ Ok(Self {+ sender: Some(sender),+ })+ }++ fn video_info(&self) -> VideoInfo {+ test_video_info()+ }++ fn start(&mut self) -> futures::future::BoxFuture<'_, anyhow::Result<()>> {+ async move {+ self.sender.as_mut().unwrap().try_send(TestVideoFrame {+ timestamp: Timestamp::Instant(Instant::now()),+ })?;+ Ok(())+ }+ .boxed()+ }++ fn stop(&mut self) -> futures::future::BoxFuture<'_, anyhow::Result<()>> {+ drop(self.sender.take());+ async { Ok(()) }.boxed()+ }+ }++ #[tokio::test]+ async fn successful_resume_commits_once_and_stop_handles_the_committed_race() {+ let directory = tempfile::tempdir().unwrap();+ let stop = Arc::new(std::sync::Mutex::new(None));+ let next_path = directory+ .path()+ .join("content/segments/segment-1/display.mp4");+ let handle = paused_resume_actor(+ directory.path(),+ Arc::new({+ let stop = stop.clone();+ move |_, _| {+ let stop = stop.clone();+ let next_path = next_path.clone();+ async move {+ let start_time = Timestamps::now();+ let screen = OutputPipeline::builder(next_path)+ .with_video::<ResumeVideo>(stop)+ .with_timestamps(start_time)+ .build::<SuccessfulVideoMuxer>(())+ .await?;+ Ok(Pipeline {+ start_time,+ screen,+ microphone: None,+ camera: None,+ system_audio: None,+ cursor: None,+ track_failures: Arc::new(std::sync::Mutex::new(Vec::new())),+ watcher_task: None,+ #[cfg(target_os = "linux")]+ stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)),+ })+ }+ .boxed()+ }+ }),+ );+ handle.resume().await.unwrap();+ assert!(!handle.is_paused().await.unwrap());+ assert!(!stop.lock().unwrap().as_ref().unwrap().is_cancelled());+ handle.resume().await.unwrap();+ assert_eq!(+ handle.actor_ref.ask(ResumeStateSnapshot).await.unwrap().5,+ 2+ );+ let completed = tokio::time::timeout(Duration::from_secs(3), handle.stop())+ .await+ .unwrap()+ .unwrap();+ let StudioRecordingMeta::MultipleSegments { inner } = completed.meta else {+ panic!("wrong metadata")+ };+ assert_eq!(inner.segments.len(), 2);+ assert!(stop.lock().unwrap().as_ref().unwrap().is_cancelled());+ }+ }++ struct DelayedStopAudioSource {+ tx: Option<futures::channel::mpsc::Sender<crate::output_pipeline::AudioFrame>>,+ started: Arc<tokio::sync::Notify>,+ release: Arc<tokio::sync::Notify>,+ }++ impl AudioSource for DelayedStopAudioSource {+ type Config = (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>);++ fn setup(+ (started, release): Self::Config,+ mut tx: futures::channel::mpsc::Sender<crate::output_pipeline::AudioFrame>,+ _: &mut SetupCtx,+ ) -> impl std::future::Future<Output = anyhow::Result<Self>> + Send + 'static {+ let result = (|| {+ tx.try_send(crate::output_pipeline::AudioFrame::new(+ test_audio_info().empty_frame(960),+ Timestamp::Instant(Instant::now()),+ ))?;+ Ok(Self {+ tx: Some(tx),+ started,+ release,+ })+ })();+ futures::future::ready(result)+ }++ fn audio_info(&self) -> cap_media_info::AudioInfo {+ test_audio_info()+ }++ async fn stop(&mut self) -> anyhow::Result<()> {+ self.started.notify_one();+ self.release.notified().await;+ drop(self.tx.take());+ Ok(())+ }+ }++ #[tokio::test]+ async fn screen_stop_does_not_wait_for_optional_audio_shutdown() {+ let temp_dir = tempfile::tempdir().unwrap();+ let timestamps = Timestamps::now();+ let (screen_tx, screen_rx) = flume::bounded(4);+ let started = Arc::new(tokio::sync::Notify::new());+ let release = Arc::new(tokio::sync::Notify::new());++ let screen = OutputPipeline::builder(temp_dir.path().join("display.mp4"))+ .with_video::<ChannelVideoSource<TestVideoFrame>>(ChannelVideoSourceConfig::new(+ test_video_info(),+ screen_rx,+ ))+ .with_timestamps(timestamps)+ .build::<SuccessfulVideoMuxer>(())+ .await+ .unwrap();+ let screen_stop = screen.cancel_token();+ let microphone = OutputPipeline::builder(temp_dir.path().join("audio-input.ogg"))+ .with_audio_source::<DelayedStopAudioSource>((started.clone(), release.clone()))+ .with_timestamps(timestamps)+ .build::<SuccessfulVideoMuxer>(())+ .await+ .unwrap();+ screen_tx+ .send_async(TestVideoFrame {+ timestamp: Timestamp::Instant(timestamps.instant()),+ })+ .await+ .unwrap();+ let pipeline = Pipeline {+ start_time: timestamps,+ screen,+ microphone: Some(microphone),+ camera: None,+ system_audio: None,+ cursor: None,+ track_failures: Arc::new(std::sync::Mutex::new(Vec::new())),+ watcher_task: None,+ #[cfg(any(target_os = "linux", windows))]+ stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)),+ };++ let stopping = tokio::spawn(pipeline.stop());+ tokio::time::timeout(Duration::from_secs(2), started.notified())+ .await+ .unwrap();+ let screen_stopped_while_audio_waited = screen_stop.is_cancelled();+ release.notify_one();+ drop(screen_tx);+ let finished = stopping.await.unwrap().unwrap();++ assert!(screen_stopped_while_audio_waited);+ assert!(finished.microphone.is_some());+ }+fn test_finished_output_pipeline() -> FinishedOutputPipeline {let timestamps = Timestamps::now();test_finished_output_pipeline_at(@@ -2035,6 +3771,7 @@ mod tests {Default::default(),false,None,+ None,).await.expect("recording should stop");@@ -2193,7 +3930,7 @@ mod tests {}#[tokio::test]- async fn stop_recording_keeps_success_when_diagnostics_sidecar_write_fails() {+ async fn failed_requested_track_remains_failed_when_diagnostics_sidecar_write_fails() {let temp_dir = tempfile::tempdir().expect("temp dir should be created");let recording_dir = temp_dir.path().join("recording");let start_time = Timestamps::now();@@ -2227,30 +3964,417 @@ mod tests {mic_device_id: None,};- let completed = stop_recording(+ let result = stop_recording(recording_dir.clone(),vec![segment],Default::default(),false,None,+ None,)- .await- .expect("diagnostics sidecar failure should not abort stop_recording");+ .await;+ assert!(result.is_err());+ let meta = RecordingMeta::load_for_project(&recording_dir).unwrap();+ assert!(matches!(+ meta.studio_meta().unwrap().status(),+ StudioRecordingStatus::Failed { .. }+ ));- assert_eq!(completed.project_path, recording_dir);assert!(- completed.project_path.join("project-config.json").is_file(),+ recording_dir.join("project-config.json").is_file(),"project config should still be written");assert!(- completed- .project_path- .join("recording-diagnostics.json")- .is_dir(),+ recording_dir.join("recording-diagnostics.json").is_dir(),"the pre-existing diagnostics directory should remain, proving the sidecar write failed");}+ #[tokio::test]+ async fn requested_track_failure_never_finalizes_complete_or_needs_remux() {+ for track in [+ RecordingTrackKind::Microphone,+ RecordingTrackKind::Camera,+ RecordingTrackKind::SystemAudio,+ ] {+ for fragmented in [false, true] {+ let temp_dir = tempfile::tempdir().unwrap();+ let recording_dir = temp_dir.path().join("recording");+ std::fs::create_dir_all(recording_dir.join("content")).unwrap();+ let display_path = recording_dir.join("content/display");+ if fragmented {+ std::fs::create_dir(&display_path).unwrap();+ std::fs::write(display_path.join("preserved-fragment"), b"partial").unwrap();+ } else {+ std::fs::write(&display_path, b"preserved-display").unwrap();+ }+ let timestamps = Timestamps::now();+ let segment = RecordingSegment {+ start: 0.0,+ end: 1.0,+ pipeline: FinishedPipeline {+ start_time: timestamps,+ screen: test_finished_output_pipeline_at(+ display_path.clone(),+ Timestamp::Instant(timestamps.instant()),+ Some(test_video_info()),+ 1,+ ),+ microphone: None,+ camera: None,+ system_audio: None,+ cursor: None,+ track_failures: vec![TrackFailureRecord {+ track,+ stage: TrackFailureStage::Stop,+ error: "required output failed".to_string(),+ }],+ },+ camera_device_id: None,+ mic_device_id: None,+ };+ let result = stop_recording(+ recording_dir.clone(),+ vec![segment],+ Default::default(),+ fragmented,+ None,+ None,+ )+ .await;+ assert!(result.is_err());+ let meta = RecordingMeta::load_for_project(&recording_dir).unwrap();+ assert!(matches!(+ meta.studio_meta().unwrap().status(),+ StudioRecordingStatus::Failed { .. }+ ));+ assert!(display_path.exists());+ assert!(recording_dir.join("recording-diagnostics.json").is_file());+ }+ }+ }++ #[cfg(windows)]+ struct HeldEncoderMuxer(Option<std::thread::JoinHandle<anyhow::Result<()>>>);++ #[cfg(windows)]+ impl Muxer for HeldEncoderMuxer {+ type Config = (+ std::sync::mpsc::Receiver<()>,+ tokio::sync::oneshot::Sender<()>,+ );+ async fn setup(+ (release, exited): Self::Config,+ _output_path: PathBuf,+ _video_config: Option<VideoInfo>,+ _audio_config: Option<cap_media_info::AudioInfo>,+ _pause_flag: Arc<std::sync::atomic::AtomicBool>,+ _tasks: &mut TaskPool,+ ) -> anyhow::Result<Self> {+ Ok(Self(Some(std::thread::spawn(move || {+ release.recv().map_err(|error| anyhow!("{error}"))?;+ let _ = exited.send(());+ Ok(())+ }))))+ }+ fn finish(&mut self, _timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ use crate::output_pipeline::{BlockingThreadFinish, wait_for_blocking_thread_finish};+ let handle = self.0.take().unwrap();+ Ok(+ match wait_for_blocking_thread_finish(handle, Duration::ZERO, "held-test-encoder") {+ BlockingThreadFinish::Clean => Ok(()),+ BlockingThreadFinish::Failed(error) | BlockingThreadFinish::TimedOut(error) => {+ Err(error)+ }+ },+ )+ }+ }++ #[cfg(windows)]+ impl AudioMuxer for HeldEncoderMuxer {+ fn send_audio_frame(+ &mut self,+ _frame: crate::output_pipeline::AudioFrame,+ _timestamp: Duration,+ ) -> anyhow::Result<()> {+ Ok(())+ }+ }++ #[cfg(windows)]+ impl VideoMuxer for HeldEncoderMuxer {+ type VideoFrame = TestVideoFrame;+ fn send_video_frame(+ &mut self,+ _frame: TestVideoFrame,+ _timestamp: Duration,+ ) -> anyhow::Result<()> {+ Ok(())+ }+ }++ #[cfg(windows)]+ #[tokio::test]+ async fn windows_actual_encoder_join_timeout_preserves_failed_without_acknowledgement() {+ let temp = tempfile::tempdir().unwrap();+ std::fs::create_dir(temp.path().join("content")).unwrap();+ write_in_progress_meta(temp.path()).unwrap();+ std::fs::write(temp.path().join("content/partial.m4s"), b"partial").unwrap();+ let (release, held) = std::sync::mpsc::channel();+ let (exited, mut joined) = tokio::sync::oneshot::channel();+ let (frames, receiver) = flume::bounded(4);+ let timestamps = Timestamps::now();+ let screen = OutputPipeline::builder(temp.path().join("content/display.mp4"))+ .with_video::<ChannelVideoSource<TestVideoFrame>>(ChannelVideoSourceConfig::new(+ test_video_info(),+ receiver,+ ))+ .with_timestamps(timestamps)+ .build::<HeldEncoderMuxer>((held, exited))+ .await+ .unwrap();+ let mut actor = super::windows_cancel_tests::cancelled_actor(None);+ actor.recording_dir = temp.path().to_owned();+ actor.state = Some(ActorState::Recording {+ pipeline: Pipeline {+ start_time: timestamps,+ screen,+ microphone: None,+ camera: None,+ system_audio: None,+ cursor: None,+ track_failures: Arc::new(std::sync::Mutex::new(Vec::new())),+ watcher_task: None,+ stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)),+ },+ index: 0,+ segment_start_time: 0.0,+ segment_start_instant: Instant::now().checked_sub(Duration::from_secs(2)).unwrap(),+ });+ let done_fut = completion_rx_to_done_fut(actor.completion_tx.subscribe());+ let actor_ref = Actor::spawn(actor);+ let handle = ActorHandle {+ recording_dir: temp.path().to_owned(),+ terminal: Arc::new(WindowsStudioTerminal::default()),+ actor_ref: actor_ref.clone(),+ capture_target: ScreenCaptureTarget::CameraOnly,+ done_fut,+ };+ let report = handle.stop_with_intent(StudioStopIntent::Preserve).await;+ assert!(!report.stop_acknowledged);+ assert!(report.result.err().unwrap().contains("held-test-encoder"));+ assert!(matches!(+ joined.try_recv(),+ Err(tokio::sync::oneshot::error::TryRecvError::Empty)+ ));+ assert!(matches!(+ RecordingMeta::load_for_project(temp.path())+ .unwrap()+ .studio_meta()+ .unwrap()+ .status(),+ StudioRecordingStatus::Failed { .. }+ ));+ assert_eq!(+ std::fs::read(temp.path().join("content/partial.m4s")).unwrap(),+ b"partial"+ );+ release.send(()).unwrap();+ joined.await.unwrap();+ drop(frames);+ actor_ref.kill();+ actor_ref.wait_for_stop().await;+ }++ #[cfg(windows)]+ async fn failing_requested_actor(+ recording_dir: &Path,+ role: RecordingTrackKind,+ ) -> (Actor, flume::Sender<TestVideoFrame>) {+ std::fs::create_dir_all(recording_dir.join("content")).unwrap();+ write_in_progress_meta(recording_dir).unwrap();+ std::fs::write(+ recording_dir.join("content/partial.m4s"),+ b"retained-real-output",+ )+ .unwrap();+ let timestamps = Timestamps::now();+ let (screen_tx, screen_rx) = flume::bounded(4);+ let (completion_tx, _completion_rx) = watch::channel(None);+ let (mut microphone_tx, microphone_rx) = futures::channel::mpsc::channel(4);+ let screen = OutputPipeline::builder(recording_dir.join("content/display.mp4"))+ .with_video::<ChannelVideoSource<TestVideoFrame>>(ChannelVideoSourceConfig::new(+ test_video_info(),+ screen_rx,+ ))+ .with_timestamps(timestamps)+ .build::<SuccessfulVideoMuxer>(())+ .await+ .unwrap();+ let microphone = OutputPipeline::builder(recording_dir.join("content/audio-input.ogg"))+ .with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(+ test_audio_info(),+ microphone_rx,+ ))+ .with_timestamps(timestamps)+ .build::<FailingAudioMuxer>(FailingAudioMuxerConfig {+ fail_after_frame: 1,+ })+ .await+ .unwrap();+ let microphone_done = microphone.done_fut();+ let mut pipeline = Pipeline {+ start_time: timestamps,+ screen,+ microphone: None,+ camera: None,+ system_audio: None,+ cursor: None,+ track_failures: Arc::new(std::sync::Mutex::new(Vec::new())),+ watcher_task: None,+ stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)),+ };+ match role {+ RecordingTrackKind::Microphone => pipeline.microphone = Some(microphone),+ RecordingTrackKind::Camera => pipeline.camera = Some(microphone),+ RecordingTrackKind::SystemAudio => pipeline.system_audio = Some(microphone),+ _ => panic!("requested-role fixture only"),+ }+ pipeline.spawn_watcher(completion_tx.clone());+ screen_tx+ .send_async(TestVideoFrame {+ timestamp: Timestamp::Instant(timestamps.instant()),+ })+ .await+ .unwrap();+ microphone_tx+ .try_send(crate::output_pipeline::AudioFrame::new(+ test_audio_info().empty_frame(960),+ Timestamp::Instant(timestamps.instant()),+ ))+ .unwrap();+ drop(microphone_tx);+ assert!(microphone_done.await.is_err());+ let segment_factory = SegmentPipelineFactory::new(+ recording_dir.join("content/segments"),+ recording_dir.join("content/cursors"),+ RecordingBaseInputs {+ capture_target: ScreenCaptureTarget::CameraOnly,+ capture_system_audio: false,+ mic_feed: None,+ camera_feed: None,+ },+ false,+ false,+ true,+ false,+ 30,+ crate::StudioQuality::Balanced,+ completion_tx.clone(),+ );+ (+ Actor {+ recording_dir: recording_dir.to_owned(),+ cancel_error: None,+ state: Some(ActorState::Recording {+ pipeline,+ index: 0,+ segment_start_time: 0.0,+ segment_start_instant: Instant::now()+ .checked_sub(Duration::from_secs(2))+ .unwrap(),+ }),+ segment_factory,+ segments: Vec::new(),+ completion_tx,+ display_notch: None,+ },+ screen_tx,+ )+ }++ #[cfg(windows)]+ #[tokio::test]+ async fn windows_required_failure_stop_and_cancel_preserve_failed_raw_data() {+ for (cancel, role) in [false, true].into_iter().flat_map(|cancel| {+ [+ RecordingTrackKind::Microphone,+ RecordingTrackKind::Camera,+ RecordingTrackKind::SystemAudio,+ ]+ .into_iter()+ .map(move |role| (cancel, role))+ }) {+ let temp = tempfile::tempdir().unwrap();+ let (actor, screen_tx) = failing_requested_actor(temp.path(), role).await;+ let completion = actor.completion_tx.subscribe();+ let actor = Actor::spawn(actor);+ let result = if cancel {+ actor.ask(Cancel).await+ } else {+ actor.ask(Stop).await.map(|_| ())+ };+ assert!(result.is_err());+ assert!(completion.borrow().as_ref().is_some_and(Result::is_err));+ assert!(matches!(+ RecordingMeta::load_for_project(temp.path())+ .unwrap()+ .studio_meta()+ .unwrap()+ .status(),+ StudioRecordingStatus::Failed { .. }+ ));+ assert_eq!(+ std::fs::read(temp.path().join("content/partial.m4s")).unwrap(),+ b"retained-real-output"+ );+ assert!(actor.ask(Cancel).await.is_err());+ drop(screen_tx);+ actor.kill();+ actor.wait_for_stop().await;+ }+ }++ #[cfg(windows)]+ #[tokio::test]+ async fn windows_terminal_failure_is_cached_and_conflicting_intent_is_rejected() {+ for first in [StudioStopIntent::Preserve, StudioStopIntent::Discard] {+ let temp = tempfile::tempdir().unwrap();+ let (actor, screen_tx) =+ failing_requested_actor(temp.path(), RecordingTrackKind::Microphone).await;+ let done_fut = completion_rx_to_done_fut(actor.completion_tx.subscribe());+ let actor_ref = Actor::spawn(actor);+ let handle = ActorHandle {+ recording_dir: temp.path().to_owned(),+ terminal: Arc::new(WindowsStudioTerminal::default()),+ actor_ref: actor_ref.clone(),+ capture_target: ScreenCaptureTarget::CameraOnly,+ done_fut,+ };+ let report = handle.stop_with_intent(first).await;+ assert!(report.accepted_intent);+ assert!(!report.stop_acknowledged);+ assert!(report.result.is_err());+ assert!(handle.terminal_started());+ assert!(!handle.stop_acknowledged());+ assert!(handle.same_attempt(&handle.clone()));+ let repeated = handle.stop_with_intent(first).await;+ assert_eq!(repeated.result.err(), report.result.err());+ let other = match first {+ StudioStopIntent::Preserve => StudioStopIntent::Discard,+ StudioStopIntent::Discard => StudioStopIntent::Preserve,+ };+ let rejected = handle.stop_with_intent(other).await;+ assert!(!rejected.accepted_intent);+ assert!(!rejected.stop_acknowledged);+ assert!(temp.path().join("content/partial.m4s").exists());+ drop(screen_tx);+ actor_ref.kill();+ actor_ref.wait_for_stop().await;+ }+ }+#[tokio::test]async fn stop_preserves_display_when_optional_track_fails_during_runtime() {let temp_dir = tempfile::tempdir().expect("temp dir should be created");@@ -2291,6 +4415,8 @@ mod tests {cursor: None,track_failures: Arc::new(std::sync::Mutex::new(Vec::new())),watcher_task: None,+ #[cfg(any(target_os = "linux", windows))]+ stopping: Arc::new(std::sync::atomic::AtomicBool::new(false)),};pipeline.spawn_watcher(completion_tx);@@ -2300,7 +4426,6 @@ mod tests {}).await.expect("display frame should send");- drop(screen_tx);microphone_tx.try_send(crate::output_pipeline::AudioFrame::new(@@ -2320,38 +4445,109 @@ mod tests {"runtime error should retain the mux send-failure context");- let finished = pipeline- .stop()- .await- .expect("display success should still allow the recording to stop cleanly");+ let stopped = pipeline.stop().await;+ #[cfg(windows)]+ {+ assert!(stopped.is_err());+ assert!(completion_rx.borrow().as_ref().is_some_and(Result::is_err));+ drop(screen_tx);+ }+ #[cfg(not(windows))]+ let finished =+ stopped.expect("display success should still allow the recording to stop cleanly");- assert_eq!(- finished.screen.video_frame_count, 1,- "display output should be preserved"- );- assert!(- finished.microphone.is_none(),- "optional microphone output should be dropped after runtime failure"- );- assert_eq!(- finished.track_failures.len(),- 1,- "runtime failure should be recorded exactly once"- );- assert!(- completion_rx.borrow().is_none(),- "optional runtime failure should not publish a required-track completion error"- );- assert_eq!(- finished.track_failures[0].track,- RecordingTrackKind::Microphone- );- assert_eq!(finished.track_failures[0].stage, TrackFailureStage::Runtime);- assert!(- finished.track_failures[0]- .error- .contains("Audio muxer stopped accepting frames at frame 1"),- "recorded runtime failure should preserve the mux send-failure context"+ #[cfg(not(windows))]+ drop(screen_tx);+ #[cfg(not(windows))]+ {+ assert_eq!(+ finished.screen.video_frame_count, 1,+ "display output should be preserved"+ );+ assert!(+ finished.microphone.is_none(),+ "optional microphone output should be dropped after runtime failure"+ );+ assert_eq!(+ finished.track_failures.len(),+ 1,+ "runtime failure should be recorded exactly once"+ );+ #[cfg(target_os = "linux")]+ assert!(completion_rx.borrow().as_ref().is_some_and(Result::is_err));+ #[cfg(not(target_os = "linux"))]+ assert!(completion_rx.borrow().is_none());+ assert_eq!(+ finished.track_failures[0].track,+ RecordingTrackKind::Microphone+ );+ assert_eq!(finished.track_failures[0].stage, TrackFailureStage::Runtime);+ assert!(+ finished.track_failures[0]+ .error+ .contains("Audio muxer stopped accepting frames at frame 1"),+ "recorded runtime failure should preserve the mux send-failure context"+ );+ }+ }+}++#[cfg(all(test, windows))]+mod windows_cancel_tests {+ use super::*;++ pub(super) fn cancelled_actor(error: Option<String>) -> Actor {+ let (completion_tx, _completion_rx) = watch::channel(None);+ let segment_factory = SegmentPipelineFactory::new(+ PathBuf::new(),+ PathBuf::new(),+ RecordingBaseInputs {+ capture_target: ScreenCaptureTarget::CameraOnly,+ capture_system_audio: false,+ mic_feed: None,+ camera_feed: None,+ },+ false,+ false,+ true,+ false,+ 30,+ crate::StudioQuality::Balanced,+ completion_tx.clone(),);+ Actor {+ recording_dir: PathBuf::new(),+ state: None,+ cancel_error: error,+ segment_factory,+ segments: Vec::new(),+ completion_tx,+ display_notch: None,+ }+ }++ #[tokio::test]+ async fn cancel_error_stays_observable_after_pipeline_was_taken() {+ let actor = Actor::spawn(cancelled_actor(Some("display shutdown failed".into())));+ for _ in 0..2 {+ assert!(+ actor+ .ask(Cancel)+ .await+ .unwrap_err()+ .to_string()+ .contains("display shutdown failed")+ );+ }+ actor.kill();+ actor.wait_for_stop().await;+ }++ #[tokio::test]+ async fn clean_cancelled_actor_can_acknowledge_cancel() {+ let actor = Actor::spawn(cancelled_actor(None));+ actor.ask(Cancel).await.unwrap();+ actor.kill();+ actor.wait_for_stop().await;}}diff --git a/crates/recording/src/track_heal.rs b/crates/recording/src/track_heal.rsindex 2534ec7cd..c24667880 100644--- a/crates/recording/src/track_heal.rs+++ b/crates/recording/src/track_heal.rs@@ -621,10 +621,8 @@ fn rescale_project_config(project_path: &Path, scales: &HashMap<u32, f64>) {changed = true;}- if changed {- if let Err(e) = config.write(project_path) {- warn!("Failed to write rescaled project config after display heal: {e}");- }+ if changed && let Err(e) = config.write(project_path) {+ warn!("Failed to write rescaled project config after display heal: {e}");}}diff --git a/crates/recording/tests/recovery.rs b/crates/recording/tests/recovery.rsindex 3895bc32e..eed5f5281 100644--- a/crates/recording/tests/recovery.rs+++ b/crates/recording/tests/recovery.rs@@ -489,16 +489,8 @@ fn test_failed_recording_is_terminal_for_startup_recovery() {let recording = TestRecording::new().unwrap();let display_dir = recording.create_display_dir(0).unwrap();- recording- .write_manifest(- 0,- "display",- &[("segment_001.m4s", true, 150)],- Some("init.mp4"),- )- .unwrap();- std::fs::write(display_dir.join("init.mp4"), create_minimal_mp4_data()).unwrap();- std::fs::write(display_dir.join("segment_001.m4s"), vec![1u8; 150]).unwrap();+ write_synthetic_fragments(&display_dir, 180, Duration::from_secs(2));+ assert_valid_synthetic_fragments(&display_dir);recording.write_recording_meta(StudioRecordingStatus::Failed {error: "Some other error".to_string(),@@ -805,18 +797,20 @@ fn test_inspect_recording_recovers_orphaned_m4s_fragments_with_init() {let recording = TestRecording::new().unwrap();let display_dir = recording.create_display_dir(0).unwrap();+ write_synthetic_fragments(&display_dir, 180, Duration::from_secs(2));+ let expected_fragments = assert_valid_synthetic_fragments(&display_dir);+ let first = &expected_fragments[0];+ let first_name = first.file_name().unwrap().to_str().unwrap();+ let first_size = std::fs::metadata(first).unwrap().len();recording.write_manifest(0,"display",- &[("segment_001.m4s", false, 150)],+ &[(first_name, true, first_size)],Some("init.mp4"),).unwrap();- std::fs::write(display_dir.join("init.mp4"), create_minimal_mp4_data()).unwrap();- std::fs::write(display_dir.join("segment_001.m4s"), vec![1u8; 150]).unwrap();- std::fs::write(display_dir.join("segment_002.m4s"), vec![2u8; 175]).unwrap();- std::fs::write(display_dir.join("segment_003.m4s.tmp"), vec![3u8; 200]).unwrap();+ std::fs::write(display_dir.join("segment_999.m4s.tmp"), vec![3u8; 200]).unwrap();recording.write_recording_meta(StudioRecordingStatus::Failed {error: "No recoverable segments found".to_string(),@@ -828,15 +822,8 @@ fn test_inspect_recording_recovers_orphaned_m4s_fragments_with_init() {assert_eq!(incomplete.recoverable_segments.len(), 1);let segment = &incomplete.recoverable_segments[0];- assert_eq!(segment.display_fragments.len(), 2);- assert_eq!(- segment- .display_fragments- .iter()- .map(|path| path.file_name().unwrap().to_string_lossy().to_string())- .collect::<Vec<_>>(),- vec!["segment_001.m4s".to_string(), "segment_002.m4s".to_string()]- );+ assert_eq!(segment.display_fragments, expected_fragments);+ assert!(display_dir.join("segment_999.m4s.tmp").exists());assert_eq!(segment.display_init_segment@@ -1258,13 +1245,25 @@ fn write_synthetic_fragments(display_dir: &Path, total_frames: u64, segment_durafor i in 0..total_frames {let frame = make_synthetic_video_frame(320, 240);- let ts = Duration::from_micros(i * 33_333);+ let ts = Duration::from_nanos(i * 1_000_000_000 / 30);encoder.queue_frame(frame, ts).expect("queue frame");}drop(encoder);}+fn assert_valid_synthetic_fragments(display_dir: &Path) -> Vec<PathBuf> {+ let fragments = list_m4s_segments(display_dir);+ assert!(fragments.len() >= 2);+ let control = TempDir::new().unwrap();+ let output = control.path().join("fixture-control.mp4");+ concatenate_m4s_segments_with_init(&display_dir.join("init.mp4"), &fragments, &output).unwrap();+ assert!(probe_video_can_decode(&output).unwrap());+ probe_video_seek_points(&output, 8).unwrap();+ assert!(cap_enc_ffmpeg::remux::get_media_duration(&output).unwrap() >= Duration::from_secs(4));+ fragments+}+#[test]fn recover_after_simulated_crash_produces_playable_mp4_with_preserved_duration() {test_utils::init_tracing();@@ -1360,7 +1359,9 @@ fn recover_preserves_fragments_when_progressive_mp4_validation_fails() {assert!(matches!(result,- Err(RecoveryError::UnplayableVideo(_)) | Err(RecoveryError::VideoConcat(_))+ Err(RecoveryError::UnplayableVideo(_))+ | Err(RecoveryError::VideoConcat(_))+ | Err(RecoveryError::Validation(_))),"failure should be UnplayableVideo or VideoConcat, got {result:?}");@@ -1591,3 +1592,469 @@ fn finalize_to_progressive_mp4_public_api_produces_playable_output() {"finalize_to_progressive_mp4 must not delete fragments - that's the caller's responsibility");}++fn recovery_input_bytes(project: &Path) -> std::collections::BTreeMap<PathBuf, Vec<u8>> {+ fn visit(root: &Path, dir: &Path, result: &mut std::collections::BTreeMap<PathBuf, Vec<u8>>) {+ for entry in std::fs::read_dir(dir).unwrap() {+ let path = entry.unwrap().path();+ if path+ .file_name()+ .unwrap()+ .to_string_lossy()+ .starts_with(".recovery")+ {+ continue;+ }+ if path.is_dir() {+ visit(root, &path, result);+ } else {+ let _ = result.insert(+ path.strip_prefix(root).unwrap().to_path_buf(),+ std::fs::read(path).unwrap(),+ );+ }+ }+ }+ let mut result = std::collections::BTreeMap::new();+ visit(project, project, &mut result);+ result+}++fn set_recovery_optional_tracks(project: &Path) {+ let mut meta = RecordingMeta::load_for_project(project).unwrap();+ let RecordingMetaInner::Studio(studio) = &mut meta.inner else {+ panic!("studio");+ };+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {+ panic!("segments");+ };+ let segment = &mut inner.segments[0];+ segment.camera = Some(VideoMeta {+ path: RelativePathBuf::from("content/segments/segment-0/camera.mp4"),+ fps: 30,+ start_time: Some(0.0),+ device_id: None,+ });+ segment.mic = Some(cap_project::AudioMeta {+ path: RelativePathBuf::from("content/segments/segment-0/audio-input.ogg"),+ start_time: Some(0.0),+ device_id: None,+ gap_summary: None,+ });+ segment.system_audio = Some(cap_project::AudioMeta {+ path: RelativePathBuf::from("content/segments/segment-0/system_audio.ogg"),+ start_time: Some(0.0),+ device_id: None,+ gap_summary: None,+ });+ meta.save_for_project().unwrap();+}++fn write_recovery_wav(path: &Path) {+ let samples = vec![0_u8; 48000 * 2 * 3];+ let mut bytes = Vec::new();+ bytes.extend_from_slice(b"RIFF");+ bytes.extend_from_slice(&(36 + samples.len() as u32).to_le_bytes());+ bytes.extend_from_slice(b"WAVEfmt ");+ bytes.extend_from_slice(&16_u32.to_le_bytes());+ bytes.extend_from_slice(&1_u16.to_le_bytes());+ bytes.extend_from_slice(&1_u16.to_le_bytes());+ bytes.extend_from_slice(&48000_u32.to_le_bytes());+ bytes.extend_from_slice(&96000_u32.to_le_bytes());+ bytes.extend_from_slice(&2_u16.to_le_bytes());+ bytes.extend_from_slice(&16_u16.to_le_bytes());+ bytes.extend_from_slice(b"data");+ bytes.extend_from_slice(&(samples.len() as u32).to_le_bytes());+ bytes.extend_from_slice(&samples);+ std::fs::write(path, bytes).unwrap();+}++fn complete_recovery_fixture() -> TestRecording {+ let recording = TestRecording::new().unwrap();+ let display = recording.create_display_dir(0).unwrap();+ let camera = recording.create_segment_dir(0).unwrap().join("camera");+ std::fs::create_dir(&camera).unwrap();+ write_synthetic_fragments(&display, 180, Duration::from_secs(2));+ write_synthetic_fragments(&camera, 180, Duration::from_secs(2));+ let segment = recording.path().join("content/segments/segment-0");+ write_recovery_wav(&segment.join("audio-input.m4a"));+ write_recovery_wav(&segment.join("system_audio.m4a"));+ recording+ .write_recording_meta(StudioRecordingStatus::InProgress)+ .unwrap();+ set_recovery_optional_tracks(recording.path());+ recording+}++#[test]+fn recovery_and_finalize_retain_every_known_track_on_success() {+ test_utils::init_tracing();+ for finalize in [false, true] {+ let recording = complete_recovery_fixture();+ let incomplete = RecoveryManager::inspect_recording(recording.path()).unwrap();+ let recovered = if finalize {+ RecoveryManager::finalize(&incomplete)+ } else {+ RecoveryManager::recover(&incomplete)+ }+ .unwrap();+ let StudioRecordingMeta::MultipleSegments { inner } = recovered.meta else {+ panic!("segments");+ };+ assert!(matches!(+ inner.status,+ Some(StudioRecordingStatus::Complete)+ ));+ assert_eq!(inner.segments.len(), 1);+ let segment = &inner.segments[0];+ assert!(segment.camera.is_some());+ assert!(segment.mic.is_some());+ assert!(segment.system_audio.is_some());+ for path in [+ &segment.display.path,+ &segment.camera.as_ref().unwrap().path,+ &segment.mic.as_ref().unwrap().path,+ &segment.system_audio.as_ref().unwrap().path,+ ] {+ assert!(path.to_path(recording.path()).is_file());+ }+ cap_project::ProjectConfiguration::load(recording.path())+ .unwrap()+ .validate()+ .unwrap();+ assert!(recording.path().join(".recovery.lock").is_file());+ }+}++#[test]+fn recovery_and_finalize_missing_known_optional_tracks_preserve_all_original_bytes() {+ test_utils::init_tracing();+ for target in ["camera", "audio-input.m4a", "system_audio.m4a"] {+ let recording = complete_recovery_fixture();+ let target = recording+ .path()+ .join("content/segments/segment-0")+ .join(target);+ if target.is_dir() {+ std::fs::remove_dir_all(target).unwrap();+ } else {+ std::fs::remove_file(target).unwrap();+ }+ let incomplete = RecoveryManager::inspect_recording(recording.path()).unwrap();+ let before = recovery_input_bytes(recording.path());+ assert!(RecoveryManager::recover(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+ assert!(RecoveryManager::finalize(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+ }+}++#[test]+fn recovery_rejects_missing_whole_known_segment_without_mutation() {+ test_utils::init_tracing();+ let recording = complete_recovery_fixture();+ let mut meta = RecordingMeta::load_for_project(recording.path()).unwrap();+ let RecordingMetaInner::Studio(studio) = &mut meta.inner else {+ panic!("studio");+ };+ let StudioRecordingMeta::MultipleSegments { inner } = studio.as_mut() else {+ panic!("segments");+ };+ inner.segments.push(inner.segments[0].clone());+ meta.save_for_project().unwrap();+ let incomplete = RecoveryManager::inspect_recording(recording.path()).unwrap();+ let before = recovery_input_bytes(recording.path());+ assert!(RecoveryManager::recover(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+}++#[test]+fn recovery_invalid_camera_audio_and_configuration_leave_raw_and_status_unchanged() {+ test_utils::init_tracing();+ for name in [+ "content/segments/segment-0/camera/init.mp4",+ "content/segments/segment-0/audio-input.m4a",+ "content/segments/segment-0/system_audio.m4a",+ "project-config.json",+ ] {+ let recording = complete_recovery_fixture();+ std::fs::write(recording.path().join(name), b"corrupt input").unwrap();+ let incomplete = RecoveryManager::inspect_recording(recording.path()).unwrap();+ let before = recovery_input_bytes(recording.path());+ assert!(RecoveryManager::recover(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+ assert!(RecoveryManager::finalize(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+ }+}++#[test]+fn recovery_rejects_a_present_unlisted_invalid_track_and_a_stale_snapshot() {+ test_utils::init_tracing();+ let recording = TestRecording::new().unwrap();+ write_synthetic_fragments(+ &recording.create_display_dir(0).unwrap(),+ 180,+ Duration::from_secs(2),+ );+ recording+ .write_recording_meta(StudioRecordingStatus::InProgress)+ .unwrap();+ std::fs::write(+ recording+ .path()+ .join("content/segments/segment-0/audio-input.m4a"),+ b"invalid unlisted audio",+ )+ .unwrap();+ let incomplete = RecoveryManager::inspect_recording(recording.path()).unwrap();+ let before = recovery_input_bytes(recording.path());+ assert!(RecoveryManager::recover(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+ let mut meta = RecordingMeta::load_for_project(recording.path()).unwrap();+ meta.pretty_name = "changed after inspection".into();+ meta.save_for_project().unwrap();+ let before = recovery_input_bytes(recording.path());+ assert!(RecoveryManager::finalize(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+}++#[test]+fn recovery_rejects_video_only_container_used_as_required_audio() {+ test_utils::init_tracing();+ let recording = complete_recovery_fixture();+ let video = recording.path().join("audio-container.mp4");+ RecoveryManager::finalize_to_progressive_mp4(+ &recording.path().join("content/segments/segment-0/display"),+ &video,+ )+ .unwrap();+ let audio = recording+ .path()+ .join("content/segments/segment-0/audio-input.m4a");+ std::fs::copy(video, &audio).unwrap();+ assert!(cap_enc_ffmpeg::remux::probe_media_valid(&audio));+ let incomplete = RecoveryManager::inspect_recording(recording.path()).unwrap();+ let before = recovery_input_bytes(recording.path());+ assert!(RecoveryManager::recover(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+}++#[test]+fn recovery_rejects_later_corrupt_video_even_when_first_frame_decodes() {+ test_utils::init_tracing();+ let recording = complete_recovery_fixture();+ let display = recording.path().join("content/segments/segment-0/display");+ let mut fragments: Vec<_> = std::fs::read_dir(&display)+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .filter(|path| path.extension().is_some_and(|extension| extension == "m4s"))+ .collect();+ fragments.sort();+ assert!(fragments.len() >= 2);+ let target = &fragments[1];+ let mut bytes = std::fs::read(target).unwrap();+ let mdat = bytes.windows(4).position(|value| value == b"mdat").unwrap() + 4;+ let end = (mdat + 64).min(bytes.len());+ bytes[mdat..end].fill(0xff);+ std::fs::write(target, bytes).unwrap();+ let combined = recording.path().join("first-frame-control.mp4");+ let mut control = std::fs::read(display.join("init.mp4")).unwrap();+ for fragment in &fragments {+ control.extend(std::fs::read(fragment).unwrap());+ }+ std::fs::write(&combined, control).unwrap();+ assert!(probe_video_can_decode(&combined).unwrap());+ let incomplete = RecoveryManager::inspect_recording(recording.path()).unwrap();+ let before = recovery_input_bytes(recording.path());+ assert!(RecoveryManager::recover(&incomplete).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+}++fn write_recovery_dash_audio(directory: &Path) {+ let info = cap_media_info::AudioInfo::new_raw(+ ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar),+ 48000,+ 1,+ );+ let mut encoder = cap_enc_ffmpeg::dash_audio::DashAudioSegmentEncoder::init(+ directory.to_path_buf(),+ info,+ cap_enc_ffmpeg::dash_audio::DashAudioSegmentEncoderConfig {+ segment_duration: Duration::from_secs(1),+ },+ )+ .unwrap();+ for index in 0..150_u64 {+ let mut frame = info.empty_frame(1024);+ frame.data_mut(0).fill(0);+ encoder+ .queue_frame(+ frame,+ Duration::from_secs_f64(index as f64 * 1024.0 / 48000.0),+ )+ .unwrap();+ }+ encoder.finish().unwrap();+}++#[test]+fn instant_recovery_preserves_valid_audio_and_legitimate_video_only_recordings() {+ test_utils::init_tracing();+ for with_audio in [false, true] {+ let recording = TestRecording::new().unwrap();+ let display = recording.path().join("content/display");+ std::fs::create_dir_all(&display).unwrap();+ write_synthetic_fragments(&display, 180, Duration::from_secs(2));+ let audio = recording.path().join("content/audio");+ if with_audio {+ write_recovery_dash_audio(&audio);+ }+ let before = recovery_input_bytes(recording.path());+ let output = recording.path().join("content/output.mp4");+ RecoveryManager::finalize_instant_output(&display, &audio, &output).unwrap();+ let input = ffmpeg::format::input(&output).unwrap();+ assert!(input.streams().best(ffmpeg::media::Type::Video).is_some());+ assert_eq!(+ input.streams().best(ffmpeg::media::Type::Audio).is_some(),+ with_audio+ );+ for (relative, bytes) in before {+ assert_eq!(+ std::fs::read(recording.path().join(relative)).unwrap(),+ bytes+ );+ }+ }+}++#[test]+fn instant_recovery_empty_or_invalid_expected_audio_cannot_replace_existing_output() {+ test_utils::init_tracing();+ for corrupt in [false, true] {+ let recording = TestRecording::new().unwrap();+ let display = recording.path().join("content/display");+ std::fs::create_dir_all(&display).unwrap();+ write_synthetic_fragments(&display, 180, Duration::from_secs(2));+ let output = recording.path().join("content/output.mp4");+ RecoveryManager::finalize_to_progressive_mp4(&display, &output).unwrap();+ let audio = recording.path().join("content/audio");+ if corrupt {+ write_recovery_dash_audio(&audio);+ std::fs::write(audio.join("init.mp4"), b"corrupt audio init").unwrap();+ } else {+ std::fs::create_dir(&audio).unwrap();+ }+ let before = recovery_input_bytes(recording.path());+ assert!(RecoveryManager::finalize_instant_output(&display, &audio, &output).is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+ }+}++#[test]+fn instant_recovery_refuses_known_failed_and_known_missing_audio_without_mutation() {+ test_utils::init_tracing();+ for inner in [+ cap_project::InstantRecordingMeta::Failed {+ error: "required microphone failed".into(),+ },+ cap_project::InstantRecordingMeta::Complete {+ fps: 30,+ sample_rate: Some(48000),+ },+ ] {+ let recording = TestRecording::new().unwrap();+ let display = recording.path().join("content/display");+ std::fs::create_dir_all(&display).unwrap();+ write_synthetic_fragments(&display, 180, Duration::from_secs(2));+ recording+ .write_recording_meta(StudioRecordingStatus::InProgress)+ .unwrap();+ let mut meta = RecordingMeta::load_for_project(recording.path()).unwrap();+ meta.inner = RecordingMetaInner::Instant(inner);+ meta.save_for_project().unwrap();+ let before = recovery_input_bytes(recording.path());+ assert!(+ RecoveryManager::finalize_instant_output(+ &display,+ &recording.path().join("content/audio"),+ &recording.path().join("content/output.mp4")+ )+ .is_err()+ );+ assert_eq!(recovery_input_bytes(recording.path()), before);+ }+}++#[test]+fn repeated_instant_finalization_does_not_retain_staging_copies() {+ test_utils::init_tracing();+ let recording = TestRecording::new().unwrap();+ let display = recording.path().join("content/display");+ std::fs::create_dir_all(&display).unwrap();+ write_synthetic_fragments(&display, 180, Duration::from_secs(2));+ let audio = recording.path().join("content/audio");+ write_recovery_dash_audio(&audio);+ let before = recovery_input_bytes(recording.path());+ let output = recording.path().join("content/output.mp4");+ for _ in 0..3 {+ RecoveryManager::finalize_instant_output(&display, &audio, &output).unwrap();+ let mut after = recovery_input_bytes(recording.path());+ assert!(after.remove(Path::new("content/output.mp4")).is_some());+ assert_eq!(after, before);+ assert!(std::fs::read_dir(recording.path()).unwrap().all(|entry| {+ !entry+ .unwrap()+ .file_name()+ .to_string_lossy()+ .starts_with(".recovery-")+ }));+ let input = ffmpeg::format::input(&output).unwrap();+ assert!(input.streams().best(ffmpeg::media::Type::Video).is_some());+ assert!(input.streams().best(ffmpeg::media::Type::Audio).is_some());+ }+}++#[test]+fn instant_recovery_rebuilds_corrupt_prior_output_only_from_valid_required_raw() {+ test_utils::init_tracing();+ for invalid_audio in [false, true] {+ let recording = TestRecording::new().unwrap();+ let display = recording.path().join("content/display");+ std::fs::create_dir_all(&display).unwrap();+ write_synthetic_fragments(&display, 180, Duration::from_secs(2));+ let audio = recording.path().join("content/audio");+ write_recovery_dash_audio(&audio);+ if invalid_audio {+ std::fs::write(audio.join("init.mp4"), b"invalid required audio").unwrap();+ }+ let output = recording.path().join("content/output.mp4");+ std::fs::write(&output, b"interrupted MP4 header").unwrap();+ let before = recovery_input_bytes(recording.path());+ let result = RecoveryManager::finalize_instant_output(&display, &audio, &output);+ if invalid_audio {+ assert!(result.is_err());+ assert_eq!(recovery_input_bytes(recording.path()), before);+ } else {+ result.unwrap();+ for (relative, bytes) in before {+ if relative != Path::new("content/output.mp4") {+ assert_eq!(+ std::fs::read(recording.path().join(relative)).unwrap(),+ bytes+ );+ }+ }+ let input = ffmpeg::format::input(&output).unwrap();+ assert!(input.streams().best(ffmpeg::media::Type::Video).is_some());+ assert!(input.streams().best(ffmpeg::media::Type::Audio).is_some());+ assert!(std::fs::read_dir(recording.path()).unwrap().all(|entry| {+ !entry+ .unwrap()+ .file_name()+ .to_string_lossy()+ .starts_with(".recovery-")+ }));+ }+ }+}diff --git a/crates/recording/tests/sync_matrix.rs b/crates/recording/tests/sync_matrix.rsindex 8df7dc0ef..f321266bd 100644--- a/crates/recording/tests/sync_matrix.rs+++ b/crates/recording/tests/sync_matrix.rs@@ -472,7 +472,7 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {// Drops shorten coverage but must not shrink the recorded span// beyond the dropped tail/head, and must never stretch it.if let Some((first, last)) = finished.video_timestamp_span {- let span = (last - first).as_secs_f64();+ let span = last.saturating_sub(first).as_secs_f64();let expected = sent.last().unwrap() - sent[0];if span > expected + 0.25 || span < expected - 0.5 {return Err(format!(@@ -534,7 +534,7 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {// The span the recorder would persist must match the sent span.if let Some((first, last)) = finished.video_timestamp_span {- let span = (last - first).as_secs_f64();+ let span = last.saturating_sub(first).as_secs_f64();let expected = sent.last().unwrap() - sent[0];if (span - expected).abs() > 0.25 {return Err(format!(diff --git a/crates/rendering/src/project_recordings.rs b/crates/rendering/src/project_recordings.rsindex 6da1ff96c..9e4e3f471 100644--- a/crates/rendering/src/project_recordings.rs+++ b/crates/rendering/src/project_recordings.rs@@ -123,6 +123,8 @@ pub struct ProjectRecordingsMeta {impl ProjectRecordingsMeta {pub fn new(recording_path: &PathBuf, meta: &StudioRecordingMeta) -> Result<Self, String> {+ meta.ensure_ordinary_media_access(recording_path)?;+let segments = match &meta {StudioRecordingMeta::SingleSegment { segment: s } => {let display = Video::new(s.display.path.to_path(recording_path), 0.0)@@ -255,3 +257,23 @@ impl SegmentRecordings {duration_ns[0]}}++#[cfg(test)]+mod ordinary_media_access_tests {+ use super::ProjectRecordingsMeta;+ use cap_project::StudioRecordingMeta;+ use std::path::PathBuf;++ #[test]+ fn failed_project_refuses_before_opening_invalid_media() {+ let meta: StudioRecordingMeta = serde_json::from_str(+ r#"{"segments":[{"display":{"path":"never-created/display.mp4"}}],"status":{"status":"Failed","error":"requested source failed"}}"#,+ ).unwrap();+ let error = match ProjectRecordingsMeta::new(&PathBuf::from("never-created-project"), &meta)+ {+ Ok(_) => panic!("failed recording unexpectedly accepted"),+ Err(error) => error,+ };+ assert!(error.contains("requested source failed"));+ }+}diff --git a/crates/scap-targets/src/platform/linux.rs b/crates/scap-targets/src/platform/linux.rsindex 566eb6308..751d23ce9 100644--- a/crates/scap-targets/src/platform/linux.rs+++ b/crates/scap-targets/src/platform/linux.rs@@ -206,7 +206,7 @@ impl WindowImpl {pub fn physical_bounds(&self) -> Option<PhysicalBounds> {if is_wayland_portal_window(self.0) {- return Some(DisplayImpl::primary().physical_bounds()?);+ return DisplayImpl::primary().physical_bounds();}let (conn, screen_num) = x11_connection().ok()?;diff --git a/crates/timestamp/src/master_clock.rs b/crates/timestamp/src/master_clock.rsindex a97d515d1..a203d4d08 100644--- a/crates/timestamp/src/master_clock.rs+++ b/crates/timestamp/src/master_clock.rs@@ -169,6 +169,7 @@ pub struct SourceClockState {timing_set: bool,timing_adjust: i64,next_expected_ns: Option<i64>,+ last_cadence_output_ns: Option<u64>,snap_count: u64,hard_reset_count: u64,resync_count: u64,@@ -183,6 +184,7 @@ impl SourceClockState {timing_set: false,timing_adjust: 0,next_expected_ns: None,+ last_cadence_output_ns: None,snap_count: 0,hard_reset_count: 0,resync_count: 0,@@ -233,8 +235,35 @@ impl SourceClockState {source_ts: Timestamp,frame_duration_ns: u64,) -> SourceClockRemap {- let raw_ns = clock.remap_raw_ns(source_ts);- let now_ns = clock.elapsed_ns() as i64;+ self.remap_ns(+ clock.remap_raw_ns(source_ts),+ clock.elapsed_ns() as i64,+ frame_duration_ns,+ true,+ )+ }++ pub fn remap_preserving_cadence(+ &mut self,+ clock: &MasterClock,+ source_ts: Timestamp,+ frame_duration_ns: u64,+ ) -> SourceClockRemap {+ self.remap_ns(+ clock.remap_raw_ns(source_ts),+ clock.elapsed_ns() as i64,+ frame_duration_ns,+ false,+ )+ }++ fn remap_ns(+ &mut self,+ raw_ns: i64,+ now_ns: i64,+ frame_duration_ns: u64,+ smooth: bool,+ ) -> SourceClockRemap {self.frame_count = self.frame_count.saturating_add(1);let using_direct_ts = abs_diff_u64(raw_ns, now_ns) < MAX_TS_VAR_NS;@@ -262,7 +291,7 @@ impl SourceClockState {self.hard_reset_count = self.hard_reset_count.saturating_add(1);self.resync_count = self.resync_count.saturating_add(1);outcome = SourceClockOutcome::HardReset;- } else if diff < TS_SMOOTHING_THRESHOLD_NS {+ } else if smooth && diff < TS_SMOOTHING_THRESHOLD_NS {// Snap jitter onto the expected cadence, but cap how far the// ladder may lead the source clock. Each snap re-anchors// next_expected, so a source delivering faster than the@@ -288,7 +317,19 @@ impl SourceClockState {}self.next_expected_ns = Some(ts_ns.saturating_add(duration_ns));- let output_ns = ts_ns.saturating_add(self.timing_adjust).max(0) as u64;+ let mut output_ns = ts_ns.saturating_add(self.timing_adjust).max(0) as u64;+ if smooth {+ self.last_cadence_output_ns = None;+ } else {+ if let Some(previous) = self.last_cadence_output_ns+ && !matches!(outcome, SourceClockOutcome::HardReset)+ && output_ns < previous+ {+ output_ns = previous;+ outcome = SourceClockOutcome::Smoothed;+ }+ self.last_cadence_output_ns = Some(output_ns);+ }SourceClockRemap {master_ns: output_ns,@@ -301,6 +342,7 @@ impl SourceClockState {self.timing_set = false;self.timing_adjust = 0;self.next_expected_ns = None;+ self.last_cadence_output_ns = None;}}@@ -652,4 +694,208 @@ mod tests {let result = state.remap(&clock, ts, frame_ns);assert!(result.master_ns == 0 || result.master_ns <= 1_000_000_000);}+ #[test]+ fn preserving_cadence_does_not_release_recorded_smoothing_lag() {+ let samples = [+ (46154413, 78690394),+ (65568721, 135377154),+ (110897087, 172279669),+ (132556133, 193694100),+ (194257322, 206714730),+ (210630064, 228600321),+ (295866539, 326602031),+ (331422825, 390005096),+ (358539718, 429724051),+ (391572010, 454430003),+ (419586633, 474622237),+ (463879066, 499774959),+ (472447881, 533644768),+ (513265949, 568866386),+ (553800082, 589048951),+ (612231200, 650842341),+ (659399095, 685934536),+ ];+ let mut legacy = SourceClockState::new("legacy-video");+ let mut preserving = SourceClockState::new("continuous-video");+ let mut legacy_output = Vec::new();+ let mut preserved_output = Vec::new();+ for (raw, now) in samples {+ legacy_output.push(legacy.remap_ns(raw, now, 33_333_333, true).master_ns);+ preserved_output.push(preserving.remap_ns(raw, now, 33_333_333, false).master_ns);+ }+ assert_eq!(legacy_output[16] - legacy_output[15], 113_244_687);+ assert_eq!(preserved_output[16] - preserved_output[15], 47_167_895);+ assert_eq!(legacy_output[0], preserved_output[0]);+ assert_eq!(preserving.snap_count(), 0);+ assert_eq!(preserving.hard_reset_count(), 0);+ }++ #[test]+ fn preserving_cadence_replays_every_recorded_interval() {+ let samples: [i64; 166] = [+ 46154413, 65568721, 110897087, 132556133, 194257322, 210630064, 295866539, 331422825,+ 358539718, 391572010, 419586633, 463879066, 472447881, 513265949, 553800082, 612231200,+ 659399095, 684859793, 703765590, 771137903, 816569916, 829567548, 863610545, 926770792,+ 969115079, 983414049, 1040848452, 1050334828, 1099575914, 1159724806, 1175198241,+ 1207247075, 1239602166, 1305713087, 1336115915, 1367591857, 1429003927, 1450650105,+ 1482563646, 1507565298, 1548602526, 1608592995, 1615701319, 1683213311, 1697719775,+ 1742772459, 1775887617, 1801167715, 1858162227, 1910977942, 1955903885, 1977035872,+ 2006647063, 2044937201, 2127620053, 2149847594, 2170967171, 2221614788, 2279627404,+ 2289253362, 2333763286, 2382028011, 2412563172, 2444953954, 2490800736, 2549402425,+ 2584977585, 2615680580, 2650109725, 2665944218, 2745574052, 2781041320, 2820631617,+ 2842908220, 2871194752, 2915919941, 2962020029, 2991660101, 3038647128, 3057869964,+ 3092459053, 3158726868, 3166722481, 3246562870, 3281329262, 3313973509, 3371634807,+ 3398569941, 3461197437, 3499790112, 3509911781, 3588729118, 3626970626, 3632929245,+ 3696523572, 3743563090, 3770569195, 3793558443, 3831804481, 3856646119, 3898780811,+ 3940568105, 3980226504, 4016559191, 4052128431, 4066657406, 4120152494, 4151270637,+ 4184461316, 4206797820, 4275284412, 4307124812, 4323324283, 4350754207, 4400827291,+ 4450575108, 4463290634, 4517560479, 4541563458, 4574001281, 4627021529, 4639667832,+ 4701963641, 4715851742, 4756979912, 4799046093, 4825566377, 4857078700, 4888566231,+ 4915249779, 4957961094, 4987293889, 5048028694, 5071025932, 5112782536, 5148460569,+ 5180622435, 5197751016, 5247952933, 5275295305, 5331623674, 5360745415, 5382814833,+ 5433875878, 5461561168, 5491354103, 5521647539, 5567574883, 5599380402, 5623347371,+ 5664391349, 5692765944, 5731586034, 5753006938, 5774332970, 5848158628, 5884141787,+ 5911433118, 5926586376, 5998337740, 6012802883, 6052260307, 6129125352, 6162385302,+ 6196413748, 6214714645,+ ];+ let mut state = SourceClockState::new("recorded-video");+ let mut previous = None;+ for raw in samples {+ let mapped = state.remap_ns(raw, raw + 30_000_000, 33_333_333, false);+ assert_eq!(mapped.master_ns, raw as u64);+ if let Some((previous_raw, previous_output)) = previous {+ assert_eq!(+ mapped.master_ns - previous_output,+ (raw - previous_raw) as u64+ );+ assert!(mapped.master_ns - previous_output < 100_000_000);+ }+ previous = Some((raw, mapped.master_ns));+ }+ }++ #[test]+ fn preserving_cadence_matches_each_interval_across_rates_and_jitter() {+ for nominal in [24.0, 30.0, 60.0] {+ for actual in [+ 10.0, 15.0, 20.0, 24.0, 25.0, 29.97, 30.0, 48.0, 60.0, 90.0, 120.0, 240.0, 500.0,+ 1000.0,+ ] {+ for jitter in [0.0, 0.3] {+ let mut state = SourceClockState::new("cadence-matrix");+ let mut rng = TestRng(0xCA9_5EED);+ let mut previous = None;+ for frame in 0..300 {+ let raw = ((frame as f64 + (rng.next_f64() * 2.0 - 1.0) * jitter)+ * 1_000_000_000.0+ / actual)+ .max(0.0) as i64;+ let mapped = state.remap_ns(+ raw,+ raw + 25_000_000,+ (1_000_000_000.0 / nominal) as u64,+ false,+ );+ assert_eq!(mapped.master_ns, raw as u64);+ if let Some((previous_raw, previous_output)) = previous {+ assert!(raw >= previous_raw);+ assert_eq!(+ mapped.master_ns - previous_output,+ (raw - previous_raw) as u64+ );+ }+ previous = Some((raw, mapped.master_ns));+ }+ }+ }+ }+ }++ #[test]+ fn preserving_cadence_floors_backward_and_duplicate_inputs() {+ let mut state = SourceClockState::new("backward-video");+ for (raw, expected) in [+ (100_000_000, 100_000_000),+ (120_000_000, 120_000_000),+ (110_000_000, 120_000_000),+ (120_000_000, 120_000_000),+ (130_000_000, 130_000_000),+ ] {+ assert_eq!(+ state+ .remap_ns(raw, 200_000_000, 33_333_333, false)+ .master_ns,+ expected+ );+ }+ }++ #[test]+ fn preserving_cadence_retains_real_gaps() {+ let mut state = SourceClockState::new("gapped-video");+ for raw in [0, 30_000_000, 430_000_000, 460_000_000, 3_460_000_000] {+ let mapped = state.remap_ns(raw, raw + 30_000_000, 33_333_333, false);+ assert_eq!(mapped.master_ns, raw as u64);+ assert_ne!(mapped.outcome, SourceClockOutcome::HardReset);+ }+ }++ #[test]+ fn preserving_cadence_retains_initial_adjust_and_hard_reset_recovery() {+ let mut state = SourceClockState::new("reset-video");+ let first = state.remap_ns(-10_000_000_000, 0, 33_333_333, false);+ assert_eq!(first.outcome, SourceClockOutcome::InitialAdjust);+ assert_eq!(first.master_ns, 0);+ assert_eq!(+ state+ .remap_ns(-9_966_666_667, 33_333_333, 33_333_333, false)+ .master_ns,+ 33_333_333+ );+ let reset = state.remap_ns(-4_966_666_667, 66_666_666, 33_333_333, false);+ assert_eq!(reset.outcome, SourceClockOutcome::HardReset);+ assert_eq!(reset.master_ns, 66_666_666);+ assert_eq!(+ state+ .remap_ns(-4_933_333_334, 99_999_999, 33_333_333, false)+ .master_ns,+ 99_999_999+ );+ assert_eq!(state.hard_reset_count(), 1);+ }++ #[test]+ fn preserving_cadence_reset_releases_previous_epoch_floor() {+ let mut state = SourceClockState::new("new-epoch");+ assert_eq!(+ state+ .remap_ns(1_000_000_000, 1_000_000_000, 33_333_333, false)+ .master_ns,+ 1_000_000_000+ );+ state.reset();+ assert_eq!(+ state+ .remap_ns(10_000_000, 10_000_000, 33_333_333, false)+ .master_ns,+ 10_000_000+ );+ }++ #[test]+ fn preserving_cadence_public_method_keeps_source_delta() {+ let clock = clock();+ let mut state = SourceClockState::new("public-video");+ let first = state.remap_preserving_cadence(+ &clock,+ Timestamp::Instant(clock.start_instant() + Duration::from_millis(100)),+ 33_333_333,+ );+ let second = state.remap_preserving_cadence(+ &clock,+ Timestamp::Instant(clock.start_instant() + Duration::from_millis(147)),+ 33_333_333,+ );+ assert_eq!(second.master_ns - first.master_ns, 47_000_000);+ }}diff --git a/crates/timestamp/src/win.rs b/crates/timestamp/src/win.rsindex 8a111489b..c795e8fa9 100644--- a/crates/timestamp/src/win.rs+++ b/crates/timestamp/src/win.rs@@ -7,7 +7,7 @@ use std::{use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency};#[derive(Clone, Copy, Debug)]-pub struct PerformanceCounterTimestamp(i64);+pub struct PerformanceCounterTimestamp(i128);static PERF_FREQ: OnceLock<i64> = OnceLock::new();@@ -24,14 +24,18 @@ fn perf_freq() -> i64 {impl PerformanceCounterTimestamp {pub fn new(value: i64) -> Self {- Self(value)+ Self(i128::from(value))+ }++ pub fn from_100ns(value: i64) -> Self {+ Self(performance_counter_from_100ns(value, perf_freq()))}pub fn duration_since(&self, other: Self) -> Duration {let freq = perf_freq() as i128;debug_assert!(freq > 0);- let diff = self.0 as i128 - other.0 as i128;+ let diff = self.0 - other.0;if diff <= 0 {Duration::ZERO@@ -50,7 +54,7 @@ impl PerformanceCounterTimestamp {let freq = perf_freq() as i128;debug_assert!(freq > 0);- let diff = self.0 as i128 - other.0 as i128;+ let diff = self.0 - other.0;if diff < 0 {None@@ -67,29 +71,32 @@ impl PerformanceCounterTimestamp {pub fn signed_duration_since_secs(&self, other: Self) -> f64 {let freq = perf_freq() as f64;- let diff = self.0 as f64 - other.0 as f64;- diff / freq+ (self.0 - other.0) as f64 / freq}pub fn now() -> Self {let mut value = 0;unsafe { QueryPerformanceCounter(&mut value).unwrap() };- Self(value)+ Self::new(value)}pub fn from_cpal(instant: StreamInstant) -> Self {use cpal::host::wasapi::StreamInstantExt;- Self(instant.as_performance_counter())+ Self::from_100ns(instant.as_performance_counter())}}+fn performance_counter_from_100ns(timestamp: i64, frequency: i64) -> i128 {+ (i128::from(timestamp) * i128::from(frequency)) / 10_000_000+}+impl Add<Duration> for PerformanceCounterTimestamp {type Output = Self;fn add(self, rhs: Duration) -> Self::Output {let freq = perf_freq();- Self(self.0 + (rhs.as_secs_f64() * freq as f64) as i64)+ Self(self.0 + (rhs.as_secs_f64() * freq as f64) as i128)}}@@ -98,7 +105,7 @@ impl Sub<Duration> for PerformanceCounterTimestamp {fn sub(self, rhs: Duration) -> Self::Output {let freq = perf_freq();- Self(self.0 - (rhs.as_secs_f64() * freq as f64) as i64)+ Self(self.0 - (rhs.as_secs_f64() * freq as f64) as i128)}}@@ -123,4 +130,39 @@ mod tests {assert_eq!(later.duration_since(base), Duration::from_secs(1));}++ #[test]+ fn wasapi_timestamps_use_the_machine_counter_frequency() {+ for frequency in [3_000_000, 10_000_000, 24_000_000, 1_000_000_000] {+ assert_eq!(+ performance_counter_from_100ns(123_450_000, frequency),+ i128::from(frequency * 12 + frequency * 345 / 1_000)+ );+ }+ }++ #[test]+ fn invalid_device_epochs_preserve_packet_spacing_at_all_counter_frequencies() {+ assert_eq!(performance_counter_from_100ns(0, 24_000_000), 0);+ for frequency in [3_000_000, 10_000_000, 24_000_000, 5_000_000_000] {+ for epoch in [i64::MIN, -22_236_875_390_000_000, i64::MAX - 100_000] {+ let first = performance_counter_from_100ns(epoch, frequency);+ let next = performance_counter_from_100ns(epoch + 100_000, frequency);+ assert_eq!(next - first, i128::from(frequency / 100));+ }+ }+ }++ #[test]+ fn screen_audio_and_native_counter_timestamps_share_one_timebase() {+ let raw_counter = 12 * perf_freq();+ let native = PerformanceCounterTimestamp::new(raw_counter);+ let screen_or_audio = PerformanceCounterTimestamp::from_100ns(120_000_000);++ assert_eq!(screen_or_audio.signed_duration_since_secs(native), 0.0);+ assert_eq!(+ (screen_or_audio + Duration::from_millis(10)).duration_since(native),+ Duration::from_millis(10)+ );+ }}diff --git a/crates/utils/src/disk_space.rs b/crates/utils/src/disk_space.rsindex bcf29e554..a51f3227b 100644--- a/crates/utils/src/disk_space.rs+++ b/crates/utils/src/disk_space.rs@@ -15,7 +15,7 @@ pub struct RecordingStorage {impl RecordingStorage {pub fn finalization_bytes(self) -> u64 {- self.recording_bytes.saturating_mul(2)+ self.recording_bytes.saturating_mul(3)}pub fn status(self) -> DiskSpaceStatus {@@ -266,6 +266,7 @@ mod tests {available_bytes: u64::MAX,recording_bytes: u64::MAX,};+ assert_eq!(storage.finalization_bytes(), u64::MAX);assert_eq!(storage.status(), DiskSpaceStatus::Exhausted);assert!(!storage.can_finalize());}@@ -274,16 +275,22 @@ mod tests {fn recording_storage_reserves_space_for_finalization() {let recording_bytes = 1024 * 1024 * 1024;let mut storage = RecordingStorage {- available_bytes: recording_bytes * 2 + RECORDING_DISK_WARN_BYTES + 1,+ available_bytes: recording_bytes * 3 + RECORDING_DISK_WARN_BYTES + 1,recording_bytes,};assert_eq!(storage.status(), DiskSpaceStatus::Ok);storage.available_bytes -= 1;assert_eq!(storage.status(), DiskSpaceStatus::Low);- storage.available_bytes = recording_bytes * 2 + RECORDING_DISK_RESERVE_BYTES;+ storage.available_bytes = recording_bytes * 3 + RECORDING_DISK_RESERVE_BYTES;assert_eq!(storage.status(), DiskSpaceStatus::Exhausted);assert!(storage.can_finalize());- storage.available_bytes = recording_bytes * 2;+ storage.available_bytes = recording_bytes * 2 + RECORDING_DISK_RESERVE_BYTES;+ assert!(!storage.can_finalize());+ storage.available_bytes = recording_bytes * 3 + RECORDING_DISK_RESERVE_BYTES / 2;+ assert!(!storage.can_finalize());+ storage.available_bytes += 1;+ assert!(storage.can_finalize());+ storage.available_bytes = recording_bytes * 3;assert!(!storage.can_finalize());}@@ -349,7 +356,7 @@ mod tests {let mut storage = RecordingStorageMonitor::default().sample(directory.path()).unwrap();- storage.available_bytes = 2 * storage.recording_bytes + RECORDING_DISK_RESERVE_BYTES;+ storage.available_bytes = 3 * storage.recording_bytes + RECORDING_DISK_RESERVE_BYTES;assert_eq!(storage.recording_bytes, 1024 * 1024 * 1024);assert_eq!(storage.status(), DiskSpaceStatus::Exhausted);assert!(storage.can_finalize());diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rsindex 7b428feea..62f66283b 100644--- a/crates/utils/src/lib.rs+++ b/crates/utils/src/lib.rs@@ -12,6 +12,10 @@ use tracing::Instrument;pub mod disk_space;#[cfg(any(target_os = "linux", test))]pub mod linux_package;+#[cfg(target_os = "linux")]+pub mod linux_recording_stop;+#[cfg(any(target_os = "linux", test))]+pub mod linux_runtime;#[cfg(target_os = "macos")]pub mod macos_qos;diff --git a/crates/utils/src/linux_recording_stop.rs b/crates/utils/src/linux_recording_stop.rsnew file mode 100644index 000000000..73ea4507d--- /dev/null+++ b/crates/utils/src/linux_recording_stop.rs@@ -0,0 +1,488 @@+use std::{+ sync::{Arc, Mutex},+ time::Duration,+};++use tokio::task::JoinHandle;+use zbus::{Connection, Proxy, message::Header, proxy::CacheProperties, zvariant::ObjectPath};++const WATCHER: &str = "org.kde.StatusNotifierWatcher";+const WATCHER_PATH: &str = "/StatusNotifierWatcher";+const ITEM_PATH: &str = "/StatusNotifierItem";+const OPERATION_TIMEOUT: Duration = Duration::from_secs(2);+const HEALTH_INTERVAL: Duration = Duration::from_secs(1);++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StopTrayEvent {+ Activated { generation: u64 },+ Unavailable { generation: u64 },+}++#[derive(Debug)]+pub struct StopTrayOpenError {+ message: String,+ can_fallback: bool,+}++impl StopTrayOpenError {+ pub fn can_fallback(&self) -> bool {+ self.can_fallback+ }+}++impl std::fmt::Display for StopTrayOpenError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ self.message.fmt(formatter)+ }+}++impl std::error::Error for StopTrayOpenError {}++#[derive(Clone, Debug)]+pub struct StopTrayIcon {+ width: i32,+ height: i32,+ argb: Vec<u8>,+}++impl StopTrayIcon {+ pub fn from_rgba(width: u32, height: u32, rgba: &[u8]) -> Result<Self, String> {+ if width == 0 || width != height || width > 256 {+ return Err("The recording Stop icon must be square and at most 256 pixels".into());+ }+ let expected = width as usize * height as usize * 4;+ if rgba.len() != expected {+ return Err("The recording Stop icon has invalid pixel data".into());+ }+ let mut argb = Vec::with_capacity(expected);+ for pixel in rgba.chunks_exact(4) {+ argb.extend_from_slice(&[pixel[3], pixel[0], pixel[1], pixel[2]]);+ }+ Ok(Self {+ width: width as i32,+ height: height as i32,+ argb,+ })+ }+}++struct ActivationState {+ available: bool,+ activated_host: Option<String>,+}++struct StopItem {+ generation: u64,+ icon: StopTrayIcon,+ events: flume::Sender<StopTrayEvent>,+ state: Arc<Mutex<ActivationState>>,+}++impl StopItem {+ fn activate_for(&self, sender: Option<&str>) -> zbus::fdo::Result<()> {+ let sender = sender.ok_or_else(|| {+ zbus::fdo::Error::AccessDenied("The Stop activation has no bus sender".into())+ })?;+ let mut state = self+ .state+ .lock()+ .map_err(|_| zbus::fdo::Error::Failed("Recording Stop state is unavailable".into()))?;+ if !state.available {+ return Err(zbus::fdo::Error::Failed(+ "The recording Stop control is no longer available".into(),+ ));+ }+ if state+ .activated_host+ .as_deref()+ .is_some_and(|host| host != sender)+ {+ return Err(zbus::fdo::Error::AccessDenied(+ "The recording Stop activation came from a different tray host".into(),+ ));+ }+ state.activated_host = Some(sender.to_owned());+ match self.events.try_send(StopTrayEvent::Activated {+ generation: self.generation,+ }) {+ Ok(()) | Err(flume::TrySendError::Full(_)) => Ok(()),+ Err(flume::TrySendError::Disconnected(_)) => Err(zbus::fdo::Error::Failed(+ "The recording Stop listener has closed".into(),+ )),+ }+ }+}++#[zbus::interface(name = "org.kde.StatusNotifierItem")]+impl StopItem {+ fn activate(+ &self,+ _x: i32,+ _y: i32,+ #[zbus(header)] header: Header<'_>,+ ) -> zbus::fdo::Result<()> {+ self.activate_for(header.sender().map(|sender| sender.as_str()))+ }++ fn secondary_activate(+ &self,+ _x: i32,+ _y: i32,+ #[zbus(header)] header: Header<'_>,+ ) -> zbus::fdo::Result<()> {+ self.activate_for(header.sender().map(|sender| sender.as_str()))+ }++ fn context_menu(+ &self,+ _x: i32,+ _y: i32,+ #[zbus(header)] header: Header<'_>,+ ) -> zbus::fdo::Result<()> {+ self.activate_for(header.sender().map(|sender| sender.as_str()))+ }++ fn scroll(&self, _delta: i32, _orientation: &str) {}++ #[zbus(property)]+ fn category(&self) -> &str {+ "ApplicationStatus"+ }++ #[zbus(property)]+ fn id(&self) -> &str {+ "cap-recording-stop"+ }++ #[zbus(property)]+ fn title(&self) -> &str {+ "Stop Cap recording"+ }++ #[zbus(property)]+ fn status(&self) -> &str {+ "Active"+ }++ #[zbus(property)]+ fn window_id(&self) -> u32 {+ 0+ }++ #[zbus(property)]+ fn icon_name(&self) -> &str {+ ""+ }++ #[zbus(property)]+ fn icon_theme_path(&self) -> &str {+ ""+ }++ #[zbus(property)]+ fn icon_pixmap(&self) -> Vec<(i32, i32, Vec<u8>)> {+ vec![(self.icon.width, self.icon.height, self.icon.argb.clone())]+ }++ #[zbus(property)]+ fn overlay_icon_name(&self) -> &str {+ ""+ }++ #[zbus(property)]+ fn overlay_icon_pixmap(&self) -> Vec<(i32, i32, Vec<u8>)> {+ Vec::new()+ }++ #[zbus(property)]+ fn attention_icon_name(&self) -> &str {+ ""+ }++ #[zbus(property)]+ fn attention_icon_pixmap(&self) -> Vec<(i32, i32, Vec<u8>)> {+ Vec::new()+ }++ #[zbus(property)]+ fn attention_movie_name(&self) -> &str {+ ""+ }++ #[zbus(property)]+ fn item_is_menu(&self) -> bool {+ false+ }++ #[zbus(property)]+ fn menu(&self) -> ObjectPath<'_> {+ ObjectPath::from_static_str_unchecked("/")+ }+}++pub struct StopTray {+ connection: Option<Connection>,+ monitor: Option<JoinHandle<()>>,+ events: flume::Receiver<StopTrayEvent>,+}++impl StopTray {+ pub async fn open(generation: u64, icon: StopTrayIcon) -> Result<Self, StopTrayOpenError> {+ let (sender, receiver) = flume::bounded(8);+ let state = Arc::new(Mutex::new(ActivationState {+ available: true,+ activated_host: None,+ }));+ let item = StopItem {+ generation,+ icon,+ events: sender.clone(),+ state: state.clone(),+ };+ let builder = zbus::connection::Builder::session()+ .and_then(|builder| builder.serve_at(ITEM_PATH, item))+ .map_err(|error| StopTrayOpenError {+ message: format!("Could not prepare the recording Stop tray: {error}"),+ can_fallback: true,+ })?;+ let connection = tokio::time::timeout(OPERATION_TIMEOUT, builder.build())+ .await+ .map_err(|_| StopTrayOpenError {+ message: "Connecting the recording Stop tray timed out; cleanup is unconfirmed"+ .into(),+ can_fallback: false,+ })?+ .map_err(|error| StopTrayOpenError {+ message: format!("Could not connect the recording Stop tray: {error}"),+ can_fallback: false,+ })?;+ let setup = tokio::time::timeout(OPERATION_TIMEOUT, async {+ let watcher = watcher_proxy(&connection).await?;+ let bus = bus_proxy(&connection).await?;+ let owner: String = bus.call("GetNameOwner", &WATCHER).await?;+ if !watcher+ .get_property::<bool>("IsStatusNotifierHostRegistered")+ .await?+ {+ return Err(zbus::Error::Failure(+ "No system tray host is available for the recording Stop control".into(),+ ));+ }+ watcher+ .call::<_, _, ()>("RegisterStatusNotifierItem", &ITEM_PATH)+ .await?;+ Ok::<_, zbus::Error>((watcher, bus, owner))+ })+ .await;+ let (watcher, bus, owner) = match setup {+ Ok(Ok(setup)) => setup,+ failure => {+ let mut message = match failure {+ Ok(Err(error)) => {+ format!("Could not register the recording Stop control: {error}")+ }+ Err(_) => "Registering the recording Stop control timed out".into(),+ Ok(Ok(_)) => unreachable!(),+ };+ let can_fallback = match tokio::time::timeout(OPERATION_TIMEOUT, connection.close())+ .await+ {+ Ok(Ok(())) => true,+ Ok(Err(error)) => {+ message.push_str(&format!("; closing the Stop control failed: {error}"));+ false+ }+ Err(_) => {+ message.push_str("; closing the Stop control timed out");+ false+ }+ };+ return Err(StopTrayOpenError {+ message,+ can_fallback,+ });+ }+ };+ let monitor_connection = connection.clone();+ let monitor_receiver = receiver.clone();+ let monitor = tokio::spawn(async move {+ loop {+ tokio::select! {+ _ = monitor_connection.closed() => break,+ _ = tokio::time::sleep(HEALTH_INTERVAL) => {}+ }+ let host = match state.lock() {+ Ok(state) => state.activated_host.clone(),+ Err(_) => break,+ };+ let healthy = tokio::time::timeout(OPERATION_TIMEOUT, async {+ let current_owner: String = bus.call("GetNameOwner", &WATCHER).await?;+ if current_owner != owner+ || !watcher+ .get_property::<bool>("IsStatusNotifierHostRegistered")+ .await?+ {+ return Ok(false);+ }+ match host {+ Some(host) => bus.call::<_, _, bool>("NameHasOwner", &host).await,+ None => Ok(true),+ }+ })+ .await;+ if !matches!(healthy, Ok(Ok(true))) {+ break;+ }+ }+ report_unavailable(&state, &sender, &monitor_receiver, generation);+ });+ Ok(Self {+ connection: Some(connection),+ monitor: Some(monitor),+ events: receiver,+ })+ }++ pub fn events(&self) -> flume::Receiver<StopTrayEvent> {+ self.events.clone()+ }++ pub async fn close(mut self) -> Result<(), String> {+ let monitor_result = if let Some(monitor) = self.monitor.take() {+ monitor.abort();+ match monitor.await {+ Ok(()) => Ok(()),+ Err(error) if error.is_cancelled() => Ok(()),+ Err(error) => Err(format!("The recording Stop monitor failed: {error}")),+ }+ } else {+ Ok(())+ };+ if let Some(connection) = self.connection.take() {+ tokio::time::timeout(OPERATION_TIMEOUT, connection.close())+ .await+ .map_err(|_| "Closing the recording Stop control timed out".to_string())?+ .map_err(|error| format!("Could not close the recording Stop control: {error}"))?;+ }+ monitor_result+ }+}++impl Drop for StopTray {+ fn drop(&mut self) {+ if let Some(monitor) = self.monitor.take() {+ monitor.abort();+ }+ }+}++async fn watcher_proxy(connection: &Connection) -> zbus::Result<Proxy<'static>> {+ zbus::proxy::Builder::new(connection)+ .destination(WATCHER)?+ .path(WATCHER_PATH)?+ .interface(WATCHER)?+ .cache_properties(CacheProperties::No)+ .build()+ .await+}++async fn bus_proxy(connection: &Connection) -> zbus::Result<Proxy<'static>> {+ Proxy::new_owned(+ connection.clone(),+ "org.freedesktop.DBus",+ "/org/freedesktop/DBus",+ "org.freedesktop.DBus",+ )+ .await+}++fn report_unavailable(+ state: &Mutex<ActivationState>,+ sender: &flume::Sender<StopTrayEvent>,+ receiver: &flume::Receiver<StopTrayEvent>,+ generation: u64,+) {+ let mut state = state.lock().unwrap_or_else(|error| error.into_inner());+ state.available = false;+ while receiver.try_recv().is_ok() {}+ let _ = sender.try_send(StopTrayEvent::Unavailable { generation });+}++#[cfg(test)]+mod tests {+ use super::*;++ fn item() -> (StopItem, flume::Receiver<StopTrayEvent>) {+ let (events, receiver) = flume::bounded(8);+ (+ StopItem {+ generation: 42,+ icon: StopTrayIcon::from_rgba(1, 1, &[10, 20, 30, 255]).unwrap(),+ events,+ state: Arc::new(Mutex::new(ActivationState {+ available: true,+ activated_host: None,+ })),+ },+ receiver,+ )+ }++ #[test]+ fn stop_icon_uses_exact_network_argb_and_rejects_invalid_dimensions() {+ let icon = StopTrayIcon::from_rgba(1, 1, &[10, 20, 30, 40]).unwrap();+ assert_eq!(icon.argb, [40, 10, 20, 30]);+ for (width, height, data) in [+ (0, 0, &[][..]),+ (1, 2, &[0; 8]),+ (257, 257, &[]),+ (1, 1, &[0; 3]),+ ] {+ assert!(StopTrayIcon::from_rgba(width, height, data).is_err());+ }+ }++ #[test]+ fn stop_activation_is_bound_to_its_generation_and_first_host() {+ let (item, receiver) = item();+ assert!(item.activate_for(None).is_err());+ item.activate_for(Some(":1.42")).unwrap();+ assert_eq!(+ receiver.recv().unwrap(),+ StopTrayEvent::Activated { generation: 42 }+ );+ assert!(item.activate_for(Some(":1.43")).is_err());+ assert!(receiver.is_empty());+ item.activate_for(Some(":1.42")).unwrap();+ assert_eq!(+ receiver.recv().unwrap(),+ StopTrayEvent::Activated { generation: 42 }+ );+ }++ #[test]+ fn loss_invalidates_queued_activation_and_prevents_further_events() {+ let (item, receiver) = item();+ for _ in 0..16 {+ item.activate_for(Some(":1.42")).unwrap();+ }+ assert_eq!(receiver.len(), 8);+ report_unavailable(&item.state, &item.events, &receiver, item.generation);+ assert_eq!(+ receiver.recv().unwrap(),+ StopTrayEvent::Unavailable { generation: 42 }+ );+ assert!(item.activate_for(Some(":1.42")).is_err());+ assert!(receiver.is_empty());+ }++ #[test]+ fn stop_control_has_no_popup_menu_or_scroll_action() {+ let (item, receiver) = item();+ assert!(!item.item_is_menu());+ assert_eq!(item.menu().as_str(), "/");+ item.scroll(1, "vertical");+ assert!(receiver.is_empty());+ assert_eq!(item.icon_pixmap(), vec![(1, 1, vec![255, 10, 20, 30])]);+ }+}diff --git a/crates/utils/src/linux_runtime.rs b/crates/utils/src/linux_runtime.rsnew file mode 100644index 000000000..01e43b5f0--- /dev/null+++ b/crates/utils/src/linux_runtime.rs@@ -0,0 +1,55 @@+use std::num::NonZeroUsize;++pub fn llvmpipe_thread_count() -> Option<usize> {+ select_llvmpipe_thread_count(+ std::env::var_os("LP_NUM_THREADS").is_some(),+ std::thread::available_parallelism().ok(),+ )+}++fn select_llvmpipe_thread_count(+ override_present: bool,+ available_threads: Option<NonZeroUsize>,+) -> Option<usize> {+ if override_present {+ return None;+ }++ available_threads.map(|count| count.get().min(32))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn software_rendering_respects_available_cpu_capacity() {+ for count in [1, 2, 4, 8, 16, 32] {+ assert_eq!(+ select_llvmpipe_thread_count(false, NonZeroUsize::new(count)),+ Some(count)+ );+ }+ }++ #[test]+ fn software_rendering_preserves_explicit_thread_overrides() {+ assert_eq!(+ select_llvmpipe_thread_count(true, NonZeroUsize::new(4)),+ None+ );+ }++ #[test]+ fn software_rendering_does_not_exceed_mesas_default_thread_limit() {+ assert_eq!(+ select_llvmpipe_thread_count(false, NonZeroUsize::new(128)),+ Some(32)+ );+ }++ #[test]+ fn unknown_cpu_capacity_keeps_the_driver_default() {+ assert_eq!(select_llvmpipe_thread_count(false, None), None);+ }+}