feat(media): media put seals durationMs, width and height measured by ffprobe

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-20 00:03:38 +02:00
parent 8c7b8800fa
commit 6f67bad97e
5 changed files with 78 additions and 2 deletions

View File

@@ -0,0 +1,10 @@
---
title: "media put forsegler lengde og bildestørrelse"
date: 2026-10-20
created: 2026-10-20T00:03:38+02:00
author: "Claude"
---
`media put` måler nå lengde og bildestørrelse med ffprobe og forsegler dem i meta (`durationMs`, `width`, `height`), målt på filen som faktisk forsegles (etter `--web`). Feltene fantes i `MediaMeta` og ble lest av Iris og `/watch/`, men ble aldri fylt ut. Derfor viste Iris på Android filmfliser uten lengde.
Verifisert: ny test i `tests/web-prep.test.ts` (film har lengde og størrelse, lyd bare lengde, bilde bare størrelse, manglende fil gir tomt). Hele `shade-media` er grønn: 119 bestått og 6 hoppet over. `tsc` er ren.

View File

@@ -5,6 +5,14 @@ All notable changes to Shade are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
- **`media put` records length and picture size.** Video, audio and images
are measured with ffprobe (after `--web`, so the numbers match the sealed
file) and sealed with `durationMs`, `width` and `height` in their meta. A
viewer can show a film's length on a tile and reserve its shape without
fetching a byte. Without ffprobe the fields are left out, as before.
## [4.15.0] — 2026-10-18 — Media: films, video, images, audio and live streams, end to end ## [4.15.0] — 2026-10-18 — Media: films, video, images, audio and live streams, end to end
New package **`@shade/media`** — see `docs/media.md`. New package **`@shade/media`** — see `docs/media.md`.

View File

@@ -35,7 +35,7 @@ import type { MediaMeta } from './sealed.js';
import { MediaSplitter } from './splitter.js'; import { MediaSplitter } from './splitter.js';
import { IMAGE_MIME, ImageStreamSplitter } from './image-stream.js'; import { IMAGE_MIME, ImageStreamSplitter } from './image-stream.js';
import { SUBTITLE_EXTENSIONS, subtitleFor, subtitlesOf, withSubtitles } from './subtitles.js'; import { SUBTITLE_EXTENSIONS, subtitleFor, subtitlesOf, withSubtitles } from './subtitles.js';
import { liveEncodePlan, prepareForWeb, probeLive, webIssues } from './web-prep.js'; import { describeMedia, liveEncodePlan, prepareForWeb, probeLive, webIssues } from './web-prep.js';
import { MediaLibrary } from './library.js'; import { MediaLibrary } from './library.js';
import { PutJobs, stillServed } from './put-jobs.js'; import { PutJobs, stillServed } from './put-jobs.js';
import type { PutJob } from './put-jobs.js'; import type { PutJob } from './put-jobs.js';
@@ -355,6 +355,8 @@ async function sealAndPut(ctx: PutCtx, file: string, flags: Flags, as: PutAs, ke
} }
if (tracks.length > 0) meta = withSubtitles(meta, tracks); if (tracks.length > 0) meta = withSubtitles(meta, tracks);
} }
// Measured on what is sealed (after --web), so the numbers match the file a viewer gets.
if (/^(video|audio|image)\//.test(meta.mime ?? '')) meta = { ...meta, ...(await describeMedia(source)) };
const size = (await stat(source)).size; const size = (await stat(source)).size;
// A job's sealed copy is kept for the next run; anything else is temporary. // A job's sealed copy is kept for the next run; anything else is temporary.
const sealed = key !== null ? ctx.jobs.sealedPath(key) : join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`); const sealed = key !== null ? ctx.jobs.sealedPath(key) : join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`);

View File

@@ -69,6 +69,40 @@ export async function probe(input: string): Promise<ProbeStream[]> {
return (JSON.parse(out) as { streams?: ProbeStream[] }).streams ?? []; return (JSON.parse(out) as { streams?: ProbeStream[] }).streams ?? [];
} }
/** What a viewer wants to know before opening a file: its length and picture size. */
export interface MediaFacts {
durationMs?: number;
width?: number;
height?: number;
}
/**
* Length and picture size from ffprobe, for the meta a file is sealed with:
* a viewer can then show "1:28" on a tile and reserve the right shape
* without fetching a byte of the film. Empty without ffprobe or when the
* file says nothing (a still picture has no length, a sound no size).
*/
export async function describeMedia(input: string): Promise<MediaFacts> {
if (Bun.which('ffprobe') === null) return {};
let parsed: { streams?: (ProbeStream & { width?: number; height?: number; duration?: string })[]; format?: { duration?: string; format_name?: string } };
try {
parsed = JSON.parse(await run(['ffprobe', '-v', 'error', '-show_streams', '-show_format', '-of', 'json', input]));
} catch {
return {};
}
const facts: MediaFacts = {};
const picture = parsed.streams?.find((s) => s.codec_type === 'video' && s.disposition?.attached_pic !== 1);
if (picture?.width !== undefined && picture.height !== undefined && picture.width > 0 && picture.height > 0) {
facts.width = picture.width;
facts.height = picture.height;
}
// Image formats report a nominal length (one frame, or a GIF's loop); only timed media gets one.
const still = /image2|_pipe$|png|webp|gif/.test(parsed.format?.format_name ?? '');
const seconds = Number(parsed.format?.duration ?? picture?.duration);
if (!still && Number.isFinite(seconds) && seconds > 0) facts.durationMs = Math.round(seconds * 1000);
return facts;
}
/** /**
* What in this file browsers will not play, in plain words; empty if it * What in this file browsers will not play, in plain words; empty if it
* plays as it is. Without ffprobe nothing can be said, and nothing is. * plays as it is. Without ffprobe nothing can be said, and nothing is.

View File

@@ -2,7 +2,7 @@ import { describe, test, expect, afterAll } from 'bun:test';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os'; import { tmpdir } from 'node:os';
import { join } from 'node:path'; import { join } from 'node:path';
import { liveEncodePlan, prepareForWeb, probe } from '../src/web-prep.js'; import { describeMedia, liveEncodePlan, prepareForWeb, probe } from '../src/web-prep.js';
import type { ProbeStream } from '../src/web-prep.js'; import type { ProbeStream } from '../src/web-prep.js';
const hasFfmpeg = Bun.which('ffmpeg') !== null && Bun.which('ffprobe') !== null; const hasFfmpeg = Bun.which('ffmpeg') !== null && Bun.which('ffprobe') !== null;
@@ -105,3 +105,25 @@ describe('liveEncodePlan (live video --input)', () => {
expect(() => liveEncodePlan('x', [], { realtime: false })).toThrow(/no audio or video/); expect(() => liveEncodePlan('x', [], { realtime: false })).toThrow(/no audio or video/);
}); });
}); });
describe.skipIf(!hasFfmpeg)('describeMedia (the meta media put seals)', () => {
test('a film has length and size, a sound only length, a picture only size', async () => {
const dir = await mkdtemp(join(tmpdir(), 'shade-describe-'));
dirs.push(dir);
const film = join(dir, 'film.mp4');
const sound = join(dir, 'sound.ogg');
const still = join(dir, 'still.webp');
await ff(['-f', 'lavfi', '-i', 'testsrc=size=320x180:rate=25', '-t', '2.5', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', film]);
await ff(['-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000', '-t', '1.5', '-c:a', 'libvorbis', sound]);
await ff(['-f', 'lavfi', '-i', 'testsrc=size=64x48', '-frames:v', '1', still]);
const f = await describeMedia(film);
expect([f.width, f.height]).toEqual([320, 180]);
expect(Math.abs(f.durationMs! - 2500)).toBeLessThan(80);
const a = await describeMedia(sound);
expect(a.width).toBeUndefined();
expect(Math.abs(a.durationMs! - 1500)).toBeLessThan(80);
expect(await describeMedia(still)).toEqual({ width: 64, height: 48 });
expect(await describeMedia(join(dir, 'missing.mp4'))).toEqual({});
}, 30_000);
});