import { test, expect, type Page } from "@playwright/test"; import { spawnSync } from "node:child_process"; import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import * as urls from "./urls"; import { resetPostNarrationFiles } from "./fixtures/post-narration-fixture.mjs"; // --------------------------------------------------------------------------- // LONG READS (operator, 4 Nov, a 6.5-minute post): a read's parts RE-TIMED with // no TTS (lib/report/postReread.mjs tempoPlan: the parts named faster, pitch // kept, the words scaled with them), its caps YELLED (lib/report/postYell.mjs), // and the PROGRESS BAR along the card's foot (report-to-video/post-progress.mjs) // that fills over the read's real seconds -- in the bench and in Play. // Fixture: e2e/fixtures/post-narration-fixture.mjs -- p-11, given here a take // of three timed parts (6.6 s of tone, its words timed) and progress "on". // // LONG_READS_SHOTS= screenshots there // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); const DIR = path.join(HERE, "..", ".e2e-song", "reports", "post-narration-fixture"); const MANIFEST = path.join(DIR, "video.manifest.json"); const PROJECT = "reports/post-narration-fixture"; const SHOTS = process.env.LONG_READS_SHOTS ?? null; const TAKE = "narration/posts/11/take-7.parts-zac.wav"; const TEXT = "The video speaks for ITSELF.\n\nThen it says it AGAIN, louder.\n\nAnd that is all."; type Part = { n: number; para: number; text: string; start: number; seconds: number; tempo?: number }; type Take = { file: string; seconds: number; parts?: Part[]; words?: Array<{ w: string; start: number; end: number }>; steps?: Array>; source?: { kind: string; from?: string } }; type Entry = { id: string; progress?: string; text?: string; narration?: { takes: Take[]; pick?: number; script?: string } }; const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[]; render: Record }; const p11 = () => manifest().timeline.find((e) => e.id === "p-11")!; const picked = () => { const n = p11().narration!; return n.takes[n.pick ?? 0]; }; test.beforeAll(() => { if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`); }); // The project is shared (post-narration, post-captions, picture-replies, thread-* read it after this file): leave // it as the fixture built it -- its manifest, and no take-7 or re-read of p-11 on disk to number their takes past. test.afterAll(() => { copyFileSync(`${MANIFEST}.pristine`, MANIFEST); rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); resetPostNarrationFiles(DIR); }); test.beforeEach(() => { test.setTimeout(120_000); copyFileSync(`${MANIFEST}.pristine`, MANIFEST); rmSync(path.join(DIR, "revisions"), { recursive: true, force: true }); rmSync(path.join(DIR, "notes.json"), { force: true }); // A take of three parts: 2 s, 2 s, 1.4 s of tone with the read's pauses (0.6 s), every word timed. const file = path.join(DIR, ...TAKE.split("/")); const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "aevalsrc='0.2*sin(2*PI*220*t)*(0.6+0.4*sin(2*PI*4*t))*(lt(t,2)+between(t,2.6,4.6)+between(t,5.2,6.6))':s=24000:d=6.6", file]); if (r.status !== 0) throw new Error(String(r.stderr)); const script = TEXT.replace("ITSELF", "itself").replace("AGAIN", "again"); const words: Array<{ w: string; start: number; end: number }> = []; const parts: Part[] = script.split("\n\n").map((text, i) => ({ n: i + 1, para: i, text, start: [0, 2.6, 5.2][i], seconds: [2, 2, 1.4][i] })); for (const p of parts) { const ws = p.text.split(/\s+/); ws.forEach((w, j) => words.push({ w, start: Math.round((p.start + (j * p.seconds) / ws.length) * 1000) / 1000, end: Math.round((p.start + ((j + 0.8) * p.seconds) / ws.length) * 1000) / 1000 })); } const m = manifest(); const e = m.timeline.find((x) => x.id === "p-11")!; e.text = TEXT; e.progress = "on"; e.narration = { ...e.narration!, script, takes: [...e.narration!.takes, { file: TAKE, engine: "orpheus", voice: "zac", seconds: 6.6, script, words, parts } as Take], pick: e.narration!.takes.length }; writeFileSync(MANIFEST, JSON.stringify(m, null, 2) + "\n"); }); /** In the card frame: the bar's box and its fill's clip, the counts row's box, the card words' boxes. */ const barBoxes = (page: Page) => page.frameLocator('[data-post-card-frame="read"]').locator("body").evaluate((body) => { const doc = body.ownerDocument; const r = (el: Element | null) => { if (!el) return null; const b = el.getBoundingClientRect(); return { x: b.left, y: b.top, width: b.width, height: b.height }; }; const bar = doc.querySelector("[data-post-progress]") as HTMLElement | null; return { bar: r(bar), opacity: bar ? Number(bar.style.opacity) : null, frac: bar ? Number(bar.getAttribute("data-frac")) : null, ticks: doc.querySelectorAll(".pprog-tick").length, inCard: !!bar?.closest("[data-post-card]"), counts: r(doc.querySelector("[data-post-counts]")), card: r(doc.querySelector("[data-post-card]")), words: Array.from(doc.querySelectorAll("[data-w]")).map((w) => r(w)!), }; }); const overlap = (a: { x: number; y: number; width: number; height: number }, b: { x: number; y: number; width: number; height: number }) => Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); test("PER-PART TEMPO, no TTS: the route's reread with tempo \"2=1.5\" makes a derived take -- part 2 shorter by 1.5, its words scaled, the rest untouched -- picked; a re-tune cuts from the first read", async ({ page }) => { const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.5" } }); expect(res.ok(), await res.text()).toBeTruthy(); const t = picked(); expect(t.file).toMatch(/take-\d+\.tempo-orpheus\.wav$/); expect(t.steps?.[0]).toMatchObject({ op: "tempo", tempo: { 2: 1.5 }, params: { stretch: "atempo" } }); expect(t.parts!.map((p) => [p.start, p.seconds, p.tempo ?? 1])).toEqual([[0, 2, 1], [2.6, 1.333, 1.5], [4.533, 1.4, 1]]); expect(Math.abs(t.seconds - 5.933)).toBeLessThan(0.02); // The words of part 2 scaled from its start; part 3's moved up by what part 2 lost. const then = t.words!.find((w) => w.w === "Then")!; const again = t.words!.find((w) => w.w === "again,")!; const and = t.words!.find((w) => w.w === "And")!; expect([then.start, and.start]).toEqual([2.6, 4.533]); // "again," began 1.333 s into part 2: 0.889 s into it now. expect(again.start - 2.6).toBeCloseTo(1.333 / 1.5, 2); // A re-tune: 2=1.2 is cut from the three-part take, not the re-timed one. const res2 = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.2" } }); expect(res2.ok(), await res2.text()).toBeTruthy(); expect(picked().source).toEqual({ kind: "take", from: "take-7.parts-zac" }); expect(picked().parts!.map((p) => p.tempo ?? 1)).toEqual([1, 1.2, 1]); // Out of range: refused in the tool's words. const bad = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.9" } }); expect(bad.status()).toBe(400); expect((await bad.json()).error).toMatch(/a tempo is 1–1\.6/); }); test("THE CAPS YELLED: the route's reread with yell makes a derived take of the same length and timings, its spans over ITSELF and AGAIN, picked", async ({ page }) => { const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", yell: true } }); expect(res.ok(), await res.text()).toBeTruthy(); const t = picked(); expect(t.file).toMatch(/take-\d+\.yell-orpheus\.wav$/); expect(t.steps?.[0]).toMatchObject({ op: "yell", params: { style: "raise" } }); const spans = t.steps![0].spans as number[][]; expect(spans).toHaveLength(2); const itself = t.words!.find((w) => w.w === "itself.")!; const again = t.words!.find((w) => w.w === "again,")!; expect(spans[0][0]).toBeLessThanOrEqual(itself.start); expect(spans[1][0]).toBeLessThanOrEqual(again.start); expect(Math.abs(t.seconds - 6.6)).toBeLessThan(0.02); expect(t.parts!.map((p) => p.start)).toEqual([0, 2.6, 5.2]); }); test("THE PROGRESS BAR on the bench: along the card's foot under its counts row, over no word, ticked at the parts, filling linearly with the read -- and after a tempo, no jump", async ({ page }) => { await page.setViewportSize({ width: 1500, height: 1100 }); await page.goto(urls.postBenchHref(PROJECT, "p-11")); const player = page.locator('[data-post-play="p-11"]'); await expect(player).toHaveAttribute("data-post-progress", "0", { timeout: 15_000 }); await expect(player).toHaveAttribute("data-post-progress-place", /\d+,\d+,\d+/); let g = await barBoxes(page); expect(g.bar).not.toBeNull(); expect(g.inCard, "drawn over the card, never in it").toBe(false); expect(g.ticks).toBe(2); expect(g.bar!.y).toBeGreaterThanOrEqual(g.counts!.y + g.counts!.height); expect(g.bar!.y + g.bar!.height).toBeLessThanOrEqual(g.card!.y + g.card!.height + 1); for (const w of g.words) expect(overlap(g.bar!, w)).toBe(0); // Play it: the fill follows the read. await page.locator("[data-post-bench-play]").click(); await expect.poll(async () => Number(await player.getAttribute("data-post-progress")), { timeout: 15_000 }).toBeGreaterThan(0.3); await page.locator("[data-post-bench-play]").click(); g = await barBoxes(page); expect(g.opacity).toBe(1); if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "long-reads-bench-progress.png") }); // Its fill is real time over the read: at a second of the item, (s - lead) / read. const s = Number(await player.getAttribute("data-post-s")); const frac = Number(await player.getAttribute("data-post-progress")); const lead = 0.4; expect(Math.abs(frac - Math.min(1, Math.max(0, (s - lead) / 6.6)))).toBeLessThan(0.02); }); test("THE PROGRESS BAR in Play, with the read re-timed: it fills over the new read's seconds, monotonic across the faster part", async ({ page }) => { const res = await page.request.post("/api/report/post-narration", { data: { project: PROJECT, op: "reread", id: "p-11", tempo: "2=1.5" } }); expect(res.ok(), await res.text()).toBeTruthy(); await page.setViewportSize({ width: 1366, height: 1000 }); await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-11" })); const player = page.locator('[data-post-play="p-11"]'); await expect(player).toHaveAttribute("data-post-progress", "0", { timeout: 15_000 }); await page.locator("[data-play-toggle]").click(); const seen: Array<[number, number]> = []; await expect .poll(async () => { // Both read at one instant (one evaluate): two reads a load apart are two clocks' worth of drift. const [s, f] = await player.evaluate((el) => [Number(el.getAttribute("data-post-s")), Number(el.getAttribute("data-post-progress"))]); seen.push([s, f]); return f; }, { timeout: 20_000, intervals: [150] }) .toBeGreaterThan(0.95); await page.locator("[data-play-toggle]").click(); // Monotonic, and never a jump: each step of the fill is the step of the clock over the read's 5.933 s. for (let i = 1; i < seen.length; i += 1) { const [s0, f0] = seen[i - 1]; const [s1, f1] = seen[i]; expect(f1).toBeGreaterThanOrEqual(f0); if (f0 > 0 && f1 < 1) expect(Math.abs(f1 - f0 - (s1 - s0) / 5.933)).toBeLessThan(0.03); } if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "long-reads-play-progress.png") }); });