2022-11-02 12:36:09 +01:00
|
|
|
import { h } from 'preact';
|
|
|
|
import { baseUrl } from '../api/baseUrl';
|
|
|
|
import { useEffect } from 'preact/hooks';
|
|
|
|
|
|
|
|
export default function MsePlayer({ camera, width, height }) {
|
|
|
|
const url = `${baseUrl.replace(/^http/, 'ws')}live/mse/api/ws?src=${camera}`;
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const video = document.querySelector('#video');
|
|
|
|
|
|
|
|
// support api_path
|
|
|
|
const ws = new WebSocket(url);
|
|
|
|
ws.binaryType = 'arraybuffer';
|
2022-11-09 02:48:36 +01:00
|
|
|
let mediaSource,
|
|
|
|
sourceBuffer,
|
|
|
|
queueBuffer = [];
|
2022-11-02 12:36:09 +01:00
|
|
|
|
|
|
|
ws.onopen = () => {
|
|
|
|
mediaSource = new MediaSource();
|
|
|
|
video.src = URL.createObjectURL(mediaSource);
|
|
|
|
mediaSource.onsourceopen = () => {
|
|
|
|
mediaSource.onsourceopen = null;
|
|
|
|
URL.revokeObjectURL(video.src);
|
|
|
|
ws.send(JSON.stringify({ type: 'mse' }));
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
ws.onmessage = (ev) => {
|
|
|
|
if (typeof ev.data === 'string') {
|
|
|
|
const data = JSON.parse(ev.data);
|
|
|
|
|
|
|
|
if (data.type === 'mse') {
|
|
|
|
sourceBuffer = mediaSource.addSourceBuffer(data.value);
|
2022-11-09 02:48:36 +01:00
|
|
|
sourceBuffer.mode = 'segments'; // segments or sequence
|
2022-11-02 12:36:09 +01:00
|
|
|
sourceBuffer.onupdateend = () => {
|
|
|
|
if (!sourceBuffer.updating && queueBuffer.length > 0) {
|
2022-11-09 02:48:36 +01:00
|
|
|
try {
|
|
|
|
sourceBuffer.appendBuffer(queueBuffer.shift());
|
|
|
|
} catch (e) {
|
|
|
|
// console.warn(e);
|
|
|
|
}
|
2022-11-02 12:36:09 +01:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
2022-11-09 02:48:36 +01:00
|
|
|
} else if (sourceBuffer.updating || queueBuffer.length > 0) {
|
2022-11-02 12:36:09 +01:00
|
|
|
queueBuffer.push(ev.data);
|
|
|
|
} else {
|
2022-11-09 02:48:36 +01:00
|
|
|
try {
|
|
|
|
sourceBuffer.appendBuffer(ev.data);
|
|
|
|
} catch (e) {
|
|
|
|
// console.warn(e);
|
|
|
|
}
|
2022-11-02 12:36:09 +01:00
|
|
|
}
|
|
|
|
|
2022-11-09 02:48:36 +01:00
|
|
|
if (video.seekable.length > 0) {
|
|
|
|
const delay = video.seekable.end(video.seekable.length - 1) - video.currentTime;
|
|
|
|
if (delay < 1) {
|
|
|
|
video.playbackRate = 1;
|
|
|
|
} else if (delay > 10) {
|
|
|
|
video.playbackRate = 10;
|
|
|
|
} else if (delay > 2) {
|
|
|
|
video.playbackRate = Math.floor(delay);
|
|
|
|
}
|
2022-11-02 12:36:09 +01:00
|
|
|
}
|
|
|
|
};
|
2022-11-09 02:48:36 +01:00
|
|
|
|
2022-12-18 00:56:26 +01:00
|
|
|
return () => {
|
|
|
|
const video = document.getElementById('video');
|
|
|
|
video.srcObject = null;
|
2022-11-09 02:48:36 +01:00
|
|
|
ws.close();
|
2022-12-18 00:56:26 +01:00
|
|
|
};
|
2022-11-02 12:36:09 +01:00
|
|
|
}, [url]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div>
|
|
|
|
<video id="video" autoplay playsinline controls muted width={width} height={height} />
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|