|
| 1 | +import { afterAll, beforeAll, describe, expect, it } from "vitest"; |
| 2 | +import { mkdtempSync, rmSync } from "node:fs"; |
| 3 | +import { join } from "node:path"; |
| 4 | +import { tmpdir } from "node:os"; |
| 5 | +import { spawnSync } from "node:child_process"; |
| 6 | +import { runFfmpeg } from "../utils/runFfmpeg.js"; |
| 7 | +import { extractVideoFramesRange, type ExtractedFrames } from "./videoFrameExtractor.js"; |
| 8 | + |
| 9 | +const HAS_FFMPEG = spawnSync("ffmpeg", ["-version"]).status === 0; |
| 10 | +const WIDTH = 32; |
| 11 | +const HEIGHT = 16; |
| 12 | + |
| 13 | +// B-frames at a 1/600 timescale (what Apple devices write) store each frame one tick long. |
| 14 | +describe.skipIf(!HAS_FFMPEG)("a window that ends at the source's end", () => { |
| 15 | + const fixtureDir = mkdtempSync(join(tmpdir(), "hf-final-frame-")); |
| 16 | + const source = join(fixtureDir, "index-30fps-bframes-ts600.mov"); |
| 17 | + |
| 18 | + beforeAll(async () => { |
| 19 | + // Frame k carries luma 16 + 2k, so each extracted frame names its source index. |
| 20 | + const synth = await runFfmpeg([ |
| 21 | + ...["-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i"], |
| 22 | + `nullsrc=s=${WIDTH}x${HEIGHT}:r=30:d=1.5,geq=lum='16+2*N':cb=128:cr=128`, |
| 23 | + ...["-c:v", "libx264", "-qp", "1", "-bf", "2", "-pix_fmt", "yuv420p"], |
| 24 | + ...["-video_track_timescale", "600", source], |
| 25 | + ]); |
| 26 | + if (!synth.success) throw new Error(`b-frame fixture synthesis failed: ${synth.stderr}`); |
| 27 | + }, 30_000); |
| 28 | + |
| 29 | + afterAll(() => { |
| 30 | + rmSync(fixtureDir, { recursive: true, force: true }); |
| 31 | + }); |
| 32 | + |
| 33 | + function sourceIndexes(extracted: ExtractedFrames): number[] { |
| 34 | + const decoded = spawnSync("ffmpeg", [ |
| 35 | + ...["-v", "error", "-i", join(extracted.outputDir, extracted.framePattern)], |
| 36 | + ...["-f", "rawvideo", "-pix_fmt", "gray", "pipe:1"], |
| 37 | + ]); |
| 38 | + if (decoded.status !== 0) throw new Error(decoded.stderr.toString()); |
| 39 | + const indexes: number[] = []; |
| 40 | + for (let offset = 0; offset < decoded.stdout.length; offset += WIDTH * HEIGHT) { |
| 41 | + indexes.push(Math.round(((decoded.stdout[offset] ?? 0) * 219) / 255 / 2)); |
| 42 | + } |
| 43 | + return indexes; |
| 44 | + } |
| 45 | + |
| 46 | + it("keeps the last frame of a window that ends at the source's end", async () => { |
| 47 | + const extracted = await extractVideoFramesRange(source, "bframes-tail", 37 / 30, 8 / 30, { |
| 48 | + fps: 30, |
| 49 | + outputDir: fixtureDir, |
| 50 | + format: "png", |
| 51 | + }); |
| 52 | + expect(sourceIndexes(extracted)).toEqual([37, 38, 39, 40, 41, 42, 43, 44]); |
| 53 | + }, 30_000); |
| 54 | +}); |
0 commit comments