/*! * Copyright (c) 2026-present, Vanilagy and contributors * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ import { isMainThread } from 'node:worker_threads'; import { VideoSamplePixelFormat, MediaCodec } from 'mediabunny'; import * as NodeAv from 'node-av'; import { IOContext } from 'node-av'; import { AVIO_FLAG_WRITE } from 'node-av/constants'; import { _serverOptions } from './index'; /** * Satisfies a listening socket's parked accept by dialling it, which is the only way to end one: a native * accept cannot be interrupted, so closing the context under it aborts the process. See FORK.md. * * @internal */ export const wakePendingAccept = async (url: string) => { const target = new URL(url); target.search = ''; if (target.hostname === '0.0.0.0' || target.hostname === '::' || target.hostname === '[::]') { target.hostname = '127.0.0.1'; } const peer = new IOContext(); try { await peer.open2(target.toString(), AVIO_FLAG_WRITE); } catch { // The accept may have already failed or been satisfied; either way there is nothing to wake. } await peer.closep().catch(() => {}); }; /** * The option checks every source and target in this package opens with, so their messages stay the same. * * @internal */ export const checkUrlAndOptions = (url: unknown, options: unknown): void => { if (typeof url !== 'string') { throw new TypeError('url must be a string.'); } if (!options || typeof options !== 'object') { throw new TypeError('options must be an object.'); } }; /** * Query parameters whose value is a shared secret. `passphrase` is SRT's and `secret` is RIST's; both * can only be given to FFmpeg through the URL, since `avio_open2` takes no options dictionary and a * protocol's private options do not exist until it has resolved the URL. */ const SECRET_QUERY_PARAMS = ['passphrase', 'secret']; /** * Replaces the secrets in a URL with `[redacted]`, for a message that is about to be thrown or logged. * Also drops userinfo, which is where an http(s) URL carries credentials. * * Takes the string rather than a `URL` so it can be used on input that failed to parse, and falls back * to a blunt substitution for exactly that case. * * @internal */ export const redactUrl = (url: string): string => { try { const parsed = new URL(url); for (const name of SECRET_QUERY_PARAMS) { if (parsed.searchParams.has(name)) { parsed.searchParams.set(name, '[redacted]'); } } if (parsed.password) { parsed.password = '[redacted]'; } return parsed.toString(); } catch { return redactSecretsInText(url); } }; /** * Redacts the same secrets in arbitrary text, for a line that holds a URL somewhere inside it — which * is the shape of FFmpeg's own log output. * * @internal */ export const redactSecretsInText = (text: string): string => text.replace( new RegExp(`([?&](?:${SECRET_QUERY_PARAMS.join('|')})=)[^&\\s"']*`, 'gi'), '$1[redacted]', ); let logRedactionInstalled = false; /** * Takes FFmpeg's log callback so the URL it prints on a failed open has its secrets removed. * * FFmpeg logs `Connection to failed` at `AV_LOG_ERROR` from C, and the URL is the only way to give * libsrt a passphrase - `avio_open2` takes no options dictionary, and a protocol's private options do * not exist until it has resolved the URL. Taking the callback is therefore the only place the secret * can be removed, and it replaces FFmpeg's own printing, so the line is written on unchanged otherwise. * * **Called from every class that can carry a secret, not only from `registerMediabunnyServer`.** A host * that constructs an `SrtTarget` or a `NetworkSource` without registering the server would otherwise get * the unredacted line, which is how this was found. * * @internal */ export const installSecretRedactingLog = (): void => { // One process-wide slot: a callback left behind by an exited worker aborts the process if (logRedactionInstalled || !isMainThread) { return; } logRedactionInstalled = true; NodeAv.Log.setCallback((_level: number, message: string) => { process.stderr.write(redactSecretsInText(message)); }); }; /** * Reports a failed `open2` and closes the context it failed on. Always throws. * * @internal */ export const throwFailedOpen = async ( context: IOContext, label: string, url: string, ret: number, encrypted: boolean, ): Promise => { // Without this the native handle is left for the GC to finalize whenever it likes, and these failures // come in bursts because a caller retries await context.closep().catch(() => {}); throw new Error( `${label}: could not open ${redactUrl(url)} (AVERROR ${ret}).` // SRT reports a refused connection, an unreachable host and a rejected passphrase with the same // AVERROR - measured -5 or -60 for all of them - so the passphrase is named rather than diagnosed + (encrypted ? ' SRT does not distinguish a rejected passphrase from any other refusal, so check that both' + ' ends agree on the passphrase and key length.' : ''), ); }; /** @internal */ export const __resetSecretRedactingLogForTests = (): void => { logRedactionInstalled = false; NodeAv.Log.setCallback(null); }; /** SRT key lengths in bits, as the options take them; libsrt's `pbkeylen` is the byte count. */ const KEY_LENGTHS_IN_BITS = [128, 192, 256]; /** * The passphrase checks every SRT-speaking class in this package opens with. SRT itself requires 10 to * 79 characters and refuses the connection otherwise, which it reports no differently from any other * failure - so the bound is enforced here, where it can still be attributed. * * @internal */ export const checkPassphrase = ( options: { passphrase?: unknown; keyLength?: unknown }, namespace = 'options', ): void => { if ( options.passphrase !== undefined && (typeof options.passphrase !== 'string' || options.passphrase.length < 10 || options.passphrase.length > 79) ) { throw new TypeError(`${namespace}.passphrase, when provided, must be a string of 10 to 79 characters.`); } if (options.keyLength !== undefined && !KEY_LENGTHS_IN_BITS.includes(options.keyLength as number)) { throw new TypeError(`${namespace}.keyLength, when provided, must be 128, 192 or 256.`); } }; /** @internal */ export const positive = (value: number | undefined, name: string): void => { if (value !== undefined && (!Number.isFinite(value) || value <= 0)) { throw new TypeError(`options.${name}, when provided, must be a positive number.`); } }; export const CODEC_TO_CODEC_ID: Partial> = { avc: NodeAv.AV_CODEC_ID_H264, mpeg2: NodeAv.AV_CODEC_ID_MPEG2VIDEO, hevc: NodeAv.AV_CODEC_ID_HEVC, vp8: NodeAv.AV_CODEC_ID_VP8, vp9: NodeAv.AV_CODEC_ID_VP9, av1: NodeAv.AV_CODEC_ID_AV1, prores: NodeAv.AV_CODEC_ID_PRORES, qtrle: NodeAv.AV_CODEC_ID_QTRLE, png: NodeAv.AV_CODEC_ID_PNG, aac: NodeAv.AV_CODEC_ID_AAC, opus: NodeAv.AV_CODEC_ID_OPUS, mp3: NodeAv.AV_CODEC_ID_MP3, mp2: NodeAv.AV_CODEC_ID_MP2, vorbis: NodeAv.AV_CODEC_ID_VORBIS, flac: NodeAv.AV_CODEC_ID_FLAC, ac3: NodeAv.AV_CODEC_ID_AC3, eac3: NodeAv.AV_CODEC_ID_EAC3, dts: NodeAv.AV_CODEC_ID_DTS, truehd: NodeAv.AV_CODEC_ID_TRUEHD, }; let cachedHardwareContext: NodeAv.HardwareContext | null | undefined = undefined; export const getHardwareContext = (): NodeAv.HardwareContext | null => { if (_serverOptions.hardwareContext !== undefined && typeof _serverOptions.hardwareContext !== 'function') { // Return the user-provided one return _serverOptions.hardwareContext; } if (cachedHardwareContext === undefined) { cachedHardwareContext = NodeAv.HardwareContext.auto(); } return cachedHardwareContext; }; const validateHwContext = (hw: NodeAv.HardwareContext | null) => { if (hw !== null && !(hw instanceof NodeAv.HardwareContext)) { throw new TypeError( 'When serverOptions.hardwareContext is a function, it must return or resolve to a' + ' NodeAv.HardwareContext or null.', ); } }; const hardwareDecoderCodecCache = new Map(); export const getHardwareDecoderCodec = async (codecId: NodeAv.AVCodecID): Promise => { if (typeof _serverOptions.hardwareContext === 'function') { const hw = await _serverOptions.hardwareContext(codecId); validateHwContext(hw); return hw?.getDecoderCodec(codecId) ?? null; } if (!hardwareDecoderCodecCache.has(codecId)) { const hw = getHardwareContext(); hardwareDecoderCodecCache.set(codecId, hw?.getDecoderCodec(codecId) ?? null); } return hardwareDecoderCodecCache.get(codecId)!; }; const hardwareEncoderCodecCache = new Map(); export const getHardwareEncoderCodec = async (codecId: NodeAv.AVCodecID): Promise => { if (typeof _serverOptions.hardwareContext === 'function') { const hw = await _serverOptions.hardwareContext(codecId); validateHwContext(hw); return hw?.getEncoderCodec(codecId) ?? null; } if (!hardwareEncoderCodecCache.has(codecId)) { const hw = getHardwareContext(); hardwareEncoderCodecCache.set(codecId, hw?.getEncoderCodec(codecId) ?? null); } return hardwareEncoderCodecCache.get(codecId)!; }; export const mapColorPrimaries = (primaries: string) => { switch (primaries) { case 'bt709': return NodeAv.AVCOL_PRI_BT709; case 'bt470bg': return NodeAv.AVCOL_PRI_BT470BG; case 'smpte170m': return NodeAv.AVCOL_PRI_SMPTE170M; case 'bt2020': return NodeAv.AVCOL_PRI_BT2020; case 'smpte432': return NodeAv.AVCOL_PRI_SMPTE432; } return null; }; export const unmapColorPrimaries = (primaries: number) => { switch (primaries) { case NodeAv.AVCOL_PRI_BT709: return 'bt709'; case NodeAv.AVCOL_PRI_BT470BG: return 'bt470bg'; case NodeAv.AVCOL_PRI_SMPTE170M: return 'smpte170m'; case NodeAv.AVCOL_PRI_BT2020: return 'bt2020'; case NodeAv.AVCOL_PRI_SMPTE432: return 'smpte432'; } return null; }; export const mapTransferCharacteristics = (transfer: string) => { switch (transfer) { case 'bt709': return NodeAv.AVCOL_TRC_BT709; case 'smpte170m': return NodeAv.AVCOL_TRC_SMPTE170M; case 'iec61966-2-1': return NodeAv.AVCOL_TRC_IEC61966_2_1; case 'linear': return NodeAv.AVCOL_TRC_LINEAR; case 'pq': return NodeAv.AVCOL_TRC_SMPTE2084; case 'hlg': return NodeAv.AVCOL_TRC_ARIB_STD_B67; } return null; }; export const unmapTransferCharacteristics = (transfer: number) => { switch (transfer) { case NodeAv.AVCOL_TRC_BT709: return 'bt709'; case NodeAv.AVCOL_TRC_SMPTE170M: return 'smpte170m'; case NodeAv.AVCOL_TRC_IEC61966_2_1: return 'iec61966-2-1'; case NodeAv.AVCOL_TRC_LINEAR: return 'linear'; case NodeAv.AVCOL_TRC_SMPTE2084: return 'pq'; case NodeAv.AVCOL_TRC_ARIB_STD_B67: return 'hlg'; } return null; }; export const mapMatrixCoefficients = (matrix: string) => { switch (matrix) { case 'rgb': return NodeAv.AVCOL_SPC_RGB; case 'bt709': return NodeAv.AVCOL_SPC_BT709; case 'bt470bg': return NodeAv.AVCOL_SPC_BT470BG; case 'smpte170m': return NodeAv.AVCOL_SPC_SMPTE170M; case 'bt2020-ncl': return NodeAv.AVCOL_SPC_BT2020_NCL; } return null; }; export const unmapMatrixCoefficients = (matrix: number) => { switch (matrix) { case NodeAv.AVCOL_SPC_RGB: return 'rgb'; case NodeAv.AVCOL_SPC_BT709: return 'bt709'; case NodeAv.AVCOL_SPC_BT470BG: return 'bt470bg'; case NodeAv.AVCOL_SPC_SMPTE170M: return 'smpte170m'; case NodeAv.AVCOL_SPC_BT2020_NCL: return 'bt2020-ncl'; } return null; }; export const isRgbPixelFormat = (pixelFormat: NodeAv.AVPixelFormat) => { // NodeAV doesn't expose av_pix_fmt_desc_get, so go by name const name = NodeAv.avGetPixFmtName(pixelFormat) ?? ''; return /rgb|bgr|gbr/.test(name); }; export const toPixelFormat = (ffmpegPixelFormat: NodeAv.AVPixelFormat): VideoSamplePixelFormat | null => { switch (ffmpegPixelFormat) { case NodeAv.AV_PIX_FMT_YUV420P: return 'I420'; // "deprecated in favor of AV_PIX_FMT_YUV420P and setting color_range" case NodeAv.AV_PIX_FMT_YUVJ420P: return 'I420'; case NodeAv.AV_PIX_FMT_YUV420P10LE: return 'I420P10'; case NodeAv.AV_PIX_FMT_YUV420P12LE: return 'I420P12'; case NodeAv.AV_PIX_FMT_YUVA420P: return 'I420A'; case NodeAv.AV_PIX_FMT_YUVA420P10LE: return 'I420AP10'; case NodeAv.AV_PIX_FMT_YUV422P: return 'I422'; // "deprecated in favor of AV_PIX_FMT_YUV422P and setting color_range" case NodeAv.AV_PIX_FMT_YUVJ422P: return 'I422'; case NodeAv.AV_PIX_FMT_YUV422P10LE: return 'I422P10'; case NodeAv.AV_PIX_FMT_YUV422P12LE: return 'I422P12'; case NodeAv.AV_PIX_FMT_YUVA422P: return 'I422A'; case NodeAv.AV_PIX_FMT_YUVA422P10LE: return 'I422AP10'; case NodeAv.AV_PIX_FMT_YUVA422P12LE: return 'I422AP12'; case NodeAv.AV_PIX_FMT_YUV444P: return 'I444'; // "deprecated in favor of AV_PIX_FMT_YUV444P and setting color_range" case NodeAv.AV_PIX_FMT_YUVJ444P: return 'I444'; case NodeAv.AV_PIX_FMT_YUV444P10LE: return 'I444P10'; case NodeAv.AV_PIX_FMT_YUV444P12LE: return 'I444P12'; case NodeAv.AV_PIX_FMT_YUVA444P: return 'I444A'; case NodeAv.AV_PIX_FMT_YUVA444P10LE: return 'I444AP10'; case NodeAv.AV_PIX_FMT_YUVA444P12LE: return 'I444AP12'; case NodeAv.AV_PIX_FMT_NV12: return 'NV12'; case NodeAv.AV_PIX_FMT_RGBA: return 'RGBA'; case NodeAv.AV_PIX_FMT_RGB0: return 'RGBX'; case NodeAv.AV_PIX_FMT_BGRA: return 'BGRA'; case NodeAv.AV_PIX_FMT_BGR0: return 'BGRX'; default: return null; } }; export const fromPixelFormat = (pixelFormat: VideoSamplePixelFormat) => { switch (pixelFormat) { case 'I420': return NodeAv.AV_PIX_FMT_YUV420P; case 'I420P10': return NodeAv.AV_PIX_FMT_YUV420P10LE; case 'I420P12': return NodeAv.AV_PIX_FMT_YUV420P12LE; case 'I420A': return NodeAv.AV_PIX_FMT_YUVA420P; case 'I420AP10': return NodeAv.AV_PIX_FMT_YUVA420P10LE; case 'I422': return NodeAv.AV_PIX_FMT_YUV422P; case 'I422P10': return NodeAv.AV_PIX_FMT_YUV422P10LE; case 'I422P12': return NodeAv.AV_PIX_FMT_YUV422P12LE; case 'I422A': return NodeAv.AV_PIX_FMT_YUVA422P; case 'I422AP10': return NodeAv.AV_PIX_FMT_YUVA422P10LE; case 'I422AP12': return NodeAv.AV_PIX_FMT_YUVA422P12LE; case 'I444': return NodeAv.AV_PIX_FMT_YUV444P; case 'I444P10': return NodeAv.AV_PIX_FMT_YUV444P10LE; case 'I444P12': return NodeAv.AV_PIX_FMT_YUV444P12LE; case 'I444A': return NodeAv.AV_PIX_FMT_YUVA444P; case 'I444AP10': return NodeAv.AV_PIX_FMT_YUVA444P10LE; case 'I444AP12': return NodeAv.AV_PIX_FMT_YUVA444P12LE; case 'NV12': return NodeAv.AV_PIX_FMT_NV12; case 'RGBA': return NodeAv.AV_PIX_FMT_RGBA; case 'RGBX': return NodeAv.AV_PIX_FMT_RGB0; case 'BGRA': return NodeAv.AV_PIX_FMT_BGRA; case 'BGRX': return NodeAv.AV_PIX_FMT_BGR0; default: return NodeAv.AV_PIX_FMT_NONE; } }; export const toAudioSampleFormat = (ffmpegSampleFormat: NodeAv.AVSampleFormat): AudioSampleFormat | null => { switch (ffmpegSampleFormat) { case NodeAv.AV_SAMPLE_FMT_U8: return 'u8'; case NodeAv.AV_SAMPLE_FMT_S16: return 's16'; case NodeAv.AV_SAMPLE_FMT_S32: return 's32'; case NodeAv.AV_SAMPLE_FMT_FLT: return 'f32'; case NodeAv.AV_SAMPLE_FMT_U8P: return 'u8-planar'; case NodeAv.AV_SAMPLE_FMT_S16P: return 's16-planar'; case NodeAv.AV_SAMPLE_FMT_S32P: return 's32-planar'; case NodeAv.AV_SAMPLE_FMT_FLTP: return 'f32-planar'; default: return null; } }; export const fromAudioSampleFormat = (sampleFormat: AudioSampleFormat): NodeAv.AVSampleFormat => { switch (sampleFormat) { case 'u8': return NodeAv.AV_SAMPLE_FMT_U8; case 's16': return NodeAv.AV_SAMPLE_FMT_S16; case 's32': return NodeAv.AV_SAMPLE_FMT_S32; case 'f32': return NodeAv.AV_SAMPLE_FMT_FLT; case 'u8-planar': return NodeAv.AV_SAMPLE_FMT_U8P; case 's16-planar': return NodeAv.AV_SAMPLE_FMT_S16P; case 's32-planar': return NodeAv.AV_SAMPLE_FMT_S32P; case 'f32-planar': return NodeAv.AV_SAMPLE_FMT_FLTP; default: return NodeAv.AV_SAMPLE_FMT_NONE; } }; export const getChannelLayout = (numChannels: number): NodeAv.ChannelLayout => { switch (numChannels) { case 1: return NodeAv.AV_CHANNEL_LAYOUT_MONO; case 2: return NodeAv.AV_CHANNEL_LAYOUT_STEREO; case 4: return NodeAv.AV_CHANNEL_LAYOUT_QUAD; case 6: return NodeAv.AV_CHANNEL_LAYOUT_5POINT1_BACK; case 8: return NodeAv.AV_CHANNEL_LAYOUT_7POINT1; default: return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n }; } }; /** FL + FR + SL + SR, which libav has no constant for. */ const QUAD_SIDE_MASK = 0x603n; /** * DTS insists on the side-based surround layouts and rejects the back-based ones that {@link getChannelLayout} * hands out, so it gets its own mapping. */ export const getDtsChannelLayout = (numChannels: number): NodeAv.ChannelLayout => { switch (numChannels) { case 1: return NodeAv.AV_CHANNEL_LAYOUT_MONO; case 2: return NodeAv.AV_CHANNEL_LAYOUT_STEREO; case 4: return { nbChannels: 4, order: NodeAv.AV_CHANNEL_ORDER_NATIVE, mask: QUAD_SIDE_MASK }; case 5: return NodeAv.AV_CHANNEL_LAYOUT_5POINT0; case 6: return NodeAv.AV_CHANNEL_LAYOUT_5POINT1; default: return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n }; } }; /** The TrueHD encoder only accepts a fixed set of layouts, so it gets its own mapping. */ export const getTrueHdChannelLayout = (numChannels: number): NodeAv.ChannelLayout => { switch (numChannels) { case 1: return NodeAv.AV_CHANNEL_LAYOUT_MONO; case 2: return NodeAv.AV_CHANNEL_LAYOUT_STEREO; case 3: return NodeAv.AV_CHANNEL_LAYOUT_SURROUND; case 4: return NodeAv.AV_CHANNEL_LAYOUT_4POINT0; case 5: return NodeAv.AV_CHANNEL_LAYOUT_5POINT0; case 6: return NodeAv.AV_CHANNEL_LAYOUT_5POINT1; default: return { nbChannels: numChannels, order: NodeAv.AV_CHANNEL_ORDER_UNSPEC, mask: 0n }; } }; export const DEFAULT_MAX_QUEUE_BYTES = 2 * 1024 * 1024;