apply prettier to the entire repository (#5799)

This commit is contained in:
Alessandro Ros
2026-05-26 11:35:14 +02:00
committed by GitHub
parent e63dd7132a
commit 903627ffed
16 changed files with 2213 additions and 2078 deletions
-1
View File
@@ -1,6 +1,5 @@
version: 2 version: 2
updates: updates:
- package-ecosystem: "gomod" - package-ecosystem: "gomod"
directory: "/" directory: "/"
schedule: schedule:
+47 -47
View File
@@ -2,101 +2,101 @@ name: lint
on: on:
push: push:
branches: [ main ] branches: [main]
pull_request: pull_request:
branches: [ main ] branches: [main]
jobs: jobs:
go: go:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-go@v6 - uses: actions/setup-go@v6
with: with:
go-version: "1.26" go-version: "1.26"
- run: go generate ./... - run: go generate ./...
- uses: golangci/golangci-lint-action@v9 - uses: golangci/golangci-lint-action@v9
with: with:
version: v2.12.2 version: v2.12.2
go_mod: go_mod:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions/setup-go@v6 - uses: actions/setup-go@v6
with: with:
go-version: "1.26" go-version: "1.26"
- run: make lint-go-mod - run: make lint-go-mod
conf: conf:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions/setup-go@v6 - uses: actions/setup-go@v6
with: with:
go-version: "1.26" go-version: "1.26"
- run: make lint-conf - run: make lint-conf
go2api: go2api:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions/setup-go@v6 - uses: actions/setup-go@v6
with: with:
go-version: "1.26" go-version: "1.26"
- run: make lint-go2api - run: make lint-go2api
docslinks: docslinks:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions/setup-go@v6 - uses: actions/setup-go@v6
with: with:
go-version: "1.26" go-version: "1.26"
- run: make lint-docslinks - run: make lint-docslinks
docsorder: docsorder:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions/setup-go@v6 - uses: actions/setup-go@v6
with: with:
go-version: "1.26" go-version: "1.26"
- run: make lint-docsorder - run: make lint-docsorder
docs:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- run: make lint-docs
api_docs: api_docs:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- run: make lint-api-docs - run: make lint-api-docs
other:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- run: make lint-other
+8 -8
View File
@@ -8,13 +8,13 @@ jobs:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- run: make binaries - run: make binaries
- uses: actions/upload-artifact@v7 - uses: actions/upload-artifact@v7
with: with:
name: binaries name: binaries
path: binaries path: binaries
+103 -103
View File
@@ -3,7 +3,7 @@ name: release
on: on:
push: push:
tags: tags:
- 'v*' - "v*"
permissions: permissions:
id-token: write id-token: write
@@ -18,144 +18,144 @@ jobs:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- run: make binaries - run: make binaries
- run: cd binaries && sha256sum -b * > checksums.sha256 - run: cd binaries && sha256sum -b * > checksums.sha256
- uses: actions/attest@v4 - uses: actions/attest@v4
with: with:
subject-path: '${{ github.workspace }}/binaries/*' subject-path: "${{ github.workspace }}/binaries/*"
- uses: actions/upload-artifact@v7 - uses: actions/upload-artifact@v7
with: with:
name: binaries name: binaries
path: binaries path: binaries
github_release: github_release:
needs: binaries needs: binaries
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/download-artifact@v8 - uses: actions/download-artifact@v8
with: with:
name: binaries name: binaries
path: binaries path: binaries
- uses: actions/github-script@v9 - uses: actions/github-script@v9
with: with:
github-token: ${{ secrets.GITHUB_TOKEN }} github-token: ${{ secrets.GITHUB_TOKEN }}
script: | script: |
const fs = require('fs').promises; const fs = require('fs').promises;
const { repo: { owner, repo } } = context; const { repo: { owner, repo } } = context;
const currentRelease = context.ref.split('/')[2]; const currentRelease = context.ref.split('/')[2];
let body = `## New major features\n` let body = `## New major features\n`
+ `\n` + `\n`
+ `TODO\n` + `TODO\n`
+ `\n` + `\n`
+ `## Fixes and improvements\n` + `## Fixes and improvements\n`
+ `\n` + `\n`
+ `TODO\n` + `TODO\n`
+ `\n` + `\n`
+ `## Security\n` + `## Security\n`
+ `\n` + `\n`
+ `Binaries are compiled from source code by the [Release workflow](https://github.com/${owner}/${repo}/actions/workflows/release.yml), which is a fully-visible process that prevents any change or external interference in produced artifacts.\n` + `Binaries are compiled from source code by the [Release workflow](https://github.com/${owner}/${repo}/actions/workflows/release.yml), which is a fully-visible process that prevents any change or external interference in produced artifacts.\n`
+ `\n` + `\n`
+ 'Checksums of binaries are also published in a public blockchain by using [GitHub Attestations](https://docs.github.com/en/actions/concepts/security/artifact-attestations), and they can be verified by running:\n' + 'Checksums of binaries are also published in a public blockchain by using [GitHub Attestations](https://docs.github.com/en/actions/concepts/security/artifact-attestations), and they can be verified by running:\n'
+ `\n` + `\n`
+ '```\n' + '```\n'
+ `ls mediamtx_* | xargs -L1 gh attestation verify --repo bluenviron/mediamtx\n` + `ls mediamtx_* | xargs -L1 gh attestation verify --repo bluenviron/mediamtx\n`
+ '```\n' + '```\n'
+ `\n` + `\n`
+ 'You can verify checksums of binaries by downloading `checksums.sha256` and running:\n' + 'You can verify checksums of binaries by downloading `checksums.sha256` and running:\n'
+ `\n` + `\n`
+ '```\n' + '```\n'
+ `cat checksums.sha256 | grep "$(ls mediamtx_*)" | sha256sum --check\n` + `cat checksums.sha256 | grep "$(ls mediamtx_*)" | sha256sum --check\n`
+ '```\n' + '```\n'
+ `\n`; + `\n`;
const res = await github.rest.repos.createRelease({ const res = await github.rest.repos.createRelease({
owner,
repo,
tag_name: currentRelease,
name: currentRelease,
body,
});
const release_id = res.data.id;
for (const name of await fs.readdir('./binaries/')) {
await github.rest.repos.uploadReleaseAsset({
owner, owner,
repo, repo,
release_id, tag_name: currentRelease,
name, name: currentRelease,
data: await fs.readFile(`./binaries/${name}`), body,
}); });
} const release_id = res.data.id;
for (const name of await fs.readdir('./binaries/')) {
await github.rest.repos.uploadReleaseAsset({
owner,
repo,
release_id,
name,
data: await fs.readFile(`./binaries/${name}`),
});
}
github_notify_issues: github_notify_issues:
needs: github_release needs: github_release
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/github-script@v9 - uses: actions/github-script@v9
with: with:
github-token: ${{ secrets.GITHUB_TOKEN }} github-token: ${{ secrets.GITHUB_TOKEN }}
script: | script: |
const { repo: { owner, repo } } = context; const { repo: { owner, repo } } = context;
const tags = await github.rest.repos.listTags({ const tags = await github.rest.repos.listTags({
owner, owner,
repo, repo,
}); });
const curTag = tags.data[0]; const curTag = tags.data[0];
const prevTag = tags.data[1]; const prevTag = tags.data[1];
const diff = await github.rest.repos.compareCommitsWithBasehead({ const diff = await github.rest.repos.compareCommitsWithBasehead({
owner, owner,
repo, repo,
basehead: `${prevTag.commit.sha}...${curTag.commit.sha}`, basehead: `${prevTag.commit.sha}...${curTag.commit.sha}`,
}); });
const issues = {}; const issues = {};
for (const commit of diff.data.commits) { for (const commit of diff.data.commits) {
for (const match of commit.commit.message.matchAll(/(^| |\()#([0-9]+)( |\)|$)/g)) { for (const match of commit.commit.message.matchAll(/(^| |\()#([0-9]+)( |\)|$)/g)) {
issues[match[2]] = 1; issues[match[2]] = 1;
}
} }
}
for (const issue in issues) { for (const issue in issues) {
try { try {
await github.rest.issues.createComment({ await github.rest.issues.createComment({
owner, owner,
repo, repo,
issue_number: parseInt(issue), issue_number: parseInt(issue),
body: `This issue is mentioned in release ${curTag.name} 🚀\n` body: `This issue is mentioned in release ${curTag.name} 🚀\n`
+ `Check out the entire changelog by [clicking here](https://github.com/${owner}/${repo}/releases/tag/${curTag.name})`, + `Check out the entire changelog by [clicking here](https://github.com/${owner}/${repo}/releases/tag/${curTag.name})`,
}); });
} catch (exc) { } catch (exc) {
console.error(exc.toString()); console.error(exc.toString());
}
} }
}
dockerhub: dockerhub:
needs: binaries needs: binaries
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
- uses: actions/download-artifact@v8 - uses: actions/download-artifact@v8
with: with:
name: binaries name: binaries
path: binaries path: binaries
- run: make dockerhub - run: make dockerhub
env: env:
DOCKER_USER: ${{ secrets.DOCKER_USER }} DOCKER_USER: ${{ secrets.DOCKER_USER }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }} DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
+20 -20
View File
@@ -2,45 +2,45 @@ name: test
on: on:
push: push:
branches: [ main ] branches: [main]
pull_request: pull_request:
branches: [ main ] branches: [main]
jobs: jobs:
test_64: test_64:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- run: make test - run: make test
- uses: codecov/codecov-action@v6 - uses: codecov/codecov-action@v6
with: with:
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}
test_32: test_32:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- run: make test-32 - run: make test-32
test_e2e: test_e2e:
runs-on: ubuntu-24.04 runs-on: ubuntu-24.04
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v6
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: actions/setup-go@v6 - uses: actions/setup-go@v6
with: with:
go-version: "1.26" go-version: "1.26"
- run: make test-e2e-nodocker - run: make test-e2e-nodocker
+67 -67
View File
@@ -2,90 +2,90 @@ version: "2"
linters: linters:
enable: enable:
- asciicheck - asciicheck
- bidichk - bidichk
- bodyclose - bodyclose
- copyloopvar - copyloopvar
- dupl - dupl
- errorlint - errorlint
- gochecknoinits - gochecknoinits
- gocritic - gocritic
- lll - lll
- misspell - misspell
- modernize - modernize
- nilerr - nilerr
- prealloc - prealloc
- predeclared - predeclared
- reassign - reassign
- revive - revive
- usestdlibvars - usestdlibvars
- unconvert - unconvert
- tparallel - tparallel
- wastedassign - wastedassign
- whitespace - whitespace
settings: settings:
errcheck: errcheck:
exclude-functions: exclude-functions:
- io.Copy - io.Copy
- (io.Closer).Close - (io.Closer).Close
- (io.Writer).Write - (io.Writer).Write
- (hash.Hash).Write - (hash.Hash).Write
- (net.Conn).Close - (net.Conn).Close
- (net.Conn).SetReadDeadline - (net.Conn).SetReadDeadline
- (net.Conn).SetWriteDeadline - (net.Conn).SetWriteDeadline
- (*net.TCPConn).SetKeepAlive - (*net.TCPConn).SetKeepAlive
- (*net.TCPConn).SetKeepAlivePeriod - (*net.TCPConn).SetKeepAlivePeriod
- (*net.TCPConn).SetNoDelay - (*net.TCPConn).SetNoDelay
- (net.Listener).Close - (net.Listener).Close
- (net.PacketConn).Close - (net.PacketConn).Close
- (net.PacketConn).SetReadDeadline - (net.PacketConn).SetReadDeadline
- (net.PacketConn).SetWriteDeadline - (net.PacketConn).SetWriteDeadline
- (net/http.ResponseWriter).Write - (net/http.ResponseWriter).Write
- (*net/http.Server).Serve - (*net/http.Server).Serve
- (*net/http.Server).ServeTLS - (*net/http.Server).ServeTLS
- (*net/http.Server).Shutdown - (*net/http.Server).Shutdown
- os.Chdir - os.Chdir
- os.Mkdir - os.Mkdir
- os.MkdirAll - os.MkdirAll
- os.Remove - os.Remove
- os.RemoveAll - os.RemoveAll
- os.Setenv - os.Setenv
- os.Unsetenv - os.Unsetenv
- (*os.File).WriteString - (*os.File).WriteString
- (*os.File).Close - (*os.File).Close
- (github.com/datarhei/gosrt.Conn).Close - (github.com/datarhei/gosrt.Conn).Close
- (github.com/datarhei/gosrt.Conn).SetReadDeadline - (github.com/datarhei/gosrt.Conn).SetReadDeadline
- (github.com/datarhei/gosrt.Conn).SetWriteDeadline - (github.com/datarhei/gosrt.Conn).SetWriteDeadline
- (*github.com/bluenviron/gortsplib/v5.Client).Close - (*github.com/bluenviron/gortsplib/v5.Client).Close
- (*github.com/bluenviron/gortsplib/v5.Server).Close - (*github.com/bluenviron/gortsplib/v5.Server).Close
- (*github.com/bluenviron/gortsplib/v5.ServerSession).Close - (*github.com/bluenviron/gortsplib/v5.ServerSession).Close
- (*github.com/bluenviron/gortsplib/v5.ServerStream).Close - (*github.com/bluenviron/gortsplib/v5.ServerStream).Close
- (*github.com/bluenviron/gortsplib/v5.ServerConn).Close - (*github.com/bluenviron/gortsplib/v5.ServerConn).Close
govet: govet:
enable-all: true enable-all: true
disable: disable:
- fieldalignment - fieldalignment
- reflectvaluecompare - reflectvaluecompare
settings: settings:
shadow: shadow:
strict: true strict: true
modernize: modernize:
disable: disable:
- reflecttypefor - reflecttypefor
- stringsbuilder - stringsbuilder
- testingcontext - testingcontext
exclusions: exclusions:
rules: rules:
- linters: - linters:
- lll - lll
source: "^\\s*// https?://" source: "^\\s*// https?://"
formatters: formatters:
enable: enable:
- gofmt - gofmt
- gofumpt - gofumpt
- goimports - goimports
+9 -8
View File
@@ -6,12 +6,13 @@
<br> <br>
<br> <br>
[![Website](https://img.shields.io/badge/website-mediamtx.org-1c94b5)](https://mediamtx.org) [![Website](https://img.shields.io/badge/website-mediamtx.org-1c94b5)](https://mediamtx.org)
[![Test](https://github.com/bluenviron/mediamtx/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/bluenviron/mediamtx/actions/workflows/test.yml?query=branch%3Amain) [![Test](https://github.com/bluenviron/mediamtx/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/bluenviron/mediamtx/actions/workflows/test.yml?query=branch%3Amain)
[![Lint](https://github.com/bluenviron/mediamtx/actions/workflows/lint.yml/badge.svg?branch=main)](https://github.com/bluenviron/mediamtx/actions/workflows/lint.yml?query=branch%3Amain) [![Lint](https://github.com/bluenviron/mediamtx/actions/workflows/lint.yml/badge.svg?branch=main)](https://github.com/bluenviron/mediamtx/actions/workflows/lint.yml?query=branch%3Amain)
[![CodeCov](https://codecov.io/gh/bluenviron/mediamtx/branch/main/graph/badge.svg)](https://app.codecov.io/gh/bluenviron/mediamtx/tree/main) [![CodeCov](https://codecov.io/gh/bluenviron/mediamtx/branch/main/graph/badge.svg)](https://app.codecov.io/gh/bluenviron/mediamtx/tree/main)
[![Release](https://img.shields.io/github/v/release/bluenviron/mediamtx)](https://github.com/bluenviron/mediamtx/releases) [![Release](https://img.shields.io/github/v/release/bluenviron/mediamtx)](https://github.com/bluenviron/mediamtx/releases)
[![Docker Hub](https://img.shields.io/badge/docker-bluenviron/mediamtx-blue)](https://hub.docker.com/r/bluenviron/mediamtx) [![Docker Hub](https://img.shields.io/badge/docker-bluenviron/mediamtx-blue)](https://hub.docker.com/r/bluenviron/mediamtx)
</h1> </h1>
<br> <br>
@@ -20,8 +21,8 @@ _MediaMTX_ is a ready-to-use and zero-dependency real-time media server and medi
<div align="center"> <div align="center">
|[Install](https://mediamtx.org/docs/kickoff/install)|[Documentation](https://mediamtx.org/docs/kickoff/introduction)| | [Install](https://mediamtx.org/docs/kickoff/install) | [Documentation](https://mediamtx.org/docs/kickoff/introduction) |
|-|-| | ---------------------------------------------------- | --------------------------------------------------------------- |
</div> </div>
+779 -780
View File
File diff suppressed because it is too large Load Diff
+181 -182
View File
@@ -1,204 +1,203 @@
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width"> <meta name="viewport" content="width=device-width" />
<style> <style>
html, body { html,
margin: 0; body {
padding: 0; margin: 0;
height: 100%; padding: 0;
font-family: 'Arial', sans-serif; height: 100%;
} font-family: "Arial", sans-serif;
#video { }
position: absolute; #video {
top: 0; position: absolute;
left: 0; top: 0;
width: 100%; left: 0;
height: 100%; width: 100%;
background: rgb(30, 30, 30); height: 100%;
} background: rgb(30, 30, 30);
#message { }
position: absolute; #message {
left: 0; position: absolute;
top: 0; left: 0;
width: 100%; top: 0;
height: 100%; width: 100%;
display: flex; height: 100%;
align-items: center; display: flex;
text-align: center; align-items: center;
justify-content: center; text-align: center;
font-size: 16px; justify-content: center;
font-weight: bold; font-size: 16px;
color: white; font-weight: bold;
pointer-events: none; color: white;
padding: 20px; pointer-events: none;
box-sizing: border-box; padding: 20px;
text-shadow: 0 0 5px black; box-sizing: border-box;
} text-shadow: 0 0 5px black;
#lang-icon { }
display: none; #lang-icon {
position: absolute; display: none;
top: 20px; position: absolute;
right: 20px; top: 20px;
width: 30px; right: 20px;
height: 30px; width: 30px;
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MCA1MCIgZmlsbD0iI2ZmZiIgeG1sbnM6dj0iaHR0cHM6Ly92ZWN0YS5pby9uYW5vIj48cGF0aCBkPSJNMzguNSAzMy45bC0xLjktMS42YzIuNS0yLjkgMy44LTYuMyAzLjgtOS45IDAtMy4xLTEtNi4xLTIuOS04LjhsMi4xLTEuNWMyLjIgMy4xIDMuNCA2LjYgMy40IDEwLjItLjEgNC4zLTEuNiA4LjMtNC41IDExLjZ6TTUuNiAyMy4yaC0zYy0uNSAwLTEgLjUtMSAxLjF2MTAuNWMwIC42LjQgMS4xIDEgMS4xaDNjLjIgMCAuMyAwIC40LjFsMTMuOCA3LjhjLjYuNCAxLjQtLjIgMS40LTFWMTYuM2MwLS44LS44LTEuMy0xLjQtMUw2LjEgMjMuMWMtLjIuMS0uMy4xLS41LjF6bTIxLTE2LjlMMTIuOCAxNGMtLjEuMS0uMy4xLS40LjFoLTNjLS41IDAtMSAuNS0xIDEuMVYyMGwxMi4yLTYuOGExLjM2IDEuMzYgMCAwIDEgMS41IDBjLjUuMy44LjguOCAxLjV2MTcuOWwzLjcgMi4xYy42LjQgMS40LS4yIDEuNC0xVjcuMmMuMS0uOC0uNy0xLjMtMS40LS45em0xNi41IDMwLjJsLTEuOS0xLjZjMy4xLTMuNyA0LjctOCA0LjctMTIuNSAwLTQtMS4zLTcuOC0zLjctMTEuMmwyLjEtMS41YzIuNyAzLjggNC4yIDguMiA0LjIgMTIuNy0uMiA1LjEtMiA5LjktNS40IDE0LjF6TTM1IDMxLjFsLTItMS42YzEuNy0yLjEgMi42LTQuNiAyLjYtNy4yIDAtMi40LS44LTQuNy0yLjItNi43bDItMS41YzEuOCAyLjUgMi43IDUuMyAyLjcgOC4yIDAgMy4yLTEuMSA2LjItMy4xIDguOHoiLz48L3N2Zz4="); height: 30px;
background-size: 80%; background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA1MCA1MCIgZmlsbD0iI2ZmZiIgeG1sbnM6dj0iaHR0cHM6Ly92ZWN0YS5pby9uYW5vIj48cGF0aCBkPSJNMzguNSAzMy45bC0xLjktMS42YzIuNS0yLjkgMy44LTYuMyAzLjgtOS45IDAtMy4xLTEtNi4xLTIuOS04LjhsMi4xLTEuNWMyLjIgMy4xIDMuNCA2LjYgMy40IDEwLjItLjEgNC4zLTEuNiA4LjMtNC41IDExLjZ6TTUuNiAyMy4yaC0zYy0uNSAwLTEgLjUtMSAxLjF2MTAuNWMwIC42LjQgMS4xIDEgMS4xaDNjLjIgMCAuMyAwIC40LjFsMTMuOCA3LjhjLjYuNCAxLjQtLjIgMS40LTFWMTYuM2MwLS44LS44LTEuMy0xLjQtMUw2LjEgMjMuMWMtLjIuMS0uMy4xLS41LjF6bTIxLTE2LjlMMTIuOCAxNGMtLjEuMS0uMy4xLS40LjFoLTNjLS41IDAtMSAuNS0xIDEuMVYyMGwxMi4yLTYuOGExLjM2IDEuMzYgMCAwIDEgMS41IDBjLjUuMy44LjguOCAxLjV2MTcuOWwzLjcgMi4xYy42LjQgMS40LS4yIDEuNC0xVjcuMmMuMS0uOC0uNy0xLjMtMS40LS45em0xNi41IDMwLjJsLTEuOS0xLjZjMy4xLTMuNyA0LjctOCA0LjctMTIuNSAwLTQtMS4zLTcuOC0zLjctMTEuMmwyLjEtMS41YzIuNyAzLjggNC4yIDguMiA0LjIgMTIuNy0uMiA1LjEtMiA5LjktNS40IDE0LjF6TTM1IDMxLjFsLTItMS42YzEuNy0yLjEgMi42LTQuNiAyLjYtNy4yIDAtMi40LS44LTQuNy0yLjItNi43bDItMS41YzEuOCAyLjUgMi43IDUuMyAyLjcgOC4yIDAgMy4yLTEuMSA2LjItMy4xIDguOHoiLz48L3N2Zz4=");
background-position: center; background-size: 80%;
background-repeat: no-repeat; background-position: center;
cursor: pointer; background-repeat: no-repeat;
} cursor: pointer;
#lang-list { }
display: none; #lang-list {
position: absolute; display: none;
top: 100%; position: absolute;
right: 0; top: 100%;
background: rgb(190, 190, 190); right: 0;
color: black; background: rgb(190, 190, 190);
} color: black;
#lang-icon:hover #lang-list { }
display: block; #lang-icon:hover #lang-list {
} display: block;
#lang-list div { }
border-bottom: 1px solid black; #lang-list div {
padding: 5px 15px; border-bottom: 1px solid black;
} padding: 5px 15px;
</style> }
</head> </style>
<body> </head>
<body>
<video id="video"></video>
<div id="message"></div>
<div id="lang-icon"><div id="lang-list"></div></div>
<video id="video"></video> <script defer src="hls.min.js"></script>
<div id="message"></div>
<div id="lang-icon"><div id="lang-list"></div></div>
<script defer src="hls.min.js"></script> <script>
const retryPause = 2000;
<script> const video = document.getElementById("video");
const message = document.getElementById("message");
const langIcon = document.getElementById("lang-icon");
const langList = document.getElementById("lang-list");
const retryPause = 2000; let defaultControls = false;
const video = document.getElementById('video'); const setMessage = (str) => {
const message = document.getElementById('message'); if (str !== "") {
const langIcon = document.getElementById('lang-icon'); video.controls = false;
const langList = document.getElementById('lang-list'); } else {
video.controls = defaultControls;
}
message.innerText = str;
};
let defaultControls = false; const isIOS = () =>
/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
const setMessage = (str) => { const loadStream = () => {
if (str !== '') { // Prefer hls.js over native HLS.
video.controls = false; // This is because some Android versions support native HLS
} else { // but don't support fMP4s.
video.controls = defaultControls; // Skip iPad iOS >= 13 and iPhone iOS >= 17,
} // which support hls.js but don't support well maxLiveSyncPlaybackRate.
message.innerText = str; if (Hls.isSupported() && !isIOS()) {
}; const hls = new Hls({
maxLiveSyncPlaybackRate: 1.5,
});
const isIOS = () => ( hls.on(Hls.Events.ERROR, (evt, data) => {
/iPad|iPhone|iPod/.test(navigator.platform) if (data.fatal) {
|| (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) hls.destroy();
);
const loadStream = () => { langIcon.style.display = "none";
// Prefer hls.js over native HLS. langList.innerHTML = "";
// This is because some Android versions support native HLS
// but don't support fMP4s.
// Skip iPad iOS >= 13 and iPhone iOS >= 17,
// which support hls.js but don't support well maxLiveSyncPlaybackRate.
if (Hls.isSupported() && !isIOS()) {
const hls = new Hls({
maxLiveSyncPlaybackRate: 1.5,
});
hls.on(Hls.Events.ERROR, (evt, data) => { if (data.details === "manifestIncompatibleCodecsError") {
if (data.fatal) { setMessage(
hls.destroy(); "stream makes use of codecs which are not compatible with this browser or operative system",
);
} else if (data.response && data.response.code === 404) {
setMessage("stream not found, retrying in some seconds");
} else {
setMessage(data.error + ", retrying in some seconds");
}
langIcon.style.display = 'none'; setTimeout(() => loadStream(), retryPause);
langList.innerHTML = ''; }
});
if (data.details === 'manifestIncompatibleCodecsError') { hls.on(Hls.Events.MEDIA_ATTACHED, () => {
setMessage('stream makes use of codecs which are not compatible with this browser or operative system'); hls.loadSource("index.m3u8" + window.location.search);
} else if (data.response && data.response.code === 404) { });
setMessage('stream not found, retrying in some seconds');
} else {
setMessage(data.error + ', retrying in some seconds');
}
setTimeout(() => loadStream(), retryPause); hls.on(Hls.Events.MANIFEST_LOADED, () => {
} if (hls.audioTracks.length > 1) {
}); for (const track of hls.audioTracks) {
const div = document.createElement("DIV");
div.innerText = track.name;
div.addEventListener("click", () => {
hls.audioTrack = track.id;
});
langList.appendChild(div);
}
langIcon.style.display = "block";
}
hls.on(Hls.Events.MEDIA_ATTACHED, () => { setMessage("");
hls.loadSource('index.m3u8' + window.location.search); video.play();
}); });
hls.on(Hls.Events.MANIFEST_LOADED, () => { // when the video is resumed after a manual or forced pause
if (hls.audioTracks.length > 1) { // (i.e. when the window is minimized), restore live streaming.
for (const track of hls.audioTracks) { video.onplay = () => {
const div = document.createElement('DIV'); video.currentTime = hls.liveSyncPosition;
div.innerText = track.name; };
div.addEventListener('click', () => {
hls.audioTrack = track.id;
});
langList.appendChild(div);
}
langIcon.style.display = 'block';
}
setMessage(''); hls.attachMedia(video);
video.play(); } else if (video.canPlayType("application/vnd.apple.mpegurl")) {
}); // since it's not possible to detect timeout errors in iOS,
// wait for the playlist to be available before starting the stream
fetch("index.m3u8" + window.location.search).then(() => {
video.src = "index.m3u8" + window.location.search;
video.play();
});
}
};
// when the video is resumed after a manual or forced pause const parseBoolString = (str, defaultVal) => {
// (i.e. when the window is minimized), restore live streaming. str = str || "";
video.onplay = () => {
video.currentTime = hls.liveSyncPosition;
};
hls.attachMedia(video); if (["1", "yes", "true"].includes(str.toLowerCase())) {
return true;
}
if (["0", "no", "false"].includes(str.toLowerCase())) {
return false;
}
return defaultVal;
};
} else if (video.canPlayType('application/vnd.apple.mpegurl')) { const loadAttributesFromQuery = () => {
// since it's not possible to detect timeout errors in iOS, const params = new URLSearchParams(window.location.search);
// wait for the playlist to be available before starting the stream video.controls = parseBoolString(params.get("controls"), true);
fetch('index.m3u8' + window.location.search) video.muted = parseBoolString(params.get("muted"), true);
.then(() => { video.autoplay = parseBoolString(params.get("autoplay"), true);
video.src = 'index.m3u8' + window.location.search; video.playsInline = parseBoolString(params.get("playsinline"), true);
video.play(); video.disablepictureinpicture = parseBoolString(
}); params.get("disablepictureinpicture"),
} false,
}; );
defaultControls = video.controls;
};
const parseBoolString = (str, defaultVal) => { // use load instead of DOMContentLoaded, otherwise, in Firefox,
str = (str || ''); // the page gets stuck in the "loading" state.
window.addEventListener("load", () => {
if (['1', 'yes', 'true'].includes(str.toLowerCase())) { loadAttributesFromQuery();
return true; loadStream();
} });
if (['0', 'no', 'false'].includes(str.toLowerCase())) { </script>
return false; </body>
}
return defaultVal;
};
const loadAttributesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
video.controls = parseBoolString(params.get('controls'), true);
video.muted = parseBoolString(params.get('muted'), true);
video.autoplay = parseBoolString(params.get('autoplay'), true);
video.playsInline = parseBoolString(params.get('playsinline'), true);
video.disablepictureinpicture = parseBoolString(params.get('disablepictureinpicture'), false);
defaultControls = video.controls;
};
// use load instead of DOMContentLoaded, otherwise, in Firefox,
// the page gets stuck in the "loading" state.
window.addEventListener('load', () => {
loadAttributesFromQuery();
loadStream();
});
</script>
</body>
</html> </html>
+427 -408
View File
@@ -1,434 +1,453 @@
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width"> <meta name="viewport" content="width=device-width" />
<style> <style>
html, body { html,
margin: 0; body {
padding: 0; margin: 0;
height: 100%; padding: 0;
font-family: 'Arial', sans-serif; height: 100%;
} font-family: "Arial", sans-serif;
#video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(30, 30, 30);
}
#controls {
display: none;
flex-shrink: 0;
align-items: center;
justify-content: center;
padding: 10px;
flex-direction: column;
min-height: 100%;
width: 100%;
box-sizing: border-box;
background: rgb(30, 30, 30);
color: white;
}
.item {
display: grid;
grid-auto-flow: column;
grid-template-columns: auto 220px;
align-items: center;
gap: 20px;
max-width: 500px;
margin: 10px 0;
}
select, input[type="text"] {
appearance: none;
background: inherit;
color: inherit;
border: 1px solid rgb(200, 200, 200);
border-radius: 3px;
height: 40px;
padding: 0 10px;
}
select option {
color: black;
}
#message {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
color: white;
pointer-events: none;
padding: 20px;
box-sizing: border-box;
text-shadow: 0 0 5px black;
}
#publish-button {
margin-top: 10px;
appearance: none;
background: rgb(200, 200, 200);
color: black;
border-radius: 3px;
height: 50px;
padding: 0 20px;
border: none;
}
</style>
<script defer src="./publisher.js"></script>
</head>
<body>
<video id="video" muted autoplay playsinline></video>
<div id="controls">
<div id="items">
<div class="item">
<label for="video-device">video device</label>
<select id="video-device">
<option value="none">none</option>
</select>
</div>
<div class="item">
<label for="video-codec">video codec</label>
<select id="video-codec">
</select>
</div>
<div class="item">
<label for="video-bitrate">video bitrate (kbps)</label>
<input id="video-bitrate" type="text" value="10000" />
</div>
<div class="item">
<label for="video-framerate">video framerate (ideal)</label>
<input id="video-framerate" type="text" value="30" />
</div>
<div class="item">
<label for="video-width">video width (ideal)</label>
<input id="video-width" type="text" value="1920" />
</div>
<div class="item">
<label for="video-height">video height (ideal)</label>
<input id="video-height" type="text" value="1080" />
</div>
<div class="item">
<label for="audio-device">audio device</label>
<select id="audio-device">
<option value="none">none</option>
</select>
</div>
<div class="item">
<label for="audio-codec">audio codec</label>
<select id="audio-codec">
</select>
</div>
<div class="item">
<label for="audio-bitrate">audio bitrate (kbps)</label>
<input id="audio-bitrate" type="text" value="32" />
</div>
<div class="item">
<label for="audio-voice">optimize for voice</label>
<div>
<input id="audio-voice" type="checkbox" checked>
</div>
</div>
</div>
<div id="submit-line">
<button id="publish-button">publish</button>
</div>
</div>
<div id="message"></div>
<script>
const video = document.getElementById('video');
const controls = document.getElementById('controls');
const message = document.getElementById('message');
const publishButton = document.getElementById('publish-button');
let publisher = null;
const videoForm = {
device: document.getElementById('video-device'),
codec: document.getElementById('video-codec'),
bitrate: document.getElementById('video-bitrate'),
framerate: document.getElementById('video-framerate'),
width: document.getElementById('video-width'),
height: document.getElementById('video-height')
};
const audioForm = {
device: document.getElementById('audio-device'),
codec: document.getElementById('audio-codec'),
bitrate: document.getElementById('audio-bitrate'),
voice: document.getElementById('audio-voice'),
};
const setMessage = (str) => {
message.innerText = str;
};
const onStream = (stream) => {
video.srcObject = stream;
publisher = new MediaMTXWebRTCPublisher({
url: new URL('whip', window.location.href) + window.location.search,
stream,
videoCodec: videoForm.codec.value,
videoBitrate: videoForm.bitrate.value,
audioCodec: audioForm.codec.value,
audioBitrate: audioForm.bitrate.value,
audioVoice: audioForm.voice.checked,
onError: (err) => {
setMessage(err);
},
onConnected: (evt) => {
setMessage('');
},
});
};
const onPublish = () => {
controls.style.display = 'none';
video.style.display = 'block';
setMessage('connecting');
const videoId = videoForm.device.value;
const audioId = audioForm.device.value;
if (videoId !== 'screen') {
let videoOpts = false;
if (videoId !== 'none') {
videoOpts = {
deviceId: videoId,
width: { ideal: videoForm.width.value },
height: { ideal: videoForm.height.value },
frameRate: { ideal: videoForm.framerate.value },
};
}
let audioOpts = false;
if (audioId !== 'none') {
audioOpts = {
deviceId: audioId,
};
const voice = audioForm.voice.checked;
if (!voice) {
audioOpts.autoGainControl = false;
audioOpts.echoCancellation = false;
audioOpts.noiseSuppression = false;
} }
} #video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgb(30, 30, 30);
}
#controls {
display: none;
flex-shrink: 0;
align-items: center;
justify-content: center;
padding: 10px;
flex-direction: column;
min-height: 100%;
width: 100%;
box-sizing: border-box;
background: rgb(30, 30, 30);
color: white;
}
.item {
display: grid;
grid-auto-flow: column;
grid-template-columns: auto 220px;
align-items: center;
gap: 20px;
max-width: 500px;
margin: 10px 0;
}
select,
input[type="text"] {
appearance: none;
background: inherit;
color: inherit;
border: 1px solid rgb(200, 200, 200);
border-radius: 3px;
height: 40px;
padding: 0 10px;
}
select option {
color: black;
}
#message {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
text-align: center;
justify-content: center;
font-size: 16px;
font-weight: bold;
color: white;
pointer-events: none;
padding: 20px;
box-sizing: border-box;
text-shadow: 0 0 5px black;
}
#publish-button {
margin-top: 10px;
appearance: none;
background: rgb(200, 200, 200);
color: black;
border-radius: 3px;
height: 50px;
padding: 0 20px;
border: none;
}
</style>
<script defer src="./publisher.js"></script>
</head>
<body>
<video id="video" muted autoplay playsinline></video>
navigator.mediaDevices.getUserMedia({ <div id="controls">
video: videoOpts, <div id="items">
audio: audioOpts, <div class="item">
}) <label for="video-device">video device</label>
.then((stream) => onStream(stream)) <select id="video-device">
.catch((err) => { <option value="none">none</option>
setMessage(err.toString()); </select>
}); </div>
} else {
navigator.mediaDevices.getDisplayMedia({
video: {
width: { ideal: videoForm.width.value },
height: { ideal: videoForm.height.value },
frameRate: { ideal: videoForm.framerate.value },
cursor: 'always',
},
audio: true,
})
.then((stream) => onStream(stream))
.catch((err) => {
setMessage(err.toString());
});
}
};
const selectHasOption = (select, option) => { <div class="item">
for (const opt of select.querySelectorAll('option')) { <label for="video-codec">video codec</label>
if (opt.value === option) { <select id="video-codec"></select>
return true; </div>
}
}
return false;
};
const populateDevices = () => { <div class="item">
return navigator.mediaDevices.enumerateDevices() <label for="video-bitrate">video bitrate (kbps)</label>
.then((devices) => { <input id="video-bitrate" type="text" value="10000" />
for (const device of devices) { </div>
if (device.kind === 'videoinput' || device.kind === 'audioinput') {
const select = (device.kind === 'videoinput') ? videoForm.device : audioForm.device;
if (!selectHasOption(select, device.deviceId)) { <div class="item">
const opt = document.createElement('option'); <label for="video-framerate">video framerate (ideal)</label>
opt.value = device.deviceId; <input id="video-framerate" type="text" value="30" />
opt.text = device.label; </div>
select.appendChild(opt);
<div class="item">
<label for="video-width">video width (ideal)</label>
<input id="video-width" type="text" value="1920" />
</div>
<div class="item">
<label for="video-height">video height (ideal)</label>
<input id="video-height" type="text" value="1080" />
</div>
<div class="item">
<label for="audio-device">audio device</label>
<select id="audio-device">
<option value="none">none</option>
</select>
</div>
<div class="item">
<label for="audio-codec">audio codec</label>
<select id="audio-codec"></select>
</div>
<div class="item">
<label for="audio-bitrate">audio bitrate (kbps)</label>
<input id="audio-bitrate" type="text" value="32" />
</div>
<div class="item">
<label for="audio-voice">optimize for voice</label>
<div>
<input id="audio-voice" type="checkbox" checked />
</div>
</div>
</div>
<div id="submit-line">
<button id="publish-button">publish</button>
</div>
</div>
<div id="message"></div>
<script>
const video = document.getElementById("video");
const controls = document.getElementById("controls");
const message = document.getElementById("message");
const publishButton = document.getElementById("publish-button");
let publisher = null;
const videoForm = {
device: document.getElementById("video-device"),
codec: document.getElementById("video-codec"),
bitrate: document.getElementById("video-bitrate"),
framerate: document.getElementById("video-framerate"),
width: document.getElementById("video-width"),
height: document.getElementById("video-height"),
};
const audioForm = {
device: document.getElementById("audio-device"),
codec: document.getElementById("audio-codec"),
bitrate: document.getElementById("audio-bitrate"),
voice: document.getElementById("audio-voice"),
};
const setMessage = (str) => {
message.innerText = str;
};
const onStream = (stream) => {
video.srcObject = stream;
publisher = new MediaMTXWebRTCPublisher({
url: new URL("whip", window.location.href) + window.location.search,
stream,
videoCodec: videoForm.codec.value,
videoBitrate: videoForm.bitrate.value,
audioCodec: audioForm.codec.value,
audioBitrate: audioForm.bitrate.value,
audioVoice: audioForm.voice.checked,
onError: (err) => {
setMessage(err);
},
onConnected: (evt) => {
setMessage("");
},
});
};
const onPublish = () => {
controls.style.display = "none";
video.style.display = "block";
setMessage("connecting");
const videoId = videoForm.device.value;
const audioId = audioForm.device.value;
if (videoId !== "screen") {
let videoOpts = false;
if (videoId !== "none") {
videoOpts = {
deviceId: videoId,
width: { ideal: videoForm.width.value },
height: { ideal: videoForm.height.value },
frameRate: { ideal: videoForm.framerate.value },
};
}
let audioOpts = false;
if (audioId !== "none") {
audioOpts = {
deviceId: audioId,
};
const voice = audioForm.voice.checked;
if (!voice) {
audioOpts.autoGainControl = false;
audioOpts.echoCancellation = false;
audioOpts.noiseSuppression = false;
}
}
navigator.mediaDevices
.getUserMedia({
video: videoOpts,
audio: audioOpts,
})
.then((stream) => onStream(stream))
.catch((err) => {
setMessage(err.toString());
});
} else {
navigator.mediaDevices
.getDisplayMedia({
video: {
width: { ideal: videoForm.width.value },
height: { ideal: videoForm.height.value },
frameRate: { ideal: videoForm.framerate.value },
cursor: "always",
},
audio: true,
})
.then((stream) => onStream(stream))
.catch((err) => {
setMessage(err.toString());
});
}
};
const selectHasOption = (select, option) => {
for (const opt of select.querySelectorAll("option")) {
if (opt.value === option) {
return true;
} }
} }
} return false;
};
if (navigator.mediaDevices.getDisplayMedia !== undefined) { const populateDevices = () => {
const opt = document.createElement('option'); return navigator.mediaDevices.enumerateDevices().then((devices) => {
opt.value = 'screen'; for (const device of devices) {
opt.text = 'screen'; if (device.kind === "videoinput" || device.kind === "audioinput") {
videoForm.device.appendChild(opt); const select =
} device.kind === "videoinput"
? videoForm.device
: audioForm.device;
// set first available device as default device if (!selectHasOption(select, device.deviceId)) {
if (videoForm.device.children.length !== 0) { const opt = document.createElement("option");
videoForm.device.value = videoForm.device.children[1].value; opt.value = device.deviceId;
} opt.text = device.label;
select.appendChild(opt);
}
}
}
// set first available device as default device if (navigator.mediaDevices.getDisplayMedia !== undefined) {
if (audioForm.device.children.length !== 0) { const opt = document.createElement("option");
audioForm.device.value = audioForm.device.children[1].value; opt.value = "screen";
} opt.text = "screen";
}); videoForm.device.appendChild(opt);
}; }
const populateCodecs = () => { // set first available device as default device
const tempPC = new RTCPeerConnection({}); if (videoForm.device.children.length !== 0) {
tempPC.addTransceiver('video', { direction: 'sendonly' }); videoForm.device.value = videoForm.device.children[1].value;
tempPC.addTransceiver('audio', { direction: 'sendonly' }); }
return tempPC.createOffer() // set first available device as default device
.then((desc) => { if (audioForm.device.children.length !== 0) {
const sdp = desc.sdp.toLowerCase(); audioForm.device.value = audioForm.device.children[1].value;
}
for (const codec of ['av1/90000', 'vp9/90000', 'vp8/90000', 'h264/90000', 'h265/90000']) {
if (sdp.includes(codec)) {
const opt = document.createElement('option');
opt.value = codec;
opt.text = codec.split('/')[0].toUpperCase();
videoForm.codec.appendChild(opt);
}
}
for (const codec of ['opus/48000', 'g722/8000', 'pcmu/8000', 'pcma/8000']) {
if (sdp.includes(codec)) {
const opt = document.createElement('option');
opt.value = codec;
opt.text = codec.split('/')[0].toUpperCase();
audioForm.codec.appendChild(opt);
}
}
tempPC.close();
});
};
const populateOptions = () => {
setMessage('loading devices');
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then((tempStream) => {
return Promise.all([
populateDevices(),
populateCodecs(),
])
.then(() => {
// free the webcam to prevent 'NotReadableError' on Android
tempStream.getTracks()
.forEach((track) => track.stop());
setMessage('');
loadValuesFromQuery();
setupEventListeners();
video.style.display = 'none';
controls.style.display = 'flex';
}); });
}) };
.catch((err) => {
setMessage(err.toString());
});
};
const setupEventListeners = () => { const populateCodecs = () => {
const url = new URL(window.location.href); const tempPC = new RTCPeerConnection({});
const inputs = [...Object.values(videoForm), ...Object.values(audioForm)] tempPC.addTransceiver("video", { direction: "sendonly" });
tempPC.addTransceiver("audio", { direction: "sendonly" });
for (const input of inputs) { return tempPC.createOffer().then((desc) => {
if (input instanceof HTMLInputElement && input.type === 'text') { const sdp = desc.sdp.toLowerCase();
input.addEventListener('input', () => {
url.searchParams.set(input.id, input.value);
window.history.replaceState(null, null, url);
})
}
if (input instanceof HTMLInputElement && input.type === 'checkbox') { for (const codec of [
input.addEventListener('input', () => { "av1/90000",
url.searchParams.set(input.id, input.checked); "vp9/90000",
window.history.replaceState(null, null, url); "vp8/90000",
}) "h264/90000",
} "h265/90000",
]) {
if (sdp.includes(codec)) {
const opt = document.createElement("option");
opt.value = codec;
opt.text = codec.split("/")[0].toUpperCase();
videoForm.codec.appendChild(opt);
}
}
if (input instanceof HTMLSelectElement) { for (const codec of [
input.addEventListener('input', () => { "opus/48000",
url.searchParams.set(input.id, input.value); "g722/8000",
window.history.replaceState(null, null, url); "pcmu/8000",
}) "pcma/8000",
} ]) {
} if (sdp.includes(codec)) {
}; const opt = document.createElement("option");
opt.value = codec;
opt.text = codec.split("/")[0].toUpperCase();
audioForm.codec.appendChild(opt);
}
}
const loadValuesFromQuery = () => { tempPC.close();
const params = new URLSearchParams(window.location.search); });
const inputs = [...Object.values(videoForm), ...Object.values(audioForm)] };
for (const input of inputs) { const populateOptions = () => {
const value = params.get(input.id); setMessage("loading devices");
if (value) {
if (input instanceof HTMLInputElement && input.type === 'text') {
input.value = value;
} else if (input instanceof HTMLInputElement && input.type === 'checkbox') {
input.checked = value === 'true';
} else if (input instanceof HTMLSelectElement) {
input.value = value;
}
}
}
};
window.addEventListener('load', () => { navigator.mediaDevices
if (navigator.mediaDevices === undefined) { .getUserMedia({ video: true, audio: true })
setMessage(`can't access webcams or microphones. Make sure that WebRTC encryption is enabled.`); .then((tempStream) => {
return; return Promise.all([populateDevices(), populateCodecs()]).then(
} () => {
// free the webcam to prevent 'NotReadableError' on Android
tempStream.getTracks().forEach((track) => track.stop());
publishButton.addEventListener('click', onPublish); setMessage("");
populateOptions();
});
window.addEventListener('beforeunload', () => { loadValuesFromQuery();
if (publisher !== null) { setupEventListeners();
publisher.close();
}
});
</script> video.style.display = "none";
controls.style.display = "flex";
},
);
})
.catch((err) => {
setMessage(err.toString());
});
};
</body> const setupEventListeners = () => {
const url = new URL(window.location.href);
const inputs = [
...Object.values(videoForm),
...Object.values(audioForm),
];
for (const input of inputs) {
if (input instanceof HTMLInputElement && input.type === "text") {
input.addEventListener("input", () => {
url.searchParams.set(input.id, input.value);
window.history.replaceState(null, null, url);
});
}
if (input instanceof HTMLInputElement && input.type === "checkbox") {
input.addEventListener("input", () => {
url.searchParams.set(input.id, input.checked);
window.history.replaceState(null, null, url);
});
}
if (input instanceof HTMLSelectElement) {
input.addEventListener("input", () => {
url.searchParams.set(input.id, input.value);
window.history.replaceState(null, null, url);
});
}
}
};
const loadValuesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
const inputs = [
...Object.values(videoForm),
...Object.values(audioForm),
];
for (const input of inputs) {
const value = params.get(input.id);
if (value) {
if (input instanceof HTMLInputElement && input.type === "text") {
input.value = value;
} else if (
input instanceof HTMLInputElement &&
input.type === "checkbox"
) {
input.checked = value === "true";
} else if (input instanceof HTMLSelectElement) {
input.value = value;
}
}
}
};
window.addEventListener("load", () => {
if (navigator.mediaDevices === undefined) {
setMessage(
`can't access webcams or microphones. Make sure that WebRTC encryption is enabled.`,
);
return;
}
publishButton.addEventListener("click", onPublish);
populateOptions();
});
window.addEventListener("beforeunload", () => {
if (publisher !== null) {
publisher.close();
}
});
</script>
</body>
</html> </html>
+167 -128
View File
@@ -1,4 +1,4 @@
'use strict'; "use strict";
/** /**
* @callback OnError * @callback OnError
@@ -44,7 +44,7 @@ class MediaMTXWebRTCPublisher {
constructor(conf) { constructor(conf) {
this.#retryPause = 2000; this.#retryPause = 2000;
this.#conf = conf; this.#conf = conf;
this.#state = 'running'; this.#state = "running";
this.#restartTimeout = null; this.#restartTimeout = null;
this.#pc = null; this.#pc = null;
this.#offerData = null; this.#offerData = null;
@@ -57,7 +57,7 @@ class MediaMTXWebRTCPublisher {
* Close the publisher and all its resources. * Close the publisher and all its resources.
*/ */
close = () => { close = () => {
this.#state = 'closed'; this.#state = "closed";
if (this.#pc !== null) { if (this.#pc !== null) {
this.#pc.close(); this.#pc.close();
@@ -73,36 +73,40 @@ class MediaMTXWebRTCPublisher {
} }
static #linkToIceServers(links) { static #linkToIceServers(links) {
return (links !== null) ? links.split(', ').map((link) => { return links !== null
const m = link.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i); ? links.split(", ").map((link) => {
const ret = { const m = link.match(
urls: [m[1]], /^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i,
}; );
const ret = {
urls: [m[1]],
};
if (m[3] !== undefined) { if (m[3] !== undefined) {
ret.username = this.#unquoteCredential(m[3]); ret.username = this.#unquoteCredential(m[3]);
ret.credential = this.#unquoteCredential(m[4]); ret.credential = this.#unquoteCredential(m[4]);
ret.credentialType = 'password'; ret.credentialType = "password";
} }
return ret; return ret;
}) : []; })
: [];
} }
static #parseOffer(offer) { static #parseOffer(offer) {
const ret = { const ret = {
iceUfrag: '', iceUfrag: "",
icePwd: '', icePwd: "",
medias: [], medias: [],
}; };
for (const line of offer.split('\r\n')) { for (const line of offer.split("\r\n")) {
if (line.startsWith('m=')) { if (line.startsWith("m=")) {
ret.medias.push(line.slice('m='.length)); ret.medias.push(line.slice("m=".length));
} else if (ret.iceUfrag === '' && line.startsWith('a=ice-ufrag:')) { } else if (ret.iceUfrag === "" && line.startsWith("a=ice-ufrag:")) {
ret.iceUfrag = line.slice('a=ice-ufrag:'.length); ret.iceUfrag = line.slice("a=ice-ufrag:".length);
} else if (ret.icePwd === '' && line.startsWith('a=ice-pwd:')) { } else if (ret.icePwd === "" && line.startsWith("a=ice-pwd:")) {
ret.icePwd = line.slice('a=ice-pwd:'.length); ret.icePwd = line.slice("a=ice-pwd:".length);
} }
} }
@@ -119,18 +123,17 @@ class MediaMTXWebRTCPublisher {
candidatesByMedia[mid].push(candidate); candidatesByMedia[mid].push(candidate);
} }
let frag = 'a=ice-ufrag:' + od.iceUfrag + '\r\n' let frag =
+ 'a=ice-pwd:' + od.icePwd + '\r\n'; "a=ice-ufrag:" + od.iceUfrag + "\r\n" + "a=ice-pwd:" + od.icePwd + "\r\n";
let mid = 0; let mid = 0;
for (const media of od.medias) { for (const media of od.medias) {
if (candidatesByMedia[mid] !== undefined) { if (candidatesByMedia[mid] !== undefined) {
frag += 'm=' + media + '\r\n' frag += "m=" + media + "\r\n" + "a=mid:" + mid + "\r\n";
+ 'a=mid:' + mid + '\r\n';
for (const candidate of candidatesByMedia[mid]) { for (const candidate of candidatesByMedia[mid]) {
frag += 'a=' + candidate.candidate + '\r\n'; frag += "a=" + candidate.candidate + "\r\n";
} }
} }
mid++; mid++;
@@ -140,16 +143,16 @@ class MediaMTXWebRTCPublisher {
} }
static #setCodec(section, codec) { static #setCodec(section, codec) {
const lines = section.split('\r\n'); const lines = section.split("\r\n");
const lines2 = []; const lines2 = [];
const payloadFormats = []; const payloadFormats = [];
for (const line of lines) { for (const line of lines) {
if (!line.startsWith('a=rtpmap:')) { if (!line.startsWith("a=rtpmap:")) {
lines2.push(line); lines2.push(line);
} else { } else {
if (line.toLowerCase().includes(codec)) { if (line.toLowerCase().includes(codec)) {
payloadFormats.push(line.slice('a=rtpmap:'.length).split(' ')[0]); payloadFormats.push(line.slice("a=rtpmap:".length).split(" ")[0]);
lines2.push(line); lines2.push(line);
} }
} }
@@ -161,13 +164,19 @@ class MediaMTXWebRTCPublisher {
for (const line of lines2) { for (const line of lines2) {
if (firstLine) { if (firstLine) {
firstLine = false; firstLine = false;
lines3.push(line.split(' ').slice(0, 3).concat(payloadFormats).join(' ')); lines3.push(
} else if (line.startsWith('a=fmtp:')) { line.split(" ").slice(0, 3).concat(payloadFormats).join(" "),
if (payloadFormats.includes(line.slice('a=fmtp:'.length).split(' ')[0])) { );
} else if (line.startsWith("a=fmtp:")) {
if (
payloadFormats.includes(line.slice("a=fmtp:".length).split(" ")[0])
) {
lines3.push(line); lines3.push(line);
} }
} else if (line.startsWith('a=rtcp-fb:')) { } else if (line.startsWith("a=rtcp-fb:")) {
if (payloadFormats.includes(line.slice('a=rtcp-fb:'.length).split(' ')[0])) { if (
payloadFormats.includes(line.slice("a=rtcp-fb:".length).split(" ")[0])
) {
lines3.push(line); lines3.push(line);
} }
} else { } else {
@@ -175,76 +184,93 @@ class MediaMTXWebRTCPublisher {
} }
} }
return lines3.join('\r\n'); return lines3.join("\r\n");
} }
static #setVideoBitrate(section, bitrate) { static #setVideoBitrate(section, bitrate) {
let lines = section.split('\r\n'); let lines = section.split("\r\n");
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('c=')) { if (lines[i].startsWith("c=")) {
lines = [...lines.slice(0, i+1), 'b=TIAS:' + (parseInt(bitrate) * 1024).toString(), ...lines.slice(i+1)]; lines = [
break ...lines.slice(0, i + 1),
} "b=TIAS:" + (parseInt(bitrate) * 1024).toString(),
} ...lines.slice(i + 1),
];
return lines.join('\r\n');
}
static #setAudioBitrate(section, bitrate, voice) {
let opusPayloadFormat = '';
let lines = section.split('\r\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('a=rtpmap:') && lines[i].toLowerCase().includes('opus/')) {
opusPayloadFormat = lines[i].slice('a=rtpmap:'.length).split(' ')[0];
break; break;
} }
} }
if (opusPayloadFormat === '') { return lines.join("\r\n");
}
static #setAudioBitrate(section, bitrate, voice) {
let opusPayloadFormat = "";
let lines = section.split("\r\n");
for (let i = 0; i < lines.length; i++) {
if (
lines[i].startsWith("a=rtpmap:") &&
lines[i].toLowerCase().includes("opus/")
) {
opusPayloadFormat = lines[i].slice("a=rtpmap:".length).split(" ")[0];
break;
}
}
if (opusPayloadFormat === "") {
return section; return section;
} }
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('a=fmtp:' + opusPayloadFormat + ' ')) { if (lines[i].startsWith("a=fmtp:" + opusPayloadFormat + " ")) {
if (voice) { if (voice) {
lines[i] = 'a=fmtp:' + opusPayloadFormat + ' minptime=10;useinbandfec=1;maxaveragebitrate=' lines[i] =
+ (parseInt(bitrate) * 1024).toString(); "a=fmtp:" +
opusPayloadFormat +
" minptime=10;useinbandfec=1;maxaveragebitrate=" +
(parseInt(bitrate) * 1024).toString();
} else { } else {
lines[i] = 'a=fmtp:' + opusPayloadFormat + ' maxplaybackrate=48000;stereo=1;sprop-stereo=1;maxaveragebitrate=' lines[i] =
+ (parseInt(bitrate) * 1024).toString(); "a=fmtp:" +
opusPayloadFormat +
" maxplaybackrate=48000;stereo=1;sprop-stereo=1;maxaveragebitrate=" +
(parseInt(bitrate) * 1024).toString();
} }
} }
} }
return lines.join('\r\n'); return lines.join("\r\n");
} }
static #editOffer(sdp, videoCodec, audioCodec, audioBitrate, audioVoice) { static #editOffer(sdp, videoCodec, audioCodec, audioBitrate, audioVoice) {
const sections = sdp.split('m='); const sections = sdp.split("m=");
for (let i = 0; i < sections.length; i++) { for (let i = 0; i < sections.length; i++) {
if (sections[i].startsWith('video')) { if (sections[i].startsWith("video")) {
sections[i] = this.#setCodec(sections[i], videoCodec); sections[i] = this.#setCodec(sections[i], videoCodec);
} else if (sections[i].startsWith('audio')) { } else if (sections[i].startsWith("audio")) {
sections[i] = this.#setAudioBitrate(this.#setCodec(sections[i], audioCodec), audioBitrate, audioVoice); sections[i] = this.#setAudioBitrate(
this.#setCodec(sections[i], audioCodec),
audioBitrate,
audioVoice,
);
} }
} }
return sections.join('m='); return sections.join("m=");
} }
static #editAnswer(sdp, videoBitrate) { static #editAnswer(sdp, videoBitrate) {
const sections = sdp.split('m='); const sections = sdp.split("m=");
for (let i = 0; i < sections.length; i++) { for (let i = 0; i < sections.length; i++) {
if (sections[i].startsWith('video')) { if (sections[i].startsWith("video")) {
sections[i] = this.#setVideoBitrate(sections[i], videoBitrate); sections[i] = this.#setVideoBitrate(sections[i], videoBitrate);
} }
} }
return sections.join('m='); return sections.join("m=");
} }
#start() { #start() {
@@ -259,7 +285,7 @@ class MediaMTXWebRTCPublisher {
/** @param {string} err */ /** @param {string} err */
#handleError(err) { #handleError(err) {
if (this.#state === 'running') { if (this.#state === "running") {
if (this.#pc !== null) { if (this.#pc !== null) {
this.#pc.close(); this.#pc.close();
this.#pc = null; this.#pc = null;
@@ -269,17 +295,17 @@ class MediaMTXWebRTCPublisher {
if (this.#sessionUrl !== null) { if (this.#sessionUrl !== null) {
fetch(this.#sessionUrl, { fetch(this.#sessionUrl, {
method: 'DELETE', method: "DELETE",
}); });
this.#sessionUrl = null; this.#sessionUrl = null;
} }
this.#queuedCandidates = []; this.#queuedCandidates = [];
this.#state = 'restarting'; this.#state = "restarting";
this.#restartTimeout = window.setTimeout(() => { this.#restartTimeout = window.setTimeout(() => {
this.#restartTimeout = null; this.#restartTimeout = null;
this.#state = 'running'; this.#state = "running";
this.#start(); this.#start();
}, this.#retryPause); }, this.#retryPause);
@@ -290,35 +316,36 @@ class MediaMTXWebRTCPublisher {
} }
#authHeader() { #authHeader() {
if (this.#conf.user !== undefined && this.#conf.user !== '') { if (this.#conf.user !== undefined && this.#conf.user !== "") {
const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`); const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`);
return {'Authorization': `Basic ${credentials}`}; return { Authorization: `Basic ${credentials}` };
} }
if (this.#conf.token !== undefined && this.#conf.token !== '') { if (this.#conf.token !== undefined && this.#conf.token !== "") {
return {'Authorization': `Bearer ${this.#conf.token}`}; return { Authorization: `Bearer ${this.#conf.token}` };
} }
return {}; return {};
} }
#requestICEServers() { #requestICEServers() {
return fetch(this.#conf.url, { return fetch(this.#conf.url, {
method: 'OPTIONS', method: "OPTIONS",
headers: { headers: {
...this.#authHeader(), ...this.#authHeader(),
}, },
}) }).then((res) =>
.then((res) => MediaMTXWebRTCPublisher.#linkToIceServers(res.headers.get('Link'))); MediaMTXWebRTCPublisher.#linkToIceServers(res.headers.get("Link")),
);
} }
#setupPeerConnection(iceServers) { #setupPeerConnection(iceServers) {
if (this.#state !== 'running') { if (this.#state !== "running") {
throw new Error('closed'); throw new Error("closed");
} }
this.#pc = new RTCPeerConnection({ this.#pc = new RTCPeerConnection({
iceServers, iceServers,
// https://webrtc.org/getting-started/unified-plan-transition-guide // https://webrtc.org/getting-started/unified-plan-transition-guide
sdpSemantics: 'unified-plan', sdpSemantics: "unified-plan",
}); });
this.#pc.onicecandidate = (evt) => this.#onLocalCandidate(evt); this.#pc.onicecandidate = (evt) => this.#onLocalCandidate(evt);
@@ -328,18 +355,16 @@ class MediaMTXWebRTCPublisher {
this.#pc.addTrack(track, this.#conf.stream); this.#pc.addTrack(track, this.#conf.stream);
}); });
return this.#pc.createOffer() return this.#pc.createOffer().then((offer) => {
.then((offer) => { this.#offerData = MediaMTXWebRTCPublisher.#parseOffer(offer.sdp);
this.#offerData = MediaMTXWebRTCPublisher.#parseOffer(offer.sdp);
return this.#pc.setLocalDescription(offer) return this.#pc.setLocalDescription(offer).then(() => offer.sdp);
.then(() => offer.sdp); });
});
} }
#sendOffer(offer) { #sendOffer(offer) {
if (this.#state !== 'running') { if (this.#state !== "running") {
throw new Error('closed'); throw new Error("closed");
} }
offer = MediaMTXWebRTCPublisher.#editOffer( offer = MediaMTXWebRTCPublisher.#editOffer(
@@ -347,45 +372,56 @@ class MediaMTXWebRTCPublisher {
this.#conf.videoCodec, this.#conf.videoCodec,
this.#conf.audioCodec, this.#conf.audioCodec,
this.#conf.audioBitrate, this.#conf.audioBitrate,
this.#conf.audioVoice); this.#conf.audioVoice,
);
return fetch(this.#conf.url, { return fetch(this.#conf.url, {
method: 'POST', method: "POST",
headers: { headers: {
...this.#authHeader(), ...this.#authHeader(),
'Content-Type': 'application/sdp', "Content-Type": "application/sdp",
}, },
body: offer, body: offer,
}) }).then((res) => {
.then((res) => { switch (res.status) {
switch (res.status) { case 201:
case 201: break;
break; case 400:
case 400: return res.json().then((e) => {
return res.json().then((e) => { throw new Error(e.error); }); throw new Error(e.error);
default: });
throw new Error(`bad status code ${res.status}`); default:
} throw new Error(`bad status code ${res.status}`);
}
this.#sessionUrl = new URL(res.headers.get('location'), this.#conf.url).toString(); this.#sessionUrl = new URL(
res.headers.get("location"),
this.#conf.url,
).toString();
return res.text(); return res.text();
}); });
} }
#setAnswer(answer) { #setAnswer(answer) {
if (this.#state !== 'running') { if (this.#state !== "running") {
throw new Error('closed'); throw new Error("closed");
} }
answer = MediaMTXWebRTCPublisher.#editAnswer(answer, this.#conf.videoBitrate); answer = MediaMTXWebRTCPublisher.#editAnswer(
answer,
this.#conf.videoBitrate,
);
return this.#pc.setRemoteDescription(new RTCSessionDescription({ return this.#pc
type: 'answer', .setRemoteDescription(
sdp: answer, new RTCSessionDescription({
})) type: "answer",
sdp: answer,
}),
)
.then(() => { .then(() => {
if (this.#state !== 'running') { if (this.#state !== "running") {
return; return;
} }
@@ -397,7 +433,7 @@ class MediaMTXWebRTCPublisher {
} }
#onLocalCandidate(evt) { #onLocalCandidate(evt) {
if (this.#state !== 'running') { if (this.#state !== "running") {
return; return;
} }
@@ -412,19 +448,22 @@ class MediaMTXWebRTCPublisher {
#sendLocalCandidates(candidates) { #sendLocalCandidates(candidates) {
fetch(this.#sessionUrl, { fetch(this.#sessionUrl, {
method: 'PATCH', method: "PATCH",
headers: { headers: {
'Content-Type': 'application/trickle-ice-sdpfrag', "Content-Type": "application/trickle-ice-sdpfrag",
'If-Match': '*', "If-Match": "*",
}, },
body: MediaMTXWebRTCPublisher.#generateSdpFragment(this.#offerData, candidates), body: MediaMTXWebRTCPublisher.#generateSdpFragment(
this.#offerData,
candidates,
),
}) })
.then((res) => { .then((res) => {
switch (res.status) { switch (res.status) {
case 204: case 204:
break; break;
case 404: case 404:
throw new Error('stream not found'); throw new Error("stream not found");
default: default:
throw new Error(`bad status code ${res.status}`); throw new Error(`bad status code ${res.status}`);
} }
@@ -435,7 +474,7 @@ class MediaMTXWebRTCPublisher {
} }
#onConnectionState() { #onConnectionState() {
if (this.#state !== 'running') { if (this.#state !== "running") {
return; return;
} }
@@ -443,17 +482,17 @@ class MediaMTXWebRTCPublisher {
// the close() method being called at all. // the close() method being called at all.
// It happens when the other peer sends a termination // It happens when the other peer sends a termination
// message like a DTLS CloseNotify. // message like a DTLS CloseNotify.
if (this.#pc.connectionState === 'failed' if (
|| this.#pc.connectionState === 'closed' this.#pc.connectionState === "failed" ||
this.#pc.connectionState === "closed"
) { ) {
this.#handleError('peer connection closed'); this.#handleError("peer connection closed");
} else if (this.#pc.connectionState === 'connected') { } else if (this.#pc.connectionState === "connected") {
if (this.#conf.onConnected !== undefined) { if (this.#conf.onConnected !== undefined) {
this.#conf.onConnected(); this.#conf.onConnected();
} }
} }
} }
} }
window.MediaMTXWebRTCPublisher = MediaMTXWebRTCPublisher; window.MediaMTXWebRTCPublisher = MediaMTXWebRTCPublisher;
+107 -107
View File
@@ -1,115 +1,115 @@
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width"> <meta name="viewport" content="width=device-width" />
<style> <style>
html, body { html,
margin: 0; body {
padding: 0; margin: 0;
height: 100%; padding: 0;
font-family: 'Arial', sans-serif; height: 100%;
} font-family: "Arial", sans-serif;
#video { }
position: absolute; #video {
top: 0; position: absolute;
left: 0; top: 0;
width: 100%; left: 0;
height: 100%; width: 100%;
background: rgb(30, 30, 30); height: 100%;
} background: rgb(30, 30, 30);
#message { }
position: absolute; #message {
left: 0; position: absolute;
top: 0; left: 0;
width: 100%; top: 0;
height: 100%; width: 100%;
display: flex; height: 100%;
align-items: center; display: flex;
text-align: center; align-items: center;
justify-content: center; text-align: center;
font-size: 16px; justify-content: center;
font-weight: bold; font-size: 16px;
color: white; font-weight: bold;
pointer-events: none; color: white;
padding: 20px; pointer-events: none;
box-sizing: border-box; padding: 20px;
text-shadow: 0 0 5px black; box-sizing: border-box;
} text-shadow: 0 0 5px black;
</style> }
<script defer src="./reader.js"></script> </style>
</head> <script defer src="./reader.js"></script>
<body> </head>
<body>
<video id="video"></video>
<div id="message"></div>
<video id="video"></video> <script>
<div id="message"></div> const video = document.getElementById("video");
const message = document.getElementById("message");
let defaultControls = false;
let reader = null;
<script> const setMessage = (str) => {
if (str !== "") {
const video = document.getElementById('video'); video.controls = false;
const message = document.getElementById('message'); } else {
let defaultControls = false; video.controls = defaultControls;
let reader = null; }
message.innerText = str;
const setMessage = (str) => {
if (str !== '') {
video.controls = false;
} else {
video.controls = defaultControls;
}
message.innerText = str;
};
const parseBoolString = (str, defaultVal) => {
str = (str || '');
if (['1', 'yes', 'true'].includes(str.toLowerCase())) {
return true;
}
if (['0', 'no', 'false'].includes(str.toLowerCase())) {
return false;
}
return defaultVal;
};
const loadAttributesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
video.controls = parseBoolString(params.get('controls'), true);
video.muted = parseBoolString(params.get('muted'), true);
video.autoplay = parseBoolString(params.get('autoplay'), true);
video.playsInline = parseBoolString(params.get('playsinline'), true);
video.disablepictureinpicture = parseBoolString(params.get('disablepictureinpicture'), false);
defaultControls = video.controls;
};
window.addEventListener('load', () => {
loadAttributesFromQuery();
reader = new MediaMTXWebRTCReader({
url: new URL('whep', window.location.href) + window.location.search,
onError: (err) => {
setMessage(err);
},
onTrack: (evt) => {
setMessage('');
video.srcObject = evt.streams[0];
},
onDataChannel: (evt) => {
evt.channel.binaryType = 'arraybuffer';
evt.channel.onmessage = (evt) => {
console.log('data channel message', evt.data);
}; };
},
});
});
window.addEventListener('beforeunload', () => { const parseBoolString = (str, defaultVal) => {
if (reader !== null) { str = str || "";
reader.close();
}
});
</script> if (["1", "yes", "true"].includes(str.toLowerCase())) {
return true;
}
if (["0", "no", "false"].includes(str.toLowerCase())) {
return false;
}
return defaultVal;
};
</body> const loadAttributesFromQuery = () => {
const params = new URLSearchParams(window.location.search);
video.controls = parseBoolString(params.get("controls"), true);
video.muted = parseBoolString(params.get("muted"), true);
video.autoplay = parseBoolString(params.get("autoplay"), true);
video.playsInline = parseBoolString(params.get("playsinline"), true);
video.disablepictureinpicture = parseBoolString(
params.get("disablepictureinpicture"),
false,
);
defaultControls = video.controls;
};
window.addEventListener("load", () => {
loadAttributesFromQuery();
reader = new MediaMTXWebRTCReader({
url: new URL("whep", window.location.href) + window.location.search,
onError: (err) => {
setMessage(err);
},
onTrack: (evt) => {
setMessage("");
video.srcObject = evt.streams[0];
},
onDataChannel: (evt) => {
evt.channel.binaryType = "arraybuffer";
evt.channel.onmessage = (evt) => {
console.log("data channel message", evt.data);
};
},
});
});
window.addEventListener("beforeunload", () => {
if (reader !== null) {
reader.close();
}
});
</script>
</body>
</html> </html>
+245 -165
View File
@@ -1,4 +1,4 @@
'use strict'; "use strict";
/** /**
* @callback OnError * @callback OnError
@@ -46,7 +46,7 @@ class MediaMTXWebRTCReader {
constructor(conf) { constructor(conf) {
this.#retryPause = 2000; this.#retryPause = 2000;
this.#conf = conf; this.#conf = conf;
this.#state = 'getting_codecs'; this.#state = "getting_codecs";
this.#restartTimeout = null; this.#restartTimeout = null;
this.#pc = null; this.#pc = null;
this.#offerData = null; this.#offerData = null;
@@ -59,7 +59,7 @@ class MediaMTXWebRTCReader {
* Close the reader and all its resources. * Close the reader and all its resources.
*/ */
close() { close() {
this.#state = 'closed'; this.#state = "closed";
if (this.#pc !== null) { if (this.#pc !== null) {
this.#pc.close(); this.#pc.close();
@@ -73,54 +73,59 @@ class MediaMTXWebRTCReader {
static #supportsNonAdvertisedCodec(codec, fmtp) { static #supportsNonAdvertisedCodec(codec, fmtp) {
return new Promise((resolve) => { return new Promise((resolve) => {
const pc = new RTCPeerConnection({ iceServers: [] }); const pc = new RTCPeerConnection({ iceServers: [] });
const mediaType = 'audio'; const mediaType = "audio";
let payloadType = ''; let payloadType = "";
pc.addTransceiver(mediaType, { direction: 'recvonly' }); pc.addTransceiver(mediaType, { direction: "recvonly" });
pc.createOffer() pc.createOffer()
.then((offer) => { .then((offer) => {
if (offer.sdp === undefined) { if (offer.sdp === undefined) {
throw new Error('SDP not present'); throw new Error("SDP not present");
} }
if (offer.sdp.includes(` ${codec}`)) { // codec is advertised, there's no need to add it manually if (offer.sdp.includes(` ${codec}`)) {
throw new Error('already present'); // codec is advertised, there's no need to add it manually
throw new Error("already present");
} }
const sections = offer.sdp.split(`m=${mediaType}`); const sections = offer.sdp.split(`m=${mediaType}`);
const payloadTypes = sections.slice(1) const payloadTypes = sections
.map((s) => s.split('\r\n')[0].split(' ').slice(3)) .slice(1)
.map((s) => s.split("\r\n")[0].split(" ").slice(3))
.reduce((prev, cur) => [...prev, ...cur], []); .reduce((prev, cur) => [...prev, ...cur], []);
payloadType = this.#reservePayloadType(payloadTypes); payloadType = this.#reservePayloadType(payloadTypes);
const lines = sections[1].split('\r\n'); const lines = sections[1].split("\r\n");
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} ${codec}`); lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} ${codec}`);
if (fmtp !== undefined) { if (fmtp !== undefined) {
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} ${fmtp}`); lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} ${fmtp}`);
} }
sections[1] = lines.join('\r\n'); sections[1] = lines.join("\r\n");
offer.sdp = sections.join(`m=${mediaType}`); offer.sdp = sections.join(`m=${mediaType}`);
return pc.setLocalDescription(offer); return pc.setLocalDescription(offer);
}) })
.then(() => ( .then(() =>
pc.setRemoteDescription(new RTCSessionDescription({ pc.setRemoteDescription(
type: 'answer', new RTCSessionDescription({
sdp: 'v=0\r\n' type: "answer",
+ 'o=- 6539324223450680508 0 IN IP4 0.0.0.0\r\n' sdp:
+ 's=-\r\n' "v=0\r\n" +
+ 't=0 0\r\n' "o=- 6539324223450680508 0 IN IP4 0.0.0.0\r\n" +
+ 'a=fingerprint:sha-256 0D:9F:78:15:42:B5:4B:E6:E2:94:3E:5B:37:78:E1:4B:54:59:A3:36:3A:E5:05:EB:27:EE:8F:D2:2D:41:29:25\r\n' "s=-\r\n" +
+ `m=${mediaType} 9 UDP/TLS/RTP/SAVPF ${payloadType}\r\n` "t=0 0\r\n" +
+ 'c=IN IP4 0.0.0.0\r\n' "a=fingerprint:sha-256 0D:9F:78:15:42:B5:4B:E6:E2:94:3E:5B:37:78:E1:4B:54:59:A3:36:3A:E5:05:EB:27:EE:8F:D2:2D:41:29:25\r\n" +
+ 'a=ice-pwd:7c3bf4770007e7432ee4ea4d697db675\r\n' `m=${mediaType} 9 UDP/TLS/RTP/SAVPF ${payloadType}\r\n` +
+ 'a=ice-ufrag:29e036dc\r\n' "c=IN IP4 0.0.0.0\r\n" +
+ 'a=sendonly\r\n' "a=ice-pwd:7c3bf4770007e7432ee4ea4d697db675\r\n" +
+ 'a=rtcp-mux\r\n' "a=ice-ufrag:29e036dc\r\n" +
+ `a=rtpmap:${payloadType} ${codec}\r\n` "a=sendonly\r\n" +
+ ((fmtp !== undefined) ? `a=fmtp:${payloadType} ${fmtp}\r\n` : ''), "a=rtcp-mux\r\n" +
})) `a=rtpmap:${payloadType} ${codec}\r\n` +
)) (fmtp !== undefined ? `a=fmtp:${payloadType} ${fmtp}\r\n` : ""),
}),
),
)
.then(() => { .then(() => {
resolve(true); resolve(true);
}) })
@@ -138,36 +143,40 @@ class MediaMTXWebRTCReader {
} }
static #linkToIceServers(links) { static #linkToIceServers(links) {
return (links !== null) ? links.split(', ').map((link) => { return links !== null
const m = link.match(/^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i); ? links.split(", ").map((link) => {
const ret = { const m = link.match(
urls: [m[1]], /^<(.+?)>; rel="ice-server"(; username="(.*?)"; credential="(.*?)"; credential-type="password")?/i,
}; );
const ret = {
urls: [m[1]],
};
if (m[3] !== undefined) { if (m[3] !== undefined) {
ret.username = this.#unquoteCredential(m[3]); ret.username = this.#unquoteCredential(m[3]);
ret.credential = this.#unquoteCredential(m[4]); ret.credential = this.#unquoteCredential(m[4]);
ret.credentialType = 'password'; ret.credentialType = "password";
} }
return ret; return ret;
}) : []; })
: [];
} }
static #parseOffer(sdp) { static #parseOffer(sdp) {
const ret = { const ret = {
iceUfrag: '', iceUfrag: "",
icePwd: '', icePwd: "",
medias: [], medias: [],
}; };
for (const line of sdp.split('\r\n')) { for (const line of sdp.split("\r\n")) {
if (line.startsWith('m=')) { if (line.startsWith("m=")) {
ret.medias.push(line.slice('m='.length)); ret.medias.push(line.slice("m=".length));
} else if (ret.iceUfrag === '' && line.startsWith('a=ice-ufrag:')) { } else if (ret.iceUfrag === "" && line.startsWith("a=ice-ufrag:")) {
ret.iceUfrag = line.slice('a=ice-ufrag:'.length); ret.iceUfrag = line.slice("a=ice-ufrag:".length);
} else if (ret.icePwd === '' && line.startsWith('a=ice-pwd:')) { } else if (ret.icePwd === "" && line.startsWith("a=ice-pwd:")) {
ret.icePwd = line.slice('a=ice-pwd:'.length); ret.icePwd = line.slice("a=ice-pwd:".length);
} }
} }
@@ -184,11 +193,11 @@ class MediaMTXWebRTCReader {
return pl; return pl;
} }
} }
throw Error('unable to find a free payload type'); throw Error("unable to find a free payload type");
} }
static #enableStereoPcmau(payloadTypes, section) { static #enableStereoPcmau(payloadTypes, section) {
const lines = section.split('\r\n'); const lines = section.split("\r\n");
let payloadType = this.#reservePayloadType(payloadTypes); let payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
@@ -200,53 +209,101 @@ class MediaMTXWebRTCReader {
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} PCMA/8000/2`); lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} PCMA/8000/2`);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`); lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
return lines.join('\r\n'); return lines.join("\r\n");
} }
static #enableMultichannelOpus(payloadTypes, section) { static #enableMultichannelOpus(payloadTypes, section) {
const lines = section.split('\r\n'); const lines = section.split("\r\n");
let payloadType = this.#reservePayloadType(payloadTypes); let payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/3`); lines.splice(
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,2,1;num_streams=2;coupled_streams=1`); lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/3`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,2,1;num_streams=2;coupled_streams=1`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`); lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes); payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/4`); lines.splice(
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2`); lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/4`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,1,2,3;num_streams=2;coupled_streams=2`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`); lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes); payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/5`); lines.splice(
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2`); lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/5`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,4,1,2,3;num_streams=3;coupled_streams=2`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`); lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes); payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/6`); lines.splice(
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2`); lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/6`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`); lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes); payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/7`); lines.splice(
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4`); lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/7`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,4,1,2,3,5,6;num_streams=4;coupled_streams=4`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`); lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
payloadType = this.#reservePayloadType(payloadTypes); payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} multiopus/48000/8`); lines.splice(
lines.splice(lines.length - 1, 0, `a=fmtp:${payloadType} channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4`); lines.length - 1,
0,
`a=rtpmap:${payloadType} multiopus/48000/8`,
);
lines.splice(
lines.length - 1,
0,
`a=fmtp:${payloadType} channel_mapping=0,6,1,4,5,2,3,7;num_streams=5;coupled_streams=4`,
);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`); lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
return lines.join('\r\n'); return lines.join("\r\n");
} }
static #enableL16(payloadTypes, section) { static #enableL16(payloadTypes, section) {
const lines = section.split('\r\n'); const lines = section.split("\r\n");
let payloadType = this.#reservePayloadType(payloadTypes); let payloadType = this.#reservePayloadType(payloadTypes);
lines[0] += ` ${payloadType}`; lines[0] += ` ${payloadType}`;
@@ -263,56 +320,60 @@ class MediaMTXWebRTCReader {
lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} L16/48000/2`); lines.splice(lines.length - 1, 0, `a=rtpmap:${payloadType} L16/48000/2`);
lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`); lines.splice(lines.length - 1, 0, `a=rtcp-fb:${payloadType} transport-cc`);
return lines.join('\r\n'); return lines.join("\r\n");
} }
static #enableStereoOpus(section) { static #enableStereoOpus(section) {
let opusPayloadFormat = ''; let opusPayloadFormat = "";
const lines = section.split('\r\n'); const lines = section.split("\r\n");
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('a=rtpmap:') && lines[i].toLowerCase().includes('opus/')) { if (
opusPayloadFormat = lines[i].slice('a=rtpmap:'.length).split(' ')[0]; lines[i].startsWith("a=rtpmap:") &&
lines[i].toLowerCase().includes("opus/")
) {
opusPayloadFormat = lines[i].slice("a=rtpmap:".length).split(" ")[0];
break; break;
} }
} }
if (opusPayloadFormat === '') { if (opusPayloadFormat === "") {
return section; return section;
} }
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith(`a=fmtp:${opusPayloadFormat} `)) { if (lines[i].startsWith(`a=fmtp:${opusPayloadFormat} `)) {
if (!lines[i].includes('stereo')) { if (!lines[i].includes("stereo")) {
lines[i] += ';stereo=1'; lines[i] += ";stereo=1";
} }
if (!lines[i].includes('sprop-stereo')) { if (!lines[i].includes("sprop-stereo")) {
lines[i] += ';sprop-stereo=1'; lines[i] += ";sprop-stereo=1";
} }
} }
} }
return lines.join('\r\n'); return lines.join("\r\n");
} }
static #editOffer(sdp, nonAdvertisedCodecs) { static #editOffer(sdp, nonAdvertisedCodecs) {
const sections = sdp.split('m='); const sections = sdp.split("m=");
const payloadTypes = sections.slice(1) const payloadTypes = sections
.map((s) => s.split('\r\n')[0].split(' ').slice(3)) .slice(1)
.map((s) => s.split("\r\n")[0].split(" ").slice(3))
.reduce((prev, cur) => [...prev, ...cur], []); .reduce((prev, cur) => [...prev, ...cur], []);
for (let i = 1; i < sections.length; i++) { for (let i = 1; i < sections.length; i++) {
if (sections[i].startsWith('audio')) { if (sections[i].startsWith("audio")) {
sections[i] = this.#enableStereoOpus(sections[i]); sections[i] = this.#enableStereoOpus(sections[i]);
if (nonAdvertisedCodecs.includes('pcma/8000/2')) { if (nonAdvertisedCodecs.includes("pcma/8000/2")) {
sections[i] = this.#enableStereoPcmau(payloadTypes, sections[i]); sections[i] = this.#enableStereoPcmau(payloadTypes, sections[i]);
} }
if (nonAdvertisedCodecs.includes('multiopus/48000/6')) { if (nonAdvertisedCodecs.includes("multiopus/48000/6")) {
sections[i] = this.#enableMultichannelOpus(payloadTypes, sections[i]); sections[i] = this.#enableMultichannelOpus(payloadTypes, sections[i]);
} }
if (nonAdvertisedCodecs.includes('L16/48000/2')) { if (nonAdvertisedCodecs.includes("L16/48000/2")) {
sections[i] = this.#enableL16(payloadTypes, sections[i]); sections[i] = this.#enableL16(payloadTypes, sections[i]);
} }
@@ -320,7 +381,7 @@ class MediaMTXWebRTCReader {
} }
} }
return sections.join('m='); return sections.join("m=");
} }
static #generateSdpFragment(od, candidates) { static #generateSdpFragment(od, candidates) {
@@ -333,15 +394,13 @@ class MediaMTXWebRTCReader {
candidatesByMedia[mid].push(candidate); candidatesByMedia[mid].push(candidate);
} }
let frag = `a=ice-ufrag:${od.iceUfrag}\r\n` let frag = `a=ice-ufrag:${od.iceUfrag}\r\n` + `a=ice-pwd:${od.icePwd}\r\n`;
+ `a=ice-pwd:${od.icePwd}\r\n`;
let mid = 0; let mid = 0;
for (const media of od.medias) { for (const media of od.medias) {
if (candidatesByMedia[mid] !== undefined) { if (candidatesByMedia[mid] !== undefined) {
frag += `m=${media}\r\n` frag += `m=${media}\r\n` + `a=mid:${mid}\r\n`;
+ `a=mid:${mid}\r\n`;
for (const candidate of candidatesByMedia[mid]) { for (const candidate of candidatesByMedia[mid]) {
frag += `a=${candidate.candidate}\r\n`; frag += `a=${candidate.candidate}\r\n`;
@@ -355,7 +414,7 @@ class MediaMTXWebRTCReader {
/** @param {string} err */ /** @param {string} err */
#handleError(err) { #handleError(err) {
if (this.#state === 'running') { if (this.#state === "running") {
if (this.#pc !== null) { if (this.#pc !== null) {
this.#pc.close(); this.#pc.close();
this.#pc = null; this.#pc = null;
@@ -365,25 +424,25 @@ class MediaMTXWebRTCReader {
if (this.#sessionUrl !== null) { if (this.#sessionUrl !== null) {
fetch(this.#sessionUrl, { fetch(this.#sessionUrl, {
method: 'DELETE', method: "DELETE",
}); });
this.#sessionUrl = null; this.#sessionUrl = null;
} }
this.#queuedCandidates = []; this.#queuedCandidates = [];
this.#state = 'restarting'; this.#state = "restarting";
this.#restartTimeout = window.setTimeout(() => { this.#restartTimeout = window.setTimeout(() => {
this.#restartTimeout = null; this.#restartTimeout = null;
this.#state = 'running'; this.#state = "running";
this.#start(); this.#start();
}, this.#retryPause); }, this.#retryPause);
if (this.#conf.onError !== undefined) { if (this.#conf.onError !== undefined) {
this.#conf.onError(`${err}, retrying in some seconds`); this.#conf.onError(`${err}, retrying in some seconds`);
} }
} else if (this.#state === 'getting_codecs') { } else if (this.#state === "getting_codecs") {
this.#state = 'failed'; this.#state = "failed";
if (this.#conf.onError !== undefined) { if (this.#conf.onError !== undefined) {
this.#conf.onError(err); this.#conf.onError(err);
@@ -392,20 +451,28 @@ class MediaMTXWebRTCReader {
} }
#getNonAdvertisedCodecs() { #getNonAdvertisedCodecs() {
Promise.all([ Promise.all(
['pcma/8000/2'], [
['multiopus/48000/6', 'channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2'], ["pcma/8000/2"],
['L16/48000/2'], [
] "multiopus/48000/6",
.map((c) => MediaMTXWebRTCReader.#supportsNonAdvertisedCodec(c[0], c[1]).then((r) => ((r) ? c[0] : false)))) "channel_mapping=0,4,1,2,3,5;num_streams=4;coupled_streams=2",
],
["L16/48000/2"],
].map((c) =>
MediaMTXWebRTCReader.#supportsNonAdvertisedCodec(c[0], c[1]).then(
(r) => (r ? c[0] : false),
),
),
)
.then((c) => c.filter((e) => e !== false)) .then((c) => c.filter((e) => e !== false))
.then((codecs) => { .then((codecs) => {
if (this.#state !== 'getting_codecs') { if (this.#state !== "getting_codecs") {
throw new Error('closed'); throw new Error("closed");
} }
this.#nonAdvertisedCodecs = codecs; this.#nonAdvertisedCodecs = codecs;
this.#state = 'running'; this.#state = "running";
this.#start(); this.#start();
}) })
.catch((err) => { .catch((err) => {
@@ -424,101 +491,110 @@ class MediaMTXWebRTCReader {
} }
#authHeader() { #authHeader() {
if (this.#conf.user !== undefined && this.#conf.user !== '') { if (this.#conf.user !== undefined && this.#conf.user !== "") {
const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`); const credentials = btoa(`${this.#conf.user}:${this.#conf.pass}`);
return {'Authorization': `Basic ${credentials}`}; return { Authorization: `Basic ${credentials}` };
} }
if (this.#conf.token !== undefined && this.#conf.token !== '') { if (this.#conf.token !== undefined && this.#conf.token !== "") {
return {'Authorization': `Bearer ${this.#conf.token}`}; return { Authorization: `Bearer ${this.#conf.token}` };
} }
return {}; return {};
} }
#requestICEServers() { #requestICEServers() {
return fetch(this.#conf.url, { return fetch(this.#conf.url, {
method: 'OPTIONS', method: "OPTIONS",
headers: { headers: {
...this.#authHeader(), ...this.#authHeader(),
}, },
}) }).then((res) =>
.then((res) => MediaMTXWebRTCReader.#linkToIceServers(res.headers.get('Link'))); MediaMTXWebRTCReader.#linkToIceServers(res.headers.get("Link")),
);
} }
#setupPeerConnection(iceServers) { #setupPeerConnection(iceServers) {
if (this.#state !== 'running') { if (this.#state !== "running") {
throw new Error('closed'); throw new Error("closed");
} }
this.#pc = new RTCPeerConnection({ this.#pc = new RTCPeerConnection({
iceServers, iceServers,
// https://webrtc.org/getting-started/unified-plan-transition-guide // https://webrtc.org/getting-started/unified-plan-transition-guide
sdpSemantics: 'unified-plan', sdpSemantics: "unified-plan",
}); });
const direction = 'recvonly'; const direction = "recvonly";
this.#pc.addTransceiver('video', { direction }); this.#pc.addTransceiver("video", { direction });
this.#pc.addTransceiver('audio', { direction }); this.#pc.addTransceiver("audio", { direction });
// using data channels requires creating a data channel locally // using data channels requires creating a data channel locally
this.#pc.createDataChannel(''); this.#pc.createDataChannel("");
this.#pc.onicecandidate = (evt) => this.#onLocalCandidate(evt); this.#pc.onicecandidate = (evt) => this.#onLocalCandidate(evt);
this.#pc.onconnectionstatechange = () => this.#onConnectionState(); this.#pc.onconnectionstatechange = () => this.#onConnectionState();
this.#pc.ontrack = (evt) => this.#onTrack(evt); this.#pc.ontrack = (evt) => this.#onTrack(evt);
this.#pc.ondatachannel = (evt) => this.#onDataChannel(evt); this.#pc.ondatachannel = (evt) => this.#onDataChannel(evt);
return this.#pc.createOffer() return this.#pc.createOffer().then((offer) => {
.then((offer) => { offer.sdp = MediaMTXWebRTCReader.#editOffer(
offer.sdp = MediaMTXWebRTCReader.#editOffer(offer.sdp, this.#nonAdvertisedCodecs); offer.sdp,
this.#offerData = MediaMTXWebRTCReader.#parseOffer(offer.sdp); this.#nonAdvertisedCodecs,
);
this.#offerData = MediaMTXWebRTCReader.#parseOffer(offer.sdp);
return this.#pc.setLocalDescription(offer) return this.#pc.setLocalDescription(offer).then(() => offer.sdp);
.then(() => offer.sdp); });
});
} }
#sendOffer(offer) { #sendOffer(offer) {
if (this.#state !== 'running') { if (this.#state !== "running") {
throw new Error('closed'); throw new Error("closed");
} }
return fetch(this.#conf.url, { return fetch(this.#conf.url, {
method: 'POST', method: "POST",
headers: { headers: {
...this.#authHeader(), ...this.#authHeader(),
'Content-Type': 'application/sdp', "Content-Type": "application/sdp",
}, },
body: offer, body: offer,
}) }).then((res) => {
.then((res) => { switch (res.status) {
switch (res.status) { case 201:
case 201: break;
break; case 404:
case 404: throw new Error("stream not found");
throw new Error('stream not found'); case 400:
case 400: return res.json().then((e) => {
return res.json().then((e) => { throw new Error(e.error); }); throw new Error(e.error);
default: });
throw new Error(`bad status code ${res.status}`); default:
} throw new Error(`bad status code ${res.status}`);
}
this.#sessionUrl = new URL(res.headers.get('location'), this.#conf.url).toString(); this.#sessionUrl = new URL(
res.headers.get("location"),
this.#conf.url,
).toString();
return res.text(); return res.text();
}); });
} }
#setAnswer(answer) { #setAnswer(answer) {
if (this.#state !== 'running') { if (this.#state !== "running") {
throw new Error('closed'); throw new Error("closed");
} }
return this.#pc.setRemoteDescription(new RTCSessionDescription({ return this.#pc
type: 'answer', .setRemoteDescription(
sdp: answer, new RTCSessionDescription({
})) type: "answer",
sdp: answer,
}),
)
.then(() => { .then(() => {
if (this.#state !== 'running') { if (this.#state !== "running") {
return; return;
} }
@@ -530,7 +606,7 @@ class MediaMTXWebRTCReader {
} }
#onLocalCandidate(evt) { #onLocalCandidate(evt) {
if (this.#state !== 'running') { if (this.#state !== "running") {
return; return;
} }
@@ -545,19 +621,22 @@ class MediaMTXWebRTCReader {
#sendLocalCandidates(candidates) { #sendLocalCandidates(candidates) {
fetch(this.#sessionUrl, { fetch(this.#sessionUrl, {
method: 'PATCH', method: "PATCH",
headers: { headers: {
'Content-Type': 'application/trickle-ice-sdpfrag', "Content-Type": "application/trickle-ice-sdpfrag",
'If-Match': '*', "If-Match": "*",
}, },
body: MediaMTXWebRTCReader.#generateSdpFragment(this.#offerData, candidates), body: MediaMTXWebRTCReader.#generateSdpFragment(
this.#offerData,
candidates,
),
}) })
.then((res) => { .then((res) => {
switch (res.status) { switch (res.status) {
case 204: case 204:
break; break;
case 404: case 404:
throw new Error('stream not found'); throw new Error("stream not found");
default: default:
throw new Error(`bad status code ${res.status}`); throw new Error(`bad status code ${res.status}`);
} }
@@ -568,7 +647,7 @@ class MediaMTXWebRTCReader {
} }
#onConnectionState() { #onConnectionState() {
if (this.#state !== 'running') { if (this.#state !== "running") {
return; return;
} }
@@ -576,10 +655,11 @@ class MediaMTXWebRTCReader {
// the close() method being called at all. // the close() method being called at all.
// It happens when the other peer sends a termination // It happens when the other peer sends a termination
// message like a DTLS CloseNotify. // message like a DTLS CloseNotify.
if (this.#pc.connectionState === 'failed' if (
|| this.#pc.connectionState === 'closed' this.#pc.connectionState === "failed" ||
this.#pc.connectionState === "closed"
) { ) {
this.#handleError('peer connection closed'); this.#handleError("peer connection closed");
} }
} }
+44 -45
View File
@@ -62,34 +62,34 @@ authMethod: internal
authInternalUsers: authInternalUsers:
# Default unprivileged user. # Default unprivileged user.
# Username. 'any' means any user, including anonymous ones. # Username. 'any' means any user, including anonymous ones.
- user: any - user: any
# Password. Not used in case of 'any' user. # Password. Not used in case of 'any' user.
pass: pass:
# IPs or networks allowed to use this user. An empty list means any IP. # IPs or networks allowed to use this user. An empty list means any IP.
ips: [] ips: []
# Permissions. # Permissions.
permissions: permissions:
# Available actions are: publish, read, playback, api, metrics, pprof. # Available actions are: publish, read, playback, api, metrics, pprof.
- action: publish - action: publish
# Paths can be set to further restrict access to a specific path. # Paths can be set to further restrict access to a specific path.
# An empty path means any path. # An empty path means any path.
# Regular expressions can be used by using a tilde as prefix. # Regular expressions can be used by using a tilde as prefix.
path: path:
- action: read - action: read
path: path:
- action: playback - action: playback
path: path:
# Default administrator. # Default administrator.
# This allows to use API, metrics and PPROF without authentication, # This allows to use API, metrics and PPROF without authentication,
# if the IP is localhost. # if the IP is localhost.
- user: any - user: any
pass: pass:
ips: ['127.0.0.1', '::1'] ips: ["127.0.0.1", "::1"]
permissions: permissions:
- action: api - action: api
- action: metrics - action: metrics
- action: pprof - action: pprof
# HTTP-based authentication. # HTTP-based authentication.
# URL called to perform authentication. Every time a user wants # URL called to perform authentication. Every time a user wants
@@ -118,9 +118,9 @@ authHTTPFingerprint:
# Actions to exclude from HTTP-based authentication. # Actions to exclude from HTTP-based authentication.
# Format is the same as the one of user permissions. # Format is the same as the one of user permissions.
authHTTPExclude: authHTTPExclude:
- action: api - action: api
- action: metrics - action: metrics
- action: pprof - action: pprof
# JWT-based authentication. # JWT-based authentication.
# Users have to log in through an external identity server and obtain a JWT. # Users have to log in through an external identity server and obtain a JWT.
@@ -172,7 +172,7 @@ apiServerKey: server.key
apiServerCert: server.crt apiServerCert: server.crt
# Allowed CORS origins. # Allowed CORS origins.
# Supports wildcards: ['http://*.example.com'] # Supports wildcards: ['http://*.example.com']
apiAllowOrigins: ['*'] apiAllowOrigins: ["*"]
# IPs or CIDRs of proxies placed before the HTTP server. # IPs or CIDRs of proxies placed before the HTTP server.
# These proxies can use the X-Forwarded-For header to set the real IP of clients, # These proxies can use the X-Forwarded-For header to set the real IP of clients,
# and the X-Forwarded-Proto header to set the original protocol. # and the X-Forwarded-Proto header to set the original protocol.
@@ -196,7 +196,7 @@ metricsServerKey: server.key
metricsServerCert: server.crt metricsServerCert: server.crt
# Allowed CORS origins. # Allowed CORS origins.
# Supports wildcards: ['http://*.example.com'] # Supports wildcards: ['http://*.example.com']
metricsAllowOrigins: ['*'] metricsAllowOrigins: ["*"]
# IPs or CIDRs of proxies placed before the HTTP server. # IPs or CIDRs of proxies placed before the HTTP server.
# These proxies can use the X-Forwarded-For header to set the real IP of clients, # These proxies can use the X-Forwarded-For header to set the real IP of clients,
# and the X-Forwarded-Proto header to set the original protocol. # and the X-Forwarded-Proto header to set the original protocol.
@@ -220,7 +220,7 @@ pprofServerKey: server.key
pprofServerCert: server.crt pprofServerCert: server.crt
# Allowed CORS origins. # Allowed CORS origins.
# Supports wildcards: ['http://*.example.com'] # Supports wildcards: ['http://*.example.com']
pprofAllowOrigins: ['*'] pprofAllowOrigins: ["*"]
# IPs or CIDRs of proxies placed before the HTTP server. # IPs or CIDRs of proxies placed before the HTTP server.
# These proxies can use the X-Forwarded-For header to set the real IP of clients, # These proxies can use the X-Forwarded-For header to set the real IP of clients,
# and the X-Forwarded-Proto header to set the original protocol. # and the X-Forwarded-Proto header to set the original protocol.
@@ -244,7 +244,7 @@ playbackServerKey: server.key
playbackServerCert: server.crt playbackServerCert: server.crt
# Allowed CORS origins. # Allowed CORS origins.
# Supports wildcards: ['http://*.example.com'] # Supports wildcards: ['http://*.example.com']
playbackAllowOrigins: ['*'] playbackAllowOrigins: ["*"]
# IPs or CIDRs of proxies placed before the HTTP server. # IPs or CIDRs of proxies placed before the HTTP server.
# These proxies can use the X-Forwarded-For header to set the real IP of clients, # These proxies can use the X-Forwarded-For header to set the real IP of clients,
# and the X-Forwarded-Proto header to set the original protocol. # and the X-Forwarded-Proto header to set the original protocol.
@@ -332,7 +332,7 @@ hlsServerKey: server.key
hlsServerCert: server.crt hlsServerCert: server.crt
# Allowed CORS origins. # Allowed CORS origins.
# Supports wildcards: ['http://*.example.com'] # Supports wildcards: ['http://*.example.com']
hlsAllowOrigins: ['*'] hlsAllowOrigins: ["*"]
# IPs or CIDRs of proxies placed before the HLS server. # IPs or CIDRs of proxies placed before the HLS server.
# If the server receives a request from one of these entries, IP in logs # If the server receives a request from one of these entries, IP in logs
# will be taken from the X-Forwarded-For header. # will be taken from the X-Forwarded-For header.
@@ -367,14 +367,14 @@ hlsSegmentMaxSize: 50M
# Directory in which to save segments and non-low-latency playlists. # Directory in which to save segments and non-low-latency playlists.
# This has two purposes: offloading RAM and creating a self-consistent directory # This has two purposes: offloading RAM and creating a self-consistent directory
# that can be served by a CDN. # that can be served by a CDN.
hlsDirectory: '' hlsDirectory: ""
# The muxer will be closed when there are no # The muxer will be closed when there are no
# reader requests and this amount of time has passed. # reader requests and this amount of time has passed.
hlsMuxerCloseAfter: 60s hlsMuxerCloseAfter: 60s
# Secret to identify requests coming from a CDN. # Secret to identify requests coming from a CDN.
# The CDN must insert this secret in every request in the # The CDN must insert this secret in every request in the
# 'Authorization: Bearer' header. # 'Authorization: Bearer' header.
hlsCDNSecret: '' hlsCDNSecret: ""
############################################### ###############################################
# Global settings -> WebRTC server # Global settings -> WebRTC server
@@ -396,7 +396,7 @@ webrtcServerKey: server.key
webrtcServerCert: server.crt webrtcServerCert: server.crt
# Allowed CORS origins. # Allowed CORS origins.
# Supports wildcards: ['http://*.example.com'] # Supports wildcards: ['http://*.example.com']
webrtcAllowOrigins: ['*'] webrtcAllowOrigins: ["*"]
# IPs or CIDRs of proxies placed before the WebRTC server. # IPs or CIDRs of proxies placed before the WebRTC server.
# If the server receives a request from one of these entries, IP in logs # If the server receives a request from one of these entries, IP in logs
# will be taken from the X-Forwarded-For header. # will be taken from the X-Forwarded-For header.
@@ -407,7 +407,7 @@ webrtcLocalUDPAddress: :8189
# Address of a local TCP listener that will receive connections. # Address of a local TCP listener that will receive connections.
# This is disabled by default since TCP is less efficient than UDP and # This is disabled by default since TCP is less efficient than UDP and
# introduces a progressive delay when network is congested. # introduces a progressive delay when network is congested.
webrtcLocalTCPAddress: '' webrtcLocalTCPAddress: ""
# WebRTC clients need to know the IP of the server. # WebRTC clients need to know the IP of the server.
# Gather IPs from interfaces and send them to clients. # Gather IPs from interfaces and send them to clients.
webrtcIPsFromInterfaces: true webrtcIPsFromInterfaces: true
@@ -447,7 +447,6 @@ srtAddress: :8890
# Settings in "pathDefaults" are applied anywhere, # Settings in "pathDefaults" are applied anywhere,
# unless they are overridden in "paths". # unless they are overridden in "paths".
pathDefaults: pathDefaults:
############################################### ###############################################
# Default path settings -> General # Default path settings -> General
@@ -513,7 +512,7 @@ pathDefaults:
# # in case of G711, muLaw must be provided too. # # in case of G711, muLaw must be provided too.
# muLaw: false # muLaw: false
# An MP4 file can be used instead of the default offline segment. # An MP4 file can be used instead of the default offline segment.
alwaysAvailableFile: '' alwaysAvailableFile: ""
############################################### ###############################################
# Default path settings -> Record # Default path settings -> Record
@@ -586,7 +585,7 @@ pathDefaults:
# Default path settings -> WebRTC / WHEP source (when source is WHEP) # Default path settings -> WebRTC / WHEP source (when source is WHEP)
# Token to insert in the Authorization: Bearer header. # Token to insert in the Authorization: Bearer header.
whepBearerToken: '' whepBearerToken: ""
# Maximum time to gather STUN candidates. # Maximum time to gather STUN candidates.
whepSTUNGatherTimeout: 5s whepSTUNGatherTimeout: 5s
# Time to wait for the WebRTC handshake to complete. # Time to wait for the WebRTC handshake to complete.
@@ -675,7 +674,7 @@ pathDefaults:
rpiCameraTextOverlayEnable: false rpiCameraTextOverlayEnable: false
# Text that is printed on each frame. # Text that is printed on each frame.
# format is the one of the strftime() function. # format is the one of the strftime() function.
rpiCameraTextOverlay: '%Y-%m-%d %H:%M:%S - MediaMTX' rpiCameraTextOverlay: "%Y-%m-%d %H:%M:%S - MediaMTX"
# Codec (auto, hardwareH264, softwareH264 or mjpeg). # Codec (auto, hardwareH264, softwareH264 or mjpeg).
# When is "auto" and stream is primary, it defaults to hardwareH264 (if available) or softwareH264. # When is "auto" and stream is primary, it defaults to hardwareH264 (if available) or softwareH264.
# When is "auto" and stream is secondary, it defaults to mjpeg. # When is "auto" and stream is secondary, it defaults to mjpeg.
@@ -687,11 +686,11 @@ pathDefaults:
# Hardware H264 profile (baseline, main or high) (when codec is hardwareH264). # Hardware H264 profile (baseline, main or high) (when codec is hardwareH264).
rpiCameraHardwareH264Profile: main rpiCameraHardwareH264Profile: main
# Hardware H264 level (4.0, 4.1 or 4.2) (when codec is hardwareH264). # Hardware H264 level (4.0, 4.1 or 4.2) (when codec is hardwareH264).
rpiCameraHardwareH264Level: '4.1' rpiCameraHardwareH264Level: "4.1"
# Software H264 profile (baseline, main or high) (when codec is softwareH264). # Software H264 profile (baseline, main or high) (when codec is softwareH264).
rpiCameraSoftwareH264Profile: baseline rpiCameraSoftwareH264Profile: baseline
# Software H264 level (4.0, 4.1 or 4.2) (when codec is softwareH264). # Software H264 level (4.0, 4.1 or 4.2) (when codec is softwareH264).
rpiCameraSoftwareH264Level: '4.1' rpiCameraSoftwareH264Level: "4.1"
# M-JPEG JPEG quality (when codec is mjpeg). # M-JPEG JPEG quality (when codec is mjpeg).
rpiCameraMJPEGQuality: 60 rpiCameraMJPEGQuality: 60
+3 -3
View File
@@ -15,9 +15,9 @@ format-go:
docker run --rm -it -v "$(shell pwd):/s" -w /s temp \ docker run --rm -it -v "$(shell pwd):/s" -w /s temp \
sh -c "gofumpt -l -w ." sh -c "gofumpt -l -w ."
format-docs: format-other:
echo "$$DOCKERFILE_PRETTIER" | docker build . -f - -t temp echo "$$DOCKERFILE_PRETTIER" | docker build . -f - -t temp
docker run --rm -v "$(shell pwd)/docs:/s" -w /s temp \ docker run --rm -v "$(shell pwd)/:/s" -w /s temp \
sh -c "prettier --write ." sh -c "prettier --write ."
format: format-go format-docs format: format-go format-other
+6 -6
View File
@@ -24,14 +24,14 @@ lint-docslinks:
lint-docsorder: lint-docsorder:
go test -v -tags enable_linters ./internal/linters/docsorder go test -v -tags enable_linters ./internal/linters/docsorder
lint-docs:
echo "$$DOCKERFILE_PRETTIER" | docker build . -f - -t temp
docker run --rm -v "$(shell pwd)/docs:/s" -w /s temp \
sh -c "prettier --check ."
lint-api-docs: lint-api-docs:
echo "$$DOCKERFILE_API_DOCS_LINT" | docker build . -f - -t temp echo "$$DOCKERFILE_API_DOCS_LINT" | docker build . -f - -t temp
docker run --rm -v "$(shell pwd)/api:/s" -w /s temp \ docker run --rm -v "$(shell pwd)/api:/s" -w /s temp \
sh -c "openapi lint openapi.yaml" sh -c "openapi lint openapi.yaml"
lint: lint-go lint-go-mod lint-conf lint-go2api lint-docslinks lint-docsorder lint-docs lint-api-docs lint-other:
echo "$$DOCKERFILE_PRETTIER" | docker build . -f - -t temp
docker run --rm -v "$(shell pwd)/:/s" -w /s temp \
sh -c "prettier --check ."
lint: lint-go lint-go-mod lint-conf lint-go2api lint-docslinks lint-docsorder lint-api-docs lint-other