Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: stabilize Studio recording and editor loading (#2278)

Richie McIlroy5786c3d6d64e
diff --git a/apps/desktop-gpui/src/controls_window.rs b/apps/desktop-gpui/src/controls_window.rs
index b5460fe54..6a5da71b3 100644
--- a/apps/desktop-gpui/src/controls_window.rs
+++ b/apps/desktop-gpui/src/controls_window.rs
@@ -105,7 +105,9 @@ impl ControlsWindow {
let theme = self.theme;
div()
.id(id)
- .size(px(32.))
+ .w(px(28.))
+ .h(px(32.))
+ .flex_shrink_0()
.flex()
.items_center()
.justify_center()
@@ -128,7 +130,6 @@ impl ControlsWindow {
let stopping = session.phase == Phase::Stopping;
let countdown = session.countdown_remaining();
let can_stop = (!starting && !stopping) || countdown.is_some();
- let error = session.error.clone();
let label: SharedString = if let Some(countdown) = countdown {
countdown.to_string().into()
} else if starting {
@@ -142,23 +143,25 @@ impl ControlsWindow {
"Pausing…"
}
.into()
- } else if error.is_some() {
- "Error".into()
} else if session.is_paused() {
"Paused".into()
+ } else if session.error.is_some() {
+ "Error".into()
} else {
Self::format_elapsed(session.elapsed()).into()
};
div()
.id("stop")
+ .min_w_0()
+ .flex_1()
.flex()
.flex_row()
.items_center()
.gap(px(4.))
.rounded(px(8.))
.py(px(4.))
- .px(px(8.))
+ .px(px(6.))
.text_color(theme.red_300)
.when(can_stop, |this| {
this.hover(|style| style.bg(Theme::with_alpha(theme.red_300, 0.08)))
@@ -168,17 +171,17 @@ impl ControlsWindow {
}))
})
.when(!can_stop, |this| this.opacity(0.6))
- .when_some(error, |this, error| {
- this.tooltip(move |_, cx| ui::Tooltip::new(&theme, error.clone()).view(cx))
- })
.child(
svg()
.path("icons/stop-circle.svg")
- .size(px(16.))
+ .size(px(20.))
+ .flex_shrink_0()
.text_color(theme.red_300),
)
.child(
div()
+ .min_w_0()
+ .truncate()
.text_size(px(14.))
.font_weight(gpui::FontWeight::MEDIUM)
.child(label),
@@ -215,7 +218,9 @@ impl ControlsWindow {
div()
.id("microphone")
- .size(px(32.))
+ .w(px(28.))
+ .h(px(32.))
+ .flex_shrink_0()
.relative()
.flex()
.items_center()
@@ -352,6 +357,7 @@ impl ControlsWindow {
div()
.h(px(40.))
+ .flex_shrink_0()
.w_full()
.flex()
.flex_row()
@@ -373,9 +379,11 @@ impl ControlsWindow {
div()
.flex()
.flex_1()
+ .min_w_0()
.flex_row()
.items_center()
.justify_between()
+ .gap(px(4.))
.p(px(4.))
.child(self.render_stop(cx))
.child(
@@ -383,7 +391,8 @@ impl ControlsWindow {
.flex()
.flex_row()
.items_center()
- .gap(px(4.))
+ .gap(px(2.))
+ .flex_shrink_0()
.child(self.render_microphone(cx))
.child(
self.action_button(
@@ -440,6 +449,8 @@ impl ControlsWindow {
.child(
div()
.id("drag")
+ .w(px(24.))
+ .flex_shrink_0()
.cursor_move()
.flex()
.items_center()
@@ -465,29 +476,67 @@ impl ControlsWindow {
impl Render for ControlsWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.theme.refresh(window, cx, false);
+ let session = self.session.read(cx);
+ let issue = session.error.clone().or_else(|| {
+ session
+ .storage_warning
+ .then(|| "Low storage. Cap will stop soon to save your recording.".to_owned())
+ });
div()
.size_full()
.flex()
.flex_col()
.justify_end()
- .px(px(12.))
- .pb(px(12.))
+ .p(px(12.))
.font_family("Geist")
// `body { font-weight: 500 }` (`ui-solid/src/main.css:189-192`).
.font_weight(FontWeight::MEDIUM)
- .when(self.session.read(cx).storage_warning, |this| {
+ .when_some(issue, |this, issue| {
this.child(
div()
+ .min_h_0()
+ .w_full()
+ .flex()
+ .items_start()
+ .gap(px(8.))
.mb(px(8.))
- .rounded(px(8.))
- .bg(self.theme.red_2)
+ .rounded(px(12.))
+ .border_1()
+ .border_color(Theme::with_alpha(self.theme.red_9, 0.4))
+ .bg(self.theme.gray_1)
.p(px(8.))
- .text_size(px(11.))
+ .text_size(px(12.))
.text_color(self.theme.red_11)
- .child("Low storage. Cap will stop soon to save your recording."),
+ .child(
+ svg()
+ .path("icons/triangle-alert.svg")
+ .size(px(20.))
+ .flex_shrink_0()
+ .text_color(self.theme.red_9),
+ )
+ .child(recording_issue_text(issue)),
)
})
.child(self.render_bar(cx))
}
}
+
+fn recording_issue_text(error: String) -> impl IntoElement + Styled {
+ div()
+ .id("recording-issue-text")
+ .min_w_0()
+ .min_h_0()
+ .flex_1()
+ .max_h(px(56.))
+ .overflow_x_scroll()
+ .overflow_y_scroll()
+ .child(if error.contains("Insufficient disk space")
+ && error.contains("Your recording is still paused")
+ {
+ "Not enough disk space to resume. Free up space and try again, or press Stop to save."
+ .to_owned()
+ } else {
+ error
+ })
+}
diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs
index a7e7ad9b2..4fc25acb1 100644
--- a/apps/desktop-gpui/src/editor_window.rs
+++ b/apps/desktop-gpui/src/editor_window.rs
@@ -59,11 +59,10 @@ use core_foundation::base::TCFType;
#[cfg(target_os = "macos")]
use core_video::pixel_buffer::{CVPixelBuffer, CVPixelBufferRef};
use gpui::{
- Animation, AnimationExt as _, AppContext as _, Bounds, Context, Entity, FocusHandle,
- FontWeight, Hsla, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent,
- MouseUpEvent, ParentElement, Pixels, Point, Render, RenderImage, SharedString,
- StatefulInteractiveElement as _, StyleRefinement, Styled, Subscription, WeakEntity, Window,
- div, point, prelude::FluentBuilder, px, svg,
+ AppContext as _, Bounds, Context, Entity, FocusHandle, FontWeight, Hsla, InteractiveElement,
+ IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels,
+ Point, Render, RenderImage, SharedString, StatefulInteractiveElement as _, StyleRefinement,
+ Styled, Subscription, WeakEntity, Window, div, point, prelude::FluentBuilder, px, svg,
};
use crate::{
@@ -75,6 +74,7 @@ use crate::{
};
mod frame;
+mod loading;
mod scenes;
// ---------------------------------------------------------------------------
@@ -740,16 +740,24 @@ impl Render for EditorSectionView {
// clips sidebar; the config sidebar is hidden, not destroyed
// (`Editor.tsx:728-747`).
EditorSection::Sidebar => {
- if !editor.project_ready() {
- return editor.render_preparing_sidebar().into_any_element();
+ if !editor.visual_ready() {
+ return editor.render_preparing_sidebar(!matches!(
+ editor.state,
+ LoadState::Failed(_)
+ ));
}
- if editor.clips.open {
+ let sidebar = if editor.clips.open {
editor.render_clips_sidebar(cx).into_any_element()
} else {
editor.with_style_controls(|editor| {
editor.render_sidebar(cx).into_any_element()
})
- }
+ };
+ loading::reveal(
+ "editor-sidebar-ready",
+ sidebar,
+ editor.render_preparing_sidebar(false),
+ )
}
EditorSection::Timeline => {
let viewport_width: f32 = window.viewport_size().width.into();
@@ -8661,12 +8669,8 @@ impl EditorWindow {
)
}
- fn render_preparing_sidebar(&self) -> impl IntoElement {
+ fn render_preparing_sidebar(&self, animated: bool) -> gpui::AnyElement {
let theme = self.theme;
- let project = self
- .preparing_seed
- .as_ref()
- .map_or(&self.project, |seed| &seed.project);
div()
.size_full()
.flex()
@@ -8704,33 +8708,8 @@ impl EditorWindow {
}),
),
)
- .child(
- div()
- .flex()
- .flex_col()
- .p(px(16.))
- .gap(px(16.))
- .text_size(px(12.))
- .child(
- div()
- .font_weight(FontWeight::MEDIUM)
- .text_color(Hsla::from(theme.editor.text_1))
- .child("Background"),
- )
- .child(
- div()
- .flex()
- .justify_between()
- .text_color(Hsla::from(theme.editor.text_3))
- .child("Aspect ratio")
- .child(Self::aspect_ratio_label(project.aspect_ratio.as_ref())),
- )
- .child(
- div()
- .text_color(Hsla::from(theme.editor.text_3))
- .child("Editing is available when your recording is ready."),
- ),
- )
+ .child(loading::sidebar(&theme, animated))
+ .into_any_element()
}
/// The player's top row: the stage's own triggers on the left, the
@@ -8888,24 +8867,14 @@ impl EditorWindow {
let theme = self.theme;
let body = match (&self.state, self.latest_frame.is_some()) {
(LoadState::Failed(message), _) => self.render_error_state(message).into_any_element(),
- (_, true) => self
- .preview
- .clone()
- .cached(StyleRefinement::default().size_full())
- .into_any_element(),
- (_, false) => div()
- .absolute()
- .inset_0()
- .flex()
- .items_center()
- .justify_center()
- .child(
- svg()
- .path("icons/video.svg")
- .size(px(48.))
- .text_color(Hsla::from(theme.editor.text_3)),
- )
- .into_any_element(),
+ (_, true) => loading::reveal(
+ "editor-preview-ready",
+ self.preview
+ .clone()
+ .cached(StyleRefinement::default().size_full()),
+ loading::preview(&theme, false),
+ ),
+ (_, false) => loading::preview(&theme, true),
};
div()
@@ -8915,17 +8884,6 @@ impl EditorWindow {
.overflow_hidden()
.bg(Hsla::from(theme.editor.card))
.child(body)
- .children(self.latest_frame.is_some().then(|| {
- div()
- .absolute()
- .inset_0()
- .bg(Hsla::from(theme.editor.card))
- .with_animation(
- "editor-preview-reveal",
- Animation::new(Duration::from_millis(300)),
- |veil, progress| veil.opacity(1. - progress),
- )
- }))
// `CanvasElementsOverlay` + `SnapGuidesOverlay`
// (`Player.tsx:636-643`), both mounted inside the letterbox
// wrapper and only while a frame exists.
@@ -9258,6 +9216,14 @@ impl EditorWindow {
) -> impl IntoElement {
let theme = self.theme;
if !self.project_ready() {
+ if self
+ .preparing_presentation
+ .as_ref()
+ .and_then(|presentation| presentation.progress.total_duration)
+ .is_none()
+ {
+ return loading::timeline(&theme, !matches!(self.state, LoadState::Failed(_)));
+ }
return div()
.size_full()
.child(timeline::render_preparing_timeline(
@@ -10541,29 +10507,20 @@ impl Render for EditorWindow {
}))
// The open `KSelect` menu, painted last of all so it is over the
// sidebar and the drag layers alike.
- .children((!matches!(self.state, LoadState::Failed(_))).then(|| {
- let veil = div()
- .absolute()
- .top(px(HEADER_HEIGHT))
- .bottom_0()
- .left_0()
- .right_0()
- .bg(Hsla::from(theme.editor.window).opacity(0.45));
- if self.visual_ready() {
- veil.with_animation(
- "editor-controls-reveal",
- Animation::new(Duration::from_millis(300)),
- |veil, progress| veil.opacity(1. - progress),
- )
- .into_any_element()
- } else {
- veil.occlude()
+ .children(
+ (!self.visual_ready() && !matches!(self.state, LoadState::Failed(_))).then(|| {
+ div()
+ .absolute()
+ .top(px(HEADER_HEIGHT))
+ .bottom_0()
+ .left_0()
+ .right_0()
+ .occlude()
.on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
.on_mouse_down(MouseButton::Right, |_, _, cx| cx.stop_propagation())
.on_scroll_wheel(|_, _, cx| cx.stop_propagation())
- .into_any_element()
- }
- }))
+ }),
+ )
.children(self.with_style_controls(|this| this.render_sidebar_menu(cx)))
.children(self.render_toolbar_menu(cx))
.children(self.render_frame_controls(window, cx))
diff --git a/apps/desktop-gpui/src/editor_window/loading.rs b/apps/desktop-gpui/src/editor_window/loading.rs
new file mode 100644
index 000000000..ec70ee0e4
--- /dev/null
+++ b/apps/desktop-gpui/src/editor_window/loading.rs
@@ -0,0 +1,164 @@
+use std::time::Duration;
+
+use gpui::{
+ Animation, AnimationExt, AnyElement, Div, Hsla, IntoElement, ParentElement, Styled, div, px,
+ relative,
+};
+
+use crate::theme::Theme;
+
+fn block(theme: &Theme, width: f32, height: f32) -> Div {
+ div()
+ .w(px(width))
+ .h(px(height))
+ .flex_none()
+ .rounded(px(5.))
+ .bg(Hsla::from(theme.editor.ctl_hover))
+}
+
+fn pulse(id: &'static str, content: Div, animated: bool) -> AnyElement {
+ if !animated {
+ return content.into_any_element();
+ }
+ content
+ .with_animation(
+ id,
+ Animation::new(Duration::from_millis(1800)).repeat(),
+ |element, progress| {
+ let opacity = 0.78 + 0.22 * (progress * std::f32::consts::TAU).cos();
+ element.opacity(opacity)
+ },
+ )
+ .into_any_element()
+}
+
+pub(super) fn preview(theme: &Theme, animated: bool) -> AnyElement {
+ div()
+ .absolute()
+ .inset_0()
+ .flex()
+ .items_center()
+ .justify_center()
+ .p(px(24.))
+ .bg(Hsla::from(theme.editor.card))
+ .child(pulse(
+ "editor-preview-skeleton",
+ div()
+ .w_full()
+ .h_full()
+ .rounded(px(12.))
+ .bg(Hsla::from(theme.editor.ctl))
+ .border_1()
+ .border_color(Hsla::from(theme.editor.line)),
+ animated,
+ ))
+ .into_any_element()
+}
+
+pub(super) fn sidebar(theme: &Theme, animated: bool) -> AnyElement {
+ pulse(
+ "editor-sidebar-skeleton",
+ div()
+ .flex()
+ .flex_col()
+ .p(px(16.))
+ .gap(px(20.))
+ .child(block(theme, 92., 12.))
+ .child(
+ div()
+ .flex()
+ .gap(px(6.))
+ .children((0..4).map(|_| block(theme, 64., 28.).flex_1().min_w_0())),
+ )
+ .child(
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(8.))
+ .children((0..2).map(|_| {
+ div()
+ .flex()
+ .gap(px(8.))
+ .children((0..4).map(|_| block(theme, 64., 48.).flex_1().min_w_0()))
+ })),
+ )
+ .child(div().h(px(1.)).w_full().bg(Hsla::from(theme.editor.line)))
+ .children([72., 88., 64.].into_iter().map(|width| {
+ div()
+ .flex()
+ .flex_col()
+ .gap(px(12.))
+ .child(
+ div()
+ .flex()
+ .justify_between()
+ .child(block(theme, width, 10.))
+ .child(block(theme, 36., 20.)),
+ )
+ .child(block(theme, 0., 5.).w_full())
+ })),
+ animated,
+ )
+}
+
+pub(super) fn timeline(theme: &Theme, animated: bool) -> AnyElement {
+ pulse(
+ "editor-timeline-skeleton",
+ div()
+ .size_full()
+ .flex()
+ .flex_col()
+ .p(px(12.))
+ .gap(px(12.))
+ .child(
+ div()
+ .h(px(24.))
+ .flex()
+ .items_center()
+ .justify_between()
+ .children((0..8).map(|_| block(theme, 28., 8.))),
+ )
+ .children([1., 0.72].into_iter().map(|width| {
+ div()
+ .flex()
+ .items_center()
+ .gap(px(16.))
+ .child(block(theme, 24., 24.))
+ .child(
+ div()
+ .flex_1()
+ .child(block(theme, 0., 28.).w(relative(width))),
+ )
+ })),
+ animated,
+ )
+}
+
+pub(super) fn reveal(
+ id: &'static str,
+ content: impl IntoElement,
+ placeholder: impl IntoElement,
+) -> AnyElement {
+ div()
+ .relative()
+ .size_full()
+ .child(content)
+ .child(
+ div()
+ .absolute()
+ .inset_0()
+ .child(placeholder)
+ .with_animation(
+ id,
+ Animation::new(Duration::from_millis(180)),
+ |element, progress| {
+ if progress >= 1. {
+ div()
+ } else {
+ element.opacity((1. - progress).powi(3))
+ }
+ },
+ ),
+ )
+ .into_any_element()
+}
diff --git a/apps/desktop/src/app.tsx b/apps/desktop/src/app.tsx
index 44ed6b972..2a0af6b25 100644
--- a/apps/desktop/src/app.tsx
+++ b/apps/desktop/src/app.tsx
@@ -35,6 +35,9 @@ const NewMainPage = lazy(() => import("./routes/(window-chrome)/new-main"));
const SettingsGeneralPage = lazy(
() => import("./routes/(window-chrome)/settings/general"),
);
+const SettingsQualityPage = lazy(
+ () => import("./routes/(window-chrome)/settings/quality"),
+);
const SettingsRecordingsPage = lazy(
() => import("./routes/(window-chrome)/settings/recordings"),
);
@@ -198,6 +201,7 @@ function Inner() {
<Route path="/settings" component={SettingsLayout}>
<Route path="/" component={SettingsGeneralPage} />
<Route path="/general" component={SettingsGeneralPage} />
+ <Route path="/quality" component={SettingsQualityPage} />
<Route path="/recordings" component={SettingsRecordingsPage} />
<Route
path="/transcription"
diff --git a/apps/desktop/src/routes/(window-chrome)/settings.tsx b/apps/desktop/src/routes/(window-chrome)/settings.tsx
index b7c592ade..7e32e8b59 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings.tsx
@@ -30,6 +30,7 @@ import {
getConfiguredServerUrl,
protectedHeaders,
} from "~/utils/web-api";
+import IconLucideSlidersHorizontal from "~icons/lucide/sliders-horizontal";
import IconLucideTerminal from "~icons/lucide/terminal";
import IconLucideUserRound from "~icons/lucide/user-round";
import IconLucideZap from "~icons/lucide/zap";
@@ -203,7 +204,7 @@ export default function Settings(props: RouteSectionProps) {
{
href: "quality",
name: "Recording quality",
- icon: IconCapFilmCut,
+ icon: IconLucideSlidersHorizontal,
},
{
href: "hotkeys",
diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsx
index 47de69bdb..89c54e890 100644
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@ -1,3 +1,5 @@
+import "@radix-ui/colors/amber.css";
+import "@radix-ui/colors/amber-dark.css";
import { createTimer } from "@solid-primitives/timer";
import { createMutation } from "@tanstack/solid-query";
import { LogicalPosition } from "@tauri-apps/api/dpi";
@@ -208,11 +210,13 @@ function InProgressRecordingInner() {
if (failure) issues.push(failure);
const controlError = pauseError();
if (controlError) issues.push(controlError);
+ const degraded = degradedReason();
+ if (degraded) issues.push(degraded);
const nativeError = cleanCapture.data?.error;
if (nativeError) issues.push(nativeError);
const localError = stopError();
if (localError) issues.push(localError);
- return [...new Set(issues)];
+ return [...new Set(issues.map(recordingIssueMessage))];
});
const hasRecordingIssue = () => issueMessages().length > 0;
@@ -477,13 +481,19 @@ function InProgressRecordingInner() {
console.error("Failed to sync recording controls hit area", error);
})
.finally(() => {
- if (pendingInteractiveBoundsKey === key)
+ if (pendingInteractiveBoundsKey === key) {
pendingInteractiveBoundsKey = "";
+ if (lastInteractiveBoundsKey === key) syncInteractiveAreaBounds();
+ }
});
};
createEffect(() => {
- interactiveAreaRef();
+ const area = interactiveAreaRef();
+ if (!area) return;
+ const observer = new ResizeObserver(syncInteractiveAreaBounds);
+ observer.observe(area);
+ onCleanup(() => observer.disconnect());
queueMicrotask(syncInteractiveAreaBounds);
});
@@ -579,7 +589,9 @@ function InProgressRecordingInner() {
(state().variant === "recording" || state().variant === "paused")
) {
setPauseError(
- `Could not ${request.resume ? "resume" : "pause"} recording: ${String(error)}`,
+ String(error).startsWith("Could not ")
+ ? String(error)
+ : `Could not ${request.resume ? "resume" : "pause"} recording: ${String(error)}`,
);
}
throw error;
@@ -874,15 +886,18 @@ function InProgressRecordingInner() {
};
return (
- <div class="flex h-full w-full flex-col justify-end px-3 pb-3">
- <div ref={setInteractiveAreaRef} class="flex w-full flex-col gap-2">
+ <div class="flex h-full w-full flex-col justify-end p-3">
+ <div
+ ref={setInteractiveAreaRef}
+ class="flex max-h-full w-full min-h-0 flex-col gap-2"
+ >
<Show when={hasRecordingIssue() && issuePanelVisible()}>
- <div class="flex w-full shrink-0 flex-row items-start gap-3 rounded-2xl border border-red-8 bg-gray-1 px-3 py-2 text-[12px] leading-snug text-red-11 shadow-lg">
+ <div class="flex min-h-0 w-full flex-row items-start gap-2 rounded-xl border border-red-8 bg-gray-1 p-2 text-xs leading-snug text-red-11 shadow-lg">
<IconLucideAlertTriangle class="mt-0.5 size-5 shrink-0 text-red-9" />
<div
role="alert"
tabIndex={0}
- class="max-h-16 min-w-0 flex-1 space-y-1 overflow-auto whitespace-pre-wrap break-words"
+ class="max-h-14 min-w-0 flex-1 space-y-1 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere]"
>
{issueMessages().map((message) => (
<p>{message}</p>
@@ -899,27 +914,36 @@ function InProgressRecordingInner() {
</div>
</Show>
<div class="h-10 w-full flex-none rounded-2xl">
- <div class="flex h-full w-full flex-row items-stretch overflow-hidden rounded-2xl bg-gray-1 border border-gray-5 shadow-[0_1px_3px_rgba(0,0,0,0.1)]">
- <div class="flex flex-1 flex-col gap-2 p-1">
- <div class="flex flex-1 flex-row justify-between">
+ <div
+ class="flex h-full w-full flex-row items-stretch overflow-hidden rounded-2xl bg-gray-1 border shadow-[0_1px_3px_rgba(0,0,0,0.1)]"
+ style={{
+ "border-color":
+ state().variant === "paused"
+ ? "var(--amber-6)"
+ : "var(--gray-5)",
+ }}
+ >
+ <div class="flex min-w-0 flex-1 flex-col p-1">
+ <div class="flex min-w-0 flex-1 flex-row items-center justify-between gap-1">
<Show
when={!isInitializing()}
fallback={
<div class="flex flex-row items-center gap-1.5 rounded-lg py-1 px-2 text-gray-12">
<IconLucideLoader2 class="size-4 animate-spin" />
- <span class="text-[0.875rem] font-medium tabular-nums">
+ <span class="truncate text-sm font-medium tabular-nums">
Starting
</span>
</div>
}
>
<RecordingControlButton
+ flexible
disabled={
stopRequested() ||
stopRecording.isPending ||
isCountdown()
}
- class="flex flex-row items-center gap-1 rounded-lg py-1 px-2 text-red-300 transition-colors duration-100 hover:bg-red-500/8 active:bg-red-500/12 disabled:opacity-60 disabled:hover:bg-transparent"
+ class="flex min-w-0 flex-1 flex-row items-center gap-1 rounded-lg py-1 px-1.5 text-red-300 transition-colors duration-100 hover:bg-red-500/8 active:bg-red-500/12 disabled:opacity-60 disabled:hover:bg-transparent"
type="button"
onPointerDown={(event) => {
if (event.button !== 0) return;
@@ -931,8 +955,8 @@ function InProgressRecordingInner() {
title="Stop recording"
aria-label="Stop recording"
>
- <IconCapStopCircle />
- <span class="text-[0.875rem] font-medium tabular-nums">
+ <IconCapStopCircle class="size-5 shrink-0" />
+ <span class="truncate text-sm font-medium tabular-nums">
<Show
when={!isCountdown()}
fallback={
@@ -1004,18 +1028,18 @@ function InProgressRecordingInner() {
</RecordingControlButton>
</Show>
- <div class="flex items-center gap-1">
+ <div class="flex shrink-0 items-center">
<Show
when={canToggleMicMute()}
fallback={
<RecordingControlTooltip content={microphoneTitle()}>
<div
aria-label={microphoneTitle()}
- class="relative flex h-8 w-8 items-center justify-center"
+ class="relative flex h-8 w-7 shrink-0 items-center justify-center"
>
{optionsQuery.rawOptions.micName != null ? (
disconnectedInputs.microphone ? (
- <IconLucideMicOff class="size-5 text-amber-11" />
+ <IconLucideMicOff class="size-5 text-[var(--amber-11)]" />
) : (
<>
<IconCapMicrophone class="size-5 text-gray-12" />
@@ -1043,7 +1067,7 @@ function InProgressRecordingInner() {
>
<RecordingControlButton
type="button"
- class="relative flex h-8 w-8 items-center justify-center rounded-lg transition-colors duration-100 hover:bg-gray-12/6 active:bg-gray-12/10 disabled:opacity-50 disabled:hover:bg-transparent dark:hover:bg-white/8 dark:active:bg-white/12"
+ class="relative flex h-8 w-7 shrink-0 items-center justify-center rounded-lg transition-colors duration-100 hover:bg-gray-12/6 active:bg-gray-12/10 disabled:opacity-50 disabled:hover:bg-transparent dark:hover:bg-white/8 dark:active:bg-white/12"
disabled={toggleMicMute.isPending}
onClick={() => toggleMicMute.mutate()}
title={
@@ -1073,32 +1097,6 @@ function InProgressRecordingInner() {
)}
</RecordingControlButton>
</Show>
- <Show when={hasCameraInput() && disconnectedInputs.camera}>
- <RecordingControlTooltip
- content={
- "Camera disconnected - recording continues without camera overlay"
- }
- >
- <div
- aria-label="Camera disconnected - recording continues without camera overlay"
- class="flex h-8 w-8 items-center justify-center"
- >
- <IconLucideVideoOff class="size-5 text-amber-11" />
- </div>
- </RecordingControlTooltip>
- </Show>
- <Show when={degradedReason()}>
- {(reason) => (
- <RecordingControlTooltip content={reason()}>
- <div
- class="flex h-8 w-8 items-center justify-center"
- aria-label={`Recording quality degraded: ${reason()}`}
- >
- <div class="size-2 rounded-full bg-amber-9 animate-pulse" />
- </div>
- </RecordingControlTooltip>
- )}
- </Show>
<Show
when={!isInitializing()}
fallback={
@@ -1143,7 +1141,7 @@ function InProgressRecordingInner() {
class={cx(
"active:scale-90 motion-reduce:transform-none",
state().variant === "paused" &&
- "bg-amber-3 text-amber-11 ring-1 ring-amber-6",
+ "bg-[var(--amber-3)] text-[var(--amber-11)] ring-1 ring-[var(--amber-6)]",
)}
title={
state().variant === "paused"
@@ -1204,10 +1202,11 @@ function InProgressRecordingInner() {
</div>
</div>
<div
- class="non-styled-move flex cursor-move items-center justify-center border-l border-gray-5 p-1 hover:cursor-move transition-colors duration-100 hover:bg-gray-12/4 dark:hover:bg-white/6"
+ aria-label="Move recording controls"
+ class="non-styled-move flex w-6 shrink-0 cursor-move items-center justify-center border-l border-gray-5 p-1 hover:cursor-move transition-colors duration-100 hover:bg-gray-12/4 dark:hover:bg-white/6"
data-tauri-drag-region
>
- <IconCapMoreVertical class="pointer-events-none text-gray-10" />
+ <IconCapMoreVertical class="pointer-events-none size-4 text-gray-10" />
</div>
</div>
</div>
@@ -1216,9 +1215,20 @@ function InProgressRecordingInner() {
);
}
+function recordingIssueMessage(message: string): string {
+ if (
+ message.includes("Insufficient disk space") &&
+ message.includes("Your recording is still paused")
+ ) {
+ return "Not enough disk space to resume. Free up space and try again, or press Stop to save.";
+ }
+ return message;
+}
+
function RecordingControlTooltip(props: {
content: string | undefined;
children: JSX.Element;
+ flexible?: boolean;
}) {
const [open, setOpen] = createSignal(false);
const boundsPrefix = `recording-control-tooltip-${createUniqueId()}`;
@@ -1284,7 +1294,10 @@ function RecordingControlTooltip(props: {
{props.content}
</span>
}
- childClass="flex h-full items-center"
+ childClass={cx(
+ "flex h-full min-w-0 items-center",
+ props.flexible ? "flex-1" : "shrink-0",
+ )}
placement="top"
gutter={6}
flip={false}
@@ -1294,7 +1307,7 @@ function RecordingControlTooltip(props: {
onOpenChange={setOpen}
>
<span
- class="flex h-full items-center"
+ class="flex h-full min-w-0 w-full items-center"
onFocusIn={() => setOpen(true)}
onFocusOut={(event) => {
if (
@@ -1312,13 +1325,18 @@ function RecordingControlTooltip(props: {
);
}
-function RecordingControlButton(props: ComponentProps<"button">) {
- const [local, buttonProps] = splitProps(props, ["title"]);
+function RecordingControlButton(
+ props: ComponentProps<"button"> & { flexible?: boolean },
+) {
+ const [local, buttonProps] = splitProps(props, ["title", "flexible"]);
return (
- <RecordingControlTooltip content={local.title}>
+ <RecordingControlTooltip content={local.title} flexible={local.flexible}>
<button
{...buttonProps}
- class={cx(props.class, "disabled:pointer-events-none")}
+ class={cx(
+ props.class,
+ "outline-none focus-visible:ring-2 focus-visible:ring-blue-9 disabled:pointer-events-none",
+ )}
/>
</RecordingControlTooltip>
);
@@ -1333,7 +1351,7 @@ function ActionButton(props: ComponentProps<"button">) {
"text-gray-11 hover:text-gray-12",
"hover:bg-gray-12/6 dark:hover:bg-white/8",
"active:bg-gray-12/10 dark:active:bg-white/12",
- "h-8 w-8 flex items-center justify-center",
+ "h-8 w-7 shrink-0 flex items-center justify-center",
"disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-transparent",
props.class,
)}
diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs
index 3b9248e6d..054df3d2e 100644
--- a/crates/recording/src/instant_recording.rs
+++ b/crates/recording/src/instant_recording.rs
@@ -1100,7 +1100,7 @@ async fn spawn_instant_recording_actor_inner(
#[cfg(windows)]
{
let scope = output_pipeline::PipelineBuildScope::new();
- output_pipeline::finish_windows_pipeline_startup(&scope, startup).await
+ output_pipeline::finish_pipeline_startup(&scope, startup).await
}
#[cfg(not(windows))]
startup.await
diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rs
index 34523cd5b..a0bd989b6 100644
--- a/crates/recording/src/output_pipeline/core.rs
+++ b/crates/recording/src/output_pipeline/core.rs
@@ -1819,13 +1819,13 @@ pub(crate) struct PipelineBuildScope(Arc<PipelineBuildScopeInner>);
type CaptureCompletion = Shared<BoxFuture<'static, Result<(), String>>>;
struct ScopeError {
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
message: String,
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
uncertain: bool,
}
-#[cfg(any(test, target_os = "linux", windows))]
+#[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
#[derive(Debug)]
pub(crate) struct PipelineJoinReport {
pub quiescent: bool,
@@ -1835,9 +1835,10 @@ pub(crate) struct PipelineJoinReport {
struct PipelineBuildScopeInner {
parent: Option<PipelineBuildScope>,
strict_lifetime: bool,
+ wait_for_video_start: bool,
#[cfg(target_os = "linux")]
required_source_health: bool,
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
drain: tokio::sync::Mutex<()>,
cancelled: CancellationToken,
committed: AtomicBool,
@@ -1879,6 +1880,11 @@ impl PipelineBuildScope {
Self::with_lifetime(false)
}
+ #[cfg(target_os = "macos")]
+ pub(crate) fn new_macos_segment() -> Self {
+ Self::with_lifetime_policy(false, false, false)
+ }
+
#[cfg(any(test, target_os = "linux"))]
pub(crate) fn new_lifetime() -> Self {
Self::with_lifetime(true)
@@ -1886,19 +1892,24 @@ impl PipelineBuildScope {
#[cfg(any(test, target_os = "linux", windows))]
fn with_lifetime(strict_lifetime: bool) -> Self {
- Self::with_lifetime_policy(strict_lifetime, false)
+ Self::with_lifetime_policy(strict_lifetime, false, true)
}
#[cfg(target_os = "linux")]
pub(crate) fn new_studio_lifetime() -> Self {
- Self::with_lifetime_policy(true, true)
+ Self::with_lifetime_policy(true, true, true)
}
- #[cfg(any(test, target_os = "linux", windows))]
- fn with_lifetime_policy(strict_lifetime: bool, _required_source_health: bool) -> Self {
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
+ fn with_lifetime_policy(
+ strict_lifetime: bool,
+ _required_source_health: bool,
+ wait_for_video_start: bool,
+ ) -> Self {
Self(Arc::new(PipelineBuildScopeInner {
parent: None,
strict_lifetime,
+ wait_for_video_start,
#[cfg(target_os = "linux")]
required_source_health: _required_source_health,
drain: tokio::sync::Mutex::new(()),
@@ -1915,6 +1926,7 @@ impl PipelineBuildScope {
Self(Arc::new(PipelineBuildScopeInner {
parent: Some(self.clone()),
strict_lifetime: self.requires_joined_stop(),
+ wait_for_video_start: self.0.wait_for_video_start,
required_source_health: self.0.required_source_health,
drain: tokio::sync::Mutex::new(()),
cancelled: self.cancellation().child_token(),
@@ -2008,7 +2020,7 @@ impl PipelineBuildScope {
});
}
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
pub(crate) async fn cancel_and_join_report(&self) -> PipelineJoinReport {
self.cancel();
let _drain = self.0.drain.lock().await;
@@ -2050,7 +2062,7 @@ impl PipelineBuildScope {
self.0.strict_lifetime
}
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
pub(crate) fn commit(&self) -> bool {
let mut tokens = self.0.tokens.lock().unwrap();
if self.0.cancelled.is_cancelled() {
@@ -2072,9 +2084,9 @@ impl PipelineBuildScope {
}
if !self.0.committed.load(Ordering::Acquire) {
self.0.cleanup_errors.lock().unwrap().push(ScopeError {
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
message: error,
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
uncertain: true,
});
}
@@ -2123,9 +2135,9 @@ impl PipelineBuildScope {
}
if !self.is_committed() {
self.0.cleanup_errors.lock().unwrap().push(ScopeError {
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
message: error,
- #[cfg(any(test, target_os = "linux", windows))]
+ #[cfg(any(test, target_os = "linux", target_os = "macos", windows))]
uncertain: !self.requires_joined_stop(),
});
}
@@ -2246,14 +2258,14 @@ impl TaskPool {
}
}
-#[cfg(any(windows, test))]
-struct WindowsStartupGuard {
+#[cfg(any(windows, target_os = "macos", test))]
+struct PipelineStartupGuard {
scope: PipelineBuildScope,
armed: bool,
}
-#[cfg(any(windows, test))]
-impl Drop for WindowsStartupGuard {
+#[cfg(any(windows, target_os = "macos", test))]
+impl Drop for PipelineStartupGuard {
fn drop(&mut self) {
if self.armed {
self.scope.cancel();
@@ -2262,7 +2274,7 @@ impl Drop for WindowsStartupGuard {
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");
+ error!(%error, "Dropped capture startup cleanup failed");
}
});
}
@@ -2270,12 +2282,17 @@ impl Drop for WindowsStartupGuard {
}
}
-#[cfg(any(windows, test))]
-pub(crate) async fn finish_windows_pipeline_startup<T>(
+#[cfg(any(windows, target_os = "macos", test))]
+#[derive(Debug, thiserror::Error)]
+#[error("Capture startup cleanup is unconfirmed: {0}")]
+pub(crate) struct PipelineStartupCleanupUnconfirmed(String);
+
+#[cfg(any(windows, target_os = "macos", test))]
+pub(crate) async fn finish_pipeline_startup<T>(
scope: &PipelineBuildScope,
startup: impl Future<Output = anyhow::Result<T>>,
) -> anyhow::Result<T> {
- let mut guard = WindowsStartupGuard {
+ let mut guard = PipelineStartupGuard {
scope: scope.clone(),
armed: true,
};
@@ -2294,15 +2311,14 @@ pub(crate) async fn finish_windows_pipeline_startup<T>(
Err(error) => error,
Ok(output) => {
drop(output);
- anyhow!("Windows capture startup was cancelled")
+ anyhow!("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()
+ (false, cleanup) => Err(error.context(PipelineStartupCleanupUnconfirmed(
+ cleanup.unwrap_or_default(),
))),
(true, Some(cleanup)) => {
Err(error.context(format!("Capture startup cleanup: {cleanup}")))
@@ -2321,11 +2337,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {
#[cfg(windows)]
if PipelineBuildScope::current().is_none() {
let scope = PipelineBuildScope::new();
- return finish_windows_pipeline_startup(
- &scope,
- self.build_inner::<TMuxer>(muxer_config),
- )
- .await;
+ return finish_pipeline_startup(&scope, self.build_inner::<TMuxer>(muxer_config)).await;
}
self.build_inner::<TMuxer>(muxer_config).await
}
@@ -2823,12 +2835,13 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V
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)
- };
+ let (start_tx, started) =
+ if PipelineBuildScope::current().is_some_and(|scope| scope.0.wait_for_video_start) {
+ 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();
@@ -8487,6 +8500,8 @@ mod build_scope_tests {
MuxerSetup,
MuxerPending,
VideoStart,
+ #[cfg(target_os = "macos")]
+ VideoStartPending,
#[cfg(windows)]
VideoStop,
None,
@@ -8567,6 +8582,10 @@ mod build_scope_tests {
if self.probe.stage == FailureStage::VideoStart {
anyhow::bail!("video start fault");
}
+ #[cfg(target_os = "macos")]
+ if self.probe.stage == FailureStage::VideoStartPending {
+ self.probe.setup_pending.notified().await;
+ }
Ok(())
}
.boxed()
@@ -8683,7 +8702,7 @@ mod build_scope_tests {
let observed = exited.clone();
let result = tokio::time::timeout(
Duration::from_secs(2),
- finish_windows_pipeline_startup(&scope, async move {
+ finish_pipeline_startup(&scope, async move {
let build = BuildCtx::new();
let mut setup = SetupCtx::new(
build.health_tx.clone(),
@@ -8727,7 +8746,7 @@ mod build_scope_tests {
let scope = PipelineBuildScope::new();
let probe = Probe::new(FailureStage::VideoStop, &scope);
let directory = tempfile::tempdir().unwrap();
- let pipeline = finish_windows_pipeline_startup(
+ let pipeline = finish_pipeline_startup(
&scope,
OutputPipeline::builder(directory.path().join("stop-fault.mp4"))
.with_video::<Video>(probe.clone())
@@ -8756,7 +8775,7 @@ mod build_scope_tests {
let directory = tempfile::tempdir().unwrap();
let result = tokio::time::timeout(
Duration::from_secs(3),
- finish_windows_pipeline_startup(
+ finish_pipeline_startup(
&scope,
OutputPipeline::builder(directory.path().join("unused.mp4"))
.with_video::<Video>(probe.clone())
@@ -8783,7 +8802,7 @@ mod build_scope_tests {
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 result = finish_pipeline_startup(&scope, async {
let _screen = OutputPipeline::builder(directory.path().join("screen.mp4"))
.with_video::<Video>(screen.clone())
.build::<Encoder>(screen.clone())
@@ -8817,7 +8836,7 @@ mod build_scope_tests {
let ready = entered.clone();
let owned = scope.clone();
let task = tokio::spawn(async move {
- finish_windows_pipeline_startup(&owned, async {
+ finish_pipeline_startup(&owned, async {
ready.notify_one();
std::future::pending::<anyhow::Result<()>>().await
})
@@ -8835,7 +8854,7 @@ mod build_scope_tests {
let scope = PipelineBuildScope::new();
let probe = Probe::new(FailureStage::None, &scope);
let directory = tempfile::tempdir().unwrap();
- let pipeline = finish_windows_pipeline_startup(
+ let pipeline = finish_pipeline_startup(
&scope,
OutputPipeline::builder(directory.path().join("unused.mp4"))
.with_video::<Video>(probe.clone())
@@ -8850,6 +8869,33 @@ mod build_scope_tests {
assert_eq!(probe.stopped.load(Ordering::Acquire), 1);
}
+ #[cfg(target_os = "macos")]
+ #[tokio::test]
+ async fn macos_segment_startup_keeps_video_start_concurrent() {
+ let scope = PipelineBuildScope::new_macos_segment();
+ let probe = Probe::new(FailureStage::VideoStartPending, &scope);
+ let directory = tempfile::tempdir().unwrap();
+ let pipeline = tokio::time::timeout(
+ Duration::from_secs(2),
+ finish_pipeline_startup(
+ &scope,
+ OutputPipeline::builder(directory.path().join("screen.mp4"))
+ .with_video::<Video>(probe.clone())
+ .build::<Encoder>(probe.clone()),
+ ),
+ )
+ .await
+ .expect("camera and microphone setup must not wait for screen startup")
+ .unwrap();
+ assert!(scope.is_committed());
+ probe.setup_pending.notify_one();
+ tokio::task::yield_now().await;
+ 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();
@@ -8857,7 +8903,7 @@ mod build_scope_tests {
let (entered, ready) = oneshot::channel();
let scoped = scope.clone();
let task = tokio::spawn(async move {
- finish_windows_pipeline_startup(&scoped, async {
+ finish_pipeline_startup(&scoped, async {
let completion = PipelineBuildScope::current().unwrap().task_completion();
tokio::spawn(async move {
let _completion = completion;
@@ -8883,7 +8929,7 @@ mod build_scope_tests {
let scope = PipelineBuildScope::new();
let token = CancellationToken::new();
scope.register_token(token.clone());
- let result = finish_windows_pipeline_startup(&scope, async {
+ let result = finish_pipeline_startup(&scope, async {
token.cancel();
Ok(())
})
@@ -8897,7 +8943,7 @@ mod build_scope_tests {
let scope = PipelineBuildScope::new();
scope.cancel();
assert!(
- finish_windows_pipeline_startup(&scope, async { Ok(()) })
+ finish_pipeline_startup(&scope, async { Ok(()) })
.await
.is_err()
);
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index a8e881e16..898d1070f 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -1024,12 +1024,15 @@ impl Message<Resume> for Actor {
if !self.all_tracks_stopped {
bail!(UNCONFIRMED_CAPTURE_CLEANUP);
}
- self.state = match self.state.take() {
+ match self.state.as_ref() {
Some(ActorState::Paused {
next_index,
cursors,
next_cursor_id,
}) => {
+ let next_index = *next_index;
+ let next_cursor_id = *next_cursor_id;
+ let cursors = cursors.clone();
if let Some(diagnostic) = &mut self.diagnostic {
diagnostic.stage("resuming");
}
@@ -1037,24 +1040,43 @@ impl Message<Resume> for Actor {
.segment_factory
.create_next(cursors, next_cursor_id)
.await;
- #[cfg(windows)]
- let pipeline = pipeline.map_err(|error| self.preserve_windows_stop_failure(error));
- let pipeline = pipeline?;
+ let pipeline = match pipeline {
+ Ok(pipeline) => pipeline,
+ Err(error) => {
+ if error.downcast_ref::<crate::output_pipeline::PipelineStartupCleanupUnconfirmed>().is_some() {
+ self.all_tracks_stopped = false;
+ self.state = None;
+ if let Some(diagnostic) = &mut self.diagnostic {
+ diagnostic.stage("resume_cleanup_failed");
+ }
+ return Err(self.preserve_terminal_stop_failure(error, false));
+ }
+ warn!(error = %format!("{error:#}"), "Studio resume failed; retaining paused recording");
+ if let Some(diagnostic) = &mut self.diagnostic {
+ diagnostic.stage("paused");
+ }
+ let message = format!(
+ "Could not resume recording: {error:#}. Your recording is still paused; you can retry or press Stop to save it"
+ );
+ return Err(error.context(message));
+ }
+ };
if let Some(diagnostic) = &mut self.diagnostic {
diagnostic.stage("recording");
}
let new_segment_start_time = current_time_f64();
- Some(ActorState::Recording {
+ self.state = Some(ActorState::Recording {
pipeline,
index: next_index,
segment_start_time: new_segment_start_time,
segment_start_instant: Instant::now(),
- })
+ });
}
- state => state,
- };
+ Some(ActorState::Recording { .. }) => {}
+ None => bail!("Recording no longer active"),
+ }
Ok(())
}
@@ -1924,7 +1946,7 @@ impl ActorHandle {
}
pub async fn resume(&self) -> anyhow::Result<()> {
- #[cfg(windows)]
+ #[cfg(any(target_os = "macos", windows))]
if self.terminal_started() {
bail!("Studio terminal cleanup already owns this attempt");
}
@@ -2115,8 +2137,7 @@ impl ActorBuilder {
#[cfg(windows)]
{
let scope = crate::output_pipeline::PipelineBuildScope::new();
- let result =
- crate::output_pipeline::finish_windows_pipeline_startup(&scope, startup).await;
+ let result = crate::output_pipeline::finish_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:#}")) {
@@ -2818,7 +2839,7 @@ async fn stop_recording(
})
}
-#[cfg(all(test, target_os = "linux"))]
+#[cfg(test)]
type ResumeTestFactory = Arc<
dyn Fn(Cursors, u32) -> futures::future::BoxFuture<'static, anyhow::Result<Pipeline>>
+ Send
@@ -2827,7 +2848,7 @@ type ResumeTestFactory = Arc<
#[derive(Clone)]
struct SegmentPipelineFactory {
- #[cfg(all(test, target_os = "linux"))]
+ #[cfg(test)]
prepare_override: Option<ResumeTestFactory>,
segments_dir: PathBuf,
cursors_dir: PathBuf,
@@ -2859,7 +2880,7 @@ impl SegmentPipelineFactory {
completion_tx: watch::Sender<Option<Result<(), PipelineDoneError>>>,
) -> Self {
Self {
- #[cfg(all(test, target_os = "linux"))]
+ #[cfg(test)]
prepare_override: None,
segments_dir,
cursors_dir,
@@ -2931,25 +2952,39 @@ impl SegmentPipelineFactory {
cursors: Cursors,
next_cursors_id: u32,
) -> anyhow::Result<Pipeline> {
- let segment_start_time = Timestamps::now();
- let mut pipeline = 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?;
+ let startup = async {
+ #[cfg(test)]
+ if let Some(prepare) = &self.prepare_override {
+ return prepare(cursors, next_cursors_id).await;
+ }
+ 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,
+ Timestamps::now(),
+ #[cfg(windows)]
+ self.encoder_preferences.clone(),
+ )
+ .await
+ };
+ let mut pipeline = if crate::output_pipeline::PipelineBuildScope::current().is_some() {
+ startup.await?
+ } else {
+ #[cfg(target_os = "macos")]
+ let scope = crate::output_pipeline::PipelineBuildScope::new_macos_segment();
+ #[cfg(not(target_os = "macos"))]
+ let scope = crate::output_pipeline::PipelineBuildScope::new();
+ crate::output_pipeline::finish_pipeline_startup(&scope, startup).await?
+ };
self.index += 1;
@@ -3876,6 +3911,250 @@ mod tests {
assert_eq!(replay.result.err().expect("cached unconfirmed stop"), error);
}
+ #[cfg(any(target_os = "macos", windows))]
+ mod failed_resume_tests {
+ use super::*;
+
+ struct Snapshot;
+
+ impl Message<Snapshot> for Actor {
+ type Reply = (u32, u32, usize, u32);
+
+ async fn handle(
+ &mut self,
+ _: Snapshot,
+ _: &mut Context<Self, Self::Reply>,
+ ) -> Self::Reply {
+ let Some(ActorState::Paused {
+ next_index,
+ next_cursor_id,
+ cursors,
+ }) = &self.state
+ else {
+ panic!("failed resume must retain paused state");
+ };
+ assert_eq!(cursors.get(&42).unwrap().id, 7);
+ (
+ *next_index,
+ *next_cursor_id,
+ self.segments.len(),
+ self.segment_factory.index,
+ )
+ }
+ }
+
+ fn paused_handle(path: &Path, prepare: ResumeTestFactory) -> ActorHandle {
+ write_in_progress_meta(path).unwrap();
+ 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.prepare_override = Some(prepare);
+ factory.index = 2;
+ let timestamps = Timestamps::now();
+ let segments = (0..2)
+ .map(|index| {
+ let file = path.join(format!("saved-{index}.m4s"));
+ std::fs::write(&file, format!("saved segment {index}")).unwrap();
+ RecordingSegment {
+ start: index as f64,
+ end: index as f64 + 1.0,
+ pipeline: FinishedPipeline {
+ start_time: timestamps,
+ screen: test_finished_output_pipeline_at(
+ file,
+ Timestamp::Instant(timestamps.instant()),
+ Some(test_video_info()),
+ 30,
+ ),
+ microphone: None,
+ camera: None,
+ system_audio: None,
+ cursor: None,
+ track_failures: Vec::new(),
+ },
+ camera_device_id: None,
+ mic_device_id: None,
+ }
+ })
+ .collect();
+ let response = sidecar_response();
+ let actor_ref = Actor::spawn(Actor {
+ diagnostic: None,
+ recording_dir: path.to_path_buf(),
+ state: Some(ActorState::Paused {
+ next_index: 2,
+ cursors: response.cursors,
+ next_cursor_id: response.next_cursor_id,
+ }),
+ all_tracks_stopped: true,
+ terminal_stop_failure: None,
+ #[cfg(windows)]
+ cancel_error: None,
+ segment_factory: factory,
+ segments,
+ completion_tx,
+ display_notch: None,
+ });
+ ActorHandle {
+ recording_dir: path.to_path_buf(),
+ terminal: Arc::new(WindowsStudioTerminal::default()),
+ actor_ref,
+ capture_target: target,
+ done_fut: completion_rx_to_done_fut(completion_rx),
+ }
+ }
+
+ #[tokio::test]
+ async fn repeated_resume_failures_preserve_segments_and_allow_stop() {
+ for failure in [
+ "Insufficient disk space to start recording: 193MB available, 500MB required",
+ "camera pipeline setup failed",
+ "microphone pipeline setup failed",
+ "screen capture init failed",
+ ] {
+ let temp = tempfile::tempdir().unwrap();
+ let handle = paused_handle(
+ temp.path(),
+ Arc::new(move |cursors, next_id| {
+ assert_eq!(cursors.get(&42).unwrap().id, 7);
+ assert_eq!(next_id, 8);
+ async move { Err(anyhow!(failure)) }.boxed()
+ }),
+ );
+ for _ in 0..3 {
+ let error = handle.resume().await.unwrap_err();
+ assert!(error.to_string().contains(failure));
+ assert!(handle.is_paused().await.unwrap());
+ assert_eq!(handle.actor_ref.ask(Snapshot).await.unwrap(), (2, 8, 2, 2));
+ }
+ let report = handle.stop_with_intent(StudioStopIntent::Preserve).await;
+ assert!(report.accepted_intent && report.stop_acknowledged);
+ let completed = report.result.unwrap();
+ let StudioRecordingMeta::MultipleSegments { inner } = completed.meta else {
+ panic!("expected saved segments");
+ };
+ assert_eq!(inner.segments.len(), 2);
+ assert!(handle.done_fut().await.is_ok());
+ assert!(
+ handle
+ .resume()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("terminal cleanup")
+ );
+ let replay = handle.stop_with_intent(StudioStopIntent::Preserve).await;
+ assert!(replay.stop_acknowledged && replay.result.is_ok());
+ for index in 0..2 {
+ assert_eq!(
+ std::fs::read_to_string(temp.path().join(format!("saved-{index}.m4s")))
+ .unwrap(),
+ format!("saved segment {index}")
+ );
+ }
+ let saved = RecordingMeta::load_for_project(temp.path()).unwrap();
+ let StudioRecordingMeta::MultipleSegments { inner } = saved.studio_meta().unwrap()
+ else {
+ panic!("expected saved segments");
+ };
+ assert_eq!(inner.segments.len(), 2);
+ }
+ }
+
+ #[tokio::test]
+ async fn failed_resume_waits_for_owned_cleanup_before_stop() {
+ let temp = tempfile::tempdir().unwrap();
+ let (release, hold) = tokio::sync::oneshot::channel::<()>();
+ let hold = Arc::new(std::sync::Mutex::new(Some(hold)));
+ let entered = Arc::new(tokio::sync::Notify::new());
+ let ready = entered.clone();
+ let handle = paused_handle(
+ temp.path(),
+ Arc::new(move |_, _| {
+ let hold = hold.lock().unwrap().take().unwrap();
+ let ready = ready.clone();
+ async move {
+ let scope = crate::output_pipeline::PipelineBuildScope::current().unwrap();
+ scope.spawn_cleanup(async move {
+ ready.notify_one();
+ hold.await.unwrap();
+ Ok(())
+ });
+ Err(anyhow!("camera setup failed after screen setup"))
+ }
+ .boxed()
+ }),
+ );
+ let resume_handle = handle.clone();
+ let resume = tokio::spawn(async move { resume_handle.resume().await });
+ entered.notified().await;
+ assert!(!resume.is_finished());
+ release.send(()).unwrap();
+ assert!(resume.await.unwrap().is_err());
+ assert!(handle.is_paused().await.unwrap());
+ let report = handle.stop_with_intent(StudioStopIntent::Preserve).await;
+ assert!(report.stop_acknowledged && report.result.is_ok());
+ }
+
+ #[tokio::test]
+ async fn unconfirmed_resume_cleanup_cannot_acknowledge_stop_or_retry() {
+ let temp = tempfile::tempdir().unwrap();
+ let handle = paused_handle(
+ temp.path(),
+ Arc::new(|_, _| {
+ async {
+ let scope = crate::output_pipeline::PipelineBuildScope::current().unwrap();
+ scope.spawn_cleanup(async {
+ Err(anyhow!("source stop acknowledgement lost"))
+ });
+ Err(anyhow!("screen setup failed"))
+ }
+ .boxed()
+ }),
+ );
+ assert!(
+ handle
+ .resume()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("cleanup is unconfirmed")
+ );
+ assert!(
+ handle
+ .resume()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains(UNCONFIRMED_CAPTURE_CLEANUP)
+ );
+ let report = handle.stop_with_intent(StudioStopIntent::Preserve).await;
+ assert!(!report.stop_acknowledged);
+ assert!(report.result.is_err());
+ handle.actor_ref.stop_gracefully().await.unwrap();
+ }
+ }
+
#[cfg(target_os = "linux")]
mod resume_transaction_tests {
use super::*;
diff --git a/crates/recording/tests/hardware_studio_recording.rs b/crates/recording/tests/hardware_studio_recording.rs
index 78d60a4d4..91a72d59a 100644
--- a/crates/recording/tests/hardware_studio_recording.rs
+++ b/crates/recording/tests/hardware_studio_recording.rs
@@ -29,6 +29,106 @@ fn init() {
ffmpeg::init().expect("failed to initialize ffmpeg");
}
+#[tokio::test]
+async fn studio_failed_second_resume_can_save_or_retry_with_real_screen() {
+ init();
+ let shareable_content: SendableShareableContent = cidre::sc::ShareableContent::current()
+ .await
+ .expect("Screen Recording permission is required")
+ .into();
+
+ for (retry, fail_after_screen_start) in
+ [(false, false), (true, false), (false, true), (true, true)]
+ {
+ let temp = TempDir::new().unwrap();
+ let recording_dir = temp.path().join("failed-resume.cap");
+ let handle = studio_recording::Actor::builder(
+ recording_dir.clone(),
+ ScreenCaptureTarget::Display {
+ id: scap_targets::Display::primary().id(),
+ },
+ )
+ .with_fragmented(false)
+ .with_system_audio(fail_after_screen_start)
+ .with_max_fps(30)
+ .with_keyboard_capture(false)
+ .build(Some(shareable_content.clone()))
+ .await
+ .unwrap();
+
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ handle.pause().await.unwrap();
+ handle.resume().await.unwrap();
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ handle.pause().await.unwrap();
+
+ let segments = recording_dir.join("content/segments");
+ let original_bytes: Vec<_> = (0..2)
+ .map(|index| {
+ std::fs::read(segments.join(format!("segment-{index}/display.mp4"))).unwrap()
+ })
+ .collect();
+ let obstruction = if fail_after_screen_start {
+ let path = segments.join("segment-2/system_audio.ogg");
+ std::fs::create_dir_all(&path).unwrap();
+ path
+ } else {
+ let path = segments.join("segment-2");
+ std::fs::write(&path, b"failed segment creation").unwrap();
+ path
+ };
+ for _ in 0..2 {
+ let failure = tokio::time::timeout(Duration::from_secs(5), handle.resume())
+ .await
+ .expect("resume must return its error")
+ .unwrap_err();
+ assert!(failure.to_string().contains("still paused"));
+ if fail_after_screen_start {
+ assert!(failure.to_string().contains("system audio pipeline setup"));
+ assert!(segments.join("segment-2/display.mp4").exists());
+ }
+ assert!(handle.is_paused().await.unwrap());
+ }
+ if fail_after_screen_start {
+ std::fs::remove_dir(&obstruction).unwrap();
+ } else {
+ std::fs::remove_file(&obstruction).unwrap();
+ }
+ if retry {
+ handle.resume().await.unwrap();
+ assert!(!handle.is_paused().await.unwrap());
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ }
+
+ let report = tokio::time::timeout(
+ Duration::from_secs(15),
+ handle.stop_with_intent(studio_recording::StudioStopIntent::Preserve),
+ )
+ .await
+ .expect("Stop must complete after failed resume");
+ assert!(report.accepted_intent && report.stop_acknowledged);
+ let completed = report.result.unwrap();
+ let cap_project::StudioRecordingMeta::MultipleSegments { inner } = completed.meta else {
+ panic!("expected multiple segments");
+ };
+ assert_eq!(inner.segments.len(), if retry { 3 } else { 2 });
+ for (index, original) in original_bytes.iter().enumerate() {
+ let path = segments.join(format!("segment-{index}/display.mp4"));
+ assert_eq!(&std::fs::read(&path).unwrap(), original);
+ }
+ for segment in inner.segments {
+ let path = segment.display.path.to_path(&recording_dir);
+ assert!(probe_media_valid(&path));
+ assert!(probe_video_can_decode(&path).unwrap());
+ let duration = get_media_duration(&path).unwrap().as_secs_f64();
+ assert!(
+ (1.0..3.0).contains(&duration),
+ "segment duration {duration}"
+ );
+ }
+ }
+}
+
#[tokio::test]
async fn studio_nonfragmented_record_pause_resume_with_real_screen() {
init();