Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(runtime): render media treatments deterministically
ukimsanov944640c3283d
diff --git a/packages/core/src/colorGrading.test.ts b/packages/core/src/colorGrading.test.tsindex 6085768709..ff2b7f8972 100644--- a/packages/core/src/colorGrading.test.ts+++ b/packages/core/src/colorGrading.test.ts@@ -13,6 +13,7 @@ import {normalizeHfColorGradingWithVariables,serializeHfColorGrading,} from "./colorGrading";+import { lintHyperframeHtml } from "./lint";describe("color grading", () => {it("derives grade and effect preset views from their actual payloads", () => {@@ -28,6 +29,32 @@ describe("color grading", () => {expect(HF_COLOR_GRADING_PRESETS).toHaveLength(18);});+ it("keeps every canonical grading key accepted by lint", async () => {+ const grading = normalizeHfColorGrading("neutral");+ expect(grading).not.toBeNull();+ const html = (attribute: string) => `+ <html><body>+ <div id="root" data-composition-id="c1" data-start="0" data-width="1920" data-height="1080" data-duration="1">+ <img class="clip" data-start="0" data-duration="1" src="media.jpg" data-color-grading='${attribute}'>+ </div>+ <script>window.__timelines = {};</script>+ </body></html>+ `;++ const valid = await lintHyperframeHtml(html(serializeHfColorGrading(grading)));+ expect(valid.findings.filter((finding) => finding.severity === "error")).toEqual([]);++ const invalid = await lintHyperframeHtml(html('{"effects":{"notARealEffect":1}}'));+ expect(invalid.findings).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ code: "color_grading_invalid_structure",+ severity: "error",+ }),+ ]),+ );+ });+it("parses preset shorthand", () => {const grading = normalizeHfColorGrading("warm-daylight");expect(grading?.preset).toBe("warm-daylight");diff --git a/packages/core/src/runtime/colorGrading.test.ts b/packages/core/src/runtime/colorGrading.test.tsindex a02d6bdb30..a2be6c460e 100644--- a/packages/core/src/runtime/colorGrading.test.ts+++ b/packages/core/src/runtime/colorGrading.test.ts@@ -11,6 +11,7 @@ let lastUniform1f: ReturnType<typeof vi.fn> | null = null;let lastUniform3f: ReturnType<typeof vi.fn> | null = null;let lastShaderSources: string[] = [];let texImage2DCalls: unknown[][] = [];+let loseContextCalls = 0;const IDENTITY_2 = `LUT_3D_SIZE 2@@ -24,7 +25,9 @@ LUT_3D_SIZE 21 1 1`;-function createMockWebGl(options: { failMediaUpload?: boolean } = {}): WebGLRenderingContext {+function createMockWebGl(+ options: { failMediaUpload?: boolean; halfFloatSupported?: boolean } = {},+): WebGLRenderingContext {const shader = {};const program = {};const texture = {};@@ -54,6 +57,7 @@ function createMockWebGl(options: { failMediaUpload?: boolean } = {}): WebGLRendTEXTURE1: 0x84c1,TEXTURE2: 0x84c2,TEXTURE3: 0x84c3,+ TEXTURE4: 0x84c4,FLOAT: 0x1406,TRIANGLE_STRIP: 0x0005,UNPACK_FLIP_Y_WEBGL: 0x9240,@@ -88,6 +92,14 @@ function createMockWebGl(options: { failMediaUpload?: boolean } = {}): WebGLRendframebufferTexture2D: vi.fn(),checkFramebufferStatus: vi.fn(() => 0x8cd5),deleteFramebuffer: vi.fn(),+ getExtension: vi.fn((name: string) => {+ if (name === "WEBGL_lose_context") {+ return { loseContext: () => (loseContextCalls += 1) };+ }+ if (options.halfFloatSupported === false) return null;+ if (name === "OES_texture_half_float") return { HALF_FLOAT_OES: 0x8d61 };+ return name === "EXT_color_buffer_half_float" ? {} : null;+ }),createBuffer: vi.fn(() => buffer),bindBuffer: vi.fn(),bufferData: vi.fn(),@@ -138,6 +150,21 @@ function makeDrawableVideo(): HTMLVideoElement {return video;}+function makeDrawableImage(): HTMLImageElement {+ const image = document.createElement("img");+ image.id = "hero-image";+ image.setAttribute(HF_COLOR_GRADING_ATTR, serializeHfColorGrading({ effects: { blur: 0 } }));+ image.style.setProperty("--hf-color-grading-blur", "0");+ Object.defineProperty(image, "complete", { value: true, configurable: true });+ Object.defineProperty(image, "naturalWidth", { value: 640, configurable: true });+ Object.defineProperty(image, "naturalHeight", { value: 360, configurable: true });+ Object.defineProperty(image, "offsetWidth", { value: 640, configurable: true });+ Object.defineProperty(image, "offsetHeight", { value: 360, configurable: true });+ image.getBoundingClientRect = () =>+ ({ width: 640, height: 360, left: 0, top: 0, right: 640, bottom: 360 }) as DOMRect;+ return image;+}+function stubCubeLutFetch(text = IDENTITY_2): ReturnType<typeof vi.fn> {const fetchMock = vi.fn(() =>Promise.resolve({@@ -160,6 +187,7 @@ describe("createColorGradingRuntime", () => {lastUniform3f = null;lastShaderSources = [];texImage2DCalls = [];+ loseContextCalls = 0;getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation((type: string) =>@@ -174,6 +202,7 @@ describe("createColorGradingRuntime", () => {getContextSpy.mockRestore();delete window.__hfVariables;delete window.__hfVariablesByComp;+ delete window.__player;document.head.innerHTML = "";document.body.innerHTML = "";});@@ -189,6 +218,32 @@ describe("createColorGradingRuntime", () => {return { video, canvas };}+ it.each([+ { pixelRatio: 1, width: 640, height: 360 },+ { pixelRatio: 2, width: 1280, height: 720 },+ ])(+ "matches the WebGL drawing buffer to the displayed media at DPR $pixelRatio",+ ({ pixelRatio, width, height }) => {+ vi.stubGlobal("devicePixelRatio", pixelRatio);++ const { canvas } = startRuntimeWithVideo();++ expect(canvas.style.width).toBe("640px");+ expect(canvas.style.height).toBe("360px");+ expect(canvas.width).toBe(width);+ expect(canvas.height).toBe(height);+ },+ );++ it("uses the default non-preserved drawing buffer outside capture instrumentation", () => {+ startRuntimeWithVideo();++ expect(getContextSpy).toHaveBeenCalledWith("webgl", {+ alpha: true,+ premultipliedAlpha: false,+ });+ });+async function flushLutLoad(): Promise<void> {await Promise.resolve();await Promise.resolve();@@ -250,7 +305,7 @@ describe("createColorGradingRuntime", () => {expect(texImage2DCalls.length).toBe(drawsBefore);});- it("re-hides source media after timeline visibility sync", () => {+ it("releases inactive attribute grading and recreates it when visible", () => {const { video, canvas } = startRuntimeWithVideo();expect(canvas.id).toBe("__hf_color_grading_hero-video");@@ -261,23 +316,177 @@ describe("createColorGradingRuntime", () => {expect(canvas?.style.visibility).toBe("visible");expect(canvas?.style.opacity).toBe("1");+ video.style.visibility = "hidden";+ expect(runtime.setSourceVisibility(video, false)).toBe(true);++ expect(video.style.getPropertyValue("visibility")).toBe("hidden");+ expect(video.style.getPropertyValue("opacity")).toBe("");+ expect(video.hasAttribute("data-hf-color-grading-source-hidden")).toBe(false);+ expect(canvas.isConnected).toBe(false);+video.style.visibility = "visible";- runtime.setSourceVisibility(video, true);- runtime.redraw();+ expect(runtime.setSourceVisibility(video, true)).toBe(true);- expect(video.style.getPropertyValue("visibility")).toBe("visible");+ const recreated = document.querySelector<HTMLCanvasElement>("[data-hf-color-grading-canvas]");+ expect(recreated).not.toBeNull();+ expect(recreated).toBe(canvas);+ expect(getContextSpy).toHaveBeenCalledTimes(1);expect(video.style.getPropertyValue("opacity")).toBe("0");expect(video.style.getPropertyPriority("opacity")).toBe("important");- expect(canvas?.style.visibility).toBe("visible");+ });- video.style.visibility = "hidden";- runtime.setSourceVisibility(video, false);- runtime.redraw();+ it("defers WebGL setup for hidden attributed media until it becomes visible", () => {+ const video = makeDrawableVideo();+ video.style.display = "none";+ document.body.appendChild(video);- expect(video.style.getPropertyValue("visibility")).toBe("hidden");- expect(video.style.getPropertyValue("opacity")).toBe("0");- expect(video.style.getPropertyPriority("opacity")).toBe("important");- expect(canvas?.style.visibility).toBe("hidden");+ runtime = createColorGradingRuntime();++ expect(getContextSpy).not.toHaveBeenCalled();+ expect(document.querySelector("[data-hf-color-grading-canvas]")).toBeNull();+ expect(runtime.getStatus(video)).toEqual({+ state: "pending",+ message: "Waiting for visible media",+ });++ video.style.display = "block";+ expect(runtime.setSourceVisibility(video, true)).toBe(true);+ expect(getContextSpy).toHaveBeenCalledTimes(1);+ expect(document.querySelector("[data-hf-color-grading-canvas]")).not.toBeNull();+ });++ it("renders exact preset previews for ungraded media without replacing the source", async () => {+ const video = makeDrawableVideo();+ video.removeAttribute(HF_COLOR_GRADING_ATTR);+ document.body.appendChild(video);+ const toDataUrl = vi+ .spyOn(HTMLCanvasElement.prototype, "toDataURL")+ .mockReturnValue("data:image/png;base64,preview");+ runtime = createColorGradingRuntime();++ const batch = await runtime.renderPreviews(+ "#hero-video",+ [+ { id: "clean", grading: "clean-studio" },+ { id: "warm", grading: "warm-daylight" },+ ],+ { maxDimension: 160 },+ );++ expect(batch).toMatchObject({+ width: 160,+ height: 90,+ images: [+ { id: "clean", dataUrl: "data:image/png;base64,preview" },+ { id: "warm", dataUrl: "data:image/png;base64,preview" },+ ],+ });+ expect(getContextSpy).toHaveBeenCalledTimes(1);+ expect(document.querySelector("[data-hf-color-grading-canvas]")).toBeNull();+ expect(video.style.opacity).toBe("");++ await runtime.renderPreviews("#hero-video", [{ id: "mono", grading: "mono-clean" }]);+ expect(getContextSpy).toHaveBeenCalledTimes(1);++ const retinaBatch = await runtime.renderPreviews(+ "#hero-video",+ [{ id: "retina", grading: "neutral" }],+ { maxDimension: 400 },+ );+ expect(retinaBatch).toMatchObject({ width: 320, height: 180 });+ toDataUrl.mockRestore();+ });++ it("plays only a selected video for preview and restores its media state", () => {+ const video = makeDrawableVideo();+ let paused = true;+ Object.defineProperty(video, "paused", { configurable: true, get: () => paused });+ Object.defineProperty(video, "currentTime", {+ configurable: true,+ value: 3.25,+ writable: true,+ });+ Object.defineProperty(video, "duration", { configurable: true, value: 10 });+ const play = vi.spyOn(video, "play").mockImplementation(() => {+ paused = false;+ return Promise.resolve();+ });+ const pause = vi.spyOn(video, "pause").mockImplementation(() => {+ paused = true;+ });+ video.loop = false;+ video.muted = false;+ document.body.appendChild(video);+ runtime = createColorGradingRuntime();++ const stop = runtime.startPreviewPlayback("#hero-video");++ expect(stop).not.toBeNull();+ expect(play).toHaveBeenCalledTimes(1);+ expect(video.loop).toBe(true);+ expect(video.muted).toBe(true);+ video.currentTime = 6;+ stop?.();+ expect(pause).toHaveBeenCalledTimes(1);+ expect(video.currentTime).toBe(3.25);+ expect(video.loop).toBe(false);+ expect(video.muted).toBe(false);+ });++ it("does not start preview playback for an image", () => {+ const image = makeDrawableImage();+ document.body.appendChild(image);+ runtime = createColorGradingRuntime();++ expect(runtime.startPreviewPlayback("#hero-image")).toBeNull();+ });++ it("uses selected-video time for isolated animated preview frames", async () => {+ const video = makeDrawableVideo();+ Object.defineProperty(video, "currentTime", { configurable: true, value: 6.5 });+ document.body.appendChild(video);+ window.__player = { getTime: () => 1.25 };+ vi.spyOn(HTMLCanvasElement.prototype, "toDataURL").mockReturnValue(+ "data:image/png;base64,preview",+ );+ runtime = createColorGradingRuntime();++ await runtime.renderPreviews("#hero-video", [{ id: "vhs", grading: { effects: { vhs: 1 } } }], {+ maxDimension: 160,+ useMediaTime: true,+ });++ expect(lastUniform1f?.mock.calls).toContainEqual(["u_effectTime", 6.5]);+ });++ it("uses the LUT cache and canonical multipass renderer in preview batches", async () => {+ const video = makeDrawableVideo();+ video.removeAttribute(HF_COLOR_GRADING_ATTR);+ document.body.appendChild(video);+ const fetchMock = stubCubeLutFetch();+ const toDataUrl = vi+ .spyOn(HTMLCanvasElement.prototype, "toDataURL")+ .mockReturnValue("data:image/png;base64,lut-preview");+ runtime = createColorGradingRuntime();++ const batch = await runtime.renderPreviews("#hero-video", [+ {+ id: "lut",+ grading: { preset: "warm-daylight", lut: { src: "/looks/test.cube", intensity: 0.6 } },+ },+ { id: "blur", grading: { effects: { blur: 0.5 } } },+ { id: "bloom", grading: { effects: { bloom: 0.5, bloomRadius: 8 } } },+ { id: "kuwahara", grading: { effects: { kuwahara: 1, kuwaharaRadius: 0.25 } } },+ ]);++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(batch?.images).toEqual([+ { id: "lut", dataUrl: "data:image/png;base64,lut-preview" },+ { id: "blur", dataUrl: "data:image/png;base64,lut-preview" },+ { id: "bloom", dataUrl: "data:image/png;base64,lut-preview" },+ { id: "kuwahara", dataUrl: "data:image/png;base64,lut-preview" },+ ]);+ toDataUrl.mockRestore();});it("resolves grading values from the nearest sub-composition variable scope", () => {@@ -323,6 +532,151 @@ describe("createColorGradingRuntime", () => {expect(lastUniform1f).toHaveBeenCalledWith("u_exposure", 0.35);});+ it("samples seek-derived grading values from inline CSS properties on every redraw", () => {+ const video = makeDrawableVideo();+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({+ adjust: { exposure: 0.5 },+ effects: {+ blur: 0.2,+ bloom: 0.2,+ kuwahara: 0.2,+ pixelate: 0.3,+ ascii: 0.4,+ dither: 0.5,+ },+ lut: { src: "assets/luts/test.cube", intensity: 0.4 },+ }),+ );+ video.style.setProperty("--hf-color-grading-intensity", "0.25");+ video.style.setProperty("--hf-color-grading-lut-intensity", "0.35");+ video.style.setProperty("--hf-color-grading-exposure", "-0.15");+ video.style.setProperty("--hf-color-grading-blur", "0.45");+ video.style.setProperty("--hf-color-grading-bloom", "0.45");+ video.style.setProperty("--hf-color-grading-kuwahara", "0.45");+ video.style.setProperty("--hf-color-grading-pixelate", "0.55");+ video.style.setProperty("--hf-color-grading-ascii", "0.65");+ video.style.setProperty("--hf-color-grading-dither", "0.75");+ stubCubeLutFetch();+ startRuntimeWithVideo(video);++ if (!lastUniform1f) throw new Error("Expected WebGL uniform calls");+ expect(lastUniform1f).toHaveBeenCalledWith("u_intensity", 0.25);+ expect(lastUniform1f).toHaveBeenCalledWith("u_lutIntensity", 0.35);+ expect(lastUniform1f).toHaveBeenCalledWith("u_exposure", -0.15);+ expect(lastUniform1f).toHaveBeenCalledWith("u_blur", 0.45);+ expect(lastUniform1f).toHaveBeenCalledWith("u_bloom", 0.45);+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwahara", 0.45);+ expect(lastUniform1f).toHaveBeenCalledWith("u_pixelate", 0.55);+ expect(lastUniform1f).toHaveBeenCalledWith("u_ascii", 0.65);+ expect(lastUniform1f).toHaveBeenCalledWith("u_dither", 0.75);++ video.style.setProperty("--hf-color-grading-intensity", "0.75");+ video.style.setProperty("--hf-color-grading-lut-intensity", "0.65");+ video.style.setProperty("--hf-color-grading-exposure", "0.15");+ video.style.setProperty("--hf-color-grading-blur", "0.15");+ video.style.setProperty("--hf-color-grading-bloom", "0.15");+ video.style.setProperty("--hf-color-grading-kuwahara", "0.15");+ video.style.setProperty("--hf-color-grading-pixelate", "0.05");+ video.style.setProperty("--hf-color-grading-ascii", "0.15");+ video.style.setProperty("--hf-color-grading-dither", "0.25");+ lastUniform1f.mockClear();+ runtime?.redraw();++ expect(lastUniform1f).toHaveBeenCalledWith("u_intensity", 0.75);+ expect(lastUniform1f).toHaveBeenCalledWith("u_lutIntensity", 0.65);+ expect(lastUniform1f).toHaveBeenCalledWith("u_exposure", 0.15);+ expect(lastUniform1f).toHaveBeenCalledWith("u_blur", 0.15);+ expect(lastUniform1f).toHaveBeenCalledWith("u_bloom", 0.15);+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwahara", 0.15);+ expect(lastUniform1f).toHaveBeenCalledWith("u_pixelate", 0.05);+ expect(lastUniform1f).toHaveBeenCalledWith("u_ascii", 0.15);+ expect(lastUniform1f).toHaveBeenCalledWith("u_dither", 0.25);++ video.style.setProperty("--hf-color-grading-intensity", "invalid");+ video.style.setProperty("--hf-color-grading-lut-intensity", "2");+ video.style.setProperty("--hf-color-grading-exposure", "-3");+ video.style.setProperty("--hf-color-grading-blur", "-1");+ video.style.setProperty("--hf-color-grading-bloom", "invalid");+ video.style.setProperty("--hf-color-grading-kuwahara", "invalid");+ video.style.setProperty("--hf-color-grading-pixelate", "invalid");+ video.style.setProperty("--hf-color-grading-ascii", "-1");+ video.style.setProperty("--hf-color-grading-dither", "invalid");+ lastUniform1f.mockClear();+ runtime?.redraw();++ expect(lastUniform1f).toHaveBeenCalledWith("u_intensity", 1);+ expect(lastUniform1f).toHaveBeenCalledWith("u_lutIntensity", 1);+ expect(lastUniform1f).toHaveBeenCalledWith("u_exposure", -2);+ expect(lastUniform1f).toHaveBeenCalledWith("u_blur", 0);+ expect(lastUniform1f).toHaveBeenCalledWith("u_bloom", 0.2);+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwahara", 0.2);+ expect(lastUniform1f).toHaveBeenCalledWith("u_pixelate", 0.3);+ expect(lastUniform1f).toHaveBeenCalledWith("u_ascii", 0);+ expect(lastUniform1f).toHaveBeenCalledWith("u_dither", 0.5);+ });++ it("initializes a zero-start grade when an animated property declares future state", () => {+ const video = makeDrawableVideo();+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({+ intensity: 0,+ adjust: { exposure: 0.5 },+ effects: { kuwahara: 0 },+ }),+ );+ video.style.setProperty("--hf-color-grading-intensity", "0");+ video.style.setProperty("--hf-color-grading-kuwahara", "0");+ document.body.appendChild(video);++ runtime = createColorGradingRuntime();++ expect(getContextSpy).toHaveBeenCalledTimes(1);+ if (!lastUniform1f) throw new Error("Expected WebGL uniform calls");+ expect(lastUniform1f).toHaveBeenCalledWith("u_intensity", 0);+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwahara", 0);+ expect(texImage2DCalls.some((args) => args.includes(0x8d61))).toBe(true);++ video.style.setProperty("--hf-color-grading-intensity", "1");+ video.style.setProperty("--hf-color-grading-kuwahara", "1");+ lastUniform1f.mockClear();+ runtime.redraw();++ expect(lastUniform1f).toHaveBeenCalledWith("u_intensity", 1);+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwahara", 1);+ });++ it("redraws animated still images from the transport tick", () => {+ const image = makeDrawableImage();+ document.body.appendChild(image);+ runtime = createColorGradingRuntime();+ image.style.setProperty("--hf-color-grading-blur", "0.7");+ lastUniform1f?.mockClear();++ expect(runtime.redrawAnimated()).toBe(1);+ expect(lastUniform1f).toHaveBeenCalledWith("u_blur", 0.7);+ });++ it("redraws animated held video frames without duplicating active video draws", () => {+ const video = makeDrawableVideo();+ video.style.setProperty("--hf-color-grading-blur", "0.1");+ startRuntimeWithVideo(video);+ Object.defineProperty(video, "paused", { value: false, configurable: true });+ Object.defineProperty(video, "ended", { value: false, configurable: true });++ expect(runtime?.redrawAnimated()).toBe(0);++ Object.defineProperty(video, "paused", { value: true, configurable: true });+ Object.defineProperty(video, "ended", { value: true, configurable: true });+ video.style.setProperty("--hf-color-grading-blur", "0.8");+ lastUniform1f?.mockClear();++ expect(runtime?.redrawAnimated()).toBe(1);+ expect(lastUniform1f).toHaveBeenCalledWith("u_blur", 0.8);+ });+it("keeps the last shader frame visible while a video seek is waiting for a drawable frame", () => {const { video, canvas } = startRuntimeWithVideo();@@ -373,6 +727,45 @@ describe("createColorGradingRuntime", () => {expect(canvas.style.opacity).toBe("0.75");});+ it("allows a drawable producer render frame to initialize hidden source grading", () => {+ const video = makeDrawableVideo();+ video.style.display = "none";+ document.body.appendChild(video);++ const frame = document.createElement("img");+ frame.id = "__render_frame_hero-video__";+ frame.className = "__render_frame__";+ frame.style.visibility = "visible";+ Object.defineProperty(frame, "complete", { value: true, configurable: true });+ Object.defineProperty(frame, "naturalWidth", { value: 640, configurable: true });+ Object.defineProperty(frame, "naturalHeight", { value: 360, configurable: true });+ video.after(frame);++ runtime = createColorGradingRuntime();++ expect(getContextSpy).toHaveBeenCalledTimes(1);+ expect(document.querySelector("[data-hf-color-grading-canvas]")).not.toBeNull();+ });++ it("does not recreate an inactive clip from its hidden producer frame", () => {+ const { video, canvas } = startRuntimeWithVideo();+ const frame = document.createElement("img");+ frame.id = "__render_frame_hero-video__";+ frame.className = "__render_frame__";+ frame.style.visibility = "hidden";+ Object.defineProperty(frame, "complete", { value: true, configurable: true });+ Object.defineProperty(frame, "naturalWidth", { value: 640, configurable: true });+ Object.defineProperty(frame, "naturalHeight", { value: 360, configurable: true });+ video.parentNode?.insertBefore(frame, canvas);++ video.style.visibility = "hidden";+ expect(runtime.setSourceVisibility(video, false)).toBe(true);+ runtime.refresh();+ expect(canvas.isConnected).toBe(false);+ expect(getContextSpy).toHaveBeenCalledTimes(1);+ expect(video.hasAttribute("data-hf-color-grading-source-hidden")).toBe(false);+ });+it("moves the canvas above producer render-frame images before capture", () => {const video = makeDrawableVideo();Object.defineProperty(video, "readyState", {@@ -427,20 +820,82 @@ describe("createColorGradingRuntime", () => {it("passes finishing detail uniforms into the shader", () => {const video = makeDrawableVideo();+ const details = {+ vignette: 0.4,+ vignetteMidpoint: 0.35,+ vignetteRoundness: -0.25,+ vignetteFeather: 0.8,+ grain: 0.2,+ grainSize: 0.7,+ grainRoughness: 0.3,+ };+ const effects = {+ blur: 0.3,+ pixelate: 0.1,+ chromaBleed: 0.25,+ tapeDamage: 0.35,+ tapeTracking: 0.45,+ tapeNoise: 0.55,+ tapeSpeed: 0.65,+ filmArtifacts: 0.45,+ halftone: 0.55,+ halftoneSize: 0.65,+ twoInkPrint: 0.75,+ twoInkPrintSize: 0.85,+ ascii: 0.6,+ asciiSize: 0.4,+ asciiInvert: 1,+ dither: 0.7,+ ditherSize: 0.3,+ asciiStyle: 4,+ asciiColor: 1,+ asciiRotation: 1,+ monoScreen: 0.2,+ monoScreenSize: 0.3,+ monoScreenAngle: 0.4,+ monoScreenSpread: 0.5,+ monoScreenShape: 3,+ monoScreenInvert: 1,+ scanlines: 0.25,+ scanlineCount: 0.35,+ scanlineSoftness: 0.45,+ chromaticAberration: 0.3,+ chromaticAngle: 0.4,+ crtCurvature: 0.2,+ digitalGlitch: 0.35,+ digitalGlitchColorSplit: 0.4,+ digitalGlitchLineTear: 0.45,+ digitalGlitchPixelate: 0.5,+ digitalGlitchBlockAmount: 0.55,+ digitalGlitchBlockDisplacement: 0.65,+ digitalGlitchBlockOpacity: 0.15,+ digitalGlitchSpeed: 0.75,+ engraving: 0.8,+ engravingSpacing: 0.41,+ engravingMinThickness: 0.2,+ engravingMaxThickness: 0.46,+ engravingAngle: 0.25,+ engravingContrast: 0.47,+ engravingSharpness: 0.59,+ engravingWave: 0.2,+ engravingWaveFrequency: 0.22,+ crosshatch: 0.85,+ crosshatchSpacing: 0.28,+ crosshatchThickness: 0.25,+ crosshatchAngle: 0.25,+ crosshatchContrast: 0.33,+ crosshatchEdges: 0.5,+ crosshatchLineWeight: 0.15,+ crosshatchWave: 0.33,+ crosshatchWaveFrequency: 0.22,+ };video.setAttribute(HF_COLOR_GRADING_ATTR,serializeHfColorGrading({adjust: { vibrance: 0.35 },- details: {- vignette: 0.4,- vignetteMidpoint: 0.35,- vignetteRoundness: -0.25,- vignetteFeather: 0.8,- grain: 0.2,- grainSize: 0.7,- grainRoughness: 0.3,- },- effects: { blur: 0.3, pixelate: 0.1 },+ details,+ effects,+ palette: ["#080717", "#3c185f", "#d9339f", "#ff6b66"],}),);document.body.appendChild(video);@@ -448,17 +903,192 @@ describe("createColorGradingRuntime", () => {runtime = createColorGradingRuntime();if (!lastUniform1f) throw new Error("Expected WebGL uniform calls");- expect(lastUniform1f).toHaveBeenCalledWith("u_vibrance", 0.35);- expect(lastUniform1f).toHaveBeenCalledWith("u_vignette", 0.4);- expect(lastUniform1f).toHaveBeenCalledWith("u_vignetteMidpoint", 0.35);- expect(lastUniform1f).toHaveBeenCalledWith("u_vignetteRoundness", -0.25);- expect(lastUniform1f).toHaveBeenCalledWith("u_vignetteFeather", 0.8);- expect(lastUniform1f).toHaveBeenCalledWith("u_grain", 0.2);- expect(lastUniform1f).toHaveBeenCalledWith("u_grainSize", 0.7);- expect(lastUniform1f).toHaveBeenCalledWith("u_grainRoughness", 0.3);+ for (const [key, value] of Object.entries({ vibrance: 0.35, ...details, ...effects })) {+ expect(lastUniform1f).toHaveBeenCalledWith(`u_${key}`, value);+ }expect(lastUniform1f).toHaveBeenCalledWith("u_grainSeed", expect.any(Number));- expect(lastUniform1f).toHaveBeenCalledWith("u_blur", 0.3);- expect(lastUniform1f).toHaveBeenCalledWith("u_pixelate", 0.1);+ expect(lastUniform1f).toHaveBeenCalledWith("u_paletteSize", 4);+ if (!lastUniform3f) throw new Error("Expected WebGL palette uniform calls");+ expect(lastUniform3f).toHaveBeenCalledWith("u_palette0", 8 / 255, 7 / 255, 23 / 255);+ expect(lastUniform3f).toHaveBeenCalledWith("u_palette3", 1, 107 / 255, 102 / 255);++ const fragment = lastShaderSources.find((source) => source.includes("sampleMedia"));+ expect(fragment).toContain("float centerLuma = lumaOf(base.rgb);");+ expect(fragment).toContain("vec3(centerLuma) + blurredChroma");+ expect(fragment).toContain("float headSwitch");+ expect(fragment).toContain("float tapeTrackingBand");+ expect(fragment).toContain("float tapeTime = u_effectTime");+ expect(fragment).toContain("float tapeFrame = floor(tapeTime * 60.0);");+ expect(fragment).not.toContain(+ "tapeTrackingBand(float y, float center, float width, float phase)",+ );+ expect(fragment).toContain("float lineJitter = (digitalHash");+ expect(fragment).toContain("float dustMask");+ expect(fragment).toContain("float screenDot");+ expect(fragment).toContain("vec3 applyHalftone");+ expect(fragment).toContain("vec3 applyTwoInkPrint");+ expect(fragment).toContain("float standardAsciiSample");+ expect(fragment).toContain("float bayer4");+ expect(fragment).toContain("vec3 applyAscii");+ expect(fragment).toContain("vec3 applyDither");+ expect(fragment).toContain("vec3 applyMonoScreen");+ expect(fragment).toContain("vec2 applyCrtWarp");+ expect(fragment).toContain("vec4 sampleChromaticMedia");+ expect(fragment).toContain("vec3 applyScanlines");+ expect(fragment).toContain("vec3 applyDigitalGlitch");+ expect(fragment).toContain("vec3 applyEngraving");+ expect(fragment).toContain("vec3 applyCrosshatch");+ expect(fragment).toContain("float crosshatchEdge");+ expect(fragment).toContain("vec3 applyCrosshatch(vec2 uv");+ expect(fragment).toContain("crosshatchEdge(uv)");+ expect(fragment).not.toContain("crosshatchEdge(v_uv)");+ expect(fragment).toContain("vec2 texel = 1.0 / max(u_resolution * u_uvScale, vec2(1.0));");+ expect(fragment).toContain("float baseAngle = -clamp(u_crosshatchAngle, 0.0, 1.0) * PI;");+ expect(fragment).toContain("float variation = mix(1.0, 0.5 + digitalHash");+ expect(fragment).toContain("baseAngle + PI * 0.5");+ expect(fragment).toContain("baseAngle + PI * 0.25");+ expect(fragment).toContain("baseAngle - PI * 0.25");+ expect(fragment).toContain("asciiStyleSample(floor(u_asciiStyle + 0.5)");+ expect(fragment).toContain("float cellHeight = mix(4.0, 80.0");+ expect(fragment).toContain("vec2 asciiEdgeDirection");+ expect(fragment).toContain("vec3 background = paletteColor(0.0);");+ expect(fragment).not.toContain("grainHash(cell + vec2(17.0, 43.0))");+ expect(fragment).toContain("sampleColor = sampleChromaticMedia(uv, sampleColor);");+ expect(fragment).toContain("sampleColor.rgb = applyDigitalGlitch(uv, sampleColor.rgb);");+ expect(fragment).toContain("vec3 sampleDigitalSplit");+ expect(fragment).toContain("float digitalHash(vec2 p)");+ expect(fragment).toContain("float direction = digitalHash");+ expect(fragment).toContain("float randomA = digitalHash");+ expect(fragment).toContain("float colorSplit = clamp(u_digitalGlitchColorSplit");+ expect(fragment).toContain("float pixelate = clamp(u_digitalGlitchPixelate");+ expect(fragment).toContain("blockDisplacement > 0.0 && blockOpacity > 0.0");+ expect(fragment).toContain("displaced = mix(uv, displaced, blockOpacity);");+ expect(fragment).not.toContain("vec3 electronicBlock");+ expect(fragment).toContain("color = applyMonoScreen");+ expect(fragment).toContain("color = applyEngraving");+ expect(fragment).toContain("color = applyCrosshatch");+ expect(fragment).toContain("color = applyScanlines");+ expect(fragment).toContain("float curvature = clamp(u_crtCurvature, 0.0, 1.0) * 0.5;");+ expect(fragment).toContain("float dist = dot(centered, centered);");+ expect(fragment).toContain("centered *= 1.0 + curvature * dist;");+ expect(fragment).toContain("float wave = 0.5 + 0.5 * sin(v_uv.y * count * PI);");+ expect(fragment).toContain("float line = mix(1.0 - wave, pow(1.0 - wave, 2.2), softness);");+ expect(fragment).not.toContain("float hardLine = step(0.78, wave);");+ expect(fragment.indexOf("float vignettePower")).toBeGreaterThan(+ fragment.indexOf("color = applyScanlines"),+ );+ expect(fragment).toContain("amount * 0.02");+ expect(fragment).not.toContain("mix(center.rgb, split, amount)");+ });++ it("renders Kuwahara through bounded moment passes before the main shader", () => {+ const video = makeDrawableVideo();+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({+ effects: {+ kuwahara: 0.8,+ kuwaharaRadius: 0.25,+ kuwaharaSharpness: 0.4,+ kuwaharaSaturation: 0.6,+ },+ }),+ );+ document.body.appendChild(video);++ runtime = createColorGradingRuntime();++ if (!lastUniform1f) throw new Error("Expected WebGL uniform calls");+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwahara", 0.8);+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwaharaRadius", 0.25);+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwaharaSharpness", 0.4);+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwaharaSaturation", 0.6);+ expect(lastShaderSources.some((source) => source.includes("u_kuwaharaMoments"))).toBe(true);+ expect(+ lastShaderSources.some((source) => source.includes("meanSquare - dot(mean, mean)")),+ ).toBe(true);+ expect(texImage2DCalls.some((args) => args.includes(0x8d61))).toBe(true);+ });++ it("falls back to the untreated shader output when half-float targets are unavailable", () => {+ getContextSpy.mockImplementation((type: string) =>+ type === "webgl" ? createMockWebGl({ halfFloatSupported: false }) : null,+ );+ const video = makeDrawableVideo();+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({ effects: { kuwahara: 1 } }),+ );+ const { canvas } = startRuntimeWithVideo(video);++ if (!lastUniform1f) throw new Error("Expected WebGL uniform calls");+ expect(lastUniform1f).toHaveBeenCalledWith("u_kuwaharaReady", 0);+ expect(canvas.style.display).toBe("block");+ expect(runtime?.getStatus(video)).toEqual({+ state: "unavailable",+ message: "Kuwahara requires half-float framebuffer support",+ });+ expect(texImage2DCalls.some((args) => args.includes(0x8d61))).toBe(false);+ });++ it("releases lazy Kuwahara GPU resources when attributed media becomes inactive", () => {+ const video = makeDrawableVideo();+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({ effects: { kuwahara: 1 } }),+ );+ startRuntimeWithVideo(video);+ const gl = getContextSpy.mock.results[0]?.value as WebGLRenderingContext;++ expect(runtime?.setSourceVisibility(video, false)).toBe(true);+ expect(gl.deleteFramebuffer).toHaveBeenCalledTimes(2);+ expect(gl.deleteTexture).toHaveBeenCalledTimes(2);+ expect(gl.deleteProgram).toHaveBeenCalledTimes(2);+ expect(loseContextCalls).toBe(0);+ expect(document.querySelector("[data-hf-color-grading-canvas]")).toBeNull();+ });++ it("releases pooled WebGL contexts when the runtime is destroyed", () => {+ const { video } = startRuntimeWithVideo();++ expect(runtime?.setSourceVisibility(video, false)).toBe(true);+ expect(loseContextCalls).toBe(0);++ runtime?.destroy();+ runtime = null;+ expect(loseContextCalls).toBe(1);+ });++ it("drives temporal shader effects from canonical composition time", () => {+ let playerTime = 2.25;+ Object.defineProperty(window, "__player", {+ value: { getTime: () => playerTime },+ configurable: true,+ });+ const video = makeDrawableVideo();+ Object.defineProperty(video, "currentTime", { value: 19.5, configurable: true });+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({ effects: { digitalGlitch: 1 } }),+ );+ document.body.appendChild(video);++ runtime = createColorGradingRuntime();++ if (!lastUniform1f) throw new Error("Expected WebGL uniform calls");+ expect(lastUniform1f).toHaveBeenCalledWith("u_effectTime", 2.25);+ const firstGrainSeed = lastUniform1f.mock.calls.findLast(+ ([uniform]) => uniform === "u_grainSeed",+ )?.[1] as number | undefined;+ playerTime = 2.5;+ runtime.redraw();+ const secondGrainSeed = lastUniform1f.mock.calls.findLast(+ ([uniform]) => uniform === "u_grainSeed",+ )?.[1] as number | undefined;+ expect(firstGrainSeed).toBeTypeOf("number");+ expect(secondGrainSeed).toBe((firstGrainSeed ?? 0) + 15);+ const fragment = lastShaderSources.find((source) => source.includes("sampleMedia"));+ expect(fragment).toContain("float time = u_effectTime * speed;");});it("uses the effected media sample as the graded shader input", () => {@@ -480,7 +1110,11 @@ describe("createColorGradingRuntime", () => {expect(fragment).toContain("float grainPixelSize");expect(fragment).toContain("float blackPoint = clamp(u_blacks * 0.18");expect(fragment).toContain("float whitePoint = clamp(1.0 - u_whites * 0.18");- expect(fragment).toContain("vec3 color = sampleColor.rgb * pow(2.0, u_exposure);");+ expect(fragment).toContain("vec3 applyPrimaryGrade(vec3 color)");+ expect(fragment).toContain(+ "vec3 color = mix(sampleColor.rgb, applyPrimaryGrade(sampleColor.rgb), u_intensity);",+ );+ expect(fragment).not.toContain("mix(original, color, u_intensity)");expect(fragment).not.toContain("sampleSoft");const blurFragment = lastShaderSources.find((source) =>source.includes("uniform vec2 u_direction;"),@@ -505,6 +1139,47 @@ describe("createColorGradingRuntime", () => {).toBe(true);});+ it("renders article bloom with thresholded half-resolution Gaussian passes", () => {+ const video = makeDrawableVideo();+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({ effects: { bloom: 0.5, bloomRadius: 8 } }),+ );+ document.body.appendChild(video);++ runtime = createColorGradingRuntime();++ expect(lastUniform1f).toHaveBeenCalledWith("u_bloom", 0.5);+ expect(lastUniform1f).toHaveBeenCalledWith("u_bloomReady", 1);+ expect(lastUniform1f).toHaveBeenCalledWith("u_radius", 4);+ expect(texImage2DCalls.some((args) => args[3] === 320 && args[4] === 180)).toBe(true);+ const bloomFragment = lastShaderSources.find((source) => source.includes("u_bloomPass"));+ expect(bloomFragment).toContain("vec3(0.299, 0.587, 0.114)");+ expect(bloomFragment).toContain("0.227027");+ expect(bloomFragment).toContain("0.1945946");+ expect(bloomFragment).toContain("0.016216");+ });++ it("releases the lazy bloom output used only when blur and bloom coexist", () => {+ const video = makeDrawableVideo();+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({+ effects: { blur: 0.4, bloom: 0.5, bloomRadius: 8 },+ }),+ );+ startRuntimeWithVideo(video);+ const gl = getContextSpy.mock.results[0]?.value as WebGLRenderingContext;++ expect(texImage2DCalls.some((args) => args[3] === 640 && args[4] === 360)).toBe(true);+ expect(texImage2DCalls.some((args) => args[3] === 320 && args[4] === 180)).toBe(true);++ expect(runtime?.setSourceVisibility(video, false)).toBe(true);+ expect(gl.deleteFramebuffer).toHaveBeenCalledTimes(3);+ expect(gl.deleteTexture).toHaveBeenCalledTimes(3);+ expect(gl.deleteProgram).toHaveBeenCalledTimes(1);+ });+it("loads cube LUTs and enables LUT uniforms", async () => {const fetchMock = stubCubeLutFetch();const origin = window.location.origin;@@ -532,6 +1207,40 @@ describe("createColorGradingRuntime", () => {expect(runtime.getStatus("#hero-video").message).toBe("Shader + LUT active");});+ it("waits for active LUTs before deterministic capture", async () => {+ let releaseFetch: (() => void) | undefined;+ vi.stubGlobal(+ "fetch",+ vi.fn(+ () =>+ new Promise<{ ok: boolean; status: number; text: () => Promise<string> }>((resolve) => {+ releaseFetch = () =>+ resolve({ ok: true, status: 200, text: () => Promise.resolve(IDENTITY_2) });+ }),+ ),+ );+ const video = makeDrawableVideo();+ video.setAttribute(+ HF_COLOR_GRADING_ATTR,+ serializeHfColorGrading({ lut: { src: "assets/luts/identity.cube", intensity: 1 } }),+ );+ document.body.appendChild(video);+ runtime = createColorGradingRuntime();++ expect(runtime.getStatus(video)).toEqual({ state: "pending", message: "Loading LUT" });+ const ready = runtime.waitForActiveLuts();+ let settled = false;+ void ready.then(() => {+ settled = true;+ });+ await Promise.resolve();+ expect(settled).toBe(false);++ releaseFetch?.();+ expect(await ready).toBe(1);+ expect(runtime.getStatus(video).message).toBe("Shader + LUT active");+ });+it("bounds the runtime LUT cache", async () => {const fetchMock = stubCubeLutFetch();const origin = window.location.origin;@@ -644,15 +1353,16 @@ describe("installAuthoredOpacityCapture", () => {el.remove();});- it("stamps an already-inserted element the moment it GAINS grading at runtime", async () => {+ it("stamps ungraded media before a live Studio grade can hide it", async () => {installAuthoredOpacityCapture();const el = document.createElement("img");el.style.opacity = "0.9";document.body.appendChild(el);await Promise.resolve();- expect(el.hasAttribute("data-hf-authored-opacity")).toBe(false);+ expect(el.getAttribute("data-hf-authored-opacity")).toBe("0.9");- // Studio applies a preset to a previously ungraded element — no re-insert.+ // The live runtime hides the source before Studio persists the attribute.+ el.style.setProperty("opacity", "0", "important");el.setAttribute(HF_COLOR_GRADING_ATTR, serializeHfColorGrading({ adjust: { exposure: 0.5 } }));await Promise.resolve();expect(el.getAttribute("data-hf-authored-opacity")).toBe("0.9");diff --git a/packages/core/src/runtime/colorGrading.ts b/packages/core/src/runtime/colorGrading.tsindex 4fd00faf0b..09bdbdc2ab 100644--- a/packages/core/src/runtime/colorGrading.ts+++ b/packages/core/src/runtime/colorGrading.ts@@ -1,9 +1,17 @@import {+ HF_COLOR_GRADING_ADJUST_KEYS,+ HF_COLOR_GRADING_ANIMATABLE_PROPERTIES,HF_COLOR_GRADING_ATTR,HF_COLOR_GRADING_CANVAS_ID_PREFIX,+ HF_COLOR_GRADING_DETAIL_KEYS,+ HF_COLOR_GRADING_EFFECT_KEYS,isHfColorGradingActive,normalizeHfColorGrading,normalizeHfColorGradingWithVariables,+ type HfColorGradingAdjustKey,+ type HfColorGradingAnimatablePath,+ type HfColorGradingDetailKey,+ type HfColorGradingEffectKey,type HfColorGradingTarget,type NormalizedHfColorGrading,COLOR_GRADING_SOURCE_HIDDEN_ATTR,@@ -39,6 +47,8 @@ interface VideoFrameCallbackHost {cancelVideoFrameCallback?: (handle: number) => void;}+type FloatUniformBinding<K extends string> = readonly [key: K, location: WebGLUniformLocation];+interface ProgramInfo {program: WebGLProgram;texture: WebGLTexture;@@ -47,37 +57,33 @@ interface ProgramInfo {position: number;source: WebGLUniformLocation | null;blurSource: WebGLUniformLocation | null;+ bloomSource: WebGLUniformLocation | null;+ kuwaharaSource: WebGLUniformLocation | null;lut: WebGLUniformLocation | null;resolution: WebGLUniformLocation | null;uvScale: WebGLUniformLocation | null;uvOffset: WebGLUniformLocation | null;blurReady: WebGLUniformLocation | null;+ bloomReady: WebGLUniformLocation | null;+ kuwaharaReady: WebGLUniformLocation | null;lutEnabled: WebGLUniformLocation | null;lutSize: WebGLUniformLocation | null;lutTextureSize: WebGLUniformLocation | null;lutDomainMin: WebGLUniformLocation | null;lutDomainMax: WebGLUniformLocation | null;lutIntensity: WebGLUniformLocation | null;- exposure: WebGLUniformLocation | null;- contrast: WebGLUniformLocation | null;- highlights: WebGLUniformLocation | null;- shadows: WebGLUniformLocation | null;- whites: WebGLUniformLocation | null;- blacks: WebGLUniformLocation | null;- temperature: WebGLUniformLocation | null;- tint: WebGLUniformLocation | null;- vibrance: WebGLUniformLocation | null;- saturation: WebGLUniformLocation | null;- vignette: WebGLUniformLocation | null;- vignetteMidpoint: WebGLUniformLocation | null;- vignetteRoundness: WebGLUniformLocation | null;- vignetteFeather: WebGLUniformLocation | null;- grain: WebGLUniformLocation | null;- grainSize: WebGLUniformLocation | null;- grainRoughness: WebGLUniformLocation | null;+ adjustUniforms: readonly FloatUniformBinding<HfColorGradingAdjustKey>[];+ detailUniforms: readonly FloatUniformBinding<HfColorGradingDetailKey>[];+ effectUniforms: readonly FloatUniformBinding<HfColorGradingEffectKey>[];grainSeed: WebGLUniformLocation | null;- blur: WebGLUniformLocation | null;- pixelate: WebGLUniformLocation | null;+ effectTime: WebGLUniformLocation | null;+ paletteSize: WebGLUniformLocation | null;+ palette0: WebGLUniformLocation | null;+ palette1: WebGLUniformLocation | null;+ palette2: WebGLUniformLocation | null;+ palette3: WebGLUniformLocation | null;+ palette4: WebGLUniformLocation | null;+ palette5: WebGLUniformLocation | null;intensity: WebGLUniformLocation | null;compareEnabled: WebGLUniformLocation | null;comparePosition: WebGLUniformLocation | null;@@ -93,11 +99,14 @@ interface BlurProgramInfo {resolution: WebGLUniformLocation | null;direction: WebGLUniformLocation | null;radius: WebGLUniformLocation | null;+ bloomPass: WebGLUniformLocation | null;+ threshold: WebGLUniformLocation | null;}interface RenderTarget {texture: WebGLTexture;framebuffer: WebGLFramebuffer;+ type: number;width: number;height: number;}@@ -106,6 +115,39 @@ interface EffectTargets {blurProgram: BlurProgramInfo;scratch: RenderTarget;blur: RenderTarget;+ bloom: RenderTarget | null;+}++interface KuwaharaHorizontalProgramInfo {+ program: WebGLProgram;+ quad: WebGLBuffer;+ position: number;+ source: WebGLUniformLocation | null;+ blurSource: WebGLUniformLocation | null;+ texel: WebGLUniformLocation | null;+ uvScale: WebGLUniformLocation | null;+ uvOffset: WebGLUniformLocation | null;+ blurReady: WebGLUniformLocation | null;+ blur: WebGLUniformLocation | null;+ radius: WebGLUniformLocation | null;+}++interface KuwaharaResolveProgramInfo {+ program: WebGLProgram;+ quad: WebGLBuffer;+ position: number;+ moments: WebGLUniformLocation | null;+ texel: WebGLUniformLocation | null;+ radius: WebGLUniformLocation | null;+ sharpness: WebGLUniformLocation | null;+ saturation: WebGLUniformLocation | null;+}++interface KuwaharaTargets {+ horizontalProgram: KuwaharaHorizontalProgramInfo;+ resolveProgram: KuwaharaResolveProgramInfo;+ moments: RenderTarget;+ output: RenderTarget;}interface RuntimeColorGradingCompareState {@@ -115,19 +157,26 @@ interface RuntimeColorGradingCompareState {lineWidth: number;}-interface ColorGradingEntry {- element: ColorGradingMediaElement;- canvas: HTMLCanvasElement;+interface EffectRenderState {gl: WebGLRenderingContext;program: ProgramInfo;+ effectTargets: EffectTargets | null;+ kuwaharaTargets: KuwaharaTargets | null;+ effectError: string | null;+}++interface ColorGradingRenderer extends EffectRenderState {+ canvas: HTMLCanvasElement;+}++interface ColorGradingEntry extends ColorGradingRenderer {+ element: ColorGradingMediaElement;grading: NormalizedHfColorGrading;compare: RuntimeColorGradingCompareState;lut: RuntimeLutTexture | null;lutLoadingSrc: string | null;lutError: string | null;drawError: string | null;- effectTargets: EffectTargets | null;- effectError: string | null;source: EntrySource;animationFrame: number | null;videoFrameHandle: number | null;@@ -146,9 +195,26 @@ interface ColorGradingEntry {destroyed: boolean;}+interface ColorGradingPreviewRenderer extends ColorGradingRenderer {+ lut: RuntimeLutTexture | null;+}++export interface RuntimeColorGradingPreviewCandidate {+ id: string;+ grading: unknown;+}++export interface RuntimeColorGradingPreviewBatch {+ width: number;+ height: number;+ images: Array<{ id: string; dataUrl: string | null; error?: string }>;+}+export interface RuntimeColorGradingApi {refresh: () => number;redraw: () => number;+ redrawAnimated: () => number;+ waitForActiveLuts: () => Promise<number>;setGrading: (target: HfColorGradingTarget | string | null | undefined,rawGrading: unknown,@@ -161,6 +227,14 @@ export interface RuntimeColorGradingApi {getStatus: (target: HfColorGradingTarget | string | null | undefined,) => RuntimeColorGradingStatus;+ renderPreviews: (+ target: HfColorGradingTarget | string | null | undefined,+ candidates: readonly RuntimeColorGradingPreviewCandidate[],+ options?: { maxDimension?: number; useMediaTime?: boolean },+ ) => Promise<RuntimeColorGradingPreviewBatch | null>;+ startPreviewPlayback: (+ target: HfColorGradingTarget | string | null | undefined,+ ) => (() => void) | null;destroy: () => void;}@@ -172,6 +246,9 @@ export type RuntimeColorGradingStatus =| { state: "unavailable"; message: string };type WindowWithColorGrading = Window & {+ __player?: {+ getTime?: () => number;+ };__hf?: {colorGrading?: RuntimeColorGradingApi;};@@ -200,27 +277,7 @@ const LUT_CACHE = new Map<string, LutCacheEntry>();const COLOR_GRADING_CANVAS_ATTR = "data-hf-color-grading-canvas";const COLOR_GRADING_CANVAS_CLASS = "__hf_color_grading_canvas__";-/**- * Capture each color-graded element's AUTHORED inline opacity before any- * animation engine can mutate it.- *- * The grading engine hides its source elements with `opacity: 0 !important`- * and mirrors their pixels onto a canvas — so at runtime, a graded element's- * inline/computed opacity no longer represents authored state. Everything that- * later re-reads element state (GSAP from()-tween re-initialization after an- * invalidate or a studio soft reload, restoring the source when grading is- * removed, lint/selection tooling) needs the authored value, and by then it is- * unrecoverable from the DOM. Stamp it onto the element as- * `data-hf-authored-opacity` (empty string = no authored inline opacity).- *- * Must be installed at runtime-bundle evaluation, while the document is still- * parsing: the runtime `<script>` sits in `<head>`, and the HTML parser- * performs a microtask checkpoint before executing each parser-inserted- * script, so the observer stamps every composition element before the- * composition's own inline animation script runs. The observer stays alive so- * late insertions (inlined sub-compositions) are stamped at insert time, and- * the has-attribute guard makes re-inserted (already-stamped) elements a no-op.- */+/** Captures authored media opacity before animation or grading can mutate it. */export function installAuthoredOpacityCapture(): void {if (typeof MutationObserver === "undefined" || typeof document === "undefined") return;const root = document.documentElement;@@ -232,38 +289,31 @@ export function installAuthoredOpacityCapture(): void {};const scan = (node: Node): void => {if (!(node instanceof Element)) return;- if (node.hasAttribute(HF_COLOR_GRADING_ATTR)) stamp(node);- for (const el of node.querySelectorAll(`[${HF_COLOR_GRADING_ATTR}]`)) stamp(el);+ if (node.matches("video, img")) stamp(node);+ for (const el of node.querySelectorAll("video, img")) stamp(el);};scan(root);new MutationObserver((mutations) => {for (const mutation of mutations) {for (const node of mutation.addedNodes) scan(node);- // An element can also GAIN grading at runtime (studio applies a preset to- // a previously ungraded element). Stamp at that moment — strictly earlier- // than the engine's hide, so the captured value can never be worse than- // the hide-time fallback, and after a soft reload's authored restore it- // IS the authored value. stamp() is idempotent: an existing stamp wins.- if (mutation.type === "attributes" && mutation.target instanceof Element) {- if (mutation.target.hasAttribute(HF_COLOR_GRADING_ATTR)) stamp(mutation.target);- }}}).observe(root, {childList: true,subtree: true,- attributes: true,- attributeFilter: [HF_COLOR_GRADING_ATTR],});}// Map insertion order gives us simple FIFO eviction for authoring sessions that cycle LUTs.const MAX_LUT_CACHE_ENTRIES = 16;+const MAX_IDLE_COLOR_GRADING_RENDERERS = 4;const DEFAULT_COMPARE: RuntimeColorGradingCompareState = {enabled: false,position: 0.5,softness: 0,lineWidth: 2,};+const DEFAULT_EFFECT_PALETTE = ["#000000", "#ffffff"] as const;+const DEFAULT_ART_PALETTE = ["#1a1a1a", "#f5f5dc"] as const;function readColorGradingAttribute(element: Element): NormalizedHfColorGrading | null {const raw = element.getAttribute(HF_COLOR_GRADING_ATTR);@@ -289,11 +339,15 @@ const FRAGMENT_SHADER = ["varying vec2 v_uv;","uniform sampler2D u_source;","uniform sampler2D u_blurSource;",+ "uniform sampler2D u_bloomSource;",+ "uniform sampler2D u_kuwaharaSource;","uniform sampler2D u_lut;","uniform vec2 u_resolution;","uniform vec2 u_uvScale;","uniform vec2 u_uvOffset;","uniform float u_blurReady;",+ "uniform float u_bloomReady;",+ "uniform float u_kuwaharaReady;","uniform float u_lutEnabled;","uniform float u_lutSize;","uniform vec2 u_lutTextureSize;",@@ -318,19 +372,121 @@ const FRAGMENT_SHADER = ["uniform float u_grainSize;","uniform float u_grainRoughness;","uniform float u_grainSeed;",+ "uniform float u_effectTime;","uniform float u_blur;",+ "uniform float u_bloom;",+ "uniform float u_kuwahara;","uniform float u_pixelate;",+ "uniform float u_chromaBleed;",+ "uniform float u_tapeDamage;",+ "uniform float u_tapeTracking;",+ "uniform float u_tapeNoise;",+ "uniform float u_tapeSpeed;",+ "uniform float u_filmArtifacts;",+ "uniform float u_halftone;",+ "uniform float u_halftoneSize;",+ "uniform float u_twoInkPrint;",+ "uniform float u_twoInkPrintSize;",+ "uniform float u_ascii;",+ "uniform float u_asciiSize;",+ "uniform float u_asciiInvert;",+ "uniform float u_asciiStyle;",+ "uniform float u_asciiColor;",+ "uniform float u_asciiRotation;",+ "uniform float u_dither;",+ "uniform float u_ditherSize;",+ "uniform float u_monoScreen;",+ "uniform float u_monoScreenSize;",+ "uniform float u_monoScreenAngle;",+ "uniform float u_monoScreenSpread;",+ "uniform float u_monoScreenShape;",+ "uniform float u_monoScreenInvert;",+ "uniform float u_scanlines;",+ "uniform float u_scanlineCount;",+ "uniform float u_scanlineSoftness;",+ "uniform float u_chromaticAberration;",+ "uniform float u_chromaticAngle;",+ "uniform float u_crtCurvature;",+ "uniform float u_digitalGlitch;",+ "uniform float u_digitalGlitchColorSplit;",+ "uniform float u_digitalGlitchLineTear;",+ "uniform float u_digitalGlitchPixelate;",+ "uniform float u_digitalGlitchBlockAmount;",+ "uniform float u_digitalGlitchBlockDisplacement;",+ "uniform float u_digitalGlitchBlockOpacity;",+ "uniform float u_digitalGlitchSpeed;",+ "uniform float u_engraving;",+ "uniform float u_engravingSpacing;",+ "uniform float u_engravingMinThickness;",+ "uniform float u_engravingMaxThickness;",+ "uniform float u_engravingAngle;",+ "uniform float u_engravingContrast;",+ "uniform float u_engravingSharpness;",+ "uniform float u_engravingWave;",+ "uniform float u_engravingWaveFrequency;",+ "uniform float u_crosshatch;",+ "uniform float u_crosshatchSpacing;",+ "uniform float u_crosshatchThickness;",+ "uniform float u_crosshatchAngle;",+ "uniform float u_crosshatchContrast;",+ "uniform float u_crosshatchEdges;",+ "uniform float u_crosshatchLineWeight;",+ "uniform float u_crosshatchWave;",+ "uniform float u_crosshatchWaveFrequency;",+ "uniform float u_paletteSize;",+ "uniform vec3 u_palette0;",+ "uniform vec3 u_palette1;",+ "uniform vec3 u_palette2;",+ "uniform vec3 u_palette3;",+ "uniform vec3 u_palette4;",+ "uniform vec3 u_palette5;","uniform float u_intensity;","uniform float u_compareEnabled;","uniform float u_comparePosition;","uniform float u_compareSoftness;","uniform float u_compareLineWidth;",+ "const float PI = 3.14159265359;","float lumaOf(vec3 c){ return dot(c, vec3(0.2126, 0.7152, 0.0722)); }",+ "float bt601Luma(vec3 c){ return dot(c, vec3(0.299, 0.587, 0.114)); }","float grainHash(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); }",+ "float digitalHash(vec2 p){",+ " vec2 q = mod(floor(p), 251.0);",+ " float x = mod(q.x * q.x * 157.0 + q.x * 89.0, 251.0);",+ " float y = mod(q.y * q.y * 113.0 + q.y * 47.0, 251.0);",+ " float xy = mod(q.x * q.y * 71.0, 251.0);",+ " return mod(x + y + xy + 19.0, 251.0) / 251.0;",+ "}","float colorSaturation(vec3 c){ return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b); }","vec2 clampUv(vec2 uv){ return clamp(uv, vec2(0.0), vec2(1.0)); }",+ "vec2 applyCrtWarp(vec2 uv){",+ " vec2 centered = uv * 2.0 - 1.0;",+ " float curvature = clamp(u_crtCurvature, 0.0, 1.0) * 0.5;",+ " float dist = dot(centered, centered);",+ " centered *= 1.0 + curvature * dist;",+ " return centered * 0.5 + 0.5;",+ "}","vec4 sampleSource(vec2 uv){ return texture2D(u_source, clampUv(uv)); }","vec4 sampleBlur(vec2 uv){ return texture2D(u_blurSource, clampUv(uv)); }",+ "vec3 sampleBloom(vec2 uv){ return texture2D(u_bloomSource, clampUv(uv)).rgb; }",+ "vec3 sampleKuwahara(vec2 uv){",+ " vec2 displayUv = uv * u_uvScale + u_uvOffset;",+ " return texture2D(u_kuwaharaSource, clampUv(displayUv)).rgb;",+ "}",+ "vec4 samplePrepared(vec2 uv){",+ " vec4 base = sampleSource(uv);",+ " float blur = clamp(u_blur, 0.0, 1.0);",+ " if (blur > 0.0 && u_blurReady > 0.5) base = mix(base, sampleBlur(uv), blur);",+ " float kuwahara = clamp(u_kuwahara, 0.0, 1.0);",+ " if (kuwahara > 0.0 && u_kuwaharaReady > 0.5) {",+ " base.rgb = mix(base.rgb, sampleKuwahara(uv), kuwahara);",+ " }",+ " return base;",+ "}",+ "float tapeTrackingBand(float y, float center, float width){",+ " float offset = fract(y - center + 0.5) - 0.5;",+ " float triangle = max(0.0, 1.0 - abs(offset) / max(width, 0.0001));",+ " return triangle * triangle * (3.0 - 2.0 * triangle);",+ "}","vec4 sampleMedia(vec2 uv){"," float pixel = clamp(u_pixelate, 0.0, 1.0);"," vec2 sampleUv = uv;",@@ -339,13 +495,442 @@ const FRAGMENT_SHADER = [" vec2 cells = max(u_resolution / blockSize, vec2(1.0));"," sampleUv = (floor(clamp(uv, vec2(0.0), vec2(0.999999)) * cells) + 0.5) / cells;"," }",- " vec4 base = sampleSource(sampleUv);",- " float blur = clamp(u_blur, 0.0, 1.0);",- " if (blur > 0.0 && u_blurReady > 0.5) {",- " base = mix(base, sampleBlur(sampleUv), blur);",+ " float tapeDamage = clamp(u_tapeDamage, 0.0, 1.0);",+ " float tapeTracking = clamp(u_tapeTracking, 0.0, 1.0);",+ " float tapeNoise = clamp(u_tapeNoise, 0.0, 1.0);",+ " float tapeTime = u_effectTime * mix(0.0, 2.0, clamp(u_tapeSpeed, 0.0, 1.0));",+ " float tapeFrame = floor(tapeTime * 60.0);",+ " float tapeLine = floor(sampleUv.y * u_resolution.y * 0.5);",+ " float lineJitter = (digitalHash(vec2(tapeLine, floor(tapeFrame * 0.5))) - 0.5) * 1.8 * tapeNoise;",+ " float slowWobble = sin(sampleUv.y * 32.0 + tapeTime * 2.6) * 0.55;",+ " float headSwitch = smoothstep(0.88, 1.0, sampleUv.y) * sin(sampleUv.y * 240.0 + tapeTime * 8.0) * 4.0;",+ " float trackingShift = tapeTrackingBand(sampleUv.y, fract(0.08 + tapeTime * 0.083), 0.035);",+ " trackingShift -= tapeTrackingBand(sampleUv.y, fract(0.28 + tapeTime * 0.061), 0.03) * 0.8;",+ " trackingShift += tapeTrackingBand(sampleUv.y, fract(0.5 + tapeTime * 0.047), 0.04) * 0.75;",+ " trackingShift -= tapeTrackingBand(sampleUv.y, fract(0.72 + tapeTime * 0.037), 0.028) * 0.65;",+ " trackingShift += tapeTrackingBand(sampleUv.y, fract(0.89 + tapeTime * 0.029), 0.032) * 0.55;",+ " trackingShift *= tapeTracking * 48.0;",+ " float tapeShift = (lineJitter + slowWobble + headSwitch + trackingShift) * tapeDamage;",+ " float texelX = 1.0 / max(u_resolution.x * max(u_uvScale.x, 0.00001), 1.0);",+ " vec2 tapeUv = sampleUv + vec2(tapeShift * texelX, 0.0);",+ " vec4 base = samplePrepared(tapeUv);",+ " if (tapeDamage > 0.0) {",+ " vec2 lumaStep = vec2(texelX * mix(1.0, 3.5, tapeDamage), 0.0);",+ " vec3 leftTape = samplePrepared(tapeUv - lumaStep).rgb;",+ " vec3 rightTape = samplePrepared(tapeUv + lumaStep).rgb;",+ " float tapeLuma = (bt601Luma(leftTape) + bt601Luma(base.rgb) * 2.0 + bt601Luma(rightTape)) * 0.25;",+ " vec3 centerChroma = base.rgb - vec3(bt601Luma(base.rgb));",+ " vec3 tapeColor = vec3(tapeLuma) + centerChroma;",+ " vec3 ghost = samplePrepared(tapeUv - vec2(texelX * 12.0, 0.0)).rgb;",+ " tapeColor = mix(tapeColor, ghost, 0.045 * tapeDamage);",+ " float fineNoise = digitalHash(floor(gl_FragCoord.xy) + vec2(tapeFrame * 17.0, tapeFrame * 3.0)) - 0.5;",+ " float band = digitalHash(vec2(floor(sampleUv.y * 92.0), floor(tapeFrame / 3.0)));",+ " float dropout = smoothstep(0.985, 1.0, band) * (digitalHash(vec2(floor(sampleUv.x * 18.0), tapeLine)) - 0.5);",+ " tapeColor += (fineNoise * 0.035 + dropout * 0.12) * tapeDamage * tapeNoise;",+ " base.rgb = mix(base.rgb, clamp(tapeColor, 0.0, 1.0), tapeDamage);",+ " }",+ " float chromaBleed = clamp(u_chromaBleed, 0.0, 1.0);",+ " if (chromaBleed > 0.0) {",+ " float radius = mix(1.0, 4.0, chromaBleed);",+ " vec2 stepUv = vec2(texelX * radius, 0.0);",+ " vec3 c0 = base.rgb;",+ " vec3 c1 = samplePrepared(tapeUv - stepUv).rgb;",+ " vec3 c2 = samplePrepared(tapeUv + stepUv).rgb;",+ " vec3 c3 = samplePrepared(tapeUv - stepUv * 2.0).rgb;",+ " vec3 c4 = samplePrepared(tapeUv + stepUv * 2.0).rgb;",+ " float centerLuma = lumaOf(base.rgb);",+ " vec3 blurredChroma = ((c0 - vec3(lumaOf(c0))) * 6.0 + (c1 - vec3(lumaOf(c1))) * 4.0 + (c2 - vec3(lumaOf(c2))) * 4.0 + (c3 - vec3(lumaOf(c3))) + (c4 - vec3(lumaOf(c4)))) / 16.0;",+ " base.rgb = mix(base.rgb, clamp(vec3(centerLuma) + blurredChroma, 0.0, 1.0), chromaBleed);"," }"," return base;","}",+ "vec4 sampleChromaticMedia(vec2 uv, vec4 center){",+ " float amount = clamp(u_chromaticAberration, 0.0, 1.0);",+ " if (amount <= 0.0) return center;",+ " float angle = clamp(u_chromaticAngle, 0.0, 1.0) * PI * 2.0;",+ " vec2 offset = vec2(cos(angle), sin(angle)) * amount * 0.02;",+ " vec4 positive = sampleMedia(uv + offset);",+ " vec4 negative = sampleMedia(uv - offset);",+ " vec3 split = vec3(positive.r, center.g, negative.b);",+ " return vec4(split, center.a);",+ "}",+ "vec3 sampleDigitalSplit(vec2 uv, vec2 block, float time, float amount){",+ " float split = amount * 0.06;",+ " float direction = digitalHash(block * 0.4 + vec2(floor(time * 3.7), floor(time * 5.3)));",+ " vec2 axis = direction > 0.66 ? vec2(1.0, 0.0) : direction > 0.33 ? vec2(0.0, 1.0) : vec2(0.7071);",+ " vec4 center = sampleMedia(uv);",+ " return vec3(sampleMedia(uv + axis * split).r, center.g, sampleMedia(uv - axis * split).b);",+ "}",+ "vec3 applyDigitalGlitch(vec2 uv, vec3 source){",+ " float amount = clamp(u_digitalGlitch, 0.0, 1.0);",+ " if (amount <= 0.0) return source;",+ " float colorSplit = clamp(u_digitalGlitchColorSplit, 0.0, 1.0) * 2.0;",+ " float lineTear = clamp(u_digitalGlitchLineTear, 0.0, 1.0) * 2.0;",+ " float pixelate = clamp(u_digitalGlitchPixelate, 0.0, 1.0) * 2.0;",+ " float blockAmount = clamp(u_digitalGlitchBlockAmount, 0.0, 1.0);",+ " float blockDisplacement = clamp(u_digitalGlitchBlockDisplacement, 0.0, 1.0) * 2.0;",+ " float blockOpacity = clamp(u_digitalGlitchBlockOpacity, 0.0, 1.0);",+ " float speed = clamp(u_digitalGlitchSpeed, 0.0, 1.0) * 2.0;",+ " float time = u_effectTime * speed;",+ " float blockCount = 8.0 + blockAmount * 60.0;",+ " vec2 block = floor(uv * blockCount);",+ " float randomA = digitalHash(block + vec2(floor(time * 7.3), floor(time * 11.1)));",+ " float randomB = digitalHash(block * 0.7 + vec2(17.3 + floor(time * 6.6), 29.1));",+ " float randomC = digitalHash(block + vec2(floor(time * 5.7) * 13.0, 41.0));",+ " float randomD = digitalHash(block * 1.3 + vec2(7.0, floor(time * 3.2) * 7.0));",+ " vec2 displaced = uv;",+ " if (blockDisplacement > 0.0 && blockOpacity > 0.0) {",+ " float threshold = 1.0 - blockDisplacement * 0.4;",+ " if (randomA > threshold) {",+ " displaced += vec2((randomB - 0.5) * blockDisplacement * 0.5, (randomC - 0.5) * blockDisplacement * 0.3);",+ " }",+ " if (randomD > 0.92 && blockDisplacement > 0.5) {",+ " displaced.x += (digitalHash(vec2(block.y, floor(time * 8.0))) - 0.5) * blockDisplacement;",+ " }",+ " displaced = mix(uv, displaced, blockOpacity);",+ " }",+ " if (lineTear > 0.0) {",+ " float row = floor(uv.y * (50.0 + lineTear * 150.0));",+ " float tearA = digitalHash(vec2(row * 7.3 + floor(time * 12.0 + row * 0.1) * 3.7, 13.0));",+ " float tearB = digitalHash(vec2(row * 13.7 + floor(time * 8.3) * 5.1, 31.0));",+ " if (tearA > 1.0 - lineTear * 0.5) displaced.x += (tearB - 0.5) * lineTear * 0.4;",+ " if (tearB > 0.95 && lineTear > 0.3) displaced.x += (tearA - 0.5) * lineTear * 0.8;",+ " }",+ " if (pixelate > 0.0) {",+ " float pixelRandom = digitalHash(block * 0.5 + vec2(floor(time * 4.9), 53.0));",+ " if (pixelRandom > 1.0 - pixelate * 0.35) {",+ " float cells = 4.0 + (1.0 - pixelRandom) * pixelate * 40.0;",+ " displaced = (floor(clampUv(displaced) * cells) + 0.5) / cells;",+ " }",+ " }",+ " displaced = clampUv(displaced);",+ " vec3 glitch = sampleDigitalSplit(displaced, block, time, colorSplit);",+ " if (blockDisplacement > 0.2 && blockOpacity > 0.0) {",+ " float corruption = digitalHash(block * 1.1 + vec2(floor(time * 11.9), 67.0));",+ " vec3 changed = glitch;",+ " if (corruption > 0.9) changed = 1.0 - glitch;",+ " else if (corruption > 0.85) changed = corruption > 0.875 ? glitch.gbr : glitch.brg;",+ " else if (corruption > 0.8) {",+ " float channel = digitalHash(block + vec2(73.0));",+ " if (channel > 0.66) changed.r = min(changed.r * 2.0, 1.0);",+ " else if (channel > 0.33) changed.g = min(changed.g * 2.0, 1.0);",+ " else changed.b = min(changed.b * 2.0, 1.0);",+ " }",+ " glitch = mix(glitch, changed, blockOpacity);",+ " }",+ " if (blockOpacity > 0.0) {",+ " float flash = digitalHash(block * 0.8 + vec2(floor(time * 14.7), 83.0));",+ " vec3 flashed = flash > 0.97 ? min(glitch * 1.8, vec3(1.0)) : flash > 0.94 ? glitch * 0.3 : glitch;",+ " glitch = mix(glitch, flashed, blockOpacity * 0.6);",+ " }",+ " if (lineTear > 0.1) {",+ " float interference = pow(sin(uv.y * (300.0 + randomA * 200.0) + time * 30.0) * 0.5 + 0.5, 6.0);",+ " glitch -= interference * 0.08 * lineTear;",+ " }",+ " return mix(source, clamp(glitch, 0.0, 1.0), amount);",+ "}",+ "float dustMask(vec2 uv, float frameBucket){",+ " vec2 grid = vec2(128.0, 72.0);",+ " vec2 cell = floor(uv * grid);",+ " vec2 local = fract(uv * grid) - 0.5;",+ " float chance = grainHash(cell + frameBucket * 19.13);",+ " float radius = mix(0.05, 0.34, grainHash(cell + 7.1));",+ " return step(0.9975, chance) * (1.0 - smoothstep(radius, radius + 0.08, length(local)));",+ "}",+ "float screenDot(vec2 p, float ink, float angle, float sharpness){",+ " float c = cos(angle);",+ " float s = sin(angle);",+ " vec2 q = mat2(c, -s, s, c) * p;",+ " vec2 d = fract(q) - 0.5;",+ " float radius = sqrt(clamp(ink, 0.0, 1.0)) * 0.68;",+ " float edge = mix(0.16, 0.025, sharpness);",+ " return 1.0 - smoothstep(radius - edge, radius + edge, length(d));",+ "}",+ "vec3 paletteColor(float index);",+ "float monoScreenMask(vec2 local, float radius, float shape, float softness){",+ " vec2 centered = local - 0.5;",+ " float distanceToInk = length(centered);",+ " if (shape > 0.5 && shape < 1.5) distanceToInk = max(abs(centered.x), abs(centered.y));",+ " if (shape > 1.5 && shape < 2.5) distanceToInk = abs(centered.x) + abs(centered.y);",+ " if (shape > 2.5 && shape < 3.5) distanceToInk = max(abs(centered.x) * 0.86 + centered.y * 0.5, -centered.y);",+ " if (shape > 3.5) distanceToInk = abs(centered.y);",+ " float shapeRadius = shape > 3.5 ? radius * 0.45 : radius;",+ " return 1.0 - smoothstep(shapeRadius, shapeRadius + softness, distanceToInk);",+ "}",+ "vec3 applyMonoScreen(vec3 source, float amount){",+ " if (amount <= 0.0) return source;",+ " float invert = step(0.5, u_monoScreenInvert);",+ " float coverage = mix(1.0 - lumaOf(source), lumaOf(source), invert);",+ " coverage = pow(clamp(coverage, 0.0, 1.0), mix(1.7, 0.58, clamp(u_monoScreenSpread, 0.0, 1.0)));",+ " float scale = max(min(u_resolution.x, u_resolution.y) / 540.0, 0.25);",+ " float cellPx = mix(4.0, 18.0, clamp(u_monoScreenSize, 0.0, 1.0)) * scale;",+ " float angle = clamp(u_monoScreenAngle, 0.0, 1.0) * PI * 0.5;",+ " float cosine = cos(angle);",+ " float sine = sin(angle);",+ " vec2 point = mat2(cosine, -sine, sine, cosine) * gl_FragCoord.xy / max(cellPx, 1.0);",+ " float radius = sqrt(coverage) * 0.68;",+ " float inkMask = monoScreenMask(fract(point), radius, floor(u_monoScreenShape + 0.5), 0.035);",+ " vec3 ink = paletteColor(0.0);",+ " vec3 paper = paletteColor(max(u_paletteSize - 1.0, 1.0));",+ " return mix(source, mix(paper, ink, inkMask), amount);",+ "}",+ "vec3 applyEngraving(vec3 source, float amount){",+ " if (amount <= 0.0) return source;",+ " float spacing = mix(3.0, 20.0, clamp(u_engravingSpacing, 0.0, 1.0));",+ " float minThickness = mix(0.0, 2.0, clamp(u_engravingMinThickness, 0.0, 1.0));",+ " float maxThickness = mix(1.0, 8.0, clamp(u_engravingMaxThickness, 0.0, 1.0));",+ " float angle = clamp(u_engravingAngle, 0.0, 1.0) * PI;",+ " vec2 alongAxis = vec2(cos(angle), sin(angle));",+ " vec2 acrossAxis = vec2(-alongAxis.y, alongAxis.x);",+ " float along = dot(gl_FragCoord.xy, alongAxis);",+ " float across = dot(gl_FragCoord.xy, acrossAxis);",+ " float frequency = mix(1.0, 10.0, clamp(u_engravingWaveFrequency, 0.0, 1.0));",+ " float wave = sin(along * frequency * 0.01);",+ " across += wave * clamp(u_engravingWave, 0.0, 1.0) * 3.0;",+ " float lineIndex = floor(across / max(spacing, 1.0));",+ " float lineDistance = abs(fract(across / max(spacing, 1.0)) - 0.5) * spacing;",+ " float contrast = mix(0.5, 2.0, clamp(u_engravingContrast, 0.0, 1.0));",+ " float darkness = 1.0 - pow(clamp(lumaOf(source), 0.0, 1.0), contrast);",+ " float variation = mix(0.88, 1.12, digitalHash(vec2(lineIndex, 73.0)));",+ " float thickness = mix(minThickness, maxThickness, darkness) * variation;",+ " float edge = mix(1.0, 0.3, clamp(u_engravingSharpness, 0.0, 1.0));",+ " float inkMask = 1.0 - smoothstep(max(thickness * 0.5 - edge, 0.0), thickness * 0.5 + edge, lineDistance);",+ " inkMask *= smoothstep(0.015, 0.12, darkness);",+ " vec3 ink = paletteColor(0.0);",+ " vec3 paper = paletteColor(max(u_paletteSize - 1.0, 1.0));",+ " return mix(source, mix(paper, ink, inkMask), amount);",+ "}",+ "float crosshatchLine(vec2 pixel, float angle, float spacing, float thickness, float seed){",+ " vec2 alongAxis = vec2(cos(angle), sin(angle));",+ " vec2 acrossAxis = vec2(-alongAxis.y, alongAxis.x);",+ " float along = dot(pixel, alongAxis);",+ " float across = dot(pixel, acrossAxis);",+ " float frequency = mix(1.0, 10.0, clamp(u_crosshatchWaveFrequency, 0.0, 1.0));",+ " across += sin(along * frequency * 0.02 + u_effectTime + seed) * clamp(u_crosshatchWave, 0.0, 1.0) * 5.0;",+ " float lineIndex = floor(across / max(spacing, 1.0));",+ " float distanceToLine = abs(fract(across / max(spacing, 1.0)) - 0.5) * spacing;",+ " float variation = mix(1.0, 0.5 + digitalHash(vec2(lineIndex, seed)), clamp(u_crosshatchLineWeight, 0.0, 1.0));",+ " float halfWidth = thickness * variation * 0.5;",+ " return 1.0 - smoothstep(max(halfWidth - 0.5, 0.0), halfWidth + 0.5, distanceToLine);",+ "}",+ "float crosshatchEdge(vec2 uv){",+ " vec2 texel = 1.0 / max(u_resolution * u_uvScale, vec2(1.0));",+ " float tl = lumaOf(sampleMedia(uv + texel * vec2(-1.0, -1.0)).rgb);",+ " float tc = lumaOf(sampleMedia(uv + texel * vec2( 0.0, -1.0)).rgb);",+ " float tr = lumaOf(sampleMedia(uv + texel * vec2( 1.0, -1.0)).rgb);",+ " float ml = lumaOf(sampleMedia(uv + texel * vec2(-1.0, 0.0)).rgb);",+ " float mr = lumaOf(sampleMedia(uv + texel * vec2( 1.0, 0.0)).rgb);",+ " float bl = lumaOf(sampleMedia(uv + texel * vec2(-1.0, 1.0)).rgb);",+ " float bc = lumaOf(sampleMedia(uv + texel * vec2( 0.0, 1.0)).rgb);",+ " float br = lumaOf(sampleMedia(uv + texel * vec2( 1.0, 1.0)).rgb);",+ " float gx = -tl - 2.0 * ml - bl + tr + 2.0 * mr + br;",+ " float gy = -tl - 2.0 * tc - tr + bl + 2.0 * bc + br;",+ " return length(vec2(gx, gy));",+ "}",+ "vec3 applyCrosshatch(vec2 uv, vec3 source, float amount){",+ " if (amount <= 0.0) return source;",+ " float spacing = mix(5.0, 30.0, clamp(u_crosshatchSpacing, 0.0, 1.0));",+ " float thickness = mix(1.0, 5.0, clamp(u_crosshatchThickness, 0.0, 1.0));",+ " float baseAngle = -clamp(u_crosshatchAngle, 0.0, 1.0) * PI;",+ " float contrast = mix(0.5, 2.0, clamp(u_crosshatchContrast, 0.0, 1.0));",+ " float darkness = 1.0 - pow(clamp(lumaOf(source), 0.0, 1.0), contrast);",+ " vec3 ink = paletteColor(0.0);",+ " vec3 paper = paletteColor(max(u_paletteSize - 1.0, 1.0));",+ " vec3 result = paper;",+ " float layer = crosshatchLine(gl_FragCoord.xy, baseAngle, spacing, thickness, 1.0) * smoothstep(0.2, 0.4, darkness);",+ " result = mix(result, ink, layer);",+ " layer = crosshatchLine(gl_FragCoord.xy, baseAngle + PI * 0.5, spacing * 0.95, thickness * 0.9, 2.0) * smoothstep(0.4, 0.6, darkness);",+ " result = mix(result, ink, layer);",+ " layer = crosshatchLine(gl_FragCoord.xy, baseAngle + PI * 0.25, spacing * 0.9, thickness * 0.8, 3.0) * smoothstep(0.6, 0.8, darkness);",+ " result = mix(result, ink, layer);",+ " layer = crosshatchLine(gl_FragCoord.xy, baseAngle - PI * 0.25, spacing * 0.85, thickness * 0.7, 4.0) * smoothstep(0.75, 0.9, darkness);",+ " result = mix(result, ink, layer);",+ " result = mix(result, ink, smoothstep(0.9, 1.0, darkness) * 0.8);",+ " float edgeStrength = mix(0.0, 2.0, clamp(u_crosshatchEdges, 0.0, 1.0));",+ " float edge = smoothstep(0.1, 0.3, crosshatchEdge(uv)) * edgeStrength;",+ " result = mix(result, ink, clamp(edge, 0.0, 1.0));",+ " return mix(source, result, amount);",+ "}",+ "vec3 applyHalftone(vec3 source, float amount){",+ " if (amount <= 0.0) return source;",+ " vec3 cmy = 1.0 - source;",+ " float k = min(cmy.r, min(cmy.g, cmy.b));",+ " vec3 inks = max(cmy - vec3(k * 0.72), 0.0);",+ " float scale = min(u_resolution.x, u_resolution.y) / 540.0;",+ " float cellPx = mix(5.0, 14.0, clamp(u_halftoneSize, 0.0, 1.0)) * max(scale, 0.25);",+ " vec2 p = gl_FragCoord.xy / max(cellPx, 1.0);",+ " float cyan = screenDot(p, inks.r, 0.261799, 0.78);",+ " float magenta = screenDot(p, inks.g, 1.308997, 0.78);",+ " float yellow = screenDot(p, inks.b, 0.0, 0.78);",+ " float blackInk = screenDot(p, k, 0.785398, 0.82);",+ " vec3 printColor = vec3(0.975, 0.962, 0.925);",+ " printColor *= mix(vec3(1.0), vec3(0.05, 0.79, 0.86), cyan);",+ " printColor *= mix(vec3(1.0), vec3(0.91, 0.08, 0.48), magenta);",+ " printColor *= mix(vec3(1.0), vec3(0.98, 0.83, 0.08), yellow);",+ " printColor *= mix(vec3(1.0), vec3(0.035), blackInk * 0.92);",+ " return mix(source, printColor, amount);",+ "}",+ "vec3 applyTwoInkPrint(vec3 source, float amount){",+ " if (amount <= 0.0) return source;",+ " float sourceLuma = lumaOf(source);",+ " float darkness = 1.0 - sourceLuma;",+ " float warmBias = clamp(source.r - (source.g + source.b) * 0.5, -0.35, 0.35);",+ " float coolBias = clamp((source.g + source.b) * 0.5 - source.r, -0.35, 0.35);",+ " float redTone = smoothstep(0.08, 0.72, darkness) * (1.0 - 0.68 * smoothstep(0.66, 1.0, darkness));",+ " float tealTone = smoothstep(0.30, 0.92, darkness);",+ " float redCoverage = clamp(redTone + warmBias * 1.35 - coolBias * 0.35, 0.0, 1.0);",+ " float tealCoverage = clamp(tealTone + coolBias * 1.1 - warmBias * 0.45, 0.0, 1.0);",+ " float scale = min(u_resolution.x, u_resolution.y) / 540.0;",+ " float cellPx = mix(4.5, 12.0, clamp(u_twoInkPrintSize, 0.0, 1.0)) * max(scale, 0.25);",+ " vec2 p = gl_FragCoord.xy / max(cellPx, 1.0);",+ " float redDot = screenDot(p, redCoverage, 0.261799, 0.84);",+ " float tealDot = screenDot(p + vec2(0.12, -0.08), tealCoverage, 1.308997, 0.84);",+ " float paperNoise = grainHash(floor(gl_FragCoord.xy * 0.5)) - 0.5;",+ " vec3 paper = vec3(0.955, 0.910, 0.795) + paperNoise * 0.018;",+ " vec3 vermilion = vec3(0.88, 0.13, 0.075);",+ " vec3 teal = vec3(0.035, 0.285, 0.355);",+ " vec3 overprint = vec3(0.045, 0.055, 0.052);",+ " vec3 printColor = paper * (1.0 - redDot) * (1.0 - tealDot);",+ " printColor += vermilion * redDot * (1.0 - tealDot);",+ " printColor += teal * (1.0 - redDot) * tealDot;",+ " printColor += overprint * redDot * tealDot;",+ " return mix(source, clamp(printColor, 0.0, 1.0), amount);",+ "}",+ "vec3 paletteColor(float index){",+ " if (index < 0.5) return u_palette0;",+ " if (index < 1.5) return u_palette1;",+ " if (index < 2.5) return u_palette2;",+ " if (index < 3.5) return u_palette3;",+ " if (index < 4.5) return u_palette4;",+ " return u_palette5;",+ "}",+ "float bayer4(vec2 point){",+ " vec2 cell = mod(floor(point), 4.0);",+ " if (cell.y < 0.5) {",+ " if (cell.x < 0.5) return 0.5 / 16.0;",+ " if (cell.x < 1.5) return 8.5 / 16.0;",+ " if (cell.x < 2.5) return 2.5 / 16.0;",+ " return 10.5 / 16.0;",+ " }",+ " if (cell.y < 1.5) {",+ " if (cell.x < 0.5) return 12.5 / 16.0;",+ " if (cell.x < 1.5) return 4.5 / 16.0;",+ " if (cell.x < 2.5) return 14.5 / 16.0;",+ " return 6.5 / 16.0;",+ " }",+ " if (cell.y < 2.5) {",+ " if (cell.x < 0.5) return 3.5 / 16.0;",+ " if (cell.x < 1.5) return 11.5 / 16.0;",+ " if (cell.x < 2.5) return 1.5 / 16.0;",+ " return 9.5 / 16.0;",+ " }",+ " if (cell.x < 0.5) return 15.5 / 16.0;",+ " if (cell.x < 1.5) return 7.5 / 16.0;",+ " if (cell.x < 2.5) return 13.5 / 16.0;",+ " return 5.5 / 16.0;",+ "}",+ "float standardAsciiSample(float brightness, vec2 grid){",+ " if (brightness < 0.1) return 0.0;",+ " if (brightness < 0.2) return grid.x == 2.0 && grid.y == 5.0 ? 1.0 : 0.0;",+ " if (brightness < 0.3) return grid.x == 2.0 && (grid.y == 2.0 || grid.y == 4.0) ? 1.0 : 0.0;",+ " if (brightness < 0.4) return (grid.y == 2.0 || grid.y == 4.0) && grid.x >= 1.0 && grid.x <= 3.0 ? 1.0 : 0.0;",+ " if (brightness < 0.5) {",+ " bool cross = (grid.x == 2.0 && grid.y >= 2.0 && grid.y <= 4.0) || (grid.y == 3.0 && grid.x >= 1.0 && grid.x <= 3.0);",+ " bool diagonals = (grid.x == 1.0 || grid.x == 3.0) && (grid.y == 2.0 || grid.y == 4.0);",+ " return cross || diagonals ? 1.0 : 0.0;",+ " }",+ " if (brightness < 0.6) {",+ " bool ring = ((grid.y == 2.0 || grid.y == 4.0) && grid.x >= 1.0 && grid.x <= 3.0) || ((grid.x == 1.0 || grid.x == 3.0) && grid.y == 3.0);",+ " return ring ? 1.0 : 0.0;",+ " }",+ " bool outline = ((grid.y == 1.0 || grid.y == 5.0) && grid.x >= 1.0 && grid.x <= 3.0) || ((grid.x == 0.0 || grid.x == 4.0) && grid.y >= 2.0 && grid.y <= 4.0) || ((grid.x == 1.0 || grid.x == 3.0) && grid.y >= 1.0 && grid.y <= 5.0);",+ " if (brightness < 0.7) return outline ? 1.0 : 0.0;",+ " if (brightness < 0.8) {",+ " bool slash = abs(grid.x - 2.0) == abs(grid.y - 3.0) && grid.x >= 1.0 && grid.x <= 3.0;",+ " return outline || slash ? 1.0 : 0.0;",+ " }",+ " if (brightness < 0.9) {",+ " bool loops = ((grid.y == 1.0 || grid.y == 3.0 || grid.y == 5.0) && grid.x >= 1.0 && grid.x <= 3.0) || ((grid.x == 1.0 || grid.x == 3.0) && (grid.y == 2.0 || grid.y == 4.0));",+ " return loops ? 1.0 : 0.0;",+ " }",+ " return 1.0;",+ "}",+ "float asciiStyleSample(float style, float brightness, vec2 uv){",+ " vec2 grid = floor(uv * vec2(5.0, 7.0));",+ " if (style < 0.5) return standardAsciiSample(brightness, grid);",+ " if (style < 1.5) {",+ " float checker = mod(grid.x + grid.y, 2.0);",+ " float ruled = mod(grid.x, 2.0) == 0.0 || mod(grid.y, 2.0) == 0.0 ? 1.0 : 0.0;",+ " if (brightness < 0.125) return 0.0;",+ " if (brightness < 0.25) return checker == 0.0 ? 0.5 : 0.0;",+ " if (brightness < 0.375) return ruled * 0.6;",+ " if (brightness < 0.5) return checker == 0.0 ? 1.0 : 0.0;",+ " if (brightness < 0.625) return ruled > 0.5 ? 1.0 : 0.3;",+ " if (brightness < 0.75) return checker == 0.0 ? 1.0 : 0.7;",+ " if (brightness < 0.875) return ruled > 0.5 ? 1.0 : 0.85;",+ " return 1.0;",+ " }",+ " if (style < 2.5) {",+ " if (brightness < 0.14) return 0.0;",+ " if (brightness < 0.28) return grid.x == 2.0 && grid.y == 1.0 ? 1.0 : 0.0;",+ " if (brightness < 0.42) return grid.x == 2.0 && grid.y == 5.0 ? 1.0 : 0.0;",+ " if (brightness < 0.56) return grid.y == 3.0 && grid.x >= 1.0 && grid.x <= 3.0 ? 1.0 : 0.0;",+ " if (brightness < 0.7) return (grid.x == 2.0 && grid.y >= 2.0 && grid.y <= 4.0) || (grid.y == 3.0 && grid.x >= 1.0 && grid.x <= 3.0) ? 1.0 : 0.0;",+ " if (brightness < 0.84) return abs(grid.x - 2.0) == abs(grid.y - 3.0) && grid.y >= 2.0 && grid.y <= 4.0 ? 1.0 : 0.0;",+ " return grid.x == 1.0 || grid.x == 3.0 || grid.y == 2.0 || grid.y == 4.0 ? 1.0 : 0.0;",+ " }",+ " if (style < 3.5) return grid.y >= 6.0 - brightness * 7.0 ? 1.0 : 0.0;",+ " if (style < 4.5) {",+ " vec2 dots = floor(uv * vec2(2.0, 4.0));",+ " if (brightness < 0.125) return 0.0;",+ " if (brightness < 0.25) return dots.y == 3.0 ? 1.0 : 0.0;",+ " if (brightness < 0.375) return dots.y >= 2.0 ? 1.0 : 0.0;",+ " if (brightness < 0.5) return dots.y >= 1.0 ? 1.0 : 0.0;",+ " if (brightness < 0.625) return dots.y >= 1.0 || dots.x == 1.0 ? 1.0 : 0.0;",+ " if (brightness < 0.75) return 1.0;",+ " if (brightness < 0.875) return mod(grid.x + grid.y, 2.0) < 1.5 ? 1.0 : 0.7;",+ " return 1.0;",+ " }",+ " if (style < 5.5) {",+ " if (brightness < 0.125) return 0.0;",+ " if (brightness < 0.25) return grid.x == 2.0 && grid.y == 3.0 ? 1.0 : 0.0;",+ " if (brightness < 0.375) return grid.y == 3.0 && grid.x >= 1.0 && grid.x <= 3.0 ? 1.0 : 0.0;",+ " if (brightness < 0.5) return grid.x + grid.y == 5.0 || grid.x + grid.y == 6.0 ? 1.0 : 0.0;",+ " if (brightness < 0.625) return grid.x == 2.0 ? 1.0 : 0.0;",+ " if (brightness < 0.75) return abs(grid.x - grid.y / 1.4) < 0.7 && grid.x >= 1.0 && grid.x <= 3.0 ? 1.0 : 0.0;",+ " if (brightness < 0.875) return grid.x == 2.0 || grid.y == 3.0 ? 1.0 : 0.0;",+ " return grid.x == 1.0 || grid.x == 3.0 || grid.y == 2.0 || grid.y == 4.0 ? 1.0 : 0.0;",+ " }",+ " if (style < 6.5) {",+ " bool top = grid.y == 0.0 && grid.x >= 1.0 && grid.x <= 3.0;",+ " bool topLeft = grid.x == 1.0 && grid.y <= 3.0;",+ " bool topRight = grid.x == 3.0 && grid.y <= 3.0;",+ " bool middle = grid.y == 3.0 && grid.x >= 1.0 && grid.x <= 3.0;",+ " bool bottomLeft = grid.x == 1.0 && grid.y >= 3.0;",+ " bool bottomRight = grid.x == 3.0 && grid.y >= 3.0;",+ " bool bottom = grid.y == 6.0 && grid.x >= 1.0 && grid.x <= 3.0;",+ " if (brightness < 0.1) return 0.0;",+ " if (brightness < 0.2) return topRight || bottomRight ? 1.0 : 0.0;",+ " if (brightness < 0.3) return top || topRight || middle || bottomLeft || bottom ? 1.0 : 0.0;",+ " if (brightness < 0.4) return top || topRight || middle || bottomRight || bottom ? 1.0 : 0.0;",+ " if (brightness < 0.5) return topLeft || middle || topRight || bottomRight ? 1.0 : 0.0;",+ " if (brightness < 0.6) return top || topLeft || middle || bottomRight || bottom ? 1.0 : 0.0;",+ " if (brightness < 0.7) return top || topLeft || middle || bottomLeft || bottomRight || bottom ? 1.0 : 0.0;",+ " if (brightness < 0.8) return top || topRight || bottomRight ? 1.0 : 0.0;",+ " if (brightness < 0.9) return top || topLeft || topRight || middle || bottomLeft || bottomRight || bottom ? 1.0 : 0.0;",+ " return top || topLeft || topRight || middle || bottomRight || bottom ? 1.0 : 0.0;",+ " }",+ " float slash = grid.x - grid.y;",+ " float backslash = grid.x + grid.y;",+ " if (brightness < 0.16) return 0.0;",+ " if (brightness < 0.33) return mod(slash, 3.0) < 0.5 ? 1.0 : 0.0;",+ " if (brightness < 0.5) return mod(slash, 2.0) < 0.5 ? 1.0 : 0.0;",+ " bool diagonalA = mod(slash, 2.0) < 0.5;",+ " bool diagonalB = mod(backslash, 2.0) < 0.5;",+ " if (brightness < 0.66) return diagonalA || diagonalB ? 1.0 : 0.0;",+ " if (brightness < 0.83) return mod(slash, 1.5) < 0.5 || mod(backslash, 1.5) < 0.5 ? 1.0 : 0.2;",+ " return mod(slash, 1.0) < 0.6 || mod(backslash, 1.0) < 0.6 ? 1.0 : 0.5;",+ "}","vec3 sampleLut(float r, float g, float b){"," float size = max(u_lutSize, 2.0);"," float x = (r + b * size + 0.5) / max(u_lutTextureSize.x, 1.0);",@@ -377,16 +962,8 @@ const FRAGMENT_SHADER = [" vec3 lutColor = mix(c0, c1, f.b);"," return mix(color, lutColor, clamp(u_lutIntensity, 0.0, 1.0));","}",- "void main(){",- " vec2 uv = (v_uv - u_uvOffset) / u_uvScale;",- " if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) {",- " gl_FragColor = vec4(0.0);",- " return;",- " }",- " vec4 originalSample = sampleSource(uv);",- " vec4 sampleColor = sampleMedia(uv);",- " vec3 original = originalSample.rgb;",- " vec3 color = sampleColor.rgb * pow(2.0, u_exposure);",+ "vec3 applyPrimaryGrade(vec3 color){",+ " color *= pow(2.0, u_exposure);"," float y = lumaOf(color);"," float shadowMask = 1.0 - smoothstep(0.0, 0.65, y);"," float highlightMask = smoothstep(0.35, 1.0, y);",@@ -405,18 +982,85 @@ const FRAGMENT_SHADER = [" float vibranceWeight = (1.0 - currentSat * 0.72) * mix(1.0, 0.55, skinLike);"," color = mix(vec3(satLuma), color, max(0.0, 1.0 + u_vibrance * vibranceWeight));"," color = mix(vec3(satLuma), color, max(0.0, 1.0 + u_saturation));",- " color = clamp(color, 0.0, 1.0);",- " color = clamp(applyLut(color), 0.0, 1.0);",- " vec2 vignetteAspect = u_resolution.x > u_resolution.y",- " ? vec2(u_resolution.x / max(u_resolution.y, 1.0), 1.0)",- " : vec2(1.0, u_resolution.y / max(u_resolution.x, 1.0));",- " vec2 vignetteUv = abs((v_uv - vec2(0.5)) * 2.0) * vignetteAspect;",- " float vignettePower = mix(8.0, 1.8, clamp(u_vignetteRoundness * 0.5 + 0.5, 0.0, 1.0));",- " float vignetteDistance = pow(pow(vignetteUv.x, vignettePower) + pow(vignetteUv.y, vignettePower), 1.0 / vignettePower);",- " float vignetteMidpoint = mix(0.22, 1.08, clamp(u_vignetteMidpoint, 0.0, 1.0));",- " float vignetteFeather = mix(0.08, 0.72, clamp(u_vignetteFeather, 0.0, 1.0));",- " float vignetteMask = smoothstep(vignetteMidpoint, vignetteMidpoint + vignetteFeather, vignetteDistance);",- " color *= 1.0 - vignetteMask * clamp(u_vignette, 0.0, 1.0) * 0.75;",+ " return clamp(applyLut(clamp(color, 0.0, 1.0)), 0.0, 1.0);",+ "}",+ "vec3 applyDither(vec3 source, float amount){",+ " if (amount <= 0.0) return source;",+ " float scale = max(min(u_resolution.x, u_resolution.y) / 540.0, 0.25);",+ " float pixelSize = mix(1.0, 5.0, clamp(u_ditherSize, 0.0, 1.0)) * scale;",+ " vec2 block = floor(gl_FragCoord.xy / max(pixelSize, 1.0));",+ " float levels = clamp(u_paletteSize, 2.0, 6.0);",+ " float index = floor(clamp(lumaOf(source) * (levels - 1.0) + bayer4(block), 0.0, levels - 1.0));",+ " return mix(source, paletteColor(index), amount);",+ "}",+ "vec2 asciiEdgeDirection(vec2 uv, vec2 stepUv){",+ " float topLeft = bt601Luma(sampleMedia(uv + vec2(-stepUv.x, -stepUv.y)).rgb);",+ " float top = bt601Luma(sampleMedia(uv + vec2(0.0, -stepUv.y)).rgb);",+ " float topRight = bt601Luma(sampleMedia(uv + vec2(stepUv.x, -stepUv.y)).rgb);",+ " float left = bt601Luma(sampleMedia(uv + vec2(-stepUv.x, 0.0)).rgb);",+ " float right = bt601Luma(sampleMedia(uv + vec2(stepUv.x, 0.0)).rgb);",+ " float bottomLeft = bt601Luma(sampleMedia(uv + vec2(-stepUv.x, stepUv.y)).rgb);",+ " float bottom = bt601Luma(sampleMedia(uv + vec2(0.0, stepUv.y)).rgb);",+ " float bottomRight = bt601Luma(sampleMedia(uv + stepUv).rgb);",+ " float x = -topLeft - 2.0 * left - bottomLeft + topRight + 2.0 * right + bottomRight;",+ " float y = -topLeft - 2.0 * top - topRight + bottomLeft + 2.0 * bottom + bottomRight;",+ " return vec2(x, y);",+ "}",+ "vec2 rotateAsciiUv(vec2 uv, float angle){",+ " float cosine = cos(angle);",+ " float sine = sin(angle);",+ " vec2 centered = uv - 0.5;",+ " return vec2(centered.x * cosine - centered.y * sine, centered.x * sine + centered.y * cosine) + 0.5;",+ "}",+ "vec3 applyAscii(vec3 source, float amount){",+ " if (amount <= 0.0) return source;",+ " float scale = max(min(u_resolution.x, u_resolution.y) / 540.0, 0.25);",+ " float cellHeight = mix(4.0, 80.0, clamp(u_asciiSize, 0.0, 1.0)) * scale;",+ " vec2 cellSize = vec2(cellHeight);",+ " vec2 cell = floor(gl_FragCoord.xy / cellSize);",+ " vec2 cellVuv = (cell + 0.5) * cellSize / max(u_resolution, vec2(1.0));",+ " vec2 cellUv = (cellVuv - u_uvOffset) / u_uvScale;",+ " cellUv = applyCrtWarp(cellUv);",+ " vec3 cellColor = applyPrimaryGrade(sampleMedia(cellUv).rgb);",+ " float brightness = bt601Luma(cellColor);",+ " float invert = step(0.5, u_asciiInvert);",+ " brightness = mix(brightness, 1.0 - brightness, invert);",+ " vec2 glyphUv = fract(gl_FragCoord.xy / cellSize);",+ " float rotation = clamp(u_asciiRotation, 0.0, 1.0);",+ " if (rotation > 0.0) {",+ " vec2 cellStepUv = cellSize / max(u_resolution * u_uvScale, vec2(1.0));",+ " vec2 edge = asciiEdgeDirection(cellUv, cellStepUv);",+ " if (length(edge) > 0.1) glyphUv = mix(glyphUv, rotateAsciiUv(glyphUv, atan(edge.y, edge.x)), rotation);",+ " }",+ " float ink = asciiStyleSample(floor(u_asciiStyle + 0.5), brightness, glyphUv);",+ " vec3 background = paletteColor(0.0);",+ " vec3 inkColor = mix(paletteColor(max(u_paletteSize - 1.0, 1.0)), cellColor, clamp(u_asciiColor, 0.0, 1.0));",+ " vec3 asciiColor = mix(background, inkColor, ink);",+ " return mix(source, asciiColor, amount);",+ "}",+ "vec3 applyScanlines(vec3 source, float amount){",+ " if (amount <= 0.0) return source;",+ " float count = mix(50.0, 500.0, clamp(u_scanlineCount, 0.0, 1.0));",+ " float softness = clamp(u_scanlineSoftness, 0.0, 1.0);",+ " float wave = 0.5 + 0.5 * sin(v_uv.y * count * PI);",+ " float line = mix(1.0 - wave, pow(1.0 - wave, 2.2), softness);",+ " return source * (1.0 - line * amount);",+ "}",+ "void main(){",+ " vec2 uv = (v_uv - u_uvOffset) / u_uvScale;",+ " if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0) {",+ " gl_FragColor = vec4(0.0);",+ " return;",+ " }",+ " vec4 originalSample = sampleSource(uv);",+ " uv = applyCrtWarp(uv);",+ " vec2 displayEdge = smoothstep(vec2(0.0), vec2(0.006), uv) * (1.0 - smoothstep(vec2(0.994), vec2(1.0), uv));",+ " float displayMask = displayEdge.x * displayEdge.y;",+ " vec4 sampleColor = sampleMedia(uv);",+ " sampleColor = sampleChromaticMedia(uv, sampleColor);",+ " sampleColor.rgb = applyDigitalGlitch(uv, sampleColor.rgb);",+ " vec3 original = originalSample.rgb;",+ " vec3 color = mix(sampleColor.rgb, applyPrimaryGrade(sampleColor.rgb), u_intensity);"," float grainAmount = clamp(u_grain, 0.0, 1.0);"," if (grainAmount > 0.0) {"," float grainPixelSize = mix(1.0, 6.0, clamp(u_grainSize, 0.0, 1.0));",@@ -428,8 +1072,40 @@ const FRAGMENT_SHADER = [" float grainMask = smoothstep(0.02, 0.55, grainLuma) * (1.0 - smoothstep(0.88, 1.0, grainLuma));"," color += grain * grainAmount * mix(0.025, 0.08, grainMask);"," }",- " color = clamp(color, 0.0, 1.0);",- " vec3 graded = mix(original, color, u_intensity);",+ " float filmArtifacts = clamp(u_filmArtifacts, 0.0, 1.0);",+ " if (filmArtifacts > 0.0) {",+ " float filmFrame = floor(u_grainSeed);",+ " float dust = dustMask(v_uv, floor(filmFrame / 3.0));",+ " float dustTone = grainHash(vec2(floor(filmFrame / 3.0), 8.0));",+ " color = mix(color, vec3(dustTone > 0.5 ? 0.95 : 0.02), dust * 0.72 * filmArtifacts);",+ " float scratchBucket = floor(filmFrame / 12.0);",+ " float scratchX = grainHash(vec2(scratchBucket, 4.2));",+ " float scratchLife = step(0.78, grainHash(vec2(scratchBucket, 8.4)));",+ " float scratch = (1.0 - smoothstep(0.0, 1.4 / max(u_resolution.x, 1.0), abs(v_uv.x - scratchX))) * scratchLife;",+ " color = mix(color, vec3(0.94, 0.88, 0.76), scratch * 0.28 * filmArtifacts);",+ " }",+ " color = applyMonoScreen(clamp(color, 0.0, 1.0), clamp(u_monoScreen, 0.0, 1.0));",+ " color = applyEngraving(clamp(color, 0.0, 1.0), clamp(u_engraving, 0.0, 1.0));",+ " color = applyCrosshatch(uv, clamp(color, 0.0, 1.0), clamp(u_crosshatch, 0.0, 1.0));",+ " color = applyHalftone(clamp(color, 0.0, 1.0), clamp(u_halftone, 0.0, 1.0));",+ " color = applyTwoInkPrint(clamp(color, 0.0, 1.0), clamp(u_twoInkPrint, 0.0, 1.0));",+ " color = applyDither(clamp(color, 0.0, 1.0), clamp(u_dither, 0.0, 1.0));",+ " color = applyAscii(clamp(color, 0.0, 1.0), clamp(u_ascii, 0.0, 1.0));",+ " if (u_bloomReady > 0.5 && u_bloom > 0.0) color += sampleBloom(uv) * u_bloom;",+ " color = applyScanlines(clamp(color, 0.0, 1.0), clamp(u_scanlines, 0.0, 1.0));",+ " vec2 vignetteAspect = u_resolution.x > u_resolution.y",+ " ? vec2(u_resolution.x / max(u_resolution.y, 1.0), 1.0)",+ " : vec2(1.0, u_resolution.y / max(u_resolution.x, 1.0));",+ " vec2 vignetteUv = abs((v_uv - vec2(0.5)) * 2.0) * vignetteAspect;",+ " float vignettePower = mix(8.0, 1.8, clamp(u_vignetteRoundness * 0.5 + 0.5, 0.0, 1.0));",+ " float vignetteDistance = pow(pow(vignetteUv.x, vignettePower) + pow(vignetteUv.y, vignettePower), 1.0 / vignettePower);",+ " float vignetteMidpoint = mix(0.22, 1.08, clamp(u_vignetteMidpoint, 0.0, 1.0));",+ " float vignetteFeather = mix(0.08, 0.72, clamp(u_vignetteFeather, 0.0, 1.0));",+ " float vignetteMask = smoothstep(vignetteMidpoint, vignetteMidpoint + vignetteFeather, vignetteDistance);",+ " color *= 1.0 - vignetteMask * clamp(u_vignette, 0.0, 1.0) * 0.75;",+ " float warpActive = step(0.0001, u_crtCurvature);",+ " color *= mix(1.0, displayMask, warpActive);",+ " vec3 graded = clamp(color, 0.0, 1.0);"," if (u_compareEnabled > 0.5) {"," float pos = clamp(u_comparePosition, 0.0, 1.0);"," float softness = max(u_compareSoftness, 0.00001);",@@ -458,12 +1134,33 @@ const BLUR_FRAGMENT_SHADER = ["uniform vec2 u_resolution;","uniform vec2 u_direction;","uniform float u_radius;",+ "uniform float u_bloomPass;",+ "uniform float u_threshold;","vec4 readSource(vec2 uv){"," vec4 color = texture2D(u_source, clamp(uv, vec2(0.0), vec2(1.0)));",+ " if (u_bloomPass > 0.5) {",+ " float luminance = dot(color.rgb, vec3(0.299, 0.587, 0.114));",+ " if (u_threshold >= 0.0 && luminance <= u_threshold) color.rgb = vec3(0.0);",+ " return vec4(color.rgb, 1.0);",+ " }"," color.rgb *= color.a;"," return color;","}","void main(){",+ " if (u_bloomPass > 0.5) {",+ " vec2 stepUv = u_direction * max(u_radius, 0.0) / max(u_resolution, vec2(1.0)) * 0.5;",+ " vec4 bloom = readSource(v_uv) * 0.227027;",+ " bloom += readSource(v_uv + stepUv) * 0.1945946;",+ " bloom += readSource(v_uv - stepUv) * 0.1945946;",+ " bloom += readSource(v_uv + stepUv * 2.0) * 0.1216216;",+ " bloom += readSource(v_uv - stepUv * 2.0) * 0.1216216;",+ " bloom += readSource(v_uv + stepUv * 3.0) * 0.054054;",+ " bloom += readSource(v_uv - stepUv * 3.0) * 0.054054;",+ " bloom += readSource(v_uv + stepUv * 4.0) * 0.016216;",+ " bloom += readSource(v_uv - stepUv * 4.0) * 0.016216;",+ " gl_FragColor = bloom;",+ " return;",+ " }"," vec2 stepUv = u_direction * max(u_radius, 0.0) / max(u_resolution, vec2(1.0)) / 12.0;"," vec4 color = readSource(v_uv) * 0.08077993;"," color += readSource(v_uv + stepUv * 1.0) * 0.07918038;",@@ -495,10 +1192,109 @@ const BLUR_FRAGMENT_SHADER = ["}",].join("\n");+const KUWAHARA_HORIZONTAL_FRAGMENT_SHADER = [+ "#ifdef GL_FRAGMENT_PRECISION_HIGH",+ "precision highp float;",+ "#else",+ "precision mediump float;",+ "#endif",+ "varying vec2 v_uv;",+ "uniform sampler2D u_source;",+ "uniform sampler2D u_blurSource;",+ "uniform vec2 u_texel;",+ "uniform vec2 u_uvScale;",+ "uniform vec2 u_uvOffset;",+ "uniform float u_blurReady;",+ "uniform float u_blur;",+ "uniform float u_kuwaharaRadius;",+ "vec3 readPrepared(vec2 displayUv){",+ " vec2 uv = (displayUv - u_uvOffset) / u_uvScale;",+ " vec3 color = texture2D(u_source, clamp(uv, vec2(0.0), vec2(1.0))).rgb;",+ " if (u_blurReady > 0.5 && u_blur > 0.0) {",+ " vec3 blurred = texture2D(u_blurSource, clamp(uv, vec2(0.0), vec2(1.0))).rgb;",+ " color = mix(color, blurred, clamp(u_blur, 0.0, 1.0));",+ " }",+ " return color;",+ "}",+ "void main(){",+ " float radius = floor(mix(2.0, 16.0, clamp(u_kuwaharaRadius, 0.0, 1.0)) + 0.5);",+ " vec3 sum = vec3(0.0);",+ " float sumSquares = 0.0;",+ " float count = 0.0;",+ " for (int offset = 0; offset <= 16; offset++) {",+ " if (float(offset) > radius) continue;",+ " vec3 color = readPrepared(v_uv + vec2(float(offset), 0.0) * u_texel);",+ " sum += color;",+ " sumSquares += dot(color, color) / 3.0;",+ " count += 1.0;",+ " }",+ " gl_FragColor = vec4(sum / count, sumSquares / count);",+ "}",+].join("\n");++const KUWAHARA_RESOLVE_FRAGMENT_SHADER = [+ "#ifdef GL_FRAGMENT_PRECISION_HIGH",+ "precision highp float;",+ "#else",+ "precision mediump float;",+ "#endif",+ "varying vec2 v_uv;",+ "uniform sampler2D u_kuwaharaMoments;",+ "uniform vec2 u_texel;",+ "uniform float u_kuwaharaRadius;",+ "uniform float u_kuwaharaSharpness;",+ "uniform float u_kuwaharaSaturation;",+ "void main(){",+ " float radius = floor(mix(2.0, 16.0, clamp(u_kuwaharaRadius, 0.0, 1.0)) + 0.5);",+ " vec2 origins[4];",+ " origins[0] = vec2(-radius, -radius);",+ " origins[1] = vec2(0.0, -radius);",+ " origins[2] = vec2(-radius, 0.0);",+ " origins[3] = vec2(0.0, 0.0);",+ " vec3 means[4];",+ " float variances[4];",+ " float minVariance = 1.0;",+ " for (int quadrant = 0; quadrant < 4; quadrant++) {",+ " vec4 moment = vec4(0.0);",+ " float count = 0.0;",+ " for (int offset = 0; offset <= 16; offset++) {",+ " if (float(offset) > radius) continue;",+ " vec2 sampleOffset = origins[quadrant] + vec2(0.0, float(offset));",+ " moment += texture2D(u_kuwaharaMoments, clamp(v_uv + sampleOffset * u_texel, vec2(0.0), vec2(1.0)));",+ " count += 1.0;",+ " }",+ " moment /= count;",+ " vec3 mean = moment.rgb;",+ " float meanSquare = moment.a * 3.0;",+ " float variance = max(meanSquare - dot(mean, mean), 0.0);",+ " means[quadrant] = mean;",+ " variances[quadrant] = variance;",+ " minVariance = min(minVariance, variance);",+ " }",+ " float exponent = 1.0 + clamp(u_kuwaharaSharpness, 0.0, 1.0) * 8.0;",+ " vec3 result = vec3(0.0);",+ " float totalWeight = 0.0;",+ " for (int quadrant = 0; quadrant < 4; quadrant++) {",+ " float weight = pow((minVariance + 0.0001) / (variances[quadrant] + 0.0001), exponent);",+ " result += means[quadrant] * weight;",+ " totalWeight += weight;",+ " }",+ " result /= max(totalWeight, 0.0001);",+ " float luma = dot(result, vec3(0.2126, 0.7152, 0.0722));",+ " float saturation = clamp(u_kuwaharaSaturation, 0.0, 1.0) * 2.0;",+ " gl_FragColor = vec4(clamp(mix(vec3(luma), result, saturation), 0.0, 1.0), 1.0);",+ "}",+].join("\n");+function isColorGradingMediaElement(value: Element): value is ColorGradingMediaElement {return value instanceof HTMLVideoElement || value instanceof HTMLImageElement;}+function isVisibleForColorGrading(element: ColorGradingMediaElement): boolean {+ const style = window.getComputedStyle(element);+ return style.display !== "none" && style.visibility !== "hidden";+}+function compileShader(gl: WebGLRenderingContext,source: string,@@ -542,7 +1338,11 @@ function createProgram(return program;}-function createTexture(gl: WebGLRenderingContext, filter: number = gl.LINEAR): WebGLTexture | null {+function createTexture(+ gl: WebGLRenderingContext,+ filter: number = gl.LINEAR,+ type: number = gl.UNSIGNED_BYTE,+): WebGLTexture | null {const texture = gl.createTexture();if (!texture) return null;gl.bindTexture(gl.TEXTURE_2D, texture);@@ -550,7 +1350,7 @@ function createTexture(gl: WebGLRenderingContext, filter: number = gl.LINEAR): Wgl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, type, null);return texture;}@@ -568,11 +1368,56 @@ function createBlurProgramInfo(resolution: gl.getUniformLocation(program, "u_resolution"),direction: gl.getUniformLocation(program, "u_direction"),radius: gl.getUniformLocation(program, "u_radius"),+ bloomPass: gl.getUniformLocation(program, "u_bloomPass"),+ threshold: gl.getUniformLocation(program, "u_threshold"),};}-function createRenderTarget(gl: WebGLRenderingContext): RenderTarget | null {- const texture = createTexture(gl);+function createKuwaharaHorizontalProgramInfo(+ gl: WebGLRenderingContext,+ quad: WebGLBuffer,+): KuwaharaHorizontalProgramInfo | null {+ const program = createProgram(gl, KUWAHARA_HORIZONTAL_FRAGMENT_SHADER);+ if (!program) return null;+ return {+ program,+ quad,+ position: gl.getAttribLocation(program, "a_pos"),+ source: gl.getUniformLocation(program, "u_source"),+ blurSource: gl.getUniformLocation(program, "u_blurSource"),+ texel: gl.getUniformLocation(program, "u_texel"),+ uvScale: gl.getUniformLocation(program, "u_uvScale"),+ uvOffset: gl.getUniformLocation(program, "u_uvOffset"),+ blurReady: gl.getUniformLocation(program, "u_blurReady"),+ blur: gl.getUniformLocation(program, "u_blur"),+ radius: gl.getUniformLocation(program, "u_kuwaharaRadius"),+ };+}++function createKuwaharaResolveProgramInfo(+ gl: WebGLRenderingContext,+ quad: WebGLBuffer,+): KuwaharaResolveProgramInfo | null {+ const program = createProgram(gl, KUWAHARA_RESOLVE_FRAGMENT_SHADER);+ if (!program) return null;+ return {+ program,+ quad,+ position: gl.getAttribLocation(program, "a_pos"),+ moments: gl.getUniformLocation(program, "u_kuwaharaMoments"),+ texel: gl.getUniformLocation(program, "u_texel"),+ radius: gl.getUniformLocation(program, "u_kuwaharaRadius"),+ sharpness: gl.getUniformLocation(program, "u_kuwaharaSharpness"),+ saturation: gl.getUniformLocation(program, "u_kuwaharaSaturation"),+ };+}++function createRenderTarget(+ gl: WebGLRenderingContext,+ type: number = gl.UNSIGNED_BYTE,+ filter: number = gl.LINEAR,+): RenderTarget | null {+ const texture = createTexture(gl, filter, type);const framebuffer = gl.createFramebuffer();if (!texture || !framebuffer) {if (texture) gl.deleteTexture(texture);@@ -588,7 +1433,7 @@ function createRenderTarget(gl: WebGLRenderingContext): RenderTarget | null {gl.deleteFramebuffer(framebuffer);return null;}- return { texture, framebuffer, width: 1, height: 1 };+ return { texture, framebuffer, type, width: 1, height: 1 };}function resizeRenderTarget(@@ -601,7 +1446,20 @@ function resizeRenderTarget(target.width = width;target.height = height;gl.bindTexture(gl.TEXTURE_2D, target.texture);- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, target.type, null);+}++function createFloatUniformBindings<K extends string>(+ gl: WebGLRenderingContext,+ program: WebGLProgram,+ keys: readonly K[],+): readonly FloatUniformBinding<K>[] {+ const bindings: FloatUniformBinding<K>[] = [];+ for (const key of keys) {+ const location = gl.getUniformLocation(program, `u_${key}`);+ if (location !== null) bindings.push([key, location]);+ }+ return bindings;}function createProgramInfo(canvas: HTMLCanvasElement): {@@ -611,7 +1469,6 @@ function createProgramInfo(canvas: HTMLCanvasElement): {const gl = canvas.getContext("webgl", {alpha: true,premultipliedAlpha: false,- preserveDrawingBuffer: true,});if (!gl) return null;const program = createProgram(gl);@@ -643,37 +1500,33 @@ function createProgramInfo(canvas: HTMLCanvasElement): {position: gl.getAttribLocation(program, "a_pos"),source: gl.getUniformLocation(program, "u_source"),blurSource: gl.getUniformLocation(program, "u_blurSource"),+ bloomSource: gl.getUniformLocation(program, "u_bloomSource"),+ kuwaharaSource: gl.getUniformLocation(program, "u_kuwaharaSource"),lut: gl.getUniformLocation(program, "u_lut"),resolution: gl.getUniformLocation(program, "u_resolution"),uvScale: gl.getUniformLocation(program, "u_uvScale"),uvOffset: gl.getUniformLocation(program, "u_uvOffset"),blurReady: gl.getUniformLocation(program, "u_blurReady"),+ bloomReady: gl.getUniformLocation(program, "u_bloomReady"),+ kuwaharaReady: gl.getUniformLocation(program, "u_kuwaharaReady"),lutEnabled: gl.getUniformLocation(program, "u_lutEnabled"),lutSize: gl.getUniformLocation(program, "u_lutSize"),lutTextureSize: gl.getUniformLocation(program, "u_lutTextureSize"),lutDomainMin: gl.getUniformLocation(program, "u_lutDomainMin"),lutDomainMax: gl.getUniformLocation(program, "u_lutDomainMax"),lutIntensity: gl.getUniformLocation(program, "u_lutIntensity"),- exposure: gl.getUniformLocation(program, "u_exposure"),- contrast: gl.getUniformLocation(program, "u_contrast"),- highlights: gl.getUniformLocation(program, "u_highlights"),- shadows: gl.getUniformLocation(program, "u_shadows"),- whites: gl.getUniformLocation(program, "u_whites"),- blacks: gl.getUniformLocation(program, "u_blacks"),- temperature: gl.getUniformLocation(program, "u_temperature"),- tint: gl.getUniformLocation(program, "u_tint"),- vibrance: gl.getUniformLocation(program, "u_vibrance"),- saturation: gl.getUniformLocation(program, "u_saturation"),- vignette: gl.getUniformLocation(program, "u_vignette"),- vignetteMidpoint: gl.getUniformLocation(program, "u_vignetteMidpoint"),- vignetteRoundness: gl.getUniformLocation(program, "u_vignetteRoundness"),- vignetteFeather: gl.getUniformLocation(program, "u_vignetteFeather"),- grain: gl.getUniformLocation(program, "u_grain"),- grainSize: gl.getUniformLocation(program, "u_grainSize"),- grainRoughness: gl.getUniformLocation(program, "u_grainRoughness"),+ adjustUniforms: createFloatUniformBindings(gl, program, HF_COLOR_GRADING_ADJUST_KEYS),+ detailUniforms: createFloatUniformBindings(gl, program, HF_COLOR_GRADING_DETAIL_KEYS),+ effectUniforms: createFloatUniformBindings(gl, program, HF_COLOR_GRADING_EFFECT_KEYS),grainSeed: gl.getUniformLocation(program, "u_grainSeed"),- blur: gl.getUniformLocation(program, "u_blur"),- pixelate: gl.getUniformLocation(program, "u_pixelate"),+ effectTime: gl.getUniformLocation(program, "u_effectTime"),+ paletteSize: gl.getUniformLocation(program, "u_paletteSize"),+ palette0: gl.getUniformLocation(program, "u_palette0"),+ palette1: gl.getUniformLocation(program, "u_palette1"),+ palette2: gl.getUniformLocation(program, "u_palette2"),+ palette3: gl.getUniformLocation(program, "u_palette3"),+ palette4: gl.getUniformLocation(program, "u_palette4"),+ palette5: gl.getUniformLocation(program, "u_palette5"),intensity: gl.getUniformLocation(program, "u_intensity"),compareEnabled: gl.getUniformLocation(program, "u_compareEnabled"),comparePosition: gl.getUniformLocation(program, "u_comparePosition"),@@ -783,20 +1636,7 @@ function uploadEntryLut(const packed = packCubeLutToRgba8(lut);const { gl, program } = entry;try {- gl.activeTexture(gl.TEXTURE2);- gl.bindTexture(gl.TEXTURE_2D, program.lutTexture);- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);- gl.texImage2D(- gl.TEXTURE_2D,- 0,- gl.RGBA,- packed.width,- packed.height,- 0,- gl.RGBA,- gl.UNSIGNED_BYTE,- packed.data,- );+ uploadLutTexture(gl, program.lutTexture, packed);entry.lut = {src,size: lut.size,@@ -817,26 +1657,89 @@ function uploadEntryLut(}}+async function loadCubeLut(src: string): Promise<CubeLut3D> {+ const cached = getCubeLut(src);+ if (cached.state === "ready") return cached.lut;+ if (cached.state === "pending") return cached.promise;+ throw new Error(cached.message);+}++function uploadLutTexture(+ gl: WebGLRenderingContext,+ texture: WebGLTexture,+ packed: ReturnType<typeof packCubeLutToRgba8>,+): void {+ gl.activeTexture(gl.TEXTURE2);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.RGBA,+ packed.width,+ packed.height,+ 0,+ gl.RGBA,+ gl.UNSIGNED_BYTE,+ packed.data,+ );+}++function uploadPreviewLut(+ renderer: ColorGradingPreviewRenderer,+ src: string,+ lut: CubeLut3D,+): RuntimeLutTexture {+ const packed = packCubeLutToRgba8(lut);+ const { gl, program } = renderer;+ uploadLutTexture(gl, program.lutTexture, packed);+ return {+ src,+ size: lut.size,+ domainMin: lut.domainMin,+ domainMax: lut.domainMax,+ textureWidth: packed.width,+ textureHeight: packed.height,+ };+}+function destroyRenderTarget(gl: WebGLRenderingContext, target: RenderTarget): void {gl.deleteTexture(target.texture);gl.deleteFramebuffer(target.framebuffer);}-function destroyEffectTargets(entry: ColorGradingEntry): void {- const targets = entry.effectTargets;+function destroyEffectTargets(state: EffectRenderState): void {+ const targets = state.effectTargets;if (!targets) return;- entry.gl.deleteProgram(targets.blurProgram.program);- destroyRenderTarget(entry.gl, targets.scratch);- destroyRenderTarget(entry.gl, targets.blur);- entry.effectTargets = null;+ state.gl.deleteProgram(targets.blurProgram.program);+ destroyRenderTarget(state.gl, targets.scratch);+ destroyRenderTarget(state.gl, targets.blur);+ if (targets.bloom) destroyRenderTarget(state.gl, targets.bloom);+ state.effectTargets = null;}-function destroyProgramResources(entry: ColorGradingEntry): void {- destroyEffectTargets(entry);- entry.gl.deleteTexture(entry.program.texture);- entry.gl.deleteTexture(entry.program.lutTexture);- entry.gl.deleteBuffer(entry.program.quad);- entry.gl.deleteProgram(entry.program.program);+function destroyKuwaharaTargets(state: EffectRenderState): void {+ const targets = state.kuwaharaTargets;+ if (!targets) return;+ state.gl.deleteProgram(targets.horizontalProgram.program);+ state.gl.deleteProgram(targets.resolveProgram.program);+ destroyRenderTarget(state.gl, targets.moments);+ destroyRenderTarget(state.gl, targets.output);+ state.kuwaharaTargets = null;+}++function destroyProgramResources(renderer: ColorGradingRenderer, loseContext = false): void {+ destroyEffectTargets(renderer);+ destroyKuwaharaTargets(renderer);+ destroyMainProgramResources(renderer.gl, renderer.program);+ if (loseContext) renderer.gl.getExtension("WEBGL_lose_context")?.loseContext();+}++function destroyMainProgramResources(gl: WebGLRenderingContext, program: ProgramInfo): void {+ gl.deleteTexture(program.texture);+ gl.deleteTexture(program.lutTexture);+ gl.deleteBuffer(program.quad);+ gl.deleteProgram(program.program);}function replaceProgramResources(entry: ColorGradingEntry): boolean {@@ -871,22 +1774,71 @@ function restoreSourceElement(entry: ColorGradingEntry): void {entry.sourceHidden = false;}-function ensureEffectTargets(entry: ColorGradingEntry): EffectTargets | null {- if (entry.effectTargets) return entry.effectTargets;- const { gl } = entry;- const blurProgram = createBlurProgramInfo(gl, entry.program.quad);+function ensureEffectTargets(state: EffectRenderState): EffectTargets | null {+ if (state.effectTargets) return state.effectTargets;+ const { gl } = state;+ const blurProgram = createBlurProgramInfo(gl, state.program.quad);const scratch = createRenderTarget(gl);const blur = createRenderTarget(gl);if (!blurProgram || !scratch || !blur) {if (blurProgram) gl.deleteProgram(blurProgram.program);if (scratch) destroyRenderTarget(gl, scratch);if (blur) destroyRenderTarget(gl, blur);- entry.effectError = "Framebuffer effects unavailable";+ state.effectError = "Framebuffer effects unavailable";return null;}- entry.effectError = null;- entry.effectTargets = { blurProgram, scratch, blur };- return entry.effectTargets;+ state.effectError = null;+ state.effectTargets = { blurProgram, scratch, blur, bloom: null };+ return state.effectTargets;+}++function ensureBloomOutput(state: EffectRenderState, targets: EffectTargets): RenderTarget | null {+ if (targets.bloom) return targets.bloom;+ targets.bloom = createRenderTarget(state.gl);+ state.effectError = targets.bloom ? null : "Framebuffer effects unavailable";+ return targets.bloom;+}++function destroyBloomOutput(state: EffectRenderState): void {+ const targets = state.effectTargets;+ if (!targets?.bloom) return;+ destroyRenderTarget(state.gl, targets.bloom);+ targets.bloom = null;+}++function ensureKuwaharaTargets(state: EffectRenderState): KuwaharaTargets | null {+ if (state.kuwaharaTargets) return state.kuwaharaTargets;+ const { gl } = state;+ const halfFloat = gl.getExtension("OES_texture_half_float");+ const colorBufferHalfFloat = gl.getExtension("EXT_color_buffer_half_float");+ if (!halfFloat || !colorBufferHalfFloat) {+ state.effectError = "Kuwahara requires half-float framebuffer support";+ return null;+ }+ const horizontalProgram = createKuwaharaHorizontalProgramInfo(gl, state.program.quad);+ const resolveProgram = createKuwaharaResolveProgramInfo(gl, state.program.quad);+ const moments = createRenderTarget(gl, halfFloat.HALF_FLOAT_OES, gl.NEAREST);+ const output = createRenderTarget(gl);+ if (!horizontalProgram || !resolveProgram || !moments || !output) {+ destroyIncompleteKuwaharaTargets(gl, horizontalProgram, resolveProgram, moments, output);+ state.effectError = "Kuwahara framebuffer effects unavailable";+ return null;+ }+ state.kuwaharaTargets = { horizontalProgram, resolveProgram, moments, output };+ return state.kuwaharaTargets;+}++function destroyIncompleteKuwaharaTargets(+ gl: WebGLRenderingContext,+ horizontalProgram: KuwaharaHorizontalProgramInfo | null,+ resolveProgram: KuwaharaResolveProgramInfo | null,+ moments: RenderTarget | null,+ output: RenderTarget | null,+): void {+ if (horizontalProgram) gl.deleteProgram(horizontalProgram.program);+ if (resolveProgram) gl.deleteProgram(resolveProgram.program);+ if (moments) destroyRenderTarget(gl, moments);+ if (output) destroyRenderTarget(gl, output);}function resizeEffectTargetPair(@@ -911,6 +1863,8 @@ function renderBlurPass(layout: { width: number; height: number },direction: { x: number; y: number },radius: number,+ bloomPass = false,+ threshold = -1,): void {gl.bindFramebuffer(gl.FRAMEBUFFER, output.framebuffer);gl.viewport(0, 0, layout.width, layout.height);@@ -921,10 +1875,43 @@ function renderBlurPass(gl.uniform2f(program.resolution, layout.width, layout.height);gl.uniform2f(program.direction, direction.x, direction.y);gl.uniform1f(program.radius, radius);- gl.bindBuffer(gl.ARRAY_BUFFER, program.quad);- gl.enableVertexAttribArray(program.position);- gl.vertexAttribPointer(program.position, 2, gl.FLOAT, false, 0, 0);- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ gl.uniform1f(program.bloomPass, bloomPass ? 1 : 0);+ gl.uniform1f(program.threshold, threshold);+ drawFullscreenQuad(gl, program);+}++function renderBloomTexture(+ gl: WebGLRenderingContext,+ targets: EffectTargets,+ input: WebGLTexture,+ output: RenderTarget,+ width: number,+ height: number,+ radius: number,+): void {+ const layout = resizeEffectTargetPair(gl, targets.scratch, output, width / 2, height / 2);+ const passRadius = radius / 2;+ renderBlurPass(+ gl,+ targets.blurProgram,+ input,+ targets.scratch,+ layout,+ { x: 1, y: 0 },+ passRadius,+ true,+ 0.5,+ );+ renderBlurPass(+ gl,+ targets.blurProgram,+ targets.scratch.texture,+ output,+ layout,+ { x: 0, y: 1 },+ passRadius,+ true,+ );}function renderGaussianTexture(@@ -960,6 +1947,225 @@ function renderGaussianTexture(}}+function drawFullscreenQuad(+ gl: WebGLRenderingContext,+ program: { quad: WebGLBuffer; position: number },+): void {+ gl.bindBuffer(gl.ARRAY_BUFFER, program.quad);+ gl.enableVertexAttribArray(program.position);+ gl.vertexAttribPointer(program.position, 2, gl.FLOAT, false, 0, 0);+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+}++function renderKuwaharaTexture(+ gl: WebGLRenderingContext,+ targets: KuwaharaTargets,+ source: WebGLTexture,+ blurSource: WebGLTexture,+ layout: { width: number; height: number },+ uv: { scaleX: number; scaleY: number; offsetX: number; offsetY: number },+ blurReady: boolean,+ effects: NormalizedHfColorGrading["effects"],+): void {+ resizeRenderTarget(gl, targets.moments, layout.width, layout.height);+ resizeRenderTarget(gl, targets.output, layout.width, layout.height);++ const horizontal = targets.horizontalProgram;+ gl.bindFramebuffer(gl.FRAMEBUFFER, targets.moments.framebuffer);+ gl.viewport(0, 0, layout.width, layout.height);+ gl.useProgram(horizontal.program);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, source);+ gl.activeTexture(gl.TEXTURE1);+ gl.bindTexture(gl.TEXTURE_2D, blurSource);+ gl.uniform1i(horizontal.source, 0);+ gl.uniform1i(horizontal.blurSource, 1);+ gl.uniform2f(horizontal.texel, 1 / layout.width, 1 / layout.height);+ gl.uniform2f(horizontal.uvScale, uv.scaleX, uv.scaleY);+ gl.uniform2f(horizontal.uvOffset, uv.offsetX, uv.offsetY);+ gl.uniform1f(horizontal.blurReady, blurReady ? 1 : 0);+ gl.uniform1f(horizontal.blur, effects.blur);+ gl.uniform1f(horizontal.radius, effects.kuwaharaRadius);+ drawFullscreenQuad(gl, horizontal);++ const resolve = targets.resolveProgram;+ gl.bindFramebuffer(gl.FRAMEBUFFER, targets.output.framebuffer);+ gl.useProgram(resolve.program);+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, targets.moments.texture);+ gl.uniform1i(resolve.moments, 0);+ gl.uniform2f(resolve.texel, 1 / layout.width, 1 / layout.height);+ gl.uniform1f(resolve.radius, effects.kuwaharaRadius);+ gl.uniform1f(resolve.sharpness, effects.kuwaharaSharpness);+ gl.uniform1f(resolve.saturation, effects.kuwaharaSaturation);+ drawFullscreenQuad(gl, resolve);+}++interface PreparedEffectTextures {+ blurReady: boolean;+ bloomReady: boolean;+ kuwaharaReady: boolean;+ blurTexture: WebGLTexture;+ bloomTexture: WebGLTexture;+ kuwaharaTexture: WebGLTexture;+}++function prepareBlurTexture(+ state: EffectRenderState,+ targets: EffectTargets,+ amount: number,+ layout: { width: number; height: number },+): boolean {+ if (amount <= 0) return false;+ const blurLayout = resizeEffectTargetPair(+ state.gl,+ targets.scratch,+ targets.blur,+ layout.width,+ layout.height,+ );+ renderGaussianTexture(+ state.gl,+ targets,+ state.program.texture,+ targets.blur,+ blurLayout,+ 0.75 + Math.pow(amount, 1.35) * 32,+ amount > 0.55 ? 3 : 2,+ );+ return true;+}++function prepareBloomTexture(+ state: EffectRenderState,+ targets: EffectTargets,+ amount: number,+ radius: number,+ layout: { width: number; height: number },+ blurReady: boolean,+): WebGLTexture | null {+ if (amount <= 0) {+ destroyBloomOutput(state);+ return null;+ }+ if (!blurReady) destroyBloomOutput(state);+ const output = blurReady ? ensureBloomOutput(state, targets) : targets.blur;+ if (!output) return null;+ renderBloomTexture(+ state.gl,+ targets,+ state.program.texture,+ output,+ layout.width,+ layout.height,+ radius,+ );+ return output.texture;+}++function prepareBlurAndBloomTextures(+ state: EffectRenderState,+ grading: NormalizedHfColorGrading,+ layout: { width: number; height: number },+ releaseIdleTargets: boolean,+): Pick<PreparedEffectTextures, "blurReady" | "bloomReady" | "blurTexture" | "bloomTexture"> {+ const { program } = state;+ const blurAmount = grading.effects.blur;+ const bloomAmount = grading.effects.bloom;+ if (blurAmount <= 0 && bloomAmount <= 0) {+ if (state.effectTargets && releaseIdleTargets) destroyEffectTargets(state);+ return {+ blurReady: false,+ bloomReady: false,+ blurTexture: program.texture,+ bloomTexture: program.texture,+ };+ }++ const targets = ensureEffectTargets(state);+ if (!targets) {+ return {+ blurReady: false,+ bloomReady: false,+ blurTexture: program.texture,+ bloomTexture: program.texture,+ };+ }++ const blurReady = prepareBlurTexture(state, targets, blurAmount, layout);+ const bloomTexture = prepareBloomTexture(+ state,+ targets,+ bloomAmount,+ grading.effects.bloomRadius,+ layout,+ blurReady,+ );+ return {+ blurReady,+ bloomReady: bloomTexture !== null,+ blurTexture: targets.blur.texture,+ bloomTexture: bloomTexture ?? program.texture,+ };+}++function prepareKuwaharaTexture(+ state: EffectRenderState,+ grading: NormalizedHfColorGrading,+ layout: { width: number; height: number },+ uv: { scaleX: number; scaleY: number; offsetX: number; offsetY: number },+ blurReady: boolean,+ preserve: boolean,+ releaseIdleTargets: boolean,+): Pick<PreparedEffectTextures, "kuwaharaReady" | "kuwaharaTexture"> {+ const amount = grading.effects.kuwahara;+ if (amount <= 0 && !preserve) {+ if (state.kuwaharaTargets && releaseIdleTargets) destroyKuwaharaTargets(state);+ return { kuwaharaReady: false, kuwaharaTexture: state.program.texture };+ }++ const targets = ensureKuwaharaTargets(state);+ if (!targets || amount <= 0) {+ return {+ kuwaharaReady: false,+ kuwaharaTexture: targets?.output.texture ?? state.program.texture,+ };+ }+ renderKuwaharaTexture(+ state.gl,+ targets,+ state.program.texture,+ state.effectTargets?.blur.texture ?? state.program.texture,+ layout,+ uv,+ blurReady,+ grading.effects,+ );+ return { kuwaharaReady: true, kuwaharaTexture: targets.output.texture };+}++function prepareEffectTextures(+ state: EffectRenderState,+ grading: NormalizedHfColorGrading,+ layout: { width: number; height: number },+ uv: { scaleX: number; scaleY: number; offsetX: number; offsetY: number },+ options: { preserveKuwahara?: boolean; releaseIdleTargets?: boolean } = {},+): PreparedEffectTextures {+ const releaseIdleTargets = options.releaseIdleTargets ?? true;+ state.effectError = null;+ const blurAndBloom = prepareBlurAndBloomTextures(state, grading, layout, releaseIdleTargets);+ const kuwahara = prepareKuwaharaTexture(+ state,+ grading,+ layout,+ uv,+ blurAndBloom.blurReady,+ options.preserveKuwahara ?? false,+ releaseIdleTargets,+ );+ return { ...blurAndBloom, ...kuwahara };+}+// fallow-ignore-next-line complexityfunction ensureEntryLut(entry: ColorGradingEntry): RuntimeLutTexture | null {const src = entry.grading.lut?.src.trim() ?? "";@@ -1080,6 +2286,14 @@ function findRenderFrameImage(video: HTMLVideoElement): HTMLImageElement | nullreturn frame instanceof HTMLImageElement && isDrawableSource(frame) ? frame : null;}+function hasInjectedRenderFrame(element: ColorGradingMediaElement): boolean {+ if (!(element instanceof HTMLVideoElement)) return false;+ const frame = findRenderFrameImage(element);+ if (!frame) return false;+ const style = window.getComputedStyle(frame);+ return style.display !== "none" && style.visibility !== "hidden";+}+function isRenderFrameImage(source: TexImageSource): source is HTMLImageElement {return source instanceof HTMLImageElement && source.classList.contains("__render_frame__");}@@ -1193,6 +2407,10 @@ function ensureParentPosition(entry: ColorGradingEntry, parent: HTMLElement): voparent.style.position = "relative";}+function resolvedLayoutSize(primary: number, fallback: number): number {+ return Math.max(0, Math.round(primary > 0 ? primary : fallback));+}+function updateCanvasLayout(entry: ColorGradingEntry,styleSource: HTMLElement,@@ -1217,17 +2435,33 @@ function updateCanvasLayout(canvas.style.visibility = entry.sourceVisibleForCanvas ? "visible" : "hidden";const rect = element.getBoundingClientRect();- const width = Math.max(0, Math.round(element.offsetWidth || rect.width));- const height = Math.max(0, Math.round(element.offsetHeight || rect.height));- if (width <= 0 || height <= 0) {+ const cssWidth = resolvedLayoutSize(element.offsetWidth, rect.width);+ const cssHeight = resolvedLayoutSize(element.offsetHeight, rect.height);+ if (cssWidth <= 0 || cssHeight <= 0) {canvas.style.display = "none";return null;}+ const pixelRatio = Math.max(1, window.devicePixelRatio || 1);+ const width = Math.round(cssWidth * pixelRatio);+ const height = Math.round(cssHeight * pixelRatio);if (canvas.width !== width) canvas.width = width;if (canvas.height !== height) canvas.height = height;return { width, height };}+function setPaletteColorUniform(+ gl: WebGLRenderingContext,+ location: WebGLUniformLocation | null,+ color: string,+): void {+ gl.uniform3f(+ location,+ Number.parseInt(color.slice(1, 3), 16) / 255,+ Number.parseInt(color.slice(3, 5), 16) / 255,+ Number.parseInt(color.slice(5, 7), 16) / 255,+ );+}+// fallow-ignore-next-line complexityfunction applyUniforms(gl: WebGLRenderingContext,@@ -1235,18 +2469,25 @@ function applyUniforms(grading: NormalizedHfColorGrading,lut: RuntimeLutTexture | null,blurReady: boolean,+ bloomReady: boolean,+ kuwaharaReady: boolean,compare: RuntimeColorGradingCompareState,layout: { width: number; height: number },uv: { scaleX: number; scaleY: number; offsetX: number; offsetY: number },grainSeed: number,+ effectTime: number,): void {gl.uniform1i(program.source, 0);gl.uniform1i(program.blurSource, 1);gl.uniform1i(program.lut, 2);+ gl.uniform1i(program.kuwaharaSource, 3);+ gl.uniform1i(program.bloomSource, 4);gl.uniform2f(program.resolution, layout.width, layout.height);gl.uniform2f(program.uvScale, uv.scaleX, uv.scaleY);gl.uniform2f(program.uvOffset, uv.offsetX, uv.offsetY);gl.uniform1f(program.blurReady, blurReady ? 1 : 0);+ gl.uniform1f(program.bloomReady, bloomReady ? 1 : 0);+ gl.uniform1f(program.kuwaharaReady, kuwaharaReady ? 1 : 0);gl.uniform1f(program.lutEnabled, lut ? 1 : 0);gl.uniform1f(program.lutSize, lut?.size ?? 2);gl.uniform2f(program.lutTextureSize, lut?.textureWidth ?? 1, lut?.textureHeight ?? 1);@@ -1263,26 +2504,30 @@ function applyUniforms(lut?.domainMax[2] ?? 1,);gl.uniform1f(program.lutIntensity, grading.lut?.intensity ?? 0);- gl.uniform1f(program.exposure, grading.adjust.exposure);- gl.uniform1f(program.contrast, grading.adjust.contrast);- gl.uniform1f(program.highlights, grading.adjust.highlights);- gl.uniform1f(program.shadows, grading.adjust.shadows);- gl.uniform1f(program.whites, grading.adjust.whites);- gl.uniform1f(program.blacks, grading.adjust.blacks);- gl.uniform1f(program.temperature, grading.adjust.temperature);- gl.uniform1f(program.tint, grading.adjust.tint);- gl.uniform1f(program.vibrance, grading.adjust.vibrance);- gl.uniform1f(program.saturation, grading.adjust.saturation);- gl.uniform1f(program.vignette, grading.details.vignette);- gl.uniform1f(program.vignetteMidpoint, grading.details.vignetteMidpoint);- gl.uniform1f(program.vignetteRoundness, grading.details.vignetteRoundness);- gl.uniform1f(program.vignetteFeather, grading.details.vignetteFeather);- gl.uniform1f(program.grain, grading.details.grain);- gl.uniform1f(program.grainSize, grading.details.grainSize);- gl.uniform1f(program.grainRoughness, grading.details.grainRoughness);+ for (const [key, location] of program.adjustUniforms) {+ gl.uniform1f(location, grading.adjust[key]);+ }+ for (const [key, location] of program.detailUniforms) {+ gl.uniform1f(location, grading.details[key]);+ }gl.uniform1f(program.grainSeed, grainSeed);- gl.uniform1f(program.blur, grading.effects.blur);- gl.uniform1f(program.pixelate, grading.effects.pixelate);+ gl.uniform1f(program.effectTime, effectTime);+ for (const [key, location] of program.effectUniforms) {+ gl.uniform1f(location, grading.effects[key]);+ }+ const palette =+ grading.palette ??+ (grading.effects.engraving > 0 || grading.effects.crosshatch > 0+ ? DEFAULT_ART_PALETTE+ : DEFAULT_EFFECT_PALETTE);+ const lastColor = palette[palette.length - 1] ?? DEFAULT_EFFECT_PALETTE[1];+ gl.uniform1f(program.paletteSize, palette.length);+ setPaletteColorUniform(gl, program.palette0, palette[0] ?? DEFAULT_EFFECT_PALETTE[0]);+ setPaletteColorUniform(gl, program.palette1, palette[1] ?? lastColor);+ setPaletteColorUniform(gl, program.palette2, palette[2] ?? lastColor);+ setPaletteColorUniform(gl, program.palette3, palette[3] ?? lastColor);+ setPaletteColorUniform(gl, program.palette4, palette[4] ?? lastColor);+ setPaletteColorUniform(gl, program.palette5, palette[5] ?? lastColor);gl.uniform1f(program.intensity, grading.intensity);gl.uniform1f(program.compareEnabled, compare.enabled ? 1 : 0);gl.uniform1f(program.comparePosition, compare.position);@@ -1312,6 +2557,122 @@ function hideSourceElement(entry: ColorGradingEntry): void {entry.sourceHidden = true;}+type AnimatedProperty = {+ name: string;+ min: number;+ max: number;+};++function animatedProperty(path: HfColorGradingAnimatablePath): AnimatedProperty {+ const property = HF_COLOR_GRADING_ANIMATABLE_PROPERTIES.find(+ (candidate) => candidate.path === path,+ );+ if (!property) throw new Error(`Missing color-grading animation property: ${path}`);+ return property;+}++const ANIMATED_INTENSITY_PROPERTY = animatedProperty("intensity");+const ANIMATED_LUT_INTENSITY_PROPERTY = animatedProperty("lut.intensity");+const ANIMATED_EXPOSURE_PROPERTY = animatedProperty("adjust.exposure");+const ANIMATED_KUWAHARA_PROPERTY = animatedProperty("effects.kuwahara");+const ANIMATED_EFFECT_PROPERTIES = [+ ["blur", animatedProperty("effects.blur")],+ ["bloom", animatedProperty("effects.bloom")],+ ["kuwahara", ANIMATED_KUWAHARA_PROPERTY],+ ["pixelate", animatedProperty("effects.pixelate")],+ ["ascii", animatedProperty("effects.ascii")],+ ["dither", animatedProperty("effects.dither")],+] as const satisfies readonly (readonly [HfColorGradingEffectKey, AnimatedProperty])[];+const ANIMATED_GRADING_PROPERTIES = [+ ANIMATED_INTENSITY_PROPERTY,+ ANIMATED_LUT_INTENSITY_PROPERTY,+ ANIMATED_EXPOSURE_PROPERTY,+ ...ANIMATED_EFFECT_PROPERTIES.map(([, property]) => property),+];++function readAnimatedValue(element: HTMLElement, property: AnimatedProperty): number | null {+ const raw = element.style.getPropertyValue(property.name);+ if (!raw) return null;+ const value = Number(raw);+ return Number.isFinite(value) ? Math.min(property.max, Math.max(property.min, value)) : null;+}++function isRuntimeColorGradingActive(+ element: ColorGradingMediaElement,+ grading: NormalizedHfColorGrading | null,+): grading is NormalizedHfColorGrading {+ return (+ grading !== null &&+ (isHfColorGradingActive(grading) ||+ ANIMATED_GRADING_PROPERTIES.some((property) => readAnimatedValue(element, property) !== null))+ );+}++function readAnimatedEffects(+ element: HTMLElement,+ grading: NormalizedHfColorGrading,+): NormalizedHfColorGrading["effects"] | null {+ let effects: NormalizedHfColorGrading["effects"] | null = null;+ for (const [key, property] of ANIMATED_EFFECT_PROPERTIES) {+ const value = readAnimatedValue(element, property);+ if (value === null) continue;+ effects ??= { ...grading.effects };+ effects[key] = value;+ }+ return effects;+}++function readAnimatedGrading(entry: ColorGradingEntry): NormalizedHfColorGrading {+ const { element, grading } = entry;+ const intensity = readAnimatedValue(element, ANIMATED_INTENSITY_PROPERTY);+ const lutIntensity = readAnimatedValue(element, ANIMATED_LUT_INTENSITY_PROPERTY);+ const exposure = readAnimatedValue(element, ANIMATED_EXPOSURE_PROPERTY);+ const effects = readAnimatedEffects(element, grading);+ const hasDirectOverride = [intensity, lutIntensity, exposure].some((value) => value !== null);+ if (!hasDirectOverride && effects === null) {+ return grading;+ }+ const animated = {+ ...grading,+ adjust: exposure === null ? grading.adjust : { ...grading.adjust, exposure },+ effects: effects ?? grading.effects,+ };+ if (intensity !== null) animated.intensity = intensity;+ if (grading.lut && lutIntensity !== null) {+ animated.lut = { ...grading.lut, intensity: lutIntensity };+ }+ return animated;+}++function uploadSourceTexture(+ gl: WebGLRenderingContext,+ texture: WebGLTexture,+ source: TexImageSource,+): void {+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);+}++function bindProgramTextures(+ gl: WebGLRenderingContext,+ program: ProgramInfo,+ prepared: PreparedEffectTextures,+): void {+ const textures = [+ program.texture,+ prepared.blurTexture,+ program.lutTexture,+ prepared.kuwaharaTexture,+ prepared.bloomTexture,+ ];+ for (const [unit, texture] of textures.entries()) {+ gl.activeTexture(gl.TEXTURE0 + unit);+ gl.bindTexture(gl.TEXTURE_2D, texture);+ }+}+// fallow-ignore-next-line complexityfunction drawEntry(entry: ColorGradingEntry): boolean {if (entry.destroyed || entry.contextLost) return false;@@ -1350,60 +2711,44 @@ function drawEntry(entry: ColorGradingEntry): boolean {);const { gl, program } = entry;try {+ const grading = readAnimatedGrading(entry);const lut = ensureEntryLut(entry);- gl.activeTexture(gl.TEXTURE0);- gl.bindTexture(gl.TEXTURE_2D, program.texture);// Browser media elements are top-left oriented; WebGL texture coordinates// are bottom-left oriented unless the upload is flipped.- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);-- let blurReady = false;- const blurAmount = Math.min(1, Math.max(0, entry.grading.effects.blur));- if (blurAmount > 0) {- // If framebuffer setup fails, keep the non-blur shader path alive and surface status.- const targets = ensureEffectTargets(entry);- if (targets) {- const blurLayout = resizeEffectTargetPair(- gl,- targets.scratch,- targets.blur,- layout.width,- layout.height,- );- renderGaussianTexture(- gl,- targets,- program.texture,- targets.blur,- blurLayout,- 0.75 + Math.pow(blurAmount, 1.35) * 32,- blurAmount > 0.55 ? 3 : 2,- );- blurReady = true;- }- } else {- entry.effectError = null;- if (entry.effectTargets) destroyEffectTargets(entry);- }+ uploadSourceTexture(gl, program.texture, source);+ const hasAnimatedKuwahara =+ readAnimatedValue(entry.element, ANIMATED_KUWAHARA_PROPERTY) !== null;+ const prepared = prepareEffectTextures(entry, grading, layout, uv, {+ preserveKuwahara: hasAnimatedKuwahara,+ });gl.bindFramebuffer(gl.FRAMEBUFFER, null);gl.viewport(0, 0, layout.width, layout.height);gl.useProgram(program.program);- gl.activeTexture(gl.TEXTURE0);- gl.bindTexture(gl.TEXTURE_2D, program.texture);- gl.activeTexture(gl.TEXTURE1);- gl.bindTexture(gl.TEXTURE_2D, entry.effectTargets?.blur.texture ?? program.texture);- gl.activeTexture(gl.TEXTURE2);- gl.bindTexture(gl.TEXTURE_2D, program.lutTexture);- const grainSeed =- entry.grainSeed +- (entry.element instanceof HTMLVideoElement ? Math.floor(entry.element.currentTime * 60) : 0);- applyUniforms(gl, program, entry.grading, lut, blurReady, entry.compare, layout, uv, grainSeed);- gl.bindBuffer(gl.ARRAY_BUFFER, program.quad);- gl.enableVertexAttribArray(program.position);- gl.vertexAttribPointer(program.position, 2, gl.FLOAT, false, 0, 0);- gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);+ bindProgramTextures(gl, program, prepared);+ const runtimeTime = (window as WindowWithColorGrading).__player?.getTime?.();+ const frameTime =+ typeof runtimeTime === "number" && Number.isFinite(runtimeTime)+ ? Math.max(0, runtimeTime)+ : entry.element instanceof HTMLVideoElement+ ? Math.max(0, entry.element.currentTime)+ : 0;+ const grainSeed = entry.grainSeed + Math.floor(frameTime * 60);+ applyUniforms(+ gl,+ program,+ grading,+ lut,+ prepared.blurReady,+ prepared.bloomReady,+ prepared.kuwaharaReady,+ entry.compare,+ layout,+ uv,+ grainSeed,+ frameTime,+ );+ drawFullscreenQuad(gl, program);hideSourceElement(entry);entry.hasDrawn = true;entry.drawError = null;@@ -1415,6 +2760,173 @@ function drawEntry(entry: ColorGradingEntry): boolean {}}+function previewDimensions(+ element: ColorGradingMediaElement,+ sourceSize: { width: number; height: number },+ rawMaxDimension: number | undefined,+): { width: number; height: number } {+ const rect = element.getBoundingClientRect();+ const boxWidth = element.offsetWidth || rect.width || sourceSize.width;+ const boxHeight = element.offsetHeight || rect.height || sourceSize.height;+ const maxDimension = Math.min(320, Math.max(64, Math.round(rawMaxDimension ?? 160)));+ const aspect =+ boxWidth > 0 && boxHeight > 0 ? boxWidth / boxHeight : sourceSize.width / sourceSize.height;+ return aspect >= 1+ ? { width: maxDimension, height: Math.max(1, Math.round(maxDimension / aspect)) }+ : { width: Math.max(1, Math.round(maxDimension * aspect)), height: maxDimension };+}++function createPreviewRenderer(): ColorGradingPreviewRenderer | null {+ const canvas = document.createElement("canvas");+ const created = createProgramInfo(canvas);+ return created+ ? {+ canvas,+ ...created,+ lut: null,+ effectTargets: null,+ kuwaharaTargets: null,+ effectError: null,+ }+ : null;+}++interface PreviewFrame {+ dimensions: { width: number; height: number };+ uv: { scaleX: number; scaleY: number; offsetX: number; offsetY: number };+ grainSeed: number;+ effectTime: number;+}++function previewEffectTime(element: ColorGradingMediaElement, useMediaTime: boolean): number {+ const runtimeTime = useMediaTime+ ? undefined+ : (window as WindowWithColorGrading).__player?.getTime?.();+ if (typeof runtimeTime === "number" && Number.isFinite(runtimeTime)) {+ return Math.max(0, runtimeTime);+ }+ return element instanceof HTMLVideoElement ? Math.max(0, element.currentTime) : 0;+}++function preparePreviewFrame(+ renderer: ColorGradingPreviewRenderer,+ element: ColorGradingMediaElement,+ maxDimension: number | undefined,+ useMediaTime: boolean,+): PreviewFrame | null {+ const source = getDrawableSource(element);+ if (!source) return null;+ const sourceSize = readSourceSize(source);+ if (!sourceSize) return null;+ const dimensions = previewDimensions(element, sourceSize, maxDimension);+ renderer.canvas.width = dimensions.width;+ renderer.canvas.height = dimensions.height;+ const styleSource = source instanceof HTMLElement ? source : element;+ const style = window.getComputedStyle(styleSource);+ const uv = calculateObjectFitUv(+ dimensions.width,+ dimensions.height,+ sourceSize.width,+ sourceSize.height,+ style.objectFit,+ style.objectPosition,+ );+ uploadSourceTexture(renderer.gl, renderer.program.texture, source);+ return {+ dimensions,+ uv,+ effectTime: previewEffectTime(element, useMediaTime),+ grainSeed:+ seedForElement(element) ++ (element instanceof HTMLVideoElement ? Math.floor(element.currentTime * 60) : 0),+ };+}++async function renderPreviewBatch(+ renderer: ColorGradingPreviewRenderer,+ element: ColorGradingMediaElement,+ candidates: readonly RuntimeColorGradingPreviewCandidate[],+ maxDimension: number | undefined,+ useMediaTime = false,+): Promise<RuntimeColorGradingPreviewBatch | null> {+ const frame = preparePreviewFrame(renderer, element, maxDimension, useMediaTime);+ if (!frame) return null;+ const { dimensions, uv, grainSeed, effectTime } = frame;+ const images: RuntimeColorGradingPreviewBatch["images"] = [];++ for (const candidate of candidates.slice(0, 32)) {+ const grading = normalizeHfColorGrading(candidate.grading);+ if (!grading) {+ images.push({ id: candidate.id, dataUrl: null, error: "Invalid grading" });+ continue;+ }+ let lut: RuntimeLutTexture | null = null;+ try {+ if (grading.lut) {+ if (renderer.lut?.src !== grading.lut.src) {+ renderer.lut = uploadPreviewLut(+ renderer,+ grading.lut.src,+ await loadCubeLut(grading.lut.src),+ );+ }+ lut = renderer.lut;+ }+ images.push({+ id: candidate.id,+ dataUrl: renderPreviewCandidate(+ renderer,+ grading,+ lut,+ dimensions,+ uv,+ grainSeed,+ effectTime,+ ),+ });+ } catch (err) {+ images.push({ id: candidate.id, dataUrl: null, error: errorMessage(err) });+ }+ }+ return { ...dimensions, images };+}++function renderPreviewCandidate(+ renderer: ColorGradingPreviewRenderer,+ grading: NormalizedHfColorGrading,+ lut: RuntimeLutTexture | null,+ dimensions: { width: number; height: number },+ uv: { scaleX: number; scaleY: number; offsetX: number; offsetY: number },+ grainSeed: number,+ effectTime: number,+): string {+ const { canvas, gl, program } = renderer;+ const prepared = prepareEffectTextures(renderer, grading, dimensions, uv, {+ releaseIdleTargets: false,+ });+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);+ gl.viewport(0, 0, dimensions.width, dimensions.height);+ gl.useProgram(program.program);+ bindProgramTextures(gl, program, prepared);+ if (!lut) renderer.lut = null;+ applyUniforms(+ gl,+ program,+ grading,+ lut,+ prepared.blurReady,+ prepared.bloomReady,+ prepared.kuwaharaReady,+ DEFAULT_COMPARE,+ dimensions,+ uv,+ grainSeed,+ effectTime,+ );+ drawFullscreenQuad(gl, program);+ return canvas.toDataURL("image/png");+}+function addListener(entry: ColorGradingEntry,target: EventTarget,@@ -1521,15 +3033,16 @@ function installEntryListeners(entry: ColorGradingEntry): void {}}-function destroyEntry(entry: ColorGradingEntry): void {- if (entry.destroyed) return;+function detachEntry(entry: ColorGradingEntry): ColorGradingRenderer | null {+ if (entry.destroyed) return null;entry.destroyed = true;cancelScheduledFrame(entry);entry.resizeObserver?.disconnect();for (const cleanup of entry.cleanup) cleanup();entry.cleanup.length = 0;entry.canvas.remove();- destroyProgramResources(entry);+ destroyEffectTargets(entry);+ destroyKuwaharaTargets(entry);restoreSourceElement(entry);if (entry.touchedParent) {if (entry.parentInlinePosition === null) {@@ -1538,11 +3051,23 @@ function destroyEntry(entry: ColorGradingEntry): void {entry.touchedParent.style.position = entry.parentInlinePosition;}}+ return {+ canvas: entry.canvas,+ gl: entry.gl,+ program: entry.program,+ effectTargets: null,+ kuwaharaTargets: null,+ effectError: null,+ };}-function makeCanvas(element: ColorGradingMediaElement): HTMLCanvasElement {- const canvas = document.createElement("canvas");+function attachCanvas(+ canvas: HTMLCanvasElement,+ element: ColorGradingMediaElement,+): HTMLCanvasElement {+ canvas.removeAttribute("style");if (element.id) canvas.id = `${HF_COLOR_GRADING_CANVAS_ID_PREFIX}${element.id}`;+ else canvas.removeAttribute("id");canvas.className = COLOR_GRADING_CANVAS_CLASS;canvas.setAttribute(COLOR_GRADING_CANVAS_ATTR, "true");canvas.setAttribute("data-hyperframes-ignore", "");@@ -1555,10 +3080,16 @@ function makeCanvas(element: ColorGradingMediaElement): HTMLCanvasElement {return canvas;}+function makeCanvas(element: ColorGradingMediaElement): HTMLCanvasElement {+ return attachCanvas(document.createElement("canvas"), element);+}+export function createColorGradingRuntime(): RuntimeColorGradingApi {const entries = new WeakMap<ColorGradingMediaElement, ColorGradingEntry>();const trackedElements = new Set<ColorGradingMediaElement>();+ const idleRenderers: ColorGradingRenderer[] = [];let observer: MutationObserver | null = null;+ let previewRenderer: ColorGradingPreviewRenderer | null = null;let destroyed = false;const upsert = (@@ -1574,17 +3105,28 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {if (element instanceof HTMLVideoElement && !element.paused) scheduleVideoDraw(existing);return true;}- const canvas = makeCanvas(element);- const created = createProgramInfo(canvas);- if (!created) {- canvas.remove();- return false;+ let renderer = idleRenderers.pop();+ if (renderer) {+ attachCanvas(renderer.canvas, element);+ } else {+ const canvas = makeCanvas(element);+ const created = createProgramInfo(canvas);+ if (!created) {+ canvas.remove();+ return false;+ }+ renderer = {+ canvas,+ gl: created.gl,+ program: created.program,+ effectTargets: null,+ kuwaharaTargets: null,+ effectError: null,+ };}const entry: ColorGradingEntry = {element,- canvas,- gl: created.gl,- program: created.program,+ ...renderer,grading,compare: { ...DEFAULT_COMPARE },lut: null,@@ -1592,6 +3134,7 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {lutError: null,drawError: null,effectTargets: null,+ kuwaharaTargets: null,effectError: null,source,animationFrame: null,@@ -1628,7 +3171,12 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {let entry = entries.get(element);if (!entry) {const grading = readColorGradingAttribute(element);- if (!isHfColorGradingActive(grading) || !upsert(element, grading, "attribute")) return false;+ if (+ !isRuntimeColorGradingActive(element, grading) ||+ !upsert(element, grading, "attribute")+ ) {+ return false;+ }entry = entries.get(element);}if (!entry) return false;@@ -1640,7 +3188,14 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {const removeElement = (element: ColorGradingMediaElement): void => {const entry = entries.get(element);if (!entry) return;- destroyEntry(entry);+ const renderer = detachEntry(entry);+ if (renderer) {+ if (entry.contextLost || idleRenderers.length >= MAX_IDLE_COLOR_GRADING_RENDERERS) {+ destroyProgramResources(renderer, true);+ } else {+ idleRenderers.push(renderer);+ }+ }entries.delete(element);trackedElements.delete(element);};@@ -1655,13 +3210,17 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {if (!isColorGradingMediaElement(node)) return;attributeElements.add(node);const grading = readColorGradingAttribute(node);- if (isHfColorGradingActive(grading)) {- upsert(node, grading, "attribute");+ if (isRuntimeColorGradingActive(node, grading)) {+ if (isVisibleForColorGrading(node) || hasInjectedRenderFrame(node)) {+ upsert(node, grading, "attribute");+ } else {+ removeElement(node);+ }} else {removeElement(node);}});- for (const element of Array.from(trackedElements)) {+ for (const element of trackedElements) {const entry = entries.get(element);if (!entry) continue;if (@@ -1677,8 +3236,41 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {const redraw = (): number => {if (destroyed) return 0;let drawn = 0;- for (const entry of Array.from(trackedElements, (element) => entries.get(element))) {- if (entry && drawEntry(entry)) drawn += 1;+ for (const element of trackedElements) {+ const entry = entries.get(element);+ if (!entry) continue;+ if (drawEntry(entry)) drawn += 1;+ }+ return drawn;+ };++ const waitForActiveLuts = async (): Promise<number> => {+ const pending = new Set<Promise<CubeLut3D>>();+ for (const element of trackedElements) {+ const lut = entries.get(element)?.grading.lut;+ if (!lut?.src.trim() || (lut.intensity ?? 1) <= 0) continue;+ const cached = getCubeLut(lut.src);+ if (cached.state === "pending") pending.add(cached.promise);+ }+ if (pending.size > 0) await Promise.allSettled(pending);+ // Capture awaits this method after every seek; this paint is required even+ // when no LUT is pending so the screenshot receives the current frame.+ redraw();+ return pending.size;+ };++ const redrawAnimated = (): number => {+ if (destroyed) return 0;+ let drawn = 0;+ for (const element of trackedElements) {+ const entry = entries.get(element);+ if (!entry) continue;+ const hasAnimatedProperty = ANIMATED_GRADING_PROPERTIES.some(+ (property) => readAnimatedValue(element, property) !== null,+ );+ if (!hasAnimatedProperty) continue;+ if (element instanceof HTMLVideoElement && !element.paused && !element.ended) continue;+ if (drawEntry(entry)) drawn += 1;}return drawn;};@@ -1691,7 +3283,7 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {const element = resolveTarget(target);if (!element) return false;const grading = normalizeHfColorGrading(rawGrading);- if (!isHfColorGradingActive(grading)) {+ if (!isRuntimeColorGradingActive(element, grading)) {removeElement(element);return true;}@@ -1701,8 +3293,15 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {const setSourceVisibility = (target: Element, visible: boolean): boolean => {if (!isColorGradingMediaElement(target)) return false;const entry = entries.get(target);- if (!entry) return false;+ if (!entry) {+ if (!visible) return false;+ const grading = readColorGradingAttribute(target);+ return isRuntimeColorGradingActive(target, grading) && upsert(target, grading, "attribute");+ }entry.sourceVisibleForCanvas = visible;+ if (!visible && entry.source === "attribute") {+ removeElement(target);+ }return true;};@@ -1735,18 +3334,69 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {};}const grading = readColorGradingAttribute(element);- if (isHfColorGradingActive(grading)) {+ if (isRuntimeColorGradingActive(element, grading)) {+ if (!isVisibleForColorGrading(element) && !hasInjectedRenderFrame(element)) {+ return { state: "pending", message: "Waiting for visible media" };+ }return { state: "unavailable", message: "WebGL unavailable" };}return { state: "inactive", message: "No grading applied" };};+ const renderPreviews = async (+ target: HfColorGradingTarget | string | null | undefined,+ candidates: readonly RuntimeColorGradingPreviewCandidate[],+ options?: { maxDimension?: number; useMediaTime?: boolean },+ ): Promise<RuntimeColorGradingPreviewBatch | null> => {+ if (destroyed || candidates.length === 0) return null;+ const element = resolveTarget(target);+ if (!element) return null;+ previewRenderer ??= createPreviewRenderer();+ if (!previewRenderer) return null;+ return renderPreviewBatch(+ previewRenderer,+ element,+ candidates,+ options?.maxDimension,+ options?.useMediaTime,+ );+ };++ const startPreviewPlayback = (+ target: HfColorGradingTarget | string | null | undefined,+ ): (() => void) | null => {+ const element = resolveTarget(target);+ if (!(element instanceof HTMLVideoElement)) return null;+ if (!element.paused) return () => undefined;+ const time = element.currentTime;+ const loop = element.loop;+ const muted = element.muted;+ element.loop = true;+ element.muted = true;+ if (element.ended || (Number.isFinite(element.duration) && time >= element.duration)) {+ element.currentTime = 0;+ }+ void element.play().catch(() => undefined);+ return () => {+ element.pause();+ element.loop = loop;+ element.muted = muted;+ element.currentTime = time;+ };+ };+const destroy = (): void => {if (destroyed) return;destroyed = true;observer?.disconnect();observer = null;- for (const element of Array.from(trackedElements)) removeElement(element);+ for (const element of trackedElements) removeElement(element);+ for (const renderer of idleRenderers) destroyProgramResources(renderer, true);+ idleRenderers.length = 0;+ if (previewRenderer) {+ destroyProgramResources(previewRenderer, true);+ previewRenderer = null;+ }};if (document.body) {@@ -1762,10 +3412,14 @@ export function createColorGradingRuntime(): RuntimeColorGradingApi {const api: RuntimeColorGradingApi = {refresh,redraw,+ redrawAnimated,+ waitForActiveLuts,setGrading,setCompare,setSourceVisibility,getStatus,+ renderPreviews,+ startPreviewPlayback,destroy,};const win = window as WindowWithColorGrading;diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.tsindex 8cbde87b53..3087aac7a9 100644--- a/packages/core/src/runtime/init.test.ts+++ b/packages/core/src/runtime/init.test.ts@@ -1320,6 +1320,53 @@ describe("initSandboxRuntimeModular", () => {expect(video.style.visibility).toBe("hidden");});+ it("allocates color grading only for the active timed media", () => {+ const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);+ const root = document.createElement("div");+ root.setAttribute("data-composition-id", "main");+ root.setAttribute("data-root", "true");+ root.setAttribute("data-start", "0");+ root.setAttribute("data-duration", "4");+ root.setAttribute("data-width", "1920");+ root.setAttribute("data-height", "1080");+ document.body.appendChild(root);++ const futureComposition = document.createElement("div");+ futureComposition.id = "future-composition";+ futureComposition.setAttribute("data-start", "2");+ root.appendChild(futureComposition);++ for (const [id, start] of [+ ["first", "0"],+ ["second", "2"],+ ]) {+ const video = document.createElement("video");+ video.id = id;+ video.setAttribute("data-start", start);+ video.setAttribute("data-duration", "2");+ video.setAttribute("data-color-grading", '{"adjust":{"exposure":0.1}}');+ Object.defineProperty(video, "paused", { value: true, configurable: true });+ Object.defineProperty(video, "readyState", { value: 0, configurable: true });+ video.load = () => {};+ root.appendChild(video);+ }++ window.__timelines = { main: createMockTimeline(4) };+ initSandboxRuntimeModular();++ expect(getContextSpy).toHaveBeenCalledTimes(1);+ expect(document.getElementById("first")?.style.visibility).toBe("visible");+ expect(document.getElementById("second")?.style.visibility).toBe("hidden");+ expect(futureComposition.style.visibility).toBe("");+ expect(futureComposition.style.display).toBe("");++ window.__player?.seek(3);++ expect(getContextSpy).toHaveBeenCalledTimes(2);+ expect(document.getElementById("first")?.style.visibility).toBe("hidden");+ expect(document.getElementById("second")?.style.visibility).toBe("visible");+ });+it("plays scheduled child timelines without a captured root timeline when audio has failed", () => {const raf = createManualRaf();vi.spyOn(performance, "now").mockImplementation(() => raf.now());@@ -2122,6 +2169,36 @@ describe("initSandboxRuntimeModular", () => {expect(seekTimes.length).toBeGreaterThan(beforeResume);});+ it("redraws animated grading from the transport clock only during playback", () => {+ const raf = createManualRaf();+ vi.spyOn(performance, "now").mockImplementation(() => raf.now());+ window.requestAnimationFrame = raf.requestAnimationFrame as typeof window.requestAnimationFrame;+ window.cancelAnimationFrame = raf.cancelAnimationFrame as typeof window.cancelAnimationFrame;++ document.body.innerHTML = `+ <div data-composition-id="root" data-duration="5" data-width="1920" data-height="1080"></div>+ `;+ window.__timelines = { root: createMockTimeline(5) };+ initSandboxRuntimeModular();++ const runtime = (+ window as Window & { __hf?: { colorGrading?: { redrawAnimated: () => number } } }+ ).__hf?.colorGrading;+ if (!runtime) throw new Error("Expected color grading runtime");+ const redrawAnimated = vi.spyOn(runtime, "redrawAnimated");++ raf.step(16);+ expect(redrawAnimated).not.toHaveBeenCalled();++ window.__player?.play();+ raf.step(16);+ expect(redrawAnimated).toHaveBeenCalledTimes(1);++ window.__player?.pause();+ raf.step(16);+ expect(redrawAnimated).toHaveBeenCalledTimes(1);+ });+it("keeps a usable bound timeline when the registry entry is replaced", () => {const raf = createManualRaf();vi.spyOn(performance, "now").mockImplementation(() => raf.now());diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex 06e8a31d6c..4ba8108996 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -1793,8 +1793,10 @@ export function initSandboxRuntimeModular(): void {const dataHiddenDisplayRestores = new WeakMap<HTMLElement, string>();const dataHiddenDisplayNodes = new WeakSet<HTMLElement>();- const syncTimedElementVisibility = (currentTime: number) => {- const visibilityNodes = Array.from(document.querySelectorAll("[data-start]"));+ const syncTimedElementVisibility = (+ currentTime: number,+ visibilityNodes: Element[] = Array.from(document.querySelectorAll("[data-start]")),+ ) => {const rootComp = resolveRootCompositionElement();for (const rawNode of visibilityNodes) {if (!(rawNode instanceof HTMLElement)) continue;@@ -2174,6 +2176,10 @@ export function initSandboxRuntimeModular(): void {});picker.installPickerApi();+ syncTimedElementVisibility(+ state.currentTime,+ Array.from(document.querySelectorAll("video[data-start], img[data-start]")),+ );const colorGrading = createColorGradingRuntime();colorGradingRuntime = colorGrading;registerRuntimeCleanup(() => {@@ -2839,6 +2845,9 @@ export function initSandboxRuntimeModular(): void {if (clock.isPlaying() || !hasActiveStudioManualEditGesture()) {seekTimelineAndAdapters(t);}+ if (clock.isPlaying()) {+ colorGrading.redrawAnimated();+ }// Looping is handled at the player layer (<hyperframes-player>),// not the runtime. The clock pauses at duration; GSAP's repeat:-1diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.tsindex 0c7346dc7a..12b0d4f8da 100644--- a/packages/engine/src/services/frameCapture.ts+++ b/packages/engine/src/services/frameCapture.ts@@ -2356,6 +2356,14 @@ async function prepareFrameForCapture(if (session.onBeforeCapture) {await session.onBeforeCapture(page, quantizedTime);}+ await page.evaluate(async () => {+ const runtime = (+ window as Window & {+ __hf?: { colorGrading?: { waitForActiveLuts?: () => Promise<number> } };+ }+ ).__hf?.colorGrading;+ await runtime?.waitForActiveLuts?.();+ });const beforeCaptureMs = Date.now() - beforeCaptureStart;// Page-side compositing three-phase protocol:diff --git a/packages/engine/src/services/screenshotService.test.ts b/packages/engine/src/services/screenshotService.test.tsindex 28a2a1196f..ff459eed06 100644--- a/packages/engine/src/services/screenshotService.test.ts+++ b/packages/engine/src/services/screenshotService.test.ts@@ -181,9 +181,12 @@ describe("injectVideoFramesBatch replacement layout", () => {'<html><body><div id="root"><video id="clip" style="position:absolute;inset:0;width:100%;height:100%;object-fit:cover"></video></div></body></html>',);+ const events: string[] = [];Object.defineProperty(window.HTMLImageElement.prototype, "decode", {configurable: true,- value: () => Promise.resolve(),+ value: async () => {+ events.push("decode");+ },});const video = document.getElementById("clip") as HTMLVideoElement;@@ -232,6 +235,10 @@ describe("injectVideoFramesBatch replacement layout", () => {const previousDocument = globals.document;globals.window = window;globals.document = document;+ const redraw = vi.fn(() => events.push("redraw"));+ (window as unknown as { __hf: { colorGrading: { redraw: () => void } } }).__hf = {+ colorGrading: { redraw },+ };try {const page = {evaluate: async (@@ -266,6 +273,8 @@ describe("injectVideoFramesBatch replacement layout", () => {expect(img?.style.right).toBe("auto");expect(img?.style.bottom).toBe("auto");expect(img?.style.inset).toBe("auto");+ expect(redraw).toHaveBeenCalledOnce();+ expect(events).toEqual(["decode", "redraw"]);});});@@ -569,6 +578,10 @@ describe("video-frame injection respects ancestor visibility", () => {seededImg.classList.add("__render_frame__");seededImg.style.opacity = "0";setup.video.parentNode?.insertBefore(seededImg, setup.video.nextSibling);+ const setSourceVisibility = vi.fn();+ (setup.window as unknown as { __hf: unknown }).__hf = {+ colorGrading: { setSourceVisibility },+ };try {await syncVideoFrameVisibility(passthroughPage(), ["pip"]);@@ -578,6 +591,7 @@ describe("video-frame injection respects ancestor visibility", () => {expect(seededImg.style.opacity).toBe("1");expect(seededImg.style.visibility).toBe("visible");+ expect(setSourceVisibility).toHaveBeenCalledWith(setup.video, true);});it("syncVideoFrameVisibility shows the replacement <img> when a plain [data-start] host is visibility:hidden", async () => {@@ -643,6 +657,10 @@ describe("video-frame injection respects ancestor visibility", () => {seededImg.style.visibility = "visible";setup.video.parentNode?.insertBefore(seededImg, setup.video.nextSibling);const setPropertySpy = vi.spyOn(seededImg.style, "setProperty");+ const setSourceVisibility = vi.fn();+ (setup.window as unknown as { __hf: unknown }).__hf = {+ colorGrading: { setSourceVisibility },+ };try {await syncVideoFrameVisibility(passthroughPage(), ["pip"]);@@ -652,6 +670,7 @@ describe("video-frame injection respects ancestor visibility", () => {expect(seededImg.style.visibility).toBe("hidden");expect(setPropertySpy).toHaveBeenCalledWith("visibility", "hidden", "important");+ expect(setSourceVisibility).toHaveBeenCalledWith(setup.video, false);});it("applyDomLayerMask does not revive hidden idless timed descendants of a shown layer", async () => {diff --git a/packages/engine/src/services/screenshotService.ts b/packages/engine/src/services/screenshotService.tsindex fa5c521233..ae3abeaba6 100644--- a/packages/engine/src/services/screenshotService.ts+++ b/packages/engine/src/services/screenshotService.ts@@ -8,13 +8,13 @@// fallow-ignore-file code-duplicationimport { type Page } from "puppeteer-core";import { type CaptureOptions } from "../types.js";+import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "@hyperframes/core/color-grading";import {HF_COLOR_GRADING_CANVAS_ID_PREFIX,MEDIA_VISUAL_STYLE_PROPERTIES,} from "@hyperframes/core";export const cdpSessionCache = new WeakMap<Page, import("puppeteer-core").CDPSession>();-const COLOR_GRADING_SOURCE_HIDDEN_ATTR = "data-hf-color-grading-source-hidden";export async function getCdpSession(page: Page): Promise<import("puppeteer-core").CDPSession> {let client = cdpSessionCache.get(page);@@ -789,6 +789,11 @@ export async function injectVideoFramesBatch(if (pendingDecodes.length > 0) {await Promise.all(pendingDecodes);}+ if (injectedIds.length > 0) {+ const redraw = (window as Window & { __hf?: { colorGrading?: { redraw?: () => void } } })+ .__hf?.colorGrading?.redraw;+ redraw?.();+ }return injectedIds;},updates,@@ -825,6 +830,13 @@ export async function syncVideoFrameVisibility(return false;};const active = new Set(ids);+ const setColorGradingVisibility = (+ window as Window & {+ __hf?: {+ colorGrading?: { setSourceVisibility?: (target: Element, visible: boolean) => boolean };+ };+ }+ ).__hf?.colorGrading?.setSourceVisibility;const videos = Array.from(document.querySelectorAll("video[data-start]"),) as HTMLVideoElement[];@@ -832,7 +844,8 @@ export async function syncVideoFrameVisibility(const img = video.nextElementSibling as HTMLElement | null;const hasImg = img && img.classList.contains("__render_frame__");const ancestorHidden = isVisualAncestorHidden(video);- if (active.has(video.id) && !ancestorHidden) {+ const visible = active.has(video.id) && !ancestorHidden;+ if (visible) {// Active video: show injected <img>, hide native <video>.// Do NOT clobber inline opacity here — GSAP-controlled opacity must// survive until injectVideoFramesBatch reads it via getComputedStyle.@@ -859,6 +872,7 @@ export async function syncVideoFrameVisibility(img.style.setProperty("visibility", "hidden", "important");}}+ setColorGradingVisibility?.(video, visible);}},activeVideoIds,diff --git a/packages/engine/src/services/videoFrameInjector.ts b/packages/engine/src/services/videoFrameInjector.tsindex b9ed6d07fd..ca443e5c65 100644--- a/packages/engine/src/services/videoFrameInjector.ts+++ b/packages/engine/src/services/videoFrameInjector.ts@@ -148,25 +148,6 @@ function createFrameSourceCache(export const __testing = { createFrameSourceCache };-async function redrawRuntimeColorGrading(page: Page): Promise<void> {- await page.evaluate(() => {- const hf = (- window as Window & {- __hf?: {- colorGrading?: { redraw?: () => unknown };- };- }- ).__hf;- const redraw = hf?.colorGrading?.redraw;- if (typeof redraw !== "function") return;- try {- redraw();- } catch {- // Optional page-side shader layer.- }- });-}-/*** Creates a BeforeCaptureHook that injects pre-extracted video frames* into the page, replacing native <video> elements with frame images.@@ -248,7 +229,6 @@ export function createVideoFrameInjector(}, time);}}- await redrawRuntimeColorGrading(page);};}diff --git a/packages/lint/src/rules/media.test.ts b/packages/lint/src/rules/media.test.tsindex 3be4187a2d..49ad5768d9 100644--- a/packages/lint/src/rules/media.test.ts+++ b/packages/lint/src/rules/media.test.ts@@ -81,6 +81,114 @@ describe("media rules", () => {expect(finding).toBeUndefined();});+ it("reports grading controls placed outside their schema sections", async () => {+ const html = `+<html><body>+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">+ <video id="v1" data-start="0" data-duration="5" src="clip.mp4" muted data-color-grading='{"preset":"skin-soft","intensity":0.58,"highlights":-0.06,"temperature":0.02}'></video>+ </div>+ <script>window.__timelines = {};</script>+</body></html>`;+ const result = await lintHyperframeHtml(html);+ const finding = result.findings.find((f) => f.code === "color_grading_invalid_structure");+ expect(finding?.severity).toBe("error");+ expect(finding?.message).toContain("highlights");+ expect(finding?.fixHint).toContain('"adjust"');+ });++ it("accepts grading controls inside their schema sections", async () => {+ const html = `+<html><body>+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">+ <video id="v1" data-start="0" data-duration="5" src="clip.mp4" muted data-color-grading='{"preset":"skin-soft","intensity":0.58,"adjust":{"highlights":-0.06,"temperature":0.02},"details":{"vignette":0.03},"effects":{"blur":0.1,"chromaBleed":0.2,"tapeDamage":0.3,"tapeTracking":0.4,"tapeNoise":0.5,"tapeSpeed":0.6,"filmArtifacts":0.4,"halftone":0.5,"halftoneSize":0.6,"twoInkPrint":0.7,"twoInkPrintSize":0.8,"ascii":0.9,"asciiSize":0.4,"asciiInvert":1,"dither":0.8,"ditherSize":0.3,"bloom":0.5,"bloomRadius":8,"asciiStyle":4,"asciiColor":1,"asciiRotation":1,"monoScreen":0.5,"monoScreenSize":0.4,"monoScreenAngle":0.3,"monoScreenSpread":0.2,"monoScreenShape":3,"monoScreenInvert":1,"scanlines":0.3,"scanlineCount":0.4,"scanlineSoftness":0.5,"chromaticAberration":0.2,"chromaticAngle":0.6,"crtCurvature":0.25,"digitalGlitch":0.4,"digitalGlitchColorSplit":0.45,"digitalGlitchLineTear":0.5,"digitalGlitchPixelate":0.55,"digitalGlitchBlockAmount":0.6,"digitalGlitchBlockDisplacement":0.7,"digitalGlitchBlockOpacity":0.2,"digitalGlitchSpeed":0.7,"engraving":1,"engravingSpacing":0.4117647,"engravingMinThickness":0.2,"engravingMaxThickness":0.4571429,"engravingAngle":0.25,"engravingContrast":0.4666667,"engravingSharpness":0.59,"engravingWave":0.2,"engravingWaveFrequency":0.2222222},"palette":["#ff6b66","#080717","#d9339f","#3c185f"],"lut":null}'></video>+ </div>+ <script>window.__timelines = {};</script>+</body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(result.findings.find((f) => f.code.startsWith("color_grading_"))).toBeUndefined();+ });++ it("accepts crosshatch controls in the effects section", async () => {+ const html = `+<html><body>+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">+ <video data-start="0" data-duration="5" src="clip.mp4" muted data-color-grading='{"effects":{"crosshatch":1,"crosshatchSpacing":0.28,"crosshatchThickness":0.25,"crosshatchAngle":0.25,"crosshatchContrast":0.3333333,"crosshatchEdges":0.5,"crosshatchLineWeight":0,"crosshatchWave":0.33,"crosshatchWaveFrequency":0.2222222}}'></video>+ </div>+ <script>window.__timelines = {};</script>+</body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(result.findings.find((f) => f.code.startsWith("color_grading_"))).toBeUndefined();+ });++ it("accepts Kuwahara controls in the effects section", async () => {+ const html = `+<html><body>+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">+ <video data-start="0" data-duration="5" src="clip.mp4" muted data-color-grading='{"effects":{"kuwahara":1,"kuwaharaRadius":0.142857,"kuwaharaSharpness":0.3125,"kuwaharaSaturation":0.5}}'></video>+ </div>+ <script>window.__timelines = {};</script>+</body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(result.findings.find((f) => f.code.startsWith("color_grading_"))).toBeUndefined();+ });++ it("reports malformed or out-of-range color grading palettes", async () => {+ const html = `+<html><body>+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">+ <video id="v1" data-start="0" data-duration="5" src="clip.mp4" muted data-color-grading='{"effects":{"dither":1},"palette":["#000000","red"]}'></video>+ </div>+ <script>window.__timelines = {};</script>+</body></html>`;+ const result = await lintHyperframeHtml(html);+ const finding = result.findings.find((f) => f.code === "color_grading_invalid_structure");+ expect(finding?.severity).toBe("error");+ expect(finding?.fixHint).toContain("2 to 6");+ expect(finding?.fixHint).toContain("#RRGGBB");+ });++ it("reports malformed grading JSON", async () => {+ const html = `+<html><body>+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">+ <video id="v1" data-start="0" data-duration="5" src="clip.mp4" muted data-color-grading='{"preset":"skin-soft"'></video>+ </div>+ <script>window.__timelines = {};</script>+</body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(result.findings.find((f) => f.code === "color_grading_invalid_json")?.severity).toBe(+ "error",+ );+ });++ it("reports invalid string values for structured grading sections", async () => {+ const html = `+<html><body>+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">+ <video id="v1" data-start="0" data-duration="5" src="clip.mp4" muted data-color-grading='{"adjust":"cinematic"}'></video>+ </div>+ <script>window.__timelines = {};</script>+</body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(+ result.findings.find((f) => f.code === "color_grading_invalid_structure")?.severity,+ ).toBe("error");+ });++ it("reports color grading on non-media elements", async () => {+ const html = `+<html><body>+ <div id="root" data-composition-id="c1" data-width="1920" data-height="1080">+ <div id="background" data-color-grading='{"preset":"skin-soft"}'></div>+ </div>+ <script>window.__timelines = {};</script>+</body></html>`;+ const result = await lintHyperframeHtml(html);+ expect(result.findings.find((f) => f.code === "color_grading_non_media")?.severity).toBe(+ "error",+ );+ });+it("reports warning for media with preload=none", async () => {const html = `<html><body>diff --git a/packages/lint/src/rules/media.ts b/packages/lint/src/rules/media.tsindex 8e14fc4df4..3084d4ce77 100644--- a/packages/lint/src/rules/media.ts+++ b/packages/lint/src/rules/media.ts@@ -1,5 +1,6 @@import type { LintContext, HyperframeLintFinding } from "../context";import { readAttr, readDecodedAttr, truncateSnippet, isMediaTag } from "../utils";+import { validateColorGradingContract } from "@hyperframes/parsers/color-grading-contract";function escapeRegExp(value: string): string {return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");@@ -247,6 +248,59 @@ export const mediaRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> =return findings;},+ // color_grading_* — grading is a structured media-only contract. Unknown+ // keys are ignored by the runtime, so catch them before an agent can report+ // controls that never actually rendered.+ ({ tags }) => {+ const findings: HyperframeLintFinding[] = [];+ for (const tag of tags) {+ const raw = readDecodedAttr(tag.raw, "data-color-grading");+ if (raw === null) continue;+ const elementId = readAttr(tag.raw, "id") || undefined;+ const report = (code: string, message: string, fixHint: string) => {+ findings.push({+ code,+ severity: "error",+ message,+ elementId,+ fixHint,+ snippet: truncateSnippet(tag.raw),+ });+ };+ if (tag.name !== "video" && tag.name !== "img") {+ report(+ "color_grading_non_media",+ `data-color-grading on <${tag.name}> has no effect. The shader runtime only grades real <video> and <img> elements.`,+ "Move the grading attribute to the real <video> or <img> media element. Do not attach it to a wrapper or CSS background.",+ );+ continue;+ }++ const trimmed = raw.trim();+ if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) continue;+ let parsed: unknown;+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ report(+ "color_grading_invalid_json",+ "data-color-grading contains malformed JSON and will not render.",+ 'Use valid JSON, for example {"preset":"skin-soft","intensity":0.6,"adjust":{"highlights":-0.08}}.',+ );+ continue;+ }+ for (const issue of validateColorGradingContract(parsed)) {+ report(+ "color_grading_invalid_structure",+ `data-color-grading ${issue.path} ${issue.message}.`,+ issue.hint ??+ "Use the documented media-treatment contract and correct or remove the invalid value.",+ );+ }+ }+ return findings;+ },+// video_missing_muted({ tags }) => {const findings: HyperframeLintFinding[] = [];diff --git a/packages/parsers/src/colorGradingContract.ts b/packages/parsers/src/colorGradingContract.tsindex 95d99f85ef..cb2fc0b95a 100644--- a/packages/parsers/src/colorGradingContract.ts+++ b/packages/parsers/src/colorGradingContract.ts@@ -139,6 +139,20 @@ export function isColorGradingVariableRef(value: unknown): value is string {return typeof value === "string" && VARIABLE_REF.test(value.trim());}+function unknownKeysHint(path: string, unknown: readonly string[]): string {+ if (path !== "grading") return `Correct or remove the unsupported "${path}" keys.`;+ const sections = new Set(+ unknown.flatMap((key) =>+ OBJECT_SECTIONS.filter(([, keys]) => (keys as readonly string[]).includes(key)).map(+ ([section]) => section,+ ),+ ),+ );+ return sections.size === 1+ ? `Move those controls under "${[...sections][0]}".`+ : "Use only the documented media-treatment keys at the top level.";+}+function validateObject(value: unknown,path: string,@@ -153,7 +167,11 @@ function validateObject(const allowed = new Set(keys);const unknown = Object.keys(value).filter((key) => !allowed.has(key));if (unknown.length > 0) {- issues.push({ path, message: `has unsupported key(s): ${unknown.join(", ")}` });+ issues.push({+ path,+ message: `has unsupported key(s): ${unknown.join(", ")}`,+ hint: unknownKeysHint(path, unknown),+ });}return value;}@@ -192,13 +210,19 @@ function validateNumericSection(function validatePalette(value: unknown, issues: ColorGradingContractIssue[]): void {if (value === undefined || value === null || isColorGradingVariableRef(value)) return;+ const hint =+ 'Use 2 to 6 colors in the intended mapping order, each written as exact "#RRGGBB", or use a project variable reference.';if (!Array.isArray(value) || value.length < 2 || value.length > 6) {- issues.push({ path: "palette", message: "must contain 2 to 6 hex colors" });+ issues.push({ path: "palette", message: "must contain 2 to 6 hex colors", hint });return;}value.forEach((color, index) => {if (typeof color !== "string" || !PALETTE_COLOR.test(color)) {- issues.push({ path: `palette[${index}]`, message: "must be a six-digit hex color" });+ issues.push({+ path: `palette[${index}]`,+ message: "must be a six-digit hex color",+ hint,+ });}});}diff --git a/packages/parsers/src/gsapParser.test.ts b/packages/parsers/src/gsapParser.test.tsindex 9bdd1bb1ff..2452e8f759 100644--- a/packages/parsers/src/gsapParser.test.ts+++ b/packages/parsers/src/gsapParser.test.ts@@ -170,13 +170,14 @@ describe("parseGsapScript", () => {it("extracts all GSAP properties including non-standard ones", () => {const script = `const tl = gsap.timeline({ paused: true });- tl.to("#el1", { opacity: 1, backgroundColor: "red", x: 50, duration: 0.5 }, 0);+ tl.to("#el1", { opacity: 1, backgroundColor: "red", x: 50, "--hf-color-grading-intensity": 0.5, duration: 0.5 }, 0);`;const result = parseGsapScript(script);expect(result.animations[0].properties.opacity).toBe(1);expect(result.animations[0].properties.x).toBe(50);expect(result.animations[0].properties.backgroundColor).toBe("red");+ expect(result.animations[0].properties["--hf-color-grading-intensity"]).toBe(0.5);});it("extracts ease from properties", () => {