working version
This commit is contained in:
@ -3,9 +3,9 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Beacon Tracker - Live Stream (FastAPI)</title>
|
||||
<!-- JSMpeg for H.264/MPEG-TS decoding -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/jsmpeg@0.1.0/jsmpeg.min.js"></script>
|
||||
<title>Beacon Tracker - Live Stream (HLS)</title>
|
||||
<!-- HLS.js for H.264 HLS decoding -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
@ -92,12 +92,20 @@
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
#videoFrame, #videoCanvas {
|
||||
#videoFrame {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
}
|
||||
|
||||
#videoPlayer {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
display: block;
|
||||
background: #000;
|
||||
min-height: 480px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
@ -276,24 +284,14 @@
|
||||
</header>
|
||||
|
||||
<div class="main-content">
|
||||
<div class="stream-selector">
|
||||
<span style="font-weight: 600;">Выбрать метод передачи:</span>
|
||||
<button id="btnWebSocket" onclick="switchToWebSocket()" class="active">
|
||||
WebSocket (H.264) <span class="perf-badge websocket">Быстрее</span>
|
||||
</button>
|
||||
<button id="btnSSE" onclick="switchToSSE()">
|
||||
SSE (JPEG) <span class="perf-badge sse">Совместимость</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="video-container">
|
||||
<!-- Canvas for WebSocket/JSMpeg streaming -->
|
||||
<canvas id="videoCanvas"></canvas>
|
||||
<!-- Image for SSE/JPEG streaming -->
|
||||
<!-- HTML5 video element for HLS playback -->
|
||||
<video id="videoPlayer" controls autoplay muted playsinline></video>
|
||||
<!-- Image for SSE/JPEG streaming (fallback) -->
|
||||
<img id="videoFrame" class="hidden" alt="Video stream">
|
||||
<div class="loading-overlay" id="loadingOverlay">
|
||||
<div class="spinner"></div>
|
||||
<p>Ожидание данных...</p>
|
||||
<p>Ожидание HLS потока...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -326,21 +324,21 @@
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Stream mode: 'websocket' or 'sse'
|
||||
let streamMode = 'websocket';
|
||||
// Stream mode: 'hls' or 'sse'
|
||||
let streamMode = 'hls';
|
||||
|
||||
// SSE variables
|
||||
// SSE variables (fallback)
|
||||
let eventSource = null;
|
||||
let sseFrameCount = 0;
|
||||
let sseLastFrameTime = Date.now();
|
||||
let sseTotalBytes = 0;
|
||||
let sseLastBitrateCalc = Date.now();
|
||||
|
||||
// WebSocket variables
|
||||
let websocket = null;
|
||||
let player = null;
|
||||
let wsFrameCount = 0;
|
||||
let wsLastFrameTime = Date.now();
|
||||
// HLS variables
|
||||
let hls = null;
|
||||
let video = null;
|
||||
let hlsFrameCount = 0;
|
||||
let hlsLastFrameTime = Date.now();
|
||||
let reconnectAttempts = 0;
|
||||
const MAX_RECONNECT_ATTEMPTS = 5;
|
||||
|
||||
@ -357,124 +355,106 @@
|
||||
}
|
||||
}
|
||||
|
||||
function switchToWebSocket() {
|
||||
if (streamMode === 'websocket') return;
|
||||
|
||||
streamMode = 'websocket';
|
||||
document.getElementById('btnWebSocket').classList.add('active');
|
||||
document.getElementById('btnSSE').classList.remove('active');
|
||||
|
||||
disconnectSSE();
|
||||
connectWebSocket();
|
||||
}
|
||||
|
||||
function switchToSSE() {
|
||||
if (streamMode === 'sse') return;
|
||||
|
||||
streamMode = 'sse';
|
||||
document.getElementById('btnSSE').classList.add('active');
|
||||
document.getElementById('btnWebSocket').classList.remove('active');
|
||||
|
||||
disconnectWebSocket();
|
||||
connectSSE();
|
||||
}
|
||||
|
||||
function connectWebSocket() {
|
||||
document.getElementById('streamMethod').textContent = 'WebSocket (H.264)';
|
||||
document.getElementById('videoCanvas').classList.remove('hidden');
|
||||
function connectHLS() {
|
||||
document.getElementById('streamMethod').textContent = 'HLS (H.264)';
|
||||
document.getElementById('videoPlayer').classList.remove('hidden');
|
||||
document.getElementById('videoFrame').classList.add('hidden');
|
||||
|
||||
console.log('Connecting to WebSocket video stream...');
|
||||
console.log('Connecting to HLS video stream...');
|
||||
|
||||
// Build WebSocket URL
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const wsUrl = `${protocol}//${window.location.host}/ws/video`;
|
||||
video = document.getElementById('videoPlayer');
|
||||
const hlsUrl = `${window.location.protocol}//${window.location.host}/hls/playlist.m3u8`;
|
||||
|
||||
// Connect to native WebSocket
|
||||
websocket = new WebSocket(wsUrl);
|
||||
websocket.binaryType = 'arraybuffer';
|
||||
if (Hls.isSupported()) {
|
||||
hls = new Hls({
|
||||
// Low latency configuration
|
||||
lowLatencyMode: true,
|
||||
backBufferLength: 90,
|
||||
maxBufferLength: 3,
|
||||
maxBufferSize: 1 * 1024 * 1024, // 1MB
|
||||
liveSyncDurationCount: 1,
|
||||
liveMaxLatencyDurationCount: 2,
|
||||
enableWorker: true,
|
||||
debug: false
|
||||
});
|
||||
|
||||
websocket.onopen = () => {
|
||||
console.log('WebSocket connected');
|
||||
updateConnectionStatus(true);
|
||||
hideError();
|
||||
reconnectAttempts = 0;
|
||||
hls.loadSource(hlsUrl);
|
||||
hls.attachMedia(video);
|
||||
|
||||
// Initialize JSMpeg player
|
||||
const canvas = document.getElementById('videoCanvas');
|
||||
player = new JSMpeg.Player(null, {
|
||||
canvas: canvas,
|
||||
disableGl: false,
|
||||
disableWebAssembly: false,
|
||||
preserveDrawingBuffer: false,
|
||||
progressive: true,
|
||||
throttled: true,
|
||||
chunkSize: 1024 * 32,
|
||||
onVideoDecode: (decoder, time) => {
|
||||
// Update FPS counter
|
||||
const now = Date.now();
|
||||
const timeDiff = (now - wsLastFrameTime) / 1000;
|
||||
if (timeDiff > 0.1) { // Update every 100ms
|
||||
fps = Math.round(1 / timeDiff);
|
||||
document.getElementById('fpsCounter').textContent = fps;
|
||||
wsFrameCount++;
|
||||
document.getElementById('frameCounter').textContent = wsFrameCount;
|
||||
hls.on(Hls.Events.MANIFEST_PARSED, function() {
|
||||
console.log('HLS manifest parsed, starting playback...');
|
||||
video.play().catch(e => {
|
||||
console.warn('Autoplay prevented, waiting for user interaction:', e);
|
||||
});
|
||||
updateConnectionStatus(true);
|
||||
hideError();
|
||||
});
|
||||
|
||||
hls.on(Hls.Events.ERROR, function(event, data) {
|
||||
console.error('HLS error:', data.type, data.details);
|
||||
if (data.fatal) {
|
||||
switch(data.type) {
|
||||
case Hls.ErrorTypes.NETWORK_ERROR:
|
||||
console.log('Network error, attempting to recover...');
|
||||
hls.startLoad();
|
||||
break;
|
||||
case Hls.ErrorTypes.MEDIA_ERROR:
|
||||
console.log('Media error, attempting to recover...');
|
||||
hls.recoverMediaError();
|
||||
break;
|
||||
default:
|
||||
console.error('Fatal error, cannot recover');
|
||||
updateConnectionStatus(false);
|
||||
showError('Ошибка HLS потока: ' + data.details);
|
||||
break;
|
||||
}
|
||||
wsLastFrameTime = now;
|
||||
|
||||
// Update resolution
|
||||
if (decoder.width && decoder.height) {
|
||||
document.getElementById('resolution').textContent =
|
||||
`${decoder.width}×${decoder.height}`;
|
||||
}
|
||||
|
||||
// Hide loading overlay on first frame
|
||||
document.getElementById('loadingOverlay').classList.add('hidden');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
websocket.onmessage = (event) => {
|
||||
if (player && event.data instanceof ArrayBuffer) {
|
||||
const uint8Array = new Uint8Array(event.data);
|
||||
// Hide loading overlay when playback starts
|
||||
video.addEventListener('playing', () => {
|
||||
console.log('Video playback started');
|
||||
document.getElementById('loadingOverlay').classList.add('hidden');
|
||||
updateConnectionStatus(true);
|
||||
});
|
||||
|
||||
if (!player.source) {
|
||||
// Create source buffer if needed
|
||||
player.source = {
|
||||
write: function(data) {
|
||||
if (player.demuxer && player.demuxer.write) {
|
||||
player.demuxer.write(data);
|
||||
}
|
||||
}
|
||||
};
|
||||
// Track video stats
|
||||
video.addEventListener('timeupdate', () => {
|
||||
const now = Date.now();
|
||||
const timeDiff = (now - hlsLastFrameTime) / 1000;
|
||||
if (timeDiff > 0.5) { // Update every 500ms
|
||||
// Estimate FPS from video framerate
|
||||
if (video.videoWidth && video.videoHeight) {
|
||||
document.getElementById('resolution').textContent =
|
||||
`${video.videoWidth}×${video.videoHeight}`;
|
||||
}
|
||||
|
||||
// Calculate approximate FPS
|
||||
fps = hls.media ? Math.round(1 / timeDiff * 10) : 0;
|
||||
document.getElementById('fpsCounter').textContent = fps;
|
||||
hlsFrameCount++;
|
||||
document.getElementById('frameCounter').textContent = hlsFrameCount;
|
||||
|
||||
hlsLastFrameTime = now;
|
||||
}
|
||||
});
|
||||
|
||||
// Feed data to JSMpeg
|
||||
if (player.demuxer && player.demuxer.write) {
|
||||
player.demuxer.write(uint8Array);
|
||||
}
|
||||
}
|
||||
};
|
||||
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
|
||||
// Native HLS support (Safari)
|
||||
console.log('Using native HLS support');
|
||||
video.src = hlsUrl;
|
||||
video.addEventListener('loadedmetadata', function() {
|
||||
console.log('HLS metadata loaded');
|
||||
video.play();
|
||||
});
|
||||
|
||||
websocket.onerror = (error) => {
|
||||
console.error('WebSocket error:', error);
|
||||
updateConnectionStatus(false);
|
||||
showError('Ошибка WebSocket соединения');
|
||||
};
|
||||
|
||||
websocket.onclose = () => {
|
||||
console.log('WebSocket disconnected');
|
||||
updateConnectionStatus(false);
|
||||
|
||||
// Auto-reconnect
|
||||
if (streamMode === 'websocket' && reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
|
||||
reconnectAttempts++;
|
||||
console.log(`Attempting to reconnect (${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})...`);
|
||||
setTimeout(connectWebSocket, 2000);
|
||||
} else if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
|
||||
showError('Потеряно соединение. Нажмите "Переподключиться"');
|
||||
}
|
||||
};
|
||||
video.addEventListener('playing', () => {
|
||||
document.getElementById('loadingOverlay').classList.add('hidden');
|
||||
updateConnectionStatus(true);
|
||||
});
|
||||
} else {
|
||||
showError('HLS не поддерживается в этом браузере');
|
||||
}
|
||||
|
||||
// Start memory monitoring
|
||||
if (!statsInterval) {
|
||||
@ -482,25 +462,16 @@
|
||||
updateMemoryUsage();
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// Send periodic ping to keep connection alive
|
||||
const pingInterval = setInterval(() => {
|
||||
if (websocket && websocket.readyState === WebSocket.OPEN) {
|
||||
websocket.send('ping');
|
||||
} else {
|
||||
clearInterval(pingInterval);
|
||||
}
|
||||
}, 30000); // Every 30 seconds
|
||||
}
|
||||
|
||||
function disconnectWebSocket() {
|
||||
if (websocket) {
|
||||
websocket.close();
|
||||
websocket = null;
|
||||
function disconnectHLS() {
|
||||
if (hls) {
|
||||
hls.destroy();
|
||||
hls = null;
|
||||
}
|
||||
if (player) {
|
||||
player.destroy();
|
||||
player = null;
|
||||
if (video) {
|
||||
video.pause();
|
||||
video.src = '';
|
||||
}
|
||||
if (statsInterval) {
|
||||
clearInterval(statsInterval);
|
||||
@ -510,7 +481,7 @@
|
||||
|
||||
function connectSSE() {
|
||||
document.getElementById('streamMethod').textContent = 'SSE (JPEG)';
|
||||
document.getElementById('videoCanvas').classList.add('hidden');
|
||||
document.getElementById('videoPlayer').classList.add('hidden');
|
||||
document.getElementById('videoFrame').classList.remove('hidden');
|
||||
|
||||
if (eventSource) {
|
||||
@ -635,9 +606,9 @@
|
||||
function reconnect() {
|
||||
document.getElementById('loadingOverlay').classList.remove('hidden');
|
||||
reconnectAttempts = 0;
|
||||
if (streamMode === 'websocket') {
|
||||
disconnectWebSocket();
|
||||
connectWebSocket();
|
||||
if (streamMode === 'hls') {
|
||||
disconnectHLS();
|
||||
connectHLS();
|
||||
} else {
|
||||
disconnectSSE();
|
||||
connectSSE();
|
||||
@ -647,8 +618,13 @@
|
||||
function takeScreenshot() {
|
||||
let dataUrl;
|
||||
|
||||
if (streamMode === 'websocket') {
|
||||
const canvas = document.getElementById('videoCanvas');
|
||||
if (streamMode === 'hls') {
|
||||
// Capture current frame from video element
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||||
dataUrl = canvas.toDataURL('image/jpeg', 0.95);
|
||||
} else {
|
||||
const img = document.getElementById('videoFrame');
|
||||
@ -661,16 +637,16 @@
|
||||
link.click();
|
||||
}
|
||||
|
||||
// Connect on page load with default WebSocket mode
|
||||
if (streamMode === 'websocket') {
|
||||
connectWebSocket();
|
||||
// Connect on page load with default HLS mode
|
||||
if (streamMode === 'hls') {
|
||||
connectHLS();
|
||||
} else {
|
||||
connectSSE();
|
||||
}
|
||||
|
||||
// Cleanup on page unload
|
||||
window.addEventListener('beforeunload', () => {
|
||||
disconnectWebSocket();
|
||||
disconnectHLS();
|
||||
disconnectSSE();
|
||||
});
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user