π₯ Make videos programmatically with React
@remotion/studio: Add LUT asset previews
Jonny Burger9a38e77a0484
diff --git a/packages/docs/docs/studio/quick-switcher.mdx b/packages/docs/docs/studio/quick-switcher.mdxindex f9697f56c0..47427e3441 100644--- a/packages/docs/docs/studio/quick-switcher.mdx+++ b/packages/docs/docs/studio/quick-switcher.mdx@@ -7,6 +7,23 @@ crumb: "Remotion Studio"Press <kbd>β/Ctrl</kbd> + <kbd>K</kbd> to invoke the quick switcher. By default it will let you select a [composition](/docs/terminology/composition).In the input field, you filter for compositions by typing in their [ID](/docs/terminology/composition#composition-id).+## Searching assets++Type `$` as the first character to search files in your [public folder](/docs/terminology/public-folder).+Filter by file type with `type:audio`, `type:video`, `type:image`, `type:font`, `type:json`, `type:txt`, or `type:other`.+For example, `$ type:video intro` searches video filenames matching `intro`.++### LUT previews<AvailableFrom v="4.0.526" />++Use `$ type:lut` to find `.cube` color lookup tables.+Select a LUT in the Quick Switcher or the assets sidebar to compare a sample image before and after applying it.+Drag the divider across the image to compare the original and graded colors. You can also focus the slider and use the arrow keys, or press Home and End to reveal either version in full.+The sample image is loaded from `remotion.media` and requires an internet connection.++The preview supports standalone 1D and 3D LUTs, including custom input ranges.+Combined 1D/3D LUTs are not supported.+Previewing a LUT does not apply it to your compositions.+## Navigating through menu itemsIf you type "`>`" as the first character, you can navigate through the menu items.diff --git a/packages/example/e2e/lut-preview.test.mts b/packages/example/e2e/lut-preview.test.mtsnew file mode 100644index 0000000000..c708bc2414--- /dev/null+++ b/packages/example/e2e/lut-preview.test.mts@@ -0,0 +1,167 @@+import fs from 'node:fs';+import path from 'node:path';+import {expect, test} from '@playwright/test';+import sharp from 'sharp';+import {exampleDir, STUDIO_URL} from './constants.mts';+import {startStudio, stopStudio} from './studio-server.mts';++test('finds LUT assets and previews their colors, updates, and errors', async ({+ page,+}) => {+ const directory = fs.mkdtempSync(+ path.join(exampleDir, 'public', 'lut-preview-'),+ );+ const directoryName = path.basename(directory);+ const file = path.join(directory, 'invert.CUBE');+ fs.writeFileSync(+ file,+ `TITLE "Invert"+LUT_3D_SIZE 2+1 1 1+0 1 1+1 0 1+0 0 1+1 1 0+0 1 0+1 0 0+0 0 0`,+ );+ fs.writeFileSync(path.join(directory, 'not-a-lut.txt'), 'Not a LUT');++ try {+ await startStudio();+ await page.route('https://remotion.media/transition-bg-blue.jpg', (route) =>+ route.fulfill({+ contentType: 'image/svg+xml',+ headers: {'access-control-allow-origin': '*'},+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="427"><rect width="640" height="427" fill="rgb(32,128,224)"/></svg>',+ }),+ );+ await page.goto(STUDIO_URL);+ await page.keyboard.press('ControlOrMeta+k');+ const search = page.getByPlaceholder('Search compositions...');+ await search.fill(`$ type:lut ${directoryName}`);+ await page.keyboard.press('Enter');+ await expect(page).toHaveURL(+ new RegExp(`/assets/${directoryName}/invert.CUBE$`),+ );+ const before = page.getByRole('img', {name: 'Sample image before LUT'});+ const after = page.getByRole('img', {name: 'Sample image after LUT'});+ await expect(before).toBeVisible();+ await expect(after).toBeVisible();+ const readPixel = (canvas: SVGElement | HTMLElement) => {+ if (!(canvas instanceof HTMLCanvasElement)) {+ throw new Error('Expected the LUT preview canvas');+ }++ const context = canvas.getContext('2d');+ if (!context) {+ throw new Error('Expected a 2D canvas context');+ }++ return [...context.getImageData(100, 100, 1, 1).data];+ };+ expect(await before.evaluate(readPixel)).toEqual([32, 128, 224, 255]);+ expect(await after.evaluate(readPixel)).toEqual([223, 127, 31, 255]);+ const slider = page.getByRole('slider', {+ name: 'Before and after comparison',+ });+ await expect(before).toHaveCSS('user-select', 'none');+ await expect(after).toHaveCSS('user-select', 'none');+ await expect(page.getByText('Before', {exact: true})).toHaveCount(0);+ await expect(page.getByText('After', {exact: true})).toHaveCount(0);+ const readComparison = async () => {+ const {data, info} = await sharp(await slider.screenshot())+ .removeAlpha()+ .raw()+ .toBuffer({resolveWithObject: true});+ return [0.25, 0.75].map((fraction) => {+ const offset =+ (Math.floor(info.height * 0.75) * info.width ++ Math.floor(info.width * fraction)) *+ info.channels;+ return [...data.subarray(offset, offset + 3)];+ });+ };+ expect(await readComparison()).toEqual([+ [32, 128, 224],+ [223, 127, 31],+ ]);+ await expect(page.getByText('2 x 2 x 2 LUT', {exact: false})).toHaveCount(+ 0,+ );+ await slider.click();+ await expect(slider).toBeFocused();+ expect(+ await slider.evaluate((element) => getComputedStyle(element).boxShadow),+ ).toBe('none');+ await page.keyboard.press('Tab');+ await page.keyboard.press('Shift+Tab');+ await expect(slider).toBeFocused();+ expect(+ await slider.evaluate((element) => getComputedStyle(element).boxShadow),+ ).not.toBe('none');+ await slider.press('Home');+ expect(await readComparison()).toEqual([+ [223, 127, 31],+ [223, 127, 31],+ ]);+ await slider.press('End');+ expect(await readComparison()).toEqual([+ [32, 128, 224],+ [32, 128, 224],+ ]);+ const bounds = await slider.boundingBox();+ if (!bounds) {+ throw new Error('Expected the comparison slider bounds');+ }++ await page.mouse.move(+ bounds.x + bounds.width * 0.9,+ bounds.y + bounds.height * 0.5,+ );+ await page.mouse.down();+ await page.mouse.move(+ bounds.x + bounds.width * 0.5,+ bounds.y + bounds.height * 0.5,+ {steps: 5},+ );+ await page.mouse.up();+ expect(await page.evaluate(() => window.getSelection()?.toString())).toBe(+ '',+ );+ expect(await readComparison()).toEqual([+ [32, 128, 224],+ [223, 127, 31],+ ]);+ fs.writeFileSync(file, 'LUT_3D_SIZE 2\n0 0 0');+ await expect(page.getByRole('alert')).toContainText(+ 'Expected 8 LUT colors, got 1',+ );+ await expect(after).toBeHidden();++ fs.writeFileSync(file, 'TITLE "Identity"\nLUT_1D_SIZE 2\n0 0 0\n1 1 1');+ await expect(slider).toBeVisible();+ expect(await after.evaluate(readPixel)).toEqual([32, 128, 224, 255]);+ await page.setViewportSize({width: 720, height: 800});+ await expect(before).toBeVisible();+ await expect(after).toBeVisible();+ await expect+ .poll(async () => {+ const resized = await slider.boundingBox();+ return (+ resized !== null &&+ resized.width > 0 &&+ resized.height > 0 &&+ resized.x >= 0 &&+ resized.y >= 0 &&+ resized.x + resized.width <= 720 &&+ resized.y + resized.height <= 800+ );+ })+ .toBe(true);+ } finally {+ await stopStudio();+ fs.rmSync(directory, {recursive: true});+ }+});diff --git a/packages/example/public/luts/warm.cube b/packages/example/public/luts/warm.cubenew file mode 100644index 0000000000..6e1eb0c2c2--- /dev/null+++ b/packages/example/public/luts/warm.cube@@ -0,0 +1,10 @@+TITLE "Warm"+LUT_3D_SIZE 2+0.06 0 0+1 0 0+0.06 0.97 0+1 0.97 0+0.06 0 0.75+1 0 0.75+0.06 0.97 0.75+1 0.97 0.75diff --git a/packages/studio/src/components/AssetFileIcon.tsx b/packages/studio/src/components/AssetFileIcon.tsxindex 7f10a2a5ff..d9fa0a06ed 100644--- a/packages/studio/src/components/AssetFileIcon.tsx+++ b/packages/studio/src/components/AssetFileIcon.tsx@@ -5,6 +5,7 @@ import {FileIcon} from '../icons/file';import {FontFileIcon} from '../icons/font';import {PicIcon} from '../icons/frame';import {JsonFileIcon} from '../icons/json';+import {LutFileIcon} from '../icons/lut';import {VideoFileIcon} from '../icons/video';type AssetFileIconProps = SVGProps<SVGSVGElement> & {@@ -19,6 +20,7 @@ const iconByFileType: Record<font: FontFileIcon,image: PicIcon,json: JsonFileIcon,+ lut: LutFileIcon,other: FileIcon,txt: FileIcon,video: VideoFileIcon,diff --git a/packages/studio/src/components/FilePreview.tsx b/packages/studio/src/components/FilePreview.tsxindex e8d5c884a6..3d12fdda8e 100644--- a/packages/studio/src/components/FilePreview.tsx+++ b/packages/studio/src/components/FilePreview.tsx@@ -5,6 +5,7 @@ import type {AssetMetadata} from '../helpers/get-asset-metadata';import type {AssetFileType} from '../helpers/get-preview-file-type';import {JSONViewer} from './JSONViewer';import {Spacing} from './layout';+import {LutPreview} from './LutPreview';import {TextViewer} from './TextViewer';const msgStyle: React.CSSProperties = {@@ -135,6 +136,10 @@ export const FilePreview: React.FC<{return <FontPreview src={src} />;}+ if (fileType === 'lut') {+ return <LutPreview key={src} src={src} />;+ }+if (fileType === 'json') {return <JSONViewer src={src} />;}diff --git a/packages/studio/src/components/LutPreview.tsx b/packages/studio/src/components/LutPreview.tsxnew file mode 100644index 0000000000..7696ca2a6f--- /dev/null+++ b/packages/studio/src/components/LutPreview.tsx@@ -0,0 +1,308 @@+import {PlayerInternals} from '@remotion/player';+import React, {useCallback, useEffect, useRef, useState} from 'react';+import {+ BACKGROUND,+ CURRENT_COLOR,+ LIGHT_TEXT,+ TRANSPARENT,+ WHITE,+} from '../helpers/colors';+import {applyCubeLut, parseCubeLut} from '../helpers/cube-lut';+import {+ FOCUS_VISIBLE_ONLY_CLASS_NAME,+ HOVERABLE_CLASS_NAME,+ hoverableStyle,+} from '../helpers/hoverable';+import {useZIndex} from '../state/z-index';++const sampleImage = 'https://remotion.media/transition-bg-blue.jpg';+const previewWidth = 640;+const previewHeight = 427;++const container: React.CSSProperties = {+ padding: 24,+ flex: 1,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontFamily: 'sans-serif',+ fontSize: 13,+ minHeight: 0,+};++const comparison: React.CSSProperties = {+ position: 'relative',+ flexShrink: 0,+ userSelect: 'none',+ WebkitUserSelect: 'none',+};++const canvasStyle: React.CSSProperties = {+ display: 'block',+ width: '100%',+ height: 'auto',+ borderRadius: 4,+ userSelect: 'none',+ WebkitUserSelect: 'none',+};++const sliderStyle: React.CSSProperties = {+ ...hoverableStyle({+ idleBackground: TRANSPARENT,+ hoverBackground: TRANSPARENT,+ idleColor: LIGHT_TEXT,+ hoverColor: WHITE,+ }),+ position: 'absolute',+ inset: 0,+ borderRadius: 4,+ cursor: 'default',+ touchAction: 'none',+ userSelect: 'none',+ WebkitUserSelect: 'none',+};++const dividerStyle: React.CSSProperties = {+ position: 'absolute',+ top: 0,+ bottom: 0,+ width: 2,+ backgroundColor: CURRENT_COLOR,+ transform: 'translateX(-50%)',+ pointerEvents: 'none',+};++const handleStyle: React.CSSProperties = {+ position: 'absolute',+ top: '50%',+ left: '50%',+ transform: 'translate(-50%, -50%)',+ width: 32,+ height: 32,+ borderRadius: '50%',+ border: `2px solid ${CURRENT_COLOR}`,+ backgroundColor: BACKGROUND,+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+};++const message: React.CSSProperties = {+ color: LIGHT_TEXT,+ textAlign: 'center',+ overflowWrap: 'anywhere',+};++type PreviewState =+ | {readonly type: 'loading'}+ | {readonly type: 'error'; readonly error: string}+ | {readonly type: 'loaded'};++export const LutPreview: React.FC<{readonly src: string}> = ({src}) => {+ const containerRef = useRef<HTMLDivElement>(null);+ const beforeRef = useRef<HTMLCanvasElement>(null);+ const afterRef = useRef<HTMLCanvasElement>(null);+ const [state, setState] = useState<PreviewState>({type: 'loading'});+ const [position, setPosition] = useState(50);+ const {tabIndex} = useZIndex();+ const size = PlayerInternals.useElementSize(containerRef, {+ triggerOnWindowResize: true,+ shouldApplyCssTransforms: true,+ });++ const updatePosition = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ const rect = event.currentTarget.getBoundingClientRect();+ setPosition(+ Math.max(+ 0,+ Math.min(100, ((event.clientX - rect.left) / rect.width) * 100),+ ),+ );+ },+ [],+ );++ const onPointerDown = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ if (event.button !== 0 || !event.isPrimary) {+ return;+ }++ event.currentTarget.setPointerCapture(event.pointerId);+ updatePosition(event);+ },+ [updatePosition],+ );++ const onPointerMove = useCallback(+ (event: React.PointerEvent<HTMLDivElement>) => {+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {+ updatePosition(event);+ }+ },+ [updatePosition],+ );++ const onKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLDivElement>) => {+ const step = event.shiftKey ? 10 : 1;+ if (event.key === 'Home') {+ setPosition(0);+ } else if (event.key === 'End') {+ setPosition(100);+ } else if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') {+ setPosition((value) => Math.max(0, value - step));+ } else if (event.key === 'ArrowRight' || event.key === 'ArrowUp') {+ setPosition((value) => Math.min(100, value + step));+ } else {+ return;+ }++ event.preventDefault();+ event.stopPropagation();+ },+ [],+ );++ useEffect(() => {+ const controller = new AbortController();+ const image = new Image();+ image.crossOrigin = 'anonymous';+ setState({type: 'loading'});++ const load = async () => {+ const response = await fetch(src, {signal: controller.signal});+ if (!response.ok) {+ throw new Error(`Could not load LUT (HTTP ${response.status}).`);+ }++ const lut = parseCubeLut(await response.text());+ if (controller.signal.aborted) {+ return;+ }++ image.src = sampleImage;+ try {+ await image.decode();+ } catch {+ throw new Error(+ 'Could not load the LUT sample image. Check your internet connection.',+ );+ }++ if (controller.signal.aborted) {+ return;+ }++ const before = beforeRef.current?.getContext('2d');+ const after = afterRef.current?.getContext('2d');+ if (!before || !after) {+ throw new Error('Could not create the LUT preview canvas.');+ }++ before.drawImage(image, 0, 0, previewWidth, previewHeight);+ const pixels = before.getImageData(0, 0, previewWidth, previewHeight);+ applyCubeLut(pixels.data, lut);+ after.putImageData(pixels, 0, 0);+ setState({type: 'loaded'});+ };++ load().catch((error: unknown) => {+ if (!controller.signal.aborted) {+ setState({+ type: 'error',+ error: error instanceof Error ? error.message : String(error),+ });+ }+ });++ return () => {+ controller.abort();+ image.removeAttribute('src');+ };+ }, [src]);++ return (+ <div ref={containerRef} style={container}>+ {state.type === 'error' ? (+ <div style={message} role="alert">+ Could not preview LUT: {state.error}+ </div>+ ) : state.type === 'loading' ? (+ <div style={message} role="status">+ Loading LUT preview...+ </div>+ ) : null}+ <div+ style={{+ ...comparison,+ width: size+ ? Math.max(+ 0,+ Math.min(+ 960,+ size.width - 48,+ ((size.height - 48) * previewWidth) / previewHeight,+ ),+ )+ : 0,+ display: state.type === 'loaded' ? 'block' : 'none',+ }}+ >+ <canvas+ ref={afterRef}+ width={previewWidth}+ height={previewHeight}+ style={canvasStyle}+ role="img"+ aria-label="Sample image after LUT"+ />+ <div+ style={{+ position: 'absolute',+ inset: 0,+ clipPath: `inset(0 ${100 - position}% 0 0)`,+ }}+ >+ <canvas+ ref={beforeRef}+ width={previewWidth}+ height={previewHeight}+ style={canvasStyle}+ role="img"+ aria-label="Sample image before LUT"+ />+ </div>+ <div+ role="slider"+ aria-label="Before and after comparison"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.round(position)}+ aria-valuetext={`${Math.round(position)}% before, ${100 - Math.round(position)}% after`}+ tabIndex={tabIndex}+ className={`${HOVERABLE_CLASS_NAME} ${FOCUS_VISIBLE_ONLY_CLASS_NAME}`}+ style={sliderStyle}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onKeyDown={onKeyDown}+ >+ <div aria-hidden style={{...dividerStyle, left: `${position}%`}}>+ <div style={handleStyle}>+ <svg width={20} height={20} viewBox="0 0 24 24" fill="none">+ <path+ d="M8 8 4 12l4 4M16 8l4 4-4 4"+ stroke={CURRENT_COLOR}+ strokeWidth={2}+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/packages/studio/src/helpers/cube-lut.ts b/packages/studio/src/helpers/cube-lut.tsnew file mode 100644index 0000000000..129e6e61d5--- /dev/null+++ b/packages/studio/src/helpers/cube-lut.ts@@ -0,0 +1,236 @@+type Rgb = [number, number, number];++export type CubeLut = {+ readonly type: '1d' | '3d';+ readonly size: number;+ readonly title: string | null;+ readonly domainMin: Rgb;+ readonly domainMax: Rgb;+ readonly data: Float32Array;+};++export const parseCubeLut = (text: string): CubeLut => {+ let type: CubeLut['type'] | null = null;+ let size = 0;+ let title: string | null = null;+ let domainMin: Rgb = [0, 0, 0];+ let domainMax: Rgb = [1, 1, 1];+ let data: Float32Array | null = null;+ let offset = 0;+ const headers = new Set<string>();++ for (const [index, rawLine] of text.split(/\r\n?|\n/).entries()) {+ const line = rawLine.trim();+ if (!line || line.startsWith('#')) {+ continue;+ }++ const titleMatch = line.match(/^TITLE\s+"([^"]*)"\s*(?:#.*)?$/);+ const [keyword, ...values] = line.replace(/#.*$/, '').trim().split(/\s+/);+ const numbers = values.map(Number);+ const isHeader = /^[A-Z][A-Z0-9_]*$/.test(keyword);++ if (isHeader) {+ if (offset > 0) {+ throw new Error(`LUT header after color data on line ${index + 1}.`);+ }++ if (headers.has(keyword)) {+ throw new Error(`Duplicate ${keyword} on line ${index + 1}.`);+ }++ headers.add(keyword);+ }++ if (keyword === 'TITLE' && titleMatch) {+ title = titleMatch[1];+ continue;+ }++ if (keyword === 'LUT_1D_SIZE' || keyword === 'LUT_3D_SIZE') {+ if (type !== null) {+ throw new Error('Combined 1D and 3D LUTs are not supported.');+ }++ type = keyword === 'LUT_1D_SIZE' ? '1d' : '3d';+ size = numbers[0];+ const maxSize = type === '1d' ? 65536 : 256;+ if (+ numbers.length !== 1 ||+ !Number.isInteger(size) ||+ size < 2 ||+ size > maxSize+ ) {+ throw new Error(`${keyword} must be an integer from 2 to ${maxSize}.`);+ }++ data = new Float32Array((type === '1d' ? size : size ** 3) * 3);+ continue;+ }++ if (keyword === 'DOMAIN_MIN' || keyword === 'DOMAIN_MAX') {+ if (numbers.length !== 3 || !numbers.every(Number.isFinite)) {+ throw new Error(`${keyword} must contain three finite numbers.`);+ }++ if (keyword === 'DOMAIN_MIN') {+ domainMin = [numbers[0], numbers[1], numbers[2]];+ } else {+ domainMax = [numbers[0], numbers[1], numbers[2]];+ }++ continue;+ }++ if (keyword === 'LUT_1D_INPUT_RANGE' || keyword === 'LUT_3D_INPUT_RANGE') {+ if (+ numbers.length !== 2 ||+ !numbers.every(Number.isFinite) ||+ numbers[0] >= numbers[1]+ ) {+ throw new Error(`${keyword} must contain an increasing input range.`);+ }++ domainMin = [numbers[0], numbers[0], numbers[0]];+ domainMax = [numbers[1], numbers[1], numbers[1]];+ continue;+ }++ if (isHeader) {+ throw new Error(+ `Unsupported LUT header "${keyword}" on line ${index + 1}.`,+ );+ }++ if (data === null) {+ throw new Error('Expected LUT_1D_SIZE or LUT_3D_SIZE before color data.');+ }++ const color = [Number(keyword), ...numbers];+ if (+ color.length !== 3 ||+ !color.every((value) => Number.isFinite(Math.fround(value)))+ ) {+ throw new Error(`Invalid LUT color on line ${index + 1}.`);+ }++ if (offset + 3 > data.length) {+ throw new Error(`Expected ${data.length / 3} LUT colors, got more.`);+ }++ data.set(color, offset);+ offset += 3;+ }++ if (type === null || data === null) {+ throw new Error('Expected LUT_1D_SIZE or LUT_3D_SIZE.');+ }++ if (offset !== data.length) {+ throw new Error(+ `Expected ${data.length / 3} LUT colors, got ${offset / 3}.`,+ );+ }++ if (domainMin.some((min, channel) => min >= domainMax[channel])) {+ throw new Error(+ 'DOMAIN_MAX must be greater than DOMAIN_MIN in every channel.',+ );+ }++ if (+ domainMin.some((min, channel) => !Number.isFinite(domainMax[channel] - min))+ ) {+ throw new Error('LUT input ranges must be finite.');+ }++ if (+ (headers.has('LUT_1D_INPUT_RANGE') || headers.has('LUT_3D_INPUT_RANGE')) &&+ (headers.has('DOMAIN_MIN') ||+ headers.has('DOMAIN_MAX') ||+ headers.has(type === '1d' ? 'LUT_3D_INPUT_RANGE' : 'LUT_1D_INPUT_RANGE'))+ ) {+ throw new Error('Conflicting LUT input range headers.');+ }++ return {type, size, title, domainMin, domainMax, data};+};++export const applyCubeLut = (pixels: Uint8ClampedArray, lut: CubeLut): void => {+ const {data, size, domainMin, domainMax, type} = lut;+ const last = size - 1;+ const range = domainMin.map((min, channel) => domainMax[channel] - min);++ for (let pixel = 0; pixel < pixels.length; pixel += 4) {+ if (type === '1d') {+ for (let channel = 0; channel < 3; channel++) {+ const position = Math.max(+ 0,+ Math.min(+ last,+ ((pixels[pixel + channel] / 255 - domainMin[channel]) /+ range[channel]) *+ last,+ ),+ );+ const low = Math.floor(position);+ const high = Math.min(low + 1, last);+ const fraction = position - low;+ pixels[pixel + channel] =+ 255 *+ (data[low * 3 + channel] * (1 - fraction) ++ data[high * 3 + channel] * fraction);+ }++ continue;+ }++ const r = Math.max(+ 0,+ Math.min(last, ((pixels[pixel] / 255 - domainMin[0]) / range[0]) * last),+ );+ const g = Math.max(+ 0,+ Math.min(+ last,+ ((pixels[pixel + 1] / 255 - domainMin[1]) / range[1]) * last,+ ),+ );+ const b = Math.max(+ 0,+ Math.min(+ last,+ ((pixels[pixel + 2] / 255 - domainMin[2]) / range[2]) * last,+ ),+ );+ const r0 = Math.floor(r);+ const g0 = Math.floor(g);+ const b0 = Math.floor(b);+ const r1 = Math.min(r0 + 1, last);+ const g1 = Math.min(g0 + 1, last);+ const b1 = Math.min(b0 + 1, last);+ const rf = r - r0;+ const gf = g - g0;+ const bf = b - b0;++ // .cube files store red fastest, then green, then blue.+ for (let channel = 0; channel < 3; channel++) {+ const c00 =+ data[(r0 + g0 * size + b0 * size * size) * 3 + channel] * (1 - rf) ++ data[(r1 + g0 * size + b0 * size * size) * 3 + channel] * rf;+ const c10 =+ data[(r0 + g1 * size + b0 * size * size) * 3 + channel] * (1 - rf) ++ data[(r1 + g1 * size + b0 * size * size) * 3 + channel] * rf;+ const c01 =+ data[(r0 + g0 * size + b1 * size * size) * 3 + channel] * (1 - rf) ++ data[(r1 + g0 * size + b1 * size * size) * 3 + channel] * rf;+ const c11 =+ data[(r0 + g1 * size + b1 * size * size) * 3 + channel] * (1 - rf) ++ data[(r1 + g1 * size + b1 * size * size) * 3 + channel] * rf;+ pixels[pixel + channel] =+ 255 *+ ((c00 * (1 - gf) + c10 * gf) * (1 - bf) ++ (c01 * (1 - gf) + c11 * gf) * bf);+ }+ }+};diff --git a/packages/studio/src/helpers/get-preview-file-type.ts b/packages/studio/src/helpers/get-preview-file-type.tsindex 8bf797c5f3..f6021d1a11 100644--- a/packages/studio/src/helpers/get-preview-file-type.ts+++ b/packages/studio/src/helpers/get-preview-file-type.ts@@ -4,6 +4,7 @@ export type AssetFileType =| 'video'| 'image'| 'json'+ | 'lut'| 'txt'| 'other';@@ -61,6 +62,10 @@ export const getPreviewFileType = (fileName: string | null): AssetFileType => {return 'json';}+ if (fileExtension === 'cube') {+ return 'lut';+ }+if (fileExtension === 'txt') {return 'txt';}diff --git a/packages/studio/src/icons/lut.tsx b/packages/studio/src/icons/lut.tsxnew file mode 100644index 0000000000..92bff2da37--- /dev/null+++ b/packages/studio/src/icons/lut.tsx@@ -0,0 +1,14 @@+import type {SVGProps} from 'react';++export const LutFileIcon = ({+ color,+ ...props+}: SVGProps<SVGSVGElement> & {readonly color: string}) => (+ <svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">+ {/* Font Awesome Pro v7.3.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2026 Fonticons, Inc. */}+ <path+ fill={color}+ d="M537.7 64C522.8 64 508.4 68.7 496.3 77.5L286.1 230.3C257.1 251.4 240 285 240 320.9L240 321C234.8 320.3 229.4 320 224 320C153.3 320 96 377.3 96 448C96 463.5 98.8 478.4 103.8 492.2C111.4 513 98 544 75.8 544L48 544C39.2 544 32 551.2 32 560C32 568.8 39.2 576 48 576L224 576C294.7 576 352 518.7 352 448C352 442.6 351.7 437.2 351 432L351.1 432C386.9 432 420.6 414.9 441.7 385.9L594.5 175.7C603.3 163.7 608 149.2 608 134.3C608 95.5 576.5 64 537.7 64zM342.7 400C329.7 367.9 304.1 342.3 272 329.3L272 320.9C272 295.3 284.2 271.3 304.9 256.2L515.1 103.3C521.7 98.5 529.5 96 537.6 96C558.8 96 575.9 113.2 575.9 134.3C575.9 142.4 573.3 150.3 568.6 156.8L415.8 367.1C400.7 387.8 376.7 400 351.1 400L342.7 400zM320 448C320 501 277 544 224 544L127.6 544C128.3 542.7 129 541.4 129.7 540.2C138 523.5 141.4 501.3 133.9 481.2C130.1 470.9 128 459.8 128 448.1C128 395.1 171 352.1 224 352.1C277 352.1 320 395.1 320 448.1z"+ />+ </svg>+);diff --git a/packages/studio/src/test/cube-lut.test.ts b/packages/studio/src/test/cube-lut.test.tsnew file mode 100644index 0000000000..5f42af83cc--- /dev/null+++ b/packages/studio/src/test/cube-lut.test.ts@@ -0,0 +1,102 @@+import {expect, test} from 'bun:test';+import {applyCubeLut, parseCubeLut} from '../helpers/cube-lut';++const identity3d = `LUT_3D_SIZE 2+0 0 0+1 0 0+0 1 0+1 1 0+0 0 1+1 0 1+0 1 1+1 1 1`;++test('parses cube headers, comments and scientific notation, and preserves identity pixels', () => {+ const lut = parseCubeLut(+ `\uFEFF# Test LUT\r\nTITLE "Identity #1" # comment\r\n${identity3d.replaceAll('\n', '\r\n').replace('1 1 1', '1e0 1.0 1 # white')}`,+ );+ const pixels = new Uint8ClampedArray([+ 0, 0, 0, 0, 255, 255, 255, 255, 17, 128, 209, 127,+ ]);+ const original = pixels.slice();+ applyCubeLut(pixels, lut);+ expect(lut.title).toBe('Identity #1');+ expect(pixels).toEqual(original);+});++test('interpolates all three axes in red-fastest order', () => {+ const lut = parseCubeLut(`LUT_3D_SIZE 2+0 0 0+0 0 0+0 0 0+1 0 0+0 0 0+0 0 1+0 1 0+1 1 1`);+ const pixels = new Uint8ClampedArray([64, 128, 192, 127]);+ applyCubeLut(pixels, lut);+ expect([...pixels]).toEqual([32, 96, 48, 127]);+});++test('normalizes input domains per channel and clamps to the LUT edges', () => {+ const lut = parseCubeLut(`DOMAIN_MIN 0 0.25 -0.5+DOMAIN_MAX 1 0.75 0.5+${identity3d}`);+ const pixels = new Uint8ClampedArray([128, 128, 128, 200, 0, 0, 0, 255]);+ applyCubeLut(pixels, lut);+ expect([...pixels]).toEqual([128, 128, 255, 200, 0, 0, 128, 255]);+});++test('interpolates 1D channels independently, including input ranges and out-of-range outputs', () => {+ const lut = parseCubeLut(`LUT_1D_SIZE 3+LUT_1D_INPUT_RANGE 0.25 0.75+1 -1 0+0.5 0.5 1+0 2 2`);+ const pixels = new Uint8ClampedArray([64, 128, 192, 80, 255, 0, 0, 255]);+ applyCubeLut(pixels, lut);+ expect([...pixels]).toEqual([254, 130, 255, 80, 0, 0, 0, 255]);+});++test('normalizes very small input ranges without overflowing', () => {+ const lut = parseCubeLut(+ 'LUT_1D_SIZE 2\nLUT_1D_INPUT_RANGE 0 1e-320\n1 1 1\n0 0 0',+ );+ const pixels = new Uint8ClampedArray([0, 128, 255, 255]);+ applyCubeLut(pixels, lut);+ expect([...pixels]).toEqual([255, 0, 0, 255]);+});++test.each([+ ['', 'Expected LUT_1D_SIZE or LUT_3D_SIZE'],+ ['0 0 0', 'before color data'],+ ['LUT_3D_SIZE 1', 'integer from 2 to 256'],+ ['LUT_3D_SIZE 2.5', 'integer from 2 to 256'],+ ['LUT_3D_SIZE 257', 'integer from 2 to 256'],+ ['LUT_1D_SIZE Infinity', 'integer from 2 to 65536'],+ ['LUT_3D_SIZE 2\n0 0 0', 'Expected 8 LUT colors, got 1'],+ [identity3d + '\n1 1 1', 'Expected 8 LUT colors, got more'],+ [identity3d.replace('0 0 0', 'NaN 0 0'), 'Invalid LUT color'],+ [identity3d.replace('0 0 0', '1e40 0 0'), 'Invalid LUT color'],+ [identity3d.replace('0 0 0', '0 0'), 'Invalid LUT color'],+ ['LUT_1D_SIZE 2\n' + identity3d, 'Combined 1D and 3D'],+ ['LUT_3D_SIZE 2\n' + identity3d, 'Duplicate LUT_3D_SIZE'],+ ['DOMAIN_MIN 1 1 1\n' + identity3d, 'DOMAIN_MAX must be greater'],+ ['DOMAIN_MIN NaN 0 0\n' + identity3d, 'three finite numbers'],+ ['DOMAIN_MIN 0 0\n' + identity3d, 'three finite numbers'],+ [+ 'LUT_3D_INPUT_RANGE -1e308 1e308\n' + identity3d,+ 'LUT input ranges must be finite',+ ],+ ['LUT_3D_INPUT_RANGE 1 0\n' + identity3d, 'increasing input range'],+ ['LUT_1D_INPUT_RANGE 0 1\n' + identity3d, 'Conflicting LUT input range'],+ [+ 'DOMAIN_MIN 0 0 0\nLUT_3D_INPUT_RANGE 0 1\n' + identity3d,+ 'Conflicting LUT input range',+ ],+ [identity3d + '\nDOMAIN_MIN 0 0 0', 'header after color data'],+ ['UNKNOWN_HEADER 1\n' + identity3d, 'Unsupported LUT header'],+])('rejects malformed or unsupported cube data: %s', (text, error) => {+ expect(() => parseCubeLut(text)).toThrow(error);+});diff --git a/packages/studio/src/test/quick-switcher-asset-search.test.tsx b/packages/studio/src/test/quick-switcher-asset-search.test.tsxindex 5f91772717..c87d46295e 100644--- a/packages/studio/src/test/quick-switcher-asset-search.test.tsx+++ b/packages/studio/src/test/quick-switcher-asset-search.test.tsx@@ -70,8 +70,29 @@ const assets: StaticFile[] = [sizeInBytes: 1,src: '/videos/playlist.m3u8',},+ {+ lastModified: 0,+ name: 'luts/cinematic.cube',+ sizeInBytes: 1,+ src: '/luts/cinematic.cube',+ },+ {+ lastModified: 0,+ name: 'luts/warm.CUBE',+ sizeInBytes: 1,+ src: '/luts/warm.CUBE',+ },];+test('filters LUT assets and preserves the filename query', () => {+ const result = filterAssetsByType({assets, query: 'type:LUT cinematic'});+ expect(result.query).toBe('cinematic');+ expect(result.assets.map((asset) => asset.name)).toEqual([+ 'luts/cinematic.cube',+ 'luts/warm.CUBE',+ ]);+});+test('filters quick switcher assets by type', () => {const result = filterAssetsByType({assets,