Files
aigc-home/calliope-web/src/lib/media/exportFrame.ts
T
施工员andmultica-agent 4f3293fc02 feat(media): 视频一键导出尾帧 PNG(生成结果页 + 共用播放弹层)(HEL-669)
- lib/media/exportFrame.ts:隐藏 video 取片尾前约 1 帧,黑帧/空帧逐级回退(≤1s),
  原生尺寸 canvas 导出 PNG;加载/损坏/404/403/跨域/超时/无法定位结尾分类报错
- lib/media/lastFrame.ts:下载 + 中文 Toast 反馈
- Inspector.svelte 操作区、ImageLightbox.svelte 视频工具栏加「导出尾帧」
- ToastHost 层级提到灯箱之上,弹层内反馈可见
- 七语言文案;npm test 新增 check-export-frame;e2e/lastframe.mjs 浏览器验收

Co-authored-by: multica-agent <github@multica.ai>
2026-10-01 23:12:34 +08:00

344 lines
10 KiB
TypeScript

/**
* 导出尾帧 (HEL-669): decode a frame just before the end of a video in the
* browser and save it as a PNG at the video's native resolution.
*
* Frames are taken from a hidden, muted <video> of the same URL so the
* player the user is watching never jumps. Media is served same-origin by
* /api/file, so the canvas stays untainted.
*
* The pure helpers at the top touch no DOM and import nothing, so
* scripts/check-export-frame.mjs can run them under plain Node.
*/
export type FrameErrorCode =
| "timeout"
| "not-found"
| "forbidden"
| "network"
| "decode"
| "unsupported"
| "cross-origin"
| "no-picture"
| "unseekable"
| "black"
| "empty";
export class FrameExportError extends Error {
code: FrameErrorCode;
constructor(code: FrameErrorCode, detail?: string) {
super(detail ? `${code}: ${detail}` : code);
this.name = "FrameExportError";
this.code = code;
}
}
/**
* Seconds before the end to try, nearest first. The exact end is often not
* decodable, so the first try is ~1 frame back; later tries step past a
* black fade-out tail.
*/
export const TAIL_OFFSETS = [0.05, 0.12, 0.25, 0.5, 1];
export function tailSeekTimes(duration: number): number[] {
if (!Number.isFinite(duration) || duration <= 0) return [0];
const times: number[] = [];
for (const off of TAIL_OFFSETS) {
const t = Math.max(0, Math.round((duration - off) * 1000) / 1000);
if (!times.includes(t)) times.push(t);
}
return times;
}
/** File name of the video behind a media URL (`/api/file?path=…` or plain). */
export function videoBaseName(src: string): string {
let name = "";
try {
const url = new URL(src, "http://local.invalid/");
const path =
url.searchParams.get("path") ?? decodeURIComponent(url.pathname);
name = path.split(/[\\/]/).pop() ?? "";
} catch {
name = "";
}
name = name.replace(/\.[a-z0-9]{1,5}$/i, "");
name = name.replace(/[\\/:*?"<>|\u0000-\u001f]+/g, "_").trim();
return name || "video";
}
/** `{视频名}_{tag}_{秒}s.png` — names the source video and the frame time. */
export function frameFileName(
src: string,
seconds: number,
tag: string,
): string {
const safeTag = tag.replace(/[\\/:*?"<>|\s]+/g, "-");
return `${videoBaseName(src)}_${safeTag}_${seconds.toFixed(3)}s.png`;
}
/**
* Classify sampled RGBA pixels: "empty" when nothing was painted (the
* decoder handed back no picture), "black" for an all-dark frame, else null.
* A bright highlight anywhere keeps a dark scene from counting as black.
*/
export function blankKind(rgba: ArrayLike<number>): "empty" | "black" | null {
let opaque = 0;
let sum = 0;
let max = 0;
for (let i = 0; i + 3 < rgba.length; i += 4) {
if (rgba[i + 3] < 8) continue;
opaque++;
const luma = 0.2126 * rgba[i] + 0.7152 * rgba[i + 1] + 0.0722 * rgba[i + 2];
sum += luma;
if (luma > max) max = luma;
}
if (opaque === 0) return "empty";
// 16 = limited-range video black when a decoder skips range expansion.
if (max < 40 && sum / opaque < 20) return "black";
return null;
}
/** HTTP status of a failed media fetch → error code (null = not decisive). */
export function statusErrorCode(status: number): FrameErrorCode | null {
if (status === 404 || status === 410) return "not-found";
if (status === 401 || status === 403) return "forbidden";
if (status >= 400) return "network";
return null;
}
// ---- browser side -------------------------------------------------------
export interface LastFrame {
blob: Blob;
width: number;
height: number;
/** Media time of the exported frame, in seconds. */
time: number;
fileName: string;
}
export interface CaptureOptions {
/** Word placed in the file name, e.g. 尾帧. */
fileTag: string;
timeoutMs?: number;
}
const SAMPLE = 64;
function isCrossOrigin(src: string): boolean {
try {
const url = new URL(src, location.href);
if (url.protocol === "blob:" || url.protocol === "data:") return false;
return url.origin !== location.origin;
} catch {
return false;
}
}
/** Probe the URL so a failed load can say 不存在 / 无权限 / 跨域 precisely. */
async function classifyLoadFailure(
video: HTMLVideoElement,
src: string,
crossOrigin: boolean,
): Promise<FrameExportError> {
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), 5000);
try {
const res = await fetch(src, {
headers: { Range: "bytes=0-0" },
mode: crossOrigin ? "cors" : "same-origin",
signal: ctl.signal,
});
ctl.abort();
const code = statusErrorCode(res.status);
if (code) return new FrameExportError(code, `HTTP ${res.status}`);
} catch {
if (crossOrigin) return new FrameExportError("cross-origin");
return new FrameExportError("network");
} finally {
clearTimeout(timer);
}
const mediaCode = video.error?.code;
if (mediaCode === MediaError.MEDIA_ERR_NETWORK) {
return new FrameExportError("network", video.error?.message);
}
if (mediaCode === MediaError.MEDIA_ERR_DECODE) {
return new FrameExportError("decode", video.error?.message);
}
return new FrameExportError("unsupported", video.error?.message);
}
export async function captureLastFrame(
src: string,
{ fileTag, timeoutMs = 30000 }: CaptureOptions,
): Promise<LastFrame> {
const crossOrigin = isCrossOrigin(src);
const video = document.createElement("video");
if (crossOrigin) video.crossOrigin = "anonymous";
video.muted = true;
video.playsInline = true;
video.preload = "auto";
video.setAttribute("aria-hidden", "true");
// Kept in the DOM (some engines never paint a detached video) but unseen.
Object.assign(video.style, {
position: "fixed",
left: "0",
top: "0",
width: "1px",
height: "1px",
opacity: "0",
pointerEvents: "none",
});
document.body.appendChild(video);
const deadline = Date.now() + timeoutMs;
/** Resolve on `event`; reject on a media error or the shared deadline. */
const until = (event: string) =>
new Promise<void>((resolve, reject) => {
const done = (fn: () => void) => {
clearTimeout(timer);
video.removeEventListener(event, onEvent);
video.removeEventListener("error", onError);
fn();
};
const onEvent = () => done(resolve);
const onError = () =>
done(() => {
classifyLoadFailure(video, src, crossOrigin).then(reject, reject);
});
const timer = setTimeout(
() => done(() => reject(new FrameExportError("timeout"))),
Math.max(0, deadline - Date.now()),
);
video.addEventListener(event, onEvent);
video.addEventListener("error", onError);
});
const seek = async (time: number) => {
const settled = until("seeked");
video.currentTime = time;
await settled;
};
/** Wait until the seeked frame has actually been decoded and presented. */
const presented = () =>
new Promise<void>((resolve) => {
const fallback = setTimeout(resolve, 250);
const finish = () => {
clearTimeout(fallback);
resolve();
};
if (typeof video.requestVideoFrameCallback === "function") {
video.requestVideoFrameCallback(() => finish());
} else {
requestAnimationFrame(() => requestAnimationFrame(finish));
}
});
try {
const metadata = until("loadedmetadata");
video.src = src;
video.load();
await metadata;
if (!video.videoWidth || !video.videoHeight) {
throw new FrameExportError("no-picture");
}
// MediaRecorder WebM reports Infinity until the end has been read. When
// the server cannot seek either, the end is unreachable — fail rather
// than hand back the first frame.
let duration = video.duration;
if (!Number.isFinite(duration) || duration <= 0) {
await seek(1e101);
duration = video.duration;
if (!Number.isFinite(duration) || duration <= 0) {
throw new FrameExportError("unseekable", "duration unknown");
}
}
const width = video.videoWidth;
const height = video.videoHeight;
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
const sample = document.createElement("canvas");
sample.width = SAMPLE;
sample.height = SAMPLE;
const sampleCtx = sample.getContext("2d", { willReadFrequently: true });
if (!ctx || !sampleCtx)
throw new FrameExportError("empty", "no 2d context");
let lastBlank: "empty" | "black" = "empty";
for (const time of tailSeekTimes(duration)) {
await seek(time);
if (video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA) {
// iOS Safari only decodes after a play(); muted inline play is allowed.
await video.play().catch(() => {});
video.pause();
await seek(time);
}
if (Math.abs(video.currentTime - time) > 0.5) {
throw new FrameExportError(
"unseekable",
`asked ${time}s, landed at ${video.currentTime}s`,
);
}
await presented();
ctx.clearRect(0, 0, width, height);
ctx.drawImage(video, 0, 0, width, height);
sampleCtx.clearRect(0, 0, SAMPLE, SAMPLE);
sampleCtx.drawImage(canvas, 0, 0, SAMPLE, SAMPLE);
let pixels: Uint8ClampedArray;
try {
pixels = sampleCtx.getImageData(0, 0, SAMPLE, SAMPLE).data;
} catch (err) {
throw new FrameExportError("cross-origin", String(err));
}
const blank = blankKind(pixels);
if (blank) {
lastBlank = blank;
continue;
}
const blob = await new Promise<Blob | null>((resolve) => {
try {
canvas.toBlob(resolve, "image/png");
} catch {
resolve(null);
}
});
if (!blob) throw new FrameExportError("empty", "toBlob returned nothing");
const shown = video.currentTime;
return {
blob,
width,
height,
time: shown,
fileName: frameFileName(src, shown, fileTag),
};
}
throw new FrameExportError(lastBlank);
} finally {
video.removeAttribute("src");
video.load();
video.remove();
}
}
export function downloadBlob(blob: Blob, fileName: string): void {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.rel = "noopener";
a.style.display = "none";
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 60000);
}