WebRTC
- Technology that allows voice, video, and data to be sent and received between web browsers in real time
- Enables P2P communication from within the browser itself, without the need to install any plugins or software
Mediasoup
- Powerful Selective Forwarding Unit (SFU) media server for WebRTC
- As a media server, it relays and manages media streams between participants
- Written in
Node.jswith a media server core implemented inC++ - Support for real-time video/audio routing
- Support for multiple codecs (VP8, VP9, H.264, Opus, etc.)
Multiprocessing in Mediasoup
1. Worker pool management
1
2
3
// Managing multiple workers through the mediasoup Workers array
const mediasoupWorkers = [];
let nextMediasoupWorkerIdx = 0;
2. Create the set number of workers
1
2
3
4
5
const { numWorkers } = config.mediasoup;
for (let i = 0; i < numWorkers; ++i) {
const worker = await mediasoup.createWorker({...});
mediasoupWorkers.push(worker);
}
3. Assigning Workers in Round-Robin
1
2
3
4
5
6
7
8
function getMediasoupWorker() {
const worker = mediasoupWorkers[nextMediasoupWorkerIdx];
if (++nextMediasoupWorkerIdx === mediasoupWorkers.length)
nextMediasoupWorkerIdx = 0;
return worker;
}
What is a Round-Robin?
Round robin is a scheduling algorithm that alternately allocates resources in a sequential order
- Advantages
- Simple and intuitive implementation
- Provide fair opportunities for all workers
- Evenly distribute CPU load
- Prevents work from being pushed to certain workers
- disadvantages
- Doesn’t take into account a worker’s current load status
- Difficult to reflect the prioritization of tasks
- Assumes all workers have the same processing power
4. Assign Workers to each Room
1
2
3
4
5
6
async function getOrCreateRoom({ roomId, consumerReplicas }) {
if (!room) {
const mediasoupWorker = getMediasoupWorker();
room = await Room.create({ mediasoupWorker, roomId, consumerReplicas });
}
}
Key features
- Parallelization: Each Worker runs on a separate CPU process, enabling parallel processing.
- Load balancing: Evenly distributes system load across multiple CPUs by allocating Workers in a round-robin fashion.
- Monitoring: Periodic monitoring of each worker’s resource usage.
1 2 3 4
setInterval(async () => { const usage = await worker.getResourceUsage(); logger.info('mediasoup Worker resource usage [pid:%d]: %o', worker.pid, usage); }, 120000);
- Failover: Designed to restart the entire process if a worker is terminated.
1 2 3 4
worker.on('died', () => { logger.error('mediasoup Worker died, exiting in 2 seconds... [pid:%d]', worker.pid); setTimeout(() => process.exit(1), 2000); });
How Mediasoup works with WebRTC
- The client uses the browser’s WebRTC API to create a media stream.
- The Mediasoup server receives this stream and efficiently routes it to the other participants.