diff --git a/go2rtc/Chart.yaml b/go2rtc/Chart.yaml index 43de19a..5409e82 100644 --- a/go2rtc/Chart.yaml +++ b/go2rtc/Chart.yaml @@ -6,7 +6,7 @@ description: >- chart appVersion, which scripts/update-charts.sh bumps from AlexxIT/go2rtc releases through the annotation below. type: application -version: 0.1.1 +version: 0.1.2 appVersion: "1.9.15" annotations: version-source: github-release:AlexxIT/go2rtc diff --git a/go2rtc/templates/deployment.yaml b/go2rtc/templates/deployment.yaml index 0c4cccd..37dd1c1 100644 --- a/go2rtc/templates/deployment.yaml +++ b/go2rtc/templates/deployment.yaml @@ -23,6 +23,9 @@ spec: app: {{ .Release.Name }} annotations: checksum/config: {{ .Values.config | sha256sum }} + {{- if .Values.customWww.enabled }} + checksum/www: {{ (.Files.Glob "www/*").AsConfig | sha256sum }} + {{- end }} spec: {{- if .Values.hostNetwork }} hostNetwork: true @@ -115,6 +118,11 @@ spec: - name: config mountPath: /config readOnly: true + {{- if .Values.customWww.enabled }} + - name: www + mountPath: /www + readOnly: true + {{- end }} {{- if .Values.persistence.enabled }} - name: data mountPath: /data @@ -123,6 +131,11 @@ spec: - name: config configMap: name: {{ .Release.Name }}-config + {{- if .Values.customWww.enabled }} + - name: www + configMap: + name: {{ .Release.Name }}-www + {{- end }} {{- if .Values.persistence.enabled }} - name: data persistentVolumeClaim: diff --git a/go2rtc/templates/www-configmap.yaml b/go2rtc/templates/www-configmap.yaml new file mode 100644 index 0000000..49599a0 --- /dev/null +++ b/go2rtc/templates/www-configmap.yaml @@ -0,0 +1,11 @@ +{{- if .Values.customWww.enabled }} +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ .Release.Name }}-www + labels: + app.kubernetes.io/name: {{ .Chart.Name }} + app.kubernetes.io/instance: {{ .Release.Name }} +data: + {{- (.Files.Glob "www/*").AsConfig | nindent 2 }} +{{- end }} diff --git a/go2rtc/values.yaml b/go2rtc/values.yaml index 952d074..3b1060a 100644 --- a/go2rtc/values.yaml +++ b/go2rtc/values.yaml @@ -29,6 +29,14 @@ config: | listen: ":1984" streams: {} +# Patched copy of the go2rtc web UI (www/ in this chart, taken from the release +# in www/VERSION). It hides the mode label (RTC, MSE) in the video corner. +# It is mounted at /www. Set `api.static_dir: /www` in `config` to use it. +# When appVersion changes, refresh www/ from the same tag of AlexxIT/go2rtc and +# apply the small patch in www/video-stream.js again. +customWww: + enabled: true + # Existing Secret. Every key becomes an environment variable of the container. existingSecret: "" diff --git a/go2rtc/www/VERSION b/go2rtc/www/VERSION new file mode 100644 index 0000000..1bcb9da --- /dev/null +++ b/go2rtc/www/VERSION @@ -0,0 +1 @@ +1.9.15 diff --git a/go2rtc/www/add.html b/go2rtc/www/add.html new file mode 100644 index 0000000..a2e0d85 --- /dev/null +++ b/go2rtc/www/add.html @@ -0,0 +1,569 @@ + + + + + + add - go2rtc + + + + + + + + +
+ +
+
+ + + +
+
+ + + + +
+
+
+ + + + +
+
+ + + + +
+
+ + +
+
+
+ + + + +
+
+
+ + + + +
+
+
+ + + + +
+
+
+ + + + +
+
+ + + + + +
+
+
+ + + +
+
+
+ + + + +
+
+
+ + + + +
+
+ + +
+
+
+ + + + +
+
+ + + + +
+
+ + +
+
+
+ + + + +
+
+ + + + +
+
+
+ + + + +
+
+ + + +
+ +
+
+ + + + +
+
+
+ + + + +
+

+ API Key required: Get your API Key +

+
+ + + + + +
+
+ + +
+
+
+ + + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+
+ + + + +
+
+
+ +
+ + + \ No newline at end of file diff --git a/go2rtc/www/config.html b/go2rtc/www/config.html new file mode 100644 index 0000000..026b5be --- /dev/null +++ b/go2rtc/www/config.html @@ -0,0 +1,1230 @@ + + + + + + config - go2rtc + + + + + + +
+
+ + +
+
+
+ + + + + + + diff --git a/go2rtc/www/hls.html b/go2rtc/www/hls.html new file mode 100644 index 0000000..70f5cdc --- /dev/null +++ b/go2rtc/www/hls.html @@ -0,0 +1,37 @@ + + + + + hls - go2rtc + + + + + + + + \ No newline at end of file diff --git a/go2rtc/www/index.html b/go2rtc/www/index.html new file mode 100644 index 0000000..69126e6 --- /dev/null +++ b/go2rtc/www/index.html @@ -0,0 +1,157 @@ + + + + + + go2rtc + + + + + + +
+
+ + modes + + + + +
+ + + + + + + + + + +
onlinecommands
+
+
+ + + + + diff --git a/go2rtc/www/links.html b/go2rtc/www/links.html new file mode 100644 index 0000000..13e08ed --- /dev/null +++ b/go2rtc/www/links.html @@ -0,0 +1,268 @@ + + + + + + links - go2rtc + + + + + + +
+ + + + + + +
+

Play audio

+ + + +
+ + + / cameras with two way audio support +
+ + +
+

Publish stream

+
YouTube:  rtmps://xxx.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx
+Telegram: rtmps://xxx-x.rtmp.t.me/s/xxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxx
+ + + / Telegram RTMPS server +
+ + +
+

WebRTC Magic

+ + + + + +
+
  • webrtc.html local WebRTC viewer
  • + +
  • + share link + copy link + delete + external WebRTC viewer +
  • +
    + +
    + + + diff --git a/go2rtc/www/log.html b/go2rtc/www/log.html new file mode 100644 index 0000000..5809c45 --- /dev/null +++ b/go2rtc/www/log.html @@ -0,0 +1,145 @@ + + + + + + log - go2rtc + + + + + + +
    +
    + + + +
    + + + + + + + + + + +
    TimeLevelMessage
    +
    + + + + + diff --git a/go2rtc/www/main.js b/go2rtc/www/main.js new file mode 100644 index 0000000..d562917 --- /dev/null +++ b/go2rtc/www/main.js @@ -0,0 +1,135 @@ +document.head.innerHTML += ` + +`; + +document.body.innerHTML = ` +
    + +
    +` + document.body.innerHTML; diff --git a/go2rtc/www/net.html b/go2rtc/www/net.html new file mode 100644 index 0000000..1c2a697 --- /dev/null +++ b/go2rtc/www/net.html @@ -0,0 +1,74 @@ + + + + + + net - go2rtc + + + + + + + +
    + + + + + diff --git a/go2rtc/www/schema.json b/go2rtc/www/schema.json new file mode 100644 index 0000000..27fee57 --- /dev/null +++ b/go2rtc/www/schema.json @@ -0,0 +1,750 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "go2rtc", + "type": "object", + "additionalProperties": false, + "definitions": { + "listen": { + "type": "string", + "anyOf": [ + { + "type": "string", + "pattern": ":[0-9]{1,5}$" + }, + { + "type": "string", + "const": "" + } + ] + }, + "log_level": { + "type": "string", + "enum": [ + "trace", + "debug", + "info", + "warn", + "error", + "fatal", + "panic", + "disabled" + ] + }, + "source": { + "type": "string", + "examples": [ + "rtsp://username:password@192.168.1.123/cam/realmonitor?channel=1&subtype=0&unicast=true&proto=Onvif", + "rtsp://username:password@192.168.1.123/stream1", + "rtsp://username:password@192.168.1.123/h264Preview_01_main", + "rtmp://192.168.1.123/bcs/channel0_main.bcs?channel=0&stream=0&user=username&password=password", + "http://192.168.1.123/flv?port=1935&app=bcs&stream=channel0_main.bcs&user=username&password=password", + "http://username:password@192.168.1.123/cgi-bin/snapshot.cgi?channel=1", + "ffmpeg:media.mp4#video=h264#hardware#width=1920#height=1080#rotate=180#audio=copy", + "ffmpeg:virtual?video=testsrc&size=4K#video=h264#hardware#bitrate=50M", + "exec:ffmpeg -re -i media.mp4 -c copy -rtsp_transport tcp -f rtsp {output}", + "onvif://username:password@192.168.1.123:80?subtype=0", + "tapo://password@192.168.1.123:8800?channel=0&subtype=0" + ] + } + }, + "properties": { + "api": { + "type": "object", + "properties": { + "listen": { + "type": "string", + "default": ":1984", + "examples": [ + "127.0.0.1:1984" + ] + }, + "username": { + "description": "Basic auth for WebUI", + "type": "string", + "examples": [ + "admin" + ] + }, + "password": { + "type": "string" + }, + "local_auth": { + "description": "Enable auth check for localhost requests", + "type": "boolean", + "default": false + }, + "base_path": { + "description": "API prefix for serving on suburl (/api => /rtc/api)", + "type": "string", + "examples": [ + "/rtc" + ] + }, + "static_dir": { + "description": "Folder for static files (custom web interface)", + "type": "string", + "examples": [ + "www" + ] + }, + "origin": { + "description": "Allow CORS requests (only * supported)", + "type": "string", + "enum": [ + "*", + "" + ] + }, + "tls_listen": { + "type": "string" + }, + "tls_cert": { + "type": "string", + "examples": [ + "-----BEGIN CERTIFICATE-----", + "/ssl/fullchain.pem" + ] + }, + "tls_key": { + "type": "string", + "examples": [ + "-----BEGIN PRIVATE KEY-----", + "/ssl/privkey.pem" + ] + }, + "unix_listen": { + "type": "string", + "examples": [ + "/tmp/go2rtc.sock" + ] + }, + "allow_paths": { + "description": "Allow only these HTTP paths (full paths, including base_path)", + "type": "array", + "items": { + "type": "string" + }, + "examples": [ + [ + "/api", + "/api/streams", + "/api/webrtc" + ] + ] + } + } + }, + "app": { + "type": "object", + "properties": { + "modules": { + "description": "Enable only these modules (empty / omitted means all)", + "type": "array", + "items": { + "type": "string", + "enum": [ + "api", + "ws", + "http", + "rtsp", + "webrtc", + "mp4", + "hls", + "mjpeg", + "hass", + "homekit", + "onvif", + "rtmp", + "webtorrent", + "wyoming", + "echo", + "exec", + "expr", + "ffmpeg", + "alsa", + "v4l2", + "bubble", + "doorbird", + "dvrip", + "eseecloud", + "flussonic", + "gopro", + "isapi", + "ivideon", + "kasa", + "mpeg", + "nest", + "ring", + "roborock", + "tapo", + "tuya", + "xiaomi", + "yandex", + "debug", + "ngrok", + "pinggy", + "srtp" + ] + } + } + } + }, + "env": { + "description": "Config variables that can be referenced as ${NAME} / ${NAME:default}", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "echo": { + "type": "object", + "properties": { + "allow_paths": { + "description": "Allow only these binaries for echo: URLs (exact cmd name/path)", + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "exec": { + "type": "object", + "properties": { + "allow_paths": { + "description": "Allow only these binaries for exec: URLs (exact cmd name/path)", + "type": "array", + "items": { + "type": "string" + }, + "examples": [ + [ + "ffmpeg", + "/usr/bin/ffmpeg" + ] + ] + } + } + }, + "ffmpeg": { + "type": "object", + "properties": { + "bin": { + "type": "string", + "default": "ffmpeg" + }, + "global": { + "type": "string", + "default": "-hide_banner" + }, + "file": { + "type": "string", + "default": "-re -i {input}" + }, + "http": { + "type": "string", + "default": "-fflags nobuffer -flags low_delay -i {input}" + }, + "rtsp": { + "type": "string", + "default": "-fflags nobuffer -flags low_delay -timeout 5000000 -user_agent go2rtc/ffmpeg -rtsp_flags prefer_tcp -i {input}" + }, + "rtsp/udp": { + "type": "string", + "default": "-fflags nobuffer -flags low_delay -timeout 5000000 -user_agent go2rtc/ffmpeg -i {input}" + } + }, + "additionalProperties": { + "description": "FFmpeg template", + "type": "string" + } + }, + "hass": { + "type": "object", + "properties": { + "config": { + "description": "Home Assistant config directory path", + "type": "string", + "examples": [ + "/config" + ] + } + } + }, + "homekit": { + "type": "object", + "additionalProperties": { + "type": [ + "object", + "null" + ], + "properties": { + "pin": { + "description": "HomeKit pairing PIN", + "type": "string", + "default": "19550224", + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9]{8}$" + }, + { + "type": "string", + "pattern": "^[0-9]{3}-[0-9]{2}-[0-9]{3}$" + } + ] + }, + "name": { + "type": "string" + }, + "device_id": { + "type": "string" + }, + "device_private": { + "type": "string" + }, + "category_id": { + "description": "Accessory category: `bridge`, `doorbell` or numeric ID", + "type": "string", + "default": "camera", + "anyOf": [ + { + "type": "string", + "enum": [ + "bridge", + "camera", + "doorbell" + ] + }, + { + "type": "string", + "pattern": "^[0-9]+$" + }, + { + "type": "string", + "const": "" + } + ] + }, + "pairings": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + }, + "log": { + "type": "object", + "properties": { + "format": { + "description": "Log format: color/json/text or empty for autodetect", + "type": "string", + "default": "color", + "enum": [ + "", + "color", + "json", + "text" + ] + }, + "level": { + "description": "Defaul log level", + "default": "info", + "$ref": "#/definitions/log_level" + }, + "output": { + "description": "Log output: stdout/stderr/file[:path] or empty (memory only)", + "type": "string", + "default": "stdout", + "anyOf": [ + { + "type": "string", + "enum": [ + "", + "stdout", + "stderr" + ] + }, + { + "type": "string", + "pattern": "^file(:.+)?$", + "examples": [ + "file", + "file:go2rtc.log" + ] + } + ] + }, + "time": { + "type": "string", + "default": "UNIXMS", + "anyOf": [ + { + "type": "string", + "enum": [ + "", + "UNIXMS", + "UNIXMICRO", + "UNIXNANO", + "2006-01-02T15:04:05Z07:00", + "2006-01-02T15:04:05.999999999Z07:00" + ] + }, + { + "type": "string" + } + ] + }, + "api": { + "$ref": "#/definitions/log_level" + }, + "echo": { + "$ref": "#/definitions/log_level" + }, + "exec": { + "description": "Value `exec: debug` will print stderr", + "$ref": "#/definitions/log_level" + }, + "expr": { + "$ref": "#/definitions/log_level" + }, + "ffmpeg": { + "description": "Will only be displayed with `exec: debug` setting", + "default": "error", + "$ref": "#/definitions/log_level" + }, + "hass": { + "$ref": "#/definitions/log_level" + }, + "hls": { + "$ref": "#/definitions/log_level" + }, + "homekit": { + "$ref": "#/definitions/log_level" + }, + "mjpeg": { + "$ref": "#/definitions/log_level" + }, + "mp4": { + "$ref": "#/definitions/log_level" + }, + "ngrok": { + "$ref": "#/definitions/log_level" + }, + "onvif": { + "$ref": "#/definitions/log_level" + }, + "rtmp": { + "$ref": "#/definitions/log_level" + }, + "rtsp": { + "$ref": "#/definitions/log_level" + }, + "streams": { + "$ref": "#/definitions/log_level" + }, + "webrtc": { + "$ref": "#/definitions/log_level" + }, + "webtorrent": { + "$ref": "#/definitions/log_level" + }, + "wyoming": { + "$ref": "#/definitions/log_level" + } + } + }, + "ngrok": { + "type": "object", + "properties": { + "command": { + "type": "string", + "examples": [ + "ngrok tcp 8555 --authtoken xxx", + "ngrok start --all --config ngrok.yaml" + ] + } + } + }, + "pinggy": { + "type": "object", + "properties": { + "tunnel": { + "description": "Expose local address via Pinggy", + "type": "string", + "examples": [ + "http://127.0.0.1:1984", + "tcp://192.168.1.123:554" + ] + } + } + }, + "preload": { + "description": "Preload streams on startup (map stream name => probe query, default `video&audio`)", + "type": "object", + "additionalProperties": { + "type": "string", + "examples": [ + "video&audio", + "video" + ] + } + }, + "publish": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "string", + "examples": [ + "rtmp://xxx.rtmp.youtube.com/live2/xxxx-xxxx-xxxx-xxxx-xxxx", + "rtmps://xxx-x.rtmp.t.me/s/xxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxx" + ] + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + }, + "rtmp": { + "type": "object", + "properties": { + "listen": { + "type": "string", + "examples": [ + ":1935" + ] + } + } + }, + "rtsp": { + "type": "object", + "properties": { + "listen": { + "type": "string", + "default": ":8554" + }, + "username": { + "type": "string", + "examples": [ + "admin" + ] + }, + "password": { + "type": "string" + }, + "default_query": { + "type": "string", + "default": "video&audio" + }, + "pkt_size": { + "type": "integer" + } + } + }, + "srtp": { + "description": "SRTP server for HomeKit", + "type": "object", + "properties": { + "listen": { + "type": "string", + "default": ":8443" + } + } + }, + "streams": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "$ref": "#/definitions/source" + }, + { + "type": "array", + "items": { + "$ref": "#/definitions/source" + } + }, + { + "type": "null" + } + ] + } + }, + "xiaomi": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "webrtc": { + "type": "object", + "properties": { + "listen": { + "type": "string", + "default": ":8555", + "examples": [ + ":8555/udp" + ] + }, + "candidates": { + "type": "array", + "items": { + "type": "string", + "examples": [ + "216.58.210.174:8555", + "stun:8555", + "home.duckdns.org:8555" + ] + } + }, + "ice_servers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "urls": { + "type": "array", + "items": { + "type": "string", + "examples": [ + "stun:stun.l.google.com:19302", + "turn:123.123.123.123:3478" + ] + } + }, + "username": { + "type": "string" + }, + "credential": { + "type": "string" + } + } + } + }, + "filters": { + "type": "object", + "properties": { + "candidates": { + "description": "Keep only these candidates", + "type": "array", + "items": { + "type": "string" + } + }, + "interfaces": { + "description": "Keep only these interfaces", + "type": "array", + "items": { + "type": "string" + } + }, + "ips": { + "description": "Keep only these IP-addresses", + "type": "array", + "items": { + "type": "string" + } + }, + "networks": { + "description": "Use only these network types", + "type": "array", + "items": { + "type": "string", + "enum": [ + "tcp4", + "tcp6", + "udp4", + "udp6" + ] + } + }, + "udp_ports": { + "description": "Use only these UDP ports range [min, max]", + "type": "array", + "items": { + "type": "integer" + }, + "maxItems": 2, + "minItems": 2 + } + } + } + } + }, + "webtorrent": { + "type": "object", + "properties": { + "trackers": { + "type": "array", + "items": { + "type": "string" + } + }, + "shares": { + "additionalProperties": { + "type": "object", + "properties": { + "pwd": { + "type": "string", + "minLength": 4 + }, + "src": { + "type": "string" + } + } + } + } + } + }, + "wyoming": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "listen": { + "description": "Listen address for Wyoming server", + "type": "string" + }, + "name": { + "description": "Optional satellite name (default: stream name)", + "type": "string" + }, + "mode": { + "description": "Optional mode: mic / snd / default", + "type": "string", + "enum": [ + "", + "mic", + "snd" + ] + }, + "event": { + "description": "Event handlers (map event type => expr script)", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "wake_uri": { + "description": "Optional WAKE service URI (ex. tcp://host:port?name=...)", + "type": "string", + "examples": [ + "tcp://192.168.1.23:10400" + ] + }, + "vad_threshold": { + "description": "Optional VAD threshold (0.1..3.5 typical)", + "type": "number" + } + } + } + } + } +} diff --git a/go2rtc/www/stream.html b/go2rtc/www/stream.html new file mode 100644 index 0000000..de7ad12 --- /dev/null +++ b/go2rtc/www/stream.html @@ -0,0 +1,67 @@ + + + + + + + + stream - go2rtc + + + + + + + diff --git a/go2rtc/www/video-rtc.js b/go2rtc/www/video-rtc.js new file mode 100644 index 0000000..953fdae --- /dev/null +++ b/go2rtc/www/video-rtc.js @@ -0,0 +1,695 @@ +/** + * VideoRTC v1.6.0 - Video player for go2rtc streaming application. + * + * All modern web technologies are supported in almost any browser except Apple Safari. + * + * Support: + * - 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 + * - Customized built-in elements (extends HTMLVideoElement) because Safari + * - Autoplay for WebRTC in Safari + */ +export class VideoRTC extends HTMLElement { + constructor() { + super(); + + this.DISCONNECT_TIMEOUT = 5000; + this.RECONNECT_TIMEOUT = 15000; + + this.CODECS = [ + 'avc1.640029', // H.264 high 4.1 (Chromecast 1st and 2nd Gen) + 'avc1.64002A', // H.264 high 4.2 (Chromecast 3rd Gen) + 'avc1.640033', // H.264 high 5.1 (Chromecast with Google TV) + 'hvc1.1.6.L153.B0', // H.265 main 5.1 (Chromecast Ultra) + 'mp4a.40.2', // AAC LC + 'mp4a.40.5', // AAC HE + 'flac', // FLAC (PCM compatible) + 'opus', // OPUS Chrome, Firefox + ]; + + /** + * [config] Supported modes (webrtc, webrtc/tcp, mse, hls, mp4, mjpeg). + * @type {string} + */ + 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} + */ + this.background = false; + + /** + * [config] Run stream only when player in the viewport. Stop when user scroll out player. + * Value is percentage of visibility from `0` (not visible) to `1` (full visible). + * Default `0` - disable; + * @type {number} + */ + this.visibilityThreshold = 0; + + /** + * [config] Run stream only when browser page on the screen. Stop when user change browser + * tab or minimise browser windows. + * @type {boolean} + */ + this.visibilityCheck = true; + + /** + * [config] WebRTC configuration + * @type {RTCConfiguration} + */ + this.pcConfig = { + bundlePolicy: 'max-bundle', + iceServers: [{urls: ['stun:stun.cloudflare.com:3478', 'stun:stun.l.google.com:19302']}], + sdpSemantics: 'unified-plan', // important for Chromecast 1 + }; + + /** + * [info] WebSocket connection state. Values: CONNECTING, OPEN, CLOSED + * @type {number} + */ + this.wsState = WebSocket.CLOSED; + + /** + * [info] WebRTC connection state. + * @type {number} + */ + this.pcState = WebSocket.CLOSED; + + /** + * @type {HTMLVideoElement} + */ + this.video = null; + + /** + * @type {WebSocket} + */ + this.ws = null; + + /** + * @type {string|URL} + */ + this.wsURL = ''; + + /** + * @type {RTCPeerConnection} + */ + this.pc = null; + + /** + * @type {number} + */ + this.connectTS = 0; + + /** + * @type {string} + */ + this.mseCodecs = ''; + + /** + * [internal] Disconnect TimeoutID. + * @type {number} + */ + this.disconnectTID = 0; + + /** + * [internal] Reconnect TimeoutID. + * @type {number} + */ + this.reconnectTID = 0; + + /** + * [internal] Handler for receiving Binary from WebSocket. + * @type {Function} + */ + this.ondata = null; + + /** + * [internal] Handlers list for receiving JSON from WebSocket. + * @type {Object.} + */ + this.onmessage = null; + } + + /** + * Set video source (WebSocket URL). Support relative path. + * @param {string|URL} value + */ + set src(value) { + if (typeof value !== 'string') value = value.toString(); + if (value.startsWith('http')) { + value = 'ws' + value.substring(4); + } else if (value.startsWith('/')) { + value = 'ws' + location.origin.substring(4) + value; + } + + this.wsURL = value; + + this.onconnect(); + } + + /** + * Play video. Support automute when autoplay blocked. + * https://developer.chrome.com/blog/autoplay/ + */ + play() { + this.video.play().catch(() => { + if (!this.video.muted) { + this.video.muted = true; + this.video.play().catch(er => { + console.warn(er); + }); + } + }); + } + + /** + * Send message to server via WebSocket + * @param {Object} value + */ + send(value) { + if (this.ws) this.ws.send(JSON.stringify(value)); + } + + /** @param {Function} isSupported */ + codecs(isSupported) { + return this.CODECS + .filter(codec => this.media.includes(codec.includes('vc1') ? 'video' : 'audio')) + .filter(codec => isSupported(`video/mp4; codecs="${codec}"`)).join(); + } + + /** + * `CustomElement`. Invoked each time the custom element is appended into a + * document-connected element. + */ + connectedCallback() { + if (this.disconnectTID) { + clearTimeout(this.disconnectTID); + this.disconnectTID = 0; + } + + // because video autopause on disconnected from DOM + if (this.video) { + const seek = this.video.seekable; + if (seek.length > 0) { + this.video.currentTime = seek.end(seek.length - 1); + } + this.play(); + } else { + this.oninit(); + } + + this.onconnect(); + } + + /** + * `CustomElement`. Invoked each time the custom element is disconnected from the + * document's DOM. + */ + disconnectedCallback() { + if (this.background || this.disconnectTID) return; + if (this.wsState === WebSocket.CLOSED && this.pcState === WebSocket.CLOSED) return; + + this.disconnectTID = setTimeout(() => { + if (this.reconnectTID) { + clearTimeout(this.reconnectTID); + this.reconnectTID = 0; + } + + this.disconnectTID = 0; + + this.ondisconnect(); + }, this.DISCONNECT_TIMEOUT); + } + + /** + * Creates child DOM elements. Called automatically once on `connectedCallback`. + */ + oninit() { + this.video = document.createElement('video'); + this.video.controls = true; + this.video.playsInline = true; + this.video.preload = 'auto'; + + this.video.style.display = 'block'; // fix bottom margin 4px + this.video.style.width = '100%'; + this.video.style.height = '100%'; + + this.appendChild(this.video); + + this.video.addEventListener('error', ev => { + const err = this.video.error; + // https://developer.mozilla.org/en-US/docs/Web/API/MediaError/code + const MEDIA_ERRORS = { + 1: 'MEDIA_ERR_ABORTED', + 2: 'MEDIA_ERR_NETWORK', + 3: 'MEDIA_ERR_DECODE', + 4: 'MEDIA_ERR_SRC_NOT_SUPPORTED' + }; + console.error('[VideoRTC] Video error:', { + error: err ? MEDIA_ERRORS[err.code] : 'unknown', + message: err ? err.message : 'unknown', + codecs: this.mseCodecs || 'not set', + readyState: this.video.readyState, + networkState: this.video.networkState, + currentTime: this.video.currentTime + }); + if (this.ws) this.ws.close(); // run reconnect for broken MSE stream + }); + + // all Safari lies about supported audio codecs + const m = window.navigator.userAgent.match(/Version\/(\d+).+Safari/); + if (m) { + // AAC from v13, FLAC from v14, OPUS - unsupported + const skip = m[1] < '13' ? 'mp4a.40.2' : m[1] < '14' ? 'flac' : 'opus'; + this.CODECS.splice(this.CODECS.indexOf(skip)); + } + + if (this.background) return; + + if ('hidden' in document && this.visibilityCheck) { + document.addEventListener('visibilitychange', () => { + if (document.hidden) { + this.disconnectedCallback(); + } else if (this.isConnected) { + this.connectedCallback(); + } + }); + } + + if ('IntersectionObserver' in window && this.visibilityThreshold) { + const observer = new IntersectionObserver(entries => { + entries.forEach(entry => { + if (!entry.isIntersecting) { + this.disconnectedCallback(); + } else if (this.isConnected) { + this.connectedCallback(); + } + }); + }, {threshold: this.visibilityThreshold}); + observer.observe(this); + } + } + + /** + * Connect to WebSocket. Called automatically on `connectedCallback`. + * @return {boolean} true if the connection has started. + */ + onconnect() { + if (!this.isConnected || !this.wsURL || this.ws || this.pc) return false; + + // CLOSED or CONNECTING => CONNECTING + this.wsState = WebSocket.CONNECTING; + + this.connectTS = Date.now(); + + this.ws = new WebSocket(this.wsURL); + this.ws.binaryType = 'arraybuffer'; + this.ws.addEventListener('open', () => this.onopen()); + this.ws.addEventListener('close', () => this.onclose()); + + return true; + } + + ondisconnect() { + this.wsState = WebSocket.CLOSED; + if (this.ws) { + this.ws.close(); + this.ws = null; + } + + this.pcState = WebSocket.CLOSED; + if (this.pc) { + this.pc.getSenders().forEach(sender => { + if (sender.track) sender.track.stop(); + }); + this.pc.close(); + this.pc = null; + } + + this.video.src = ''; + this.video.srcObject = null; + } + + /** + * @returns {Array.} of modes (mse, webrtc, etc.) + */ + onopen() { + // CONNECTING => OPEN + this.wsState = WebSocket.OPEN; + + this.ws.addEventListener('message', ev => { + if (typeof ev.data === 'string') { + const msg = JSON.parse(ev.data); + for (const mode in this.onmessage) { + this.onmessage[mode](msg); + } + } else { + this.ondata(ev.data); + } + }); + + this.ondata = null; + this.onmessage = {}; + + const modes = []; + + if (this.mode.includes('mse') && ('MediaSource' in window || 'ManagedMediaSource' in window)) { + modes.push('mse'); + this.onmse(); + } else if (this.mode.includes('hls') && this.video.canPlayType('application/vnd.apple.mpegurl')) { + modes.push('hls'); + this.onhls(); + } else if (this.mode.includes('mp4')) { + modes.push('mp4'); + this.onmp4(); + } + + if (this.mode.includes('webrtc') && 'RTCPeerConnection' in window) { + modes.push('webrtc'); + this.onwebrtc(); + } + + if (this.mode.includes('mjpeg')) { + if (modes.length) { + this.onmessage['mjpeg'] = msg => { + if (msg.type !== 'error' || msg.value.indexOf(modes[0]) !== 0) return; + this.onmjpeg(); + }; + } else { + modes.push('mjpeg'); + this.onmjpeg(); + } + } + + return modes; + } + + /** + * @return {boolean} true if reconnection has started. + */ + onclose() { + if (this.wsState === WebSocket.CLOSED) return false; + + // CONNECTING, OPEN => CONNECTING + this.wsState = WebSocket.CONNECTING; + this.ws = null; + + // reconnect no more than once every X seconds + const delay = Math.max(this.RECONNECT_TIMEOUT - (Date.now() - this.connectTS), 0); + + this.reconnectTID = setTimeout(() => { + this.reconnectTID = 0; + this.onconnect(); + }, delay); + + return true; + } + + onmse() { + /** @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.play(); + + this.mseCodecs = ''; + + this.onmessage['mse'] = msg => { + if (msg.type !== 'mse') return; + + this.mseCodecs = msg.value; + + const sb = ms.addSourceBuffer(msg.value); + sb.mode = 'segments'; // segments or sequence + sb.addEventListener('updateend', () => { + if (!sb.updating && bufLen > 0) { + try { + const data = buf.slice(0, bufLen); + sb.appendBuffer(data); + bufLen = 0; + } catch (e) { + // console.debug(e); + } + } + + if (!sb.updating && sb.buffered && sb.buffered.length) { + const end = sb.buffered.end(sb.buffered.length - 1); + const start = end - 5; + const start0 = sb.buffered.start(0); + if (start > start0) { + sb.remove(start0, start); + ms.setLiveSeekableRange(start, end); + } + if (this.video.currentTime < start) { + this.video.currentTime = start; + } + const gap = end - this.video.currentTime; + this.video.playbackRate = gap > 0.1 ? gap : 0.1; + // console.debug('VideoRTC.buffered', gap, this.video.playbackRate, this.video.readyState); + } + }); + + const buf = new Uint8Array(2 * 1024 * 1024); + let bufLen = 0; + + this.ondata = data => { + if (sb.updating || bufLen > 0) { + const b = new Uint8Array(data); + buf.set(b, bufLen); + bufLen += b.byteLength; + // console.debug('VideoRTC.buffer', b.byteLength, bufLen); + } else { + try { + sb.appendBuffer(data); + } catch (e) { + // console.debug(e); + } + } + }; + }; + } + + onwebrtc() { + const pc = new RTCPeerConnection(this.pcConfig); + + pc.addEventListener('icecandidate', ev => { + if (ev.candidate && this.mode.includes('webrtc/tcp') && ev.candidate.protocol === 'udp') return; + + const candidate = ev.candidate ? ev.candidate.toJSON().candidate : ''; + this.send({type: 'webrtc/candidate', value: candidate}); + }); + + pc.addEventListener('connectionstatechange', () => { + if (pc.connectionState === 'connected') { + const tracks = pc.getTransceivers() + .filter(tr => tr.currentDirection === 'recvonly') // skip inactive + .map(tr => tr.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; + this.pc = null; + + this.onconnect(); + } + }); + + this.onmessage['webrtc'] = msg => { + switch (msg.type) { + case 'webrtc/candidate': + if (this.mode.includes('webrtc/tcp') && msg.value.includes(' udp ')) return; + + pc.addIceCandidate({candidate: msg.value, sdpMid: '0'}).catch(er => { + console.warn(er); + }); + break; + case 'webrtc/answer': + pc.setRemoteDescription({type: 'answer', sdp: msg.value}).catch(er => { + console.warn(er); + }); + break; + case 'error': + if (!msg.value.includes('webrtc/offer')) return; + pc.close(); + } + }; + + this.createOffer(pc).then(offer => { + this.send({type: 'webrtc/offer', value: offer.sdp}); + }); + + this.pcState = WebSocket.CONNECTING; + this.pc = pc; + } + + /** + * @param pc {RTCPeerConnection} + * @return {Promise} + */ + async createOffer(pc) { + try { + if (this.media.includes('microphone')) { + const media = await navigator.mediaDevices.getUserMedia({audio: true}); + media.getTracks().forEach(track => { + pc.addTransceiver(track, {direction: 'sendonly'}); + }); + } + } catch (e) { + console.warn(e); + } + + for (const kind of ['video', 'audio']) { + if (this.media.includes(kind)) { + pc.addTransceiver(kind, {direction: 'recvonly'}); + } + } + + const offer = await pc.createOffer(); + await pc.setLocalDescription(offer); + return offer; + } + + /** + * @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 stream = video2.srcObject; + if (stream.getVideoTracks().length > 0) { + // not the best, but a pretty simple way to check a codec + const isH265Supported = this.pc.remoteDescription.sdp.includes('H265/90000'); + rtcPriority += isH265Supported ? 0x240 : 0x220; + } + if (stream.getAudioTracks().length > 0) rtcPriority += 0x102; + + if (this.mseCodecs.includes('hvc1.')) msePriority += 0x230; + if (this.mseCodecs.includes('avc1.')) msePriority += 0x210; + if (this.mseCodecs.includes('mp4a.')) msePriority += 0x101; + + if (rtcPriority >= msePriority) { + this.video.srcObject = stream; + this.play(); + + this.pcState = WebSocket.OPEN; + + this.wsState = WebSocket.CLOSED; + if (this.ws) { + this.ws.close(); + this.ws = null; + } + } else { + this.pcState = WebSocket.CLOSED; + if (this.pc) { + this.pc.close(); + this.pc = null; + } + } + } + + video2.srcObject = null; + } + + onmjpeg() { + this.ondata = data => { + this.video.controls = false; + this.video.poster = 'data:image/jpeg;base64,' + VideoRTC.btoa(data); + }; + + this.send({type: 'mjpeg'}); + } + + onhls() { + this.onmessage['hls'] = msg => { + if (msg.type !== 'hls') return; + + const url = 'http' + this.wsURL.substring(2, this.wsURL.indexOf('/ws')) + '/hls/'; + const playlist = msg.value.replace('hls/', url); + this.video.src = 'data:application/vnd.apple.mpegurl;base64,' + btoa(playlist); + this.play(); + }; + + this.send({type: 'hls', value: this.codecs(type => this.video.canPlayType(type))}); + } + + onmp4() { + /** @type {HTMLCanvasElement} **/ + const canvas = document.createElement('canvas'); + /** @type {CanvasRenderingContext2D} */ + let context; + + /** @type {HTMLVideoElement} */ + const video2 = document.createElement('video'); + video2.autoplay = true; + video2.playsInline = true; + video2.muted = true; + + video2.addEventListener('loadeddata', () => { + if (!context) { + canvas.width = video2.videoWidth; + canvas.height = video2.videoHeight; + context = canvas.getContext('2d'); + } + + context.drawImage(video2, 0, 0, canvas.width, canvas.height); + + this.video.controls = false; + this.video.poster = canvas.toDataURL('image/jpeg'); + }); + + this.ondata = data => { + video2.src = 'data:video/mp4;base64,' + VideoRTC.btoa(data); + }; + + this.send({type: 'mp4', value: this.codecs(this.video.canPlayType)}); + } + + static btoa(buffer) { + const bytes = new Uint8Array(buffer); + const len = bytes.byteLength; + let binary = ''; + for (let i = 0; i < len; i++) { + binary += String.fromCharCode(bytes[i]); + } + return window.btoa(binary); + } +} diff --git a/go2rtc/www/video-stream.js b/go2rtc/www/video-stream.js new file mode 100644 index 0000000..ff69ef8 --- /dev/null +++ b/go2rtc/www/video-stream.js @@ -0,0 +1,107 @@ +import {VideoRTC} from './video-rtc.js'; + +/** + * This is example, how you can extend VideoRTC player for your app. + * Also you can check this example: https://github.com/AlexxIT/WebRTC + */ +class VideoStream extends VideoRTC { + set divMode(value) { + this.querySelector('.mode').innerText = value; + this.querySelector('.status').innerText = ''; + } + + set divError(value) { + const state = this.querySelector('.mode').innerText; + if (state !== 'loading') return; + this.querySelector('.mode').innerText = 'error'; + this.querySelector('.status').innerText = value; + } + + /** + * Custom GUI + */ + oninit() { + console.debug('stream.oninit'); + super.oninit(); + + this.innerHTML = ` + +
    +
    +
    +
    + `; + + const info = this.querySelector('.info'); + this.insertBefore(this.video, info); + } + + onconnect() { + console.debug('stream.onconnect'); + const result = super.onconnect(); + if (result) this.divMode = 'loading'; + return result; + } + + ondisconnect() { + console.debug('stream.ondisconnect'); + super.ondisconnect(); + } + + onopen() { + console.debug('stream.onopen'); + const result = super.onopen(); + + this.onmessage['stream'] = msg => { + console.debug('stream.onmessge', msg); + switch (msg.type) { + case 'error': + this.divError = msg.value; + break; + case 'mse': + case 'hls': + case 'mp4': + case 'mjpeg': + this.divMode = msg.type.toUpperCase(); + break; + } + }; + + return result; + } + + onclose() { + console.debug('stream.onclose'); + return super.onclose(); + } + + onpcvideo(ev) { + console.debug('stream.onpcvideo'); + super.onpcvideo(ev); + + if (this.pcState !== WebSocket.CLOSED) { + this.divMode = 'RTC'; + } + } +} + +customElements.define('video-stream', VideoStream); diff --git a/go2rtc/www/webrtc-sync.html b/go2rtc/www/webrtc-sync.html new file mode 100644 index 0000000..89d742b --- /dev/null +++ b/go2rtc/www/webrtc-sync.html @@ -0,0 +1,66 @@ + + + + + webrtc - go2rtc + + + + + + + \ No newline at end of file diff --git a/go2rtc/www/webrtc.html b/go2rtc/www/webrtc.html new file mode 100644 index 0000000..dc12178 --- /dev/null +++ b/go2rtc/www/webrtc.html @@ -0,0 +1,107 @@ + + + + + webrtc - go2rtc + + + + + + + \ No newline at end of file