tiny-server-essentials
Version:
A good utility toolkit to unify Express v5 and Socket.IO v4 into a seamless development experience with modular helpers, server wrappers, and WebSocket tools.
296 lines • 12.6 kB
text/typescript
export default TinyMediaReceiver;
export type ReceiverTags = "video" | "audio" | HTMLVideoElement | HTMLAudioElement;
/** @typedef {'video'|'audio'|HTMLVideoElement|HTMLAudioElement} ReceiverTags */
/**
* TinyMediaReceiver is a lightweight media stream handler designed to manage
* continuous streaming of audio or video chunks into an HTMLMediaElement using MediaSource.
*
* It handles buffering, memory cleanup, and playback synchronization, allowing for dynamic
* appending of media data and auto-cleaning old buffer segments to preserve memory and prevent playback issues.
*
* This class supports custom configuration such as buffer size, cleanup interval, and buffer tolerance.
* It emits events throughout the lifecycle, such as when the media source is open, buffer is cleaned,
* time is synced, or an error occurs.
*
* Example usage:
* ```js
* const receiver = new TinyMediaReceiver({
* element: 'audio',
* mimeType: 'audio/webm;codecs=opus'
* });
* receiver.push(someAudioChunk);
* ```
*
* @class
* @beta
*/
declare class TinyMediaReceiver {
/**
* Initializes a media player for continuous streaming from received chunks.
*
* @param {Object} [options={}]
* @param {ReceiverTags} [options.element] - The tag to attach the stream.
* @param {string} [options.mimeType] - The mime type, e.g., 'audio/webm;codecs=opus'.
* @param {number} [options.maxBufferBack=10] - Maximum buffer (in seconds) back to keep in the buffer behind the current time.
* @param {number} [options.cleanupTime] - Interval time in milliseconds to perform buffer cleanup. Must be a positive number.
* @param {number} [options.bufferTolerance] - Tolerance value (in seconds) used when comparing buffer ranges. Must be a positive number.
*/
constructor({ element, mimeType, maxBufferBack, cleanupTime, bufferTolerance, }?: {
element?: ReceiverTags | undefined;
mimeType?: string | undefined;
maxBufferBack?: number | undefined;
cleanupTime?: number | undefined;
bufferTolerance?: number | undefined;
});
/**
* Event labels used internally and externally for stream control and monitoring.
* These events are emitted or listened to over socket or internal dispatch.
* @readonly
*/
readonly Events: {
/**
* Emitted when the buffer has been successfully cleaned.
* Useful for freeing up memory or managing playback state.
* @type {'BufferCleaned'}
*/
BufferCleaned: "BufferCleaned";
/**
* Emitted to synchronize the playback time, typically used
* when aligning multiple streams or correcting drift.
* @type {'SyncTime'}
*/
SyncTime: "SyncTime";
/**
* Event name emitted when the instance is destroyed.
* This constant can be used to subscribe to the destruction event of the instance.
* @type {'Destroyed'}
*/
Destroyed: "Destroyed";
/**
* Emitted when an error occurs in the stream process.
* Can be used to log or handle critical failures.
* @type {'Error'}
*/
Error: "Error";
/**
* Emitted when the MediaSource becomes open and is ready for SourceBuffer initialization.
* @type {'SourceOpen'}
*/
SourceOpen: "SourceOpen";
/**
* Emitted when a new chunk of data is being fed into the SourceBuffer queue.
* Useful for tracking data flow or debugging buffering behavior.
* @type {'FeedQueue'}
*/
FeedQueue: "FeedQueue";
};
/**
* Checks whether a given event name is defined in the Events map.
*
* This method verifies if the provided string matches one of the predefined
* event labels (e.g., "Mic", "Cam", "Screen", "MicMeter", "ScreenMeter").
*
* @param {string} name - The name of the event to check.
* @returns {boolean} Returns `true` if the event exists in the Events map, otherwise `false`.
*/
existsEvent(name: string): boolean;
/**
* Provides access to a secure internal EventEmitter for subclass use only.
*
* This method exposes a dedicated EventEmitter instance intended specifically for subclasses
* that extend the main class. It prevents subclasses from accidentally or intentionally using
* the primary class's public event system (`emit`), which could lead to unpredictable behavior
* or interference in the base class's event flow.
*
* For security and consistency, this method is designed to be accessed only once.
* Multiple accesses are blocked to avoid leaks or misuse of the internal event bus.
*
* @returns {EventEmitter} A special internal EventEmitter instance for subclass use.
* @throws {Error} If the method is called more than once.
*/
getSysEvents(): EventEmitter;
/**
* @typedef {(...args: any[]) => void} ListenerCallback
* A generic callback function used for event listeners.
*/
/**
* Sets the maximum number of listeners for the internal event emitter.
*
* @param {number} max - The maximum number of listeners allowed.
*/
setMaxListeners(max: number): void;
/**
* Emits an event with optional arguments.
* @param {string | symbol} event - The name of the event to emit.
* @param {...any} args - Arguments passed to event listeners.
* @returns {boolean} `true` if the event had listeners, `false` otherwise.
*/
emit(event: string | symbol, ...args: any[]): boolean;
/**
* Registers a listener for the specified event.
* @param {string | symbol} event - The name of the event to listen for.
* @param {ListenerCallback} listener - The callback function to invoke.
* @returns {this} The current class instance (for chaining).
*/
on(event: string | symbol, listener: (...args: any[]) => void): this;
/**
* Registers a one-time listener for the specified event.
* @param {string | symbol} event - The name of the event to listen for once.
* @param {ListenerCallback} listener - The callback function to invoke.
* @returns {this} The current class instance (for chaining).
*/
once(event: string | symbol, listener: (...args: any[]) => void): this;
/**
* Removes a listener from the specified event.
* @param {string | symbol} event - The name of the event.
* @param {ListenerCallback} listener - The listener to remove.
* @returns {this} The current class instance (for chaining).
*/
off(event: string | symbol, listener: (...args: any[]) => void): this;
/**
* Alias for `on`.
* @param {string | symbol} event - The name of the event.
* @param {ListenerCallback} listener - The callback to register.
* @returns {this} The current class instance (for chaining).
*/
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
/**
* Alias for `off`.
* @param {string | symbol} event - The name of the event.
* @param {ListenerCallback} listener - The listener to remove.
* @returns {this} The current class instance (for chaining).
*/
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
/**
* Removes all listeners for a specific event, or all events if no event is specified.
* @param {string | symbol} [event] - The name of the event. If omitted, all listeners from all events will be removed.
* @returns {this} The current class instance (for chaining).
*/
removeAllListeners(event?: string | symbol): this;
/**
* Returns the number of times the given `listener` is registered for the specified `event`.
* If no `listener` is passed, returns how many listeners are registered for the `event`.
* @param {string | symbol} eventName - The name of the event.
* @param {Function} [listener] - Optional listener function to count.
* @returns {number} Number of matching listeners.
*/
listenerCount(eventName: string | symbol, listener?: Function): number;
/**
* Adds a listener function to the **beginning** of the listeners array for the specified event.
* The listener is called every time the event is emitted.
* @param {string | symbol} eventName - The event name.
* @param {ListenerCallback} listener - The callback function.
* @returns {this} The current class instance (for chaining).
*/
prependListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Adds a **one-time** listener function to the **beginning** of the listeners array.
* The next time the event is triggered, this listener is removed and then invoked.
* @param {string | symbol} eventName - The event name.
* @param {ListenerCallback} listener - The callback function.
* @returns {this} The current class instance (for chaining).
*/
prependOnceListener(eventName: string | symbol, listener: (...args: any[]) => void): this;
/**
* Returns an array of event names for which listeners are currently registered.
* @returns {(string | symbol)[]} Array of event names.
*/
eventNames(): (string | symbol)[];
/**
* Gets the current maximum number of listeners allowed for any single event.
* @returns {number} The max listener count.
*/
getMaxListeners(): number;
/**
* Returns a copy of the listeners array for the specified event.
* @param {string | symbol} eventName - The event name.
* @returns {Function[]} An array of listener functions.
*/
listeners(eventName: string | symbol): Function[];
/**
* Returns a copy of the internal listeners array for the specified event,
* including wrapper functions like those used by `.once()`.
* @param {string | symbol} eventName - The event name.
* @returns {Function[]} An array of raw listener functions.
*/
rawListeners(eventName: string | symbol): Function[];
/**
* Handles the `sourceopen` event from the MediaSource.
* Initializes the SourceBuffer and starts feeding data into it.
* Emits an error and destroys the instance if the MIME type is not supported.
*
* @private
* @returns {void}
*/
private _onSourceOpen;
sourceBuffer: SourceBuffer | null;
/**
* Feeds queued media chunks into the SourceBuffer if it's ready.
* Emits FeedQueue event for each chunk and handles errors by emitting an Error event and destroying the instance.
*
* @private
* @returns {void}
*/
private _feedQueue;
/**
* Cleans the SourceBuffer to maintain a limited buffer size.
* Removes old buffered data that exceeds the configured max buffer back.
* Also adjusts the currentTime if it leaves the valid buffered range.
* Emits BufferCleaned and SyncTime events when appropriate.
*
* @private
* @returns {void}
*/
private _cleanupBuffer;
mimeType: string;
/** @type {BufferSource[]} */
queue: BufferSource[];
mediaSource: MediaSource;
isBufferUpdating: boolean;
isEnded: boolean;
maxBufferBack: number;
tolerance: number;
/**
* Returns the current buffer tolerance in seconds.
* @returns {number} The current tolerance value.
*/
getTolerance(): number;
/**
* Sets a new buffer tolerance value.
*
* @param {number} value - The new tolerance value in seconds. Must be a positive number.
* @throws {Error} If the value is not a positive number.
*/
setTolerance(value: number): void;
/**
* Gets the maximum buffer back.
* Only returns a positive integer.
* @returns {number}
*/
getMaxBufferBack(): number;
/**
* Sets the maximum buffer back.
* Value must be a positive integer.
* @param {number} value
*/
setMaxBufferBack(value: number): void;
/** @returns {HTMLMediaElement} */
getElement(): HTMLMediaElement;
/**
* Pushes a new chunk of media data to the playback buffer.
* @param {ArrayBuffer} buffer
*/
pushChunk(buffer: ArrayBuffer): Promise<any> | undefined;
/**
* Alias for `pushChunk`.
* @param {ArrayBuffer} buffer
*/
push(buffer: ArrayBuffer): Promise<any> | undefined;
/**
* Finalizes the media stream and releases resources.
*/
destroy(): void;
#private;
}
import { EventEmitter } from 'events';
//# sourceMappingURL=TinyMediaReceiver.d.mts.map