diff --git a/packages/cli/src/commands/snapshotHeldVideos.ts b/packages/cli/src/commands/snapshotHeldVideos.ts index 63c41a0c2d..e5df9a682a 100644 --- a/packages/cli/src/commands/snapshotHeldVideos.ts +++ b/packages/cli/src/commands/snapshotHeldVideos.ts @@ -1,7 +1,7 @@ import { existsSync } from "node:fs"; import { isAbsolute, relative, resolve } from "node:path"; import { parseHTML } from "linkedom"; -import { MEDIA_RENDER_ID_ATTR } from "@hyperframes/core"; +import { MEDIA_RENDER_ID_ATTR, naturalVideoSize, streamRotation } from "@hyperframes/core"; import { isPrivateFileUnder, isStudioPrivatePath } from "@hyperframes/core/safe-path"; import { isNotMediaPayload, type CaptureVideoMetadataHint } from "@hyperframes/engine"; import { mediaInputFormatArgs } from "@hyperframes/parsers/ff-binaries"; @@ -84,19 +84,12 @@ interface ProbeJson { function parseProbe(json: ProbeJson): HeldVideoProbe { const duration = Number(json.format?.duration); const stream = json.streams?.[0]; - const rotation = Number( - stream?.side_data_list?.find((d) => d.rotation !== undefined)?.rotation ?? - stream?.tags?.rotate ?? - 0, - ); - const turned = Math.abs(rotation) % 180 === 90; const [width, height] = [Number(stream?.width), Number(stream?.height)]; - const sized = width > 0 && height > 0; - return { - duration: Number.isFinite(duration) && duration > 0 ? duration : 0, - width: sized ? (turned ? height : width) : 0, - height: sized ? (turned ? width : height) : 0, - }; + const shown = + stream && width > 0 && height > 0 + ? naturalVideoSize({ width, height, rotation: streamRotation(stream) }) + : { width: 0, height: 0 }; + return { duration: Number.isFinite(duration) && duration > 0 ? duration : 0, ...shown }; } /** A file's duration and display size from FFprobe, zeros when it cannot be read; each file is probed once. */ @@ -119,7 +112,7 @@ export function probeHeldVideo( "-select_streams", "v:0", "-show_entries", - "format=duration:stream=width,height:stream_tags=rotate:stream_side_data=rotation", + "format=duration:stream=width,height:stream_tags=rotate:stream_side_data_list", "-of", "json", "--", diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 0cbedad7d6..3b9abec906 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -308,6 +308,12 @@ export { type PreviewQuality, type PreviewSourceFacts, } from "./previewProxyBox"; +export { + naturalVideoSize, + parseSampleAspectRatio, + streamRotation, + type MediaDisplayFacts, +} from "./mediaDisplaySize"; export type { PausedVideoFrameProvider, PausedVideoFrameRequest, diff --git a/packages/core/src/mediaDisplaySize.ts b/packages/core/src/mediaDisplaySize.ts new file mode 100644 index 0000000000..2746a7cf3a --- /dev/null +++ b/packages/core/src/mediaDisplaySize.ts @@ -0,0 +1,37 @@ +/** A video file's facts as ffprobe reports them, as far as its shown size needs. */ +export interface MediaDisplayFacts { + width: number; + height: number; + sampleAspectRatio?: number; + rotation?: number; +} + +/** The size a browser lays a video file out at: narrow pixels make it taller, wide ones wider, then it turns. */ +export function naturalVideoSize(facts: MediaDisplayFacts): { width: number; height: number } { + const ratio = facts.sampleAspectRatio ?? 1; + const width = ratio > 1 ? Math.round(facts.width * ratio) : facts.width; + const height = ratio < 1 ? Math.round(facts.height / ratio) : facts.height; + return Math.abs(facts.rotation ?? 0) % 180 === 90 + ? { width: height, height: width } + : { width, height }; +} + +export function parseSampleAspectRatio(value: string | undefined): number | undefined { + const [num, den] = (value ?? "").split(":").map(Number); + if (!num || !den || !Number.isFinite(num) || !Number.isFinite(den)) return undefined; + const ratio = num / den; + return Math.abs(ratio - 1) < 1e-3 ? undefined : ratio; +} + +/** The turn ffprobe reports for a stream, from its display matrix or its older `rotate` tag. */ +export function streamRotation(stream: { + side_data_list?: { rotation?: number | string }[]; + tags?: Record; +}): number | undefined { + const turn = Number( + stream.side_data_list?.find((data) => data.rotation !== undefined)?.rotation ?? + stream.tags?.rotate ?? + 0, + ); + return Number.isFinite(turn) && turn % 360 !== 0 ? turn : undefined; +} diff --git a/packages/core/src/previewProxyBox.ts b/packages/core/src/previewProxyBox.ts index 1b27e536de..eb1056763d 100644 --- a/packages/core/src/previewProxyBox.ts +++ b/packages/core/src/previewProxyBox.ts @@ -57,6 +57,8 @@ export type PreviewSourceFacts = { codec?: string; frameRate?: number; variableFrameRate?: boolean; + sampleAspectRatio?: number; + rotation?: number; }; export const HEAVY_PIXEL_SHARE = 0.5; diff --git a/packages/core/src/runtime/mediaProxy.test.ts b/packages/core/src/runtime/mediaProxy.test.ts index cc36e5a1df..fac0840a75 100644 --- a/packages/core/src/runtime/mediaProxy.test.ts +++ b/packages/core/src/runtime/mediaProxy.test.ts @@ -18,6 +18,8 @@ import { type MediaCodecMapEntry, } from "./mediaProxy"; import { deriveCodecMapKey } from "./mediaSourceLookup"; +import { escapeCssString } from "./editingElement"; +import type { PreviewSourceFacts } from "../previewProxyBox"; import { recordOpenedAtInPoint, unproxiedSrc } from "./proxySrc"; vi.mock("./bridge", () => ({ @@ -101,9 +103,22 @@ beforeEach(() => { ); }); -afterEach(() => { +// Each runtime a test loads fresh keeps its own copy reporting: reset every one, or a late report reaches a later test. +const freshCopyResets: Array<() => void> = []; + +async function freshRuntime() { + vi.resetModules(); + vi.spyOn(window, "parent", "get").mockReturnValue({} as Window); + const mod = await import("./mediaProxy"); + const copies = await import("./previewCopies"); + freshCopyResets.push(copies.resetCopyReporting); + return { mod, copies }; +} + +function cleanUp(): void { resetSeekDispatchState(); resetCopyReporting(); + for (const reset of freshCopyResets.splice(0)) reset(); vi.useRealTimers(); vi.unstubAllGlobals(); vi.clearAllMocks(); @@ -112,7 +127,9 @@ afterEach(() => { document.head.innerHTML = ""; delete (window as { __HF_MEDIA_CODEC_MAP__?: unknown }).__HF_MEDIA_CODEC_MAP__; delete (window as { __HF_EXPORT_RENDER_SEEK_CONFIG?: unknown }).__HF_EXPORT_RENDER_SEEK_CONFIG; -}); +} + +afterEach(cleanUp); describe("maybeProxyProactively", () => { it("rewrites src and calls load() before first load for a hostile, undecodable asset", async () => { @@ -880,9 +897,7 @@ describe("deriveCodecMapKey", () => { describe("a copy sized to how large the video shows", () => { // A framed document learns its on-screen scale from its host; load a module that is framed. async function framedVideo(width: number, height: number) { - vi.resetModules(); - vi.spyOn(window, "parent", "get").mockReturnValue({} as Window); - const { maybeProxyProactively, setProxyDisplayScale } = await import("./mediaProxy"); + const { maybeProxyProactively, setProxyDisplayScale } = (await freshRuntime()).mod; window.__HF_MEDIA_CODEC_MAP__ = { "/video.mp4": HEVC_ENTRY }; const el = createVideo("/video.mp4"); stubCanPlayType(el, ""); @@ -903,6 +918,21 @@ describe("a copy sized to how large the video shows", () => { const boxOf = (el: HTMLMediaElement) => new URL(el.src, document.baseURI).searchParams.get("hf-proxy-box"); + // fails without the fix: a framed runtime nobody reset reported its removed copy (copies: null) into a later test. + it("keeps a framed runtime's copy report out of the next test", async () => { + vi.useFakeTimers(); + const { el } = await framedVideo(1080, 1920); + const copies = await import("./previewCopies"); + // A copy of a video the browser cannot play is reported at every quality. + copies.noteCopy(el, "making", null, false); + await vi.advanceTimersByTimeAsync(5000); + cleanUp(); + + copies.noteCopy(el, "ready", null, false); + const reports = postRuntimeMessageMock.mock.calls.filter(([m]) => m.type === "preview-copies"); + expect(reports).toEqual([]); + }); + it("names the lower levels at which a video would get a lighter copy", async () => { const { setProxyDisplayScale } = await framedVideo(1080, 1920); const { levelsWithLighterCopies } = await import("./mediaProxy"); @@ -1049,10 +1079,11 @@ describe("preview quality: lighter copies of heavy files", () => { const MID = { width: 2560, height: 1440, bitDepth: 8, bitrate: 10_000_000 }; // A framed page showing a 1920x1080 stage at full size on a 1x screen: a 2048x1218 box. - async function stage(facts: Record, codecMap?: Record) { - vi.resetModules(); - vi.spyOn(window, "parent", "get").mockReturnValue({} as Window); - const mod = await import("./mediaProxy"); + async function stage( + facts: Record, + codecMap?: Record, + ) { + const { mod, copies } = await freshRuntime(); window.__HF_MEDIA_SOURCE_FACTS__ = facts; if (codecMap) window.__HF_MEDIA_CODEC_MAP__ = codecMap as never; Object.defineProperty(document.documentElement, "clientWidth", { @@ -1072,7 +1103,7 @@ describe("preview quality: lighter copies of heavy files", () => { return el; }; mod.setProxyDisplayScale(1); - return { ...mod, video, posted: vi.mocked(bridge.postRuntimeMessage) }; + return { ...mod, video, copies, posted: vi.mocked(bridge.postRuntimeMessage) }; } const params = (el: HTMLMediaElement) => new URL(el.src, document.baseURI).searchParams; @@ -1405,6 +1436,188 @@ describe("preview quality: lighter copies of heavy files", () => { expect(el.getAttribute("poster")).toBe("/cover.jpg"); }); + // jsdom lays nothing out: give a video the content box a browser would, here its file's own or the default. + const laidOut = ( + el: HTMLVideoElement, + width: number, + height: number, + decoded?: [number, number], + ) => { + Object.defineProperty(el, "clientWidth", { configurable: true, value: width }); + Object.defineProperty(el, "clientHeight", { configurable: true, value: height }); + el.getClientRects = () => [{}] as unknown as DOMRectList; + if (decoded) { + Object.defineProperty(el, "videoWidth", { configurable: true, value: decoded[0] }); + Object.defineProperty(el, "videoHeight", { configurable: true, value: decoded[1] }); + } + return el; + }; + // The size the runtime pins for the copy the video plays now, or undefined when it pins none. + const pinnedSize = (el: HTMLMediaElement) => { + const mark = el.getAttribute("data-hf-file-size"); + const rule = Array.from(document.querySelectorAll("style")) + .flatMap((sheet) => (sheet.textContent ?? "").split("\n")) + .find( + (line) => + mark && + line.includes(`="${mark}"][src="${escapeCssString(el.getAttribute("src") ?? "")}"]`), + ); + return rule && /\{ ([^}]+) \}/.exec(rule)?.[1]; + }; + + it("keeps a video the film leaves unsized at its file's size, as a browser lays the file out, while a lighter copy plays", async () => { + const { video, setPreviewQuality, maybeProxyProactively } = await stage({ + "/video.mp4": HEAVY, + "/phone.mp4": { ...HEAVY, rotation: -90 }, + "/narrow.mp4": { ...HEAVY, sampleAspectRatio: 2 / 3 }, + "/sized.mp4": HEAVY, + "/decoded.mp4": HEAVY, + "/padded.mp4": HEAVY, + }); + setPreviewQuality(0.25); + const cases: Array<[string, (el: HTMLVideoElement) => HTMLVideoElement]> = [ + ["/video.mp4", (el) => laidOut(el, 300, 150)], + ["/phone.mp4", (el) => laidOut(el, 300, 150)], + ["/narrow.mp4", (el) => laidOut(el, 300, 150)], + ["/sized.mp4", (el) => laidOut(el, 320, 180)], + ["/decoded.mp4", (el) => laidOut(el, 3000, 1688, [3000, 1688])], + [ + "/padded.mp4", + (el) => { + el.style.boxSizing = "border-box"; + el.style.padding = "10px"; + return laidOut(el, 320, 170); + }, + ], + ]; + const pinned = []; + for (const [src, layOut] of cases) { + const el = layOut(video(src) as HTMLVideoElement); + maybeProxyProactively(el); + await settle(); + expect(params(el).get("hf-proxy-light")).toBe("1"); + pinned.push(pinnedSize(el)); + } + + expect(pinned).toEqual([ + "width: 3840px; height: 2160px; flex-shrink: 0;", + "width: 2160px; height: 3840px; flex-shrink: 0;", + "width: 3840px; height: 3240px; flex-shrink: 0;", + undefined, + "width: 3000px; height: 1688px; flex-shrink: 0;", + "width: 3860px; height: 2180px; flex-shrink: 0;", + ]); + }); + + it("keeps an unsized video at its file's size when its copy is made cold, behind a still that set its box", async () => { + vi.useFakeTimers(); + const statuses = [202, 206]; + vi.stubGlobal( + "fetch", + vi.fn(async () => { + const status = statuses.length > 1 ? statuses.shift()! : statuses[0]!; + const headers = status === 202 ? { "Retry-After": "2" } : undefined; + return new Response(status === 206 ? "x" : null, { status, headers }); + }), + ); + const { video, setPreviewQuality, maybeProxyProactively } = await stage({ + "/video.mp4": HEAVY, + }); + setPreviewQuality(0.25); + const el = laidOut(video() as HTMLVideoElement, 300, 150); + const media = await import("./media"); + media.syncRuntimeMedia({ + clips: [ + { + el, + start: 0, + mediaStart: 0, + duration: 10, + end: 10, + volume: null, + playbackRate: 1, + loop: false, + sourceDuration: null, + }, + ], + timeSeconds: 1, + playing: false, + playbackRate: 1, + getCompositionDuration: () => 0, + }); + maybeProxyProactively(el); + await vi.advanceTimersByTimeAsync(0); + expect(el.hasAttribute("src")).toBe(false); + expect(el.getAttribute("poster")).toContain("hf-proxy-still"); + + laidOut(el, 456, 256); + await vi.advanceTimersByTimeAsync(2_000); + expect(params(el).get("hf-proxy-light")).toBe("1"); + expect(pinnedSize(el)).toBe("width: 3840px; height: 2160px; flex-shrink: 0;"); + }); + + // fails without the fix: a throw while waiting for the copy skipped cleanup; a held video never got its src back. + it("gives a held video its file back when waiting for its copy throws", async () => { + vi.useFakeTimers(); + const broken = { + status: 202, + ok: false, + body: null, + headers: { + get: () => { + throw new Error("bad header"); + }, + }, + }; + vi.stubGlobal( + "fetch", + vi.fn(async () => broken), + ); + const { video, setPreviewQuality, maybeProxyProactively } = await stage({ + "/video.mp4": HEAVY, + }); + setPreviewQuality(0.25); + const el = laidOut(video() as HTMLVideoElement, 300, 150); + const media = await import("./media"); + media.syncRuntimeMedia({ + clips: [ + { + el, + start: 0, + mediaStart: 0, + duration: 10, + end: 10, + volume: null, + playbackRate: 1, + loop: false, + sourceDuration: null, + }, + ], + timeSeconds: 1, + playing: false, + playbackRate: 1, + getCompositionDuration: () => 0, + }); + maybeProxyProactively(el); + await vi.advanceTimersByTimeAsync(2_000); + expect(el.getAttribute("src")).toBe("/video.mp4"); + expect(el.hasAttribute("poster")).toBe(false); + }); + + it("keeps the file of a video that shows it at its own size when it fits", async () => { + const { video, setPreviewQuality, maybeProxyProactively } = await stage({ + "/video.mp4": HEAVY, + }); + setPreviewQuality(0.25); + for (const fit of ["none", "scale-down"]) { + const el = video(); + el.style.objectFit = fit; + maybeProxyProactively(el); + await settle(); + expect(isProxied(el)).toBe(false); + } + }); + it("lightens a video that appears after the level was lowered", async () => { const { video, setPreviewQuality, maybeProxyProactively } = await stage({ "/video.mp4": HEAVY, @@ -1447,6 +1660,24 @@ describe("preview quality: lighter copies of heavy files", () => { .filter((message) => message.type === "preview-copies") .at(-1); + // fails without the fix: an earlier test's runtime, never reset, reported its removed copies into this test. + it("keeps an earlier test's runtime silent once that test is cleaned up", async () => { + vi.useFakeTimers(); + const earlier = await stage({ "/video.mp4": HEAVY }); + const el = earlier.video(); + earlier.setPreviewQuality(0.5); + earlier.copies.noteCopy(el, "making", 0.5); + // Past the report throttle, as a test that advanced its clock ends. + await vi.advanceTimersByTimeAsync(2000); + cleanUp(); + + const { posted } = await stage({ "/video.mp4": HEAVY }); + posted.mockClear(); + // A chain the earlier runtime left mid-wait reaches its report after the next test began. + earlier.copies.noteCopy(el, "failed"); + expect(lastCopies(posted)).toBeUndefined(); + }); + it("counts the copies wanted, with how far the making has got, and says none at full quality", async () => { vi.useFakeTimers(); let reply = new Response(null, { diff --git a/packages/core/src/runtime/mediaProxy.ts b/packages/core/src/runtime/mediaProxy.ts index 73565c2491..a6a3fc2d23 100644 --- a/packages/core/src/runtime/mediaProxy.ts +++ b/packages/core/src/runtime/mediaProxy.ts @@ -15,7 +15,10 @@ import { deriveCodecMapKey, lookupCodecMapEntry, sourceFactsOf, + sourceFactsOfSrc, } from "./mediaSourceLookup"; +import { naturalVideoSize } from "../mediaDisplaySize"; +import { escapeCssString } from "./editingElement"; import { heldForCopy, heldPosters, @@ -46,7 +49,7 @@ import { type PreviewSourceFacts, wantsLighterCopy, } from "../previewProxyBox"; -import { capturePageIn } from "../studioPreviewMark"; +import { capturePageIn, PREVIEW_FILE_SIZE_ATTR } from "../studioPreviewMark"; /** * One entry per project-root-relative asset pathname, injected by the @@ -128,8 +131,8 @@ function shownScale(): Promise { /** The video's box in device pixels, at least the stage so a later zoom or a clip still hidden fits. */ function shownBox(el: HTMLMediaElement, scale: number): PreviewProxyBox | null { - // object-fit: none shows the source at its own size. - if (getComputedStyle(el).objectFit === "none") return null; + // These show the file at its own size when it fits, so a smaller copy would show smaller. + if (["none", "scale-down"].includes(getComputedStyle(el).objectFit)) return null; const rect = el.getBoundingClientRect(); const stage = document.documentElement; const pixels = scale * (window.devicePixelRatio || 1); @@ -299,10 +302,89 @@ function loadProxy( evictMediaSyncState(el); restartPlaybackHealth(); holdShownFrame(el); + keepFileSize(el, href, originalSrc); el.src = href; el.load(); } +// Each size this page pinned, keyed by mark and copy address, so a video given any other file is sized as before. +// ponytail: rules are never removed; at most one per copy and size this page asked for. +let copySizes: HTMLStyleElement | null = null; +const sizeRules = new Set(); +const pinnedSizes = new WeakMap(); +// Read before a hold or a still lays the box out instead of the file. +const sizedBeforeCopy = new WeakMap(); +const isCopyAddress = (src: string | null) => /[?&]hf-proxy=/.test(src ?? ""); + +/** While a smaller copy plays, a video the film leaves unsized keeps the size its file gave it. */ +function keepFileSize(el: HTMLMediaElement, href: string, originalSrc: string): void { + const decided = sizedBeforeCopy.get(el); + sizedBeforeCopy.delete(el); + const size = + isVideoElement(el) && (decided ?? sizedByItsFile(el)) ? fileSizeOf(el, originalSrc) : null; + if (!size) { + pinnedSizes.delete(el); + el.removeAttribute(PREVIEW_FILE_SIZE_ATTR); + return; + } + const mark = `${size.width}x${size.height}`; + pinnedSizes.set(el, { href, mark }); + el.setAttribute(PREVIEW_FILE_SIZE_ATTR, mark); + const rule = + `:where(video[${PREVIEW_FILE_SIZE_ATTR}="${mark}"][src="${escapeCssString(href)}"]) ` + + `{ width: ${size.width}px; height: ${size.height}px; flex-shrink: 0; }`; + if (sizeRules.has(rule)) return; + sizeRules.add(rule); + copySizes ??= document.createElement("style"); + copySizes.textContent += `${rule}\n`; + if (!copySizes.isConnected) document.head.appendChild(copySizes); +} + +/** The film leaves the video's size to its file: its content box is the file's own size (300x150 with none). */ +function sizedByItsFile(el: HTMLVideoElement): boolean { + if (pinnedSizes.get(el)?.href === el.getAttribute("src")) return true; + if (el.getClientRects().length === 0) return false; + const style = getComputedStyle(el); + const px = (value: string) => parseFloat(value) || 0; + const width = el.clientWidth - px(style.paddingLeft) - px(style.paddingRight); + const height = el.clientHeight - px(style.paddingTop) - px(style.paddingBottom); + const [own, ownHeight] = el.videoWidth ? [el.videoWidth, el.videoHeight] : [300, 150]; + return Math.abs(width - own) < 1 && Math.abs(height - ownHeight) < 1; +} + +/** The video's box at its file's size: the original's decoded size when it has one, else its facts. */ +function fileSizeOf( + el: HTMLVideoElement, + originalSrc: string, +): { width: number; height: number } | null { + const pinned = pinnedSizes.get(el); + if (pinned?.href === el.getAttribute("src")) { + const [width = 0, height = 0] = pinned.mark.split("x").map(Number); + return { width, height }; + } + if (!isCopyAddress(el.getAttribute("src")) && el.videoWidth > 0) { + return withBoxEdges(el, { width: el.videoWidth, height: el.videoHeight }); + } + const facts = sourceFactsOfSrc(originalSrc); + return facts && withBoxEdges(el, naturalVideoSize(facts)); +} + +/** A border-box video's size with its padding and border added, so its content box stays `size`. */ +function withBoxEdges(el: HTMLVideoElement, size: { width: number; height: number }) { + const style = getComputedStyle(el); + if (style.boxSizing !== "border-box") return size; + const px = (...values: string[]) => + values.reduce((sum, value) => sum + (parseFloat(value) || 0), 0); + return { + width: + size.width + + px(style.paddingLeft, style.paddingRight, style.borderLeftWidth, style.borderRightWidth), + height: + size.height + + px(style.paddingTop, style.paddingBottom, style.borderTopWidth, style.borderBottomWidth), + }; +} + /** * Render mode never proxies: the codec map arrives by injection (not a * fetch, so determinism holds) but render always decodes the original via @@ -447,6 +529,7 @@ async function makeCopy(el: HTMLMediaElement, job: CopyJob, scale: number | null if (proxyRequested.get(el) === originalAttr) proxyRequested.delete(el); return; } + if (isVideoElement(el)) sizedBeforeCopy.set(el, sizedByItsFile(el)); const held = lightFacts && box && isOversizedForPreview(lightFacts, box) && holdForCopy(el); const proxiedSrc = appendProxyParam( originalSrc, @@ -466,6 +549,7 @@ async function makeCopy(el: HTMLMediaElement, job: CopyJob, scale: number | null light && !held ? undefined : () => showStill(el, originalSrc, variant, box), ); const wanted = live(); + if (!served || !wanted) sizedBeforeCopy.delete(el); if (held) endCopyHold(el, served && wanted ? null : originalAttr); if (!wanted) { dropStill(el); diff --git a/packages/core/src/runtime/mediaSourceLookup.ts b/packages/core/src/runtime/mediaSourceLookup.ts index edce44d3ec..589bd72669 100644 --- a/packages/core/src/runtime/mediaSourceLookup.ts +++ b/packages/core/src/runtime/mediaSourceLookup.ts @@ -12,7 +12,10 @@ export function currentSrcValue(el: HTMLMediaElement): string { /** The decoded, query-free pathname the server's maps are keyed by; null with no src or a cross-origin one. */ export function deriveCodecMapKey(el: HTMLMediaElement): string | null { - const raw = currentSrcValue(el); + return codecMapKeyOf(currentSrcValue(el)); +} + +function codecMapKeyOf(raw: string): string | null { if (!raw) return null; let url: URL; try { @@ -67,7 +70,11 @@ export function lookupCodecMapEntry(pathname: string, map: Record) } export function sourceFactsOf(el: HTMLMediaElement): PreviewSourceFacts | null { + return sourceFactsOfSrc(currentSrcValue(el)); +} + +export function sourceFactsOfSrc(src: string): PreviewSourceFacts | null { const facts = window.__HF_MEDIA_SOURCE_FACTS__; - const key = deriveCodecMapKey(el); + const key = codecMapKeyOf(src); return facts && key !== null ? lookupCodecMapEntry(key, facts) : null; } diff --git a/packages/core/src/runtime/proxyWait.ts b/packages/core/src/runtime/proxyWait.ts index b61c5ffa66..164a1ebe26 100644 --- a/packages/core/src/runtime/proxyWait.ts +++ b/packages/core/src/runtime/proxyWait.ts @@ -33,7 +33,7 @@ function reportProgress(res: Response | null, onProgress?: (fraction: number) => } /** Asks for one byte of a `?hf-proxy=` URL until it is served, after each Retry-After: while the - * server answers 202 (copy being made) or 503 (queue full), and after up to 3 failed asks. */ + * server answers 202 (copy being made) or 503 (queue full), after up to 3 failed asks; a throw is not served. */ export async function waitForServedProxy( href: string, live: () => boolean, @@ -44,17 +44,21 @@ export async function waitForServedProxy( ): Promise { let failed = 0; let ask = href; - while (live()) { - const headers = askHeaders(atPlayhead(), background, onAsk); - const res = await fetch(ask, { headers, cache: "no-store" }).catch(() => null); - ask = withoutRetryFlag(href); - void res?.body?.cancel().catch(() => {}); - const pending = res?.status === 202 || res?.status === 503; - reportProgress(res, onProgress); - if (!pending && res?.ok) return true; - if (!pending && ++failed > MAX_FAILED_ASKS) return false; - const seconds = Math.min(Number(res?.headers.get("Retry-After")) || 2, 30); - await new Promise((resolveWait) => wallSetTimeout(resolveWait, seconds * 1000)); + try { + while (live()) { + const headers = askHeaders(atPlayhead(), background, onAsk); + const res = await fetch(ask, { headers, cache: "no-store" }).catch(() => null); + ask = withoutRetryFlag(href); + void res?.body?.cancel().catch(() => {}); + const pending = res?.status === 202 || res?.status === 503; + reportProgress(res, onProgress); + if (!pending && res?.ok) return true; + if (!pending && ++failed > MAX_FAILED_ASKS) return false; + const seconds = Math.min(Number(res?.headers.get("Retry-After")) || 2, 30); + await new Promise((resolveWait) => wallSetTimeout(resolveWait, seconds * 1000)); + } + } catch { + return false; } return false; } diff --git a/packages/core/src/studioPreviewMark.ts b/packages/core/src/studioPreviewMark.ts index 1df21126da..901615298d 100644 --- a/packages/core/src/studioPreviewMark.ts +++ b/packages/core/src/studioPreviewMark.ts @@ -66,6 +66,7 @@ export const RUNTIME_STAMPED_ATTR = "data-hf-autostamped"; export const CLIP_HIDDEN_ATTR = "data-hf-clip-hidden"; export const STUDIO_PREVIEW_FAR_SCENE_ATTR = "data-hf-far-scene"; export const STUDIO_PREVIEW_PARKED_SCENE_ATTR = "data-hf-parked-scene"; +export const PREVIEW_FILE_SIZE_ATTR = "data-hf-file-size"; export const PREVIEW_ONLY_ATTRS = [ PREVIEW_VIDEO_FRAME_ATTR, PREVIEW_VIDEO_SOURCE_ATTR, @@ -76,6 +77,7 @@ export const PREVIEW_ONLY_ATTRS = [ STUDIO_PREVIEW_LAZY_ATTR, PREVIEW_RASTER_ATTR, RUNTIME_STAMPED_ATTR, + PREVIEW_FILE_SIZE_ATTR, ] as const; export const isClipHiddenByRuntime = (el: HTMLElement) => diff --git a/packages/engine/src/utils/ffprobe.ts b/packages/engine/src/utils/ffprobe.ts index 0fd57cfcc2..3f5c9ab109 100644 --- a/packages/engine/src/utils/ffprobe.ts +++ b/packages/engine/src/utils/ffprobe.ts @@ -6,7 +6,7 @@ import { chunkCrc32 } from "./crc32.js"; import { StringDecoder } from "node:string_decoder"; import { tmpdir } from "os"; import { basename, join } from "path"; -import { redactTelemetryString } from "@hyperframes/core"; +import { parseSampleAspectRatio, redactTelemetryString, streamRotation } from "@hyperframes/core"; import { alphaDecoderFor, pixelFormatHasAlpha, @@ -907,12 +907,8 @@ export function parseFrameRate(frameRateStr: string | undefined): number { } function displayRotation(stream: FFProbeStream): { rotation?: number } { - const turn = Number( - stream.side_data_list?.find((data) => data.rotation !== undefined)?.rotation ?? - stream.tags?.rotate ?? - 0, - ); - return Number.isFinite(turn) && turn % 360 !== 0 ? { rotation: turn } : {}; + const rotation = streamRotation(stream); + return rotation === undefined ? {} : { rotation }; } export function displaySize( @@ -924,12 +920,7 @@ export function displaySize( : { width, height: metadata.height }; } -export function parseSampleAspectRatio(value: string | undefined): number | undefined { - const [num, den] = (value ?? "").split(":").map(Number); - if (!num || !den || !Number.isFinite(num) || !Number.isFinite(den)) return undefined; - const ratio = num / den; - return Math.abs(ratio - 1) < 1e-3 ? undefined : ratio; -} +export { parseSampleAspectRatio }; /** * Whether the first frame decoded with `decoder` (alpha-aware) has an alpha pixel format; undefined on any diff --git a/packages/studio-server/src/helpers/mediaMetadata.test.ts b/packages/studio-server/src/helpers/mediaMetadata.test.ts index bc651131e6..9c44be9b96 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.test.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.test.ts @@ -188,6 +188,34 @@ describe("probeMediaMetadata", () => { ).toMatchObject({ frameRate: 60, variableFrameRate: true }); }); + it("reads how a file's pixels stretch and turn, for the size it shows at", async () => { + const asked: string[][] = []; + const probe = (stream: object) => + probeMediaMetadata("/tmp/clip.mp4", (_path, args) => { + asked.push(args); + return { + status: 0, + stdout: JSON.stringify({ streams: [{ codec_type: "video", ...stream }] }), + stderr: "", + }; + }); + const size = { width: 1440, height: 1080 }; + + expect( + (await probe({ ...size, sample_aspect_ratio: "4:3", side_data_list: [{ rotation: -90 }] })) + .source, + ).toMatchObject({ ...size, sampleAspectRatio: 4 / 3, rotation: -90 }); + expect((await probe({ ...size, tags: { rotate: "90" } })).source).toMatchObject({ + rotation: 90, + }); + const plain = (await probe({ ...size, sample_aspect_ratio: "1:1" })).source; + expect(plain).not.toHaveProperty("sampleAspectRatio"); + expect(plain).not.toHaveProperty("rotation"); + expect(asked[0]?.join(" ")).toMatch( + /sample_aspect_ratio.*stream_tags=alpha_mode,rotate:stream_side_data_list:format/, + ); + }); + it("lists every stream with its flags, for a failure report", async () => { const metadata = await probeMediaMetadata("/tmp/clip.mov", () => ({ status: 0, diff --git a/packages/studio-server/src/helpers/mediaMetadata.ts b/packages/studio-server/src/helpers/mediaMetadata.ts index 3fab79fbdd..a83a197c7c 100644 --- a/packages/studio-server/src/helpers/mediaMetadata.ts +++ b/packages/studio-server/src/helpers/mediaMetadata.ts @@ -7,6 +7,8 @@ import { parseFirstFrameColour, readsKeyframeTransfers, parseKeyframeTransfers, + parseSampleAspectRatio, + streamRotation, type PreviewSourceFacts, type ToneMapFrameColour, } from "@hyperframes/core"; @@ -105,8 +107,10 @@ interface FfprobeStream { bit_rate?: string; r_frame_rate?: string; avg_frame_rate?: string; + sample_aspect_ratio?: string; disposition?: Record; tags?: Record; + side_data_list?: { rotation?: number | string }[]; } const VIDEO_EXT = new Set([ @@ -232,6 +236,17 @@ function bitDepthOf(stream: FfprobeStream): number { return suffixed ? Number(suffixed[1]) : 8; } +function shownAs( + stream: FfprobeStream, +): Pick { + const sampleAspectRatio = parseSampleAspectRatio(stream.sample_aspect_ratio); + const rotation = streamRotation(stream); + return { + ...(sampleAspectRatio === undefined ? {} : { sampleAspectRatio }), + ...(rotation === undefined ? {} : { rotation }), + }; +} + function sourceFactsOf( stream: FfprobeStream | undefined, formatBitrate: string | undefined, @@ -248,6 +263,7 @@ function sourceFactsOf( return { width: stream.width, height: stream.height, + ...shownAs(stream), bitDepth: bitDepthOf(stream), bitrate: Number.isFinite(bitrate) ? bitrate : 0, ...(nominal > 0 @@ -372,7 +388,7 @@ export async function probeMediaMetadata( "-v", "error", "-show_entries", - "stream=codec_type,codec_name,profile,pix_fmt,color_space,color_transfer,color_primaries,bits_per_raw_sample,width,height,bit_rate,r_frame_rate,avg_frame_rate:stream_disposition:stream_tags=alpha_mode:format=duration,bit_rate", + "stream=codec_type,codec_name,profile,pix_fmt,color_space,color_transfer,color_primaries,bits_per_raw_sample,width,height,sample_aspect_ratio,bit_rate,r_frame_rate,avg_frame_rate:stream_disposition:stream_tags=alpha_mode,rotate:stream_side_data_list:format=duration,bit_rate", "-of", "json", ...mediaInputArgs(filePath),