Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: Implement resolution picker setting for Instant Mode (#1258)

Richie McIlroy466ab591a520
diff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rs
index d2c3bfaae..7bc7d3e71 100644
--- a/apps/desktop/src-tauri/src/general_settings.rs
+++ b/apps/desktop/src-tauri/src/general_settings.rs
@@ -120,6 +120,8 @@ pub struct GeneralSettingsStore {
pub excluded_windows: Vec<WindowExclusion>,
#[serde(default)]
pub delete_instant_recordings_after_upload: bool,
+ #[serde(default = "default_instant_mode_max_resolution")]
+ pub instant_mode_max_resolution: u32,
}
fn default_enable_native_camera_preview() -> bool {
@@ -139,6 +141,10 @@ fn default_true() -> bool {
true
}
+fn default_instant_mode_max_resolution() -> u32 {
+ 1920
+}
+
fn default_server_url() -> String {
std::option_env!("VITE_SERVER_URL")
.unwrap_or("https://cap.so")
@@ -180,6 +186,7 @@ impl Default for GeneralSettingsStore {
post_deletion_behaviour: PostDeletionBehaviour::DoNothing,
excluded_windows: default_excluded_windows(),
delete_instant_recordings_after_upload: false,
+ instant_mode_max_resolution: 1920,
}
}
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 9c8c11195..10b136e55 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -466,6 +466,7 @@ pub async fn start_recording(
Err(SendError::HandlerError(camera::LockFeedError::NoInput)) => None,
Err(e) => return Err(e.to_string()),
};
+
#[cfg(target_os = "macos")]
let shareable_content = crate::platform::get_shareable_content()
.await
@@ -537,7 +538,13 @@ pub async fn start_recording(
recording_dir.clone(),
inputs.capture_target.clone(),
)
- .with_system_audio(inputs.capture_system_audio);
+ .with_system_audio(inputs.capture_system_audio)
+ .with_max_output_size(
+ general_settings
+ .as_ref()
+ .map(|settings| settings.instant_mode_max_resolution)
+ .unwrap_or_else(|| 1920),
+ );
#[cfg(target_os = "macos")]
{
diff --git a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
index c1b147516..868fb762f 100644
--- a/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
+++ b/apps/desktop/src/routes/(window-chrome)/settings/general.tsx
@@ -61,7 +61,9 @@ const getWindowOptionLabel = (window: CaptureWindow) => {
return parts.join(" • ");
};
-const createDefaultGeneralSettings = (): GeneralSettingsStore => ({
+type ExtendedGeneralSettingsStore = GeneralSettingsStore;
+
+const createDefaultGeneralSettings = (): ExtendedGeneralSettingsStore => ({
uploadIndividualFiles: false,
hideDockIcon: false,
autoCreateShareableLink: false,
@@ -71,11 +73,12 @@ const createDefaultGeneralSettings = (): GeneralSettingsStore => ({
autoZoomOnClicks: false,
custom_cursor_capture2: true,
excludedWindows: [],
+ instantModeMaxResolution: 1920,
});
const deriveInitialSettings = (
store: GeneralSettingsStore | null,
-): GeneralSettingsStore => {
+): ExtendedGeneralSettingsStore => {
const defaults = createDefaultGeneralSettings();
if (!store) return defaults;
@@ -85,6 +88,16 @@ const deriveInitialSettings = (
};
};
+const INSTANT_MODE_RESOLUTION_OPTIONS = [
+ { value: 1280, label: "720p" },
+ { value: 1920, label: "1080p" },
+ { value: 2560, label: "1440p" },
+ { value: 3840, label: "4K" },
+] satisfies {
+ value: number;
+ label: string;
+}[];
+
export default function GeneralSettings() {
const [store] = createResource(() => generalSettingsStore.get());
@@ -167,7 +180,7 @@ function AppearanceSection(props: {
}
function Inner(props: { initialStore: GeneralSettingsStore | null }) {
- const [settings, setSettings] = createStore<GeneralSettingsStore>(
+ const [settings, setSettings] = createStore<ExtendedGeneralSettingsStore>(
deriveInitialSettings(props.initialStore),
);
@@ -417,13 +430,23 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
)}
<SettingGroup title="Recording">
+ <SelectSettingItem
+ label="Instant mode max resolution"
+ description="Choose the maximum resolution for Instant Mode recordings."
+ value={settings.instantModeMaxResolution ?? 1920}
+ onChange={(value) =>
+ handleChange("instantModeMaxResolution", value)
+ }
+ options={INSTANT_MODE_RESOLUTION_OPTIONS.map((option) => ({
+ text: option.label,
+ value: option.value,
+ }))}
+ />
<SelectSettingItem
label="Recording countdown"
description="Countdown before recording starts"
value={settings.recordingCountdown ?? 0}
- onChange={(value) =>
- handleChange("recordingCountdown", value as number)
- }
+ onChange={(value) => handleChange("recordingCountdown", value)}
options={[
{ text: "Off", value: 0 },
{ text: "3 seconds", value: 3 },
@@ -436,10 +459,7 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
description="The main window recording start behaviour"
value={settings.mainWindowRecordingStartBehaviour ?? "close"}
onChange={(value) =>
- handleChange(
- "mainWindowRecordingStartBehaviour",
- value as MainWindowRecordingStartBehaviour,
- )
+ handleChange("mainWindowRecordingStartBehaviour", value)
}
options={[
{ text: "Close", value: "close" },
@@ -451,10 +471,7 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
description="The studio recording finish behaviour"
value={settings.postStudioRecordingBehaviour ?? "openEditor"}
onChange={(value) =>
- handleChange(
- "postStudioRecordingBehaviour",
- value as PostStudioRecordingBehaviour,
- )
+ handleChange("postStudioRecordingBehaviour", value)
}
options={[
{ text: "Open editor", value: "openEditor" },
@@ -468,12 +485,7 @@ function Inner(props: { initialStore: GeneralSettingsStore | null }) {
label="After deleting recording behaviour"
description="Should Cap reopen after deleting an in progress recording?"
value={settings.postDeletionBehaviour ?? "doNothing"}
- onChange={(value) =>
- handleChange(
- "postDeletionBehaviour",
- value as PostDeletionBehaviour,
- )
- }
+ onChange={(value) => handleChange("postDeletionBehaviour", value)}
options={[
{ text: "Do Nothing", value: "doNothing" },
{
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index b522ed568..2fcc5423d 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -393,7 +393,7 @@ export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ format
export type FileType = "recording" | "screenshot"
export type Flags = { captions: boolean }
export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }
-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: 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; enableNewRecordingFlow: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean }
+export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: 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; enableNewRecordingFlow: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number }
export type GifExportSettings = { fps: number; resolution_base: XY<number>; quality: GifQuality | null }
export type GifQuality = {
/**
diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rs
index 08c614ebc..62b49adfd 100644
--- a/crates/enc-ffmpeg/src/video/h264.rs
+++ b/crates/enc-ffmpeg/src/video/h264.rs
@@ -12,10 +12,18 @@ use tracing::{debug, error};
use crate::base::EncoderBase;
+fn is_420(format: ffmpeg::format::Pixel) -> bool {
+ format
+ .descriptor()
+ .map(|desc| desc.log2_chroma_w() == 1 && desc.log2_chroma_h() == 1)
+ .unwrap_or(false)
+}
+
pub struct H264EncoderBuilder {
bpp: f32,
input_config: VideoInfo,
preset: H264Preset,
+ output_size: Option<(u32, u32)>,
}
#[derive(Clone, Copy)]
@@ -33,6 +41,8 @@ pub enum H264EncoderError {
CodecNotFound,
#[error("Pixel format {0:?} not supported")]
PixFmtNotSupported(Pixel),
+ #[error("Invalid output dimensions {width}x{height}; expected non-zero even width and height")]
+ InvalidOutputDimensions { width: u32, height: u32 },
}
impl H264EncoderBuilder {
@@ -43,6 +53,7 @@ impl H264EncoderBuilder {
input_config,
bpp: Self::QUALITY_BPP,
preset: H264Preset::Ultrafast,
+ output_size: None,
}
}
@@ -56,45 +67,106 @@ impl H264EncoderBuilder {
self
}
+ pub fn with_output_size(mut self, width: u32, height: u32) -> Result<Self, H264EncoderError> {
+ if width == 0 || height == 0 {
+ return Err(H264EncoderError::InvalidOutputDimensions { width, height });
+ }
+
+ self.output_size = Some((width, height));
+ Ok(self)
+ }
+
pub fn build(
self,
output: &mut format::context::Output,
) -> Result<H264Encoder, H264EncoderError> {
- let input_config = &self.input_config;
- let (codec, encoder_options) = get_codec_and_options(input_config, self.preset)
+ let input_config = self.input_config;
+ let (codec, encoder_options) = get_codec_and_options(&input_config, self.preset)
.ok_or(H264EncoderError::CodecNotFound)?;
- let (format, converter) = if !codec
+ let (output_width, output_height) = self
+ .output_size
+ .unwrap_or((input_config.width, input_config.height));
+
+ if output_width == 0 || output_height == 0 {
+ return Err(H264EncoderError::InvalidOutputDimensions {
+ width: output_width,
+ height: output_height,
+ });
+ }
+
+ let encoder_supports_input_format = codec
.video()
- .unwrap()
- .formats()
- .unwrap()
- .any(|f| f == input_config.pixel_format)
- {
+ .ok()
+ .and_then(|codec_video| codec_video.formats())
+ .map_or(false, |mut formats| {
+ formats.any(|f| f == input_config.pixel_format)
+ });
+
+ let mut needs_pixel_conversion = false;
+
+ let output_format = if encoder_supports_input_format {
+ input_config.pixel_format
+ } else {
+ needs_pixel_conversion = true;
let format = ffmpeg::format::Pixel::NV12;
debug!(
"Converting from {:?} to {:?} for H264 encoding",
input_config.pixel_format, format
);
- (
- format,
- Some(
- ffmpeg::software::converter(
- (input_config.width, input_config.height),
- input_config.pixel_format,
- format,
- )
- .map_err(|e| {
+ format
+ };
+
+ if is_420(output_format) && (output_width % 2 != 0 || output_height % 2 != 0) {
+ return Err(H264EncoderError::InvalidOutputDimensions {
+ width: output_width,
+ height: output_height,
+ });
+ }
+
+ let needs_scaling =
+ output_width != input_config.width || output_height != input_config.height;
+
+ if needs_scaling {
+ debug!(
+ "Scaling video frames for H264 encoding from {}x{} to {}x{}",
+ input_config.width, input_config.height, output_width, output_height
+ );
+ }
+
+ let converter = if needs_pixel_conversion || needs_scaling {
+ let flags = if needs_scaling {
+ ffmpeg::software::scaling::flag::Flags::BICUBIC
+ } else {
+ ffmpeg::software::scaling::flag::Flags::FAST_BILINEAR
+ };
+
+ match ffmpeg::software::scaling::Context::get(
+ input_config.pixel_format,
+ input_config.width,
+ input_config.height,
+ output_format,
+ output_width,
+ output_height,
+ flags,
+ ) {
+ Ok(context) => Some(context),
+ Err(e) => {
+ if needs_pixel_conversion {
error!(
- "Failed to create converter from {:?} to NV12: {:?}",
- input_config.pixel_format, e
+ "Failed to create converter from {:?} to {:?}: {:?}",
+ input_config.pixel_format, output_format, e
);
- H264EncoderError::PixFmtNotSupported(input_config.pixel_format)
- })?,
- ),
- )
+ return Err(H264EncoderError::PixFmtNotSupported(
+ input_config.pixel_format,
+ ));
+ }
+
+ return Err(H264EncoderError::FFmpeg(e));
+ }
+ }
} else {
- (input_config.pixel_format, None)
+ None
};
let mut encoder_ctx = context::Context::new_with_codec(codec);
@@ -105,16 +177,16 @@ impl H264EncoderBuilder {
encoder_ctx.set_threading(Config::count(thread_count));
let mut encoder = encoder_ctx.encoder().video()?;
- encoder.set_width(input_config.width);
- encoder.set_height(input_config.height);
- encoder.set_format(format);
+ encoder.set_width(output_width);
+ encoder.set_height(output_height);
+ encoder.set_format(output_format);
encoder.set_time_base(input_config.time_base);
encoder.set_frame_rate(Some(input_config.frame_rate));
// let target_bitrate = compression.bitrate();
let bitrate = get_bitrate(
- input_config.width,
- input_config.height,
+ output_width,
+ output_height,
input_config.frame_rate.0 as f32 / input_config.frame_rate.1 as f32,
self.bpp,
);
@@ -133,8 +205,10 @@ impl H264EncoderBuilder {
Ok(H264Encoder {
base: EncoderBase::new(stream_index),
encoder,
- config: self.input_config,
converter,
+ output_format,
+ output_width,
+ output_height,
})
}
}
@@ -142,8 +216,10 @@ impl H264EncoderBuilder {
pub struct H264Encoder {
base: EncoderBase,
encoder: encoder::Video,
- config: VideoInfo,
converter: Option<ffmpeg::software::scaling::Context>,
+ output_format: format::Pixel,
+ output_width: u32,
+ output_height: u32,
}
#[derive(thiserror::Error, Debug)]
@@ -170,16 +246,16 @@ impl H264Encoder {
self.base
.update_pts(&mut frame, timestamp, &mut self.encoder);
- let frame = if let Some(converter) = &mut self.converter {
- let mut new_frame = frame::Video::empty();
+ if let Some(converter) = &mut self.converter {
+ let pts = frame.pts();
+ let mut converted =
+ frame::Video::new(self.output_format, self.output_width, self.output_height);
converter
- .run(&frame, &mut new_frame)
+ .run(&frame, &mut converted)
.map_err(QueueFrameError::Converter)?;
- new_frame.set_pts(frame.pts());
- new_frame
- } else {
- frame
- };
+ converted.set_pts(pts);
+ frame = converted;
+ }
self.base
.send_frame(&frame, output, &mut self.encoder)
@@ -250,8 +326,9 @@ fn get_codec_and_options(
fn get_bitrate(width: u32, height: u32, frame_rate: f32, bpp: f32) -> usize {
// higher frame rates don't really need double the bitrate lets be real
- let frame_rate_multiplier = (frame_rate - 30.0).max(0.0) * 0.6 + 30.0;
- let pixels_per_second = (width * height) as f32 * frame_rate_multiplier;
+ let frame_rate_multiplier = ((frame_rate as f64 - 30.0).max(0.0) * 0.6) + 30.0;
+ let area = (width as f64) * (height as f64);
+ let pixels_per_second = area * frame_rate_multiplier;
- (pixels_per_second * bpp) as usize
+ (pixels_per_second * bpp as f64) as usize
}
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index b448f7b00..b9f372e73 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -6,7 +6,6 @@ use crate::{
};
use anyhow::anyhow;
use cap_timestamp::Timestamps;
-use scap_targets::bounds::LogicalBounds;
use std::{path::PathBuf, sync::Arc};
pub trait MakeCapturePipeline: ScreenCaptureFormat + std::fmt::Debug + 'static {
@@ -23,6 +22,7 @@ pub trait MakeCapturePipeline: ScreenCaptureFormat + std::fmt::Debug + 'static {
system_audio: Option<screen_capture::SystemAudioSourceConfig>,
mic_feed: Option<Arc<MicrophoneFeedLock>>,
output_path: PathBuf,
+ output_resolution: (u32, u32),
) -> anyhow::Result<OutputPipeline>
where
Self: Sized;
@@ -49,6 +49,7 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {
system_audio: Option<screen_capture::SystemAudioSourceConfig>,
mic_feed: Option<Arc<MicrophoneFeedLock>>,
output_path: PathBuf,
+ output_resolution: (u32, u32),
) -> anyhow::Result<OutputPipeline> {
let mut output = OutputPipeline::builder(output_path.clone())
.with_video::<screen_capture::VideoSource>(screen_capture);
@@ -63,7 +64,7 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {
output
.build::<AVFoundationMp4Muxer>(AVFoundationMp4MuxerConfig {
- output_height: Some(1080),
+ output_height: Some(output_resolution.1),
})
.await
}
@@ -84,8 +85,9 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {
.build::<WindowsMuxer>(WindowsMuxerConfig {
pixel_format: screen_capture::Direct3DCapture::PIXEL_FORMAT.as_dxgi(),
d3d_device,
- bitrate_multiplier: 0.1f32,
+ bitrate_multiplier: 0.15f32,
frame_rate: 30u32,
+ output_size: None,
})
.await
}
@@ -95,6 +97,7 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {
system_audio: Option<screen_capture::SystemAudioSourceConfig>,
mic_feed: Option<Arc<MicrophoneFeedLock>>,
output_path: PathBuf,
+ output_resolution: (u32, u32),
) -> anyhow::Result<OutputPipeline> {
let d3d_device = screen_capture.d3d_device.clone();
let mut output_builder = OutputPipeline::builder(output_path.clone())
@@ -112,9 +115,13 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {
output_builder
.build::<WindowsMuxer>(WindowsMuxerConfig {
pixel_format: screen_capture::Direct3DCapture::PIXEL_FORMAT.as_dxgi(),
- bitrate_multiplier: 0.08f32,
+ bitrate_multiplier: 0.15f32,
frame_rate: 30u32,
d3d_device,
+ output_size: Some(windows::Graphics::SizeInt32 {
+ Width: output_resolution.0 as i32,
+ Height: output_resolution.1 as i32,
+ }),
})
.await
}
diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rs
index 3ac2bd3d4..ae3258919 100644
--- a/crates/recording/src/instant_recording.rs
+++ b/crates/recording/src/instant_recording.rs
@@ -22,6 +22,7 @@ use tracing::*;
struct Pipeline {
output: OutputPipeline,
+ video_info: VideoInfo,
}
enum ActorState {
@@ -192,6 +193,7 @@ async fn create_pipeline(
output_path: PathBuf,
screen_source: ScreenCaptureConfig<ScreenCaptureMethod>,
mic_feed: Option<Arc<MicrophoneFeedLock>>,
+ max_output_size: Option<u32>,
) -> anyhow::Result<Pipeline> {
if let Some(mic_feed) = &mic_feed {
debug!(
@@ -200,6 +202,20 @@ async fn create_pipeline(
);
};
+ let screen_info = screen_source.info();
+
+ let output_resolution = max_output_size
+ .map(|max_output_size| {
+ clamp_size(
+ (screen_info.width, screen_info.height),
+ (
+ max_output_size,
+ (max_output_size as f64 / 16.0 * 9.0) as u32,
+ ),
+ )
+ })
+ .unwrap_or((screen_info.width, screen_info.height));
+
let (screen_capture, system_audio) = screen_source.to_sources().await?;
let output = ScreenCaptureMethod::make_instant_mode_pipeline(
@@ -207,10 +223,19 @@ async fn create_pipeline(
system_audio,
mic_feed,
output_path.clone(),
+ output_resolution,
)
.await?;
- Ok(Pipeline { output })
+ Ok(Pipeline {
+ output,
+ video_info: VideoInfo::from_raw_ffmpeg(
+ screen_info.pixel_format,
+ output_resolution.0,
+ output_resolution.1,
+ screen_info.fps(),
+ ),
+ })
}
impl Actor {
@@ -224,6 +249,7 @@ pub struct ActorBuilder {
capture_target: ScreenCaptureTarget,
system_audio: bool,
mic_feed: Option<Arc<MicrophoneFeedLock>>,
+ max_output_size: Option<u32>,
#[cfg(target_os = "macos")]
excluded_windows: Vec<WindowId>,
}
@@ -235,6 +261,7 @@ impl ActorBuilder {
capture_target,
system_audio: false,
mic_feed: None,
+ max_output_size: None,
#[cfg(target_os = "macos")]
excluded_windows: Vec::new(),
}
@@ -250,6 +277,11 @@ impl ActorBuilder {
self
}
+ pub fn with_max_output_size(mut self, max_output_size: u32) -> Self {
+ self.max_output_size = Some(max_output_size);
+ self
+ }
+
#[cfg(target_os = "macos")]
pub fn with_excluded_windows(mut self, excluded_windows: Vec<WindowId>) -> Self {
self.excluded_windows = excluded_windows;
@@ -272,6 +304,7 @@ impl ActorBuilder {
#[cfg(target_os = "macos")]
excluded_windows: self.excluded_windows,
},
+ self.max_output_size,
)
.await
}
@@ -281,6 +314,7 @@ impl ActorBuilder {
pub async fn spawn_instant_recording_actor(
recording_dir: PathBuf,
inputs: RecordingBaseInputs,
+ max_output_size: Option<u32>,
) -> anyhow::Result<ActorHandle> {
ensure_dir(&recording_dir)?;
@@ -296,12 +330,12 @@ pub async fn spawn_instant_recording_actor(
#[cfg(windows)]
let d3d_device = crate::capture_pipeline::create_d3d_device()?;
- let (display, crop) =
+ let (display, crop_bounds) =
target_to_display_and_crop(&inputs.capture_target).context("target_display_crop")?;
let screen_source = ScreenCaptureConfig::<ScreenCaptureMethod>::init(
display,
- crop,
+ crop_bounds,
true,
30,
start_time,
@@ -322,9 +356,11 @@ pub async fn spawn_instant_recording_actor(
content_dir.join("output.mp4"),
screen_source.clone(),
inputs.mic_feed.clone(),
+ max_output_size,
)
.await?;
+ let video_info = pipeline.video_info;
let segment_start_time = current_time_f64();
trace!("spawning recording actor");
@@ -333,7 +369,7 @@ pub async fn spawn_instant_recording_actor(
let actor_ref = Actor::spawn(Actor {
recording_dir,
capture_target: inputs.capture_target.clone(),
- video_info: screen_source.info(),
+ video_info,
state: ActorState::Recording {
pipeline,
// pipeline_done_rx,
@@ -361,3 +397,175 @@ fn current_time_f64() -> f64 {
.unwrap()
.as_secs_f64()
}
+
+fn clamp_size(input: (u32, u32), max: (u32, u32)) -> (u32, u32) {
+ // 16/9-ish
+ if input.0 >= input.1 && (input.0 as f64 / input.1 as f64) <= 16.0 / 9.0 {
+ let mut width = max.0.min(input.0);
+ if width % 2 != 0 {
+ width -= 1;
+ }
+
+ let height_ratio = input.1 as f64 / input.0 as f64;
+ let mut height = (height_ratio * width as f64).round() as u32;
+ if height % 2 != 0 {
+ height -= 1;
+ }
+
+ (width, height)
+ }
+ // 9/16-ish
+ else if input.0 <= input.1 && (input.0 as f64 / input.1 as f64) >= 9.0 / 16.0 {
+ let mut height = max.0.min(input.1);
+ if height % 2 != 0 {
+ height -= 1;
+ }
+
+ let width_ratio = input.0 as f64 / input.1 as f64;
+ let mut width = (width_ratio * height as f64).round() as u32;
+ if width % 2 != 0 {
+ width -= 1;
+ }
+
+ (width, height)
+ }
+ // ultrawide
+ else if input.0 >= input.1 && (input.0 as f64 / input.1 as f64) > 16.0 / 9.0 {
+ let mut height = max.1.min(input.1);
+ if height % 2 != 0 {
+ height -= 1;
+ }
+
+ let width_ratio = input.0 as f64 / input.1 as f64;
+ let mut width = (width_ratio * height as f64).round() as u32;
+ if width % 2 != 0 {
+ width -= 1;
+ }
+
+ (width, height)
+ }
+ // ultratall
+ else if input.0 < input.1 && (input.0 as f64 / input.1 as f64) <= 9.0 / 16.0 {
+ // swapped since max_width/height assume horizontal
+ let mut width = max.1.min(input.0);
+ if width % 2 != 0 {
+ width -= 1;
+ }
+
+ let height_ratio = input.1 as f64 / input.0 as f64;
+ let mut height = (height_ratio * width as f64).round() as u32;
+ if height % 2 != 0 {
+ height -= 1;
+ }
+
+ (width, height)
+ } else {
+ unreachable!()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_clamp_size_16_9_ish_landscape() {
+ // Test 16:9 aspect ratio (boundary case)
+ let result = clamp_size((1920, 1080), (1920, 1080));
+ assert_eq!(result, (1920, 1080));
+
+ // Test aspect ratio less than 16:9 (wider than tall, but not ultrawide)
+ let result = clamp_size((1600, 1200), (1920, 1080)); // 4:3 ratio
+ assert_eq!(result, (1600, 1200));
+
+ // Test scaling down when input exceeds max width
+ let result = clamp_size((2560, 1440), (1920, 1080)); // 16:9 ratio, needs scaling
+ assert_eq!(result, (1920, 1080));
+ }
+
+ #[test]
+ fn test_clamp_size_9_16_ish_portrait() {
+ // Test 9:16 aspect ratio (boundary case)
+ let result = clamp_size((1080, 1920), (1920, 1080));
+ assert_eq!(result, (1080, 1920));
+
+ // Test aspect ratio greater than 9:16 but still portrait
+ let result = clamp_size((1200, 1600), (1920, 1080)); // 3:4 ratio
+ assert_eq!(result, (1200, 1600));
+
+ // Test square format (1:1 ratio) - should use portrait path when width <= height
+ let result = clamp_size((1080, 1080), (1920, 1080));
+ assert_eq!(result, (1080, 1080));
+ }
+
+ #[test]
+ fn test_clamp_size_ultrawide() {
+ // Test ultrawide aspect ratio (> 16:9)
+ let result = clamp_size((2560, 1080), (1920, 1080)); // ~2.37:1 ratio
+ assert_eq!(result, (2560, 1080));
+
+ // Test very ultrawide
+ let result = clamp_size((3440, 1440), (1920, 1080)); // ~2.39:1 ratio
+ assert_eq!(result, (2580, 1080));
+
+ // Test when height constraint is the limiting factor
+ let result = clamp_size((3840, 1600), (1920, 1080)); // 2.4:1 ratio
+ assert_eq!(result, (2592, 1080));
+
+ // Test even number enforcement for height
+ let result = clamp_size((2561, 1080), (1920, 1081)); // Odd max height
+ assert_eq!(result, (2560, 1080)); // Height should be made even
+
+ // Test even number enforcement for calculated width
+ let result = clamp_size((2561, 1080), (1920, 1080)); // Results in odd width calculation
+ assert_eq!(result, (2560, 1080)); // Width should be made even
+ }
+
+ #[test]
+ fn test_clamp_size_ultratall() {
+ // Test ultratall aspect ratio (< 9:16)
+ let result = clamp_size((1080, 2560), (1920, 1920)); // ~9:21.3 ratio
+ assert_eq!(result, (1080, 2560));
+
+ // Test very ultratall that needs scaling
+ let result = clamp_size((800, 3200), (1920, 2000)); // 1:4 ratio
+ assert_eq!(result, (800, 3200));
+
+ // Test when width constraint is the limiting factor (using max.1 as width limit)
+ let result = clamp_size((500, 3000), (1920, 1000)); // Very tall, width limited by max.1
+ assert_eq!(result, (500, 3000));
+
+ // Test even number enforcement for width (using max.1)
+ let result = clamp_size((500, 3000), (1920, 1001)); // Odd max.1 used as width
+ assert_eq!(result, (500, 3000)); // Width should be made even
+
+ // Test even number enforcement for calculated height
+ let result = clamp_size((500, 3000), (1920, 1000)); // Results in odd height calculation
+ assert_eq!(result, (500, 3000)); // Height should be made even
+ }
+
+ #[test]
+ fn test_clamp_size_edge_cases() {
+ // Test minimum sizes
+ let result = clamp_size((2, 2), (1920, 1080));
+ assert_eq!(result, (2, 2));
+
+ // Test when input is smaller than max in all dimensions
+ let result = clamp_size((800, 600), (1920, 1080));
+ assert_eq!(result, (800, 600));
+
+ // Test exact 16:9 boundary
+ let sixteen_nine = 16.0 / 9.0;
+ let width = 1920;
+ let height = (width as f64 / sixteen_nine) as u32; // Should be exactly 1080
+ let result = clamp_size((width, height), (1920, 1080));
+ assert_eq!(result, (1920, 1080));
+
+ // Test exact 9:16 boundary
+ let nine_sixteen = 9.0 / 16.0;
+ let height = 1920;
+ let width = (height as f64 * nine_sixteen) as u32; // Should be exactly 1080
+ let result = clamp_size((width, height), (1920, 1080));
+ assert_eq!(result, (1080, 1920));
+ }
+}
diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rs
index 4845f5a54..e7e08eea1 100644
--- a/crates/recording/src/output_pipeline/win.rs
+++ b/crates/recording/src/output_pipeline/win.rs
@@ -32,6 +32,7 @@ pub struct WindowsMuxerConfig {
pub d3d_device: ID3D11Device,
pub frame_rate: u32,
pub bitrate_multiplier: f32,
+ pub output_size: Option<SizeInt32>,
}
impl Muxer for WindowsMuxer {
@@ -50,6 +51,11 @@ impl Muxer for WindowsMuxer {
{
let video_config =
video_config.ok_or_else(|| anyhow!("invariant: video config expected"))?;
+ let input_size = SizeInt32 {
+ Width: video_config.width as i32,
+ Height: video_config.height as i32,
+ };
+ let output_size = config.output_size.unwrap_or(input_size);
let (video_tx, video_rx) = sync_channel::<Option<(scap_direct3d::Frame, Duration)>>(8);
let mut output = ffmpeg::format::output(&output_path)?;
@@ -73,14 +79,8 @@ impl Muxer for WindowsMuxer {
cap_enc_mediafoundation::H264Encoder::new_with_scaled_output(
&config.d3d_device,
config.pixel_format,
- SizeInt32 {
- Width: video_config.width as i32,
- Height: video_config.height as i32,
- },
- SizeInt32 {
- Width: video_config.width as i32,
- Height: video_config.height as i32,
- },
+ input_size,
+ output_size,
config.frame_rate,
config.bitrate_multiplier,
);
@@ -89,8 +89,8 @@ impl Muxer for WindowsMuxer {
Ok(encoder) => cap_mediafoundation_ffmpeg::H264StreamMuxer::new(
&mut output,
cap_mediafoundation_ffmpeg::MuxerConfig {
- width: video_config.width,
- height: video_config.height,
+ width: output_size.Width as u32,
+ height: output_size.Height as u32,
fps: config.frame_rate,
bitrate: encoder.bitrate(),
},
@@ -103,8 +103,20 @@ impl Muxer for WindowsMuxer {
error!("Failed to create native encoder: {e}");
info!("Falling back to software H264 encoder");
+ let fallback_width = if output_size.Width > 0 {
+ output_size.Width as u32
+ } else {
+ video_config.width
+ };
+ let fallback_height = if output_size.Height > 0 {
+ output_size.Height as u32
+ } else {
+ video_config.height
+ };
+
cap_enc_ffmpeg::H264Encoder::builder(video_config)
- .build(&mut output)
+ .with_output_size(fallback_width, fallback_height)
+ .and_then(|builder| builder.build(&mut output))
.map(either::Right)
.map_err(|e| anyhow!("ScreenSoftwareEncoder/{e}"))
}