// THE INGEST (architecture, "Other wires": live media): an RTMP publisher's connection as the kernel's byte stream // (`TwinStream`), its publish ruled by the pack's dialect (`semantics/live.ts`), its media cut into segments whose bytes // go to the pack's resource blobs and whose facts go to the tree as bookkeeping (`_live`, `_live_segment`), and the // dialect told when the publish starts playing and when it ends. What a connection is (the chunk stream, the encoder's // configuration, the segment being cut) stays on the connection. The World's own writes and blobs are handed in // (`LiveWorld`), so this module opens no store. Nothing here runs at module scope beyond the empty registry. import type { TwinStream } from '../twin-fetch.ts'; import { initBlob, LIVE, LIVE_SEGMENT, recordingOf, segmentBlob, segmentsOf, type LiveReads } from './access.ts'; import { readAudioTag, readVideoTag } from './flv.ts'; import { RtmpRefusal, rtmpSession } from './rtmp.ts'; import { type Cut, LiveOverrun, Segmenter } from './segmenter.ts'; import type { LiveAdmission, LiveAudio, LiveDecl, LiveEngine, LivePublish, LiveRecording, LiveVideo } from './types.ts'; /** What the ingest reads and writes of the World, bound by the pack's fetch to its service and root. */ export type LiveWorld = LiveReads & { /** a bookkeeping subject written (or, with `deleted: true`, deleted) at the World's time */ record(type: string, id: string, fields: Record, operation: string): Promise; putBlob(key: string, bytes: Uint8Array): Promise; removeBlob(key: string): Promise; now(): string; }; export type LiveIngestOptions = { /** the World this ingest's recordings are kept in (its service and root): one publisher per stream within it */ world: string; decls: ReadonlyArray; engines: Record>; readOnly: boolean; /** the handler contract's context a hook runs over, opened at the moment it runs */ open(decl: LiveDecl, ask: LivePublish): Promise; /** runs a hook and the writes it causes as the vendor's own move, one correlation */ run(fn: () => Promise): Promise; store: LiveWorld; log?(line: string): void; }; const STREAM_ID = /^[A-Za-z0-9._-]{1,128}$/; /** Connections one ingest's listener takes at once: publishers and the connections still on their way to publishing. */ const MAX_CONNECTIONS = 32; /** The streams being published now, per World: a second publisher to one is refused, as a vendor's ingest refuses it. */ const publishing = new Map>(); export function liveIngest(options: LiveIngestOptions): TwinStream { for (const d of options.decls) if (!options.engines[d.id]) throw new Error(`the manifest declares the ingest ${d.id}, and semantics/live.ts exports no ${d.id}`); const log = options.log ?? ((line: string) => console.error(`live: ${line}`)); const store = options.store; const active = publishing.get(options.world) ?? publishing.set(options.world, new Set()).get(options.world)!; // the listener's cap (serveStream reads it): a World's publishers are its encoders, a few at once return Object.assign((sink: Parameters[0], peer: string): ReturnType => { let decl: LiveDecl | undefined; let ask: LivePublish | undefined; let stream: string | undefined; let admitted: Extract | undefined; let segmenter: Segmenter | undefined; let initIndex = -1; let priorInit: number | undefined; let started = false; let metadata: Record | undefined; let video: LiveVideo | undefined; let audio: LiveAudio | undefined; const recording = (): LiveRecording => { const row = store.rows(LIVE).find((r) => r.id === stream)!; return recordingOf(row, segmentsOf(store, stream!)); }; const hook = async (name: 'started' | 'ended'): Promise => { const engine = options.engines[decl!.id]!; const fn = engine[name]; if (!fn) return; try { await options.run(async () => fn.call(engine, await options.open(decl!, ask!), recording())); } catch (error) { log(`${decl!.id}'s ${name} for ${stream} was not written: ${String((error as Error)?.message ?? error)}`); } }; /** A closed segment kept: its init first when it opens one, its bytes, its subject; then what `retain` lets go. */ const keep = async (cut: Cut): Promise => { if (!stream || !admitted) return; if (cut.init) { video = cut.init.video; audio = cut.init.audio; // a publisher that reconnects with the encoder it had plays on under the recording's last init, its timeline // carried on, so no player meets a discontinuity; a changed configuration opens the next init const prior = initIndex < 0 && priorInit !== undefined ? await store.blob(initBlob(stream, priorInit)) : null; if (prior && sameBytes(prior, cut.init.bytes)) initIndex = priorInit!; else { initIndex = initIndex < 0 ? (priorInit ?? -1) + 1 : initIndex + 1; await store.putBlob(initBlob(stream, initIndex), cut.init.bytes); } await options.run(() => store.record(LIVE, stream!, { video: video ?? null, audio: audio ?? null, ...(metadata ? { metadata } : {}), }, 'live.configure')); } const blob = segmentBlob(stream, cut.sequence); await store.putBlob(blob, cut.bytes); await options.run(() => store.record(LIVE_SEGMENT, `${stream}:${cut.sequence}`, { stream, seq: cut.sequence, init: initIndex, start: round(cut.start), duration: round(cut.duration), size: cut.bytes.length, blob, ...(video ? { video } : {}), ...(audio ? { audio } : {}), }, 'live.segment')); if (admitted.retain !== undefined && admitted.retain > 0) { for (const old of segmentsOf(store, stream).slice(0, -admitted.retain)) { await store.removeBlob(old.blob); await options.run(() => store.record(LIVE_SEGMENT, `${stream}:${old.seq}`, { deleted: true }, 'live.segment.expire')); } } if (!started) { started = true; await hook('started'); } }; const keepAll = async (cuts: Cut[]): Promise => { for (const cut of cuts) await keep(cut); }; return rtmpSession(sink, { connect(app) { decl = options.decls.find((d) => d.app === app); return decl ? undefined : `There is no application ${app || '(none)'} here.`; }, async publish(asked) { if (!decl) return { code: 'NetStream.Publish.BadName', description: 'No application was connected.' }; if (options.readOnly) return { code: 'NetStream.Publish.Denied', description: 'This World is read-only: it records nothing.' }; const [key = '', query = ''] = splitOnce(asked.name, '?'); ask = { app: asked.app, key, query: Object.fromEntries(new URLSearchParams(query)), peer, ...(asked.tcUrl !== undefined ? { tcUrl: asked.tcUrl } : {}), ...(asked.flashVer !== undefined ? { flashVer: asked.flashVer } : {}), ...(asked.type !== undefined ? { type: asked.type } : {}), }; const engine = options.engines[decl.id]!; const ruling = await options.run(async () => engine.publish(await options.open(decl!, ask!), ask!)); if ('refused' in ruling) return { code: ruling.refused, description: ruling.description }; if (!STREAM_ID.test(ruling.stream)) throw new Error(`${decl.id}'s publish named the stream ${JSON.stringify(ruling.stream)}; a stream is 1-128 letters, digits, '.', '_' or '-'`); if (active.has(ruling.stream)) return { code: 'NetStream.Publish.BadName', description: `The stream ${ruling.stream} is already being published.` }; const named = ruling.stream; active.add(named); try { // a recording continued: its segments' numbers, its inits' and its timeline carry on from where it stood const prior = store.rows(LIVE).find((r) => r.id === named && r.deleted !== true); const kept = segmentsOf(store, named); const last = kept[kept.length - 1]; const offsetMs = last ? Math.ceil((last.start + last.duration) * 1000) : 0; const now = store.now(); await options.run(() => store.record(LIVE, named, { app: ask!.app, key: ask!.key, state: 'publishing', startedAt: typeof prior?.startedAt === 'string' ? prior.startedAt : now, endedAt: null, publishes: Number(prior?.publishes ?? 0) + 1, window: ruling.window ?? 6, segmentSeconds: ruling.segmentSeconds ?? 2, ...(ruling.retain !== undefined ? { retain: ruling.retain } : {}), }, 'live.publish')); // Every admitted publish has its own encoder and hook state. Continuation comes from the recording above, // including on a connection reused after FCUnpublish, never from the prior publish's in-memory state. initIndex = -1; priorInit = last?.init; started = false; metadata = undefined; video = undefined; audio = undefined; segmenter = new Segmenter({ targetMs: Math.max(0.5, ruling.segmentSeconds ?? 2) * 1000, offsetMs, firstSequence: last ? last.seq + 1 : 0 }); stream = named; admitted = ruling; } catch (error) { // the publish was not recorded: the stream is free again, and the publisher refused (rtmp.ts) active.delete(named); throw error; } return undefined; }, metadata(meta) { const flat = flatMetadata(meta as Record); metadata = { ...(metadata ?? {}), ...flat }; segmenter?.metadata(flat); }, async video(timestamp, payload) { if (!segmenter) return; const tag = readVideoTag(payload); if (tag.kind === 'unsupported') throw new RtmpRefusal('NetStream.Failed', `${tag.codec} video is not supported; publish H.264.`); const s = segmenter; if (tag.kind === 'config') await keepAll(s.videoConfig(tag.config)); else if (tag.kind === 'frame') await keepAll(overrun(() => s.videoFrame(timestamp, tag.key, tag.cts, tag.data))); }, async audio(timestamp, payload) { if (!segmenter) return; const tag = readAudioTag(payload); if (tag.kind === 'unsupported') throw new RtmpRefusal('NetStream.Failed', `${tag.codec} audio is not supported; publish AAC.`); const s = segmenter; if (tag.kind === 'config') await keepAll(s.audioConfig(tag.config)); else await keepAll(overrun(() => s.audioFrame(timestamp, tag.data))); }, async unpublish() { if (!stream || !segmenter) return; const s = segmenter; segmenter = undefined; // the recording always ends: what was cut is kept where it can be, and the end is written whatever the last // segment did, so no playlist is left waiting on a publisher that is gone try { await keepAll(s.flush()); } catch (error) { log(`${stream}: the last segment was not kept: ${String((error as Error)?.message ?? error)}`); } try { await options.run(() => store.record(LIVE, stream!, { state: 'ended', endedAt: store.now() }, 'live.end')); } catch (error) { log(`${stream}: its end was not written: ${String((error as Error)?.message ?? error)}`); } finally { active.delete(stream); } await hook('ended'); }, }, log); }, { maxConnections: MAX_CONNECTIONS }); } const round = (n: number): number => Math.round(n * 1000) / 1000; /** What a segmenter refuses, as RTMP's refusal of the publish (rtmp.ts ends it and closes the connection). */ function overrun(fn: () => T): T { try { return fn(); } catch (error) { throw error instanceof LiveOverrun ? new RtmpRefusal('NetStream.Failed', error.message) : error; } } /** The publisher's metadata as the World keeps it: its flat values (`onMetaData` is one level: an encoder's name, sizes, * rates), at most 64 of them, a string at most 256 characters; nested values are not kept, so nothing it sent (a * reference back to itself among them) can make the recording's row unwritable. */ function flatMetadata(meta: Record): Record { const out: Record = {}; for (const [key, value] of Object.entries(meta).slice(0, 64)) { if (typeof value === 'number' ? Number.isFinite(value) : typeof value === 'boolean') out[key.slice(0, 64)] = value as number | boolean; else if (typeof value === 'string') out[key.slice(0, 64)] = value.slice(0, 256); } return out; } function sameBytes(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; return true; } function splitOnce(s: string, sep: string): [string, string] { const at = s.indexOf(sep); return at < 0 ? [s, ''] : [s.slice(0, at), s.slice(at + 1)]; }