Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): add timeline comment recording stack
Richie McIlroy681054417f1c
diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/CameraRecorderPanel.tsx b/apps/web/app/s/[videoId]/_components/timeline/recording/CameraRecorderPanel.tsxnew file mode 100644index 000000000..e9b7a8fb4--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/CameraRecorderPanel.tsx@@ -0,0 +1,165 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { useCameraDevices } from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/useCameraDevices";+import { formatClock } from "../timeline-format";+import {+ type CommentRecording,+ useCommentRecorder,+} from "./useCommentRecorder";++/**+ * Inline camera reply: mirrored live preview, device picker only when there's+ * a choice, Start → timer → Stop. Mic is on by default (mutable).+ */+export function CameraRecorderPanel({+ timestamp,+ onFinish,+ onCancel,+}: {+ timestamp: number;+ onFinish: (recording: CommentRecording) => void;+ onCancel: () => void;+}) {+ const previewRef = useRef<HTMLVideoElement | null>(null);+ const [opened, setOpened] = useState(false);+ const { devices: cameras } = useCameraDevices(true);++ const {+ phase,+ durationMs,+ micMuted,+ previewStream,+ error,+ openCamera,+ startCameraRecording,+ toggleMic,+ stop,+ cancel,+ } = useCommentRecorder({ onFinish, onPickerCancelled: onCancel });++ useEffect(() => {+ if (!opened) {+ setOpened(true);+ void openCamera();+ }+ }, [openCamera, opened]);++ useEffect(() => {+ if (previewRef.current && previewStream)+ previewRef.current.srcObject = previewStream;+ }, [previewStream]);++ const handleCancel = () => {+ cancel();+ onCancel();+ };++ const switchCamera = (deviceId: string) => {+ cancel();+ void openCamera({ camera: deviceId });+ };++ return (+ <div className="new-card-style flex w-80 flex-col gap-2 p-2.5">+ <div className="relative aspect-video w-full overflow-hidden rounded-xl bg-gray-3">+ {error ? (+ <div className="grid size-full place-items-center px-6 text-center text-xs text-gray-10">+ {error}+ </div>+ ) : (+ <video+ ref={previewRef}+ autoPlay+ muted+ playsInline+ className="size-full -scale-x-100 object-cover"+ />+ )}+ {phase === "recording" && (+ <span className="absolute top-2 left-2 flex items-center gap-1.5 rounded-full bg-black/55 px-2 py-0.5 text-[11px] tabular-nums text-white backdrop-blur-md">+ <span className="inline-flex size-2 rounded-full bg-red-500" />+ {formatClock(durationMs / 1000)}+ </span>+ )}+ </div>++ <div className="flex items-center gap-1.5">+ <span className="rounded-md bg-gray-2 px-1.5 py-0.5 font-mono text-[10px] tabular-nums text-gray-11 ring-1 ring-gray-4">+ {formatClock(timestamp)}+ </span>++ {cameras.length > 1 && phase === "ready" && (+ <select+ aria-label="Camera"+ onChange={(event) => switchCamera(event.target.value)}+ className="h-7 max-w-28 truncate rounded-lg bg-gray-2 px-1.5 text-[11px] text-gray-11 ring-1 ring-gray-4 outline-none"+ >+ {cameras.map((camera) => (+ <option key={camera.deviceId} value={camera.deviceId}>+ {camera.label || "Camera"}+ </option>+ ))}+ </select>+ )}++ <button+ type="button"+ onClick={toggleMic}+ aria-label={micMuted ? "Unmute microphone" : "Mute microphone"}+ aria-pressed={micMuted}+ className={`flex size-7 items-center justify-center rounded-lg ring-1 ring-gray-4 transition-colors ${+ micMuted ? "bg-gray-3 text-gray-9" : "bg-gray-2 text-gray-12"+ }`}+ >+ <svg+ viewBox="0 0 16 16"+ className="size-3.5"+ fill="currentColor"+ aria-hidden="true"+ >+ <path d="M8 1.5A2.25 2.25 0 0 0 5.75 3.75v3.5a2.25 2.25 0 0 0 4.5 0v-3.5A2.25 2.25 0 0 0 8 1.5Z" />+ <path d="M3.75 6.75a.65.65 0 0 1 1.3 0v.5a2.95 2.95 0 0 0 5.9 0v-.5a.65.65 0 0 1 1.3 0v.5a4.25 4.25 0 0 1-3.6 4.2v1.55h1.6a.65.65 0 0 1 0 1.3h-4.5a.65.65 0 0 1 0-1.3h1.6v-1.55a4.25 4.25 0 0 1-3.6-4.2v-.5Z" />+ {micMuted && (+ <path+ d="M2 2l12 12"+ stroke="currentColor"+ strokeWidth="1.4"+ strokeLinecap="round"+ />+ )}+ </svg>+ </button>++ <div className="flex-1" />++ <button+ type="button"+ onClick={handleCancel}+ className="h-7 rounded-lg px-2.5 text-xs text-gray-10 transition-colors hover:bg-gray-2 hover:text-gray-12"+ >+ Cancel+ </button>+ {phase === "recording" ? (+ <button+ type="button"+ onClick={stop}+ className="flex h-7 items-center gap-1.5 rounded-lg bg-gray-12 px-3 text-xs font-medium text-white transition-opacity hover:opacity-90"+ >+ <span className="inline-flex size-2 rounded-sm bg-red-400" />+ Stop+ </button>+ ) : (+ <button+ type="button"+ onClick={startCameraRecording}+ disabled={phase !== "ready"}+ className="h-7 rounded-lg bg-blue-9 px-3 text-xs font-medium text-white transition-opacity hover:opacity-90 disabled:opacity-40"+ >+ Start+ </button>+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/MediaPreviewPanel.tsx b/apps/web/app/s/[videoId]/_components/timeline/recording/MediaPreviewPanel.tsxnew file mode 100644index 000000000..b9d0dcc05--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/MediaPreviewPanel.tsx@@ -0,0 +1,62 @@+"use client";++import { useEffect, useMemo } from "react";+import { formatMediaDuration } from "../../media-comment/format-media-duration";+import { formatClock } from "../timeline-format";++/** Stop → look at it → send or retake. The blob loops muted until sent. */+export function MediaPreviewPanel({+ blob,+ durationSeconds,+ timestamp,+ onSend,+ onDiscard,+}: {+ blob: Blob;+ durationSeconds: number;+ timestamp: number;+ onSend: () => void;+ onDiscard: () => void;+}) {+ const previewUrl = useMemo(() => URL.createObjectURL(blob), [blob]);+ useEffect(() => () => URL.revokeObjectURL(previewUrl), [previewUrl]);++ return (+ <div className="new-card-style flex w-80 flex-col gap-2 p-2.5">+ <div className="relative aspect-video w-full overflow-hidden rounded-xl bg-gray-3">+ {/* biome-ignore lint/a11y/useMediaCaption: preview of the author's own recording */}+ <video+ src={previewUrl}+ autoPlay+ muted+ loop+ playsInline+ className="size-full object-contain"+ />+ <span className="absolute right-1.5 bottom-1.5 rounded bg-black/60 px-1.5 py-0.5 text-[10px] tabular-nums text-white">+ {formatMediaDuration(durationSeconds)}+ </span>+ </div>+ <div className="flex items-center gap-1.5">+ <span className="rounded-md bg-gray-2 px-1.5 py-0.5 font-mono text-[10px] tabular-nums text-gray-11 ring-1 ring-gray-4">+ {formatClock(timestamp)}+ </span>+ <div className="flex-1" />+ <button+ type="button"+ onClick={onDiscard}+ className="h-7 rounded-lg px-2.5 text-xs text-gray-10 transition-colors hover:bg-gray-2 hover:text-gray-12"+ >+ Retake+ </button>+ <button+ type="button"+ onClick={onSend}+ className="h-7 rounded-lg bg-blue-9 px-3.5 text-xs font-medium text-white transition-opacity hover:opacity-90"+ >+ Send+ </button>+ </div>+ </div>+ );+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/RecorderSurface.tsx b/apps/web/app/s/[videoId]/_components/timeline/recording/RecorderSurface.tsxnew file mode 100644index 000000000..b4354a364--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/RecorderSurface.tsx@@ -0,0 +1,272 @@+"use client";++import { Comment, type Video } from "@cap/web-domain";+import { AnimatePresence, motion, useReducedMotion } from "motion/react";+import { startTransition, useCallback, useState } from "react";+import { toast } from "sonner";+import { captureThumbnail } from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-conversion";+import { useCurrentUser } from "@/app/Layout/AuthContext";+import type { CommentType } from "../../../Share";+import {+ dropLocalMediaUrl,+ remapLocalMediaUrl,+ setLocalMediaUrl,+} from "../../media-comment/local-media-urls";+import type { RecordIntentKind } from "../TimelineComposer";+import { formatClock } from "../timeline-format";+import { CameraRecorderPanel } from "./CameraRecorderPanel";+import { normalizeCommentMedia } from "./convert-comment-media";+import { MediaPreviewPanel } from "./MediaPreviewPanel";+import { ScreenRecorderFloatingBar } from "./ScreenRecorderFloatingBar";+import {+ CommentMediaUploadError,+ uploadCommentMedia,+} from "./upload-comment-media";+import type { CommentRecording } from "./useCommentRecorder";+import type { VoiceRecording } from "./useVoiceRecorder";+import { VoiceRecorderBar } from "./VoiceRecorderBar";++export interface RecorderSurfaceProps {+ kind: RecordIntentKind;+ timestamp: number;+ videoId: Video.VideoId;+ onOptimisticComment?: (comment: CommentType) => void;+ onCommentSuccess?: (comment: CommentType) => void;+ onClose: () => void;+}++interface PendingVideo {+ blob: Blob;+ mime: string;+ durationSeconds: number;+ width?: number;+ height?: number;+ hasAudio: boolean;+}++const uploadErrorMessage = (error: unknown) => {+ if (error instanceof CommentMediaUploadError) {+ if (error.reason === "upgrade_required")+ return "Media comments aren't available on this video.";+ if (error.reason === "rate_limited")+ return "You're sending media comments too fast — try again in a bit.";+ }+ return "Couldn't send your recording. Please try again.";+};++/**+ * Lazy-loaded host for the three recording flows. Mounted by the timeline the+ * first time a record button is pressed; the capture hooks live in the child+ * components inside this chunk, so none of this code ships until then.+ */+export default function RecorderSurface({+ kind,+ timestamp,+ videoId,+ onOptimisticComment,+ onCommentSuccess,+ onClose,+}: RecorderSurfaceProps) {+ const user = useCurrentUser();+ const reduceMotion = useReducedMotion() ?? false;+ const [pendingVideo, setPendingVideo] = useState<PendingVideo | null>(null);++ const send = useCallback(+ (input: {+ blob: Blob;+ mime: string;+ mediaKind: "video" | "audio";+ durationSeconds: number;+ width?: number;+ height?: number;+ waveform?: number[];+ hasAudio: boolean;+ }) => {+ if (!user) return;++ const tempId = Comment.CommentId.make(`temp-${Date.now()}`);+ setLocalMediaUrl(tempId, URL.createObjectURL(input.blob));++ const now = new Date();+ const optimistic: CommentType = {+ id: tempId,+ authorId: user.id,+ authorName: user.name,+ authorImage: user.imageUrl,+ content: "",+ createdAt: now,+ updatedAt: now,+ videoId,+ parentCommentId: Comment.CommentId.make(""),+ type: input.mediaKind,+ timestamp,+ // Placeholder so isMediaComment holds; playback comes from the local+ // blob registry until the real key exists.+ mediaKey: `local/${tempId}`,+ mediaDuration: input.durationSeconds,+ mediaMeta: {+ mime: input.mime,+ width: input.width,+ height: input.height,+ waveform: input.waveform,+ },+ sending: true,+ };+ onOptimisticComment?.(optimistic);++ const pipeline = (async () => {+ const normalized = await normalizeCommentMedia({+ blob: input.blob,+ mime: input.mime,+ kind: input.mediaKind,+ hasAudio: input.hasAudio,+ });+ const thumbnailBlob =+ input.mediaKind === "video"+ ? await captureThumbnail(normalized.blob, {+ width: input.width,+ height: input.height,+ })+ : null;+ const saved = await uploadCommentMedia({+ videoId,+ blob: normalized.blob,+ mime: normalized.mime,+ kind: input.mediaKind,+ durationSeconds: input.durationSeconds,+ timestamp,+ parentCommentId: Comment.CommentId.make(""),+ width: input.width,+ height: input.height,+ waveform: input.waveform,+ thumbnailBlob,+ authorImage: user.imageUrl,+ });+ remapLocalMediaUrl(tempId, saved.id);+ onCommentSuccess?.(saved as CommentType);+ return saved;+ })().catch((error) => {+ dropLocalMediaUrl(tempId);+ throw error;+ });++ toast.promise(pipeline, {+ loading:+ input.mediaKind === "video"+ ? "Sending video comment…"+ : "Sending voice note…",+ success: `Comment added at ${formatClock(timestamp)}`,+ error: uploadErrorMessage,+ });++ // An async transition keeps the optimistic entry applied for the whole+ // upload; a sync one settles immediately and the card would vanish+ // until the real comment lands.+ startTransition(async () => {+ await pipeline.catch(() => {});+ });++ // The surface unmounts now; the pipeline keeps running behind the toast.+ onClose();+ },+ [onClose, onCommentSuccess, onOptimisticComment, timestamp, user, videoId],+ );++ const handleVoiceFinish = useCallback(+ (recording: VoiceRecording) => {+ send({+ blob: recording.blob,+ mime: recording.mime,+ mediaKind: "audio",+ durationSeconds: recording.durationSeconds,+ waveform: recording.waveform,+ hasAudio: true,+ });+ },+ [send],+ );++ const handleVideoFinish = useCallback((recording: CommentRecording) => {+ setPendingVideo(recording);+ }, []);++ const handlePreviewSend = useCallback(() => {+ if (!pendingVideo) return;+ send({+ blob: pendingVideo.blob,+ mime: pendingVideo.mime,+ mediaKind: "video",+ durationSeconds: pendingVideo.durationSeconds,+ width: pendingVideo.width,+ height: pendingVideo.height,+ hasAudio: pendingVideo.hasAudio,+ });+ }, [pendingVideo, send]);++ const handleCancel = useCallback(() => {+ onClose();+ }, [onClose]);++ if (!user) return null;++ const anchored = kind !== "screen" || pendingVideo !== null;++ return (+ <>+ {anchored && (+ <AnimatePresence>+ <motion.div+ key="recorder-surface"+ className="absolute bottom-full left-1/2 z-50 mb-2 -translate-x-1/2"+ initial={+ reduceMotion ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.96 }+ }+ animate={+ reduceMotion ? { opacity: 1 } : { opacity: 1, y: 0, scale: 1 }+ }+ exit={+ reduceMotion+ ? { opacity: 0, transition: { duration: 0 } }+ : { opacity: 0, scale: 0.95, transition: { duration: 0.12 } }+ }+ transition={+ reduceMotion+ ? { duration: 0 }+ : { type: "spring", stiffness: 420, damping: 34 }+ }+ >+ {pendingVideo ? (+ <MediaPreviewPanel+ blob={pendingVideo.blob}+ durationSeconds={pendingVideo.durationSeconds}+ timestamp={timestamp}+ onSend={handlePreviewSend}+ onDiscard={handleCancel}+ />+ ) : kind === "voice" ? (+ <VoiceRecorderBar+ timestamp={timestamp}+ onFinish={handleVoiceFinish}+ onCancel={handleCancel}+ />+ ) : kind === "camera" ? (+ <CameraRecorderPanel+ timestamp={timestamp}+ onFinish={handleVideoFinish}+ onCancel={handleCancel}+ />+ ) : null}+ </motion.div>+ </AnimatePresence>+ )}++ {kind === "screen" && !pendingVideo && (+ <ScreenRecorderFloatingBar+ timestamp={timestamp}+ onFinish={handleVideoFinish}+ onCancel={handleCancel}+ />+ )}+ </>+ );+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/ScreenRecorderFloatingBar.tsx b/apps/web/app/s/[videoId]/_components/timeline/recording/ScreenRecorderFloatingBar.tsxnew file mode 100644index 000000000..e45eb1dab--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/ScreenRecorderFloatingBar.tsx@@ -0,0 +1,137 @@+"use client";++import { AnimatePresence, motion } from "motion/react";+import { useEffect, useState } from "react";+import { formatClock } from "../timeline-format";+import {+ type CommentRecording,+ useCommentRecorder,+} from "./useCommentRecorder";++/**+ * Screen replies show the browser's picker immediately, then collapse to a+ * small fixed bar so the author can switch tabs while recording. The browser's+ * own "Stop sharing" also ends the recording.+ */+export function ScreenRecorderFloatingBar({+ timestamp,+ onFinish,+ onCancel,+}: {+ timestamp: number;+ onFinish: (recording: CommentRecording) => void;+ onCancel: () => void;+}) {+ const [started, setStarted] = useState(false);+ const {+ phase,+ durationMs,+ micMuted,+ error,+ startScreen,+ toggleMic,+ stop,+ cancel,+ } = useCommentRecorder({ onFinish, onPickerCancelled: onCancel });++ useEffect(() => {+ if (!started) {+ setStarted(true);+ void startScreen();+ }+ }, [startScreen, started]);++ useEffect(() => {+ if (error) {+ const timer = setTimeout(onCancel, 2500);+ return () => clearTimeout(timer);+ }+ }, [error, onCancel]);++ const handleCancel = () => {+ cancel();+ onCancel();+ };++ return (+ <AnimatePresence>+ {(phase === "recording" || error) && (+ <motion.div+ key="screen-bar"+ initial={{ opacity: 0, y: 16 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: 12 }}+ transition={{ type: "spring", stiffness: 420, damping: 34 }}+ className="fixed bottom-6 left-1/2 z-[60] -translate-x-1/2"+ >+ <div className="flex items-center gap-3 rounded-full border border-gray-5 bg-white py-2 pr-2 pl-4 shadow-[0_8px_24px_rgba(18,22,31,0.12)]">+ {error ? (+ <span className="text-xs text-gray-11">{error}</span>+ ) : (+ <>+ <span className="flex items-center gap-2">+ <span className="relative flex size-2.5">+ <span className="absolute inline-flex size-full animate-ping rounded-full bg-red-500 opacity-60" />+ <span className="relative inline-flex size-2.5 rounded-full bg-red-500" />+ </span>+ <span className="font-mono text-xs tabular-nums text-gray-12">+ {formatClock(durationMs / 1000)}+ </span>+ </span>+ <span className="text-[11px] text-gray-9">+ Recording reply at {formatClock(timestamp)}+ </span>+ <button+ type="button"+ onClick={toggleMic}+ aria-label={+ micMuted ? "Unmute microphone" : "Mute microphone"+ }+ aria-pressed={micMuted}+ className={`flex size-8 items-center justify-center rounded-full ring-1 ring-gray-4 transition-colors ${+ micMuted+ ? "bg-gray-3 text-gray-9"+ : "bg-gray-2 text-gray-12"+ }`}+ >+ <svg+ viewBox="0 0 16 16"+ className="size-3.5"+ fill="currentColor"+ aria-hidden="true"+ >+ <path d="M8 1.5A2.25 2.25 0 0 0 5.75 3.75v3.5a2.25 2.25 0 0 0 4.5 0v-3.5A2.25 2.25 0 0 0 8 1.5Z" />+ <path d="M3.75 6.75a.65.65 0 0 1 1.3 0v.5a2.95 2.95 0 0 0 5.9 0v-.5a.65.65 0 0 1 1.3 0v.5a4.25 4.25 0 0 1-3.6 4.2v1.55h1.6a.65.65 0 0 1 0 1.3h-4.5a.65.65 0 0 1 0-1.3h1.6v-1.55a4.25 4.25 0 0 1-3.6-4.2v-.5Z" />+ {micMuted && (+ <path+ d="M2 2l12 12"+ stroke="currentColor"+ strokeWidth="1.4"+ strokeLinecap="round"+ />+ )}+ </svg>+ </button>+ <button+ type="button"+ onClick={handleCancel}+ className="h-8 rounded-full px-3 text-xs text-gray-10 transition-colors hover:bg-gray-2 hover:text-gray-12"+ >+ Discard+ </button>+ <button+ type="button"+ onClick={stop}+ className="flex h-8 items-center gap-1.5 rounded-full bg-gray-12 px-3.5 text-xs font-medium text-white transition-opacity hover:opacity-90"+ >+ <span className="inline-flex size-2 rounded-sm bg-red-400" />+ Stop+ </button>+ </>+ )}+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ );+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/VoiceRecorderBar.tsx b/apps/web/app/s/[videoId]/_components/timeline/recording/VoiceRecorderBar.tsxnew file mode 100644index 000000000..62bd7e6fc--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/VoiceRecorderBar.tsx@@ -0,0 +1,130 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { formatClock } from "../timeline-format";+import { useVoiceRecorder, type VoiceRecording } from "./useVoiceRecorder";++const METER_BARS = 48;++/**+ * WhatsApp-style recording bar: pulsing dot, timer, live level bars, trash to+ * cancel, arrow to stop-and-send. Recording starts the moment it mounts — the+ * click that opened it is the one gesture, the permission prompt follows.+ */+export function VoiceRecorderBar({+ timestamp,+ onFinish,+ onCancel,+}: {+ timestamp: number;+ onFinish: (recording: VoiceRecording) => void;+ onCancel: () => void;+}) {+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const levelsRef = useRef<number[]>([]);+ const [started, setStarted] = useState(false);++ const { phase, durationMs, start, stop, cancel } = useVoiceRecorder({+ onFinish,+ onLevel: (level) => {+ const levels = levelsRef.current;+ levels.push(level);+ if (levels.length > METER_BARS) levels.shift();+ const canvas = canvasRef.current;+ const context = canvas?.getContext("2d");+ if (!canvas || !context) return;+ context.clearRect(0, 0, canvas.width, canvas.height);+ const mid = canvas.height / 2;+ context.fillStyle = "#1696e0";+ for (let index = 0; index < levels.length; index += 1) {+ const height = Math.max(2, (levels[index] ?? 0) * canvas.height);+ context.beginPath();+ context.roundRect(index * 4, mid - height / 2, 2, height, 1);+ context.fill();+ }+ },+ });++ useEffect(() => {+ if (!started) {+ setStarted(true);+ void start();+ }+ }, [start, started]);++ const handleCancel = () => {+ cancel();+ onCancel();+ };++ return (+ <div className="new-card-style flex items-center gap-3 p-2.5">+ <span className="flex items-center gap-2">+ <span className="relative flex size-2.5">+ <span className="absolute inline-flex size-full animate-ping rounded-full bg-red-500 opacity-60" />+ <span className="relative inline-flex size-2.5 rounded-full bg-red-500" />+ </span>+ <span className="font-mono text-xs tabular-nums text-gray-12">+ {formatClock(durationMs / 1000)}+ </span>+ </span>++ {phase === "denied" ? (+ <span className="text-xs text-gray-10">+ Microphone blocked — enable it in your browser+ </span>+ ) : (+ <canvas+ ref={canvasRef}+ width={METER_BARS * 4}+ height={22}+ className="h-[22px]"+ aria-hidden+ />+ )}++ <span className="rounded-md bg-gray-2 px-1.5 py-0.5 font-mono text-[10px] tabular-nums text-gray-11 ring-1 ring-gray-4">+ {formatClock(timestamp)}+ </span>++ <button+ type="button"+ onClick={handleCancel}+ aria-label="Discard voice note"+ className="flex size-8 items-center justify-center rounded-lg text-gray-10 transition-colors hover:bg-gray-2 hover:text-gray-12"+ >+ <svg+ viewBox="0 0 16 16"+ className="size-3.5"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.4"+ strokeLinecap="round"+ aria-hidden="true"+ >+ <path d="M3 4.5h10M6.5 4V3a1 1 0 0 1 1-1h1a1 1 0 0 1 1 1v1M4.5 4.5l.6 8a1 1 0 0 0 1 .9h3.8a1 1 0 0 0 1-.9l.6-8" />+ </svg>+ </button>+ <button+ type="button"+ onClick={stop}+ disabled={phase !== "recording"}+ aria-label="Send voice note"+ className="grid size-8 place-items-center rounded-full bg-blue-9 text-white transition-opacity hover:opacity-90 disabled:opacity-40"+ >+ <svg+ viewBox="0 0 16 16"+ className="size-4"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.6"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ >+ <path d="M8 12.5v-9M4 7l4-3.5L12 7" />+ </svg>+ </button>+ </div>+ );+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/compute-waveform-peaks.ts b/apps/web/app/s/[videoId]/_components/timeline/recording/compute-waveform-peaks.tsnew file mode 100644index 000000000..c25ffc02d--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/compute-waveform-peaks.ts@@ -0,0 +1,82 @@+export const WAVEFORM_PEAK_COUNT = 64;++/**+ * Accumulates loudness samples while a voice note records, so the waveform the+ * comment ships with is the same one the recorder showed live — no post-hoc+ * decode of a potentially long file on the send path.+ */+export class LivePeaksAccumulator {+ private samples: number[] = [];++ /** Push one RMS/level sample in 0..1 (call every ~60ms from the meter). */+ push(level: number) {+ this.samples.push(+ Number.isFinite(level) ? Math.min(1, Math.max(0, level)) : 0,+ );+ }++ get isEmpty() {+ return this.samples.length === 0;+ }++ /** Max-resample the run into `count` peaks, normalized so speech fills 0..1. */+ finish(count = WAVEFORM_PEAK_COUNT): number[] | undefined {+ if (this.samples.length === 0) return undefined;+ const out: number[] = new Array(count);+ for (let index = 0; index < count; index += 1) {+ const start = Math.floor((index * this.samples.length) / count);+ const end = Math.max(+ start + 1,+ Math.floor(((index + 1) * this.samples.length) / count),+ );+ let peak = 0;+ for (let source = start; source < end; source += 1) {+ const value = this.samples[source] ?? 0;+ if (value > peak) peak = value;+ }+ out[index] = peak;+ }+ // Quiet mics still deserve a visible waveform: scale the loudest peak to+ // full height, floors at a 0.1 gate so silence stays flat.+ const max = Math.max(...out);+ if (max > 0.1 && max < 1) {+ for (let index = 0; index < out.length; index += 1) {+ const value = out[index] ?? 0;+ out[index] = Math.min(1, value / max);+ }+ }+ return out.map((value) => Math.round(value * 100) / 100);+ }+}++/**+ * Fallback when the live meter produced nothing (e.g. the AudioContext failed+ * to start): decode the finished blob and extract peaks offline.+ */+export async function decodeToPeaks(+ blob: Blob,+ count = WAVEFORM_PEAK_COUNT,+): Promise<number[] | undefined> {+ try {+ const arrayBuffer = await blob.arrayBuffer();+ const context = new OfflineAudioContext(1, 1, 44100);+ const decoded = await context.decodeAudioData(arrayBuffer);+ const channel = decoded.getChannelData(0);+ if (channel.length === 0) return undefined;++ const accumulator = new LivePeaksAccumulator();+ const bucket = Math.max(1, Math.floor(channel.length / (count * 4)));+ for (let start = 0; start < channel.length; start += bucket) {+ let sum = 0;+ const end = Math.min(channel.length, start + bucket);+ for (let index = start; index < end; index += 1) {+ const sample = channel[index] ?? 0;+ sum += sample * sample;+ }+ accumulator.push(Math.sqrt(sum / (end - start)) * 3);+ }+ return accumulator.finish(count);+ } catch {+ return undefined;+ }+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/convert-comment-media.ts b/apps/web/app/s/[videoId]/_components/timeline/recording/convert-comment-media.tsnew file mode 100644index 000000000..4c9613fcf--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/convert-comment-media.ts@@ -0,0 +1,81 @@+import { installAvcLevelClamp } from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/avc-level-clamp";+import { canConvertToMp4InBrowser } from "@/app/(org)/dashboard/caps/components/web-recorder-dialog/recording-conversion";++const isMp4 = (mime: string) => mime.startsWith("video/mp4");+const isAudioMp4 = (mime: string) => mime.startsWith("audio/mp4");++const canEncodeAac = async () => {+ if (typeof AudioEncoder === "undefined") return false;+ try {+ const support = await AudioEncoder.isConfigSupported({+ codec: "mp4a.40.2",+ sampleRate: 48000,+ numberOfChannels: 2,+ });+ return support.supported === true;+ } catch {+ return false;+ }+};++const convert = async (+ blob: Blob,+ options: { video: boolean; onProgress?: (fraction: number) => void },+) => {+ const { convertMedia } = await import("@remotion/webcodecs");+ const restoreAvcLevelClamp = options.video ? installAvcLevelClamp() : null;+ try {+ const result = await convertMedia({+ src: new File([blob], "recording", { type: blob.type }),+ container: "mp4",+ ...(options.video ? { videoCodec: "h264" as const } : {}),+ audioCodec: "aac",+ onProgress: ({ overallProgress }) => {+ if (overallProgress !== null)+ options.onProgress?.(Math.min(1, Math.max(0, overallProgress)));+ },+ });+ return await result.save();+ } finally {+ restoreAvcLevelClamp?.();+ }+};++/**+ * Best-effort normalization of a recorded comment to mp4 (H.264/AAC) so iOS+ * viewers can play it. Falls back to the original blob when the platform has+ * no encoder (Firefox) or conversion fails — sending must never block on+ * conversion. Returns the blob plus the true mime to persist.+ */+export async function normalizeCommentMedia(input: {+ blob: Blob;+ mime: string;+ kind: "video" | "audio";+ hasAudio: boolean;+ onProgress?: (fraction: number) => void;+}): Promise<{ blob: Blob; mime: string }> {+ const { blob, mime, kind, hasAudio, onProgress } = input;++ try {+ if (kind === "video") {+ if (isMp4(mime)) return { blob, mime: "video/mp4" };+ if (!(await canConvertToMp4InBrowser(hasAudio))) return { blob, mime };+ const converted = await convert(blob, { video: true, onProgress });+ if (converted.size === 0) return { blob, mime };+ return { blob: converted, mime: "video/mp4" };+ }++ if (isAudioMp4(mime)) return { blob, mime: "audio/mp4" };+ if (!(await canEncodeAac())) return { blob, mime };+ const converted = await convert(blob, { video: false, onProgress });+ if (converted.size === 0) return { blob, mime };+ // convertMedia's mp4 output reports video/mp4 even for audio-only input;+ // the extension/content-type allowlist wants the audio flavour.+ return {+ blob: new Blob([converted], { type: "audio/mp4" }),+ mime: "audio/mp4",+ };+ } catch {+ return { blob, mime };+ }+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/recorder-constraints.ts b/apps/web/app/s/[videoId]/_components/timeline/recording/recorder-constraints.tsnew file mode 100644index 000000000..5a63486ed--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/recorder-constraints.ts@@ -0,0 +1,60 @@+export const MIC_CONSTRAINTS: MediaTrackConstraints = {+ echoCancellation: true,+ noiseSuppression: true,+ autoGainControl: true,+};++export const CAMERA_CONSTRAINTS: MediaTrackConstraints = {+ width: { ideal: 1280 },+ height: { ideal: 720 },+ frameRate: { ideal: 30 },+};++export const DISPLAY_CONSTRAINTS: MediaStreamConstraints & {+ systemAudio?: string;+} = {+ video: { height: { ideal: 720 }, frameRate: { ideal: 30 } },+ audio: true,+ // Chromium hint; ignored elsewhere.+ systemAudio: "include",+};++const pickSupported = (candidates: string[]) => {+ if (typeof MediaRecorder === "undefined") return null;+ for (const candidate of candidates) {+ try {+ if (MediaRecorder.isTypeSupported(candidate)) return candidate;+ } catch {+ // Some engines throw on unknown container strings.+ }+ }+ return null;+};++/**+ * Prefer AAC-in-mp4 (plays everywhere including iOS) over opus-in-webm.+ * Chrome-recorded webm/opus gets a conversion pass before upload where the+ * encoder exists; the true mime always travels in mediaMeta.+ */+export const pickVoiceMime = () =>+ pickSupported([+ "audio/mp4;codecs=mp4a.40.2",+ "audio/mp4",+ "audio/webm;codecs=opus",+ "audio/webm",+ ]);++/**+ * Prefer H.264 so the recording is mp4-ready without re-encoding; VP-in-webm+ * is the fallback and goes through the WebCodecs conversion pass when+ * supported (Firefox uploads raw webm — known iOS-viewer gap).+ */+export const pickVideoMime = () =>+ pickSupported([+ "video/mp4;codecs=avc1.42E01F,mp4a.40.2",+ "video/mp4",+ "video/webm;codecs=h264,opus",+ "video/webm;codecs=vp9,opus",+ "video/webm;codecs=vp8,opus",+ "video/webm",+ ]);diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/upload-comment-media.ts b/apps/web/app/s/[videoId]/_components/timeline/recording/upload-comment-media.tsnew file mode 100644index 000000000..b75714be0--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/upload-comment-media.ts@@ -0,0 +1,161 @@+import { InstantRecordingUploader } from "@cap/recorder-core";+import type { Storage } from "@cap/web-domain";+import { Comment, type ImageUpload, type Video } from "@cap/web-domain";+import { newMediaComment } from "@/actions/videos/new-media-comment";+import { uploadWithTarget } from "@/utils/upload-target";++const COMMENT_MEDIA_BASE = "/api/upload/comment-media";++export class CommentMediaUploadError extends Error {+ readonly reason: "upgrade_required" | "rate_limited" | "failed";++ constructor(reason: "upgrade_required" | "rate_limited" | "failed") {+ super(`Comment media upload failed: ${reason}`);+ this.name = "CommentMediaUploadError";+ this.reason = reason;+ }+}++interface InitiateResponse {+ commentId: string;+ key: string;+ uploadToken: string;+ upload?: Storage.UploadTarget;+ uploadId?: string;+ provider?: "s3" | "googleDrive";+ thumbnailUpload?: Storage.UploadTarget | null;+}++async function initiate(input: {+ videoId: string;+ kind: "video" | "audio";+ contentType: string;+ mode: "single" | "multipart";+ withThumbnail?: boolean;+}): Promise<InitiateResponse> {+ const response = await fetch(`${COMMENT_MEDIA_BASE}/initiate`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(input),+ });+ if (response.status === 403)+ throw new CommentMediaUploadError("upgrade_required");+ if (response.status === 429)+ throw new CommentMediaUploadError("rate_limited");+ if (!response.ok) throw new CommentMediaUploadError("failed");+ return (await response.json()) as InitiateResponse;+}++export interface CommentMediaUploadInput {+ videoId: Video.VideoId;+ blob: Blob;+ mime: string;+ kind: "video" | "audio";+ durationSeconds: number;+ timestamp: number | null;+ /** "" sentinel for top-level, matching the web client convention. */+ parentCommentId: Comment.CommentId;+ content?: string;+ width?: number;+ height?: number;+ waveform?: number[];+ thumbnailBlob?: Blob | null;+ authorImage: ImageUpload.ImageUrl | null;+ onProgress?: (fraction: number) => void;+}++/**+ * Full pipeline for a recorded comment: presign under the parent video's+ * prefix, upload (single PUT for voice notes, multipart for video), then+ * create the comment row. Returns the created comment (the shape+ * handleCommentSuccess expects).+ */+export async function uploadCommentMedia(input: CommentMediaUploadInput) {+ const isVideo = input.kind === "video";+ const init = await initiate({+ videoId: input.videoId,+ kind: input.kind,+ contentType: input.mime,+ mode: isVideo ? "multipart" : "single",+ withThumbnail: isVideo && Boolean(input.thumbnailBlob),+ });++ if (isVideo) {+ if (!init.uploadId) throw new CommentMediaUploadError("failed");+ const uploader = new InstantRecordingUploader({+ // Only used for labels and passthrough body fields the comment routes+ // ignore; authorization travels in the token.+ videoId: input.videoId,+ uploadId: init.uploadId,+ provider: init.provider ?? "s3",+ mimeType: input.mime,+ subpath: init.key,+ setUploadStatus: () => {},+ sendProgressUpdate: async (uploaded, total) => {+ if (total > 0) input.onProgress?.(Math.min(1, uploaded / total));+ },+ api: {+ multipartBasePath: COMMENT_MEDIA_BASE,+ extraBody: { uploadToken: init.uploadToken },+ },+ });+ try {+ await uploader.finalize({+ durationSeconds: input.durationSeconds,+ width: input.width,+ height: input.height,+ subpath: init.key,+ finalBlob: input.blob,+ });+ } catch (error) {+ // Incomplete multipart uploads accrue storage in the owner's bucket+ // until aborted; best-effort, the failure itself still surfaces.+ await fetch(`${COMMENT_MEDIA_BASE}/abort`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ uploadToken: init.uploadToken,+ uploadId: init.uploadId,+ }),+ }).catch(() => {});+ throw error;+ }+ } else {+ if (!init.upload) throw new CommentMediaUploadError("failed");+ await uploadWithTarget({+ target: init.upload,+ body: input.blob,+ onProgress: ({ loaded, total }) => {+ if (total > 0) input.onProgress?.(Math.min(1, loaded / total));+ },+ });+ }++ let hasThumbnail = false;+ if (isVideo && input.thumbnailBlob && init.thumbnailUpload) {+ // Non-fatal: a comment without a poster still plays.+ hasThumbnail = await uploadWithTarget({+ target: init.thumbnailUpload,+ body: input.thumbnailBlob,+ }).then(+ () => true,+ () => false,+ );+ }++ return await newMediaComment({+ videoId: input.videoId,+ commentId: Comment.CommentId.make(init.commentId),+ uploadToken: init.uploadToken,+ kind: input.kind,+ durationSeconds: input.durationSeconds,+ parentCommentId: input.parentCommentId,+ timestamp: input.timestamp,+ content: input.content,+ width: input.width,+ height: input.height,+ waveform: input.waveform,+ hasThumbnail,+ authorImage: input.authorImage,+ });+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/useCommentRecorder.ts b/apps/web/app/s/[videoId]/_components/timeline/recording/useCommentRecorder.tsnew file mode 100644index 000000000..082a7c2c6--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/useCommentRecorder.ts@@ -0,0 +1,325 @@+"use client";++import { isUserCancellationError } from "@cap/recorder-core";+import { useCallback, useEffect, useRef, useState } from "react";+import {+ CAMERA_CONSTRAINTS,+ DISPLAY_CONSTRAINTS,+ MIC_CONSTRAINTS,+ pickVideoMime,+} from "./recorder-constraints";++export type CommentRecorderMode = "camera" | "screen";++export type CommentRecorderPhase =+ | "idle"+ | "requesting"+ | "ready" // camera only: live preview, not yet recording+ | "recording"+ | "processing";++export interface CommentRecording {+ blob: Blob;+ mime: string;+ durationSeconds: number;+ width?: number;+ height?: number;+ hasAudio: boolean;+}++/**+ * Camera/screen recorder for video comments. Screen mode calls+ * `getDisplayMedia` immediately (the browser picker is the mode selector) and+ * mixes system audio with the mic through a limiter — the graph proven in the+ * dashboard web recorder. No duration cap (Pro feature).+ */+export function useCommentRecorder(options: {+ onFinish: (recording: CommentRecording) => void;+ /** User dismissed the browser's screen picker — treat as a silent cancel. */+ onPickerCancelled?: () => void;+}) {+ const [phase, setPhase] = useState<CommentRecorderPhase>("idle");+ const [durationMs, setDurationMs] = useState(0);+ const [micMuted, setMicMuted] = useState(false);+ const [previewStream, setPreviewStream] = useState<MediaStream | null>(null);+ const [error, setError] = useState<string | null>(null);++ const recorderRef = useRef<MediaRecorder | null>(null);+ const streamsRef = useRef<MediaStream[]>([]);+ const mixedStreamRef = useRef<MediaStream | null>(null);+ const audioContextRef = useRef<AudioContext | null>(null);+ const chunksRef = useRef<Blob[]>([]);+ const startedAtRef = useRef(0);+ const tickRef = useRef(0);+ const discardRef = useRef(false);+ // Bumped by cancel/unmount so an acquisition suspended on a permission+ // prompt or picker knows its run was abandoned and stops the granted+ // tracks instead of recording into an unmounted component.+ const runIdRef = useRef(0);+ const optionsRef = useRef(options);+ optionsRef.current = options;++ const abandoned = useCallback((runId: number, stream?: MediaStream) => {+ if (runId === runIdRef.current && !discardRef.current) return false;+ if (stream) for (const track of stream.getTracks()) track.stop();+ return true;+ }, []);++ const cleanup = useCallback(() => {+ if (tickRef.current) window.clearInterval(tickRef.current);+ tickRef.current = 0;+ for (const stream of streamsRef.current)+ for (const track of stream.getTracks()) track.stop();+ streamsRef.current = [];+ for (const track of mixedStreamRef.current?.getTracks() ?? []) track.stop();+ mixedStreamRef.current = null;+ void audioContextRef.current?.close().catch(() => {});+ audioContextRef.current = null;+ recorderRef.current = null;+ setPreviewStream(null);+ }, []);++ const beginRecording = useCallback(+ (stream: MediaStream) => {+ const mime = pickVideoMime();+ let recorder: MediaRecorder;+ try {+ recorder = new MediaRecorder(+ stream,+ mime ? { mimeType: mime } : undefined,+ );+ } catch {+ cleanup();+ setError("Recording isn't supported in this browser.");+ setPhase("idle");+ return;+ }+ recorderRef.current = recorder;+ chunksRef.current = [];++ recorder.addEventListener("dataavailable", (event) => {+ if (event.data.size > 0) chunksRef.current.push(event.data);+ });+ recorder.addEventListener("stop", () => {+ const elapsed = (performance.now() - startedAtRef.current) / 1000;+ const recordedMime = recorder.mimeType || mime || "video/webm";+ const blob = new Blob(chunksRef.current, { type: recordedMime });+ chunksRef.current = [];+ const settings = stream.getVideoTracks()[0]?.getSettings();+ const hasAudio = stream.getAudioTracks().length > 0;+ cleanup();++ if (discardRef.current || blob.size === 0) {+ setPhase("idle");+ setDurationMs(0);+ return;+ }+ setPhase("processing");+ optionsRef.current.onFinish({+ blob,+ mime: recordedMime,+ durationSeconds: elapsed,+ width: settings?.width,+ height: settings?.height,+ hasAudio,+ });+ setPhase("idle");+ setDurationMs(0);+ });++ // The browser's own "Stop sharing" bar ends the video track; treat it as+ // a normal stop.+ stream.getVideoTracks()[0]?.addEventListener("ended", () => {+ if (recorder.state === "recording") recorder.stop();+ });++ startedAtRef.current = performance.now();+ setDurationMs(0);+ tickRef.current = window.setInterval(() => {+ setDurationMs(performance.now() - startedAtRef.current);+ }, 500);+ recorder.start(1000);+ setPhase("recording");+ },+ [cleanup],+ );++ /** Camera: acquire devices and enter live preview; `startRecording` begins. */+ const openCamera = useCallback(+ async (deviceIds?: { camera?: string; microphone?: string }) => {+ setError(null);+ setPhase("requesting");+ discardRef.current = false;+ const runId = ++runIdRef.current;+ try {+ const stream = await navigator.mediaDevices.getUserMedia({+ video: {+ ...CAMERA_CONSTRAINTS,+ ...(deviceIds?.camera ? { deviceId: deviceIds.camera } : {}),+ },+ audio: {+ ...MIC_CONSTRAINTS,+ ...(deviceIds?.microphone+ ? { deviceId: deviceIds.microphone }+ : {}),+ },+ });+ if (abandoned(runId, stream)) return;+ streamsRef.current = [stream];+ mixedStreamRef.current = stream;+ setPreviewStream(stream);+ setPhase("ready");+ } catch (cause) {+ cleanup();+ setPhase("idle");+ if (isUserCancellationError(cause)) {+ optionsRef.current.onPickerCancelled?.();+ return;+ }+ setError("Camera or microphone access was blocked.");+ }+ },+ [cleanup],+ );++ const startCameraRecording = useCallback(() => {+ const stream = mixedStreamRef.current;+ if (phase !== "ready" || !stream) return;+ beginRecording(stream);+ }, [beginRecording, phase]);++ /** Screen: picker immediately, then mic mix, then recording starts. */+ const startScreen = useCallback(async () => {+ setError(null);+ setPhase("requesting");+ discardRef.current = false;+ const runId = ++runIdRef.current;++ let displayStream: MediaStream;+ try {+ displayStream = await navigator.mediaDevices.getDisplayMedia(+ DISPLAY_CONSTRAINTS as MediaStreamConstraints,+ );+ } catch (cause) {+ if (isUserCancellationError(cause)) {+ if (runId === runIdRef.current) setPhase("idle");+ optionsRef.current.onPickerCancelled?.();+ return;+ }+ // Some setups reject the audio request outright; retry video-only.+ try {+ displayStream = await navigator.mediaDevices.getDisplayMedia({+ video: DISPLAY_CONSTRAINTS.video,+ });+ } catch (retryCause) {+ if (runId !== runIdRef.current) return;+ setPhase("idle");+ if (isUserCancellationError(retryCause)) {+ optionsRef.current.onPickerCancelled?.();+ return;+ }+ setError("Screen recording isn't available here.");+ return;+ }+ }+ if (abandoned(runId, displayStream)) return;+ streamsRef.current = [displayStream];++ let micStream: MediaStream | null = null;+ try {+ micStream = await navigator.mediaDevices.getUserMedia({+ audio: MIC_CONSTRAINTS,+ });+ if (abandoned(runId, micStream)) return;+ streamsRef.current.push(micStream);+ } catch {+ // No mic is fine; system audio (if granted) still records.+ }++ const systemAudioTracks = displayStream.getAudioTracks();+ let audioTracks: MediaStreamTrack[] = [];+ if (systemAudioTracks.length > 0 && micStream) {+ // System + mic mixed through a limiter — verbatim from the dashboard+ // recorder's proven graph.+ const audioCtx = new AudioContext();+ audioContextRef.current = audioCtx;+ if (audioCtx.state !== "running") await audioCtx.resume();+ const systemSource = audioCtx.createMediaStreamSource(+ new MediaStream(systemAudioTracks),+ );+ const micSource = audioCtx.createMediaStreamSource(micStream);+ const destination = audioCtx.createMediaStreamDestination();+ const limiter = audioCtx.createDynamicsCompressor();+ limiter.threshold.value = -3;+ limiter.knee.value = 2;+ limiter.ratio.value = 20;+ limiter.attack.value = 0.002;+ limiter.release.value = 0.05;+ systemSource.connect(limiter);+ micSource.connect(limiter);+ limiter.connect(destination);+ audioTracks = destination.stream.getAudioTracks();+ } else if (systemAudioTracks.length > 0) {+ audioTracks = systemAudioTracks;+ } else if (micStream) {+ audioTracks = micStream.getAudioTracks();+ }++ const mixed = new MediaStream([+ ...displayStream.getVideoTracks(),+ ...audioTracks,+ ]);+ mixedStreamRef.current = mixed;+ beginRecording(mixed);+ }, [beginRecording]);++ const toggleMic = useCallback(() => {+ setMicMuted((muted) => {+ const next = !muted;+ for (const stream of streamsRef.current)+ for (const track of stream.getAudioTracks()) track.enabled = !next;+ return next;+ });+ }, []);++ const stop = useCallback(() => {+ if (recorderRef.current?.state === "recording") recorderRef.current.stop();+ }, []);++ const cancel = useCallback(() => {+ discardRef.current = true;+ runIdRef.current += 1;+ if (recorderRef.current?.state === "recording") {+ recorderRef.current.stop();+ } else {+ cleanup();+ setPhase("idle");+ setDurationMs(0);+ }+ }, [cleanup]);++ useEffect(+ () => () => {+ discardRef.current = true;+ runIdRef.current += 1;+ if (recorderRef.current?.state === "recording")+ recorderRef.current.stop();+ cleanup();+ },+ [cleanup],+ );++ return {+ phase,+ durationMs,+ micMuted,+ previewStream,+ error,+ openCamera,+ startCameraRecording,+ startScreen,+ toggleMic,+ stop,+ cancel,+ };+}diff --git a/apps/web/app/s/[videoId]/_components/timeline/recording/useVoiceRecorder.ts b/apps/web/app/s/[videoId]/_components/timeline/recording/useVoiceRecorder.tsnew file mode 100644index 000000000..0fd633125--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/timeline/recording/useVoiceRecorder.ts@@ -0,0 +1,191 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { decodeToPeaks, LivePeaksAccumulator } from "./compute-waveform-peaks";+import { MIC_CONSTRAINTS, pickVoiceMime } from "./recorder-constraints";++export type VoiceRecorderPhase =+ | "idle"+ | "requesting"+ | "denied"+ | "recording"+ | "processing";++export interface VoiceRecording {+ blob: Blob;+ mime: string;+ durationSeconds: number;+ waveform: number[] | undefined;+}++const LEVEL_SAMPLE_MS = 60;++/**+ * Audio-only recorder for voice-note comments: one tap starts (permission+ * prompt included), live level samples feed both the on-screen meter and the+ * waveform the comment ships with. No duration cap (Pro feature).+ */+export function useVoiceRecorder(options: {+ onFinish: (recording: VoiceRecording) => void;+ /** Live meter callback (0..1), called ~16/sec while recording. */+ onLevel?: (level: number) => void;+}) {+ const [phase, setPhase] = useState<VoiceRecorderPhase>("idle");+ const [durationMs, setDurationMs] = useState(0);++ const recorderRef = useRef<MediaRecorder | null>(null);+ const streamRef = useRef<MediaStream | null>(null);+ const audioContextRef = useRef<AudioContext | null>(null);+ const peaksRef = useRef<LivePeaksAccumulator | null>(null);+ const chunksRef = useRef<Blob[]>([]);+ const startedAtRef = useRef(0);+ const timersRef = useRef<{ level?: number; tick?: number }>({});+ const discardRef = useRef(false);+ // Bumped by cancel/unmount so a start() suspended on the permission prompt+ // can tell its run was abandoned — otherwise the granted mic stream would+ // record into an unmounted component with the indicator lit forever.+ const runIdRef = useRef(0);+ const optionsRef = useRef(options);+ optionsRef.current = options;++ const cleanup = useCallback(() => {+ const { level, tick } = timersRef.current;+ if (level) window.clearInterval(level);+ if (tick) window.clearInterval(tick);+ timersRef.current = {};+ for (const track of streamRef.current?.getTracks() ?? []) track.stop();+ streamRef.current = null;+ void audioContextRef.current?.close().catch(() => {});+ audioContextRef.current = null;+ recorderRef.current = null;+ }, []);++ const start = useCallback(async () => {+ if (phase === "recording" || phase === "requesting") return;+ setPhase("requesting");+ discardRef.current = false;+ const runId = ++runIdRef.current;++ let stream: MediaStream;+ try {+ stream = await navigator.mediaDevices.getUserMedia({+ audio: MIC_CONSTRAINTS,+ });+ } catch {+ if (runId === runIdRef.current) setPhase("denied");+ return;+ }+ if (runId !== runIdRef.current || discardRef.current) {+ for (const track of stream.getTracks()) track.stop();+ return;+ }+ streamRef.current = stream;++ const mime = pickVoiceMime();+ let recorder: MediaRecorder;+ try {+ recorder = new MediaRecorder(+ stream,+ mime ? { mimeType: mime } : undefined,+ );+ } catch {+ cleanup();+ setPhase("denied");+ return;+ }+ recorderRef.current = recorder;+ chunksRef.current = [];+ peaksRef.current = new LivePeaksAccumulator();++ // Live level meter: AnalyserNode RMS sampled on an interval — drives the+ // recording bar's canvas AND accumulates the persisted waveform.+ try {+ const audioContext = new AudioContext();+ audioContextRef.current = audioContext;+ const source = audioContext.createMediaStreamSource(stream);+ const analyser = audioContext.createAnalyser();+ analyser.fftSize = 256;+ source.connect(analyser);+ const buffer = new Float32Array(analyser.fftSize);+ timersRef.current.level = window.setInterval(() => {+ analyser.getFloatTimeDomainData(buffer);+ let sum = 0;+ for (const sample of buffer) sum += sample * sample;+ const level = Math.min(1, Math.sqrt(sum / buffer.length) * 3);+ peaksRef.current?.push(level);+ optionsRef.current.onLevel?.(level);+ }, LEVEL_SAMPLE_MS);+ } catch {+ // Meter is cosmetic; recording continues, decodeToPeaks covers the+ // waveform on stop.+ }++ recorder.addEventListener("dataavailable", (event) => {+ if (event.data.size > 0) chunksRef.current.push(event.data);+ });+ recorder.addEventListener("stop", () => {+ const elapsed = (performance.now() - startedAtRef.current) / 1000;+ const recordedMime = recorder.mimeType || mime || "audio/webm";+ const blob = new Blob(chunksRef.current, { type: recordedMime });+ chunksRef.current = [];+ const livePeaks = peaksRef.current?.finish();+ cleanup();++ if (discardRef.current || blob.size === 0) {+ setPhase("idle");+ setDurationMs(0);+ return;+ }++ setPhase("processing");+ void (async () => {+ const waveform = livePeaks ?? (await decodeToPeaks(blob));+ optionsRef.current.onFinish({+ blob,+ mime: recordedMime,+ durationSeconds: elapsed,+ waveform,+ });+ setPhase("idle");+ setDurationMs(0);+ })();+ });++ startedAtRef.current = performance.now();+ setDurationMs(0);+ timersRef.current.tick = window.setInterval(() => {+ setDurationMs(performance.now() - startedAtRef.current);+ }, 500);+ recorder.start(1000);+ setPhase("recording");+ }, [cleanup, phase]);++ const stop = useCallback(() => {+ if (recorderRef.current?.state === "recording") recorderRef.current.stop();+ }, []);++ const cancel = useCallback(() => {+ discardRef.current = true;+ runIdRef.current += 1;+ if (recorderRef.current?.state === "recording") {+ recorderRef.current.stop();+ } else {+ cleanup();+ setPhase("idle");+ setDurationMs(0);+ }+ }, [cleanup]);++ useEffect(+ () => () => {+ discardRef.current = true;+ runIdRef.current += 1;+ if (recorderRef.current?.state === "recording")+ recorderRef.current.stop();+ cleanup();+ },+ [cleanup],+ );++ return { phase, durationMs, start, stop, cancel };+}