From b8b0d0b68f897c734de7488fca28ae4e8257a531 Mon Sep 17 00:00:00 2001 From: EtienneLescot Date: Sun, 22 Nov 2026 14:07:41 +0100 Subject: [PATCH 01/74] feat(mcp): give agents a contact sheet, region crops and an audio report An agent checked a film through getFrames alone: twelve stills a call, 1280 px wide, and nothing of the sound. It could not see a rhythm or a transition, read small text, or tell a mix from silence. - getContactSheet lays up to 36 frames out on one image, each with its time in its corner: the whole film at a glance, or a zoom or a cut frame by frame, for the cost of a single frame. - getFrames takes a region, returned at the video's own resolution, and startSec/endSec to spread its frames over a span. - getAudioReport renders the project's audio as the export mixes it and measures its integrated loudness (BS.1770-4, R128 gates), its true peak and its silences, placed on the ruler like every other time. The layout, the labels and the measurements are plain code on buffers, unit-tested. Decoding, cropping and encoding go through Electron's nativeImage, handed to the tools so they still import no electron. --- electron/cli/cliMain.ts | 2 + electron/ipc/handlers.ts | 2 + electron/mcp/audio-report.test.ts | 185 ++++++ electron/mcp/audio-report.ts | 350 +++++++++++ electron/mcp/contact-sheet.test.ts | 136 +++++ electron/mcp/contact-sheet.ts | 168 ++++++ electron/mcp/frame-images.ts | 36 ++ electron/mcp/media-tools.test.ts | 304 +++++++++- electron/mcp/media-tools.ts | 567 +++++++++++++----- electron/mcp/openscreen-mcp-server.test.ts | 2 + electron/mcp/stdio-server.ts | 2 + .../architecture/mcp-server.md | 9 +- .../testing/manual-e2e-checklist.md | 1 + 13 files changed, 1617 insertions(+), 147 deletions(-) create mode 100644 electron/mcp/audio-report.test.ts create mode 100644 electron/mcp/audio-report.ts create mode 100644 electron/mcp/contact-sheet.test.ts create mode 100644 electron/mcp/contact-sheet.ts create mode 100644 electron/mcp/frame-images.ts diff --git a/electron/cli/cliMain.ts b/electron/cli/cliMain.ts index b8d600a65b..3a0f3a54c3 100644 --- a/electron/cli/cliMain.ts +++ b/electron/cli/cliMain.ts @@ -11,6 +11,7 @@ import { renameWithRetry } from "../atomic-rename"; import { isDiagnosticModeEnabled } from "../diagnostics/main-log-file"; import { getInstallChannel, ownsItsUpdates } from "../install-channel"; import { getSelectedDesktopSource, registerIpcHandlers } from "../ipc/handlers"; +import { frameImages } from "../mcp/frame-images"; import { openVideoInHiddenWindow } from "../mcp/hidden-video"; import { watchForMacMcpShutdown } from "../mcp/mac-update-shutdown"; import { serveMcpOverStdio } from "../mcp/stdio-server"; @@ -421,6 +422,7 @@ export function runCli(command: CliCommand): void { userDataDir, runners, openVideo: openVideoInHiddenWindow, + images: frameImages, updateNotice: tellsAboutUpdates ? (updateNotice(app.getVersion(), readReleaseLookup(userDataDir)) ?? undefined) : undefined, diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts index e4bab0f5cb..ead5b9bdc6 100644 --- a/electron/ipc/handlers.ts +++ b/electron/ipc/handlers.ts @@ -90,6 +90,7 @@ import { } from "../main"; import { createAppRecorder, pickTakePrefs, takePrefs } from "../mcp/app-recorder"; import { EditorDocumentHost } from "../mcp/editor-document-host"; +import { frameImages } from "../mcp/frame-images"; import { openVideoInHiddenWindow } from "../mcp/hidden-video"; import { NAMED_TAKE_NEEDS_SCREEN_ACCESS, namedTakeMayEnumerate } from "../mcp/macNamedTake"; import { McpController } from "../mcp/mcp-controller"; @@ -5518,6 +5519,7 @@ export function registerIpcHandlers( documents: aiEditionDocuments, openVideo: openVideoInHiddenWindow, renderFrames: (...args) => loudnessService.renderFrames(...args), + images: frameImages, readCursor: async (videoPath) => (await readCursorTelemetryFile(videoPath)).samples, // Never overriding the switch: setPointerTrack is refused while MCP edits is off. runTool: mcpRunTool, diff --git a/electron/mcp/audio-report.test.ts b/electron/mcp/audio-report.test.ts new file mode 100644 index 0000000000..f854beb9a2 --- /dev/null +++ b/electron/mcp/audio-report.test.ts @@ -0,0 +1,185 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { measureWav, readWavLayout } from "./audio-report"; + +type Encoding = "s16" | "s24" | "f32"; + +/** A WAV of `channels` (one array of samples each, in -1..1), as a writer would lay it out. */ +function wav( + channels: Float64Array[], + sampleRate = 48_000, + encoding: Encoding = "s16", + options: { extensible?: boolean; before?: Buffer } = {}, +): Buffer { + const bytesPerSample = encoding === "s16" ? 2 : encoding === "s24" ? 3 : 4; + const frames = channels[0].length; + const data = Buffer.alloc(frames * channels.length * bytesPerSample); + for (let i = 0; i < frames; i++) { + channels.forEach((samples, c) => { + const at = (i * channels.length + c) * bytesPerSample; + const value = Math.max(-1, Math.min(1, samples[i])); + if (encoding === "f32") data.writeFloatLE(value, at); + else if (encoding === "s16") data.writeInt16LE(Math.round(value * 32767), at); + else data.writeIntLE(Math.round(value * 8388607), at, 3); + }); + } + const tag = encoding === "f32" ? 3 : 1; + const fmt = Buffer.alloc(options.extensible ? 40 : 16); + fmt.writeUInt16LE(options.extensible ? 0xfffe : tag, 0); + fmt.writeUInt16LE(channels.length, 2); + fmt.writeUInt32LE(sampleRate, 4); + fmt.writeUInt32LE(sampleRate * channels.length * bytesPerSample, 8); + fmt.writeUInt16LE(channels.length * bytesPerSample, 12); + fmt.writeUInt16LE(bytesPerSample * 8, 14); + if (options.extensible) { + fmt.writeUInt16LE(22, 16); + fmt.writeUInt16LE(bytesPerSample * 8, 18); + fmt.writeUInt16LE(tag, 24); + } + const chunk = (id: string, body: Buffer) => { + const head = Buffer.alloc(8); + head.write(id, 0, "latin1"); + head.writeUInt32LE(body.length, 4); + return Buffer.concat([head, body, Buffer.alloc(body.length % 2)]); + }; + const body = Buffer.concat([ + Buffer.from("WAVE", "latin1"), + chunk("fmt ", fmt), + ...(options.before ? [chunk("LIST", options.before)] : []), + chunk("data", data), + ]); + const riff = Buffer.alloc(8); + riff.write("RIFF", 0, "latin1"); + riff.writeUInt32LE(body.length, 4); + return Buffer.concat([riff, body]); +} + +const dbToAmplitude = (db: number) => 10 ** (db / 20); + +/** A sine at `hz`, `db` dBFS at its crest, for `seconds`. */ +function tone(db: number, seconds: number, sampleRate = 48_000, hz = 1_000, phase = 0) { + const samples = new Float64Array(Math.round(seconds * sampleRate)); + const amplitude = dbToAmplitude(db); + for (let i = 0; i < samples.length; i++) { + samples[i] = amplitude * Math.sin((2 * Math.PI * hz * i) / sampleRate + phase); + } + return samples; +} + +function join(...parts: Float64Array[]): Float64Array { + const joined = new Float64Array(parts.reduce((total, part) => total + part.length, 0)); + let at = 0; + for (const part of parts) { + joined.set(part, at); + at += part.length; + } + return joined; +} + +const silence = (seconds: number, sampleRate = 48_000) => + new Float64Array(Math.round(seconds * sampleRate)); + +let dir = ""; +beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "audio-report-")); +}); +afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); +}); + +async function measure(file: Buffer) { + const filePath = path.join(dir, "audio.wav"); + await fs.writeFile(filePath, file); + return measureWav(filePath); +} + +describe("measureWav", () => { + it("reads a stereo tone at its level: -23 dBFS on both channels is -23 LUFS", async () => { + const sine = tone(-23, 5); + const report = await measure(wav([sine, sine])); + expect(report).toMatchObject({ durationSec: 5, sampleRate: 48_000, channels: 2, silences: [] }); + expect(report.integratedLufs).toBeCloseTo(-23, 1); + expect(report.truePeakDbtp).toBeCloseTo(-23, 1); + }); + + it("weights the same at another sample rate", async () => { + const sine = tone(-23, 5, 44_100); + const report = await measure(wav([sine, sine], 44_100)); + expect(report.sampleRate).toBe(44_100); + expect(report.integratedLufs).toBeCloseTo(-23, 1); + }); + + it("counts one channel alone 3 LU under two", async () => { + const report = await measure(wav([tone(-23, 5)])); + expect(report.integratedLufs).toBeCloseTo(-26, 1); + }); + + it("finds the peak between the samples, which no sample shows", async () => { + // A quarter of the sample rate, 45° off: every sample sits 3 dB under the wave's crest. + const report = await measure(wav([tone(0, 1, 48_000, 12_000, Math.PI / 4)], 48_000, "f32")); + expect(report.truePeakDbtp).toBeGreaterThan(-0.6); + expect(report.truePeakDbtp).toBeLessThan(0.3); + }); + + it("leaves a quiet passage out of the loudness, as the R128 gate does", async () => { + const mixed = join(tone(-23, 10), tone(-50, 10)); + const report = await measure(wav([mixed, mixed])); + // Ungated, the quiet half would pull the figure down to -26. The few blocks that straddle + // the change of level still count, as the standard has it: a hair under -23. + expect(report.integratedLufs).toBeGreaterThan(-23.2); + expect(report.integratedLufs).toBeLessThan(-22.9); + }); + + it("lists the stretches with no sound of half a second or more, not the shorter ones", async () => { + const film = join(silence(1), tone(-20, 1), silence(0.3), tone(-20, 1), silence(0.8)); + const { silences, durationSec } = await measure(wav([film, film])); + expect(durationSec).toBeCloseTo(4.1, 5); + expect(silences).toHaveLength(2); + expect(silences[0].startSec).toBe(0); + expect(silences[0].endSec).toBeCloseTo(1, 2); + expect(silences[1].startSec).toBeCloseTo(3.3, 2); + expect(silences[1].endSec).toBeCloseTo(4.1, 2); + }); + + it("has no loudness and no peak to give for digital silence", async () => { + const report = await measure(wav([silence(2), silence(2)])); + expect(report.integratedLufs).toBeNull(); + expect(report.truePeakDbtp).toBeNull(); + expect(report.silences).toEqual([{ startSec: 0, endSec: 2 }]); + }); + + it("reads 24-bit samples behind an extensible header and a chunk of tags", async () => { + const sine = tone(-23, 2); + const report = await measure( + wav([sine, sine], 48_000, "s24", { extensible: true, before: Buffer.from("INFOodd") }), + ); + expect(report.channels).toBe(2); + expect(report.durationSec).toBe(2); + expect(report.integratedLufs).toBeCloseTo(-23, 1); + }); + + it("says why it cannot read a file", async () => { + await expect(measure(Buffer.from("not a wav at all"))).rejects.toThrow("Not a WAV file"); + const mp3InWav = wav([tone(-23, 0.1)]); + mp3InWav.writeUInt16LE(85, 20); + await expect(measure(mp3InWav)).rejects.toThrow("Unsupported WAV encoding (format 85)"); + }); +}); + +describe("readWavLayout", () => { + it("runs the samples to the end of the file when a streaming writer left their size open", () => { + const file = wav([tone(-23, 0.01)]); + const dataSizeAt = file.indexOf("data", 0, "latin1") + 4; + file.writeUInt32LE(0xffffffff, dataSizeAt); + const layout = readWavLayout(file, file.length); + expect(layout.dataBytes).toBe(file.length - layout.dataStart); + expect(layout).toMatchObject({ + channels: 1, + sampleRate: 48_000, + bytesPerSample: 2, + float: false, + }); + }); +}); diff --git a/electron/mcp/audio-report.ts b/electron/mcp/audio-report.ts new file mode 100644 index 0000000000..93b55f2628 --- /dev/null +++ b/electron/mcp/audio-report.ts @@ -0,0 +1,350 @@ +// What a film sounds like, in numbers: its integrated loudness, its true peak and the stretches +// with no sound at all, measured on the WAV an audio export writes. An agent cannot listen, and +// a still frame says nothing of the sound: these three numbers are how it checks a mix. +// +// The file is read in chunks and measured as it goes, so an hour of audio costs no more memory +// than a minute. + +import { open } from "node:fs/promises"; + +export interface AudioReport { + durationSec: number; + sampleRate: number; + channels: number; + /** LUFS, per ITU-R BS.1770-4 with the EBU R128 gates; `null` when nothing clears them. */ + integratedLufs: number | null; + /** dBTP, the highest peak of the signal oversampled four times; `null` for digital silence. */ + truePeakDbtp: number | null; + /** Every stretch of at least `SILENCE_MIN_SEC` that stays under `SILENCE_FLOOR`. */ + silences: Array<{ startSec: number; endSec: number }>; +} + +/** Under -60 dBFS nothing is heard: an encoder's dither, not a sound someone placed. */ +const SILENCE_FLOOR = 10 ** (-60 / 20); +/** Shorter than this is a breath between two words, not dead air. */ +const SILENCE_MIN_SEC = 0.5; + +const ABSOLUTE_GATE_LUFS = -70; +const RELATIVE_GATE_LU = -10; +/** Gating blocks last 400 ms and overlap by 75 %: four hops of 100 ms. */ +const HOPS_PER_BLOCK = 4; + +/** Samples each side of an oversampled point: BS.1770's own interpolator spans as many. */ +const TAPS_PER_PHASE = 12; +const OVERSAMPLING = 4; + +type Biquad = readonly [b0: number, b1: number, b2: number, a1: number, a2: number]; + +/** The K-weighting of BS.1770 at any sample rate: a high shelf for the head, then a high-pass. + * Derived from the standard's analogue prototypes, as libebur128 does; at 48 kHz they are the + * standard's own coefficients. */ +function kWeighting(sampleRate: number): [Biquad, Biquad] { + const shelfK = Math.tan((Math.PI * 1681.974450955533) / sampleRate); + const shelfQ = 0.7071752369554196; + const vh = 10 ** (3.999843853973347 / 20); + const vb = vh ** 0.4996667741545416; + const shelfNorm = 1 + shelfK / shelfQ + shelfK * shelfK; + const passK = Math.tan((Math.PI * 38.13547087602444) / sampleRate); + const passQ = 0.5003270373238773; + const passNorm = 1 + passK / passQ + passK * passK; + return [ + [ + (vh + (vb * shelfK) / shelfQ + shelfK * shelfK) / shelfNorm, + (2 * (shelfK * shelfK - vh)) / shelfNorm, + (vh - (vb * shelfK) / shelfQ + shelfK * shelfK) / shelfNorm, + (2 * (shelfK * shelfK - 1)) / shelfNorm, + (1 - shelfK / shelfQ + shelfK * shelfK) / shelfNorm, + ], + [ + 1, + -2, + 1, + (2 * (passK * passK - 1)) / passNorm, + (1 - passK / passQ + passK * passK) / passNorm, + ], + ]; +} + +/** A windowed-sinc interpolator, one row of taps per point between two samples. Each row sums + * to one, so a steady level comes through at its own height. */ +function interpolator(): Float64Array[] { + const length = TAPS_PER_PHASE * OVERSAMPLING; + const centre = (length - 1) / 2; + return Array.from({ length: OVERSAMPLING }, (_, phase) => { + const taps = new Float64Array(TAPS_PER_PHASE); + let sum = 0; + for (let k = 0; k < TAPS_PER_PHASE; k++) { + const n = k * OVERSAMPLING + phase; + const x = (Math.PI * (n - centre)) / OVERSAMPLING; + const sinc = x === 0 ? 1 : Math.sin(x) / x; + const window = 0.5 - 0.5 * Math.cos((2 * Math.PI * (n + 0.5)) / length); + taps[k] = sinc * window; + sum += taps[k]; + } + return taps.map((tap) => tap / sum); + }); +} + +const INTERPOLATOR = interpolator(); + +/** Measures interleaved samples pushed frame by frame. */ +class AudioMeter { + private readonly filters: [Biquad, Biquad]; + /** Per channel, the two filters' memories: x1, x2, y1, y2, twice. */ + private readonly state: Float64Array; + /** Per channel, the last `TAPS_PER_PHASE` samples, oldest first from `historyAt`. */ + private readonly history: Float64Array; + private historyAt = 0; + private readonly hopFrames: number; + private hopEnergy = 0; + private hopFilled = 0; + /** Mean square of each finished 100 ms hop, the channels summed. */ + private readonly hops: number[] = []; + private peak = 0; + private frames = 0; + private quietSince: number | null = 0; + private readonly silences: Array<{ startSec: number; endSec: number }> = []; + + constructor( + private readonly sampleRate: number, + private readonly channels: number, + ) { + this.filters = kWeighting(sampleRate); + this.state = new Float64Array(channels * 8); + this.history = new Float64Array(channels * TAPS_PER_PHASE); + this.hopFrames = Math.round(sampleRate / 10); + } + + /** One frame: `frame[c]` is channel `c`'s sample, in -1..1. */ + push(frame: Float64Array): void { + let loudest = 0; + for (let c = 0; c < this.channels; c++) { + const x = frame[c]; + const magnitude = Math.abs(x); + if (magnitude > loudest) loudest = magnitude; + this.hopEnergy += this.weighted(c, x) ** 2; + this.history[c * TAPS_PER_PHASE + this.historyAt] = x; + } + this.historyAt = (this.historyAt + 1) % TAPS_PER_PHASE; + if (loudest > this.peak) this.peak = loudest; + this.measureBetweenSamples(); + + if (loudest < SILENCE_FLOOR) { + this.quietSince ??= this.frames; + } else { + this.endSilence(this.frames); + } + this.frames++; + if (++this.hopFilled === this.hopFrames) { + this.hops.push(this.hopEnergy / this.hopFrames); + this.hopEnergy = 0; + this.hopFilled = 0; + } + } + + private weighted(channel: number, x: number): number { + const s = this.state; + let value = x; + for (let stage = 0; stage < 2; stage++) { + const [b0, b1, b2, a1, a2] = this.filters[stage]; + const at = channel * 8 + stage * 4; + const y = b0 * value + b1 * s[at] + b2 * s[at + 1] - a1 * s[at + 2] - a2 * s[at + 3]; + s[at + 1] = s[at]; + s[at] = value; + s[at + 3] = s[at + 2]; + s[at + 2] = y; + value = y; + } + return value; + } + + /** The signal between the two samples in the middle of the history, where the interpolator + * is centred: half its span behind the newest sample. */ + private measureBetweenSamples(): void { + // The newest sample, kept positive for the modulo below. + const newest = this.historyAt - 1 + TAPS_PER_PHASE; + const half = TAPS_PER_PHASE / 2; + for (let c = 0; c < this.channels; c++) { + const base = c * TAPS_PER_PHASE; + const around = Math.max( + Math.abs(this.history[base + ((newest - half + 1) % TAPS_PER_PHASE)]), + Math.abs(this.history[base + ((newest - half) % TAPS_PER_PHASE)]), + ); + // A peak between two samples rises a few decibels above them at most: where they are + // well under the peak already found, there is none to look for. + if (around === 0 || around * 2 < this.peak) continue; + for (const taps of INTERPOLATOR) { + let value = 0; + for (let k = 0; k < TAPS_PER_PHASE; k++) { + value += taps[k] * this.history[base + ((newest - k) % TAPS_PER_PHASE)]; + } + if (Math.abs(value) > this.peak) this.peak = Math.abs(value); + } + } + } + + /** Lets the last samples reach the middle of the history: a peak right at the end counts. */ + private flushHistory(): void { + for (let i = 0; i < TAPS_PER_PHASE / 2; i++) { + for (let c = 0; c < this.channels; c++) { + this.history[c * TAPS_PER_PHASE + this.historyAt] = 0; + } + this.historyAt = (this.historyAt + 1) % TAPS_PER_PHASE; + this.measureBetweenSamples(); + } + } + + private endSilence(atFrame: number): void { + if (this.quietSince === null) return; + const startSec = this.quietSince / this.sampleRate; + const endSec = atFrame / this.sampleRate; + if (endSec - startSec >= SILENCE_MIN_SEC) this.silences.push({ startSec, endSec }); + this.quietSince = null; + } + + finish(): AudioReport { + this.endSilence(this.frames); + this.flushHistory(); + return { + durationSec: this.frames / this.sampleRate, + sampleRate: this.sampleRate, + channels: this.channels, + integratedLufs: this.integratedLoudness(), + truePeakDbtp: this.peak > 0 ? 20 * Math.log10(this.peak) : null, + silences: this.silences, + }; + } + + private integratedLoudness(): number | null { + const blocks: number[] = []; + for (let i = 0; i + HOPS_PER_BLOCK <= this.hops.length; i++) { + let sum = 0; + for (let k = 0; k < HOPS_PER_BLOCK; k++) sum += this.hops[i + k]; + blocks.push(sum / HOPS_PER_BLOCK); + } + const lufs = (meanSquare: number) => -0.691 + 10 * Math.log10(meanSquare); + const mean = (values: number[]) => + values.reduce((sum, value) => sum + value, 0) / values.length; + const heard = blocks.filter((block) => lufs(block) > ABSOLUTE_GATE_LUFS); + if (heard.length === 0) return null; + const relativeGate = lufs(mean(heard)) + RELATIVE_GATE_LU; + const counted = heard.filter((block) => lufs(block) > relativeGate); + return counted.length === 0 ? null : lufs(mean(counted)); + } +} + +interface WavLayout { + sampleRate: number; + channels: number; + bytesPerSample: number; + float: boolean; + dataStart: number; + dataBytes: number; +} + +const WAVE_FORMAT_PCM = 1; +const WAVE_FORMAT_FLOAT = 3; +const WAVE_FORMAT_EXTENSIBLE = 0xfffe; + +/** Where a WAV's samples are and how they are written, from its header. */ +export function readWavLayout(header: Buffer, fileBytes: number): WavLayout { + if ( + header.length < 12 || + header.toString("latin1", 0, 4) !== "RIFF" || + header.toString("latin1", 8, 12) !== "WAVE" + ) { + throw new Error("Not a WAV file"); + } + let format: Omit | null = null; + let at = 12; + while (at + 8 <= header.length) { + const id = header.toString("latin1", at, at + 4); + const size = header.readUInt32LE(at + 4); + const body = at + 8; + if (id === "fmt " && body + 16 <= header.length) { + let tag = header.readUInt16LE(body); + const bits = header.readUInt16LE(body + 14); + // The extensible form keeps the real format in the first bytes of its sub-format. + if (tag === WAVE_FORMAT_EXTENSIBLE && size >= 26 && body + 26 <= header.length) { + tag = header.readUInt16LE(body + 24); + } + if (tag !== WAVE_FORMAT_PCM && tag !== WAVE_FORMAT_FLOAT) { + throw new Error(`Unsupported WAV encoding (format ${tag})`); + } + format = { + channels: header.readUInt16LE(body + 2), + sampleRate: header.readUInt32LE(body + 4), + bytesPerSample: bits / 8, + float: tag === WAVE_FORMAT_FLOAT, + }; + } else if (id === "data") { + if (!format) throw new Error("The WAV's samples come before its format"); + const supported = format.float + ? [4, 8].includes(format.bytesPerSample) + : [1, 2, 3, 4].includes(format.bytesPerSample); + if (!supported || format.channels < 1 || format.sampleRate < 1) { + throw new Error("Unsupported WAV sample format"); + } + // A writer that streams leaves the size at zero or all ones: the samples run to the end. + const declared = size === 0 || size === 0xffffffff ? Number.POSITIVE_INFINITY : size; + return { ...format, dataStart: body, dataBytes: Math.min(declared, fileBytes - body) }; + } + at = body + size + (size % 2); + } + throw new Error("The WAV has no samples"); +} + +function sampleReader(layout: WavLayout): (buffer: Buffer, at: number) => number { + if (layout.float) { + return layout.bytesPerSample === 4 + ? (buffer, at) => buffer.readFloatLE(at) + : (buffer, at) => buffer.readDoubleLE(at); + } + switch (layout.bytesPerSample) { + case 1: + return (buffer, at) => (buffer[at] - 128) / 128; + case 2: + return (buffer, at) => buffer.readInt16LE(at) / 32768; + case 3: + return (buffer, at) => buffer.readIntLE(at, 3) / 8388608; + default: + return (buffer, at) => buffer.readInt32LE(at) / 2147483648; + } +} + +/** Enough for the chunks a writer puts before the samples (a LIST of tags, say). */ +const HEADER_BYTES = 64 * 1024; +const CHUNK_FRAMES = 16_384; + +/** Measures the WAV at `path`. Throws, saying why, when it is not a WAV this reads. */ +export async function measureWav(path: string): Promise { + const file = await open(path, "r"); + try { + const { size } = await file.stat(); + const header = Buffer.alloc(Math.min(HEADER_BYTES, size)); + await file.read(header, 0, header.length, 0); + const layout = readWavLayout(header, size); + const read = sampleReader(layout); + const frameBytes = layout.bytesPerSample * layout.channels; + const meter = new AudioMeter(layout.sampleRate, layout.channels); + const frame = new Float64Array(layout.channels); + const chunk = Buffer.alloc(CHUNK_FRAMES * frameBytes); + const end = layout.dataStart + layout.dataBytes - (layout.dataBytes % frameBytes); + for (let position = layout.dataStart; position < end; ) { + const wanted = Math.min(chunk.length, end - position); + const { bytesRead } = await file.read(chunk, 0, wanted, position); + const whole = bytesRead - (bytesRead % frameBytes); + if (whole === 0) break; + for (let at = 0; at < whole; at += frameBytes) { + for (let c = 0; c < layout.channels; c++) { + frame[c] = read(chunk, at + c * layout.bytesPerSample); + } + meter.push(frame); + } + position += whole; + } + return meter.finish(); + } finally { + await file.close(); + } +} diff --git a/electron/mcp/contact-sheet.test.ts b/electron/mcp/contact-sheet.test.ts new file mode 100644 index 0000000000..1c650d7c2d --- /dev/null +++ b/electron/mcp/contact-sheet.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from "vitest"; +import { type Bitmap, composeContactSheet, regionRect, tileWidthFor } from "./contact-sheet"; + +/** A tile of one value, so a pixel says which tile it came from. */ +function flat(width: number, height: number, value: number): Bitmap { + return { width, height, pixels: Buffer.alloc(width * height * 4, value) }; +} + +function pixel(bitmap: Bitmap, x: number, y: number): number { + return bitmap.pixels[(y * bitmap.width + x) * 4]; +} + +/** How many pixels of a rectangle hold `value`. */ +function count( + bitmap: Bitmap, + left: number, + top: number, + width: number, + height: number, + value: number, +) { + let found = 0; + for (let y = top; y < top + height; y++) { + for (let x = left; x < left + width; x++) { + if (pixel(bitmap, x, y) === value) found++; + } + } + return found; +} + +describe("regionRect", () => { + it("turns fractions into pixels of the picture", () => { + expect(regionRect(1920, 1080, { x: 0.5, y: 0.25, width: 0.25, height: 0.5 })).toEqual({ + x: 960, + y: 270, + width: 480, + height: 540, + }); + }); + + it("stays inside the picture, and never comes out empty", () => { + expect(regionRect(100, 50, { x: 0.9, y: 0.9, width: 0.5, height: 0.5 })).toEqual({ + x: 90, + y: 45, + width: 10, + height: 5, + }); + expect(regionRect(100, 50, { x: 1, y: 1, width: 0.001, height: 0.001 })).toEqual({ + x: 99, + y: 49, + width: 1, + height: 1, + }); + }); +}); + +describe("tileWidthFor", () => { + it("fits the columns and their gaps in the width of one frame", () => { + expect(tileWidthFor(4)).toBe(318); + expect(4 * tileWidthFor(4) + 3 * 2).toBeLessThanOrEqual(1280); + expect(6 * tileWidthFor(6) + 5 * 2).toBeLessThanOrEqual(1280); + expect(tileWidthFor(2)).toBe(639); + }); +}); + +describe("composeContactSheet", () => { + const tileWidth = 80; + const tileHeight = 45; + const sheet = composeContactSheet( + [ + { bitmap: flat(tileWidth, tileHeight, 100), label: "0.50s" }, + { bitmap: flat(tileWidth, tileHeight, 150), label: "1.00s" }, + { bitmap: null, label: "9.99s" }, + ], + 2, + tileWidth, + tileHeight, + ); + + it("lays the tiles out in reading order, a gap apart", () => { + expect(sheet.width).toBe(2 * tileWidth + 2); + expect(sheet.height).toBe(2 * tileHeight + 2); + expect(sheet.pixels).toHaveLength(sheet.width * sheet.height * 4); + // Bottom-right of each tile: clear of its label. + expect(pixel(sheet, tileWidth - 1, tileHeight - 1)).toBe(100); + expect(pixel(sheet, tileWidth + 2 + tileWidth - 1, tileHeight - 1)).toBe(150); + // The gap, and the place of the tile that has no frame. + expect(pixel(sheet, tileWidth, 10)).toBe(32); + expect(pixel(sheet, tileWidth - 1, tileHeight + 2 + tileHeight - 1)).toBe(32); + // No tile in the last cell. + expect(pixel(sheet, tileWidth + 2 + 10, tileHeight + 2 + 30)).toBe(32); + }); + + it("is opaque everywhere", () => { + for (let alpha = 3; alpha < sheet.pixels.length; alpha += 4) { + if (sheet.pixels[alpha] !== 255) throw new Error(`transparent at byte ${alpha}`); + } + }); + + it("prints each tile's time in white on a black plate, the missing frame's too", () => { + // "0.50s" at scale 2: five characters, 12 px each, on a plate 18 px high. + for (const [left, top] of [ + [0, 0], + [tileWidth + 2, 0], + [0, tileHeight + 2], + ]) { + const white = count(sheet, left, top, 62, 18, 255); + const black = count(sheet, left, top, 62, 18, 0); + expect(white).toBeGreaterThan(40); + expect(black).toBeGreaterThan(white); + expect(white + black).toBe(62 * 18); + } + }); + + it("draws different times differently, and the same time the same", () => { + const one = composeContactSheet([{ bitmap: null, label: "1.00s" }], 1, 80, 45); + const same = composeContactSheet([{ bitmap: null, label: "1.00s" }], 1, 80, 45); + const other = composeContactSheet([{ bitmap: null, label: "7.25s" }], 1, 80, 45); + expect(one.pixels.equals(same.pixels)).toBe(true); + expect(one.pixels.equals(other.pixels)).toBe(false); + }); + + it("cuts a tile larger than its cell instead of spilling into the next", () => { + const spilled = composeContactSheet( + [ + { bitmap: flat(tileWidth + 20, tileHeight + 20, 200), label: "" }, + { bitmap: flat(tileWidth, tileHeight, 90), label: "" }, + ], + 2, + tileWidth, + tileHeight, + ); + expect(pixel(spilled, tileWidth, 20)).toBe(32); + expect(pixel(spilled, tileWidth + 2, 20)).toBe(90); + }); +}); diff --git a/electron/mcp/contact-sheet.ts b/electron/mcp/contact-sheet.ts new file mode 100644 index 0000000000..62412c98c9 --- /dev/null +++ b/electron/mcp/contact-sheet.ts @@ -0,0 +1,168 @@ +// A contact sheet: frames of a video laid out as one picture, each with its time on it, so a +// client reads a film's rhythm, or a transition frame by frame, for the cost of one image. +// +// Pixels only. The host decodes and encodes (frame-images.ts, Electron's own codec), so the +// layout and the labels run under plain vitest. + +/** Raw pixels, four bytes each, in whatever channel order the host's decoder gives. The sheet + * only moves them and draws in white, black and grey, which read the same in any order. */ +export interface Bitmap { + width: number; + height: number; + pixels: Buffer; +} + +/** Part of a frame, as fractions of its width and height from its top-left corner. */ +export interface FrameRegion { + x: number; + y: number; + width: number; + height: number; +} + +/** The pixel work the media tools ask their host for. */ +export interface FrameImages { + /** A JPEG's pixels, scaled down to at most `maxWidth` wide. */ + decode(jpeg: Buffer, maxWidth: number): Bitmap; + encode(bitmap: Bitmap): Buffer; + /** The part of a JPEG inside `region`, at its own resolution, scaled down only when it is + * wider than `maxWidth`. */ + crop(jpeg: Buffer, region: FrameRegion, maxWidth: number): Buffer; +} + +/** `region` in whole pixels of a `width` by `height` picture: inside it, and never empty. */ +export function regionRect( + width: number, + height: number, + region: FrameRegion, +): { x: number; y: number; width: number; height: number } { + const x = Math.min(width - 1, Math.max(0, Math.round(region.x * width))); + const y = Math.min(height - 1, Math.max(0, Math.round(region.y * height))); + return { + x, + y, + width: Math.max(1, Math.min(width - x, Math.round(region.width * width))), + height: Math.max(1, Math.min(height - y, Math.round(region.height * height))), + }; +} + +/** As wide as a single frame of getFrames, so a sheet costs a client what one frame does. */ +const SHEET_WIDTH = 1280; +/** Between two tiles: enough to tell where one frame ends. */ +const GAP = 2; +/** Behind the tiles, and in place of a frame the video does not have. */ +const BACKGROUND = 32; + +export function tileWidthFor(columns: number): number { + return Math.floor((SHEET_WIDTH - GAP * (columns - 1)) / columns); +} + +// Five by seven, the characters a time takes: "12.40s". +const GLYPHS: Record = { + "0": [".###.", "#...#", "#..##", "#.#.#", "##..#", "#...#", ".###."], + "1": ["..#..", ".##..", "..#..", "..#..", "..#..", "..#..", ".###."], + "2": [".###.", "#...#", "....#", "...#.", "..#..", ".#...", "#####"], + "3": [".###.", "#...#", "....#", "..##.", "....#", "#...#", ".###."], + "4": ["...#.", "..##.", ".#.#.", "#..#.", "#####", "...#.", "...#."], + "5": ["#####", "#....", "####.", "....#", "....#", "#...#", ".###."], + "6": ["..##.", ".#...", "#....", "####.", "#...#", "#...#", ".###."], + "7": ["#####", "....#", "...#.", "..#..", ".#...", ".#...", ".#..."], + "8": [".###.", "#...#", "#...#", ".###.", "#...#", "#...#", ".###."], + "9": [".###.", "#...#", "#...#", ".####", "....#", "...#.", ".##.."], + ".": [".....", ".....", ".....", ".....", ".....", ".##..", ".##.."], + s: [".....", ".....", ".####", "#....", ".###.", "....#", "####."], +}; +const GLYPH_WIDTH = 5; +const GLYPH_HEIGHT = 7; + +export interface SheetTile { + /** `null` where the video has no frame: the tile keeps its place and its label. */ + bitmap: Bitmap | null; + label: string; +} + +/** The tiles in reading order, `columns` across, each `tileWidth` by `tileHeight`. */ +export function composeContactSheet( + tiles: readonly SheetTile[], + columns: number, + tileWidth: number, + tileHeight: number, +): Bitmap { + const rows = Math.ceil(tiles.length / columns); + const width = columns * tileWidth + (columns - 1) * GAP; + const height = rows * tileHeight + (rows - 1) * GAP; + const pixels = Buffer.alloc(width * height * 4, BACKGROUND); + const sheet = { width, height, pixels }; + // Read at a glance on a narrow tile, without covering a wide one. + const scale = Math.max(2, Math.round(tileWidth / 160)); + tiles.forEach((tile, i) => { + const left = (i % columns) * (tileWidth + GAP); + const top = Math.floor(i / columns) * (tileHeight + GAP); + if (tile.bitmap) blit(sheet, tile.bitmap, left, top, tileWidth, tileHeight); + drawLabel(sheet, tile.label, left, top, scale); + }); + // Opaque whatever the tiles carried: a sheet is a picture, not a layer. + for (let alpha = 3; alpha < pixels.length; alpha += 4) pixels[alpha] = 255; + return sheet; +} + +/** Copies `source` onto `sheet` at (`left`, `top`), cut to `maxWidth` by `maxHeight`. */ +function blit( + sheet: Bitmap, + source: Bitmap, + left: number, + top: number, + maxWidth: number, + maxHeight: number, +): void { + const rowBytes = Math.min(source.width, maxWidth) * 4; + const rows = Math.min(source.height, maxHeight); + for (let y = 0; y < rows; y++) { + const from = y * source.width * 4; + source.pixels.copy(sheet.pixels, ((top + y) * sheet.width + left) * 4, from, from + rowBytes); + } +} + +function fill( + sheet: Bitmap, + left: number, + top: number, + width: number, + height: number, + value: number, +): void { + const right = Math.min(sheet.width, left + width); + const bottom = Math.min(sheet.height, top + height); + for (let y = top; y < bottom; y++) { + const row = y * sheet.width; + for (let x = left; x < right; x++) { + const at = (row + x) * 4; + sheet.pixels[at] = value; + sheet.pixels[at + 1] = value; + sheet.pixels[at + 2] = value; + } + } +} + +/** White on a black plate, in the tile's top-left corner: readable over any frame. */ +function drawLabel(sheet: Bitmap, label: string, left: number, top: number, scale: number): void { + const advance = (GLYPH_WIDTH + 1) * scale; + fill(sheet, left, top, label.length * advance + scale, (GLYPH_HEIGHT + 2) * scale, 0); + [...label].forEach((character, index) => { + const glyph = GLYPHS[character]; + if (!glyph) return; + glyph.forEach((row, y) => { + for (let x = 0; x < GLYPH_WIDTH; x++) { + if (row[x] !== "#") continue; + fill( + sheet, + left + scale + index * advance + x * scale, + top + scale + y * scale, + scale, + scale, + 255, + ); + } + }); + }); +} diff --git a/electron/mcp/frame-images.ts b/electron/mcp/frame-images.ts new file mode 100644 index 0000000000..6ae02af185 --- /dev/null +++ b/electron/mcp/frame-images.ts @@ -0,0 +1,36 @@ +// The media tools' pixel work, done by Electron's own image codec: no window, no canvas and no +// dependency. Both servers hand this to the tools (media-tools.ts), which import no `electron`. + +import { nativeImage } from "electron"; +import { type FrameImages, regionRect } from "./contact-sheet"; + +/** What the addon and the hidden video window encode their frames at. */ +const JPEG_QUALITY = 85; + +function decoded(jpeg: Buffer): Electron.NativeImage { + const image = nativeImage.createFromBuffer(jpeg); + if (image.isEmpty()) throw new Error("a frame is not a picture this build can decode"); + return image; +} + +/** No wider than `maxWidth`: scaled down, never up. */ +function fitted(image: Electron.NativeImage, maxWidth: number): Electron.NativeImage { + return image.getSize().width > maxWidth + ? image.resize({ width: Math.max(1, Math.round(maxWidth)), quality: "best" }) + : image; +} + +export const frameImages: FrameImages = { + decode(jpeg, maxWidth) { + const image = fitted(decoded(jpeg), maxWidth); + return { ...image.getSize(), pixels: image.toBitmap() }; + }, + encode({ width, height, pixels }) { + return nativeImage.createFromBitmap(pixels, { width, height }).toJPEG(JPEG_QUALITY); + }, + crop(jpeg, region, maxWidth) { + const image = decoded(jpeg); + const { width, height } = image.getSize(); + return fitted(image.crop(regionRect(width, height, region)), maxWidth).toJPEG(JPEG_QUALITY); + }, +}; diff --git a/electron/mcp/media-tools.test.ts b/electron/mcp/media-tools.test.ts index 126a5cfd26..d7af5ad63b 100644 --- a/electron/mcp/media-tools.test.ts +++ b/electron/mcp/media-tools.test.ts @@ -2,6 +2,7 @@ // hand projects to: a real DocumentService on a temp directory, the real tool // runner, and stand-ins for the runner windows and the video decoder. +import { writeFileSync } from "node:fs"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; @@ -42,6 +43,8 @@ class FakeRunners { holdExport = false; releaseExport: () => void = () => undefined; private exportHeld: () => void = () => undefined; + /** What an audio render to a WAV writes, as the export runner would. */ + wav: Buffer | null = null; open = 0; constructor(private readonly videoPath: string) {} @@ -86,6 +89,10 @@ class FakeRunners { }, }; const result = this.results[request.kind] ?? { success: true }; + const rendersWav = request.kind === "export" && request.format === "wav"; + if (rendersWav && request.outPath && this.wav && result.success) { + writeFileSync(request.outPath, this.wav); + } if (request.kind === "export" && this.holdExport) { this.releaseExport = () => finish(result); this.exportHeld(); @@ -123,6 +130,8 @@ let videoPath = ""; let documents: DocumentService; let runners: FakeRunners; let closed: number; +/** The widths the video decoder was asked for its frames at, in order. */ +let capturedWidths: number[]; let openVideoFails: boolean; let client: Client; let media: ReturnType; @@ -149,6 +158,7 @@ beforeEach(async () => { await fs.writeFile(`${videoPath}.cursor.json`, JSON.stringify({ samples: clickTrack() })); runners = new FakeRunners(videoPath); closed = 0; + capturedWidths = []; openVideoFails = false; renderFrames = undefined; @@ -171,10 +181,13 @@ beforeEach(async () => { durationSec: 12, width: 1920, height: 1080, - capture: async (timeSec) => ({ - mimeType: "image/jpeg", - data: Buffer.from(`frame@${timeSec}`).toString("base64"), - }), + capture: async (timeSec, maxWidth) => { + capturedWidths.push(maxWidth); + return { + mimeType: "image/jpeg", + data: Buffer.from(`frame@${timeSec}`).toString("base64"), + }; + }, close: () => { closed++; }, @@ -182,6 +195,19 @@ beforeEach(async () => { }, readCursor: readSidecar, renderFrames: async (...args) => (renderFrames ? renderFrames(...args) : null), + // The host's image codec: a frame decodes to a flat 16:9 picture as wide as asked, and + // a crop or a sheet says what it was made from. + images: { + decode: (_jpeg, maxWidth) => { + const height = Math.round((maxWidth * 9) / 16); + return { width: maxWidth, height, pixels: Buffer.alloc(maxWidth * height * 4, 7) }; + }, + encode: (bitmap) => Buffer.from(`sheet ${bitmap.width}x${bitmap.height}`), + crop: (jpeg, region, maxWidth) => + Buffer.from( + `${jpeg} cropped to ${region.x},${region.y} ${region.width}x${region.height} within ${maxWidth}`, + ), + }, runTool, now: () => 1_000, }; @@ -1061,6 +1087,276 @@ describe("getFrames", () => { }); }); +/** What a frame result says of each frame, without its opening line. */ +const captionsOf = (result: CallToolResult) => + result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).slice(1); + +/** The picture of a result, as the stand-in codec wrote it. */ +const pictureOf = (result: CallToolResult) => { + const image = result.content.find((part) => part.type === "image"); + return image?.type === "image" ? Buffer.from(image.data, "base64").toString() : null; +}; + +describe("frameTimes over a span", () => { + it("runs from one end of the span to the other, both shown", () => { + expect(frameTimes(12, null, 3, { startSec: 2, endSec: 4 })).toEqual([2, 3, 4]); + expect(frameTimes(12, null, 1, { startSec: 2, endSec: 4 })).toEqual([3]); + expect(frameTimes(12, null, 2, { endSec: 6 })).toEqual([0, 6]); + // An open end is the video's own, one frame short of it. + const toTheEnd = frameTimes(12, null, 2, { startSec: 10 }); + expect(toTheEnd[0]).toBe(10); + expect(toTheEnd[1]).toBeGreaterThan(11.9); + expect(toTheEnd[1]).toBeLessThan(12); + // A span past the end shows the last frame, never a time the video does not have. + expect(frameTimes(12, null, 2, { startSec: 20, endSec: 30 }).every((t) => t < 12)).toBe(true); + }); +}); + +describe("getFrames over a span and on a region", () => { + it("spreads the frames from startSec to endSec", async () => { + const result = await call("getFrames", { + path: "take.mp4", + startSec: 2, + endSec: 4, + count: 3, + }); + expect(captionsOf(result)).toEqual(["2.00s", "3.00s", "4.00s"]); + expect(capturedWidths).toEqual([1280, 1280, 1280]); + }); + + it("takes times or a span, not both, and a span that runs forward", async () => { + const both = await call("getFrames", { path: "take.mp4", atSec: [1], startSec: 0 }); + expect(both.isError).toBe(true); + expect(textOf(both)).toContain("not both"); + const backwards = await call("getFrames", { path: "take.mp4", startSec: 4, endSec: 2 }); + expect(backwards.isError).toBe(true); + expect(textOf(backwards)).toContain("endSec must be after startSec"); + }); + + it("crops each frame to the region, out of the video at its own size", async () => { + const result = await call("getFrames", { + path: "take.mp4", + atSec: [1], + region: { x: 0.5, y: 0, width: 0.5, height: 0.5 }, + }); + expect(pictureOf(result)).toBe("frame@1 cropped to 0.5,0 0.5x0.5 within 1280"); + // Asked wider than any video, so the crop is cut from every pixel the frame has. + expect(capturedWidths).toEqual([16_384]); + }); + + it("renders a project's frames at full size before it crops them", async () => { + const { projectId } = await recordTake(); + const widths: number[] = []; + renderFrames = async (_clips, _scene, _fps, frames, maxWidth) => { + widths.push(maxWidth); + return frames.map((index) => ({ + index, + width: 1920, + height: 1080, + jpeg: Buffer.from(`render@${index}`), + })); + }; + const result = await call("getFrames", { + projectId, + atSec: [1], + region: { x: 0, y: 0, width: 0.25, height: 0.25 }, + }); + expect(pictureOf(result)).toBe("render@60 cropped to 0,0 0.25x0.25 within 1280"); + expect(widths).toEqual([16_384]); + }); +}); + +describe("getContactSheet", () => { + it("lays a video's frames out on one image, and says the times in reading order", async () => { + const result = await call("getContactSheet", { + path: "take.mp4", + startSec: 0, + endSec: 10, + count: 6, + columns: 3, + }); + expect(result.isError).toBeFalsy(); + expect(result.content).toHaveLength(2); + expect(textOf(result)).toContain( + "3 across, in reading order: 0.00s, 2.00s, 4.00s, 6.00s, 8.00s, 10.00s.", + ); + // Three tiles of 425 px and two gaps wide; two rows of 239 px and one gap high. + expect(pictureOf(result)).toBe("sheet 1279x480"); + // Each frame is asked for at the width of its tile, never larger. + expect(capturedWidths).toEqual(Array(6).fill(425)); + expect(closed).toBe(1); + }); + + it("shows twelve moments of the whole film, four across, rendered from a project with no export", async () => { + const { projectId } = await recordTake(); + const asked: Array<{ frames: number; maxWidth: number }> = []; + renderFrames = async (_clips, _scene, _fps, frames, maxWidth) => { + asked.push({ frames: frames.length, maxWidth }); + return frames.map((index) => ({ + index, + width: maxWidth, + height: 179, + jpeg: Buffer.from(`render@${index}`), + })); + }; + const result = await call("getContactSheet", { projectId }); + expect(asked).toEqual([{ frames: 12, maxWidth: 318 }]); + expect(textOf(result)).toContain("rendered from the project"); + expect(textOf(result)).toContain("4 across"); + // Three rows of four tiles, 318 by 179. + expect(pictureOf(result)).toBe(`sheet ${4 * 318 + 3 * 2}x${3 * 179 + 2 * 2}`); + }); + + it("keeps the place and the time of a frame the video does not have", async () => { + const { projectId } = await recordTake(); + renderFrames = async (_clips, _scene, _fps, frames, maxWidth) => + frames.slice(0, 1).map((index) => ({ + index, + width: maxWidth, + height: 360, + jpeg: Buffer.from("the only frame"), + })); + const partial = await call("getContactSheet", { projectId, atSec: [1, 2], columns: 2 }); + expect(textOf(partial)).toContain("in reading order: 1.00s, 2.00s."); + expect(pictureOf(partial)).toBe(`sheet ${2 * 639 + 2}x359`); + + renderFrames = async () => []; + const none = await call("getContactSheet", { projectId, atSec: [1] }); + expect(none.isError).toBe(true); + expect(textOf(none)).toContain("No frame to show"); + }); + + it("cuts the region out of the full-size frame before it makes a tile of it", async () => { + const result = await call("getContactSheet", { + path: "take.mp4", + atSec: [1], + columns: 2, + region: { x: 0, y: 0, width: 0.5, height: 0.5 }, + }); + expect(result.isError).toBeFalsy(); + expect(capturedWidths).toEqual([16_384]); + }); + + it("takes a project or a file like getFrames, and refuses the same mistakes", async () => { + expect((await call("getContactSheet", {})).isError).toBe(true); + const both = await call("getContactSheet", { path: "take.mp4", atSec: [1], endSec: 3 }); + expect(textOf(both)).toContain("not both"); + }); +}); + +describe("getAudioReport", () => { + /** A 16-bit stereo WAV: each part is a 1 kHz tone at `db` dBFS, or silence when `db` is null. */ + function wavOf(parts: Array<[db: number | null, seconds: number]>): Buffer { + const sampleRate = 48_000; + const frames = parts.reduce( + (total, [, seconds]) => total + Math.round(seconds * sampleRate), + 0, + ); + const file = Buffer.alloc(44 + frames * 4); + file.write("RIFF", 0, "latin1"); + file.writeUInt32LE(36 + frames * 4, 4); + file.write("WAVEfmt ", 8, "latin1"); + file.writeUInt32LE(16, 16); + file.writeUInt16LE(1, 20); + file.writeUInt16LE(2, 22); + file.writeUInt32LE(sampleRate, 24); + file.writeUInt32LE(sampleRate * 4, 28); + file.writeUInt16LE(4, 32); + file.writeUInt16LE(16, 34); + file.write("data", 36, "latin1"); + file.writeUInt32LE(frames * 4, 40); + let at = 44; + let n = 0; + for (const [db, seconds] of parts) { + const amplitude = db === null ? 0 : 10 ** (db / 20); + for (let i = 0; i < Math.round(seconds * sampleRate); i++, n++) { + const value = Math.round( + amplitude * Math.sin((2 * Math.PI * 1_000 * n) / sampleRate) * 32767, + ); + file.writeInt16LE(value, at); + file.writeInt16LE(value, at + 2); + at += 4; + } + } + return file; + } + + const reportOf = async (args: Record) => + JSON.parse(textOf(await call("getAudioReport", args))) as { + durationSec: number; + integratedLufs: number | null; + truePeakDbtp: number | null; + silences: Array<{ startSec: number; endSec: number }>; + }; + + it("measures the project's sound, and places its silences on the ruler", async () => { + const { projectId } = await recordTake(); + // A cut of 2 s early in the take: what the export plays at 5 s is ruler second 7. + await call("addTrim", { projectId, startSec: 2, endSec: 4 }); + runners.wav = wavOf([ + [-20, 5], + [null, 1], + [-20, 4], + ]); + const report = await reportOf({ projectId }); + expect(report.durationSec).toBe(10); + expect(report.integratedLufs).toBeCloseTo(-20, 0); + expect(report.truePeakDbtp).toBeCloseTo(-20, 0); + expect(report.silences).toEqual([{ startSec: 7, endSec: 8 }]); + + const request = runners.started.at(-1); + expect(request).toMatchObject({ kind: "export", format: "wav", audioTrackId: null }); + // Rendered to a file of its own, gone once it is measured. + const rendered = (request?.kind === "export" && request.outPath) || ""; + expect(path.dirname(rendered)).toBe(os.tmpdir()); + await expect(fs.access(rendered)).rejects.toThrow(); + expect(media.isBusy()).toBe(false); + }); + + it("measures one imported track alone", async () => { + const { projectId } = await recordTake(); + runners.wav = wavOf([[-30, 2]]); + const report = await reportOf({ projectId, audioId: "music" }); + expect(report.integratedLufs).toBeCloseTo(-30, 0); + expect(runners.started.at(-1)).toMatchObject({ audioTrackId: "music" }); + }); + + it("says a silent film is silent, rather than give it a loudness", async () => { + const { projectId } = await recordTake(); + runners.wav = wavOf([[null, 2]]); + const report = await reportOf({ projectId }); + expect(report).toMatchObject({ integratedLufs: null, truePeakDbtp: null }); + expect(report.silences).toEqual([{ startSec: 0, endSec: 2 }]); + }); + + it("says why it has nothing to give: no such project, a failed render, a file it cannot read", async () => { + expect(textOf(await call("getAudioReport", { projectId: "nope" }))).toContain( + 'No project has the id "nope"', + ); + const { projectId } = await recordTake(); + runners.results.export = { success: false, error: "no audio track" }; + const failed = await call("getAudioReport", { projectId }); + expect(failed.isError).toBe(true); + expect(textOf(failed)).toContain("could not be rendered: no audio track"); + + runners.results.export = { success: true }; + runners.wav = Buffer.from("not a wav"); + const unreadable = await call("getAudioReport", { projectId }); + expect(unreadable.isError).toBe(true); + expect(textOf(unreadable)).toContain("could not be measured: Not a WAV file"); + expect(media.isBusy()).toBe(false); + }); + + it("waits for a take to end", async () => { + const { projectId } = await recordTake(); + await call("startRecording", { window: "My App" }); + const during = await call("getAudioReport", { projectId }); + expect(during.isError).toBe(true); + expect(textOf(during)).toContain("A recording is running"); + await call("stopRecording", { title: "Second" }); + }); +}); + describe("the media tools in the app", () => { let allowed: boolean; let asked: Parameters[0][]; diff --git a/electron/mcp/media-tools.ts b/electron/mcp/media-tools.ts index 85ee0f6c29..91f493fd63 100644 --- a/electron/mcp/media-tools.ts +++ b/electron/mcp/media-tools.ts @@ -12,6 +12,9 @@ // No `electron` import: the runners, the recorder, the decoder and the documents are // handed in, so the tools run under plain vitest with stand-ins. +import { randomUUID } from "node:crypto"; +import { rm } from "node:fs/promises"; +import os from "node:os"; import path from "node:path"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js"; @@ -53,6 +56,13 @@ import { buildNativeClipList, buildSceneDescription } from "../../src/native/sce import { runDocumentTool } from "../ai-edition/deep-agent/service"; import type { DocumentService } from "../ai-edition/document-service"; import type { RunnerHandlers } from "../cli/runnerHost"; +import { type AudioReport, measureWav } from "./audio-report"; +import { + composeContactSheet, + type FrameImages, + type FrameRegion, + tileWidthFor, +} from "./contact-sheet"; import type { OpenedVideo } from "./hidden-video"; import { MCP_EDITS_SETTING, @@ -138,6 +148,9 @@ export interface MediaToolDeps { frames: number[], maxWidth: number, ): Promise | null>; + /** Crops frames and lays them out as a contact sheet (frame-images.ts). Absent, a region + * and a sheet are refused. */ + images?: FrameImages; /** The pointer samples recorded with a video; empty when there are none. */ readCursor(videoPath: string): Promise; /** The document tools' runner: a fresh project's checkpoint and every edit go through it. */ @@ -150,18 +163,148 @@ export const NO_WEBCAM_PICTURE = "The webcam delivered no picture, so the take has no camera. Call listSources and pass startRecording part of the name of a camera that works."; export const MAX_FRAMES = 12; +/** The most a contact sheet holds: six rows of six. */ +export const MAX_SHEET_FRAMES = 36; // Wide enough to read UI text, small enough that a dozen frames stay cheap. const FRAME_WIDTH = 1280; +/** Wider than any render or video: a frame asked for at this width comes at its own size. */ +const FULL_WIDTH = 16_384; /** exportVideo's frame rate when none is asked: the grid getFrames renders on without an export. */ const EXPORT_FPS = 60; // A seek to the exact end shows no frame in Chromium; stop one frame short of it. const END_MARGIN_SEC = 1 / 60; -/** The times to grab: `atSec` clamped inside the video, else `count` centred in equal slices. */ -export function frameTimes(durationSec: number, atSec: number[] | null, count: number): number[] { +/** The stretch of a video a client asks to see frames of; an open end is the video's own. */ +interface FrameSpan { + startSec?: number; + endSec?: number; +} + +/** + * The times to grab: `atSec` clamped inside the video, else `count` of them. Over a `span` + * they run from one of its ends to the other, both shown: a transition is read from its first + * frame to its last. Over the whole video they sit centred in equal slices, clear of a black + * first frame. + */ +export function frameTimes( + durationSec: number, + atSec: number[] | null, + count: number, + span: FrameSpan = {}, +): number[] { const last = Math.max(0, durationSec - END_MARGIN_SEC); if (atSec) return atSec.map((t) => Math.min(t, last)); - return Array.from({ length: count }, (_, i) => Math.min(((i + 0.5) * durationSec) / count, last)); + if (span.startSec === undefined && span.endSec === undefined) { + return Array.from({ length: count }, (_, i) => + Math.min(((i + 0.5) * durationSec) / count, last), + ); + } + const from = Math.min(span.startSec ?? 0, last); + const to = Math.max(from, Math.min(span.endSec ?? last, last)); + if (count === 1) return [(from + to) / 2]; + return Array.from({ length: count }, (_, i) => from + ((to - from) * i) / (count - 1)); +} + +/** The moments a client asks to see, of a project or of a video file. */ +interface FrameQuery extends FrameSpan { + projectId?: string; + path?: string; + atSec?: number[]; + count?: number; +} + +/** One moment looked at: what is said before its picture, and the picture when there is one. */ +interface Shot { + caption: string; + /** The moment, in the seconds the client asked in. */ + sec: number; + jpeg: Buffer | null; +} + +interface Shots { + intro: string; + shots: Shot[]; +} + +/** A frame query answered with its frames, not with why it could not be. A tool result takes + * any key, so the type alone does not tell the two apart. */ +function isShots(found: Shots | CallToolResult): found is Shots { + return Array.isArray(found.shots); +} + +/** Why a frame query cannot be answered as asked, or `null`. */ +function frameQueryProblem(query: FrameQuery): string | null { + if ((query.projectId === undefined) === (query.path === undefined)) { + return "Pass either projectId or path."; + } + if (query.atSec && (query.startSec !== undefined || query.endSec !== undefined)) { + return "Pass atSec, or startSec and endSec with count, not both."; + } + if ( + query.startSec !== undefined && + query.endSec !== undefined && + query.endSec <= query.startSec + ) { + return "endSec must be after startSec."; + } + return null; +} + +const NO_FRAME_HERE = "No frame here: the rendered video ends before it."; +const NO_IMAGE_WORK = "This OpenScreen cannot crop frames or lay them out on a sheet."; + +const REGION_SCHEMA: z.ZodType = z + .object({ + x: z.number().min(0).max(1), + y: z.number().min(0).max(1), + width: z.number().gt(0).max(1), + height: z.number().gt(0).max(1), + }) + .describe( + "Only this part of each frame, as fractions of the frame from its top-left corner: x 0.5, y 0, width 0.5, height 0.5 is the top-right quarter.", + ); + +/** What getFrames and getContactSheet both take, to say which moments of what. */ +function frameQueryShape(transport: McpTransport, maxFrames: number, defaultCount: number) { + return { + projectId: z + .string() + .optional() + .describe("Look at this project: its last export, or the frames an export would show."), + path: z + .string() + .optional() + .describe( + transport === "http" + ? "Or look at this video file, by its absolute path." + : "Or look at this video file.", + ), + atSec: z + .array(z.number().nonnegative()) + .max(maxFrames) + .optional() + .describe("Times in seconds: ruler seconds with projectId, the file's own with path."), + count: z + .number() + .int() + .min(1) + .max(maxFrames) + .optional() + .describe( + `How many frames, when atSec is not given. Default ${defaultCount}. Spread evenly over the whole video, or from startSec to endSec when either is given.`, + ), + startSec: z + .number() + .nonnegative() + .optional() + .describe("With count: the first frame's time. Default: the start of the video."), + endSec: z + .number() + .nonnegative() + .optional() + .describe("With count: the last frame's time. Default: the end of the video."), + region: REGION_SCHEMA.optional(), + }; } export interface PointerEvent { @@ -248,7 +391,7 @@ const TAKE_NOTES: Record = { export function mediaPreamble(transport: McpTransport): string { return [ "OpenScreen records the screen, turns each take into a project you edit with the document tools, and exports it as a video.", - "A demo goes: listSources, then startRecording, then drive the app, then stopRecording. To observe a take the user controls on the in-app HTTP server, call waitForRecording while it is recording or saving; the user stops it. It returns the projectId and a checkpointId. Edit with the document tools, always passing that projectId: every edit is saved to the project straight away, and restoreCheckpoint with the checkpointId takes the project back to the raw take in one step. Then exportVideo, and getFrames with the projectId to check the export before you hand it over: it takes the same ruler seconds as the document tools, so a trim or a speed region never shifts what you look at.", + "A demo goes: listSources, then startRecording, then drive the app, then stopRecording. To observe a take the user controls on the in-app HTTP server, call waitForRecording while it is recording or saving; the user stops it. It returns the projectId and a checkpointId. Edit with the document tools, always passing that projectId: every edit is saved to the project straight away, and restoreCheckpoint with the checkpointId takes the project back to the raw take in one step. Then exportVideo, and getFrames with the projectId to check the export before you hand it over: it takes the same ruler seconds as the document tools, so a trim or a speed region never shifts what you look at. getContactSheet shows many moments as one image, to read the rhythm of the whole film or a transition frame by frame, and getAudioReport measures the sound, which no frame shows.", "To edit a video you already have instead, createProject with its videoPath; importMedia adds a video or an audio file to a project.", "Drive the app with the real mouse when you can: OpenScreen records the pointer, draws a clean cursor and zooms on the clicks as the editor does: clicks close in time and on screen share one zoom, and the first seconds and the end stay on the whole screen. If you drive it from a script instead (Playwright, CDP), the screen pointer never moves: log each action as the script runs it, then hand the log to setPointerTrack after stopRecording. A video your script captured itself takes one too: createProject with it, then setPointerTrack with recordingStartedAt.", TAKE_NOTES[transport], @@ -575,12 +718,13 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { /** getFrames when no export shows the project as it is (`docs/shader-effects.md`, E.4): its * frames composed as its export would compose them, on the export's default frame grid, * without encoding a video. `null` when the addon cannot render them: the export decides. */ - async function renderProjectFrames( + async function renderProjectShots( document: AxcutDocument, - atSec: number[] | null, + query: FrameQuery, count: number, + maxWidth: number, why: string, - ): Promise { + ): Promise { if (!deps.renderFrames) return null; // The frame grid below counts every clip, the render only those with media: past a clip // without one, the two would disagree on which frame a moment is. @@ -591,7 +735,7 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { const clips = buildNativeClipList(document); if (clips.length === 0) return text("This project's timeline has no clip to show.", true); const rulerEndSec = Math.max(0, ...document.timeline.clips.map((clip) => clip.timelineEndSec)); - const times = frameTimes(rulerEndSec, atSec, count); + const times = frameTimes(rulerEndSec, query.atSec ?? null, count, query); // The output frame showing at that moment: the last one that starts at or before it. const indices = times.map((sec) => Math.floor(programmeSecOf(document, sec) * EXPORT_FPS + 1e-6), @@ -599,31 +743,128 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { let frames: Awaited>>; try { const scene = JSON.stringify(buildSceneDescription(document)); - frames = await deps.renderFrames(clips, scene, EXPORT_FPS, indices, FRAME_WIDTH); + frames = await deps.renderFrames(clips, scene, EXPORT_FPS, indices, maxWidth); } catch (error) { const message = error instanceof Error ? error.message : String(error); return text(`The frames could not be rendered: ${message}`, true); } if (!frames) return null; const byIndex = new Map(frames.map((frame) => [frame.index, frame])); - const content: CallToolResult["content"] = [ - { - type: "text", - text: `${times.length} frame(s) rendered from the project as its export would show them: ${why}.`, - }, - ]; - times.forEach((sec, i) => { - content.push({ type: "text", text: `${sec.toFixed(2)}s on the ruler` }); - const frame = byIndex.get(indices[i]); - content.push( - frame - ? { type: "image", data: frame.jpeg.toString("base64"), mimeType: "image/jpeg" } - : { type: "text", text: "No frame here: the rendered video ends before it." }, - ); - }); - return { content }; + return { + intro: `${times.length} frame(s) rendered from the project as its export would show them: ${why}.`, + shots: times.map((sec, i) => ({ + caption: `${sec.toFixed(2)}s on the ruler`, + sec, + jpeg: byIndex.get(indices[i])?.jpeg ?? null, + })), + }; } + /** + * The frames a query asks for, at most `maxWidth` wide: of a project (its current export, + * else rendered from it) or of a video file. An error result when they cannot be had. + */ + async function shotsOf( + query: FrameQuery, + defaultCount: number, + maxWidth: number, + ): Promise { + const problem = frameQueryProblem(query); + if (problem) return text(problem, true); + const count = query.count ?? defaultCount; + let videoPath: string; + /** Ruler seconds → seconds of the exported file, when looking at a project. */ + let toVideoSec = (sec: number) => sec; + let rulerEndSec: number | null = null; + let note = ""; + if (query.projectId !== undefined) { + const exported = lastExports.get(query.projectId); + // A project deleted since still left its export on disk: show it, unflagged. + const current = await deps.documents.getProject(query.projectId).catch(() => null); + const stale = + exported !== undefined && + current !== null && + Date.parse(current.project.updatedAt) > exported.at.getTime(); + // No export shows the project as it is: render its frames as an export would. + if (current && (!exported || stale)) { + const why = exported ? "it changed after its last export" : "it has no export yet"; + const rendered = await renderProjectShots(current, query, count, maxWidth, why); + if (rendered) return rendered; + } + if (!exported) { + return text("This project has no export yet: call exportVideo first.", true); + } + // Mapped through the document the export rendered, so a cut made since cannot shift + // which frame of this video is shown; the current one only says whether it is stale. + const { rendered } = exported; + videoPath = exported.path; + toVideoSec = (sec) => programmeSecOf(rendered, sec); + rulerEndSec = Math.max(0, ...rendered.timeline.clips.map((clip) => clip.timelineEndSec)); + if (stale) { + note = " The project changed after this export: export it again to see the changes."; + } + } else { + const resolved = clientPath(transport, query.path ?? ""); + if (!resolved) return text(`The path must be absolute, got "${query.path}".`, true); + videoPath = resolved; + } + + const video = await deps.openVideo(videoPath); + try { + const asked = + query.atSec ?? (rulerEndSec === null ? null : frameTimes(rulerEndSec, null, count, query)); + const times = asked + ? asked.map((sec) => ({ + asked: sec, + at: frameTimes(video.durationSec, [toVideoSec(sec)], 1)[0], + })) + : frameTimes(video.durationSec, null, count, query).map((at) => ({ asked: at, at })); + const shots: Shot[] = []; + for (const { asked: askedSec, at } of times) { + const frame = await video.capture(at, maxWidth); + shots.push({ + caption: + rulerEndSec === null + ? `${at.toFixed(2)}s` + : `${askedSec.toFixed(2)}s on the ruler, ${at.toFixed(2)}s into the video`, + sec: askedSec, + jpeg: Buffer.from(frame.data, "base64"), + }); + } + return { + intro: `${times.length} frame(s) of a ${video.width}x${video.height} video lasting ${video.durationSec.toFixed(2)}s.${note}`, + shots, + }; + } finally { + video.close(); + } + } + + /** The request an audio render makes of the export runner: exportAudio's, and the report's. */ + const audioRender = ( + projectId: string, + outPath: string, + format: "wav" | "m4a", + audioId: string | undefined, + ): CliRequest => ({ + kind: "export", + projectPath: deps.documents.filePathFor(projectId), + projectId, + outPath, + format, + quality: null, + // The frame grid exportVideo lays the audio out on by default. + mp4FrameRate: EXPORT_FPS, + gifFrameRate: null, + gifSizePreset: null, + gifLoop: null, + autoZoom: false, + audioPath: null, + audioMode: "mix", + audioOffsetSec: 0, + audioTrackId: audioId ?? null, + }); + /** A fresh project's checkpoint, so a client can edit it at once and take it back in one step. */ async function checkpointOf(projectId: string): Promise { // Never fails the call: the project exists either way, and its id is the answer. @@ -1034,27 +1275,9 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { return text(`No project has the id "${args.projectId}".`, true); } const result = await finish( - deps.runners.start( - { - kind: "export", - projectPath: deps.documents.filePathFor(args.projectId), - projectId: args.projectId, - outPath, - format, - quality: null, - // The frame grid exportVideo lays the audio out on by default. - mp4FrameRate: EXPORT_FPS, - gifFrameRate: null, - gifSizePreset: null, - gifLoop: null, - autoZoom: false, - audioPath: null, - audioMode: "mix", - audioOffsetSec: 0, - audioTrackId: args.audioId ?? null, - }, - { onProgress: progressNotifier(extra) }, - ), + deps.runners.start(audioRender(args.projectId, outPath, format, args.audioId), { + onProgress: progressNotifier(extra), + }), ); if (!result.success) { return text(`The export failed: ${result.error ?? "unknown error"}`, true); @@ -1067,117 +1290,162 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { ); server.registerTool( - "getFrames", + "getAudioReport", { description: [ - `Look at a video as still images, at most ${MAX_FRAMES} per call. Ask for the moments you need to check, such as each zoom and each callout.`, - "To check an edit, pass projectId: atSec are the ruler seconds the document tools use, mapped through the trims and speed regions to the moment the export plays them. You get the project's last export, or, when it has none or has changed since, the frames its export would show, rendered from the project without exporting it. With path instead, you get any video file (a take's videoPath, say) and atSec are that file's own seconds.", + "Measure a project's sound, exactly as exportVideo's MP4 mixes it: you cannot hear a film, so check its mix with these numbers. Returns integratedLufs, the loudness of the whole film (null when it is silent; video platforms play at about -14 LUFS); truePeakDbtp, its highest peak; durationSec, the exported film's length; and silences, every stretch of half a second or more with no sound at all, in the ruler seconds the document tools use.", + "With audioId (addAudio's, or an audioTracks entry's trackId, its id when it has no trackId), that imported track alone: a music bed and a voice measured apart say how far one sits under the other. It renders the project as an export does, so it takes about as long as exportVideo. Call it again after an edit that moves time (a trim, a speed region, a track's offset).", ].join("\n"), inputSchema: z.object({ - projectId: z - .string() - .optional() - .describe("Look at this project: its last export, or the frames an export would show."), - path: z + projectId: z.string(), + audioId: z .string() .optional() - .describe( - transport === "http" - ? "Or look at this video file, by its absolute path." - : "Or look at this video file.", - ), - atSec: z - .array(z.number().nonnegative()) - .max(MAX_FRAMES) - .optional() - .describe("Times in seconds: ruler seconds with projectId, the file's own with path."), - count: z - .number() - .int() - .min(1) - .max(MAX_FRAMES) - .optional() - .describe("Frames spread evenly, when atSec is not given. Default 6."), + .describe("Measure this imported track alone. Default: the whole programme audio."), }), annotations: READ_ONLY, }, - async (args) => { - if ((args.projectId === undefined) === (args.path === undefined)) { - return text("Pass either projectId or path.", true); - } - let videoPath: string; - /** Ruler seconds → seconds of the exported file, when looking at a project. */ - let toVideoSec = (sec: number) => sec; - let rulerEndSec: number | null = null; - let note = ""; - if (args.projectId !== undefined) { - const exported = lastExports.get(args.projectId); - // A project deleted since still left its export on disk: show it, unflagged. - const current = await deps.documents.getProject(args.projectId).catch(() => null); - const stale = - exported !== undefined && - current !== null && - Date.parse(current.project.updatedAt) > exported.at.getTime(); - // No export shows the project as it is: render its frames as an export would. - if (current && (!exported || stale)) { - const why = exported ? "it changed after its last export" : "it has no export yet"; - const rendered = await renderProjectFrames( - current, - args.atSec ?? null, - args.count ?? 6, - why, + async (args, extra) => { + if (take) return text("A recording is running. Stop it before measuring the sound.", true); + if (exporting) + return text("An export is already running. Wait for it, then try again.", true); + // Rendered beside nothing of the client's: measured, then removed. + const wavPath = path.join(os.tmpdir(), `openscreen-audio-report-${randomUUID()}.wav`); + exporting = true; + try { + const document = await deps.documents.getProject(args.projectId).catch(() => null); + if (!document) return text(`No project has the id "${args.projectId}".`, true); + const result = await finish( + deps.runners.start(audioRender(args.projectId, wavPath, "wav", args.audioId), { + onProgress: progressNotifier(extra), + }), + ); + if (!result.success) { + return text( + `The sound could not be rendered: ${result.error ?? "unknown error"}`, + true, ); - if (rendered) return rendered; } - if (!exported) { - return text("This project has no export yet: call exportVideo first.", true); - } - // Mapped through the document the export rendered, so a cut made since cannot shift - // which frame of this video is shown; the current one only says whether it is stale. - const { rendered } = exported; - videoPath = exported.path; - toVideoSec = (sec) => programmeSecOf(rendered, sec); - rulerEndSec = Math.max(0, ...rendered.timeline.clips.map((clip) => clip.timelineEndSec)); - if (stale) { - note = " The project changed after this export: export it again to see the changes."; + let report: AudioReport; + try { + report = await measureWav(wavPath); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return text(`The sound could not be measured: ${message}`, true); } - } else { - const resolved = clientPath(transport, args.path ?? ""); - if (!resolved) return text(`The path must be absolute, got "${args.path}".`, true); - videoPath = resolved; + const round = (value: number, digits: number) => Number(value.toFixed(digits)); + return text( + JSON.stringify({ + durationSec: round(report.durationSec, 2), + integratedLufs: + report.integratedLufs === null ? null : round(report.integratedLufs, 1), + truePeakDbtp: report.truePeakDbtp === null ? null : round(report.truePeakDbtp, 1), + silences: report.silences.map(({ startSec, endSec }) => ({ + startSec: round(rulerSecOf(document, startSec), 2), + endSec: round(rulerSecOf(document, endSec), 2), + })), + }), + ); + } finally { + exporting = false; + await rm(wavPath, { force: true }).catch(() => undefined); } + }, + ); - const video = await deps.openVideo(videoPath); + server.registerTool( + "getFrames", + { + description: [ + `Look at a video as still images, at most ${MAX_FRAMES} per call. Ask for the moments you need to check, such as each zoom and each callout.`, + "To check an edit, pass projectId: atSec are the ruler seconds the document tools use, mapped through the trims and speed regions to the moment the export plays them. You get the project's last export, or, when it has none or has changed since, the frames its export would show, rendered from the project without exporting it. With path instead, you get any video file (a take's videoPath, say) and atSec are that file's own seconds.", + "With region, each frame is only that part of the picture, at the video's own resolution: the way to read small text, or to check an edge or a corner. To see many moments at once, such as the rhythm of the whole film or a transition frame by frame, use getContactSheet.", + ].join("\n"), + inputSchema: z.object(frameQueryShape(transport, MAX_FRAMES, 6)), + annotations: READ_ONLY, + }, + async (args) => { + const { region } = args; + if (region && !deps.images) return text(NO_IMAGE_WORK, true); + const found = await shotsOf(args, 6, region ? FULL_WIDTH : FRAME_WIDTH); + if (!isShots(found)) return found; + const content: CallToolResult["content"] = [{ type: "text", text: found.intro }]; try { - const asked = - args.atSec ?? - (rulerEndSec === null ? null : frameTimes(rulerEndSec, null, args.count ?? 6)); - const times = asked - ? asked.map((sec) => ({ - asked: sec, - at: frameTimes(video.durationSec, [toVideoSec(sec)], 1)[0], - })) - : frameTimes(video.durationSec, null, args.count ?? 6).map((at) => ({ asked: at, at })); - const content: CallToolResult["content"] = [ - { - type: "text", - text: `${times.length} frame(s) of a ${video.width}x${video.height} video lasting ${video.durationSec.toFixed(2)}s.${note}`, - }, - ]; - for (const { asked: askedSec, at } of times) { - const frame = await video.capture(at, FRAME_WIDTH); - content.push({ - type: "text", - text: - rulerEndSec === null - ? `${at.toFixed(2)}s` - : `${askedSec.toFixed(2)}s on the ruler, ${at.toFixed(2)}s into the video`, - }); - content.push({ type: "image", data: frame.data, mimeType: frame.mimeType }); + for (const shot of found.shots) { + content.push({ type: "text", text: shot.caption }); + if (!shot.jpeg) { + content.push({ type: "text", text: NO_FRAME_HERE }); + continue; + } + const jpeg = + region && deps.images ? deps.images.crop(shot.jpeg, region, FRAME_WIDTH) : shot.jpeg; + content.push({ type: "image", data: jpeg.toString("base64"), mimeType: "image/jpeg" }); } - return { content }; - } finally { - video.close(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return text(`The frames could not be cropped: ${message}`, true); + } + return { content }; + }, + ); + + server.registerTool( + "getContactSheet", + { + description: [ + `Look at many moments of a video as one image: a grid of up to ${MAX_SHEET_FRAMES} small frames, each with its time printed in its corner, read left to right then top to bottom. It costs what a single frame of getFrames does.`, + "Over the whole film (the default) it shows the rhythm: where the zooms, the callouts and the cuts fall. Over a short span, startSec to endSec, it shows a zoom's move, an effect or a cut frame by frame: 12 frames over one second, say. The frames are too small to read text: use getFrames, with region if need be, for that.", + "projectId, path and the times mean what they mean for getFrames: ruler seconds with projectId, rendered from the project when it has no current export; the file's own seconds with path.", + ].join("\n"), + inputSchema: z.object({ + ...frameQueryShape(transport, MAX_SHEET_FRAMES, 12), + columns: z + .number() + .int() + .min(2) + .max(6) + .optional() + .describe("Frames per row. Fewer make each frame larger. Default 4."), + }), + annotations: READ_ONLY, + }, + async (args) => { + const { images } = deps; + if (!images) return text(NO_IMAGE_WORK, true); + const { region } = args; + const columns = args.columns ?? 4; + const tileWidth = tileWidthFor(columns); + const found = await shotsOf(args, 12, region ? FULL_WIDTH : tileWidth); + if (!isShots(found)) return found; + try { + const tiles = found.shots.map((shot) => ({ + label: `${shot.sec.toFixed(2)}s`, + bitmap: shot.jpeg + ? images.decode( + region ? images.crop(shot.jpeg, region, tileWidth) : shot.jpeg, + tileWidth, + ) + : null, + })); + const shown = tiles.find((tile) => tile.bitmap)?.bitmap; + if (!shown) return text("No frame to show: the video ends before these times.", true); + const sheet = composeContactSheet(tiles, columns, tileWidth, shown.height); + return { + content: [ + { + type: "text", + text: `${found.intro} On one sheet, ${columns} across, in reading order: ${tiles.map((tile) => tile.label).join(", ")}.`, + }, + { + type: "image", + data: images.encode(sheet).toString("base64"), + mimeType: "image/jpeg", + }, + ], + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return text(`The sheet could not be made: ${message}`, true); } }, ); @@ -1280,3 +1548,20 @@ function programmeSecOf(document: AxcutDocument, rulerSec: number): number { readSpeedRegions(document), ); } + +/** + * The ruler second the export plays at `programmeSec`: `programmeSecOf` read backwards, which + * it allows because it never goes back. Where a cut makes several ruler seconds play at once, + * the first of them. + */ +function rulerSecOf(document: AxcutDocument, programmeSec: number): number { + let before = 0; + let after = Math.max(0, ...document.timeline.clips.map((clip) => clip.timelineEndSec)); + // Forty halvings of any film come down to well under a frame. + for (let step = 0; step < 40; step++) { + const middle = (before + after) / 2; + if (programmeSecOf(document, middle) < programmeSec) before = middle; + else after = middle; + } + return after; +} diff --git a/electron/mcp/openscreen-mcp-server.test.ts b/electron/mcp/openscreen-mcp-server.test.ts index f04a5489b0..ef6a6ac0ca 100644 --- a/electron/mcp/openscreen-mcp-server.test.ts +++ b/electron/mcp/openscreen-mcp-server.test.ts @@ -331,7 +331,9 @@ describe("the MCP tool surface", () => { "setPointerTrack", "exportVideo", "exportAudio", + "getAudioReport", "getFrames", + "getContactSheet", "createProject", ]); for (const tool of tools.slice(1, 1 + OPENSCREEN_TOOL_NAMES.length)) { diff --git a/electron/mcp/stdio-server.ts b/electron/mcp/stdio-server.ts index 2544150758..6e2a25b527 100644 --- a/electron/mcp/stdio-server.ts +++ b/electron/mcp/stdio-server.ts @@ -32,6 +32,7 @@ export async function serveMcpOverStdio(options: { runners: MediaToolDeps["runners"]; openVideo: MediaToolDeps["openVideo"]; renderFrames?: MediaToolDeps["renderFrames"]; + images?: MediaToolDeps["images"]; /** A newer OpenScreen to tell the agent about (update-notice.ts). */ updateNotice?: string; /** The client went away: nothing is left to serve. */ @@ -57,6 +58,7 @@ export async function serveMcpOverStdio(options: { documents: options.documents, openVideo: options.openVideo, renderFrames: options.renderFrames, + images: options.images, readCursor: options.readCursorTelemetry, runTool, }); diff --git a/technical-documentation/architecture/mcp-server.md b/technical-documentation/architecture/mcp-server.md index fcacb1501f..d82e097023 100644 --- a/technical-documentation/architecture/mcp-server.md +++ b/technical-documentation/architecture/mcp-server.md @@ -12,7 +12,7 @@ The same tools are served over two transports, by two different processes: | Edits, recording, export | Off until the user turns on **MCP edits** | Always allowed | | Project open in the editor | Edited live through the editor, one undo step per call | The same while the app runs: the call is forwarded to it. With no app answering, refused ([the marker](#the-open-in-editor-marker)) | | Other projects | Read from and saved to their file, a checkpoint first | Same | -| Tools | `listProjects`, the agent's tools, `transcribe`, the project tools (`setProjectInfo`, `importMedia`, `removeMedia`), the checkpoint tools, and the media tools: `listSources`, `startRecording`, `stopRecording`, `waitForRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `getFrames`, `createProject` | The same | +| Tools | `listProjects`, the agent's tools, `transcribe`, the project tools (`setProjectInfo`, `importMedia`, `removeMedia`), the checkpoint tools, and the media tools: `listSources`, `startRecording`, `stopRecording`, `waitForRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `getAudioReport`, `getFrames`, `getContactSheet`, `createProject` | The same | | A take | Recorded by the app's recording bar, as its Record button records; the editor opens it ([below](#the-media-tools)) | Recorded by a hidden runner of its own process, and made a project there | | Checkpoints | In the app's memory, shared with forwarded `openscreen mcp` calls, lost when the app quits | In the app's while it runs; otherwise in this process's, lost when it exits, which it does when the client disconnects | @@ -211,8 +211,13 @@ Then both servers carry on alike: - `exportVideo` renders in a hidden `cli-export` runner, the same in both processes: in the app, `listSources` and `exportVideo` run the CLI's runners (`createRunnerHost` with `createRunnerWindow`), whose IPC the app registers on first use. The runner reads the project by id (`CliExportRequest.projectId`, the editor's own `aiEdition.get`), not by path: opening a file by path moves the main process's current project and recording-session slot, which in the app is the hand-off from the recorder to the editor. - `exportVideo` takes the Export dialog's options and choices: `quality` and `fps` (24, 30, 60) for an MP4, `gifFrameRate`, `gifSize` and `gifLoop` for a GIF, the dialog's defaults when left out. An option of the other format is refused rather than ignored. Hiding the desktop icons is not a `startRecording` option: the HUD has no such control, so it follows the user's Record mode setting on both servers. Nor are the CLI's `--auto-zoom` and `--audio`: zooms and a voiceover are edits of the project, and an export that added them would not be the project `getFrames` maps through. - `exportAudio` (#1280) is the same runner with `format` `wav` or `m4a`: `CliExportRunner` renders the MP4 beside the output (`audioRenderPath`, removed by `createRunnerHost` once the run reports) and `extractAudio` takes its audio stream out, so the file is the MP4's own mix, not a second mixer's. With `audioId` (`CliExportRequest.audioTrackId`, the CLI's `--track`), `isolateAudioTrack` keeps that track's fragments only, the clips render with `hasAudio: false` and the click sound is dropped: the track alone, where the export places it. There is no option to replace the take's sound for the whole programme: the document has no such switch (the take's gain is bounded at ±12 dB), and an export option would make a file the project does not describe. -- `exportVideo`, `exportAudio` and `getFrames` read projects; they write none. Over HTTP their paths must be absolute. +- `exportVideo`, `exportAudio`, `getAudioReport`, `getFrames` and `getContactSheet` read projects; they write none. Over HTTP their paths must be absolute. - `getFrames` with a `projectId` reads the project's last export while it is current. With no export, or one the project changed after, it renders the frames from the project instead (`renderFrames` in the addon, through the export's own walk), so an agent checks an edit without exporting. See [docs/shader-effects.md](../../docs/shader-effects.md), E.4. +- `getFrames` and `getContactSheet` find their frames the same way (`shotsOf`): explicit `atSec`, or `count` of them, spread over the whole video or from `startSec` to `endSec`, both ends shown. What differs is what they do with them. + - `getFrames` returns each frame as an image, 1280 pixels wide at most. With a `region` it asks for the frame at its own size instead and returns that part of it, so a client reads small text or checks an edge at the export's resolution. + - `getContactSheet` asks for the frames at the width of a tile and lays up to 36 of them on one image, each with its time in its corner ([`contact-sheet.ts`](../../electron/mcp/contact-sheet.ts)). One image is what a client pays for the rhythm of a whole film, or for a zoom or a cut frame by frame. + - The pixel work (decoding a frame, cropping it, encoding the sheet) is Electron's `nativeImage` ([`frame-images.ts`](../../electron/mcp/frame-images.ts)), handed to the tools as `images` so they still import no `electron`. The layout and the labels are plain code on pixel buffers, with a small built-in font for the times: no canvas, no window and no dependency. +- `getAudioReport` is how a client checks a mix it cannot hear. It renders the project's audio to a temporary WAV through `exportAudio`'s own path, so what it measures is the MP4's mix, then removes the file. [`audio-report.ts`](../../electron/mcp/audio-report.ts) reads it in chunks and measures the integrated loudness (ITU-R BS.1770-4 with the EBU R128 gates), the true peak on a signal oversampled four times, and every stretch of half a second or more under -60 dBFS. The stretches are in the export's seconds; the tool maps them back to ruler seconds (`rulerSecOf`), the clock of every other tool. It is not gated by **MCP edits**: it writes nothing a client can reach. - `createProject` makes a project with `DocumentService.createProject`, so it starts in the look new projects take (the preset marked for them, else the last edited project's), as the editor's New does. With a `videoPath` it lays the video out with `createProjectFromVideo`, the path a stdio take goes through: one clip, measured, and the zooms on its clicks when a pointer track sits beside it. Either way it returns a checkpoint, as `stopRecording` does, so the client can edit the closed project at once. It runs where the media tools run (in the CLI process for `openscreen mcp`): a new project is one no editor holds. **MCP edits** gates it. ## `openscreen mcp` and the running app diff --git a/technical-documentation/testing/manual-e2e-checklist.md b/technical-documentation/testing/manual-e2e-checklist.md index 6b46ffc4ea..95887ba26a 100644 --- a/technical-documentation/testing/manual-e2e-checklist.md +++ b/technical-documentation/testing/manual-e2e-checklist.md @@ -597,6 +597,7 @@ Two servers. The **in-app** one is HTTP, in *AI settings* → *MCP server*, off - [ ] Edit that project while it is closed, `restoreCheckpoint` with the returned checkpoint, and confirm the project is back to the raw take. Confirm an edit to a closed project with no checkpoint is refused. - [ ] Open the project in the editor, with the in-app MCP server turned off, then send an edit to it through the **stdio** server, a process apart from the app (#1174): `listProjects` reports the project `open: true`, the edit shows in the editor at once, Ctrl+Z takes it back in one step, and a later change in the editor (its autosave) keeps it. Create a checkpoint while the GUI owns the project, make another edit, and confirm `restoreCheckpoint` lands in the editor as one undo step. Checkpoints are held in the process that created them: a checkpoint returned by stdio `stopRecording` while the GUI was closed is unknown to the GUI. Confirm that refusal leaves the editor unchanged, then create a GUI-owned checkpoint to continue. Quit OpenScreen mid-session: the next stdio edit to that project, now closed, asks for a checkpoint, and after `createCheckpoint` lands in its file. Relaunch OpenScreen and open the project: the next stdio edit goes through the editor again, with no restart of the MCP client. - [ ] `exportVideo`, then `getFrames` at a few ruler seconds after a trim, and confirm the frames show the moments asked for; edit the project again and confirm `getFrames` warns that the export is stale. +- [ ] `getContactSheet` on that project with `startSec`, `endSec` and `count: 12` across a zoom: one image comes back, a grid whose tiles carry their times and show the zoom's move frame by frame. `getFrames` with a `region` over a line of small text returns that part of the frame alone, sharp enough to read. `getAudioReport` on a take with a voice and a silent stretch reports a loudness, a peak and that stretch in ruler seconds, and leaves no file behind. - [ ] On each server, `startRecording` with `camera: true` (then a camera's name from `listSources`) and `cursor: "system"`: the take opens with the webcam as a picture-in-picture, the system pointer is in the video and no zoom was planned. `exportVideo` at `fps: 30` gives a 30 fps MP4; to a `.gif` with `gifSize: "small"` and `gifLoop: false` a GIF 480 pixels high that plays once; `gifLoop` on an `.mp4` path is refused. - [ ] Drive a take from a script instead of the mouse, hand its action log to `setPointerTrack`, and confirm the export draws a cursor and zooms on the logged clicks. From a5d90faddf9be7a927ac1667b2bd5b657b4dacc4 Mon Sep 17 00:00:00 2001 From: EtienneLescot Date: Sun, 22 Nov 2026 13:43:22 +0100 Subject: [PATCH 02/74] feat(mcp): set an annotation's font family from the shipped list --- electron/ai-edition/agent-tools.test.ts | 50 +++++++++++++++++++ electron/ai-edition/agent-tools.ts | 17 ++++++- electron/ai-edition/deep-agent/service.ts | 6 +-- .../architecture/ai-agent.md | 2 +- 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.ts index 44fa595e36..3bd1f2d02d 100644 --- a/electron/ai-edition/agent-tools.test.ts +++ b/electron/ai-edition/agent-tools.test.ts @@ -3505,6 +3505,56 @@ describe("region tools reach the inspector's settings (#1180)", () => { expect(added.payload).toMatchObject({ type: "text", fontSize: 48 }); }); + it("sets a text's font family from the shipped list, refits its box, and refuses another", () => { + const added = run(fixtureDocument(), "addAnnotation", { + startSec: 1, + endSec: 3, + text: "Shipped fonts", + fontFamily: "Oswald", + }); + expect(added.ok).toBe(true); + expect(added.document?.annotations[0].style.fontFamily).toBe("Oswald"); + expect(added.payload).toMatchObject({ fontFamily: "Oswald" }); + expect(snapshot(added.document).annotations[0]).toMatchObject({ fontFamily: "Oswald" }); + + // The box is the size of its words, measured in the face it is drawn in: a new face + // refits it. + vi.stubEnv("OPENSCREEN_FONTS_DIR", path.resolve(__dirname, "../../public/fonts")); + try { + const inShippedFonts = run(fixtureDocument(), "addAnnotation", { + startSec: 1, + endSec: 3, + text: "Shipped fonts", + fontFamily: "Oswald", + }); + const mono = run(inShippedFonts.document as AxcutDocument, "setAnnotation", { + annotationId: inShippedFonts.payload.annotationId, + fontFamily: "IBM Plex Mono", + }); + expect(mono.ok).toBe(true); + const stored = mono.document?.annotations[0]; + expect(stored?.style.fontFamily).toBe("IBM Plex Mono"); + expect(stored?.size.width).toBeGreaterThan( + inShippedFonts.document?.annotations[0].size.width ?? Number.POSITIVE_INFINITY, + ); + } finally { + vi.unstubAllEnvs(); + } + + // The default text reads back the family the renderer draws it in. + const plain = run(fixtureDocument(), "addAnnotation", { startSec: 1, endSec: 3, text: "Hi" }); + expect(plain.payload).toMatchObject({ fontFamily: "Inter" }); + + const comic = run(fixtureDocument(), "addAnnotation", { + startSec: 1, + endSec: 3, + text: "Hi", + fontFamily: "Comic Sans MS", + }); + expect(comic.ok).toBe(false); + expect(comic.document).toBeUndefined(); + }); + it("adds a privacy blur on the recording's picture, sized and placed as asked", () => { const added = run(fixtureDocument(), "addAnnotation", { startSec: 1, diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts index 3cbccdb011..cba4810b09 100644 --- a/electron/ai-edition/agent-tools.ts +++ b/electron/ai-edition/agent-tools.ts @@ -106,6 +106,11 @@ import { } from "../../src/lib/ai-edition/timeline/zoom-transitions"; import { LAYOUT_PRESETS } from "../../src/lib/layoutTypes"; import { SETTING_BOUNDS } from "../../src/lib/projectDefaults"; +import { + resolveTextFontFamily, + TEXT_FONT_FAMILIES, + type TextFontFamily, +} from "../../src/lib/textFonts"; import type { SegmentationSupport } from "../../src/native/contracts"; import { annotationFootageRect, zoomScaleLimit } from "../../src/native/sceneDescription"; import { ASPECT_RATIO_PRESETS } from "../../src/utils/aspectRatioUtils"; @@ -218,6 +223,7 @@ function refuseIfBlocked { text: a.content || a.textContent || "", ...geometry, fontSize: a.style.fontSize, + fontFamily: resolveTextFontFamily(a.style.fontFamily), color: a.style.color, background: a.style.backgroundColor === "transparent" ? "none" : a.style.backgroundColor, bold: a.style.fontWeight === "bold", @@ -925,6 +933,10 @@ const annotationLookArgs = { .max(200) .optional() .describe("Text size; 32 is the editor's default, a title reads well at 56 to 80."), + fontFamily: z + .enum(TEXT_FONT_FAMILIES) + .optional() + .describe("Typeface: one of the families the app ships and draws. Inter by default."), color: z.string().optional().describe("Text colour, a CSS colour such as #ffffff."), background: z .string() @@ -3307,12 +3319,13 @@ export function executeAgentTool( }; const moved = x !== undefined || y !== undefined; if (a.type === "text") { - // A text box is the size of its text: refit it whenever the text, its size or its - // weight changes, around its centre or the new one. One saved before frame placement + // A text box is the size of its text: refit it whenever the text, its size, its font + // or its weight changes, around its centre or the new one. One saved before frame placement // moves onto the frame the first time it is moved, as the editor does. const resized = text !== undefined || parsed.data.fontSize !== undefined || + parsed.data.fontFamily !== undefined || parsed.data.bold !== undefined; return moved || (resized && a.space === "frame") ? placeTextOnFrame(next, centre, document) diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts index b7dafcb93e..657adee5f3 100644 --- a/electron/ai-edition/deep-agent/service.ts +++ b/electron/ai-edition/deep-agent/service.ts @@ -49,6 +49,7 @@ import { ZOOM_DEPTH_LEGEND, } from "../../../src/lib/ai-edition/timeline/zoom-scale"; import { ZOOM_TRANSITION_LEGEND } from "../../../src/lib/ai-edition/timeline/zoom-transitions"; +import { TEXT_FONT_FAMILIES } from "../../../src/lib/textFonts"; import type { AgentTurnUsage, SegmentationSupport } from "../../../src/native/contracts"; import { AGENT_EDITS_SETTING, @@ -270,10 +271,9 @@ export const TOOL_DESCRIPTIONS: Record = { "Add a speed-change region over a span of the edited timeline (virtual seconds). speed > 1 fast-forwards, < 1 slows down, from 0.25× to 16× (default 1.5×). Use to speed through slow stretches without cutting them.", setSpeed: "Move, resize, or change the multiplier of an existing speed region by id (virtual-timeline seconds). Only the fields you pass are changed.", - addAnnotation: - "Add an annotation over a span of the edited timeline (virtual seconds). type picks what it is: 'text' (the default) for callouts, labels and titles; 'figure' for an arrow pointing at something; 'blur' for a privacy mask that blurs or pixelates what is under it, the way to hide an email address, a token, a password field or any private detail the recording shows. Image annotations are not available here: they need a file, added in the editor. x/y place the centre, 0–100 percent of the annotation's box (default the centre). Text and arrows sit on the output frame, the whole picture padding included, as the editor places them: zooms and padding never move them. A blur sits on the recording's picture instead, so x/y/width/height are percent of the recording and it stays on what it hides when padding or a zoom moves the picture. A text box is sized to its words and kept inside the frame; it is drawn on a dark plate by default, and fontSize, color, background, bold and animation set its look. An arrow or a blur takes width/height (default 30 × 20) and its own data: figureData {arrowDirection, color, strokeWidth} for an arrow, blurData {type 'blur' or 'mosaic', shape 'rectangle' or 'oval', color, intensity, blockSize} for a blur. The result reads the annotation back as getCurrentDocument reports it.", + addAnnotation: `Add an annotation over a span of the edited timeline (virtual seconds). type picks what it is: 'text' (the default) for callouts, labels and titles; 'figure' for an arrow pointing at something; 'blur' for a privacy mask that blurs or pixelates what is under it, the way to hide an email address, a token, a password field or any private detail the recording shows. Image annotations are not available here: they need a file, added in the editor. x/y place the centre, 0–100 percent of the annotation's box (default the centre). Text and arrows sit on the output frame, the whole picture padding included, as the editor places them: zooms and padding never move them. A blur sits on the recording's picture instead, so x/y/width/height are percent of the recording and it stays on what it hides when padding or a zoom moves the picture. A text box is sized to its words and kept inside the frame; it is drawn on a dark plate by default, and fontSize, fontFamily (${TEXT_FONT_FAMILIES.join(", ")}; Inter by default), color, background, bold and animation set its look. An arrow or a blur takes width/height (default 30 × 20) and its own data: figureData {arrowDirection, color, strokeWidth} for an arrow, blurData {type 'blur' or 'mosaic', shape 'rectangle' or 'oval', color, intensity, blockSize} for a blur. The result reads the annotation back as getCurrentDocument reports it.`, setAnnotation: - "Change an existing annotation by id: its span (virtual-timeline seconds), its type, its centre (x/y, percent of its box), its size (width/height, arrow and blur only), its text and look (text only: fontSize, color, background, bold, animation), or its figureData / blurData, of which only the keys you pass change. Only the fields you pass are changed. A type change converts it as the editor's type switch does: it stays where it is on screen, a text turned into an arrow or a blur takes the default box, and the text is kept to come back to. A text box is refitted to its text around its centre. Arguments that belong to another kind (width on a text, blurData on an arrow) are refused. A new span that would run into another annotation is refused, naming it.", + "Change an existing annotation by id: its span (virtual-timeline seconds), its type, its centre (x/y, percent of its box), its size (width/height, arrow and blur only), its text and look (text only: fontSize, fontFamily, color, background, bold, animation), or its figureData / blurData, of which only the keys you pass change. Only the fields you pass are changed. A type change converts it as the editor's type switch does: it stays where it is on screen, a text turned into an arrow or a blur takes the default box, and the text is kept to come back to. A text box is refitted to its text around its centre. Arguments that belong to another kind (width on a text, blurData on an arrow) are refused. A new span that would run into another annotation is refused, naming it.", setAspectRatio: "Set the shape of the exported video: 16:9 for X, YouTube or a slide, 9:16 for a vertical story or short, 1:1 or 4:5 for a square feed, auto to follow the recording, or one of the clips' own shapes (getCurrentDocument's settingsContext.originalAspectRatios). Annotations on the frame keep their place and shape. The same as setEditorSettings with aspectRatio alone.", setEditorSettings: diff --git a/technical-documentation/architecture/ai-agent.md b/technical-documentation/architecture/ai-agent.md index 4565da726d..2792cb0e59 100644 --- a/technical-documentation/architecture/ai-agent.md +++ b/technical-documentation/architecture/ai-agent.md @@ -60,7 +60,7 @@ The model never free-writes the project document. `deep-agent/service.ts#buildTo | `setZoom` | Moves, resizes, or restyles a zoom pill: level, focus, `focusMode`, `hideCursor`, 3D camera. Changing `depth` clears any `customScale` on that pill — otherwise the write is a no-op at render — and says so in the result. A `customScale` is written as the inspector writes a typed level (`zoomLevelFor`: to the hundredth, a table level as its depth) and refused past the clip's `zoomScaleLimit`; `depth` with `customScale` is refused. Reports `cursorAnchor` against the zoom's EFFECTIVE focus, read back off the document, so a span-only edit still learns what its unchanged focus now looks at. | The clip-anchored `zoomRanges` fragments represented by that pill. | | `addSpeed` | Adds a clip-anchored speed region over virtual timeline time. | `legacyEditor.speedRegions`. | | `setSpeed` | Moves, resizes, or changes an existing speed pill. | The corresponding `legacyEditor.speedRegions` fragments. | -| `addAnnotation` | Adds a text, arrow (`figure`) or privacy `blur` annotation over virtual timeline time. An arrow or a blur is the editor's text switched through `convertAnnotationKind`, then given its box and its `figureData` / `blurData` (validated by `figureDataSchema` / `blurDataSchema`). Images are left out: they need a file. A freehand blur is refused, as the inspector no longer offers it. | `annotations`. | +| `addAnnotation` | Adds a text, arrow (`figure`) or privacy `blur` annotation over virtual timeline time. An arrow or a blur is the editor's text switched through `convertAnnotationKind`, then given its box and its `figureData` / `blurData` (validated by `figureDataSchema` / `blurDataSchema`). A text's `fontFamily` is one of `TEXT_FONT_FAMILIES`, the faces the compositor ships and draws, and its box is measured in that face. Images are left out: they need a file. A freehand blur is refused, as the inspector no longer offers it. | `annotations`. | | `setAnnotation` | Moves, resizes, retypes or restyles an annotation. A type change goes through `convertAnnotationKind` with the footage under each fragment (`annotationFootageRect`), as the inspector's type switch does; `figureData` / `blurData` merge only the keys sent. Arguments of another kind (width on a text, blurData on an arrow) are refused. | The corresponding clip-anchored `annotations` fragments. | | `addLayoutChange` | Changes the layout from a RAW document-timeline time until the next change. Camera presets require linked camera footage. | The shared `layoutRegions` partition, or the global preset when uniform. | | `setLayoutPreset` | Changes one passage by an ID from `getCurrentDocument.layoutSegments`; equal neighbours merge. An unchanged preset is refused. | The same layout partition. | From b3e05dec7ea83dbaa0fc5297f4d673debf5849ff Mon Sep 17 00:00:00 2001 From: EtienneLescot Date: Sun, 22 Nov 2026 13:47:26 +0100 Subject: [PATCH 03/74] feat(mcp): turn a clip upside down through setClipRange --- electron/ai-edition/agent-tools.test.ts | 50 +++++++++++++++ electron/ai-edition/agent-tools.ts | 42 ++++++++++--- electron/ai-edition/deep-agent/service.ts | 2 +- src/lib/ai-edition/document/timeline.test.ts | 50 +++++++++++++++ src/lib/ai-edition/document/timeline.ts | 63 +++++++++++++++++++ src/lib/ai-edition/store/useTimeline.ts | 57 +---------------- .../architecture/ai-agent.md | 2 +- 7 files changed, 200 insertions(+), 66 deletions(-) diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.ts index 3bd1f2d02d..6d5fef75d9 100644 --- a/electron/ai-edition/agent-tools.test.ts +++ b/electron/ai-edition/agent-tools.test.ts @@ -3872,6 +3872,56 @@ describe("clip structure (#1180)", () => { ]); }); + it("setClipRange turns a clip upside down and back, and the snapshot reads it back", () => { + const crop = { x: 0.1, y: 0.2, width: 0.5, height: 0.6 }; + const cropped = run(twoTakes(), "setClipRange", { clipId: "clip_1", cropRegion: crop }) + .document as AxcutDocument; + const turned = run(cropped, "setClipRange", { clipId: "clip_1", rotation: 180 }); + expect(turned.ok).toBe(true); + const document = turned.document as AxcutDocument; + // The range, the crop (in the recording's own coordinates) and the cut stay as they were. + expect(document.timeline.clips[0]).toMatchObject({ + sourceStartSec: 0, + sourceEndSec: 10, + cropRegion: crop, + rotation: 180, + }); + expect(document.timeline.trimRanges).toHaveLength(1); + expect(JSON.parse(turned.resultJson)).toMatchObject({ rotation: 180, cropRegion: crop }); + expect(() => documentSchema.parse(document)).not.toThrow(); + const snapshot = JSON.parse(run(document, "getCurrentDocument", {}).resultJson); + expect(snapshot.clips[0].rotation).toBe(180); + + const upright = run(document, "setClipRange", { clipId: "clip_1", rotation: 0 }); + expect((upright.document as AxcutDocument).timeline.clips[0]).not.toHaveProperty("rotation"); + const plain = JSON.parse( + run(upright.document as AxcutDocument, "getCurrentDocument", {}).resultJson, + ); + expect(plain.clips[0]).not.toHaveProperty("rotation"); + }); + + it("setClipRange turns the clip's zoom focus with its picture", () => { + const zoomed = run(twoTakes(), "addZoom", { + startSec: 5, + endSec: 7, + focus: { cx: 0.2, cy: 0.3 }, + }); + const turned = run(zoomed.document as AxcutDocument, "setClipRange", { + clipId: "clip_1", + rotation: 180, + }); + expect((turned.document as AxcutDocument).zoomRanges[0].focus).toEqual({ + cx: 0.8, + cy: 0.7, + }); + }); + + it("setClipRange accepts only the rotations the Edit clip dialog offers", () => { + const sideways = run(twoTakes(), "setClipRange", { clipId: "clip_1", rotation: 90 }); + expect(sideways.ok).toBe(false); + expect(sideways.document).toBeUndefined(); + }); + it("setClipRange moves one edge and keeps the other", () => { const result = run(twoTakes(), "setClipRange", { clipId: "clip_1", sourceEndSec: 6 }); expect((result.document as AxcutDocument).timeline.clips[0]).toMatchObject({ diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts index cba4810b09..2db75ec56c 100644 --- a/electron/ai-edition/agent-tools.ts +++ b/electron/ai-edition/agent-tools.ts @@ -22,6 +22,7 @@ import { DEFAULT_ANNOTATION_BOX, fitTextInFrame, } from "../../src/lib/ai-edition/annotations/placement"; +import { clipRotation } from "../../src/lib/ai-edition/clipRotation"; import { AUDIO_FADE_MAX_MS, collapseTracksToPills, @@ -49,6 +50,7 @@ import { removeRegion, replaceTimeline, setClipCrop, + setClipRotation, setClipSourceRange, } from "../../src/lib/ai-edition/document/timeline"; import { setDocumentWordText } from "../../src/lib/ai-edition/document/transcript"; @@ -724,6 +726,12 @@ export const setClipRangeArgs = z.object({ .describe( "The part of the source frame this clip shows, as 0–1 fractions of it ({x, y, width, height}); null shows the whole frame again.", ), + rotation: z + .union([z.literal(0), z.literal(180)]) + .optional() + .describe( + "Turns the clip's picture: 180 shows it upside down (a camera mounted the wrong way up), 0 upright again.", + ), }); /** `beforeClipId`, never an index, for the reason `moveClipArgs` gives. */ @@ -1472,6 +1480,8 @@ export function documentSnapshotForModel( timelineEndSec: c.timelineEndSec, // Only when set: absent is the whole frame. ...(c.cropRegion ? { cropRegion: c.cropRegion } : {}), + // Only when turned: absent is upright. + ...(c.rotation === 180 ? { rotation: 180 } : {}), })), trimRanges: document.timeline.trimRanges.map((s) => ({ id: s.id, @@ -2604,14 +2614,14 @@ export function executeAgentTool( case "setClipRange": { const parsed = setClipRangeArgs.safeParse(args); if (!parsed.success) return failure(parsed.error.message); - const { clipId, cropRegion } = parsed.data; + const { clipId, cropRegion, rotation } = parsed.data; const clip = document.timeline.clips.find((c) => c.id === clipId); if (!clip) return failure(`Unknown clip: ${clipId}. ${clipRoster(document)}`); const ranged = parsed.data.sourceStartSec !== undefined || parsed.data.sourceEndSec !== undefined; - if (!ranged && cropRegion === undefined) { + if (!ranged && cropRegion === undefined && rotation === undefined) { return failure( - "Pass sourceStartSec / sourceEndSec, cropRegion, or both: nothing to change.", + "Pass sourceStartSec / sourceEndSec, cropRegion, rotation, or any of them together: nothing to change.", ); } const start = parsed.data.sourceStartSec ?? clip.sourceStartSec; @@ -2634,10 +2644,14 @@ export function executeAgentTool( cropRegion.width === 1 && cropRegion.height === 1; const crop = cropRegion === undefined ? undefined : wholeFrame ? null : cropRegion; - // One pass for both, as the dialog's Apply: the fold weighs range and crop together. + // The rotation first, as the dialog's Apply does it, then one pass for range and crop: the + // fold weighs range, crop and rotation together. Without a range or a new crop, the clip's + // own crop goes back through `setClipCrop`, which is what folds or splits the neighbours. + const turned = + rotation === undefined ? document : setClipRotation(document, clipId, rotation); const next = ranged - ? setClipSourceRange(document, clipId, sourceStartSec, sourceEndSec, crop) - : setClipCrop(document, clipId, crop ?? null); + ? setClipSourceRange(turned, clipId, sourceStartSec, sourceEndSec, crop) + : setClipCrop(turned, clipId, crop === undefined ? (clip.cropRegion ?? null) : crop); const dropped = droppedByEdit(document, next); const casualties = dropped.droppedModifierIds.length + dropped.droppedTrimIds.length; const after = next.timeline.clips.find((c) => c.id === clipId); @@ -2649,6 +2663,7 @@ export function executeAgentTool( sourceStartSec, sourceEndSec, cropRegion: after?.cropRegion ?? null, + rotation: after ? clipRotation(after) : clipRotation(clip), // Its media now continues the clip before it, with the same framing: one clip. ...(after ? {} @@ -2656,10 +2671,17 @@ export function executeAgentTool( ...dropped, }), summary: - (ranged - ? `trimmed clip to ${formatSec(sourceStartSec)} – ${formatSec(sourceEndSec)}` - : `cropped clip ${clipId}`) + - (ranged && cropRegion !== undefined ? ", cropped" : "") + + [ + ranged + ? `trimmed clip to ${formatSec(sourceStartSec)} – ${formatSec(sourceEndSec)}` + : null, + cropRegion !== undefined ? `cropped clip ${clipId}` : null, + rotation !== undefined + ? `turned clip ${clipId} ${rotation === 180 ? "upside down" : "upright"}` + : null, + ] + .filter(Boolean) + .join(", ") + (casualties > 0 ? ` — dropped ${[...dropped.droppedModifierIds, ...dropped.droppedTrimIds].join(", ")}` : ""), diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts index 657adee5f3..5f2216ee05 100644 --- a/electron/ai-edition/deep-agent/service.ts +++ b/electron/ai-edition/deep-agent/service.ts @@ -253,7 +253,7 @@ export const TOOL_DESCRIPTIONS: Record = { addTrims: `Add MANY trim ranges in one call: \`ranges\` is a list, each entry taking exactly the fields addTrim takes. Use this whenever you have more than one cut to make — 'remove the silences' on a half-hour recording is hundreds of cuts, and sending them one at a time costs one round trip each. Each range stands or falls ALONE: one that cannot be placed is refused by itself and listed in \`refused\` with its index and the reason, while every other range is still applied. Nothing is rolled back, so a single bad bound never costs you the rest. The result leads with requested / appliedCount / refusedCount so you can see a partial outcome without re-reading the document — report what was refused rather than claiming the whole list landed. ${ZOOM_TRANSITIONS_NOTE} Each applied entry carries the same \`cutTransitions\` warning addTrim reports.`, setTrim: `Move or resize an existing trim range by id. Times are source-time seconds. The cut follows to whichever clip the new range lands in, when that clip is unambiguous. ${ZOOM_TRANSITIONS_NOTE} ${CUT_TRANSITIONS_RESULT}`, setClipRange: - "Set a clip's in/out points (source-time seconds) to shorten its head or tail — distinct from a trim (which cuts a span inside the clip) — and/or its crop. Only the fields you pass are changed. All clips are re-laid back-to-back afterwards, so downstream clips shift automatically. Change the range ONLY when the user explicitly asks to shorten or extend a clip. Do NOT use this for 'remove silences' or 'cut pauses' — for those, use addTrim. cropRegion is the part of the source frame the clip shows, {x, y, width, height} in 0–1 fractions of it, per clip as in the editor's Edit clip; null shows the whole frame again. getCurrentDocument reports it on the clip, absent when the clip shows the whole frame. Two neighbouring clips of the same asset whose source ranges meet and whose crops match are one clip: the result says joinedIntoNeighbour when an edit made them so.", + "Set a clip's in/out points (source-time seconds) to shorten its head or tail — distinct from a trim (which cuts a span inside the clip) — and/or its crop and rotation. Only the fields you pass are changed. All clips are re-laid back-to-back afterwards, so downstream clips shift automatically. Change the range ONLY when the user explicitly asks to shorten or extend a clip. Do NOT use this for 'remove silences' or 'cut pauses' — for those, use addTrim. cropRegion is the part of the source frame the clip shows, {x, y, width, height} in 0–1 fractions of it, per clip as in the editor's Edit clip; null shows the whole frame again. getCurrentDocument reports it on the clip, absent when the clip shows the whole frame. rotation 180 turns the clip's picture upside down (a camera mounted the wrong way up), 0 turns it upright again, as the Edit clip dialog's rotation does: the clip's zoom focus and its privacy blurs follow the turned picture, text and arrows on the frame do not move, and cropRegion stays in the recording's own unturned coordinates. getCurrentDocument reports rotation on the clip, absent when upright. Two neighbouring clips of the same asset whose source ranges meet and whose crops and rotations match are one clip: the result says joinedIntoNeighbour when an edit made them so.", moveClip: "Reorder a placed clip: move `clipId` so it plays just before `beforeClipId` (pass null, or omit it, to move it last). Ids come from getCurrentDocument, where each clip carries its `index` and its label in `reason`. This preserves every clip id, every source range, every trim, and the zooms / speed regions / annotations anchored to each clip. This is the tool for 'swap these clips', 'put X first' and 'change the clip order' — replaceTimeline cannot reorder anything.", insertClip: diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.ts index f826e8da82..13b8bcd2f4 100644 --- a/src/lib/ai-edition/document/timeline.test.ts +++ b/src/lib/ai-edition/document/timeline.test.ts @@ -25,6 +25,7 @@ import { resolvePlaybackSegments, restoreFullTimeline, setClipCrop, + setClipRotation, setClipSourceRange, subtractInterval, timelineIntervals, @@ -2059,6 +2060,55 @@ describe("withClipsChanged — rotation", () => { }); }); +describe("setClipRotation — the one shared clip-rotation mutator", () => { + const anchor = { + clipId: "clip_a", + sourceStartSec: 1, + sourceEndSec: 2, + startMs: 1000, + endMs: 2000, + }; + const doc = makeDoc({ + timeline: { ...makeDoc().timeline, clips: [makeClip()] }, + zoomRanges: [{ id: "z1", ...anchor, depth: 3, focus: { cx: 0.2, cy: 0.7 } }], + annotations: [ + { + id: "blur", + ...anchor, + type: "blur", + position: { x: 10, y: 20 }, + size: { width: 30, height: 10 }, + }, + { + id: "text", + ...anchor, + type: "text", + space: "frame", + position: { x: 10, y: 20 }, + size: { width: 30, height: 10 }, + }, + ] as unknown as AxcutDocument["annotations"], + }); + + it("turns the clip, and its zoom focus and footage blurs with it, not what sits on the frame", () => { + const turned = setClipRotation(doc, "clip_a", 180); + expect(turned.timeline.clips[0].rotation).toBe(180); + expect(turned.zoomRanges[0].focus).toEqual({ cx: 0.8, cy: expect.closeTo(0.3, 9) }); + expect(turned.annotations[0].position).toEqual({ x: 60, y: 70 }); + expect(turned.annotations[1].position).toEqual({ x: 10, y: 20 }); + + const back = setClipRotation(turned, "clip_a", 0); + expect(back.timeline.clips[0]).not.toHaveProperty("rotation"); + expect(back.zoomRanges[0].focus).toEqual({ cx: expect.closeTo(0.2, 9), cy: 0.7 }); + }); + + it("moves nothing when the clip already has that rotation", () => { + const upright = setClipRotation(doc, "clip_a", 0); + expect(upright.zoomRanges).toBe(doc.zoomRanges); + expect(upright.annotations).toBe(doc.annotations); + }); +}); + describe("removeClip — delete a clip, close the gap, drop its pills", () => { const doc = () => makeDoc({ diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.ts index da05eca5e3..ab1fa45c1b 100644 --- a/src/lib/ai-edition/document/timeline.ts +++ b/src/lib/ai-edition/document/timeline.ts @@ -4,6 +4,7 @@ // or a new document with updated clips. import { clampToBound } from "../../projectDefaults"; +import { type ClipRotation, clipRotation } from "../clipRotation"; import type { AxcutClip, AxcutClipCropRegion, @@ -1147,6 +1148,68 @@ export function setClipCrop( ); } +/** + * The single mutator for a clip's rotation, shared by the Edit clip dialog and the agent's + * `setClipRange`: `0` removes the field, `180` sets it. Turning the clip moves its content to + * the mirrored point, so the clip's own zoom focus and footage-space privacy blurs (freehand + * outline included) follow it; frame-space annotations, text and arrows do not turn. Clamped + * at 0 like `turnCropRegion`: a box flush against the far edge would turn to -5e-15. + * + * It does not relay or fold the clips: the caller follows it with `setClipSourceRange` or + * `setClipCrop`, which do, so a clip turned in the same edit that makes its media meet an + * upright neighbour is not swallowed by it. An unknown `clipId` is a no-op. Pure. + */ +export function setClipRotation( + document: AxcutDocument, + clipId: string, + rotation: ClipRotation, +): AxcutDocument { + const current = document.timeline.clips.find((c) => c.id === clipId); + const turning = !!current && clipRotation(current) !== rotation; + return { + ...document, + timeline: { + ...document.timeline, + clips: document.timeline.clips.map((c) => { + if (c.id !== clipId) return c; + const { rotation: _old, ...rest } = c; + return rotation === 180 ? { ...rest, rotation: 180 as const } : rest; + }), + }, + zoomRanges: turning + ? document.zoomRanges.map((z) => + z.clipId === clipId + ? { ...z, focus: { ...z.focus, cx: 1 - z.focus.cx, cy: 1 - z.focus.cy } } + : z, + ) + : document.zoomRanges, + annotations: turning + ? document.annotations.map((a) => + a.clipId === clipId && a.type === "blur" && a.space !== "frame" + ? { + ...a, + position: { + x: Math.max(0, 100 - a.position.x - a.size.width), + y: Math.max(0, 100 - a.position.y - a.size.height), + }, + ...(a.blurData?.freehandPoints + ? { + blurData: { + ...a.blurData, + freehandPoints: a.blurData.freehandPoints.map((p) => ({ + x: Math.max(0, 100 - p.x), + y: Math.max(0, 100 - p.y), + })), + }, + } + : {}), + } + : a, + ) + : document.annotations, + }; +} + /** * The single mutator for "narrow/extend a clip's own source in/out" — the edit the * clip's Edit modal, the renderer op dispatcher, and the LLM's `setClipRange` tool all diff --git a/src/lib/ai-edition/store/useTimeline.ts b/src/lib/ai-edition/store/useTimeline.ts index 3171ac416e..e59648bea1 100644 --- a/src/lib/ai-edition/store/useTimeline.ts +++ b/src/lib/ai-edition/store/useTimeline.ts @@ -15,7 +15,7 @@ import { useScopedT } from "@/contexts/I18nContext"; import type { LayoutPreset } from "../../layoutTypes"; import { DEFAULT_TEXT_PLATE } from "../annotations/background"; import { fitTextBox } from "../annotations/placement"; -import { type ClipRotation, clipRotation } from "../clipRotation"; +import type { ClipRotation } from "../clipRotation"; import { collapseTracksToPills, patchAudioTrack, @@ -46,6 +46,7 @@ import { removeClip as removeClipInDocument, removeRegion as removeRegionInDocument, resequenceClips, + setClipRotation, setClipSourceRange, } from "../document/timeline"; import type { @@ -1457,59 +1458,7 @@ export function useTimeline() { ) => { const doc = useProjectStore.getState().document; if (!doc) return; - const current = doc.timeline.clips.find((c) => c.id === clipId); - const turning = rotation !== undefined && !!current && clipRotation(current) !== rotation; - const turned: AxcutDocument = - rotation === undefined - ? doc - : { - ...doc, - timeline: { - ...doc.timeline, - clips: doc.timeline.clips.map((c) => { - if (c.id !== clipId) return c; - const { rotation: _old, ...rest } = c; - return rotation === 180 ? { ...rest, rotation: 180 as const } : rest; - }), - }, - // A stored zoom focus is where the viewer sees it; turning the clip moves that - // content to the mirrored point, so the clip's own zooms follow it. - zoomRanges: turning - ? doc.zoomRanges.map((z) => - z.clipId === clipId - ? { ...z, focus: { ...z.focus, cx: 1 - z.focus.cx, cy: 1 - z.focus.cy } } - : z, - ) - : doc.zoomRanges, - // A footage-space privacy blur must stay on what it hides, so it moves with - // that content, freehand outline included. Frame-space annotations, text and - // figures do not turn. Clamped at 0 like `turnCropRegion`: a box flush against - // the far edge would turn to -5e-15. - annotations: turning - ? doc.annotations.map((a) => - a.clipId === clipId && a.type === "blur" && a.space !== "frame" - ? { - ...a, - position: { - x: Math.max(0, 100 - a.position.x - a.size.width), - y: Math.max(0, 100 - a.position.y - a.size.height), - }, - ...(a.blurData?.freehandPoints - ? { - blurData: { - ...a.blurData, - freehandPoints: a.blurData.freehandPoints.map((p) => ({ - x: Math.max(0, 100 - p.x), - y: Math.max(0, 100 - p.y), - })), - }, - } - : {}), - } - : a, - ) - : doc.annotations, - }; + const turned = rotation === undefined ? doc : setClipRotation(doc, clipId, rotation); const next = setClipSourceRange(turned, clipId, sourceStartSec, sourceEndSec, cropRegion); await saveDocument(next, { history: true }); }, diff --git a/technical-documentation/architecture/ai-agent.md b/technical-documentation/architecture/ai-agent.md index 2792cb0e59..46348b8ca3 100644 --- a/technical-documentation/architecture/ai-agent.md +++ b/technical-documentation/architecture/ai-agent.md @@ -52,7 +52,7 @@ The model never free-writes the project document. `deep-agent/service.ts#buildTo | `addTrims` | Adds many cuts in one call, replaying `addTrim` per entry so the rules cannot drift apart. Each range stands alone: one that cannot be placed is refused by itself and named with its index and reason while the rest are applied, and the result leads with `requested` / `appliedCount` / `refusedCount`. Only a batch where nothing landed is an error. | `timeline.trimRanges`. | | `removeWords` | Cuts spoken words chosen by their `getTranscriptWords` IDs (fillers, a flubbed phrase, a duplicate take), qualified by `assetId` since IDs restart per asset. Every ID is resolved to one recorded asset, valid timestamps and exactly one covering clip before anything is written; a missing, invalid, duplicated, already-cut or ambiguous ID refuses the whole request. Words consecutive in the transcript go out as one `addTrim` span, so a phrase leaves no gaps playing. The result reports each word with the trim actually stored. The transcript is untouched. | `timeline.trimRanges`. | | `setTrim` | Moves or resizes an existing source-time trim. | The matching `timeline.trimRanges` entry. | -| `setClipRange` | Changes a clip's source in/out points and relays clips back-to-back. | The clip range and any anchored regions clamped or removed by the shared timeline mutator. | +| `setClipRange` | Changes a clip's source in/out points and relays clips back-to-back, its crop, and its rotation (`0` or `180`, the Edit clip dialog's choices). A rotation goes through `setClipRotation`, the mutator the dialog's Apply uses, so the clip's zoom focus and footage-space blurs follow the turned picture. | The clip range, crop and rotation, and any anchored regions clamped, removed or turned by the shared timeline mutators. | | `moveClip` | Reorders a placed clip by naming the clip it should play before (`null` = last). Preserves every clip id, source range, trim and anchored modifier. | Timeline clip order; anchored modifiers' derived ms follow their clip. | | `replaceTimeline` | Rebuilds the primary-asset timeline from kept source-time intervals. Preserves the id, origin and label of every clip an interval reproduces exactly, carries existing trims through, and never touches another asset's trims. Refused when it would merge away, shorten or drop a clip, or when the intervals are not ascending (a reorder it cannot perform — the refusal points at `moveClip`). | Timeline clips and trim ranges. | | `addZoom` | Adds a clip-anchored zoom over virtual timeline time. `depth` is an ordinal selecting from `ZOOM_DEPTH_SCALES` (1.25×–5.0×, non-linear); the result reports the resulting `renderedScale`. It also takes the inspector's `focusMode`, `hideCursor` and `customScale`, under the same rules as `setZoom`. When the pointer track can be read for the footage under the span it also reports `cursorAnchor`: the `focus` the call used (default included) beside the median recorded pointer position over the span the zoom LANDED on, with `spread`, `offset` and the sample count. The source windows come from the stored fragments' own `sourceStartSec`/`sourceEndSec`, so a clamped or split zoom is described by the windows it really occupies; trimmed instants are left out; and the field is OMITTED — never guessed, never turned into an absence of data — when no track covers that footage. | `zoomRanges`. | From e6a90f9eeb447bb0d9e230d4d35e67c2ebd2da4f Mon Sep 17 00:00:00 2001 From: EtienneLescot Date: Sun, 22 Nov 2026 13:55:05 +0100 Subject: [PATCH 04/74] feat(mcp): list and apply style presets --- electron/ai-edition/agent-tools.test.ts | 1 + electron/ai-edition/agent-tools.ts | 24 +++- electron/ai-edition/chat-service.ts | 4 + .../ai-edition/deep-agent/service.test.ts | 50 +++++++ electron/ai-edition/deep-agent/service.ts | 32 ++++- .../ai-edition/editor-settings-tool.test.ts | 97 ++++++++++++++ electron/ai-edition/editor-settings-tool.ts | 123 +++++++++++++++++- electron/ipc/handlers.ts | 2 + electron/mcp/openscreen-mcp-server.ts | 4 + .../architecture/ai-agent.md | 2 + .../architecture/mcp-server.md | 2 +- 11 files changed, 337 insertions(+), 4 deletions(-) diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.ts index 6d5fef75d9..bc9e42ed17 100644 --- a/electron/ai-edition/agent-tools.test.ts +++ b/electron/ai-edition/agent-tools.test.ts @@ -221,6 +221,7 @@ describe("the mutating-tool table", () => { "setEffect", "setEffectDefinition", "setEditorSettings", + "applyStylePreset", "setLayoutPreset", "setSpeed", "setTrim", diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.ts index 2db75ec56c..fbe3763ef7 100644 --- a/electron/ai-edition/agent-tools.ts +++ b/electron/ai-edition/agent-tools.ts @@ -75,6 +75,7 @@ import { storedShaderEffectValues, } from "../../src/lib/ai-edition/shaderEffects"; import { getEditorSettings } from "../../src/lib/ai-edition/store/editorSettings"; +import type { StylePreset } from "../../src/lib/ai-edition/stylePresets"; import { appendAutoZoomSuggestions } from "../../src/lib/ai-edition/timeline/apply-auto-zooms"; import { hasAnyClipWithCamera } from "../../src/lib/ai-edition/timeline/camera"; import { isGeneratedAssetId } from "../../src/lib/ai-edition/timeline/clip-parts"; @@ -117,7 +118,12 @@ import type { SegmentationSupport } from "../../src/native/contracts"; import { annotationFootageRect, zoomScaleLimit } from "../../src/native/sceneDescription"; import { ASPECT_RATIO_PRESETS } from "../../src/utils/aspectRatioUtils"; import { CAPTION_TOOL_NAMES, executeCaptionTool, MUTATING_CAPTION_TOOLS } from "./caption-tools"; -import { editorSettingsSnapshot, executeSetEditorSettings } from "./editor-settings-tool"; +import { + editorSettingsSnapshot, + executeApplyStylePreset, + executeListStylePresets, + executeSetEditorSettings, +} from "./editor-settings-tool"; import { measureTextInShippedFonts } from "./text-measure"; export interface AgentToolExecution { @@ -1180,6 +1186,8 @@ export const OPENSCREEN_TOOL_NAMES = [ "removeClip", "setAspectRatio", "setEditorSettings", + "listStylePresets", + "applyStylePreset", ...CAPTION_TOOL_NAMES, ] as const; @@ -1264,6 +1272,7 @@ export const MUTATING_TOOL_NAMES: ReadonlySet = new Set([ "removeClip", "setAspectRatio", "setEditorSettings", + "applyStylePreset", ...MUTATING_CAPTION_TOOLS, ]); @@ -1837,6 +1846,9 @@ export interface AgentToolOptions { /** `addAutoZooms`' plan, made by the async wrapper from the recorded clicks. Absent means * no cursor reader is wired here, which the tool reports as "could not look". */ autoZooms?: AutoZoomPlan; + /** The user's saved style presets, read by the async wrapper for the two preset tools. + * Absent where nothing can read them: only the built-in one is offered, and that is said. */ + stylePresets?: StylePreset[]; } /** What the timeline wand would add, and what each recording's cursor read gave. */ @@ -2081,6 +2093,16 @@ export function executeAgentTool( }; } + case "listStylePresets": + return executeListStylePresets(document, options?.stylePresets); + case "applyStylePreset": + return executeApplyStylePreset( + document, + args, + options?.stylePresets, + options?.cameraSegmentation?.() ?? null, + ); + case "setEditorSettings": return executeSetEditorSettings(document, args, options?.cameraSegmentation?.() ?? null); diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.ts index e1ea71ee7a..dfe905d856 100644 --- a/electron/ai-edition/chat-service.ts +++ b/electron/ai-edition/chat-service.ts @@ -18,6 +18,7 @@ import { documentSchema, } from "../../src/lib/ai-edition/schema"; import type { ShaderEffectChecker } from "../../src/lib/ai-edition/shaderEffects"; +import type { StylePreset } from "../../src/lib/ai-edition/stylePresets"; import type { AgentTurnUsage, AiEditionChatMessage, @@ -327,6 +328,8 @@ export interface ChatRunEnv { cameraSegmentation?: () => SegmentationSupport; /** The compositor's check of an agent-written effect's WGSL. */ checkShaderEffect?: ShaderEffectChecker; + /** The user's saved style presets (`StylePresetService.list`). */ + stylePresets?: () => Promise; /** Runtime-only model retry override used by bounded measurement harnesses. */ maxRetries?: number; } @@ -518,6 +521,7 @@ export async function runChat( cursor: env.cursor, cameraSegmentation: env.cameraSegmentation, checkShaderEffect: env.checkShaderEffect, + stylePresets: env.stylePresets, }); const executionSteps = execution.finish(Boolean(result.cancelled)); diff --git a/electron/ai-edition/deep-agent/service.test.ts b/electron/ai-edition/deep-agent/service.test.ts index 839d33a0a7..25ce58e201 100644 --- a/electron/ai-edition/deep-agent/service.test.ts +++ b/electron/ai-edition/deep-agent/service.test.ts @@ -24,6 +24,8 @@ import { createEmptyDocument, documentSchema, } from "../../../src/lib/ai-edition/schema"; +import type { StylePreset } from "../../../src/lib/ai-edition/stylePresets"; +import { factoryStylePresetAppearance } from "../../../src/lib/ai-edition/stylePresetsEditor"; import { ZOOM_DEPTH_LEGEND, ZOOM_DEPTH_SCALES, @@ -115,6 +117,8 @@ const ARGS: Record = { removeClip: { clipId: "clip_1" }, setAspectRatio: { aspectRatio: "16:9" }, setEditorSettings: { padding: 30 }, + listStylePresets: {}, + applyStylePreset: { presetId: "openscreen-factory" }, getCaptions: {}, setCaptionSettings: { enabled: true, style: "bold" }, getCaptionTranslationUnits: { language: "fr" }, @@ -445,6 +449,7 @@ describe("one description of the tools, not two", () => { "getTranscriptWords", "getCursorTrack", "getEffect", + "listStylePresets", "getCaptions", "getCaptionTranslationUnits", ]); @@ -823,6 +828,51 @@ describe("addAutoZooms reads the clicks through the runtime's cursor reader", () }); }); +describe("the style preset tools read the saved presets before the executor runs", () => { + const preset = (padding: number): StylePreset => ({ + id: "Roomy", + name: "Roomy", + updatedAt: "2026-11-01T00:00:00.000Z", + appearance: { ...factoryStylePresetAppearance(), padding }, + }); + + it("hands the executor the list the runtime reads, and only to those two tools", async () => { + let reads = 0; + const runtime = { + stylePresets: async () => { + reads += 1; + return [preset(40)]; + }, + }; + const listed = await runDocumentTool(fixtureDocument(), "listStylePresets", {}, true, runtime); + expect(JSON.parse(listed.resultJson).presets.map((p: { id: string }) => p.id)).toEqual([ + "openscreen-factory", + "Roomy", + ]); + const applied = await runDocumentTool( + fixtureDocument(), + "applyStylePreset", + { presetId: "Roomy" }, + true, + runtime, + ); + expect(applied.ok).toBe(true); + expect(JSON.parse(applied.resultJson).settings.padding).toBe(40); + await runDocumentTool(fixtureDocument(), "getCurrentDocument", {}, true, runtime); + expect(reads).toBe(2); + }); + + it("reports a folder that cannot be read rather than failing the call", async () => { + const result = await runDocumentTool(fixtureDocument(), "listStylePresets", {}, true, { + stylePresets: async () => { + throw new Error("EACCES"); + }, + }); + expect(result.ok).toBe(true); + expect(JSON.parse(result.resultJson).warning).toContain("could not be read"); + }); +}); + describe("an effect's code is checked off the main thread, before the executor reads it", () => { const LEVEL = { type: "number", name: "level", label: "Level", default: 1, min: 0, max: 2 }; const effect = (code: string) => ({ diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.ts index 5f2216ee05..5c4a04d0f2 100644 --- a/electron/ai-edition/deep-agent/service.ts +++ b/electron/ai-edition/deep-agent/service.ts @@ -38,6 +38,7 @@ import { AUDIO_FADE_MAX_MS } from "../../../src/lib/ai-edition/document/audioTra import { VOCABULARY_MAX_CHARS } from "../../../src/lib/ai-edition/document/transcript"; import type { AxcutDocument } from "../../../src/lib/ai-edition/schema"; import type { ShaderEffectChecker } from "../../../src/lib/ai-edition/shaderEffects"; +import type { StylePreset } from "../../../src/lib/ai-edition/stylePresets"; import { collectAutoZoomSuggestionsForDocument } from "../../../src/lib/ai-edition/timeline/apply-auto-zooms"; // ponytail: the legend is DERIVED from the depth→scale table, not retyped. Both // tool descriptions used to assert "depth 1–6 maps to 1.0×–3.5×" — a formula @@ -110,7 +111,11 @@ import { executionText, toolExecutionStep, } from "../chat-execution"; -import { setEditorSettingsArgs } from "../editor-settings-tool"; +import { + applyStylePresetArgs, + listStylePresetsArgs, + setEditorSettingsArgs, +} from "../editor-settings-tool"; import { abortable } from "./cancellation"; import { createOpenScreenChatModel, @@ -278,6 +283,10 @@ export const TOOL_DESCRIPTIONS: Record = { "Set the shape of the exported video: 16:9 for X, YouTube or a slide, 9:16 for a vertical story or short, 1:1 or 4:5 for a square feed, auto to follow the recording, or one of the clips' own shapes (getCurrentDocument's settingsContext.originalAspectRatios). Annotations on the frame keep their place and shape. The same as setEditorSettings with aspectRatio alone.", setEditorSettings: 'Change the project\'s look: pass only the settings to change, named as getCurrentDocument returns them under `settings`. Background: wallpaper (a bundled path from settingsContext.bundledWallpapers, a CSS colour or gradient, or a base64 PNG/JPEG data URL; never a file path or web URL; an embedded image reads back as a marker, leave the key out to keep it), wallpaperMotion (moves a gradient or image only), backgroundBlur 0–1. Frame: aspectRatio ("auto", a preset, or an originalAspectRatios token; a fixed format picked for the first time fills the frame with a window that follows the cursor, which formatFollowCursor turns off when settingsContext.formatFill is "available"), padding 0–100 %, borderRadius 0–64 px, shadowIntensity 0–1, frame (none, window, laptop, phone, monitor) and frameTheme (light, dark), motionBlurAmount 0–1, depthOfField (blurs 3D-tilted zooms only). Camera: webcamLayoutPreset, webcamMirrored, webcamReactiveZoom (shrinks on zoom), webcamMaskShape (square or rectangle, the camera\'s own proportions; an untouched roundness follows it), webcamRoundness 0–1, webcamSizePreset 15–60, webcamAnchor (a corner or an edge middle), webcamCropRegion (the framing: a square share of the picture, width = height ≥ 1/3) and webcamCropPan (where that window sits, 0–1 per axis, 0.5 centred), webcamBackgroundMode (none, transparent, blur, custom: needs settingsContext.cameraSegmentation ready), webcamBlurIntensity 0–1, webcamWallpaper (as wallpaper). Cursor, under `cursor`: show, autoHide, theme (settingsContext.cursorThemes), asArrow (the recorded cursor kinds drawn as the arrow instead), size 1.5–6, smoothing 0–1, motionBlur 0–1, clickBounce 0–2, clickImpact, clickSound (only heard when the take recorded clicks) and clickSoundGainDb −24–0, model3d. Also autoFocusAll (every zoom follows the cursor), audioGainDb −12–12 dB, the master volume, and recordingMuted (silences the recording\'s own sound in the preview and the export; added audio tracks still play). A value out of range or a key not listed is refused with the reason, and nothing changes. The result lists what was applied, including what the editor changes with it, and `inactive` for any of those the current state leaves without effect.', + listStylePresets: + "List the style presets the editor's Style presets menu offers: the built-in OpenScreen look first, then the user's saved presets. Each comes with its id, name, builtIn, forNewProjects when new projects start from it, `look` (the settings it applies, in the editor's settings shape, embedded images elided) and `active`, true for the one preset whose look is the project's look now (at most one). Takes no arguments. `warning` says when the saved presets could not be read from here and only the built-in one is listed.", + applyStylePreset: + "Apply a style preset by its id from listStylePresets, as the editor's Style presets menu applies it: the whole look in one edit (background, frame, padding, corners, shadow, blur, output format, camera shape and style, cursor look). A preset is the project's look, never its content: clips, cuts, zooms, annotations, captions and audio are untouched. The result gives the project's settings after it, in getCurrentDocument's `settings` shape, and `inactive` for any setting the current state leaves without effect. setEditorSettings changes single settings afterwards.", addEffect: "Write a visual effect as a shader and pose it over a span of the edited timeline (virtual seconds), or pose one of this project's effects again (effectId). Use it for a look the settings do not offer. `effect.code` is WGSL that defines `fn effect(uv: vec2) -> vec4`, called for every pixel; uv is 0..1 with (0,0) top-left. Available inside it: `frame(uv)` samples the composed picture; `footage(p)` samples the recording itself at its own resolution at point p of its surface (the space of `fx_to_footage`), transparent outside 0..1, with no cursor or webcam on it: read it for anything that magnifies, frame() for the rest; `params.` reads each declared parameter; `ctx.time` is programme seconds; `ctx.region.x` goes 0 to 1 across the region (y its length in s, z seconds since it began); `ctx.resolution` and `ctx.aspect`; `ctx.cursor` (xy in uv, z = 1 when on screen); `ctx.clicks[0..3]`, the last four clicks, newest first (xy in uv where it happened, z seconds since, w = 1 when the slot holds one); `ctx.footage` and `ctx.camera`, the recording's and the webcam's rects (x, y, w, h in uv; camera zero-sized when absent) — all already placed through zoom and layout; `fx_to_footage(uv)` and `fx_from_footage(p)` map between output uv and the recording's own surface (0..1 across the recording) through the warp the compositor draws it with, zoom, layout and 3D camera included, and `ctx.footage_aspect` is its width over height: the effect works in whichever of the two spaces fits it; `fx_px(n)`, n pixels of a 1080p frame as a fraction of the height; `fx_hash(vec2)`, a random number in [0,1) identical on every GPU. Rules: the effect is a pure function of those inputs (no state between frames), so the preview and the export show the same pixels; reason in uv or fx_px, never raw pixels; every loop is a `for` with literal bounds (`for (var i = 0; i < 16; i++)`), at most 4096 iterations per pixel — the one hard rule. `params` declares up to 8 (recommended) parameters, each `{type: number|toggle|color|point, name, label, default}` (number also `min`, `max`); declare one only when moving it visibly changes the effect over its whole range. `target`: `image` (default: the picture under the annotations and captions), `text` (the annotations and captions alone, premultiplied alpha), `both` (everything); use text or both only when asked. One effect runs at a time: to combine two looks, write them in one shader. The result gives the cost tier, in frame() and footage() reads per pixel, with what a 1080p frame pays on a fast discrete GPU (RTX 4070 Ti) and on an integrated one (Apple M1): light ≤ 8, up to 0.06 ms and 1.3 ms; medium ≤ 32, 0.14 ms and 4.3 ms; heavy ≤ 128, 0.54 ms and 16 ms; very heavy beyond, 2 ms and 49 ms at 512 reads. It also gives a recommendation when the tier runs long: light anywhere, medium up to a minute, heavy up to 10 s, very heavy a few seconds. It is a recommendation, never a refusal. Code that does not compile is refused with the compiler's error at the line of your code: fix it and call again. Check the result with getFrames.", setEffect: @@ -347,8 +356,16 @@ export interface ToolRuntime { cameraSegmentation?: () => SegmentationSupport; /** Asks the compositor to check an effect's WGSL. */ checkShaderEffect?: ShaderEffectChecker; + /** Reads the user's saved style presets (`StylePresetService.list`). */ + stylePresets?: () => Promise; } +/** The tools that read the user's saved style presets before the executor runs. */ +const TOOLS_READING_STYLE_PRESETS: ReadonlySet = new Set([ + "listStylePresets", + "applyStylePreset", +]); + /** * The tools whose RESULT depends on the recorded pointer track, so the async * wrapper knows to do the read before entering the synchronous executor. @@ -493,6 +510,13 @@ export async function runDocumentTool( await runtime.checkShaderEffect(effectSource.code, effectSource.params), ) : undefined; + const stylePresets = + TOOLS_READING_STYLE_PRESETS.has(name) && runtime.stylePresets + ? await runtime.stylePresets().catch((error) => { + console.warn("[agent] style presets unavailable:", error); + return undefined; + }) + : undefined; // Async work above is read-only. An abort discards its result before the // synchronous executor or document holder can commit anything. runtime.signal?.throwIfAborted(); @@ -502,6 +526,7 @@ export async function runDocumentTool( cameraSegmentation: runtime.cameraSegmentation, checkShaderEffect, autoZooms, + stylePresets, }); } @@ -625,6 +650,8 @@ export const TOOL_ARG_SCHEMAS: ReadonlyArray = [ ["removeClip", removeClipArgs], ["setAspectRatio", setAspectRatioArgs], ["setEditorSettings", setEditorSettingsArgs], + ["listStylePresets", listStylePresetsArgs], + ["applyStylePreset", applyStylePresetArgs], ["getCaptions", getCaptionsArgs], ["setCaptionSettings", setCaptionSettingsArgs], ["getCaptionTranslationUnits", getCaptionTranslationUnitsArgs], @@ -673,6 +700,8 @@ export interface InvokeArgs { cameraSegmentation?: () => SegmentationSupport; /** Injected the same way: the compositor's check of an effect's WGSL. */ checkShaderEffect?: ShaderEffectChecker; + /** Injected the same way: the user's saved style presets. */ + stylePresets?: () => Promise; } /** One cheap probe per asset, run before the tools are built so the very first @@ -775,6 +804,7 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise { expect(inactive["cursor.model3d"]).toMatch(/hidden/); }); }); + +describe("style presets", () => { + const look = { + ...factoryStylePresetAppearance(), + padding: 12, + borderRadius: 30, + aspectRatio: "9:16" as const, + wallpaper: "#123456", + }; + const saved: StylePreset[] = [ + { id: "Vertical", name: "Vertical", updatedAt: "2026-11-01T00:00:00.000Z", appearance: look }, + ]; + const list = (document: AxcutDocument, presets: StylePreset[] | undefined) => + JSON.parse( + executeAgentTool(document, "listStylePresets", "", { stylePresets: presets }).resultJson, + ); + // `null`: nothing could read the saved presets. + const apply = ( + document: AxcutDocument, + presetId: string, + presets: StylePreset[] | null = saved, + ) => + executeAgentTool(document, "applyStylePreset", JSON.stringify({ presetId }), { + stylePresets: presets ?? undefined, + }); + + it("lists the built-in look first, then the saved ones, and lights the one in use", () => { + const listed = list(fixture(), saved); + expect(listed.presets.map((p: { id: string }) => p.id)).toEqual([ + "openscreen-factory", + "Vertical", + ]); + expect(listed.presets[0]).toMatchObject({ name: "OpenScreen", builtIn: true, active: true }); + expect(listed.presets[1]).toMatchObject({ + builtIn: false, + active: false, + look: { padding: 12, aspectRatio: "9:16" }, + }); + expect(listed).not.toHaveProperty("warning"); + }); + + it("applies a preset's whole look as the menu does, and leaves the content alone", () => { + const document = fixture(); + const applied = apply(document, "Vertical"); + expect(applied.ok).toBe(true); + const next = applied.document as AxcutDocument; + expect(() => documentSchema.parse(next)).not.toThrow(); + expect(stylePresetAppearanceFromSettings(getEditorSettings(next))).toEqual(look); + expect(next.timeline).toEqual(document.timeline); + expect(JSON.parse(applied.resultJson)).toMatchObject({ + presetId: "Vertical", + name: "Vertical", + settings: { padding: 12, borderRadius: 30, aspectRatio: "9:16" }, + }); + expect(list(next, saved).presets.map((p: { active: boolean }) => p.active)).toEqual([ + false, + true, + ]); + + // And back to the built-in look. + const reset = apply(next, "openscreen-factory").document as AxcutDocument; + expect(stylePresetAppearanceFromSettings(getEditorSettings(reset))).toEqual( + factoryStylePresetAppearance(), + ); + }); + + it("refuses an unknown preset, naming the ones there are", () => { + const unknown = apply(fixture(), "Nope"); + expect(unknown.ok).toBe(false); + expect(unknown.document).toBeUndefined(); + expect(unknown.resultJson).toContain("Vertical (Vertical)"); + }); + + it("says so when the saved presets cannot be read, and still offers the built-in one", () => { + const listed = list(fixture(), undefined); + expect(listed.presets).toHaveLength(1); + expect(listed.warning).toContain("could not be read"); + expect(apply(fixture(), "openscreen-factory", null).ok).toBe(true); + expect(apply(fixture(), "Vertical", null).resultJson).toContain("could not be read"); + }); + + it("is a write, refused while edits are off", () => { + const refused = executeAgentTool( + fixture(), + "applyStylePreset", + JSON.stringify({ presetId: "openscreen-factory" }), + { editsAllowed: false }, + ); + expect(refused.ok).toBe(false); + expect(refused.document).toBeUndefined(); + }); +}); diff --git a/electron/ai-edition/editor-settings-tool.ts b/electron/ai-edition/editor-settings-tool.ts index 9b708b957e..20fd1adec5 100644 --- a/electron/ai-edition/editor-settings-tool.ts +++ b/electron/ai-edition/editor-settings-tool.ts @@ -30,7 +30,18 @@ import { panOfCropRegion, } from "../../src/lib/ai-edition/store/editorSettings"; import { applySettingsPatch } from "../../src/lib/ai-edition/store/settingsPatch"; -import { parseStylePresetWallpaper } from "../../src/lib/ai-edition/stylePresets"; +import { + FACTORY_STYLE_PRESET_ID, + parseStylePresetWallpaper, + type StylePreset, + type StylePresetAppearance, +} from "../../src/lib/ai-edition/stylePresets"; +import { + factoryStylePresetAppearance, + sameStylePresetLook, + stylePresetAppearanceFromSettings, + stylePresetPatch, +} from "../../src/lib/ai-edition/stylePresetsEditor"; import { hasAnyClipWithCamera } from "../../src/lib/ai-edition/timeline/camera"; import { resolveWebcamLayoutPreset, @@ -460,3 +471,113 @@ export function executeSetEditorSettings( summary: `set ${keys.join(", ")}`, }; } + +// ---- Style presets ------------------------------------------------------------------- +// The editor's Style presets menu, for the agent: a preset is the project's LOOK, never its +// content, applied as the menu applies it (`stylePresetPatch`, one settings patch). The presets +// themselves are files the main process reads (`StylePresetService`); the async wrapper reads +// them and hands this pure layer the list. + +export const listStylePresetsArgs = z.object({}); + +export const applyStylePresetArgs = z.object({ + presetId: z.string().min(1).describe("A preset id from listStylePresets."), +}); + +/** The menu's built-in row: the look a new project has before anything is changed. */ +const FACTORY_PRESET_NAME = "OpenScreen"; + +/** The menu's rows, built-in first, as it orders them. */ +function presetRows(presets: StylePreset[]) { + return [ + { + id: FACTORY_STYLE_PRESET_ID, + name: FACTORY_PRESET_NAME, + builtIn: true, + appearance: factoryStylePresetAppearance(), + }, + ...presets.map((preset) => ({ + id: preset.id, + name: preset.name, + builtIn: false, + appearance: preset.appearance, + ...(preset.forNewProjects ? { forNewProjects: true } : {}), + })), + ]; +} + +const PRESETS_UNREADABLE = + "The saved style presets could not be read from here; only the built-in one is listed."; + +/** A preset's look as the model reads it: its embedded images elided. */ +function appearanceForModel(appearance: StylePresetAppearance) { + return { + ...appearance, + wallpaper: elideDataUrl(appearance.wallpaper), + webcamWallpaper: elideDataUrl(appearance.webcamWallpaper), + }; +} + +/** + * Every preset, built-in first, each with its look and whether it is the project's look now. + * At most one reads as active, the first match in menu order, as the menu lights one row. + * `presets` absent: nothing here can read the folder, which is said rather than listed as none. + */ +export function executeListStylePresets( + document: AxcutDocument, + presets: StylePreset[] | undefined, +): AgentToolExecution { + const current = stylePresetAppearanceFromSettings(getEditorSettings(document)); + const rows = presetRows(presets ?? []); + const activeId = rows.find((row) => sameStylePresetLook(row.appearance, current))?.id ?? null; + return { + ok: true, + resultJson: JSON.stringify({ + presets: rows.map(({ appearance, ...row }) => ({ + ...row, + active: row.id === activeId, + look: appearanceForModel(appearance), + })), + ...(presets ? {} : { warning: PRESETS_UNREADABLE }), + }), + }; +} + +/** The menu's apply: the whole look as one patch, through the editor's own write. */ +export function executeApplyStylePreset( + document: AxcutDocument, + args: unknown, + presets: StylePreset[] | undefined, + segmentation: SegmentationSupport | null, +): AgentToolExecution { + const parsed = applyStylePresetArgs.safeParse(args); + if (!parsed.success) { + return { ok: false, resultJson: JSON.stringify({ error: parsed.error.message }) }; + } + const rows = presetRows(presets ?? []); + const row = rows.find((r) => r.id === parsed.data.presetId); + if (!row) { + const known = rows.map((r) => `${r.id} (${r.name})`).join(", "); + const error = presets + ? `Unknown style preset: ${parsed.data.presetId}. The presets are: ${known}.` + : `Unknown style preset: ${parsed.data.presetId}. ${PRESETS_UNREADABLE} It is ${known}.`; + return { ok: false, resultJson: JSON.stringify({ error }) }; + } + const next = applySettingsPatch( + document, + stylePresetPatch(row.appearance), + measureTextInShippedFonts, + ); + const inactive = inactiveSettings(next, segmentation); + return { + ok: true, + document: next, + resultJson: JSON.stringify({ + presetId: row.id, + name: row.name, + settings: settingsForModel(next), + ...(Object.keys(inactive).length ? { inactive } : {}), + }), + summary: `applied style preset "${row.name}"`, + }; +} diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts index ead5b9bdc6..725c9e5ae3 100644 --- a/electron/ipc/handlers.ts +++ b/electron/ipc/handlers.ts @@ -5406,6 +5406,7 @@ export function registerIpcHandlers( cursor: agentCursorTelemetryReader, cameraSegmentation: () => loudnessService.probeSegmentation(), checkShaderEffect: (code, params) => loudnessService.checkShaderEffect(code, params), + stylePresets: () => stylePresets.list(), // The editor's own engine, in this process: `openscreen mcp` transcribes without the app. transcribe: (request) => getSttManager().transcribe(request), version: app.getVersion(), @@ -5592,6 +5593,7 @@ export function registerIpcHandlers( cursor: agentCursorTelemetryReader, cameraSegmentation: () => loudnessService.probeSegmentation(), checkShaderEffect: (code, params) => loudnessService.checkShaderEffect(code, params), + stylePresets: () => stylePresets.list(), }), undoAiEditionToolBatch: (_projectId, _sessionId) => ({ success: false, diff --git a/electron/mcp/openscreen-mcp-server.ts b/electron/mcp/openscreen-mcp-server.ts index 774f3ccde0..688024da36 100644 --- a/electron/mcp/openscreen-mcp-server.ts +++ b/electron/mcp/openscreen-mcp-server.ts @@ -55,6 +55,7 @@ import { } from "../../src/lib/ai-edition/document/transcript"; import { type AxcutDocument, documentSchema } from "../../src/lib/ai-edition/schema"; import type { ShaderEffectChecker } from "../../src/lib/ai-edition/shaderEffects"; +import type { StylePreset } from "../../src/lib/ai-edition/stylePresets"; import { segmentsFromStt, transcriptFromSegments, @@ -174,6 +175,8 @@ export interface McpToolDeps extends ImportMediaDeps { cameraSegmentation?: () => SegmentationSupport; /** The compositor's check of an agent-written effect's WGSL; absent where nothing can ask. */ checkShaderEffect?: ShaderEffectChecker; + /** The user's saved style presets (`StylePresetService.list`); absent where none can be read. */ + stylePresets?: () => Promise; /** The main process's on-device Whisper (`SttManager.transcribe`). Absent: no transcribe tool. */ transcribe?(request: SttTranscribeRequest): Promise; version: string; @@ -587,6 +590,7 @@ export function createToolRunner(deps: McpToolDeps): McpToolRunner { availableByAssetId, cameraSegmentation: deps.cameraSegmentation, checkShaderEffect: deps.checkShaderEffect, + stylePresets: deps.stylePresets, }); } diff --git a/technical-documentation/architecture/ai-agent.md b/technical-documentation/architecture/ai-agent.md index 46348b8ca3..7fcd5de82b 100644 --- a/technical-documentation/architecture/ai-agent.md +++ b/technical-documentation/architecture/ai-agent.md @@ -69,6 +69,8 @@ The model never free-writes the project document. `deep-agent/service.ts#buildTo | `setEffect` | Moves, re-tunes (`values`) or retargets an effect pill. | The pill's `shaderEffectRanges` fragments. | | `setEffectDefinition` | Changes an effect's name, description, code or parameters, and so every region using it; new code is checked first. A removed parameter's values drop. | The `shaderEffects` entry and its regions' `values`. | | `getEffect` | Reads one effect in full, code included; `getCurrentDocument` lists effects without their code. | Read only. | +| `listStylePresets` | Lists the Style presets menu: the built-in look first, then the saved presets read through `ToolRuntime.stylePresets`, each with its look and `active`. | Nothing. | +| `applyStylePreset` | Applies a preset as the menu does, `stylePresetPatch` through `applySettingsPatch`: the look, never the content. | `legacyEditor` look settings. | | `removeTrim` | Deletes a trim so its source span plays and exports again. | `timeline.trimRanges`. | | `removeModifier` | Resolves and deletes a zoom, speed, annotation, layout change, audio, or effect by ID; `removedIds` lists the identifiers of the removed items. Audio IDs identify whole tracks (track groups), even when a track contains multiple stored fragments. Removing a layout change extends the preceding passage; the first passage is protected. | The matching modifier collection. | | `removeClip` | Deletes a placed clip, closes the gap, and drops effects anchored only to it. The result names the modifiers and trims it took with it. | Timeline clips and affected anchored modifiers. | diff --git a/technical-documentation/architecture/mcp-server.md b/technical-documentation/architecture/mcp-server.md index d82e097023..fb55db174e 100644 --- a/technical-documentation/architecture/mcp-server.md +++ b/technical-documentation/architecture/mcp-server.md @@ -57,7 +57,7 @@ The server's one resource, `openscreen://effects/contract` ([`effects-contract.t - **Validation.** Numbers are held to `SETTING_BOUNDS`, enums to the constant lists, and both wallpapers go through `parseStylePresetWallpaper`: a colour, a gradient, a bundled path or an inline PNG/JPEG, never `file://` nor a URL. The schema is strict, so a misnamed key is refused rather than dropped. - **Read side.** `getCurrentDocument` adds `settings`, in the tool's own shape with data-URL wallpapers elided, and `settingsContext`: the formats on offer (`originalAspectRatios` from `collectNativeFormats`), `formatFill`, `hasTiltedZoom`, the bundled wallpapers, the cursor themes, `cameraSegmentation`, and `inactive`, each setting the editor hides in the current state with why. A write reports the same for the keys it set. The captions stay out of `settings`: `getCaptions` reads them and `setCaptionSettings` writes them, so no caption field has two owners. - **Segmentation.** `McpToolDeps.cameraSegmentation` and the in-app agent's `ChatRunEnv` ask the compositor (`probeSegmentation`), wired in `registerIpcHandlers`; `openscreen mcp` inherits it with `mcpToolDeps`. Where nothing is wired it reads `null`, "not checked". -- **Not covered yet:** style presets (`StylePresetService`) are not exposed; `setEditorSettings` reaches every field a preset holds. +- **Style presets.** `listStylePresets` lists the editor's Style presets menu, built-in look first, each with its `look` and whether it is the project's look now (`sameStylePresetLook`, first match, as the menu lights one row). `applyStylePreset` applies one as the menu does, `stylePresetPatch` through `applySettingsPatch`: the look in one edit, never the content. The saved presets are read through `McpToolDeps.stylePresets` and the in-app agent's `ChatRunEnv.stylePresets` (`StylePresetService.list`, wired in `registerIpcHandlers`, inherited by `openscreen mcp`); where nothing is wired only the built-in one is offered, with a `warning`. ## What each transport tells its client From bab809a57fa8dabe43525f103390d032db28683e Mon Sep 17 00:00:00 2001 From: EtienneLescot Date: Sun, 22 Nov 2026 14:01:44 +0100 Subject: [PATCH 05/74] feat(mcp): export a project's captions to an SRT or WebVTT file --- electron/mcp/media-tools.test.ts | 92 +++++++- electron/mcp/media-tools.ts | 79 ++++++- electron/mcp/openscreen-mcp-server.test.ts | 3 +- electron/mcp/openscreen-mcp-server.ts | 2 +- .../ai-edition/captions/subtitleFile.test.ts | 197 ++++++++++++++++++ src/lib/ai-edition/captions/subtitleFile.ts | 75 +++++++ .../architecture/mcp-server.md | 5 +- website/docs/ai-editing.md | 2 +- .../current/ai-editing.md | 2 +- .../current/ai-editing.md | 2 +- .../current/ai-editing.md | 2 +- .../current/ai-editing.md | 2 +- .../current/ai-editing.md | 2 +- .../current/ai-editing.md | 2 +- .../current/ai-editing.md | 2 +- 15 files changed, 454 insertions(+), 15 deletions(-) create mode 100644 src/lib/ai-edition/captions/subtitleFile.test.ts create mode 100644 src/lib/ai-edition/captions/subtitleFile.ts diff --git a/electron/mcp/media-tools.test.ts b/electron/mcp/media-tools.test.ts index d7af5ad63b..a677fc05f0 100644 --- a/electron/mcp/media-tools.test.ts +++ b/electron/mcp/media-tools.test.ts @@ -915,6 +915,96 @@ describe("exportAudio", () => { }); }); +describe("exportCaptions", () => { + /** The take with two spoken lines in its transcript. */ + async function spokenTake() { + const { projectId } = await recordTake(); + const project = await documents.getProject(projectId); + const assetId = project.project.primaryAssetId as string; + const word = ( + id: string, + segmentId: string, + startSec: number, + endSec: number, + text: string, + ) => ({ + id, + segmentId, + startSec, + endSec, + text, + }); + await documents.saveProject({ + ...project, + transcripts: [ + { + assetId, + language: "en", + segments: [ + { + id: "s1", + kind: "speech", + startSec: 1, + endSec: 2, + text: "hello there", + wordIds: ["w1", "w2"], + }, + { id: "s2", kind: "speech", startSec: 4, endSec: 5, text: "goodbye", wordIds: ["w3"] }, + ], + words: [ + word("w1", "s1", 1, 1.5, "hello"), + word("w2", "s1", 1.5, 2, "there"), + word("w3", "s2", 4, 5, "goodbye"), + ], + }, + ], + }); + return projectId; + } + + it("writes the captions to the subtitle file the extension names", async () => { + const projectId = await spokenTake(); + const srt = path.join(dir, "demo.srt"); + const written = await call("exportCaptions", { projectId, path: srt }); + expect(written.isError).toBeFalsy(); + expect(JSON.parse(textOf(written))).toEqual({ + path: srt, + format: "srt", + language: null, + entries: 2, + }); + expect(await fs.readFile(srt, "utf8")).toBe( + "1\n00:00:01,000 --> 00:00:02,000\nhello there\n\n2\n00:00:04,000 --> 00:00:05,000\ngoodbye\n", + ); + const vtt = path.join(dir, "demo.vtt"); + await call("exportCaptions", { projectId, path: vtt }); + expect((await fs.readFile(vtt, "utf8")).startsWith("WEBVTT\n\n00:00:01.000")).toBe(true); + // Nothing is rendered for it. + expect(runners.started.filter((request) => request.kind === "export")).toHaveLength(0); + }); + + it("refuses a project with no words, a layer it lacks, another extension or an unknown project", async () => { + const { projectId } = await recordTake(); + const empty = await call("exportCaptions", { projectId, path: path.join(dir, "none.srt") }); + expect(empty.isError).toBe(true); + expect(textOf(empty)).toContain("transcribe"); + await expect(fs.access(path.join(dir, "none.srt"))).rejects.toThrow(); + + const spoken = await spokenTake(); + const layer = await call("exportCaptions", { + projectId: spoken, + path: path.join(dir, "fr.srt"), + language: "fr", + }); + expect(textOf(layer)).toContain('no "fr" caption translation'); + expect((await call("exportCaptions", { projectId: spoken, path: "out.txt" })).isError).toBe( + true, + ); + const unknown = await call("exportCaptions", { projectId: "proj_x", path: "out.srt" }); + expect(textOf(unknown)).toContain('No project has the id "proj_x"'); + }); +}); + describe("getFrames on a project", () => { it("reads the last export at the ruler seconds the document tools use", async () => { const { projectId } = await recordTake(); @@ -1455,7 +1545,7 @@ describe("the media tools in the app", () => { allowed = false; const app = await connectApp(); expect(app.getInstructions()).toContain( - "startRecording, exportVideo, exportAudio and createProject are refused too while 'MCP edits'", + "startRecording, exportVideo, exportAudio, exportCaptions and createProject are refused too while 'MCP edits'", ); const started = await callOn(app, "startRecording", {}); expect(started.isError).toBe(true); diff --git a/electron/mcp/media-tools.ts b/electron/mcp/media-tools.ts index 91f493fd63..719415091b 100644 --- a/electron/mcp/media-tools.ts +++ b/electron/mcp/media-tools.ts @@ -13,7 +13,7 @@ // handed in, so the tools run under plain vitest with stand-ins. import { randomUUID } from "node:crypto"; -import { rm } from "node:fs/promises"; +import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; @@ -25,6 +25,13 @@ import type { } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; import type { CursorTelemetryPoint } from "../../src/components/video-editor/types"; +import { getCaptionSettings } from "../../src/lib/ai-edition/captions/settings"; +import { + formatSubtitleFile, + isSubtitleFileFormat, + subtitleCuesForExport, +} from "../../src/lib/ai-edition/captions/subtitleFile"; +import { getCaptionTranslations } from "../../src/lib/ai-edition/captions/translations"; import { projectRawTimelineSecToPlayback, readSpeedRegions, @@ -436,6 +443,12 @@ const AUDIO_PATH_DESCRIPTIONS: Record = { "Where to write the audio: an absolute path, or one relative to this server's working directory, ending in .wav or .m4a.", }; +const CAPTIONS_PATH_DESCRIPTIONS: Record = { + http: "Where to write the subtitles: an absolute path ending in .srt or .vtt. This server runs inside the app, so it has no working directory of yours to resolve a relative one against.", + stdio: + "Where to write the subtitles: an absolute path, or one relative to this server's working directory, ending in .srt or .vtt.", +}; + const GATED_MESSAGE = `Nothing was recorded or exported: OpenScreen lets MCP clients record and export only while the user allows it. Ask the user to turn on ${MCP_EDITS_SETTING}.`; /** A path a client passed, resolved; `null` for a relative one the in-app server cannot place. */ @@ -1289,6 +1302,68 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { }, ); + server.registerTool( + "exportCaptions", + { + description: + "Write a project's captions to a subtitle file, SubRip (.srt) or WebVTT (.vtt), picked by the path's extension. The entries are the lines the burnt-in captions show, with the same words per line, timed in seconds of the exported video: after the trims and the speed regions, so the file plays in sync with exportVideo's MP4. It does not need the captions to be on, and does not turn them on. language picks the words: omitted, the language the captions show (getCaptions' language); null, the transcript's own words; a code, that translation layer (getCaptions lists them under translations). Captions come from the transcript, so a project with none on its caption lane has nothing to write and is refused. Returns the path, the format, the language written and the number of entries. Instant: nothing is rendered.", + inputSchema: z.object({ + projectId: z.string(), + path: z.string().describe(CAPTIONS_PATH_DESCRIPTIONS[transport]), + language: z + .string() + .nullable() + .optional() + .describe( + "A translation layer's code, null for the transcript's own words, omitted for what the captions show.", + ), + }), + annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, + }, + async (args) => { + if (!deps.editsAllowed()) return text(GATED_MESSAGE, true); + const outPath = clientPath(transport, args.path); + if (!outPath) return text(`The path must be absolute, got "${args.path}".`, true); + const format = path.extname(outPath).toLowerCase().slice(1); + if (!isSubtitleFileFormat(format)) { + return text(`The path must end in .srt or .vtt, got "${args.path}".`, true); + } + const document = await deps.documents.getProject(args.projectId).catch(() => null); + if (!document) return text(`No project has the id "${args.projectId}".`, true); + if (typeof args.language === "string") { + const layers = Object.keys(getCaptionTranslations(document)); + if (!layers.includes(args.language)) { + return text( + `The project has no "${args.language}" caption translation. ${ + layers.length + ? `Its layers are: ${layers.join(", ")}.` + : "It has none: putCaptionTranslation writes one." + } Pass null for the transcript's own words.`, + true, + ); + } + } + const cues = subtitleCuesForExport(document, args.language); + if (cues.length === 0) { + return text( + "Nothing was written: the captions have no words to show. They come from the transcript of what the caption lane plays, so transcribe it first (transcribe), or check getCaptions' captionedAssets.", + true, + ); + } + try { + await fs.writeFile(outPath, formatSubtitleFile(cues, format), "utf8"); + } catch (error) { + return text( + `The subtitles could not be written to "${outPath}": ${error instanceof Error ? error.message : String(error)}`, + true, + ); + } + const language = + args.language === undefined ? getCaptionSettings(document).language : args.language; + return text(JSON.stringify({ path: outPath, format, language, entries: cues.length })); + }, + ); + server.registerTool( "getAudioReport", { @@ -1348,7 +1423,7 @@ export function createMediaTools(deps: MediaToolDeps): MediaTools { ); } finally { exporting = false; - await rm(wavPath, { force: true }).catch(() => undefined); + await fs.rm(wavPath, { force: true }).catch(() => undefined); } }, ); diff --git a/electron/mcp/openscreen-mcp-server.test.ts b/electron/mcp/openscreen-mcp-server.test.ts index ef6a6ac0ca..582880c62d 100644 --- a/electron/mcp/openscreen-mcp-server.test.ts +++ b/electron/mcp/openscreen-mcp-server.test.ts @@ -331,6 +331,7 @@ describe("the MCP tool surface", () => { "setPointerTrack", "exportVideo", "exportAudio", + "exportCaptions", "getAudioReport", "getFrames", "getContactSheet", @@ -384,7 +385,7 @@ describe("the MCP tool surface", () => { ); expect(instructions).toContain("startRecording hands over to OpenScreen's recording bar"); expect(instructions).toContain( - "startRecording, exportVideo, exportAudio and createProject are refused too", + "startRecording, exportVideo, exportAudio, exportCaptions and createProject are refused too", ); expect(instructions).toContain("all of them are lost when OpenScreen quits."); expect(instructions).toContain("turn on 'MCP edits' under MCP server in AI settings"); diff --git a/electron/mcp/openscreen-mcp-server.ts b/electron/mcp/openscreen-mcp-server.ts index 688024da36..5a9664129f 100644 --- a/electron/mcp/openscreen-mcp-server.ts +++ b/electron/mcp/openscreen-mcp-server.ts @@ -305,7 +305,7 @@ export function mcpInstructions(options: { CHECKPOINT_LIFETIMES[transport], ...(media && !editsAllowed ? [ - `startRecording, exportVideo, exportAudio and createProject are refused too while ${MCP_EDITS_SETTING} is off.`, + `startRecording, exportVideo, exportAudio, exportCaptions and createProject are refused too while ${MCP_EDITS_SETTING} is off.`, ] : []), ...(options.transcribe ? [TRANSCRIBE_NOTE] : []), diff --git a/src/lib/ai-edition/captions/subtitleFile.test.ts b/src/lib/ai-edition/captions/subtitleFile.test.ts new file mode 100644 index 0000000000..33cddb9c9c --- /dev/null +++ b/src/lib/ai-edition/captions/subtitleFile.test.ts @@ -0,0 +1,197 @@ +import { describe, expect, it } from "vitest"; +import type { AxcutDocument } from "../schema"; +import { patchCaptionSettings } from "./settings"; +import { formatSubtitleFile, subtitleCuesForExport } from "./subtitleFile"; +import { captionTranslationUnits, putCaptionTranslation } from "./translations"; + +function doc(overrides: Partial = {}): AxcutDocument { + return { + schemaVersion: 5, + project: { + id: "p1", + title: "Test", + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + primaryAssetId: "asset-1", + }, + assets: [ + { + id: "asset-1", + kind: "video", + label: "take", + originalPath: "C:/rec/take.mp4", + video: { width: 1920, height: 1080, fps: 30 }, + cameraTrack: null, + }, + ], + transcript: null, + transcripts: [ + { + assetId: "asset-1", + language: "en", + segments: [ + { + id: "seg_1", + kind: "speech", + startSec: 0, + endSec: 2, + text: "hello there friend", + wordIds: ["w1", "w2", "w3"], + }, + { + id: "seg_2", + kind: "speech", + startSec: 4, + endSec: 6, + text: "goodbye now", + wordIds: ["w4", "w5"], + }, + ], + words: [ + { id: "w1", segmentId: "seg_1", startSec: 0, endSec: 0.6, text: "hello" }, + { id: "w2", segmentId: "seg_1", startSec: 0.6, endSec: 1.2, text: "there" }, + { id: "w3", segmentId: "seg_1", startSec: 1.2, endSec: 2, text: "friend" }, + { id: "w4", segmentId: "seg_2", startSec: 4, endSec: 5, text: "goodbye" }, + { id: "w5", segmentId: "seg_2", startSec: 5, endSec: 6, text: "now" }, + ], + }, + ], + timeline: { + clips: [ + { + id: "clip-1", + assetId: "asset-1", + sourceStartSec: 0, + sourceEndSec: 10, + timelineStartSec: 0, + timelineEndSec: 10, + wordRefs: [], + origin: "user", + reason: "", + }, + ], + gaps: [], + trimRanges: [], + muteRanges: [], + speedRanges: [], + captionRanges: [], + }, + annotations: [], + zoomRanges: [], + legacyEditor: null, + ...overrides, + } as AxcutDocument; +} + +describe("subtitleCuesForExport", () => { + it("gives the burnt-in lines, whether or not the captions are on", () => { + expect(subtitleCuesForExport(doc())).toEqual([ + { startSec: 0, endSec: 2, text: "hello there friend" }, + { startSec: 4, endSec: 6, text: "goodbye now" }, + ]); + }); + + it("times them on the export: a trim is skipped and a speed region plays faster", () => { + const base = doc(); + const edited = doc({ + timeline: { + ...base.timeline, + trimRanges: [ + { + id: "trim_1", + assetId: "asset-1", + clipId: "clip-1", + startSec: 2.5, + endSec: 3.5, + reason: "", + origin: "user", + }, + ], + }, + legacyEditor: { + speedRegions: [ + { + id: "speed_1", + clipId: "clip-1", + sourceStartSec: 4, + sourceEndSec: 6, + startMs: 4000, + endMs: 6000, + speed: 2, + }, + ], + }, + }); + const cues = subtitleCuesForExport(edited); + expect(cues[0]).toEqual({ startSec: 0, endSec: 2, text: "hello there friend" }); + // 4 s on the ruler is 3 s of export after the 1 s cut; its 2 s at 2× last 1 s. + expect(cues[1].startSec).toBeCloseTo(3, 6); + expect(cues[1].endSec).toBeCloseTo(4, 6); + }); + + it("drops a line the cuts remove entirely", () => { + const base = doc(); + const cut = doc({ + timeline: { + ...base.timeline, + trimRanges: [ + { + id: "trim_1", + assetId: "asset-1", + clipId: "clip-1", + startSec: 3.5, + endSec: 6.5, + reason: "", + origin: "user", + }, + ], + }, + }); + expect(subtitleCuesForExport(cut).map((c) => c.text)).toEqual(["hello there friend"]); + }); + + it("reads a translation layer when asked, and the transcript's words with null", () => { + const transcript = doc().transcripts[0]; + const segments = Object.fromEntries( + captionTranslationUnits(transcript).map((unit, i) => [unit.id, i === 0 ? "salut" : "adieu"]), + ); + const translated = patchCaptionSettings( + putCaptionTranslation(doc(), { + language: "fr", + label: "Français", + assetId: "asset-1", + segments, + }), + { language: "fr" }, + ); + // Omitted: what the captions show. + expect(subtitleCuesForExport(translated).map((c) => c.text)).toEqual(["salut", "adieu"]); + expect(subtitleCuesForExport(translated, null).map((c) => c.text)).toEqual([ + "hello there friend", + "goodbye now", + ]); + expect(subtitleCuesForExport(doc(), "fr").map((c) => c.text)).toEqual([ + "hello there friend", + "goodbye now", + ]); + }); +}); + +describe("formatSubtitleFile", () => { + const cues = [ + { startSec: 0, endSec: 2.5, text: "hello there" }, + { startSec: 3661.0425, endSec: 3662, text: "goodbye" }, + ]; + + it("writes numbered SubRip entries with comma milliseconds", () => { + expect(formatSubtitleFile(cues, "srt")).toBe( + "1\n00:00:00,000 --> 00:00:02,500\nhello there\n\n2\n01:01:01,043 --> 01:01:02,000\ngoodbye\n", + ); + }); + + it("writes a WebVTT header and dot milliseconds", () => { + expect(formatSubtitleFile(cues, "vtt")).toBe( + "WEBVTT\n\n00:00:00.000 --> 00:00:02.500\nhello there\n\n01:01:01.043 --> 01:01:02.000\ngoodbye\n", + ); + }); +}); diff --git a/src/lib/ai-edition/captions/subtitleFile.ts b/src/lib/ai-edition/captions/subtitleFile.ts new file mode 100644 index 0000000000..e9dac23bba --- /dev/null +++ b/src/lib/ai-edition/captions/subtitleFile.ts @@ -0,0 +1,75 @@ +// The captions as a subtitle file (.srt or .vtt), timed on the exported programme. +// +// The cues are the ones the burn-in draws (`deriveCaptionCues`), so the file and the burnt-in +// captions say the same words at the same moments. They come off the ruler, so each edge goes +// through the exporter's own projection (`projectRawTimelineSecToPlayback`): a trim is a hole +// the export skips, a speed region plays faster. A cue the cuts remove entirely leaves no entry. + +import { projectRawTimelineSecToPlayback, readSpeedRegions } from "../document/timeline"; +import type { AxcutDocument } from "../schema"; +import { deriveCaptionCues } from "./cues"; +import { getCaptionSettings } from "./settings"; +import { getCaptionTranslations } from "./translations"; + +export const SUBTITLE_FILE_FORMATS = ["srt", "vtt"] as const; +export type SubtitleFileFormat = (typeof SUBTITLE_FILE_FORMATS)[number]; + +export function isSubtitleFileFormat(value: string): value is SubtitleFileFormat { + return (SUBTITLE_FILE_FORMATS as readonly string[]).includes(value); +} + +/** One subtitle entry, in seconds of the exported video. */ +export interface SubtitleCue { + startSec: number; + endSec: number; + text: string; +} + +/** + * The captions' cues on the export's clock. `language` picks what they read: omitted, the + * language the captions show; `null`, the transcript's own words; a code, that translation + * layer. Written whether or not the captions are burnt in: the file does not depend on it. + */ +export function subtitleCuesForExport( + document: AxcutDocument, + language?: string | null, +): SubtitleCue[] { + const settings = getCaptionSettings(document); + const cues = deriveCaptionCues( + document, + { ...settings, enabled: true, ...(language === undefined ? {} : { language }) }, + getCaptionTranslations(document), + ); + const speed = readSpeedRegions(document); + const { clips, trimRanges } = document.timeline; + const toExport = (ms: number) => + projectRawTimelineSecToPlayback(clips, trimRanges, ms / 1000, speed); + return cues + .map((cue) => ({ + startSec: toExport(cue.startMs), + endSec: toExport(cue.endMs), + // A blank line ends an entry in both formats. + text: cue.text.replace(/\n\s*\n/g, "\n").trim(), + })) + .filter((cue) => cue.endSec - cue.startSec >= 0.001 && cue.text.length > 0); +} + +/** `HH:MM:SS,mmm` for SRT, `HH:MM:SS.mmm` for WebVTT. */ +function timestamp(sec: number, format: SubtitleFileFormat): string { + const ms = Math.max(0, Math.round(sec * 1000)); + const pad = (n: number, width = 2) => String(n).padStart(width, "0"); + const hh = pad(Math.floor(ms / 3_600_000)); + const mm = pad(Math.floor(ms / 60_000) % 60); + const ss = pad(Math.floor(ms / 1000) % 60); + return `${hh}:${mm}:${ss}${format === "srt" ? "," : "."}${pad(ms % 1000, 3)}`; +} + +/** The file's text: numbered entries for SRT, a `WEBVTT` header then entries for WebVTT. */ +export function formatSubtitleFile(cues: SubtitleCue[], format: SubtitleFileFormat): string { + const entries = cues.map((cue, index) => { + const timing = `${timestamp(cue.startSec, format)} --> ${timestamp(cue.endSec, format)}`; + return format === "srt" ? `${index + 1}\n${timing}\n${cue.text}` : `${timing}\n${cue.text}`; + }); + const blocks = format === "vtt" ? ["WEBVTT", ...entries] : entries; + return `${blocks.join("\n\n")}\n`; +} diff --git a/technical-documentation/architecture/mcp-server.md b/technical-documentation/architecture/mcp-server.md index fb55db174e..d7cc007e49 100644 --- a/technical-documentation/architecture/mcp-server.md +++ b/technical-documentation/architecture/mcp-server.md @@ -12,7 +12,7 @@ The same tools are served over two transports, by two different processes: | Edits, recording, export | Off until the user turns on **MCP edits** | Always allowed | | Project open in the editor | Edited live through the editor, one undo step per call | The same while the app runs: the call is forwarded to it. With no app answering, refused ([the marker](#the-open-in-editor-marker)) | | Other projects | Read from and saved to their file, a checkpoint first | Same | -| Tools | `listProjects`, the agent's tools, `transcribe`, the project tools (`setProjectInfo`, `importMedia`, `removeMedia`), the checkpoint tools, and the media tools: `listSources`, `startRecording`, `stopRecording`, `waitForRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `getAudioReport`, `getFrames`, `getContactSheet`, `createProject` | The same | +| Tools | `listProjects`, the agent's tools, `transcribe`, the project tools (`setProjectInfo`, `importMedia`, `removeMedia`), the checkpoint tools, and the media tools: `listSources`, `startRecording`, `stopRecording`, `waitForRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `exportCaptions`, `getAudioReport`, `getFrames`, `getContactSheet`, `createProject` | The same | | A take | Recorded by the app's recording bar, as its Record button records; the editor opens it ([below](#the-media-tools)) | Recorded by a hidden runner of its own process, and made a project there | | Checkpoints | In the app's memory, shared with forwarded `openscreen mcp` calls, lost when the app quits | In the app's while it runs; otherwise in this process's, lost when it exits, which it does when the client disconnects | @@ -211,7 +211,8 @@ Then both servers carry on alike: - `exportVideo` renders in a hidden `cli-export` runner, the same in both processes: in the app, `listSources` and `exportVideo` run the CLI's runners (`createRunnerHost` with `createRunnerWindow`), whose IPC the app registers on first use. The runner reads the project by id (`CliExportRequest.projectId`, the editor's own `aiEdition.get`), not by path: opening a file by path moves the main process's current project and recording-session slot, which in the app is the hand-off from the recorder to the editor. - `exportVideo` takes the Export dialog's options and choices: `quality` and `fps` (24, 30, 60) for an MP4, `gifFrameRate`, `gifSize` and `gifLoop` for a GIF, the dialog's defaults when left out. An option of the other format is refused rather than ignored. Hiding the desktop icons is not a `startRecording` option: the HUD has no such control, so it follows the user's Record mode setting on both servers. Nor are the CLI's `--auto-zoom` and `--audio`: zooms and a voiceover are edits of the project, and an export that added them would not be the project `getFrames` maps through. - `exportAudio` (#1280) is the same runner with `format` `wav` or `m4a`: `CliExportRunner` renders the MP4 beside the output (`audioRenderPath`, removed by `createRunnerHost` once the run reports) and `extractAudio` takes its audio stream out, so the file is the MP4's own mix, not a second mixer's. With `audioId` (`CliExportRequest.audioTrackId`, the CLI's `--track`), `isolateAudioTrack` keeps that track's fragments only, the clips render with `hasAudio: false` and the click sound is dropped: the track alone, where the export places it. There is no option to replace the take's sound for the whole programme: the document has no such switch (the take's gain is bounded at ±12 dB), and an export option would make a file the project does not describe. -- `exportVideo`, `exportAudio`, `getAudioReport`, `getFrames` and `getContactSheet` read projects; they write none. Over HTTP their paths must be absolute. +- `exportCaptions` writes the captions to a `.srt` or `.vtt` with no runner (`captions/subtitleFile.ts`): the cues the burn-in draws (`deriveCaptionCues`, whether or not the captions are on), each edge projected onto the export's clock with `projectRawTimelineSecToPlayback`, the exporter's own projection through trims and speed regions. `language` picks a translation layer, `null` the transcript's words, omitted what the captions show. A project with no words on its caption lane is refused and nothing is written. **MCP edits** gates it, as it gates the other exports. +- `exportVideo`, `exportAudio`, `exportCaptions`, `getAudioReport`, `getFrames` and `getContactSheet` read projects; they write none. Over HTTP their paths must be absolute. - `getFrames` with a `projectId` reads the project's last export while it is current. With no export, or one the project changed after, it renders the frames from the project instead (`renderFrames` in the addon, through the export's own walk), so an agent checks an edit without exporting. See [docs/shader-effects.md](../../docs/shader-effects.md), E.4. - `getFrames` and `getContactSheet` find their frames the same way (`shotsOf`): explicit `atSec`, or `count` of them, spread over the whole video or from `startSec` to `endSec`, both ends shown. What differs is what they do with them. - `getFrames` returns each frame as an image, 1280 pixels wide at most. With a `region` it asks for the frame at its own size instead and returns that part of it, so a client reads small text or checks an edge at the export's resolution. diff --git a/website/docs/ai-editing.md b/website/docs/ai-editing.md index a79a48f05f..9f0fdc2b96 100644 --- a/website/docs/ai-editing.md +++ b/website/docs/ai-editing.md @@ -76,7 +76,7 @@ Checkpoints are kept in OpenScreen's memory: they are lost when it quits or when ## Letting an agent make the whole video -An agent can make a whole video on its own, from the recording to the export. Besides the editing tools, both ways of adding OpenScreen to it give it `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `getFrames` and `createProject`. On the server in the app, `waitForRecording` also waits for a take you record yourself from the recording bar, and returns it as `stopRecording` does. A take can also record your webcam and the system's own cursor, as the recording bar can, and an export takes the Export dialog's options: quality and frame rate for an MP4; frame rate, size and looping for a GIF. `exportAudio` writes the project's audio, or one imported track alone (a voiceover added with `importMedia` and `addAudio`), to a WAV or an M4A, exactly as the MP4 mixes it. +An agent can make a whole video on its own, from the recording to the export. Besides the editing tools, both ways of adding OpenScreen to it give it `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `exportCaptions`, `getFrames` and `createProject`. On the server in the app, `waitForRecording` also waits for a take you record yourself from the recording bar, and returns it as `stopRecording` does. A take can also record your webcam and the system's own cursor, as the recording bar can, and an export takes the Export dialog's options: quality and frame rate for an MP4; frame rate, size and looping for a GIF. `exportAudio` writes the project's audio, or one imported track alone (a voiceover added with `importMedia` and `addAudio`), to a WAV or an M4A, exactly as the MP4 mixes it. `exportCaptions` writes the captions to an SRT or a WebVTT subtitle file, timed on the exported video. **Through the server above**, a take is recorded by OpenScreen itself, as with its Record button: the editor closes, the recording bar counts down and records, and the take opens in the editor as a new project, where you watch each edit land. It needs **MCP edits** on, and the recording bar gets your own settings back once the take ends. diff --git a/website/i18n/de/docusaurus-plugin-content-docs/current/ai-editing.md b/website/i18n/de/docusaurus-plugin-content-docs/current/ai-editing.md index b02573d2ae..c4134c707c 100644 --- a/website/i18n/de/docusaurus-plugin-content-docs/current/ai-editing.md +++ b/website/i18n/de/docusaurus-plugin-content-docs/current/ai-editing.md @@ -76,7 +76,7 @@ Wiederherstellungspunkte liegen im Speicher von OpenScreen: Sie gehen verloren, ## Einen Agenten das ganze Video erstellen lassen {#letting-an-agent-make-the-whole-video} -Ein Agent kann ein ganzes Video selbstständig erstellen, von der Aufnahme bis zum Export. Neben den Bearbeitungswerkzeugen geben ihm beide Wege, OpenScreen hinzuzufügen, `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `getFrames` und `createProject`. Über den Server in der App wartet `waitForRecording` außerdem auf eine Aufnahme, die du selbst mit der Aufnahmeleiste machst, und gibt sie zurück wie `stopRecording`. Eine Aufnahme kann wie mit der Aufnahmeleiste auch deine Webcam und den eigenen Mauszeiger des Systems aufnehmen, und ein Export übernimmt die Optionen des Export-Dialogs: Qualität und Bildrate für ein MP4; Bildrate, Größe und Wiederholung für ein GIF. +Ein Agent kann ein ganzes Video selbstständig erstellen, von der Aufnahme bis zum Export. Neben den Bearbeitungswerkzeugen geben ihm beide Wege, OpenScreen hinzuzufügen, `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `exportCaptions`, `getFrames` und `createProject`. Über den Server in der App wartet `waitForRecording` außerdem auf eine Aufnahme, die du selbst mit der Aufnahmeleiste machst, und gibt sie zurück wie `stopRecording`. Eine Aufnahme kann wie mit der Aufnahmeleiste auch deine Webcam und den eigenen Mauszeiger des Systems aufnehmen, und ein Export übernimmt die Optionen des Export-Dialogs: Qualität und Bildrate für ein MP4; Bildrate, Größe und Wiederholung für ein GIF. `exportAudio` schreibt den Ton des Projekts, oder eine einzelne importierte Spur (ein mit `importMedia` und `addAudio` hinzugefügtes Voiceover), in eine WAV- oder M4A-Datei, genau so, wie das MP4 ihn mischt. `exportCaptions` schreibt die Untertitel in eine SRT- oder WebVTT-Datei, getaktet auf das exportierte Video. **Über den Server oben** nimmt OpenScreen eine Aufnahme selbst auf, wie mit seinem Aufnahme-Button: Der Editor schließt sich, die Aufnahmeleiste zählt herunter und nimmt auf, und die Aufnahme öffnet sich im Editor als neues Projekt, wo du jede Änderung ankommen siehst. Dafür muss **MCP-Änderungen** an sein, und die Aufnahmeleiste bekommt am Ende der Aufnahme deine eigenen Einstellungen zurück. diff --git a/website/i18n/es/docusaurus-plugin-content-docs/current/ai-editing.md b/website/i18n/es/docusaurus-plugin-content-docs/current/ai-editing.md index 1d4d0c4f0a..d29b372bc7 100644 --- a/website/i18n/es/docusaurus-plugin-content-docs/current/ai-editing.md +++ b/website/i18n/es/docusaurus-plugin-content-docs/current/ai-editing.md @@ -76,7 +76,7 @@ Los puntos de restauración se guardan en la memoria de OpenScreen: se pierden c ## Dejar que un agente haga todo el video {#letting-an-agent-make-the-whole-video} -Un agente puede hacer un video completo por sí solo, desde la grabación hasta la exportación. Además de las herramientas de edición, las dos formas de agregar OpenScreen al agente le dan `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `getFrames` y `createProject`. En el servidor de la app, `waitForRecording` también espera una toma que grabas tú mismo desde la barra de grabación y la devuelve como `stopRecording`. Una toma también puede grabar tu cámara web y el cursor propio del sistema, como la barra de grabación, y una exportación acepta las opciones del diálogo de exportación: calidad y velocidad de fotogramas para un MP4; velocidad de fotogramas, tamaño y bucle para un GIF. +Un agente puede hacer un video completo por sí solo, desde la grabación hasta la exportación. Además de las herramientas de edición, las dos formas de agregar OpenScreen al agente le dan `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `exportCaptions`, `getFrames` y `createProject`. En el servidor de la app, `waitForRecording` también espera una toma que grabas tú mismo desde la barra de grabación y la devuelve como `stopRecording`. Una toma también puede grabar tu cámara web y el cursor propio del sistema, como la barra de grabación, y una exportación acepta las opciones del diálogo de exportación: calidad y velocidad de fotogramas para un MP4; velocidad de fotogramas, tamaño y bucle para un GIF. `exportAudio` escribe el audio del proyecto, o una sola pista importada (una voz en off agregada con `importMedia` y `addAudio`), en un WAV o un M4A, exactamente como lo mezcla el MP4. `exportCaptions` escribe los subtítulos en un archivo SRT o WebVTT, sincronizado con el video exportado. **Con el servidor de arriba**, la toma la graba el propio OpenScreen, como con su botón Grabar: el editor se cierra, la barra de grabación hace su cuenta regresiva y graba, y la toma se abre en el editor como un proyecto nuevo, donde ves llegar cada edición. Necesita **Ediciones por MCP** activado, y la barra de grabación recupera tus propios ajustes al terminar la toma. diff --git a/website/i18n/fr/docusaurus-plugin-content-docs/current/ai-editing.md b/website/i18n/fr/docusaurus-plugin-content-docs/current/ai-editing.md index e110d946f9..eed0ee0325 100644 --- a/website/i18n/fr/docusaurus-plugin-content-docs/current/ai-editing.md +++ b/website/i18n/fr/docusaurus-plugin-content-docs/current/ai-editing.md @@ -76,7 +76,7 @@ Les points de restauration sont gardés dans la mémoire d'OpenScreen : ils son ## Laisser un agent faire toute la vidéo {#letting-an-agent-make-the-whole-video} -Un agent peut faire une vidéo entière tout seul, de l'enregistrement à l'export. En plus des outils d'édition, les deux façons d'ajouter OpenScreen à l'agent lui donnent `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `getFrames` et `createProject`. Sur le serveur de l'app, `waitForRecording` attend aussi une prise que vous enregistrez vous-même depuis la barre d'enregistrement, et la rend comme `stopRecording`. Une prise peut aussi enregistrer votre webcam et le curseur du système, comme la barre d'enregistrement, et un export prend les options de la boîte d'export : qualité et fréquence d'images pour un MP4 ; fréquence d'images, taille et boucle pour un GIF. +Un agent peut faire une vidéo entière tout seul, de l'enregistrement à l'export. En plus des outils d'édition, les deux façons d'ajouter OpenScreen à l'agent lui donnent `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `exportCaptions`, `getFrames` et `createProject`. Sur le serveur de l'app, `waitForRecording` attend aussi une prise que vous enregistrez vous-même depuis la barre d'enregistrement, et la rend comme `stopRecording`. Une prise peut aussi enregistrer votre webcam et le curseur du système, comme la barre d'enregistrement, et un export prend les options de la boîte d'export : qualité et fréquence d'images pour un MP4 ; fréquence d'images, taille et boucle pour un GIF. `exportAudio` écrit l'audio du projet, ou une seule piste importée (une voix off ajoutée avec `importMedia` et `addAudio`), dans un WAV ou un M4A, exactement comme le MP4 le mixe. `exportCaptions` écrit les sous-titres dans un fichier SRT ou WebVTT, calé sur la vidéo exportée. **Par le serveur ci-dessus**, une prise est enregistrée par OpenScreen lui-même, comme avec son bouton Enregistrer : l'éditeur se ferme, la barre d'enregistrement fait son décompte et enregistre, et la prise s'ouvre dans l'éditeur comme nouveau projet, où vous voyez chaque modification arriver. Il faut que **Modifications par MCP** soit activé, et la barre d'enregistrement retrouve vos propres réglages à la fin de la prise. diff --git a/website/i18n/ja/docusaurus-plugin-content-docs/current/ai-editing.md b/website/i18n/ja/docusaurus-plugin-content-docs/current/ai-editing.md index c758ff9210..132d56ce9e 100644 --- a/website/i18n/ja/docusaurus-plugin-content-docs/current/ai-editing.md +++ b/website/i18n/ja/docusaurus-plugin-content-docs/current/ai-editing.md @@ -76,7 +76,7 @@ Claude Code や Codex などの AI コーディングエージェントをすで ## エージェントに動画全体を作らせる {#letting-an-agent-make-the-whole-video} -エージェントは、録画からエクスポートまで、動画全体を自力で作れます。どちらの方法で OpenScreen を追加しても、編集ツールに加えて `listSources`、`startRecording`、`stopRecording`、`setPointerTrack`、`exportVideo`、`getFrames`、`createProject` を使えます。アプリ内のサーバーでは、`waitForRecording` で、あなた自身が録画バーから録画するテイクの完了を待ち、`stopRecording` と同じ形で受け取ることもできます。録画バーと同じく、テイクには Web カメラやシステム自身のカーソルも録画でき、エクスポートでは書き出しダイアログのオプションを使えます。MP4 なら画質とフレームレート、GIF ならフレームレート、サイズ、ループです。 +エージェントは、録画からエクスポートまで、動画全体を自力で作れます。どちらの方法で OpenScreen を追加しても、編集ツールに加えて `listSources`、`startRecording`、`stopRecording`、`setPointerTrack`、`exportVideo`、`exportAudio`、`exportCaptions`、`getFrames`、`createProject` を使えます。アプリ内のサーバーでは、`waitForRecording` で、あなた自身が録画バーから録画するテイクの完了を待ち、`stopRecording` と同じ形で受け取ることもできます。録画バーと同じく、テイクには Web カメラやシステム自身のカーソルも録画でき、エクスポートでは書き出しダイアログのオプションを使えます。MP4 なら画質とフレームレート、GIF ならフレームレート、サイズ、ループです。`exportAudio` は、プロジェクトの音声、またはインポートした 1 本のトラック(`importMedia` と `addAudio` で追加したナレーションなど)を、MP4 のミックスとまったく同じように WAV または M4A に書き出します。`exportCaptions` は、字幕を書き出した動画のタイミングに合わせて SRT または WebVTT の字幕ファイルに書き出します。 **上のサーバーを使う場合**、録画は OpenScreen 自身が、録画ボタンを押したときと同じように行います。エディターが閉じ、録画バーがカウントダウンして録画し、録画は新しいプロジェクトとしてエディターで開きます。そこで各編集が反映されるのを確認できます。**MCP による編集**をオンにする必要があり、録画が終わると録画バーの設定はあなた自身のものに戻ります。 diff --git a/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/ai-editing.md b/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/ai-editing.md index 28dbbdbfc9..eb6f9664fa 100644 --- a/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/ai-editing.md +++ b/website/i18n/pt-BR/docusaurus-plugin-content-docs/current/ai-editing.md @@ -76,7 +76,7 @@ Os pontos de restauração ficam na memória do OpenScreen: eles se perdem quand ## Como deixar um agente fazer o vídeo inteiro {#letting-an-agent-make-the-whole-video} -Um agente pode fazer um vídeo inteiro sozinho, da gravação à exportação. Além das ferramentas de edição, as duas formas de adicionar o OpenScreen ao agente lhe dão `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `getFrames` e `createProject`. No servidor do app, `waitForRecording` também espera uma gravação que você faz pela barra de gravação e a devolve como `stopRecording`. Uma gravação também pode incluir sua webcam e o cursor do próprio sistema, como a barra de gravação, e uma exportação aceita as opções da caixa de exportação: qualidade e taxa de quadros para um MP4; taxa de quadros, tamanho e repetição para um GIF. +Um agente pode fazer um vídeo inteiro sozinho, da gravação à exportação. Além das ferramentas de edição, as duas formas de adicionar o OpenScreen ao agente lhe dão `listSources`, `startRecording`, `stopRecording`, `setPointerTrack`, `exportVideo`, `exportAudio`, `exportCaptions`, `getFrames` e `createProject`. No servidor do app, `waitForRecording` também espera uma gravação que você faz pela barra de gravação e a devolve como `stopRecording`. Uma gravação também pode incluir sua webcam e o cursor do próprio sistema, como a barra de gravação, e uma exportação aceita as opções da caixa de exportação: qualidade e taxa de quadros para um MP4; taxa de quadros, tamanho e repetição para um GIF. `exportAudio` grava o áudio do projeto, ou uma única faixa importada (uma narração adicionada com `importMedia` e `addAudio`), em um WAV ou um M4A, exatamente como o MP4 o mixa. `exportCaptions` grava as legendas em um arquivo SRT ou WebVTT, sincronizado com o vídeo exportado. **Pelo servidor acima**, a gravação é feita pelo próprio OpenScreen, como com o botão Gravar: o editor fecha, a barra de gravação faz a contagem regressiva e grava, e a gravação abre no editor como um novo projeto, onde você vê cada edição chegar. É preciso ativar **Edições via MCP**, e a barra de gravação volta às suas próprias configurações quando a gravação termina. diff --git a/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/ai-editing.md b/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/ai-editing.md index e48600adaf..0848cda8de 100644 --- a/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/ai-editing.md +++ b/website/i18n/zh-CN/docusaurus-plugin-content-docs/current/ai-editing.md @@ -76,7 +76,7 @@ ChatGPT 和 GitHub Copilot 登录选项已**在 1.8.0 中移除**。它们的工 ## 让 AI 代理制作整段视频 {#letting-an-agent-make-the-whole-video} -AI 代理可以从录制到导出独立完成一整段视频。无论以哪种方式添加 OpenScreen,除编辑工具外,AI 代理都能使用 `listSources`、`startRecording`、`stopRecording`、`setPointerTrack`、`exportVideo`、`getFrames` 和 `createProject`。在应用内的服务器上,`waitForRecording` 还能等待你自己用录制栏录下的一段录制,并像 `stopRecording` 一样返回它。与录制栏一样,录制时也可以录下你的摄像头和系统自带的光标;导出则接受导出对话框的选项:MP4 的画质和帧率,GIF 的帧率、尺寸和循环。 +AI 代理可以从录制到导出独立完成一整段视频。无论以哪种方式添加 OpenScreen,除编辑工具外,AI 代理都能使用 `listSources`、`startRecording`、`stopRecording`、`setPointerTrack`、`exportVideo`、`exportAudio`、`exportCaptions`、`getFrames` 和 `createProject`。在应用内的服务器上,`waitForRecording` 还能等待你自己用录制栏录下的一段录制,并像 `stopRecording` 一样返回它。与录制栏一样,录制时也可以录下你的摄像头和系统自带的光标;导出则接受导出对话框的选项:MP4 的画质和帧率,GIF 的帧率、尺寸和循环。`exportAudio` 将项目的音频,或单独一条导入的音轨(用 `importMedia` 和 `addAudio` 添加的旁白),写入 WAV 或 M4A,与 MP4 的混音完全一致。`exportCaptions` 将字幕写入 SRT 或 WebVTT 字幕文件,时间与导出的视频对齐。 **通过上面的服务器**,录制由 OpenScreen 自己完成,就像按下它的录制按钮一样:编辑器关闭,录制栏倒计时后开始录制,录好的内容作为新项目在编辑器中打开,你可以看到每项编辑实时生效。这需要开启**MCP 编辑**,录制结束后,录制栏会恢复你自己的设置。 diff --git a/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/ai-editing.md b/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/ai-editing.md index 8cdc4fe886..90de80f87f 100644 --- a/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/ai-editing.md +++ b/website/i18n/zh-TW/docusaurus-plugin-content-docs/current/ai-editing.md @@ -76,7 +76,7 @@ ChatGPT 與 GitHub Copilot 的登入選項已**在 1.8.0 中移除**。它們的 ## 讓代理製作整支影片 {#letting-an-agent-make-the-whole-video} -代理可以從錄影到匯出自行製作一整支影片。無論以哪種方式加入 OpenScreen,除了剪輯工具之外,代理都能使用 `listSources`、`startRecording`、`stopRecording`、`setPointerTrack`、`exportVideo`、`getFrames` 與 `createProject`。在應用程式內的伺服器上,`waitForRecording` 還能等待你自己用錄影列錄下的一段錄影,並像 `stopRecording` 一樣傳回它。與錄影列一樣,錄影時也能錄下你的網路攝影機與系統本身的游標;匯出則接受匯出對話框的選項:MP4 的畫質與影格速率,GIF 的影格速率、尺寸與循環播放。 +代理可以從錄影到匯出自行製作一整支影片。無論以哪種方式加入 OpenScreen,除了剪輯工具之外,代理都能使用 `listSources`、`startRecording`、`stopRecording`、`setPointerTrack`、`exportVideo`、`exportAudio`、`exportCaptions`、`getFrames` 與 `createProject`。在應用程式內的伺服器上,`waitForRecording` 還能等待你自己用錄影列錄下的一段錄影,並像 `stopRecording` 一樣傳回它。與錄影列一樣,錄影時也能錄下你的網路攝影機與系統本身的游標;匯出則接受匯出對話框的選項:MP4 的畫質與影格速率,GIF 的影格速率、尺寸與循環播放。`exportAudio` 將專案的音訊,或單獨一條匯入的音軌(以 `importMedia` 與 `addAudio` 加入的旁白),寫入 WAV 或 M4A,與 MP4 的混音完全相同。`exportCaptions` 將字幕寫入 SRT 或 WebVTT 字幕檔,時間與匯出的影片對齊。 **透過上述伺服器**,錄影由 OpenScreen 自己完成,就像按下它的錄影按鈕一樣:編輯器會關閉,錄影列倒數後開始錄影,錄好的內容會以新專案在編輯器中開啟,你可以看到每項編輯即時生效。這需要開啟**MCP 編輯**,錄影結束後,錄影列會恢復你自己的設定。 From ba067eb0c65bf980bff33a14d62319e61671ea2e Mon Sep 17 00:00:00 2001 From: EtienneLescot Date: Sun, 22 Nov 2026 13:52:14 +0100 Subject: [PATCH 06/74] feat(plugin): bundle OpenScreen's MCP server through a launcher plugin/.mcp.json starts scripts/openscreen-mcp.mjs, which finds the installed app (OPENSCREEN_EXE, then the known locations per OS, the Store query last) and runs " mcp" with the streams inherited. When the app is missing, older than 2.1.0 or fails to start, it answers MCP itself with one openscreenSetup tool instead of failing. --- electron/mcp/plugin-launcher.test.ts | 139 +++++++++++++++ plugin/.mcp.json | 8 + plugin/scripts/openscreen-mcp.mjs | 244 +++++++++++++++++++++++++++ 3 files changed, 391 insertions(+) create mode 100644 electron/mcp/plugin-launcher.test.ts create mode 100644 plugin/.mcp.json create mode 100644 plugin/scripts/openscreen-mcp.mjs diff --git a/electron/mcp/plugin-launcher.test.ts b/electron/mcp/plugin-launcher.test.ts new file mode 100644 index 0000000000..4edfb68650 --- /dev/null +++ b/electron/mcp/plugin-launcher.test.ts @@ -0,0 +1,139 @@ +import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createInterface } from "node:readline"; +import { afterEach, describe, expect, it } from "vitest"; + +// The plugin's MCP launcher (plugin/scripts/openscreen-mcp.mjs), run as Claude Code runs it: +// `node