101 lines
2.9 KiB
JavaScript
101 lines
2.9 KiB
JavaScript
const socket = io();
|
|
const overlay = document.getElementById('overlay');
|
|
const videoWrapper = document.getElementById('videoWrapper');
|
|
|
|
// Initialize video.js player
|
|
const player = videojs('remoteVideo', {
|
|
controls: true,
|
|
autoplay: true,
|
|
preload: 'auto',
|
|
fluid: true,
|
|
controlBar: {
|
|
volumePanel: { inline: false },
|
|
fullscreenToggle: true,
|
|
pictureInPictureToggle: true
|
|
}
|
|
});
|
|
|
|
let peerConnection;
|
|
const config = {
|
|
iceServers: [
|
|
{ urls: "stun:localhost:3478" },
|
|
{
|
|
urls: "turn:localhost:3478",
|
|
username: "myuser",
|
|
credential: "mypassword"
|
|
}
|
|
]
|
|
};
|
|
|
|
socket.on('offer', (id, description) => {
|
|
peerConnection = new RTCPeerConnection(config);
|
|
|
|
peerConnection.ontrack = event => {
|
|
// Need to set srcObject on the raw video element inside video.js
|
|
const videoElement = document.querySelector('#remoteVideo_html5_api');
|
|
if (videoElement) {
|
|
videoElement.srcObject = event.streams[0];
|
|
|
|
// Notify video.js of the media change
|
|
player.trigger('loadstart');
|
|
player.trigger('loadedmetadata');
|
|
player.trigger('loadeddata');
|
|
player.trigger('canplay');
|
|
player.trigger('playing');
|
|
|
|
videoWrapper.classList.add('active');
|
|
overlay.classList.add('hidden');
|
|
|
|
// Force play after stream is attached
|
|
setTimeout(() => {
|
|
player.muted(true); // Ensure autoplay policies don't block visuals
|
|
player.play().catch(e => console.error("Autoplay prevented:", e));
|
|
}, 100);
|
|
}
|
|
};
|
|
|
|
peerConnection.onicecandidate = event => {
|
|
if (event.candidate) {
|
|
socket.emit('candidate', id, event.candidate);
|
|
}
|
|
};
|
|
|
|
peerConnection
|
|
.setRemoteDescription(description)
|
|
.then(() => peerConnection.createAnswer())
|
|
.then(sdp => peerConnection.setLocalDescription(sdp))
|
|
.then(() => {
|
|
socket.emit('answer', id, peerConnection.localDescription);
|
|
});
|
|
});
|
|
|
|
socket.on('candidate', (id, candidate) => {
|
|
if (peerConnection) {
|
|
peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
|
|
.catch(e => console.error(e));
|
|
}
|
|
});
|
|
|
|
socket.on('broadcaster', () => {
|
|
socket.emit('viewer');
|
|
});
|
|
|
|
socket.on('disconnectPeer', () => {
|
|
if (peerConnection) {
|
|
peerConnection.close();
|
|
peerConnection = null;
|
|
}
|
|
|
|
videoWrapper.classList.remove('active');
|
|
const videoElement = document.querySelector('#remoteVideo_html5_api');
|
|
if (videoElement) videoElement.srcObject = null;
|
|
|
|
overlay.classList.remove('hidden');
|
|
overlay.querySelector('h1').innerText = 'Stream Ended';
|
|
overlay.querySelector('.status-indicator span:last-child').innerText = 'Waiting for new stream...';
|
|
});
|
|
|
|
socket.on('connect', () => {
|
|
socket.emit('viewer');
|
|
});
|