Skip to content

Commit

Permalink
Update JS deps
Browse files Browse the repository at this point in the history
  • Loading branch information
golles committed Oct 16, 2023
1 parent e70451c commit a15f8d9
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 70 deletions.
141 changes: 85 additions & 56 deletions www/video-rtc.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
* - ECMAScript 2017 (ES8) = ES6 + async
* - RTCPeerConnection for Safari iOS 11.0+
* - IntersectionObserver for Safari iOS 12.2+
* - ManagedMediaSource for Safari 17+
*
* Doesn't support:
* - MediaSource for Safari iOS
Expand Down Expand Up @@ -37,6 +38,12 @@ export class VideoRTC extends HTMLElement {
*/
this.mode = 'webrtc,mse,hls,mjpeg';

/**
* [Config] Requested medias (video, audio, microphone).
* @type {string}
*/
this.media = 'video,audio';

/**
* [config] Run stream when not displayed on the screen. Default `false`.
* @type {boolean}
Expand Down Expand Up @@ -128,8 +135,8 @@ export class VideoRTC extends HTMLElement {
this.ondata = null;

/**
* [internal] Handlers list for receiving JSON from WebSocket
* @type {Object.<string,Function>}}
* [internal] Handlers list for receiving JSON from WebSocket.
* @type {Object.<string,Function>}
*/
this.onmessage = null;
}
Expand Down Expand Up @@ -174,11 +181,11 @@ export class VideoRTC extends HTMLElement {
if (this.ws) this.ws.send(JSON.stringify(value));
}

codecs(type) {
const test = type === 'mse'
? codec => MediaSource.isTypeSupported(`video/mp4; codecs="${codec}"`)
: codec => this.video.canPlayType(`video/mp4; codecs="${codec}"`);
return this.CODECS.filter(test).join();
/** @param {Function} isSupported */
codecs(isSupported) {
return this.CODECS
.filter(codec => this.media.indexOf(codec.indexOf('vc1') > 0 ? 'video' : 'audio') >= 0)
.filter(codec => isSupported(`video/mp4; codecs="${codec}"`)).join();
}

/**
Expand Down Expand Up @@ -303,6 +310,9 @@ export class VideoRTC extends HTMLElement {

this.pcState = WebSocket.CLOSED;
if (this.pc) {
this.pc.getSenders().forEach(sender => {
if (sender.track) sender.track.stop();
});
this.pc.close();
this.pc = null;
}
Expand Down Expand Up @@ -334,7 +344,7 @@ export class VideoRTC extends HTMLElement {

const modes = [];

if (this.mode.indexOf('mse') >= 0 && 'MediaSource' in window) { // iPhone
if (this.mode.indexOf('mse') >= 0 && ('MediaSource' in window || 'ManagedMediaSource' in window)) {
modes.push('mse');
this.onmse();
} else if (this.mode.indexOf('hls') >= 0 && this.video.canPlayType('application/vnd.apple.mpegurl')) {
Expand All @@ -345,7 +355,7 @@ export class VideoRTC extends HTMLElement {
this.onmp4();
}

if (this.mode.indexOf('webrtc') >= 0 && 'RTCPeerConnection' in window) { // macOS Desktop app
if (this.mode.indexOf('webrtc') >= 0 && 'RTCPeerConnection' in window) {
modes.push('webrtc');
this.onwebrtc();
}
Expand Down Expand Up @@ -387,14 +397,30 @@ export class VideoRTC extends HTMLElement {
}

onmse() {
const ms = new MediaSource();
ms.addEventListener('sourceopen', () => {
URL.revokeObjectURL(this.video.src);
this.send({type: 'mse', value: this.codecs('mse')});
}, {once: true});
/** @type {MediaSource} */
let ms;

if ('ManagedMediaSource' in window) {
const MediaSource = window.ManagedMediaSource;

ms = new MediaSource();
ms.addEventListener('sourceopen', () => {
this.send({type: 'mse', value: this.codecs(MediaSource.isTypeSupported)});
}, {once: true});

this.video.disableRemotePlayback = true;
this.video.srcObject = ms;
} else {
ms = new MediaSource();
ms.addEventListener('sourceopen', () => {
URL.revokeObjectURL(this.video.src);
this.send({type: 'mse', value: this.codecs(MediaSource.isTypeSupported)});
}, {once: true});

this.video.src = URL.createObjectURL(ms);
this.video.srcObject = null;
}

this.video.src = URL.createObjectURL(ms);
this.video.srcObject = null;
this.play();

this.mseCodecs = '';
Expand Down Expand Up @@ -451,32 +477,21 @@ export class VideoRTC extends HTMLElement {
onwebrtc() {
const pc = new RTCPeerConnection(this.pcConfig);

/** @type {HTMLVideoElement} */
const video2 = document.createElement('video');
video2.addEventListener('loadeddata', ev => this.onpcvideo(ev), {once: true});

pc.addEventListener('icecandidate', ev => {
if (ev.candidate && this.mode.indexOf('webrtc/tcp') >= 0 && ev.candidate.protocol === 'udp') return;

const candidate = ev.candidate ? ev.candidate.toJSON().candidate : '';
this.send({type: 'webrtc/candidate', value: candidate});
});

pc.addEventListener('track', ev => {
// when stream already init
if (video2.srcObject !== null) return;

// when audio track not exist in Chrome
if (ev.streams.length === 0) return;

// when audio track not exist in Firefox
if (ev.streams[0].id[0] === '{') return;

video2.srcObject = ev.streams[0];
});

pc.addEventListener('connectionstatechange', () => {
if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') {
if (pc.connectionState === 'connected') {
const tracks = pc.getReceivers().map(receiver => receiver.track);
/** @type {HTMLVideoElement} */
const video2 = document.createElement('video');
video2.addEventListener('loadeddata', () => this.onpcvideo(video2), {once: true});
video2.srcObject = new MediaStream(tracks);
} else if (pc.connectionState === 'failed' || pc.connectionState === 'disconnected') {
pc.close(); // stop next events

this.pcState = WebSocket.CLOSED;
Expand Down Expand Up @@ -506,46 +521,60 @@ export class VideoRTC extends HTMLElement {
}
};

// Safari doesn't support "offerToReceiveVideo"
pc.addTransceiver('video', {direction: 'recvonly'});
pc.addTransceiver('audio', {direction: 'recvonly'});

pc.createOffer().then(offer => {
pc.setLocalDescription(offer).then(() => {
this.send({type: 'webrtc/offer', value: offer.sdp});
});
this.createOffer(pc).then(offer => {
this.send({type: 'webrtc/offer', value: offer.sdp});
});

this.pcState = WebSocket.CONNECTING;
this.pc = pc;
}

/**
* @param ev {Event}
* @param pc {RTCPeerConnection}
* @return {Promise<RTCSessionDescriptionInit>}
*/
onpcvideo(ev) {
if (!this.pc) return;
async createOffer(pc) {
try {
if (this.media.indexOf('microphone') >= 0) {
const media = await navigator.mediaDevices.getUserMedia({audio: true});
media.getTracks().forEach(track => {
pc.addTransceiver(track, {direction: 'sendonly'});
});
}
} catch (e) {
console.warn(e);
}

/** @type {HTMLVideoElement} */
const video2 = ev.target;
const state = this.pc.connectionState;
for (const kind of ['video', 'audio']) {
if (this.media.indexOf(kind) >= 0) {
pc.addTransceiver(kind, {direction: 'recvonly'});
}
}

const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
return offer;
}

// Firefox doesn't support pc.connectionState
if (state === 'connected' || state === 'connecting' || !state) {
/**
* @param video2 {HTMLVideoElement}
*/
onpcvideo(video2) {
if (this.pc) {
// Video+Audio > Video, H265 > H264, Video > Audio, WebRTC > MSE
let rtcPriority = 0, msePriority = 0;

/** @type {MediaStream} */
const ms = video2.srcObject;
if (ms.getVideoTracks().length > 0) rtcPriority += 0x220;
if (ms.getAudioTracks().length > 0) rtcPriority += 0x102;
const stream = video2.srcObject;
if (stream.getVideoTracks().length > 0) rtcPriority += 0x220;
if (stream.getAudioTracks().length > 0) rtcPriority += 0x102;

if (this.mseCodecs.indexOf('hvc1.') >= 0) msePriority += 0x230;
if (this.mseCodecs.indexOf('avc1.') >= 0) msePriority += 0x210;
if (this.mseCodecs.indexOf('mp4a.') >= 0) msePriority += 0x101;

if (rtcPriority >= msePriority) {
this.video.srcObject = ms;
this.video.srcObject = stream;
this.play();

this.pcState = WebSocket.OPEN;
Expand Down Expand Up @@ -586,7 +615,7 @@ export class VideoRTC extends HTMLElement {
this.play();
};

this.send({type: 'hls', value: this.codecs('hls')});
this.send({type: 'hls', value: this.codecs(type => this.video.canPlayType(type))});
}

onmp4() {
Expand Down Expand Up @@ -618,7 +647,7 @@ export class VideoRTC extends HTMLElement {
video2.src = 'data:video/mp4;base64,' + VideoRTC.btoa(data);
};

this.send({type: 'mp4', value: this.codecs('mp4')});
this.send({type: 'mp4', value: this.codecs(this.video.canPlayType)});
}

static btoa(buffer) {
Expand Down
27 changes: 13 additions & 14 deletions www/webrtc-camera.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/** Chrome 63+, Safari 11.1+ */
import {VideoRTC} from './video-rtc.js?v=1.6.2';
import {VideoRTC} from './video-rtc.js?v=1.8.0';
import {DigitalPTZ} from './digital-ptz.js?v=3.3.0';

class WebRTCCamera extends VideoRTC {
Expand All @@ -15,27 +15,19 @@ class WebRTCCamera extends VideoRTC {
if (config.intersection === 0) this.visibilityThreshold = 0;
else this.visibilityThreshold = config.intersection || 0.75;

/** @type {string} configMode */
this.configMode = config.mode
? config.mode
: config.mse === false
? 'webrtc'
: config.webrtc === false
? 'mse'
: this.mode;

/**
* @type {{
* url: string,
* entity: string,
* mode: string,
* server: string,
* media: string,
*
* streams: Array<{
* name: string,
* url: string,
* entity: string,
* mode: string
* mode: string,
* media: string,
* }>,
*
* title: string,
Expand All @@ -45,6 +37,8 @@ class WebRTCCamera extends VideoRTC {
* ui: boolean,
* style: string,
*
* server: string,
*
* mse: boolean,
* webrtc: boolean,
*
Expand All @@ -65,7 +59,10 @@ class WebRTCCamera extends VideoRTC {
* shortcuts:Array<{ name:string, icon:string }>,
* }} config
*/
this.config = Object.assign({}, config);
this.config = Object.assign({
mode: config.mse === false ? 'webrtc' : config.webrtc === false ? 'mse' : this.mode,
media: this.media,
}, config);

if (!this.config.streams) {
this.config.streams = [{url: config.url, entity: config.entity}];
Expand Down Expand Up @@ -107,10 +104,12 @@ class WebRTCCamera extends VideoRTC {
/** @param reload {boolean} */
nextStream(reload) {
this.streamID = (this.streamID + 1) % this.config.streams.length;

const stream = this.config.streams[this.streamID];
this.config.url = stream.url;
this.config.entity = stream.entity;
this.mode = stream.mode || this.configMode;
this.mode = stream.mode || this.config.mode;
this.media = stream.media || this.config.media;

if (reload) {
this.ondisconnect();
Expand Down

0 comments on commit a15f8d9

Please sign in to comment.