diff --git a/.scaffold/branches/streaming.md b/.scaffold/branches/streaming.md index e0e378b..eb3768b 100644 --- a/.scaffold/branches/streaming.md +++ b/.scaffold/branches/streaming.md @@ -28,6 +28,7 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video - [x] Sikkerhet: `shade media get` brukte `meta.name` som filsti (sti-traversering) — rettet - [x] Android live: `LiveWatcher` + `ShadeLiveDataSource` (WebM/fMP4 i ExoPlayer, sen innstigning, hull, tidslinje fra 0), demo-appen spiller live video og følger loggkanaler - [x] Undertekster: `Film.no.srt` ved siden av filmen forsegles og følger filmen i dens meta; `` i nettleseren (språkvalg, SRT→VTT), ExoPlayer på Android, `media get` skriver dem tilbake +- [x] `media put --web`: HEVC/AC3/DTS-filmer (som Chromium nekter) konverteres før forsegling, innebygde tekstundertekster blir spor; advarsel uten flagget ## Neste - Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18) diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/08-web-hevc-ac3.png b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/08-web-hevc-ac3.png new file mode 100644 index 0000000..cb955d9 Binary files /dev/null and b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/08-web-hevc-ac3.png differ diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt index 6332d72..7edf3b1 100644 --- a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt +++ b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt @@ -5,3 +5,4 @@ 05 — Live H.264/AAC som fragmentert MP4 (ffmpeg → shade live video → relay → Chromium), sen innstigning på keyframe-fragment, 3,2 s forsinkelse 06 — Et album («Ferie 2026»): én lenke åpner film, video, lyd, bilde og et nøstet album; forhåndsvisningene dekrypteres i nettleseren, relayen ser bare én ugjennomsiktig fil til 07 — En forseglet film med Testfilm.no.srt og Testfilm.en.srt ved siden av: undertekstene følger filmen kryptert, og nettleseren velger norsk fordi den er satt til bokmål +08 — En ekte MKV-film med HEVC-video og AC3 5.1-lyd: Chromium nekter originalen («no supported streams»); med media put --web spiller den med lyd og den innebygde norske underteksten diff --git a/CHANGELOG.md b/CHANGELOG.md index 410b104..3adf526 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,11 @@ New package **`@shade/media`** — see `docs/media.md`. VTT, the viewer's language on), `media get` writes them back, and Android plays them as side-loaded ExoPlayer text tracks (`ShadeMedia.openFilm`). +- **`media put --web`.** Films with AC-3/DTS audio or HEVC video (Chromium + refuses them outright) are converted before sealing: what browsers play + is copied, the rest becomes H.264/AAC, embedded text subtitles become + subtitle tracks, all in one ffmpeg pass. Without the flag, `put` warns + when ffprobe sees streams browsers will not play. - **Kotlin.** `no.zyon.shade.media`: SMF1 reader and sealer, grants, live subscriber and publisher — byte-for-byte against `test-vectors/media.json`. `:shade-android-media` plays sealed files in Media3/ExoPlayer diff --git a/docs/media.md b/docs/media.md index 753125b..14fefa0 100644 --- a/docs/media.md +++ b/docs/media.md @@ -298,6 +298,25 @@ in TS, `Albums.parse` / `Albums.read` in Kotlin. The `/watch/` page shows an alb grid with decrypted previews, and Back returns from an item to its album. History entries hold only a depth, never a grant. +## Films that play in any browser (`--web`) + +Real films are often MKV with AC-3, E-AC-3 or DTS audio, or HEVC video. Browsers decode +none of those: Chromium refuses such a file outright ("no supported streams"). Since +sealing happens on the uploader's machine and the relay never sees the content, that is +the only place to fix it. `shade media put Film.mkv --web` runs ffmpeg first: + +| In the file | Becomes | +|---|---| +| H.264, VP8, VP9, AV1 video | copied | +| other video (HEVC, MPEG-2, …) | H.264 (CRF 20), which takes a while | +| AAC, MP3, Opus audio | copied | +| other audio (AC-3, E-AC-3, DTS, TrueHD) | AAC, all tracks kept with their languages | +| text subtitles (SubRip, ASS, mov_text) | subtitle tracks (below), in the same pass | +| picture subtitles (PGS, DVD) | reported and skipped: they cannot become text | + +The result is an MP4 with its index first. Without `--web`, `media put` uses ffprobe +(when it is installed) to say which streams browsers will not play. + ## Subtitles `shade media put Film.mkv` also seals and uploads the subtitle files next to it, named diff --git a/packages/shade-media/src/cli.ts b/packages/shade-media/src/cli.ts index 9b82f0e..5958dac 100644 --- a/packages/shade-media/src/cli.ts +++ b/packages/shade-media/src/cli.ts @@ -14,7 +14,7 @@ * `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure. */ -import { chmod, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { chmod, mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'; import { createWriteStream } from 'node:fs'; import { homedir, tmpdir } from 'node:os'; import { basename, dirname, extname, join } from 'node:path'; @@ -31,6 +31,7 @@ import { OwnerKey } from './owner.js'; import type { MediaMeta } from './sealed.js'; import { MediaSplitter } from './splitter.js'; import { SUBTITLE_EXTENSIONS, subtitleFor, subtitlesOf, withSubtitles } from './subtitles.js'; +import { prepareForWeb, webIssues } from './web-prep.js'; import type { SubtitleTrack } from './subtitles.js'; import type { LiveContainer } from './splitter.js'; @@ -208,18 +209,42 @@ async function putFile(client: MediaClient, file: string, flags: Flags, as: { na let meta: MediaMeta = { name: as.name ?? basename(file) }; const mime = as.mime ?? guessMime(file); if (mime !== undefined) meta.mime = mime; - if (mime?.startsWith('video/')) { - const tracks = await putSubtitles(client, file, flags); - if (tracks.length > 0) meta = withSubtitles(meta, tracks); - } - const size = (await stat(file)).size; - const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`); + let source = file; + let work: string | null = null; try { - err(`sealing ${basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`); - const result = await sealFile(file, tmp, { meta }); - return await client.putSealed(result, Bun.file(tmp), { meta, ...putOpts(flags) }); + if (mime?.startsWith('video/')) { + const tracks = await putSubtitles(client, file, flags); + if (flags.web === true) { + // Re-encode only what browsers cannot play; pull text subtitles out as tracks. + work = await mkdtemp(join(tmpdir(), 'shade-web-')); + const prep = await prepareForWeb(file, work, { onProgress: (l) => err(` ${basename(file)}: ${l}`) }); + const stem = basename(file).slice(0, basename(file).length - extname(file).length); + source = prep.file; + meta = { name: as.name ?? `${stem}.mp4`, mime: prep.mime }; + for (const sub of prep.subtitles) { + const name = `${stem}${sub.lang !== undefined ? `.${sub.lang}` : ''}.srt`; + const grant = await putFile(client, sub.path, flags, { name, mime: 'text/plain; charset=utf-8' }); + tracks.push({ grant, ...(sub.lang !== undefined ? { lang: sub.lang } : {}), ...(sub.title !== undefined ? { label: sub.title } : {}) }); + } + } else { + const issues = await webIssues(file); + if (issues.length > 0) { + err(` note: browsers will not play ${issues.join(', ')} in ${basename(file)} (most Android devices will); add --web to convert`); + } + } + if (tracks.length > 0) meta = withSubtitles(meta, tracks); + } + const size = (await stat(source)).size; + const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`); + try { + err(`sealing ${meta.name ?? basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`); + const result = await sealFile(source, tmp, { meta }); + return await client.putSealed(result, Bun.file(tmp), { meta, ...putOpts(flags) }); + } finally { + await rm(tmp, { force: true }); + } } finally { - await rm(tmp, { force: true }); + if (work !== null) await rm(work, { recursive: true, force: true }); } } @@ -528,9 +553,13 @@ export const MEDIA_HELP = ` Run a media relay: sealed store, live relay, watch page. Only this machine's key (and --owners) may upload/publish. media whoami Print this machine's owner key (to add to a relay's --owners) - media put … --server URL [--album T] [--name N] [--mime M] [--public] [--json] + media put … --server URL [--album T] [--name N] [--mime M] [--web] [--public] [--json] Seal a film/video/image/song, upload it, print a watch link. Several files or a directory become an album: one link for all. + Film.no.srt etc. next to a film travel with it as subtitles. + --web: make films play in any browser first (ffmpeg): copy + what browsers play, AC-3/DTS audio → AAC, HEVC → H.264, + embedded text subtitles → subtitle tracks. media get [-o file|dir|-] Download and decrypt a sealed file (an album: a directory) media ls --server URL Your uploads on that server diff --git a/packages/shade-media/src/web-prep.ts b/packages/shade-media/src/web-prep.ts new file mode 100644 index 0000000..9bf7c01 --- /dev/null +++ b/packages/shade-media/src/web-prep.ts @@ -0,0 +1,147 @@ +/** + * Make a film playable in any browser before it is sealed (`media put --web`). + * + * Real films are often MKV with AC-3/E-AC-3/DTS audio or HEVC video, which + * browsers do not decode: the picture plays and the sound is missing, or + * nothing plays. Sealing happens client-side and the relay never sees the + * content, so this is the only place it can be fixed. With ffprobe/ffmpeg: + * + * - video browsers play (H.264, VP8, VP9, AV1) is copied, anything else is + * encoded to H.264; + * - audio browsers play (AAC, MP3, Opus) is copied, anything else becomes AAC; + * - text subtitles inside the file (SubRip, ASS, mov_text, WebVTT) are pulled + * out as `.srt` files, to travel as subtitle tracks; picture subtitles + * (PGS, DVD) cannot become text and are reported, not dropped silently; + * - the result is an MP4 with the index first, so playback starts at once. + * + * Node/Bun only: it runs ffmpeg. + */ + +import { join } from 'node:path'; + +export interface WebPrepared { + /** The MP4 to seal. */ + file: string; + mime: 'video/mp4' | 'audio/mp4'; + /** Text subtitle streams extracted from the input, as `.srt` files. */ + subtitles: { path: string; lang?: string; title?: string }[]; + /** What was done, in plain words, for the CLI to print. */ + notes: string[]; +} + +interface ProbeStream { + index: number; + codec_type: 'video' | 'audio' | 'subtitle' | 'data' | 'attachment'; + codec_name?: string; + channels?: number; + disposition?: { attached_pic?: number }; + tags?: { language?: string; title?: string }; +} + +const WEB_VIDEO = new Set(['h264', 'vp8', 'vp9', 'av1']); +const WEB_AUDIO = new Set(['aac', 'mp3', 'opus']); +const TEXT_SUBS = new Set(['subrip', 'ass', 'ssa', 'mov_text', 'webvtt', 'text']); + +/** ISO 639-2 codes in MKV tags → the short tags subtitle files use. */ +const LANG2: Record = { + nor: 'no', nob: 'nb', nno: 'nn', eng: 'en', swe: 'sv', dan: 'da', fin: 'fi', isl: 'is', ger: 'de', deu: 'de', + fre: 'fr', fra: 'fr', spa: 'es', ita: 'it', por: 'pt', dut: 'nl', nld: 'nl', pol: 'pl', rus: 'ru', jpn: 'ja', + chi: 'zh', zho: 'zh', kor: 'ko', ara: 'ar', tur: 'tr', ukr: 'uk', cze: 'cs', ces: 'cs', gre: 'el', ell: 'el', + heb: 'he', hin: 'hi', hun: 'hu', ron: 'ro', rum: 'ro', tha: 'th', vie: 'vi', ind: 'id', est: 'et', lav: 'lv', lit: 'lt', +}; + +function lang(tag: string | undefined): string | undefined { + if (tag === undefined || tag === 'und') return undefined; + const t = tag.toLowerCase(); + if (/^[a-z]{2}$/.test(t)) return t; + return LANG2[t] ?? (/^[a-z]{3}$/.test(t) ? t : undefined); +} + +async function run(cmd: string[]): Promise { + const p = Bun.spawn(cmd, { stdout: 'pipe', stderr: 'pipe' }); + const [out, errText, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]); + if (code !== 0) throw new Error(`${cmd[0]} failed: ${errText.trim().split('\n').slice(-3).join(' / ')}`); + return out; +} + +export async function probe(input: string): Promise { + const out = await run(['ffprobe', '-v', 'error', '-show_streams', '-of', 'json', input]); + return (JSON.parse(out) as { streams?: ProbeStream[] }).streams ?? []; +} + +/** + * 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. + */ +export async function webIssues(input: string): Promise { + if (Bun.which('ffprobe') === null) return []; + let streams: ProbeStream[]; + try { + streams = await probe(input); + } catch { + return []; + } + const issues: string[] = []; + for (const s of streams) { + if (s.codec_type === 'video' && s.disposition?.attached_pic !== 1 && !WEB_VIDEO.has(s.codec_name ?? '')) issues.push(`video ${s.codec_name}`); + if (s.codec_type === 'audio' && !WEB_AUDIO.has(s.codec_name ?? '') && s.codec_name !== 'vorbis' && s.codec_name !== 'flac') issues.push(`audio ${s.codec_name}`); + } + return issues; +} + +/** Prepare `input` for browsers into `workdir`. Throws if ffmpeg is missing or fails. */ +export async function prepareForWeb(input: string, workdir: string, opts: { onProgress?: (line: string) => void } = {}): Promise { + if (Bun.which('ffmpeg') === null || Bun.which('ffprobe') === null) { + throw new Error('--web needs ffmpeg and ffprobe on PATH'); + } + const streams = await probe(input); + const video = streams.find((s) => s.codec_type === 'video' && s.disposition?.attached_pic !== 1); + const audio = streams.filter((s) => s.codec_type === 'audio'); + if (video === undefined && audio.length === 0) throw new Error('no audio or video stream to prepare'); + const notes: string[] = []; + const args = ['ffmpeg', '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', '-i', input]; + + if (video !== undefined) { + args.push('-map', `0:${video.index}`); + if (WEB_VIDEO.has(video.codec_name ?? '')) { + args.push('-c:v', 'copy'); + } else { + // Encoding takes as long as it takes; quality first, the file is kept. + args.push('-c:v', 'libx264', '-preset', 'medium', '-crf', '20', '-pix_fmt', 'yuv420p'); + notes.push(`video ${video.codec_name} → H.264 (browsers do not play ${video.codec_name}; this takes a while)`); + } + } + // Every audio track is kept (Android players can switch); the first is the default. + audio.forEach((a, i) => { + args.push('-map', `0:${a.index}`); + if (WEB_AUDIO.has(a.codec_name ?? '')) { + args.push(`-c:a:${i}`, 'copy'); + } else { + args.push(`-c:a:${i}`, 'aac', `-b:a:${i}`, (a.channels ?? 2) > 2 ? '384k' : '192k'); + if ((a.channels ?? 2) > 6) args.push(`-ac:a:${i}`, '6'); + notes.push(`audio ${a.codec_name}${a.tags?.language ? ` (${a.tags.language})` : ''} → AAC`); + } + const l = a.tags?.language; + if (l !== undefined) args.push(`-metadata:s:a:${i}`, `language=${l}`); + }); + const file = join(workdir, 'web.mp4'); + args.push('-sn', '-dn', '-map_chapters', '0', '-movflags', '+faststart', '-f', 'mp4', file); + + // Text subtitles come out of the same pass: one read of a 20 GB film, not one per track. + const subtitles: WebPrepared['subtitles'] = []; + for (const s of streams.filter((x) => x.codec_type === 'subtitle')) { + const l = lang(s.tags?.language); + if (!TEXT_SUBS.has(s.codec_name ?? '')) { + notes.push(`subtitle ${s.codec_name}${l ? ` (${l})` : ''} skipped: picture subtitles cannot become text`); + continue; + } + const path = join(workdir, `sub-${s.index}.srt`); + args.push('-map', `0:${s.index}`, '-c:s', 'srt', '-f', 'srt', path); + subtitles.push({ path, ...(l !== undefined ? { lang: l } : {}), ...(s.tags?.title !== undefined ? { title: s.tags.title } : {}) }); + notes.push(`subtitle ${s.codec_name}${l ? ` (${l})` : ''} → subtitle track`); + } + // Said before the run: encoding a film can take a long time. + for (const n of notes.length > 0 ? notes : ['remuxing to MP4 (no re-encoding needed)']) opts.onProgress?.(n); + await run(args); + return { file, mime: video !== undefined ? 'video/mp4' : 'audio/mp4', subtitles, notes }; +} diff --git a/packages/shade-media/tests/web-prep.test.ts b/packages/shade-media/tests/web-prep.test.ts new file mode 100644 index 0000000..e8c2ff5 --- /dev/null +++ b/packages/shade-media/tests/web-prep.test.ts @@ -0,0 +1,72 @@ +import { describe, test, expect, afterAll } from 'bun:test'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { prepareForWeb, probe } from '../src/web-prep.js'; + +const hasFfmpeg = Bun.which('ffmpeg') !== null && Bun.which('ffprobe') !== null; +const dirs: string[] = []; +afterAll(async () => { + for (const d of dirs) await rm(d, { recursive: true, force: true }); +}); + +async function ff(args: string[]): Promise { + const p = Bun.spawn(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', ...args], { stderr: 'inherit' }); + if ((await p.exited) !== 0) throw new Error('ffmpeg failed'); +} + +describe.skipIf(!hasFfmpeg)('prepareForWeb (media put --web)', () => { + test('HEVC + AC-3 5.1 + AAC + two embedded SubRip tracks → H.264/AAC MP4 and two .srt', async () => { + const dir = await mkdtemp(join(tmpdir(), 'shade-webprep-')); + dirs.push(dir); + await writeFile(join(dir, 'no.srt'), '1\n00:00:00,500 --> 00:00:01,500\nHei på deg\n'); + await writeFile(join(dir, 'en.srt'), '1\n00:00:00,500 --> 00:00:01,500\nHello there\n'); + const mkv = join(dir, 'Film.mkv'); + await ff([ + '-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=25,format=yuv420p', + '-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000', + '-f', 'lavfi', '-i', 'sine=frequency=660:sample_rate=48000', + '-i', join(dir, 'no.srt'), '-i', join(dir, 'en.srt'), + '-t', '2', '-map', '0', '-map', '1', '-map', '2', '-map', '3', '-map', '4', + '-c:v', 'libx265', '-preset', 'ultrafast', '-x265-params', 'log-level=none', + '-c:a:0', 'ac3', '-ac:a:0', '6', '-c:a:1', 'aac', + '-c:s', 'srt', + '-metadata:s:a:0', 'language=eng', '-metadata:s:a:1', 'language=nor', + '-metadata:s:s:0', 'language=nor', '-metadata:s:s:0', 'title=Norsk', '-metadata:s:s:1', 'language=eng', + mkv, + ]); + const work = await mkdtemp(join(tmpdir(), 'shade-webprep-out-')); + dirs.push(work); + const prep = await prepareForWeb(mkv, work); + + const out = await probe(prep.file); + expect(out.filter((s) => s.codec_type === 'video').map((s) => s.codec_name)).toEqual(['h264']); + expect(out.filter((s) => s.codec_type === 'audio').map((s) => [s.codec_name, s.channels, s.tags?.language])).toEqual([ + ['aac', 6, 'eng'], + ['aac', 1, 'nor'], // the source is mono; copied, not upmixed + ]); + expect(out.some((s) => s.codec_type === 'subtitle')).toBe(false); + // Index first: playback starts without fetching the end of the file. + const head = new TextDecoder().decode((await readFile(prep.file)).subarray(0, 64 * 1024)); + expect(head.indexOf('moov')).toBeGreaterThan(-1); + expect(head.indexOf('moov')).toBeLessThan(Math.max(head.indexOf('mdat'), 0) || Infinity); + + expect(prep.subtitles.map((s) => [s.lang, s.title])).toEqual([['no', 'Norsk'], ['en', undefined]]); + expect(await readFile(prep.subtitles[0]!.path, 'utf8')).toContain('Hei på deg'); + expect(await readFile(prep.subtitles[1]!.path, 'utf8')).toContain('Hello there'); + expect(prep.notes.join('\n')).toMatch(/hevc → H\.264/); + expect(prep.notes.join('\n')).toMatch(/ac3 \(eng\) → AAC/); + }, 60_000); + + test('a file browsers already play is only remuxed', async () => { + const dir = await mkdtemp(join(tmpdir(), 'shade-webprep-')); + dirs.push(dir); + const mkv = join(dir, 'Clip.mkv'); + await ff(['-f', 'lavfi', '-i', 'testsrc=size=160x120:rate=25,format=yuv420p', '-f', 'lavfi', '-i', 'sine', '-t', '1', '-c:v', 'libx264', '-preset', 'ultrafast', '-c:a', 'aac', mkv]); + const work = await mkdtemp(join(tmpdir(), 'shade-webprep-out-')); + dirs.push(work); + const prep = await prepareForWeb(mkv, work); + expect(prep.notes).toEqual([]); + expect((await probe(prep.file)).map((s) => s.codec_name)).toEqual(['h264', 'aac']); + }, 30_000); +});