// What a handler and a screen read of the World's recordings (`ctx.live`, architecture "Other wires": live media): a // recording's facts from its bookkeeping subjects, and its playlists, init and segments answered as a media host // answers them. The recording's rows are the tree's (`_live`, `_live_segment`); the bytes are the pack's resource blobs. import { bytesResponse } from '../file-response.ts'; import { masterPlaylist, mediaPlaylist, rangedMasterPlaylist, type HlsSegment } from './hls.ts'; import type { LiveAccess, LiveAudio, LiveRecording, LiveVideo } from './types.ts'; /** The bookkeeping types a recording is kept in. */ export const LIVE = '_live'; export const LIVE_SEGMENT = '_live_segment'; /** Where a recording's bytes are kept among the pack's resource blobs. */ export const initBlob = (stream: string, init: number): string => `live/${stream}/init-${init}.mp4`; export const segmentBlob = (stream: string, seq: number): string => `live/${stream}/seg-${seq}.m4s`; type Row = Record; export type LiveReads = { rows(type: string): Row[]; blob(key: string): Promise; }; /** A recording's kept segments, in order. */ export function segmentsOf(reads: LiveReads, stream: string): Array { return reads.rows(LIVE_SEGMENT) .filter((r) => r.stream === stream && r.deleted !== true) .map((r) => ({ seq: Number(r.seq), init: Number(r.init), duration: Number(r.duration), size: Number(r.size), start: Number(r.start), blob: String(r.blob), ...(r.video && typeof r.video === 'object' ? { video: r.video as LiveVideo } : {}), ...(r.audio && typeof r.audio === 'object' ? { audio: r.audio as LiveAudio } : {}), })) .sort((a, b) => a.seq - b.seq); } export function recordingOf(row: Row, segments: ReadonlyArray): LiveRecording { return { stream: String(row.id), app: String(row.app ?? ''), key: String(row.key ?? ''), state: row.state === 'ended' ? 'ended' : 'publishing', startedAt: String(row.startedAt ?? ''), ...(typeof row.endedAt === 'string' ? { endedAt: row.endedAt } : {}), publishes: Number(row.publishes ?? 1), segments: segments.length, nextSequence: segments.reduce((next, segment) => Math.max(next, segment.seq + 1), 0), duration: Math.round(segments.reduce((n, s) => n + s.duration, 0) * 1000) / 1000, ...(row.video && typeof row.video === 'object' ? { video: row.video as LiveVideo } : {}), ...(row.audio && typeof row.audio === 'object' ? { audio: row.audio as LiveAudio } : {}), ...(row.metadata && typeof row.metadata === 'object' ? { metadata: row.metadata as Record } : {}), }; } const CORS = { 'access-control-allow-origin': '*' }; const missing = (): Response => new Response('Not Found', { status: 404, headers: { 'content-type': 'text/plain; charset=utf-8', ...CORS } }); /** `ctx.live` over a request (the one a media host answers, for its Range and its method). */ export function liveAccess(reads: LiveReads, request: Request): LiveAccess { const rowOf = (stream: string): Row | undefined => reads.rows(LIVE).find((r) => r.id === stream && r.deleted !== true); return { recording(stream) { const row = rowOf(stream); return row ? recordingOf(row, segmentsOf(reads, stream)) : undefined; }, recordings() { return reads.rows(LIVE).filter((r) => r.deleted !== true).map((r) => recordingOf(r, segmentsOf(reads, String(r.id)))); }, async serve(stream, file, options = {}) { const range = options.range; if (range !== undefined && (!range || !Number.isInteger(range.start) || range.start < 0 || (range.end !== undefined && (!Number.isInteger(range.end) || range.end < range.start)))) return missing(); const row = rowOf(stream); if (!row) return missing(); const segments = segmentsOf(reads, stream).filter((segment) => !range || (segment.seq >= range.start && (range.end === undefined || segment.seq < range.end))); const ended = range === undefined ? row.state === 'ended' : range.end !== undefined; if (file === 'index.m3u8' || file === 'master.m3u8') { // a recording with nothing playable yet has no playlist: a player waits, as for a stream not yet live if (!segments.length) return missing(); const uri = options.uri ?? ((f: string) => f); const text = file === 'index.m3u8' ? mediaPlaylist({ state: ended ? 'ended' : 'publishing', ...(typeof row.window === 'number' ? { window: row.window } : {}) }, segments, options) : range ? rangedMasterPlaylist(segments, uri('index.m3u8')) : masterPlaylist(recordingOf(row, segments), segments, uri('index.m3u8')); return new Response(request.method === 'HEAD' ? null : text, { headers: { 'content-type': 'application/vnd.apple.mpegurl', 'cache-control': ended ? 'public, max-age=3600' : 'no-cache, no-store', ...CORS } }); } const init = /^init-(\d{1,9})\.mp4$/.exec(file); const seg = /^seg-(\d{1,12})\.m4s$/.exec(file); let key: string | undefined; if (init && segments.some((s) => s.init === Number(init[1]))) key = initBlob(stream, Number(init[1])); else if (seg) key = segments.find((s) => s.seq === Number(seg[1]))?.blob; if (!key) return missing(); const bytes = await reads.blob(key); if (!bytes) return missing(); const answer = bytesResponse(request, bytes, 'video/mp4'); for (const [k, v] of Object.entries(CORS)) answer.headers.set(k, v); return answer; }, }; }