diff --git a/public/model-cache-sw.js b/public/model-cache-sw.js index f050ce7..ac6b894 100644 --- a/public/model-cache-sw.js +++ b/public/model-cache-sw.js @@ -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) => { diff --git a/src/App.jsx b/src/App.jsx index a6e1895..9753976 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -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} diff --git a/src/components/EditorSidebar.jsx b/src/components/EditorSidebar.jsx index 0c19f39..0fbfd78 100644 --- a/src/components/EditorSidebar.jsx +++ b/src/components/EditorSidebar.jsx @@ -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} diff --git a/src/components/VoicePanel.jsx b/src/components/VoicePanel.jsx index b55c7e6..826f9ce 100644 --- a/src/components/VoicePanel.jsx +++ b/src/components/VoicePanel.jsx @@ -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({
{isSmartAutoContext ? : null} {isSmartFrameContext ? : null} + {isAiMusicContext ? : null} {isStickerContext ? : null} {isOverlayContext ?
{selectedVisualOverlay.type === "video" ?
diff --git a/src/components/panels.jsx b/src/components/panels.jsx index b8d8141..a8d398f 100644 --- a/src/components/panels.jsx +++ b/src/components/panels.jsx @@ -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 ( +
+ {!embedded ? setOpen((value) => !value)} aria-expanded={open}> + ✦ + {copy.title}{copy.hint} + + : null} + {open ? ( +
+