Open source CapCut alternative.
TypeScript
feat(site): camera and mic pickers in the Cut record dialog
David Le37a7cfe1425a
diff --git a/site/src/cut/components/RecordDialog.tsx b/site/src/cut/components/RecordDialog.tsxindex 699506df..66ab4211 100644--- a/site/src/cut/components/RecordDialog.tsx+++ b/site/src/cut/components/RecordDialog.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useRef, useState } from "react";-import { Mic, Square } from "lucide-react";+import { Mic, Square, Video } from "lucide-react";import { Button } from "@/components/ui/button";import {Dialog,@@ -9,6 +9,13 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";import { formatTimecode } from "@/cut/lib/time";import { cn } from "@/lib/utils";@@ -29,6 +36,14 @@ function stamp() {return `${p(d.getHours())}.${p(d.getMinutes())}.${p(d.getSeconds())}`;}+type DeviceOption = { id: string; label: string };++function toOptions(devices: MediaDeviceInfo[], kind: MediaDeviceKind, fallback: string) {+ return devices+ .filter((d) => d.kind === kind && d.deviceId)+ .map((d, i) => ({ id: d.deviceId, label: d.label || `${fallback} ${i + 1}` }));+}+export function RecordDialog({mode,onClose,@@ -40,8 +55,13 @@ export function RecordDialog({}) {const [stream, setStream] = useState<MediaStream | null>(null);const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);const [recording, setRecording] = useState(false);const [elapsed, setElapsed] = useState(0);+ const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);+ // null = browser default; the pills show the device the live stream landed on.+ const [cameraId, setCameraId] = useState<string | null>(null);+ const [micId, setMicId] = useState<string | null>(null);const videoRef = useRef<HTMLVideoElement>(null);const recorderRef = useRef<MediaRecorder | null>(null);const chunksRef = useRef<Blob[]>([]);@@ -49,33 +69,64 @@ export function RecordDialog({useEffect(() => {let canceled = false;+ streamRef.current?.getTracks().forEach((t) => t.stop());+ streamRef.current = null;+ setStream(null);+ const audio: MediaTrackConstraints | boolean = micId+ ? { deviceId: { exact: micId } }+ : true;+ const constraints: MediaStreamConstraints =+ mode === "camera"+ ? {+ video: {+ width: { ideal: 1920 },+ height: { ideal: 1080 },+ ...(cameraId ? { deviceId: { exact: cameraId } } : {}),+ },+ audio,+ }+ : { audio };navigator.mediaDevices- .getUserMedia(- mode === "camera"- ? { video: { width: { ideal: 1920 }, height: { ideal: 1080 } }, audio: true }- : { audio: true }- )- .then((s) => {+ .getUserMedia(constraints)+ .then(async (s) => {if (canceled) {s.getTracks().forEach((t) => t.stop());return;}streamRef.current = s;setStream(s);+ // Device labels are only populated once permission is granted.+ const list = await navigator.mediaDevices.enumerateDevices();+ if (!canceled) setDevices(list);})- .catch(() =>+ .catch(() => {+ if (canceled) return;+ if (cameraId || micId) {+ // The picked device failed to start; fall back to the default.+ setCameraId(null);+ setMicId(null);+ setNotice("That device could not be started — switched back to the default.");+ return;+ }setError(mode === "camera"? "Camera access was blocked. Allow camera and microphone for this site in Chrome, then try again.": "Microphone access was blocked. Allow the microphone for this site in Chrome, then try again."- )- );+ );+ });return () => {canceled = true;recorderRef.current?.state === "recording" && recorderRef.current.stop();streamRef.current?.getTracks().forEach((t) => t.stop());};- }, [mode]);+ }, [mode, cameraId, micId]);++ useEffect(() => {+ const refresh = () =>+ navigator.mediaDevices.enumerateDevices().then(setDevices).catch(() => {});+ navigator.mediaDevices.addEventListener("devicechange", refresh);+ return () => navigator.mediaDevices.removeEventListener("devicechange", refresh);+ }, []);useEffect(() => {if (stream && videoRef.current) {@@ -123,6 +174,24 @@ export function RecordDialog({recorderRef.current?.stop();};+ // Picking a device clears the fallback notice so the live guidance returns —+ // the notice is set once on a device failure and must not outlive the retry.+ const pickCamera = (id: string) => {+ setNotice(null);+ setCameraId(id);+ };+ const pickMic = (id: string) => {+ setNotice(null);+ setMicId(id);+ };++ const cameras = toOptions(devices, "videoinput", "Camera");+ const mics = toOptions(devices, "audioinput", "Microphone");+ const activeCameraId =+ cameraId ?? stream?.getVideoTracks()[0]?.getSettings().deviceId ?? "";+ const activeMicId =+ micId ?? stream?.getAudioTracks()[0]?.getSettings().deviceId ?? "";+return (<Dialog open onOpenChange={(o) => !o && onClose()}><DialogContent className="sm:max-w-md">@@ -143,19 +212,55 @@ export function RecordDialog({playsInlineclassName="aspect-video w-full -scale-x-100 object-cover"/>+ {stream && (+ <LiveWaveform+ stream={stream}+ className={cn(+ "absolute inset-x-3 bottom-11 h-8 text-white/80",+ recording && "text-red-400"+ )}+ />+ )}{recording && <RecTimer elapsed={elapsed} />}+ <div className="absolute inset-x-0 bottom-2 flex justify-center gap-2 px-2">+ <DevicePill+ icon={<Video className="size-3.5 shrink-0" />}+ options={cameras}+ value={activeCameraId}+ onChange={pickCamera}+ disabled={recording}+ />+ <DevicePill+ icon={<Mic className="size-3.5 shrink-0" />}+ options={mics}+ value={activeMicId}+ onChange={pickMic}+ disabled={recording}+ />+ </div></div>) : (- <div className="relative grid h-36 place-items-center rounded-xl bg-muted">- <span- className={cn(- "grid size-16 place-items-center rounded-full bg-card text-foreground shadow-sm",- recording && "animate-pulse text-red-500"- )}- >- <Mic className="size-7" />- </span>+ <div className="relative grid h-36 place-items-center rounded-xl bg-muted px-4 pb-12">+ {stream ? (+ <LiveWaveform+ stream={stream}+ className={cn("h-16 w-full text-foreground/70", recording && "text-red-500")}+ />+ ) : (+ <span className="grid size-16 place-items-center rounded-full bg-card text-foreground shadow-sm">+ <Mic className="size-7" />+ </span>+ )}{recording && <RecTimer elapsed={elapsed} />}+ <div className="absolute inset-x-0 bottom-2 flex justify-center px-2">+ <DevicePill+ icon={<Mic className="size-3.5 shrink-0" />}+ options={mics}+ value={activeMicId}+ onChange={pickMic}+ disabled={recording}+ />+ </div></div>)}@@ -182,9 +287,8 @@ export function RecordDialog({<p className="text-center text-xs text-muted-foreground">{recording? "Recording — click stop to drop it on the timeline."- : stream- ? "Click the red button to start."- : "Waiting for permission…"}+ : notice ??+ (stream ? "Click the red button to start." : "Waiting for permission…")}</p></>)}@@ -199,6 +303,113 @@ export function RecordDialog({);}+/** Meet-style rounded device picker: icon + truncated device name + chevron. */+function DevicePill({+ icon,+ options,+ value,+ onChange,+ disabled,+}: {+ icon: React.ReactNode;+ options: DeviceOption[];+ value: string;+ onChange: (id: string) => void;+ disabled: boolean;+}) {+ if (options.length === 0) return null;+ const items = Object.fromEntries(options.map((o) => [o.id, o.label]));+ return (+ <Select+ value={items[value] ? value : options[0].id}+ items={items}+ onValueChange={(id) => onChange(id as string)}+ >+ <SelectTrigger+ size="sm"+ disabled={disabled}+ className="max-w-[46%] min-w-0 rounded-full border-white/25 bg-black/55 text-xs text-white backdrop-blur-sm hover:bg-black/70 dark:bg-black/55 dark:hover:bg-black/70 [&_svg]:text-white/80"+ >+ {icon}+ <SelectValue className="truncate" />+ </SelectTrigger>+ <SelectContent>+ {options.map((o) => (+ <SelectItem key={o.id} value={o.id} className="text-xs">+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}++/** Scrolling level meter fed by the stream's audio track; color follows CSS `color`. */+function LiveWaveform({ stream, className }: { stream: MediaStream; className?: string }) {+ const canvasRef = useRef<HTMLCanvasElement>(null);+ // Bar color follows CSS `color`. Resolve it only when the className changes+ // (i.e. when `recording` toggles) instead of every animation frame.+ const colorRef = useRef("");+ useEffect(() => {+ if (canvasRef.current) colorRef.current = getComputedStyle(canvasRef.current).color;+ }, [className]);++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas || stream.getAudioTracks().length === 0) return;+ const audioCtx = new AudioContext();+ void audioCtx.resume().catch(() => {});+ const source = audioCtx.createMediaStreamSource(stream);+ const analyser = audioCtx.createAnalyser();+ analyser.fftSize = 1024;+ source.connect(analyser);+ const samples = new Uint8Array(analyser.fftSize);+ const levels: number[] = [];+ let raf = 0;++ const draw = () => {+ raf = requestAnimationFrame(draw);+ analyser.getByteTimeDomainData(samples);+ let sum = 0;+ for (let i = 0; i < samples.length; i++) {+ const v = (samples[i] - 128) / 128;+ sum += v * v;+ }+ const rms = Math.sqrt(sum / samples.length);++ const dpr = window.devicePixelRatio || 1;+ const width = Math.round(canvas.clientWidth * dpr);+ const height = Math.round(canvas.clientHeight * dpr);+ if (canvas.width !== width) canvas.width = width;+ if (canvas.height !== height) canvas.height = height;+ const barWidth = 2 * dpr;+ const step = barWidth + 1 * dpr;+ const maxBars = Math.max(1, Math.floor(width / step));+ levels.push(rms);+ if (levels.length > maxBars) levels.splice(0, levels.length - maxBars);++ const g = canvas.getContext("2d");+ if (!g) return;+ g.clearRect(0, 0, width, height);+ g.fillStyle = colorRef.current || getComputedStyle(canvas).color;+ for (let i = 0; i < levels.length; i++) {+ const h = Math.max(2 * dpr, Math.min(1, levels[i] * 3) * height);+ const x = width - (levels.length - i) * step;+ g.fillRect(x, (height - h) / 2, barWidth, h);+ }+ };+ draw();++ return () => {+ cancelAnimationFrame(raf);+ source.disconnect();+ void audioCtx.close().catch(() => {});+ };+ }, [stream]);++ return <canvas ref={canvasRef} className={className} />;+}+function RecTimer({ elapsed }: { elapsed: number }) {return (<span className="absolute top-2 left-2 flex items-center gap-1.5 rounded-md bg-black/60 px-2 py-1 font-mono text-xs text-white tabular-nums">