diff --git a/packages/starpod/src/components/media/publish.ts b/packages/starpod/src/components/media/publish.ts index 308cfb4..4dd180b 100644 --- a/packages/starpod/src/components/media/publish.ts +++ b/packages/starpod/src/components/media/publish.ts @@ -20,7 +20,8 @@ * video plays and floats in a corner (the glow is the only thing that shows * it): sampled once a second from a 16×16 frame made asynchronously and read * back in a worker, then eased and stepped coarsely, so it writes only when - * the scene changes. + * the scene changes, and written as `oklch()`. Nothing is sampled until the media + * plays, and a pause stops it with the last colour held. * `video-color` itself reads the frame back synchronously, which stalled the * main thread 24–41ms per sample here (once 900ms). * @@ -88,13 +89,30 @@ type Rgb = Array; // Coarse enough that a glow only changes with the scene, not the noise. const STEP = 16; +const PAUSES = ['pause', 'ended', 'emptied']; + /** Halfway from the last colour to the new one, in coarse steps, so the colour drifts rather than flickers and small changes write nothing. */ export function ease(from: Rgb | undefined, to: Rgb): Rgb { return to.map((c, i) => Math.round((from ? (from[i] + c) / 2 : c) / STEP) * STEP); } -const css = (c: Rgb) => `rgb(${c.join(' ')})`; +/** An sRGB colour (0–255 a channel, clamped as CSS would) as `oklch()`. */ +export function oklch(rgb: Rgb) { + const [r, g, b] = rgb.map((c) => { + const v = Math.min(Math.max(c, 0), 255) / 255; + return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; + }); + const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s; + const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s; + const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s; + const C = Math.hypot(A, B); + const H = C < 0.0001 ? 0 : (Math.atan2(B, A) * 180) / Math.PI; + return `oklch(${+L.toFixed(4)} ${+C.toFixed(4)} ${+((H + 360) % 360).toFixed(2)})`; +} export function toneSource(media: HTMLVideoElement): Source { const listeners = new Set<(tones: Tones) => void>(); @@ -109,7 +127,7 @@ export function toneSource(media: HTMLVideoElement): Source { } const video = ease(eased.video, data.video); const accent = ease(eased.accent, data.accent); - const next = { video: css(video), 'video-accent': css(accent) }; + const next = { video: oklch(video), 'video-accent': oklch(accent) }; if (`${next.video}${next['video-accent']}` !== eased.css) { eased = { video, accent, css: `${next.video}${next['video-accent']}` }; listeners.forEach((listen) => listen(next)); @@ -151,6 +169,11 @@ export function toneSource(media: HTMLVideoElement): Source { } worker.postMessage(frame, [frame]); }; + const run = () => (timer ||= window.setInterval(sample, 1000)); + const rest = () => { + window.clearInterval(timer); + timer = 0; + }; return { key: 'video-tone', scope: 'element', @@ -166,14 +189,21 @@ export function toneSource(media: HTMLVideoElement): Source { }; listeners.add(listen); if (eased.css) { - listen({ video: css(eased.video!), 'video-accent': css(eased.accent!) }); + listen({ video: oklch(eased.video!), 'video-accent': oklch(eased.accent!) }); + } + if (listeners.size === 1) { + media.addEventListener('play', run); + PAUSES.forEach((type) => media.addEventListener(type, rest)); + if (!media.paused) { + run(); + } } - timer ||= window.setInterval(sample, 1000); return () => { listeners.delete(listen); if (!listeners.size) { - window.clearInterval(timer); - timer = 0; + media.removeEventListener('play', run); + PAUSES.forEach((type) => media.removeEventListener(type, rest)); + rest(); eased = {}; } }; diff --git a/tests/unit/publish.test.ts b/tests/unit/publish.test.ts index d4d0471..15a6ac6 100644 --- a/tests/unit/publish.test.ts +++ b/tests/unit/publish.test.ts @@ -1,5 +1,5 @@ -import { describe, expect, it } from 'vitest'; -import { clock, ease, publish } from 'starpod/src/components/media/publish'; +import { describe, expect, it, vi } from 'vitest'; +import { clock, ease, oklch, publish, toneSource } from 'starpod/src/components/media/publish'; function fakeMedia(duration: number) { const media = document.createElement('video'); @@ -64,3 +64,48 @@ describe('the picture colour', () => { expect(ease(first, [201, 41, 99])).toEqual(first); }); }); + +describe('the picture colour as oklch()', () => { + it('matches the reference OKLab values for white, black and the primaries', () => { + expect(oklch([255, 255, 255])).toBe('oklch(1 0 0)'); + expect(oklch([0, 0, 0])).toBe('oklch(0 0 0)'); + expect(oklch([255, 0, 0])).toBe('oklch(0.628 0.2577 29.23)'); + expect(oklch([0, 255, 0])).toBe('oklch(0.8664 0.2948 142.5)'); + expect(oklch([0, 0, 255])).toBe('oklch(0.452 0.3132 264.05)'); + }); + + it('clamps a channel stepped past 255 the way CSS clamps rgb()', () => { + expect(oklch([256, 256, 256])).toBe(oklch([255, 255, 255])); + }); +}); + +describe('the picture colour sampler', () => { + it('runs only while the media plays', () => { + const set = vi.spyOn(window, 'setInterval'); + const clear = vi.spyOn(window, 'clearInterval'); + const media = document.createElement('video'); + let paused = true; + Object.defineProperty(media, 'paused', { get: () => paused }); + const stop = toneSource(media).start({ + target: document.createElement('i'), + config: {} as never, + write: () => {} + }); + expect(set).not.toHaveBeenCalled(); + + paused = false; + media.dispatchEvent(new Event('play')); + expect(set).toHaveBeenCalledTimes(1); + const timer = set.mock.results[0].value; + + paused = true; + media.dispatchEvent(new Event('pause')); + expect(clear).toHaveBeenCalledWith(timer); + + stop?.(); + media.dispatchEvent(new Event('play')); + expect(set).toHaveBeenCalledTimes(1); + set.mockRestore(); + clear.mockRestore(); + }); +}); diff --git a/tests/unit/tone-worker.test.ts b/tests/unit/tone-worker.test.ts index bc49149..aa1ae47 100644 --- a/tests/unit/tone-worker.test.ts +++ b/tests/unit/tone-worker.test.ts @@ -1,25 +1,35 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; +/** A 16×16 frame: 192 pixels of one colour, 64 of another. */ +function frame(common: Array, rare: Array) { + const data = new Uint8ClampedArray(16 * 16 * 4); + for (let i = 0; i < 256; i++) { + data.set([...(i < 192 ? common : rare), 255], i * 4); + } + return data; +} + describe('the tone worker', () => { afterEach(() => vi.unstubAllGlobals()); - it('draws the frame at 16×16 itself, whatever size the bitmap came in', async () => { + it('draws the frame at 16×16 and posts its common and vivid colours', async () => { const drawImage = vi.fn(); + const pixels = frame([40, 40, 48], [200, 30, 30]); vi.stubGlobal( 'OffscreenCanvas', class { getContext() { - return { drawImage, getImageData: () => ({ data: new Uint8ClampedArray(16 * 16 * 4) }) }; + return { drawImage, getImageData: () => ({ data: pixels }) }; } } ); const posted = vi.fn(); vi.spyOn(self, 'postMessage').mockImplementation(posted); await import('starpod/src/components/media/tone-worker'); - const frame = { close: vi.fn() }; - (self.onmessage as (event: { data: unknown }) => void)({ data: frame }); - expect(drawImage).toHaveBeenCalledWith(frame, 0, 0, 16, 16); - expect(frame.close).toHaveBeenCalled(); - expect(posted).toHaveBeenCalled(); + const bitmap = { close: vi.fn() }; + (self.onmessage as (event: { data: unknown }) => void)({ data: bitmap }); + expect(drawImage).toHaveBeenCalledWith(bitmap, 0, 0, 16, 16); + expect(bitmap.close).toHaveBeenCalled(); + expect(posted).toHaveBeenCalledWith({ video: [40, 40, 48], accent: [200, 30, 30] }); }); });