Javascript webrtc group video streamming

Viewed 129

I would like to receive help to add group video streaming to the bellow code, i would like to implement a group streaming which ll be working with a link like

domain.net/video.html?id=123&host=1 domain.net/video.html?id=456&host=1 to allow friends joining using param id.

'use strict';

// Put variables in global scope to make them available to the browser console.
const constraints = window.constraints = {
    audio: true,
    video: true
};

function handleSuccess(stream) {
    const video = document.querySelector('video');
    const videoTracks = stream.getVideoTracks();
    window.stream = stream;
    video.srcObject = stream;
}

function handleError(error) {
    if (error.name === 'ConstraintNotSatisfiedError') {
        const v = constraints.video;
        console.log("The resolution not supported");
    } else if (error.name === 'PermissionDeniedError') {
        console.log('Permissions have not been granted');
    }
    console.log(`getUserMedia error: ${error.name}`, error);
}

async function init(e) {
    try {
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        handleSuccess(stream);
        e.target.disabled = true;
    } catch (e) {
        handleError(e);
    }
}

document.querySelector('#showVideo').addEventListener('click', e => init(e));

Am in my learning stages to JavaScript please help, thanks.
1 Answers

The script you provided currently gets the user camera and audio. You will need to feed that to an RTCPeerConnection and establish a WebRTC session with the other peers by exchanging SDP messages and ICE candidates via a signaling server. Read this to understand more in detail how WebRTC connectivity works.

Since you want to stream to a group of people, one approach is to create a new RTCPeerConnection for every new peer in your room. Check out this example, it does exactly that.

However, since WebRTC is intended for peer-to-peer, this solution is not very scalable, because you are going to be creating new peer connections exponentially, which is quite heavy for the browser to handle and consumes a lot of bandwidth. With +6 people, the quality of your call will already be terrible, but I think up to 4 people it should be doable.

If your intention is to have a conference room, you should really look into using a Selective Forwarding Unit (SFU) media server. With this approach, the server will perform stream routing and apply some tricks such as Simulcast to make your stream more scalable and adaptive, providing a better experience.

Checkout Janus VideoRoom plugin for an open-source SFU implementation.

Related