Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Implement compression options in editor (#452)

Richie McIlroyd1b8991143c5
diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rs
index 3b363c432..fecf9c2ef 100644
--- a/apps/cli/src/main.rs
+++ b/apps/cli/src/main.rs
@@ -7,7 +7,7 @@ use std::{
};
use cap_editor::create_segments;
-use cap_export::ExportSettings;
+use cap_export::{ExportCompression, ExportSettings};
use cap_media::sources::get_target_fps;
use cap_project::{RecordingMeta, XY};
use cap_rendering::{ProjectRecordings, RenderVideoConstants};
@@ -207,6 +207,7 @@ impl Export {
ExportSettings {
fps: 60,
resolution_base: XY::new(1920, 1080),
+ compression: ExportCompression::Web,
},
)
.await
diff --git a/apps/desktop/src/routes/editor/ExportDialog.tsx b/apps/desktop/src/routes/editor/ExportDialog.tsx
index c516ef0dc..3ad23e423 100644
--- a/apps/desktop/src/routes/editor/ExportDialog.tsx
+++ b/apps/desktop/src/routes/editor/ExportDialog.tsx
@@ -26,8 +26,12 @@ import toast from "solid-toast";
import Tooltip from "~/components/Tooltip";
import { authStore } from "~/store";
import { trackEvent } from "~/utils/analytics";
-import { exportVideo } from "~/utils/export";
-import { commands, events } from "~/utils/tauri";
+import {
+ commands,
+ events,
+ ExportCompression,
+ FramesRendered,
+} from "~/utils/tauri";
import { RenderState, useEditorContext } from "./context";
import { RESOLUTION_OPTIONS } from "./Header";
import {
@@ -38,13 +42,17 @@ import {
PopperContent,
topSlideAnimateClasses,
} from "./ui";
+import { exportVideo } from "~/utils/export";
-export const COMPRESSION_OPTIONS = [
- { label: "Studio", value: "studio" },
- { label: "Social Media", value: "social" },
- { label: "Web", value: "web" },
- { label: "Web (Low)", value: "web_low" },
-] as const;
+export const COMPRESSION_OPTIONS: Array<{
+ label: string;
+ value: ExportCompression;
+}> = [
+ { label: "Minimal", value: "Minimal" },
+ { label: "Social Media", value: "Social" },
+ { label: "Web", value: "Web" },
+ { label: "Potato", value: "Potato" },
+];
export const FPS_OPTIONS = [
{ label: "15 FPS", value: 15 },
@@ -94,11 +102,26 @@ export function ExportDialog() {
fps: 30,
exportTo: "file" as ExportToOption,
resolution: { label: "720p", value: "720p", width: 1280, height: 720 },
- compression: "social",
+ compression: "Minimal" as ExportCompression,
}),
{ name: "export_settings" }
);
+ // just a wrapper of exportVideo that provides the current settings
+ const exportWithSettings = (onProgress: (progress: FramesRendered) => void) =>
+ exportVideo(
+ projectPath,
+ {
+ fps: settings.fps,
+ resolution_base: {
+ x: settings.resolution.width,
+ y: settings.resolution.height,
+ },
+ compression: settings.compression,
+ },
+ onProgress
+ );
+
const [outputPath, setOutputPath] = createSignal<string | null>(null);
const selectedStyle =
@@ -134,11 +157,8 @@ export function ExportDialog() {
if (exportState.type !== "idle") return;
setExportState(reconcile({ action: "copy", type: "starting" }));
- const { fps, resolution } = settings;
- const outputPath = await exportVideo(
- projectPath,
- { fps, resolution_base: { x: resolution.width, y: resolution.height } },
- (progress) => setExportState({ type: "rendering", progress })
+ const outputPath = await exportWithSettings((progress) =>
+ setExportState({ type: "rendering", progress })
);
setExportState({ type: "copying" });
@@ -193,19 +213,9 @@ export function ExportDialog() {
path: savePath,
});
- const videoPath = await exportVideo(
- projectPath,
- {
- fps: settings.fps,
- resolution_base: {
- x: settings.resolution.width,
- y: settings.resolution.height,
- },
- },
- (progress) => {
- setExportState({ type: "rendering", progress });
- }
- );
+ const videoPath = await exportWithSettings((progress) => {
+ setExportState({ type: "rendering", progress });
+ });
setExportState({ type: "copying" });
@@ -280,16 +290,8 @@ export function ExportDialog() {
});
try {
- await exportVideo(
- projectPath,
- {
- fps: settings.fps,
- resolution_base: {
- x: settings.resolution.width,
- y: settings.resolution.height,
- },
- },
- (progress) => setExportState({ type: "rendering", progress })
+ await exportWithSettings((progress) =>
+ setExportState({ type: "rendering", progress })
);
setExportState({ type: "uploading", progress: 0 });
@@ -545,14 +547,21 @@ export function ExportDialog() {
{/* Compression */}
<div class="p-4 bg-gray-100 rounded-xl">
<div class="flex flex-col gap-3">
- <h3 class="text-gray-400">Compression (Coming Soon)</h3>
+ <h3 class="text-gray-500">Compression</h3>
<div class="flex gap-2">
<For each={COMPRESSION_OPTIONS}>
{(option) => (
<Button
- onClick={() => setSettings("compression", option.value)}
+ onClick={() => {
+ setSettings(
+ "compression",
+ option.value as ExportCompression
+ );
+ }}
variant="secondary"
- disabled
+ class={cx(
+ settings.compression === option.value && selectedStyle
+ )}
>
{option.label}
</Button>
diff --git a/apps/desktop/src/routes/editor/ShareButton.tsx b/apps/desktop/src/routes/editor/ShareButton.tsx
index 35071f677..106a74604 100644
--- a/apps/desktop/src/routes/editor/ShareButton.tsx
+++ b/apps/desktop/src/routes/editor/ShareButton.tsx
@@ -70,6 +70,7 @@ function ShareButton() {
x: RESOLUTION_OPTIONS._1080p.width,
y: RESOLUTION_OPTIONS._1080p.height,
},
+ compression: "Web",
},
(msg) => {
setUploadState(
diff --git a/apps/desktop/src/routes/recordings-overlay.tsx b/apps/desktop/src/routes/recordings-overlay.tsx
index 9efbc62ec..485d94f40 100644
--- a/apps/desktop/src/routes/recordings-overlay.tsx
+++ b/apps/desktop/src/routes/recordings-overlay.tsx
@@ -552,6 +552,16 @@ function createRecordingMutations(
queryFn: () => commands.getRecordingMeta(media.path, type),
}));
+ // just a wrapper of exportVideo to provide base settings
+ const exportWithDefaultSettings = (
+ onProgress: (progress: FramesRendered) => void
+ ) =>
+ exportVideo(
+ media.path,
+ { fps: FPS, resolution_base: OUTPUT_SIZE, compression: "Web" },
+ onProgress
+ );
+
const copy = createMutation(() => ({
mutationFn: async () => {
setActionState({
@@ -562,9 +572,7 @@ function createRecordingMutations(
try {
if (isRecording) {
// First try to get existing rendered video
- const outputPath = await exportVideo(
- media.path,
- { fps: FPS, resolution_base: OUTPUT_SIZE },
+ const outputPath = await exportWithDefaultSettings(
createRenderProgressCallback("copy", setActionState)
);
@@ -649,9 +657,7 @@ function createRecordingMutations(
});
if (isRecording) {
- const outputPath = await exportVideo(
- media.path,
- { fps: FPS, resolution_base: OUTPUT_SIZE },
+ const outputPath = await exportWithDefaultSettings(
createRenderProgressCallback("save", setActionState)
);
@@ -736,11 +742,7 @@ function createRecordingMutations(
setActionState
);
- await exportVideo(
- media.path,
- { fps: FPS, resolution_base: OUTPUT_SIZE },
- progress
- );
+ await exportWithDefaultSettings(progress);
// Show quick progress animation for existing video
setActionState(
diff --git a/apps/desktop/src/utils/export.ts b/apps/desktop/src/utils/export.ts
index 4faa349e7..d8cb9cc5b 100644
--- a/apps/desktop/src/utils/export.ts
+++ b/apps/desktop/src/utils/export.ts
@@ -1,6 +1,10 @@
import { Channel } from "@tauri-apps/api/core";
-import { commands, ExportSettings, FramesRendered } from "./tauri";
-import { trackEvent } from "./analytics";
+import {
+ commands,
+ ExportCompression,
+ ExportSettings,
+ FramesRendered,
+} from "./tauri";
export async function exportVideo(
projectPath: string,
@@ -8,8 +12,6 @@ export async function exportVideo(
onProgress: (progress: FramesRendered) => void
) {
const progress = new Channel<FramesRendered>();
-
progress.onmessage = onProgress;
-
return await commands.exportVideo(projectPath, progress, settings);
}
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index e79d1a503..702908f06 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -251,8 +251,9 @@ export type CursorMeta = { imagePath: string; hotspot: XY<number> }
export type CursorType = "pointer" | "circle"
export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }
export type EditorStateChanged = { playhead_position: number }
+export type ExportCompression = "Minimal" | "Social" | "Web" | "Potato"
export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }
-export type ExportSettings = { fps: number; resolution_base: XY<number> }
+export type ExportSettings = { fps: number; resolution_base: XY<number>; compression: ExportCompression }
export type Flags = { systemAudioRecording: boolean; split: 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; customCursorCapture?: boolean; systemAudioCapture?: boolean;
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 0f5bc0b6a..8b2fcb230 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -58,10 +58,30 @@ pub struct Exporter<TOnProgress> {
recordings: Arc<ProjectRecordings>,
}
-#[derive(Deserialize, Type, Clone, Copy, Debug)]
+#[derive(Deserialize, Type, Clone, Debug)]
pub struct ExportSettings {
pub fps: u32,
pub resolution_base: XY<u32>,
+ pub compression: ExportCompression,
+}
+
+#[derive(Deserialize, Clone, Copy, Debug, Type)]
+pub enum ExportCompression {
+ Minimal,
+ Social,
+ Web,
+ Potato,
+}
+
+impl ExportCompression {
+ pub fn bits_per_pixel(&self) -> f32 {
+ match self {
+ Self::Minimal => 0.3,
+ Self::Social => 0.15,
+ Self::Web => 0.08,
+ Self::Potato => 0.04,
+ }
+ }
}
impl<TOnProgress> Exporter<TOnProgress>
@@ -168,7 +188,11 @@ where
let mut encoder = cap_media::encoders::MP4File::init(
"output",
self.output_path.clone(),
- H264Encoder::factory("output_video", video_info),
+ |o| {
+ H264Encoder::builder("output_video", video_info)
+ .with_bpp(self.settings.compression.bits_per_pixel())
+ .build(o)
+ },
|o| {
has_audio.then(|| {
AACEncoder::init("output_audio", AudioRenderer::info(), o)
diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rs
index bc2c2c4d1..d6838b69d 100644
--- a/crates/media/src/encoders/h264.rs
+++ b/crates/media/src/encoders/h264.rs
@@ -9,55 +9,71 @@ use ffmpeg::{
Dictionary,
};
-pub struct H264Encoder {
- tag: &'static str,
- encoder: encoder::Video,
- config: VideoInfo,
- converter: Option<ffmpeg::software::scaling::Context>,
- stream_index: usize,
- packet: ffmpeg::Packet,
+pub struct H264EncoderBuilder {
+ name: &'static str,
+ bpp: f32,
+ input_config: VideoInfo,
+ preset: H264Preset,
}
-impl H264Encoder {
- pub fn factory(
- tag: &'static str,
- config: VideoInfo,
- ) -> impl FnOnce(&mut format::context::Output) -> Result<Self, MediaError> {
- move |o| Self::init(tag, config, o)
+#[derive(Clone, Copy)]
+pub enum H264Preset {
+ Slow,
+ Medium,
+ Ultrafast,
+}
+
+impl H264EncoderBuilder {
+ pub const QUALITY_BPP: f32 = 0.3;
+
+ pub fn new(name: &'static str, input_config: VideoInfo) -> Self {
+ Self {
+ name,
+ input_config,
+ bpp: Self::QUALITY_BPP,
+ preset: H264Preset::Ultrafast,
+ }
+ }
+
+ pub fn with_preset(mut self, preset: H264Preset) -> Self {
+ self.preset = preset;
+ self
+ }
+
+ pub fn with_bpp(mut self, bpp: f32) -> Self {
+ self.bpp = bpp;
+ self
}
- pub fn init(
- tag: &'static str,
- config: VideoInfo,
- output: &mut format::context::Output,
- ) -> Result<Self, MediaError> {
- let (codec, options) = get_codec_and_options(&config)?;
+ pub fn build(self, output: &mut format::context::Output) -> Result<H264Encoder, MediaError> {
+ let input_config = &self.input_config;
+ let (codec, encoder_options) = get_codec_and_options(&input_config, self.preset)?;
let (format, converter) = if !codec
.video()
.unwrap()
.formats()
.unwrap()
- .any(|f| f == config.pixel_format)
+ .any(|f| f == input_config.pixel_format)
{
let format = ffmpeg::format::Pixel::YUV420P;
tracing::debug!(
"Converting from {:?} to {:?} for H264 encoding",
- config.pixel_format,
+ input_config.pixel_format,
format
);
(
format,
Some(
ffmpeg::software::converter(
- (config.width, config.height),
- config.pixel_format,
+ (input_config.width, input_config.height),
+ input_config.pixel_format,
format,
)
.map_err(|e| {
tracing::error!(
"Failed to create converter from {:?} to YUV420P: {:?}",
- config.pixel_format,
+ input_config.pixel_format,
e
);
MediaError::Any("Failed to create frame converter".into())
@@ -65,47 +81,63 @@ impl H264Encoder {
),
)
} else {
- (config.pixel_format, None)
+ (input_config.pixel_format, None)
};
let mut encoder_ctx = context::Context::new_with_codec(codec);
- // TODO: Configure this per system
encoder_ctx.set_threading(Config::count(4));
let mut encoder = encoder_ctx.encoder().video()?;
- encoder.set_width(config.width);
- encoder.set_height(config.height);
+ encoder.set_width(input_config.width);
+ encoder.set_height(input_config.height);
encoder.set_format(format);
- encoder.set_time_base(config.frame_rate.invert());
- encoder.set_frame_rate(Some(config.frame_rate));
+ encoder.set_time_base(input_config.frame_rate.invert());
+ encoder.set_frame_rate(Some(input_config.frame_rate));
+ // let target_bitrate = compression.bitrate();
let bitrate = get_bitrate(
- config.width,
- config.height,
- config.frame_rate.0 as f32 / config.frame_rate.1 as f32,
+ input_config.width,
+ input_config.height,
+ input_config.frame_rate.0 as f32 / input_config.frame_rate.1 as f32,
+ self.bpp,
);
encoder.set_bit_rate(bitrate);
encoder.set_max_bit_rate(bitrate);
- let video_encoder = encoder.open_with(options)?;
+ let video_encoder = encoder.open_with(encoder_options)?;
let mut output_stream = output.add_stream(codec)?;
let stream_index = output_stream.index();
- output_stream.set_time_base(config.frame_rate.invert());
- output_stream.set_rate(config.frame_rate);
+ output_stream.set_time_base(input_config.frame_rate.invert());
+ output_stream.set_rate(input_config.frame_rate);
output_stream.set_parameters(&video_encoder);
- Ok(Self {
- tag,
+ Ok(H264Encoder {
+ tag: self.name,
encoder: video_encoder,
stream_index,
- config,
+ config: self.input_config,
converter,
packet: FFPacket::empty(),
})
}
+}
+
+pub struct H264Encoder {
+ tag: &'static str,
+ encoder: encoder::Video,
+ config: VideoInfo,
+ converter: Option<ffmpeg::software::scaling::Context>,
+ stream_index: usize,
+ packet: ffmpeg::Packet,
+}
+
+impl H264Encoder {
+ pub fn builder(name: &'static str, input_config: VideoInfo) -> H264EncoderBuilder {
+ H264EncoderBuilder::new(name, input_config)
+ }
pub fn queue_frame(&mut self, frame: FFVideo, output: &mut format::context::Output) {
let frame = if let Some(converter) = &mut self.converter {
@@ -160,7 +192,10 @@ impl H264Encoder {
}
}
-fn get_codec_and_options(config: &VideoInfo) -> Result<(Codec, Dictionary), MediaError> {
+fn get_codec_and_options(
+ config: &VideoInfo,
+ preset: H264Preset,
+) -> Result<(Codec, Dictionary), MediaError> {
let encoder_name = {
if cfg!(target_os = "macos") {
"libx264"
@@ -175,20 +210,26 @@ fn get_codec_and_options(config: &VideoInfo) -> Result<(Codec, Dictionary), Medi
let mut options = Dictionary::new();
if encoder_name == "h264_videotoolbox" {
- // options.set("constant_bit_rate", "true");
options.set("realtime", "true");
} else {
let keyframe_interval_secs = 2;
let keyframe_interval = keyframe_interval_secs * config.frame_rate.numerator();
let keyframe_interval_str = keyframe_interval.to_string();
- options.set("preset", "ultrafast");
- options.set("tune", "zerolatency");
+ options.set(
+ "preset",
+ match preset {
+ H264Preset::Slow => "slow",
+ H264Preset::Medium => "medium",
+ H264Preset::Ultrafast => "ultrafast",
+ },
+ );
+ if let H264Preset::Ultrafast = preset {
+ options.set("tune", "zerolatency");
+ }
options.set("vsync", "1");
options.set("g", &keyframe_interval_str);
options.set("keyint_min", &keyframe_interval_str);
- // // TODO: Is it worth limiting quality? Maybe make this configurable
- // options.set("crf", "14");
}
return Ok((codec, options));
@@ -197,23 +238,10 @@ fn get_codec_and_options(config: &VideoInfo) -> Result<(Codec, Dictionary), Medi
Err(MediaError::MissingCodec("H264 video"))
}
-fn get_bitrate(width: u32, height: u32, frame_rate: f32) -> usize {
+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.4 + 30.0;
+ 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 base_bpp = 0.15;
-
- // Apply resolution efficiency scaling (larger resolutions can use relatively lower bitrates)
- let resolution_factor = if width * height > 1920 * 1080 {
- 0.7
- } else if width * height > 1280 * 720 {
- 0.8
- } else if width * height > 640 * 480 {
- 0.9
- } else {
- 1.0
- };
-
- (pixels_per_second * base_bpp * resolution_factor) as usize
+ (pixels_per_second * bpp) as usize
}
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rs
index 521a5ca8c..e61442715 100644
--- a/crates/recording/src/capture_pipeline.rs
+++ b/crates/recording/src/capture_pipeline.rs
@@ -216,7 +216,7 @@ impl MakeCapturePipeline for AVFrameCapture {
let mut screen_encoder = MP4File::init(
"screen",
output_path.into(),
- H264Encoder::factory("screen", screen_config),
+ |o| H264Encoder::builder("screen", screen_config).build(o),
|_| None,
)?;
@@ -274,7 +274,7 @@ impl MakeCapturePipeline for AVFrameCapture {
let mp4 = Arc::new(std::sync::Mutex::new(MP4File::init(
"screen",
output_path.into(),
- H264Encoder::factory("screen", screen_config),
+ |o| H264Encoder::builder("screen", screen_config).build(o),
|o| {
has_audio_sources.then(|| {
OpusEncoder::init("mic_audio", AudioMixer::info(), o).map(|v| v.boxed())
diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rs
index 4bb932578..1c044a17c 100644
--- a/crates/recording/src/studio_recording.rs
+++ b/crates/recording/src/studio_recording.rs
@@ -655,7 +655,7 @@ async fn create_segment_pipeline(
let mut camera_encoder = MP4File::init(
"camera",
output_path.clone(),
- H264Encoder::factory("camera", camera_config),
+ |o| H264Encoder::builder("camera", camera_config).build(o),
|_| None,
)?;