///
/**
* Provides a uniform API for both versions of WebRTC Insertable Streams,
* now officially called WebRTC Encoded Transform.
*
* https://w3c.github.io/webrtc-encoded-transform
*
* Because the new version requires the transform to be handled from a worker,
* and because of the negative implications of doing so on the window context,
* we only provide the option of a Worker here. However, the user can supply
* wrap / unwrap functions so that messages generated by this module can be
* multiplexed with any other communications to/from that worker. This should
* allow arbitrary worker lifecycle patterns (reusing a worker, using it to
* handle multiple transforms, sharing it for other tasks, etc.).
*
* ## Basic usage
*
* The API has two sides; {@link attachRtpScriptTransform} is called from the local
* (i.e. non worker) side, and gets passed a Worker object. This worker must have
* called {@link startRtpScriptTransformService} to receive and handle the created
* transformer. It is okay to pass a worker that hasn't yet started up, as
* long as {@link startRtpScriptTransformService} is called in the initialization.
*
* In addition to using these APIs, in case the old Encoded Transform APIs are
* used, you need to pass `encodedInsertableStreams: true` in the configuration
* object when creating the `RTCPeerConnection`.
*
* Basic example:
*
* ~~~ js
* // main.js
*
* import { attachRtpScriptTransform } from 'nal-extractor'
*
* // in this example we use a single worker for all processing for simplicity
* const rtcTransformWorker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' })
*
* const peerConnection = new RTCPeerConnection({
* // needed in case the old API is used
* encodedInsertableStreams: true,
* })
* // TODO: establish connection with other peer and negotiate content
*
* function onNegotiationDone() {
* // attach filters to every receiver:
* for (const transceiver of peerConnection.getTransceivers()) {
* const options = { mid: transceiver.mid } // custom data to send with the created transformer
* attachRtpScriptTransform(transceiver.receiver, rtcTransformWorker, { options }))
* }
* }
* ~~~
*
* ~~~ js
* // worker.js
*
* import { startRtpScriptTransformService } from 'nal-extractor'
*
* startRtpScriptTransformService((transformer, options) => {
* console.log('Received a transformer for MID:', options.mid)
* // TODO: do something more interesting
* transformer.readable.pipeTo(transformer.writable)
* })
* ~~~
*
* ### API availability
*
* You can use {@link isEncodedStreamSupported} to test for availability of either
* of the API versions supported by this method. If it succeeds, you may call
* {@link attachRtpScriptTransform}. This is not required for the service side;
* there's no problem in starting up a worker and calling
* {@link startRtpScriptTransformService} even if the API is not available.
*
* ### Considerations
*
* Note that {@link attachRtpScriptTransform} is synchronous and doesn't wait for
* acknowledgment from the worker that the transformer has been received and
* set up. This may happen much later, especially if the worker is busy or
* still starting up. If you need this, send a message from the worker service
* callback.
*
* It is the caller's responsibility to:
*
* - adequately create the worker, and handle errors in its execution
*
* - make sure the worker service is started when receiving the next
* posted message, and that exactly one instance of the service is started
*
* - make sure the worker is using the exact same version of
* this library (there are no version checks for communications)
*
* - if the worker will send or receive other messages, ensure the provided
* wrapping works correctly (doesn't conflict with other messages, and
* wrapped messages get successfully detected & unwrapped at the other end)
*
* Failure to meet any of these results in undefined behavior.
*
* ## Metadata extraction
*
* For convenience, an alternative pair of functions is provided that
* also handle:
*
* - waiting for the transformer to be fully set up
* - installing a transform stream that inspects every frame
* - sending the results of inspection (user-defined function)
* back to the main context
*
* These are {@link attachMetadataExtractor} and {@link startMetadataExtractorService}.
*
* When compared to the base APIs, {@link attachMetadataExtractor} takes an extra
* argument: a callback to be invoked for every received metadata frame.
* For {@link startMetadataExtractorService}, the callback must return an 'extraction
* function' to be invoked for each frame. The extraction function must return the
* metadata object to send back to the main frame (together with the transfer list,
* see {@link MessageData}), or `undefined` to send nothing for that frame.
*
* Unless adequate wrapping is used, this API should never be mixed with the
* basic API: a worker must not start both worker services at the same time;
* {@link attachMetadataExtractor} may only be called on a worker that called
* {@link startMetadataExtractorService}, and vice versa.
*
* @module
*/
/** Tests if either version of the Encoded Streams API is present */
export const isEncodedStreamSupported = () =>
('RTCRtpScriptTransform' in window) || // new API
('createEncodedStreams' in RTCRtpSender.prototype) // old API
// MESSAGE WRAPPING
// a system for users to multiplex our messages with their own
/** data to be sent to/from a worker, as a [payload, transferList] pair */
export type MessageData = [T, Transferable[]]
/** pair of functions to multiplex messages in a user-specified way */
export interface MessageWrapper {
/**
* wraps a message generated by this library into a user-multiplexed message.
* returns the wrapped message, and any additional items to transfer.
* */
wrap(data: unknown): MessageData
/** tests if a user-multiplied message is for this library and if so, returns the demultiplexed message */
unwrap(data: unknown): undefined | { unwrapped: unknown }
}
const identityWrapping: MessageWrapper = {
wrap: (x) => [x, []],
unwrap: (x) => ({ unwrapped: x }),
}
const getWrap = (wrapping = identityWrapping) => (
(msg: WorkerMessage, transferList: Transferable[]): MessageData => {
const [msg2, transferList2] = wrapping.wrap(msg)
return [msg2, [...transferList, ...transferList2]]
}
)
const getUnwrap = (wrapping = identityWrapping) => (
(msg: unknown, cb: (msg: WorkerMessage) => void) => {
const unwrapped = wrapping.unwrap(msg)
unwrapped && cb(unwrapped.unwrapped as WorkerMessage)
}
)
// MISSING TYPES
/**
* transformer object, with properties common to both APIs. for the old API, this
* is the object returned by `createEncodedStreams()`; for the new API, this is the
* `transformer` object passed at the event.
*/
export interface RTCRtpScriptTransformer {
readable: ReadableStream,
writable: WritableStream,
}
interface RTCTransformEvent extends Event {
transformer: RTCRtpScriptTransformer & { options: unknown },
}
// BASIC API
/**
* type of our internal messages. we won't actually validate the data,
* and just assume both local and worker are running the same version of
* the code.
*/
type WorkerMessage =
// when using the old API, this message carries the transformer
{ type: 'transformer', transformer: RTCRtpScriptTransformer, options: unknown } |
// when using the new API, this message carries just the wrapped options
{ type: 'options', options: unknown } |
// for convenience API: notifies transformer is set up
{ type: 'ready', id: number } |
// for convenience API: carries metadata frame
{ type: 'metadata', id: number, metadata: unknown }
export interface AttachRtpScriptTransformOptions {
/**
* data that will be associated to the created transform, sent to the
* worker, and supplied to the worker service callback
*/
options?: MessageData,
/** message wrapping to multiplex messages, see module description */
wrapping?: MessageWrapper,
}
/**
* Local side of the API: Creates a new script transform, and attaches it to
* the passed RTP sender or received.
*
* Make sure to pass `encodedInsertableStreams: true` in the configuration
* when creating the `RTCPeerConnection`.
*
* See module description for detailed instructions.
*/
export function attachRtpScriptTransform(
/**
* part of the RTP transceiver to attach the transform
* at (either the RTPRtcSender, or the RTPRtcReceiver).
*/
rtpProcessor: RTCRtpSender | RTCRtpReceiver,
/**
* worker where processing will take place; this worker must have the
* worker service started, and will have its callback invoked with
* the created transformer (see module description for requirements).
* the same worker can be used for multiple script transforms.
*/
worker: Worker,
/** attachment options */
options: AttachRtpScriptTransformOptions = {},
) {
const [sendOptions, sendTransfer] = options.options || [undefined, []]
const wrap = getWrap(options.wrapping)
if ('RTCRtpScriptTransform' in window) {
// new API is available; use it
const { RTCRtpScriptTransform } = window as any
const transform = new RTCRtpScriptTransform(worker, ...wrap(
{ type: 'options', options: sendOptions },
sendTransfer,
))
; (rtpProcessor as any).transform = transform
} else {
// fallback to trying the old API.
// we send transformer and options through a regular worker message
const transformer = (rtpProcessor as any).createEncodedStreams()
worker.postMessage(...wrap(
{ type: 'transformer', transformer, options: sendOptions },
[ transformer.readable, transformer.writable, ...sendTransfer ]
))
}
}
export type RtpScriptTransformServiceCallback = (
/** the newly created transformer */
transformer: RTCRtpScriptTransformer,
/** `options` data supplied to the associated {@link attachRtpScriptTransform} call */
options: O,
/**
* the raw event that caused receival of the transformer, mostly for debugging purposes.
* for the old API, this will be a regular 'message' event, for the new one, an 'rtctransform' event.
*/
event: Event,
) => R
export interface StartRtpScriptTransformServiceOptions {
/** message wrapping to multiplex messages, see module description */
wrapping?: MessageWrapper
}
/**
* Service side of the API: Starts the worker service to receive incoming
* newly created transformers.
*
* See module description for detailed instructions.
*
* @returns Callback to stop / deregister the service.
*/
export function startRtpScriptTransformService(
/** callback to invoke when a transformer is received by this worker. */
callback: RtpScriptTransformServiceCallback,
/** service options */
options: StartRtpScriptTransformServiceOptions = {},
): () => void {
const unwrap = getUnwrap(options.wrapping)
const onmessage = (ev: MessageEvent) => unwrap(ev.data, msg => {
if (msg.type === 'transformer') {
callback(msg.transformer, msg.options as O, ev)
} else {
throw new Error(`received unexpected ${msg.type} message`)
}
ev.stopImmediatePropagation()
})
const onrtctransform = (ev: RTCTransformEvent) => unwrap(ev.transformer.options, msg => {
if (msg.type === 'options') {
callback(ev.transformer, msg.options as O, ev)
} else {
throw new Error(`received unexpected ${msg.type} message`)
}
ev.stopImmediatePropagation()
})
self.addEventListener('message', onmessage)
self.addEventListener('rtctransform', onrtctransform as any)
return () => {
self.removeEventListener('message', onmessage)
self.removeEventListener('rtctransform', onrtctransform as any)
}
}
// METADATA EXTRACTION API
type WrappedOptions = { id: number, options: O }
let nextId = 0
/**
* Convenience API that builds on top of {@link attachRtpScriptTransform} for
* transforms that just need to extract metadata from frames and send it back.
*
* @returns Stop / deregister callback, wrapped in a promise that resolves
* when the transformer is fully set up.
*/
export function attachMetadataExtractor(
/**
* part of the RTP transceiver to attach the transform
* at (either the RTPRtcSender, or the RTPRtcReceiver).
*/
rtpProcessor: RTCRtpSender | RTCRtpReceiver,
/**
* worker where processing will take place; this worker must have the
* worker service started, and will have its callback invoked with
* the created transformer (see module description for requirements).
* the same worker can be used for multiple metadata extractions.
*/
worker: Worker,
/** callback to invoke whenever a new metadata frame arrives */
processMetadata: (meta: Meta) => void,
/** attachment options */
options: AttachRtpScriptTransformOptions = {},
): Promise<() => void> {
// first, attach our transform
const id = nextId++
const [sendOptions, sendTransfer] = options.options || [undefined as any, []]
const newOptions: MessageData> = [{ id, options: sendOptions }, sendTransfer]
attachRtpScriptTransform(rtpProcessor, worker, { ...options, options: newOptions })
// begin processing incoming messages
const unwrap = getUnwrap(options.wrapping)
const onmessage = (ev: MessageEvent) => unwrap(ev.data, msg => {
if (msg.type === 'ready' || msg.type === 'metadata') {
if (msg.id !== id)
return
if (msg.type === 'ready')
readyResolve()
else
processMetadata(msg.metadata as Meta)
} else {
throw new Error(`received unexpected ${msg.type} message`)
}
ev.stopImmediatePropagation()
})
worker.addEventListener('message', onmessage)
const cleanup = () => worker.removeEventListener('message', onmessage)
let readyResolve: () => void
return new Promise((resolve) => readyResolve = resolve)
.then(() => cleanup)
}
type ExtractionFunction = (frame: unknown) => MessageData | undefined
/**
* Service side of the API: Starts the worker service to receive incoming
* newly created transformers and extract metadata from processed frames.
*
* See module description for detailed instructions.
*
* @returns Callback to stop / deregister the service.
*/
export function startMetadataExtractorService(
/**
* callback to invoke when a transformer is received by this worker.
* the callback should return an 'extraction function'.
*/
callback: RtpScriptTransformServiceCallback>,
/** service options */
options: StartRtpScriptTransformServiceOptions = {},
): () => void {
const wrap = getWrap(options.wrapping)
const postMessage = (msg: WorkerMessage, transferList: Transferable[]) => {
const [data, transfer] = wrap(msg, transferList)
self.postMessage(data, { transfer })
}
return startRtpScriptTransformService((transformer, newOptions: WrappedOptions, event) => {
const { id, options } = newOptions
const extract = callback(transformer, options, event)
// for each frame, inspect using the extraction function and send back
const processChunk = (chunk: unknown) => {
const metadata = extract(chunk)
if (metadata)
postMessage({ type: 'metadata', id, metadata: metadata[0] }, metadata[1])
}
// pipe data through
const transform = new TransformStream({
start() {},
transform(chunk, controller) {
controller.enqueue(chunk)
processChunk(chunk)
},
})
transformer.readable.pipeThrough(transform).pipeTo(transformer.writable)
// confirm ready
postMessage({ type: 'ready', id }, [])
})
}