feat: add browser talking avatar pipeline
This commit is contained in:
1 parent
ebcb6e880a
commit
16c0bf7f2e
21 files changed
+1746
-22
No files matched your search
+199
@@ -82,6 +82,7 @@ import {
|
||||
getSmartCropRect,
|
||||
mapNormalizedBoxToFrame,
|
||||
} from "./lib/visualGeometry.js";
|
||||
import { JOYVASA_PROJECT_MODEL_BASE_URL } from "./config/joyVasa.js";
|
||||
|
||||
const PLAYBACK_UI_FRAME_MS = 50;
|
||||
const DEFAULT_VISION_OPTIONS = Object.freeze({
|
||||
@@ -97,6 +98,59 @@ const EMPTY_VISION_OPTIONS = Object.freeze({
|
||||
smartCrop: false,
|
||||
});
|
||||
|
||||
async function decodeAvatarAudio16k(blob) {
|
||||
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
|
||||
if (!AudioContextClass) throw new Error("当前浏览器不支持音频解码");
|
||||
const context = new AudioContextClass();
|
||||
try {
|
||||
const decoded = await context.decodeAudioData((await blob.arrayBuffer()).slice(0));
|
||||
const mono = new Float32Array(decoded.length);
|
||||
for (let channel = 0; channel < decoded.numberOfChannels; channel += 1) {
|
||||
const values = decoded.getChannelData(channel);
|
||||
for (let i = 0; i < mono.length; i += 1) mono[i] += values[i] / decoded.numberOfChannels;
|
||||
}
|
||||
const outputLength = Math.min(64_000, Math.ceil(decoded.duration * 16_000));
|
||||
const resampled = new Float32Array(64_000);
|
||||
for (let i = 0; i < outputLength; i += 1) {
|
||||
const position = (i * decoded.sampleRate) / 16_000;
|
||||
const left = Math.min(mono.length - 1, Math.floor(position));
|
||||
const right = Math.min(mono.length - 1, left + 1);
|
||||
const ratio = position - left;
|
||||
resampled[i] = mono[left] * (1 - ratio) + mono[right] * ratio;
|
||||
}
|
||||
return resampled;
|
||||
} finally {
|
||||
await context.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function encodeAvatarFrames(blobs, width, height, fps) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const context = canvas.getContext("2d", { alpha: false });
|
||||
const stream = canvas.captureStream(fps);
|
||||
const mimeType = ["video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"]
|
||||
.find((type) => MediaRecorder.isTypeSupported(type));
|
||||
const recorder = mimeType ? new MediaRecorder(stream, { mimeType }) : new MediaRecorder(stream);
|
||||
const chunks = [];
|
||||
recorder.ondataavailable = (event) => { if (event.data.size) chunks.push(event.data); };
|
||||
const stopped = new Promise((resolve, reject) => {
|
||||
recorder.onstop = () => resolve(new Blob(chunks, { type: recorder.mimeType || "video/webm" }));
|
||||
recorder.onerror = () => reject(recorder.error || new Error("数字人视频编码失败"));
|
||||
});
|
||||
recorder.start();
|
||||
for (const blob of blobs) {
|
||||
const bitmap = await createImageBitmap(blob);
|
||||
context.drawImage(bitmap, 0, 0, width, height);
|
||||
bitmap.close();
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 1000 / fps));
|
||||
}
|
||||
recorder.stop();
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
return stopped;
|
||||
}
|
||||
|
||||
function getNearestRatioIdForSize(width, height) {
|
||||
const mediaWidth = Number(width);
|
||||
const mediaHeight = Number(height);
|
||||
@@ -270,6 +324,7 @@ export function App() {
|
||||
phase: "",
|
||||
});
|
||||
const [avatarPanelOpen, setAvatarPanelOpen] = useState(false);
|
||||
const [avatarJob, setAvatarJob] = useState({ running: false, progress: 0, phase: "" });
|
||||
|
||||
const fileInputRef = useRef(null);
|
||||
const projectFileInputRef = useRef(null);
|
||||
@@ -307,6 +362,8 @@ export function App() {
|
||||
const visionObjectUrlsRef = useRef(new Map());
|
||||
const visionAbortControllerRef = useRef(null);
|
||||
const visionJobGenerationRef = useRef(0);
|
||||
const avatarWorkerRef = useRef(null);
|
||||
const avatarTestImportedRef = useRef(false);
|
||||
const activeLanguage = uiLanguage || "zh";
|
||||
const t = useMemo(() => createTranslator(activeLanguage), [activeLanguage]);
|
||||
const trOption = (name, option) => {
|
||||
@@ -327,6 +384,112 @@ export function App() {
|
||||
setAvatarPanelOpen(true);
|
||||
}
|
||||
|
||||
async function generateAvatarAcceptanceFrame() {
|
||||
if (avatarJob.running) return;
|
||||
if (!previewVisualSrc || previewVisualType !== "image") {
|
||||
notify(t("avatarNeedsPortrait"));
|
||||
return;
|
||||
}
|
||||
if (!audioBlob) {
|
||||
notify(t("avatarNeedsAudio"));
|
||||
return;
|
||||
}
|
||||
|
||||
setAvatarJob({ running: true, progress: 1, phase: t("avatarPreparing") });
|
||||
try {
|
||||
const sourceBlob = previewVisualSegment?.blob instanceof Blob
|
||||
? previewVisualSegment.blob
|
||||
: await fetch(previewVisualSrc).then((response) => {
|
||||
if (!response.ok) throw new Error(`读取肖像失败(HTTP ${response.status})`);
|
||||
return response.blob();
|
||||
});
|
||||
const sourceDuration = Math.max(MIN_VISUAL_SEGMENT_SECONDS, Math.min(4, audioDuration || imageDuration || 4));
|
||||
const audioSamples = await decodeAvatarAudio16k(audioBlob);
|
||||
const motionWorker = new Worker(new URL("./workers/joyvasa.worker.js", import.meta.url), { type: "module" });
|
||||
avatarWorkerRef.current?.terminate();
|
||||
avatarWorkerRef.current = motionWorker;
|
||||
|
||||
motionWorker.onmessage = (event) => {
|
||||
if (event.data?.type === "progress") {
|
||||
setAvatarJob({ running: true, progress: event.data.progress, phase: event.data.phase });
|
||||
return;
|
||||
}
|
||||
if (event.data?.type === "error") {
|
||||
console.error("LivePortrait worker error", event.data.message);
|
||||
setAvatarJob({ running: false, progress: 0, phase: `${t("avatarGenerationFailed")}:${event.data.message}` });
|
||||
notify(`${t("avatarGenerationFailed")}:${event.data.message}`);
|
||||
motionWorker.terminate();
|
||||
if (avatarWorkerRef.current === motionWorker) avatarWorkerRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (event.data?.type !== "motion") return;
|
||||
motionWorker.terminate();
|
||||
const renderWorker = new Worker(new URL("./workers/liveportrait.worker.js", import.meta.url), { type: "module" });
|
||||
avatarWorkerRef.current = renderWorker;
|
||||
renderWorker.onmessage = async (renderEvent) => {
|
||||
if (renderEvent.data?.type === "progress") {
|
||||
setAvatarJob({ running: true, progress: renderEvent.data.progress, phase: renderEvent.data.phase });
|
||||
return;
|
||||
}
|
||||
if (renderEvent.data?.type === "error") {
|
||||
setAvatarJob({ running: false, progress: 0, phase: `${t("avatarGenerationFailed")}:${renderEvent.data.message}` });
|
||||
notify(`${t("avatarGenerationFailed")}:${renderEvent.data.message}`);
|
||||
renderWorker.terminate();
|
||||
if (avatarWorkerRef.current === renderWorker) avatarWorkerRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (renderEvent.data?.type !== "videoFrames") return;
|
||||
|
||||
try {
|
||||
setAvatarJob({ running: true, progress: 99, phase: "编码数字人视频" });
|
||||
const blob = await encodeAvatarFrames(renderEvent.data.blobs, renderEvent.data.width, renderEvent.data.height, renderEvent.data.fps);
|
||||
const url = URL.createObjectURL(blob);
|
||||
imageUrlRefs.current.add(url);
|
||||
const asset = {
|
||||
id: crypto.randomUUID(), type: "video", src: url, name: "liveportrait-joyvasa.webm",
|
||||
meta: `${renderEvent.data.width} x ${renderEvent.data.height} · JoyVASA + LivePortrait Web`, blob,
|
||||
duration: sourceDuration, width: renderEvent.data.width, height: renderEvent.data.height, trackFrames: [],
|
||||
};
|
||||
setUserAssets((assets) => [asset, ...assets]);
|
||||
replaceVisualTimeline(asset, sourceDuration);
|
||||
setCurrentTime(0);
|
||||
setAvatarJob({ running: false, progress: 100, phase: t("avatarAcceptanceDone") });
|
||||
notify(t("avatarTrackReplaced"));
|
||||
} catch (error) {
|
||||
setAvatarJob({ running: false, progress: 0, phase: `${t("avatarGenerationFailed")}:${error.message}` });
|
||||
notify(`${t("avatarGenerationFailed")}:${error.message}`);
|
||||
} finally {
|
||||
renderWorker.terminate();
|
||||
if (avatarWorkerRef.current === renderWorker) avatarWorkerRef.current = null;
|
||||
}
|
||||
};
|
||||
renderWorker.postMessage({
|
||||
type: "generateVideo", portraitBlob: sourceBlob, motionBuffer: event.data.motion,
|
||||
modelBaseUrl: import.meta.env.VITE_LIVE_PORTRAIT_MODEL_BASE_URL || "",
|
||||
joyVasaModelBaseUrl: JOYVASA_PROJECT_MODEL_BASE_URL,
|
||||
renderFps: 8,
|
||||
}, [event.data.motion]);
|
||||
};
|
||||
|
||||
motionWorker.onerror = (event) => {
|
||||
console.error("LivePortrait worker module error", event.message, event);
|
||||
setAvatarJob({ running: false, progress: 0, phase: `${t("avatarGenerationFailed")}:${event.message || "Worker error"}` });
|
||||
notify(`${t("avatarGenerationFailed")}:${event.message || "Worker error"}`);
|
||||
motionWorker.terminate();
|
||||
if (avatarWorkerRef.current === motionWorker) avatarWorkerRef.current = null;
|
||||
};
|
||||
|
||||
motionWorker.postMessage({
|
||||
type: "generate",
|
||||
audioSamples: audioSamples.buffer,
|
||||
modelBaseUrl: JOYVASA_PROJECT_MODEL_BASE_URL,
|
||||
}, [audioSamples.buffer]);
|
||||
} catch (error) {
|
||||
setAvatarJob({ running: false, progress: 0, phase: "" });
|
||||
notify(`${t("avatarGenerationFailed")}:${error instanceof Error ? error.message : String(error)}`);
|
||||
}
|
||||
}
|
||||
|
||||
const ratio = useMemo(
|
||||
() => RATIO_OPTIONS.find((option) => option.id === ratioId) ?? RATIO_OPTIONS[0],
|
||||
[ratioId],
|
||||
@@ -658,6 +821,40 @@ export function App() {
|
||||
setFitMode("contain");
|
||||
}, [ratioId]);
|
||||
|
||||
useEffect(() => {
|
||||
const testImageUrl = import.meta.env.DEV ? import.meta.env.VITE_AVATAR_TEST_IMAGE_URL : "";
|
||||
if (!testImageUrl || avatarTestImportedRef.current) return;
|
||||
avatarTestImportedRef.current = true;
|
||||
fetch(testImageUrl)
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return response.blob();
|
||||
})
|
||||
.then((blob) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
imageUrlRefs.current.add(url);
|
||||
const asset = {
|
||||
id: crypto.randomUUID(),
|
||||
type: "image",
|
||||
src: url,
|
||||
name: "老外戴眼镜中年人物肖像生成-modnet.png",
|
||||
meta: "819 x 1024 · E2E test",
|
||||
blob,
|
||||
duration: 4,
|
||||
width: 819,
|
||||
height: 1024,
|
||||
trackFrames: [],
|
||||
};
|
||||
setUserAssets((assets) => [asset, ...assets]);
|
||||
replaceVisualTimeline(asset, 4);
|
||||
notify("端到端测试肖像已载入画面轨");
|
||||
})
|
||||
.catch((error) => {
|
||||
avatarTestImportedRef.current = false;
|
||||
console.error("Avatar E2E test image import failed", error);
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const ratioSource = visualSegments.find((segment) => segment.width > 0 && segment.height > 0);
|
||||
if (!ratioSource) {
|
||||
@@ -4585,6 +4782,8 @@ export function App() {
|
||||
hasVisual={Boolean(previewVisualSrc)}
|
||||
visualType={previewVisualType}
|
||||
audioDuration={audioDuration}
|
||||
avatarJob={avatarJob}
|
||||
generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame}
|
||||
/>
|
||||
</section>
|
||||
|
||||
|
||||
Binary file not shown.
@@ -8,8 +8,11 @@ import {
|
||||
Trash,
|
||||
Waveform,
|
||||
} from "@phosphor-icons/react";
|
||||
import { useState } from "react";
|
||||
|
||||
import { formatTime, getSegmentStartTime } from "../lib/timeline.js";
|
||||
import { LIVE_PORTRAIT_WEB_MODEL } from "../config/livePortrait.js";
|
||||
import { probeLivePortraitWebEnvironment } from "../lib/livePortraitWeb.js";
|
||||
import { HistoryPanel, MyVoicesPanel, VoiceSynthesisPanel } from "./panels.jsx";
|
||||
|
||||
function CaptionContextPanel({
|
||||
@@ -136,8 +139,22 @@ function CaptionContextPanel({
|
||||
);
|
||||
}
|
||||
|
||||
function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration, captionSegments, selectedVoice }) {
|
||||
function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration, captionSegments, selectedVoice, avatarJob, generateAvatarAcceptanceFrame }) {
|
||||
const hasPortrait = hasVisual && visualType === "image";
|
||||
const [probeState, setProbeState] = useState("idle");
|
||||
const [probeResult, setProbeResult] = useState(null);
|
||||
|
||||
const runProbe = async () => {
|
||||
setProbeState("running");
|
||||
try {
|
||||
setProbeResult(await probeLivePortraitWebEnvironment());
|
||||
setProbeState("done");
|
||||
} catch (error) {
|
||||
setProbeResult({ readyForPorting: false, checks: [{ id: "runtime", state: "failed", detail: error instanceof Error ? error.message : String(error) }] });
|
||||
setProbeState("done");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="avatar-context-panel">
|
||||
<div className="avatar-context-hero">
|
||||
@@ -149,9 +166,37 @@ function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration
|
||||
<div className={audioBlob ? "is-ready" : ""}><Waveform size={17} weight="duotone" /><span><strong>{t("avatarAudio")}</strong><em>{audioBlob ? `${selectedVoice?.name ?? "AI"} · ${audioDuration.toFixed(1)}s` : t("avatarNeedsAudio")}</em></span></div>
|
||||
<div className={captionSegments.length ? "is-ready" : ""}><ClosedCaptioning size={17} weight="duotone" /><span><strong>{t("avatarLipSyncSource")}</strong><em>{captionSegments.length ? `${captionSegments.length} ${t("captionSegmentsUnit")} · ${t("avatarCaptionSync")}` : t("avatarNeedsCaptions")}</em></span></div>
|
||||
</div>
|
||||
<div className="avatar-sync-mode"><span>{t("avatarSyncMode")}</span><strong>{t("avatarSyncModeCaption")}</strong></div>
|
||||
<div className="avatar-sync-mode"><span>{t("avatarModelSource")}</span><strong>{LIVE_PORTRAIT_WEB_MODEL.id}</strong></div>
|
||||
<p className="avatar-context-note">{t("avatarGenerationNote")}</p>
|
||||
<div className="avatar-official-notice"><PersonSimpleRun size={17} weight="duotone" /><span><strong>{t("avatarServiceNeeded")}</strong><em>{t("avatarServiceHint")}</em></span></div>
|
||||
<div className="avatar-porting-stages" aria-label={t("avatarPortingStatus")}>
|
||||
<div className="is-done"><span>1</span><strong>{t("avatarStagePinned")}</strong></div>
|
||||
<div className="is-done"><span>2</span><strong>{t("avatarStageGrid")}</strong></div>
|
||||
<div className="is-active"><span>3</span><strong>{t("avatarStageAudio")}</strong></div>
|
||||
</div>
|
||||
{probeResult ? (
|
||||
<div className="avatar-probe-results">
|
||||
{probeResult.checks.map((check) => <div className={`is-${check.state}`} key={check.id}><span />{check.detail}</div>)}
|
||||
</div>
|
||||
) : null}
|
||||
<button className="panel-secondary avatar-probe-button" type="button" disabled={probeState === "running"} onClick={runProbe}>
|
||||
{probeState === "running" ? t("avatarChecking") : t("avatarCheck")}
|
||||
</button>
|
||||
{avatarJob?.running || avatarJob?.progress > 0 || avatarJob?.phase ? (
|
||||
<div className="avatar-generation-progress" aria-live="polite">
|
||||
<div><span>{avatarJob.phase || t("avatarGenerating")}</span><strong>{avatarJob.progress}%</strong></div>
|
||||
<i><b style={{ width: `${avatarJob.progress}%` }} /></i>
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
className="panel-primary avatar-generate-button"
|
||||
type="button"
|
||||
disabled={!hasPortrait || avatarJob?.running}
|
||||
onClick={generateAvatarAcceptanceFrame}
|
||||
>
|
||||
<PersonSimpleRun size={17} weight="duotone" />
|
||||
{avatarJob?.running ? t("avatarGenerating") : t("avatarGenerate")}
|
||||
</button>
|
||||
<div className="avatar-official-notice"><PersonSimpleRun size={17} weight="duotone" /><span><strong>{t("avatarPortingStatus")}</strong><em>{t("avatarServiceHint")}</em></span></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -217,6 +262,8 @@ export function VoicePanel({
|
||||
hasVisual,
|
||||
visualType,
|
||||
audioDuration,
|
||||
avatarJob,
|
||||
generateAvatarAcceptanceFrame,
|
||||
}) {
|
||||
const isCaptionContext = activeTool === "caption";
|
||||
const isAvatarContext = activeTool === "smart" && avatarPanelOpen;
|
||||
@@ -226,7 +273,7 @@ export function VoicePanel({
|
||||
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
|
||||
: t("noCaptionSegments")
|
||||
: isAvatarContext
|
||||
? t("avatarServiceNeeded")
|
||||
? t("avatarPortingStatus")
|
||||
: statusText === "模型待命"
|
||||
? t("modelReady")
|
||||
: statusText;
|
||||
@@ -280,7 +327,7 @@ export function VoicePanel({
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{isAvatarContext ? <AvatarContextPanel t={t} hasVisual={hasVisual} visualType={visualType} audioBlob={audioBlob} audioDuration={audioDuration} captionSegments={captionSegments} selectedVoice={selectedVoice} /> : null}
|
||||
{isAvatarContext ? <AvatarContextPanel t={t} hasVisual={hasVisual} visualType={visualType} audioBlob={audioBlob} audioDuration={audioDuration} captionSegments={captionSegments} selectedVoice={selectedVoice} avatarJob={avatarJob} generateAvatarAcceptanceFrame={generateAvatarAcceptanceFrame} /> : null}
|
||||
|
||||
{!isCaptionContext && !isAvatarContext && voiceTab === "synthesis" ? (
|
||||
<VoiceSynthesisPanel
|
||||
|
||||
@@ -776,12 +776,12 @@ function SmartVisionPanel({
|
||||
<div className="avatar-lab-heading">
|
||||
<span className="avatar-lab-icon"><PersonSimpleRun size={18} weight="duotone" /></span>
|
||||
<div><span>{t("avatarKicker")}</span><strong>{t("avatarTitle")}</strong></div>
|
||||
<em className="is-ready">{t("avatarOfficial")}</em>
|
||||
<em className="is-ready">{t("avatarWebPort")}</em>
|
||||
</div>
|
||||
<p>{t("avatarDescription")}</p>
|
||||
<div className="avatar-lab-requirements">
|
||||
<span className={hasVisual && visualType === "image" ? "is-ready" : ""}>{t("avatarPortrait")}</span>
|
||||
<span className="is-ready">{t("avatarService")}</span>
|
||||
<span className="is-ready">{t("avatarWebgpu")}</span>
|
||||
<span>{t("avatarAudio")}</span>
|
||||
</div>
|
||||
<button className="panel-primary avatar-open-button" type="button" onClick={onOpenAvatarPanel}>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
const JOYVASA_REVISION = "b8f13fe9c23679c56f21b1baafb92ed00dc087c3";
|
||||
|
||||
export const JOYVASA_WEB_MODEL = Object.freeze({
|
||||
id: "jdh-algo/JoyVASA",
|
||||
sourceRevision: "916a90f8de490e8648fee460c1200bd5d9a795af",
|
||||
revision: JOYVASA_REVISION,
|
||||
license: "MIT",
|
||||
files: Object.freeze({
|
||||
audio: Object.freeze([
|
||||
"joyvasa-audio.onnx.part-aa",
|
||||
"joyvasa-audio.onnx.part-ab",
|
||||
"joyvasa-audio.onnx.part-ac",
|
||||
"joyvasa-audio.onnx.part-ad",
|
||||
"joyvasa-audio.onnx.part-ae",
|
||||
"joyvasa-audio.onnx.part-af",
|
||||
"joyvasa-audio.onnx.part-ag",
|
||||
"joyvasa-audio.onnx.part-ah",
|
||||
]),
|
||||
denoiser: "joyvasa-denoiser.onnx",
|
||||
conditioning: "joyvasa-conditioning.bin",
|
||||
schedule: "joyvasa-schedule.bin",
|
||||
template: "joyvasa-motion-template.json",
|
||||
}),
|
||||
knownArtifacts: Object.freeze({
|
||||
audio: Object.freeze({ bytes: 378_452_736, sha256: "51629927a44e13b117c163f8466b7eaa6653ffba71b0d26b8091610497ebf7d8" }),
|
||||
denoiser: Object.freeze({ bytes: 33_558_033, sha256: "6e0ea70203df8db5cdd663c75c1764134b207b87f2897ff4e53d279aa3f54928" }),
|
||||
conditioning: Object.freeze({ bytes: 14_184, sha256: "89e571e6b1491a88eeedfa7f17ba3ff43e70800e1daa6f544c1366c195dbd6ba" }),
|
||||
schedule: Object.freeze({ bytes: 408, sha256: "8ef96b44a0673a6f699b0fa4c6259d89db183cd6d0f8b483203bd84ca8baa828" }),
|
||||
template: Object.freeze({ bytes: 9_014, sha256: "f321337873a5b646ca26f80e97edd0efdc9d3c0f63d3a9d09ad7fb72d7d7f828" }),
|
||||
}),
|
||||
runtime: Object.freeze({ sampleRate: 16_000, windowSamples: 64_000, paddedSamples: 64_080, fps: 25, frames: 100, diffusionSteps: 50 }),
|
||||
});
|
||||
|
||||
export const JOYVASA_PROJECT_MODEL_BASE_URL = "/models/joyvasa/";
|
||||
@@ -0,0 +1,58 @@
|
||||
const LIVE_PORTRAIT_REVISION = "e6c5d2407593a39f29c92ffd5ea3eaf5e59d52a1";
|
||||
|
||||
export const LIVE_PORTRAIT_WEB_MODEL = Object.freeze({
|
||||
id: "dyicnc/Live-Portrait-ONNX",
|
||||
upstream: "myn0908/Live-Portrait-ONNX",
|
||||
revision: LIVE_PORTRAIT_REVISION,
|
||||
license: "MIT",
|
||||
status: "research",
|
||||
files: Object.freeze({
|
||||
appearanceFeatureExtractor: "appearance_feature_extractor.onnx",
|
||||
motionExtractor: "motion_extractor.onnx",
|
||||
generator: "generator_fix_grid.onnx",
|
||||
landmark: "landmark.onnx",
|
||||
warping: "warping.onnx",
|
||||
spadeGenerator: "spade_generator.onnx",
|
||||
stitching: "stitching.onnx",
|
||||
stitchingLip: "stitching_lip.onnx",
|
||||
stitchingRetargeting: "stitching_retargeting.onnx",
|
||||
}),
|
||||
knownArtifacts: Object.freeze({
|
||||
appearanceFeatureExtractor: Object.freeze({
|
||||
bytes: 3_355_896,
|
||||
sha256: "e9cd2bd864a970f25bbe660e132778fc7f81a4f32945a97940a6225c8b2dafb0",
|
||||
}),
|
||||
motionExtractor: Object.freeze({
|
||||
bytes: 112_593_241,
|
||||
sha256: "6be4dcb59827a5c9af587c8d7eb07bc9f5128ea01856e9b78cf7db316787cf86",
|
||||
}),
|
||||
generator: Object.freeze({
|
||||
bytes: 421_238_874,
|
||||
sha256: "44effc5f2129c03353feb56bb8db7828346c36e81ffbacb4ab0622b3d91d2c77",
|
||||
}),
|
||||
landmark: Object.freeze({
|
||||
bytes: 114_666_491,
|
||||
sha256: "31d22a5041326c31f19b78886939a634a5aedcaa5ab8b9b951a1167595d147db",
|
||||
}),
|
||||
warping: Object.freeze({
|
||||
bytes: 182_274_422,
|
||||
sha256: "3dbdccbd99417da27d8280111f18990bbaaebf54d08435e25bb48ef6ecf0bbf7",
|
||||
}),
|
||||
spadeGenerator: Object.freeze({
|
||||
bytes: 221_924_849,
|
||||
sha256: "16c815413f4b56537af1eca6cf92b83221d6ee8f5f9f65212c533a4dc8ae155d",
|
||||
}),
|
||||
stitching: Object.freeze({
|
||||
bytes: 182_363,
|
||||
sha256: "28b5fd0b97f3cee29b37b24937f2fa294d1548799b8a16d3cfe70fab1f49c785",
|
||||
}),
|
||||
stitchingLip: Object.freeze({
|
||||
bytes: 150_609,
|
||||
sha256: "33489d795915b78a8e96787c42c367cac23a0d5d3d2bd3efbb4af5ee758d42bb",
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
export function getLivePortraitModelUrl(file) {
|
||||
return `https://huggingface.co/${LIVE_PORTRAIT_WEB_MODEL.id}/resolve/${LIVE_PORTRAIT_WEB_MODEL.revision}/${file}`;
|
||||
}
|
||||
+38
-14
@@ -139,20 +139,32 @@ export const UI_COPY = {
|
||||
smartVisionClear: "清除当前分析",
|
||||
smartVisionCutoutDownload: "下载透明 PNG",
|
||||
smartVisionNoSubject: "没有找到高置信度主体,可换一帧后重试。",
|
||||
avatarKicker: "Avatar lab · WebGPU",
|
||||
avatarKicker: "Avatar lab · Browser ONNX",
|
||||
avatarTitle: "数字人(实验室)",
|
||||
avatarExperimental: "实验功能",
|
||||
avatarSupported: "浏览器已就绪",
|
||||
avatarDescription: "使用正脸照片与当前 AI 配音生成会说话的人像。首版采用浏览器端 ONNX 路径,模型将在首次生成时按需下载。",
|
||||
avatarPortrait: "正脸照片",
|
||||
avatarWebgpu: "WebGPU",
|
||||
avatarWebgpu: "WASM 稳定路径",
|
||||
avatarAudio: "当前配音",
|
||||
avatarCheck: "检查浏览器支持",
|
||||
avatarRecheck: "重新检查 WebGPU",
|
||||
avatarOfficial: "官方服务路线",
|
||||
avatarRecheck: "重新检查浏览器",
|
||||
avatarOfficial: "完整模型路线",
|
||||
avatarWebPort: "Web 移植中",
|
||||
avatarService: "官方推理服务",
|
||||
avatarServiceNeeded: "待配置官方 LivePortrait 服务",
|
||||
avatarServiceHint: "官方 LivePortrait 通过服务端完整模型运行:头像 + 音频驱动视频 → 正式人像动画。浏览器不会再生成伪口型结果。",
|
||||
avatarServiceNeeded: "LivePortrait Web 移植中",
|
||||
avatarServiceHint: "浏览器单帧与画面轨替换已通过验收;3D 形变当前使用较慢的 WASM 正确性路径,下一阶段接入音频驱动 ONNX 并进行 WebGPU 加速。",
|
||||
avatarPortingStatus: "模型工程 · 阶段 2/3",
|
||||
avatarModelSource: "锁定模型",
|
||||
avatarStagePinned: "模型版本已锁定",
|
||||
avatarStageGrid: "3D 形变单帧已跑通",
|
||||
avatarStageAudio: "音频驱动 ONNX",
|
||||
avatarChecking: "正在检测浏览器…",
|
||||
avatarPreparing: "准备肖像",
|
||||
avatarGenerateAcceptance: "生成单帧并替换画面轨",
|
||||
avatarAcceptanceDone: "单帧验收完成",
|
||||
avatarTrackReplaced: "LivePortrait 单帧已替换到画面轨",
|
||||
avatarGenerationFailed: "数字人生成失败",
|
||||
avatarOpen: "打开数字人控制台",
|
||||
avatarLipSyncTitle: "字幕口型同步",
|
||||
avatarLipSyncDescription: "将字幕时间轴和当前 AI 配音映射为人物嘴型与表情节奏。",
|
||||
@@ -164,7 +176,7 @@ export const UI_COPY = {
|
||||
avatarNeedsCaptions: "请先生成或添加字幕",
|
||||
avatarSyncMode: "同步方式",
|
||||
avatarSyncModeCaption: "字幕 + 配音精确对齐",
|
||||
avatarGenerationNote: "生成时会按需下载浏览器 ONNX 模型;首次运行需要 WebGPU,并可能耗时较长。",
|
||||
avatarGenerationNote: "已锁定 Hugging Face 模型提交与生成器校验值;兼容性验证不会下载 421MB 生成器。",
|
||||
avatarGenerate: "生成口型视频",
|
||||
avatarGenerating: "正在生成数字人视频",
|
||||
avatarGenerationHint: "首次运行会下载模型;请保持此页面打开。",
|
||||
@@ -371,20 +383,32 @@ export const UI_COPY = {
|
||||
smartVisionClear: "Clear current analysis",
|
||||
smartVisionCutoutDownload: "Download transparent PNG",
|
||||
smartVisionNoSubject: "No high-confidence subject found. Seek to another frame and retry.",
|
||||
avatarKicker: "Avatar lab · WebGPU",
|
||||
avatarKicker: "Avatar lab · Browser ONNX",
|
||||
avatarTitle: "Talking avatar (Lab)",
|
||||
avatarExperimental: "Experimental",
|
||||
avatarSupported: "Browser ready",
|
||||
avatarDescription: "Generate a talking portrait from a front-facing photo and the current AI voiceover. The browser ONNX model will download on first use.",
|
||||
avatarPortrait: "Front-facing photo",
|
||||
avatarWebgpu: "WebGPU",
|
||||
avatarWebgpu: "Stable WASM path",
|
||||
avatarAudio: "Current voiceover",
|
||||
avatarCheck: "Check browser support",
|
||||
avatarRecheck: "Recheck WebGPU",
|
||||
avatarOfficial: "Official service path",
|
||||
avatarRecheck: "Recheck browser",
|
||||
avatarOfficial: "Full-model path",
|
||||
avatarWebPort: "Web port in progress",
|
||||
avatarService: "Official inference service",
|
||||
avatarServiceNeeded: "Official LivePortrait service required",
|
||||
avatarServiceHint: "Official LivePortrait runs as a full server-side pipeline: portrait + audio-driven video → portrait animation. The browser will no longer produce simulated lip-sync output.",
|
||||
avatarServiceNeeded: "LivePortrait Web port in progress",
|
||||
avatarServiceHint: "Browser single-frame inference and visual-track replacement have passed. The 3D warping path currently uses the slower WASM correctness path; audio-driver ONNX and WebGPU acceleration are next.",
|
||||
avatarPortingStatus: "Model engineering · Stage 2/3",
|
||||
avatarModelSource: "Pinned model",
|
||||
avatarStagePinned: "Model revision pinned",
|
||||
avatarStageGrid: "3D browser frame passed",
|
||||
avatarStageAudio: "Audio driver ONNX",
|
||||
avatarChecking: "Checking browser…",
|
||||
avatarPreparing: "Preparing portrait",
|
||||
avatarGenerateAcceptance: "Generate frame and replace visual track",
|
||||
avatarAcceptanceDone: "Single-frame acceptance complete",
|
||||
avatarTrackReplaced: "LivePortrait frame replaced the visual track",
|
||||
avatarGenerationFailed: "Avatar generation failed",
|
||||
avatarOpen: "Open avatar controls",
|
||||
avatarLipSyncTitle: "Caption lip sync",
|
||||
avatarLipSyncDescription: "Map caption timing and the current voiceover into mouth and expression timing.",
|
||||
@@ -396,7 +420,7 @@ export const UI_COPY = {
|
||||
avatarNeedsCaptions: "Generate or add captions first",
|
||||
avatarSyncMode: "Sync method",
|
||||
avatarSyncModeCaption: "Captions + voiceover alignment",
|
||||
avatarGenerationNote: "The browser ONNX model downloads on demand. First use requires WebGPU and can take a while.",
|
||||
avatarGenerationNote: "The Hugging Face revision and generator checksum are pinned. Compatibility diagnostics do not download the 421 MB generator.",
|
||||
avatarGenerate: "Generate lip-sync video",
|
||||
avatarGenerating: "Generating avatar video",
|
||||
avatarGenerationHint: "First use downloads models. Keep this page open.",
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { LIVE_PORTRAIT_WEB_MODEL } from "../config/livePortrait.js";
|
||||
|
||||
const REQUIRED_GENERATOR_BYTES = LIVE_PORTRAIT_WEB_MODEL.knownArtifacts.generator.bytes;
|
||||
|
||||
function makeCheck(id, state, detail) {
|
||||
return { id, state, detail };
|
||||
}
|
||||
|
||||
export async function probeLivePortraitWebEnvironment() {
|
||||
const checks = [];
|
||||
const gpu = globalThis.navigator?.gpu;
|
||||
|
||||
if (!gpu) {
|
||||
checks.push(makeCheck("webgpu", "failed", "WebGPU unavailable"));
|
||||
return { readyForPorting: false, checks };
|
||||
}
|
||||
|
||||
let adapter;
|
||||
try {
|
||||
adapter = await gpu.requestAdapter({ powerPreference: "high-performance" });
|
||||
} catch (error) {
|
||||
checks.push(makeCheck("webgpu", "failed", error instanceof Error ? error.message : String(error)));
|
||||
return { readyForPorting: false, checks };
|
||||
}
|
||||
|
||||
if (!adapter) {
|
||||
checks.push(makeCheck("webgpu", "failed", "No WebGPU adapter"));
|
||||
return { readyForPorting: false, checks };
|
||||
}
|
||||
|
||||
checks.push(makeCheck("webgpu", "passed", "WebGPU adapter ready"));
|
||||
checks.push(makeCheck(
|
||||
"buffer",
|
||||
adapter.limits.maxBufferSize >= REQUIRED_GENERATOR_BYTES ? "passed" : "warning",
|
||||
`${Math.round(adapter.limits.maxBufferSize / 1024 / 1024)} MB max GPU buffer`,
|
||||
));
|
||||
|
||||
if (globalThis.crossOriginIsolated) {
|
||||
checks.push(makeCheck("isolation", "passed", "Cross-origin isolated"));
|
||||
} else {
|
||||
checks.push(makeCheck("isolation", "warning", "Single-thread fallback; COOP/COEP not enabled"));
|
||||
}
|
||||
|
||||
try {
|
||||
const estimate = await globalThis.navigator?.storage?.estimate?.();
|
||||
const available = Math.max(0, (estimate?.quota ?? 0) - (estimate?.usage ?? 0));
|
||||
checks.push(makeCheck(
|
||||
"storage",
|
||||
available >= 1_200_000_000 ? "passed" : "warning",
|
||||
estimate?.quota ? `${(available / 1024 / 1024 / 1024).toFixed(1)} GB cache available` : "Storage quota unavailable",
|
||||
));
|
||||
} catch {
|
||||
checks.push(makeCheck("storage", "warning", "Storage quota unavailable"));
|
||||
}
|
||||
|
||||
checks.push(makeCheck(
|
||||
"gridSample5d",
|
||||
"warning",
|
||||
"3D Conv / 5D GridSample use the verified WASM fallback; WebGPU acceleration pending",
|
||||
));
|
||||
|
||||
return {
|
||||
readyForPorting: checks.every((check) => check.state !== "failed"),
|
||||
checks,
|
||||
};
|
||||
}
|
||||
@@ -1494,6 +1494,19 @@ button:disabled {
|
||||
.avatar-input-list span { display: grid; gap: 3px; }.avatar-input-list strong { color: #dfe9ef; font-size: 11px; }.avatar-input-list em { color: #778592; font-size: 9px; font-style: normal; }
|
||||
.avatar-sync-mode { display: flex; justify-content: space-between; align-items: center; border-radius: 8px; padding: 10px; color: #93a2b0; background: rgba(255,255,255,.035); font-size: 10px; }.avatar-sync-mode strong { color: #77e5da; font-size: 10px; }.avatar-context-note { margin: 0; color: #778592; font-size: 10px; line-height: 1.55; }.avatar-generate-button { display: flex; align-items: center; justify-content: center; gap: 7px; min-height: 42px; width: 100%; }
|
||||
.avatar-official-notice { display: grid; grid-template-columns: 26px minmax(0, 1fr); gap: 8px; align-items: start; border: 1px solid rgba(108, 137, 255, .24); border-radius: 8px; padding: 10px; color: #9bb6ff; background: rgba(93, 122, 240, .08); }.avatar-official-notice > span { display: grid; gap: 3px; }.avatar-official-notice strong { color: #dce7ff; font-size: 11px; }.avatar-official-notice em { color: #94a2b4; font-size: 9px; font-style: normal; line-height: 1.45; }
|
||||
.avatar-porting-stages { display: grid; gap: 7px; }
|
||||
.avatar-porting-stages > div { display: grid; grid-template-columns: 22px minmax(0, 1fr); align-items: center; gap: 8px; color: #6f7c8a; font-size: 10px; }
|
||||
.avatar-porting-stages span { display: grid; place-items: center; width: 22px; height: 22px; border: 1px solid rgba(255,255,255,.08); border-radius: 50%; font-size: 9px; }
|
||||
.avatar-porting-stages .is-done { color: #70ded3; }.avatar-porting-stages .is-done span { border-color: rgba(53,234,217,.3); background: rgba(53,234,217,.08); }
|
||||
.avatar-porting-stages .is-active { color: #b9c8ff; }.avatar-porting-stages .is-active span { border-color: rgba(112,139,255,.38); background: rgba(112,139,255,.12); }
|
||||
.avatar-probe-results { display: grid; gap: 5px; border-radius: 8px; padding: 9px; background: rgba(255,255,255,.025); }
|
||||
.avatar-probe-results > div { display: grid; grid-template-columns: 7px minmax(0,1fr); align-items: center; gap: 7px; color: #91a0af; font-size: 9px; line-height: 1.4; }
|
||||
.avatar-probe-results > div > span { width: 6px; height: 6px; border-radius: 50%; background: #7e8b98; }
|
||||
.avatar-probe-results .is-passed > span { background: #35ead9; }.avatar-probe-results .is-warning > span { background: #f0b75c; }.avatar-probe-results .is-blocked > span,.avatar-probe-results .is-failed > span { background: #ff7f86; }
|
||||
.avatar-probe-button { display: flex; align-items: center; justify-content: center; width: 100%; min-height: 36px; }
|
||||
.avatar-generation-progress { display: grid; gap: 7px; border-radius: 8px; padding: 9px 10px; background: rgba(53,234,217,.045); }
|
||||
.avatar-generation-progress > div { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: #91a4b2; font-size: 9px; }.avatar-generation-progress strong { color: #70ded3; font-size: 10px; }
|
||||
.avatar-generation-progress > i { display: block; overflow: hidden; height: 4px; border-radius: 999px; background: rgba(255,255,255,.07); }.avatar-generation-progress b { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg,#6ea6ff,#35ead9); transition: width .25s ease; }
|
||||
|
||||
.vision-result-actions {
|
||||
display: grid;
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import * as ort from "onnxruntime-web/wasm";
|
||||
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.mjs?url";
|
||||
import ortWasmUrl from "../assets/ort-wasm-simd-threaded.wasm?url";
|
||||
|
||||
import { JOYVASA_WEB_MODEL } from "../config/joyVasa.js";
|
||||
|
||||
ort.env.wasm.numThreads = 1;
|
||||
ort.env.wasm.simd = true;
|
||||
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
|
||||
|
||||
const tensor = (data, dims) => new ort.Tensor("float32", data, dims);
|
||||
|
||||
function progress(value, phase) {
|
||||
self.postMessage({ type: "progress", progress: Math.round(value), phase });
|
||||
}
|
||||
|
||||
function modelUrl(file, baseUrl) {
|
||||
if (!baseUrl) throw new Error("JoyVASA 浏览器模型包尚未配置托管地址");
|
||||
return new URL(file, new URL(baseUrl, self.location.origin)).href;
|
||||
}
|
||||
|
||||
async function fetchArtifact(key, baseUrl, start, span) {
|
||||
const configuredFiles = JOYVASA_WEB_MODEL.files[key];
|
||||
const files = Array.isArray(configuredFiles) ? configuredFiles : [configuredFiles];
|
||||
const total = JOYVASA_WEB_MODEL.knownArtifacts[key].bytes;
|
||||
let loaded = 0;
|
||||
const parts = [];
|
||||
for (const file of files) {
|
||||
const response = await fetch(modelUrl(file, baseUrl));
|
||||
if (!response.ok) throw new Error(`${file} 下载失败(HTTP ${response.status})`);
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
const part = new Uint8Array(await response.arrayBuffer());
|
||||
parts.push(part);
|
||||
loaded += part.byteLength;
|
||||
continue;
|
||||
}
|
||||
const chunks = [];
|
||||
let partBytes = 0;
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
chunks.push(value);
|
||||
partBytes += value.byteLength;
|
||||
loaded += value.byteLength;
|
||||
progress(start + Math.min(1, loaded / total) * span, `下载 ${file}`);
|
||||
}
|
||||
const part = new Uint8Array(partBytes);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
part.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
parts.push(part);
|
||||
}
|
||||
const combined = new Uint8Array(loaded);
|
||||
let offset = 0;
|
||||
for (const part of parts) {
|
||||
combined.set(part, offset);
|
||||
offset += part.byteLength;
|
||||
}
|
||||
return combined.buffer;
|
||||
}
|
||||
|
||||
async function createSession(key, bytes) {
|
||||
// Use the deterministic WASM backend for the audio driver as well. The ORT
|
||||
// WebGPU bundle currently fails during module initialization in some browsers,
|
||||
// outside this session-level error boundary.
|
||||
return ort.InferenceSession.create(bytes, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
|
||||
}
|
||||
|
||||
function reflectPadOnce(input, amount) {
|
||||
const output = new Float32Array(input.length + amount * 2);
|
||||
output.set(input, amount);
|
||||
for (let i = 0; i < amount; i += 1) {
|
||||
output[amount - 1 - i] = input[i + 1];
|
||||
output[amount + input.length + i] = input[input.length - 2 - i];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
function prepareWindow(samples) {
|
||||
const source = new Float32Array(64_000);
|
||||
source.set(samples.subarray(0, Math.min(samples.length, source.length)));
|
||||
// Exact equivalent of JoyVASA pad_audio for a 64,000-sample window:
|
||||
// reflect-pad 20 samples twice, producing 64,080 samples.
|
||||
return reflectPadOnce(reflectPadOnce(source, 20), 20);
|
||||
}
|
||||
|
||||
function makeGaussian(seed = 0x6a09e667) {
|
||||
let state = seed >>> 0;
|
||||
let spare = null;
|
||||
const uniform = () => {
|
||||
state ^= state << 13;
|
||||
state ^= state >>> 17;
|
||||
state ^= state << 5;
|
||||
return ((state >>> 0) + 1) / 4294967297;
|
||||
};
|
||||
return () => {
|
||||
if (spare !== null) {
|
||||
const value = spare;
|
||||
spare = null;
|
||||
return value;
|
||||
}
|
||||
const radius = Math.sqrt(-2 * Math.log(uniform()));
|
||||
const angle = Math.PI * 2 * uniform();
|
||||
spare = radius * Math.sin(angle);
|
||||
return radius * Math.cos(angle);
|
||||
};
|
||||
}
|
||||
|
||||
function randomNormal(length, gaussian) {
|
||||
const values = new Float32Array(length);
|
||||
for (let i = 0; i < length; i += 1) values[i] = gaussian();
|
||||
return values;
|
||||
}
|
||||
|
||||
function repeatRows(values, rows, width) {
|
||||
const output = new Float32Array(rows * width);
|
||||
for (let row = 0; row < rows; row += 1) output.set(values, row * width);
|
||||
return output;
|
||||
}
|
||||
|
||||
async function sampleMotion(denoiser, audioFeatures, conditioning, schedule) {
|
||||
const startAudio = conditioning.subarray(0, 2560);
|
||||
const startMotion = conditioning.subarray(2560, 3290);
|
||||
const nullAudio = conditioning.subarray(3290, 3546);
|
||||
const audioBatch = new Float32Array(2 * 100 * 256);
|
||||
audioBatch.set(repeatRows(nullAudio, 100, 256), 0);
|
||||
audioBatch.set(audioFeatures, 100 * 256);
|
||||
const previousMotion = new Float32Array(2 * 10 * 73);
|
||||
previousMotion.set(startMotion, 0);
|
||||
previousMotion.set(startMotion, startMotion.length);
|
||||
const previousAudio = new Float32Array(2 * 10 * 256);
|
||||
previousAudio.set(startAudio, 0);
|
||||
previousAudio.set(startAudio, startAudio.length);
|
||||
const gaussian = makeGaussian();
|
||||
let motion = randomNormal(100 * 73, gaussian);
|
||||
|
||||
for (let step = 50; step >= 1; step -= 1) {
|
||||
const motionBatch = new Float32Array(motion.length * 2);
|
||||
motionBatch.set(motion, 0);
|
||||
motionBatch.set(motion, motion.length);
|
||||
const result = await denoiser.run({
|
||||
motion: tensor(motionBatch, [2, 100, 73]),
|
||||
audio: tensor(audioBatch, [2, 100, 256]),
|
||||
previous_motion: tensor(previousMotion, [2, 10, 73]),
|
||||
previous_audio: tensor(previousAudio, [2, 10, 256]),
|
||||
step: new ort.Tensor("int64", BigInt64Array.from([BigInt(step), BigInt(step)]), [2]),
|
||||
});
|
||||
const prediction = result.motion_prediction.data;
|
||||
const target = new Float32Array(motion.length);
|
||||
const unconditionalOffset = 10 * 73;
|
||||
const conditionalOffset = 110 * 73 + unconditionalOffset;
|
||||
for (let i = 0; i < target.length; i += 1) {
|
||||
const base = prediction[unconditionalOffset + i];
|
||||
target[i] = base + 1.15 * (prediction[conditionalOffset + i] - base);
|
||||
}
|
||||
const alpha = schedule[step * 2];
|
||||
const alphaBar = schedule[step * 2 + 1];
|
||||
const alphaBarPrevious = schedule[(step - 1) * 2 + 1];
|
||||
const beta = 1 - alpha;
|
||||
const c0 = ((1 - alphaBarPrevious) * Math.sqrt(alpha)) / (1 - alphaBar);
|
||||
const c1 = (beta * Math.sqrt(alphaBarPrevious)) / (1 - alphaBar);
|
||||
const sigma = Math.sqrt(((1 - alphaBarPrevious) / (1 - alphaBar)) * beta);
|
||||
const noise = step > 1 ? randomNormal(motion.length, gaussian) : null;
|
||||
const next = new Float32Array(motion.length);
|
||||
for (let i = 0; i < next.length; i += 1) next[i] = c0 * motion[i] + c1 * target[i] + (noise ? sigma * noise[i] : 0);
|
||||
motion = next;
|
||||
progress(66 + ((51 - step) / 50) * 32, `生成口型运动 ${51 - step}/50`);
|
||||
}
|
||||
return motion;
|
||||
}
|
||||
|
||||
async function generate({ audioSamples, modelBaseUrl }) {
|
||||
progress(1, "准备真实音频驱动");
|
||||
const [audioBytes, denoiserBytes, conditioningBytes, scheduleBytes] = await Promise.all([
|
||||
fetchArtifact("audio", modelBaseUrl, 2, 47),
|
||||
fetchArtifact("denoiser", modelBaseUrl, 49, 12),
|
||||
fetchArtifact("conditioning", modelBaseUrl, 61, 1),
|
||||
fetchArtifact("schedule", modelBaseUrl, 62, 1),
|
||||
]);
|
||||
progress(63, "初始化 JoyVASA ONNX");
|
||||
const [audioSession, denoiserSession] = await Promise.all([
|
||||
createSession("audio", audioBytes),
|
||||
createSession("denoiser", denoiserBytes),
|
||||
]);
|
||||
const window = prepareWindow(new Float32Array(audioSamples));
|
||||
const audioResult = await audioSession.run({ audio_padded: tensor(window, [1, 64_080]) });
|
||||
progress(66, "音频特征完成");
|
||||
const motion = await sampleMotion(
|
||||
denoiserSession,
|
||||
audioResult.audio_features.data,
|
||||
new Float32Array(conditioningBytes),
|
||||
new Float32Array(scheduleBytes),
|
||||
);
|
||||
progress(100, "真实音频运动生成完成");
|
||||
self.postMessage({ type: "motion", motion: motion.buffer, frames: 100, fps: 25 }, [motion.buffer]);
|
||||
}
|
||||
|
||||
self.onmessage = (event) => {
|
||||
if (event.data?.type !== "generate") return;
|
||||
generate(event.data).catch((error) => {
|
||||
self.postMessage({ type: "error", message: error instanceof Error ? error.message : String(error) });
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,294 @@
|
||||
import * as ort from "onnxruntime-web/wasm";
|
||||
import ortWasmMjsUrl from "onnxruntime-web/ort-wasm-simd-threaded.mjs?url";
|
||||
import ortWasmUrl from "../assets/ort-wasm-simd-threaded.wasm?url";
|
||||
|
||||
import { LIVE_PORTRAIT_WEB_MODEL, getLivePortraitModelUrl } from "../config/livePortrait.js";
|
||||
|
||||
ort.env.wasm.numThreads = 1;
|
||||
ort.env.wasm.simd = true;
|
||||
ort.env.wasm.wasmPaths = { mjs: ortWasmMjsUrl, wasm: ortWasmUrl };
|
||||
|
||||
const tensor = (data, dims) => new ort.Tensor("float32", data, dims);
|
||||
|
||||
function postProgress(progress, phase) {
|
||||
self.postMessage({ type: "progress", progress: Math.max(0, Math.min(100, Math.round(progress))), phase });
|
||||
}
|
||||
|
||||
function resolveModelUrl(file, modelBaseUrl) {
|
||||
return modelBaseUrl ? new URL(file, modelBaseUrl).href : getLivePortraitModelUrl(file);
|
||||
}
|
||||
|
||||
async function fetchModel(key, file, modelBaseUrl, completedBytes, totalBytes) {
|
||||
const response = await fetch(resolveModelUrl(file, modelBaseUrl));
|
||||
if (!response.ok) throw new Error(`${file} 下载失败(HTTP ${response.status})`);
|
||||
if (!response.body) return response.arrayBuffer();
|
||||
let loaded = 0;
|
||||
const stream = response.body.pipeThrough(new TransformStream({
|
||||
transform(chunk, controller) {
|
||||
loaded += chunk.byteLength;
|
||||
postProgress(5 + ((completedBytes + loaded) / totalBytes) * 55, `下载 ${key}`);
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
}));
|
||||
return new Response(stream).arrayBuffer();
|
||||
}
|
||||
|
||||
async function loadSession(key, modelBaseUrl, downloadState) {
|
||||
const file = LIVE_PORTRAIT_WEB_MODEL.files[key];
|
||||
const bytes = LIVE_PORTRAIT_WEB_MODEL.knownArtifacts[key]?.bytes ?? 0;
|
||||
const model = await fetchModel(key, file, modelBaseUrl, downloadState.completed, downloadState.total);
|
||||
downloadState.completed += bytes;
|
||||
postProgress(5 + (downloadState.completed / downloadState.total) * 55, `初始化 ${key}`);
|
||||
// Keep the accepted browser pipeline on WASM until the complete LivePortrait
|
||||
// graph has been validated on WebGPU. Importing the WebGPU bundle can throw an
|
||||
// asynchronous ORT-internal error before session fallback gets a chance to run.
|
||||
return ort.InferenceSession.create(model, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
|
||||
}
|
||||
|
||||
function preprocessPortrait(blob) {
|
||||
return createImageBitmap(blob).then((bitmap) => {
|
||||
const size = Math.min(bitmap.width, bitmap.height);
|
||||
const sx = Math.max(0, (bitmap.width - size) / 2);
|
||||
const sy = Math.max(0, (bitmap.height - size) / 2 - size * 0.125);
|
||||
const canvas = new OffscreenCanvas(256, 256);
|
||||
const context = canvas.getContext("2d", { willReadFrequently: true });
|
||||
context.clearRect(0, 0, 256, 256);
|
||||
context.drawImage(bitmap, sx, sy, size, size, 0, 0, 256, 256);
|
||||
bitmap.close();
|
||||
const rgba = context.getImageData(0, 0, 256, 256).data;
|
||||
const plane = 256 * 256;
|
||||
const chw = new Float32Array(plane * 3);
|
||||
for (let i = 0; i < plane; i += 1) {
|
||||
const alpha = rgba[i * 4 + 3] / 255;
|
||||
chw[i] = (rgba[i * 4] / 255) * alpha;
|
||||
chw[plane + i] = (rgba[i * 4 + 1] / 255) * alpha;
|
||||
chw[plane * 2 + i] = (rgba[i * 4 + 2] / 255) * alpha;
|
||||
}
|
||||
return tensor(chw, [1, 3, 256, 256]);
|
||||
});
|
||||
}
|
||||
|
||||
function headposeDegree(logits) {
|
||||
let max = -Infinity;
|
||||
for (const value of logits) max = Math.max(max, value);
|
||||
let sum = 0;
|
||||
let weighted = 0;
|
||||
for (let i = 0; i < logits.length; i += 1) {
|
||||
const value = Math.exp(logits[i] - max);
|
||||
sum += value;
|
||||
weighted += value * i;
|
||||
}
|
||||
return (weighted / sum) * 3 - 97.5;
|
||||
}
|
||||
|
||||
function multiply3x3(a, b) {
|
||||
const out = new Float32Array(9);
|
||||
for (let row = 0; row < 3; row += 1) for (let col = 0; col < 3; col += 1) {
|
||||
out[row * 3 + col] = a[row * 3] * b[col] + a[row * 3 + 1] * b[3 + col] + a[row * 3 + 2] * b[6 + col];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function transpose3x3(value) {
|
||||
return new Float32Array([value[0], value[3], value[6], value[1], value[4], value[7], value[2], value[5], value[8]]);
|
||||
}
|
||||
|
||||
function rotationMatrix(pitchDegree, yawDegree, rollDegree) {
|
||||
const x = pitchDegree * Math.PI / 180;
|
||||
const y = yawDegree * Math.PI / 180;
|
||||
const z = rollDegree * Math.PI / 180;
|
||||
const rx = new Float32Array([1, 0, 0, 0, Math.cos(x), -Math.sin(x), 0, Math.sin(x), Math.cos(x)]);
|
||||
const ry = new Float32Array([Math.cos(y), 0, Math.sin(y), 0, 1, 0, -Math.sin(y), 0, Math.cos(y)]);
|
||||
const rz = new Float32Array([Math.cos(z), -Math.sin(z), 0, Math.sin(z), Math.cos(z), 0, 0, 0, 1]);
|
||||
const value = multiply3x3(rz, multiply3x3(ry, rx));
|
||||
return new Float32Array([value[0], value[3], value[6], value[1], value[4], value[7], value[2], value[5], value[8]]);
|
||||
}
|
||||
|
||||
function transformKeypoints(motion) {
|
||||
const rotation = rotationMatrix(headposeDegree(motion.pitch.data), headposeDegree(motion.yaw.data), headposeDegree(motion.roll.data));
|
||||
const out = new Float32Array(63);
|
||||
for (let point = 0; point < 21; point += 1) {
|
||||
const offset = point * 3;
|
||||
for (let axis = 0; axis < 3; axis += 1) {
|
||||
out[offset + axis] = motion.scale.data[0] * (
|
||||
motion.kp.data[offset] * rotation[axis]
|
||||
+ motion.kp.data[offset + 1] * rotation[3 + axis]
|
||||
+ motion.kp.data[offset + 2] * rotation[6 + axis]
|
||||
+ motion.exp.data[offset + axis]
|
||||
);
|
||||
}
|
||||
out[offset] += motion.t.data[0];
|
||||
out[offset + 1] += motion.t.data[1];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function retargetAndStitch(lipSession, stitchingSession, source, targetRatio) {
|
||||
const lipInput = new Float32Array(65);
|
||||
lipInput.set(source);
|
||||
lipInput[63] = 0.05;
|
||||
lipInput[64] = targetRatio;
|
||||
const lipResult = await lipSession.run({ input: tensor(lipInput, [1, 65]) });
|
||||
const driving = new Float32Array(63);
|
||||
for (let i = 0; i < 63; i += 1) driving[i] = source[i] + lipResult.output.data[i];
|
||||
const stitchInput = new Float32Array(126);
|
||||
stitchInput.set(source);
|
||||
stitchInput.set(driving, 63);
|
||||
const stitchResult = await stitchingSession.run({ input: tensor(stitchInput, [1, 126]) });
|
||||
for (let i = 0; i < 63; i += 1) driving[i] += stitchResult.output.data[i];
|
||||
for (let point = 0; point < 21; point += 1) {
|
||||
driving[point * 3] += stitchResult.output.data[63];
|
||||
driving[point * 3 + 1] += stitchResult.output.data[64];
|
||||
}
|
||||
return driving;
|
||||
}
|
||||
|
||||
async function outputToBlob(output) {
|
||||
const [, , height, width] = output.dims;
|
||||
const plane = width * height;
|
||||
const rgba = new Uint8ClampedArray(plane * 4);
|
||||
for (let i = 0; i < plane; i += 1) {
|
||||
rgba[i * 4] = Math.round(Math.max(0, Math.min(1, output.data[i])) * 255);
|
||||
rgba[i * 4 + 1] = Math.round(Math.max(0, Math.min(1, output.data[plane + i])) * 255);
|
||||
rgba[i * 4 + 2] = Math.round(Math.max(0, Math.min(1, output.data[plane * 2 + i])) * 255);
|
||||
rgba[i * 4 + 3] = 255;
|
||||
}
|
||||
const canvas = new OffscreenCanvas(width, height);
|
||||
canvas.getContext("2d").putImageData(new ImageData(rgba, width, height), 0, 0);
|
||||
return canvas.convertToBlob({ type: "image/png" });
|
||||
}
|
||||
|
||||
function templateValue(template, key, index = 0) {
|
||||
return Array.isArray(template[key]) ? template[key][index] : template[key];
|
||||
}
|
||||
|
||||
function decodeJoyVasaFrame(coefficients, frame, template) {
|
||||
const offset = frame * 73;
|
||||
const exp = new Float32Array(63);
|
||||
for (let i = 0; i < 63; i += 1) exp[i] = coefficients[offset + i] * template.std_exp[i] + template.mean_exp[i];
|
||||
const interpolate = (key, value, index = 0) => value * (templateValue(template, `max_${key}`, index) - templateValue(template, `min_${key}`, index)) + templateValue(template, `min_${key}`, index);
|
||||
const scale = interpolate("scale", coefficients[offset + 63]);
|
||||
const translation = new Float32Array(3);
|
||||
for (let i = 0; i < 3; i += 1) translation[i] = interpolate("t", coefficients[offset + 64 + i], i);
|
||||
const pitch = interpolate("pitch", coefficients[offset + 67]);
|
||||
const yaw = interpolate("yaw", coefficients[offset + 68]);
|
||||
const roll = interpolate("roll", coefficients[offset + 69]);
|
||||
return { exp, scale, translation, rotation: rotationMatrix(pitch, yaw, roll) };
|
||||
}
|
||||
|
||||
function buildDrivingKeypoints(motion, source, driving, initialDriving) {
|
||||
const sourceRotation = rotationMatrix(headposeDegree(motion.pitch.data), headposeDegree(motion.yaw.data), headposeDegree(motion.roll.data));
|
||||
const relativeRotation = multiply3x3(multiply3x3(driving.rotation, transpose3x3(initialDriving.rotation)), sourceRotation);
|
||||
const lipPoints = new Set([6, 12, 14, 17, 19, 20]);
|
||||
const output = new Float32Array(63);
|
||||
for (let point = 0; point < 21; point += 1) {
|
||||
const base = point * 3;
|
||||
for (let axis = 0; axis < 3; axis += 1) {
|
||||
const relativeExpression = motion.exp.data[base + axis] + driving.exp[base + axis] - initialDriving.exp[base + axis];
|
||||
const expression = lipPoints.has(point) ? driving.exp[base + axis] : relativeExpression;
|
||||
const canonical = motion.kp.data[base] * relativeRotation[axis]
|
||||
+ motion.kp.data[base + 1] * relativeRotation[3 + axis]
|
||||
+ motion.kp.data[base + 2] * relativeRotation[6 + axis];
|
||||
output[base + axis] = motion.scale.data[0] * (driving.scale / initialDriving.scale) * (canonical + expression);
|
||||
}
|
||||
output[base] += motion.t.data[0] + driving.translation[0] - initialDriving.translation[0];
|
||||
output[base + 1] += motion.t.data[1] + driving.translation[1] - initialDriving.translation[1];
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
async function generateVideo({ portraitBlob, motionBuffer, modelBaseUrl, joyVasaModelBaseUrl, renderFps = 8 }) {
|
||||
postProgress(2, "准备肖像与真实口型运动");
|
||||
const image = await preprocessPortrait(portraitBlob);
|
||||
const keys = ["appearanceFeatureExtractor", "motionExtractor", "stitching", "warping", "spadeGenerator"];
|
||||
const downloadState = { completed: 0, total: keys.reduce((sum, key) => sum + (LIVE_PORTRAIT_WEB_MODEL.knownArtifacts[key]?.bytes ?? 0), 0) };
|
||||
const sessions = {};
|
||||
for (const key of keys) sessions[key] = await loadSession(key, modelBaseUrl, downloadState);
|
||||
const templateResponse = await fetch(new URL("joyvasa-motion-template.json", new URL(joyVasaModelBaseUrl, self.location.origin)));
|
||||
if (!templateResponse.ok) throw new Error(`JoyVASA 运动模板下载失败(HTTP ${templateResponse.status})`);
|
||||
const template = await templateResponse.json();
|
||||
const coefficients = new Float32Array(motionBuffer);
|
||||
|
||||
postProgress(63, "提取人物 3D 特征");
|
||||
const feature = (await sessions.appearanceFeatureExtractor.run({ img: image })).output;
|
||||
const sourceMotion = await sessions.motionExtractor.run({ img: image });
|
||||
const source = transformKeypoints(sourceMotion);
|
||||
const initialDriving = decodeJoyVasaFrame(coefficients, 0, template);
|
||||
const frameCount = Math.ceil(4 * renderFps);
|
||||
const blobs = [];
|
||||
for (let outputFrame = 0; outputFrame < frameCount; outputFrame += 1) {
|
||||
const motionFrame = Math.min(99, Math.round((outputFrame / renderFps) * 25));
|
||||
const driving = decodeJoyVasaFrame(coefficients, motionFrame, template);
|
||||
const rawDriving = buildDrivingKeypoints(sourceMotion, source, driving, initialDriving);
|
||||
const stitched = await (async () => {
|
||||
const input = new Float32Array(126);
|
||||
input.set(source);
|
||||
input.set(rawDriving, 63);
|
||||
const result = await sessions.stitching.run({ input: tensor(input, [1, 126]) });
|
||||
const value = new Float32Array(rawDriving);
|
||||
for (let i = 0; i < 63; i += 1) value[i] += result.output.data[i];
|
||||
for (let point = 0; point < 21; point += 1) {
|
||||
value[point * 3] += result.output.data[63];
|
||||
value[point * 3 + 1] += result.output.data[64];
|
||||
}
|
||||
return value;
|
||||
})();
|
||||
const warped = await sessions.warping.run({ feature_3d: feature, kp_source: tensor(source, [1, 21, 3]), kp_driving: tensor(stitched, [1, 21, 3]) });
|
||||
const generated = await sessions.spadeGenerator.run({ input: warped["879"] });
|
||||
blobs.push(await outputToBlob(generated.output));
|
||||
postProgress(68 + ((outputFrame + 1) / frameCount) * 31, `渲染口型帧 ${outputFrame + 1}/${frameCount}`);
|
||||
}
|
||||
postProgress(100, "真实口型帧生成完成");
|
||||
self.postMessage({ type: "videoFrames", blobs, width: 512, height: 512, fps: renderFps, duration: 4 });
|
||||
}
|
||||
|
||||
async function generate({ portraitBlob, modelBaseUrl }) {
|
||||
postProgress(2, "准备肖像");
|
||||
const image = await preprocessPortrait(portraitBlob);
|
||||
const keys = ["appearanceFeatureExtractor", "motionExtractor", "stitchingLip", "stitching", "warping", "spadeGenerator"];
|
||||
const downloadState = {
|
||||
completed: 0,
|
||||
total: keys.reduce((sum, key) => sum + (LIVE_PORTRAIT_WEB_MODEL.knownArtifacts[key]?.bytes ?? 0), 0),
|
||||
};
|
||||
const sessions = {};
|
||||
for (const key of keys) sessions[key] = await loadSession(key, modelBaseUrl, downloadState);
|
||||
|
||||
postProgress(63, "提取人物特征");
|
||||
const feature = (await sessions.appearanceFeatureExtractor.run({ img: image })).output;
|
||||
const motion = await sessions.motionExtractor.run({ img: image });
|
||||
const source = transformKeypoints(motion);
|
||||
const driving = await retargetAndStitch(sessions.stitchingLip, sessions.stitching, source, 0.35);
|
||||
|
||||
postProgress(70, "计算 3D 形变(可能需要约 1 分钟)");
|
||||
const warped = await sessions.warping.run({
|
||||
feature_3d: feature,
|
||||
kp_source: tensor(source, [1, 21, 3]),
|
||||
kp_driving: tensor(driving, [1, 21, 3]),
|
||||
});
|
||||
postProgress(86, "渲染 512×512 人像");
|
||||
const generated = await sessions.spadeGenerator.run({ input: warped["879"] });
|
||||
const blob = await outputToBlob(generated.output);
|
||||
postProgress(100, "单帧验收完成");
|
||||
self.postMessage({ type: "result", blob, width: 512, height: 512 });
|
||||
}
|
||||
|
||||
async function probe({ modelBaseUrl }) {
|
||||
const bytes = LIVE_PORTRAIT_WEB_MODEL.knownArtifacts.stitching.bytes;
|
||||
const session = await loadSession("stitching", modelBaseUrl, { completed: 0, total: bytes });
|
||||
session.release();
|
||||
self.postMessage({ type: "ready", backend: "wasm" });
|
||||
}
|
||||
|
||||
self.onmessage = (event) => {
|
||||
const task = event.data?.type === "generateVideo"
|
||||
? generateVideo
|
||||
: event.data?.type === "generate"
|
||||
? generate
|
||||
: event.data?.type === "probe"
|
||||
? probe
|
||||
: null;
|
||||
if (!task) return;
|
||||
task(event.data).catch((error) => {
|
||||
self.postMessage({ type: "error", message: error instanceof Error ? error.message : String(error) });
|
||||
});
|
||||
};
|
||||
Reference in new issue
Block a user