OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat(editor): add beat sync for audio clips
Augustus Otuafad4ac795cf
diff --git a/apps/web/src/bridges/audio-text-sync-bridge.ts b/apps/web/src/bridges/audio-text-sync-bridge.tsnew file mode 100644index 00000000..39b56418--- /dev/null+++ b/apps/web/src/bridges/audio-text-sync-bridge.ts@@ -0,0 +1,356 @@+import {+ getBeatSyncEngine,+ type ClipTiming,+ type ClipInfo,+ type SyncProgress,+ type BeatSyncConfig,+ type BeatAnalysisResult,+ DEFAULT_BEAT_SYNC_CONFIG,+} from "@openreel/core";+import { useProjectStore } from "../stores/project-store";++export interface BeatSyncState {+ isProcessing: boolean;+ progress: SyncProgress | null;+ beatAnalysis: BeatAnalysisResult | null;+ selectedAudioClipId: string | null;+ selectedTrackIds: string[];+ clipsToSync: ClipInfo[];+ previewTimings: ClipTiming[];+ config: BeatSyncConfig;+ error: string | null;+}++type StateListener = (state: BeatSyncState) => void;++const initialState: BeatSyncState = {+ isProcessing: false,+ progress: null,+ beatAnalysis: null,+ selectedAudioClipId: null,+ selectedTrackIds: [],+ clipsToSync: [],+ previewTimings: [],+ config: DEFAULT_BEAT_SYNC_CONFIG,+ error: null,+};++export class BeatSyncBridge {+ private state: BeatSyncState = { ...initialState };+ private listeners: Set<StateListener> = new Set();+ private audioContext: AudioContext | null = null;++ subscribe(listener: StateListener): () => void {+ this.listeners.add(listener);+ listener(this.state);+ return () => this.listeners.delete(listener);+ }++ private setState(updates: Partial<BeatSyncState>): void {+ this.state = { ...this.state, ...updates };+ this.listeners.forEach((listener) => listener(this.state));+ }++ getState(): BeatSyncState {+ return this.state;+ }++ setSelectedAudioClip(clipId: string | null): void {+ this.setState({+ selectedAudioClipId: clipId,+ beatAnalysis: null,+ previewTimings: [],+ error: null,+ });+ }++ setSelectedTracks(trackIds: string[]): void {+ this.setState({ selectedTrackIds: trackIds });+ this.updateClipsToSync();+ this.updatePreview();+ }++ toggleTrackSelection(trackId: string): void {+ const { selectedTrackIds } = this.state;+ const newIds = selectedTrackIds.includes(trackId)+ ? selectedTrackIds.filter((id) => id !== trackId)+ : [...selectedTrackIds, trackId];+ this.setSelectedTracks(newIds);+ }++ updateConfig(updates: Partial<BeatSyncConfig>): void {+ this.setState({+ config: { ...this.state.config, ...updates } as BeatSyncConfig,+ });+ this.updatePreview();+ }++ private updateClipsToSync(): void {+ const { selectedTrackIds } = this.state;+ const store = useProjectStore.getState();+ const { project } = store;++ const clips: ClipInfo[] = [];++ for (const track of project.timeline.tracks) {+ if (selectedTrackIds.includes(track.id)) {+ for (const clip of track.clips) {+ clips.push({+ id: clip.id,+ startTime: clip.startTime,+ duration: clip.duration,+ trackId: track.id,+ });+ }+ }+ }++ this.setState({ clipsToSync: clips });+ }++ private updatePreview(): void {+ const { beatAnalysis, clipsToSync, config, selectedAudioClipId } = this.state;+ if (!beatAnalysis || clipsToSync.length === 0) {+ this.setState({ previewTimings: [] });+ return;+ }++ const store = useProjectStore.getState();+ const audioClip = selectedAudioClipId ? store.getClip(selectedAudioClipId) : null;+ const audioStartTime = audioClip?.startTime ?? 0;++ const engine = getBeatSyncEngine();+ const timings = engine.calculateSyncedTimings(+ clipsToSync,+ beatAnalysis,+ audioStartTime,+ config,+ );++ this.setState({ previewTimings: timings });+ }++ async analyzeBeats(): Promise<void> {+ const { selectedAudioClipId } = this.state;+ if (!selectedAudioClipId) {+ this.setState({ error: "No audio clip selected" });+ return;+ }++ const store = useProjectStore.getState();+ const clip = store.getClip(selectedAudioClipId);+ if (!clip) {+ this.setState({ error: "Clip not found" });+ return;+ }++ const mediaItem = store.getMediaItem(clip.mediaId);+ if (!mediaItem?.blob) {+ this.setState({ error: "Media blob not found" });+ return;+ }++ this.setState({ isProcessing: true, error: null });++ try {+ const audioBlob = await this.extractAudioFromBlob(+ mediaItem.blob,+ clip.inPoint ?? 0,+ clip.outPoint ?? clip.duration,+ );++ const engine = getBeatSyncEngine();+ const beatAnalysis = await engine.analyzeBeats(audioBlob, (progress) =>+ this.setState({ progress }),+ );++ this.setState({+ beatAnalysis,+ isProcessing: false,+ progress: null,+ });++ this.updatePreview();+ } catch (error) {+ this.setState({+ isProcessing: false,+ error: error instanceof Error ? error.message : "Beat analysis failed",+ progress: null,+ });+ }+ }++ async applySync(): Promise<boolean> {+ const { previewTimings } = this.state;+ if (previewTimings.length === 0) {+ this.setState({ error: "No clips to sync" });+ return false;+ }++ const store = useProjectStore.getState();++ this.setState({ isProcessing: true, error: null });++ try {+ for (const timing of previewTimings) {+ await store.moveClip(timing.clipId, timing.newStartTime);++ const clip = store.getClip(timing.clipId);+ if (clip && this.state.config.syncMode !== "preserve-duration") {+ const newOutPoint = (clip.inPoint ?? 0) + timing.newDuration;+ await store.trimClip(timing.clipId, clip.inPoint, newOutPoint);+ }+ }++ this.setState({+ isProcessing: false,+ progress: {+ phase: "complete",+ percent: 100,+ message: `Synced ${previewTimings.length} clips to beats`,+ },+ });++ return true;+ } catch (error) {+ this.setState({+ isProcessing: false,+ error: error instanceof Error ? error.message : "Failed to apply sync",+ });+ return false;+ }+ }++ getAvailableTracks(): Array<{ id: string; name: string; type: string; clipCount: number }> {+ const store = useProjectStore.getState();+ const { project } = store;+ const { selectedAudioClipId } = this.state;++ const audioClip = selectedAudioClipId ? store.getClip(selectedAudioClipId) : null;+ const audioTrackId = audioClip+ ? project.timeline.tracks.find((t) => t.clips.some((c) => c.id === selectedAudioClipId))?.id+ : null;++ return project.timeline.tracks+ .filter((track) => track.id !== audioTrackId && track.clips.length > 0)+ .map((track) => ({+ id: track.id,+ name: track.name,+ type: track.type,+ clipCount: track.clips.length,+ }));+ }++ private async extractAudioFromBlob(+ blob: Blob,+ inPoint: number,+ outPoint: number,+ ): Promise<Blob> {+ if (!this.audioContext) {+ this.audioContext = new AudioContext();+ }++ const arrayBuffer = await blob.arrayBuffer();+ const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);++ const duration = Math.min(outPoint - inPoint, audioBuffer.duration - inPoint);+ const sampleRate = audioBuffer.sampleRate;+ const startSample = Math.floor(inPoint * sampleRate);+ const numSamples = Math.floor(duration * sampleRate);++ const offlineContext = new OfflineAudioContext(1, numSamples, sampleRate);+ const trimmedBuffer = offlineContext.createBuffer(1, numSamples, sampleRate);+ const channelData = trimmedBuffer.getChannelData(0);+ const sourceData = audioBuffer.getChannelData(0);++ for (let i = 0; i < numSamples; i++) {+ channelData[i] = sourceData[startSample + i] || 0;+ }++ const source = offlineContext.createBufferSource();+ source.buffer = trimmedBuffer;+ source.connect(offlineContext.destination);+ source.start(0);++ const renderedBuffer = await offlineContext.startRendering();+ return this.audioBufferToWav(renderedBuffer);+ }++ private audioBufferToWav(buffer: AudioBuffer): Blob {+ const numChannels = buffer.numberOfChannels;+ const sampleRate = buffer.sampleRate;+ const format = 1;+ const bitDepth = 16;++ const bytesPerSample = bitDepth / 8;+ const blockAlign = numChannels * bytesPerSample;+ const byteRate = sampleRate * blockAlign;+ const dataSize = buffer.length * blockAlign;+ const headerSize = 44;+ const totalSize = headerSize + dataSize;++ const arrayBuffer = new ArrayBuffer(totalSize);+ const view = new DataView(arrayBuffer);++ const writeString = (offset: number, str: string) => {+ for (let i = 0; i < str.length; i++) {+ view.setUint8(offset + i, str.charCodeAt(i));+ }+ };++ writeString(0, "RIFF");+ view.setUint32(4, totalSize - 8, true);+ writeString(8, "WAVE");+ writeString(12, "fmt ");+ view.setUint32(16, 16, true);+ view.setUint16(20, format, true);+ view.setUint16(22, numChannels, true);+ view.setUint32(24, sampleRate, true);+ view.setUint32(28, byteRate, true);+ view.setUint16(32, blockAlign, true);+ view.setUint16(34, bitDepth, true);+ writeString(36, "data");+ view.setUint32(40, dataSize, true);++ const channelDataArr = buffer.getChannelData(0);+ let offset = 44;+ for (let i = 0; i < buffer.length; i++) {+ const sample = Math.max(-1, Math.min(1, channelDataArr[i]));+ const intSample = sample < 0 ? sample * 0x8000 : sample * 0x7fff;+ view.setInt16(offset, intSample, true);+ offset += 2;+ }++ return new Blob([arrayBuffer], { type: "audio/wav" });+ }++ reset(): void {+ this.setState({ ...initialState });+ }++ dispose(): void {+ if (this.audioContext) {+ this.audioContext.close();+ this.audioContext = null;+ }+ this.listeners.clear();+ }+}++let bridgeInstance: BeatSyncBridge | null = null;++export function getBeatSyncBridge(): BeatSyncBridge {+ if (!bridgeInstance) {+ bridgeInstance = new BeatSyncBridge();+ }+ return bridgeInstance;+}++export function disposeBeatSyncBridge(): void {+ if (bridgeInstance) {+ bridgeInstance.dispose();+ bridgeInstance = null;+ }+}++export { DEFAULT_BEAT_SYNC_CONFIG, type BeatSyncConfig, type ClipTiming, type BeatAnalysisResult };diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsxindex a1e26617..0e936352 100644--- a/apps/web/src/components/editor/InspectorPanel.tsx+++ b/apps/web/src/components/editor/InspectorPanel.tsx@@ -45,6 +45,7 @@ import {EmphasisAnimationSection,MotionPathSection,ParticleEffectsSection,+ AudioTextSyncPanel,} from "./inspector";import {getAudioBridgeEffects,@@ -711,6 +712,13 @@ export const InspectorPanel: React.FC = () => {</div>)}+ {/* Beat Sync - Sync other clips to this audio's beats */}+ {clipType === "audio" && (+ <Section title="Beat Sync" sectionId="beat-sync" defaultOpen={false}>+ <AudioTextSyncPanel clipId={clipId} />+ </Section>+ )}+{/* Transform */}{showTransformControls && (<Section title="Transform" sectionId="transform">diff --git a/apps/web/src/components/editor/inspector/AudioTextSyncPanel.tsx b/apps/web/src/components/editor/inspector/AudioTextSyncPanel.tsxnew file mode 100644index 00000000..685e24f3--- /dev/null+++ b/apps/web/src/components/editor/inspector/AudioTextSyncPanel.tsx@@ -0,0 +1,325 @@+import React, { useCallback, useEffect, useState, useMemo } from "react";+import { Music, Loader2, AlertCircle, Check, Settings2, Image, Type, Video } from "lucide-react";+import { Button, LabeledSlider } from "@openreel/ui";+import {+ getBeatSyncBridge,+ type BeatSyncState,+ DEFAULT_BEAT_SYNC_CONFIG,+} from "../../../bridges/audio-text-sync-bridge";+import type { SyncMode } from "@openreel/core";++interface BeatSyncPanelProps {+ clipId: string;+}++const TRACK_ICONS: Record<string, React.ReactNode> = {+ video: <Video size={12} />,+ image: <Image size={12} />,+ text: <Type size={12} />,+ graphics: <Type size={12} />,+};++export const AudioTextSyncPanel: React.FC<BeatSyncPanelProps> = ({ clipId }) => {+ const [state, setState] = useState<BeatSyncState | null>(null);+ const [showSettings, setShowSettings] = useState(false);++ const bridge = useMemo(() => getBeatSyncBridge(), []);++ useEffect(() => {+ const unsubscribe = bridge.subscribe(setState);+ bridge.setSelectedAudioClip(clipId);+ return unsubscribe;+ }, [bridge, clipId]);++ const availableTracks = useMemo(() => {+ return bridge.getAvailableTracks();+ }, [bridge, state?.beatAnalysis]);++ const handleAnalyzeBeats = useCallback(() => {+ bridge.analyzeBeats();+ }, [bridge]);++ const handleToggleTrack = useCallback(+ (trackId: string) => {+ bridge.toggleTrackSelection(trackId);+ },+ [bridge],+ );++ const handleApply = useCallback(async () => {+ await bridge.applySync();+ }, [bridge]);++ const handleUpdateConfig = useCallback(+ (updates: Partial<typeof DEFAULT_BEAT_SYNC_CONFIG>) => {+ bridge.updateConfig(updates);+ },+ [bridge],+ );++ if (!state) {+ return (+ <div className="p-4 flex items-center justify-center">+ <Loader2 size={20} className="animate-spin text-primary" />+ </div>+ );+ }++ const {+ isProcessing,+ progress,+ beatAnalysis,+ selectedTrackIds,+ clipsToSync,+ previewTimings,+ config,+ error,+ } = state;++ return (+ <div className="space-y-4">+ <div className="flex items-center gap-2 text-text-secondary">+ <Music size={14} />+ <span className="text-[10px]">Sync clips to the beat of this audio</span>+ </div>++ {error && (+ <div className="flex items-center gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg">+ <AlertCircle size={14} className="text-red-400 shrink-0" />+ <span className="text-[10px] text-red-400">{error}</span>+ </div>+ )}++ {!beatAnalysis ? (+ <div className="space-y-3">+ {isProcessing && progress ? (+ <div className="space-y-2">+ <div className="flex items-center gap-2">+ <Loader2 size={12} className="animate-spin text-primary" />+ <span className="text-[10px] text-text-primary">{progress.message}</span>+ </div>+ <div className="h-1.5 bg-background-tertiary rounded-full overflow-hidden">+ <div+ className="h-full bg-primary transition-all duration-300"+ style={{ width: `${progress.percent}%` }}+ />+ </div>+ </div>+ ) : (+ <Button+ onClick={handleAnalyzeBeats}+ className="w-full bg-primary/20 hover:bg-primary/30 text-primary border border-primary/30"+ >+ <Music size={14} className="mr-2" />+ Detect Beats+ </Button>+ )}+ </div>+ ) : (+ <div className="space-y-4">+ <div className="flex items-center justify-between p-3 bg-primary/10 rounded-lg border border-primary/30">+ <div>+ <span className="text-[10px] text-text-secondary block">BPM Detected</span>+ <span className="text-lg font-bold text-primary">{beatAnalysis.bpm}</span>+ </div>+ <div className="text-right">+ <span className="text-[10px] text-text-secondary block">Beats</span>+ <span className="text-sm font-medium text-text-primary">+ {beatAnalysis.beats.length}+ </span>+ </div>+ </div>++ <div className="space-y-2">+ <span className="text-[10px] text-text-secondary block">+ Select tracks to sync to beats:+ </span>++ {availableTracks.length === 0 ? (+ <p className="text-[10px] text-text-muted p-3 bg-background-tertiary rounded-lg">+ No other tracks with clips found. Add clips to other tracks first.+ </p>+ ) : (+ <div className="space-y-1">+ {availableTracks.map((track) => (+ <button+ key={track.id}+ onClick={() => handleToggleTrack(track.id)}+ className={`w-full flex items-center justify-between p-2 rounded-lg text-left transition-colors ${+ selectedTrackIds.includes(track.id)+ ? "bg-primary/20 border border-primary/50"+ : "bg-background-tertiary border border-transparent hover:border-border"+ }`}+ >+ <div className="flex items-center gap-2">+ {TRACK_ICONS[track.type] || <Video size={12} />}+ <span className="text-[11px] text-text-primary">{track.name}</span>+ </div>+ <span className="text-[9px] text-text-muted">+ {track.clipCount} {track.clipCount === 1 ? "clip" : "clips"}+ </span>+ </button>+ ))}+ </div>+ )}+ </div>++ {clipsToSync.length > 0 && (+ <div className="p-2 bg-background-tertiary rounded-lg">+ <span className="text-[9px] text-text-muted">+ {clipsToSync.length} clips will be synced to {beatAnalysis.beats.length} beats+ </span>+ </div>+ )}++ <div className="border-t border-border pt-3">+ <button+ onClick={() => setShowSettings(!showSettings)}+ className="flex items-center gap-2 text-[10px] text-text-secondary hover:text-text-primary mb-3"+ >+ <Settings2 size={12} />+ Sync Settings+ </button>++ {showSettings && (+ <div className="space-y-3 p-3 bg-background-tertiary rounded-lg">+ <div>+ <span className="text-[10px] text-text-secondary block mb-2">Sync Mode</span>+ <div className="space-y-1">+ {([+ { value: "smart", label: "Smart", desc: "Adjust duration to fit nearest beat count" },+ { value: "one-per-beat", label: "One per Beat", desc: "Each clip gets exactly one beat" },+ { value: "preserve-duration", label: "Preserve Duration", desc: "Keep original duration, snap start to beat" },+ ] as const).map((mode) => (+ <button+ key={mode.value}+ onClick={() => handleUpdateConfig({ syncMode: mode.value as SyncMode })}+ className={`w-full text-left p-2 rounded transition-colors ${+ config.syncMode === mode.value+ ? "bg-primary/20 border border-primary/50"+ : "bg-background-secondary border border-transparent hover:border-border"+ }`}+ >+ <span className="text-[10px] text-text-primary block">{mode.label}</span>+ <span className="text-[9px] text-text-muted">{mode.desc}</span>+ </button>+ ))}+ </div>+ </div>++ <div className="flex items-center justify-between">+ <span className="text-[10px] text-text-secondary">Beat Subdivision</span>+ <div className="flex gap-1">+ {([1, 2, 4] as const).map((sub) => (+ <button+ key={sub}+ onClick={() => handleUpdateConfig({ beatSubdivision: sub })}+ className={`px-2 py-1 text-[9px] rounded transition-colors ${+ config.beatSubdivision === sub+ ? "bg-primary text-black"+ : "bg-background-secondary text-text-secondary hover:text-text-primary"+ }`}+ >+ 1/{sub}+ </button>+ ))}+ </div>+ </div>++ <LabeledSlider+ label="Offset"+ value={config.offsetMs}+ onChange={(v) => handleUpdateConfig({ offsetMs: v })}+ min={-500}+ max={500}+ step={10}+ unit="ms"+ />++ <div className="flex items-center justify-between">+ <span className="text-[10px] text-text-secondary">Downbeats Only</span>+ <div className="flex gap-1">+ <button+ onClick={() => handleUpdateConfig({ snapToDownbeats: false })}+ className={`px-2 py-1 text-[9px] rounded transition-colors ${+ !config.snapToDownbeats+ ? "bg-primary text-black"+ : "bg-background-secondary text-text-secondary"+ }`}+ >+ All Beats+ </button>+ <button+ onClick={() => handleUpdateConfig({ snapToDownbeats: true })}+ className={`px-2 py-1 text-[9px] rounded transition-colors ${+ config.snapToDownbeats+ ? "bg-primary text-black"+ : "bg-background-secondary text-text-secondary"+ }`}+ >+ Downbeats+ </button>+ </div>+ </div>+ </div>+ )}+ </div>++ {previewTimings.length > 0 && (+ <div className="space-y-2">+ <span className="text-[9px] text-text-muted">Preview:</span>+ <div className="max-h-24 overflow-y-auto bg-background-tertiary rounded-lg p-2 space-y-1">+ {previewTimings.slice(0, 5).map((timing, idx) => (+ <div+ key={timing.clipId}+ className="flex items-center justify-between text-[9px]"+ >+ <span className="text-text-muted">Clip {idx + 1}</span>+ <span className="text-text-primary">+ {timing.originalStartTime.toFixed(2)}s → {timing.newStartTime.toFixed(2)}s+ </span>+ </div>+ ))}+ {previewTimings.length > 5 && (+ <span className="text-[9px] text-text-muted">+ ...and {previewTimings.length - 5} more+ </span>+ )}+ </div>+ </div>+ )}++ {progress?.phase === "complete" && (+ <div className="flex items-center gap-2 p-2 bg-green-500/10 rounded-lg border border-green-500/30">+ <Check size={14} className="text-green-400" />+ <span className="text-[10px] text-green-400">{progress.message}</span>+ </div>+ )}++ <Button+ onClick={handleApply}+ disabled={isProcessing || previewTimings.length === 0}+ className="w-full bg-primary hover:bg-primary/80 text-black disabled:opacity-50"+ >+ {isProcessing ? (+ <>+ <Loader2 size={14} className="mr-2 animate-spin" />+ Syncing...+ </>+ ) : (+ `Sync ${previewTimings.length} Clips to Beats`+ )}+ </Button>++ <Button+ onClick={handleAnalyzeBeats}+ variant="outline"+ className="w-full"+ >+ Re-analyze Beats+ </Button>+ </div>+ )}+ </div>+ );+};diff --git a/apps/web/src/components/editor/inspector/index.ts b/apps/web/src/components/editor/inspector/index.tsindex 7fa689c5..fd74ae9b 100644--- a/apps/web/src/components/editor/inspector/index.ts+++ b/apps/web/src/components/editor/inspector/index.ts@@ -32,6 +32,7 @@ export { FilterPresetsPanel } from "./FilterPresetsPanel";export { TextSection } from "./TextSection";export { TextAnimationSection } from "./TextAnimationSection";export { AutoCaptionPanel } from "./AutoCaptionPanel";+export { AudioTextSyncPanel } from "./AudioTextSyncPanel";// Graphics & Shapesexport { ShapeSection } from "./ShapeSection";diff --git a/packages/core/src/text/audio-text-sync-engine.ts b/packages/core/src/text/audio-text-sync-engine.tsnew file mode 100644index 00000000..24dc0de8--- /dev/null+++ b/packages/core/src/text/audio-text-sync-engine.ts@@ -0,0 +1,209 @@+import { getBeatDetectionEngine, type BeatAnalysisResult } from "../audio/beat-detection-engine";++export interface ClipTiming {+ readonly clipId: string;+ readonly originalStartTime: number;+ readonly originalDuration: number;+ readonly newStartTime: number;+ readonly newDuration: number;+}++export type SyncMode = "smart" | "one-per-beat" | "preserve-duration";++export interface BeatSyncConfig {+ readonly syncMode: SyncMode;+ readonly beatSubdivision: 1 | 2 | 4;+ readonly offsetMs: number;+ readonly snapToDownbeats: boolean;+}++export const DEFAULT_BEAT_SYNC_CONFIG: BeatSyncConfig = {+ syncMode: "smart",+ beatSubdivision: 1,+ offsetMs: 0,+ snapToDownbeats: false,+};++export interface SyncProgress {+ readonly phase: "analyzing" | "syncing" | "complete" | "error";+ readonly percent: number;+ readonly message: string;+}++export type SyncProgressCallback = (progress: SyncProgress) => void;++export interface ClipInfo {+ readonly id: string;+ readonly startTime: number;+ readonly duration: number;+ readonly trackId: string;+}++export class BeatSyncEngine {+ async analyzeBeats(+ audioBlob: Blob,+ onProgress?: SyncProgressCallback,+ ): Promise<BeatAnalysisResult> {+ onProgress?.({+ phase: "analyzing",+ percent: 20,+ message: "Analyzing audio for beats...",+ });++ const beatEngine = getBeatDetectionEngine();+ const result = await beatEngine.analyzeFromBlob(audioBlob);++ onProgress?.({+ phase: "complete",+ percent: 100,+ message: `Detected ${result.bpm} BPM with ${result.beats.length} beats`,+ });++ return result;+ }++ calculateSyncedTimings(+ clips: ClipInfo[],+ beatAnalysis: BeatAnalysisResult,+ audioStartTime: number,+ config: BeatSyncConfig,+ ): ClipTiming[] {+ if (clips.length === 0 || beatAnalysis.beats.length === 0) {+ return [];+ }++ const sortedClips = [...clips].sort((a, b) => a.startTime - b.startTime);+ const beatTimes = this.getSubdividedBeats(beatAnalysis, config);+ const offsetSeconds = config.offsetMs / 1000;+ const timings: ClipTiming[] = [];++ if (beatTimes.length < 2) {+ return [];+ }++ const avgBeatInterval = (beatTimes[beatTimes.length - 1] - beatTimes[0]) / (beatTimes.length - 1);+ let currentBeatIndex = 0;++ for (const clip of sortedClips) {+ if (currentBeatIndex >= beatTimes.length) break;++ const beatTime = beatTimes[currentBeatIndex] + audioStartTime + offsetSeconds;++ switch (config.syncMode) {+ case "preserve-duration": {+ timings.push({+ clipId: clip.id,+ originalStartTime: clip.startTime,+ originalDuration: clip.duration,+ newStartTime: beatTime,+ newDuration: clip.duration,+ });+ currentBeatIndex++;+ break;+ }++ case "one-per-beat": {+ const nextBeatIndex = Math.min(currentBeatIndex + 1, beatTimes.length - 1);+ const nextBeatTime = beatTimes[nextBeatIndex] + audioStartTime + offsetSeconds;+ const beatDuration = nextBeatTime - beatTime;++ timings.push({+ clipId: clip.id,+ originalStartTime: clip.startTime,+ originalDuration: clip.duration,+ newStartTime: beatTime,+ newDuration: Math.max(0.1, beatDuration),+ });+ currentBeatIndex++;+ break;+ }++ case "smart":+ default: {+ const beatsToSpan = Math.max(1, Math.round(clip.duration / avgBeatInterval));+ const endBeatIndex = Math.min(currentBeatIndex + beatsToSpan, beatTimes.length - 1);+ const endBeatTime = beatTimes[endBeatIndex] + audioStartTime + offsetSeconds;+ const newDuration = endBeatTime - beatTime;++ timings.push({+ clipId: clip.id,+ originalStartTime: clip.startTime,+ originalDuration: clip.duration,+ newStartTime: beatTime,+ newDuration: Math.max(0.1, newDuration),+ });+ currentBeatIndex = endBeatIndex;+ break;+ }+ }+ }++ return timings;+ }++ private getSubdividedBeats(+ beatAnalysis: BeatAnalysisResult,+ config: BeatSyncConfig,+ ): number[] {+ const beats = config.snapToDownbeats+ ? beatAnalysis.beats.filter((_, i) => i % 4 === 0)+ : beatAnalysis.beats;++ if (config.beatSubdivision === 1) {+ return beats.map((b) => b.time);+ }++ const times: number[] = [];+ for (let i = 0; i < beats.length - 1; i++) {+ const beatDuration = beats[i + 1].time - beats[i].time;+ const subBeatDuration = beatDuration / config.beatSubdivision;+ for (let j = 0; j < config.beatSubdivision; j++) {+ times.push(beats[i].time + j * subBeatDuration);+ }+ }+ if (beats.length > 0) {+ times.push(beats[beats.length - 1].time);+ }+ return times;+ }++ snapClipToNearestBeat(+ clipStartTime: number,+ beatAnalysis: BeatAnalysisResult,+ audioStartTime: number,+ maxSnapDistance: number = 0.2,+ ): number {+ const relativeTime = clipStartTime - audioStartTime;+ let nearestBeat = beatAnalysis.beats[0];+ let minDistance = Math.abs(nearestBeat.time - relativeTime);++ for (const beat of beatAnalysis.beats) {+ const distance = Math.abs(beat.time - relativeTime);+ if (distance < minDistance) {+ minDistance = distance;+ nearestBeat = beat;+ }+ }++ if (minDistance <= maxSnapDistance) {+ return nearestBeat.time + audioStartTime;+ }++ return clipStartTime;+ }+}++let beatSyncEngineInstance: BeatSyncEngine | null = null;++export function getBeatSyncEngine(): BeatSyncEngine {+ if (!beatSyncEngineInstance) {+ beatSyncEngineInstance = new BeatSyncEngine();+ }+ return beatSyncEngineInstance;+}++export function disposeBeatSyncEngine(): void {+ beatSyncEngineInstance = null;+}++export { type BeatAnalysisResult };diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.tsindex 9c63eabe..fd170c57 100644--- a/packages/core/src/text/index.ts+++ b/packages/core/src/text/index.ts@@ -7,3 +7,4 @@ export * from "./transcription-service";export * from "./caption-animation-renderer";export * from "./text-animation-presets";export * from "./character-animator";+export * from "./audio-text-sync-engine";