feat(media): media put --web — films browsers refuse (HEVC, AC-3, DTS) converted before sealing
ffprobe decides per stream: H.264/VP8/VP9/AV1 and AAC/MP3/Opus are copied, anything else becomes H.264 (CRF 20) / AAC with every audio track and its language kept; embedded text subtitles come out of the same ffmpeg pass as subtitle tracks; picture subtitles are reported. Output is an MP4 with the index first. Without --web, put warns when ffprobe sees streams browsers will not play. Verified: an HEVC + AC-3 5.1 MKV with embedded Norwegian/English SubRip: Chromium refuses the original (DEMUXER_ERROR_NO_SUPPORTED_STREAMS); the --web upload plays with audio decoded and the Norwegian track showing. 78 TS tests. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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 <file|dir>… --server URL [--album T] [--name N] [--mime M] [--public] [--json]
|
||||
media put <file|dir>… --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 <link> [-o file|dir|-]
|
||||
Download and decrypt a sealed file (an album: a directory)
|
||||
media ls --server URL Your uploads on that server
|
||||
|
||||
147
packages/shade-media/src/web-prep.ts
Normal file
147
packages/shade-media/src/web-prep.ts
Normal file
@@ -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<string, string> = {
|
||||
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<string> {
|
||||
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<ProbeStream[]> {
|
||||
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<string[]> {
|
||||
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<WebPrepared> {
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user