Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop): add optional MacBook notch overlay in Studio Mode

Jamie Davenport536c73e54392
diff --git a/Cargo.lock b/Cargo.lock
index 411fca9b6..f4a7fc205 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1914,6 +1914,7 @@ dependencies = [
"log",
"metal 0.31.0",
"objc2 0.6.2",
+ "pollster",
"pretty_assertions",
"rayon",
"reactive_graph",
diff --git a/apps/cli/src/selftest/playback.rs b/apps/cli/src/selftest/playback.rs
index 6b295fccb..0458443bc 100644
--- a/apps/cli/src/selftest/playback.rs
+++ b/apps/cli/src/selftest/playback.rs
@@ -869,6 +869,7 @@ mod fixture {
}),
cursor: None,
keyboard: None,
+ display_notch: None,
};
// Clip offsets exactly as the studio recorder persists them.
let offsets = segment.calculate_audio_offsets();
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index 565032a39..8ea2ce2fd 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -194,6 +194,11 @@ pub struct GeneralSettingsStore {
pub enable_native_camera_preview: bool,
#[serde(default = "default_true")]
pub auto_zoom_on_clicks: bool,
+ /// `None` until [`init`] seeds it from whether this machine has a notched
+ /// display. From then on it is the user's preference and nothing re-reads
+ /// the hardware, so moving between machines can't silently flip it.
+ #[serde(default)]
+ pub macbook_notch_overlay: Option<bool>,
#[serde(default = "default_capture_keyboard_events")]
pub capture_keyboard_events: bool,
#[serde(default)]
@@ -323,6 +328,7 @@ impl Default for GeneralSettingsStore {
// Keep aligned with the field's serde `default_true`: auto zooms
// are on by default, matching configs that never stored the key.
auto_zoom_on_clicks: true,
+ macbook_notch_overlay: None,
capture_keyboard_events: cap_recording::DEFAULT_CAPTURE_KEYBOARD_EVENTS,
post_deletion_behaviour: PostDeletionBehaviour::DoNothing,
excluded_windows: default_excluded_windows(),
@@ -468,6 +474,13 @@ fn sync_dock_visibility_on_general_settings_change(app: &AppHandle) {
});
}
+/// Always false off macOS, so the overlay starts off and waits to be asked for.
+fn machine_has_notched_display() -> bool {
+ scap_targets::Display::list()
+ .iter()
+ .any(|display| display.notch().is_some())
+}
+
pub fn init(app: &AppHandle) {
println!("Initializing GeneralSettingsStore");
@@ -482,6 +495,10 @@ pub fn init(app: &AppHandle) {
append_missing_default_excluded_windows(&mut store.excluded_windows);
+ if store.macbook_notch_overlay.is_none() {
+ store.macbook_notch_overlay = Some(machine_has_notched_display());
+ }
+
const REMOVE_TARGET_SELECT_MIGRATION_KEY: &str = "remove_cap_target_select_exclusion_v1";
if let Ok(raw_store) = app.store("store")
&& raw_store.get(REMOVE_TARGET_SELECT_MIGRATION_KEY).is_none()
diff --git a/apps/desktop/src-tauri/src/import.rs b/apps/desktop/src-tauri/src/import.rs
index f8f4f36a3..b2baf436a 100644
--- a/apps/desktop/src-tauri/src/import.rs
+++ b/apps/desktop/src-tauri/src/import.rs
@@ -286,6 +286,7 @@ fn ensure_multiple_segments(meta: &mut RecordingMeta) -> Result<&mut MultipleSeg
system_audio: None,
cursor: segment.cursor,
keyboard: None,
+ display_notch: None,
}],
cursors: Cursors::default(),
status: Some(StudioRecordingStatus::Complete),
@@ -844,6 +845,7 @@ fn single_segment_to_multiple(segment: &SingleSegment) -> MultipleSegment {
system_audio: None,
cursor: segment.cursor.clone(),
keyboard: None,
+ display_notch: None,
}
}
@@ -1019,6 +1021,7 @@ fn copy_source_segment(
system_audio,
cursor,
keyboard,
+ display_notch: None,
})
}
@@ -1425,6 +1428,7 @@ pub async fn start_video_import(app: AppHandle, source_path: PathBuf) -> Result<
system_audio: None,
cursor: None,
keyboard: None,
+ display_notch: None,
}],
cursors: Cursors::default(),
status: Some(StudioRecordingStatus::InProgress),
@@ -1520,6 +1524,7 @@ pub async fn start_video_import(app: AppHandle, source_path: PathBuf) -> Result<
system_audio,
cursor: None,
keyboard: None,
+ display_notch: None,
}],
cursors: Cursors::default(),
status: Some(StudioRecordingStatus::Complete),
@@ -1694,6 +1699,7 @@ async fn append_mp4_to_editor_project(
system_audio,
cursor: None,
keyboard: None,
+ display_notch: None,
};
{
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index deb087400..f6f3f9866 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -3018,6 +3018,10 @@ struct SerializedEditorInstance {
saved_project_config: ProjectConfiguration,
recordings: Arc<ProjectRecordingsMeta>,
path: PathBuf,
+ /// Notch geometry the overlay uses when the project sets no manual
+ /// placement: this recording's own measurements where the recorder took
+ /// them, else a stock MacBook notch for the editor to start from.
+ notch_base: cap_project::DisplayNotch,
}
#[tauri::command]
@@ -3051,6 +3055,11 @@ async fn create_editor_instance(window: Window) -> Result<SerializedEditorInstan
},
recordings: editor_instance.recordings.clone(),
path: editor_instance.project_path.clone(),
+ notch_base: editor_instance
+ .render_constants
+ .meta
+ .display_notch()
+ .unwrap_or(cap_project::DEFAULT_MACBOOK_NOTCH),
})
}
@@ -4787,44 +4796,10 @@ fn configure_camera_blur_recovery(
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
-pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
- // Arm the unexpected-termination sentinel before anything else can crash, and
- // report any previous session that died without a clean shutdown.
- let previous_termination = crash_sentinel::init(&logs_dir, env!("CARGO_PKG_VERSION"));
- configure_windows_graphics_recovery(previous_termination);
-
- // Keep the sentinel's blur marker in sync with live BlurProcessor instances
- // (camera preview and editor render alike), so a native blur crash is
- // attributable on the next launch.
- cap_camera_effects::set_blur_session_observer(|active| {
- if active {
- crash_sentinel::enter_blur_session();
- } else {
- crash_sentinel::exit_blur_session();
- }
- });
-
- ffmpeg::init()
- .map_err(|e| {
- error!("Failed to initialize ffmpeg: {e}");
- })
- .ok();
-
- // Detect the camera-preview quality profile once from total RAM. On low-RAM
- // machines (<= 8GB) this opts the preview into a cheaper profile (smaller
- // textures, 30fps, no background blur); higher-spec machines keep the exact
- // current behaviour. Only the preview is affected — recording is untouched.
- {
- let mut system = sysinfo::System::new();
- system.refresh_memory();
- camera::init_preview_profile(system.total_memory());
- }
-
- telemetry::init();
-
- let tauri_context = tauri::generate_context!();
-
- let specta_builder = tauri_specta::Builder::new()
+/// Extracted so the TypeScript bindings can be regenerated without booting
+/// the app, which would otherwise ask for camera and microphone access.
+fn create_specta_builder() -> tauri_specta::Builder {
+ tauri_specta::Builder::new()
.commands(tauri_specta::collect_commands![
set_mic_input,
set_camera_input,
@@ -5040,22 +5015,64 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
.typ::<cap_automation::ClipboardSource>()
.typ::<cap_automation::ExportFormat>()
.typ::<cap_automation::AutomationExportCompression>()
- .typ::<cap_automation::ExportDestination>();
+ .typ::<cap_automation::ExportDestination>()
+}
- #[cfg(debug_assertions)]
- {
- let bindings_path = std::path::Path::new("../src/utils/tauri.ts");
- if bindings_path.parent().is_some_and(|parent| parent.exists()) {
- if let Err(err) =
- specta_builder.export(specta_typescript::Typescript::default(), bindings_path)
- {
- warn!(error = %err, "Failed to export TypeScript bindings");
- }
+#[cfg(debug_assertions)]
+fn export_typescript_bindings(builder: &tauri_specta::Builder) {
+ let bindings_path = std::path::Path::new("../src/utils/tauri.ts");
+ if !bindings_path.parent().is_some_and(|parent| parent.exists()) {
+ debug!("Skipping TypeScript bindings export outside source checkout");
+ return;
+ }
+
+ if let Err(err) = builder.export(specta_typescript::Typescript::default(), bindings_path) {
+ warn!(error = %err, "Failed to export TypeScript bindings");
+ }
+}
+
+pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
+ // Arm the unexpected-termination sentinel before anything else can crash, and
+ // report any previous session that died without a clean shutdown.
+ let previous_termination = crash_sentinel::init(&logs_dir, env!("CARGO_PKG_VERSION"));
+ configure_windows_graphics_recovery(previous_termination);
+
+ // Keep the sentinel's blur marker in sync with live BlurProcessor instances
+ // (camera preview and editor render alike), so a native blur crash is
+ // attributable on the next launch.
+ cap_camera_effects::set_blur_session_observer(|active| {
+ if active {
+ crash_sentinel::enter_blur_session();
} else {
- debug!("Skipping TypeScript bindings export outside source checkout");
+ crash_sentinel::exit_blur_session();
}
+ });
+
+ ffmpeg::init()
+ .map_err(|e| {
+ error!("Failed to initialize ffmpeg: {e}");
+ })
+ .ok();
+
+ // Detect the camera-preview quality profile once from total RAM. On low-RAM
+ // machines (<= 8GB) this opts the preview into a cheaper profile (smaller
+ // textures, 30fps, no background blur); higher-spec machines keep the exact
+ // current behaviour. Only the preview is affected — recording is untouched.
+ {
+ let mut system = sysinfo::System::new();
+ system.refresh_memory();
+ camera::init_preview_profile(system.total_memory());
}
+ telemetry::init();
+
+ let tauri_context = tauri::generate_context!();
+
+ let specta_builder = create_specta_builder();
+
+ #[cfg(debug_assertions)]
+ export_typescript_bindings(&specta_builder);
+
let (camera_preview_state_tx, camera_preview_state_rx) =
tokio::sync::watch::channel(CameraPreviewState::default());
let (camera_tx, camera_ws_port, _shutdown) =
@@ -6830,3 +6847,14 @@ mod screenshot_share_cache_tests {
assert!(link.is_none());
}
}
+
+#[cfg(all(test, debug_assertions))]
+mod bindings_tests {
+ /// Regenerates `apps/desktop/src/utils/tauri.ts`, which is committed and
+ /// which CI typechecks against. Running the app in debug does the same, but
+ /// that needs camera and microphone access; this does not.
+ #[test]
+ fn export_typescript_bindings() {
+ super::export_typescript_bindings(&super::create_specta_builder());
+ }
+}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 5def0f60b..bc32fdd28 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -3853,6 +3853,19 @@ fn project_config_from_recording(
Vec::new()
};
+ // Screen captures only; the editor's toggle is there for anyone who wants a
+ // notch over a window recording anyway.
+ let captured_screen = matches!(
+ capture_target,
+ Some(ScreenCaptureTarget::Display { .. } | ScreenCaptureTarget::Area { .. })
+ );
+ if captured_screen && settings.macbook_notch_overlay.unwrap_or(false) {
+ config.background.notch = Some(cap_project::NotchConfiguration {
+ enabled: true,
+ ..Default::default()
+ });
+ }
+
config.timeline = Some(TimelineConfiguration {
segments: timeline_segments,
transitions: Vec::new(),
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
index face896e3..50eeaf7f0 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
@@ -668,6 +668,12 @@ function Inner(props: {
value={!!settings.captureKeyboardEvents}
onChange={(value) => handleChange("captureKeyboardEvents", value)}
/>
+ <ToggleSettingItem
+ label="Draw the MacBook notch on screen recordings"
+ description="Screen capture records straight through the notch, so recordings show an unbroken menu bar. This draws it back on by default for new screen and area recordings; window recordings are left alone. Each recording can override it in the editor."
+ value={!!settings.macbookNotchOverlay}
+ onChange={(value) => handleChange("macbookNotchOverlay", value)}
+ />
<SelectSettingItem
label="Max capture framerate"
description={
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index a10c49b06..cbad8d11d 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -66,6 +66,7 @@ import {
type CursorType,
commands,
type KeyboardTrackSegment,
+ type NotchConfiguration,
type SceneMode,
type SceneSegment,
type SplitLayout,
@@ -80,6 +81,7 @@ import IconLucideEyeOff from "~icons/lucide/eye-off";
import IconLucideGrid from "~icons/lucide/grid";
import IconLucideImageOff from "~icons/lucide/image-off";
import IconLucideKeyboard from "~icons/lucide/keyboard";
+import IconLucideLaptop from "~icons/lucide/laptop";
import IconLucideMonitor from "~icons/lucide/monitor";
import IconLucideMoon from "~icons/lucide/moon";
import IconLucideMusic from "~icons/lucide/music";
@@ -272,6 +274,15 @@ const WALLPAPER_NAMES = [
"orange/9",
] as const;
+// Null placement means "use the recording's own measurements", so untouched
+// sliders must stay null rather than being written out at their displayed value.
+const UNPLACED_NOTCH = {
+ enabled: false,
+ x: null,
+ width: null,
+ height: null,
+} satisfies NotchConfiguration;
+
const CURRENT_DESKTOP_BACKGROUND_ID = "current-desktop-background";
const CURRENT_DESKTOP_BACKGROUND_BASENAME = "current-desktop-background";
const getCurrentDesktopBackgroundLabel = () => {
@@ -2677,6 +2688,81 @@ function BackgroundConfig(props: {
</div>
</KCollapsible.Content>
</KCollapsible>
+ <Field
+ name="MacBook notch"
+ icon={<IconLucideLaptop class="size-4" />}
+ value={
+ <Toggle
+ checked={project.background.notch?.enabled ?? false}
+ onChange={(enabled) =>
+ setProject("background", "notch", {
+ ...(project.background.notch ?? UNPLACED_NOTCH),
+ enabled,
+ })
+ }
+ />
+ }
+ />
+ <KCollapsible open={project.background.notch?.enabled ?? false}>
+ <KCollapsible.Content class="overflow-hidden opacity-0 transition-opacity animate-collapsible-up data-expanded:animate-collapsible-down data-expanded:opacity-100">
+ <div class="flex flex-col gap-6 pb-6">
+ <p class="text-xs text-gray-11">
+ Draws a MacBook notch over the recording. Recordings made on a Mac
+ with a notch use their own measurements; otherwise start from the
+ size below and adjust to match.
+ </p>
+ <For
+ each={
+ [
+ { key: "width", name: "Notch Width", max: 0.4 },
+ { key: "height", name: "Notch Height", max: 0.15 },
+ { key: "x", name: "Notch Position", max: 1 },
+ ] as const
+ }
+ >
+ {(field) => (
+ <Field
+ name={field.name}
+ icon={<IconCapEnlarge class="size-4" />}
+ >
+ <Slider
+ value={[
+ project.background.notch?.[field.key] ??
+ editorInstance.notchBase[field.key],
+ ]}
+ onChange={(v) => {
+ const base = editorInstance.notchBase;
+ const prev = project.background.notch ?? UNPLACED_NOTCH;
+ const next: NotchConfiguration = {
+ ...prev,
+ enabled: true,
+ };
+ next[field.key] = v[0];
+
+ if (field.key === "width") {
+ // Resize about the centre rather than dragging the
+ // left edge along with the width.
+ const centre =
+ (prev.x ?? base.x) + (prev.width ?? base.width) / 2;
+ next.x = Math.min(
+ Math.max(centre - v[0] / 2, 0),
+ 1 - v[0],
+ );
+ }
+
+ setProject("background", "notch", next);
+ }}
+ minValue={0}
+ maxValue={field.max}
+ step={0.001}
+ formatTooltip={(value) => `${(value * 100).toFixed(1)}%`}
+ />
+ </Field>
+ )}
+ </For>
+ </div>
+ </KCollapsible.Content>
+ </KCollapsible>
<Field name="Shadow" icon={<IconCapShadow class="size-4" />}>
<Slider
value={[project.background.shadow ?? 0]}
diff --git a/apps/desktop/src/utils/general-settings.ts b/apps/desktop/src/utils/general-settings.ts
index 37dcbab6f..f878b4488 100644
--- a/apps/desktop/src/utils/general-settings.ts
+++ b/apps/desktop/src/utils/general-settings.ts
@@ -45,6 +45,8 @@ export function createDefaultGeneralSettings(): GeneralSettingsStore {
enableNotifications: true,
enableNativeCameraPreview: false,
autoZoomOnClicks: false,
+ // Off until the backend seeds it from whether this machine has a notch.
+ macbookNotchOverlay: false,
captureKeyboardEvents: true,
custom_cursor_capture2: true,
excludedWindows: [],
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index c29ce47cd..923a834e7 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -637,7 +637,13 @@ displayPosition: XY<number> | null; shadow: number; advancedShadow: ShadowConfig
* Decorative frame around the recording. `None` (or `FrameStyle::None`)
* renders the bare video exactly as before the feature existed.
*/
-frame: FrameConfiguration | null }
+frame: FrameConfiguration | null;
+/**
+ * Redraws the recording device's physical notch over the capture. Distinct
+ * from `frame`: the decorative MacBook style is a mockup, this restores
+ * something the capture really did hide, and the two are independent.
+ */
+notch: NotchConfiguration | null }
export type BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number]; alpha?: number } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number; noise_intensity?: number | null; noise_scale?: number | null; animated?: boolean | null; animation_speed?: number | null }
export type BorderConfiguration = { enabled: boolean; width: number; color: [number, number, number]; opacity: number }
export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition;
@@ -711,6 +717,19 @@ export type DeviceOrModelID = { DeviceID: string } | { ModelID: ModelIDType }
export type DevicesUpdated = { cameras: CameraInfo[]; microphones: string[]; permissions: OSPermissionsCheck }
export type DisplayId = string
export type DisplayInformation = { name: string | null; physical_size: PhysicalSize | null; logical_size: LogicalSize | null; logical_bounds: LogicalBounds | null; refresh_rate: string }
+/**
+ * Where the recording device's physical notch sits within the captured video.
+ *
+ * macOS captures the pixels behind the notch, so without this the recording
+ * shows an unbroken menu bar where the recorder saw a cutout. Fractions of the
+ * captured frame rather than of the display, so area recordings, which are
+ * cropped at capture time, need no extra context to interpret.
+ */
+export type DisplayNotch = {
+/**
+ * Distance from the left edge of the video to the notch.
+ */
+x: number; width: number; height: number }
export type DownloadProgress = { progress: number; message: string }
export type EditorPreviewQuality = "quarter" | "half" | "full"
export type EditorRecordingAdded = { editor_path: string; recording_path: string }
@@ -768,7 +787,13 @@ export type FrameStyle =
"macbook"
export type FrameTheme = "dark" | "light"
export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }
-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; captureKeyboardEvents?: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number; defaultProjectNameTemplate?: string | null; crashRecoveryRecording?: boolean; maxFps?: number; transcriptionHints?: string[]; editorPreviewQuality?: EditorPreviewQuality; studioRecordingQuality?: StudioRecordingQuality; mainWindowPosition?: WindowPosition | null; cameraWindowPosition?: WindowPosition | null; cameraWindowPositionsByMonitorName?: { [key in string]: WindowPosition }; hasCompletedOnboarding?: boolean; enableTelemetry?: boolean; outOfProcessMuxer?: boolean; recordingsPath?: string | null;
+export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean;
+/**
+ * `None` until [`init`] seeds it from whether this machine has a notched
+ * display. From then on it is the user's preference and nothing re-reads
+ * the hardware, so moving between machines can't silently flip it.
+ */
+macbookNotchOverlay?: boolean | null; captureKeyboardEvents?: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number; defaultProjectNameTemplate?: string | null; crashRecoveryRecording?: boolean; maxFps?: number; transcriptionHints?: string[]; editorPreviewQuality?: EditorPreviewQuality; studioRecordingQuality?: StudioRecordingQuality; mainWindowPosition?: WindowPosition | null; cameraWindowPosition?: WindowPosition | null; cameraWindowPositionsByMonitorName?: { [key in string]: WindowPosition }; hasCompletedOnboarding?: boolean; enableTelemetry?: boolean; outOfProcessMuxer?: boolean; recordingsPath?: string | null;
/**
* Custom recordings folders that were used before; recordings left in
* them stay visible in the library. Most recent last.
@@ -831,11 +856,21 @@ export type ModelDownloadStatus = { state: ModelDownloadState; progress: number;
export type ModelIDType = string
export type MovExportSettings = { fps: number; resolution_base: XY<number>; cursor_only?: boolean }
export type Mp4ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression; custom_bpp: number | null; force_ffmpeg_decoder?: boolean; optimize_filesize?: boolean }
-export type MultipleSegment = { display: VideoMeta; camera?: VideoMeta | null; mic?: AudioMeta | null; system_audio?: AudioMeta | null; cursor?: string | null; keyboard?: string | null }
+export type MultipleSegment = { display: VideoMeta; camera?: VideoMeta | null; mic?: AudioMeta | null; system_audio?: AudioMeta | null; cursor?: string | null; keyboard?: string | null; display_notch?: DisplayNotch | null }
export type MultipleSegments = { segments: MultipleSegment[]; cursors: Cursors; status?: StudioRecordingStatus | null }
export type NewNotification = { title: string; body: string; is_error: boolean }
export type NewScreenshotAdded = { path: string }
export type NewStudioRecordingAdded = { path: string }
+/**
+ * Draws a MacBook notch over the recording. Nothing here is inferred from the
+ * video: a finished recording carries no evidence of the panel it came from.
+ */
+export type NotchConfiguration = { enabled: boolean;
+/**
+ * Manual placement, as fractions of the video. Each `None` falls back to
+ * the geometry measured at capture time, else [`DEFAULT_MACBOOK_NOTCH`].
+ */
+x: number | null; width: number | null; height: number | null }
export type OSPermission = "screenRecording" | "camera" | "microphone" | "accessibility"
export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"
export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus; accessibility: OSPermissionStatus }
@@ -902,7 +937,13 @@ export type ScreenshotProjectExport = { imageBytes: number[]; config: ProjectCon
export type ScreenshotProjectShareState = { config: ProjectConfiguration; sharing: ScreenshotSharingState | null }
export type ScreenshotSharingState = { link: string; contentHash: string | null }
export type SegmentRecordings = { display: Video; camera: Video | null; mic: Audio | null; system_audio: Audio | null }
-export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string }
+export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string;
+/**
+ * Notch geometry the overlay uses when the project sets no manual
+ * placement: this recording's own measurements where the recorder took
+ * them, else a stock MacBook notch for the editor to start from.
+ */
+notchBase: DisplayNotch }
export type SerializedScreenshotEditorInstance = { framesSocketUrl: string; path: string; config: ProjectConfiguration | null; prettyName: string; imageWidth: number; imageHeight: number }
export type SetCaptureAreaPending = boolean
export type ShadowConfiguration = { size: number; opacity: number; blur: number }
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 9f5661a8e..71e22b1ec 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -10,6 +10,8 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
+use crate::DisplayNotch;
+
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub enum AspectRatio {
@@ -290,6 +292,53 @@ impl FrameConfiguration {
}
}
+/// Draws a MacBook notch over the recording. Nothing here is inferred from the
+/// video: a finished recording carries no evidence of the panel it came from.
+#[derive(Type, Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq)]
+#[serde(rename_all = "camelCase", default)]
+pub struct NotchConfiguration {
+ pub enabled: bool,
+ /// Manual placement, as fractions of the video. Each `None` falls back to
+ /// the geometry measured at capture time, else [`DEFAULT_MACBOOK_NOTCH`].
+ pub x: Option<f64>,
+ pub width: Option<f64>,
+ pub height: Option<f64>,
+}
+
+/// Notch of a 14" MacBook Pro, measured via `NSScreen` on a 1512x982pt display.
+///
+/// Only a starting point for placing one by hand on recordings that carry no
+/// measurements of their own. The cutout is physically the same size across
+/// MacBook models but the panels are not, so this reads a little wide on
+/// 15"/16" machines until adjusted.
+pub const DEFAULT_MACBOOK_NOTCH: DisplayNotch = DisplayNotch {
+ x: 0.438_492_063_492_063_5,
+ width: 0.122_354_497_354_497_35,
+ height: 0.032_586_558_044_806_514,
+};
+
+impl NotchConfiguration {
+ /// Notch rect to draw, in fractions of the recorded video, or `None` when
+ /// the overlay is switched off.
+ pub fn resolve(&self, recorded: Option<DisplayNotch>) -> Option<DisplayNotch> {
+ if !self.enabled {
+ return None;
+ }
+
+ let base = recorded.unwrap_or(DEFAULT_MACBOOK_NOTCH);
+
+ let width = self.width.unwrap_or(base.width).clamp(0.0, 1.0);
+ let height = self.height.unwrap_or(base.height).clamp(0.0, 1.0);
+ if width <= 0.0 || height <= 0.0 {
+ return None;
+ }
+
+ let x = self.x.unwrap_or(base.x).clamp(0.0, 1.0 - width);
+
+ Some(DisplayNotch { x, width, height })
+ }
+}
+
#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", default)]
pub struct BackgroundConfiguration {
@@ -310,6 +359,10 @@ pub struct BackgroundConfiguration {
/// Decorative frame around the recording. `None` (or `FrameStyle::None`)
/// renders the bare video exactly as before the feature existed.
pub frame: Option<FrameConfiguration>,
+ /// Redraws the recording device's physical notch over the capture. Distinct
+ /// from `frame`: the decorative MacBook style is a mockup, this restores
+ /// something the capture really did hide, and the two are independent.
+ pub notch: Option<NotchConfiguration>,
}
impl Default for BorderConfiguration {
@@ -338,6 +391,7 @@ impl Default for BackgroundConfiguration {
advanced_shadow: Some(ShadowConfiguration::default()),
border: None, // Border is disabled by default for backwards compatibility
frame: None, // No decorative frame by default
+ notch: None,
}
}
}
@@ -1815,6 +1869,100 @@ pub const SLOW_VELOCITY_THRESHOLD: f64 = 0.003;
pub const REGULAR_VELOCITY_THRESHOLD: f64 = 0.008;
pub const FAST_VELOCITY_THRESHOLD: f64 = 0.015;
+#[cfg(test)]
+mod notch_tests {
+ use super::*;
+
+ const RECORDED: DisplayNotch = DisplayNotch {
+ x: 0.4,
+ width: 0.2,
+ height: 0.04,
+ };
+
+ fn enabled() -> NotchConfiguration {
+ NotchConfiguration {
+ enabled: true,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn disabled_by_default() {
+ assert_eq!(NotchConfiguration::default().resolve(Some(RECORDED)), None);
+ }
+
+ #[test]
+ fn prefers_geometry_measured_at_capture_time() {
+ assert_eq!(enabled().resolve(Some(RECORDED)), Some(RECORDED));
+ }
+
+ /// Recordings the recorder could not measure still get a notch on request;
+ /// it just starts from the stock MacBook rect for the user to adjust.
+ #[test]
+ fn unmeasured_recordings_start_from_the_default_rect() {
+ assert_eq!(enabled().resolve(None), Some(DEFAULT_MACBOOK_NOTCH));
+ }
+
+ /// Each field falls back independently, so resizing without repositioning
+ /// leaves the notch where it was measured. Keeping the notch centred as it
+ /// resizes is the editor's job, which lets its sliders show the real value.
+ #[test]
+ fn each_field_falls_back_on_its_own() {
+ let resolved = NotchConfiguration {
+ enabled: true,
+ x: None,
+ width: Some(0.1),
+ height: Some(0.02),
+ }
+ .resolve(Some(RECORDED))
+ .unwrap();
+
+ assert_eq!(resolved.width, 0.1);
+ assert_eq!(resolved.height, 0.02);
+ assert_eq!(resolved.x, RECORDED.x);
+ }
+
+ #[test]
+ fn explicit_x_overrides_the_centring() {
+ let resolved = NotchConfiguration {
+ enabled: true,
+ x: Some(0.1),
+ width: Some(0.2),
+ height: None,
+ }
+ .resolve(Some(RECORDED))
+ .unwrap();
+
+ assert_eq!(resolved.x, 0.1);
+ }
+
+ #[test]
+ fn placement_stays_inside_the_video() {
+ let resolved = NotchConfiguration {
+ enabled: true,
+ x: Some(0.95),
+ width: Some(0.2),
+ height: None,
+ }
+ .resolve(Some(RECORDED))
+ .unwrap();
+
+ assert!(resolved.x + resolved.width <= 1.0, "{resolved:?}");
+ }
+
+ #[test]
+ fn zero_sized_override_draws_nothing() {
+ let config = NotchConfiguration {
+ enabled: true,
+ x: None,
+ width: Some(0.0),
+ height: None,
+ };
+
+ assert_eq!(config.resolve(Some(RECORDED)), None);
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rs
index 857003efe..216ee8b07 100644
--- a/crates/project/src/meta.rs
+++ b/crates/project/src/meta.rs
@@ -30,6 +30,20 @@ fn legacy_static_video_fps() -> u32 {
30
}
+/// Where the recording device's physical notch sits within the captured video.
+///
+/// macOS captures the pixels behind the notch, so without this the recording
+/// shows an unbroken menu bar where the recorder saw a cutout. Fractions of the
+/// captured frame rather than of the display, so area recordings, which are
+/// cropped at capture time, need no extra context to interpret.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Type)]
+pub struct DisplayNotch {
+ /// Distance from the left edge of the video to the notch.
+ pub x: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct AudioMeta {
#[specta(type = String)]
@@ -331,6 +345,18 @@ pub enum StudioRecordingMeta {
}
impl StudioRecordingMeta {
+ /// Notch captured with this recording. Every segment shares one display, so
+ /// the first segment speaks for all of them. `None` for recordings made
+ /// before Cap started capturing this, and for every non-macOS recording.
+ pub fn display_notch(&self) -> Option<DisplayNotch> {
+ match self {
+ StudioRecordingMeta::SingleSegment { .. } => None,
+ StudioRecordingMeta::MultipleSegments { inner } => {
+ inner.segments.first().and_then(|s| s.display_notch)
+ }
+ }
+ }
+
pub fn status(&self) -> StudioRecordingStatus {
match self {
StudioRecordingMeta::SingleSegment { .. } => StudioRecordingStatus::Complete,
@@ -493,6 +519,8 @@ pub struct MultipleSegment {
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(type = Option<String>)]
pub keyboard: Option<RelativePathBuf>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub display_notch: Option<DisplayNotch>,
}
impl MultipleSegment {
@@ -768,6 +796,7 @@ mod test {
system_audio: system_start.map(|s| audio(Some(s))),
cursor: None,
keyboard: None,
+ display_notch: None,
}
}
@@ -805,3 +834,83 @@ mod test {
}
}
}
+
+#[cfg(test)]
+mod display_notch_tests {
+ use crate::{DisplayNotch, RecordingMeta, RecordingMetaInner, StudioRecordingMeta};
+
+ fn multiple_segments(display_notch: &str) -> String {
+ format!(
+ r#"{{
+ "pretty_name": "Cap",
+ "segments": [
+ {{
+ "display": {{ "path": "content/segments/segment-0/display.mp4", "fps": 30 }}
+ {display_notch}
+ }}
+ ]
+ }}"#
+ )
+ }
+
+ fn studio(meta: &RecordingMeta) -> &StudioRecordingMeta {
+ match &meta.inner {
+ RecordingMetaInner::Studio(studio) => studio,
+ RecordingMetaInner::Instant(_) => panic!("expected a studio recording"),
+ }
+ }
+
+ /// Every recording made before this field existed must still load.
+ #[test]
+ fn absent_notch_loads_as_none() {
+ let meta: RecordingMeta = serde_json::from_str(&multiple_segments("")).unwrap();
+
+ assert_eq!(studio(&meta).display_notch(), None);
+ }
+
+ #[test]
+ fn notch_round_trips() {
+ let notch = DisplayNotch {
+ x: 0.4384920634920635,
+ width: 0.12235449735449735,
+ height: 0.032586558044806514,
+ };
+
+ let meta: RecordingMeta = serde_json::from_str(&multiple_segments(
+ r#", "display_notch": { "x": 0.4384920634920635, "width": 0.12235449735449735, "height": 0.032586558044806514 }"#,
+ ))
+ .unwrap();
+ assert_eq!(studio(&meta).display_notch(), Some(notch));
+
+ let reparsed: RecordingMeta =
+ serde_json::from_str(&serde_json::to_string(&meta).unwrap()).unwrap();
+ assert_eq!(studio(&reparsed).display_notch(), Some(notch));
+ }
+
+ /// Recordings without a notch shouldn't gain a null key in their metadata.
+ #[test]
+ fn absent_notch_is_not_serialized() {
+ let meta: RecordingMeta = serde_json::from_str(&multiple_segments("")).unwrap();
+
+ assert!(
+ !serde_json::to_string(&meta)
+ .unwrap()
+ .contains("display_notch")
+ );
+ }
+
+ /// Single-segment recordings predate the field entirely.
+ #[test]
+ fn legacy_single_segment_has_no_notch() {
+ let meta: RecordingMeta = serde_json::from_str(
+ r#"{
+ "pretty_name": "Cap",
+ "display": { "path": "content/display.mp4" },
+ "segments": [{ "start": 0.0, "end": 1.0 }]
+ }"#,
+ )
+ .unwrap();
+
+ assert_eq!(studio(&meta).display_notch(), None);
+ }
+}
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index 217dd2548..09bec811a 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -546,6 +546,56 @@ pub fn target_to_display_and_crop(
Ok((display, crop_bounds))
}
+/// Locates the recording display's physical notch within the frames this target
+/// will produce.
+///
+/// Window captures get `None`: they record the window's own surface rather than
+/// a screen region, and the window moves, so there is no stable position.
+pub fn resolve_display_notch(target: &ScreenCaptureTarget) -> Option<cap_project::DisplayNotch> {
+ let display = target.display()?;
+ let notch = display.notch()?;
+
+ match target {
+ ScreenCaptureTarget::Display { .. } => Some(cap_project::DisplayNotch {
+ x: notch.x,
+ width: notch.width,
+ height: notch.height,
+ }),
+ // Cropped at capture time, so the notch is rebased onto the crop and
+ // dropped when it falls outside.
+ ScreenCaptureTarget::Area { bounds, .. } => {
+ let display_size = display.logical_size()?;
+ let notch_left = notch.x * display_size.width();
+ let notch_right = notch_left + notch.width * display_size.width();
+ let notch_bottom = notch.height * display_size.height();
+
+ let area_left = bounds.position().x();
+ let area_top = bounds.position().y();
+ let area_width = bounds.size().width();
+ let area_height = bounds.size().height();
+
+ if area_width <= 0.0 || area_height <= 0.0 {
+ return None;
+ }
+
+ let left = notch_left.max(area_left);
+ let right = notch_right.min(area_left + area_width);
+ let bottom = notch_bottom.min(area_top + area_height);
+
+ if right <= left || bottom <= area_top {
+ return None;
+ }
+
+ Some(cap_project::DisplayNotch {
+ x: (left - area_left) / area_width,
+ width: (right - left) / area_width,
+ height: (bottom - area_top) / area_height,
+ })
+ }
+ ScreenCaptureTarget::Window { .. } | ScreenCaptureTarget::CameraOnly => None,
+ }
+}
+
#[cfg(windows)]
pub fn create_d3d_device()
-> windows::core::Result<windows::Win32::Graphics::Direct3D11::ID3D11Device> {
diff --git a/crates/recording/src/recovery.rs b/crates/recording/src/recovery.rs
index a797c6add..a9bc3cf32 100644
--- a/crates/recording/src/recovery.rs
+++ b/crates/recording/src/recovery.rs
@@ -1443,6 +1443,7 @@ impl RecoveryManager {
} else {
None
},
+ display_notch: original_segment.and_then(|s| s.display_notch),
}
})
.collect();
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index a4480da0e..cacc07199 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -98,6 +98,9 @@ pub struct Actor {
segment_factory: SegmentPipelineFactory,
segments: Vec<RecordingSegment>,
completion_tx: watch::Sender<Option<Result<(), PipelineDoneError>>>,
+ // Resolved once at recording start: the display can be disconnected, or its
+ // mode changed, by the time the recording stops.
+ display_notch: Option<cap_project::DisplayNotch>,
}
impl Actor {
@@ -193,6 +196,7 @@ impl Message<Stop> for Actor {
std::mem::take(&mut self.segments),
cursors,
self.segment_factory.fragmented,
+ self.display_notch,
)
.await?;
@@ -887,6 +891,7 @@ async fn spawn_studio_recording_actor(
segment_factory: segment_pipeline_factory,
segments: Vec::new(),
completion_tx: completion_tx.clone(),
+ display_notch: crate::capture_pipeline::resolve_display_notch(&base_inputs.capture_target),
});
Ok(ActorHandle {
@@ -920,6 +925,7 @@ async fn stop_recording(
segments: Vec<RecordingSegment>,
cursors: Cursors,
fragmented: bool,
+ display_notch: Option<cap_project::DisplayNotch>,
) -> Result<CompletedRecording, RecordingError> {
use cap_project::*;
use cap_timestamp::{AUDIO_OUTPUT_FRAMES, DEFAULT_SAMPLE_RATE};
@@ -1096,6 +1102,7 @@ async fn stop_recording(
.filter(|path| path.exists())
.map(make_relative)
}),
+ display_notch,
},
diagnostics,
duration: display_media_duration,
@@ -2014,6 +2021,7 @@ mod tests {
vec![segment],
Default::default(),
false,
+ None,
)
.await
.expect("recording should stop");
@@ -2211,6 +2219,7 @@ mod tests {
vec![segment],
Default::default(),
false,
+ None,
)
.await
.expect("diagnostics sidecar failure should not abort stop_recording");
diff --git a/crates/recording/tests/recovery.rs b/crates/recording/tests/recovery.rs
index 05154ffdd..3895bc32e 100644
--- a/crates/recording/tests/recovery.rs
+++ b/crates/recording/tests/recovery.rs
@@ -136,6 +136,7 @@ impl TestRecording {
system_audio: None,
cursor: None,
keyboard: None,
+ display_notch: None,
}],
cursors: Cursors::default(),
status: Some(status),
diff --git a/crates/rendering/Cargo.toml b/crates/rendering/Cargo.toml
index 34ac9e4a2..dbe09bb55 100644
--- a/crates/rendering/Cargo.toml
+++ b/crates/rendering/Cargo.toml
@@ -63,6 +63,7 @@ windows_0_58 = { package = "windows", version = "0.58", features = [
] }
[dev-dependencies]
+pollster = "0.4.0"
pretty_assertions = "1.4.1"
[build-dependencies]
diff --git a/crates/rendering/src/layers/mod.rs b/crates/rendering/src/layers/mod.rs
index b0e31c08c..258af84ed 100644
--- a/crates/rendering/src/layers/mod.rs
+++ b/crates/rendering/src/layers/mod.rs
@@ -7,6 +7,7 @@ mod display;
mod frame;
mod keyboard;
mod mask;
+mod notch;
mod text;
use std::sync::OnceLock;
@@ -69,6 +70,7 @@ pub use display::*;
pub use frame::*;
pub use keyboard::*;
pub use mask::*;
+pub use notch::*;
pub use text::*;
#[cfg(test)]
diff --git a/crates/rendering/src/layers/notch.rs b/crates/rendering/src/layers/notch.rs
new file mode 100644
index 000000000..4d90a6ca3
--- /dev/null
+++ b/crates/rendering/src/layers/notch.rs
@@ -0,0 +1,375 @@
+use std::sync::Arc;
+
+use crate::composite_frame::{CompositeVideoFramePipeline, CompositeVideoFrameUniforms};
+use crate::notch_shape;
+
+/// `composite.frame_size` and `crop_bounds` are filled in by the layer once the
+/// texture size is known, as the frame chrome does.
+#[derive(Clone, Copy, Debug)]
+pub struct NotchUniforms {
+ pub composite: CompositeVideoFrameUniforms,
+ /// Unzoomed notch size in output px. Zoom scales the texture rather than
+ /// re-rasterizing it, so an animating zoom doesn't thrash the cache.
+ pub raster_size: [f64; 2],
+}
+
+/// Redraws the recording device's physical notch over the screen capture.
+pub struct NotchLayer {
+ pipeline: Arc<CompositeVideoFramePipeline>,
+ uniforms_buffer: wgpu::Buffer,
+ texture: Option<wgpu::Texture>,
+ texture_view: Option<wgpu::TextureView>,
+ bind_group: Option<wgpu::BindGroup>,
+ cache_key: Option<(u32, u32)>,
+ failed_key: Option<(u32, u32)>,
+ ready: bool,
+}
+
+impl NotchLayer {
+ pub fn new(device: &wgpu::Device, pipeline: Arc<CompositeVideoFramePipeline>) -> Self {
+ Self {
+ pipeline,
+ uniforms_buffer: CompositeVideoFrameUniforms::default().to_buffer(device),
+ texture: None,
+ texture_view: None,
+ bind_group: None,
+ cache_key: None,
+ failed_key: None,
+ ready: false,
+ }
+ }
+
+ pub fn prepare(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ notch: Option<NotchUniforms>,
+ ) {
+ self.ready = false;
+
+ let Some(notch) = notch else {
+ return;
+ };
+ if notch.composite.opacity <= 0.001 {
+ return;
+ }
+
+ let (tex_w, tex_h) = notch_shape::texture_size(notch.raster_size[0], notch.raster_size[1]);
+ let key = (tex_w, tex_h);
+
+ if self.failed_key == Some(key) {
+ return;
+ }
+
+ if self.cache_key != Some(key) {
+ let Some(rgba) = notch_shape::rasterize(tex_w, tex_h) else {
+ // Remember the failure so a bad size doesn't re-rasterize every
+ // frame; any size change retries.
+ self.failed_key = Some(key);
+ return;
+ };
+
+ if self.texture.as_ref().map(|t| (t.width(), t.height())) != Some(key) {
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Notch texture"),
+ size: wgpu::Extent3d {
+ width: tex_w,
+ height: tex_h,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ self.texture_view = Some(texture.create_view(&Default::default()));
+ self.texture = Some(texture);
+ self.bind_group = None;
+ }
+
+ if let Some(texture) = self.texture.as_ref() {
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ &rgba,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(4 * tex_w),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: tex_w,
+ height: tex_h,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+
+ self.failed_key = None;
+ self.cache_key = Some(key);
+ }
+
+ let Some(view) = self.texture_view.as_ref() else {
+ return;
+ };
+ if self.bind_group.is_none() {
+ self.bind_group = Some(
+ self.pipeline
+ .bind_group(device, &self.uniforms_buffer, view),
+ );
+ }
+
+ let mut composite = notch.composite;
+ composite.frame_size = [tex_w as f32, tex_h as f32];
+ composite.crop_bounds = [0.0, 0.0, tex_w as f32, tex_h as f32];
+ composite.write_to_buffer(queue, &self.uniforms_buffer);
+ self.ready = true;
+ }
+
+ pub fn has_content(&self) -> bool {
+ self.ready
+ }
+
+ pub fn render(&self, pass: &mut wgpu::RenderPass<'_>) {
+ let Some(bind_group) = self.bind_group.as_ref() else {
+ return;
+ };
+ if !self.ready {
+ return;
+ }
+
+ pass.set_pipeline(&self.pipeline.render_pipeline);
+ pass.set_bind_group(0, bind_group, &[]);
+ pass.draw(0..3, 0..1);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const OUTPUT: u32 = 256;
+ /// A notch spanning x 64..192 and y 0..48 of the output.
+ const BOUNDS: [f32; 4] = [64.0, 0.0, 192.0, 48.0];
+
+ fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
+ let instance = crate::create_wgpu_instance_sync();
+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::LowPower,
+ force_fallback_adapter: false,
+ compatible_surface: None,
+ }))
+ .ok()?;
+
+ pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()
+ }
+
+ fn uniforms() -> NotchUniforms {
+ NotchUniforms {
+ composite: CompositeVideoFrameUniforms {
+ output_size: [OUTPUT as f32, OUTPUT as f32],
+ target_bounds: BOUNDS,
+ target_size: [BOUNDS[2] - BOUNDS[0], BOUNDS[3] - BOUNDS[1]],
+ opacity: 1.0,
+ // The outline lives in the texture's alpha, so the SDF has to
+ // stay out of the way.
+ preserve_source_alpha: 1.0,
+ rounding_px: 0.0,
+ corner_radii: [0.0; 4],
+ ..Default::default()
+ },
+ raster_size: [
+ (BOUNDS[2] - BOUNDS[0]) as f64,
+ (BOUNDS[3] - BOUNDS[1]) as f64,
+ ],
+ }
+ }
+
+ /// Renders the notch over a white frame and returns the RGBA pixels.
+ fn render() -> Option<Vec<u8>> {
+ let (device, queue) = device()?;
+
+ let mut layer =
+ NotchLayer::new(&device, Arc::new(CompositeVideoFramePipeline::new(&device)));
+ layer.prepare(&device, &queue, Some(uniforms()));
+ assert!(layer.has_content());
+
+ let target = device.create_texture(&wgpu::TextureDescriptor {
+ label: None,
+ size: wgpu::Extent3d {
+ width: OUTPUT,
+ height: OUTPUT,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ });
+ let view = target.create_view(&Default::default());
+
+ let bytes_per_row = OUTPUT * 4;
+ let readback = device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size: (bytes_per_row * OUTPUT) as u64,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: None,
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::WHITE),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ layer.render(&mut pass);
+ }
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo {
+ texture: &target,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyBufferInfo {
+ buffer: &readback,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(bytes_per_row),
+ rows_per_image: Some(OUTPUT),
+ },
+ },
+ wgpu::Extent3d {
+ width: OUTPUT,
+ height: OUTPUT,
+ depth_or_array_layers: 1,
+ },
+ );
+ queue.submit([encoder.finish()]);
+
+ readback.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ device.poll(wgpu::PollType::Wait).ok()?;
+ let pixels = readback.slice(..).get_mapped_range().to_vec();
+ readback.unmap();
+
+ Some(pixels)
+ }
+
+ fn pixel(pixels: &[u8], x: u32, y: u32) -> [u8; 4] {
+ let i = ((y * OUTPUT + x) * 4) as usize;
+ [pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
+ }
+
+ fn is_black(p: [u8; 4]) -> bool {
+ p[0] < 16 && p[1] < 16 && p[2] < 16 && p[3] > 240
+ }
+
+ fn is_white(p: [u8; 4]) -> bool {
+ p[0] > 240 && p[1] > 240 && p[2] > 240
+ }
+
+ /// Number of solidly black pixels in a row, i.e. the notch's width there.
+ fn black_run(pixels: &[u8], y: u32) -> u32 {
+ (0..OUTPUT)
+ .filter(|x| is_black(pixel(pixels, *x, y)))
+ .count() as u32
+ }
+
+ #[test]
+ fn draws_an_opaque_notch_that_flares_at_the_top() {
+ let Some(pixels) = render() else {
+ eprintln!("no wgpu adapter available, skipping");
+ return;
+ };
+
+ let height = (BOUNDS[3] - BOUNDS[1]) as u32;
+
+ // Solid through the middle: the rasterized fill really is opaque black
+ // once composited, not a washed-out blend.
+ assert!(
+ is_black(pixel(&pixels, OUTPUT / 2, height / 2)),
+ "notch centre not black"
+ );
+
+ let wall = black_run(&pixels, height / 2);
+ // Row 0 straddles the top edge, so read the flare just inside it.
+ let top = black_run(&pixels, 1);
+ let bottom = black_run(&pixels, height - 1);
+
+ assert!(
+ top > wall,
+ "top should flare wider than the wall: {top} vs {wall}"
+ );
+ assert!(
+ bottom + 8 < wall,
+ "bottom should pull in from the wall: {bottom} vs {wall}"
+ );
+
+ // Nothing spills outside the notch.
+ assert_eq!(black_run(&pixels, height + 6), 0, "spilled below");
+ assert!(
+ is_white(pixel(&pixels, 10, height / 2)),
+ "spilled left of the notch"
+ );
+ assert!(
+ is_white(pixel(&pixels, OUTPUT - 10, height / 2)),
+ "spilled right of the notch"
+ );
+ }
+
+ #[test]
+ fn draws_nothing_when_there_is_no_notch() {
+ let Some((device, queue)) = device() else {
+ return;
+ };
+
+ let mut layer =
+ NotchLayer::new(&device, Arc::new(CompositeVideoFramePipeline::new(&device)));
+
+ layer.prepare(&device, &queue, None);
+ assert!(!layer.has_content());
+
+ let mut faded = uniforms();
+ faded.composite.opacity = 0.0;
+ layer.prepare(&device, &queue, Some(faded));
+ assert!(!layer.has_content());
+ }
+
+ /// Zoom scales the texture; it must not re-rasterize per frame.
+ #[test]
+ fn reuses_the_texture_while_the_unzoomed_size_holds() {
+ let Some((device, queue)) = device() else {
+ return;
+ };
+
+ let mut layer =
+ NotchLayer::new(&device, Arc::new(CompositeVideoFramePipeline::new(&device)));
+
+ let mut zoomed = uniforms();
+ layer.prepare(&device, &queue, Some(zoomed));
+ let first = layer.cache_key;
+
+ zoomed.composite.target_size = [512.0, 192.0];
+ layer.prepare(&device, &queue, Some(zoomed));
+
+ assert_eq!(layer.cache_key, first, "zoom should not re-rasterize");
+ }
+}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 3afbb1512..feb92c7fb 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -18,7 +18,7 @@ use frame_pipeline::{
use futures::future::OptionFuture;
use layers::{
Background, BackgroundLayer, BlurLayer, CameraLayer, CaptionsLayer, CursorLayer, DisplayLayer,
- FrameLayer, KeyboardLayer, MaskLayer, TextLayer,
+ FrameLayer, KeyboardLayer, MaskLayer, NotchLayer, NotchUniforms, TextLayer,
};
use specta::Type;
use spring_mass_damper::SpringMassDamperSimulationConfig;
@@ -42,6 +42,7 @@ mod frame_pipeline;
pub mod iosurface_texture;
mod layers;
mod mask;
+pub mod notch_shape;
mod project_recordings;
mod scene;
pub mod spring_mass_damper;
@@ -2244,6 +2245,9 @@ pub struct ProjectUniforms {
/// Decorative frame chrome around the display; `None` when no frame style
/// is active.
pub frame_chrome: Option<frame_chrome::FrameChromeUniforms>,
+ /// The recording device's physical notch, redrawn over the capture;
+ /// `None` when the overlay is off or the recording has no notch.
+ pub notch: Option<layers::NotchUniforms>,
/// Final placement of the outer display card (chrome included) in output
/// px. Equals `display.target_bounds` when no frame is active.
display_outer_bounds: [f32; 4],
@@ -2542,6 +2546,54 @@ const FLOATING_ROUNDING_FRAC: f32 = 0.028;
const SCREEN_MAX_PADDING: f64 = 0.4;
+/// Places a notch on the output frame, returning its bounds and size in output
+/// px, or `None` when the crop leaves nothing of it to draw.
+///
+/// The notch is part of the screen rather than decoration around it, so it goes
+/// through the same RawDisplaySpace -> zoomed frame space chain the cursor
+/// uses. Crop, padding, aspect fit and zoom all follow from that for free.
+fn notch_bounds(
+ notch: cap_project::DisplayNotch,
+ options: &RenderOptions,
+ project: &ProjectConfiguration,
+ resolution_base: XY<u32>,
+ zoom: &InterpolatedZoom,
+) -> Option<([f32; 4], [f32; 2])> {
+ let screen = options.screen_size.map(|v| v as f64);
+ let crop = ProjectUniforms::get_crop(options, project);
+ let crop_start = crop.position.map(|v| v as f64);
+ let crop_end = crop_start + crop.size.map(|v| v as f64);
+
+ let left = (notch.x * screen.x).max(crop_start.x);
+ let right = ((notch.x + notch.width) * screen.x).min(crop_end.x);
+ let top = crop_start.y.max(0.0);
+ let bottom = (notch.height * screen.y).min(crop_end.y);
+
+ if right <= left || bottom <= top {
+ return None;
+ }
+
+ let to_output = |p: XY<f64>| {
+ Coord::<RawDisplaySpace>::new(p)
+ .to_cropped_display_space(options, project)
+ .to_frame_space(options, project, resolution_base)
+ .to_zoomed_frame_space(options, project, resolution_base, zoom)
+ .coord
+ };
+
+ let start = to_output(XY::new(left, top));
+ let end = to_output(XY::new(right, bottom));
+ let size = [(end.x - start.x) as f32, (end.y - start.y) as f32];
+ if size[0] <= 0.0 || size[1] <= 0.0 {
+ return None;
+ }
+
+ Some((
+ [start.x as f32, start.y as f32, end.x as f32, end.y as f32],
+ size,
+ ))
+}
+
const MOTION_BLUR_BASELINE_FPS: f32 = 60.0;
/// Velocity is measured strictly against the previous frame (Screen Studio
/// samples frame f vs f-1); averaging over more frames lags peaks and lets
@@ -3387,7 +3439,7 @@ impl ProjectUniforms {
None
};
- let (display, display_motion_parent, frame_chrome, display_outer_bounds) = {
+ let (display, display_motion_parent, frame_chrome, display_outer_bounds, notch) = {
let output_size = XY::new(output_size.0 as f64, output_size.1 as f64);
let size = [options.screen_size.x as f32, options.screen_size.y as f32];
@@ -3593,6 +3645,59 @@ impl ProjectUniforms {
.map(|f| f.composite.target_bounds)
.unwrap_or(final_target_bounds);
+ let notch = project
+ .background
+ .notch
+ .and_then(|config| config.resolve(constants.meta.display_notch()))
+ .and_then(|notch| {
+ let (bounds, size) =
+ notch_bounds(notch, options, project, resolution_base, &zoom)?;
+ // Rasterize at the unzoomed size and let zoom scale the
+ // texture, so an animating zoom reuses one rasterization.
+ let (_, unzoomed) = notch_bounds(
+ notch,
+ options,
+ project,
+ resolution_base,
+ &InterpolatedZoom {
+ t: 0.0,
+ bounds: SegmentBounds::default(),
+ },
+ )?;
+
+ Some(NotchUniforms {
+ composite: CompositeVideoFrameUniforms {
+ output_size: [output_size.x as f32, output_size.y as f32],
+ target_bounds: bounds,
+ target_size: size,
+ // The outline is baked into the texture's alpha, so
+ // the SDF has to leave the edges alone.
+ preserve_source_alpha: 1.0,
+ rounding_px: 0.0,
+ corner_radii: [0.0; 4],
+ rounding_type: rounding_type_value(CornerStyle::Rounded),
+ mirror_x: 0.0,
+ motion_blur_vector: [0.0; 2],
+ motion_blur_zoom_center: [0.0; 2],
+ motion_blur_params: [0.0; 4],
+ shadow: 0.0,
+ shadow_size: 0.0,
+ shadow_opacity: 0.0,
+ shadow_blur: 0.0,
+ // Fades out as a split-screen scene morphs in, where
+ // the geometry above stops describing the pane.
+ opacity: scene.screen_opacity as f32 * split_fade,
+ border_enabled: 0.0,
+ border_width: 0.0,
+ _padding1: [0.0; 3],
+ border_color: [0.0; 4],
+ frame_size: [1.0, 1.0],
+ crop_bounds: [0.0, 0.0, 1.0, 1.0],
+ },
+ raster_size: [unzoomed[0] as f64, unzoomed[1] as f64],
+ })
+ });
+
(
CompositeVideoFrameUniforms {
output_size: [output_size.x as f32, output_size.y as f32],
@@ -3643,6 +3748,7 @@ impl ProjectUniforms {
display_parent_motion_px,
frame_chrome,
display_outer_bounds,
+ notch,
)
};
@@ -3973,6 +4079,7 @@ impl ProjectUniforms {
camera,
camera_only,
frame_chrome,
+ notch,
display_outer_bounds,
project: project.clone(),
zoom,
@@ -5048,6 +5155,7 @@ pub struct RendererLayers {
background_blur: BlurLayer,
frame: FrameLayer,
display: DisplayLayer,
+ notch: NotchLayer,
cursor: CursorLayer,
camera: CameraLayer,
camera_only: CameraLayer,
@@ -5077,6 +5185,7 @@ impl RendererLayers {
background: BackgroundLayer::new(device),
background_blur: BlurLayer::new(device),
frame: FrameLayer::new(device, shared_composite_pipeline.clone()),
+ notch: NotchLayer::new(device, shared_composite_pipeline.clone()),
display: DisplayLayer::new_with_all_shared_pipelines(
device,
shared_yuv_pipelines.clone(),
@@ -5240,6 +5349,8 @@ impl RendererLayers {
if render_display {
self.frame.prepare(constants, uniforms);
+ self.notch
+ .prepare(&constants.device, &constants.queue, uniforms.notch);
self.display.prepare(
&constants.device,
&constants.queue,
@@ -5382,6 +5493,8 @@ impl RendererLayers {
let start = Instant::now();
if render_display {
self.frame.prepare(constants, uniforms);
+ self.notch
+ .prepare(&constants.device, &constants.queue, uniforms.notch);
let display_ready = self.display.prepare_with_encoder(
&constants.device,
&constants.queue,
@@ -5573,6 +5686,13 @@ impl RendererLayers {
self.cursor.render(&mut pass);
}
+ // After the cursor, which really does disappear behind the notch on a
+ // Mac, but before masks and text, which are editor annotations.
+ if should_render_screen && self.notch.has_content() {
+ let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
+ self.notch.render(&mut pass);
+ }
+
// Render camera-only layer when transitioning with CameraOnly mode
if uniforms.scene.is_transitioning_camera_only() {
let mut pass = render_pass!(session.current_texture_view(), wgpu::LoadOp::Load);
@@ -5829,6 +5949,165 @@ pub fn create_shader_render_pipeline(
})
}
+#[cfg(test)]
+mod notch_bounds_tests {
+ use super::*;
+ use cap_project::{Crop, DisplayNotch, XY as ProjectXY};
+
+ /// 14" MacBook Pro panel and the notch measured on it.
+ const SCREEN: XY<u32> = XY { x: 3024, y: 1964 };
+ const NOTCH: DisplayNotch = DisplayNotch {
+ x: 0.438_492_063_492_063_5,
+ width: 0.122_354_497_354_497_35,
+ height: 0.032_586_558_044_806_514,
+ };
+
+ fn options() -> RenderOptions {
+ RenderOptions {
+ screen_size: SCREEN,
+ camera_size: None,
+ preserve_screen_alpha: false,
+ }
+ }
+
+ fn place(
+ project: &ProjectConfiguration,
+ zoom: &InterpolatedZoom,
+ ) -> Option<([f32; 4], [f32; 2])> {
+ notch_bounds(NOTCH, &options(), project, SCREEN, zoom)
+ }
+
+ fn no_zoom() -> InterpolatedZoom {
+ InterpolatedZoom {
+ t: 0.0,
+ bounds: SegmentBounds::default(),
+ }
+ }
+
+ #[test]
+ fn sits_flush_against_the_top_of_the_screen() {
+ let project = ProjectConfiguration::default();
+ let (bounds, size) = place(&project, &no_zoom()).unwrap();
+
+ let display_offset = ProjectUniforms::display_offset(&options(), &project, SCREEN);
+ assert!(
+ (bounds[1] as f64 - display_offset.coord.y).abs() < 1e-3,
+ "notch top {} should meet the display top {}",
+ bounds[1],
+ display_offset.coord.y
+ );
+ assert!(size[0] > 0.0 && size[1] > 0.0);
+ }
+
+ #[test]
+ fn is_horizontally_centred_on_the_display() {
+ let project = ProjectConfiguration::default();
+ let (bounds, _) = place(&project, &no_zoom()).unwrap();
+
+ let display_offset = ProjectUniforms::display_offset(&options(), &project, SCREEN);
+ let display_size = ProjectUniforms::display_size(&options(), &project, SCREEN);
+
+ let notch_centre = (bounds[0] + bounds[2]) as f64 / 2.0;
+ let display_centre = display_offset.coord.x + display_size.coord.x / 2.0;
+
+ // The measured notch is half a point off-centre on a 1512pt panel.
+ assert!(
+ (notch_centre - display_centre).abs() < 2.0,
+ "notch centre {notch_centre} vs display centre {display_centre}"
+ );
+ }
+
+ #[test]
+ fn keeps_its_proportions_relative_to_the_display() {
+ let project = ProjectConfiguration::default();
+ let (_, size) = place(&project, &no_zoom()).unwrap();
+ let display_size = ProjectUniforms::display_size(&options(), &project, SCREEN);
+
+ let width_frac = size[0] as f64 / display_size.coord.x;
+ let height_frac = size[1] as f64 / display_size.coord.y;
+
+ assert!((width_frac - NOTCH.width).abs() < 1e-3, "{width_frac}");
+ assert!((height_frac - NOTCH.height).abs() < 1e-3, "{height_frac}");
+ }
+
+ #[test]
+ fn scales_and_translates_with_zoom() {
+ let project = ProjectConfiguration::default();
+ let (unzoomed, unzoomed_size) = place(&project, &no_zoom()).unwrap();
+
+ let zoom = InterpolatedZoom {
+ t: 1.0,
+ bounds: SegmentBounds::from_amount_center(2.0, ProjectXY::new(0.5, 0.5)),
+ };
+ let (zoomed, zoomed_size) = place(&project, &zoom).unwrap();
+
+ assert!(
+ zoomed_size[0] > unzoomed_size[0] * 1.9,
+ "2x zoom should roughly double the notch width: {} -> {}",
+ unzoomed_size[0],
+ zoomed_size[0]
+ );
+ assert!(
+ zoomed[1] < unzoomed[1],
+ "zooming into the centre should push the top edge off-frame"
+ );
+ }
+
+ #[test]
+ fn travels_off_frame_when_zoomed_into_the_bottom_right() {
+ let project = ProjectConfiguration::default();
+ let zoom = InterpolatedZoom {
+ t: 1.0,
+ bounds: SegmentBounds::from_amount_center(3.0, ProjectXY::new(1.0, 1.0)),
+ };
+
+ let (bounds, _) = place(&project, &zoom).unwrap();
+ let output = ProjectUniforms::get_output_size(&options(), &project, SCREEN);
+
+ assert!(
+ bounds[3] < 0.0 || bounds[0] > output.0 as f32,
+ "notch should leave the frame entirely, got {bounds:?}"
+ );
+ }
+
+ #[test]
+ fn disappears_when_the_crop_excludes_the_top_of_the_screen() {
+ let mut project = ProjectConfiguration::default();
+ project.background.crop = Some(Crop {
+ position: ProjectXY::new(0, SCREEN.y / 2),
+ size: ProjectXY::new(SCREEN.x, SCREEN.y / 2),
+ });
+
+ assert_eq!(place(&project, &no_zoom()), None);
+ }
+
+ #[test]
+ fn survives_a_crop_that_keeps_the_top_of_the_screen() {
+ let mut project = ProjectConfiguration::default();
+ project.background.crop = Some(Crop {
+ position: ProjectXY::new(0, 0),
+ size: ProjectXY::new(SCREEN.x, SCREEN.y / 2),
+ });
+
+ let (_, size) = place(&project, &no_zoom()).expect("notch is still visible");
+ assert!(size[0] > 0.0 && size[1] > 0.0);
+ }
+
+ #[test]
+ fn padding_shrinks_the_notch_with_the_display() {
+ let mut project = ProjectConfiguration::default();
+ let (_, unpadded) = place(&project, &no_zoom()).unwrap();
+
+ project.background.padding = 40.0;
+ let (_, padded) = place(&project, &no_zoom()).unwrap();
+
+ assert!(
+ padded[0] < unpadded[0],
+ "padded notch {padded:?} should be narrower than {unpadded:?}"
+ );
+ }
+}
+
#[cfg(test)]
mod project_uniforms_tests {
use super::*;
diff --git a/crates/rendering/src/notch_shape.rs b/crates/rendering/src/notch_shape.rs
new file mode 100644
index 000000000..39b2e573f
--- /dev/null
+++ b/crates/rendering/src/notch_shape.rs
@@ -0,0 +1,164 @@
+//! Outline of a MacBook's camera housing, rasterized for the notch overlay.
+//!
+//! A vector path rather than the composite pipeline's SDF because the upper
+//! corners are *concave* — the cutout widens as it meets the top of the panel,
+//! flaring into the bezel — and `sdf_rounded_rect` only does convex corners.
+
+/// Both radii as fractions of the notch's height, measured off a 14" panel:
+/// ~7.9pt and ~2.4pt on a 32pt-tall cutout.
+pub const BOTTOM_RADIUS_FRAC: f64 = 0.25;
+pub const TOP_FILLET_FRAC: f64 = 0.075;
+
+/// Rasterize above display size so the curves survive being scaled up by zoom.
+/// Higher than the frame chrome's factor because a thin band shows softening
+/// far sooner than a full window frame does.
+const SUPERSAMPLE: f64 = 8.0;
+const MAX_TEXTURE_DIM: f64 = 4096.0;
+
+/// Texture size to rasterize a notch of `w` x `h` output px into.
+pub fn texture_size(w: f64, h: f64) -> (u32, u32) {
+ let scale = (MAX_TEXTURE_DIM / w.max(1.0))
+ .min(MAX_TEXTURE_DIM / h.max(1.0))
+ .min(SUPERSAMPLE);
+ let tw = ((w * scale).round() as u32).clamp(8, MAX_TEXTURE_DIM as u32);
+ let th = ((h * scale).round() as u32).clamp(8, MAX_TEXTURE_DIM as u32);
+ (tw, th)
+}
+
+/// The notch outline, filling a `w` x `h` box, widest along its top edge.
+fn notch_svg(w: f64, h: f64) -> String {
+ // Bounded so a short or narrow notch degrades into a plain rectangle
+ // instead of self-intersecting.
+ let fillet = (h * TOP_FILLET_FRAC).min(w / 2.0).max(0.0);
+ let bottom = (h * BOTTOM_RADIUS_FRAC)
+ .min(h - fillet)
+ .min(w / 2.0 - fillet)
+ .max(0.0);
+
+ let path = format!(
+ "M 0 0 \
+ A {fillet} {fillet} 0 0 1 {fillet} {fillet} \
+ L {fillet} {bottom_y} \
+ A {bottom} {bottom} 0 0 0 {bl_x} {h} \
+ L {br_x} {h} \
+ A {bottom} {bottom} 0 0 0 {right_wall} {bottom_y} \
+ L {right_wall} {fillet} \
+ A {fillet} {fillet} 0 0 1 {w} 0 Z",
+ bottom_y = h - bottom,
+ bl_x = fillet + bottom,
+ br_x = w - fillet - bottom,
+ right_wall = w - fillet,
+ );
+
+ format!(
+ r##"<svg width="{w}" height="{h}" viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg"><path d="{path}" fill="#000000"/></svg>"##
+ )
+}
+
+/// RGBA pixels for the notch outline, or `None` if rasterization fails, which
+/// makes the layer skip drawing rather than erroring the whole frame.
+pub fn rasterize(tex_w: u32, tex_h: u32) -> Option<Vec<u8>> {
+ let svg = notch_svg(tex_w as f64, tex_h as f64);
+
+ let tree = match resvg::usvg::Tree::from_str(&svg, &resvg::usvg::Options::default()) {
+ Ok(tree) => tree,
+ Err(error) => {
+ tracing::warn!("Failed to parse notch SVG: {error}");
+ return None;
+ }
+ };
+
+ let mut pixmap = tiny_skia::Pixmap::new(tex_w, tex_h)?;
+ resvg::render(
+ &tree,
+ tiny_skia::Transform::identity(),
+ &mut pixmap.as_mut(),
+ );
+
+ Some(
+ pixmap
+ .pixels()
+ .iter()
+ .flat_map(|p| {
+ let c = p.demultiply();
+ [c.red(), c.green(), c.blue(), c.alpha()]
+ })
+ .collect(),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const W: u32 = 256;
+ const H: u32 = 64;
+
+ fn alpha_at(pixels: &[u8], x: u32, y: u32) -> u8 {
+ pixels[((y * W + x) * 4 + 3) as usize]
+ }
+
+ /// Opaque pixels in a row, i.e. how wide the notch is there.
+ fn run(pixels: &[u8], y: u32) -> u32 {
+ (0..W).filter(|x| alpha_at(pixels, *x, y) > 200).count() as u32
+ }
+
+ #[test]
+ fn widens_towards_the_top_and_narrows_at_the_bottom() {
+ let pixels = rasterize(W, H).expect("notch should rasterize");
+
+ let fillet = (H as f64 * TOP_FILLET_FRAC).round() as u32;
+ let wall = run(&pixels, H / 2);
+
+ // The straight flanks sit a fillet's width in from each edge.
+ assert!(
+ wall + 2 * fillet <= W && wall + 2 * fillet + 4 >= W,
+ "wall {wall} should sit about {fillet}px in from each edge of {W}"
+ );
+
+ // Concave top: the notch is at its widest on the very first row and
+ // narrows to the wall, rather than rounding inwards like the bottom.
+ let top = run(&pixels, 0);
+ assert!(
+ top > wall,
+ "top row {top} should flare past the wall {wall}"
+ );
+ assert!(
+ (0..H).all(|y| run(&pixels, y) <= top),
+ "no row should be wider than the top edge"
+ );
+ assert!(
+ run(&pixels, fillet + 1) == wall,
+ "the flare should be spent by the time the fillet ends"
+ );
+
+ // Convex bottom, pulling in from the wall on a much larger radius.
+ let bottom = run(&pixels, H - 1);
+ assert!(
+ bottom + 8 < wall,
+ "bottom row {bottom} should be clearly narrower than the wall {wall}"
+ );
+ assert!(
+ wall - bottom > top - wall,
+ "the bottom radius should be the more pronounced of the two"
+ );
+ }
+
+ #[test]
+ fn degenerate_sizes_still_rasterize() {
+ for (w, h) in [(8, 8), (256, 4), (4, 64), (1024, 32)] {
+ assert!(rasterize(w, h).is_some(), "{w}x{h} should rasterize");
+ }
+ }
+
+ #[test]
+ fn texture_size_supersamples_within_the_cap() {
+ // A notch on a 1080p export, comfortably inside the cap.
+ assert_eq!(texture_size(260.0, 21.0), (2080, 168));
+
+ // A 4K one is clamped, and keeps its aspect while clamping.
+ let (w, h) = texture_size(520.0, 42.0);
+ assert!(w <= MAX_TEXTURE_DIM as u32 && h <= MAX_TEXTURE_DIM as u32);
+ assert!((w as f64 / h as f64 - 520.0 / 42.0).abs() < 0.1);
+ }
+}
diff --git a/crates/scap-targets/src/lib.rs b/crates/scap-targets/src/lib.rs
index 7a7422905..34a085f18 100644
--- a/crates/scap-targets/src/lib.rs
+++ b/crates/scap-targets/src/lib.rs
@@ -52,6 +52,30 @@ impl Display {
pub fn refresh_rate(&self) -> f64 {
self.0.refresh_rate()
}
+
+ pub fn notch(&self) -> Option<NotchGeometry> {
+ #[cfg(target_os = "macos")]
+ {
+ self.0.notch()
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ {
+ None
+ }
+ }
+}
+
+/// Geometry of the camera housing ("notch") on a built-in MacBook display, as
+/// fractions of that display's size. Fractions rather than points so the values
+/// survive scaled display modes and the logical-to-physical step between
+/// capture and playback.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct NotchGeometry {
+ /// Distance from the left edge of the display to the notch.
+ pub x: f64,
+ pub width: f64,
+ pub height: f64,
}
#[derive(Serialize, Deserialize, Type, Clone, PartialEq, Debug)]
@@ -233,6 +257,32 @@ impl FromStr for WindowId {
}
}
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn notch_geometry_is_within_the_display() {
+ for display in Display::list() {
+ let Some(notch) = display.notch() else {
+ continue;
+ };
+
+ assert!(notch.width > 0.0 && notch.height > 0.0, "{notch:?}");
+ assert!(notch.x > 0.0 && notch.x + notch.width < 1.0, "{notch:?}");
+ assert!(notch.height < 0.5, "{notch:?}");
+
+ println!("{:?}: {notch:?}", display.name());
+ }
+ }
+
+ #[cfg(not(target_os = "macos"))]
+ #[test]
+ fn no_notch_off_macos() {
+ assert!(Display::list().iter().all(|d| d.notch().is_none()));
+ }
+}
+
mod serde_window_id {
use serde::{Deserialize, Deserializer, Serializer};
diff --git a/crates/scap-targets/src/platform/macos.rs b/crates/scap-targets/src/platform/macos.rs
index a9a8183dd..df961872e 100644
--- a/crates/scap-targets/src/platform/macos.rs
+++ b/crates/scap-targets/src/platform/macos.rs
@@ -19,6 +19,7 @@ use core_graphics::{
},
};
+use crate::NotchGeometry;
use crate::bounds::{LogicalBounds, LogicalPosition, LogicalSize, PhysicalSize};
#[derive(Clone, Copy)]
@@ -157,6 +158,45 @@ impl DisplayImpl {
})
}
+ pub fn notch(&self) -> Option<NotchGeometry> {
+ use cocoa::appkit::NSScreen;
+ use cocoa::foundation::NSRect;
+ use objc::runtime::YES;
+ use objc::{msg_send, *};
+
+ objc::rc::autoreleasepool(|| unsafe {
+ let screen = self.as_ns_screen()?;
+
+ let responds: runtime::BOOL =
+ msg_send![screen, respondsToSelector: sel!(auxiliaryTopLeftArea)];
+ if responds != YES {
+ return None;
+ }
+
+ let frame = NSScreen::frame(screen);
+ if frame.size.width <= 0.0 || frame.size.height <= 0.0 {
+ return None;
+ }
+
+ let left: NSRect = msg_send![screen, auxiliaryTopLeftArea];
+ let right: NSRect = msg_send![screen, auxiliaryTopRightArea];
+
+ // Both auxiliary rects are NSZeroRect on displays with no camera
+ // housing, which makes `height` zero and rejects them below.
+ let width = frame.size.width - left.size.width - right.size.width;
+ let height = left.size.height;
+ if width <= 0.0 || height <= 0.0 {
+ return None;
+ }
+
+ Some(NotchGeometry {
+ x: left.size.width / frame.size.width,
+ width: width / frame.size.width,
+ height: height / frame.size.height,
+ })
+ })
+ }
+
fn as_ns_screen(&self) -> Option<*mut objc::runtime::Object> {
use cocoa::appkit::NSScreen;
use cocoa::base::{id, nil};