8000 feat(arrange): screen-blend mel overlay on Polaroid + FilmStrip Frame by johannboehme · Pull Request #42 · johannboehme/tk-1 · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions frontend/src/components/arrange/Frame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import { useEffect, useRef, useState } from "react";
import type { Chunk, VideoAsset } from "../../storage/jobs-db";
import { useChunkThumbnail } from "./useChunkThumbnail";
import { useArrangeStore } from "../../local/arrange/arrange-store";
import { renderMelOverlay } from "../../local/arrange/chunk-mel-render";

interface FrameProps {
jobId: string | null;
Expand Down Expand Up @@ -71,6 +73,19 @@ export function Frame({
const camColor = cam?.color ?? "#FF5722";
const lengthS = (chunk.endMs - chunk.startMs) / 1000;

// Mel overlay — phosphor screen-blended onto the (tiled) still.
// dstFrames scales with the frame's display width so wider, length-
// proportional frames keep crisp time resolution instead of blurring
// a fixed 96-column canvas across hundreds of pixels.
const mel = useArrangeStore((s) => s.melByChunkId[chunk.id] ?? null);
const melCanvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = melCanvasRef.current;
if (!canvas || !mel) return;
const cols = Math.max(48, Math.min(512, Math.floor(width)));
renderMelOverlay(canvas, mel, cols);
}, [mel, width]);

// Tile-count shown in the image area: wider frames carry more
// copies of the thumbnail, faking the "multiple still frames in a
// long strip-region" feel without actually decoding more frames.
Expand Down Expand Up @@ -159,6 +174,21 @@ export function Frame({
)}
</div>
))}
{/* Mel overlay — spans the whole image area regardless of
* tile-count. Screen-blended onto whatever sits below
* (thumbnails or empty bg) so the audio identity reads
* uniformly across the strip. */}
<canvas
ref={melCanvasRef}
aria-hidden
className="absolute inset-0 h-full w-full pointer-events-none"
style={{
gridColumn: `1 / -1`,
mixBlendMode: "screen",
opacity: mel ? 0.85 : 0,
transition: "opacity 600ms ease-out",
}}
/>
</div>

{/* Bottom label band: chunk index + spectral mini-dot + bar count.
Expand Down
34 changes: 1 addition & 33 deletions frontend/src/components/arrange/PlayerCockpit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
chunkStemHeuristic,
type ChunkMelData,
} from "../../local/arrange/chunk-mel";
import { PHOSPHOR_LUT } from "../../local/arrange/chunk-mel-render";
import { CamPreviewArrange } from "./CamPreviewArrange";

// ─── Props (presentational layer) ──────────────────────────────────────
Expand Down Expand Up @@ -59,39 +60,6 @@ export interface CockpitDisplayProps {
onSeekToFraction?: (fraction: number) => void;
}

// ─── Phosphor color ramp ───────────────────────────────────────────────
// Three-stop interpolation tuned for OP-1 amber. Floor is not pure black
// — real LCDs leak a tiny warm bloom even when "off". Mid is hand-warm
// copper. Peak is phosphor-flare amber that reads as "lit" without going
// neon-orange. Baked once at module load: 256 × 4 bytes.
const PHOSPHOR_LUT: Uint8ClampedArray = (() => {
const lut = new Uint8ClampedArray(256 * 4);
const FLOOR_RGB = [14, 8, 7];
const MID_RGB = [154, 72, 24];
const PEAK_RGB = [255, 138, 79];
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
for (let i = 0; i < 256; i++) {
const t = i / 255;
let r: number, g: number, b: number;
if (t < 0.5) {
const u = t / 0.5;
r = lerp(FLOOR_RGB[0], MID_RGB[0], u);
g = lerp(FLOOR_RGB[1], MID_RGB[1], u);
b = lerp(FLOOR_RGB[2], MID_RGB[2], u);
} else {
const u = (t - 0.5) / 0.5;
r = lerp(MID_RGB[0], PEAK_RGB[0], u);
g = lerp(MID_RGB[1], PEAK_RGB[1], u);
b = lerp(MID_RGB[2], PEAK_RGB[2], u);
}
lut[i * 4 + 0] = r;
lut[i * 4 + 1] = g;
lut[i * 4 + 2] = b;
lut[i * 4 + 3] = 255;
}
return lut;
})();

// ─── Top-level shell (store-coupled) ───────────────────────────────────

export function PlayerCockpit() {
Expand Down
32 changes: 32 additions & 0 deletions frontend/src/components/arrange/Polaroid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ import { motion } from "framer-motion";
import type { Chunk, VideoAsset } from "../../storage/jobs-db";
import { useChunkThumbnail } from "./useChunkThumbnail";
import { useArrangeStore } from "../../local/arrange/arrange-store";
import { renderMelOverlay } from "../../local/arrange/chunk-mel-render";

/** Image-well column count for the screen-blended mel overlay. The
* well is ~108 px wide on the deployed card; 96 internal columns
* give the browser room to bilinear-bleed without blocking up. */
const POLAROID_MEL_COLS = 96;

interface PolaroidProps {
jobId: string | null;
Expand Down Expand Up @@ -74,6 +80,17 @@ export function Polaroid({
const lengthS = (chunk.endMs - chunk.startMs) / 1000;
const camColor = cam?.color ?? "#FF5722";

// Mel overlay — phosphor "haunts" the still photograph via screen
// blend. Subscribed per-chunk so the polaroid only rerenders when
// *its own* mel finishes computing, not on every other chunk's.
const mel = useArrangeStore((s) => s.melByChunkId[chunk.id] ?? null);
const melCanvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = melCanvasRef.current;
if (!canvas || !mel) return;
renderMelOverlay(canvas, mel, POLAROID_MEL_COLS);
}, [mel]);

// Drag-from-Polaroid → drop-on-Strip. We start the drag on
// pointerdown but only after the user has moved past a small
// threshold — that way a plain click still routes to the preview
Expand Down Expand Up @@ -178,6 +195,21 @@ export function Polaroid({
) : (
<PolaroidEmpty failed={thumb.failed} camColor={camColor} />
)}
{/* Mel overlay — OP-1 phosphor screen-blended onto the still.
* Wine-floor LUT means quiet bins stay near-black so the
* photograph reads through; loud amber peaks light up the
* print like a darkroom double exposure. Fades in once the
* worker delivers the chunk's mel data. */}
<canvas
ref={melCanvasRef}
aria-hidden
className="absolute inset-0 h-full w-full pointer-events-none"
style={{
mixBlendMode: "screen",
opacity: mel ? 0.9 : 0,
transition: "opacity 600ms ease-out",
}}
/>
{/* Spectral fingerprint stripe — 3px on the right edge of the
* image well, fading at top + bottom so it doesn't slam into
* the corners. Reads as part of the photograph rather than a
Expand Down
92 changes: 92 additions & 0 deletions frontend/src/local/arrange/chunk-mel-render.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* Tests for the mel-spectrogram rendering helpers used by the
* Polaroid + FilmStrip Frame overlay (variant: double exposure).
*
* The overlay needs two summarisation steps to behave well across
* chunk durations (a chunk can be 10 s or 6 min — same canvas width):
*
* 1. `maxPoolTimeAxis`: aggregate the native-rate mel data into the
* canvas's pixel-column count by taking the **peak** of each bin
* over the source window. Mean-pool would smooth percussive peaks
* into a uniform smear at long durations; max-pool keeps them.
*
* 2. `normalizeP95`: scale so the 95th-percentile non-trivial value
* maps to 1.0. Keeps the visual exposure consistent — short clips
* and long clips end up similarly bright.
*/
import { describe, expect, it } from "vitest";
import { maxPoolTimeAxis, normalizeP95 } from "./chunk-mel-render";

describe("maxPoolTimeAxis", () => {
it("returns the source unchanged when src ≤ dst", () => {
const src = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const out = maxPoolTimeAxis(src, /*nMels*/ 2, /*srcFrames*/ 4, /*dstFrames*/ 8);
expect(out).toBe(src);
});

it("max-pools 4 src frames down to 2 dst frames per mel bin", () => {
// 2 mel bins × 4 src frames, frame-major (data[f * nMels + m])
// Frames: f0=[1,2] f1=[3,4] f2=[5,1] f3=[7,0]
// Pool 4→2 ⇒ dst0 = max(f0,f1) = [3,4], dst1 = max(f2,f3) = [7,1]
const src = new Uint8Array([1, 2, 3, 4, 5, 1, 7, 0]);
const out = maxPoolTimeAxis(src, 2, 4, 2);
expect(Array.from(out)).toEqual([3, 4, 7, 1]);
});

it("preserves percussive peaks under heavy compression", () => {
// 1 mel bin × 100 src frames with a peak at f=50, otherwise zero.
const src = new Uint8Array(100);
src[50] = 255;
const out = maxPoolTimeAxis(src, 1, 100, 10);
// Whatever bucket frame 50 lands in must keep the peak. The other
// 9 buckets remain 0.
expect(Math.max(...out)).toBe(255);
const peakCount = Array.from(out).filter((v) => v === 255).length;
expect(peakCount).toBe(1);
});

it("handles dst > 1 even when src is tiny", () => {
const src = new Uint8Array([100]);
const out = maxPoolTimeAxis(src, 1, 1, 4);
// src ≤ dst → returns src as-is per contract.
expect(out).toBe(src);
});
});

describe("normalizeP95", () => {
it("maps the 95th percentile of non-trivial values to ~255", () => {
// 100 values: 1..100. p95 = 95.
const data = new Uint8Array(100);
for (let i = 0; i < 100; i++) data[i] = i + 1;
normalizeP95(data);
// The original 95 should now be near 255. Values above 95 clamp.
expect(data[94]).toBeGreaterThanOrEqual(245); // ~255 (within rounding)
expect(data[99]).toBe(255);
// Lower values scaled proportionally.
expect(data[49]).toBeLessThan(180);
expect(data[49]).toBeGreaterThan(110);
});

it("leaves silent data alone (target ≤ 0)", () => {
const data = new Uint8Array(50);
normalizeP95(data);
expect(Array.from(data).every((v) => v === 0)).toBe(true);
});

it("ignores near-zero noise floor when picking the percentile", () => {
// 99 noise values + 1 strong signal: signal must end up at peak,
// not get squashed because most of the array is silent.
const data = new Uint8Array(100);
for (let i = 0; i < 99; i++) data[i] = 1; // noise floor
data[99] = 200;
normalizeP95(data);
expect(data[99]).toBeGreaterThan(200);
});

it("is a no-op when the array is too small to take a percentile", () => {
const data = new Uint8Array([10, 20, 30]);
const before = Array.from(data);
normalizeP95(data);
expect(Array.from(data)).toEqual(before);
});
});
Loading
Loading
0