Compare commits

...

8 Commits

7 changed files with 165 additions and 97 deletions

View File

@@ -1,6 +1,8 @@
{ {
"server_ip": "0.0.0.0", "server_ip": "0.0.0.0",
"server_port": 3000, "server_port": 8080,
"video_path": "videos/Orb-22.mp4", "video_path": "videos/Orb-21.mp4",
"subtitles_path": "videos/Orb-21.vtt",
"bg_path": "videos/bg-20.png",
"password": "password" "password": "password"
} }

View File

@@ -1,6 +1,106 @@
const vid = document.querySelector('video'); const vid = document.querySelector('video');
const wsProto = window.location.protocol === 'https:' ? 'wss' : 'ws'; const wsProto = window.location.protocol === 'https:' ? 'wss' : 'ws';
const socket = new WebSocket(`${wsProto}://${window.location.hostname}:${window.location.port}`); let socket = null; // Initialize socket as null
let retryInterval = 1000; // Initial retry interval in milliseconds
const maxRetryInterval = 30000; // Maximum retry interval
function createWebSocket() {
socket = new WebSocket(`${wsProto}://${window.location.hostname}:${window.location.port}`);
// Connection opened
socket.addEventListener('open', function (event) {
console.log('Connected to WS Server');
retryInterval = 1000; // Reset retry interval on successful connection
});
// Got message from the server
socket.addEventListener("message", (event) => {
// Reload the page if the server sends a reload request
if (event.data.startsWith("reload_request")) {
console.log("Reloading the page as requested by the server");
setTimeout(() => window.location.reload(), 1000);
return;
}
// Time syncing backward server-response
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');
}
// Time syncing forward server-response
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');
}
// Video state update from server
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) {
// tolerance while the video is playing
if (gap > PLAYING_THRESH) {
vid.currentTime = proposed_time;
}
vid.play()
} else {
vid.pause()
// condition to prevent an unnecessary seek
if (gap > PAUSED_THRESH) {
vid.currentTime = proposed_time;
}
}
}
});
// Connection closed
socket.addEventListener('close', function (event) {
console.log('Disconnected from the WS Server');
client_uid = null;
retryWebSocketConnection(); // Attempt to reconnect
});
// Connection error
socket.addEventListener('error', function (event) {
console.error('WebSocket error:', event);
socket.close(); // Ensure the socket is closed on error
});
}
function retryWebSocketConnection() {
console.log(`Attempting to reconnect in ${retryInterval / 1000} seconds...`);
setTimeout(() => {
retryInterval = Math.min(retryInterval * 2, maxRetryInterval); // Exponential backoff
createWebSocket(); // Recreate the WebSocket connection
}, retryInterval);
}
// Initial WebSocket connection
createWebSocket();
// if the new tms is within this margin of the current tms, then the change is ignored for smoother viewing // 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 PLAYING_THRESH = 1;
@@ -19,77 +119,6 @@ let over_estimate = 0;
let under_estimate = 0; let under_estimate = 0;
let correction = 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) => {
// Time syncing backward server-response
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');
}
// Time syncing forward server-response
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');
}
// Video state update from server
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) {
// tolerance while the video is playing
if (gap > PLAYING_THRESH) {
vid.currentTime = proposed_time;
}
vid.play()
} else {
vid.pause()
// condition to prevent an unnecessary seek
if (gap > PAUSED_THRESH) {
vid.currentTime = proposed_time;
}
}
}
});
// Connection closed
socket.addEventListener('close', function (event) {
console.log('Disconnected from the WS Server');
client_uid = null;
});
// Send video state update to the server // Send video state update to the server
// event: the video event (ex: seeking, pause play) // event: the video event (ex: seeking, pause play)
function state_change_handler(event) { function state_change_handler(event) {
@@ -110,7 +139,9 @@ function state_change_handler(event) {
client_uid: client_uid client_uid: client_uid
}; };
socket.send(`state_update_from_client ${JSON.stringify(state_image)}`); if (socket.readyState === WebSocket.OPEN) {
socket.send(`state_update_from_client ${JSON.stringify(state_image)}`);
}
} }
// assigning event handlers // assigning event handlers
@@ -212,3 +243,4 @@ document.addEventListener('DOMContentLoaded', function() {
style.textContent = `::cue { font-size: ${size} !important; }`; style.textContent = `::cue { font-size: ${size} !important; }`;
}); });
}); });

BIN
src/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 KiB

View File

@@ -80,6 +80,14 @@ wss.on('connection', function connection(ws) {
//// Web server //// //// Web server ////
// app settings // app settings
// disable cache globally because it may break things between server restarts,
// since the paths aren't unique
app.use(function (req, res, next) {
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
next();
});
app.use('/', express.static(__dirname)); app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ app.use(bodyParser.urlencoded({
extended: true extended: true
@@ -145,6 +153,7 @@ app.get("/video", function (req, res) {
"Accept-Ranges": "bytes", "Accept-Ranges": "bytes",
"Content-Length": contentLength, "Content-Length": contentLength,
"Content-Type": "video/mp4", "Content-Type": "video/mp4",
"Cache-Control": "no-cache, no-store, must-revalidate",
}; };
// HTTP Status 206 for Partial Content // HTTP Status 206 for Partial Content
@@ -163,7 +172,11 @@ app.get("/video", function (req, res) {
// subtitles track // subtitles track
app.get("/subtitles", function (req, res) { app.get("/subtitles", function (req, res) {
console.log("hello)"); console.log("hello)");
res.sendFile(__dirname + "/subs/Orb-22.vtt"); res.sendFile(fs.realpathSync(settings.subtitles_path));
});
app.get("/background", function (req, res) {
res.sendFile(fs.realpathSync(settings.bg_path))
}); });
@@ -171,9 +184,22 @@ app.get("/subtitles", function (req, res) {
server.listen(settings.server_port, settings.server_ip, server.listen(settings.server_port, settings.server_ip,
() => console.log(`Server started at ${settings.server_ip}:${settings.server_port}`)); () => console.log(`Server started at ${settings.server_ip}:${settings.server_port}`));
process.on('SIGINT', () => {
console.log("Shutting down server...");
// wss.close();
wss.clients.forEach(client => {
client.send("reload_request");
client.terminate();
});
server.close(() => {
console.log("Server closed");
process.exit(0);
});
});
// function to get the current time // function to get the current time
function get_time() { function get_time() {
let d = new Date(); let d = new Date();
return d.getTime(); return d.getTime();
} }

View File

@@ -8,15 +8,23 @@
} }
body { body {
height: 100vh; color: aliceblue;
min-height: 100vh;
margin: 0; margin: 0;
padding: 2rem; padding: 2rem;
background-color: gray; background-color: #161616;
font-family: "Roboto", sans-serif; font-family: "Roboto", sans-serif;
} }
body[data-background] {
background-image: url('/background');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-blend-mode: multiply;
}
.container { .container {
max-height: 100vh;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
@@ -25,18 +33,13 @@ body {
header { header {
text-align: center; text-align: center;
font-size: 2rem; font-size: 2rem;
} text-shadow: aliceblue 0 0 0.25rem;
.video-wrapper {
/*position: relative;*/
/*width: 100%;*/
/*padding-bottom: 56.25%;*/
/* 16:9 aspect ratio for responsive video */
} }
video { video {
/*height:;*/ /*height:;*/
max-width: 100%; max-width: 100%;
max-height: 80vh;
/*max-height: 400px;*/ /*max-height: 400px;*/
/*position: absolute;*/ /*position: absolute;*/
/*top: 0;*/ /*top: 0;*/

View File

@@ -5,21 +5,26 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="main.css"> <link rel="stylesheet" type="text/css" href="main.css">
<script defer type="text/javascript" src="client.js"></script> <script defer type="text/javascript" src="client.js"></script>
<title>Client</title> <title>Orboverse</title>
<link rel="icon" href="/icon.png" type="image/png">
<!-- Open Graph Meta Tags -->
<meta property="og:title" content="The Orboverse">
<meta property="og:description" content="Join the funny. 🔫.">
<meta property="og:image" content="/stars.jpg">
<meta property="og:url" content="https://anistream.cazzzer.com">
<meta property="og:type" content="website">
</head> </head>
<body> <body data-background>
<div class="container"> <div class="container">
<header> <header>
<h1>Watch-Together</h1> <h1>Welcome to the Orboverse</h1>
</header> </header>
<div class="video-wrapper"> <video id="videoPlayer" muted controls controlsList="nodownload noplaybackrate">
<video id="videoPlayer" controls controlsList="nodownload noplaybackrate"> <source src="/video" type="video/mp4" />
<source src="/video" type="video/mp4" />
<!-- subtitle track--> <!-- subtitle track-->
<track kind="subtitles" src="/subtitles" srclang="en" label="English" default> <track kind="subtitles" src="/subtitles" srclang="en" label="English" default>
<p>Your browser does not support the video tag.</p> <p>Your browser does not support the video tag.</p>
</video> </video>
</div>
<div class="subtitle-controls"> <div class="subtitle-controls">
<label for="subtitle-size">Subtitle Size: <span id="size-value">1.25em</span></label> <label for="subtitle-size">Subtitle Size: <span id="size-value">1.25em</span></label>
<input type="range" id="subtitle-size" min="0.8" max="2.5" step="0.05" value="1.25"> <input type="range" id="subtitle-size" min="0.8" max="2.5" step="0.05" value="1.25">

BIN
src/stars.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB