OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Remote Video Not Displaying in Django WebSockets Video Call Implementation

  • Thread starter Thread starter Neiheel
  • Start date Start date
N

Neiheel

Guest
I'm trying to build a video call feature for two users (local and remote peers) using Django, WebSockets, HTML, and JavaScript. The local video is working fine, but the remote video is not showing up even though its exists. I'm getting the following error:

Error: DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable The error occurs in this snippet of code:

function handleAnswer(answer) { console.log('Handling answer:', answer); if (peerConnection.signalingState !== 'have-local-offer') { console.warn('Unexpected signaling state:', peerConnection.signalingState, 'Answer ignored.'); return; } peerConnection.setRemoteDescription(new RTCSessionDescription(answer)).then(() => { console.log('Remote description set for answer:', answer); }).catch(error => { console.error('Error setting remote description for answer:', error); }); }

HTML:

Code:
<div class="video-root" id="vid-area">
    <div class="username-wrapper"><span class="user-name">+11ß</span></div>
    <video class="video-player" id="consultant" autoplay playsinline></video>
    <!-- Here where the remote comes in  -->
    <div id="remoteVideoFrame" class="smallFrame" style="display : none;">
        <video class="video-player" id="client" autoplay playsinline></video>
    </div>
    <div class="controls-wrapper">
        <div class="icon-wrapper">
            <i class='bx bx-microphone control-icon' id="mic-btn"></i>
        </div>
        <div class="icon-wrapper">
            <i class='bx bx-camera-home control-icon' id="camera-btn"></i>
        </div>
        <div class="icon-wrapper">
            <i class='bx bx-screenshot control-icon' id="screen-share"></i>
        </div>
        <div class="icon-wrapper">
            <i class='bx bx-phone-off control-icon' id="leave-btn"></i>
        </div>
    </div>
</div>

JavaScript:

Code:
document.addEventListener('DOMContentLoaded', function () {
    var loc = window.location;
    var wsStart = loc.protocol === 'https:' ? 'wss://' : 'ws://';
    var endPoint = wsStart + loc.host + loc.pathname;
    console.log(endPoint);

    const localVideo = document.getElementById('consultant');
    const remoteVideoContainer = document.getElementById('remoteVideoFrame');

    let peerConnection;
    let localStream;
    let ws = new WebSocket(endPoint);

    ws.onopen = function() {
        console.log('WebSocket connection established');
    };

    ws.onerror = function(event) {
        console.error('WebSocket error:', event);
    };

    ws.onmessage = function(message) {
        console.log('WebSocket message received:', message.data);
        const signal = JSON.parse(message.data);
        switch(signal.type) {
            case 'offer':
                console.log('Received offer:', signal.offer);
                handleOffer(signal.offer);
                break;
            case 'answer':
                console.log('Received answer:', signal.answer);
                handleAnswer(signal.answer);
                break;
            case 'candidate':
                console.log('Received candidate:', signal.candidate);
                handleCandidate(signal.candidate);
                break;
            default:
                console.log('Unknown signal type:', signal.type);
        }
    };

    function startConnection() {
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
            .then(stream => {
                localVideo.srcObject = stream;
                localStream = stream;
                createPeerConnection();
            }).catch(error => {
                console.error('Media access error:', error);
            });
    }

    function createPeerConnection() {
        peerConnection = new RTCPeerConnection();

        peerConnection.onicecandidate = function(event) {
            if (event.candidate) {
                console.log("Sending candidate:", event.candidate);
                ws.send(JSON.stringify({ type: 'candidate', candidate: event.candidate }));
            } else {
                console.log("Null candidate may indicate end of candidates.");
            }
        };

        peerConnection.ontrack = event => {
            console.log('Track received:', event);
            remoteVideoContainer.srcObject = event.streams[0];
            remoteVideoContainer.style.display = 'block';
        };

        localStream.getTracks().forEach(track => {
            peerConnection.addTrack(track, localStream);
            console.log('Adding track:', track);
        });

        console.log('Creating offer...');
        peerConnection.createOffer().then(offer => {
            console.log('Offer created:', offer);
            return peerConnection.setLocalDescription(offer);
        }).then(() => {
            console.log('Local description set:', peerConnection.localDescription);
            ws.send(JSON.stringify({ type: 'offer', offer: peerConnection.localDescription }));
            console.log('Offer sent:', peerConnection.localDescription);
        }).catch(error => console.error('Offer creation error:', error));
    }

    function handleOffer(offer) {
        console.log('Handling offer:', offer);
        createRemotePeerConnection();
        peerConnection.setRemoteDescription(new RTCSessionDescription(offer)).then(() => {
            console.log('Remote description set for offer:', offer);
            return peerConnection.createAnswer();
        }).then(answer => {
            console.log('Answer created:', answer);
            return peerConnection.setLocalDescription(answer);
        }).then(() => {
            console.log('Local description set for answer:', peerConnection.localDescription);
            ws.send(JSON.stringify({ type: 'answer', answer: peerConnection.localDescription }));
            console.log('Answer sent:', peerConnection.localDescription);
        }).catch(error => console.error('Answer creation error:', error));
    }

    function createRemotePeerConnection() {
        if (peerConnection) {
            console.log('Closing existing peer connection');
            peerConnection.close();
        }
        peerConnection = new RTCPeerConnection();

        peerConnection.onicecandidate = function(event) {
            if (event.candidate) {
                console.log("Sending candidate:", event.candidate);
                ws.send(JSON.stringify({ type: 'candidate', candidate: event.candidate }));
            } else {
                console.log("Null candidate may indicate end of candidates.");
            }
        };

        peerConnection.ontrack = event => {
            console.log('Track received:', event);
            remoteVideoContainer.srcObject = event.streams[0];
            remoteVideoContainer.style.display = 'block';
        };
    }

    function handleAnswer(answer) {
        console.log('Handling answer:', answer);
        if (peerConnection.signalingState !== 'have-local-offer') {
            console.warn('Unexpected signaling state:', peerConnection.signalingState, 'Answer ignored.');
            return;
        }
        peerConnection.setRemoteDescription(new RTCSessionDescription(answer)).then(() => {
            console.log('Remote description set for answer:', answer);
        }).catch(error => {
            console.error('Error setting remote description for answer:', error);
        });
    }

    function handleCandidate(candidate) {
        console.log('Handling candidate:', candidate);
        if (candidate) {
            peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
                .then(() => console.log("ICE candidate added successfully"))
                .catch(error => console.error("Error adding ICE candidate:", error));
        } else {
            console.error("Invalid or incomplete candidate data received:", candidate);
        }
    }

    // Start the connection process when the user navigates to the page
    startConnection();
});

Python (consumers.py) :

Code:
import json
from channels.generic.websocket import AsyncWebsocketConsumer

class WebRTCConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = f'webrtc_{self.room_name}'

        # Join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        data = json.loads(text_data)
        message_type = data.get('type')

        # Log received message
        print(f'Received message: {data}')

        # Handle different message types and send them to the room group
        if message_type in ['offer', 'answer', 'candidate']:
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'webrtc_message',
                    'message': data
                }
            )

    async def webrtc_message(self, event):
        message = event['message']

        # Log sending message
        print(f'Sending message: {message}')

        # Send message to WebSocket
        await self.send(text_data=json.dumps(message))

Issue Summary: The main problem is that the remote video isn't displaying, and I'm getting an error related to the signaling state when setting the remote description. Any help to troubleshoot this issue would be greatly appreciated!

Thank you in advance!

<p>I'm trying to build a video call feature for two users (local and remote peers) using Django, WebSockets, HTML, and JavaScript. The local video is working fine, but the remote video is not showing up even though its exists. I'm getting the following error:</p>
<p>Error:
<code>DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable </code>
The error occurs in this snippet of code:</p>
<p><code>function handleAnswer(answer) { console.log('Handling answer:', answer); if (peerConnection.signalingState !== 'have-local-offer') { console.warn('Unexpected signaling state:', peerConnection.signalingState, 'Answer ignored.'); return; } peerConnection.setRemoteDescription(new RTCSessionDescription(answer)).then(() => { console.log('Remote description set for answer:', answer); }).catch(error => { console.error('Error setting remote description for answer:', error); }); }</code></p>
<p>HTML:</p>
<pre><code><div class="video-root" id="vid-area">
<div class="username-wrapper"><span class="user-name">+11ß</span></div>
<video class="video-player" id="consultant" autoplay playsinline></video>
<!-- Here where the remote comes in -->
<div id="remoteVideoFrame" class="smallFrame" style="display : none;">
<video class="video-player" id="client" autoplay playsinline></video>
</div>
<div class="controls-wrapper">
<div class="icon-wrapper">
<i class='bx bx-microphone control-icon' id="mic-btn"></i>
</div>
<div class="icon-wrapper">
<i class='bx bx-camera-home control-icon' id="camera-btn"></i>
</div>
<div class="icon-wrapper">
<i class='bx bx-screenshot control-icon' id="screen-share"></i>
</div>
<div class="icon-wrapper">
<i class='bx bx-phone-off control-icon' id="leave-btn"></i>
</div>
</div>
</div>
</code></pre>
<p>JavaScript:</p>
<pre><code>document.addEventListener('DOMContentLoaded', function () {
var loc = window.location;
var wsStart = loc.protocol === 'https:' ? 'wss://' : 'ws://';
var endPoint = wsStart + loc.host + loc.pathname;
console.log(endPoint);

const localVideo = document.getElementById('consultant');
const remoteVideoContainer = document.getElementById('remoteVideoFrame');

let peerConnection;
let localStream;
let ws = new WebSocket(endPoint);

ws.onopen = function() {
console.log('WebSocket connection established');
};

ws.onerror = function(event) {
console.error('WebSocket error:', event);
};

ws.onmessage = function(message) {
console.log('WebSocket message received:', message.data);
const signal = JSON.parse(message.data);
switch(signal.type) {
case 'offer':
console.log('Received offer:', signal.offer);
handleOffer(signal.offer);
break;
case 'answer':
console.log('Received answer:', signal.answer);
handleAnswer(signal.answer);
break;
case 'candidate':
console.log('Received candidate:', signal.candidate);
handleCandidate(signal.candidate);
break;
default:
console.log('Unknown signal type:', signal.type);
}
};

function startConnection() {
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(stream => {
localVideo.srcObject = stream;
localStream = stream;
createPeerConnection();
}).catch(error => {
console.error('Media access error:', error);
});
}

function createPeerConnection() {
peerConnection = new RTCPeerConnection();

peerConnection.onicecandidate = function(event) {
if (event.candidate) {
console.log("Sending candidate:", event.candidate);
ws.send(JSON.stringify({ type: 'candidate', candidate: event.candidate }));
} else {
console.log("Null candidate may indicate end of candidates.");
}
};

peerConnection.ontrack = event => {
console.log('Track received:', event);
remoteVideoContainer.srcObject = event.streams[0];
remoteVideoContainer.style.display = 'block';
};

localStream.getTracks().forEach(track => {
peerConnection.addTrack(track, localStream);
console.log('Adding track:', track);
});

console.log('Creating offer...');
peerConnection.createOffer().then(offer => {
console.log('Offer created:', offer);
return peerConnection.setLocalDescription(offer);
}).then(() => {
console.log('Local description set:', peerConnection.localDescription);
ws.send(JSON.stringify({ type: 'offer', offer: peerConnection.localDescription }));
console.log('Offer sent:', peerConnection.localDescription);
}).catch(error => console.error('Offer creation error:', error));
}

function handleOffer(offer) {
console.log('Handling offer:', offer);
createRemotePeerConnection();
peerConnection.setRemoteDescription(new RTCSessionDescription(offer)).then(() => {
console.log('Remote description set for offer:', offer);
return peerConnection.createAnswer();
}).then(answer => {
console.log('Answer created:', answer);
return peerConnection.setLocalDescription(answer);
}).then(() => {
console.log('Local description set for answer:', peerConnection.localDescription);
ws.send(JSON.stringify({ type: 'answer', answer: peerConnection.localDescription }));
console.log('Answer sent:', peerConnection.localDescription);
}).catch(error => console.error('Answer creation error:', error));
}

function createRemotePeerConnection() {
if (peerConnection) {
console.log('Closing existing peer connection');
peerConnection.close();
}
peerConnection = new RTCPeerConnection();

peerConnection.onicecandidate = function(event) {
if (event.candidate) {
console.log("Sending candidate:", event.candidate);
ws.send(JSON.stringify({ type: 'candidate', candidate: event.candidate }));
} else {
console.log("Null candidate may indicate end of candidates.");
}
};

peerConnection.ontrack = event => {
console.log('Track received:', event);
remoteVideoContainer.srcObject = event.streams[0];
remoteVideoContainer.style.display = 'block';
};
}

function handleAnswer(answer) {
console.log('Handling answer:', answer);
if (peerConnection.signalingState !== 'have-local-offer') {
console.warn('Unexpected signaling state:', peerConnection.signalingState, 'Answer ignored.');
return;
}
peerConnection.setRemoteDescription(new RTCSessionDescription(answer)).then(() => {
console.log('Remote description set for answer:', answer);
}).catch(error => {
console.error('Error setting remote description for answer:', error);
});
}

function handleCandidate(candidate) {
console.log('Handling candidate:', candidate);
if (candidate) {
peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
.then(() => console.log("ICE candidate added successfully"))
.catch(error => console.error("Error adding ICE candidate:", error));
} else {
console.error("Invalid or incomplete candidate data received:", candidate);
}
}

// Start the connection process when the user navigates to the page
startConnection();
});

</code></pre>
<p>Python (consumers.py) :</p>
<pre><code>import json
from channels.generic.websocket import AsyncWebsocketConsumer

class WebRTCConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = f'webrtc_{self.room_name}'

# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)

await self.accept()

async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)

async def receive(self, text_data):
data = json.loads(text_data)
message_type = data.get('type')

# Log received message
print(f'Received message: {data}')

# Handle different message types and send them to the room group
if message_type in ['offer', 'answer', 'candidate']:
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'webrtc_message',
'message': data
}
)

async def webrtc_message(self, event):
message = event['message']

# Log sending message
print(f'Sending message: {message}')

# Send message to WebSocket
await self.send(text_data=json.dumps(message))

</code></pre>
<p>Issue Summary:
The main problem is that the remote video isn't displaying, and I'm getting an error related to the signaling state when setting the remote description. Any help to troubleshoot this issue would be greatly appreciated!</p>
<p>Thank you in advance!</p>
 

Latest posts

Top