Added video-sync for clients. Tweaked the code.

Moved the script for index.html (the home page) to client.js
Created a new directory for videos: /videos
Added a new video: /videos/Shreksophone_Original.mp4
Moved bigbuck.mp4 to /videos
Added the video-sync clinet code to client.js
Added the video-sync client code to index.js
Updated index.html inner html to work with the vidoe-sync
This commit is contained in:
ShakedAp 2023-06-24 21:42:11 +03:00
parent d00e6e04ff
commit 828697aa68
5 changed files with 242 additions and 18 deletions

166
client.js Normal file
View File

@ -0,0 +1,166 @@
const vid = document.querySelector('video')
const socket = new WebSocket('ws://192.168.68.118:3000');
// if the new tms is within this margin of the current tms, then the change is ignored for smoother viewing
const PLAYING_THRESH = 1
const PAUSED_THRESH = 0.01
// local state
let video_playing = false
let last_updated = 0
let client_uid = null
// clocks sync variables
const num_time_sync_cycles = 10
let over_estimates = new Array()
let under_estimates = new Array()
let over_estimate = 0
let under_estimate = 0
let correction = 0
// Connection opened
socket.addEventListener('open', function (event) {
console.log('Connected to WS Server');
});
// Got message from the server
socket.addEventListener("message", (event) => {
if (event.data.startsWith("time_sync_response_backward"))
{
let time_at_server = Number(event.data.slice("time_sync_response_backward".length + 1));
let under_estimate_latest = time_at_server - get_global_time(0);
under_estimates.push(under_estimate_latest);
under_estimate = median(under_estimates);
correction = (under_estimate + over_estimate)/2;
console.log(`%c Updated val for under_estimate is ${under_estimate}`, "color:green");
console.log(`%c New correction time is ${correction} miliseconds`, 'color:red; font-size:12px');
}
if (event.data.startsWith("time_sync_response_forward"))
{
let calculated_diff = Number(event.data.slice("time_sync_response_forward".length + 1));
over_estimates.push(calculated_diff);
over_estimate = median(over_estimates);
correction = (under_estimate + over_estimate)/2;
console.log(`%c Updated val for over_estimate is ${over_estimate}`, "color:green");
console.log(`%c New correction time is ${correction} miliseconds`, 'color:red; font-size:12px');
}
if (event.data.startsWith("state_update_from_server"))
{
let state = JSON.parse(event.data.slice("state_update_from_server".length + 1));
// Whenever the client connects or reconnects
if (client_uid == null){
client_uid = state.client_uid;
}
// calculating the new timestamp for both cases - when the video is playing and when it is paused
let proposed_time = (state.playing) ? ((get_global_time(correction) - state.global_timestamp)/1000 + state.video_timestamp) : (state.video_timestamp)
let gap = Math.abs(proposed_time - vid.currentTime)
console.log(`%cGap was ${proposed_time - vid.currentTime}`, 'font-size:12px; color:purple')
if (state.playing){
if(gap > PLAYING_THRESH){
// tolerance while the video is playing
vid.currentTime = proposed_time
}
vid.play()
}
else{
vid.pause()
if (gap > PAUSED_THRESH){
// condition to prevent an unnecessary seek
vid.currentTime = proposed_time
}
}
}
});
// Connection closed
socket.addEventListener('close', function (event) {
console.log('Disconnected from the WS Server');
client_uid = null
});
function state_change_handler(event)
{
if (event !== null && event !== undefined){
if (event.type === 'pause')
video_playing = false;
else if (event.type === 'play')
video_playing = true;
}
last_updated = get_global_time(correction);
state_image = {
video_timestamp: vid.currentTime,
last_updated: last_updated,
playing: video_playing,
global_timestamp: get_global_time(correction),
client_uid: client_uid
}
socket.send(`state_update_from_client ${JSON.stringify(state_image)}`)
}
// assigning event handlers
vid.onseeking = state_change_handler;
vid.onplay = state_change_handler;
vid.onpause = state_change_handler;
// handling the video ended case separately
vid.onended = () => {
video_playing = false;
last_updated = get_global_time(correction);
vid.load();
state_change_handler();
}
// Helper Functions
function get_global_time(delta = 0) {
let d = new Date();
return d.getTime() + delta;
}
function median(values) {
if(values.length === 0) { return 0; }
values.sort((x,y) => (x-y));
let half = Math.floor(values.length / 2);
if (values.length % 2){
return values[half];
}
return (values[half - 1] + values[half]) / 2.0;
}
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function do_time_sync_one_cycle_backward() {
socket.send("time_sync_request_backward");
}
function do_time_sync_one_cycle_forward() {
socket.send(`time_sync_request_forward ${get_global_time()}`);
}
// time requests are made every second
async function do_time_sync() {
for(let i = 0; i < num_time_sync_cycles; i++){
await timeout(500);
do_time_sync_one_cycle_backward();
await timeout(500);
do_time_sync_one_cycle_forward();
}
}
do_time_sync();

View File

@ -3,22 +3,15 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script defer type="text/javascript" src="client.js"></script>
<title>Client</title>
</head>
<body>
Client page!
<br/>
<video id="videoPlayer" width="650" controls disablePictureInPicture controlsList="nodownload" autoplay>
<video id="videoPlayer" width="650" controls disablePictureInPicture controlsList="nodownload noplaybackrate" muted>
<source src="/video" type="video/mp4" />
</video>
</body>
<script>
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', function (event) {
console.log('Connected to WS Server')
});
</script>
</html>

View File

@ -1,16 +1,75 @@
// https://www.npmjs.com/package/ws#api-docs
// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
const fs = require("fs");
const express = require('express')
const app = express()
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const WebSocket = require('ws')
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server:server });
const THRESH_IGNORANCE = 250;
let users_amount = 0;
let unique_id = 0;
let state = {
video_timestamp: 0,
last_updated: get_time(),
playing: false,
global_timestamp: 0,
client_uid: null
};
wss.on('connection', function connection(ws) {
console.log('A new client Connected!');
ws.send('Welcome New Client!');
users_amount += 1;
console.log('A new client Connected. Amount of users: ', users_amount);
state.client_uid = unique_id;
unique_id +=1 ;
ws.send(`state_update_from_server ${JSON.stringify(state)}`);
ws.on('error', console.error);
ws.on('message', function message(data) {
data = data.toString();
if(data.startsWith("time_sync_request_backward"))
{
ws.send(`time_sync_response_backward ${get_time()}`);
}
if(data.startsWith("time_sync_request_forward"))
{
let client_time = Number(data.slice("time_sync_request_forward".length + 1));
ws.send(`time_sync_response_forward ${get_time() - client_time}`);
}
if(data.startsWith("state_update_from_client"))
{
let new_state = JSON.parse(data.slice("state_update_from_client".length + 1));
let too_soon = (get_time() - state.last_updated) < THRESH_IGNORANCE;
let other_ip = (new_state.client_uid != state.client_uid);
let stale = (new_state.last_updated < state.last_updated)
if (!stale && !(too_soon && other_ip))
{
state = new_state;
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`state_update_from_server ${JSON.stringify(state)}`);
}
});
}
}
});
ws.on('close', function close() {
users_amount -= 1;
console.log('Client diconnected. Amount of users: ', users_amount);
});
});
app.use(express.static(__dirname));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
@ -24,12 +83,12 @@ app.get("/video", function (req, res) {
}
// get video stats (about 61MB)
const videoPath = "bigbuck.mp4";
const videoSize = fs.statSync("bigbuck.mp4").size;
const videoPath = "videos/Shreksophone_Original.mp4";
const videoSize = fs.statSync(videoPath).size;
// Parse Range
// Example: "bytes=32324-"
const CHUNK_SIZE = 10 ** 5; // 1MB
const CHUNK_SIZE = 10 ** 6; // 1MB
const start = Number(range.replace(/\D/g, ""));
const end = Math.min(start + CHUNK_SIZE, videoSize - 1);
@ -52,4 +111,10 @@ app.get("/video", function (req, res) {
videoStream.pipe(res);
});
server.listen(3000, () => console.log(`Lisening on port :3000`))
server.listen(3000, () => console.log(`Listening on port: 3000`));
function get_time(){
let d = new Date();
return d.getTime();
}

Binary file not shown.