Add local browser AI music generation (#46)
This commit is contained in:
1 parent
0cd777342d
commit
e7b7743f0f
14 files changed
+851
-17
No files matched your search
@@ -66,22 +66,32 @@ function shouldCacheRequest(request) {
|
||||
return isHuggingFaceModelRequest(url) || isRuntimeAssetRequest(url);
|
||||
}
|
||||
|
||||
async function cacheFirst(request) {
|
||||
function withCacheStatus(response, status) {
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("X-Timeline-Model-Cache", status);
|
||||
return new Response(response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
async function cacheFirst(request, event) {
|
||||
const cache = await caches.open(MODEL_CACHE_NAME);
|
||||
const cached = await cache.match(request);
|
||||
if (cached) {
|
||||
return cached;
|
||||
return withCacheStatus(cached, "hit");
|
||||
}
|
||||
|
||||
const response = await fetch(request);
|
||||
if (response.ok || response.type === "opaque") {
|
||||
// Cache persistence is an optimization. A full browser quota must never
|
||||
// block the live response consumed by an inference worker.
|
||||
cache.put(request, response.clone()).catch((error) => {
|
||||
// Keep the service worker alive until the large model shard is durably
|
||||
// committed. The live response remains streaming and is not blocked.
|
||||
event.waitUntil(cache.put(request, response.clone()).catch((error) => {
|
||||
if (error?.name !== "QuotaExceededError") console.warn("Model cache write failed.", error);
|
||||
});
|
||||
}));
|
||||
}
|
||||
return response;
|
||||
return withCacheStatus(response, "miss");
|
||||
}
|
||||
|
||||
async function networkFirst(request) {
|
||||
@@ -128,6 +138,7 @@ self.addEventListener("activate", (event) => {
|
||||
// Older Transformers.js builds created a second copy of Hugging Face model
|
||||
// assets here. The service worker is now the sole cache owner.
|
||||
event.waitUntil(caches.delete("transformers-cache").catch(() => false));
|
||||
event.waitUntil(caches.delete("stable-audio-3-small-music-q4-v1").catch(() => false));
|
||||
event.waitUntil(removeLegacyPiperDuplicates().catch(() => {}));
|
||||
});
|
||||
|
||||
@@ -141,7 +152,7 @@ self.addEventListener("fetch", (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
event.respondWith(cacheFirst(event.request));
|
||||
event.respondWith(cacheFirst(event.request, event));
|
||||
});
|
||||
|
||||
self.addEventListener("message", (event) => {
|
||||
|
||||
+12
-2
@@ -62,6 +62,7 @@ import { createEditorCommandActions } from "./lib/editorCommandActions.js";
|
||||
import { createTimelineViewModel } from "./lib/timelineViewModel.js";
|
||||
import { createTranslator, getStoredLanguage, translateOptionName } from "./i18n.js";
|
||||
import { decodeWaveform, downloadBlob } from "./lib/media.js";
|
||||
import { useAiMusicGeneration } from "./hooks/useAiMusicGeneration.js";
|
||||
import { getImageThumbnailCount, getVisualSegmentsTotal, normalizeTimedSegmentIds } from "./lib/timeline.js";
|
||||
import { normalizeVisualTransform, removeVisualPropertyKeyframe, updateVisualSegmentPlaybackRate, upsertVisualKeyframe, upsertVisualPropertyKeyframe } from "./lib/visualEffects.js";
|
||||
import { getLinkedSourceAudioEnd, getLinkedSourceAudioSegments, shouldMuteEmbeddedVideoAudio } from "./lib/sourceAudioSync.js";
|
||||
@@ -187,6 +188,15 @@ export function App() {
|
||||
voiceRecorderChunksRef, voiceRecorderRef, voiceRecorderStartedAtRef,
|
||||
voiceRecorderStreamRef, voiceRecorderTimerRef,
|
||||
} = useEditorRefs();
|
||||
const activeLanguage = uiLanguage || "zh";
|
||||
const aiMusic = useAiMusicGeneration({
|
||||
activeLanguage,
|
||||
imageUrlRefs,
|
||||
setActiveTool,
|
||||
setMediaTab,
|
||||
setSelectedLibraryAssetId,
|
||||
setUserAssets,
|
||||
});
|
||||
const { redo, undo } = useEditorHistory({
|
||||
audioSegments, captionPlacement, captionPosition, captionSegments, captionSize,
|
||||
captionStyle, captionsEnabled, currentTime, fitMode, imageClipCount, imageDuration,
|
||||
@@ -209,7 +219,6 @@ export function App() {
|
||||
timelineHorizon, trackLocks, trackVisibility, userAssets, visualSegments, visualType,
|
||||
visualOverlaySegments, selectedVisualOverlayId, setVisualOverlaySegments, setSelectedVisualOverlayId,
|
||||
});
|
||||
const activeLanguage = uiLanguage || "zh";
|
||||
const t = useMemo(() => createTranslator(activeLanguage), [activeLanguage]);
|
||||
const handleCancelExport = () => {
|
||||
const controller = exportAbortControllerRef.current;
|
||||
@@ -899,7 +908,7 @@ export function App() {
|
||||
sourceAudioBlob, sourceAudioDuration, sourceAudioLinked, sourceAudioName, sourceAudioVolume, status, t,
|
||||
selectedAudioToolTarget, separateSelectedAudioVocals, separateSourceVocals, vocalSeparationJob,
|
||||
toggleCaptionSegmentHidden, toggleVisionOption, trOption, updateCaptionSegmentText,
|
||||
updateScript, userAssets, visionJob,
|
||||
updateScript, userAssets, visionJob, aiMusic,
|
||||
selectedVisualSegment, visualLocalTime, updateSelectedVisualEffects,
|
||||
mobilePanel, setMobilePanel: changeMobilePanel, applyAssetToTrack,
|
||||
}} />
|
||||
@@ -1075,6 +1084,7 @@ export function App() {
|
||||
automaticCaptionProgress={status === "captioning" ? progress : 0}
|
||||
avatarPanelOpen={avatarPanelOpen}
|
||||
smartMode={smartMode}
|
||||
aiMusic={aiMusic}
|
||||
autoEdit={autoEdit}
|
||||
uiLanguage={activeLanguage}
|
||||
visionAnalysis={previewVisionAnalysis}
|
||||
|
||||
@@ -124,6 +124,7 @@ export function EditorSidebar({ model: d }) {
|
||||
openAvatarPanel={d.openAvatarPanel}
|
||||
smartMode={d.smartMode}
|
||||
setSmartMode={d.setSmartMode}
|
||||
openMobileInspector={() => d.setMobilePanel?.("inspector")}
|
||||
musicBlob={d.musicBlob}
|
||||
musicName={d.musicName}
|
||||
musicDuration={d.musicDuration}
|
||||
|
||||
@@ -26,7 +26,7 @@ import { getCaptionVoiceSegment } from "../lib/captionVoice.js";
|
||||
import { findCaptionAudioLinkTarget } from "../lib/captionEditingActions.js";
|
||||
import { normalizeVisualKeyframes } from "../lib/visualEffects.js";
|
||||
import { MAX_SRT_FILE_BYTES, parseSrt } from "../lib/subtitles.js";
|
||||
import { HistoryPanel, MyVoicesPanel, SmartVisionPanel, VisualEffectsPanel, VoiceSynthesisPanel } from "./panels.jsx";
|
||||
import { AiMusicGenerator, HistoryPanel, MyVoicesPanel, SmartVisionPanel, VisualEffectsPanel, VoiceSynthesisPanel } from "./panels.jsx";
|
||||
|
||||
function AutoEditReviewDialog({ t, autoEdit }) {
|
||||
const { review, job } = autoEdit || {};
|
||||
@@ -547,6 +547,7 @@ export function VoicePanel({
|
||||
automaticCaptionProgress,
|
||||
avatarPanelOpen,
|
||||
smartMode = "auto-edit",
|
||||
aiMusic,
|
||||
autoEdit,
|
||||
uiLanguage,
|
||||
visionAnalysis,
|
||||
@@ -598,6 +599,7 @@ export function VoicePanel({
|
||||
const isAvatarContext = isSmartContext && smartMode === "avatar" && avatarPanelOpen;
|
||||
const isSmartAutoContext = isSmartContext && smartMode === "auto-edit";
|
||||
const isSmartFrameContext = isSmartContext && smartMode === "smart-frame";
|
||||
const isAiMusicContext = isSmartContext && smartMode === "ai-music";
|
||||
const audioPropertySegment = selectedTrack === "audio" ? selectedAudioSegment : selectedTrackAudioSegment;
|
||||
const isAudioClipContext = Boolean(selectedTrack === "audio" && selectedAudioSegment)
|
||||
|| Boolean(audioClipInspectorOpen && ["source", "music"].includes(selectedTrack) && audioPropertySegment);
|
||||
@@ -606,8 +608,8 @@ export function VoicePanel({
|
||||
const isOverlayContext = selectedTrack === "overlay" && Boolean(selectedVisualOverlay);
|
||||
const selectedCaptionAudioSegment = getCaptionVoiceSegment(audioSegments, selectedCaptionSegment);
|
||||
const localizedStatusText = statusText?.startsWith?.("tts") ? t(statusText) : statusText;
|
||||
const title = isSmartAutoContext ? t("smartAutoEdit") : isSmartFrameContext ? t("smartFrame") : isAvatarContext ? t("avatarTitle") : isOverlayContext ? t("pictureInPicture", "画中画") : isStickerContext ? t("stickerProperties") : isVisualContext ? t("visualPanelTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
|
||||
const panelStatusText = isSmartAutoContext ? t(`autoEditStatus_${autoEdit?.support?.availability || "unknown"}`) : isSmartFrameContext ? (hasVisual ? t("smartVisualReady") : t("smartWaitingVisual")) : isCaptionContext
|
||||
const title = isAiMusicContext ? (uiLanguage === "zh" ? "AI 音乐" : "AI music") : isSmartAutoContext ? t("smartAutoEdit") : isSmartFrameContext ? t("smartFrame") : isAvatarContext ? t("avatarTitle") : isOverlayContext ? t("pictureInPicture", "画中画") : isStickerContext ? t("stickerProperties") : isVisualContext ? t("visualPanelTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
|
||||
const panelStatusText = isAiMusicContext ? (aiMusic?.job?.state === "running" ? `${Math.round((aiMusic.job.progress || 0) * 100)}%` : aiMusic?.job?.state === "complete" ? t("complete") : t("modelReady")) : isSmartAutoContext ? t(`autoEditStatus_${autoEdit?.support?.availability || "unknown"}`) : isSmartFrameContext ? (hasVisual ? t("smartVisualReady") : t("smartWaitingVisual")) : isCaptionContext
|
||||
? captionSegments.length
|
||||
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
|
||||
: t("noCaptionSegments")
|
||||
@@ -696,6 +698,7 @@ export function VoicePanel({
|
||||
<div className="voice-tab-body">
|
||||
{isSmartAutoContext ? <AutoEditPanel t={t} hasVisual={hasVisual} language={uiLanguage} autoEdit={autoEdit} /> : null}
|
||||
{isSmartFrameContext ? <SmartVisionPanel t={t} language={uiLanguage} hasVisual={hasVisual} visualType={visualType} analysis={visionAnalysis} options={visionOptions} running={visionRunning} progress={visionProgress} phase={visionPhase} onAnalyze={analyzeCurrentVisual} onToggle={toggleVisionOption} onClear={clearVisionAnalysis} onDownloadCutout={downloadVisionCutout} /> : null}
|
||||
{isAiMusicContext ? <AiMusicGenerator language={uiLanguage} music={aiMusic} embedded /> : null}
|
||||
{isStickerContext ? <StickerContextPanel t={t} segment={selectedStickerSegment} updateStickerSegment={updateStickerSegment} deleteStickerSegment={deleteStickerSegment} /> : null}
|
||||
{isOverlayContext ? <div className="visual-overlay-inspector">
|
||||
<div className="sticker-properties-preview">{selectedVisualOverlay.type === "video" ? <video src={selectedVisualOverlay.src} muted playsInline /> : <img src={selectedVisualOverlay.src} alt="" />}</div>
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
VOICES,
|
||||
} from "../config/editor.js";
|
||||
import { APP_LANGUAGES } from "../i18n.js";
|
||||
import { AI_MUSIC_PRESETS, buildEnglishMusicPrompt } from "../lib/aiMusicPrompt.js";
|
||||
import { getRemoteAssetBlob } from "../lib/remoteAssetCache.js";
|
||||
import { formatClock, formatTime, getSegmentStartTime } from "../lib/timeline.js";
|
||||
import { hasVisualPropertyKeyframe, normalizeVisualKeyframes, resolveVisualTransform } from "../lib/visualEffects.js";
|
||||
@@ -264,6 +265,76 @@ export function MediaPanel({
|
||||
);
|
||||
}
|
||||
|
||||
const AI_MUSIC_COPY = {
|
||||
zh: { title: "AI 音乐", hint: "本地音乐生成", description: "音乐描述", descriptionPlaceholder: "例如:雨夜咖啡店里安静忧郁的爵士钢琴", style: "风格", mood: "氛围", instrument: "主乐器", duration: "时长", bpm: "速度", generate: "生成音乐", cancel: "取消", first: "首次下载模型,之后从本地缓存加载。", modelSetup: "模型准备", modelReady: "模型已就绪", musicGeneration: "音乐生成", waitingToGenerate: "等待生成", download: "并行下载模型", cache: "从本地缓存加载模型", initializing: "初始化 WebGPU 模型", translating: "翻译音乐描述", conditioning: "理解音乐描述", generating: "正在生成", decoding: "正在合成音频", complete: "已添加到 My assets", english: "高级:模型提示词" },
|
||||
en: { title: "AI music", hint: "Local music", description: "Describe your music", descriptionPlaceholder: "e.g. melancholic jazz piano in a rainy café", style: "Style", mood: "Mood", instrument: "Lead", duration: "Length", bpm: "Tempo", generate: "Generate music", cancel: "Cancel", first: "The model downloads once, then loads from local cache.", modelSetup: "Model setup", modelReady: "Model ready", musicGeneration: "Music generation", waitingToGenerate: "Waiting to generate", download: "Downloading model files in parallel", cache: "Loading models from local cache", initializing: "Initializing WebGPU models", translating: "Translating description", conditioning: "Understanding prompt", generating: "Generating", decoding: "Decoding audio", complete: "Added to My assets", english: "Advanced: model prompt" },
|
||||
};
|
||||
const AI_OPTION_LABELS = {
|
||||
zh: { cinematic: "电影感", lofi: "Lo-fi", ambient: "氛围", electronic: "电子", orchestral: "管弦", uplifting: "振奋", calm: "平静", dreamy: "梦幻", dramatic: "戏剧性", dark: "暗黑", piano: "钢琴", guitar: "木吉他", synth: "合成器", strings: "弦乐", drums: "鼓组" },
|
||||
};
|
||||
|
||||
export function AiMusicGenerator({ language, music, embedded = false }) {
|
||||
const copy = AI_MUSIC_COPY[language] || AI_MUSIC_COPY.en;
|
||||
const labels = AI_OPTION_LABELS[language] || {};
|
||||
const [open, setOpen] = useState(embedded);
|
||||
const [selection, setSelection] = useState({ description: "", style: "cinematic", mood: "dreamy", instrument: "piano", seconds: 30, bpm: 90 });
|
||||
const running = music?.job?.state === "running";
|
||||
const phaseLabel = copy[music?.job?.phase] || copy.generating;
|
||||
const setupRunning = running && ["download", "cache", "initializing"].includes(music?.job?.phase);
|
||||
const setupProgress = setupRunning ? Math.min(100, Math.round((music.job.progress / 0.64) * 100)) : (running || music?.job?.state === "complete" ? 100 : 0);
|
||||
const generationStarted = running && !setupRunning;
|
||||
const generationProgress = generationStarted ? Math.max(1, Math.min(100, Math.round(((music.job.progress - 0.64) / 0.36) * 100))) : (music?.job?.state === "complete" ? 100 : 0);
|
||||
const activeStageProgress = setupRunning ? setupProgress : generationProgress;
|
||||
const activeStageLabel = setupRunning ? copy.modelSetup : copy.musicGeneration;
|
||||
const activeStageStatus = setupRunning ? phaseLabel : generationStarted ? phaseLabel : copy.waitingToGenerate;
|
||||
const select = (group, value) => setSelection((current) => ({ ...current, [group]: value }));
|
||||
const HeadTag = embedded ? "div" : "button";
|
||||
return (
|
||||
<section className={`ai-music-card ${open ? "is-open" : ""} ${embedded ? "is-embedded" : ""}`}>
|
||||
{!embedded ? <HeadTag className="ai-music-card-head" type="button" onClick={() => setOpen((value) => !value)} aria-expanded={open}>
|
||||
<span className="ai-music-spark">✦</span>
|
||||
<span><strong>{copy.title}</strong><small>{copy.hint}</small></span>
|
||||
<CaretDown size={17} />
|
||||
</HeadTag> : null}
|
||||
{open ? (
|
||||
<div className="ai-music-card-body">
|
||||
<label className="ai-music-description">{copy.description}<textarea rows="3" value={selection.description} disabled={running} placeholder={copy.descriptionPlaceholder} onChange={(event) => select("description", event.target.value)} /></label>
|
||||
<div className="ai-music-select-grid">
|
||||
{[["style", copy.style], ["mood", copy.mood], ["instrument", copy.instrument]].map(([group, title]) => (
|
||||
<label key={group}>{title}<select value={selection[group]} disabled={running} onChange={(event) => select(group, event.target.value)}>
|
||||
{AI_MUSIC_PRESETS[group].map(([id]) => <option value={id} key={id}>{labels[id] || id}</option>)}
|
||||
</select></label>
|
||||
))}
|
||||
</div>
|
||||
<div className="ai-music-numbers">
|
||||
<label>{copy.duration}<select value={selection.seconds} disabled={running} onChange={(event) => select("seconds", Number(event.target.value))}><option value="30">30s</option><option value="60">60s</option><option value="90">90s</option><option value="120">120s</option></select></label>
|
||||
<label>{copy.bpm}<input type="number" min="60" max="180" value={selection.bpm} disabled={running} onChange={(event) => select("bpm", event.target.value)} /></label>
|
||||
</div>
|
||||
<details className="ai-music-prompt"><summary>{copy.english}</summary><p>{buildEnglishMusicPrompt(selection)}</p></details>
|
||||
<small className="ai-music-model-note">{copy.first}</small>
|
||||
{running ? (
|
||||
<div className="ai-music-stage-progress">
|
||||
<div className="ai-music-stage-labels">
|
||||
<span className={setupProgress === 100 ? "is-complete" : "is-active"}><i>1</i>{copy.modelSetup}<small>{setupProgress === 100 ? copy.modelReady : setupRunning ? `${setupProgress}%` : ""}</small></span>
|
||||
<span className={generationStarted ? "is-active" : ""}><i>2</i>{copy.musicGeneration}<small>{generationStarted ? `${generationProgress}%` : copy.waitingToGenerate}</small></span>
|
||||
</div>
|
||||
<div className="ai-music-progress">
|
||||
<div><strong>{activeStageLabel}</strong><small>{activeStageStatus} · {activeStageProgress}%</small></div>
|
||||
<span><i style={{ width: `${activeStageProgress}%` }} /></span>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{music?.job?.error ? <p className="ai-music-error">{music.job.error}</p> : null}
|
||||
{music?.job?.state === "complete" ? <p className="ai-music-success">{copy.complete}</p> : null}
|
||||
<div className="ai-music-actions">
|
||||
{running ? <button type="button" className="secondary" onClick={music.cancel}>{copy.cancel}</button> : <button type="button" className="primary" onClick={() => music.generate(selection)}><MusicNote size={17} />{copy.generate}</button>}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function AssetPreviewDialog({ asset, t, onClose }) {
|
||||
const mediaSrc = asset.type === "image" ? (asset.originalSrc || asset.src) : (asset.previewSrc || asset.src);
|
||||
const [audioPreviewStatus, setAudioPreviewStatus] = useState(asset.type === "audio" ? "loading" : "ready");
|
||||
@@ -515,6 +586,7 @@ export function ToolPanel(props) {
|
||||
openAvatarPanel,
|
||||
smartMode,
|
||||
setSmartMode,
|
||||
openMobileInspector,
|
||||
musicBlob,
|
||||
musicName,
|
||||
musicDuration,
|
||||
@@ -590,17 +662,20 @@ export function ToolPanel(props) {
|
||||
}
|
||||
|
||||
if (activeTool === "smart") {
|
||||
const aiCopy = AI_MUSIC_COPY[uiLanguage] || AI_MUSIC_COPY.en;
|
||||
return (
|
||||
<div className="tool-panel smart-hub-panel">
|
||||
<div className="smart-hub-grid" role="tablist" aria-label={t("smartTools")}>
|
||||
{[
|
||||
["auto-edit", Scissors, t("smartAutoEdit"), t("smartAutoEditHint")],
|
||||
["ai-music", MusicNote, aiCopy.title, aiCopy.hint],
|
||||
["smart-frame", FrameCorners, t("smartFrame"), t("smartFrameHint")],
|
||||
["avatar", PersonSimpleRun, t("smartAvatar"), t("smartAvatarHint")],
|
||||
].map(([id, Icon, title, hint]) => (
|
||||
<button className={smartMode === id ? "is-active" : ""} type="button" role="tab" aria-selected={smartMode === id} key={id} onClick={() => {
|
||||
setSmartMode(id);
|
||||
if (id === "avatar") openAvatarPanel();
|
||||
if (id === "ai-music" && window.matchMedia?.("(max-width: 760px)").matches) openMobileInspector?.();
|
||||
}}>
|
||||
<Icon size={24} weight="duotone" /><strong>{title}</strong><span>{hint}</span>
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { buildEnglishMusicPrompt, createAiMusicFileName, translateMusicDescriptionToEnglish } from "../lib/aiMusicPrompt.js";
|
||||
import { repeatPcm16WavAtBestBoundary } from "../lib/aiMusicLoop.js";
|
||||
import { decodeWaveform } from "../lib/media.js";
|
||||
|
||||
export function useAiMusicGeneration({ activeLanguage, imageUrlRefs, setActiveTool, setMediaTab, setSelectedLibraryAssetId, setUserAssets }) {
|
||||
const workerRef = useRef(null);
|
||||
const [job, setJob] = useState({ state: "idle", progress: 0, phase: "", error: "" });
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
workerRef.current?.terminate();
|
||||
workerRef.current = null;
|
||||
setJob({ state: "idle", progress: 0, phase: "", error: "" });
|
||||
}, []);
|
||||
|
||||
useEffect(() => cancel, [cancel]);
|
||||
|
||||
const generate = useCallback(async (selection) => {
|
||||
setJob({ state: "running", progress: 0.64, phase: "translating", error: "" });
|
||||
let prompt;
|
||||
try {
|
||||
const descriptionEnglish = await translateMusicDescriptionToEnglish(selection.description || "", activeLanguage);
|
||||
prompt = buildEnglishMusicPrompt({ ...selection, descriptionEnglish });
|
||||
} catch (error) {
|
||||
setJob({ state: "error", progress: 0, phase: "", error: error?.message || String(error) });
|
||||
return;
|
||||
}
|
||||
await navigator.storage?.persist?.().catch(() => false);
|
||||
const worker = workerRef.current ?? new Worker(new URL("../workers/ai-music.worker.js", import.meta.url), { type: "module" });
|
||||
const warmRuntime = Boolean(workerRef.current);
|
||||
workerRef.current = worker;
|
||||
setJob({ state: "running", progress: warmRuntime ? 0.64 : 0.01, phase: warmRuntime ? "conditioning" : "download", error: "" });
|
||||
worker.onmessage = async ({ data }) => {
|
||||
if (data.type === "progress") {
|
||||
setJob((current) => ({ ...current, progress: data.progress, phase: data.phase }));
|
||||
return;
|
||||
}
|
||||
if (data.type === "error") {
|
||||
worker.terminate();
|
||||
workerRef.current = null;
|
||||
setJob({ state: "error", progress: 0, phase: "", error: data.message });
|
||||
return;
|
||||
}
|
||||
if (data.type !== "complete") return;
|
||||
const requestedSeconds = Number(selection.seconds) || 30;
|
||||
const wav = requestedSeconds > 60
|
||||
? repeatPcm16WavAtBestBoundary(data.wav, 2, 5)
|
||||
: data.wav;
|
||||
const blob = new Blob([wav], { type: "audio/wav" });
|
||||
const src = URL.createObjectURL(blob);
|
||||
imageUrlRefs.current.add(src);
|
||||
const decoded = await decodeWaveform(blob, 96);
|
||||
const asset = {
|
||||
id: crypto.randomUUID(),
|
||||
type: "audio",
|
||||
kind: "music",
|
||||
name: createAiMusicFileName(selection),
|
||||
meta: `AI music · ${decoded.duration.toFixed(1)}s`,
|
||||
src,
|
||||
previewSrc: src,
|
||||
blob,
|
||||
duration: decoded.duration,
|
||||
peaks: decoded.peaks,
|
||||
provider: "Stable Audio 3 Small · ONNX",
|
||||
generated: true,
|
||||
prompt,
|
||||
};
|
||||
setUserAssets((current) => [asset, ...current]);
|
||||
setSelectedLibraryAssetId(asset.id);
|
||||
setActiveTool("media");
|
||||
setMediaTab("mine");
|
||||
setJob({ state: "complete", progress: 1, phase: "complete", error: "" });
|
||||
};
|
||||
worker.onerror = (event) => {
|
||||
worker.terminate();
|
||||
workerRef.current = null;
|
||||
setJob({ state: "error", progress: 0, phase: "", error: event.message || "Music generation failed." });
|
||||
};
|
||||
worker.postMessage({
|
||||
type: "generate",
|
||||
prompt,
|
||||
seconds: (Number(selection.seconds) || 30) / (Number(selection.seconds) > 60 ? 2 : 1),
|
||||
steps: 8,
|
||||
seed: Math.floor(Math.random() * 0x7fffffff),
|
||||
});
|
||||
}, [activeLanguage, imageUrlRefs, setActiveTool, setMediaTab, setSelectedLibraryAssetId, setUserAssets]);
|
||||
|
||||
return { job, generate, cancel };
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
function copyAscii(view, offset, text) {
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
view.setUint8(offset + index, text.charCodeAt(index));
|
||||
}
|
||||
}
|
||||
|
||||
export function repeatPcm16WavWithFades(sourceBuffer, repeats = 2, fadeSeconds = 1.5) {
|
||||
return repeatWavSection(sourceBuffer, getWavInfo(sourceBuffer).sourceFrames, repeats, fadeSeconds);
|
||||
}
|
||||
|
||||
export function repeatPcm16WavAtBestBoundary(sourceBuffer, repeats = 2, searchSeconds = 5) {
|
||||
const info = getWavInfo(sourceBuffer);
|
||||
const boundary = findBestLoopBoundary(sourceBuffer, searchSeconds);
|
||||
return repeatWavSection(sourceBuffer, boundary.cutFrame, repeats, boundary.fadeSeconds, info);
|
||||
}
|
||||
|
||||
export function findBestLoopBoundary(sourceBuffer, searchSeconds = 5) {
|
||||
const info = getWavInfo(sourceBuffer);
|
||||
const { source, channels, sampleRate, sourceFrames } = info;
|
||||
const searchFrames = Math.min(sourceFrames >> 1, Math.round(searchSeconds * sampleRate));
|
||||
const firstCut = Math.max(1, sourceFrames - searchFrames);
|
||||
const lastCut = Math.max(firstCut, sourceFrames - Math.round(sampleRate * 0.08));
|
||||
const hop = Math.max(1, Math.round(sampleRate / 200));
|
||||
const window = Math.max(2, Math.round(sampleRate * 0.06));
|
||||
const sampleMono = (frame) => {
|
||||
let sum = 0;
|
||||
const safeFrame = Math.max(0, Math.min(sourceFrames - 1, frame));
|
||||
for (let channel = 0; channel < channels; channel += 1) {
|
||||
sum += source.getInt16(44 + (safeFrame * channels + channel) * 2, true) / 32768;
|
||||
}
|
||||
return sum / channels;
|
||||
};
|
||||
|
||||
const head = sampleMono(0);
|
||||
const headSlope = sampleMono(1) - head;
|
||||
let best = { cutFrame: lastCut, score: Number.POSITIVE_INFINITY, rms: 0 };
|
||||
for (let cutFrame = firstCut; cutFrame <= lastCut; cutFrame += hop) {
|
||||
let energy = 0;
|
||||
const samples = 16;
|
||||
for (let index = 0; index < samples; index += 1) {
|
||||
const frame = cutFrame - 1 - Math.round(index * window / samples);
|
||||
const value = sampleMono(frame);
|
||||
energy += value * value;
|
||||
}
|
||||
const rms = Math.sqrt(energy / samples);
|
||||
const tail = sampleMono(cutFrame - 1);
|
||||
const tailSlope = tail - sampleMono(cutFrame - 2);
|
||||
const jump = Math.abs(tail - head);
|
||||
const slopeJump = Math.abs(tailSlope - headSlope);
|
||||
const shortenedRatio = (sourceFrames - cutFrame) / Math.max(1, searchFrames);
|
||||
const score = rms * 0.7 + jump * 0.8 + slopeJump * 0.25 + shortenedRatio * 0.08;
|
||||
if (score < best.score) best = { cutFrame, score, rms };
|
||||
}
|
||||
|
||||
const fadeSeconds = Math.max(0.25, Math.min(1.5, 0.25 + best.rms * 4));
|
||||
return { ...best, fadeSeconds };
|
||||
}
|
||||
|
||||
function getWavInfo(sourceBuffer) {
|
||||
const source = new DataView(sourceBuffer);
|
||||
if (
|
||||
copyFourCC(source, 0) !== "RIFF"
|
||||
|| copyFourCC(source, 8) !== "WAVE"
|
||||
|| copyFourCC(source, 36) !== "data"
|
||||
|| source.getUint16(20, true) !== 1
|
||||
|| source.getUint16(34, true) !== 16
|
||||
) {
|
||||
throw new Error("AI music looping requires a PCM 16-bit WAV.");
|
||||
}
|
||||
|
||||
const channels = source.getUint16(22, true);
|
||||
const sampleRate = source.getUint32(24, true);
|
||||
const sourceDataBytes = source.getUint32(40, true);
|
||||
const frameBytes = channels * 2;
|
||||
const sourceFrames = Math.floor(sourceDataBytes / frameBytes);
|
||||
return { source, channels, sampleRate, frameBytes, sourceFrames };
|
||||
}
|
||||
|
||||
function repeatWavSection(sourceBuffer, sectionFrames, repeats, fadeSeconds, wavInfo = getWavInfo(sourceBuffer)) {
|
||||
const { source, channels, sampleRate, frameBytes, sourceFrames } = wavInfo;
|
||||
const usedFrames = Math.max(1, Math.min(sourceFrames, Math.floor(sectionFrames)));
|
||||
const repeatCount = Math.max(1, Math.floor(repeats));
|
||||
const outputDataBytes = usedFrames * frameBytes * repeatCount;
|
||||
const outputBuffer = new ArrayBuffer(44 + outputDataBytes);
|
||||
const output = new DataView(outputBuffer);
|
||||
|
||||
new Uint8Array(outputBuffer, 0, 44).set(new Uint8Array(sourceBuffer, 0, 44));
|
||||
copyAscii(output, 0, "RIFF");
|
||||
output.setUint32(4, 36 + outputDataBytes, true);
|
||||
output.setUint32(40, outputDataBytes, true);
|
||||
|
||||
const fadeFrames = Math.min(usedFrames >> 1, Math.max(1, Math.round(fadeSeconds * sampleRate)));
|
||||
for (let repeat = 0; repeat < repeatCount; repeat += 1) {
|
||||
for (let frame = 0; frame < usedFrames; frame += 1) {
|
||||
let gain = 1;
|
||||
if (repeat > 0 && frame < fadeFrames) {
|
||||
gain *= Math.sin((frame / fadeFrames) * Math.PI / 2);
|
||||
}
|
||||
if (repeat < repeatCount - 1 && frame >= usedFrames - fadeFrames) {
|
||||
gain *= Math.cos(((frame - (usedFrames - fadeFrames)) / fadeFrames) * Math.PI / 2);
|
||||
}
|
||||
for (let channel = 0; channel < channels; channel += 1) {
|
||||
const sourceOffset = 44 + (frame * channels + channel) * 2;
|
||||
const outputFrame = repeat * usedFrames + frame;
|
||||
const outputOffset = 44 + (outputFrame * channels + channel) * 2;
|
||||
output.setInt16(outputOffset, Math.round(source.getInt16(sourceOffset, true) * gain), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
return outputBuffer;
|
||||
}
|
||||
|
||||
function copyFourCC(view, offset) {
|
||||
return String.fromCharCode(
|
||||
view.getUint8(offset),
|
||||
view.getUint8(offset + 1),
|
||||
view.getUint8(offset + 2),
|
||||
view.getUint8(offset + 3),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { findBestLoopBoundary, repeatPcm16WavAtBestBoundary, repeatPcm16WavWithFades } from "./aiMusicLoop.js";
|
||||
|
||||
function makeMonoWav(samples, sampleRate = 4) {
|
||||
const buffer = new ArrayBuffer(44 + samples.length * 2);
|
||||
const view = new DataView(buffer);
|
||||
const text = (offset, value) => [...value].forEach((character, index) => view.setUint8(offset + index, character.charCodeAt(0)));
|
||||
text(0, "RIFF"); view.setUint32(4, 36 + samples.length * 2, true); text(8, "WAVE");
|
||||
text(12, "fmt "); view.setUint32(16, 16, true); view.setUint16(20, 1, true);
|
||||
view.setUint16(22, 1, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * 2, true);
|
||||
view.setUint16(32, 2, true); view.setUint16(34, 16, true); text(36, "data"); view.setUint32(40, samples.length * 2, true);
|
||||
samples.forEach((sample, index) => view.setInt16(44 + index * 2, sample, true));
|
||||
return buffer;
|
||||
}
|
||||
|
||||
describe("AI music long-duration looping", () => {
|
||||
it("duplicates the PCM duration and fades both sides of the join", () => {
|
||||
const output = repeatPcm16WavWithFades(makeMonoWav([1000, 1000, 1000, 1000]), 2, 0.5);
|
||||
const view = new DataView(output);
|
||||
expect(view.getUint32(40, true)).toBe(16);
|
||||
expect(view.getInt16(44 + 3 * 2, true)).toBeLessThan(1000);
|
||||
expect(view.getInt16(44 + 4 * 2, true)).toBe(0);
|
||||
expect(view.getInt16(44 + 5 * 2, true)).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("selects a quiet boundary in the tail instead of blindly using the end", () => {
|
||||
const samples = [
|
||||
0, 1000, 1000, 1000,
|
||||
1000, 1000, 1000, 1000,
|
||||
1000, 1000, 1000, 1000,
|
||||
1000, 1000, 20, 0,
|
||||
20, 1000, 1000, 1000,
|
||||
];
|
||||
const source = makeMonoWav(samples);
|
||||
const boundary = findBestLoopBoundary(source, 2);
|
||||
const output = repeatPcm16WavAtBestBoundary(source, 2, 2);
|
||||
expect(boundary.cutFrame).toBeGreaterThanOrEqual(14);
|
||||
expect(boundary.cutFrame).toBeLessThan(20);
|
||||
expect(new DataView(output).getUint32(40, true)).toBe(boundary.cutFrame * 4);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
export const AI_MUSIC_PRESETS = {
|
||||
style: [
|
||||
["cinematic", "cinematic soundtrack"],
|
||||
["lofi", "lo-fi hip hop"],
|
||||
["ambient", "ambient"],
|
||||
["electronic", "electronic"],
|
||||
["orchestral", "orchestral"],
|
||||
],
|
||||
mood: [
|
||||
["uplifting", "uplifting"],
|
||||
["calm", "calm and peaceful"],
|
||||
["dreamy", "dreamy"],
|
||||
["dramatic", "dramatic"],
|
||||
["dark", "dark and tense"],
|
||||
],
|
||||
instrument: [
|
||||
["piano", "piano"],
|
||||
["guitar", "acoustic guitar"],
|
||||
["synth", "analog synthesizer"],
|
||||
["strings", "cinematic strings"],
|
||||
["drums", "punchy drums"],
|
||||
],
|
||||
};
|
||||
|
||||
export function buildEnglishMusicPrompt(selection) {
|
||||
const lookup = (group, id) => AI_MUSIC_PRESETS[group].find(([key]) => key === id)?.[1];
|
||||
return [
|
||||
selection.descriptionEnglish?.trim(),
|
||||
lookup("style", selection.style),
|
||||
lookup("mood", selection.mood),
|
||||
lookup("instrument", selection.instrument),
|
||||
`${Math.max(60, Math.min(180, Number(selection.bpm) || 90))} BPM`,
|
||||
"instrumental music, clean production, no vocals",
|
||||
].filter(Boolean).join(", ");
|
||||
}
|
||||
|
||||
function containsOnlyEnglishPromptText(text) {
|
||||
return /^[\x00-\x7F]*$/.test(text);
|
||||
}
|
||||
|
||||
export async function translateMusicDescriptionToEnglish(text, sourceLanguage = "en") {
|
||||
const value = text.trim();
|
||||
if (!value || containsOnlyEnglishPromptText(value)) return value;
|
||||
|
||||
let detectedLanguage = sourceLanguage === "zh" ? "zh" : sourceLanguage;
|
||||
if (globalThis.LanguageDetector?.create) {
|
||||
try {
|
||||
const detector = await globalThis.LanguageDetector.create();
|
||||
const results = await detector.detect(value);
|
||||
detectedLanguage = results?.[0]?.detectedLanguage || detectedLanguage;
|
||||
detector.destroy?.();
|
||||
} catch {
|
||||
// The selected interface language remains a useful source-language hint.
|
||||
}
|
||||
}
|
||||
if (!globalThis.Translator?.create) {
|
||||
throw new Error("Browser translation is unavailable. Use English or enable Chrome built-in translation.");
|
||||
}
|
||||
const translator = await globalThis.Translator.create({
|
||||
sourceLanguage: detectedLanguage,
|
||||
targetLanguage: "en",
|
||||
});
|
||||
try {
|
||||
return await translator.translate(value);
|
||||
} finally {
|
||||
translator.destroy?.();
|
||||
}
|
||||
}
|
||||
|
||||
export function createAiMusicFileName(selection) {
|
||||
const style = selection.style || "music";
|
||||
return `AI ${style} ${new Date().toISOString().slice(0, 19).replaceAll(":", "-")}.wav`;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildEnglishMusicPrompt } from "./aiMusicPrompt.js";
|
||||
|
||||
describe("buildEnglishMusicPrompt", () => {
|
||||
it("maps localized UI choices to a stable English-only model prompt", () => {
|
||||
const prompt = buildEnglishMusicPrompt({
|
||||
style: "cinematic",
|
||||
mood: "dreamy",
|
||||
instrument: "piano",
|
||||
bpm: 92,
|
||||
});
|
||||
|
||||
expect(prompt).toBe("cinematic soundtrack, dreamy, piano, 92 BPM, instrumental music, clean production, no vocals");
|
||||
expect(prompt).toMatch(/^[\x20-\x7E]+$/);
|
||||
});
|
||||
|
||||
it("clamps tempo to the supported range", () => {
|
||||
expect(buildEnglishMusicPrompt({ style: "ambient", bpm: 999 })).toContain("180 BPM");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
export function buildPingPongSchedule(steps, sigmaMax = 1) {
|
||||
const count = Math.max(1, Math.floor(steps));
|
||||
return Array.from({ length: count + 1 }, (_, index) => {
|
||||
if (index === 0) return sigmaMax;
|
||||
if (index === count) return 0;
|
||||
const t = sigmaMax * (1 - index / count);
|
||||
const logSnr = 2 - t * 8.2;
|
||||
return 1 / (1 + Math.exp(logSnr));
|
||||
});
|
||||
}
|
||||
|
||||
export function pingPongStep(latent, velocity, current, next, noise) {
|
||||
const updated = new Float32Array(latent.length);
|
||||
const isFinalStep = next <= 0;
|
||||
for (let index = 0; index < latent.length; index += 1) {
|
||||
const denoised = latent[index] - current * velocity[index];
|
||||
updated[index] = isFinalStep
|
||||
? denoised
|
||||
: (1 - next) * denoised + next * noise[index];
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildPingPongSchedule, pingPongStep } from "./aiMusicSampling.js";
|
||||
|
||||
describe("AI music ping-pong sampler", () => {
|
||||
it("uses exact 1-to-0 endpoints", () => {
|
||||
const schedule = buildPingPongSchedule(8);
|
||||
expect(schedule).toHaveLength(9);
|
||||
expect(schedule[0]).toBe(1);
|
||||
expect(schedule.at(-1)).toBe(0);
|
||||
expect(schedule.every((value, index) => index === 0 || value < schedule[index - 1])).toBe(true);
|
||||
});
|
||||
|
||||
it("does not add fresh noise to the final denoised sample", () => {
|
||||
const output = pingPongStep(
|
||||
Float32Array.of(1, 2),
|
||||
Float32Array.of(0.25, 0.5),
|
||||
0.5,
|
||||
0,
|
||||
Float32Array.of(100, 100),
|
||||
);
|
||||
expect(Array.from(output)).toEqual([0.875, 1.75]);
|
||||
});
|
||||
});
|
||||
+97
-4
@@ -1257,6 +1257,58 @@ button:disabled {
|
||||
.library-search { margin-top: 8px; }
|
||||
.library-search input { width: 100%; border: 1px solid rgba(255,255,255,.09); border-radius: 7px; padding: 9px 10px; color: #e9f2f4; background: rgba(6,10,14,.62); outline: none; }
|
||||
.library-search input:focus { border-color: rgba(53,234,217,.52); }
|
||||
.ai-music-card { margin-top: 10px; border: 1px solid rgba(53,234,217,.2); border-radius: 10px; overflow: hidden; background: linear-gradient(145deg, rgba(24,42,47,.88), rgba(13,18,24,.92)); }
|
||||
.ai-music-card.is-open { position: absolute; z-index: 8; top: 118px; right: 18px; bottom: 16px; left: 18px; display: flex; flex-direction: column; margin: 0; box-shadow: 0 14px 30px rgba(0,0,0,.34); }
|
||||
.ai-music-card-head { display: grid; grid-template-columns: auto 1fr auto; gap: 10px; align-items: center; width: 100%; padding: 11px 12px; border: 0; color: #eefbfa; background: transparent; text-align: left; }
|
||||
.ai-music-card-head > span:nth-child(2) { display: grid; gap: 2px; }
|
||||
.ai-music-card-head small { color: #8e9ba5; font-size: 11px; font-weight: 400; }
|
||||
.ai-music-card-head svg { transition: transform .18s ease; }
|
||||
.ai-music-card.is-open .ai-music-card-head svg { transform: rotate(180deg); }
|
||||
.ai-music-spark { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 8px; color: #35ead9; background: rgba(53,234,217,.12); font-size: 19px; }
|
||||
.ai-music-card-body { display: grid; gap: 11px; padding: 0 12px 12px; border-top: 1px solid rgba(255,255,255,.06); }
|
||||
.ai-music-card.is-open .ai-music-card-body { flex: 1 1 0; min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; touch-action: pan-y; }
|
||||
.ai-music-card-body fieldset { min-width: 0; padding: 10px 0 0; border: 0; }
|
||||
.ai-music-card-body legend { margin-bottom: 6px; color: #9aa6af; font-size: 11px; }
|
||||
.ai-music-chips { display: flex; gap: 5px; overflow-x: auto; scrollbar-width: none; }
|
||||
.ai-music-chips button { flex: 0 0 auto; padding: 6px 8px; border: 1px solid rgba(255,255,255,.08); border-radius: 7px; color: #abb5bc; background: rgba(255,255,255,.035); font-size: 11px; }
|
||||
.ai-music-chips button.is-active { border-color: rgba(53,234,217,.42); color: #eafffd; background: rgba(53,234,217,.12); }
|
||||
.ai-music-numbers { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
|
||||
.ai-music-numbers label { display: grid; gap: 5px; color: #9aa6af; font-size: 11px; }
|
||||
.ai-music-numbers input, .ai-music-numbers select { width: 100%; min-width: 0; height: 32px; padding: 0 8px; border: 1px solid rgba(255,255,255,.09); border-radius: 7px; color: #e9f2f4; background: #10161c; }
|
||||
.ai-music-description { display: grid; gap: 6px; padding-top: 10px; color: #aab6bd; font-size: 11px; }
|
||||
.ai-music-description textarea { width: 100%; min-height: 70px; resize: vertical; border: 1px solid rgba(255,255,255,.1); border-radius: 8px; padding: 9px 10px; color: #eef5f6; font: inherit; line-height: 1.45; background: #10161c; outline: none; }
|
||||
.ai-music-description textarea:focus { border-color: rgba(53,234,217,.52); }
|
||||
.ai-music-description textarea::placeholder { color: #65737c; }
|
||||
.ai-music-select-grid { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 7px; }
|
||||
.ai-music-select-grid label { display: grid; gap: 5px; min-width: 0; color: #9aa6af; font-size: 10px; }
|
||||
.ai-music-select-grid select { width: 100%; min-width: 0; height: 32px; border: 1px solid rgba(255,255,255,.09); border-radius: 7px; padding: 0 7px; color: #e9f2f4; background: #10161c; }
|
||||
.ai-music-prompt { color: #88959f; font-size: 10px; }
|
||||
.ai-music-prompt p { margin: 5px 0 0; line-height: 1.45; color: #aeb9c0; }
|
||||
.ai-music-model-note { color: #7f8c95; line-height: 1.45; }
|
||||
.ai-music-stage-progress { display: grid; gap: 8px; }
|
||||
.ai-music-stage-labels { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
|
||||
.ai-music-stage-labels > span { display: grid; grid-template-columns: 18px minmax(0,1fr); align-items: center; gap: 1px 6px; min-width: 0; color: #78868f; font-size: 10px; font-weight: 700; }
|
||||
.ai-music-stage-labels i { grid-row: span 2; display: grid; place-items: center; width: 18px; height: 18px; border-radius: 50%; color: #6f7e87; font-size: 8px; font-style: normal; background: rgba(255,255,255,.06); }
|
||||
.ai-music-stage-labels small { overflow: hidden; color: #64737c; font-size: 8px; font-weight: 500; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ai-music-stage-labels > span.is-active { color: #dce8e9; }
|
||||
.ai-music-stage-labels > span.is-active i { color: #061716; background: #35ead9; }
|
||||
.ai-music-stage-labels > span.is-complete { color: #8debe1; }
|
||||
.ai-music-stage-labels > span.is-complete i { color: #07211f; background: #8debe1; }
|
||||
.ai-music-progress { display: grid; gap: 6px; border: 1px solid rgba(255,255,255,.07); border-radius: 8px; padding: 8px; background: rgba(255,255,255,.025); }
|
||||
.ai-music-progress > div { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.ai-music-progress strong { color: #cbd6da; font-size: 10px; }
|
||||
.ai-music-progress > span { height: 5px; overflow: hidden; border-radius: 9px; background: rgba(255,255,255,.08); }
|
||||
.ai-music-progress i { display: block; height: 100%; border-radius: inherit; background: #35ead9; transition: width .2s ease; }
|
||||
.ai-music-progress small { overflow: hidden; color: #87959e; font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ai-music-success { margin: 0; color: #8debe1; }
|
||||
.ai-music-error { margin: 0; color: #ff929a; font-size: 11px; line-height: 1.4; }
|
||||
.ai-music-actions { display: flex; justify-content: flex-end; }
|
||||
.ai-music-actions button { display: inline-flex; gap: 6px; align-items: center; justify-content: center; min-height: 34px; padding: 0 12px; border-radius: 7px; }
|
||||
.ai-music-actions .primary { border: 0; color: #071311; background: #35ead9; font-weight: 700; }
|
||||
.ai-music-actions .secondary { border: 1px solid rgba(255,255,255,.12); color: #d7e0e4; background: rgba(255,255,255,.04); }
|
||||
@media (max-width: 760px) {
|
||||
.ai-music-card.is-open { top: 126px; right: 8px; bottom: 8px; left: 8px; }
|
||||
}
|
||||
.library-provider { margin-top: 7px; color: #697680; font-size: 10px; }
|
||||
.library-provider strong { color: #9aa9b2; font-weight: 600; }
|
||||
|
||||
@@ -1548,7 +1600,6 @@ button:disabled {
|
||||
.smart-hub-panel { gap: 16px; }
|
||||
.smart-hub-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; }
|
||||
.smart-hub-grid > button { display: grid; align-content: start; min-width: 0; min-height: 104px; border: 1px solid rgba(255,255,255,.08); border-radius: 11px; padding: 13px; color: #8e9ca8; text-align: left; background: linear-gradient(145deg, rgba(255,255,255,.045), rgba(255,255,255,.018)); cursor: pointer; }
|
||||
.smart-hub-grid > button:first-child { grid-column: span 2; min-height: 92px; }
|
||||
.smart-hub-grid > button:hover { border-color: rgba(53,234,217,.32); color: #e9f7f6; }
|
||||
.smart-hub-grid > button.is-active { border-color: rgba(53,234,217,.64); color: #35ead9; background: linear-gradient(145deg, rgba(53,234,217,.14), rgba(77,128,255,.07)); box-shadow: inset 0 0 0 1px rgba(53,234,217,.1); }
|
||||
.smart-hub-grid svg { margin-bottom: 13px; }
|
||||
@@ -1561,6 +1612,12 @@ button:disabled {
|
||||
.smart-feature-empty em { margin-top: 16px; border-radius: 999px; padding: 5px 9px; color: #8d9ca7; font-size: 10px; font-style: normal; background: rgba(255,255,255,.05); }
|
||||
.smart-feature-empty.is-avatar em { color: #77ded3; background: rgba(53,234,217,.07); }
|
||||
.smart-hub-panel .smart-vision-panel { overflow: visible; padding: 0; }
|
||||
.smart-feature-back { align-self: start; min-height: 32px; border: 1px solid rgba(255,255,255,.08); border-radius: 8px; padding: 0 10px; color: #9cabb4; background: rgba(255,255,255,.035); cursor: pointer; }
|
||||
.smart-feature-back:hover { border-color: rgba(53,234,217,.28); color: #eaf9f7; }
|
||||
.ai-music-smart-panel { gap: 10px; }
|
||||
.ai-music-card.is-open.is-embedded { position: static; z-index: auto; display: flex; flex: 0 0 auto; min-height: 0; margin: 0; box-shadow: none; }
|
||||
.ai-music-card.is-embedded .ai-music-card-head { cursor: default; }
|
||||
.ai-music-card.is-embedded .ai-music-card-body { flex: 0 0 auto; height: auto; overflow: visible; }
|
||||
.smart-context-empty { display: grid; place-items: center; min-height: 310px; border: 1px dashed rgba(255,255,255,.1); border-radius: 12px; padding: 30px; color: #70808c; text-align: center; }
|
||||
.smart-context-empty svg { color: #5c7280; }
|
||||
.smart-context-empty strong { margin-top: 15px; color: #e3edef; font-size: 14px; }
|
||||
@@ -6024,15 +6081,30 @@ button:disabled {
|
||||
|
||||
.preview-stage {
|
||||
grid-area: preview;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
margin: 6px 6px 0;
|
||||
min-height: 280px;
|
||||
height: auto;
|
||||
border-radius: 10px;
|
||||
padding: 3px;
|
||||
}
|
||||
.preview-canvas { padding: 8px 6px 2px; }
|
||||
.preview-canvas { min-width: 0; padding: 8px 6px 2px; }
|
||||
.preview-stage .transport {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.preview-stage > .transport-row { min-width: 0; padding: 0 7px; }
|
||||
.transport-row { gap: 4px; }
|
||||
.preview-stage .transport-row {
|
||||
width: auto;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
gap: 4px;
|
||||
}
|
||||
.preview-stage .transport-row > span {
|
||||
flex: 1 1 auto;
|
||||
min-width: 74px;
|
||||
}
|
||||
.playback-controls { min-width: 0; gap: 1px; }
|
||||
.playback-controls .icon-button { width: 36px; height: 36px; }
|
||||
.transport-time { min-width: 74px; font-size: 11px; }
|
||||
@@ -6468,7 +6540,13 @@ button:disabled {
|
||||
transform: translateX(50%);
|
||||
content: "";
|
||||
}
|
||||
.timeline-tools { gap: 5px; padding: 0 7px; overflow-x: auto; }
|
||||
.timeline-tools {
|
||||
gap: 5px;
|
||||
padding: 0 7px;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.timeline-tools::-webkit-scrollbar { display: none; }
|
||||
.timeline-tools .icon-button { flex: 0 0 auto; width: 36px; height: 36px; }
|
||||
.timeline-icon-group { flex: 0 0 auto; }
|
||||
.timeline-sync-readout { display: none; }
|
||||
@@ -6674,6 +6752,21 @@ button:disabled {
|
||||
.timeline-ruler-canvas { min-width: 480px; }
|
||||
}
|
||||
|
||||
@media (max-width: 340px) {
|
||||
.preview-stage .transport-row > span {
|
||||
min-width: 64px;
|
||||
font-size: 10px;
|
||||
}
|
||||
.preview-stage .playback-controls .icon-button,
|
||||
.preview-stage .transport-row > .icon-button {
|
||||
width: 32px;
|
||||
height: 36px;
|
||||
}
|
||||
.mobile-ratio-select { min-width: 52px; }
|
||||
.mobile-ratio-select select { padding-right: 20px; padding-left: 7px; }
|
||||
.mobile-ratio-select svg { right: 5px; }
|
||||
}
|
||||
|
||||
/* Tool panels remain wheel/trackpad scrollable without persistent scrollbar chrome. */
|
||||
.media-panel .tool-panel {
|
||||
overflow-x: hidden;
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
import { GemmaTokenizer, env } from "@huggingface/transformers";
|
||||
import * as ort from "onnxruntime-web/webgpu";
|
||||
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.mjs?url";
|
||||
import ortWasmUrl from "onnxruntime-web/ort-wasm-simd-threaded.asyncify.wasm?url";
|
||||
import { buildPingPongSchedule, pingPongStep } from "../lib/aiMusicSampling.js";
|
||||
|
||||
const MODEL_REVISION = "0b8a05e0bc3511e674b4cb3413d3ef6c48880cdb";
|
||||
const BASE = `https://huggingface.co/haixin/stable-audio-3-small-music-onnx/resolve/${MODEL_REVISION}`;
|
||||
const LEGACY_BASE = "https://huggingface.co/lsb/stable-audio-3-small-music-onnx/resolve/main";
|
||||
const SAMPLE_RATE = 44100;
|
||||
const MODEL_CACHE_NAME = "timeline-studio-model-cache-v4";
|
||||
|
||||
env.allowLocalModels = false;
|
||||
env.allowRemoteModels = true;
|
||||
ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 4) : 1;
|
||||
ort.env.wasm.simd = true;
|
||||
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
|
||||
ort.env.webgpu.powerPreference = "high-performance";
|
||||
ort.env.webgpu.forceFallbackAdapter = false;
|
||||
|
||||
function progress(phase, value) {
|
||||
self.postMessage({ type: "progress", phase, progress: value });
|
||||
}
|
||||
|
||||
const GRAPH_SPECS = [
|
||||
["text_encoder_q4", "text_encoder_q4.onnx"],
|
||||
["number_conditioner", "number_conditioner.onnx"],
|
||||
["dit_q4", "dit_q4.onnx"],
|
||||
["decoder_q4", "decoder_q4.onnx"],
|
||||
];
|
||||
|
||||
async function fetchModelFile(path) {
|
||||
const url = `${BASE}/${path}`;
|
||||
const cache = await caches.open(MODEL_CACHE_NAME);
|
||||
const cached = await cache.match(url) || await cache.match(`${LEGACY_BASE}/${path}`);
|
||||
if (cached) {
|
||||
return { response: cached, fromCache: true };
|
||||
}
|
||||
|
||||
// The service worker is the single cache writer. Writing the same large
|
||||
// response here as well can temporarily require twice the storage and cause
|
||||
// QuotaExceededError on otherwise capable devices.
|
||||
const response = await fetch(url);
|
||||
return {
|
||||
response,
|
||||
fromCache: false,
|
||||
};
|
||||
}
|
||||
|
||||
async function downloadAllResources() {
|
||||
const manifestResults = await Promise.all(GRAPH_SPECS.map(async ([name]) => {
|
||||
const resource = await fetchModelFile(`onnx/${name}_chunks.json`);
|
||||
const { response } = resource;
|
||||
if (!response.ok) throw new Error(`Model manifest download failed (${response.status}): ${name}`);
|
||||
return { manifest: await response.json(), resource };
|
||||
}));
|
||||
const manifests = manifestResults.map(({ manifest }) => manifest);
|
||||
const paths = [
|
||||
...GRAPH_SPECS.flatMap(([, graph], index) => [
|
||||
`onnx/${graph}`,
|
||||
...(manifests[index].chunks || manifests[index].files || []).map((item) => `onnx/${item.name || item.path}`),
|
||||
]),
|
||||
"tokenizer/tokenizer.json",
|
||||
"tokenizer/tokenizer_config.json",
|
||||
];
|
||||
|
||||
// Start every request before consuming any response body. This lets Chrome
|
||||
// multiplex the model shards while keeping WebGPU session creation separate.
|
||||
const responses = await Promise.all(paths.map(async (path) => {
|
||||
const { response, fromCache } = await fetchModelFile(path);
|
||||
if (!response.ok) throw new Error(`Model download failed (${response.status}): ${path}`);
|
||||
return { path, response, fromCache };
|
||||
}));
|
||||
const allResources = [
|
||||
...manifestResults.map(({ resource }) => resource),
|
||||
...responses,
|
||||
];
|
||||
const phase = allResources.every(({ fromCache }) => fromCache) ? "cache" : "download";
|
||||
const expectedBytes = responses.reduce((sum, { response }) => sum + (Number(response.headers.get("content-length")) || 0), 0);
|
||||
const loadedByPath = new Map(paths.map((path) => [path, 0]));
|
||||
const report = (path, bytes) => {
|
||||
loadedByPath.set(path, bytes);
|
||||
const loaded = [...loadedByPath.values()].reduce((sum, value) => sum + value, 0);
|
||||
progress(phase, 0.02 + 0.55 * Math.min(1, expectedBytes ? loaded / expectedBytes : loadedByPath.size / paths.length));
|
||||
};
|
||||
const artifacts = new Map(await Promise.all(responses.map(async ({ path, response }) => {
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
const data = new Uint8Array(await response.arrayBuffer());
|
||||
report(path, data.byteLength);
|
||||
return [path, data];
|
||||
}
|
||||
const chunks = [];
|
||||
let loaded = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
chunks.push(value);
|
||||
loaded += value.byteLength;
|
||||
report(path, loaded);
|
||||
}
|
||||
const data = new Uint8Array(loaded);
|
||||
let cursor = 0;
|
||||
for (const chunk of chunks) {
|
||||
data.set(chunk, cursor);
|
||||
cursor += chunk.byteLength;
|
||||
}
|
||||
return [path, data];
|
||||
})));
|
||||
progress(phase, 0.57);
|
||||
return { artifacts, manifests };
|
||||
}
|
||||
|
||||
async function createSession(index, resources) {
|
||||
const [, graph] = GRAPH_SPECS[index];
|
||||
const manifest = resources.manifests[index];
|
||||
const graphPath = `onnx/${graph}`;
|
||||
const graphBytes = resources.artifacts.get(graphPath);
|
||||
const pieces = manifest.chunks || manifest.files || [];
|
||||
const externalData = pieces.map((item) => {
|
||||
const path = item.name || item.path;
|
||||
return { path, data: resources.artifacts.get(`onnx/${path}`) };
|
||||
});
|
||||
if (!navigator.gpu) {
|
||||
throw new Error("This Q4 music model requires WebGPU. Enable WebGPU in a current Chrome or Edge browser.");
|
||||
}
|
||||
const session = await ort.InferenceSession.create(graphBytes, {
|
||||
executionProviders: ["webgpu"],
|
||||
externalData,
|
||||
});
|
||||
resources.artifacts.delete(graphPath);
|
||||
for (const item of pieces) resources.artifacts.delete(`onnx/${item.name || item.path}`);
|
||||
return session;
|
||||
}
|
||||
|
||||
function createTokenizer(artifacts) {
|
||||
const decoder = new TextDecoder();
|
||||
const tokenizerJSON = JSON.parse(decoder.decode(artifacts.get("tokenizer/tokenizer.json")));
|
||||
const tokenizerConfig = JSON.parse(decoder.decode(artifacts.get("tokenizer/tokenizer_config.json")));
|
||||
artifacts.delete("tokenizer/tokenizer.json");
|
||||
artifacts.delete("tokenizer/tokenizer_config.json");
|
||||
return new GemmaTokenizer(tokenizerJSON, tokenizerConfig);
|
||||
}
|
||||
|
||||
function randomNormal(length, seed) {
|
||||
let state = seed >>> 0;
|
||||
const random = () => {
|
||||
state = (1664525 * state + 1013904223) >>> 0;
|
||||
return (state + 1) / 4294967297;
|
||||
};
|
||||
const output = new Float32Array(length);
|
||||
for (let index = 0; index < length; index += 2) {
|
||||
const radius = Math.sqrt(-2 * Math.log(random()));
|
||||
const angle = 2 * Math.PI * random();
|
||||
output[index] = radius * Math.cos(angle);
|
||||
if (index + 1 < length) output[index + 1] = radius * Math.sin(angle);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function wavFromAudio(audio, seconds) {
|
||||
const frames = Math.min(Math.floor(seconds * SAMPLE_RATE), audio.dims.at(-1));
|
||||
const bytes = new ArrayBuffer(44 + frames * 4);
|
||||
const view = new DataView(bytes);
|
||||
const text = (offset, value) => [...value].forEach((character, index) => view.setUint8(offset + index, character.charCodeAt(0)));
|
||||
text(0, "RIFF"); view.setUint32(4, 36 + frames * 4, true); text(8, "WAVE");
|
||||
text(12, "fmt "); view.setUint32(16, 16, true); view.setUint16(20, 1, true);
|
||||
view.setUint16(22, 2, true); view.setUint32(24, SAMPLE_RATE, true); view.setUint32(28, SAMPLE_RATE * 4, true);
|
||||
view.setUint16(32, 4, true); view.setUint16(34, 16, true); text(36, "data"); view.setUint32(40, frames * 4, true);
|
||||
const channelLength = audio.dims.at(-1);
|
||||
for (let frame = 0; frame < frames; frame += 1) {
|
||||
for (let channel = 0; channel < 2; channel += 1) {
|
||||
const sample = Math.max(-1, Math.min(1, audio.data[channel * channelLength + frame] || 0));
|
||||
view.setInt16(44 + (frame * 2 + channel) * 2, sample < 0 ? sample * 32768 : sample * 32767, true);
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
let runtimePromise = null;
|
||||
|
||||
async function initializeRuntime() {
|
||||
progress("download", 0.02);
|
||||
const resources = await downloadAllResources();
|
||||
const tokenizer = createTokenizer(resources.artifacts);
|
||||
// WebGPU permits only one EP session to be initialized at a time. Keeping
|
||||
// these sequential also avoids holding every graph's temporary upload
|
||||
// buffers at once on integrated-memory Macs.
|
||||
progress("initializing", 0.58);
|
||||
const textSession = await createSession(0, resources);
|
||||
progress("initializing", 0.595);
|
||||
const numberSession = await createSession(1, resources);
|
||||
progress("initializing", 0.61);
|
||||
const ditSession = await createSession(2, resources);
|
||||
progress("initializing", 0.625);
|
||||
const decoderSession = await createSession(3, resources);
|
||||
return { tokenizer, textSession, numberSession, ditSession, decoderSession };
|
||||
}
|
||||
|
||||
async function generate({ prompt, seconds, steps, seed }) {
|
||||
runtimePromise ??= initializeRuntime().catch((error) => {
|
||||
runtimePromise = null;
|
||||
throw error;
|
||||
});
|
||||
const { tokenizer, textSession, numberSession, ditSession, decoderSession } = await runtimePromise;
|
||||
progress("conditioning", 0.64);
|
||||
const tokens = await tokenizer(prompt, { padding: "max_length", truncation: true, max_length: 256 });
|
||||
const ids = BigInt64Array.from(tokens.input_ids.data, BigInt);
|
||||
const mask = BigInt64Array.from(tokens.attention_mask.data, BigInt);
|
||||
const text = (await textSession.run({
|
||||
[textSession.inputNames[0]]: new ort.Tensor("int64", ids, [1, 256]),
|
||||
[textSession.inputNames[1]]: new ort.Tensor("int64", mask, [1, 256]),
|
||||
}))[textSession.outputNames[0]];
|
||||
const duration = (await numberSession.run({
|
||||
seconds: new ort.Tensor("float32", Float32Array.of(seconds), [1]),
|
||||
}))[numberSession.outputNames[0]];
|
||||
const cross = new Float32Array(257 * 768);
|
||||
cross.set(text.data.subarray(0, 256 * 768));
|
||||
cross.set(duration.data.subarray(0, 768), 256 * 768);
|
||||
const latentLength = Math.ceil((seconds + 6) * SAMPLE_RATE / 8192) * 2;
|
||||
let latent = randomNormal(256 * latentLength, seed);
|
||||
const times = buildPingPongSchedule(steps);
|
||||
for (let step = 0; step < steps; step += 1) {
|
||||
progress("generating", 0.65 + step / steps * 0.27);
|
||||
const current = times[step];
|
||||
const next = times[step + 1];
|
||||
const result = await ditSession.run({
|
||||
x: new ort.Tensor("float32", latent, [1, 256, latentLength]),
|
||||
t: new ort.Tensor("float32", Float32Array.of(current), [1]),
|
||||
cross_attn_cond: new ort.Tensor("float32", cross, [1, 257, 768]),
|
||||
global_embed: new ort.Tensor("float32", duration.data, [1, 768]),
|
||||
local_add_cond: new ort.Tensor("float32", new Float32Array(257 * latentLength), [1, 257, latentLength]),
|
||||
padding_mask: new ort.Tensor("bool", new Uint8Array(latentLength).fill(1), [1, latentLength]),
|
||||
});
|
||||
const velocity = result[ditSession.outputNames[0]].data;
|
||||
const noise = next > 0 ? randomNormal(latent.length, seed + step + 1) : null;
|
||||
latent = pingPongStep(latent, velocity, current, next, noise);
|
||||
}
|
||||
progress("decoding", 0.94);
|
||||
const decoded = await decoderSession.run({
|
||||
[decoderSession.inputNames[0]]: new ort.Tensor("float32", latent, [1, 256, latentLength]),
|
||||
});
|
||||
const wav = wavFromAudio(decoded[decoderSession.outputNames[0]], seconds);
|
||||
progress("complete", 1);
|
||||
self.postMessage({ type: "complete", wav }, [wav]);
|
||||
}
|
||||
|
||||
self.onmessage = ({ data }) => {
|
||||
if (data.type !== "generate") return;
|
||||
generate(data).catch((error) => self.postMessage({ type: "error", message: error?.message || String(error) }));
|
||||
};
|
||||
Reference in new issue
Block a user