bởi Jaxon C.

A powerful SFU (Selective Forwarding Unit) for Node.js and Rust that handles WebRTC and plain RTP media routing with simulcast, SVC, congestion control, and DataChannel support. Ideal for building group video chat, broadcasting, and real-time streaming applications.
This block provides the complete Node.js TypeScript source for mediasoup v3, a Selective Forwarding Unit (SFU) that handles WebRTC and plain RTP media routing in server-side applications. It manages Workers, Routers, Transports, Producers, and Consumers to build scalable real-time video/audio infrastructure. The typical buyer is a backend engineer building group video conferencing, live broadcasting, or RTP streaming systems.
index.ts - Main entry point; exports createWorker, version, observer, getSupportedRtpCapabilities, etc.Worker.ts / WorkerTypes.ts - Spawns and manages the mediasoup-worker C++ subprocessRouter.ts / RouterTypes.ts - Media routing entity; creates Transports and RTP observersTransport.ts / TransportTypes.ts - Base transport logic shared by all transport typesWebRtcTransport.ts / WebRtcTransportTypes.ts - ICE+DTLS transport for browser WebRTC peersPlainTransport.ts / PlainTransportTypes.ts - Plain RTP/UDP transport for FFmpeg, GStreamer, etc.PipeTransport.ts / PipeTransportTypes.ts - Internal transport for piping media between RoutersDirectTransport.ts / DirectTransportTypes.ts - In-process transport for Node.js data messagesProducer.ts / ProducerTypes.ts - Incoming media/data stream from a peerConsumer.ts / ConsumerTypes.ts - Outgoing media stream forwarded to a peerDataProducer.ts / DataProducerTypes.ts - Incoming SCTP/DataChannel data streamDataConsumer.ts / DataConsumerTypes.ts - Outgoing SCTP/DataChannel data streamActiveSpeakerObserver.ts / ActiveSpeakerObserverTypes.ts - Detects the dominant speakerAudioLevelObserver.ts / AudioLevelObserverTypes.ts - Reports per-producer audio levelsRtpObserver.ts / RtpObserverTypes.ts - Base class for RTP observer implementationsChannel.ts - Internal IPC channel between Node.js and the worker subprocessKhởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This TypeScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Quy trình avcp-2026-08-04.1 · SHA-256 4184191f5d0a80a4…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
ortc.ts - ORTC utilities: capability validation, RTP parameter matching, codec negotiationerrors.ts - Custom error classes: UnsupportedError, InvalidStateErrorutils.ts - General utility functions used internallyfbsUtils.ts - FlatBuffers serialization helpersrtpParametersTypes.ts - RTP capability and parameter type definitionsrtpParametersFbsUtils.ts - FlatBuffers parsing for RTP parameterssctpParametersTypes.ts / sctpParametersFbsUtils.ts - SCTP parameter types and parsingsrtpParametersTypes.ts / srtpParametersFbsUtils.ts - SRTP parameter types and parsingrtpStreamStatsTypes.ts / rtpStreamStatsFbsUtils.ts - RTP stream statistics types and parsingscalabilityModesTypes.ts / scalabilityModesUtils.ts - SVC/simulcast scalability mode parsingsupportedRtpCapabilities.ts - Built-in supported codec capabilitiesenhancedEvents.ts - Typed EnhancedEventEmitter base classLogger.ts - Internal namespaced debug loggertypes.ts / indexTypes.ts - Shared AppData and top-level observer typesextras.ts - Additional exported utility typesindex.ts - Re-exports all public API surfacenpm install user@example.com
# If installing from source rather than npm:
npm install debug flatbuffers h264-profile-level-id node-fetch supports-color tar
No additional native build steps are required when using the prebuilt npm package — mediasoup downloads prebuilt worker binaries automatically. If building from source, a C++ toolchain (gcc/clang, Python 3, make) is required and npm install will compile the worker binary.
source/ directory into your project, e.g. src/mediasoup/.tsconfig.json includes the source directory and has these compiler options:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"resolveJsonModule": true
},
"include": ["src/**/*"]
}
export MEDIASOUP_WORKER_BIN=/path/to/custom/mediasoup-worker
import * as mediasoup from './mediasoup/index';
createWorkerimport { createWorker } from './mediasoup/index';
import type { WorkerSettings } from './mediasoup/WorkerTypes';
const worker = await createWorker<WorkerSettings>({
logLevel: 'warn',
rtcMinPort: 10000,
rtcMaxPort: 10100,
});
Creates and starts a mediasoup-worker subprocess. Returns a Worker instance. Call once per CPU core for parallelism; monitor the 'died' event to detect crashes.
observerimport { observer } from './mediasoup/index';
observer.on('newworker', (worker) => {
console.log('new worker created, pid:', worker.pid);
});
A global EnhancedEventEmitter that emits 'newworker' whenever a Worker is created. Use it for centralized lifecycle monitoring across all workers in the process.
getSupportedRtpCapabilitiesimport { getSupportedRtpCapabilities } from './mediasoup/index';
import type { RouterRtpCapabilities } from './mediasoup/rtpParametersTypes';
const caps: RouterRtpCapabilities = getSupportedRtpCapabilities();
Returns the RTP capabilities built into this mediasoup build. Pass these (or a subset) to router.createRouter() as mediaCodecs. Use to discover which codecs are available before configuring a Router.
parseScalabilityModeimport { parseScalabilityMode } from './mediasoup/scalabilityModesUtils';
const mode = parseScalabilityMode('L3T3_KEY');
// { spatialLayers: 3, temporalLayers: 3, ksvc: true }
Parses a scalability mode string (e.g., from SDP) into structured layer counts. Use when inspecting or validating SVC encoding parameters on Producers.
Create a Worker, Router, two WebRTC Transports (send and receive), a Producer, and a Consumer. This is the core pattern for a video call participant.
import * as mediasoup from './mediasoup/index';
async function main() {
const worker = await mediasoup.createWorker({
logLevel: 'warn',
rtcMinPort: 40000,
rtcMaxPort: 49999,
});
worker.on('died', (error) => {
console.error('mediasoup worker died', error);
process.exit(1);
});
const router = await worker.createRouter({
mediaCodecs: [
{
kind: 'audio',
mimeType: 'audio/opus',
clockRate: 48000,
channels: 2,
},
{
kind: 'video',
mimeType: 'video/VP8',
clockRate: 90000,
},
],
});
// Transport for the sending peer
const sendTransport = await router.createWebRtcTransport({
listenInfos: [{ protocol: 'udp', ip: '0.0.0.0', announcedAddress: '1.2.3.4' }],
enableUdp: true,
enableTcp: true,
});
// Transport for the receiving peer
const recvTransport = await router.createWebRtcTransport({
listenInfos: [{ protocol: 'udp', ip: '0.0.0.0', announcedAddress: '1.2.3.4' }],
enableUdp: true,
enableTcp: true,
});
console.log('send transport id:', sendTransport.id);
console.log('recv transport id:', recvTransport.id);
}
main().catch(console.error);
Attach an AudioLevelObserver to a Router to detect who is speaking. Emit the active speaker to your signaling layer.
import * as mediasoup from './mediasoup/index';
async function setupAudioLevelObserver(
router: mediasoup.types.Router
) {
const audioLevelObserver = await router.createAudioLevelObserver({
maxEntries: 1,
threshold: -80,
interval: 800,
});
audioLevelObserver.on('volumes', (volumes) => {
for (const { producer, volume } of volumes) {
console.log(`producer ${producer.id} volume: ${volume} dBvo`);
}
});
audioLevelObserver.on('silence', () => {
console.log('silence detected');
});
return audioLevelObserver;
}
Scale across CPU cores by piping a Producer from one Router to another using pipeToRouter.
import * as mediasoup from './mediasoup/index';
async function scaleAcrossWorkers() {
const worker1 = await mediasoup.createWorker({ rtcMinPort: 40000, rtcMaxPort: 41000 });
const worker2 = await mediasoup.createWorker({ rtcMinPort: 41001, rtcMaxPort: 42000 });
const mediaCodecs = [
{ kind: 'video' as const, mimeType: 'video/VP8', clockRate: 90000 },
];
const router1 = await worker1.createRouter({ mediaCodecs });
const router2 = await worker2.createRouter({ mediaCodecs });
// Assume producerOnRouter1 already exists
// const { pipeProducer } = await router1.pipeToRouter({
// producerId: producerOnRouter1.id,
// router: router2,
// });
// Now create consumers from pipeProducer on router2
console.log('router1 id:', router1.id);
console.log('router2 id:', router2.id);
await worker1.close();
await worker2.close();
}
scaleAcrossWorkers().catch(console.error);
index.ts: Public entry point; re-exports createWorker, version, observer, getSupportedRtpCapabilities, parseScalabilityMode, and all types.Worker.ts / WorkerTypes.ts: Spawns the C++ worker subprocess via WorkerImpl; exposes createRouter and resource management.Router.ts / RouterTypes.ts: Central routing entity; creates all transport types and RTP observers; implements pipeToRouter.Transport.ts / TransportTypes.ts: Abstract base containing produce, consume, produceData, consumeData shared by all transport subtypes.WebRtcTransport.ts / WebRtcTransportTypes.ts: Handles ICE negotiation, DTLS, and SRTP for browser peers.PlainTransport.ts / PlainTransportTypes.ts: Plain UDP/TCP RTP transport for non-WebRTC tools.PipeTransport.ts / PipeTransportTypes.ts: Low-overhead internal transport for Router-to-Router media piping.DirectTransport.ts / DirectTransportTypes.ts: In-process data-only transport for Node.js DataConsumer/DataProducer.Producer.ts / ProducerTypes.ts: Represents an inbound media stream; tracks RTP parameters and stats.Consumer.ts / ConsumerTypes.ts: Represents an outbound media stream; supports simulcast layer selection.DataProducer.ts / DataProducerTypes.ts: Inbound SCTP data stream abstraction.DataConsumer.ts / DataConsumerTypes.ts: Outbound SCTP data stream abstraction.ActiveSpeakerObserver.ts / ActiveSpeakerObserverTypes.ts: Emits 'dominantspeaker' events based on audio activity.AudioLevelObserver.ts / AudioLevelObserverTypes.ts: Periodically emits 'volumes' with dBvo levels per Producer.RtpObserver.ts / RtpObserverTypes.ts: Shared base class for observer add/remove producer lifecycle.Channel.ts: Internal FlatBuffers-based IPC channel; not used directly by application code.ortc.ts: RTP capability matching, codec validation, and encoding mapping utilities used by Router and Transport.errors.ts: Exports UnsupportedError and InvalidStateError for error handling in application code.enhancedEvents.ts: Typed EnhancedEventEmitter providing type-safe .on(), .off(), .emit().Logger.ts: Namespaced debug logger wrapping the debug npm package.rtpParametersTypes.ts: Core type definitions for RtpCapabilities, RtpParameters, MediaKind, etc.sctpParametersTypes.ts: SctpCapabilities and SctpStreamParameters type definitions.srtpParametersTypes.ts: SrtpParameters and SrtpCryptoSuite type definitions.scalabilityModesUtils.ts: Exports parseScalabilityMode for SVC string parsing.supportedRtpCapabilities.ts: Static object listing all codecs and header extensions mediasoup supports.utils.ts: Internal clone, generate ID, and other utility functions.fbsUtils.ts / rtpParametersFbsUtils.ts / rtpStreamStatsFbsUtils.ts / sctpParametersFbsUtils.ts / srtpParametersFbsUtils.ts: FlatBuffers serialization/deserialization helpers for worker IPC.types.ts / indexTypes.ts / extras.ts: Aggregate type re-exports for the public API surface.MEDIASOUP_WORKER_BIN env var or ensure the npm postinstall script completed; run npm rebuild mediasoup to recompile.no available UDP port: Widen rtcMinPort/rtcMaxPort in createWorker options and open those ports in your firewall/security group.announcedAddress not set in Docker/cloud: Always set announcedAddress in listenInfos to the public IP; the default 0.0.0.0 is unreachable by remote peers."type": "module", use createRequire or set "moduleResolution": "node16" with "module": "Node16" in tsconfig.json.Consumer created before transport connected: Call transport.connect() with DTLS parameters before producing/consuming, otherwise media will not flow and the consumer will remain in transportclose state.createWorker does not auto-balance; maintain a worker pool and assign Routers to workers in round-robin or by CPU load.I have the mediasoup Node.js SFU library source in `source/` (mediasoup@3.19.22, Node.js TypeScript).
I also have `USAGE.md` which documents the real API, imports, and working examples.
My project is a Node.js TypeScript backend using Express. I need you to:
1. Read `USAGE.md` fully before writing any code.
2. Install all required dependencies listed in the "Required dependencies" section.
3. Add the `source/` directory to my project under `src/mediasoup/` and update `tsconfig.json` as described in "Project setup".
4. Create `src/mediaServer.ts` that:
- Creates a mediasoup Worker with a port range of 40000-49999
- Creates a Router with Opus audio and VP8 video codecs
- Exports a function `createWebRtcTransportPair()` that creates send and receive WebRtcTransports
- Sets up an AudioLevelObserver and logs active speaker events
5. Wire `src/mediaServer.ts` into my existing `src/server.ts` Express app so that the Worker starts on app boot.
6. Show me only real imports from `source/index.ts` and `source/WorkerTypes.ts` — do not invent any API.
7. Follow the patterns in the "Working examples" section of USAGE.md exactly.
Upstream package: user@example.com
Source root: source/ (maps to mediasoup node/src)
mediasoup is released under the ISC License. See the LICENSE file in the upstream repository or source/ if present.
Upstream project: mediasoup on npm — maintained by Iñaki Baz Castillo, José Luis Millán, and Nazar Mokynskyi at versatica/mediasoup.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
PHP, Laravel & Business Scripts
Miễn phí