Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Add microphone waveform in editor (#575)

Richie McIlroy59d4eeb65a91
diff --git a/apps/desktop/src-tauri/src/audio.rs b/apps/desktop/src-tauri/src/audio.rs
index 354436a80..7cca0218f 100644
--- a/apps/desktop/src-tauri/src/audio.rs
+++ b/apps/desktop/src-tauri/src/audio.rs
@@ -1,3 +1,5 @@
+use cap_audio::AudioData;
+
fn play_audio(bytes: &'static [u8]) {
use rodio::{Decoder, OutputStream, Sink};
use std::io::Cursor;
@@ -35,3 +37,34 @@ impl AppSounds {
}
}
}
+
+pub fn get_waveform(audio: &AudioData) -> Vec<f32> {
+ const CHUNK_SIZE: usize = (cap_audio::AudioData::SAMPLE_RATE as usize) / 10; // ~100ms
+
+ let channels = audio.channels() as usize;
+ let samples = audio.samples();
+ let mut waveform = Vec::new();
+
+ let mut i = 0;
+ while i < samples.len() {
+ let end = (i + CHUNK_SIZE * channels).min(samples.len());
+ let mut sum = 0.0f32;
+ for s in &samples[i..end] {
+ sum += s.abs();
+ }
+ let avg = if end > i { sum / (end - i) as f32 } else { 0.0 };
+ waveform.push(avg);
+ i += CHUNK_SIZE * channels;
+ }
+
+ // Convert to absolute dBFS (0 dBFS = digital full scale)
+ for v in waveform.iter_mut() {
+ *v = if *v > 0.0 {
+ 20.0 * v.log10() // Absolute dBFS relative to 1.0
+ } else {
+ -60.0 // Set silence to -60dBFS instead of -∞ for practical use
+ };
+ }
+
+ waveform
+}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 3154a6b47..9b6ae3c23 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1599,6 +1599,41 @@ async fn seek_to(editor_instance: WindowEditorInstance, frame_number: u32) -> Re
Ok(())
}
+#[tauri::command]
+#[specta::specta]
+async fn get_mic_waveforms(editor_instance: WindowEditorInstance) -> Result<Vec<Vec<f32>>, String> {
+ let mut out = Vec::new();
+
+ for segment in editor_instance.segments.iter() {
+ if let Some(audio) = &segment.audio {
+ out.push(audio::get_waveform(audio));
+ } else {
+ out.push(Vec::new());
+ }
+ }
+
+ Ok(out)
+}
+
+#[tauri::command]
+#[specta::specta]
+async fn get_system_audio_waveforms(
+ editor_instance: WindowEditorInstance,
+) -> Result<Vec<Vec<f32>>, String> {
+ let mut out = Vec::new();
+
+ for segment in editor_instance.segments.iter() {
+ if let Some(audio) = &segment.system_audio {
+ out.push(audio::get_waveform(audio));
+ } else {
+ out.push(Vec::new());
+ }
+ }
+
+ Ok(out)
+}
+
+// keep this async otherwise opening windows may hang on windows
#[tauri::command]
#[specta::specta]
async fn show_window(app: AppHandle, window: ShowCapWindow) -> Result<(), String> {
@@ -1729,6 +1764,8 @@ pub async fn run(recording_logging_handle: LoggingHandle) {
open_file_path,
get_video_metadata,
create_editor_instance,
+ get_mic_waveforms,
+ get_system_audio_waveforms,
start_playback,
stop_playback,
set_playhead_position,
diff --git a/apps/desktop/src/components/CapErrorBoundary.tsx b/apps/desktop/src/components/CapErrorBoundary.tsx
index 2de3d7258..a4385d8c5 100644
--- a/apps/desktop/src/components/CapErrorBoundary.tsx
+++ b/apps/desktop/src/components/CapErrorBoundary.tsx
@@ -33,6 +33,16 @@ export function CapErrorBoundary(props: ParentProps) {
Reload
</Button>
</div>
+
+ {import.meta.env.DEV && (
+ <div class="h-0 text-sm">
+ <pre class="text-left mt-8">{`${e.toString()}\n\n${e.stack
+ ?.toString()
+ .split("\n")
+ .slice(0, 10)
+ .join("\n")}`}</pre>
+ </div>
+ )}
</div>
);
}}
diff --git a/apps/desktop/src/routes/editor/Header.tsx b/apps/desktop/src/routes/editor/Header.tsx
index d659ec6ee..89f6d3a20 100644
--- a/apps/desktop/src/routes/editor/Header.tsx
+++ b/apps/desktop/src/routes/editor/Header.tsx
@@ -5,7 +5,14 @@ import { remove } from "@tauri-apps/plugin-fs";
import { revealItemInDir } from "@tauri-apps/plugin-opener";
import { type as ostype } from "@tauri-apps/plugin-os";
import { cx } from "cva";
-import { ComponentProps, createEffect, createSignal, onCleanup, onMount, Show } from "solid-js";
+import {
+ ComponentProps,
+ createEffect,
+ createSignal,
+ onCleanup,
+ onMount,
+ Show,
+} from "solid-js";
import { Button } from "@cap/ui-solid";
import CaptionControlsWindows11 from "~/components/titlebar/controls/CaptionControlsWindows11";
@@ -44,7 +51,7 @@ export function Header() {
meta,
exportState,
setExportState,
- customDomain
+ customDomain,
} = useEditorContext();
let unlistenTitlebar: UnlistenFn | undefined;
@@ -95,11 +102,11 @@ export function Header() {
/>
<div class="flex flex-row items-center">
- <Tooltip
- disabled={!truncated()}
- content={meta().prettyName}
- >
- <p ref={prettyNameRef} class="text-sm truncate text-gray-12 max-w-[300px] cursor-default">
+ <Tooltip disabled={!truncated()} content={meta().prettyName}>
+ <p
+ ref={prettyNameRef}
+ class="text-sm truncate text-gray-12 max-w-[300px] cursor-default"
+ >
{meta().prettyName}
</p>
</Tooltip>
@@ -167,7 +174,7 @@ export function Header() {
leftIcon={<IconCapRedo class="w-5" />}
/>
<div data-tauri-drag-region class="flex-1 h-full" />
- <Show when={customDomain()}>
+ <Show when={customDomain.data}>
<ShareButton />
</Show>
<Button
diff --git a/apps/desktop/src/routes/editor/ShareButton.tsx b/apps/desktop/src/routes/editor/ShareButton.tsx
index ef5d73e7f..7dbc499f0 100644
--- a/apps/desktop/src/routes/editor/ShareButton.tsx
+++ b/apps/desktop/src/routes/editor/ShareButton.tsx
@@ -10,13 +10,19 @@ import { exportVideo } from "~/utils/export";
import { commands, events } from "~/utils/tauri";
import { useEditorContext } from "./context";
import { RESOLUTION_OPTIONS } from "./Header";
-import { Dialog, DialogContent, MenuItem, MenuItemList, PopperContent, topLeftAnimateClasses } from "./ui";
+import {
+ Dialog,
+ DialogContent,
+ MenuItem,
+ MenuItemList,
+ PopperContent,
+ topLeftAnimateClasses,
+} from "./ui";
function ShareButton() {
const { editorInstance, meta, customDomain } = useEditorContext();
const projectPath = editorInstance.path;
-
const upload = createMutation(() => ({
mutationFn: async () => {
setUploadState({ type: "idle" });
@@ -90,8 +96,8 @@ function ShareButton() {
const result = meta().sharing
? await commands.uploadExportedVideo(projectPath, "Reupload")
: await commands.uploadExportedVideo(projectPath, {
- Initial: { pre_created_video: null },
- });
+ Initial: { pre_created_video: null },
+ });
if (result === "NotAuthenticated") {
throw new Error("You need to sign in to share recordings");
@@ -139,21 +145,27 @@ function ShareButton() {
<div class="relative">
<Show when={meta().sharing}>
{(sharing) => {
-
const normalUrl = () => new URL(sharing().link);
- const customUrl = () => customDomain()?.custom_domain ? new URL(customDomain()?.custom_domain + `/s/${meta().sharing?.id}`) : null;
+ const customUrl = () =>
+ customDomain.data?.custom_domain
+ ? new URL(
+ customDomain.data?.custom_domain + `/s/${meta().sharing?.id}`
+ )
+ : null;
const normalLink = `${normalUrl().host}${normalUrl().pathname}`;
const customLink = `${customUrl()?.host}${customUrl()?.pathname}`;
-
const copyLinks = {
normal: sharing().link,
- custom: customUrl()?.href
- }
+ custom: customUrl()?.href,
+ };
const [linkToDisplay, setLinkToDisplay] = createSignal<string | null>(
- customDomain()?.custom_domain && customDomain()?.domain_verified ? customLink : normalLink
+ customDomain.data?.custom_domain &&
+ customDomain.data?.domain_verified
+ ? customLink
+ : normalLink
);
const [copyPressed, setCopyPressed] = createSignal(false);
@@ -190,26 +202,36 @@ function ShareButton() {
<div class="rounded-xl px-3 py-2 flex flex-row items-center gap-[0.375rem] bg-gray-3 hover:bg-gray-4 transition-colors duration-100">
<a
href={
- linkToDisplay() === customLink ? copyLinks.custom : copyLinks.normal
+ linkToDisplay() === customLink
+ ? copyLinks.custom
+ : copyLinks.normal
}
target="_blank"
rel="noreferrer"
class="w-full truncate max-w-[200px]"
>
- <span class="text-xs text-gray-12">
- {linkToDisplay()}
- </span>
+ <span class="text-xs text-gray-12">{linkToDisplay()}</span>
</a>
{/** Dropdown */}
- <Show when={customDomain()?.custom_domain && customDomain()?.domain_verified}>
+ <Show
+ when={
+ customDomain.data?.custom_domain &&
+ customDomain.data?.domain_verified
+ }
+ >
<Tooltip content="Select link">
<KSelect
value={linkToDisplay()}
onChange={(value) => value && setLinkToDisplay(value)}
- options={[customLink, normalLink].filter(link => link !== linkToDisplay())}
+ options={[customLink, normalLink].filter(
+ (link) => link !== linkToDisplay()
+ )}
multiple={false}
itemComponent={(props) => (
- <MenuItem<typeof KSelect.Item> as={KSelect.Item} item={props.item}>
+ <MenuItem<typeof KSelect.Item>
+ as={KSelect.Item}
+ item={props.item}
+ >
<KSelect.ItemLabel class="flex-1 text-xs truncate">
{props.item.rawValue}
</KSelect.ItemLabel>
@@ -218,9 +240,7 @@ function ShareButton() {
placement="bottom-end"
gutter={4}
>
- <KSelect.Trigger
- class="flex justify-center items-center transition-colors duration-200 rounded-lg size-[22px] text-gray-12 bg-gray-6 hover:bg-gray-7 group focus:outline-none focus-visible:outline-none"
- >
+ <KSelect.Trigger class="flex justify-center items-center transition-colors duration-200 rounded-lg size-[22px] text-gray-12 bg-gray-6 hover:bg-gray-7 group focus:outline-none focus-visible:outline-none">
<KSelect.Icon>
<IconCapChevronDown class="size-4 transition-transform duration-200 group-data-[expanded]:rotate-180" />
</KSelect.Icon>
@@ -270,19 +290,20 @@ function ShareButton() {
<div
class="bg-blue-9 h-2.5 rounded-full"
style={{
- width: `${uploadState.type === "uploading"
- ? uploadState.progress
- : uploadState.type === "link-copied"
+ width: `${
+ uploadState.type === "uploading"
+ ? uploadState.progress
+ : uploadState.type === "link-copied"
? 100
: uploadState.type === "rendering"
- ? Math.min(
+ ? Math.min(
(uploadState.renderedFrames /
uploadState.totalFrames) *
- 100,
+ 100,
100
)
- : 0
- }%`,
+ : 0
+ }%`,
}}
/>
</div>
@@ -291,10 +312,10 @@ function ShareButton() {
{uploadState.type == "idle" || uploadState.type === "starting"
? "Preparing to render..."
: uploadState.type === "rendering"
- ? `Rendering video (${uploadState.renderedFrames}/${uploadState.totalFrames} frames)`
- : uploadState.type === "uploading"
- ? `Uploading - ${Math.floor(uploadState.progress)}%`
- : "Link copied to clipboard!"}
+ ? `Rendering video (${uploadState.renderedFrames}/${uploadState.totalFrames} frames)`
+ : uploadState.type === "uploading"
+ ? `Uploading - ${Math.floor(uploadState.progress)}%`
+ : "Link copied to clipboard!"}
</p>
</div>
</DialogContent>
diff --git a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
index f948b424a..e276305c3 100644
--- a/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/ClipTrack.tsx
@@ -29,6 +29,116 @@ import {
} from "./Track";
import { getSectionMarker } from "./sectionMarker";
+function WaveformCanvas(props: {
+ systemWaveform?: number[];
+ micWaveform?: number[];
+ segment: { start: number; end: number };
+ secsPerPixel: number;
+}) {
+ const { project } = useEditorContext();
+
+ let canvas: HTMLCanvasElement | undefined;
+ const { width } = useSegmentContext();
+ const { secsPerPixel } = useTimelineContext();
+
+ const render = (
+ ctx: CanvasRenderingContext2D,
+ h: number,
+ waveform: number[],
+ color: string,
+ gain = 0
+ ) => {
+ const maxAmplitude = h;
+
+ // yellow please
+ ctx.fillStyle = color;
+ ctx.beginPath();
+
+ const step = 0.05 / secsPerPixel();
+
+ ctx.moveTo(0, h);
+
+ const norm = (w: number) => 1.0 - Math.max(w + gain, -60) / -60;
+
+ for (
+ let segmentTime = props.segment.start;
+ segmentTime <= props.segment.end + 0.1;
+ segmentTime += 0.1
+ ) {
+ const index = Math.floor(segmentTime * 10);
+ const xTime = index / 10;
+
+ const amplitude = norm(waveform[index]) * maxAmplitude;
+
+ const x = (xTime - props.segment.start) / secsPerPixel();
+ const y = h - amplitude;
+
+ const prevX = (xTime - 0.1 - props.segment.start) / secsPerPixel();
+ const prevAmplitude = norm(waveform[index - 1]) * maxAmplitude;
+ const prevY = h - prevAmplitude;
+
+ const cpX1 = prevX + step / 2;
+ const cpX2 = x - step / 2;
+
+ ctx.bezierCurveTo(cpX1, prevY, cpX2, y, x, y);
+ }
+
+ ctx.lineTo(
+ (props.segment.end + 0.3 - props.segment.start) / secsPerPixel(),
+ h
+ );
+
+ ctx.closePath();
+ ctx.fill();
+ };
+
+ function renderWaveforms() {
+ if (!canvas) return;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+
+ const w = width();
+ if (w <= 0) return;
+
+ const h = canvas.height;
+ canvas.width = w;
+ ctx.clearRect(0, 0, w, h);
+
+ if (props.micWaveform)
+ render(
+ ctx,
+ h,
+ props.micWaveform,
+ "rgba(255,255,255,0.4)",
+ project.audio.micVolumeDb
+ );
+
+ if (props.systemWaveform)
+ render(
+ ctx,
+ h,
+ props.systemWaveform,
+ "rgba(255,150,0,0.5)",
+ project.audio.systemVolumeDb
+ );
+ }
+
+ createEffect(() => {
+ renderWaveforms();
+ });
+
+ return (
+ <canvas
+ ref={(el) => {
+ canvas = el;
+ renderWaveforms();
+ }}
+ class="absolute inset-0 w-full h-full pointer-events-none"
+ height={52}
+ />
+ );
+}
+
export function ClipTrack(
props: Pick<ComponentProps<"div">, "ref"> & {
handleUpdatePlayhead: (e: MouseEvent) => void;
@@ -43,6 +153,9 @@ export function ClipTrack(
editorState,
setEditorState,
totalDuration,
+ micWaveforms,
+ systemAudioWaveforms,
+ metaQuery,
} = useEditorContext();
const { secsPerPixel, duration } = useTimelineContext();
@@ -106,6 +219,25 @@ export function ClipTrack(
return segmentIndex === selection.index;
});
+ const micWaveform = () => {
+ if (project.audio.micVolumeDb && project.audio.micVolumeDb < -30)
+ return;
+
+ const idx = segment.recordingSegment ?? i();
+ return micWaveforms()?.[idx] ?? [];
+ };
+
+ const systemAudioWaveform = () => {
+ if (
+ project.audio.systemVolumeDb &&
+ project.audio.systemVolumeDb <= -30
+ )
+ return;
+
+ const idx = segment.recordingSegment ?? i();
+ return systemAudioWaveforms()?.[idx] ?? [];
+ };
+
return (
<>
<Show when={marker()}>
@@ -127,11 +259,7 @@ export function ClipTrack(
})()}
>
{(marker) => (
- <div
- class={cx(
- "h-7 -top-8 overflow-hidden rounded-full -translate-x-1/2"
- )}
- >
+ <div class="h-7 -top-8 overflow-hidden rounded-full -translate-x-1/2 z-10">
<CutOffsetButton
value={(() => {
const m = marker();
@@ -158,53 +286,38 @@ export function ClipTrack(
<Match
when={(() => {
const m = marker();
- if (m.type === "dual") return m;
+ if (
+ m.type === "dual" &&
+ m.right &&
+ m.right.type === "time"
+ )
+ return m.right;
})()}
>
- {(marker) => (
- <div class="h-7 w-0 absolute -top-8 flex flex-row rounded-full">
- <Show when={marker().left}>
- {(marker) => (
- <CutOffsetButton
- value={(() => {
- const m = marker();
- return m.type === "reset" ? 0 : m.time;
- })()}
- class="-right-px absolute rounded-l-full !pr-1.5 rounded-tr-full"
- onClick={() => {
- setProject(
- "timeline",
- "segments",
- i() - 1,
- "end",
- segmentRecording(i() - 1).display.duration
- );
- }}
- />
- )}
- </Show>
- <Show when={marker().right}>
- {(marker) => (
- <CutOffsetButton
- value={(() => {
- const m = marker();
- return m.type === "reset" ? 0 : m.time;
- })()}
- class="-left-px absolute rounded-r-full !pl-1.5 rounded-tl-full"
- onClick={() => {
- setProject(
- "timeline",
- "segments",
- i(),
- "start",
- 0
- );
- }}
- />
- )}
- </Show>
- </div>
- )}
+ {(marker) => {
+ const markerValue = marker();
+ return (
+ <div class="h-7 w-0 absolute -top-8 flex flex-row rounded-full">
+ <CutOffsetButton
+ value={
+ markerValue.type === "time"
+ ? markerValue.time
+ : 0
+ }
+ class="-left-px absolute rounded-r-full !pl-1.5 rounded-tl-full"
+ onClick={() => {
+ setProject(
+ "timeline",
+ "segments",
+ i(),
+ "start",
+ 0
+ );
+ }}
+ />
+ </div>
+ );
+ }}
</Match>
</Switch>
</div>
@@ -245,6 +358,13 @@ export function ClipTrack(
}
}}
>
+ <WaveformCanvas
+ micWaveform={micWaveform()}
+ systemWaveform={systemAudioWaveform()}
+ segment={segment}
+ secsPerPixel={secsPerPixel()}
+ />
+
<Markings segment={segment} prevDuration={prevDuration()} />
<SegmentHandle
@@ -421,7 +541,10 @@ export function ClipTrack(
<div class="w-[2px] bottom-0 -top-2 rounded-full from-red-300 to-transparent bg-gradient-to-b -translate-x-1/2" />
<div class="h-7 w-0 absolute -top-8 flex flex-row rounded-full">
<CutOffsetButton
- value={marker().time}
+ value={(() => {
+ const m = marker();
+ return m.type === "time" ? m.time : 0;
+ })()}
class="-right-px absolute rounded-l-full !pr-1.5 rounded-tr-full"
onClick={() => {
setProject(
diff --git a/apps/desktop/src/routes/editor/context.ts b/apps/desktop/src/routes/editor/context.ts
index ab6489c4c..867e027f6 100644
--- a/apps/desktop/src/routes/editor/context.ts
+++ b/apps/desktop/src/routes/editor/context.ts
@@ -275,16 +275,18 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
},
});
- const customDomainData = createCustomDomainQuery();
+ const [micWaveforms] = createResource(() => commands.getMicWaveforms());
+ const [systemAudioWaveforms] = createResource(() =>
+ commands.getSystemAudioWaveforms()
+ );
+ const customDomain = createCustomDomainQuery();
return {
...editorInstanceContext,
meta() {
return props.meta();
},
- customDomain() {
- return customDomainData.data;
- },
+ customDomain,
refetchMeta: () => props.refetchMeta(),
editorInstance: props.editorInstance,
dialog,
@@ -299,6 +301,8 @@ export const [EditorContextProvider, useEditorContext] = createContextProvider(
zoomOutLimit,
exportState,
setExportState,
+ micWaveforms,
+ systemAudioWaveforms,
};
},
// biome-ignore lint/style/noNonNullAssertion: it's ok
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 92fe99d66..e032c06a5 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -83,6 +83,12 @@ async getVideoMetadata(path: string) : Promise<VideoRecordingMetadata> {
async createEditorInstance() : Promise<SerializedEditorInstance> {
return await TAURI_INVOKE("create_editor_instance");
},
+async getMicWaveforms() : Promise<number[][]> {
+ return await TAURI_INVOKE("get_mic_waveforms");
+},
+async getSystemAudioWaveforms() : Promise<number[][]> {
+ return await TAURI_INVOKE("get_system_audio_waveforms");
+},
async startPlayback(fps: number, resolutionBase: XY<number>) : Promise<null> {
return await TAURI_INVOKE("start_playback", { fps, resolutionBase });
},
diff --git a/crates/media/src/feeds/audio.rs b/crates/media/src/feeds/audio.rs
index da3b5d3b7..edc0b5c7b 100644
--- a/crates/media/src/feeds/audio.rs
+++ b/crates/media/src/feeds/audio.rs
@@ -300,7 +300,12 @@ impl AudioRenderer {
if project.audio.mute {
f32::NEG_INFINITY
} else {
- t.gain(&project.audio)
+ let g = t.gain(&project.audio);
+ if g < -30.0 {
+ f32::NEG_INFINITY
+ } else {
+ g
+ }
},
t.stereo_mode(&project.audio),
)