Compare commits

..

1 Commits

Author SHA1 Message Date
aler9 73bd516c40 try to fix #2887 3 years ago
  1. 1
      .dockerignore
  2. 11
      .github/workflows/bump_hls_js.yml
  3. 6
      .github/workflows/code_lint.yml
  4. 1
      .gitignore
  5. 1
      .golangci.yml
  6. 5
      LICENSE
  7. 8
      Makefile
  8. 491
      README.md
  9. 532
      apidocs/openapi.yaml
  10. 42
      go.mod
  11. 94
      go.sum
  12. 319
      internal/api/api.go
  13. 662
      internal/api/api_test.go
  14. 139
      internal/api/record.go
  15. 1
      internal/asyncwriter/async_writer.go
  16. 22
      internal/asyncwriter/async_writer_test.go
  17. 327
      internal/auth/manager.go
  18. 309
      internal/auth/manager_test.go
  19. 52
      internal/conf/auth_action.go
  20. 15
      internal/conf/auth_internal_users.go
  21. 65
      internal/conf/auth_method.go
  22. 286
      internal/conf/conf.go
  23. 31
      internal/conf/conf_test.go
  24. 97
      internal/conf/credential.go
  25. 72
      internal/conf/credential_test.go
  26. 5
      internal/conf/encryption.go
  27. 25
      internal/conf/env/env.go
  28. 5
      internal/conf/env/env_test.go
  29. 5
      internal/conf/hls_variant.go
  30. 84
      internal/conf/ip_networks.go
  31. 66
      internal/conf/ips_or_cidrs.go
  32. 5
      internal/conf/log_destination.go
  33. 5
      internal/conf/log_level.go
  34. 235
      internal/conf/path.go
  35. 5
      internal/conf/protocol.go
  36. 63
      internal/conf/rtsp_auth_methods.go
  37. 5
      internal/conf/rtsp_range_type.go
  38. 5
      internal/conf/rtsp_transport.go
  39. 2
      internal/conf/string_size.go
  40. 7
      internal/conf/webrtc_ice_server.go
  41. 24
      internal/confwatcher/confwatcher_test.go
  42. 984
      internal/core/api_test.go
  43. 126
      internal/core/auth.go
  44. 205
      internal/core/core.go
  45. 146
      internal/core/core_test.go
  46. 222
      internal/core/hls_server_test.go
  47. 23
      internal/core/ip.go
  48. 115
      internal/core/metrics_test.go
  49. 114
      internal/core/path.go
  50. 236
      internal/core/path_manager.go
  51. 3
      internal/core/path_manager_test.go
  52. 176
      internal/core/path_test.go
  53. 348
      internal/core/rtmp_server_test.go
  54. 373
      internal/core/rtsp_server_test.go
  55. 146
      internal/core/srt_server_test.go
  56. 2
      internal/core/static_source_handler.go
  57. 362
      internal/core/webrtc_server_test.go
  58. 153
      internal/defs/api.go
  59. 23
      internal/defs/auth.go
  60. 37
      internal/defs/path.go
  61. 9
      internal/defs/path_manager.go
  62. 47
      internal/defs/source.go
  63. 18
      internal/externalcmd/cmd.go
  64. 14
      internal/externalcmd/cmd_unix.go
  65. 67
      internal/externalcmd/cmd_win.go
  66. 12
      internal/formatprocessor/ac3.go
  67. 17
      internal/formatprocessor/av1.go
  68. 12
      internal/formatprocessor/g711.go
  69. 2
      internal/formatprocessor/g711_test.go
  70. 17
      internal/formatprocessor/h264.go
  71. 2
      internal/formatprocessor/h264_test.go
  72. 17
      internal/formatprocessor/h265.go
  73. 2
      internal/formatprocessor/h265_test.go
  74. 12
      internal/formatprocessor/lpcm.go
  75. 2
      internal/formatprocessor/lpcm_test.go
  76. 12
      internal/formatprocessor/mjpeg.go
  77. 12
      internal/formatprocessor/mpeg1_audio.go
  78. 12
      internal/formatprocessor/mpeg1_video.go
  79. 12
      internal/formatprocessor/mpeg4_audio.go
  80. 12
      internal/formatprocessor/mpeg4_video.go
  81. 12
      internal/formatprocessor/opus.go
  82. 8
      internal/formatprocessor/processor.go
  83. 12
      internal/formatprocessor/vp8.go
  84. 12
      internal/formatprocessor/vp9.go
  85. 4
      internal/highleveltests/hls_manager_test.go
  86. 5
      internal/highleveltests/rtsp_server_test.go
  87. 70
      internal/highleveltests/tests_test.go
  88. 90
      internal/metrics/metrics.go
  89. 594
      internal/playback/fmp4.go
  90. 75
      internal/playback/fmp4_test.go
  91. 179
      internal/playback/on_get.go
  92. 374
      internal/playback/on_get_test.go
  93. 120
      internal/playback/on_list.go
  94. 134
      internal/playback/on_list_test.go
  95. 149
      internal/playback/segment.go
  96. 142
      internal/playback/server.go
  97. 40
      internal/pprof/pprof.go
  98. 15
      internal/protocols/httpp/remote_addr.go
  99. 2
      internal/protocols/httpserv/handler_exit_on_panic.go
  100. 2
      internal/protocols/httpserv/handler_filter_requests.go
  101. Some files were not shown because too many files have changed in this diff Show More

1
.dockerignore

@ -3,4 +3,3 @@ @@ -3,4 +3,3 @@
/binaries
/coverage*.txt
/apidocs/*.html
**/hls.min.js

11
.github/workflows/bump_hls_js.yml

@ -20,9 +20,8 @@ jobs: @@ -20,9 +20,8 @@ jobs:
&& ((git checkout deps/hlsjs && git rebase ${GITHUB_REF_NAME}) || git checkout -b deps/hlsjs)
- run: >
VERSION=$(curl -s https://api.github.com/repos/video-dev/hls.js/releases?per_page=1 | grep tag_name | sed 's/\s\+"tag_name": "\(.\+\)",/\1/')
&& echo $VERSION > internal/servers/hls/hlsjsdownloader/VERSION
&& echo VERSION=$VERSION >> $GITHUB_ENV
curl -o internal/servers/hls/hls.min.js https://cdn.jsdelivr.net/npm/hls.js@latest/dist/hls.min.js
&& echo VERSION=$(cat internal/servers/hls/hls.min.js | grep -o '"version",get:function(){return".*"}' | sed 's/"version",get:function(){return"\(.*\)"}/\1/') >> $GITHUB_ENV
- id: check_repo
run: >
@ -32,7 +31,7 @@ jobs: @@ -32,7 +31,7 @@ jobs:
run: >
git reset ${GITHUB_REF_NAME}
&& git add .
&& git commit -m "bump hls.js to ${VERSION}"
&& git commit -m "bump hls-js to v${VERSION}"
&& git push --set-upstream origin deps/hlsjs --force
- if: ${{ steps.check_repo.outputs.clean != '' }}
@ -53,13 +52,13 @@ jobs: @@ -53,13 +52,13 @@ jobs:
repo: context.repo.repo,
head: 'deps/hlsjs',
base: context.ref.slice('refs/heads/'.length),
title: `bump hls-js to ${process.env.VERSION}`,
title: `bump hls-js to v${process.env.VERSION}`,
});
} else {
github.rest.pulls.update({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: prs.data[0].number,
title: `bump hls-js to ${process.env.VERSION}`,
title: `bump hls-js to v${process.env.VERSION}`,
});
}

6
.github/workflows/code_lint.yml

@ -15,11 +15,9 @@ jobs: @@ -15,11 +15,9 @@ jobs:
- uses: actions/setup-go@v3
with:
go-version: "1.21"
- run: touch internal/servers/hls/hls.min.js
go-version: "1.19"
- uses: golangci/golangci-lint-action@v4
- uses: golangci/golangci-lint-action@v3
with:
version: v1.55.0

1
.gitignore vendored

@ -2,4 +2,3 @@ @@ -2,4 +2,3 @@
/binaries
/coverage*.txt
/apidocs/*.html
**/hls.min.js

1
.golangci.yml

@ -15,7 +15,6 @@ linters: @@ -15,7 +15,6 @@ linters:
- nilerr
- prealloc
- revive
- usestdlibvars
- unconvert
- tparallel
- wastedassign

5
LICENSE

@ -19,3 +19,8 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER @@ -19,3 +19,8 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
internal/core/hls.min.js is Copyright (c) Dailymotion and is protected by
its own license (Apache License, Version 2.0) available at
https://github.com/video-dev/hls.js/blob/master/LICENSE

8
Makefile

@ -1,7 +1,7 @@ @@ -1,7 +1,7 @@
BASE_IMAGE = golang:1.21-alpine3.19
LINT_IMAGE = golangci/golangci-lint:v1.56.2
NODE_IMAGE = node:20-alpine3.19
ALPINE_IMAGE = alpine:3.19
BASE_IMAGE = golang:1.21-alpine3.18
LINT_IMAGE = golangci/golangci-lint:v1.55.2
NODE_IMAGE = node:16-alpine3.18
ALPINE_IMAGE = alpine:3.18
RPI32_IMAGE = balenalib/raspberry-pi:bullseye-run-20230712
RPI64_IMAGE = balenalib/raspberrypi3-64:bullseye-run-20230530

491
README.md

@ -14,7 +14,7 @@ @@ -14,7 +14,7 @@
<br>
_MediaMTX_ (formerly _rtsp-simple-server_) is a ready-to-use and zero-dependency real-time media server and media proxy that allows to publish, read, proxy, record and playback video and audio streams. It has been conceived as a "media router" that routes media streams from one end to the other.
_MediaMTX_ (formerly _rtsp-simple-server_) is a ready-to-use and zero-dependency real-time media server and media proxy that allows to publish, read, proxy and record video and audio streams. It has been conceived as a "media router" that routes media streams from one end to the other.
Live streams can be published to the server with:
@ -42,7 +42,7 @@ And can be read from the server with: @@ -42,7 +42,7 @@ And can be read from the server with:
|[RTMP](#rtmp)|RTMP, RTMPS, Enhanced RTMP|H264|MPEG-4 Audio (AAC), MPEG-1/2 Audio (MP3)|
|[HLS](#hls)|Low-Latency HLS, MP4-based HLS, legacy HLS|AV1, VP9, H265, H264|Opus, MPEG-4 Audio (AAC)|
And can be recorded and played back with:
And can be recorded with:
|format|video codecs|audio codecs|
|------|------------|------------|
@ -56,10 +56,9 @@ And can be recorded and played back with: @@ -56,10 +56,9 @@ And can be recorded and played back with:
* Streams are automatically converted from a protocol to another
* Serve multiple streams at once in separate paths
* Record streams to disk
* Playback recorded streams
* Authenticate users
* Authenticate users; use internal or external authentication
* Redirect readers to other RTSP servers (load balancing)
* Control the server through the Control API
* Query and control the server through the API
* Reload the configuration without disconnecting existing clients (hot reloading)
* Read Prometheus-compatible metrics
* Run hooks (external commands) when clients connect, disconnect, read or publish streams
@ -113,13 +112,9 @@ _rtsp-simple-server_ has been rebranded as _MediaMTX_. The reason is pretty obvi @@ -113,13 +112,9 @@ _rtsp-simple-server_ has been rebranded as _MediaMTX_. The reason is pretty obvi
* [Other features](#other-features)
* [Configuration](#configuration)
* [Authentication](#authentication)
* [Internal](#internal)
* [HTTP-based](#http-based)
* [JWT-based](#jwt-based)
* [Encrypt the configuration](#encrypt-the-configuration)
* [Remuxing, re-encoding, compression](#remuxing-re-encoding-compression)
* [Record streams to disk](#record-streams-to-disk)
* [Playback recorded streams](#playback-recorded-streams)
* [Forward streams to other servers](#forward-streams-to-other-servers)
* [Proxy requests to other servers](#proxy-requests-to-other-servers)
* [On-demand publishing](#on-demand-publishing)
@ -128,26 +123,23 @@ _rtsp-simple-server_ has been rebranded as _MediaMTX_. The reason is pretty obvi @@ -128,26 +123,23 @@ _rtsp-simple-server_ has been rebranded as _MediaMTX_. The reason is pretty obvi
* [OpenWrt](#openwrt)
* [Windows](#windows)
* [Hooks](#hooks)
* [Control API](#control-api)
* [API](#api)
* [Metrics](#metrics)
* [pprof](#pprof)
* [SRT-specific features](#srt-specific-features)
* [Standard stream ID syntax](#standard-stream-id-syntax)
* [WebRTC-specific features](#webrtc-specific-features)
* [Connectivity issues](#connectivity-issues)
* [RTSP-specific features](#rtsp-specific-features)
* [Transport protocols](#transport-protocols)
* [Encryption](#encryption)
* [Corrupted frames](#corrupted-frames)
* [RTMP-specific features](#rtmp-specific-features)
* [Encryption](#encryption-1)
* [WebRTC-specific features](#webrtc-specific-features)
* [Connectivity issues](#connectivity-issues)
* [Compile from source](#compile-from-source)
* [Standard](#standard)
* [Raspberry Pi](#raspberry-pi)
* [OpenWrt](#openwrt-1)
* [Cross compile](#cross-compile)
* [Compile for all supported platforms](#compile-for-all-supported-platforms)
* [License](#license)
* [Specifications](#specifications)
* [Related projects](#related-projects)
@ -424,7 +416,7 @@ This web page can be embedded into another web page by using an iframe: @@ -424,7 +416,7 @@ This web page can be embedded into another web page by using an iframe:
<iframe src="http://mediamtx-ip:8889/mystream/publish" scrolling="no"></iframe>
```
For more advanced setups, you can create and serve a custom web page by starting from the [source code of the WebRTC publish page](internal/servers/webrtc/publish_index.html).
For more advanced setups, you can create and serve a custom web page by starting from the [source code of the publish page](internal/servers/webrtc/publish_index.html).
### By device
@ -567,8 +559,6 @@ If credentials are enabled, append username and password to `streamid`; @@ -567,8 +559,6 @@ If credentials are enabled, append username and password to `streamid`;
srt://localhost:8890?streamid=publish:mystream:user:pass&pkt_size=1316
```
If you need to use the standard stream ID syntax instead of the custom one in use by this server, see [Standard stream ID syntax](#standard-stream-id-syntax).
If you want to publish a stream by using a client in listening mode (i.e. with `mode=listener` appended to the URL), read the next section.
Known clients that can publish with SRT are [FFmpeg](#ffmpeg), [GStreamer](#gstreamer), [OBS Studio](#obs-studio).
@ -814,7 +804,7 @@ This web page can be embedded into another web page by using an iframe: @@ -814,7 +804,7 @@ This web page can be embedded into another web page by using an iframe:
<iframe src="http://mediamtx-ip:8889/mystream" scrolling="no"></iframe>
```
For more advanced setups, you can create and serve a custom web page by starting from the [source code of the WebRTC read page](internal/servers/webrtc/read_index.html).
For more advanced setups, you can create and serve a custom web page by starting from the [source code of the read page](internal/servers/webrtc/read_index.html).
Web browsers can also read a stream with the [HLS protocol](#hls). Latency is higher but there are less problems related to connectivity between server and clients, furthermore the server load can be balanced by using a common HTTP CDN (like CloudFront or Cloudflare), and this allows to handle readers in the order of millions. Visit the web page:
@ -828,8 +818,6 @@ This web page can be embedded into another web page by using an iframe: @@ -828,8 +818,6 @@ This web page can be embedded into another web page by using an iframe:
<iframe src="http://mediamtx-ip:8888/mystream" scrolling="no"></iframe>
```
For more advanced setups, you can create and serve a custom web page by starting from the [source code of the HLS read page](internal/servers/hls/index.html).
### By protocol
#### SRT
@ -848,8 +836,6 @@ If credentials are enabled, append username and password to `streamid`; @@ -848,8 +836,6 @@ If credentials are enabled, append username and password to `streamid`;
srt://localhost:8890?streamid=read:mystream:user:pass
```
If you need to use the standard stream ID syntax instead of the custom one in use by this server, see [Standard stream ID syntax](#standard-stream-id-syntax).
Known clients that can read with SRT are [FFmpeg](#ffmpeg-1), [GStreamer](#gstreamer-1) and [VLC](#vlc).
#### WebRTC
@ -1027,48 +1013,35 @@ There are 3 ways to change the configuration: @@ -1027,48 +1013,35 @@ There are 3 ways to change the configuration:
docker run --rm -it --network=host -e MTX_PATHS_TEST_SOURCE=rtsp://myurl bluenviron/mediamtx
```
3. By using the [Control API](#control-api).
3. By using the [API](#api).
### Authentication
#### Internal
The server provides three way to authenticate users:
* Internal: users are stored in the configuration file
* HTTP-based: an external HTTP URL is contacted to perform authentication
* JWT: an external identity server provides authentication through JWTs
The internal authentication method is the default one. Users are stored inside the configuration file, in this format:
Edit `mediamtx.yml` and set `publishUser` and `publishPass`:
```yml
authInternalUsers:
# Username. 'any' means any user, including anonymous ones.
- user: any
# Password. Not used in case of 'any' user.
pass:
# IPs or networks allowed to use this user. An empty list means any IP.
ips: []
# List of permissions.
permissions:
# Available actions are: publish, read, playback, api, metrics, pprof.
- action: publish
# Paths can be set to further restrict access to a specific path.
# An empty path means any path.
# Regular expressions can be used by using a tilde as prefix.
path:
- action: read
path:
- action: playback
path:
```
Only clients that provide username and passwords will be able to perform a given action:
pathDefaults:
publishUser: myuser
publishPass: mypass
```
Only publishers that provide both username and password will be able to proceed:
```
ffmpeg -re -stream_loop -1 -i file.ts -c copy -f rtsp rtsp://myuser:mypass@localhost:8554/mystream
```
If storing plain credentials in the configuration file is a security problem, username and passwords can be stored as hashed strings. The Argon2 and SHA256 hashing algorithms are supported. To use Argon2, the string must be hashed using Argon2id (recommended) or Argon2i:
It's possible to setup authentication for readers too:
```yml
pathDefaults:
readUser: myuser
readPass: mypass
```
If storing plain credentials in the configuration file is a security problem, username and passwords can be stored as hashed strings. The Argon2 and SHA256 hashing algorithms are supported.
To use Argon2, the string must be hashed using Argon2id (recommended) or Argon2i:
```
echo -n "mypass" | argon2 saltItWithSalt -id -l 32 -e
@ -1077,11 +1050,9 @@ echo -n "mypass" | argon2 saltItWithSalt -id -l 32 -e @@ -1077,11 +1050,9 @@ echo -n "mypass" | argon2 saltItWithSalt -id -l 32 -e
Then stored with the `argon2:` prefix:
```yml
authInternalUsers:
- user: argon2:$argon2id$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$OGGO0eCMN0ievb4YGSzvS/H+Vajx1pcbUmtLp2tRqRU
pass: argon2:$argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$oct3kOiFywTdDdt19kT07hdvmsPTvt9zxAUho2DLqZw
permissions:
- action: publish
pathDefaults:
readUser: argon2:$argon2id$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$OGGO0eCMN0ievb4YGSzvS/H+Vajx1pcbUmtLp2tRqRU
readPass: argon2:$argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$oct3kOiFywTdDdt19kT07hdvmsPTvt9zxAUho2DLqZw
```
To use SHA256, the string must be hashed with SHA256 and encoded with base64:
@ -1093,21 +1064,16 @@ echo -n "mypass" | openssl dgst -binary -sha256 | openssl base64 @@ -1093,21 +1064,16 @@ echo -n "mypass" | openssl dgst -binary -sha256 | openssl base64
Then stored with the `sha256:` prefix:
```yml
authInternalUsers:
- user: sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo=
pass: sha256:BdSWkrdV+ZxFBLUQQY7+7uv9RmiSVA8nrPmjGjJtZQQ=
permissions:
- action: publish
pathDefaults:
readUser: sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo=
readPass: sha256:BdSWkrdV+ZxFBLUQQY7+7uv9RmiSVA8nrPmjGjJtZQQ=
```
**WARNING**: enable encryption or use a VPN to ensure that no one is intercepting the credentials in transit.
#### HTTP-based
Authentication can be delegated to an external HTTP server:
```yml
authMethod: http
externalAuthenticationURL: http://myauthserver/auth
```
@ -1115,18 +1081,20 @@ Each time a user needs to be authenticated, the specified URL will be requested @@ -1115,18 +1081,20 @@ Each time a user needs to be authenticated, the specified URL will be requested
```json
{
"ip": "ip",
"user": "user",
"password": "password",
"ip": "ip",
"action": "publish|read|playback|api|metrics|pprof",
"path": "path",
"protocol": "rtsp|rtmp|hls|webrtc|srt",
"protocol": "rtsp|rtmp|hls|webrtc",
"id": "id",
"action": "read|publish",
"query": "query"
}
```
If the URL returns a status code that begins with `20` (i.e. `200`), authentication is successful, otherwise it fails. Be aware that it's perfectly normal for the authentication server to receive requests with empty users and passwords, i.e.:
If the URL returns a status code that begins with `20` (i.e. `200`), authentication is successful, otherwise it fails.
Please be aware that it's perfectly normal for the authentication server to receive requests with empty users and passwords, i.e.:
```json
{
@ -1135,107 +1103,7 @@ If the URL returns a status code that begins with `20` (i.e. `200`), authenticat @@ -1135,107 +1103,7 @@ If the URL returns a status code that begins with `20` (i.e. `200`), authenticat
}
```
This happens because RTSP clients don't provide credentials until they are asked to. In order to receive the credentials, the authentication server must reply with status code `401`, then the client will send credentials.
Some actions can be excluded from the process:
```yml
# Actions to exclude from HTTP-based authentication.
# Format is the same as the one of user permissions.
authHTTPExclude:
- action: api
- action: metrics
- action: pprof
```
#### JWT-based
Authentication can be delegated to an external identity server, that is capable of generating JWTs and provides a JWKS endpoint. With respect to the HTTP-based method, this has the advantage that the external server is contacted just once, and not for every request, greatly improving performance. In order to use the JWT-based authentication method, set `authMethod` and `authJWTJWKS`:
```yml
authMethod: jwt
authJWTJWKS: http://my_identity_server/jwks_endpoint
```
The JWT is expected to contain the `mediamtx_permissions` scope, with a list of permissions in the same format as the one of user permissions:
```json
{
"mediamtx_permissions": [
{
"action": "publish",
"path": ""
}
]
}
```
Clients are expected to pass the JWT in query parameters, for instance:
```
ffmpeg -re -stream_loop -1 -i file.ts -c copy -f rtsp rtsp://localhost:8554/mystream?jwt=MY_JWT
```
Here's a tutorial on how to setup the [Keycloak identity server](https://www.keycloak.org/) in order to provide such JWTs:
1. Start Keycloak:
```
docker run --name=keycloak -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:23.0.7 start-dev
```
2. Open the Keycloak administration console on http://localhost:8080, click on _master_ in the top left corner, _create realm_, set realm name to `mediamtx`, Save
3. Open page _Client scopes_, _create client scope_, set name to `mediamtx`, Save
4. Open tab _Mappers_, _Configure a new Mapper_, _User Attribute_
* Name: `mediamtx_permissions`
* User Attribute: `mediamtx_permissions`
* Token Claim Name: `mediamtx_permissions`
* Claim JSON Type: `JSON`
* Multivalued: `On`
Save
5. Open page _Clients_, _Create client_, set Client ID to `mediamtx`, Next, Client authentication `On`, Next, Save
6. Open tab _Credentials_, copy client secret somewhere
7. Open tab _Client scopes_, _Add client scope_, Select `mediamtx`, Add, Default
8. Open page _Users_, _Create user_, Username `testuser`, Tab credentials, _Set password_, pick a password, Save
9. Open tab _Attributes_, _Add an attribute_
* Key: `mediamtx_permissions`
* Value: `{"action":"publish", "paths": "all"}`
You can add as many attributes with key `mediamtx_permissions` as you want, each with a single permission in it
10. In MediaMTX, use the following URL:
```yml
authJWTJWKS: http://localhost:8080/realms/mediamtx/protocol/openid-connect/certs
```
11. Perform authentication on Keycloak:
```
curl \
-d "client_id=mediamtx" \
-d "client_secret=$CLIENT_SECRET" \
-d "username=$USER" \
-d "password=$PASS" \
-d "grant_type=password" \
http://localhost:8080/realms/mediamtx/protocol/openid-connect/token
```
The JWT is inside the `access_token` key of the response:
```json
{"access_token":"eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIyNzVjX3ptOVlOdHQ0TkhwWVk4Und6ZndUclVGSzRBRmQwY3lsM2wtY3pzIn0.eyJleHAiOjE3MDk1NTUwOTIsImlhdCI6MTcwOTU1NDc5MiwianRpIjoiMzE3ZTQ1NGUtNzczMi00OTM1LWExNzAtOTNhYzQ2ODhhYWIxIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9tZWRpYW10eCIsImF1ZCI6ImFjY291bnQiLCJzdWIiOiI2NTBhZDA5Zi03MDgxLTQyNGItODI4Ni0xM2I3YTA3ZDI0MWEiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJtZWRpYW10eCIsInNlc3Npb25fc3RhdGUiOiJjYzJkNDhjYy1kMmU5LTQ0YjAtODkzZS0wYTdhNjJiZDI1YmQiLCJhY3IiOiIxIiwiYWxsb3dlZC1vcmlnaW5zIjpbIi8qIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJvZmZsaW5lX2FjY2VzcyIsInVtYV9hdXRob3JpemF0aW9uIiwiZGVmYXVsdC1yb2xlcy1tZWRpYW10eCJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoibWVkaWFtdHggcHJvZmlsZSBlbWFpbCIsInNpZCI6ImNjMmQ0OGNjLWQyZTktNDRiMC04OTNlLTBhN2E2MmJkMjViZCIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwibWVkaWFtdHhfcGVybWlzc2lvbnMiOlt7ImFjdGlvbiI6InB1Ymxpc2giLCJwYXRocyI6ImFsbCJ9XSwicHJlZmVycmVkX3VzZXJuYW1lIjoidGVzdHVzZXIifQ.Gevz7rf1qHqFg7cqtSfSP31v_NS0VH7MYfwAdra1t6Yt5rTr9vJzqUeGfjYLQWR3fr4XC58DrPOhNnILCpo7jWRdimCnbPmuuCJ0AYM-Aoi3PAsWZNxgmtopq24_JokbFArY9Y1wSGFvF8puU64lt1jyOOyxf2M4cBHCs_EarCKOwuQmEZxSf8Z-QV9nlfkoTUszDCQTiKyeIkLRHL2Iy7Fw7_T3UI7sxJjVIt0c6HCNJhBBazGsYzmcSQ_GrmhbUteMTg00o6FicqkMBe99uZFnx9wIBm_QbO9hbAkkzF923I-DTAQrFLxT08ESMepDwmzFrmnwWYBLE3u8zuUlCA","expires_in":300,"refresh_expires_in":1800,"refresh_token":"eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI3OTI3Zjg4Zi05YWM4LTRlNmEtYWE1OC1kZmY0MDQzZDRhNGUifQ.eyJleHAiOjE3MDk1NTY1OTIsImlhdCI6MTcwOTU1NDc5MiwianRpIjoiMGVhZWFhMWItYzNhMC00M2YxLWJkZjAtZjI2NTRiODlkOTE3IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwL3JlYWxtcy9tZWRpYW10eCIsImF1ZCI6Imh0dHA6Ly9sb2NhbGhvc3Q6ODA4MC9yZWFsbXMvbWVkaWFtdHgiLCJzdWIiOiI2NTBhZDA5Zi03MDgxLTQyNGItODI4Ni0xM2I3YTA3ZDI0MWEiLCJ0eXAiOiJSZWZyZXNoIiwiYXpwIjoibWVkaWFtdHgiLCJzZXNzaW9uX3N0YXRlIjoiY2MyZDQ4Y2MtZDJlOS00NGIwLTg5M2UtMGE3YTYyYmQyNWJkIiwic2NvcGUiOiJtZWRpYW10eCBwcm9maWxlIGVtYWlsIiwic2lkIjoiY2MyZDQ4Y2MtZDJlOS00NGIwLTg5M2UtMGE3YTYyYmQyNWJkIn0.yuXV8_JU0TQLuosNdp5xlYMjn7eO5Xq-PusdHzE7bsQ","token_type":"Bearer","not-before-policy":0,"session_state":"cc2d48cc-d2e9-44b0-893e-0a7a62bd25bd","scope":"mediamtx profile email"}
```
This happens because a RTSP client doesn't provide credentials until it is asked to. In order to receive the credentials, the authentication server must reply with status code `401`, then the client will send credentials.
### Encrypt the configuration
@ -1315,62 +1183,6 @@ To upload recordings to a remote location, you can use _MediaMTX_ together with @@ -1315,62 +1183,6 @@ To upload recordings to a remote location, you can use _MediaMTX_ together with
If you want to delete local segments after they are uploaded, replace `rclone sync` with `rclone move`.
### Playback recorded streams
Existing recordings can be served to users through a dedicated HTTP server, that can be enabled inside the configuration:
```yml
playback: yes
playbackAddress: :9996
```
The server provides an endpoint to list recorded timespans:
```
http://localhost:9996/list?path=[mypath]
```
Where [mypath] is the name of a path. The server will return a list of timespans in JSON format:
```json
[
{
"start": "2006-01-02T15:04:05Z07:00",
"duration": "60.0"
},
{
"start": "2006-01-02T15:07:05Z07:00",
"duration": "32.33"
}
]
```
The server provides an endpoint for downloading recordings:
```
http://localhost:9996/get?path=[mypath]&start=[start_date]&duration=[duration]
```
Where:
* [mypath] is the path name
* [start_date] is the start date in [RFC3339 format](https://www.utctime.net/)
* [duration] is the maximum duration of the recording in seconds
All parameters must be [url-encoded](https://www.urlencoder.org/). For instance:
```
http://localhost:9996/get?path=stream2&start=2024-01-14T16%3A33%3A17%2B00%3A00&duration=200.5
```
The resulting stream uses the fMP4 format, that is natively compatible with any browser, therefore its URL can be directly inserted into a \<video> tag:
```html
<video controls>
<source src="http://localhost:9996/get?path=[mypath]&start=[start_date]&duration=[duration]" type="video/mp4" />
</video>
```
### Forward streams to other servers
To forward incoming streams to another server, use _FFmpeg_ inside the `runOnReady` parameter:
@ -1665,9 +1477,9 @@ pathDefaults: @@ -1665,9 +1477,9 @@ pathDefaults:
runOnRecordSegmentComplete: curl http://my-custom-server/webhook?path=$MTX_PATH&segment_path=$MTX_SEGMENT_PATH
```
### Control API
### API
The server can be queried and controlled with an API, that must be enabled by setting the `api` parameter in the configuration:
The server can be queried and controlled with its API, that must be enabled by setting the `api` parameter in the configuration:
```yml
api: yes
@ -1676,10 +1488,10 @@ api: yes @@ -1676,10 +1488,10 @@ api: yes
The API listens on `apiAddress`, that by default is `127.0.0.1:9997`; for instance, to obtain a list of active paths, run:
```
curl http://127.0.0.1:9997/v3/paths/list
curl http://127.0.0.1:9997/v2/paths/list
```
Full documentation of the Control API is available on the [dedicated site](https://bluenviron.github.io/mediamtx/).
Full documentation of the API is available on the [dedicated site](https://bluenviron.github.io/mediamtx/).
### Metrics
@ -1733,57 +1545,8 @@ rtmps_conns_bytes_sent{id="[id]",state="[state]"} 187 @@ -1733,57 +1545,8 @@ rtmps_conns_bytes_sent{id="[id]",state="[state]"} 187
# metrics of every SRT connection
srt_conns{id="[id]",state="[state]"} 1
srt_conns_packets_sent{id="[id]",state="[state]"} 123
srt_conns_packets_received{id="[id]",state="[state]"} 123
srt_conns_packets_sent_unique{id="[id]",state="[state]"} 123
srt_conns_packets_received_unique{id="[id]",state="[state]"} 123
srt_conns_packets_send_loss{id="[id]",state="[state]"} 123
srt_conns_packets_received_loss{id="[id]",state="[state]"} 123
srt_conns_packets_retrans{id="[id]",state="[state]"} 123
srt_conns_packets_received_retrans{id="[id]",state="[state]"} 123
srt_conns_packets_sent_ack{id="[id]",state="[state]"} 123
srt_conns_packets_received_ack{id="[id]",state="[state]"} 123
srt_conns_packets_sent_nak{id="[id]",state="[state]"} 123
srt_conns_packets_received_nak{id="[id]",state="[state]"} 123
srt_conns_packets_sent_km{id="[id]",state="[state]"} 123
srt_conns_packets_received_km{id="[id]",state="[state]"} 123
srt_conns_us_snd_duration{id="[id]",state="[state]"} 123
srt_conns_packets_send_drop{id="[id]",state="[state]"} 123
srt_conns_packets_received_drop{id="[id]",state="[state]"} 123
srt_conns_packets_received_undecrypt{id="[id]",state="[state]"} 123
srt_conns_bytes_sent{id="[id]",state="[state]"} 187
srt_conns_bytes_received{id="[id]",state="[state]"} 1234
srt_conns_bytes_sent_unique{id="[id]",state="[state]"} 123
srt_conns_bytes_received_unique{id="[id]",state="[state]"} 123
srt_conns_bytes_received_loss{id="[id]",state="[state]"} 123
srt_conns_bytes_retrans{id="[id]",state="[state]"} 123
srt_conns_bytes_received_retrans{id="[id]",state="[state]"} 123
srt_conns_bytes_send_drop{id="[id]",state="[state]"} 123
srt_conns_bytes_received_drop{id="[id]",state="[state]"} 123
srt_conns_bytes_received_undecrypt{id="[id]",state="[state]"} 123
srt_conns_us_packets_send_period{id="[id]",state="[state]"} 123.123
srt_conns_packets_flow_window{id="[id]",state="[state]"} 123
srt_conns_packets_flight_size{id="[id]",state="[state]"} 123
srt_conns_ms_rtt{id="[id]",state="[state]"} 123.123
srt_conns_mbps_send_rate{id="[id]",state="[state]"} 123
srt_conns_mbps_receive_rate{id="[id]",state="[state]"} 123.123
srt_conns_mbps_link_capacity{id="[id]",state="[state]"} 123.123
srt_conns_bytes_avail_send_buf{id="[id]",state="[state]"} 123
srt_conns_bytes_avail_receive_buf{id="[id]",state="[state]"} 123
srt_conns_mbps_max_bw{id="[id]",state="[state]"} -123
srt_conns_bytes_mss{id="[id]",state="[state]"} 123
srt_conns_packets_send_buf{id="[id]",state="[state]"} 123
srt_conns_bytes_send_buf{id="[id]",state="[state]"} 123
srt_conns_ms_send_buf{id="[id]",state="[state]"} 123
srt_conns_ms_send_tsb_pd_delay{id="[id]",state="[state]"} 123
srt_conns_packets_receive_buf{id="[id]",state="[state]"} 123
srt_conns_bytes_receive_buf{id="[id]",state="[state]"} 123
srt_conns_ms_receive_buf{id="[id]",state="[state]"} 123
srt_conns_ms_receive_tsb_pd_delay{id="[id]",state="[state]"} 123
srt_conns_packets_reorder_tolerance{id="[id]",state="[state]"} 123
srt_conns_packets_received_avg_belated_time{id="[id]",state="[state]"} 123
srt_conns_packets_send_loss_rate{id="[id]",state="[state]"} 123
srt_conns_packets_received_loss_rate{id="[id]",state="[state]"} 123
srt_conns_bytes_sent{id="[id]",state="[state]"} 187
# metrics of every WebRTC session
webrtc_sessions{id="[id]",state="[state]"} 1
@ -1801,94 +1564,6 @@ go tool pprof -text http://localhost:9999/debug/pprof/heap @@ -1801,94 +1564,6 @@ go tool pprof -text http://localhost:9999/debug/pprof/heap
go tool pprof -text http://localhost:9999/debug/pprof/profile?seconds=30
```
### SRT-specific features
#### Standard stream ID syntax
In SRT, the stream ID is a string that is sent to the counterpart in order to advertise what action the caller is gonna do (publish or read), the path and the credentials. All these informations have to be encoded into a single string. This server supports two stream ID syntaxes, a custom one (that is the one reported in rest of the README) and also a [standard one](https://github.com/Haivision/srt/blob/master/docs/features/access-control.md) proposed by the authors of the protocol and sometimes enforced by some hardware. The standard syntax can be used in this way:
```
srt://localhost:8890?streamid=#!::m=publish,r=mypath,u=myuser,s=mypass&pkt_size=1316
```
Where:
* key `m` contains the action (`publish` or `request`)
* key `r` contains the path
* key `u` contains the username
* key `s` contains the password
### WebRTC-specific features
#### Connectivity issues
If the server is hosted inside a container or is behind a NAT, additional configuration is required in order to allow the two WebRTC parts (server and client) to establish a connection.
Make sure that `webrtcAdditionalHosts` includes your public IPs, that are IPs that can be used by clients to reach the server. If clients are on the same LAN as the server, then insert the LAN address of the server. If clients are coming from the internet, insert the public IP address of the server, or alternatively a DNS name, if you have one. You can insert multiple values to support all scenarios:
```yml
webrtcAdditionalHosts: [192.168.x.x, 1.2.3.4, my-dns.example.org, ...]
```
If there's a NAT / container between server and clients, it must be configured to route all incoming UDP packets on port 8189 to the server. If you're using Docker, this can be achieved with the flag:
```sh
docker run --rm -it \
-p 8189:8189/udp
....
bluenviron/mediamtx
```
If you still have problems, maybe the UDP protocol is blocked by a firewall. Enable the local TCP listener:
```yml
# any port of choice
webrtcLocalTCPAddress: :8189
```
If there's a NAT / container between server and clients, it must be configured to route all incoming TCP packets on port 8189 to the server.
If you still have problems, enable a STUN server:
```yml
# STUN servers allows to obtain and share the public IP of the server.
webrtcICEServers2:
- url: stun:stun.l.google.com:19302
```
If you really still have problems, you can force all WebRTC/ICE connections to pass through a TURN server, like coturn, that must be configured externally. The server address and credentials must be set in the configuration file:
```yml
# TURN/TURNS servers forces all traffic through them.
webrtcICEServers2:
- url: turn:host:port
username: user
password: password
```
Where user and pass are the username and password of the server. Note that port is not optional.
If the server uses a secret-based authentication (for instance, coturn with the use-auth-secret option), it must be configured by using AUTH_SECRET as username, and the secret as password:
```yml
webrtcICEServers2:
- url: turn:host:port
username: AUTH_SECRET
password: secret
```
where secret is the secret of the TURN server. MediaMTX will generate a set of credentials by using the secret, and credentials will be sent to clients before the WebRTC/ICE connection is established.
In some cases you may want the browser to connect using TURN servers but have mediamtx not using TURN (for example if the TURN server is on the same network as mediamtx). To allow this you can configure the TURN server to be client only:
```yml
webrtcICEServers2:
- url: turn:host:port
username: user
password: password
clientOnly: true
```
### RTSP-specific features
#### Transport protocols
@ -1979,6 +1654,67 @@ rtmps://localhost:1937/... @@ -1979,6 +1654,67 @@ rtmps://localhost:1937/...
Be aware that RTMPS is currently unsupported by all major players. However, you can use a proxy like [stunnel](https://www.stunnel.org) or [nginx](https://nginx.org/) or a dedicated _MediaMTX_ instance to decrypt streams before reading them.
### WebRTC-specific features
#### Connectivity issues
If the server is hosted inside a container or is behind a NAT, additional configuration is required in order to allow the two WebRTC parts (server and client) to establish a connection.
Make sure that `webrtcAdditionalHosts` includes your public IPs, that are IPs that can be used by clients to reach the server. If clients are on the same LAN as the server, then insert the LAN address of the server. If clients are coming from the internet, insert the public IP address of the server, or alternatively a DNS name, if you have one. You can insert multiple values to support all scenarios:
```yml
webrtcAdditionalHosts: [192.168.x.x, 1.2.3.4, my-dns.example.org, ...]
```
If there's a NAT / container between server and clients, it must be configured to route all incoming UDP packets on port 8189 to the server. If you're using Docker, this can be achieved with the flag:
```sh
docker run --rm -it \
-p 8189:8189/udp
....
bluenviron/mediamtx
```
If you still have problems, maybe the UDP protocol is blocked by a firewall. Enable the local TCP listener:
```yml
# any port of choice
webrtcLocalTCPAddress: :8189
```
If there's a NAT / container between server and clients, it must be configured to route all incoming TCP packets on port 8189 to the server.
If you still have problems, enable a STUN server:
```yml
# STUN servers allows to obtain and share the public IP of the server.
webrtcICEServers2:
- url: stun:stun.l.google.com:19302
```
If you really still have problems, you can force all WebRTC/ICE connections to pass through a TURN server, like coturn, that must be configured externally. The server address and credentials must be set in the configuration file:
```yml
# TURN/TURNS servers forces all traffic through them.
webrtcICEServers2:
- url: turn:host:port
username: user
password: password
```
Where user and pass are the username and password of the server. Note that port is not optional.
If the server uses a secret-based authentication (for instance, coturn with the use-auth-secret option), it must be configured by using AUTH_SECRET as username, and the secret as password:
```yml
webrtcICEServers2:
- url: turn:host:port
username: AUTH_SECRET
password: secret
```
where secret is the secret of the TURN server. MediaMTX will generate a set of credentials by using the secret, and credentials will be sent to clients before the WebRTC/ICE connection is established.
## Compile from source
### Standard
@ -1988,7 +1724,6 @@ Install git and Go &ge; 1.21. Clone the repository, enter into the folder and st @@ -1988,7 +1724,6 @@ Install git and Go &ge; 1.21. Clone the repository, enter into the folder and st
```sh
git clone https://github.com/bluenviron/mediamtx
cd mediamtx
go generate ./...
CGO_ENABLED=0 go build .
```
@ -2009,7 +1744,6 @@ Download the repository, open a terminal in it and run: @@ -2009,7 +1744,6 @@ Download the repository, open a terminal in it and run:
cd internal/protocols/rpicamera/exe
make
cd ../../../../
go generate ./...
go build -tags rpicamera .
```
@ -2029,7 +1763,6 @@ Clone the repository, enter into the folder and start the building process: @@ -2029,7 +1763,6 @@ Clone the repository, enter into the folder and start the building process:
```sh
git clone https://github.com/bluenviron/mediamtx
cd mediamtx
go generate ./...
CGO_ENABLED=0 go build .
```
@ -2046,7 +1779,6 @@ On the machine you want to use to compile, install git and Go &ge; 1.21. Clone t @@ -2046,7 +1779,6 @@ On the machine you want to use to compile, install git and Go &ge; 1.21. Clone t
```sh
git clone https://github.com/bluenviron/mediamtx
cd mediamtx
go generate ./...
CGO_ENABLED=0 GOOS=my_os GOARCH=my_arch go build .
```
@ -2086,13 +1818,6 @@ make binaries @@ -2086,13 +1818,6 @@ make binaries
The command will produce tarballs in folder `binaries/`.
## License
All the code in this repository is released under the [MIT License](LICENSE). Compiled binaries make use of some third-party dependencies:
* hls.js, released under the [Apache License 2.0](https://github.com/video-dev/hls.js/blob/master/LICENSE)
* all the dependencies listed into the [go.mod file](go.mod), which are all released under either the MIT license, BSD-3-Clause license or Apache License 2.0
## Specifications
|name|area|
@ -2101,7 +1826,6 @@ All the code in this repository is released under the [MIT License](LICENSE). Co @@ -2101,7 +1826,6 @@ All the code in this repository is released under the [MIT License](LICENSE). Co
|[HLS specifications](https://github.com/bluenviron/gohlslib#specifications)|HLS|
|[RTMP](https://rtmp.veriskope.com/pdf/rtmp_specification_1.0.pdf)|RTMP|
|[Enhanced RTMP](https://raw.githubusercontent.com/veovera/enhanced-rtmp/main/enhanced-rtmp-v1.pdf)|RTMP|
|[Action Message Format](https://rtmp.veriskope.com/pdf/amf0-file-format-specification.pdf)|RTMP|
|[WebRTC: Real-Time Communication in Browsers](https://www.w3.org/TR/webrtc/)|WebRTC|
|[WebRTC HTTP Ingestion Protocol (WHIP)](https://datatracker.ietf.org/doc/draft-ietf-wish-whip/)|WebRTC|
|[WebRTC HTTP Egress Protocol (WHEP)](https://datatracker.ietf.org/doc/draft-murillo-whep/)|WebRTC|
@ -2119,6 +1843,7 @@ All the code in this repository is released under the [MIT License](LICENSE). Co @@ -2119,6 +1843,7 @@ All the code in this repository is released under the [MIT License](LICENSE). Co
* [pion/sdp (SDP library used internally)](https://github.com/pion/sdp)
* [pion/rtp (RTP library used internally)](https://github.com/pion/rtp)
* [pion/rtcp (RTCP library used internally)](https://github.com/pion/rtcp)
* [notedit/rtmp (RTMP library used internally)](https://github.com/notedit/rtmp)
* [go-astits (MPEG-TS library used internally)](https://github.com/asticode/go-astits)
* [go-mp4 (MP4 library used internally)](https://github.com/abema/go-mp4)
* [hls.js (browser-side HLS library used internally)](https://github.com/video-dev/hls.js)

532
apidocs/openapi.yaml

@ -43,6 +43,10 @@ components: @@ -43,6 +43,10 @@ components:
type: integer
externalAuthenticationURL:
type: string
api:
type: boolean
apiAddress:
type: string
metrics:
type: boolean
metricsAddress:
@ -58,18 +62,6 @@ components: @@ -58,18 +62,6 @@ components:
runOnDisconnect:
type: string
# API
api:
type: boolean
apiAddress:
type: string
# Playback server
playback:
type: boolean
playbackAddress:
type: string
# RTSP server
rtsp:
type: boolean
@ -97,7 +89,7 @@ components: @@ -97,7 +89,7 @@ components:
type: string
serverCert:
type: string
rtspAuthMethods:
authMethods:
type: array
items:
type: string
@ -190,8 +182,6 @@ components: @@ -190,8 +182,6 @@ components:
type: string
password:
type: string
clientOnly:
type: boolean
# SRT server
srt:
@ -223,11 +213,9 @@ components: @@ -223,11 +213,9 @@ components:
fallback:
type: string
# Record and playback
# Record
record:
type: boolean
playback:
type: boolean
recordPath:
type: string
recordFormat:
@ -300,12 +288,6 @@ components: @@ -300,12 +288,6 @@ components:
type: string
rpiCameraAWB:
type: string
rpiCameraAWBGains:
type: array
minItems: 2
maxItems: 2
items:
type: number
rpiCameraDenoise:
type: string
rpiCameraShutter:
@ -491,32 +473,6 @@ components: @@ -491,32 +473,6 @@ components:
items:
$ref: '#/components/schemas/HLSMuxer'
RecordingSegment:
type: object
properties:
start:
type: string
Recording:
type: object
properties:
name:
type: string
segments:
type: array
items:
$ref: '#/components/schemas/RecordingSegment'
RecordingList:
type: object
properties:
pageCount:
type: integer
items:
type: array
items:
$ref: '#/components/schemas/Recording'
RTMPConn:
type: object
properties:
@ -628,211 +584,12 @@ components: @@ -628,211 +584,12 @@ components:
type: string
query:
type: string
packetsSent:
type: integer
format: int64
description: The total number of sent DATA packets, including retransmitted packets
packetsReceived:
type: integer
format: int64
description: The total number of received DATA packets, including retransmitted packets
packetsSentUnique:
type: integer
format: int64
description: The total number of unique DATA packets sent by the SRT sender
packetsReceivedUnique:
type: integer
format: int64
description: The total number of unique original, retransmitted or recovered by the packet filter DATA packets received in time, decrypted without errors and, as a result, scheduled for delivery to the upstream application by the SRT receiver.
packetsSendLoss:
type: integer
format: int64
description: The total number of data packets considered or reported as lost at the sender side. Does not correspond to the packets detected as lost at the receiver side.
packetsReceivedLoss:
type: integer
format: int64
description: The total number of SRT DATA packets detected as presently missing (either reordered or lost) at the receiver side
packetsRetrans:
type: integer
format: int64
description: The total number of retransmitted packets sent by the SRT sender
packetsReceivedRetrans:
type: integer
format: int64
description: The total number of retransmitted packets registered at the receiver side
packetsSentACK:
type: integer
format: int64
description: The total number of sent ACK (Acknowledgement) control packets
packetsReceivedACK:
type: integer
format: int64
description: The total number of received ACK (Acknowledgement) control packets
packetsSentNAK:
type: integer
format: int64
description: The total number of sent NAK (Negative Acknowledgement) control packets
packetsReceivedNAK:
type: integer
format: int64
description: The total number of received NAK (Negative Acknowledgement) control packets
packetsSentKM:
type: integer
format: int64
description: The total number of sent KM (Key Material) control packets
packetsReceivedKM:
type: integer
format: int64
description: The total number of received KM (Key Material) control packets
usSndDuration:
type: integer
format: int64
description: The total accumulated time in microseconds, during which the SRT sender has some data to transmit, including packets that have been sent, but not yet acknowledged
packetsSendDrop:
type: integer
format: int64
description: The total number of dropped by the SRT sender DATA packets that have no chance to be delivered in time
packetsReceivedDrop:
type: integer
format: int64
description: The total number of dropped by the SRT receiver and, as a result, not delivered to the upstream application DATA packets
packetsReceivedUndecrypt:
type: integer
format: int64
description: The total number of packets that failed to be decrypted at the receiver side
bytesSent:
type: integer
format: int64
description: Same as packetsSent, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
bytesReceived:
type: integer
format: int64
description: Same as packetsReceived, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
bytesSentUnique:
type: integer
format: int64
description: Same as packetsSentUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
bytesReceivedUnique:
type: integer
format: int64
description: Same as packetsReceivedUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
bytesReceivedLoss:
type: integer
format: int64
description: Same as packetsReceivedLoss, but expressed in bytes, including payload and all the headers (IP, TCP, SRT), bytes for the presently missing (either reordered or lost) packets' payloads are estimated based on the average packet size
bytesRetrans:
type: integer
format: int64
description: Same as packetsRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
bytesReceivedRetrans:
type: integer
format: int64
description: Same as packetsReceivedRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
bytesSendDrop:
type: integer
format: int64
description: Same as packetsSendDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
bytesReceivedDrop:
type: integer
format: int64
description: Same as packetsReceivedDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
bytesReceivedUndecrypt:
type: integer
format: int64
description: Same as packetsReceivedUndecrypt, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
usPacketsSendPeriod:
type: number
format: float64
description: Current minimum time interval between which consecutive packets are sent, in microseconds
packetsFlowWindow:
type: integer
format: int64
description: The maximum number of packets that can be "in flight"
packetsFlightSize:
type: integer
format: int64
description: The number of packets in flight
msRTT:
type: number
format: float64
description: Smoothed round-trip time (SRTT), an exponentially-weighted moving average (EWMA) of an endpoint's RTT samples, in milliseconds
mbpsSendRate:
type: number
format: float64
description: Current transmission bandwidth, in Mbps
mbpsReceiveRate:
type: number
format: float64
description: Current receiving bandwidth, in Mbps
mbpsLinkCapacity:
type: number
format: float64
description: Estimated capacity of the network link, in Mbps
bytesAvailSendBuf:
type: integer
format: int64
description: The available space in the sender's buffer, in bytes
bytesAvailReceiveBuf:
type: integer
format: int64
description: The available space in the receiver's buffer, in bytes
mbpsMaxBW:
type: number
format: float64
description: Transmission bandwidth limit, in Mbps
byteMSS:
type: integer
format: int64
description: Maximum Segment Size (MSS), in bytes
packetsSendBuf:
type: integer
format: int64
description: The number of packets in the sender's buffer that are already scheduled for sending or even possibly sent, but not yet acknowledged
bytesSendBuf:
type: integer
format: int64
description: Instantaneous (current) value of packetsSndBuf, but expressed in bytes, including payload and all headers (IP, TCP, SRT)
msSendBuf:
type: integer
format: int64
description: The timespan (msec) of packets in the sender's buffer (unacknowledged packets)
msSendTsbPdDelay:
type: integer
format: int64
description: Timestamp-based Packet Delivery Delay value of the peer
packetsReceiveBuf:
type: integer
format: int64
description: The number of acknowledged packets in receiver's buffer
bytesReceiveBuf:
type: integer
format: int64
description: Instantaneous (current) value of packetsRcvBuf, expressed in bytes, including payload and all headers (IP, TCP, SRT)
msReceiveBuf:
type: integer
format: int64
description: The timespan (msec) of acknowledged packets in the receiver's buffer
msReceiveTsbPdDelay:
type: integer
format: int64
description: Timestamp-based Packet Delivery Delay value set on the socket via SRTO_RCVLATENCY or SRTO_LATENCY
packetsReorderTolerance:
type: integer
format: int64
description: Instant value of the packet reorder tolerance
packetsReceivedAvgBelatedTime:
bytesSent:
type: integer
format: int64
description: Accumulated difference between the current time and the time-to-play of a packet that is received late
packetsSendLossRate:
type: number
format: float64
description: Percentage of resent data vs. sent data
packetsReceivedLossRate:
type: number
format: float64
description: Percentage of retransmitted data vs. received data
SRTConnList:
type: object
@ -887,7 +644,6 @@ paths: @@ -887,7 +644,6 @@ paths:
/v3/config/global/get:
get:
operationId: configGlobalGet
tags: [Configuration]
summary: returns the global configuration.
description: ''
responses:
@ -913,7 +669,6 @@ paths: @@ -913,7 +669,6 @@ paths:
/v3/config/global/patch:
patch:
operationId: configGlobalSet
tags: [Configuration]
summary: patches the global configuration.
description: all fields are optional.
requestBody:
@ -941,7 +696,6 @@ paths: @@ -941,7 +696,6 @@ paths:
/v3/config/pathdefaults/get:
get:
operationId: configPathDefaultsGet
tags: [Configuration]
summary: returns the default path configuration.
description: ''
responses:
@ -967,7 +721,6 @@ paths: @@ -967,7 +721,6 @@ paths:
/v3/config/pathdefaults/patch:
patch:
operationId: configPathDefaultsPatch
tags: [Configuration]
summary: patches the default path configuration.
description: all fields are optional.
requestBody:
@ -995,7 +748,6 @@ paths: @@ -995,7 +748,6 @@ paths:
/v3/config/paths/list:
get:
operationId: configPathsList
tags: [Configuration]
summary: returns all path configurations.
description: ''
parameters:
@ -1034,7 +786,6 @@ paths: @@ -1034,7 +786,6 @@ paths:
/v3/config/paths/get/{name}:
get:
operationId: configPathsGet
tags: [Configuration]
summary: returns a path configuration.
description: ''
parameters:
@ -1057,12 +808,6 @@ paths: @@ -1057,12 +808,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: path not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1073,7 +818,6 @@ paths: @@ -1073,7 +818,6 @@ paths:
/v3/config/paths/add/{name}:
post:
operationId: configPathsAdd
tags: [Configuration]
summary: adds a path configuration.
description: all fields are optional.
parameters:
@ -1108,7 +852,6 @@ paths: @@ -1108,7 +852,6 @@ paths:
/v3/config/paths/patch/{name}:
patch:
operationId: configPathsPatch
tags: [Configuration]
summary: patches a path configuration.
description: all fields are optional.
parameters:
@ -1133,12 +876,6 @@ paths: @@ -1133,12 +876,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: path not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1149,7 +886,6 @@ paths: @@ -1149,7 +886,6 @@ paths:
/v3/config/paths/replace/{name}:
post:
operationId: configPathsReplace
tags: [Configuration]
summary: replaces all values of a path configuration.
description: all fields are optional.
parameters:
@ -1174,12 +910,6 @@ paths: @@ -1174,12 +910,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: path not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1190,7 +920,6 @@ paths: @@ -1190,7 +920,6 @@ paths:
/v3/config/paths/delete/{name}:
delete:
operationId: configPathsDelete
tags: [Configuration]
summary: removes a path configuration.
description: ''
parameters:
@ -1209,12 +938,6 @@ paths: @@ -1209,12 +938,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: path not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1225,7 +948,6 @@ paths: @@ -1225,7 +948,6 @@ paths:
/v3/hlsmuxers/list:
get:
operationId: hlsMuxersList
tags: [HLS]
summary: returns all HLS muxers.
description: ''
parameters:
@ -1264,7 +986,6 @@ paths: @@ -1264,7 +986,6 @@ paths:
/v3/hlsmuxers/get/{name}:
get:
operationId: hlsMuxersGet
tags: [HLS]
summary: returns a HLS muxer.
description: ''
parameters:
@ -1287,12 +1008,6 @@ paths: @@ -1287,12 +1008,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: muxer not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1303,7 +1018,6 @@ paths: @@ -1303,7 +1018,6 @@ paths:
/v3/paths/list:
get:
operationId: pathsList
tags: [Paths]
summary: returns all paths.
description: ''
parameters:
@ -1342,7 +1056,6 @@ paths: @@ -1342,7 +1056,6 @@ paths:
/v3/paths/get/{name}:
get:
operationId: pathsGet
tags: [Paths]
summary: returns a path.
description: ''
parameters:
@ -1365,12 +1078,6 @@ paths: @@ -1365,12 +1078,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: path not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1381,7 +1088,6 @@ paths: @@ -1381,7 +1088,6 @@ paths:
/v3/rtspconns/list:
get:
operationId: rtspConnsList
tags: [RTSP]
summary: returns all RTSP connections.
description: ''
parameters:
@ -1420,7 +1126,6 @@ paths: @@ -1420,7 +1126,6 @@ paths:
/v3/rtspconns/get/{id}:
get:
operationId: rtspConnsGet
tags: [RTSP]
summary: returns a RTSP connection.
description: ''
parameters:
@ -1443,12 +1148,6 @@ paths: @@ -1443,12 +1148,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1459,7 +1158,6 @@ paths: @@ -1459,7 +1158,6 @@ paths:
/v3/rtspsessions/list:
get:
operationId: rtspSessionsList
tags: [RTSP]
summary: returns all RTSP sessions.
description: ''
parameters:
@ -1498,7 +1196,6 @@ paths: @@ -1498,7 +1196,6 @@ paths:
/v3/rtspsessions/get/{id}:
get:
operationId: rtspSessionsGet
tags: [RTSP]
summary: returns a RTSP session.
description: ''
parameters:
@ -1521,12 +1218,6 @@ paths: @@ -1521,12 +1218,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: session not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1537,7 +1228,6 @@ paths: @@ -1537,7 +1228,6 @@ paths:
/v3/rtspsessions/kick/{id}:
post:
operationId: rtspSessionsKick
tags: [RTSP]
summary: kicks out a RTSP session from the server.
description: ''
parameters:
@ -1556,12 +1246,6 @@ paths: @@ -1556,12 +1246,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: session not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1572,7 +1256,6 @@ paths: @@ -1572,7 +1256,6 @@ paths:
/v3/rtspsconns/list:
get:
operationId: rtspsConnsList
tags: [RTSP]
summary: returns all RTSPS connections.
description: ''
parameters:
@ -1611,7 +1294,6 @@ paths: @@ -1611,7 +1294,6 @@ paths:
/v3/rtspsconns/get/{id}:
get:
operationId: rtspsConnsGet
tags: [RTSP]
summary: returns a RTSPS connection.
description: ''
parameters:
@ -1634,12 +1316,6 @@ paths: @@ -1634,12 +1316,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1650,7 +1326,6 @@ paths: @@ -1650,7 +1326,6 @@ paths:
/v3/rtspssessions/list:
get:
operationId: rtspsSessionsList
tags: [RTSP]
summary: returns all RTSPS sessions.
description: ''
parameters:
@ -1689,7 +1364,6 @@ paths: @@ -1689,7 +1364,6 @@ paths:
/v3/rtspssessions/get/{id}:
get:
operationId: rtspsSessionsGet
tags: [RTSP]
summary: returns a RTSPS session.
description: ''
parameters:
@ -1712,12 +1386,6 @@ paths: @@ -1712,12 +1386,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: session not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1728,7 +1396,6 @@ paths: @@ -1728,7 +1396,6 @@ paths:
/v3/rtspssessions/kick/{id}:
post:
operationId: rtspsSessionsKick
tags: [RTSP]
summary: kicks out a RTSPS session from the server.
description: ''
parameters:
@ -1747,12 +1414,6 @@ paths: @@ -1747,12 +1414,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: session not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1763,7 +1424,6 @@ paths: @@ -1763,7 +1424,6 @@ paths:
/v3/rtmpconns/list:
get:
operationId: rtmpConnsList
tags: [RTMP]
summary: returns all RTMP connections.
description: ''
parameters:
@ -1802,7 +1462,6 @@ paths: @@ -1802,7 +1462,6 @@ paths:
/v3/rtmpconns/get/{id}:
get:
operationId: rtmpConnectionsGet
tags: [RTMP]
summary: returns a RTMP connection.
description: ''
parameters:
@ -1825,12 +1484,6 @@ paths: @@ -1825,12 +1484,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1841,7 +1494,6 @@ paths: @@ -1841,7 +1494,6 @@ paths:
/v3/rtmpconns/kick/{id}:
post:
operationId: rtmpConnsKick
tags: [RTMP]
summary: kicks out a RTMP connection from the server.
description: ''
parameters:
@ -1860,12 +1512,6 @@ paths: @@ -1860,12 +1512,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1876,7 +1522,6 @@ paths: @@ -1876,7 +1522,6 @@ paths:
/v3/rtmpsconns/list:
get:
operationId: rtmpsConnsList
tags: [RTMP]
summary: returns all RTMPS connections.
description: ''
parameters:
@ -1915,7 +1560,6 @@ paths: @@ -1915,7 +1560,6 @@ paths:
/v3/rtmpsconns/get/{id}:
get:
operationId: rtmpsConnectionsGet
tags: [RTMP]
summary: returns a RTMPS connection.
description: ''
parameters:
@ -1938,12 +1582,6 @@ paths: @@ -1938,12 +1582,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1954,7 +1592,6 @@ paths: @@ -1954,7 +1592,6 @@ paths:
/v3/rtmpsconns/kick/{id}:
post:
operationId: rtmpsConnsKick
tags: [RTMP]
summary: kicks out a RTMPS connection from the server.
description: ''
parameters:
@ -1973,12 +1610,6 @@ paths: @@ -1973,12 +1610,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -1989,7 +1620,6 @@ paths: @@ -1989,7 +1620,6 @@ paths:
/v3/srtconns/list:
get:
operationId: srtConnsList
tags: [SRT]
summary: returns all SRT connections.
description: ''
parameters:
@ -2028,7 +1658,6 @@ paths: @@ -2028,7 +1658,6 @@ paths:
/v3/srtconns/get/{id}:
get:
operationId: srtConnsGet
tags: [SRT]
summary: returns a SRT connection.
description: ''
parameters:
@ -2051,12 +1680,6 @@ paths: @@ -2051,12 +1680,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -2067,7 +1690,6 @@ paths: @@ -2067,7 +1690,6 @@ paths:
/v3/srtconns/kick/{id}:
post:
operationId: srtConnsKick
tags: [SRT]
summary: kicks out a SRT connection from the server.
description: ''
parameters:
@ -2086,12 +1708,6 @@ paths: @@ -2086,12 +1708,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -2102,7 +1718,6 @@ paths: @@ -2102,7 +1718,6 @@ paths:
/v3/webrtcsessions/list:
get:
operationId: webrtcSessionsList
tags: [WebRTC]
summary: returns all WebRTC sessions.
description: ''
parameters:
@ -2141,7 +1756,6 @@ paths: @@ -2141,7 +1756,6 @@ paths:
/v3/webrtcsessions/get/{id}:
get:
operationId: webrtcSessionsGet
tags: [WebRTC]
summary: returns a WebRTC session.
description: ''
parameters:
@ -2164,12 +1778,6 @@ paths: @@ -2164,12 +1778,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: session not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
@ -2180,7 +1788,6 @@ paths: @@ -2180,7 +1788,6 @@ paths:
/v3/webrtcsessions/kick/{id}:
post:
operationId: webrtcSessionsKick
tags: [WebRTC]
summary: kicks out a WebRTC session from the server.
description: ''
parameters:
@ -2199,131 +1806,6 @@ paths: @@ -2199,131 +1806,6 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: session not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/v3/recordings/list:
get:
operationId: recordingsList
tags: [Recordings]
summary: returns all recordings.
description: ''
parameters:
- name: page
in: query
description: page number.
schema:
type: integer
default: 0
- name: itemsPerPage
in: query
description: items per page.
schema:
type: integer
default: 100
responses:
'200':
description: the request was successful.
content:
application/json:
schema:
$ref: '#/components/schemas/RecordingList'
'400':
description: invalid request.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/v3/recordings/get/{name}:
get:
operationId: recordingsGet
tags: [Recordings]
summary: returns recordings for a path.
description: ''
parameters:
- name: name
in: path
required: true
description: name of the path.
schema:
type: string
responses:
'200':
description: the request was successful.
content:
application/json:
schema:
$ref: '#/components/schemas/Recording'
'400':
description: invalid request.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: path not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
/v3/recordings/deletesegment:
delete:
operationId: recordingsDeleteSegment
tags: [Recordings]
summary: deletes a recording segment.
description: ''
parameters:
- name: path
in: query
required: true
description: path.
schema:
type: string
- name: start
in: query
required: true
description: starting date of the segment.
schema:
type: string
responses:
'200':
description: the request was successful.
'400':
description: invalid request.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'404':
description: connection not found.
content:
application/json:
schema:
$ref: '#/components/schemas/Error'
'500':
description: server error.
content:

42
go.mod

@ -4,37 +4,35 @@ go 1.21 @@ -4,37 +4,35 @@ go 1.21
require (
code.cloudfoundry.org/bytefmt v0.0.0
github.com/MicahParks/keyfunc/v3 v3.3.2
github.com/abema/go-mp4 v1.2.0
github.com/alecthomas/kong v0.9.0
github.com/bluenviron/gohlslib v1.3.0
github.com/bluenviron/gortsplib/v4 v4.8.0
github.com/bluenviron/mediacommon v1.9.2
github.com/datarhei/gosrt v0.6.0
github.com/abema/go-mp4 v1.1.1
github.com/alecthomas/kong v0.8.1
github.com/aler9/writerseeker v1.1.0
github.com/bluenviron/gohlslib v1.2.0
github.com/bluenviron/gortsplib/v4 v4.7.2-0.20240118210759-66e3d7926937
github.com/bluenviron/mediacommon v1.7.1
github.com/datarhei/gosrt v0.5.5
github.com/fsnotify/fsnotify v1.7.0
github.com/gin-gonic/gin v1.9.1
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/google/uuid v1.5.0
github.com/gookit/color v1.5.4
github.com/gorilla/websocket v1.5.1
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/matthewhartstonge/argon2 v1.0.0
github.com/notedit/rtmp v0.0.2
github.com/pion/ice/v2 v2.3.11
github.com/pion/interceptor v0.1.27
github.com/pion/interceptor v0.1.25
github.com/pion/logging v0.2.2
github.com/pion/rtcp v1.2.14
github.com/pion/rtp v1.8.5
github.com/pion/sdp/v3 v3.0.9
github.com/pion/rtcp v1.2.13
github.com/pion/rtp v1.8.3
github.com/pion/sdp/v3 v3.0.6
github.com/pion/webrtc/v3 v3.2.22
github.com/stretchr/testify v1.9.0
golang.org/x/crypto v0.22.0
golang.org/x/sys v0.19.0
golang.org/x/term v0.19.0
github.com/stretchr/testify v1.8.4
golang.org/x/crypto v0.18.0
golang.org/x/term v0.16.0
gopkg.in/yaml.v2 v2.4.0
)
require (
github.com/MicahParks/jwkset v0.5.17 // indirect
github.com/asticode/go-astikit v0.30.0 // indirect
github.com/asticode/go-astits v1.13.0 // indirect
github.com/benburkert/openpgp v0.0.0-20160410205803-c2471f86866c // indirect
@ -68,15 +66,17 @@ require ( @@ -68,15 +66,17 @@ require (
github.com/ugorji/go/codec v1.2.11 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/net v0.20.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace code.cloudfoundry.org/bytefmt => github.com/cloudfoundry/bytefmt v0.0.0-20211005130812-5bb3c17173e5
replace github.com/pion/sdp/v3 => github.com/aler9/sdp/v3 v3.0.0-20231022165400-33437e07f326
replace github.com/pion/ice/v2 => github.com/aler9/ice/v2 v2.0.0-20231112223552-32d34dfcf3a1
replace github.com/pion/webrtc/v3 => github.com/aler9/webrtc/v3 v3.0.0-20231112223655-e402ed2689c6

94
go.sum

@ -1,31 +1,35 @@ @@ -1,31 +1,35 @@
github.com/MicahParks/jwkset v0.5.17 h1:DrcwyKwSP5adD0G2XJTvDulnWXjD6gbjROMgMXDbkKA=
github.com/MicahParks/jwkset v0.5.17/go.mod h1:q8ptTGn/Z9c4MwbcfeCDssADeVQb3Pk7PnVxrvi+2QY=
github.com/MicahParks/keyfunc/v3 v3.3.2 h1:YTtwc4dxalBZKFqHhqctBWN6VhbLdGhywmne9u5RQVM=
github.com/MicahParks/keyfunc/v3 v3.3.2/go.mod h1:GJBeEjnv25OnD9y2OYQa7ELU6gYahEMBNXINZb+qm34=
github.com/abema/go-mp4 v1.2.0 h1:gi4X8xg/m179N/J15Fn5ugywN9vtI6PLk6iLldHGLAk=
github.com/abema/go-mp4 v1.2.0/go.mod h1:vPl9t5ZK7K0x68jh12/+ECWBCXoWuIDtNgPtU2f04ws=
github.com/alecthomas/assert/v2 v2.6.0 h1:o3WJwILtexrEUk3cUVal3oiQY2tfgr/FHWiz/v2n4FU=
github.com/alecthomas/assert/v2 v2.6.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
github.com/alecthomas/kong v0.9.0 h1:G5diXxc85KvoV2f0ZRVuMsi45IrBgx9zDNGNj165aPA=
github.com/alecthomas/kong v0.9.0/go.mod h1:Y47y5gKfHp1hDc7CH7OeXgLIpp+Q2m1Ni0L5s3bI8Os=
github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=
github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
github.com/abema/go-mp4 v1.1.1 h1:OfzkdMO6SWTBR1ltNSVwlTHatrAK9I3iYLQfkdEMMuc=
github.com/abema/go-mp4 v1.1.1/go.mod h1:vPl9t5ZK7K0x68jh12/+ECWBCXoWuIDtNgPtU2f04ws=
github.com/alecthomas/assert/v2 v2.1.0 h1:tbredtNcQnoSd3QBhQWI7QZ3XHOVkw1Moklp2ojoH/0=
github.com/alecthomas/assert/v2 v2.1.0/go.mod h1:b/+1DI2Q6NckYi+3mXyH3wFb8qG37K/DuK80n7WefXA=
github.com/alecthomas/kong v0.8.1 h1:acZdn3m4lLRobeh3Zi2S2EpnXTd1mOL6U7xVml+vfkY=
github.com/alecthomas/kong v0.8.1/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U=
github.com/alecthomas/repr v0.1.0 h1:ENn2e1+J3k09gyj2shc0dHr/yjaWSHRlrJ4DPMevDqE=
github.com/alecthomas/repr v0.1.0/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8=
github.com/aler9/ice/v2 v2.0.0-20231112223552-32d34dfcf3a1 h1:fD6eZt+3/t8bzFn6ZZA2eP63xBP06v3EPfPJu8DO8ys=
github.com/aler9/ice/v2 v2.0.0-20231112223552-32d34dfcf3a1/go.mod h1:lT3kv5uUIlHfXHU/ZRD7uKD/ufM202+eTa3C/umgGf4=
github.com/aler9/sdp/v3 v3.0.0-20231022165400-33437e07f326 h1:HA7u47vkcxFiHtiOjm8srh1JRgC0ZPYefPtpDCaTtS0=
github.com/aler9/sdp/v3 v3.0.0-20231022165400-33437e07f326/go.mod h1:I40uD/ZSmK2peI6AdJga5fd55d4bFK0oWOgLS9Q8sVc=
github.com/aler9/webrtc/v3 v3.0.0-20231112223655-e402ed2689c6 h1:wMd3D1mLghoYYh31STig8Kwm2qi8QyQKUy09qUUZrVw=
github.com/aler9/webrtc/v3 v3.0.0-20231112223655-e402ed2689c6/go.mod h1:1CaT2fcZzZ6VZA+O1i9yK2DU4EOcXVvSbWG9pr5jefs=
github.com/aler9/writerseeker v1.1.0 h1:t+Sm3tjp8scNlqyoa8obpeqwciMNOvdvsxjxEb3Sx3g=
github.com/aler9/writerseeker v1.1.0/go.mod h1:QNCcjSKnLsYoTfMmXkEEfgbz6nNXWxKSaBY+hGJGWDA=
github.com/asticode/go-astikit v0.30.0 h1:DkBkRQRIxYcknlaU7W7ksNfn4gMFsB0tqMJflxkRsZA=
github.com/asticode/go-astikit v0.30.0/go.mod h1:h4ly7idim1tNhaVkdVBeXQZEE3L0xblP7fCWbgwipF0=
github.com/asticode/go-astits v1.13.0 h1:XOgkaadfZODnyZRR5Y0/DWkA9vrkLLPLeeOvDwfKZ1c=
github.com/asticode/go-astits v1.13.0/go.mod h1:QSHmknZ51pf6KJdHKZHJTLlMegIrhega3LPWz3ND/iI=
github.com/benburkert/openpgp v0.0.0-20160410205803-c2471f86866c h1:8XZeJrs4+ZYhJeJ2aZxADI2tGADS15AzIF8MQ8XAhT4=
github.com/benburkert/openpgp v0.0.0-20160410205803-c2471f86866c/go.mod h1:x1vxHcL/9AVzuk5HOloOEPrtJY0MaalYr78afXZ+pWI=
github.com/bluenviron/gohlslib v1.3.0 h1:I9t1Nba6VJKg5rLoXSzQFPkZZYBUwBqCU2Divp0oU2I=
github.com/bluenviron/gohlslib v1.3.0/go.mod h1:wD8ysO6HB90d17sxoIQXGHINo2KYj/mZirMnPtKLJZQ=
github.com/bluenviron/gortsplib/v4 v4.8.0 h1:nvFp6rHALcSep3G9uBFI0uogS9stVZLNq/92TzGZdQg=
github.com/bluenviron/gortsplib/v4 v4.8.0/go.mod h1:+d+veuyvhvikUNp0GRQkk6fEbd/DtcXNidMRm7FQRaA=
github.com/bluenviron/mediacommon v1.9.2 h1:EHcvoC5YMXRcFE010bTNf07ZiSlB/e/AdZyG7GsEYN0=
github.com/bluenviron/mediacommon v1.9.2/go.mod h1:lt8V+wMyPw8C69HAqDWV5tsAwzN9u2Z+ca8B6C//+n0=
github.com/bluenviron/gohlslib v1.2.0 h1:Hrx2/n/AcmKKIV+MjZLKs5kmW+O7xCdUSPJQoS39JKw=
github.com/bluenviron/gohlslib v1.2.0/go.mod h1:kG/Sjebsxnf5asMGaGcQ0aSvtFGNChJPgctds2wDHOI=
github.com/bluenviron/gortsplib/v4 v4.6.4-0.20240108201647-63a81d0896f5 h1:DU63YvVivfcIq7jcA1KCwi9YO+jEVglYNJCIrOLj8QE=
github.com/bluenviron/gortsplib/v4 v4.6.4-0.20240108201647-63a81d0896f5/go.mod h1:UqdkRR5YvKHP/wHEQQySJFKJm6tIZcftdP7cNszIZ1g=
github.com/bluenviron/gortsplib/v4 v4.7.2-0.20240115204437-74f1bbfa3a99 h1:jdba1eZZrhk/oFXYeZBLj5Z8oqU84/4O01srr807BrY=
github.com/bluenviron/gortsplib/v4 v4.7.2-0.20240115204437-74f1bbfa3a99/go.mod h1:3+IYh85PgIPLHr4D5z7GnRvpu/ogSHMDhsYW/CjrD8E=
github.com/bluenviron/gortsplib/v4 v4.7.2-0.20240118210759-66e3d7926937 h1:I8Y0nFDyeG8d00XLKSCG594/SFC0eLLM3PEnyGXOIsU=
github.com/bluenviron/gortsplib/v4 v4.7.2-0.20240118210759-66e3d7926937/go.mod h1:3+IYh85PgIPLHr4D5z7GnRvpu/ogSHMDhsYW/CjrD8E=
github.com/bluenviron/mediacommon v1.7.1 h1:7Lm2b8M9gUk3Ben1w+OPwadAeYseIBscwgdiL+aLtfw=
github.com/bluenviron/mediacommon v1.7.1/go.mod h1:Ij/kE1LEucSjryNBVTyPL/gBI0d6/Css3f5PyrM957w=
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
@ -35,8 +39,8 @@ github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583j @@ -35,8 +39,8 @@ github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583j
github.com/cloudfoundry/bytefmt v0.0.0-20211005130812-5bb3c17173e5 h1:xB7KkA98BcUdzVcwyZxb5R0FGIHxNPHgZOzkjPEY5gM=
github.com/cloudfoundry/bytefmt v0.0.0-20211005130812-5bb3c17173e5/go.mod h1:v4VVB6oBMz/c9fRY6vZrwr5xKRWOH5NPDjQZlPk0Gbs=
github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY=
github.com/datarhei/gosrt v0.6.0 h1:HrrXAw90V78ok4WMIhX6se1aTHPCn82Sg2hj+PhdmGc=
github.com/datarhei/gosrt v0.6.0/go.mod h1:fsOWdLSHUHShHjgi/46h6wjtdQrtnSdAQFnlas8ONxs=
github.com/datarhei/gosrt v0.5.5 h1:4Xx4v7pn/rz6EaWhZRE37fROW+rry0y4yBHZBkq5d8g=
github.com/datarhei/gosrt v0.5.5/go.mod h1:In1zba2/999S1d+ENIJ0h9s3alHO3FvCNrIpykxYbEE=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -61,8 +65,6 @@ github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QX @@ -61,8 +65,6 @@ github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QX
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
@ -80,8 +82,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ @@ -80,8 +82,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
@ -113,6 +115,8 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w @@ -113,6 +115,8 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/notedit/rtmp v0.0.2 h1:5+to4yezKATiJgnrcETu9LbV5G/QsWkOV9Ts2M/p33w=
github.com/notedit/rtmp v0.0.2/go.mod h1:vzuE21rowz+lT1NGsWbreIvYulgBpCGnQyeTyFblUHc=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
@ -134,9 +138,8 @@ github.com/pion/datachannel v1.5.5 h1:10ef4kwdjije+M9d7Xm9im2Y3O6A6ccQb0zcqZcJew @@ -134,9 +138,8 @@ github.com/pion/datachannel v1.5.5 h1:10ef4kwdjije+M9d7Xm9im2Y3O6A6ccQb0zcqZcJew
github.com/pion/datachannel v1.5.5/go.mod h1:iMz+lECmfdCMqFRhXhcA/219B0SQlbpoR2V118yimL0=
github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8=
github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s=
github.com/pion/interceptor v0.1.25 h1:pwY9r7P6ToQ3+IF0bajN0xmk/fNw/suTgaTdlwTDmhc=
github.com/pion/interceptor v0.1.25/go.mod h1:wkbPYAak5zKsfpVDYMtEfWEy8D4zL+rpxCxPImLOg3Y=
github.com/pion/interceptor v0.1.27 h1:mZ01OiGiukwRxezmDGzYjjokCVlDOk4T6BfaL5qrtGo=
github.com/pion/interceptor v0.1.27/go.mod h1:/vVaqLwDjGv4GRbgmChIKZIT5EXFDijwmj4WmIYy9bI=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/mdns v0.0.7/go.mod h1:4iP2UbeFhLI/vWju/bw6ZfwjJzk0z8DNValjGxR/dD8=
@ -146,19 +149,14 @@ github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= @@ -146,19 +149,14 @@ github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.10/go.mod h1:ztfEwXZNLGyF1oQDttz/ZKIBaeeg/oWbRYqzBM9TL1I=
github.com/pion/rtcp v1.2.12/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
github.com/pion/rtcp v1.2.14 h1:KCkGV3vJ+4DAJmvP0vaQShsb0xkRfWkO540Gy102KyE=
github.com/pion/rtcp v1.2.14/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
github.com/pion/rtcp v1.2.13 h1:+EQijuisKwm/8VBs8nWllr0bIndR7Lf7cZG200mpbNo=
github.com/pion/rtcp v1.2.13/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
github.com/pion/rtp v1.8.2/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
github.com/pion/rtp v1.8.3 h1:VEHxqzSVQxCkKDSHro5/4IUUG1ea+MFdqR2R3xSpNU8=
github.com/pion/rtp v1.8.3/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
github.com/pion/rtp v1.8.4/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
github.com/pion/rtp v1.8.5 h1:uYzINfaK+9yWs7r537z/Rc1SvT8ILjBcmDOpJcTB+OU=
github.com/pion/rtp v1.8.5/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
github.com/pion/sctp v1.8.5/go.mod h1:SUFFfDpViyKejTAdwD1d/HQsCu+V/40cCs2nZIvC3s0=
github.com/pion/sctp v1.8.8 h1:5EdnnKI4gpyR1a1TwbiS/wxEgcUWBHsc7ILAjARJB+U=
github.com/pion/sctp v1.8.8/go.mod h1:igF9nZBrjh5AtmKc7U30jXltsFHicFCXSmWA2GWRaWs=
github.com/pion/sdp/v3 v3.0.6/go.mod h1:iiFWFpQO8Fy3S5ldclBkpXqmWy02ns78NOKoLLL0YQw=
github.com/pion/sdp/v3 v3.0.9 h1:pX++dCHoHUwq43kuwf3PyJfHlwIj4hXA7Vrifiq0IJY=
github.com/pion/sdp/v3 v3.0.9/go.mod h1:B5xmvENq5IXJimIO4zfp6LAe1fD9N+kFv+V/1lOdz8M=
github.com/pion/srtp/v2 v2.0.18 h1:vKpAXfawO9RtTRKZJbG4y0v1b11NZxQnxRl85kGuUlo=
github.com/pion/srtp/v2 v2.0.18/go.mod h1:0KJQjA99A6/a0DOVTu1PhDSw0CXF2jTkqOoMg3ODqdA=
github.com/pion/stun v0.6.1 h1:8lp6YejULeHBF8NmV8e2787BogQhduZugh5PdhDyyN4=
@ -181,7 +179,6 @@ github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZ @@ -181,7 +179,6 @@ github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZ
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
@ -191,9 +188,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO @@ -191,9 +188,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/sunfish-shogi/bufseekio v0.0.0-20210207115823-a4185644b365/go.mod h1:dEzdXgvImkQ3WLI+0KQpmEx8T/C/ma9KeS3AfmU899I=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
@ -214,8 +210,8 @@ golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE @@ -214,8 +210,8 @@ golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE
golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I=
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc=
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
@ -235,8 +231,10 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= @@ -235,8 +231,10 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ=
golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -268,8 +266,8 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -268,8 +266,8 @@ golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@ -280,8 +278,8 @@ golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= @@ -280,8 +278,8 @@ golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo=
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.19.0 h1:+ThwsDv+tYfnJFhF4L8jITxu1tdTWRTZpdsWgEgjL6Q=
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
golang.org/x/term v0.16.0 h1:m+B6fahuftsE9qjo0VWp2FW0mB3MTJvR0BaMQrq0pmE=
golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@ -295,8 +293,6 @@ golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= @@ -295,8 +293,6 @@ golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
@ -315,8 +311,8 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi @@ -315,8 +311,8 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=

319
internal/api/api.go

@ -3,33 +3,22 @@ package api @@ -3,33 +3,22 @@ package api
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/protocols/httpp"
"github.com/bluenviron/mediamtx/internal/record"
"github.com/bluenviron/mediamtx/internal/protocols/httpserv"
"github.com/bluenviron/mediamtx/internal/restrictnetwork"
"github.com/bluenviron/mediamtx/internal/servers/hls"
"github.com/bluenviron/mediamtx/internal/servers/rtmp"
"github.com/bluenviron/mediamtx/internal/servers/rtsp"
"github.com/bluenviron/mediamtx/internal/servers/srt"
"github.com/bluenviron/mediamtx/internal/servers/webrtc"
)
func interfaceIsEmpty(i interface{}) bool {
@ -161,7 +150,6 @@ type API struct { @@ -161,7 +150,6 @@ type API struct {
Address string
ReadTimeout conf.StringDuration
Conf *conf.Conf
AuthManager *auth.Manager
PathManager PathManager
RTSPServer RTSPServer
RTSPSServer RTSPServer
@ -172,8 +160,8 @@ type API struct { @@ -172,8 +160,8 @@ type API struct {
SRTServer SRTServer
Parent apiParent
httpServer *httpp.WrappedServer
mutex sync.RWMutex
httpServer *httpserv.WrappedServer
mutex sync.Mutex
}
// Initialize initializes API.
@ -181,7 +169,7 @@ func (a *API) Initialize() error { @@ -181,7 +169,7 @@ func (a *API) Initialize() error {
router := gin.New()
router.SetTrustedProxies(nil) //nolint:errcheck
group := router.Group("/", a.mwAuth)
group := router.Group("/")
group.GET("/v3/config/global/get", a.onConfigGlobalGet)
group.PATCH("/v3/config/global/patch", a.onConfigGlobalPatch)
@ -244,14 +232,10 @@ func (a *API) Initialize() error { @@ -244,14 +232,10 @@ func (a *API) Initialize() error {
group.POST("/v3/srtconns/kick/:id", a.onSRTConnsKick)
}
group.GET("/v3/recordings/list", a.onRecordingsList)
group.GET("/v3/recordings/get/*name", a.onRecordingsGet)
group.DELETE("/v3/recordings/deletesegment", a.onRecordingDeleteSegment)
network, address := restrictnetwork.Restrict("tcp", a.Address)
var err error
a.httpServer, err = httpp.NewWrappedServer(
a.httpServer, err = httpserv.NewWrappedServer(
network,
address,
time.Duration(a.ReadTimeout),
@ -280,44 +264,21 @@ func (a *API) Log(level logger.Level, format string, args ...interface{}) { @@ -280,44 +264,21 @@ func (a *API) Log(level logger.Level, format string, args ...interface{}) {
a.Parent.Log(level, "[API] "+format, args...)
}
// error coming from something the user inserted into the request.
func (a *API) writeError(ctx *gin.Context, status int, err error) {
// show error in logs
a.Log(logger.Error, err.Error())
// add error to response
// send error in response
ctx.JSON(status, &defs.APIError{
Error: err.Error(),
})
}
func (a *API) mwAuth(ctx *gin.Context) {
user, pass, hasCredentials := ctx.Request.BasicAuth()
err := a.AuthManager.Authenticate(&auth.Request{
User: user,
Pass: pass,
IP: net.ParseIP(ctx.ClientIP()),
Action: conf.AuthActionAPI,
})
if err != nil {
if !hasCredentials {
ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`)
ctx.AbortWithStatus(http.StatusUnauthorized)
return
}
// wait some seconds to mitigate brute force attacks
<-time.After(auth.PauseAfterError)
ctx.AbortWithStatus(http.StatusUnauthorized)
return
}
}
func (a *API) onConfigGlobalGet(ctx *gin.Context) {
a.mutex.RLock()
a.mutex.Lock()
c := a.Conf
a.mutex.RUnlock()
a.mutex.Unlock()
ctx.JSON(http.StatusOK, c.Global())
}
@ -337,7 +298,7 @@ func (a *API) onConfigGlobalPatch(ctx *gin.Context) { @@ -337,7 +298,7 @@ func (a *API) onConfigGlobalPatch(ctx *gin.Context) {
newConf.PatchGlobal(&c)
err = newConf.Validate()
err = newConf.Check()
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
@ -353,9 +314,9 @@ func (a *API) onConfigGlobalPatch(ctx *gin.Context) { @@ -353,9 +314,9 @@ func (a *API) onConfigGlobalPatch(ctx *gin.Context) {
}
func (a *API) onConfigPathDefaultsGet(ctx *gin.Context) {
a.mutex.RLock()
a.mutex.Lock()
c := a.Conf
a.mutex.RUnlock()
a.mutex.Unlock()
ctx.JSON(http.StatusOK, c.PathDefaults)
}
@ -375,7 +336,7 @@ func (a *API) onConfigPathDefaultsPatch(ctx *gin.Context) { @@ -375,7 +336,7 @@ func (a *API) onConfigPathDefaultsPatch(ctx *gin.Context) {
newConf.PatchPathDefaults(&p)
err = newConf.Validate()
err = newConf.Check()
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
@ -388,9 +349,9 @@ func (a *API) onConfigPathDefaultsPatch(ctx *gin.Context) { @@ -388,9 +349,9 @@ func (a *API) onConfigPathDefaultsPatch(ctx *gin.Context) {
}
func (a *API) onConfigPathsList(ctx *gin.Context) {
a.mutex.RLock()
a.mutex.Lock()
c := a.Conf
a.mutex.RUnlock()
a.mutex.Unlock()
data := &defs.APIPathConfList{
Items: make([]*conf.Path, len(c.Paths)),
@ -412,19 +373,19 @@ func (a *API) onConfigPathsList(ctx *gin.Context) { @@ -412,19 +373,19 @@ func (a *API) onConfigPathsList(ctx *gin.Context) {
}
func (a *API) onConfigPathsGet(ctx *gin.Context) {
confName, ok := paramName(ctx)
name, ok := paramName(ctx)
if !ok {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid name"))
return
}
a.mutex.RLock()
a.mutex.Lock()
c := a.Conf
a.mutex.RUnlock()
a.mutex.Unlock()
p, ok := c.Paths[confName]
p, ok := c.Paths[name]
if !ok {
a.writeError(ctx, http.StatusNotFound, fmt.Errorf("path configuration not found"))
a.writeError(ctx, http.StatusInternalServerError, fmt.Errorf("path configuration not found"))
return
}
@ -432,7 +393,7 @@ func (a *API) onConfigPathsGet(ctx *gin.Context) { @@ -432,7 +393,7 @@ func (a *API) onConfigPathsGet(ctx *gin.Context) {
}
func (a *API) onConfigPathsAdd(ctx *gin.Context) { //nolint:dupl
confName, ok := paramName(ctx)
name, ok := paramName(ctx)
if !ok {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid name"))
return
@ -450,13 +411,13 @@ func (a *API) onConfigPathsAdd(ctx *gin.Context) { //nolint:dupl @@ -450,13 +411,13 @@ func (a *API) onConfigPathsAdd(ctx *gin.Context) { //nolint:dupl
newConf := a.Conf.Clone()
err = newConf.AddPath(confName, &p)
err = newConf.AddPath(name, &p)
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
}
err = newConf.Validate()
err = newConf.Check()
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
@ -469,7 +430,7 @@ func (a *API) onConfigPathsAdd(ctx *gin.Context) { //nolint:dupl @@ -469,7 +430,7 @@ func (a *API) onConfigPathsAdd(ctx *gin.Context) { //nolint:dupl
}
func (a *API) onConfigPathsPatch(ctx *gin.Context) { //nolint:dupl
confName, ok := paramName(ctx)
name, ok := paramName(ctx)
if !ok {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid name"))
return
@ -487,17 +448,13 @@ func (a *API) onConfigPathsPatch(ctx *gin.Context) { //nolint:dupl @@ -487,17 +448,13 @@ func (a *API) onConfigPathsPatch(ctx *gin.Context) { //nolint:dupl
newConf := a.Conf.Clone()
err = newConf.PatchPath(confName, &p)
err = newConf.PatchPath(name, &p)
if err != nil {
if errors.Is(err, conf.ErrPathNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusBadRequest, err)
}
a.writeError(ctx, http.StatusBadRequest, err)
return
}
err = newConf.Validate()
err = newConf.Check()
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
@ -510,7 +467,7 @@ func (a *API) onConfigPathsPatch(ctx *gin.Context) { //nolint:dupl @@ -510,7 +467,7 @@ func (a *API) onConfigPathsPatch(ctx *gin.Context) { //nolint:dupl
}
func (a *API) onConfigPathsReplace(ctx *gin.Context) { //nolint:dupl
confName, ok := paramName(ctx)
name, ok := paramName(ctx)
if !ok {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid name"))
return
@ -528,17 +485,13 @@ func (a *API) onConfigPathsReplace(ctx *gin.Context) { //nolint:dupl @@ -528,17 +485,13 @@ func (a *API) onConfigPathsReplace(ctx *gin.Context) { //nolint:dupl
newConf := a.Conf.Clone()
err = newConf.ReplacePath(confName, &p)
err = newConf.ReplacePath(name, &p)
if err != nil {
if errors.Is(err, conf.ErrPathNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusBadRequest, err)
}
a.writeError(ctx, http.StatusBadRequest, err)
return
}
err = newConf.Validate()
err = newConf.Check()
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
@ -551,7 +504,7 @@ func (a *API) onConfigPathsReplace(ctx *gin.Context) { //nolint:dupl @@ -551,7 +504,7 @@ func (a *API) onConfigPathsReplace(ctx *gin.Context) { //nolint:dupl
}
func (a *API) onConfigPathsDelete(ctx *gin.Context) {
confName, ok := paramName(ctx)
name, ok := paramName(ctx)
if !ok {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid name"))
return
@ -562,17 +515,13 @@ func (a *API) onConfigPathsDelete(ctx *gin.Context) { @@ -562,17 +515,13 @@ func (a *API) onConfigPathsDelete(ctx *gin.Context) {
newConf := a.Conf.Clone()
err := newConf.RemovePath(confName)
err := newConf.RemovePath(name)
if err != nil {
if errors.Is(err, conf.ErrPathNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusBadRequest, err)
}
a.writeError(ctx, http.StatusBadRequest, err)
return
}
err = newConf.Validate()
err = newConf.Check()
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
@ -603,19 +552,15 @@ func (a *API) onPathsList(ctx *gin.Context) { @@ -603,19 +552,15 @@ func (a *API) onPathsList(ctx *gin.Context) {
}
func (a *API) onPathsGet(ctx *gin.Context) {
pathName, ok := paramName(ctx)
name, ok := paramName(ctx)
if !ok {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid name"))
return
}
data, err := a.PathManager.APIPathsGet(pathName)
data, err := a.PathManager.APIPathsGet(name)
if err != nil {
if errors.Is(err, conf.ErrPathNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -649,11 +594,7 @@ func (a *API) onRTSPConnsGet(ctx *gin.Context) { @@ -649,11 +594,7 @@ func (a *API) onRTSPConnsGet(ctx *gin.Context) {
data, err := a.RTSPServer.APIConnsGet(uuid)
if err != nil {
if errors.Is(err, rtsp.ErrConnNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -687,11 +628,7 @@ func (a *API) onRTSPSessionsGet(ctx *gin.Context) { @@ -687,11 +628,7 @@ func (a *API) onRTSPSessionsGet(ctx *gin.Context) {
data, err := a.RTSPServer.APISessionsGet(uuid)
if err != nil {
if errors.Is(err, rtsp.ErrSessionNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -707,11 +644,7 @@ func (a *API) onRTSPSessionsKick(ctx *gin.Context) { @@ -707,11 +644,7 @@ func (a *API) onRTSPSessionsKick(ctx *gin.Context) {
err = a.RTSPServer.APISessionsKick(uuid)
if err != nil {
if errors.Is(err, rtsp.ErrSessionNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -745,11 +678,7 @@ func (a *API) onRTSPSConnsGet(ctx *gin.Context) { @@ -745,11 +678,7 @@ func (a *API) onRTSPSConnsGet(ctx *gin.Context) {
data, err := a.RTSPSServer.APIConnsGet(uuid)
if err != nil {
if errors.Is(err, rtsp.ErrConnNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -783,11 +712,7 @@ func (a *API) onRTSPSSessionsGet(ctx *gin.Context) { @@ -783,11 +712,7 @@ func (a *API) onRTSPSSessionsGet(ctx *gin.Context) {
data, err := a.RTSPSServer.APISessionsGet(uuid)
if err != nil {
if errors.Is(err, rtsp.ErrSessionNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -803,11 +728,7 @@ func (a *API) onRTSPSSessionsKick(ctx *gin.Context) { @@ -803,11 +728,7 @@ func (a *API) onRTSPSSessionsKick(ctx *gin.Context) {
err = a.RTSPSServer.APISessionsKick(uuid)
if err != nil {
if errors.Is(err, rtsp.ErrSessionNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -841,11 +762,7 @@ func (a *API) onRTMPConnsGet(ctx *gin.Context) { @@ -841,11 +762,7 @@ func (a *API) onRTMPConnsGet(ctx *gin.Context) {
data, err := a.RTMPServer.APIConnsGet(uuid)
if err != nil {
if errors.Is(err, rtmp.ErrConnNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -861,11 +778,7 @@ func (a *API) onRTMPConnsKick(ctx *gin.Context) { @@ -861,11 +778,7 @@ func (a *API) onRTMPConnsKick(ctx *gin.Context) {
err = a.RTMPServer.APIConnsKick(uuid)
if err != nil {
if errors.Is(err, rtmp.ErrConnNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -899,11 +812,7 @@ func (a *API) onRTMPSConnsGet(ctx *gin.Context) { @@ -899,11 +812,7 @@ func (a *API) onRTMPSConnsGet(ctx *gin.Context) {
data, err := a.RTMPSServer.APIConnsGet(uuid)
if err != nil {
if errors.Is(err, rtmp.ErrConnNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -919,11 +828,7 @@ func (a *API) onRTMPSConnsKick(ctx *gin.Context) { @@ -919,11 +828,7 @@ func (a *API) onRTMPSConnsKick(ctx *gin.Context) {
err = a.RTMPSServer.APIConnsKick(uuid)
if err != nil {
if errors.Is(err, rtmp.ErrConnNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -949,19 +854,15 @@ func (a *API) onHLSMuxersList(ctx *gin.Context) { @@ -949,19 +854,15 @@ func (a *API) onHLSMuxersList(ctx *gin.Context) {
}
func (a *API) onHLSMuxersGet(ctx *gin.Context) {
pathName, ok := paramName(ctx)
name, ok := paramName(ctx)
if !ok {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid name"))
return
}
data, err := a.HLSServer.APIMuxersGet(pathName)
data, err := a.HLSServer.APIMuxersGet(name)
if err != nil {
if errors.Is(err, hls.ErrMuxerNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -995,11 +896,7 @@ func (a *API) onWebRTCSessionsGet(ctx *gin.Context) { @@ -995,11 +896,7 @@ func (a *API) onWebRTCSessionsGet(ctx *gin.Context) {
data, err := a.WebRTCServer.APISessionsGet(uuid)
if err != nil {
if errors.Is(err, webrtc.ErrSessionNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -1015,11 +912,7 @@ func (a *API) onWebRTCSessionsKick(ctx *gin.Context) { @@ -1015,11 +912,7 @@ func (a *API) onWebRTCSessionsKick(ctx *gin.Context) {
err = a.WebRTCServer.APISessionsKick(uuid)
if err != nil {
if errors.Is(err, webrtc.ErrSessionNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -1053,11 +946,7 @@ func (a *API) onSRTConnsGet(ctx *gin.Context) { @@ -1053,11 +946,7 @@ func (a *API) onSRTConnsGet(ctx *gin.Context) {
data, err := a.SRTServer.APIConnsGet(uuid)
if err != nil {
if errors.Is(err, srt.ErrConnNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
a.writeError(ctx, http.StatusInternalServerError, err)
return
}
@ -1073,105 +962,7 @@ func (a *API) onSRTConnsKick(ctx *gin.Context) { @@ -1073,105 +962,7 @@ func (a *API) onSRTConnsKick(ctx *gin.Context) {
err = a.SRTServer.APIConnsKick(uuid)
if err != nil {
if errors.Is(err, srt.ErrConnNotFound) {
a.writeError(ctx, http.StatusNotFound, err)
} else {
a.writeError(ctx, http.StatusInternalServerError, err)
}
return
}
ctx.Status(http.StatusOK)
}
func (a *API) onRecordingsList(ctx *gin.Context) {
a.mutex.RLock()
c := a.Conf
a.mutex.RUnlock()
pathNames := getAllPathsWithRecordings(c.Paths)
data := defs.APIRecordingList{}
data.ItemCount = len(pathNames)
pageCount, err := paginate(&pathNames, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
}
data.PageCount = pageCount
data.Items = make([]*defs.APIRecording, len(pathNames))
for i, pathName := range pathNames {
_, pathConf, _, _ := conf.FindPathConf(c.Paths, pathName)
data.Items[i] = recordingEntry(pathConf, pathName)
}
ctx.JSON(http.StatusOK, data)
}
func (a *API) onRecordingsGet(ctx *gin.Context) {
pathName, ok := paramName(ctx)
if !ok {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid name"))
return
}
a.mutex.RLock()
c := a.Conf
a.mutex.RUnlock()
_, pathConf, _, err := conf.FindPathConf(c.Paths, pathName)
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
}
if !pathConf.Playback {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("playback is disabled on path '%s'", pathName))
return
}
ctx.JSON(http.StatusOK, recordingEntry(pathConf, pathName))
}
func (a *API) onRecordingDeleteSegment(ctx *gin.Context) {
pathName := ctx.Query("path")
start, err := time.Parse(time.RFC3339, ctx.Query("start"))
if err != nil {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid 'start' parameter: %w", err))
return
}
a.mutex.RLock()
c := a.Conf
a.mutex.RUnlock()
_, pathConf, _, err := conf.FindPathConf(c.Paths, pathName)
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
return
}
if !pathConf.Playback {
a.writeError(ctx, http.StatusBadRequest, fmt.Errorf("playback is disabled on path '%s'", pathName))
return
}
pathFormat := record.PathAddExtension(
strings.ReplaceAll(pathConf.RecordPath, "%path", pathName),
pathConf.RecordFormat,
)
segmentPath := record.Path{
Start: start,
}.Encode(pathFormat)
err = os.Remove(segmentPath)
if err != nil {
a.writeError(ctx, http.StatusBadRequest, err)
a.writeError(ctx, http.StatusInternalServerError, err)
return
}

662
internal/api/api_test.go

@ -1,79 +1,11 @@ @@ -1,79 +1,11 @@
package api
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require"
)
type testParent struct{}
func (testParent) Log(_ logger.Level, _ string, _ ...interface{}) {
}
func (testParent) APIConfigSet(_ *conf.Conf) {}
func tempConf(t *testing.T, cnt string) *conf.Conf {
fi, err := test.CreateTempFile([]byte(cnt))
require.NoError(t, err)
defer os.Remove(fi)
cnf, _, err := conf.Load(fi, nil)
require.NoError(t, err)
return cnf
}
func httpRequest(t *testing.T, hc *http.Client, method string, ur string, in interface{}, out interface{}) {
buf := func() io.Reader {
if in == nil {
return nil
}
byts, err := json.Marshal(in)
require.NoError(t, err)
return bytes.NewBuffer(byts)
}()
req, err := http.NewRequest(method, ur, buf)
require.NoError(t, err)
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("bad status code: %d", res.StatusCode)
}
if out == nil {
return
}
err = json.NewDecoder(res.Body).Decode(out)
require.NoError(t, err)
}
func checkError(t *testing.T, msg string, body io.Reader) {
var resErr map[string]interface{}
err := json.NewDecoder(body).Decode(&resErr)
require.NoError(t, err)
require.Equal(t, map[string]interface{}{"error": msg}, resErr)
}
func TestPaginate(t *testing.T) {
items := make([]int, 5)
for i := 0; i < 5; i++ {
@ -105,597 +37,3 @@ func TestPaginate(t *testing.T) { @@ -105,597 +37,3 @@ func TestPaginate(t *testing.T) {
require.Equal(t, 2, pageCount)
require.Equal(t, []int{4, 5}, items)
}
var authManager = &auth.Manager{
Method: conf.AuthMethodInternal,
InternalUsers: []conf.AuthInternalUser{
{
User: "myuser",
Pass: "mypass",
Permissions: []conf.AuthInternalUserPermission{
{
Action: conf.AuthActionAPI,
},
},
},
},
RTSPAuthMethods: nil,
}
func TestConfigGlobalGet(t *testing.T) {
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out map[string]interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/global/get", nil, &out)
require.Equal(t, true, out["api"])
}
func TestConfigGlobalPatch(t *testing.T) {
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
httpRequest(t, hc, http.MethodPatch, "http://myuser:mypass@localhost:9997/v3/config/global/patch",
map[string]interface{}{
"rtmp": false,
"readTimeout": "7s",
"protocols": []string{"tcp"},
"readBufferCount": 4096, // test setting a deprecated parameter
}, nil)
time.Sleep(500 * time.Millisecond)
var out map[string]interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/global/get", nil, &out)
require.Equal(t, false, out["rtmp"])
require.Equal(t, "7s", out["readTimeout"])
require.Equal(t, []interface{}{"tcp"}, out["protocols"])
require.Equal(t, float64(4096), out["readBufferCount"])
}
func TestAPIConfigGlobalPatchUnknownField(t *testing.T) { //nolint:dupl
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
b := map[string]interface{}{
"test": "asd",
}
byts, err := json.Marshal(b)
require.NoError(t, err)
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
req, err := http.NewRequest(http.MethodPatch, "http://myuser:mypass@localhost:9997/v3/config/global/patch",
bytes.NewReader(byts))
require.NoError(t, err)
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusBadRequest, res.StatusCode)
checkError(t, "json: unknown field \"test\"", res.Body)
}
func TestAPIConfigPathDefaultsGet(t *testing.T) {
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out map[string]interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/pathdefaults/get", nil, &out)
require.Equal(t, "publisher", out["source"])
}
func TestAPIConfigPathDefaultsPatch(t *testing.T) {
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
httpRequest(t, hc, http.MethodPatch, "http://myuser:mypass@localhost:9997/v3/config/pathdefaults/patch",
map[string]interface{}{
"readUser": "myuser",
"readPass": "mypass",
}, nil)
time.Sleep(500 * time.Millisecond)
var out map[string]interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/pathdefaults/get", nil, &out)
require.Equal(t, "myuser", out["readUser"])
require.Equal(t, "mypass", out["readPass"])
}
func TestAPIConfigPathsList(t *testing.T) {
cnf := tempConf(t, "api: yes\n"+
"paths:\n"+
" path1:\n"+
" readUser: myuser1\n"+
" readPass: mypass1\n"+
" path2:\n"+
" readUser: myuser2\n"+
" readPass: mypass2\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
type pathConfig map[string]interface{}
type listRes struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []pathConfig `json:"items"`
}
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out listRes
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/paths/list", nil, &out)
require.Equal(t, 2, out.ItemCount)
require.Equal(t, 1, out.PageCount)
require.Equal(t, "path1", out.Items[0]["name"])
require.Equal(t, "myuser1", out.Items[0]["readUser"])
require.Equal(t, "mypass1", out.Items[0]["readPass"])
require.Equal(t, "path2", out.Items[1]["name"])
require.Equal(t, "myuser2", out.Items[1]["readUser"])
require.Equal(t, "mypass2", out.Items[1]["readPass"])
}
func TestAPIConfigPathsGet(t *testing.T) {
cnf := tempConf(t, "api: yes\n"+
"paths:\n"+
" my/path:\n"+
" readUser: myuser\n"+
" readPass: mypass\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out map[string]interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/paths/get/my/path", nil, &out)
require.Equal(t, "my/path", out["name"])
require.Equal(t, "myuser", out["readUser"])
}
func TestAPIConfigPathsAdd(t *testing.T) {
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
httpRequest(t, hc, http.MethodPost, "http://myuser:mypass@localhost:9997/v3/config/paths/add/my/path",
map[string]interface{}{
"source": "rtsp://127.0.0.1:9999/mypath",
"sourceOnDemand": true,
"disablePublisherOverride": true, // test setting a deprecated parameter
"rpiCameraVFlip": true,
}, nil)
var out map[string]interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/paths/get/my/path", nil, &out)
require.Equal(t, "rtsp://127.0.0.1:9999/mypath", out["source"])
require.Equal(t, true, out["sourceOnDemand"])
require.Equal(t, true, out["disablePublisherOverride"])
require.Equal(t, true, out["rpiCameraVFlip"])
}
func TestAPIConfigPathsAddUnknownField(t *testing.T) { //nolint:dupl
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
b := map[string]interface{}{
"test": "asd",
}
byts, err := json.Marshal(b)
require.NoError(t, err)
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
req, err := http.NewRequest(http.MethodPost,
"http://myuser:mypass@localhost:9997/v3/config/paths/add/my/path", bytes.NewReader(byts))
require.NoError(t, err)
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusBadRequest, res.StatusCode)
checkError(t, "json: unknown field \"test\"", res.Body)
}
func TestAPIConfigPathsPatch(t *testing.T) { //nolint:dupl
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
httpRequest(t, hc, http.MethodPost, "http://myuser:mypass@localhost:9997/v3/config/paths/add/my/path",
map[string]interface{}{
"source": "rtsp://127.0.0.1:9999/mypath",
"sourceOnDemand": true,
"disablePublisherOverride": true, // test setting a deprecated parameter
"rpiCameraVFlip": true,
}, nil)
httpRequest(t, hc, http.MethodPatch, "http://myuser:mypass@localhost:9997/v3/config/paths/patch/my/path",
map[string]interface{}{
"source": "rtsp://127.0.0.1:9998/mypath",
"sourceOnDemand": true,
}, nil)
var out map[string]interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/paths/get/my/path", nil, &out)
require.Equal(t, "rtsp://127.0.0.1:9998/mypath", out["source"])
require.Equal(t, true, out["sourceOnDemand"])
require.Equal(t, true, out["disablePublisherOverride"])
require.Equal(t, true, out["rpiCameraVFlip"])
}
func TestAPIConfigPathsReplace(t *testing.T) { //nolint:dupl
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
httpRequest(t, hc, http.MethodPost, "http://myuser:mypass@localhost:9997/v3/config/paths/add/my/path",
map[string]interface{}{
"source": "rtsp://127.0.0.1:9999/mypath",
"sourceOnDemand": true,
"disablePublisherOverride": true, // test setting a deprecated parameter
"rpiCameraVFlip": true,
}, nil)
httpRequest(t, hc, http.MethodPost, "http://myuser:mypass@localhost:9997/v3/config/paths/replace/my/path",
map[string]interface{}{
"source": "rtsp://127.0.0.1:9998/mypath",
"sourceOnDemand": true,
}, nil)
var out map[string]interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/paths/get/my/path", nil, &out)
require.Equal(t, "rtsp://127.0.0.1:9998/mypath", out["source"])
require.Equal(t, true, out["sourceOnDemand"])
require.Equal(t, nil, out["disablePublisherOverride"])
require.Equal(t, false, out["rpiCameraVFlip"])
}
func TestAPIConfigPathsDelete(t *testing.T) {
cnf := tempConf(t, "api: yes\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err := api.Initialize()
require.NoError(t, err)
defer api.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
httpRequest(t, hc, http.MethodPost, "http://myuser:mypass@localhost:9997/v3/config/paths/add/my/path",
map[string]interface{}{
"source": "rtsp://127.0.0.1:9999/mypath",
"sourceOnDemand": true,
}, nil)
httpRequest(t, hc, http.MethodDelete, "http://myuser:mypass@localhost:9997/v3/config/paths/delete/my/path", nil, nil)
req, err := http.NewRequest(http.MethodGet, "http://myuser:mypass@localhost:9997/v3/config/paths/get/my/path", nil)
require.NoError(t, err)
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusNotFound, res.StatusCode)
checkError(t, "path configuration not found", res.Body)
}
func TestRecordingsList(t *testing.T) {
dir, err := os.MkdirTemp("", "mediamtx-playback")
require.NoError(t, err)
defer os.RemoveAll(dir)
cnf := tempConf(t, "pathDefaults:\n"+
" recordPath: "+filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f")+"\n"+
"paths:\n"+
" all_others:\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err = api.Initialize()
require.NoError(t, err)
defer api.Close()
err = os.Mkdir(filepath.Join(dir, "mypath1"), 0o755)
require.NoError(t, err)
err = os.Mkdir(filepath.Join(dir, "mypath2"), 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(dir, "mypath1", "2008-11-07_11-22-00-500000.mp4"), []byte(""), 0o644)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(dir, "mypath1", "2009-11-07_11-22-00-900000.mp4"), []byte(""), 0o644)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(dir, "mypath2", "2009-11-07_11-22-00-900000.mp4"), []byte(""), 0o644)
require.NoError(t, err)
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/recordings/list", nil, &out)
require.Equal(t, map[string]interface{}{
"itemCount": float64(2),
"pageCount": float64(1),
"items": []interface{}{
map[string]interface{}{
"name": "mypath1",
"segments": []interface{}{
map[string]interface{}{
"start": time.Date(2008, 11, 0o7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano),
},
map[string]interface{}{
"start": time.Date(2009, 11, 0o7, 11, 22, 0, 900000000, time.Local).Format(time.RFC3339Nano),
},
},
},
map[string]interface{}{
"name": "mypath2",
"segments": []interface{}{
map[string]interface{}{
"start": time.Date(2009, 11, 0o7, 11, 22, 0, 900000000, time.Local).Format(time.RFC3339Nano),
},
},
},
},
}, out)
}
func TestRecordingsGet(t *testing.T) {
dir, err := os.MkdirTemp("", "mediamtx-playback")
require.NoError(t, err)
defer os.RemoveAll(dir)
cnf := tempConf(t, "pathDefaults:\n"+
" recordPath: "+filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f")+"\n"+
"paths:\n"+
" all_others:\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err = api.Initialize()
require.NoError(t, err)
defer api.Close()
err = os.Mkdir(filepath.Join(dir, "mypath1"), 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(dir, "mypath1", "2008-11-07_11-22-00-000000.mp4"), []byte(""), 0o644)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(dir, "mypath1", "2009-11-07_11-22-00-900000.mp4"), []byte(""), 0o644)
require.NoError(t, err)
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
var out interface{}
httpRequest(t, hc, http.MethodGet, "http://myuser:mypass@localhost:9997/v3/recordings/get/mypath1", nil, &out)
require.Equal(t, map[string]interface{}{
"name": "mypath1",
"segments": []interface{}{
map[string]interface{}{
"start": time.Date(2008, 11, 0o7, 11, 22, 0, 0, time.Local).Format(time.RFC3339Nano),
},
map[string]interface{}{
"start": time.Date(2009, 11, 0o7, 11, 22, 0, 900000000, time.Local).Format(time.RFC3339Nano),
},
},
}, out)
}
func TestRecordingsDeleteSegment(t *testing.T) {
dir, err := os.MkdirTemp("", "mediamtx-playback")
require.NoError(t, err)
defer os.RemoveAll(dir)
cnf := tempConf(t, "pathDefaults:\n"+
" recordPath: "+filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f")+"\n"+
"paths:\n"+
" all_others:\n")
api := API{
Address: "localhost:9997",
ReadTimeout: conf.StringDuration(10 * time.Second),
Conf: cnf,
AuthManager: authManager,
Parent: &testParent{},
}
err = api.Initialize()
require.NoError(t, err)
defer api.Close()
err = os.Mkdir(filepath.Join(dir, "mypath1"), 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(dir, "mypath1", "2008-11-07_11-22-00-900000.mp4"), []byte(""), 0o644)
require.NoError(t, err)
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
u, err := url.Parse("http://myuser:mypass@localhost:9997/v3/recordings/deletesegment")
require.NoError(t, err)
v := url.Values{}
v.Set("path", "mypath1")
v.Set("start", time.Date(2008, 11, 0o7, 11, 22, 0, 900000000, time.Local).Format(time.RFC3339Nano))
u.RawQuery = v.Encode()
req, err := http.NewRequest(http.MethodDelete, u.String(), nil)
require.NoError(t, err)
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
}

139
internal/api/record.go

@ -1,139 +0,0 @@ @@ -1,139 +0,0 @@
package api
import (
"errors"
"io/fs"
"path/filepath"
"sort"
"strings"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/playback"
"github.com/bluenviron/mediamtx/internal/record"
)
var errFound = errors.New("found")
func fixedPathHasRecordings(pathConf *conf.Path) bool {
recordPath := record.PathAddExtension(
strings.ReplaceAll(pathConf.RecordPath, "%path", pathConf.Name),
pathConf.RecordFormat,
)
// we have to convert to absolute paths
// otherwise, recordPath and fpath inside Walk() won't have common elements
recordPath, _ = filepath.Abs(recordPath)
commonPath := record.CommonPath(recordPath)
err := filepath.Walk(commonPath, func(fpath string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
var pa record.Path
ok := pa.Decode(recordPath, fpath)
if ok {
return errFound
}
}
return nil
})
if err != nil && !errors.Is(err, errFound) {
return false
}
return errors.Is(err, errFound)
}
func regexpPathGetRecordings(pathConf *conf.Path) []string {
recordPath := record.PathAddExtension(
pathConf.RecordPath,
pathConf.RecordFormat,
)
// we have to convert to absolute paths
// otherwise, recordPath and fpath inside Walk() won't have common elements
recordPath, _ = filepath.Abs(recordPath)
commonPath := record.CommonPath(recordPath)
var ret []string
filepath.Walk(commonPath, func(fpath string, info fs.FileInfo, err error) error { //nolint:errcheck
if err != nil {
return err
}
if !info.IsDir() {
var pa record.Path
ok := pa.Decode(recordPath, fpath)
if ok && pathConf.Regexp.FindStringSubmatch(pa.Path) != nil {
ret = append(ret, pa.Path)
}
}
return nil
})
return ret
}
func removeDuplicatesAndSort(in []string) []string {
ma := make(map[string]struct{}, len(in))
for _, i := range in {
ma[i] = struct{}{}
}
out := []string{}
for k := range ma {
out = append(out, k)
}
sort.Strings(out)
return out
}
func getAllPathsWithRecordings(paths map[string]*conf.Path) []string {
pathNames := []string{}
for _, pathConf := range paths {
if pathConf.Playback {
if pathConf.Regexp == nil {
if fixedPathHasRecordings(pathConf) {
pathNames = append(pathNames, pathConf.Name)
}
} else {
pathNames = append(pathNames, regexpPathGetRecordings(pathConf)...)
}
}
}
return removeDuplicatesAndSort(pathNames)
}
func recordingEntry(
pathConf *conf.Path,
pathName string,
) *defs.APIRecording {
ret := &defs.APIRecording{
Name: pathName,
}
segments, _ := playback.FindSegments(pathConf, pathName)
ret.Segments = make([]*defs.APIRecordingSegment, len(segments))
for i, seg := range segments {
ret.Segments[i] = &defs.APIRecordingSegment{
Start: seg.Start,
}
}
return ret
}

1
internal/asyncwriter/async_writer.go

@ -50,7 +50,6 @@ func (w *Writer) Error() chan error { @@ -50,7 +50,6 @@ func (w *Writer) Error() chan error {
func (w *Writer) run() {
w.err <- w.runInner()
close(w.err)
}
func (w *Writer) runInner() error {

22
internal/asyncwriter/async_writer_test.go

@ -1,22 +0,0 @@ @@ -1,22 +0,0 @@
package asyncwriter
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestAsyncWriter(t *testing.T) {
w := New(512, nil)
w.Start()
defer w.Stop()
w.Push(func() error {
return fmt.Errorf("testerror")
})
err := <-w.Error()
require.EqualError(t, err, "testerror")
}

327
internal/auth/manager.go

@ -1,327 +0,0 @@ @@ -1,327 +0,0 @@
// Package auth contains the authentication system.
package auth
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
"github.com/MicahParks/keyfunc/v3"
"github.com/bluenviron/gortsplib/v4/pkg/auth"
"github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v4/pkg/headers"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
)
const (
// PauseAfterError is the pause to apply after an authentication failure.
PauseAfterError = 2 * time.Second
rtspAuthRealm = "IPCAM"
jwtRefreshPeriod = 60 * 60 * time.Second
)
// Protocol is a protocol.
type Protocol string
// protocols.
const (
ProtocolRTSP Protocol = "rtsp"
ProtocolRTMP Protocol = "rtmp"
ProtocolHLS Protocol = "hls"
ProtocolWebRTC Protocol = "webrtc"
ProtocolSRT Protocol = "srt"
)
// Request is an authentication request.
type Request struct {
User string
Pass string
IP net.IP
Action conf.AuthAction
// only for ActionPublish, ActionRead, ActionPlayback
Path string
Protocol Protocol
ID *uuid.UUID
Query string
RTSPRequest *base.Request
RTSPBaseURL *base.URL
RTSPNonce string
}
// Error is a authentication error.
type Error struct {
Message string
}
// Error implements the error interface.
func (e Error) Error() string {
return "authentication failed: " + e.Message
}
func matchesPermission(perms []conf.AuthInternalUserPermission, req *Request) bool {
for _, perm := range perms {
if perm.Action == req.Action {
if perm.Action == conf.AuthActionPublish ||
perm.Action == conf.AuthActionRead ||
perm.Action == conf.AuthActionPlayback {
switch {
case perm.Path == "":
return true
case strings.HasPrefix(perm.Path, "~"):
regexp, err := regexp.Compile(perm.Path[1:])
if err == nil && regexp.MatchString(req.Path) {
return true
}
case perm.Path == req.Path:
return true
}
} else {
return true
}
}
}
return false
}
type customClaims struct {
jwt.RegisteredClaims
MediaMTXPermissions []conf.AuthInternalUserPermission `json:"mediamtx_permissions"`
}
// Manager is the authentication manager.
type Manager struct {
Method conf.AuthMethod
InternalUsers []conf.AuthInternalUser
HTTPAddress string
HTTPExclude []conf.AuthInternalUserPermission
JWTJWKS string
ReadTimeout time.Duration
RTSPAuthMethods []headers.AuthMethod
mutex sync.RWMutex
jwtHTTPClient *http.Client
jwtLastRefresh time.Time
jwtKeyFunc keyfunc.Keyfunc
}
// ReloadInternalUsers reloads InternalUsers.
func (m *Manager) ReloadInternalUsers(u []conf.AuthInternalUser) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.InternalUsers = u
}
// Authenticate authenticates a request.
func (m *Manager) Authenticate(req *Request) error {
err := m.authenticateInner(req)
if err != nil {
return Error{Message: err.Error()}
}
return nil
}
func (m *Manager) authenticateInner(req *Request) error {
// if this is a RTSP request, fill username and password
var rtspAuthHeader headers.Authorization
if req.RTSPRequest != nil {
err := rtspAuthHeader.Unmarshal(req.RTSPRequest.Header["Authorization"])
if err == nil {
switch rtspAuthHeader.Method {
case headers.AuthBasic:
req.User = rtspAuthHeader.BasicUser
req.Pass = rtspAuthHeader.BasicPass
case headers.AuthDigestMD5:
req.User = rtspAuthHeader.Username
default:
return fmt.Errorf("unsupported RTSP authentication method")
}
}
}
switch m.Method {
case conf.AuthMethodInternal:
return m.authenticateInternal(req, &rtspAuthHeader)
case conf.AuthMethodHTTP:
return m.authenticateHTTP(req)
default:
return m.authenticateJWT(req)
}
}
func (m *Manager) authenticateInternal(req *Request, rtspAuthHeader *headers.Authorization) error {
m.mutex.RLock()
defer m.mutex.RUnlock()
for _, u := range m.InternalUsers {
if err := m.authenticateWithUser(req, rtspAuthHeader, &u); err == nil {
return nil
}
}
return fmt.Errorf("authentication failed")
}
func (m *Manager) authenticateWithUser(
req *Request,
rtspAuthHeader *headers.Authorization,
u *conf.AuthInternalUser,
) error {
if u.User != "any" && !u.User.Check(req.User) {
return fmt.Errorf("wrong user")
}
if len(u.IPs) != 0 && !u.IPs.Contains(req.IP) {
return fmt.Errorf("IP not allowed")
}
if !matchesPermission(u.Permissions, req) {
return fmt.Errorf("user doesn't have permission to perform action")
}
if u.User != "any" {
if req.RTSPRequest != nil && rtspAuthHeader.Method == headers.AuthDigestMD5 {
err := auth.Validate(
req.RTSPRequest,
string(u.User),
string(u.Pass),
req.RTSPBaseURL,
m.RTSPAuthMethods,
rtspAuthRealm,
req.RTSPNonce)
if err != nil {
return err
}
} else if !u.Pass.Check(req.Pass) {
return fmt.Errorf("invalid credentials")
}
}
return nil
}
func (m *Manager) authenticateHTTP(req *Request) error {
if matchesPermission(m.HTTPExclude, req) {
return nil
}
enc, _ := json.Marshal(struct {
IP string `json:"ip"`
User string `json:"user"`
Password string `json:"password"`
Action string `json:"action"`
Path string `json:"path"`
Protocol string `json:"protocol"`
ID *uuid.UUID `json:"id"`
Query string `json:"query"`
}{
IP: req.IP.String(),
User: req.User,
Password: req.Pass,
Action: string(req.Action),
Path: req.Path,
Protocol: string(req.Protocol),
ID: req.ID,
Query: req.Query,
})
res, err := http.Post(m.HTTPAddress, "application/json", bytes.NewReader(enc))
if err != nil {
return fmt.Errorf("HTTP request failed: %w", err)
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode > 299 {
if resBody, err := io.ReadAll(res.Body); err == nil && len(resBody) != 0 {
return fmt.Errorf("server replied with code %d: %s", res.StatusCode, string(resBody))
}
return fmt.Errorf("server replied with code %d", res.StatusCode)
}
return nil
}
func (m *Manager) authenticateJWT(req *Request) error {
keyfunc, err := m.pullJWTJWKS()
if err != nil {
return err
}
v, err := url.ParseQuery(req.Query)
if err != nil {
return err
}
if len(v["jwt"]) != 1 {
return fmt.Errorf("JWT not provided")
}
var customClaims customClaims
_, err = jwt.ParseWithClaims(v["jwt"][0], &customClaims, keyfunc)
if err != nil {
return err
}
if !matchesPermission(customClaims.MediaMTXPermissions, req) {
return fmt.Errorf("user doesn't have permission to perform action")
}
return nil
}
func (m *Manager) pullJWTJWKS() (jwt.Keyfunc, error) {
now := time.Now()
m.mutex.Lock()
defer m.mutex.Unlock()
if now.Sub(m.jwtLastRefresh) >= jwtRefreshPeriod {
if m.jwtHTTPClient == nil {
m.jwtHTTPClient = &http.Client{
Timeout: (m.ReadTimeout),
Transport: &http.Transport{},
}
}
res, err := m.jwtHTTPClient.Get(m.JWTJWKS)
if err != nil {
return nil, err
}
defer res.Body.Close()
var raw json.RawMessage
err = json.NewDecoder(res.Body).Decode(&raw)
if err != nil {
return nil, err
}
tmp, err := keyfunc.NewJWKSetJSON(raw)
if err != nil {
return nil, err
}
m.jwtKeyFunc = tmp
m.jwtLastRefresh = now
}
return m.jwtKeyFunc.Keyfunc, nil
}

309
internal/auth/manager_test.go

@ -1,309 +0,0 @@ @@ -1,309 +0,0 @@
package auth
import (
"context"
"encoding/json"
"net"
"net/http"
"testing"
"github.com/bluenviron/gortsplib/v4/pkg/auth"
"github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v4/pkg/headers"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/stretchr/testify/require"
)
func mustParseCIDR(v string) net.IPNet {
_, ne, err := net.ParseCIDR(v)
if err != nil {
panic(err)
}
if ipv4 := ne.IP.To4(); ipv4 != nil {
return net.IPNet{IP: ipv4, Mask: ne.Mask[len(ne.Mask)-4 : len(ne.Mask)]}
}
return *ne
}
type testHTTPAuthenticator struct {
*http.Server
}
func (ts *testHTTPAuthenticator) initialize(t *testing.T, protocol string, action string) {
firstReceived := false
ts.Server = &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, http.MethodPost, r.Method)
require.Equal(t, "/auth", r.URL.Path)
var in struct {
IP string `json:"ip"`
User string `json:"user"`
Password string `json:"password"`
Path string `json:"path"`
Protocol string `json:"protocol"`
ID string `json:"id"`
Action string `json:"action"`
Query string `json:"query"`
}
err := json.NewDecoder(r.Body).Decode(&in)
require.NoError(t, err)
var user string
if action == "publish" {
user = "testpublisher"
} else {
user = "testreader"
}
if in.IP != "127.0.0.1" ||
in.User != user ||
in.Password != "testpass" ||
in.Path != "teststream" ||
in.Protocol != protocol ||
(firstReceived && in.ID == "") ||
in.Action != action ||
(in.Query != "user=testreader&pass=testpass&param=value" &&
in.Query != "user=testpublisher&pass=testpass&param=value" &&
in.Query != "param=value") {
w.WriteHeader(http.StatusBadRequest)
return
}
firstReceived = true
}),
}
ln, err := net.Listen("tcp", "127.0.0.1:9120")
require.NoError(t, err)
go ts.Server.Serve(ln)
}
func (ts *testHTTPAuthenticator) close() {
ts.Server.Shutdown(context.Background())
}
func TestAuthInternal(t *testing.T) {
for _, outcome := range []string{
"ok",
"wrong user",
"wrong pass",
"wrong ip",
"wrong action",
"wrong path",
} {
for _, encryption := range []string{
"plain",
"sha256",
"argon2",
} {
t.Run(outcome+" "+encryption, func(t *testing.T) {
m := Manager{
Method: conf.AuthMethodInternal,
InternalUsers: []conf.AuthInternalUser{
{
IPs: conf.IPNetworks{mustParseCIDR("127.1.1.1/32")},
Permissions: []conf.AuthInternalUserPermission{
{
Action: conf.AuthActionPublish,
Path: "mypath",
},
},
},
},
HTTPAddress: "",
RTSPAuthMethods: nil,
}
switch encryption {
case "plain":
m.InternalUsers[0].User = conf.Credential("testuser")
m.InternalUsers[0].Pass = conf.Credential("testpass")
case "sha256":
m.InternalUsers[0].User = conf.Credential("sha256:rl3rgi4NcZkpAEcacZnQ2VuOfJ0FxAqCRaKB/SwdZoQ=")
m.InternalUsers[0].Pass = conf.Credential("sha256:E9JJ8stBJ7QM+nV4ZoUCeHk/gU3tPFh/5YieiJp6n2w=")
case "argon2":
m.InternalUsers[0].User = conf.Credential(
"argon2:$argon2id$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$Ux/LWeTgJQPyfMMJo1myR64+o8rALHoPmlE1i/TR+58")
m.InternalUsers[0].Pass = conf.Credential(
"argon2:$argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$/mrZ42TiTv1mcPnpMUera5oi0SFYbbyueAbdx5sUvWo")
}
switch outcome {
case "ok":
err := m.Authenticate(&Request{
User: "testuser",
Pass: "testpass",
IP: net.ParseIP("127.1.1.1"),
Action: conf.AuthActionPublish,
Path: "mypath",
})
require.NoError(t, err)
case "wrong user":
err := m.Authenticate(&Request{
User: "wrong",
Pass: "testpass",
IP: net.ParseIP("127.1.1.1"),
Action: conf.AuthActionPublish,
Path: "mypath",
})
require.Error(t, err)
case "wrong pass":
err := m.Authenticate(&Request{
User: "testuser",
Pass: "wrong",
IP: net.ParseIP("127.1.1.1"),
Action: conf.AuthActionPublish,
Path: "mypath",
})
require.Error(t, err)
case "wrong ip":
err := m.Authenticate(&Request{
User: "testuser",
Pass: "testpass",
IP: net.ParseIP("127.1.1.2"),
Action: conf.AuthActionPublish,
Path: "mypath",
})
require.Error(t, err)
case "wrong action":
err := m.Authenticate(&Request{
User: "testuser",
Pass: "testpass",
IP: net.ParseIP("127.1.1.1"),
Action: conf.AuthActionRead,
Path: "mypath",
})
require.Error(t, err)
case "wrong path":
err := m.Authenticate(&Request{
User: "testuser",
Pass: "testpass",
IP: net.ParseIP("127.1.1.1"),
Action: conf.AuthActionPublish,
Path: "wrong",
})
require.Error(t, err)
}
})
}
}
}
func TestAuthInternalRTSPDigest(t *testing.T) {
m := Manager{
Method: conf.AuthMethodInternal,
InternalUsers: []conf.AuthInternalUser{
{
User: "myuser",
Pass: "mypass",
IPs: conf.IPNetworks{mustParseCIDR("127.1.1.1/32")},
Permissions: []conf.AuthInternalUserPermission{
{
Action: conf.AuthActionPublish,
Path: "mypath",
},
},
},
},
HTTPAddress: "",
RTSPAuthMethods: []headers.AuthMethod{headers.AuthDigestMD5},
}
u, err := base.ParseURL("rtsp://127.0.0.1:8554/mypath")
require.NoError(t, err)
s, err := auth.NewSender(
auth.GenerateWWWAuthenticate([]headers.AuthMethod{headers.AuthDigestMD5}, "IPCAM", "mynonce"),
"myuser",
"mypass",
)
require.NoError(t, err)
req := &base.Request{
Method: "ANNOUNCE",
URL: u,
}
s.AddAuthorization(req)
err = m.Authenticate(&Request{
IP: net.ParseIP("127.1.1.1"),
Action: conf.AuthActionPublish,
Path: "mypath",
RTSPRequest: req,
RTSPNonce: "mynonce",
})
require.NoError(t, err)
}
func TestAuthHTTP(t *testing.T) {
for _, outcome := range []string{"ok", "fail"} {
t.Run(outcome, func(t *testing.T) {
m := Manager{
Method: conf.AuthMethodHTTP,
HTTPAddress: "http://127.0.0.1:9120/auth",
RTSPAuthMethods: nil,
}
au := &testHTTPAuthenticator{}
au.initialize(t, "rtsp", "publish")
defer au.close()
if outcome == "ok" {
err := m.Authenticate(&Request{
User: "testpublisher",
Pass: "testpass",
IP: net.ParseIP("127.0.0.1"),
Action: conf.AuthActionPublish,
Path: "teststream",
Protocol: ProtocolRTSP,
Query: "param=value",
})
require.NoError(t, err)
} else {
err := m.Authenticate(&Request{
User: "invalid",
Pass: "testpass",
IP: net.ParseIP("127.0.0.1"),
Action: conf.AuthActionPublish,
Path: "teststream",
Protocol: ProtocolRTSP,
Query: "param=value",
})
require.Error(t, err)
}
})
}
}
func TestAuthHTTPExclude(t *testing.T) {
m := Manager{
Method: conf.AuthMethodHTTP,
HTTPAddress: "http://not-to-be-used:9120/auth",
HTTPExclude: []conf.AuthInternalUserPermission{{
Action: conf.AuthActionPublish,
}},
RTSPAuthMethods: nil,
}
err := m.Authenticate(&Request{
User: "",
Pass: "",
IP: net.ParseIP("127.0.0.1"),
Action: conf.AuthActionPublish,
Path: "teststream",
Protocol: ProtocolRTSP,
Query: "param=value",
})
require.NoError(t, err)
}

52
internal/conf/auth_action.go

@ -1,52 +0,0 @@ @@ -1,52 +0,0 @@
package conf
import (
"encoding/json"
"fmt"
)
// AuthAction is an authentication action.
type AuthAction string
// auth actions
const (
AuthActionPublish AuthAction = "publish"
AuthActionRead AuthAction = "read"
AuthActionPlayback AuthAction = "playback"
AuthActionAPI AuthAction = "api"
AuthActionMetrics AuthAction = "metrics"
AuthActionPprof AuthAction = "pprof"
)
// MarshalJSON implements json.Marshaler.
func (d AuthAction) MarshalJSON() ([]byte, error) {
return json.Marshal(string(d))
}
// UnmarshalJSON implements json.Unmarshaler.
func (d *AuthAction) UnmarshalJSON(b []byte) error {
var in string
if err := json.Unmarshal(b, &in); err != nil {
return err
}
switch in {
case string(AuthActionPublish),
string(AuthActionRead),
string(AuthActionPlayback),
string(AuthActionAPI),
string(AuthActionMetrics),
string(AuthActionPprof):
*d = AuthAction(in)
default:
return fmt.Errorf("invalid auth action: '%s'", in)
}
return nil
}
// UnmarshalEnv implements env.Unmarshaler.
func (d *AuthAction) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + v + `"`))
}

15
internal/conf/auth_internal_users.go

@ -1,15 +0,0 @@ @@ -1,15 +0,0 @@
package conf
// AuthInternalUserPermission is a permission of a user.
type AuthInternalUserPermission struct {
Action AuthAction `json:"action"`
Path string `json:"path"`
}
// AuthInternalUser is an user.
type AuthInternalUser struct {
User Credential `json:"user"`
Pass Credential `json:"pass"`
IPs IPNetworks `json:"ips"`
Permissions []AuthInternalUserPermission `json:"permissions"`
}

65
internal/conf/auth_method.go

@ -3,61 +3,64 @@ package conf @@ -3,61 +3,64 @@ package conf
import (
"encoding/json"
"fmt"
)
// AuthMethod is an authentication method.
type AuthMethod int
"sort"
"strings"
// authentication methods.
const (
AuthMethodInternal AuthMethod = iota
AuthMethodHTTP
AuthMethodJWT
"github.com/bluenviron/gortsplib/v4/pkg/headers"
)
// AuthMethods is the authMethods parameter.
type AuthMethods []headers.AuthMethod
// MarshalJSON implements json.Marshaler.
func (d AuthMethod) MarshalJSON() ([]byte, error) {
var out string
func (d AuthMethods) MarshalJSON() ([]byte, error) {
out := make([]string, len(d))
switch d {
case AuthMethodInternal:
out = "internal"
for i, v := range d {
switch v {
case headers.AuthBasic:
out[i] = "basic"
case AuthMethodHTTP:
out = "http"
case headers.AuthDigest:
out[i] = "digest"
default:
out = "jwt"
default:
return nil, fmt.Errorf("invalid authentication method: %v", v)
}
}
sort.Strings(out)
return json.Marshal(out)
}
// UnmarshalJSON implements json.Unmarshaler.
func (d *AuthMethod) UnmarshalJSON(b []byte) error {
var in string
func (d *AuthMethods) UnmarshalJSON(b []byte) error {
var in []string
if err := json.Unmarshal(b, &in); err != nil {
return err
}
switch in {
case "internal":
*d = AuthMethodInternal
*d = nil
case "http":
*d = AuthMethodHTTP
for _, v := range in {
switch v {
case "basic":
*d = append(*d, headers.AuthBasic)
case "jwt":
*d = AuthMethodJWT
case "digest":
*d = append(*d, headers.AuthDigest)
default:
return fmt.Errorf("invalid authMethod: '%s'", in)
default:
return fmt.Errorf("invalid authentication method: '%s'", v)
}
}
return nil
}
// UnmarshalEnv implements env.Unmarshaler.
func (d *AuthMethod) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + v + `"`))
func (d *AuthMethods) UnmarshalEnv(_ string, v string) error {
byts, _ := json.Marshal(strings.Split(v, ","))
return d.UnmarshalJSON(byts)
}

286
internal/conf/conf.go

@ -4,9 +4,7 @@ package conf @@ -4,9 +4,7 @@ package conf
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"reflect"
"sort"
@ -23,9 +21,6 @@ import ( @@ -23,9 +21,6 @@ import (
"github.com/bluenviron/mediamtx/internal/logger"
)
// ErrPathNotFound is returned when a path is not found.
var ErrPathNotFound = errors.New("path not found")
func sortedKeys(paths map[string]*OptionalPath) []string {
ret := make([]string, len(paths))
i := 0
@ -83,93 +78,43 @@ func copyStructFields(dest interface{}, source interface{}) { @@ -83,93 +78,43 @@ func copyStructFields(dest interface{}, source interface{}) {
}
}
func mustParseCIDR(v string) net.IPNet {
_, ne, err := net.ParseCIDR(v)
if err != nil {
panic(err)
}
if ipv4 := ne.IP.To4(); ipv4 != nil {
return net.IPNet{IP: ipv4, Mask: ne.Mask[len(ne.Mask)-4 : len(ne.Mask)]}
}
return *ne
}
func credentialIsNotEmpty(c *Credential) bool {
return c != nil && *c != ""
}
func ipNetworkIsNotEmpty(i *IPNetworks) bool {
return i != nil && len(*i) != 0
}
func anyPathHasDeprecatedCredentials(paths map[string]*OptionalPath) bool {
for _, pa := range paths {
if pa != nil {
rva := reflect.ValueOf(pa.Values).Elem()
if credentialIsNotEmpty(rva.FieldByName("PublishUser").Interface().(*Credential)) ||
credentialIsNotEmpty(rva.FieldByName("PublishPass").Interface().(*Credential)) ||
ipNetworkIsNotEmpty(rva.FieldByName("PublishIPs").Interface().(*IPNetworks)) ||
credentialIsNotEmpty(rva.FieldByName("ReadUser").Interface().(*Credential)) ||
credentialIsNotEmpty(rva.FieldByName("ReadPass").Interface().(*Credential)) ||
ipNetworkIsNotEmpty(rva.FieldByName("ReadIPs").Interface().(*IPNetworks)) {
return true
}
}
}
return false
}
// Conf is a configuration.
type Conf struct {
// General
LogLevel LogLevel `json:"logLevel"`
LogDestinations LogDestinations `json:"logDestinations"`
LogFile string `json:"logFile"`
ReadTimeout StringDuration `json:"readTimeout"`
WriteTimeout StringDuration `json:"writeTimeout"`
ReadBufferCount *int `json:"readBufferCount,omitempty"` // deprecated
WriteQueueSize int `json:"writeQueueSize"`
UDPMaxPayloadSize int `json:"udpMaxPayloadSize"`
Metrics bool `json:"metrics"`
MetricsAddress string `json:"metricsAddress"`
PPROF bool `json:"pprof"`
PPROFAddress string `json:"pprofAddress"`
RunOnConnect string `json:"runOnConnect"`
RunOnConnectRestart bool `json:"runOnConnectRestart"`
RunOnDisconnect string `json:"runOnDisconnect"`
// Authentication
AuthMethod AuthMethod `json:"authMethod"`
AuthInternalUsers []AuthInternalUser `json:"authInternalUsers"`
AuthHTTPAddress string `json:"authHTTPAddress"`
ExternalAuthenticationURL *string `json:"externalAuthenticationURL,omitempty"` // deprecated
AuthHTTPExclude []AuthInternalUserPermission `json:"authHTTPExclude"`
AuthJWTJWKS string `json:"authJWTJWKS"`
// API
API bool `json:"api"`
APIAddress string `json:"apiAddress"`
// Playback
Playback bool `json:"playback"`
PlaybackAddress string `json:"playbackAddress"`
LogLevel LogLevel `json:"logLevel"`
LogDestinations LogDestinations `json:"logDestinations"`
LogFile string `json:"logFile"`
ReadTimeout StringDuration `json:"readTimeout"`
WriteTimeout StringDuration `json:"writeTimeout"`
ReadBufferCount *int `json:"readBufferCount,omitempty"` // deprecated
WriteQueueSize int `json:"writeQueueSize"`
UDPMaxPayloadSize int `json:"udpMaxPayloadSize"`
ExternalAuthenticationURL string `json:"externalAuthenticationURL"`
API bool `json:"api"`
APIAddress string `json:"apiAddress"`
Metrics bool `json:"metrics"`
MetricsAddress string `json:"metricsAddress"`
PPROF bool `json:"pprof"`
PPROFAddress string `json:"pprofAddress"`
RunOnConnect string `json:"runOnConnect"`
RunOnConnectRestart bool `json:"runOnConnectRestart"`
RunOnDisconnect string `json:"runOnDisconnect"`
// RTSP server
RTSP bool `json:"rtsp"`
RTSPDisable *bool `json:"rtspDisable,omitempty"` // deprecated
Protocols Protocols `json:"protocols"`
Encryption Encryption `json:"encryption"`
RTSPAddress string `json:"rtspAddress"`
RTSPSAddress string `json:"rtspsAddress"`
RTPAddress string `json:"rtpAddress"`
RTCPAddress string `json:"rtcpAddress"`
MulticastIPRange string `json:"multicastIPRange"`
MulticastRTPPort int `json:"multicastRTPPort"`
MulticastRTCPPort int `json:"multicastRTCPPort"`
ServerKey string `json:"serverKey"`
ServerCert string `json:"serverCert"`
AuthMethods *RTSPAuthMethods `json:"authMethods,omitempty"` // deprecated
RTSPAuthMethods RTSPAuthMethods `json:"rtspAuthMethods"`
RTSP bool `json:"rtsp"`
RTSPDisable *bool `json:"rtspDisable,omitempty"` // deprecated
Protocols Protocols `json:"protocols"`
Encryption Encryption `json:"encryption"`
RTSPAddress string `json:"rtspAddress"`
RTSPSAddress string `json:"rtspsAddress"`
RTPAddress string `json:"rtpAddress"`
RTCPAddress string `json:"rtcpAddress"`
MulticastIPRange string `json:"multicastIPRange"`
MulticastRTPPort int `json:"multicastRTPPort"`
MulticastRTCPPort int `json:"multicastRTCPPort"`
ServerKey string `json:"serverKey"`
ServerCert string `json:"serverCert"`
AuthMethods AuthMethods `json:"authMethods"`
// RTMP server
RTMP bool `json:"rtmp"`
@ -194,7 +139,7 @@ type Conf struct { @@ -194,7 +139,7 @@ type Conf struct {
HLSPartDuration StringDuration `json:"hlsPartDuration"`
HLSSegmentMaxSize StringSize `json:"hlsSegmentMaxSize"`
HLSAllowOrigin string `json:"hlsAllowOrigin"`
HLSTrustedProxies IPNetworks `json:"hlsTrustedProxies"`
HLSTrustedProxies IPsOrCIDRs `json:"hlsTrustedProxies"`
HLSDirectory string `json:"hlsDirectory"`
// WebRTC server
@ -205,7 +150,7 @@ type Conf struct { @@ -205,7 +150,7 @@ type Conf struct {
WebRTCServerKey string `json:"webrtcServerKey"`
WebRTCServerCert string `json:"webrtcServerCert"`
WebRTCAllowOrigin string `json:"webrtcAllowOrigin"`
WebRTCTrustedProxies IPNetworks `json:"webrtcTrustedProxies"`
WebRTCTrustedProxies IPsOrCIDRs `json:"webrtcTrustedProxies"`
WebRTCLocalUDPAddress string `json:"webrtcLocalUDPAddress"`
WebRTCLocalTCPAddress string `json:"webrtcLocalTCPAddress"`
WebRTCIPsFromInterfaces bool `json:"webrtcIPsFromInterfaces"`
@ -246,62 +191,11 @@ func (conf *Conf) setDefaults() { @@ -246,62 +191,11 @@ func (conf *Conf) setDefaults() {
conf.WriteTimeout = 10 * StringDuration(time.Second)
conf.WriteQueueSize = 512
conf.UDPMaxPayloadSize = 1472
conf.MetricsAddress = ":9998"
conf.PPROFAddress = ":9999"
// Authentication
conf.AuthInternalUsers = []AuthInternalUser{
{
User: "any",
Pass: "",
Permissions: []AuthInternalUserPermission{
{
Action: AuthActionPublish,
},
{
Action: AuthActionRead,
},
{
Action: AuthActionPlayback,
},
},
},
{
User: "any",
Pass: "",
IPs: IPNetworks{mustParseCIDR("127.0.0.1/32"), mustParseCIDR("::1/128")},
Permissions: []AuthInternalUserPermission{
{
Action: AuthActionAPI,
},
{
Action: AuthActionMetrics,
},
{
Action: AuthActionPprof,
},
},
},
}
conf.AuthHTTPExclude = []AuthInternalUserPermission{
{
Action: AuthActionAPI,
},
{
Action: AuthActionMetrics,
},
{
Action: AuthActionPprof,
},
}
// API
conf.APIAddress = ":9997"
// Playback server
conf.PlaybackAddress = ":9996"
conf.APIAddress = "127.0.0.1:9997"
conf.MetricsAddress = "127.0.0.1:9998"
conf.PPROFAddress = "127.0.0.1:9999"
// RTSP server
// RTSP
conf.RTSP = true
conf.Protocols = Protocols{
Protocol(gortsplib.TransportUDP): {},
@ -317,9 +211,9 @@ func (conf *Conf) setDefaults() { @@ -317,9 +211,9 @@ func (conf *Conf) setDefaults() {
conf.MulticastRTCPPort = 8003
conf.ServerKey = "server.key"
conf.ServerCert = "server.crt"
conf.RTSPAuthMethods = RTSPAuthMethods{headers.AuthBasic}
conf.AuthMethods = AuthMethods{headers.AuthBasic}
// RTMP server
// RTMP
conf.RTMP = true
conf.RTMPAddress = ":1935"
conf.RTMPSAddress = ":1936"
@ -338,7 +232,7 @@ func (conf *Conf) setDefaults() { @@ -338,7 +232,7 @@ func (conf *Conf) setDefaults() {
conf.HLSSegmentMaxSize = 50 * 1024 * 1024
conf.HLSAllowOrigin = "*"
// WebRTC server
// WebRTC
conf.WebRTC = true
conf.WebRTCAddress = ":8889"
conf.WebRTCServerKey = "server.key"
@ -350,7 +244,7 @@ func (conf *Conf) setDefaults() { @@ -350,7 +244,7 @@ func (conf *Conf) setDefaults() {
conf.WebRTCAdditionalHosts = []string{}
conf.WebRTCICEServers2 = []WebRTCICEServer{}
// SRT server
// SRT
conf.SRT = true
conf.SRTAddress = ":8890"
@ -376,7 +270,7 @@ func Load(fpath string, defaultConfPaths []string) (*Conf, string, error) { @@ -376,7 +270,7 @@ func Load(fpath string, defaultConfPaths []string) (*Conf, string, error) {
return nil, "", err
}
err = conf.Validate()
err = conf.Check()
if err != nil {
return nil, "", err
}
@ -439,8 +333,8 @@ func (conf Conf) Clone() *Conf { @@ -439,8 +333,8 @@ func (conf Conf) Clone() *Conf {
return &dest
}
// Validate checks the configuration for errors.
func (conf *Conf) Validate() error {
// Check checks the configuration for errors.
func (conf *Conf) Check() error {
// General
if conf.ReadBufferCount != nil {
@ -452,69 +346,14 @@ func (conf *Conf) Validate() error { @@ -452,69 +346,14 @@ func (conf *Conf) Validate() error {
if conf.UDPMaxPayloadSize > 1472 {
return fmt.Errorf("'udpMaxPayloadSize' must be less than 1472")
}
// Authentication
if conf.ExternalAuthenticationURL != nil {
conf.AuthMethod = AuthMethodHTTP
conf.AuthHTTPAddress = *conf.ExternalAuthenticationURL
}
if conf.AuthHTTPAddress != "" &&
!strings.HasPrefix(conf.AuthHTTPAddress, "http://") &&
!strings.HasPrefix(conf.AuthHTTPAddress, "https://") {
return fmt.Errorf("'externalAuthenticationURL' must be a HTTP URL")
}
if conf.AuthJWTJWKS != "" &&
!strings.HasPrefix(conf.AuthJWTJWKS, "http://") &&
!strings.HasPrefix(conf.AuthJWTJWKS, "https://") {
return fmt.Errorf("'authJWTJWKS' must be a HTTP URL")
}
deprecatedCredentialsMode := false
if credentialIsNotEmpty(conf.PathDefaults.PublishUser) ||
credentialIsNotEmpty(conf.PathDefaults.PublishPass) ||
ipNetworkIsNotEmpty(conf.PathDefaults.PublishIPs) ||
credentialIsNotEmpty(conf.PathDefaults.ReadUser) ||
credentialIsNotEmpty(conf.PathDefaults.ReadPass) ||
ipNetworkIsNotEmpty(conf.PathDefaults.ReadIPs) ||
anyPathHasDeprecatedCredentials(conf.OptionalPaths) {
conf.AuthInternalUsers = []AuthInternalUser{
{
User: "any",
Pass: "",
Permissions: []AuthInternalUserPermission{
{
Action: AuthActionPlayback,
},
},
},
{
User: "any",
Pass: "",
IPs: IPNetworks{mustParseCIDR("127.0.0.1/32"), mustParseCIDR("::1/128")},
Permissions: []AuthInternalUserPermission{
{
Action: AuthActionAPI,
},
{
Action: AuthActionMetrics,
},
{
Action: AuthActionPprof,
},
},
},
}
deprecatedCredentialsMode = true
}
switch conf.AuthMethod {
case AuthMethodHTTP:
if conf.AuthHTTPAddress == "" {
return fmt.Errorf("'authHTTPAddress' is empty")
if conf.ExternalAuthenticationURL != "" {
if !strings.HasPrefix(conf.ExternalAuthenticationURL, "http://") &&
!strings.HasPrefix(conf.ExternalAuthenticationURL, "https://") {
return fmt.Errorf("'externalAuthenticationURL' must be a HTTP URL")
}
case AuthMethodJWT:
if conf.AuthJWTJWKS == "" {
return fmt.Errorf("'authJWTJWKS' is empty")
if contains(conf.AuthMethods, headers.AuthDigest) {
return fmt.Errorf("'externalAuthenticationURL' can't be used when 'digest' is in authMethods")
}
}
@ -531,19 +370,6 @@ func (conf *Conf) Validate() error { @@ -531,19 +370,6 @@ func (conf *Conf) Validate() error {
return fmt.Errorf("strict encryption can't be used with the UDP-multicast transport protocol")
}
}
if conf.AuthMethods != nil {
conf.RTSPAuthMethods = *conf.AuthMethods
}
if contains(conf.RTSPAuthMethods, headers.AuthDigestMD5) {
if conf.AuthMethod != AuthMethodInternal {
return fmt.Errorf("when RTSP digest is enabled, the only supported auth method is 'internal'")
}
for _, user := range conf.AuthInternalUsers {
if user.User.IsHashed() || user.Pass.IsHashed() {
return fmt.Errorf("when RTSP digest is enabled, hashed credentials cannot be used")
}
}
}
// RTMP
@ -606,7 +432,7 @@ func (conf *Conf) Validate() error { @@ -606,7 +432,7 @@ func (conf *Conf) Validate() error {
}
}
// Record (deprecated)
// Record
if conf.Record != nil {
conf.PathDefaults.Record = *conf.Record
}
@ -649,7 +475,7 @@ func (conf *Conf) Validate() error { @@ -649,7 +475,7 @@ func (conf *Conf) Validate() error {
pconf := newPath(&conf.PathDefaults, optional)
conf.Paths[name] = pconf
err := pconf.validate(conf, name, deprecatedCredentialsMode)
err := pconf.check(conf, name)
if err != nil {
return err
}
@ -705,7 +531,7 @@ func (conf *Conf) AddPath(name string, p *OptionalPath) error { @@ -705,7 +531,7 @@ func (conf *Conf) AddPath(name string, p *OptionalPath) error {
func (conf *Conf) PatchPath(name string, optional2 *OptionalPath) error {
optional, ok := conf.OptionalPaths[name]
if !ok {
return ErrPathNotFound
return fmt.Errorf("path not found")
}
copyStructFields(optional.Values, optional2.Values)
@ -716,7 +542,7 @@ func (conf *Conf) PatchPath(name string, optional2 *OptionalPath) error { @@ -716,7 +542,7 @@ func (conf *Conf) PatchPath(name string, optional2 *OptionalPath) error {
func (conf *Conf) ReplacePath(name string, optional2 *OptionalPath) error {
_, ok := conf.OptionalPaths[name]
if !ok {
return ErrPathNotFound
return fmt.Errorf("path not found")
}
conf.OptionalPaths[name] = optional2
@ -726,7 +552,7 @@ func (conf *Conf) ReplacePath(name string, optional2 *OptionalPath) error { @@ -726,7 +552,7 @@ func (conf *Conf) ReplacePath(name string, optional2 *OptionalPath) error {
// RemovePath removes a path.
func (conf *Conf) RemovePath(name string) error {
if _, ok := conf.OptionalPaths[name]; !ok {
return ErrPathNotFound
return fmt.Errorf("path not found")
}
delete(conf.OptionalPaths, name)

31
internal/conf/conf_test.go

@ -15,7 +15,7 @@ import ( @@ -15,7 +15,7 @@ import (
"github.com/bluenviron/mediamtx/internal/logger"
)
func createTempFile(byts []byte) (string, error) {
func writeTempFile(byts []byte) (string, error) {
tmpf, err := os.CreateTemp(os.TempDir(), "rtsp-")
if err != nil {
return "", err
@ -32,7 +32,7 @@ func createTempFile(byts []byte) (string, error) { @@ -32,7 +32,7 @@ func createTempFile(byts []byte) (string, error) {
func TestConfFromFile(t *testing.T) {
func() {
tmpf, err := createTempFile([]byte("logLevel: debug\n" +
tmpf, err := writeTempFile([]byte("logLevel: debug\n" +
"paths:\n" +
" cam1:\n" +
" runOnDemandStartTimeout: 5s\n"))
@ -52,7 +52,6 @@ func TestConfFromFile(t *testing.T) { @@ -52,7 +52,6 @@ func TestConfFromFile(t *testing.T) {
Source: "publisher",
SourceOnDemandStartTimeout: 10 * StringDuration(time.Second),
SourceOnDemandCloseAfter: 10 * StringDuration(time.Second),
Playback: true,
RecordPath: "./recordings/%path/%Y-%m-%d_%H-%M-%S-%f",
RecordFormat: RecordFormatFMP4,
RecordPartDuration: 100000000,
@ -66,7 +65,6 @@ func TestConfFromFile(t *testing.T) { @@ -66,7 +65,6 @@ func TestConfFromFile(t *testing.T) {
RPICameraSharpness: 1,
RPICameraExposure: "normal",
RPICameraAWB: "auto",
RPICameraAWBGains: []float64{0, 0},
RPICameraDenoise: "off",
RPICameraMetering: "centre",
RPICameraFPS: 30,
@ -84,7 +82,7 @@ func TestConfFromFile(t *testing.T) { @@ -84,7 +82,7 @@ func TestConfFromFile(t *testing.T) {
}()
func() {
tmpf, err := createTempFile([]byte(``))
tmpf, err := writeTempFile([]byte(``))
require.NoError(t, err)
defer os.Remove(tmpf)
@ -93,7 +91,7 @@ func TestConfFromFile(t *testing.T) { @@ -93,7 +91,7 @@ func TestConfFromFile(t *testing.T) {
}()
func() {
tmpf, err := createTempFile([]byte(`paths:`))
tmpf, err := writeTempFile([]byte(`paths:`))
require.NoError(t, err)
defer os.Remove(tmpf)
@ -102,7 +100,7 @@ func TestConfFromFile(t *testing.T) { @@ -102,7 +100,7 @@ func TestConfFromFile(t *testing.T) {
}()
func() {
tmpf, err := createTempFile([]byte(
tmpf, err := writeTempFile([]byte(
"paths:\n" +
" mypath:\n"))
require.NoError(t, err)
@ -126,7 +124,7 @@ func TestConfFromFileAndEnv(t *testing.T) { @@ -126,7 +124,7 @@ func TestConfFromFileAndEnv(t *testing.T) {
// deprecated path parameter
t.Setenv("MTX_PATHS_CAM2_DISABLEPUBLISHEROVERRIDE", "yes")
tmpf, err := createTempFile([]byte("{}"))
tmpf, err := writeTempFile([]byte("{}"))
require.NoError(t, err)
defer os.Remove(tmpf)
@ -178,7 +176,7 @@ func TestConfEncryption(t *testing.T) { @@ -178,7 +176,7 @@ func TestConfEncryption(t *testing.T) {
t.Setenv("RTSP_CONFKEY", key)
tmpf, err := createTempFile([]byte(encryptedConf))
tmpf, err := writeTempFile([]byte(encryptedConf))
require.NoError(t, err)
defer os.Remove(tmpf)
@ -214,6 +212,17 @@ func TestConfErrors(t *testing.T) { @@ -214,6 +212,17 @@ func TestConfErrors(t *testing.T) {
"udpMaxPayloadSize: 5000\n",
"'udpMaxPayloadSize' must be less than 1472",
},
{
"invalid externalAuthenticationURL 1",
"externalAuthenticationURL: testing\n",
"'externalAuthenticationURL' must be a HTTP URL",
},
{
"invalid externalAuthenticationURL 2",
"externalAuthenticationURL: http://myurl\n" +
"authMethods: [digest]\n",
"'externalAuthenticationURL' can't be used when 'digest' is in authMethods",
},
{
"invalid strict encryption 1",
"encryption: strict\n" +
@ -284,7 +293,7 @@ func TestConfErrors(t *testing.T) { @@ -284,7 +293,7 @@ func TestConfErrors(t *testing.T) {
},
} {
t.Run(ca.name, func(t *testing.T) {
tmpf, err := createTempFile([]byte(ca.conf))
tmpf, err := writeTempFile([]byte(ca.conf))
require.NoError(t, err)
defer os.Remove(tmpf)
@ -314,7 +323,7 @@ func TestSampleConfFile(t *testing.T) { @@ -314,7 +323,7 @@ func TestSampleConfFile(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "../../mediamtx.yml", confPath1)
tmpf, err := createTempFile([]byte("paths:\n all_others:"))
tmpf, err := writeTempFile([]byte("paths:\n all_others:"))
require.NoError(t, err)
defer os.Remove(tmpf)

97
internal/conf/credential.go

@ -18,18 +18,14 @@ var ( @@ -18,18 +18,14 @@ var (
const plainCredentialSupportedChars = "A-Z,0-9,!,$,(,),*,+,.,;,<,=,>,[,],^,_,-,\",\",@,#,&"
func sha256Base64(in string) string {
h := sha256.New()
h.Write([]byte(in))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
// Credential is a parameter that is used as username or password.
type Credential string
type Credential struct {
value string
}
// MarshalJSON implements json.Marshaler.
func (d Credential) MarshalJSON() ([]byte, error) {
return json.Marshal(string(d))
return json.Marshal(d.value)
}
// UnmarshalJSON implements json.Unmarshaler.
@ -39,9 +35,11 @@ func (d *Credential) UnmarshalJSON(b []byte) error { @@ -39,9 +35,11 @@ func (d *Credential) UnmarshalJSON(b []byte) error {
return err
}
*d = Credential(in)
*d = Credential{
value: in,
}
return d.validate()
return d.validateConfig()
}
// UnmarshalEnv implements env.Unmarshaler.
@ -49,59 +47,76 @@ func (d *Credential) UnmarshalEnv(_ string, v string) error { @@ -49,59 +47,76 @@ func (d *Credential) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + v + `"`))
}
// GetValue returns the value of the credential.
func (d *Credential) GetValue() string {
return d.value
}
// IsEmpty returns true if the credential is not configured.
func (d *Credential) IsEmpty() bool {
return d.value == ""
}
// IsSha256 returns true if the credential is a sha256 hash.
func (d Credential) IsSha256() bool {
return strings.HasPrefix(string(d), "sha256:")
func (d *Credential) IsSha256() bool {
return d.value != "" && strings.HasPrefix(d.value, "sha256:")
}
// IsArgon2 returns true if the credential is an argon2 hash.
func (d Credential) IsArgon2() bool {
return strings.HasPrefix(string(d), "argon2:")
func (d *Credential) IsArgon2() bool {
return d.value != "" && strings.HasPrefix(d.value, "argon2:")
}
// IsHashed returns true if the credential is a sha256 or argon2 hash.
func (d Credential) IsHashed() bool {
func (d *Credential) IsHashed() bool {
return d.IsSha256() || d.IsArgon2()
}
func sha256Base64(in string) string {
h := sha256.New()
h.Write([]byte(in))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
// Check returns true if the given value matches the credential.
func (d Credential) Check(guess string) bool {
func (d *Credential) Check(guess string) bool {
if d.IsSha256() {
return string(d)[len("sha256:"):] == sha256Base64(guess)
return d.value[len("sha256:"):] == sha256Base64(guess)
}
if d.IsArgon2() {
// TODO: remove matthewhartstonge/argon2 when this PR gets merged into mainline Go:
// https://go-review.googlesource.com/c/crypto/+/502515
ok, err := argon2.VerifyEncoded([]byte(guess), []byte(string(d)[len("argon2:"):]))
ok, err := argon2.VerifyEncoded([]byte(guess), []byte(d.value[len("argon2:"):]))
return ok && err == nil
}
if d != "" {
return string(d) == guess
if d.IsEmpty() {
// when no credential is set, any value is valid
return true
}
return true
return d.value == guess
}
func (d Credential) validate() error {
if d != "" {
switch {
case d.IsSha256():
if !reBase64.MatchString(string(d)) {
return fmt.Errorf("credential contains unsupported characters, sha256 hash must be base64 encoded")
}
case d.IsArgon2():
// TODO: remove matthewhartstonge/argon2 when this PR gets merged into mainline Go:
// https://go-review.googlesource.com/c/crypto/+/502515
_, err := argon2.Decode([]byte(string(d)[len("argon2:"):]))
if err != nil {
return fmt.Errorf("invalid argon2 hash: %w", err)
}
default:
if !rePlainCredential.MatchString(string(d)) {
return fmt.Errorf("credential contains unsupported characters. Supported are: %s", plainCredentialSupportedChars)
}
func (d *Credential) validateConfig() error {
if d.IsEmpty() {
return nil
}
switch {
case d.IsSha256():
if !reBase64.MatchString(d.value) {
return fmt.Errorf("credential contains unsupported characters, sha256 hash must be base64 encoded")
}
case d.IsArgon2():
// TODO: remove matthewhartstonge/argon2 when this PR gets merged into mainline Go:
// https://go-review.googlesource.com/c/crypto/+/502515
_, err := argon2.Decode([]byte(d.value[len("argon2:"):]))
if err != nil {
return fmt.Errorf("invalid argon2 hash: %w", err)
}
default:
if !rePlainCredential.MatchString(d.value) {
return fmt.Errorf("credential contains unsupported characters. Supported are: %s", plainCredentialSupportedChars)
}
}
return nil

72
internal/conf/credential_test.go

@ -8,7 +8,7 @@ import ( @@ -8,7 +8,7 @@ import (
func TestCredential(t *testing.T) {
t.Run("MarshalJSON", func(t *testing.T) {
cred := Credential("password")
cred := Credential{value: "password"}
expectedJSON := []byte(`"password"`)
actualJSON, err := cred.MarshalJSON()
assert.NoError(t, err)
@ -16,7 +16,7 @@ func TestCredential(t *testing.T) { @@ -16,7 +16,7 @@ func TestCredential(t *testing.T) {
})
t.Run("UnmarshalJSON", func(t *testing.T) {
expectedCred := Credential("password")
expectedCred := Credential{value: "password"}
jsonData := []byte(`"password"`)
var actualCred Credential
err := actualCred.UnmarshalJSON(jsonData)
@ -25,121 +25,137 @@ func TestCredential(t *testing.T) { @@ -25,121 +25,137 @@ func TestCredential(t *testing.T) {
})
t.Run("UnmarshalEnv", func(t *testing.T) {
cred := Credential("")
cred := Credential{}
err := cred.UnmarshalEnv("", "password")
assert.NoError(t, err)
assert.Equal(t, Credential("password"), cred)
assert.Equal(t, "password", cred.value)
})
t.Run("GetValue", func(t *testing.T) {
cred := Credential{value: "password"}
actualValue := cred.GetValue()
assert.Equal(t, "password", actualValue)
})
t.Run("IsEmpty", func(t *testing.T) {
cred := Credential{}
assert.True(t, cred.IsEmpty())
assert.False(t, cred.IsHashed())
cred.value = "password"
assert.False(t, cred.IsEmpty())
assert.False(t, cred.IsHashed())
})
t.Run("IsSha256", func(t *testing.T) {
cred := Credential("")
cred := Credential{}
assert.False(t, cred.IsSha256())
assert.False(t, cred.IsHashed())
cred = "sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo="
cred.value = "sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo="
assert.True(t, cred.IsSha256())
assert.True(t, cred.IsHashed())
cred = "argon2:$argon2id$v=19$m=65536,t=1," +
cred.value = "argon2:$argon2id$v=19$m=65536,t=1," +
"p=4$WXJGqwIB2qd+pRmxMOw9Dg$X4gvR0ZB2DtQoN8vOnJPR2SeFdUhH9TyVzfV98sfWeE"
assert.False(t, cred.IsSha256())
assert.True(t, cred.IsHashed())
})
t.Run("IsArgon2", func(t *testing.T) {
cred := Credential("")
cred := Credential{}
assert.False(t, cred.IsArgon2())
assert.False(t, cred.IsHashed())
cred = "sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo="
cred.value = "sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo="
assert.False(t, cred.IsArgon2())
assert.True(t, cred.IsHashed())
cred = "argon2:$argon2id$v=19$m=65536,t=1," +
cred.value = "argon2:$argon2id$v=19$m=65536,t=1," +
"p=4$WXJGqwIB2qd+pRmxMOw9Dg$X4gvR0ZB2DtQoN8vOnJPR2SeFdUhH9TyVzfV98sfWeE"
assert.True(t, cred.IsArgon2())
assert.True(t, cred.IsHashed())
})
t.Run("Check-plain", func(t *testing.T) {
cred := Credential("password")
cred := Credential{value: "password"}
assert.True(t, cred.Check("password"))
assert.False(t, cred.Check("wrongpassword"))
})
t.Run("Check-sha256", func(t *testing.T) {
cred := Credential("password")
cred := Credential{value: "password"}
assert.True(t, cred.Check("password"))
assert.False(t, cred.Check("wrongpassword"))
})
t.Run("Check-sha256", func(t *testing.T) {
cred := Credential("sha256:rl3rgi4NcZkpAEcacZnQ2VuOfJ0FxAqCRaKB/SwdZoQ=")
cred := Credential{value: "sha256:rl3rgi4NcZkpAEcacZnQ2VuOfJ0FxAqCRaKB/SwdZoQ="}
assert.True(t, cred.Check("testuser"))
assert.False(t, cred.Check("notestuser"))
})
t.Run("Check-argon2", func(t *testing.T) {
cred := Credential("argon2:$argon2id$v=19$m=4096,t=3," +
"p=1$MTIzNDU2Nzg$Ux/LWeTgJQPyfMMJo1myR64+o8rALHoPmlE1i/TR+58")
cred := Credential{value: "argon2:$argon2id$v=19$m=4096,t=3," +
"p=1$MTIzNDU2Nzg$Ux/LWeTgJQPyfMMJo1myR64+o8rALHoPmlE1i/TR+58"}
assert.True(t, cred.Check("testuser"))
assert.False(t, cred.Check("notestuser"))
})
t.Run("validate", func(t *testing.T) {
t.Run("validateConfig", func(t *testing.T) {
tests := []struct {
name string
cred Credential
cred *Credential
wantErr bool
}{
{
name: "Empty credential",
cred: Credential(""),
cred: &Credential{value: ""},
wantErr: false,
},
{
name: "Valid plain credential",
cred: Credential("validPlain123"),
cred: &Credential{value: "validPlain123"},
wantErr: false,
},
{
name: "Invalid plain credential",
cred: Credential("invalid/Plain"),
cred: &Credential{value: "invalid/Plain"},
wantErr: true,
},
{
name: "Valid sha256 credential",
cred: Credential("sha256:validBase64EncodedHash=="),
cred: &Credential{value: "sha256:validBase64EncodedHash=="},
wantErr: false,
},
{
name: "Invalid sha256 credential",
cred: Credential("sha256:inval*idBase64"),
cred: &Credential{value: "sha256:inval*idBase64"},
wantErr: true,
},
{
name: "Valid Argon2 credential",
cred: Credential("argon2:$argon2id$v=19$m=4096," +
"t=3,p=1$MTIzNDU2Nzg$zarsL19s86GzUWlAkvwt4gJBFuU/A9CVuCjNI4fksow"),
cred: &Credential{value: "argon2:$argon2id$v=19$m=4096," +
"t=3,p=1$MTIzNDU2Nzg$zarsL19s86GzUWlAkvwt4gJBFuU/A9CVuCjNI4fksow"},
wantErr: false,
},
{
name: "Invalid Argon2 credential",
cred: Credential("argon2:invalid"),
cred: &Credential{value: "argon2:invalid"},
wantErr: true,
},
{
name: "Invalid Argon2 credential",
// testing argon2d errors, because it's not supported
cred: Credential("$argon2d$v=19$m=4096,t=3," +
"p=1$MTIzNDU2Nzg$Xqyd4R7LzXvvAEHaVU12+Nzf5OkHoYcwIEIIYJUDpz0"),
cred: &Credential{value: "$argon2d$v=19$m=4096,t=3," +
"p=1$MTIzNDU2Nzg$Xqyd4R7LzXvvAEHaVU12+Nzf5OkHoYcwIEIIYJUDpz0"},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.cred.validate()
err := tt.cred.validateConfig()
if tt.wantErr {
assert.Error(t, err)
} else {

5
internal/conf/encryption.go

@ -26,8 +26,11 @@ func (d Encryption) MarshalJSON() ([]byte, error) { @@ -26,8 +26,11 @@ func (d Encryption) MarshalJSON() ([]byte, error) {
case EncryptionOptional:
out = "optional"
default:
case EncryptionStrict:
out = "strict"
default:
return nil, fmt.Errorf("invalid encryption: %v", d)
}
return json.Marshal(out)

25
internal/conf/env/env.go vendored

@ -188,31 +188,6 @@ func loadEnvInternal(env map[string]string, prefix string, prv reflect.Value) er @@ -188,31 +188,6 @@ func loadEnvInternal(env map[string]string, prefix string, prv reflect.Value) er
}
return nil
case rt.Elem() == reflect.TypeOf(float64(0)):
if ev, ok := env[prefix]; ok {
if ev == "" {
prv.Elem().Set(reflect.MakeSlice(prv.Elem().Type(), 0, 0))
} else {
if prv.IsNil() {
prv.Set(reflect.New(rt))
}
raw := strings.Split(ev, ",")
vals := make([]float64, len(raw))
for i, v := range raw {
tmp, err := strconv.ParseFloat(v, 64)
if err != nil {
return err
}
vals[i] = tmp
}
prv.Elem().Set(reflect.ValueOf(vals))
}
}
return nil
case rt.Elem().Kind() == reflect.Struct:
if ev, ok := env[prefix]; ok && ev == "" { // special case: empty list
prv.Elem().Set(reflect.MakeSlice(prv.Elem().Type(), 0, 0))

5
internal/conf/env/env_test.go vendored

@ -85,7 +85,6 @@ type testStruct struct { @@ -85,7 +85,6 @@ type testStruct struct {
MyDurationOpt *myDuration `json:"myDurationOpt"`
MyDurationOptUnset *myDuration `json:"myDurationOptUnset"`
MyMap map[string]*mapEntry `json:"myMap"`
MySliceFloat []float64 `json:"mySliceFloat"`
MySliceString []string `json:"mySliceString"`
MySliceStringEmpty []string `json:"mySliceStringEmpty"`
MySliceStringOpt *[]string `json:"mySliceStringOpt"`
@ -114,7 +113,6 @@ func TestLoad(t *testing.T) { @@ -114,7 +113,6 @@ func TestLoad(t *testing.T) {
"MYPREFIX_MYMAP_MYKEY": "",
"MYPREFIX_MYMAP_MYKEY2_MYVALUE": "asd",
"MYPREFIX_MYMAP_MYKEY2_MYSTRUCT_MYPARAM": "456",
"MYPREFIX_MYSLICEFLOAT": "0.5,0.5",
"MYPREFIX_MYSLICESTRING": "val1,val2",
"MYPREFIX_MYSLICESTRINGEMPTY": "",
"MYPREFIX_MYSLICESTRINGOPT": "aa",
@ -162,7 +160,6 @@ func TestLoad(t *testing.T) { @@ -162,7 +160,6 @@ func TestLoad(t *testing.T) {
},
},
},
MySliceFloat: []float64{0.5, 0.5},
MySliceString: []string{
"val1",
"val2",
@ -194,7 +191,7 @@ func FuzzLoad(f *testing.F) { @@ -194,7 +191,7 @@ func FuzzLoad(f *testing.F) {
f.Add("MYPREFIX_MYDURATION", "a")
f.Add("MYPREFIX_MYDURATION_A", "a")
f.Fuzz(func(_ *testing.T, key string, val string) {
f.Fuzz(func(t *testing.T, key string, val string) {
env := map[string]string{
key: val,
}

5
internal/conf/hls_variant.go

@ -21,8 +21,11 @@ func (d HLSVariant) MarshalJSON() ([]byte, error) { @@ -21,8 +21,11 @@ func (d HLSVariant) MarshalJSON() ([]byte, error) {
case HLSVariant(gohlslib.MuxerVariantFMP4):
out = "fmp4"
default:
case HLSVariant(gohlslib.MuxerVariantLowLatency):
out = "lowLatency"
default:
return nil, fmt.Errorf("invalid HLS variant: %v", d)
}
return json.Marshal(out)

84
internal/conf/ip_networks.go

@ -1,84 +0,0 @@ @@ -1,84 +0,0 @@
package conf
import (
"encoding/json"
"fmt"
"net"
"sort"
"strings"
)
// IPNetworks is a parameter that contains a list of IP networks.
type IPNetworks []net.IPNet
// MarshalJSON implements json.Marshaler.
func (d IPNetworks) MarshalJSON() ([]byte, error) {
out := make([]string, len(d))
for i, v := range d {
out[i] = v.String()
}
sort.Strings(out)
return json.Marshal(out)
}
// UnmarshalJSON implements json.Unmarshaler.
func (d *IPNetworks) UnmarshalJSON(b []byte) error {
var in []string
if err := json.Unmarshal(b, &in); err != nil {
return err
}
*d = nil
if len(in) == 0 {
return nil
}
for _, t := range in {
if _, ipnet, err := net.ParseCIDR(t); err == nil {
if ipv4 := ipnet.IP.To4(); ipv4 != nil {
*d = append(*d, net.IPNet{IP: ipv4, Mask: ipnet.Mask[len(ipnet.Mask)-4 : len(ipnet.Mask)]})
} else {
*d = append(*d, *ipnet)
}
} else if ip := net.ParseIP(t); ip != nil {
if ipv4 := ip.To4(); ipv4 != nil {
*d = append(*d, net.IPNet{IP: ipv4, Mask: net.CIDRMask(32, 32)})
} else {
*d = append(*d, net.IPNet{IP: ip, Mask: net.CIDRMask(128, 128)})
}
} else {
return fmt.Errorf("unable to parse IP/CIDR '%s'", t)
}
}
return nil
}
// UnmarshalEnv implements env.Unmarshaler.
func (d *IPNetworks) UnmarshalEnv(_ string, v string) error {
byts, _ := json.Marshal(strings.Split(v, ","))
return d.UnmarshalJSON(byts)
}
// ToTrustedProxies converts IPNetworks into a string slice for SetTrustedProxies.
func (d *IPNetworks) ToTrustedProxies() []string {
ret := make([]string, len(*d))
for i, entry := range *d {
ret[i] = entry.String()
}
return ret
}
// Contains checks whether the IP is part of one of the networks.
func (d IPNetworks) Contains(ip net.IP) bool {
for _, network := range d {
if network.Contains(ip) {
return true
}
}
return false
}

66
internal/conf/ips_or_cidrs.go

@ -0,0 +1,66 @@ @@ -0,0 +1,66 @@
package conf
import (
"encoding/json"
"fmt"
"net"
"sort"
"strings"
)
// IPsOrCIDRs is a parameter that contains a list of IPs or CIDRs.
type IPsOrCIDRs []fmt.Stringer
// MarshalJSON implements json.Marshaler.
func (d IPsOrCIDRs) MarshalJSON() ([]byte, error) {
out := make([]string, len(d))
for i, v := range d {
out[i] = v.String()
}
sort.Strings(out)
return json.Marshal(out)
}
// UnmarshalJSON implements json.Unmarshaler.
func (d *IPsOrCIDRs) UnmarshalJSON(b []byte) error {
var in []string
if err := json.Unmarshal(b, &in); err != nil {
return err
}
*d = nil
if len(in) == 0 {
return nil
}
for _, t := range in {
if _, ipnet, err := net.ParseCIDR(t); err == nil {
*d = append(*d, ipnet)
} else if ip := net.ParseIP(t); ip != nil {
*d = append(*d, ip)
} else {
return fmt.Errorf("unable to parse IP/CIDR '%s'", t)
}
}
return nil
}
// UnmarshalEnv implements env.Unmarshaler.
func (d *IPsOrCIDRs) UnmarshalEnv(_ string, v string) error {
byts, _ := json.Marshal(strings.Split(v, ","))
return d.UnmarshalJSON(byts)
}
// ToTrustedProxies converts IPsOrCIDRs into a string slice for SetTrustedProxies.
func (d *IPsOrCIDRs) ToTrustedProxies() []string {
ret := make([]string, len(*d))
for i, entry := range *d {
ret[i] = entry.String()
}
return ret
}

5
internal/conf/log_destination.go

@ -26,8 +26,11 @@ func (d LogDestinations) MarshalJSON() ([]byte, error) { @@ -26,8 +26,11 @@ func (d LogDestinations) MarshalJSON() ([]byte, error) {
case logger.DestinationFile:
v = "file"
default:
case logger.DestinationSyslog:
v = "syslog"
default:
return nil, fmt.Errorf("invalid log destination: %v", p)
}
out[i] = v

5
internal/conf/log_level.go

@ -24,8 +24,11 @@ func (d LogLevel) MarshalJSON() ([]byte, error) { @@ -24,8 +24,11 @@ func (d LogLevel) MarshalJSON() ([]byte, error) {
case LogLevel(logger.Info):
out = "info"
default:
case LogLevel(logger.Debug):
out = "debug"
default:
return nil, fmt.Errorf("invalid log level: %v", d)
}
return json.Marshal(out)

235
internal/conf/path.go

@ -11,11 +11,13 @@ import ( @@ -11,11 +11,13 @@ import (
"time"
"github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v4/pkg/headers"
)
var rePathName = regexp.MustCompile(`^[0-9a-zA-Z_\-/\.~]+$`)
func isValidPathName(name string) error {
// IsValidPathName checks if a path name is valid.
func IsValidPathName(name string) error {
if name == "" {
return fmt.Errorf("cannot be empty")
}
@ -45,41 +47,6 @@ func srtCheckPassphrase(passphrase string) error { @@ -45,41 +47,6 @@ func srtCheckPassphrase(passphrase string) error {
}
}
// FindPathConf returns the configuration corresponding to the given path name.
func FindPathConf(pathConfs map[string]*Path, name string) (string, *Path, []string, error) {
err := isValidPathName(name)
if err != nil {
return "", nil, nil, fmt.Errorf("invalid path name: %w (%s)", err, name)
}
// normal path
if pathConf, ok := pathConfs[name]; ok {
return name, pathConf, nil, nil
}
// regular expression-based path
for pathConfName, pathConf := range pathConfs {
if pathConf.Regexp != nil && pathConfName != "all" && pathConfName != "all_others" {
m := pathConf.Regexp.FindStringSubmatch(name)
if m != nil {
return pathConfName, pathConf, m, nil
}
}
}
// all_others
for pathConfName, pathConf := range pathConfs {
if pathConfName == "all" || pathConfName == "all_others" {
m := pathConf.Regexp.FindStringSubmatch(name)
if m != nil {
return pathConfName, pathConf, m, nil
}
}
}
return "", nil, nil, fmt.Errorf("path '%s' is not configured", name)
}
// Path is a path configuration.
type Path struct {
Regexp *regexp.Regexp `json:"-"` // filled by Check()
@ -95,22 +62,21 @@ type Path struct { @@ -95,22 +62,21 @@ type Path struct {
SRTReadPassphrase string `json:"srtReadPassphrase"`
Fallback string `json:"fallback"`
// Record and playback
// Record
Record bool `json:"record"`
Playback bool `json:"playback"`
RecordPath string `json:"recordPath"`
RecordFormat RecordFormat `json:"recordFormat"`
RecordPartDuration StringDuration `json:"recordPartDuration"`
RecordSegmentDuration StringDuration `json:"recordSegmentDuration"`
RecordDeleteAfter StringDuration `json:"recordDeleteAfter"`
// Authentication (deprecated)
PublishUser *Credential `json:"publishUser,omitempty"` // deprecated
PublishPass *Credential `json:"publishPass,omitempty"` // deprecated
PublishIPs *IPNetworks `json:"publishIPs,omitempty"` // deprecated
ReadUser *Credential `json:"readUser,omitempty"` // deprecated
ReadPass *Credential `json:"readPass,omitempty"` // deprecated
ReadIPs *IPNetworks `json:"readIPs,omitempty"` // deprecated
// Authentication
PublishUser Credential `json:"publishUser"`
PublishPass Credential `json:"publishPass"`
PublishIPs IPsOrCIDRs `json:"publishIPs"`
ReadUser Credential `json:"readUser"`
ReadPass Credential `json:"readPass"`
ReadIPs IPsOrCIDRs `json:"readIPs"`
// Publisher source
OverridePublisher bool `json:"overridePublisher"`
@ -129,39 +95,38 @@ type Path struct { @@ -129,39 +95,38 @@ type Path struct {
SourceRedirect string `json:"sourceRedirect"`
// Raspberry Pi Camera source
RPICameraCamID int `json:"rpiCameraCamID"`
RPICameraWidth int `json:"rpiCameraWidth"`
RPICameraHeight int `json:"rpiCameraHeight"`
RPICameraHFlip bool `json:"rpiCameraHFlip"`
RPICameraVFlip bool `json:"rpiCameraVFlip"`
RPICameraBrightness float64 `json:"rpiCameraBrightness"`
RPICameraContrast float64 `json:"rpiCameraContrast"`
RPICameraSaturation float64 `json:"rpiCameraSaturation"`
RPICameraSharpness float64 `json:"rpiCameraSharpness"`
RPICameraExposure string `json:"rpiCameraExposure"`
RPICameraAWB string `json:"rpiCameraAWB"`
RPICameraAWBGains []float64 `json:"rpiCameraAWBGains"`
RPICameraDenoise string `json:"rpiCameraDenoise"`
RPICameraShutter int `json:"rpiCameraShutter"`
RPICameraMetering string `json:"rpiCameraMetering"`
RPICameraGain float64 `json:"rpiCameraGain"`
RPICameraEV float64 `json:"rpiCameraEV"`
RPICameraROI string `json:"rpiCameraROI"`
RPICameraHDR bool `json:"rpiCameraHDR"`
RPICameraTuningFile string `json:"rpiCameraTuningFile"`
RPICameraMode string `json:"rpiCameraMode"`
RPICameraFPS float64 `json:"rpiCameraFPS"`
RPICameraIDRPeriod int `json:"rpiCameraIDRPeriod"`
RPICameraBitrate int `json:"rpiCameraBitrate"`
RPICameraProfile string `json:"rpiCameraProfile"`
RPICameraLevel string `json:"rpiCameraLevel"`
RPICameraAfMode string `json:"rpiCameraAfMode"`
RPICameraAfRange string `json:"rpiCameraAfRange"`
RPICameraAfSpeed string `json:"rpiCameraAfSpeed"`
RPICameraLensPosition float64 `json:"rpiCameraLensPosition"`
RPICameraAfWindow string `json:"rpiCameraAfWindow"`
RPICameraTextOverlayEnable bool `json:"rpiCameraTextOverlayEnable"`
RPICameraTextOverlay string `json:"rpiCameraTextOverlay"`
RPICameraCamID int `json:"rpiCameraCamID"`
RPICameraWidth int `json:"rpiCameraWidth"`
RPICameraHeight int `json:"rpiCameraHeight"`
RPICameraHFlip bool `json:"rpiCameraHFlip"`
RPICameraVFlip bool `json:"rpiCameraVFlip"`
RPICameraBrightness float64 `json:"rpiCameraBrightness"`
RPICameraContrast float64 `json:"rpiCameraContrast"`
RPICameraSaturation float64 `json:"rpiCameraSaturation"`
RPICameraSharpness float64 `json:"rpiCameraSharpness"`
RPICameraExposure string `json:"rpiCameraExposure"`
RPICameraAWB string `json:"rpiCameraAWB"`
RPICameraDenoise string `json:"rpiCameraDenoise"`
RPICameraShutter int `json:"rpiCameraShutter"`
RPICameraMetering string `json:"rpiCameraMetering"`
RPICameraGain float64 `json:"rpiCameraGain"`
RPICameraEV float64 `json:"rpiCameraEV"`
RPICameraROI string `json:"rpiCameraROI"`
RPICameraHDR bool `json:"rpiCameraHDR"`
RPICameraTuningFile string `json:"rpiCameraTuningFile"`
RPICameraMode string `json:"rpiCameraMode"`
RPICameraFPS float64 `json:"rpiCameraFPS"`
RPICameraIDRPeriod int `json:"rpiCameraIDRPeriod"`
RPICameraBitrate int `json:"rpiCameraBitrate"`
RPICameraProfile string `json:"rpiCameraProfile"`
RPICameraLevel string `json:"rpiCameraLevel"`
RPICameraAfMode string `json:"rpiCameraAfMode"`
RPICameraAfRange string `json:"rpiCameraAfRange"`
RPICameraAfSpeed string `json:"rpiCameraAfSpeed"`
RPICameraLensPosition float64 `json:"rpiCameraLensPosition"`
RPICameraAfWindow string `json:"rpiCameraAfWindow"`
RPICameraTextOverlayEnable bool `json:"rpiCameraTextOverlayEnable"`
RPICameraTextOverlay string `json:"rpiCameraTextOverlay"`
// Hooks
RunOnInit string `json:"runOnInit"`
@ -187,8 +152,7 @@ func (pconf *Path) setDefaults() { @@ -187,8 +152,7 @@ func (pconf *Path) setDefaults() {
pconf.SourceOnDemandStartTimeout = 10 * StringDuration(time.Second)
pconf.SourceOnDemandCloseAfter = 10 * StringDuration(time.Second)
// Record and playback
pconf.Playback = true
// Record
pconf.RecordPath = "./recordings/%path/%Y-%m-%d_%H-%M-%S-%f"
pconf.RecordFormat = RecordFormatFMP4
pconf.RecordPartDuration = 100 * StringDuration(time.Millisecond)
@ -206,7 +170,6 @@ func (pconf *Path) setDefaults() { @@ -206,7 +170,6 @@ func (pconf *Path) setDefaults() {
pconf.RPICameraSharpness = 1
pconf.RPICameraExposure = "normal"
pconf.RPICameraAWB = "auto"
pconf.RPICameraAWBGains = []float64{0, 0}
pconf.RPICameraDenoise = "off"
pconf.RPICameraMetering = "centre"
pconf.RPICameraFPS = 30
@ -249,11 +212,7 @@ func (pconf Path) Clone() *Path { @@ -249,11 +212,7 @@ func (pconf Path) Clone() *Path {
return &dest
}
func (pconf *Path) validate(
conf *Conf,
name string,
deprecatedCredentialsMode bool,
) error {
func (pconf *Path) check(conf *Conf, name string) error {
pconf.Name = name
switch {
@ -261,7 +220,7 @@ func (pconf *Path) validate( @@ -261,7 +220,7 @@ func (pconf *Path) validate(
pconf.Regexp = regexp.MustCompile("^.*$")
case name == "" || name[0] != '~': // normal path
err := isValidPathName(name)
err := IsValidPathName(name)
if err != nil {
return fmt.Errorf("invalid path name '%s': %w", name, err)
}
@ -366,7 +325,7 @@ func (pconf *Path) validate( @@ -366,7 +325,7 @@ func (pconf *Path) validate(
}
if pconf.Fallback != "" {
if strings.HasPrefix(pconf.Fallback, "/") {
err := isValidPathName(pconf.Fallback[1:])
err := IsValidPathName(pconf.Fallback[1:])
if err != nil {
return fmt.Errorf("'%s': %w", pconf.Fallback, err)
}
@ -378,72 +337,39 @@ func (pconf *Path) validate( @@ -378,72 +337,39 @@ func (pconf *Path) validate(
}
}
// Authentication (deprecated)
// Authentication
if deprecatedCredentialsMode {
func() {
var user Credential = "any"
if credentialIsNotEmpty(pconf.PublishUser) {
user = *pconf.PublishUser
}
var pass Credential
if credentialIsNotEmpty(pconf.PublishPass) {
pass = *pconf.PublishPass
}
ips := IPNetworks{mustParseCIDR("0.0.0.0/0")}
if ipNetworkIsNotEmpty(pconf.PublishIPs) {
ips = *pconf.PublishIPs
}
pathName := name
if name == "all_others" || name == "all" {
pathName = "~^.*$"
}
conf.AuthInternalUsers = append(conf.AuthInternalUsers, AuthInternalUser{
User: user,
Pass: pass,
IPs: ips,
Permissions: []AuthInternalUserPermission{{
Action: AuthActionPublish,
Path: pathName,
}},
})
}()
func() {
var user Credential = "any"
if credentialIsNotEmpty(pconf.ReadUser) {
user = *pconf.ReadUser
}
var pass Credential
if credentialIsNotEmpty(pconf.ReadPass) {
pass = *pconf.ReadPass
}
ips := IPNetworks{mustParseCIDR("0.0.0.0/0")}
if ipNetworkIsNotEmpty(pconf.ReadIPs) {
ips = *pconf.ReadIPs
}
pathName := name
if name == "all_others" || name == "all" {
pathName = "~^.*$"
}
conf.AuthInternalUsers = append(conf.AuthInternalUsers, AuthInternalUser{
User: user,
Pass: pass,
IPs: ips,
Permissions: []AuthInternalUserPermission{{
Action: AuthActionRead,
Path: pathName,
}},
})
}()
if (!pconf.PublishUser.IsEmpty() && pconf.PublishPass.IsEmpty()) ||
(pconf.PublishUser.IsEmpty() && !pconf.PublishPass.IsEmpty()) {
return fmt.Errorf("read username and password must be both filled")
}
if !pconf.PublishUser.IsEmpty() && pconf.Source != "publisher" {
return fmt.Errorf("'publishUser' is useless when source is not 'publisher', since " +
"the stream is not provided by a publisher, but by a fixed source")
}
if len(pconf.PublishIPs) > 0 && pconf.Source != "publisher" {
return fmt.Errorf("'publishIPs' is useless when source is not 'publisher', since " +
"the stream is not provided by a publisher, but by a fixed source")
}
if (!pconf.ReadUser.IsEmpty() && pconf.ReadPass.IsEmpty()) ||
(pconf.ReadUser.IsEmpty() && !pconf.ReadPass.IsEmpty()) {
return fmt.Errorf("read username and password must be both filled")
}
if contains(conf.AuthMethods, headers.AuthDigest) {
if pconf.PublishUser.IsHashed() ||
pconf.PublishPass.IsHashed() ||
pconf.ReadUser.IsHashed() ||
pconf.ReadPass.IsHashed() {
return fmt.Errorf("hashed credentials can't be used when the digest auth method is available")
}
}
if conf.ExternalAuthenticationURL != "" {
if !pconf.PublishUser.IsEmpty() ||
len(pconf.PublishIPs) > 0 ||
!pconf.ReadUser.IsEmpty() ||
len(pconf.ReadIPs) > 0 {
return fmt.Errorf("credentials or IPs can't be used together with 'externalAuthenticationURL'")
}
}
// Publisher source
@ -505,9 +431,6 @@ func (pconf *Path) validate( @@ -505,9 +431,6 @@ func (pconf *Path) validate(
default:
return fmt.Errorf("invalid 'rpiCameraAWB' value")
}
if len(pconf.RPICameraAWBGains) != 2 {
return fmt.Errorf("invalid 'rpiCameraAWBGains' value")
}
switch pconf.RPICameraDenoise {
case "off", "cdn_off", "cdn_fast", "cdn_hq":
default:

5
internal/conf/protocol.go

@ -30,8 +30,11 @@ func (d Protocols) MarshalJSON() ([]byte, error) { @@ -30,8 +30,11 @@ func (d Protocols) MarshalJSON() ([]byte, error) {
case Protocol(gortsplib.TransportUDPMulticast):
v = "multicast"
default:
case Protocol(gortsplib.TransportTCP):
v = "tcp"
default:
return nil, fmt.Errorf("invalid protocol: %v", p)
}
out[i] = v

63
internal/conf/rtsp_auth_methods.go

@ -1,63 +0,0 @@ @@ -1,63 +0,0 @@
package conf
import (
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/bluenviron/gortsplib/v4/pkg/headers"
)
// RTSPAuthMethods is the rtspAuthMethods parameter.
type RTSPAuthMethods []headers.AuthMethod
// MarshalJSON implements json.Marshaler.
func (d RTSPAuthMethods) MarshalJSON() ([]byte, error) {
out := make([]string, len(d))
for i, v := range d {
switch v {
case headers.AuthBasic:
out[i] = "basic"
default:
out[i] = "digest"
}
}
sort.Strings(out)
return json.Marshal(out)
}
// UnmarshalJSON implements json.Unmarshaler.
func (d *RTSPAuthMethods) UnmarshalJSON(b []byte) error {
var in []string
if err := json.Unmarshal(b, &in); err != nil {
return err
}
*d = nil
for _, v := range in {
switch v {
case "basic":
*d = append(*d, headers.AuthBasic)
case "digest":
*d = append(*d, headers.AuthDigestMD5)
default:
return fmt.Errorf("invalid authentication method: '%s'", v)
}
}
return nil
}
// UnmarshalEnv implements env.Unmarshaler.
func (d *RTSPAuthMethods) UnmarshalEnv(_ string, v string) error {
byts, _ := json.Marshal(strings.Split(v, ","))
return d.UnmarshalJSON(byts)
}

5
internal/conf/rtsp_range_type.go

@ -30,8 +30,11 @@ func (d RTSPRangeType) MarshalJSON() ([]byte, error) { @@ -30,8 +30,11 @@ func (d RTSPRangeType) MarshalJSON() ([]byte, error) {
case RTSPRangeTypeSMPTE:
out = "smpte"
default:
case RTSPRangeTypeUndefined:
out = ""
default:
return nil, fmt.Errorf("invalid rtsp range type: %v", d)
}
return json.Marshal(out)

5
internal/conf/rtsp_transport.go

@ -26,8 +26,11 @@ func (d RTSPTransport) MarshalJSON() ([]byte, error) { @@ -26,8 +26,11 @@ func (d RTSPTransport) MarshalJSON() ([]byte, error) {
case gortsplib.TransportUDPMulticast:
out = "multicast"
default:
case gortsplib.TransportTCP:
out = "tcp"
default:
return nil, fmt.Errorf("invalid protocol: %v", d.Transport)
}
}

2
internal/conf/string_size.go

@ -25,8 +25,8 @@ func (s *StringSize) UnmarshalJSON(b []byte) error { @@ -25,8 +25,8 @@ func (s *StringSize) UnmarshalJSON(b []byte) error {
if err != nil {
return err
}
*s = StringSize(v)
*s = StringSize(v)
return nil
}

7
internal/conf/webrtc_ice_server.go

@ -2,8 +2,7 @@ package conf @@ -2,8 +2,7 @@ package conf
// WebRTCICEServer is a WebRTC ICE Server.
type WebRTCICEServer struct {
URL string `json:"url"`
Username string `json:"username"`
Password string `json:"password"`
ClientOnly bool `json:"clientOnly"`
URL string `json:"url"`
Username string `json:"username"`
Password string `json:"password"`
}

24
internal/confwatcher/confwatcher_test.go

@ -5,17 +5,31 @@ import ( @@ -5,17 +5,31 @@ import (
"testing"
"time"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require"
)
func writeTempFile(byts []byte) (string, error) {
tmpf, err := os.CreateTemp(os.TempDir(), "confwatcher-")
if err != nil {
return "", err
}
defer tmpf.Close()
_, err = tmpf.Write(byts)
if err != nil {
return "", err
}
return tmpf.Name(), nil
}
func TestNoFile(t *testing.T) {
_, err := New("/nonexistent")
require.Error(t, err)
}
func TestWrite(t *testing.T) {
fpath, err := test.CreateTempFile([]byte("{}"))
fpath, err := writeTempFile([]byte("{}"))
require.NoError(t, err)
w, err := New(fpath)
@ -40,7 +54,7 @@ func TestWrite(t *testing.T) { @@ -40,7 +54,7 @@ func TestWrite(t *testing.T) {
}
func TestWriteMultipleTimes(t *testing.T) {
fpath, err := test.CreateTempFile([]byte("{}"))
fpath, err := writeTempFile([]byte("{}"))
require.NoError(t, err)
w, err := New(fpath)
@ -83,7 +97,7 @@ func TestWriteMultipleTimes(t *testing.T) { @@ -83,7 +97,7 @@ func TestWriteMultipleTimes(t *testing.T) {
}
func TestDeleteCreate(t *testing.T) {
fpath, err := test.CreateTempFile([]byte("{}"))
fpath, err := writeTempFile([]byte("{}"))
require.NoError(t, err)
w, err := New(fpath)
@ -111,7 +125,7 @@ func TestDeleteCreate(t *testing.T) { @@ -111,7 +125,7 @@ func TestDeleteCreate(t *testing.T) {
}
func TestSymlinkDeleteCreate(t *testing.T) {
fpath, err := test.CreateTempFile([]byte("{}"))
fpath, err := writeTempFile([]byte("{}"))
require.NoError(t, err)
err = os.Symlink(fpath, fpath+"-sym")

984
internal/core/api_test.go

File diff suppressed because it is too large Load Diff

126
internal/core/auth.go

@ -0,0 +1,126 @@ @@ -0,0 +1,126 @@
package core
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/bluenviron/gortsplib/v4/pkg/auth"
"github.com/bluenviron/gortsplib/v4/pkg/headers"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
)
func doExternalAuthentication(
ur string,
accessRequest defs.PathAccessRequest,
) error {
enc, _ := json.Marshal(struct {
IP string `json:"ip"`
User string `json:"user"`
Password string `json:"password"`
Path string `json:"path"`
Protocol string `json:"protocol"`
ID *uuid.UUID `json:"id"`
Action string `json:"action"`
Query string `json:"query"`
}{
IP: accessRequest.IP.String(),
User: accessRequest.User,
Password: accessRequest.Pass,
Path: accessRequest.Name,
Protocol: string(accessRequest.Proto),
ID: accessRequest.ID,
Action: func() string {
if accessRequest.Publish {
return "publish"
}
return "read"
}(),
Query: accessRequest.Query,
})
res, err := http.Post(ur, "application/json", bytes.NewReader(enc))
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode > 299 {
if resBody, err := io.ReadAll(res.Body); err == nil && len(resBody) != 0 {
return fmt.Errorf("server replied with code %d: %s", res.StatusCode, string(resBody))
}
return fmt.Errorf("server replied with code %d", res.StatusCode)
}
return nil
}
func doAuthentication(
externalAuthenticationURL string,
rtspAuthMethods conf.AuthMethods,
pathConf *conf.Path,
accessRequest defs.PathAccessRequest,
) error {
var rtspAuth headers.Authorization
if accessRequest.RTSPRequest != nil {
err := rtspAuth.Unmarshal(accessRequest.RTSPRequest.Header["Authorization"])
if err == nil && rtspAuth.Method == headers.AuthBasic {
accessRequest.User = rtspAuth.BasicUser
accessRequest.Pass = rtspAuth.BasicPass
}
}
if externalAuthenticationURL != "" {
err := doExternalAuthentication(
externalAuthenticationURL,
accessRequest,
)
if err != nil {
return defs.AuthenticationError{Message: fmt.Sprintf("external authentication failed: %s", err)}
}
}
var pathIPs conf.IPsOrCIDRs
var pathUser conf.Credential
var pathPass conf.Credential
if accessRequest.Publish {
pathIPs = pathConf.PublishIPs
pathUser = pathConf.PublishUser
pathPass = pathConf.PublishPass
} else {
pathIPs = pathConf.ReadIPs
pathUser = pathConf.ReadUser
pathPass = pathConf.ReadPass
}
if pathIPs != nil {
if !ipEqualOrInRange(accessRequest.IP, pathIPs) {
return defs.AuthenticationError{Message: fmt.Sprintf("IP %s not allowed", accessRequest.IP)}
}
}
if !pathUser.IsEmpty() {
if accessRequest.RTSPRequest != nil && rtspAuth.Method == headers.AuthDigest {
err := auth.Validate(
accessRequest.RTSPRequest,
pathUser.GetValue(),
pathPass.GetValue(),
accessRequest.RTSPBaseURL,
rtspAuthMethods,
"IPCAM",
accessRequest.RTSPNonce)
if err != nil {
return defs.AuthenticationError{Message: err.Error()}
}
} else if !pathUser.Check(accessRequest.User) || !pathPass.Check(accessRequest.Pass) {
return defs.AuthenticationError{Message: "invalid credentials"}
}
}
return nil
}

205
internal/core/core.go

@ -17,13 +17,11 @@ import ( @@ -17,13 +17,11 @@ import (
"github.com/gin-gonic/gin"
"github.com/bluenviron/mediamtx/internal/api"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/confwatcher"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/metrics"
"github.com/bluenviron/mediamtx/internal/playback"
"github.com/bluenviron/mediamtx/internal/pprof"
"github.com/bluenviron/mediamtx/internal/record"
"github.com/bluenviron/mediamtx/internal/rlimit"
@ -50,7 +48,7 @@ func gatherCleanerEntries(paths map[string]*conf.Path) []record.CleanerEntry { @@ -50,7 +48,7 @@ func gatherCleanerEntries(paths map[string]*conf.Path) []record.CleanerEntry {
for _, pa := range paths {
if pa.Record && pa.RecordDeleteAfter != 0 {
entry := record.CleanerEntry{
Path: pa.RecordPath,
PathFormat: pa.RecordPath,
Format: pa.RecordFormat,
DeleteAfter: time.Duration(pa.RecordDeleteAfter),
}
@ -67,8 +65,8 @@ func gatherCleanerEntries(paths map[string]*conf.Path) []record.CleanerEntry { @@ -67,8 +65,8 @@ func gatherCleanerEntries(paths map[string]*conf.Path) []record.CleanerEntry {
}
sort.Slice(out2, func(i, j int) bool {
if out2[i].Path != out2[j].Path {
return out2[i].Path < out2[j].Path
if out2[i].PathFormat != out2[j].PathFormat {
return out2[i].PathFormat < out2[j].PathFormat
}
return out2[i].DeleteAfter < out2[j].DeleteAfter
})
@ -89,11 +87,9 @@ type Core struct { @@ -89,11 +87,9 @@ type Core struct {
conf *conf.Conf
logger *logger.Logger
externalCmdPool *externalcmd.Pool
authManager *auth.Manager
metrics *metrics.Metrics
pprof *pprof.PPROF
recordCleaner *record.Cleaner
playbackServer *playback.Server
pathManager *pathManager
rtspServer *rtsp.Server
rtspsServer *rtsp.Server
@ -280,46 +276,30 @@ func (p *Core) createResources(initial bool) error { @@ -280,46 +276,30 @@ func (p *Core) createResources(initial bool) error {
p.externalCmdPool = externalcmd.NewPool()
}
if p.authManager == nil {
p.authManager = &auth.Manager{
Method: p.conf.AuthMethod,
InternalUsers: p.conf.AuthInternalUsers,
HTTPAddress: p.conf.AuthHTTPAddress,
HTTPExclude: p.conf.AuthHTTPExclude,
JWTJWKS: p.conf.AuthJWTJWKS,
ReadTimeout: time.Duration(p.conf.ReadTimeout),
RTSPAuthMethods: p.conf.RTSPAuthMethods,
}
}
if p.conf.Metrics &&
p.metrics == nil {
i := &metrics.Metrics{
p.metrics = &metrics.Metrics{
Address: p.conf.MetricsAddress,
ReadTimeout: p.conf.ReadTimeout,
AuthManager: p.authManager,
Parent: p,
}
err := i.Initialize()
err := p.metrics.Initialize()
if err != nil {
return err
}
p.metrics = i
}
if p.conf.PPROF &&
p.pprof == nil {
i := &pprof.PPROF{
p.pprof = &pprof.PPROF{
Address: p.conf.PPROFAddress,
ReadTimeout: p.conf.ReadTimeout,
AuthManager: p.authManager,
Parent: p,
}
err := i.Initialize()
err := p.pprof.Initialize()
if err != nil {
return err
}
p.pprof = i
}
cleanerEntries := gatherCleanerEntries(p.conf.Paths)
@ -332,36 +312,20 @@ func (p *Core) createResources(initial bool) error { @@ -332,36 +312,20 @@ func (p *Core) createResources(initial bool) error {
p.recordCleaner.Initialize()
}
if p.conf.Playback &&
p.playbackServer == nil {
i := &playback.Server{
Address: p.conf.PlaybackAddress,
ReadTimeout: p.conf.ReadTimeout,
PathConfs: p.conf.Paths,
AuthManager: p.authManager,
Parent: p,
}
err := i.Initialize()
if err != nil {
return err
}
p.playbackServer = i
}
if p.pathManager == nil {
p.pathManager = &pathManager{
logLevel: p.conf.LogLevel,
authManager: p.authManager,
rtspAddress: p.conf.RTSPAddress,
readTimeout: p.conf.ReadTimeout,
writeTimeout: p.conf.WriteTimeout,
writeQueueSize: p.conf.WriteQueueSize,
udpMaxPayloadSize: p.conf.UDPMaxPayloadSize,
pathConfs: p.conf.Paths,
externalCmdPool: p.externalCmdPool,
parent: p,
}
p.pathManager.initialize()
p.pathManager = newPathManager(
p.conf.LogLevel,
p.conf.ExternalAuthenticationURL,
p.conf.RTSPAddress,
p.conf.AuthMethods,
p.conf.ReadTimeout,
p.conf.WriteTimeout,
p.conf.WriteQueueSize,
p.conf.UDPMaxPayloadSize,
p.conf.Paths,
p.externalCmdPool,
p,
)
if p.metrics != nil {
p.metrics.SetPathManager(p.pathManager)
@ -375,9 +339,9 @@ func (p *Core) createResources(initial bool) error { @@ -375,9 +339,9 @@ func (p *Core) createResources(initial bool) error {
_, useUDP := p.conf.Protocols[conf.Protocol(gortsplib.TransportUDP)]
_, useMulticast := p.conf.Protocols[conf.Protocol(gortsplib.TransportUDPMulticast)]
i := &rtsp.Server{
p.rtspServer = &rtsp.Server{
Address: p.conf.RTSPAddress,
AuthMethods: p.conf.RTSPAuthMethods,
AuthMethods: p.conf.AuthMethods,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
WriteQueueSize: p.conf.WriteQueueSize,
@ -400,11 +364,10 @@ func (p *Core) createResources(initial bool) error { @@ -400,11 +364,10 @@ func (p *Core) createResources(initial bool) error {
PathManager: p.pathManager,
Parent: p,
}
err := i.Initialize()
err := p.rtspServer.Initialize()
if err != nil {
return err
}
p.rtspServer = i
if p.metrics != nil {
p.metrics.SetRTSPServer(p.rtspServer)
@ -415,9 +378,9 @@ func (p *Core) createResources(initial bool) error { @@ -415,9 +378,9 @@ func (p *Core) createResources(initial bool) error {
(p.conf.Encryption == conf.EncryptionStrict ||
p.conf.Encryption == conf.EncryptionOptional) &&
p.rtspsServer == nil {
i := &rtsp.Server{
p.rtspsServer = &rtsp.Server{
Address: p.conf.RTSPSAddress,
AuthMethods: p.conf.RTSPAuthMethods,
AuthMethods: p.conf.AuthMethods,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
WriteQueueSize: p.conf.WriteQueueSize,
@ -440,11 +403,10 @@ func (p *Core) createResources(initial bool) error { @@ -440,11 +403,10 @@ func (p *Core) createResources(initial bool) error {
PathManager: p.pathManager,
Parent: p,
}
err := i.Initialize()
err := p.rtspsServer.Initialize()
if err != nil {
return err
}
p.rtspsServer = i
if p.metrics != nil {
p.metrics.SetRTSPSServer(p.rtspsServer)
@ -455,7 +417,7 @@ func (p *Core) createResources(initial bool) error { @@ -455,7 +417,7 @@ func (p *Core) createResources(initial bool) error {
(p.conf.RTMPEncryption == conf.EncryptionNo ||
p.conf.RTMPEncryption == conf.EncryptionOptional) &&
p.rtmpServer == nil {
i := &rtmp.Server{
p.rtmpServer = &rtmp.Server{
Address: p.conf.RTMPAddress,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
@ -471,11 +433,10 @@ func (p *Core) createResources(initial bool) error { @@ -471,11 +433,10 @@ func (p *Core) createResources(initial bool) error {
PathManager: p.pathManager,
Parent: p,
}
err := i.Initialize()
err := p.rtmpServer.Initialize()
if err != nil {
return err
}
p.rtmpServer = i
if p.metrics != nil {
p.metrics.SetRTMPServer(p.rtmpServer)
@ -486,7 +447,7 @@ func (p *Core) createResources(initial bool) error { @@ -486,7 +447,7 @@ func (p *Core) createResources(initial bool) error {
(p.conf.RTMPEncryption == conf.EncryptionStrict ||
p.conf.RTMPEncryption == conf.EncryptionOptional) &&
p.rtmpsServer == nil {
i := &rtmp.Server{
p.rtmpsServer = &rtmp.Server{
Address: p.conf.RTMPSAddress,
ReadTimeout: p.conf.ReadTimeout,
WriteTimeout: p.conf.WriteTimeout,
@ -502,11 +463,10 @@ func (p *Core) createResources(initial bool) error { @@ -502,11 +463,10 @@ func (p *Core) createResources(initial bool) error {
PathManager: p.pathManager,
Parent: p,
}
err := i.Initialize()
err := p.rtmpsServer.Initialize()
if err != nil {
return err
}
p.rtmpsServer = i
if p.metrics != nil {
p.metrics.SetRTMPSServer(p.rtmpsServer)
@ -515,30 +475,30 @@ func (p *Core) createResources(initial bool) error { @@ -515,30 +475,30 @@ func (p *Core) createResources(initial bool) error {
if p.conf.HLS &&
p.hlsServer == nil {
i := &hls.Server{
Address: p.conf.HLSAddress,
Encryption: p.conf.HLSEncryption,
ServerKey: p.conf.HLSServerKey,
ServerCert: p.conf.HLSServerCert,
AlwaysRemux: p.conf.HLSAlwaysRemux,
Variant: p.conf.HLSVariant,
SegmentCount: p.conf.HLSSegmentCount,
SegmentDuration: p.conf.HLSSegmentDuration,
PartDuration: p.conf.HLSPartDuration,
SegmentMaxSize: p.conf.HLSSegmentMaxSize,
AllowOrigin: p.conf.HLSAllowOrigin,
TrustedProxies: p.conf.HLSTrustedProxies,
Directory: p.conf.HLSDirectory,
ReadTimeout: p.conf.ReadTimeout,
WriteQueueSize: p.conf.WriteQueueSize,
PathManager: p.pathManager,
Parent: p,
}
err := i.Initialize()
p.hlsServer = &hls.Server{
Address: p.conf.HLSAddress,
Encryption: p.conf.HLSEncryption,
ServerKey: p.conf.HLSServerKey,
ServerCert: p.conf.HLSServerCert,
ExternalAuthenticationURL: p.conf.ExternalAuthenticationURL,
AlwaysRemux: p.conf.HLSAlwaysRemux,
Variant: p.conf.HLSVariant,
SegmentCount: p.conf.HLSSegmentCount,
SegmentDuration: p.conf.HLSSegmentDuration,
PartDuration: p.conf.HLSPartDuration,
SegmentMaxSize: p.conf.HLSSegmentMaxSize,
AllowOrigin: p.conf.HLSAllowOrigin,
TrustedProxies: p.conf.HLSTrustedProxies,
Directory: p.conf.HLSDirectory,
ReadTimeout: p.conf.ReadTimeout,
WriteQueueSize: p.conf.WriteQueueSize,
PathManager: p.pathManager,
Parent: p,
}
err := p.hlsServer.Initialize()
if err != nil {
return err
}
p.hlsServer = i
p.pathManager.setHLSServer(p.hlsServer)
@ -549,7 +509,7 @@ func (p *Core) createResources(initial bool) error { @@ -549,7 +509,7 @@ func (p *Core) createResources(initial bool) error {
if p.conf.WebRTC &&
p.webRTCServer == nil {
i := &webrtc.Server{
p.webRTCServer = &webrtc.Server{
Address: p.conf.WebRTCAddress,
Encryption: p.conf.WebRTCEncryption,
ServerKey: p.conf.WebRTCServerKey,
@ -568,11 +528,11 @@ func (p *Core) createResources(initial bool) error { @@ -568,11 +528,11 @@ func (p *Core) createResources(initial bool) error {
PathManager: p.pathManager,
Parent: p,
}
err := i.Initialize()
err := p.webRTCServer.Initialize()
if err != nil {
p.webRTCServer = nil
return err
}
p.webRTCServer = i
if p.metrics != nil {
p.metrics.SetWebRTCServer(p.webRTCServer)
@ -581,7 +541,7 @@ func (p *Core) createResources(initial bool) error { @@ -581,7 +541,7 @@ func (p *Core) createResources(initial bool) error {
if p.conf.SRT &&
p.srtServer == nil {
i := &srt.Server{
p.srtServer = &srt.Server{
Address: p.conf.SRTAddress,
RTSPAddress: p.conf.RTSPAddress,
ReadTimeout: p.conf.ReadTimeout,
@ -595,11 +555,10 @@ func (p *Core) createResources(initial bool) error { @@ -595,11 +555,10 @@ func (p *Core) createResources(initial bool) error {
PathManager: p.pathManager,
Parent: p,
}
err := i.Initialize()
err := p.srtServer.Initialize()
if err != nil {
return err
}
p.srtServer = i
if p.metrics != nil {
p.metrics.SetSRTServer(p.srtServer)
@ -608,11 +567,10 @@ func (p *Core) createResources(initial bool) error { @@ -608,11 +567,10 @@ func (p *Core) createResources(initial bool) error {
if p.conf.API &&
p.api == nil {
i := &api.API{
p.api = &api.API{
Address: p.conf.APIAddress,
ReadTimeout: p.conf.ReadTimeout,
Conf: p.conf,
AuthManager: p.authManager,
PathManager: p.pathManager,
RTSPServer: p.rtspServer,
RTSPSServer: p.rtspsServer,
@ -623,11 +581,10 @@ func (p *Core) createResources(initial bool) error { @@ -623,11 +581,10 @@ func (p *Core) createResources(initial bool) error {
SRTServer: p.srtServer,
Parent: p,
}
err := i.Initialize()
err := p.api.Initialize()
if err != nil {
return err
}
p.api = i
}
if initial && p.confPath != "" {
@ -646,65 +603,42 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) { @@ -646,65 +603,42 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) {
!reflect.DeepEqual(newConf.LogDestinations, p.conf.LogDestinations) ||
newConf.LogFile != p.conf.LogFile
closeAuthManager := newConf == nil ||
newConf.AuthMethod != p.conf.AuthMethod ||
newConf.AuthHTTPAddress != p.conf.AuthHTTPAddress ||
!reflect.DeepEqual(newConf.AuthHTTPExclude, p.conf.AuthHTTPExclude) ||
newConf.AuthJWTJWKS != p.conf.AuthJWTJWKS ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
!reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods)
if !closeAuthManager && !reflect.DeepEqual(newConf.AuthInternalUsers, p.conf.AuthInternalUsers) {
p.authManager.ReloadInternalUsers(newConf.AuthInternalUsers)
}
closeMetrics := newConf == nil ||
newConf.Metrics != p.conf.Metrics ||
newConf.MetricsAddress != p.conf.MetricsAddress ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
closeAuthManager ||
closeLogger
closePPROF := newConf == nil ||
newConf.PPROF != p.conf.PPROF ||
newConf.PPROFAddress != p.conf.PPROFAddress ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
closeAuthManager ||
closeLogger
closeRecorderCleaner := newConf == nil ||
!reflect.DeepEqual(gatherCleanerEntries(newConf.Paths), gatherCleanerEntries(p.conf.Paths)) ||
closeLogger
closePlaybackServer := newConf == nil ||
newConf.Playback != p.conf.Playback ||
newConf.PlaybackAddress != p.conf.PlaybackAddress ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
closeAuthManager ||
closeLogger
if !closePlaybackServer && p.playbackServer != nil && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) {
p.playbackServer.ReloadPathConfs(newConf.Paths)
}
closePathManager := newConf == nil ||
newConf.LogLevel != p.conf.LogLevel ||
newConf.ExternalAuthenticationURL != p.conf.ExternalAuthenticationURL ||
newConf.RTSPAddress != p.conf.RTSPAddress ||
!reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) ||
!reflect.DeepEqual(newConf.AuthMethods, p.conf.AuthMethods) ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.WriteQueueSize != p.conf.WriteQueueSize ||
newConf.UDPMaxPayloadSize != p.conf.UDPMaxPayloadSize ||
closeMetrics ||
closeAuthManager ||
closeLogger
if !closePathManager && !reflect.DeepEqual(newConf.Paths, p.conf.Paths) {
p.pathManager.ReloadPathConfs(newConf.Paths)
p.pathManager.ReloadConf(newConf.Paths)
}
closeRTSPServer := newConf == nil ||
newConf.RTSP != p.conf.RTSP ||
newConf.Encryption != p.conf.Encryption ||
newConf.RTSPAddress != p.conf.RTSPAddress ||
!reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) ||
!reflect.DeepEqual(newConf.AuthMethods, p.conf.AuthMethods) ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.WriteQueueSize != p.conf.WriteQueueSize ||
@ -727,7 +661,7 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) { @@ -727,7 +661,7 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) {
newConf.RTSP != p.conf.RTSP ||
newConf.Encryption != p.conf.Encryption ||
newConf.RTSPSAddress != p.conf.RTSPSAddress ||
!reflect.DeepEqual(newConf.RTSPAuthMethods, p.conf.RTSPAuthMethods) ||
!reflect.DeepEqual(newConf.AuthMethods, p.conf.AuthMethods) ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
newConf.WriteTimeout != p.conf.WriteTimeout ||
newConf.WriteQueueSize != p.conf.WriteQueueSize ||
@ -780,6 +714,7 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) { @@ -780,6 +714,7 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) {
newConf.HLSEncryption != p.conf.HLSEncryption ||
newConf.HLSServerKey != p.conf.HLSServerKey ||
newConf.HLSServerCert != p.conf.HLSServerCert ||
newConf.ExternalAuthenticationURL != p.conf.ExternalAuthenticationURL ||
newConf.HLSAlwaysRemux != p.conf.HLSAlwaysRemux ||
newConf.HLSVariant != p.conf.HLSVariant ||
newConf.HLSSegmentCount != p.conf.HLSSegmentCount ||
@ -833,7 +768,6 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) { @@ -833,7 +768,6 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) {
newConf.API != p.conf.API ||
newConf.APIAddress != p.conf.APIAddress ||
newConf.ReadTimeout != p.conf.ReadTimeout ||
closeAuthManager ||
closePathManager ||
closeRTSPServer ||
closeRTSPSServer ||
@ -931,11 +865,6 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) { @@ -931,11 +865,6 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) {
p.pathManager = nil
}
if closePlaybackServer && p.playbackServer != nil {
p.playbackServer.Close()
p.playbackServer = nil
}
if closeRecorderCleaner && p.recordCleaner != nil {
p.recordCleaner.Close()
p.recordCleaner = nil
@ -951,16 +880,12 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) { @@ -951,16 +880,12 @@ func (p *Core) closeResources(newConf *conf.Conf, calledByAPI bool) {
p.metrics = nil
}
if closeAuthManager && p.authManager != nil {
p.authManager = nil
}
if newConf == nil && p.externalCmdPool != nil {
p.Log(logger.Info, "waiting for running hooks")
p.externalCmdPool.Close()
}
if closeLogger && p.logger != nil {
if closeLogger {
p.logger.Close()
p.logger = nil
}

146
internal/core/core_test.go

@ -8,16 +8,82 @@ import ( @@ -8,16 +8,82 @@ import (
"github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require"
)
var serverCert = []byte(`-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwIBAgIUXw1hEC3LFpTsllv7D3ARJyEq7sIwDQYJKoZIhvcNAQEL
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yMDEyMTMxNzQ0NThaFw0zMDEy
MTExNzQ0NThaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw
HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQDG8DyyS51810GsGwgWr5rjJK7OE1kTTLSNEEKax8Bj
zOyiaz8rA2JGl2VUEpi2UjDr9Cm7nd+YIEVs91IIBOb7LGqObBh1kGF3u5aZxLkv
NJE+HrLVvUhaDobK2NU+Wibqc/EI3DfUkt1rSINvv9flwTFu1qHeuLWhoySzDKEp
OzYxpFhwjVSokZIjT4Red3OtFz7gl2E6OAWe2qoh5CwLYVdMWtKR0Xuw3BkDPk9I
qkQKx3fqv97LPEzhyZYjDT5WvGrgZ1WDAN3booxXF3oA1H3GHQc4m/vcLatOtb8e
nI59gMQLEbnp08cl873bAuNuM95EZieXTHNbwUnq5iybAgMBAAGjUzBRMB0GA1Ud
DgQWBBQBKhJh8eWu0a4au9X/2fKhkFX2vjAfBgNVHSMEGDAWgBQBKhJh8eWu0a4a
u9X/2fKhkFX2vjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBj
3aCW0YPKukYgVK9cwN0IbVy/D0C1UPT4nupJcy/E0iC7MXPZ9D/SZxYQoAkdptdO
xfI+RXkpQZLdODNx9uvV+cHyZHZyjtE5ENu/i5Rer2cWI/mSLZm5lUQyx+0KZ2Yu
tEI1bsebDK30msa8QSTn0WidW9XhFnl3gRi4wRdimcQapOWYVs7ih+nAlSvng7NI
XpAyRs8PIEbpDDBMWnldrX4TP6EWYUi49gCp8OUDRREKX3l6Ls1vZ02F34yHIt/7
7IV/XSKG096bhW+icKBWV0IpcEsgTzPK1J1hMxgjhzIMxGboAeUU+kidthOob6Sd
XQxaORfgM//NzX9LhUPk
-----END CERTIFICATE-----
`)
var serverKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAxvA8skudfNdBrBsIFq+a4ySuzhNZE0y0jRBCmsfAY8zsoms/
KwNiRpdlVBKYtlIw6/Qpu53fmCBFbPdSCATm+yxqjmwYdZBhd7uWmcS5LzSRPh6y
1b1IWg6GytjVPlom6nPxCNw31JLda0iDb7/X5cExbtah3ri1oaMkswyhKTs2MaRY
cI1UqJGSI0+EXndzrRc+4JdhOjgFntqqIeQsC2FXTFrSkdF7sNwZAz5PSKpECsd3
6r/eyzxM4cmWIw0+Vrxq4GdVgwDd26KMVxd6ANR9xh0HOJv73C2rTrW/HpyOfYDE
CxG56dPHJfO92wLjbjPeRGYnl0xzW8FJ6uYsmwIDAQABAoIBACi0BKcyQ3HElSJC
kaAao+Uvnzh4yvPg8Nwf5JDIp/uDdTMyIEWLtrLczRWrjGVZYbsVROinP5VfnPTT
kYwkfKINj2u+gC6lsNuPnRuvHXikF8eO/mYvCTur1zZvsQnF5kp4GGwIqr+qoPUP
bB0UMndG1PdpoMryHe+JcrvTrLHDmCeH10TqOwMsQMLHYLkowvxwJWsmTY7/Qr5S
Wm3PPpOcW2i0uyPVuyuv4yD1368fqnqJ8QFsQp1K6QtYsNnJ71Hut1/IoxK/e6hj
5Z+byKtHVtmcLnABuoOT7BhleJNFBksX9sh83jid4tMBgci+zXNeGmgqo2EmaWAb
agQslkECgYEA8B1rzjOHVQx/vwSzDa4XOrpoHQRfyElrGNz9JVBvnoC7AorezBXQ
M9WTHQIFTGMjzD8pb+YJGi3gj93VN51r0SmJRxBaBRh1ZZI9kFiFzngYev8POgD3
ygmlS3kTHCNxCK/CJkB+/jMBgtPj5ygDpCWVcTSuWlQFphePkW7jaaECgYEA1Blz
ulqgAyJHZaqgcbcCsI2q6m527hVr9pjzNjIVmkwu38yS9RTCgdlbEVVDnS0hoifl
+jVMEGXjF3xjyMvL50BKbQUH+KAa+V4n1WGlnZOxX9TMny8MBjEuSX2+362vQ3BX
4vOlX00gvoc+sY+lrzvfx/OdPCHQGVYzoKCxhLsCgYA07HcviuIAV/HsO2/vyvhp
xF5gTu+BqNUHNOZDDDid+ge+Jre2yfQLCL8VPLXIQW3Jff53IH/PGl+NtjphuLvj
7UDJvgvpZZuymIojP6+2c3gJ3CASC9aR3JBnUzdoE1O9s2eaoMqc4scpe+SWtZYf
3vzSZ+cqF6zrD/Rf/M35IQKBgHTU4E6ShPm09CcoaeC5sp2WK8OevZw/6IyZi78a
r5Oiy18zzO97U/k6xVMy6F+38ILl/2Rn31JZDVJujniY6eSkIVsUHmPxrWoXV1HO
y++U32uuSFiXDcSLarfIsE992MEJLSAynbF1Rsgsr3gXbGiuToJRyxbIeVy7gwzD
94TpAoGAY4/PejWQj9psZfAhyk5dRGra++gYRQ/gK1IIc1g+Dd2/BxbT/RHr05GK
6vwrfjsoRyMWteC1SsNs/CurjfQ/jqCfHNP5XPvxgd5Ec8sRJIiV7V5RTuWJsPu1
+3K6cnKEyg+0ekYmLertRFIY6SwWmY1fyKgTvxudMcsBY7dC4xs=
-----END RSA PRIVATE KEY-----
`)
func writeTempFile(byts []byte) (string, error) {
tmpf, err := os.CreateTemp(os.TempDir(), "rtsp-")
if err != nil {
return "", err
}
defer tmpf.Close()
_, err = tmpf.Write(byts)
if err != nil {
return "", err
}
return tmpf.Name(), nil
}
func newInstance(conf string) (*Core, bool) {
if conf == "" {
return New([]string{})
}
tmpf, err := test.CreateTempFile([]byte(conf))
tmpf, err := writeTempFile([]byte(conf))
if err != nil {
return nil, false
}
@ -26,74 +92,6 @@ func newInstance(conf string) (*Core, bool) { @@ -26,74 +92,6 @@ func newInstance(conf string) (*Core, bool) {
return New([]string{tmpf})
}
func TestCoreErrors(t *testing.T) {
for _, ca := range []struct {
name string
conf string
}{
{
"logger",
"logDestinations: [file]\n" +
"logFile: /nonexisting/nonexist\n",
},
{
"metrics",
"metrics: yes\n" +
"metricsAddress: invalid\n",
},
{
"pprof",
"pprof: yes\n" +
"pprofAddress: invalid\n",
},
{
"playback",
"playback: yes\n" +
"playbackAddress: invalid\n",
},
{
"rtsp",
"rtspAddress: invalid\n",
},
{
"rtsps",
"encryption: strict\n" +
"rtspAddress: invalid\n",
},
{
"rtmp",
"rtmpAddress: invalid\n",
},
{
"rtmps",
"rtmpEncryption: strict\n" +
"rtmpAddress: invalid\n",
},
{
"hls",
"hlsAddress: invalid\n",
},
{
"webrtc",
"webrtcAddress: invalid\n",
},
{
"srt",
"srtAddress: invalid\n",
},
{
"api",
"api: yes\n" +
"apiAddress: invalid\n",
},
} {
t.Run(ca.name, func(t *testing.T) {
_, ok := newInstance(ca.conf)
require.Equal(t, false, ok)
})
}
}
func TestCoreHotReloading(t *testing.T) {
confPath := filepath.Join(os.TempDir(), "rtsp-conf")
@ -110,9 +108,11 @@ func TestCoreHotReloading(t *testing.T) { @@ -110,9 +108,11 @@ func TestCoreHotReloading(t *testing.T) {
defer p.Close()
func() {
medi := testMediaH264
c := gortsplib.Client{}
err = c.StartRecording("rtsp://localhost:8554/test1",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
&description.Session{Medias: []*description.Media{medi}})
require.EqualError(t, err, "bad status code: 401 (Unauthorized)")
}()
@ -124,9 +124,11 @@ func TestCoreHotReloading(t *testing.T) { @@ -124,9 +124,11 @@ func TestCoreHotReloading(t *testing.T) {
time.Sleep(1 * time.Second)
func() {
medi := testMediaH264
conn := gortsplib.Client{}
err = conn.StartRecording("rtsp://localhost:8554/test1",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer conn.Close()
}()

222
internal/core/hls_server_test.go

@ -0,0 +1,222 @@ @@ -0,0 +1,222 @@
package core
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"testing"
"time"
"github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
)
type testHTTPAuthenticator struct {
*http.Server
}
func newTestHTTPAuthenticator(t *testing.T, protocol string, action string) *testHTTPAuthenticator {
firstReceived := false
ts := &testHTTPAuthenticator{}
ts.Server = &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, http.MethodPost, r.Method)
require.Equal(t, "/auth", r.URL.Path)
var in struct {
IP string `json:"ip"`
User string `json:"user"`
Password string `json:"password"`
Path string `json:"path"`
Protocol string `json:"protocol"`
ID string `json:"id"`
Action string `json:"action"`
Query string `json:"query"`
}
err := json.NewDecoder(r.Body).Decode(&in)
require.NoError(t, err)
var user string
if action == "publish" {
user = "testpublisher"
} else {
user = "testreader"
}
if in.IP != "127.0.0.1" ||
in.User != user ||
in.Password != "testpass" ||
in.Path != "teststream" ||
in.Protocol != protocol ||
(firstReceived && in.ID == "") ||
in.Action != action ||
(in.Query != "user=testreader&pass=testpass&param=value" &&
in.Query != "user=testpublisher&pass=testpass&param=value" &&
in.Query != "param=value") {
w.WriteHeader(http.StatusBadRequest)
return
}
firstReceived = true
}),
}
ln, err := net.Listen("tcp", "127.0.0.1:9120")
require.NoError(t, err)
go ts.Server.Serve(ln)
return ts
}
func (ts *testHTTPAuthenticator) close() {
ts.Server.Shutdown(context.Background())
}
func httpPullFile(t *testing.T, hc *http.Client, u string) []byte {
res, err := hc.Get(u)
require.NoError(t, err)
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("bad status code: %v", res.StatusCode)
}
byts, err := io.ReadAll(res.Body)
require.NoError(t, err)
return byts
}
func TestHLSReadNotFound(t *testing.T) {
p, ok := newInstance("")
require.Equal(t, true, ok)
defer p.Close()
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8888/stream/", nil)
require.NoError(t, err)
hc := &http.Client{Transport: &http.Transport{}}
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusNotFound, res.StatusCode)
}
func TestHLSRead(t *testing.T) {
p, ok := newInstance("hlsAlwaysRemux: yes\n" +
"paths:\n" +
" all_others:\n")
require.Equal(t, true, ok)
defer p.Close()
medi := &description.Media{
Type: description.MediaTypeVideo,
Formats: []format.Format{&format.H264{
PayloadTyp: 96,
PacketizationMode: 1,
SPS: []byte{ // 1920x1080 baseline
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20,
},
PPS: []byte{0x08, 0x06, 0x07, 0x08},
}},
}
v := gortsplib.TransportTCP
source := gortsplib.Client{
Transport: &v,
}
err := source.StartRecording("rtsp://localhost:8554/stream",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
time.Sleep(500 * time.Millisecond)
for i := 0; i < 2; i++ {
err = source.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123 + uint16(i),
Timestamp: 45343 + uint32(i*90000),
SSRC: 563423,
},
Payload: []byte{
0x05, 0x02, 0x03, 0x04, // IDR
},
})
require.NoError(t, err)
}
hc := &http.Client{Transport: &http.Transport{}}
cnt := httpPullFile(t, hc, "http://localhost:8888/stream/index.m3u8")
require.Equal(t, "#EXTM3U\n"+
"#EXT-X-VERSION:9\n"+
"#EXT-X-INDEPENDENT-SEGMENTS\n"+
"\n"+
"#EXT-X-STREAM-INF:BANDWIDTH=1192,AVERAGE-BANDWIDTH=1192,"+
"CODECS=\"avc1.42c028\",RESOLUTION=1920x1080,FRAME-RATE=30.000\n"+
"stream.m3u8\n", string(cnt))
cnt = httpPullFile(t, hc, "http://localhost:8888/stream/stream.m3u8")
require.Regexp(t, "#EXTM3U\n"+
"#EXT-X-VERSION:9\n"+
"#EXT-X-TARGETDURATION:1\n"+
"#EXT-X-SERVER-CONTROL:CAN-BLOCK-RELOAD=YES,PART-HOLD-BACK=2\\.50000,CAN-SKIP-UNTIL=6\\.00000\n"+
"#EXT-X-PART-INF:PART-TARGET=1\\.00000\n"+
"#EXT-X-MEDIA-SEQUENCE:1\n"+
"#EXT-X-MAP:URI=\".*?_init.mp4\"\n"+
"#EXT-X-GAP\n"+
"#EXTINF:1\\.00000,\n"+
"gap.mp4\n"+
"#EXT-X-GAP\n"+
"#EXTINF:1\\.00000,\n"+
"gap.mp4\n"+
"#EXT-X-GAP\n"+
"#EXTINF:1\\.00000,\n"+
"gap.mp4\n"+
"#EXT-X-GAP\n"+
"#EXTINF:1\\.00000,\n"+
"gap.mp4\n"+
"#EXT-X-GAP\n"+
"#EXTINF:1\\.00000,\n"+
"gap.mp4\n"+
"#EXT-X-GAP\n"+
"#EXTINF:1\\.00000,\n"+
"gap.mp4\n"+
"#EXT-X-PROGRAM-DATE-TIME:.+?\n"+
"#EXT-X-PART:DURATION=1\\.00000,URI=\".*?_part0.mp4\",INDEPENDENT=YES\n"+
"#EXTINF:1\\.00000,\n"+
".*?_seg7.mp4\n"+
"#EXT-X-PRELOAD-HINT:TYPE=PART,URI=\".*?_part1.mp4\"\n", string(cnt))
/*trak := <-c.track
pkt, _, err := trak.ReadRTP()
require.NoError(t, err)
require.Equal(t, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 102,
SequenceNumber: pkt.SequenceNumber,
Timestamp: pkt.Timestamp,
SSRC: pkt.SSRC,
CSRC: []uint32{},
},
Payload: []byte{0x01, 0x02, 0x03, 0x04},
}, pkt)*/
}

23
internal/core/ip.go

@ -0,0 +1,23 @@ @@ -0,0 +1,23 @@
package core
import (
"fmt"
"net"
)
func ipEqualOrInRange(ip net.IP, ips []fmt.Stringer) bool {
for _, item := range ips {
switch titem := item.(type) {
case net.IP:
if titem.Equal(ip) {
return true
}
case *net.IPNet:
if titem.Contains(ip) {
return true
}
}
}
return false
}

115
internal/core/metrics_test.go

@ -4,7 +4,6 @@ import ( @@ -4,7 +4,6 @@ import (
"bufio"
"context"
"crypto/tls"
"io"
"net"
"net/http"
"net/url"
@ -15,6 +14,7 @@ import ( @@ -15,6 +14,7 @@ import (
"github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/mediacommon/pkg/formats/mpegts"
srt "github.com/datarhei/gosrt"
"github.com/pion/rtp"
@ -22,30 +22,14 @@ import ( @@ -22,30 +22,14 @@ import (
"github.com/bluenviron/mediamtx/internal/protocols/rtmp"
"github.com/bluenviron/mediamtx/internal/protocols/webrtc"
"github.com/bluenviron/mediamtx/internal/test"
)
func httpPullFile(t *testing.T, hc *http.Client, u string) []byte {
res, err := hc.Get(u)
require.NoError(t, err)
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("bad status code: %v", res.StatusCode)
}
byts, err := io.ReadAll(res.Body)
require.NoError(t, err)
return byts
}
func TestMetrics(t *testing.T) {
serverCertFpath, err := test.CreateTempFile(test.TLSCertPub)
serverCertFpath, err := writeTempFile(serverCert)
require.NoError(t, err)
defer os.Remove(serverCertFpath)
serverKeyFpath, err := test.CreateTempFile(test.TLSCertKey)
serverKeyFpath, err := writeTempFile(serverKey)
require.NoError(t, err)
defer os.Remove(serverKeyFpath)
@ -65,9 +49,7 @@ func TestMetrics(t *testing.T) { @@ -65,9 +49,7 @@ func TestMetrics(t *testing.T) {
require.Equal(t, true, ok)
defer p.Close()
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
hc := &http.Client{Transport: &http.Transport{}}
t.Run("initial", func(t *testing.T) {
bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
@ -111,7 +93,10 @@ webrtc_sessions_bytes_sent 0 @@ -111,7 +93,10 @@ webrtc_sessions_bytes_sent 0
defer wg.Done()
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/rtsp_path",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
&description.Session{Medias: []*description.Media{{
Type: description.MediaTypeVideo,
Formats: []format.Format{testFormatH264},
}}})
require.NoError(t, err)
defer source.Close()
<-terminate
@ -121,7 +106,10 @@ webrtc_sessions_bytes_sent 0 @@ -121,7 +106,10 @@ webrtc_sessions_bytes_sent 0
defer wg.Done()
source2 := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}}
err := source2.StartRecording("rtsps://localhost:8322/rtsps_path",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
&description.Session{Medias: []*description.Media{{
Type: description.MediaTypeVideo,
Formats: []format.Format{testFormatH264},
}}})
require.NoError(t, err)
defer source2.Close()
<-terminate
@ -139,7 +127,7 @@ webrtc_sessions_bytes_sent 0 @@ -139,7 +127,7 @@ webrtc_sessions_bytes_sent 0
conn, err := rtmp.NewClientConn(nconn, u, true)
require.NoError(t, err)
_, err = rtmp.NewWriter(conn, test.FormatH264, nil)
_, err = rtmp.NewWriter(conn, testFormatH264, nil)
require.NoError(t, err)
<-terminate
}()
@ -156,7 +144,7 @@ webrtc_sessions_bytes_sent 0 @@ -156,7 +144,7 @@ webrtc_sessions_bytes_sent 0
conn, err := rtmp.NewClientConn(nconn, u, true)
require.NoError(t, err)
_, err = rtmp.NewWriter(conn, test.FormatH264, nil)
_, err = rtmp.NewWriter(conn, testFormatH264, nil)
require.NoError(t, err)
<-terminate
}()
@ -167,17 +155,12 @@ webrtc_sessions_bytes_sent 0 @@ -167,17 +155,12 @@ webrtc_sessions_bytes_sent 0
su, err := url.Parse("http://localhost:8889/webrtc_path/whip")
require.NoError(t, err)
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
s := &webrtc.WHIPClient{
HTTPClient: hc,
HTTPClient: &http.Client{Transport: &http.Transport{}},
URL: su,
Log: test.NilLogger{},
}
tracks, err := s.Publish(context.Background(), test.MediaH264.Formats[0], nil)
tracks, err := s.Publish(context.Background(), testMediaH264.Formats[0], nil)
require.NoError(t, err)
defer checkClose(t, s.Close)
@ -219,9 +202,18 @@ webrtc_sessions_bytes_sent 0 @@ -219,9 +202,18 @@ webrtc_sessions_bytes_sent 0
require.NoError(t, err)
err = w.WriteH26x(track, 0, 0, true, [][]byte{
test.FormatH264.SPS,
test.FormatH264.PPS,
{0x05, 1}, // IDR
{ // SPS
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9,
0x20,
},
{ // PPS
0x08, 0x06, 0x07, 0x08,
},
{ // IDR
0x05, 1,
},
})
require.NoError(t, err)
@ -284,57 +276,8 @@ webrtc_sessions_bytes_sent 0 @@ -284,57 +276,8 @@ webrtc_sessions_bytes_sent 0
`rtmps_conns_bytes_received\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`rtmps_conns_bytes_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns\{id=".*?",state="publish"\} 1`+"\n"+
`srt_conns_packets_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_sent_unique\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_unique\{id=".*?",state="publish"\} 1`+"\n"+
`srt_conns_packets_send_loss\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_loss\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_retrans\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_retrans\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_sent_ack\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_ack\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_sent_nak\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_nak\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_sent_km\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_km\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_us_snd_duration\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_send_drop\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_drop\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_undecrypt\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_sent\{id=".*?",state="publish"\} 0`+"\n"+
`srt_conns_bytes_received\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_sent_unique\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_received_unique\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_received_loss\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_retrans\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_received_retrans\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_send_drop\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_received_drop\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_received_undecrypt\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_us_packets_send_period\{id=".*?",state="publish"\} \d+\.\d+`+"\n"+
`srt_conns_packets_flow_window\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_flight_size\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_ms_rtt\{id=".*?",state="publish"\} \d+\.\d+`+"\n"+
`srt_conns_mbps_send_rate\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_mbps_receive_rate\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_mbps_link_capacity\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_avail_send_buf\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_avail_receive_buf\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_mbps_max_bw\{id=".*?",state="publish"\} -1`+"\n"+
`srt_conns_bytes_mss\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_send_buf\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_send_buf\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_ms_send_buf\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_ms_send_tsb_pd_delay\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_receive_buf\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_receive_buf\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_ms_receive_buf\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_ms_receive_tsb_pd_delay\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_reorder_tolerance\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_avg_belated_time\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_send_loss_rate\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_packets_received_loss_rate\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`srt_conns_bytes_sent\{id=".*?",state="publish"\} 0`+"\n"+
`webrtc_sessions\{id=".*?",state="publish"\} 1`+"\n"+
`webrtc_sessions_bytes_received\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`webrtc_sessions_bytes_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+

114
internal/core/path.go

@ -21,7 +21,7 @@ import ( @@ -21,7 +21,7 @@ import (
"github.com/bluenviron/mediamtx/internal/stream"
)
func emptyTimer() *time.Timer {
func newEmptyTimer() *time.Timer {
t := time.NewTimer(0)
<-t.C
return t
@ -64,7 +64,6 @@ type pathAPIPathsGetReq struct { @@ -64,7 +64,6 @@ type pathAPIPathsGetReq struct {
}
type path struct {
parentCtx context.Context
logLevel conf.LogLevel
rtspAddress string
readTimeout conf.StringDuration
@ -116,33 +115,65 @@ type path struct { @@ -116,33 +115,65 @@ type path struct {
done chan struct{}
}
func (pa *path) initialize() {
ctx, ctxCancel := context.WithCancel(pa.parentCtx)
pa.ctx = ctx
pa.ctxCancel = ctxCancel
pa.readers = make(map[defs.Reader]struct{})
pa.onDemandStaticSourceReadyTimer = emptyTimer()
pa.onDemandStaticSourceCloseTimer = emptyTimer()
pa.onDemandPublisherReadyTimer = emptyTimer()
pa.onDemandPublisherCloseTimer = emptyTimer()
pa.chReloadConf = make(chan *conf.Path)
pa.chStaticSourceSetReady = make(chan defs.PathSourceStaticSetReadyReq)
pa.chStaticSourceSetNotReady = make(chan defs.PathSourceStaticSetNotReadyReq)
pa.chDescribe = make(chan defs.PathDescribeReq)
pa.chAddPublisher = make(chan defs.PathAddPublisherReq)
pa.chRemovePublisher = make(chan defs.PathRemovePublisherReq)
pa.chStartPublisher = make(chan defs.PathStartPublisherReq)
pa.chStopPublisher = make(chan defs.PathStopPublisherReq)
pa.chAddReader = make(chan defs.PathAddReaderReq)
pa.chRemoveReader = make(chan defs.PathRemoveReaderReq)
pa.chAPIPathsGet = make(chan pathAPIPathsGetReq)
pa.done = make(chan struct{})
func newPath(
parentCtx context.Context,
logLevel conf.LogLevel,
rtspAddress string,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
writeQueueSize int,
udpMaxPayloadSize int,
confName string,
cnf *conf.Path,
name string,
matches []string,
wg *sync.WaitGroup,
externalCmdPool *externalcmd.Pool,
parent pathParent,
) *path {
ctx, ctxCancel := context.WithCancel(parentCtx)
pa := &path{
logLevel: logLevel,
rtspAddress: rtspAddress,
readTimeout: readTimeout,
writeTimeout: writeTimeout,
writeQueueSize: writeQueueSize,
udpMaxPayloadSize: udpMaxPayloadSize,
confName: confName,
conf: cnf,
name: name,
matches: matches,
wg: wg,
externalCmdPool: externalCmdPool,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
readers: make(map[defs.Reader]struct{}),
onDemandStaticSourceReadyTimer: newEmptyTimer(),
onDemandStaticSourceCloseTimer: newEmptyTimer(),
onDemandPublisherReadyTimer: newEmptyTimer(),
onDemandPublisherCloseTimer: newEmptyTimer(),
chReloadConf: make(chan *conf.Path),
chStaticSourceSetReady: make(chan defs.PathSourceStaticSetReadyReq),
chStaticSourceSetNotReady: make(chan defs.PathSourceStaticSetNotReadyReq),
chDescribe: make(chan defs.PathDescribeReq),
chAddPublisher: make(chan defs.PathAddPublisherReq),
chRemovePublisher: make(chan defs.PathRemovePublisherReq),
chStartPublisher: make(chan defs.PathStartPublisherReq),
chStopPublisher: make(chan defs.PathStopPublisherReq),
chAddReader: make(chan defs.PathAddReaderReq),
chRemoveReader: make(chan defs.PathRemoveReaderReq),
chAPIPathsGet: make(chan pathAPIPathsGetReq),
done: make(chan struct{}),
}
pa.Log(logger.Debug, "created")
pa.wg.Add(1)
go pa.run()
return pa
}
func (pa *path) close() {
@ -393,7 +424,7 @@ func (pa *path) doSourceStaticSetReady(req defs.PathSourceStaticSetReadyReq) { @@ -393,7 +424,7 @@ func (pa *path) doSourceStaticSetReady(req defs.PathSourceStaticSetReadyReq) {
if pa.conf.HasOnDemandStaticSource() {
pa.onDemandStaticSourceReadyTimer.Stop()
pa.onDemandStaticSourceReadyTimer = emptyTimer()
pa.onDemandStaticSourceReadyTimer = newEmptyTimer()
pa.onDemandStaticSourceScheduleClose()
}
@ -515,7 +546,7 @@ func (pa *path) doStartPublisher(req defs.PathStartPublisherReq) { @@ -515,7 +546,7 @@ func (pa *path) doStartPublisher(req defs.PathStartPublisherReq) {
if pa.conf.HasOnDemandPublisher() && pa.onDemandPublisherState != pathOnDemandStateInitial {
pa.onDemandPublisherReadyTimer.Stop()
pa.onDemandPublisherReadyTimer = emptyTimer()
pa.onDemandPublisherReadyTimer = newEmptyTimer()
pa.onDemandPublisherScheduleClose()
}
@ -599,7 +630,7 @@ func (pa *path) doAPIPathsGet(req pathAPIPathsGetReq) { @@ -599,7 +630,7 @@ func (pa *path) doAPIPathsGet(req pathAPIPathsGetReq) {
if pa.stream == nil {
return []string{}
}
return defs.MediasToCodecs(pa.stream.Desc().Medias)
return defs.MediasDescription(pa.stream.Desc().Medias)
}(),
BytesReceived: func() uint64 {
if pa.stream == nil {
@ -674,7 +705,7 @@ func (pa *path) onDemandStaticSourceScheduleClose() { @@ -674,7 +705,7 @@ func (pa *path) onDemandStaticSourceScheduleClose() {
func (pa *path) onDemandStaticSourceStop(reason string) {
if pa.onDemandStaticSourceState == pathOnDemandStateClosing {
pa.onDemandStaticSourceCloseTimer.Stop()
pa.onDemandStaticSourceCloseTimer = emptyTimer()
pa.onDemandStaticSourceCloseTimer = newEmptyTimer()
}
pa.onDemandStaticSourceState = pathOnDemandStateInitial
@ -707,7 +738,7 @@ func (pa *path) onDemandPublisherScheduleClose() { @@ -707,7 +738,7 @@ func (pa *path) onDemandPublisherScheduleClose() {
func (pa *path) onDemandPublisherStop(reason string) {
if pa.onDemandPublisherState == pathOnDemandStateClosing {
pa.onDemandPublisherCloseTimer.Stop()
pa.onDemandPublisherCloseTimer = emptyTimer()
pa.onDemandPublisherCloseTimer = newEmptyTimer()
}
pa.onUnDemandHook(reason)
@ -857,13 +888,13 @@ func (pa *path) addReaderPost(req defs.PathAddReaderReq) { @@ -857,13 +888,13 @@ func (pa *path) addReaderPost(req defs.PathAddReaderReq) {
if pa.onDemandStaticSourceState == pathOnDemandStateClosing {
pa.onDemandStaticSourceState = pathOnDemandStateReady
pa.onDemandStaticSourceCloseTimer.Stop()
pa.onDemandStaticSourceCloseTimer = emptyTimer()
pa.onDemandStaticSourceCloseTimer = newEmptyTimer()
}
} else if pa.conf.HasOnDemandPublisher() {
if pa.onDemandPublisherState == pathOnDemandStateClosing {
pa.onDemandPublisherState = pathOnDemandStateReady
pa.onDemandPublisherCloseTimer.Stop()
pa.onDemandPublisherCloseTimer = emptyTimer()
pa.onDemandPublisherCloseTimer = newEmptyTimer()
}
}
@ -928,13 +959,12 @@ func (pa *path) describe(req defs.PathDescribeReq) defs.PathDescribeRes { @@ -928,13 +959,12 @@ func (pa *path) describe(req defs.PathDescribeReq) defs.PathDescribeRes {
}
// addPublisher is called by a publisher through pathManager.
func (pa *path) addPublisher(req defs.PathAddPublisherReq) (defs.Path, error) {
func (pa *path) addPublisher(req defs.PathAddPublisherReq) defs.PathAddPublisherRes {
select {
case pa.chAddPublisher <- req:
res := <-req.Res
return res.Path, res.Err
return <-req.Res
case <-pa.ctx.Done():
return nil, fmt.Errorf("terminated")
return defs.PathAddPublisherRes{Err: fmt.Errorf("terminated")}
}
}
@ -949,14 +979,13 @@ func (pa *path) RemovePublisher(req defs.PathRemovePublisherReq) { @@ -949,14 +979,13 @@ func (pa *path) RemovePublisher(req defs.PathRemovePublisherReq) {
}
// StartPublisher is called by a publisher.
func (pa *path) StartPublisher(req defs.PathStartPublisherReq) (*stream.Stream, error) {
func (pa *path) StartPublisher(req defs.PathStartPublisherReq) defs.PathStartPublisherRes {
req.Res = make(chan defs.PathStartPublisherRes)
select {
case pa.chStartPublisher <- req:
res := <-req.Res
return res.Stream, res.Err
return <-req.Res
case <-pa.ctx.Done():
return nil, fmt.Errorf("terminated")
return defs.PathStartPublisherRes{Err: fmt.Errorf("terminated")}
}
}
@ -971,13 +1000,12 @@ func (pa *path) StopPublisher(req defs.PathStopPublisherReq) { @@ -971,13 +1000,12 @@ func (pa *path) StopPublisher(req defs.PathStopPublisherReq) {
}
// addReader is called by a reader through pathManager.
func (pa *path) addReader(req defs.PathAddReaderReq) (defs.Path, *stream.Stream, error) {
func (pa *path) addReader(req defs.PathAddReaderReq) defs.PathAddReaderRes {
select {
case pa.chAddReader <- req:
res := <-req.Res
return res.Path, res.Stream, res.Err
return <-req.Res
case <-pa.ctx.Done():
return nil, nil, fmt.Errorf("terminated")
return defs.PathAddReaderRes{Err: fmt.Errorf("terminated")}
}
}

236
internal/core/path_manager.go

@ -6,12 +6,10 @@ import ( @@ -6,12 +6,10 @@ import (
"sort"
"sync"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/stream"
)
func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool {
@ -25,7 +23,6 @@ func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool { @@ -25,7 +23,6 @@ func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool {
clone.RPICameraSharpness = newPathConf.RPICameraSharpness
clone.RPICameraExposure = newPathConf.RPICameraExposure
clone.RPICameraAWB = newPathConf.RPICameraAWB
clone.RPICameraAWBGains = newPathConf.RPICameraAWBGains
clone.RPICameraDenoise = newPathConf.RPICameraDenoise
clone.RPICameraShutter = newPathConf.RPICameraShutter
clone.RPICameraMetering = newPathConf.RPICameraMetering
@ -38,6 +35,40 @@ func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool { @@ -38,6 +35,40 @@ func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool {
return newPathConf.Equal(clone)
}
func getConfForPath(pathConfs map[string]*conf.Path, name string) (string, *conf.Path, []string, error) {
err := conf.IsValidPathName(name)
if err != nil {
return "", nil, nil, fmt.Errorf("invalid path name: %w (%s)", err, name)
}
// normal path
if pathConf, ok := pathConfs[name]; ok {
return name, pathConf, nil, nil
}
// regular expression-based path
for pathConfName, pathConf := range pathConfs {
if pathConf.Regexp != nil && pathConfName != "all" && pathConfName != "all_others" {
m := pathConf.Regexp.FindStringSubmatch(name)
if m != nil {
return pathConfName, pathConf, m, nil
}
}
}
// process path configuration "all_others" after everything else
for pathConfName, pathConf := range pathConfs {
if pathConfName == "all" || pathConfName == "all_others" {
m := pathConf.Regexp.FindStringSubmatch(name)
if m != nil {
return pathConfName, pathConf, m, nil
}
}
}
return "", nil, nil, fmt.Errorf("path '%s' is not configured", name)
}
type pathManagerHLSServer interface {
PathReady(defs.Path)
PathNotReady(defs.Path)
@ -48,16 +79,17 @@ type pathManagerParent interface { @@ -48,16 +79,17 @@ type pathManagerParent interface {
}
type pathManager struct {
logLevel conf.LogLevel
authManager *auth.Manager
rtspAddress string
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
writeQueueSize int
udpMaxPayloadSize int
pathConfs map[string]*conf.Path
externalCmdPool *externalcmd.Pool
parent pathManagerParent
logLevel conf.LogLevel
externalAuthenticationURL string
rtspAddress string
authMethods conf.AuthMethods
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
writeQueueSize int
udpMaxPayloadSize int
pathConfs map[string]*conf.Path
externalCmdPool *externalcmd.Pool
parent pathManagerParent
ctx context.Context
ctxCancel func()
@ -67,37 +99,62 @@ type pathManager struct { @@ -67,37 +99,62 @@ type pathManager struct {
pathsByConf map[string]map[*path]struct{}
// in
chReloadConf chan map[string]*conf.Path
chSetHLSServer chan pathManagerHLSServer
chClosePath chan *path
chPathReady chan *path
chPathNotReady chan *path
chFindPathConf chan defs.PathFindPathConfReq
chDescribe chan defs.PathDescribeReq
chAddReader chan defs.PathAddReaderReq
chAddPublisher chan defs.PathAddPublisherReq
chAPIPathsList chan pathAPIPathsListReq
chAPIPathsGet chan pathAPIPathsGetReq
}
func (pm *pathManager) initialize() {
chReloadConf chan map[string]*conf.Path
chSetHLSServer chan pathManagerHLSServer
chClosePath chan *path
chPathReady chan *path
chPathNotReady chan *path
chGetConfForPath chan defs.PathGetConfForPathReq
chDescribe chan defs.PathDescribeReq
chAddReader chan defs.PathAddReaderReq
chAddPublisher chan defs.PathAddPublisherReq
chAPIPathsList chan pathAPIPathsListReq
chAPIPathsGet chan pathAPIPathsGetReq
}
func newPathManager(
logLevel conf.LogLevel,
externalAuthenticationURL string,
rtspAddress string,
authMethods conf.AuthMethods,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
writeQueueSize int,
udpMaxPayloadSize int,
pathConfs map[string]*conf.Path,
externalCmdPool *externalcmd.Pool,
parent pathManagerParent,
) *pathManager {
ctx, ctxCancel := context.WithCancel(context.Background())
pm.ctx = ctx
pm.ctxCancel = ctxCancel
pm.paths = make(map[string]*path)
pm.pathsByConf = make(map[string]map[*path]struct{})
pm.chReloadConf = make(chan map[string]*conf.Path)
pm.chSetHLSServer = make(chan pathManagerHLSServer)
pm.chClosePath = make(chan *path)
pm.chPathReady = make(chan *path)
pm.chPathNotReady = make(chan *path)
pm.chFindPathConf = make(chan defs.PathFindPathConfReq)
pm.chDescribe = make(chan defs.PathDescribeReq)
pm.chAddReader = make(chan defs.PathAddReaderReq)
pm.chAddPublisher = make(chan defs.PathAddPublisherReq)
pm.chAPIPathsList = make(chan pathAPIPathsListReq)
pm.chAPIPathsGet = make(chan pathAPIPathsGetReq)
pm := &pathManager{
logLevel: logLevel,
externalAuthenticationURL: externalAuthenticationURL,
rtspAddress: rtspAddress,
authMethods: authMethods,
readTimeout: readTimeout,
writeTimeout: writeTimeout,
writeQueueSize: writeQueueSize,
udpMaxPayloadSize: udpMaxPayloadSize,
pathConfs: pathConfs,
externalCmdPool: externalCmdPool,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
paths: make(map[string]*path),
pathsByConf: make(map[string]map[*path]struct{}),
chReloadConf: make(chan map[string]*conf.Path),
chSetHLSServer: make(chan pathManagerHLSServer),
chClosePath: make(chan *path),
chPathReady: make(chan *path),
chPathNotReady: make(chan *path),
chGetConfForPath: make(chan defs.PathGetConfForPathReq),
chDescribe: make(chan defs.PathDescribeReq),
chAddReader: make(chan defs.PathAddReaderReq),
chAddPublisher: make(chan defs.PathAddPublisherReq),
chAPIPathsList: make(chan pathAPIPathsListReq),
chAPIPathsGet: make(chan pathAPIPathsGetReq),
}
for pathConfName, pathConf := range pm.pathConfs {
if pathConf.Regexp == nil {
@ -109,6 +166,8 @@ func (pm *pathManager) initialize() { @@ -109,6 +166,8 @@ func (pm *pathManager) initialize() {
pm.wg.Add(1)
go pm.run()
return pm
}
func (pm *pathManager) close() {
@ -143,8 +202,8 @@ outer: @@ -143,8 +202,8 @@ outer:
case pa := <-pm.chPathNotReady:
pm.doPathNotReady(pa)
case req := <-pm.chFindPathConf:
pm.doFindPathConf(req)
case req := <-pm.chGetConfForPath:
pm.doGetConfForPath(req)
case req := <-pm.chDescribe:
pm.doDescribe(req)
@ -229,30 +288,32 @@ func (pm *pathManager) doPathNotReady(pa *path) { @@ -229,30 +288,32 @@ func (pm *pathManager) doPathNotReady(pa *path) {
}
}
func (pm *pathManager) doFindPathConf(req defs.PathFindPathConfReq) {
_, pathConf, _, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
func (pm *pathManager) doGetConfForPath(req defs.PathGetConfForPathReq) {
_, pathConf, _, err := getConfForPath(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathFindPathConfRes{Err: err}
req.Res <- defs.PathGetConfForPathRes{Err: err}
return
}
err = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
err = doAuthentication(pm.externalAuthenticationURL, pm.authMethods,
pathConf, req.AccessRequest)
if err != nil {
req.Res <- defs.PathFindPathConfRes{Err: err}
req.Res <- defs.PathGetConfForPathRes{Err: err}
return
}
req.Res <- defs.PathFindPathConfRes{Conf: pathConf}
req.Res <- defs.PathGetConfForPathRes{Conf: pathConf}
}
func (pm *pathManager) doDescribe(req defs.PathDescribeReq) {
pathConfName, pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
pathConfName, pathConf, pathMatches, err := getConfForPath(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathDescribeRes{Err: err}
return
}
err = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
err = doAuthentication(pm.externalAuthenticationURL, pm.authMethods,
pathConf, req.AccessRequest)
if err != nil {
req.Res <- defs.PathDescribeRes{Err: err}
return
@ -267,14 +328,15 @@ func (pm *pathManager) doDescribe(req defs.PathDescribeReq) { @@ -267,14 +328,15 @@ func (pm *pathManager) doDescribe(req defs.PathDescribeReq) {
}
func (pm *pathManager) doAddReader(req defs.PathAddReaderReq) {
pathConfName, pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
pathConfName, pathConf, pathMatches, err := getConfForPath(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathAddReaderRes{Err: err}
return
}
if !req.AccessRequest.SkipAuth {
err = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
err = doAuthentication(pm.externalAuthenticationURL, pm.authMethods,
pathConf, req.AccessRequest)
if err != nil {
req.Res <- defs.PathAddReaderRes{Err: err}
return
@ -290,14 +352,15 @@ func (pm *pathManager) doAddReader(req defs.PathAddReaderReq) { @@ -290,14 +352,15 @@ func (pm *pathManager) doAddReader(req defs.PathAddReaderReq) {
}
func (pm *pathManager) doAddPublisher(req defs.PathAddPublisherReq) {
pathConfName, pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
pathConfName, pathConf, pathMatches, err := getConfForPath(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathAddPublisherRes{Err: err}
return
}
if !req.AccessRequest.SkipAuth {
err = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
err = doAuthentication(pm.externalAuthenticationURL, pm.authMethods,
pathConf, req.AccessRequest)
if err != nil {
req.Res <- defs.PathAddPublisherRes{Err: err}
return
@ -325,7 +388,7 @@ func (pm *pathManager) doAPIPathsList(req pathAPIPathsListReq) { @@ -325,7 +388,7 @@ func (pm *pathManager) doAPIPathsList(req pathAPIPathsListReq) {
func (pm *pathManager) doAPIPathsGet(req pathAPIPathsGetReq) {
path, ok := pm.paths[req.name]
if !ok {
req.res <- pathAPIPathsGetRes{err: conf.ErrPathNotFound}
req.res <- pathAPIPathsGetRes{err: fmt.Errorf("path not found")}
return
}
@ -338,23 +401,21 @@ func (pm *pathManager) createPath( @@ -338,23 +401,21 @@ func (pm *pathManager) createPath(
name string,
matches []string,
) {
pa := &path{
parentCtx: pm.ctx,
logLevel: pm.logLevel,
rtspAddress: pm.rtspAddress,
readTimeout: pm.readTimeout,
writeTimeout: pm.writeTimeout,
writeQueueSize: pm.writeQueueSize,
udpMaxPayloadSize: pm.udpMaxPayloadSize,
confName: pathConfName,
conf: pathConf,
name: name,
matches: matches,
wg: &pm.wg,
externalCmdPool: pm.externalCmdPool,
parent: pm,
}
pa.initialize()
pa := newPath(
pm.ctx,
pm.logLevel,
pm.rtspAddress,
pm.readTimeout,
pm.writeTimeout,
pm.writeQueueSize,
pm.udpMaxPayloadSize,
pathConfName,
pathConf,
name,
matches,
&pm.wg,
pm.externalCmdPool,
pm)
pm.paths[name] = pa
@ -372,8 +433,8 @@ func (pm *pathManager) removePath(pa *path) { @@ -372,8 +433,8 @@ func (pm *pathManager) removePath(pa *path) {
delete(pm.paths, pa.name)
}
// ReloadPathConfs is called by core.
func (pm *pathManager) ReloadPathConfs(pathConfs map[string]*conf.Path) {
// ReloadConf is called by core.
func (pm *pathManager) ReloadConf(pathConfs map[string]*conf.Path) {
select {
case pm.chReloadConf <- pathConfs:
case <-pm.ctx.Done():
@ -408,15 +469,14 @@ func (pm *pathManager) closePath(pa *path) { @@ -408,15 +469,14 @@ func (pm *pathManager) closePath(pa *path) {
}
// GetConfForPath is called by a reader or publisher.
func (pm *pathManager) FindPathConf(req defs.PathFindPathConfReq) (*conf.Path, error) {
req.Res = make(chan defs.PathFindPathConfRes)
func (pm *pathManager) GetConfForPath(req defs.PathGetConfForPathReq) defs.PathGetConfForPathRes {
req.Res = make(chan defs.PathGetConfForPathRes)
select {
case pm.chFindPathConf <- req:
res := <-req.Res
return res.Conf, res.Err
case pm.chGetConfForPath <- req:
return <-req.Res
case <-pm.ctx.Done():
return nil, fmt.Errorf("terminated")
return defs.PathGetConfForPathRes{Err: fmt.Errorf("terminated")}
}
}
@ -444,36 +504,36 @@ func (pm *pathManager) Describe(req defs.PathDescribeReq) defs.PathDescribeRes { @@ -444,36 +504,36 @@ func (pm *pathManager) Describe(req defs.PathDescribeReq) defs.PathDescribeRes {
}
// AddPublisher is called by a publisher.
func (pm *pathManager) AddPublisher(req defs.PathAddPublisherReq) (defs.Path, error) {
func (pm *pathManager) AddPublisher(req defs.PathAddPublisherReq) defs.PathAddPublisherRes {
req.Res = make(chan defs.PathAddPublisherRes)
select {
case pm.chAddPublisher <- req:
res := <-req.Res
if res.Err != nil {
return nil, res.Err
return res
}
return res.Path.(*path).addPublisher(req)
case <-pm.ctx.Done():
return nil, fmt.Errorf("terminated")
return defs.PathAddPublisherRes{Err: fmt.Errorf("terminated")}
}
}
// AddReader is called by a reader.
func (pm *pathManager) AddReader(req defs.PathAddReaderReq) (defs.Path, *stream.Stream, error) {
func (pm *pathManager) AddReader(req defs.PathAddReaderReq) defs.PathAddReaderRes {
req.Res = make(chan defs.PathAddReaderRes)
select {
case pm.chAddReader <- req:
res := <-req.Res
if res.Err != nil {
return nil, nil, res.Err
return res
}
return res.Path.(*path).addReader(req)
case <-pm.ctx.Done():
return nil, nil, fmt.Errorf("terminated")
return defs.PathAddReaderRes{Err: fmt.Errorf("terminated")}
}
}

3
internal/core/path_manager_test.go

@ -7,9 +7,12 @@ import ( @@ -7,9 +7,12 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v4/pkg/headers"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/stretchr/testify/require"
)
var _ defs.PathManager = &pathManager{}
func TestPathAutoDeletion(t *testing.T) {
for _, ca := range []string{"describe", "setup"} {
t.Run(ca, func(t *testing.T) {

176
internal/core/path_test.go

@ -26,7 +26,6 @@ import ( @@ -26,7 +26,6 @@ import (
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/protocols/rtmp"
"github.com/bluenviron/mediamtx/internal/protocols/webrtc"
"github.com/bluenviron/mediamtx/internal/test"
)
var runOnDemandSampleScript = `
@ -242,7 +241,7 @@ func TestPathRunOnConnect(t *testing.T) { @@ -242,7 +241,7 @@ func TestPathRunOnConnect(t *testing.T) {
err := c.StartRecording(
"rtsp://localhost:8554/test",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
&description.Session{Medias: []*description.Media{testMediaH264}})
require.NoError(t, err)
defer c.Close()
@ -302,10 +301,9 @@ func TestPathRunOnReady(t *testing.T) { @@ -302,10 +301,9 @@ func TestPathRunOnReady(t *testing.T) {
defer p.Close()
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://localhost:8554/test?query=value",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
&description.Session{Medias: []*description.Media{testMediaH264}})
require.NoError(t, err)
defer c.Close()
@ -340,13 +338,10 @@ func TestPathRunOnRead(t *testing.T) { @@ -340,13 +338,10 @@ func TestPathRunOnRead(t *testing.T) {
require.Equal(t, true, ok)
defer p.Close()
media0 := test.UniqueMediaH264()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/test",
&description.Session{Medias: []*description.Media{media0}})
&description.Session{Medias: []*description.Media{testMediaH264}})
require.NoError(t, err)
defer source.Close()
@ -397,9 +392,7 @@ func TestPathRunOnRead(t *testing.T) { @@ -397,9 +392,7 @@ func TestPathRunOnRead(t *testing.T) {
defer reader.Close()
case "webrtc":
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
hc := &http.Client{Transport: &http.Transport{}}
u, err := url.Parse("http://localhost:8889/test/whep?query=value")
require.NoError(t, err)
@ -407,40 +400,8 @@ func TestPathRunOnRead(t *testing.T) { @@ -407,40 +400,8 @@ func TestPathRunOnRead(t *testing.T) {
c := &webrtc.WHIPClient{
HTTPClient: hc,
URL: u,
Log: test.NilLogger{},
}
writerDone := make(chan struct{})
defer func() { <-writerDone }()
writerTerminate := make(chan struct{})
defer close(writerTerminate)
go func() {
defer close(writerDone)
i := uint16(0)
for {
select {
case <-time.After(100 * time.Millisecond):
case <-writerTerminate:
return
}
err := source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123 + i,
Timestamp: 45343,
SSRC: 563423,
},
Payload: []byte{5},
})
require.NoError(t, err)
i++
}
}()
_, err = c.Read(context.Background())
require.NoError(t, err)
defer checkClose(t, c.Close)
@ -468,12 +429,11 @@ func TestPathMaxReaders(t *testing.T) { @@ -468,12 +429,11 @@ func TestPathMaxReaders(t *testing.T) {
defer p.Close()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/mystream",
&description.Session{Medias: []*description.Media{
test.UniqueMediaH264(),
test.UniqueMediaMPEG4Audio(),
testMediaH264,
testMediaAAC,
}})
require.NoError(t, err)
defer source.Close()
@ -514,18 +474,15 @@ func TestPathRecord(t *testing.T) { @@ -514,18 +474,15 @@ func TestPathRecord(t *testing.T) {
require.Equal(t, true, ok)
defer p.Close()
media0 := test.UniqueMediaH264()
source := gortsplib.Client{}
err = source.StartRecording(
"rtsp://localhost:8554/mystream",
&description.Session{Medias: []*description.Media{media0}})
&description.Session{Medias: []*description.Media{testMediaH264}})
require.NoError(t, err)
defer source.Close()
for i := 0; i < 4; i++ {
err := source.WritePacketRTP(media0, &rtp.Packet{
err := source.WritePacketRTP(testMediaH264, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
@ -545,9 +502,7 @@ func TestPathRecord(t *testing.T) { @@ -545,9 +502,7 @@ func TestPathRecord(t *testing.T) {
require.NoError(t, err)
require.Equal(t, 1, len(files))
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
hc := &http.Client{Transport: &http.Transport{}}
httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]interface{}{
"record": false,
@ -562,7 +517,7 @@ func TestPathRecord(t *testing.T) { @@ -562,7 +517,7 @@ func TestPathRecord(t *testing.T) {
time.Sleep(500 * time.Millisecond)
for i := 4; i < 8; i++ {
err := source.WritePacketRTP(media0, &rtp.Packet{
err := source.WritePacketRTP(testMediaH264, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
@ -619,7 +574,7 @@ func TestPathFallback(t *testing.T) { @@ -619,7 +574,7 @@ func TestPathFallback(t *testing.T) {
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/path2",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
&description.Session{Medias: []*description.Media{testMediaH264}})
require.NoError(t, err)
defer source.Close()
@ -650,12 +605,12 @@ func TestPathSourceRegexp(t *testing.T) { @@ -650,12 +605,12 @@ func TestPathSourceRegexp(t *testing.T) {
StatusCode: base.StatusOK,
}, stream, nil
},
onSetup: func(_ *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
onSetup: func(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onPlay: func(_ *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
onPlay: func(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, nil
@ -668,7 +623,7 @@ func TestPathSourceRegexp(t *testing.T) { @@ -668,7 +623,7 @@ func TestPathSourceRegexp(t *testing.T) {
require.NoError(t, err)
defer s.Close()
stream = gortsplib.NewServerStream(&s, &description.Session{Medias: []*description.Media{test.MediaH264}})
stream = gortsplib.NewServerStream(&s, &description.Session{Medias: []*description.Media{testMediaH264}})
defer stream.Close()
p, ok := newInstance(
@ -692,106 +647,3 @@ func TestPathSourceRegexp(t *testing.T) { @@ -692,106 +647,3 @@ func TestPathSourceRegexp(t *testing.T) {
_, _, err = reader.Describe(u)
require.NoError(t, err)
}
func TestPathOverridePublisher(t *testing.T) {
for _, ca := range []string{
"enabled",
"disabled",
} {
t.Run(ca, func(t *testing.T) {
conf := "rtmp: no\n" +
"paths:\n" +
" all_others:\n"
if ca == "disabled" {
conf += " overridePublisher: no\n"
}
p, ok := newInstance(conf)
require.Equal(t, true, ok)
defer p.Close()
medi := test.UniqueMediaH264()
s1 := gortsplib.Client{}
err := s1.StartRecording("rtsp://localhost:8554/teststream",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer s1.Close()
s2 := gortsplib.Client{}
err = s2.StartRecording("rtsp://localhost:8554/teststream",
&description.Session{Medias: []*description.Media{medi}})
if ca == "enabled" {
require.NoError(t, err)
defer s2.Close()
} else {
require.Error(t, err)
}
frameRecv := make(chan struct{})
c := gortsplib.Client{}
u, err := base.ParseURL("rtsp://localhost:8554/teststream")
require.NoError(t, err)
err = c.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer c.Close()
desc, _, err := c.Describe(u)
require.NoError(t, err)
err = c.SetupAll(desc.BaseURL, desc.Medias)
require.NoError(t, err)
c.OnPacketRTP(desc.Medias[0], desc.Medias[0].Formats[0], func(pkt *rtp.Packet) {
if ca == "enabled" {
require.Equal(t, []byte{5, 15, 16, 17, 18}, pkt.Payload)
} else {
require.Equal(t, []byte{5, 11, 12, 13, 14}, pkt.Payload)
}
close(frameRecv)
})
_, err = c.Play(nil)
require.NoError(t, err)
if ca == "enabled" {
err := s1.Wait()
require.EqualError(t, err, "EOF")
err = s2.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 0x02,
PayloadType: 96,
SequenceNumber: 57899,
Timestamp: 345234345,
SSRC: 978651231,
Marker: true,
},
Payload: []byte{5, 15, 16, 17, 18},
})
require.NoError(t, err)
} else {
err = s1.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 0x02,
PayloadType: 96,
SequenceNumber: 57899,
Timestamp: 345234345,
SSRC: 978651231,
Marker: true,
},
Payload: []byte{5, 11, 12, 13, 14},
})
require.NoError(t, err)
}
<-frameRecv
})
}
}

348
internal/core/rtmp_server_test.go

@ -0,0 +1,348 @@ @@ -0,0 +1,348 @@
package core //nolint:dupl
import (
"crypto/tls"
"net"
"net/url"
"os"
"testing"
"time"
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio"
"github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/protocols/rtmp"
)
func TestRTMPServer(t *testing.T) {
for _, encrypt := range []string{
"plain",
"tls",
} {
for _, auth := range []string{
"none",
"internal",
"external",
} {
t.Run("encrypt_"+encrypt+"_auth_"+auth, func(t *testing.T) {
var port string
var conf string
if encrypt == "plain" {
port = "1935"
conf = "rtsp: no\n" +
"hls: no\n"
} else {
port = "1936"
serverCertFpath, err := writeTempFile(serverCert)
require.NoError(t, err)
defer os.Remove(serverCertFpath)
serverKeyFpath, err := writeTempFile(serverKey)
require.NoError(t, err)
defer os.Remove(serverKeyFpath)
conf = "rtsp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"rtmpEncryption: \"yes\"\n" +
"rtmpServerCert: " + serverCertFpath + "\n" +
"rtmpServerKey: " + serverKeyFpath + "\n"
}
switch auth {
case "none":
conf += "paths:\n" +
" all_others:\n"
case "internal":
conf += "paths:\n" +
" all_others:\n" +
" publishUser: testpublisher\n" +
" publishPass: testpass\n" +
" publishIPs: [127.0.0.0/16]\n" +
" readUser: testreader\n" +
" readPass: testpass\n" +
" readIPs: [127.0.0.0/16]\n"
case "external":
conf += "externalAuthenticationURL: http://localhost:9120/auth\n" +
"paths:\n" +
" all_others:\n"
}
p, ok := newInstance(conf)
require.Equal(t, true, ok)
defer p.Close()
var a *testHTTPAuthenticator
if auth == "external" {
a = newTestHTTPAuthenticator(t, "rtmp", "publish")
}
u1, err := url.Parse("rtmp://127.0.0.1:" + port + "/teststream?user=testpublisher&pass=testpass&param=value")
require.NoError(t, err)
nconn1, err := func() (net.Conn, error) {
if encrypt == "plain" {
return net.Dial("tcp", u1.Host)
}
return tls.Dial("tcp", u1.Host, &tls.Config{InsecureSkipVerify: true})
}()
require.NoError(t, err)
defer nconn1.Close()
conn1, err := rtmp.NewClientConn(nconn1, u1, true)
require.NoError(t, err)
videoTrack := &format.H264{
PayloadTyp: 96,
SPS: []byte{ // 1920x1080 baseline
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9, 0x20,
},
PPS: []byte{0x08, 0x06, 0x07, 0x08},
PacketizationMode: 1,
}
audioTrack := &format.MPEG4Audio{
PayloadTyp: 96,
Config: &mpeg4audio.Config{
Type: 2,
SampleRate: 44100,
ChannelCount: 2,
},
SizeLength: 13,
IndexLength: 3,
IndexDeltaLength: 3,
}
w, err := rtmp.NewWriter(conn1, videoTrack, audioTrack)
require.NoError(t, err)
time.Sleep(500 * time.Millisecond)
if auth == "external" {
a.close()
a = newTestHTTPAuthenticator(t, "rtmp", "read")
defer a.close()
}
u2, err := url.Parse("rtmp://127.0.0.1:" + port + "/teststream?user=testreader&pass=testpass&param=value")
require.NoError(t, err)
nconn2, err := func() (net.Conn, error) {
if encrypt == "plain" {
return net.Dial("tcp", u2.Host)
}
return tls.Dial("tcp", u2.Host, &tls.Config{InsecureSkipVerify: true})
}()
require.NoError(t, err)
defer nconn2.Close()
conn2, err := rtmp.NewClientConn(nconn2, u2, false)
require.NoError(t, err)
r, err := rtmp.NewReader(conn2)
require.NoError(t, err)
videoTrack1, audioTrack2 := r.Tracks()
require.Equal(t, videoTrack, videoTrack1)
require.Equal(t, audioTrack, audioTrack2)
err = w.WriteH264(0, 0, true, [][]byte{
{0x05, 0x02, 0x03, 0x04}, // IDR 1
{0x05, 0x02, 0x03, 0x04}, // IDR 2
})
require.NoError(t, err)
r.OnDataH264(func(pts time.Duration, au [][]byte) {
require.Equal(t, [][]byte{
{ // SPS
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9,
0x20,
},
{ // PPS
0x08, 0x06, 0x07, 0x08,
},
{ // IDR 1
0x05, 0x02, 0x03, 0x04,
},
{ // IDR 2
0x05, 0x02, 0x03, 0x04,
},
}, au)
})
err = r.Read()
require.NoError(t, err)
})
}
}
}
func TestRTMPServerAuthFail(t *testing.T) {
t.Run("publish", func(t *testing.T) { //nolint:dupl
p, ok := newInstance("rtsp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all_others:\n" +
" publishUser: testuser2\n" +
" publishPass: testpass\n")
require.Equal(t, true, ok)
defer p.Close()
u1, err := url.Parse("rtmp://127.0.0.1:1935/teststream?user=testuser&pass=testpass")
require.NoError(t, err)
nconn1, err := net.Dial("tcp", u1.Host)
require.NoError(t, err)
defer nconn1.Close()
conn1, err := rtmp.NewClientConn(nconn1, u1, true)
require.NoError(t, err)
videoTrack := &format.H264{
PayloadTyp: 96,
SPS: []byte{
0x67, 0x64, 0x00, 0x0c, 0xac, 0x3b, 0x50, 0xb0,
0x4b, 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00,
0x00, 0x03, 0x00, 0x3d, 0x08,
},
PPS: []byte{
0x68, 0xee, 0x3c, 0x80,
},
PacketizationMode: 1,
}
_, err = rtmp.NewWriter(conn1, videoTrack, nil)
require.NoError(t, err)
time.Sleep(500 * time.Millisecond)
u2, err := url.Parse("rtmp://127.0.0.1:1935/teststream")
require.NoError(t, err)
nconn2, err := net.Dial("tcp", u2.Host)
require.NoError(t, err)
defer nconn2.Close()
conn2, err := rtmp.NewClientConn(nconn2, u2, false)
require.NoError(t, err)
_, err = rtmp.NewReader(conn2)
require.EqualError(t, err, "EOF")
})
t.Run("publish_external", func(t *testing.T) {
p, ok := newInstance("externalAuthenticationURL: http://localhost:9120/auth\n" +
"paths:\n" +
" all_others:\n")
require.Equal(t, true, ok)
defer p.Close()
a := newTestHTTPAuthenticator(t, "rtmp", "publish")
defer a.close()
u1, err := url.Parse("rtmp://127.0.0.1:1935/teststream?user=testuser1&pass=testpass")
require.NoError(t, err)
nconn1, err := net.Dial("tcp", u1.Host)
require.NoError(t, err)
defer nconn1.Close()
conn1, err := rtmp.NewClientConn(nconn1, u1, true)
require.NoError(t, err)
videoTrack := &format.H264{
PayloadTyp: 96,
SPS: []byte{
0x67, 0x64, 0x00, 0x0c, 0xac, 0x3b, 0x50, 0xb0,
0x4b, 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00,
0x00, 0x03, 0x00, 0x3d, 0x08,
},
PPS: []byte{
0x68, 0xee, 0x3c, 0x80,
},
PacketizationMode: 1,
}
_, err = rtmp.NewWriter(conn1, videoTrack, nil)
require.NoError(t, err)
time.Sleep(500 * time.Millisecond)
u2, err := url.Parse("rtmp://127.0.0.1:1935/teststream")
require.NoError(t, err)
nconn2, err := net.Dial("tcp", u2.Host)
require.NoError(t, err)
defer nconn2.Close()
conn2, err := rtmp.NewClientConn(nconn2, u2, false)
require.NoError(t, err)
_, err = rtmp.NewReader(conn2)
require.EqualError(t, err, "EOF")
})
t.Run("read", func(t *testing.T) { //nolint:dupl
p, ok := newInstance("rtsp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all_others:\n" +
" readUser: testuser2\n" +
" readPass: testpass\n")
require.Equal(t, true, ok)
defer p.Close()
u1, err := url.Parse("rtmp://127.0.0.1:1935/teststream")
require.NoError(t, err)
nconn1, err := net.Dial("tcp", u1.Host)
require.NoError(t, err)
defer nconn1.Close()
conn1, err := rtmp.NewClientConn(nconn1, u1, true)
require.NoError(t, err)
videoTrack := &format.H264{
PayloadTyp: 96,
SPS: []byte{
0x67, 0x64, 0x00, 0x0c, 0xac, 0x3b, 0x50, 0xb0,
0x4b, 0x42, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00,
0x00, 0x03, 0x00, 0x3d, 0x08,
},
PPS: []byte{
0x68, 0xee, 0x3c, 0x80,
},
PacketizationMode: 1,
}
_, err = rtmp.NewWriter(conn1, videoTrack, nil)
require.NoError(t, err)
time.Sleep(500 * time.Millisecond)
u2, err := url.Parse("rtmp://127.0.0.1:1935/teststream?user=testuser1&pass=testpass")
require.NoError(t, err)
nconn2, err := net.Dial("tcp", u2.Host)
require.NoError(t, err)
defer nconn2.Close()
conn2, err := rtmp.NewClientConn(nconn2, u2, false)
require.NoError(t, err)
_, err = rtmp.NewReader(conn2)
require.EqualError(t, err, "EOF")
})
}

373
internal/core/rtsp_server_test.go

@ -0,0 +1,373 @@ @@ -0,0 +1,373 @@
package core
import (
"testing"
"github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
)
func TestRTSPServer(t *testing.T) {
for _, auth := range []string{
"none",
"internal",
"external",
} {
t.Run("auth_"+auth, func(t *testing.T) {
var conf string
switch auth {
case "none":
conf = "paths:\n" +
" all_others:\n"
case "internal":
conf = "rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all_others:\n" +
" publishUser: testpublisher\n" +
" publishPass: testpass\n" +
" publishIPs: [127.0.0.0/16]\n" +
" readUser: testreader\n" +
" readPass: testpass\n" +
" readIPs: [127.0.0.0/16]\n"
case "external":
conf = "externalAuthenticationURL: http://localhost:9120/auth\n" +
"paths:\n" +
" all_others:\n"
}
p, ok := newInstance(conf)
require.Equal(t, true, ok)
defer p.Close()
var a *testHTTPAuthenticator
if auth == "external" {
a = newTestHTTPAuthenticator(t, "rtsp", "publish")
}
medi := testMediaH264
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://testpublisher:testpass@127.0.0.1:8554/teststream?param=value",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
if auth == "external" {
a.close()
a = newTestHTTPAuthenticator(t, "rtsp", "read")
defer a.close()
}
reader := gortsplib.Client{}
u, err := base.ParseURL("rtsp://testreader:testpass@127.0.0.1:8554/teststream?param=value")
require.NoError(t, err)
err = reader.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer reader.Close()
desc, _, err := reader.Describe(u)
require.NoError(t, err)
err = reader.SetupAll(desc.BaseURL, desc.Medias)
require.NoError(t, err)
_, err = reader.Play(nil)
require.NoError(t, err)
})
}
}
func TestRTSPServerAuthHashedSHA256(t *testing.T) {
p, ok := newInstance(
"rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all_others:\n" +
" publishUser: sha256:rl3rgi4NcZkpAEcacZnQ2VuOfJ0FxAqCRaKB/SwdZoQ=\n" +
" publishPass: sha256:E9JJ8stBJ7QM+nV4ZoUCeHk/gU3tPFh/5YieiJp6n2w=\n")
require.Equal(t, true, ok)
defer p.Close()
medi := testMediaH264
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://testuser:testpass@127.0.0.1:8554/test/stream",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
}
func TestRTSPServerAuthHashedArgon2(t *testing.T) {
p, ok := newInstance(
"rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all_others:\n" +
" publishUser: argon2:$argon2id$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$Ux/LWeTgJQPyfMMJo1myR64+o8rALHoPmlE1i/TR+58\n" +
" publishPass: argon2:$argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$/mrZ42TiTv1mcPnpMUera5oi0SFYbbyueAbdx5sUvWo\n")
require.Equal(t, true, ok)
defer p.Close()
medi := testMediaH264
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://testuser:testpass@127.0.0.1:8554/test/stream",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
}
func TestRTSPServerAuthFail(t *testing.T) {
for _, ca := range []struct {
name string
user string
pass string
}{
{
"wronguser",
"test1user",
"testpass",
},
{
"wrongpass",
"testuser",
"test1pass",
},
{
"wrongboth",
"test1user",
"test1pass",
},
} {
t.Run("publish_"+ca.name, func(t *testing.T) {
p, ok := newInstance("rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all_others:\n" +
" publishUser: testuser\n" +
" publishPass: testpass\n")
require.Equal(t, true, ok)
defer p.Close()
medi := testMediaH264
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://"+ca.user+":"+ca.pass+"@localhost:8554/test/stream",
&description.Session{Medias: []*description.Media{medi}},
)
require.EqualError(t, err, "bad status code: 401 (Unauthorized)")
})
}
for _, ca := range []struct {
name string
user string
pass string
}{
{
"wronguser",
"test1user",
"testpass",
},
{
"wrongpass",
"testuser",
"test1pass",
},
{
"wrongboth",
"test1user",
"test1pass",
},
} {
t.Run("read_"+ca.name, func(t *testing.T) {
p, ok := newInstance("rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all_others:\n" +
" readUser: testuser\n" +
" readPass: testpass\n")
require.Equal(t, true, ok)
defer p.Close()
c := gortsplib.Client{}
u, err := base.ParseURL("rtsp://" + ca.user + ":" + ca.pass + "@localhost:8554/test/stream")
require.NoError(t, err)
err = c.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer c.Close()
_, _, err = c.Describe(u)
require.EqualError(t, err, "bad status code: 401 (Unauthorized)")
})
}
t.Run("ip", func(t *testing.T) {
p, ok := newInstance("rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all_others:\n" +
" publishIPs: [128.0.0.1/32]\n")
require.Equal(t, true, ok)
defer p.Close()
medi := testMediaH264
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://localhost:8554/test/stream",
&description.Session{Medias: []*description.Media{medi}},
)
require.EqualError(t, err, "bad status code: 401 (Unauthorized)")
})
t.Run("external", func(t *testing.T) {
p, ok := newInstance("externalAuthenticationURL: http://localhost:9120/auth\n" +
"paths:\n" +
" all_others:\n")
require.Equal(t, true, ok)
defer p.Close()
a := newTestHTTPAuthenticator(t, "rtsp", "publish")
defer a.close()
medi := testMediaH264
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://testpublisher2:testpass@localhost:8554/teststream?param=value",
&description.Session{Medias: []*description.Media{medi}},
)
require.EqualError(t, err, "bad status code: 401 (Unauthorized)")
})
}
func TestRTSPServerPublisherOverride(t *testing.T) {
for _, ca := range []string{
"enabled",
"disabled",
} {
t.Run(ca, func(t *testing.T) {
conf := "rtmp: no\n" +
"paths:\n" +
" all_others:\n"
if ca == "disabled" {
conf += " overridePublisher: no\n"
}
p, ok := newInstance(conf)
require.Equal(t, true, ok)
defer p.Close()
medi := testMediaH264
s1 := gortsplib.Client{}
err := s1.StartRecording("rtsp://localhost:8554/teststream",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer s1.Close()
s2 := gortsplib.Client{}
err = s2.StartRecording("rtsp://localhost:8554/teststream",
&description.Session{Medias: []*description.Media{medi}})
if ca == "enabled" {
require.NoError(t, err)
defer s2.Close()
} else {
require.Error(t, err)
}
frameRecv := make(chan struct{})
c := gortsplib.Client{}
u, err := base.ParseURL("rtsp://localhost:8554/teststream")
require.NoError(t, err)
err = c.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer c.Close()
desc, _, err := c.Describe(u)
require.NoError(t, err)
err = c.SetupAll(desc.BaseURL, desc.Medias)
require.NoError(t, err)
c.OnPacketRTP(desc.Medias[0], desc.Medias[0].Formats[0], func(pkt *rtp.Packet) {
if ca == "enabled" {
require.Equal(t, []byte{5, 15, 16, 17, 18}, pkt.Payload)
} else {
require.Equal(t, []byte{5, 11, 12, 13, 14}, pkt.Payload)
}
close(frameRecv)
})
_, err = c.Play(nil)
require.NoError(t, err)
if ca == "enabled" {
err := s1.Wait()
require.EqualError(t, err, "EOF")
err = s2.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 0x02,
PayloadType: 96,
SequenceNumber: 57899,
Timestamp: 345234345,
SSRC: 978651231,
Marker: true,
},
Payload: []byte{5, 15, 16, 17, 18},
})
require.NoError(t, err)
} else {
err = s1.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 0x02,
PayloadType: 96,
SequenceNumber: 57899,
Timestamp: 345234345,
SSRC: 978651231,
Marker: true,
},
Payload: []byte{5, 11, 12, 13, 14},
})
require.NoError(t, err)
}
<-frameRecv
})
}
}

146
internal/core/srt_server_test.go

@ -0,0 +1,146 @@ @@ -0,0 +1,146 @@
package core
import (
"bufio"
"testing"
"time"
"github.com/bluenviron/mediacommon/pkg/formats/mpegts"
"github.com/datarhei/gosrt"
"github.com/stretchr/testify/require"
)
func TestSRTServer(t *testing.T) {
for _, ca := range []string{
"no passphrase",
"publish passphrase",
"read passphrase",
} {
t.Run(ca, func(t *testing.T) {
conf := "paths:\n" +
" all_others:\n"
switch ca {
case "publish passphrase":
conf += " srtPublishPassphrase: 123456789abcde"
case "read passphrase":
conf += " srtReadPassphrase: 123456789abcde"
}
p, ok := newInstance(conf)
require.Equal(t, true, ok)
defer p.Close()
u := "srt://localhost:8890?streamid=publish:mypath"
if ca == "publish passphrase" {
u += "&passphrase=123456789abcde"
}
srtConf := srt.DefaultConfig()
address, err := srtConf.UnmarshalURL(u)
require.NoError(t, err)
err = srtConf.Validate()
require.NoError(t, err)
publisher, err := srt.Dial("srt", address, srtConf)
require.NoError(t, err)
defer publisher.Close()
track := &mpegts.Track{
Codec: &mpegts.CodecH264{},
}
bw := bufio.NewWriter(publisher)
w := mpegts.NewWriter(bw, []*mpegts.Track{track})
require.NoError(t, err)
err = w.WriteH26x(track, 0, 0, true, [][]byte{
{ // SPS
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9,
0x20,
},
{ // PPS
0x08, 0x06, 0x07, 0x08,
},
{ // IDR
0x05, 1,
},
})
require.NoError(t, err)
err = bw.Flush()
require.NoError(t, err)
time.Sleep(500 * time.Millisecond)
u = "srt://localhost:8890?streamid=read:mypath"
if ca == "read passphrase" {
u += "&passphrase=123456789abcde"
}
srtConf = srt.DefaultConfig()
address, err = srtConf.UnmarshalURL(u)
require.NoError(t, err)
err = srtConf.Validate()
require.NoError(t, err)
reader, err := srt.Dial("srt", address, srtConf)
require.NoError(t, err)
defer reader.Close()
err = w.WriteH26x(track, 2*90000, 1*90000, true, [][]byte{
{ // IDR
0x05, 2,
},
})
require.NoError(t, err)
err = bw.Flush()
require.NoError(t, err)
r, err := mpegts.NewReader(reader)
require.NoError(t, err)
require.Equal(t, []*mpegts.Track{{
PID: 256,
Codec: &mpegts.CodecH264{},
}}, r.Tracks())
received := false
r.OnDataH26x(r.Tracks()[0], func(pts int64, dts int64, au [][]byte) error {
require.Equal(t, int64(0), pts)
require.Equal(t, int64(0), dts)
require.Equal(t, [][]byte{
{ // SPS
0x67, 0x42, 0xc0, 0x28, 0xd9, 0x00, 0x78, 0x02,
0x27, 0xe5, 0x84, 0x00, 0x00, 0x03, 0x00, 0x04,
0x00, 0x00, 0x03, 0x00, 0xf0, 0x3c, 0x60, 0xc9,
0x20,
},
{ // PPS
0x08, 0x06, 0x07, 0x08,
},
{ // IDR
0x05, 1,
},
}, au)
received = true
return nil
})
for {
err = r.Read()
require.NoError(t, err)
if received {
break
}
}
})
}
}

2
internal/core/static_source_handler.go

@ -180,7 +180,7 @@ func (s *staticSourceHandler) run() { @@ -180,7 +180,7 @@ func (s *staticSourceHandler) run() {
recreate()
recreating := false
recreateTimer := emptyTimer()
recreateTimer := newEmptyTimer()
for {
select {

362
internal/core/webrtc_server_test.go

@ -0,0 +1,362 @@ @@ -0,0 +1,362 @@
package core
import (
"bytes"
"context"
"net/http"
"net/url"
"testing"
"time"
"github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/pion/rtp"
pwebrtc "github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/protocols/webrtc"
)
func TestWebRTCPages(t *testing.T) {
p, ok := newInstance("paths:\n" +
" all:\n")
require.Equal(t, true, ok)
defer p.Close()
hc := &http.Client{Transport: &http.Transport{}}
for _, path := range []string{"/stream", "/stream/publish", "/publish"} {
func() {
req, err := http.NewRequest(http.MethodGet, "http://localhost:8889"+path, nil)
require.NoError(t, err)
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
}()
}
}
func TestWebRTCRead(t *testing.T) {
for _, auth := range []string{
"none",
"internal",
"external",
} {
t.Run("auth_"+auth, func(t *testing.T) {
var conf string
switch auth {
case "none":
conf = "paths:\n" +
" all_others:\n"
case "internal":
conf = "paths:\n" +
" all_others:\n" +
" readUser: myuser\n" +
" readPass: mypass\n"
case "external":
conf = "externalAuthenticationURL: http://localhost:9120/auth\n" +
"paths:\n" +
" all_others:\n"
}
p, ok := newInstance(conf)
require.Equal(t, true, ok)
defer p.Close()
var a *testHTTPAuthenticator
if auth == "external" {
a = newTestHTTPAuthenticator(t, "rtsp", "publish")
}
medi := &description.Media{
Type: description.MediaTypeVideo,
Formats: []format.Format{&format.H264{
PayloadTyp: 96,
PacketizationMode: 1,
}},
}
v := gortsplib.TransportTCP
source := gortsplib.Client{
Transport: &v,
}
err := source.StartRecording(
"rtsp://testpublisher:testpass@localhost:8554/teststream?param=value",
&description.Session{Medias: []*description.Media{medi}})
require.NoError(t, err)
defer source.Close()
if auth == "external" {
a.close()
a = newTestHTTPAuthenticator(t, "webrtc", "read")
defer a.close()
}
hc := &http.Client{Transport: &http.Transport{}}
user := ""
pass := ""
switch auth {
case "internal":
user = "myuser"
pass = "mypass"
case "external":
user = "testreader"
pass = "testpass"
}
ur := "http://"
if user != "" {
ur += user + ":" + pass + "@"
}
ur += "localhost:8889/teststream/whep?param=value"
go func() {
time.Sleep(500 * time.Millisecond)
err := source.WritePacketRTP(medi, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123,
Timestamp: 45343,
SSRC: 563423,
},
Payload: []byte{5, 3},
})
require.NoError(t, err)
}()
u, err := url.Parse(ur)
require.NoError(t, err)
c := &webrtc.WHIPClient{
HTTPClient: hc,
URL: u,
}
tracks, err := c.Read(context.Background())
require.NoError(t, err)
defer checkClose(t, c.Close)
pkt, err := tracks[0].ReadRTP()
require.NoError(t, err)
require.Equal(t, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 100,
SequenceNumber: pkt.SequenceNumber,
Timestamp: pkt.Timestamp,
SSRC: pkt.SSRC,
CSRC: []uint32{},
},
Payload: []byte{5, 3},
}, pkt)
})
}
}
func TestWebRTCReadNotFound(t *testing.T) {
p, ok := newInstance("paths:\n" +
" all_others:\n")
require.Equal(t, true, ok)
defer p.Close()
hc := &http.Client{Transport: &http.Transport{}}
iceServers, err := webrtc.WHIPOptionsICEServers(context.Background(), hc, "http://localhost:8889/stream/whep")
require.NoError(t, err)
pc, err := pwebrtc.NewPeerConnection(pwebrtc.Configuration{
ICEServers: iceServers,
})
require.NoError(t, err)
defer pc.Close() //nolint:errcheck
_, err = pc.AddTransceiverFromKind(pwebrtc.RTPCodecTypeVideo)
require.NoError(t, err)
offer, err := pc.CreateOffer(nil)
require.NoError(t, err)
req, err := http.NewRequest(http.MethodPost, "http://localhost:8889/stream/whep", bytes.NewReader([]byte(offer.SDP)))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/sdp")
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusNotFound, res.StatusCode)
}
func TestWebRTCPublish(t *testing.T) {
for _, auth := range []string{
"none",
"internal",
"external",
} {
t.Run("auth_"+auth, func(t *testing.T) {
var conf string
switch auth {
case "none":
conf = "paths:\n" +
" all_others:\n"
case "internal":
conf = "paths:\n" +
" all_others:\n" +
" publishUser: myuser\n" +
" publishPass: mypass\n"
case "external":
conf = "externalAuthenticationURL: http://localhost:9120/auth\n" +
"paths:\n" +
" all_others:\n"
}
p, ok := newInstance(conf)
require.Equal(t, true, ok)
defer p.Close()
var a *testHTTPAuthenticator
if auth == "external" {
a = newTestHTTPAuthenticator(t, "webrtc", "publish")
}
hc := &http.Client{Transport: &http.Transport{}}
// preflight requests must always work, without authentication
func() {
req, err := http.NewRequest(http.MethodOptions, "http://localhost:8889/teststream/whip", nil)
require.NoError(t, err)
req.Header.Set("Access-Control-Request-Method", "OPTIONS")
res, err := hc.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusNoContent, res.StatusCode)
if auth != "none" {
_, ok := res.Header["Link"]
require.Equal(t, false, ok)
}
}()
user := ""
pass := ""
switch auth {
case "internal":
user = "myuser"
pass = "mypass"
case "external":
user = "testpublisher"
pass = "testpass"
}
ur := "http://"
if user != "" {
ur += user + ":" + pass + "@"
}
ur += "localhost:8889/teststream/whip?param=value"
su, err := url.Parse(ur)
require.NoError(t, err)
s := &webrtc.WHIPClient{
HTTPClient: hc,
URL: su,
}
tracks, err := s.Publish(context.Background(), testMediaH264.Formats[0], nil)
require.NoError(t, err)
defer checkClose(t, s.Close)
err = tracks[0].WriteRTP(&rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 123,
Timestamp: 45343,
SSRC: 563423,
},
Payload: []byte{1},
})
require.NoError(t, err)
time.Sleep(200 * time.Millisecond)
if auth == "external" {
a.close()
a = newTestHTTPAuthenticator(t, "rtsp", "read")
defer a.close()
}
c := gortsplib.Client{
OnDecodeError: func(err error) {
panic(err)
},
}
u, err := base.ParseURL("rtsp://testreader:testpass@127.0.0.1:8554/teststream?param=value")
require.NoError(t, err)
err = c.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer c.Close()
desc, _, err := c.Describe(u)
require.NoError(t, err)
var forma *format.H264
medi := desc.FindFormat(&forma)
_, err = c.Setup(desc.BaseURL, medi, 0, 0)
require.NoError(t, err)
received := make(chan struct{})
c.OnPacketRTP(medi, forma, func(pkt *rtp.Packet) {
require.Equal(t, []byte{3}, pkt.Payload)
close(received)
})
_, err = c.Play(nil)
require.NoError(t, err)
err = tracks[0].WriteRTP(&rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 124,
Timestamp: 45343,
SSRC: 563423,
},
Payload: []byte{3},
})
require.NoError(t, err)
<-received
})
}
}

153
internal/defs/api.go

@ -148,133 +148,14 @@ const ( @@ -148,133 +148,14 @@ const (
// APISRTConn is a SRT connection.
type APISRTConn struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State APISRTConnState `json:"state"`
Path string `json:"path"`
Query string `json:"query"`
// The metric names/comments are pulled from GoSRT
// The total number of sent DATA packets, including retransmitted packets
PacketsSent uint64 `json:"packetsSent"`
// The total number of received DATA packets, including retransmitted packets
PacketsReceived uint64 `json:"packetsReceived"`
// The total number of unique DATA packets sent by the SRT sender
PacketsSentUnique uint64 `json:"packetsSentUnique"`
// The total number of unique original, retransmitted or recovered by the packet filter DATA packets
// received in time, decrypted without errors and, as a result, scheduled for delivery to the
// upstream application by the SRT receiver.
PacketsReceivedUnique uint64 `json:"packetsReceivedUnique"`
// The total number of data packets considered or reported as lost at the sender side.
// Does not correspond to the packets detected as lost at the receiver side.
PacketsSendLoss uint64 `json:"packetsSendLoss"`
// The total number of SRT DATA packets detected as presently missing (either reordered or lost) at the receiver side
PacketsReceivedLoss uint64 `json:"packetsReceivedLoss"`
// The total number of retransmitted packets sent by the SRT sender
PacketsRetrans uint64 `json:"packetsRetrans"`
// The total number of retransmitted packets registered at the receiver side
PacketsReceivedRetrans uint64 `json:"packetsReceivedRetrans"`
// The total number of sent ACK (Acknowledgement) control packets
PacketsSentACK uint64 `json:"packetsSentACK"`
// The total number of received ACK (Acknowledgement) control packets
PacketsReceivedACK uint64 `json:"packetsReceivedACK"`
// The total number of sent NAK (Negative Acknowledgement) control packets
PacketsSentNAK uint64 `json:"packetsSentNAK"`
// The total number of received NAK (Negative Acknowledgement) control packets
PacketsReceivedNAK uint64 `json:"packetsReceivedNAK"`
// The total number of sent KM (Key Material) control packets
PacketsSentKM uint64 `json:"packetsSentKM"`
// The total number of received KM (Key Material) control packets
PacketsReceivedKM uint64 `json:"packetsReceivedKM"`
// The total accumulated time in microseconds, during which the SRT sender has some data to transmit,
// including packets that have been sent, but not yet acknowledged
UsSndDuration uint64 `json:"usSndDuration"`
// ??
PacketsReceivedBelated uint64 `json:"packetsReceivedBelated"`
// The total number of dropped by the SRT sender DATA packets that have no chance to be delivered in time
PacketsSendDrop uint64 `json:"packetsSendDrop"`
// The total number of dropped by the SRT receiver and, as a result,
// not delivered to the upstream application DATA packets
PacketsReceivedDrop uint64 `json:"packetsReceivedDrop"`
// The total number of packets that failed to be decrypted at the receiver side
PacketsReceivedUndecrypt uint64 `json:"packetsReceivedUndecrypt"`
// Same as packetsReceived, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceived uint64 `json:"bytesReceived"`
// Same as packetsSent, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesSent uint64 `json:"bytesSent"`
// Same as packetsSentUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesSentUnique uint64 `json:"bytesSentUnique"`
// Same as packetsReceivedUnique, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedUnique uint64 `json:"bytesReceivedUnique"`
// Same as packetsReceivedLoss, but expressed in bytes, including payload and all the headers (IP, TCP, SRT),
// bytes for the presently missing (either reordered or lost) packets' payloads are estimated
// based on the average packet size
BytesReceivedLoss uint64 `json:"bytesReceivedLoss"`
// Same as packetsRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesRetrans uint64 `json:"bytesRetrans"`
// Same as packetsReceivedRetrans, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedRetrans uint64 `json:"bytesReceivedRetrans"`
// Same as PacketsReceivedBelated, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedBelated uint64 `json:"bytesReceivedBelated"`
// Same as packetsSendDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesSendDrop uint64 `json:"bytesSendDrop"`
// Same as packetsReceivedDrop, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedDrop uint64 `json:"bytesReceivedDrop"`
// Same as packetsReceivedUndecrypt, but expressed in bytes, including payload and all the headers (IP, TCP, SRT)
BytesReceivedUndecrypt uint64 `json:"bytesReceivedUndecrypt"`
// Current minimum time interval between which consecutive packets are sent, in microseconds
UsPacketsSendPeriod float64 `json:"usPacketsSendPeriod"`
// The maximum number of packets that can be "in flight"
PacketsFlowWindow uint64 `json:"packetsFlowWindow"`
// The number of packets in flight
PacketsFlightSize uint64 `json:"packetsFlightSize"`
// Smoothed round-trip time (SRTT), an exponentially-weighted moving average (EWMA)
// of an endpoint's RTT samples, in milliseconds
MsRTT float64 `json:"msRTT"`
// Current transmission bandwidth, in Mbps
MbpsSendRate float64 `json:"mbpsSendRate"`
// Current receiving bandwidth, in Mbps
MbpsReceiveRate float64 `json:"mbpsReceiveRate"`
// Estimated capacity of the network link, in Mbps
MbpsLinkCapacity float64 `json:"mbpsLinkCapacity"`
// The available space in the sender's buffer, in bytes
BytesAvailSendBuf uint64 `json:"bytesAvailSendBuf"`
// The available space in the receiver's buffer, in bytes
BytesAvailReceiveBuf uint64 `json:"bytesAvailReceiveBuf"`
// Transmission bandwidth limit, in Mbps
MbpsMaxBW float64 `json:"mbpsMaxBW"`
// Maximum Segment Size (MSS), in bytes
ByteMSS uint64 `json:"byteMSS"`
// The number of packets in the sender's buffer that are already scheduled
// for sending or even possibly sent, but not yet acknowledged
PacketsSendBuf uint64 `json:"packetsSendBuf"`
// Instantaneous (current) value of packetsSndBuf, but expressed in bytes,
// including payload and all headers (IP, TCP, SRT)
BytesSendBuf uint64 `json:"bytesSendBuf"`
// The timespan (msec) of packets in the sender's buffer (unacknowledged packets)
MsSendBuf uint64 `json:"msSendBuf"`
// Timestamp-based Packet Delivery Delay value of the peer
MsSendTsbPdDelay uint64 `json:"msSendTsbPdDelay"`
// The number of acknowledged packets in receiver's buffer
PacketsReceiveBuf uint64 `json:"packetsReceiveBuf"`
// Instantaneous (current) value of packetsRcvBuf, expressed in bytes, including payload and all headers (IP, TCP, SRT)
BytesReceiveBuf uint64 `json:"bytesReceiveBuf"`
// The timespan (msec) of acknowledged packets in the receiver's buffer
MsReceiveBuf uint64 `json:"msReceiveBuf"`
// Timestamp-based Packet Delivery Delay value set on the socket via SRTO_RCVLATENCY or SRTO_LATENCY
MsReceiveTsbPdDelay uint64 `json:"msReceiveTsbPdDelay"`
// Instant value of the packet reorder tolerance
PacketsReorderTolerance uint64 `json:"packetsReorderTolerance"`
// Accumulated difference between the current time and the time-to-play of a packet that is received late
PacketsReceivedAvgBelatedTime uint64 `json:"packetsReceivedAvgBelatedTime"`
// Percentage of resent data vs. sent data
PacketsSendLossRate float64 `json:"packetsSendLossRate"`
// Percentage of retransmitted data vs. received data
PacketsReceivedLossRate float64 `json:"packetsReceivedLossRate"`
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State APISRTConnState `json:"state"`
Path string `json:"path"`
Query string `json:"query"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
// APISRTConnList is a list of SRT connections.
@ -314,21 +195,3 @@ type APIWebRTCSessionList struct { @@ -314,21 +195,3 @@ type APIWebRTCSessionList struct {
PageCount int `json:"pageCount"`
Items []*APIWebRTCSession `json:"items"`
}
// APIRecordingSegment is a recording segment.
type APIRecordingSegment struct {
Start time.Time `json:"start"`
}
// APIRecording is a recording.
type APIRecording struct {
Name string `json:"name"`
Segments []*APIRecordingSegment `json:"segments"`
}
// APIRecordingList is a list of recordings.
type APIRecordingList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []*APIRecording `json:"items"`
}

23
internal/defs/auth.go

@ -0,0 +1,23 @@ @@ -0,0 +1,23 @@
package defs
// AuthProtocol is a authentication protocol.
type AuthProtocol string
// authentication protocols.
const (
AuthProtocolRTSP AuthProtocol = "rtsp"
AuthProtocolRTMP AuthProtocol = "rtmp"
AuthProtocolHLS AuthProtocol = "hls"
AuthProtocolWebRTC AuthProtocol = "webrtc"
AuthProtocolSRT AuthProtocol = "srt"
)
// AuthenticationError is a authentication error.
type AuthenticationError struct {
Message string
}
// Error implements the error interface.
func (e AuthenticationError) Error() string {
return "authentication failed: " + e.Message
}

37
internal/defs/path.go

@ -8,7 +8,6 @@ import ( @@ -8,7 +8,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/stream"
@ -29,7 +28,7 @@ type Path interface { @@ -29,7 +28,7 @@ type Path interface {
Name() string
SafeConf() *conf.Path
ExternalCmdEnv() externalcmd.Environment
StartPublisher(req PathStartPublisherReq) (*stream.Stream, error)
StartPublisher(req PathStartPublisherReq) PathStartPublisherRes
StopPublisher(req PathStopPublisherReq)
RemovePublisher(req PathRemovePublisherReq)
RemoveReader(req PathRemoveReaderReq)
@ -46,45 +45,23 @@ type PathAccessRequest struct { @@ -46,45 +45,23 @@ type PathAccessRequest struct {
IP net.IP
User string
Pass string
Proto auth.Protocol
Proto AuthProtocol
ID *uuid.UUID
RTSPRequest *base.Request
RTSPBaseURL *base.URL
RTSPNonce string
}
// ToAuthRequest converts a path access request into an authentication request.
func (r *PathAccessRequest) ToAuthRequest() *auth.Request {
return &auth.Request{
User: r.User,
Pass: r.Pass,
IP: r.IP,
Action: func() conf.AuthAction {
if r.Publish {
return conf.AuthActionPublish
}
return conf.AuthActionRead
}(),
Path: r.Name,
Protocol: r.Proto,
ID: r.ID,
Query: r.Query,
RTSPRequest: r.RTSPRequest,
RTSPBaseURL: r.RTSPBaseURL,
RTSPNonce: r.RTSPNonce,
}
}
// PathFindPathConfRes contains the response of FindPathConf().
type PathFindPathConfRes struct {
// PathGetConfForPathRes contains the response of GetConfForPath().
type PathGetConfForPathRes struct {
Conf *conf.Path
Err error
}
// PathFindPathConfReq contains arguments of FindPathConf().
type PathFindPathConfReq struct {
// PathGetConfForPathReq contains arguments of GetConfForPath().
type PathGetConfForPathReq struct {
AccessRequest PathAccessRequest
Res chan PathFindPathConfRes
Res chan PathGetConfForPathRes
}
// PathDescribeRes contains the response of Describe().

9
internal/defs/path_manager.go

@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
package defs
// PathManager is a path manager.
type PathManager interface {
GetConfForPath(req PathGetConfForPathReq) PathGetConfForPathRes
Describe(req PathDescribeReq) PathDescribeRes
AddPublisher(req PathAddPublisherReq) PathAddPublisherRes
AddReader(req PathAddReaderReq) PathAddReaderRes
}

47
internal/defs/source.go

@ -5,7 +5,6 @@ import ( @@ -5,7 +5,6 @@ import (
"strings"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/mediamtx/internal/logger"
)
@ -20,44 +19,32 @@ type Source interface { @@ -20,44 +19,32 @@ type Source interface {
APISourceDescribe() APIPathSourceOrReader
}
// FormatsToCodecs returns the name of codecs of given formats.
func FormatsToCodecs(formats []format.Format) []string {
ret := make([]string, len(formats))
for i, forma := range formats {
func mediaDescription(media *description.Media) string {
ret := make([]string, len(media.Formats))
for i, forma := range media.Formats {
ret[i] = forma.Codec()
}
return strings.Join(ret, "/")
}
// MediasDescription returns the description of medias.
func MediasDescription(medias []*description.Media) []string {
ret := make([]string, len(medias))
for i, media := range medias {
ret[i] = mediaDescription(media)
}
return ret
}
// FormatsInfo returns a description of formats.
func FormatsInfo(formats []format.Format) string {
// MediasInfo returns the description of medias.
func MediasInfo(medias []*description.Media) string {
return fmt.Sprintf("%d %s (%s)",
len(formats),
len(medias),
func() string {
if len(formats) == 1 {
if len(medias) == 1 {
return "track"
}
return "tracks"
}(),
strings.Join(FormatsToCodecs(formats), ", "))
}
// MediasToCodecs returns the name of codecs of given formats.
func MediasToCodecs(medias []*description.Media) []string {
var formats []format.Format
for _, media := range medias {
formats = append(formats, media.Formats...)
}
return FormatsToCodecs(formats)
}
// MediasInfo returns a description of medias.
func MediasInfo(medias []*description.Media) string {
var formats []format.Format
for _, media := range medias {
formats = append(formats, media.Formats...)
}
return FormatsInfo(formats)
strings.Join(MediasDescription(medias), ", "))
}

18
internal/externalcmd/cmd.go

@ -4,7 +4,7 @@ package externalcmd @@ -4,7 +4,7 @@ package externalcmd
import (
"errors"
"fmt"
"os"
"strings"
"time"
)
@ -42,12 +42,9 @@ func NewCmd( @@ -42,12 +42,9 @@ func NewCmd(
) *Cmd {
// replace variables in both Linux and Windows, in order to allow using the
// same commands on both of them.
cmdstr = os.Expand(cmdstr, func(variable string) string {
if value, ok := env[variable]; ok {
return value
}
return os.Getenv(variable)
})
for key, val := range env {
cmdstr = strings.ReplaceAll(cmdstr, "$"+key, val)
}
if onExit == nil {
onExit = func(_ error) {}
@ -77,13 +74,8 @@ func (e *Cmd) Close() { @@ -77,13 +74,8 @@ func (e *Cmd) Close() {
func (e *Cmd) run() {
defer e.pool.wg.Done()
env := append([]string(nil), os.Environ()...)
for key, val := range e.env {
env = append(env, key+"="+val)
}
for {
err := e.runOSSpecific(env)
err := e.runOSSpecific()
if errors.Is(err, errTerminated) {
return
}

14
internal/externalcmd/cmd_unix.go

@ -13,7 +13,7 @@ import ( @@ -13,7 +13,7 @@ import (
"github.com/kballard/go-shellquote"
)
func (e *Cmd) runOSSpecific(env []string) error {
func (e *Cmd) runOSSpecific() error {
cmdParts, err := shellquote.Split(e.cmdstr)
if err != nil {
return err
@ -21,13 +21,14 @@ func (e *Cmd) runOSSpecific(env []string) error { @@ -21,13 +21,14 @@ func (e *Cmd) runOSSpecific(env []string) error {
cmd := exec.Command(cmdParts[0], cmdParts[1:]...)
cmd.Env = env
cmd.Env = append([]string(nil), os.Environ()...)
for key, val := range e.env {
cmd.Env = append(cmd.Env, key+"="+val)
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// set process group in order to allow killing subprocesses
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
err = cmd.Start()
if err != nil {
return err
@ -50,8 +51,7 @@ func (e *Cmd) runOSSpecific(env []string) error { @@ -50,8 +51,7 @@ func (e *Cmd) runOSSpecific(env []string) error {
select {
case <-e.terminate:
// the minus is needed to kill all subprocesses
syscall.Kill(-cmd.Process.Pid, syscall.SIGINT) //nolint:errcheck
syscall.Kill(cmd.Process.Pid, syscall.SIGINT) //nolint:errcheck
<-cmdDone
return errTerminated

67
internal/externalcmd/cmd_win.go

@ -9,52 +9,11 @@ import ( @@ -9,52 +9,11 @@ import (
"os/exec"
"strings"
"syscall"
"unsafe"
"github.com/kballard/go-shellquote"
"golang.org/x/sys/windows"
)
// taken from
// https://gist.github.com/hallazzang/76f3970bfc949831808bbebc8ca15209
func createProcessGroup() (windows.Handle, error) {
h, err := windows.CreateJobObject(nil, nil)
if err != nil {
return 0, err
}
info := windows.JOBOBJECT_EXTENDED_LIMIT_INFORMATION{
BasicLimitInformation: windows.JOBOBJECT_BASIC_LIMIT_INFORMATION{
LimitFlags: windows.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
},
}
_, err = windows.SetInformationJobObject(
h,
windows.JobObjectExtendedLimitInformation,
uintptr(unsafe.Pointer(&info)),
uint32(unsafe.Sizeof(info)))
if err != nil {
return 0, err
}
return h, nil
}
func closeProcessGroup(h windows.Handle) error {
return windows.CloseHandle(h)
}
func addProcessToGroup(h windows.Handle, p *os.Process) error {
type process struct {
Pid int
Handle uintptr
}
return windows.AssignProcessToJobObject(h,
windows.Handle((*process)(unsafe.Pointer(p)).Handle))
}
func (e *Cmd) runOSSpecific(env []string) error {
func (e *Cmd) runOSSpecific() error {
var cmd *exec.Cmd
// from Golang documentation:
@ -80,22 +39,15 @@ func (e *Cmd) runOSSpecific(env []string) error { @@ -80,22 +39,15 @@ func (e *Cmd) runOSSpecific(env []string) error {
cmd = exec.Command(cmdParts[0], cmdParts[1:]...)
}
cmd.Env = env
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
// create a process group to kill all subprocesses
g, err := createProcessGroup()
if err != nil {
return err
cmd.Env = append([]string(nil), os.Environ()...)
for key, val := range e.env {
cmd.Env = append(cmd.Env, key+"="+val)
}
err = cmd.Start()
if err != nil {
return err
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = addProcessToGroup(g, cmd.Process)
err := cmd.Start()
if err != nil {
return err
}
@ -117,12 +69,13 @@ func (e *Cmd) runOSSpecific(env []string) error { @@ -117,12 +69,13 @@ func (e *Cmd) runOSSpecific(env []string) error {
select {
case <-e.terminate:
closeProcessGroup(g)
// on Windows, it's not possible to send os.Interrupt to a process.
// Kill() is the only supported way.
cmd.Process.Kill()
<-cmdDone
return errTerminated
case c := <-cmdDone:
closeProcessGroup(g)
if c != 0 {
return fmt.Errorf("command exited with code %d", c)
}

12
internal/formatprocessor/ac3.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpac3"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -16,7 +15,6 @@ import ( @@ -16,7 +15,6 @@ import (
type formatProcessorAC3 struct {
udpMaxPayloadSize int
format *format.AC3
timeEncoder *rtptime.Encoder
encoder *rtpac3.Encoder
decoder *rtpac3.Decoder
}
@ -36,14 +34,6 @@ func newAC3( @@ -36,14 +34,6 @@ func newAC3(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -65,7 +55,7 @@ func (t *formatProcessorAC3) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -65,7 +55,7 @@ func (t *formatProcessorAC3) ProcessUnit(uu unit.Unit) error { //nolint:dupl
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

17
internal/formatprocessor/av1.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpav1"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -16,9 +15,9 @@ import ( @@ -16,9 +15,9 @@ import (
type formatProcessorAV1 struct {
udpMaxPayloadSize int
format *format.AV1
timeEncoder *rtptime.Encoder
encoder *rtpav1.Encoder
decoder *rtpav1.Decoder
encoder *rtpav1.Encoder
decoder *rtpav1.Decoder
}
func newAV1(
@ -36,14 +35,6 @@ func newAV1( @@ -36,14 +35,6 @@ func newAV1(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -66,7 +57,7 @@ func (t *formatProcessorAV1) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -66,7 +57,7 @@ func (t *formatProcessorAV1) ProcessUnit(uu unit.Unit) error { //nolint:dupl
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

12
internal/formatprocessor/g711.go

@ -6,7 +6,6 @@ import ( @@ -6,7 +6,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtplpcm"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -15,7 +14,6 @@ import ( @@ -15,7 +14,6 @@ import (
type formatProcessorG711 struct {
udpMaxPayloadSize int
format *format.G711
timeEncoder *rtptime.Encoder
encoder *rtplpcm.Encoder
decoder *rtplpcm.Decoder
}
@ -35,14 +33,6 @@ func newG711( @@ -35,14 +33,6 @@ func newG711(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -67,7 +57,7 @@ func (t *formatProcessorG711) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -67,7 +57,7 @@ func (t *formatProcessorG711) ProcessUnit(uu unit.Unit) error { //nolint:dupl
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

2
internal/formatprocessor/g711_test.go

@ -32,7 +32,6 @@ func TestG611Encode(t *testing.T) { @@ -32,7 +32,6 @@ func TestG611Encode(t *testing.T) {
Version: 2,
PayloadType: 8,
SequenceNumber: unit.RTPPackets[0].SequenceNumber,
Timestamp: unit.RTPPackets[0].Timestamp,
SSRC: unit.RTPPackets[0].SSRC,
},
Payload: []byte{1, 2, 3, 4},
@ -61,7 +60,6 @@ func TestG611Encode(t *testing.T) { @@ -61,7 +60,6 @@ func TestG611Encode(t *testing.T) {
Version: 2,
PayloadType: 0,
SequenceNumber: unit.RTPPackets[0].SequenceNumber,
Timestamp: unit.RTPPackets[0].Timestamp,
SSRC: unit.RTPPackets[0].SSRC,
},
Payload: []byte{1, 2, 3, 4},

17
internal/formatprocessor/h264.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtph264"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/bluenviron/mediacommon/pkg/codecs/h264"
"github.com/pion/rtp"
@ -74,9 +73,9 @@ func rtpH264ExtractParams(payload []byte) ([]byte, []byte) { @@ -74,9 +73,9 @@ func rtpH264ExtractParams(payload []byte) ([]byte, []byte) {
type formatProcessorH264 struct {
udpMaxPayloadSize int
format *format.H264
timeEncoder *rtptime.Encoder
encoder *rtph264.Encoder
decoder *rtph264.Decoder
encoder *rtph264.Encoder
decoder *rtph264.Decoder
}
func newH264(
@ -94,14 +93,6 @@ func newH264( @@ -94,14 +93,6 @@ func newH264(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -235,7 +226,7 @@ func (t *formatProcessorH264) ProcessUnit(uu unit.Unit) error { @@ -235,7 +226,7 @@ func (t *formatProcessorH264) ProcessUnit(uu unit.Unit) error {
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

2
internal/formatprocessor/h264_test.go

@ -202,7 +202,7 @@ func TestH264EmptyPacket(t *testing.T) { @@ -202,7 +202,7 @@ func TestH264EmptyPacket(t *testing.T) {
}
func FuzzRTPH264ExtractParams(f *testing.F) {
f.Fuzz(func(_ *testing.T, b []byte) {
f.Fuzz(func(t *testing.T, b []byte) {
rtpH264ExtractParams(b)
})
}

17
internal/formatprocessor/h265.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtph265"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/bluenviron/mediacommon/pkg/codecs/h265"
"github.com/pion/rtp"
@ -81,9 +80,9 @@ func rtpH265ExtractParams(payload []byte) ([]byte, []byte, []byte) { @@ -81,9 +80,9 @@ func rtpH265ExtractParams(payload []byte) ([]byte, []byte, []byte) {
type formatProcessorH265 struct {
udpMaxPayloadSize int
format *format.H265
timeEncoder *rtptime.Encoder
encoder *rtph265.Encoder
decoder *rtph265.Decoder
encoder *rtph265.Encoder
decoder *rtph265.Decoder
}
func newH265(
@ -101,14 +100,6 @@ func newH265( @@ -101,14 +100,6 @@ func newH265(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -254,7 +245,7 @@ func (t *formatProcessorH265) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -254,7 +245,7 @@ func (t *formatProcessorH265) ProcessUnit(uu unit.Unit) error { //nolint:dupl
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

2
internal/formatprocessor/h265_test.go

@ -198,7 +198,7 @@ func TestH265EmptyPacket(t *testing.T) { @@ -198,7 +198,7 @@ func TestH265EmptyPacket(t *testing.T) {
}
func FuzzRTPH265ExtractParams(f *testing.F) {
f.Fuzz(func(_ *testing.T, b []byte) {
f.Fuzz(func(t *testing.T, b []byte) {
rtpH265ExtractParams(b)
})
}

12
internal/formatprocessor/lpcm.go

@ -6,7 +6,6 @@ import ( @@ -6,7 +6,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtplpcm"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -15,7 +14,6 @@ import ( @@ -15,7 +14,6 @@ import (
type formatProcessorLPCM struct {
udpMaxPayloadSize int
format *format.LPCM
timeEncoder *rtptime.Encoder
encoder *rtplpcm.Encoder
decoder *rtplpcm.Decoder
}
@ -35,14 +33,6 @@ func newLPCM( @@ -35,14 +33,6 @@ func newLPCM(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -67,7 +57,7 @@ func (t *formatProcessorLPCM) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -67,7 +57,7 @@ func (t *formatProcessorLPCM) ProcessUnit(uu unit.Unit) error { //nolint:dupl
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

2
internal/formatprocessor/lpcm_test.go

@ -13,7 +13,6 @@ func TestLPCMEncode(t *testing.T) { @@ -13,7 +13,6 @@ func TestLPCMEncode(t *testing.T) {
forma := &format.LPCM{
PayloadTyp: 96,
BitDepth: 16,
SampleRate: 44100,
ChannelCount: 2,
}
@ -31,7 +30,6 @@ func TestLPCMEncode(t *testing.T) { @@ -31,7 +30,6 @@ func TestLPCMEncode(t *testing.T) {
Version: 2,
PayloadType: 96,
SequenceNumber: unit.RTPPackets[0].SequenceNumber,
Timestamp: unit.RTPPackets[0].Timestamp,
SSRC: unit.RTPPackets[0].SSRC,
},
Payload: []byte{1, 2, 3, 4},

12
internal/formatprocessor/mjpeg.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpmjpeg"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -16,7 +15,6 @@ import ( @@ -16,7 +15,6 @@ import (
type formatProcessorMJPEG struct {
udpMaxPayloadSize int
format *format.MJPEG
timeEncoder *rtptime.Encoder
encoder *rtpmjpeg.Encoder
decoder *rtpmjpeg.Decoder
}
@ -36,14 +34,6 @@ func newMJPEG( @@ -36,14 +34,6 @@ func newMJPEG(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -66,7 +56,7 @@ func (t *formatProcessorMJPEG) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -66,7 +56,7 @@ func (t *formatProcessorMJPEG) ProcessUnit(uu unit.Unit) error { //nolint:dupl
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

12
internal/formatprocessor/mpeg1_audio.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpmpeg1audio"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -16,7 +15,6 @@ import ( @@ -16,7 +15,6 @@ import (
type formatProcessorMPEG1Audio struct {
udpMaxPayloadSize int
format *format.MPEG1Audio
timeEncoder *rtptime.Encoder
encoder *rtpmpeg1audio.Encoder
decoder *rtpmpeg1audio.Decoder
}
@ -36,14 +34,6 @@ func newMPEG1Audio( @@ -36,14 +34,6 @@ func newMPEG1Audio(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -65,7 +55,7 @@ func (t *formatProcessorMPEG1Audio) ProcessUnit(uu unit.Unit) error { //nolint:d @@ -65,7 +55,7 @@ func (t *formatProcessorMPEG1Audio) ProcessUnit(uu unit.Unit) error { //nolint:d
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

12
internal/formatprocessor/mpeg1_video.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpmpeg1video"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -16,7 +15,6 @@ import ( @@ -16,7 +15,6 @@ import (
type formatProcessorMPEG1Video struct {
udpMaxPayloadSize int
format *format.MPEG1Video
timeEncoder *rtptime.Encoder
encoder *rtpmpeg1video.Encoder
decoder *rtpmpeg1video.Decoder
}
@ -36,14 +34,6 @@ func newMPEG1Video( @@ -36,14 +34,6 @@ func newMPEG1Video(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -66,7 +56,7 @@ func (t *formatProcessorMPEG1Video) ProcessUnit(uu unit.Unit) error { //nolint:d @@ -66,7 +56,7 @@ func (t *formatProcessorMPEG1Video) ProcessUnit(uu unit.Unit) error { //nolint:d
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

12
internal/formatprocessor/mpeg4_audio.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpmpeg4audio"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -16,7 +15,6 @@ import ( @@ -16,7 +15,6 @@ import (
type formatProcessorMPEG4Audio struct {
udpMaxPayloadSize int
format *format.MPEG4Audio
timeEncoder *rtptime.Encoder
encoder *rtpmpeg4audio.Encoder
decoder *rtpmpeg4audio.Decoder
}
@ -36,14 +34,6 @@ func newMPEG4Audio( @@ -36,14 +34,6 @@ func newMPEG4Audio(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -69,7 +59,7 @@ func (t *formatProcessorMPEG4Audio) ProcessUnit(uu unit.Unit) error { //nolint:d @@ -69,7 +59,7 @@ func (t *formatProcessorMPEG4Audio) ProcessUnit(uu unit.Unit) error { //nolint:d
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

12
internal/formatprocessor/mpeg4_video.go

@ -8,7 +8,6 @@ import ( @@ -8,7 +8,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpmpeg4video"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4video"
"github.com/pion/rtp"
@ -18,7 +17,6 @@ import ( @@ -18,7 +17,6 @@ import (
type formatProcessorMPEG4Video struct {
udpMaxPayloadSize int
format *format.MPEG4Video
timeEncoder *rtptime.Encoder
encoder *rtpmpeg4video.Encoder
decoder *rtpmpeg4video.Decoder
}
@ -38,14 +36,6 @@ func newMPEG4Video( @@ -38,14 +36,6 @@ func newMPEG4Video(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -103,7 +93,7 @@ func (t *formatProcessorMPEG4Video) ProcessUnit(uu unit.Unit) error { //nolint:d @@ -103,7 +93,7 @@ func (t *formatProcessorMPEG4Video) ProcessUnit(uu unit.Unit) error { //nolint:d
return err
}
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

12
internal/formatprocessor/opus.go

@ -6,7 +6,6 @@ import ( @@ -6,7 +6,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpsimpleaudio"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/bluenviron/mediacommon/pkg/codecs/opus"
"github.com/pion/rtp"
@ -16,7 +15,6 @@ import ( @@ -16,7 +15,6 @@ import (
type formatProcessorOpus struct {
udpMaxPayloadSize int
format *format.Opus
timeEncoder *rtptime.Encoder
encoder *rtpsimpleaudio.Encoder
decoder *rtpsimpleaudio.Decoder
}
@ -36,14 +34,6 @@ func newOpus( @@ -36,14 +34,6 @@ func newOpus(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -69,7 +59,7 @@ func (t *formatProcessorOpus) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -69,7 +59,7 @@ func (t *formatProcessorOpus) ProcessUnit(uu unit.Unit) error { //nolint:dupl
return err
}
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(pts, time.Duration(t.format.ClockRate()), time.Second))
pkt.Timestamp += ts
rtpPackets = append(rtpPackets, pkt)

8
internal/formatprocessor/processor.go

@ -10,6 +10,14 @@ import ( @@ -10,6 +10,14 @@ import (
"github.com/bluenviron/mediamtx/internal/unit"
)
// avoid an int64 overflow and preserve resolution by splitting division into two parts:
// first add the integer part, then the decimal part.
func multiplyAndDivide(v, m, d time.Duration) time.Duration {
secs := v / d
dec := v % d
return (secs*m + dec*m/d)
}
// Processor cleans and normalizes streams.
type Processor interface {
// process a Unit.

12
internal/formatprocessor/vp8.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpvp8"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -16,7 +15,6 @@ import ( @@ -16,7 +15,6 @@ import (
type formatProcessorVP8 struct {
udpMaxPayloadSize int
format *format.VP8
timeEncoder *rtptime.Encoder
encoder *rtpvp8.Encoder
decoder *rtpvp8.Decoder
}
@ -36,14 +34,6 @@ func newVP8( @@ -36,14 +34,6 @@ func newVP8(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -66,7 +56,7 @@ func (t *formatProcessorVP8) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -66,7 +56,7 @@ func (t *formatProcessorVP8) ProcessUnit(uu unit.Unit) error { //nolint:dupl
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

12
internal/formatprocessor/vp9.go

@ -7,7 +7,6 @@ import ( @@ -7,7 +7,6 @@ import (
"github.com/bluenviron/gortsplib/v4/pkg/format"
"github.com/bluenviron/gortsplib/v4/pkg/format/rtpvp9"
"github.com/bluenviron/gortsplib/v4/pkg/rtptime"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/unit"
@ -16,7 +15,6 @@ import ( @@ -16,7 +15,6 @@ import (
type formatProcessorVP9 struct {
udpMaxPayloadSize int
format *format.VP9
timeEncoder *rtptime.Encoder
encoder *rtpvp9.Encoder
decoder *rtpvp9.Decoder
}
@ -36,14 +34,6 @@ func newVP9( @@ -36,14 +34,6 @@ func newVP9(
if err != nil {
return nil, err
}
t.timeEncoder = &rtptime.Encoder{
ClockRate: forma.ClockRate(),
}
err = t.timeEncoder.Initialize()
if err != nil {
return nil, err
}
}
return t, nil
@ -66,7 +56,7 @@ func (t *formatProcessorVP9) ProcessUnit(uu unit.Unit) error { //nolint:dupl @@ -66,7 +56,7 @@ func (t *formatProcessorVP9) ProcessUnit(uu unit.Unit) error { //nolint:dupl
}
u.RTPPackets = pkts
ts := t.timeEncoder.Encode(u.PTS)
ts := uint32(multiplyAndDivide(u.PTS, time.Duration(t.format.ClockRate()), time.Second))
for _, pkt := range u.RTPPackets {
pkt.Timestamp += ts
}

4
internal/highleveltests/hls_manager_test.go

@ -77,9 +77,7 @@ func TestHLSServerAuth(t *testing.T) { @@ -77,9 +77,7 @@ func TestHLSServerAuth(t *testing.T) {
usr = "testreader2"
}
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
hc := &http.Client{Transport: &http.Transport{}}
res, err := hc.Get("http://" + usr + ":testpass@127.0.0.1:8888/teststream/index.m3u8?param=value")
require.NoError(t, err)

5
internal/highleveltests/rtsp_server_test.go

@ -8,7 +8,6 @@ import ( @@ -8,7 +8,6 @@ import (
"testing"
"time"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require"
)
@ -55,11 +54,11 @@ func TestRTSPServerPublishRead(t *testing.T) { @@ -55,11 +54,11 @@ func TestRTSPServerPublishRead(t *testing.T) {
proto = "rtsps"
port = "8322"
serverCertFpath, err := test.CreateTempFile(test.TLSCertPub)
serverCertFpath, err := writeTempFile(serverCert)
require.NoError(t, err)
defer os.Remove(serverCertFpath)
serverKeyFpath, err := test.CreateTempFile(test.TLSCertKey)
serverKeyFpath, err := writeTempFile(serverKey)
require.NoError(t, err)
defer os.Remove(serverKeyFpath)

70
internal/highleveltests/tests_test.go

@ -10,15 +10,81 @@ import ( @@ -10,15 +10,81 @@ import (
"time"
"github.com/bluenviron/mediamtx/internal/core"
"github.com/bluenviron/mediamtx/internal/test"
)
var serverCert = []byte(`-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwIBAgIUXw1hEC3LFpTsllv7D3ARJyEq7sIwDQYJKoZIhvcNAQEL
BQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yMDEyMTMxNzQ0NThaFw0zMDEy
MTExNzQ0NThaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw
HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQDG8DyyS51810GsGwgWr5rjJK7OE1kTTLSNEEKax8Bj
zOyiaz8rA2JGl2VUEpi2UjDr9Cm7nd+YIEVs91IIBOb7LGqObBh1kGF3u5aZxLkv
NJE+HrLVvUhaDobK2NU+Wibqc/EI3DfUkt1rSINvv9flwTFu1qHeuLWhoySzDKEp
OzYxpFhwjVSokZIjT4Red3OtFz7gl2E6OAWe2qoh5CwLYVdMWtKR0Xuw3BkDPk9I
qkQKx3fqv97LPEzhyZYjDT5WvGrgZ1WDAN3booxXF3oA1H3GHQc4m/vcLatOtb8e
nI59gMQLEbnp08cl873bAuNuM95EZieXTHNbwUnq5iybAgMBAAGjUzBRMB0GA1Ud
DgQWBBQBKhJh8eWu0a4au9X/2fKhkFX2vjAfBgNVHSMEGDAWgBQBKhJh8eWu0a4a
u9X/2fKhkFX2vjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBj
3aCW0YPKukYgVK9cwN0IbVy/D0C1UPT4nupJcy/E0iC7MXPZ9D/SZxYQoAkdptdO
xfI+RXkpQZLdODNx9uvV+cHyZHZyjtE5ENu/i5Rer2cWI/mSLZm5lUQyx+0KZ2Yu
tEI1bsebDK30msa8QSTn0WidW9XhFnl3gRi4wRdimcQapOWYVs7ih+nAlSvng7NI
XpAyRs8PIEbpDDBMWnldrX4TP6EWYUi49gCp8OUDRREKX3l6Ls1vZ02F34yHIt/7
7IV/XSKG096bhW+icKBWV0IpcEsgTzPK1J1hMxgjhzIMxGboAeUU+kidthOob6Sd
XQxaORfgM//NzX9LhUPk
-----END CERTIFICATE-----
`)
var serverKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAxvA8skudfNdBrBsIFq+a4ySuzhNZE0y0jRBCmsfAY8zsoms/
KwNiRpdlVBKYtlIw6/Qpu53fmCBFbPdSCATm+yxqjmwYdZBhd7uWmcS5LzSRPh6y
1b1IWg6GytjVPlom6nPxCNw31JLda0iDb7/X5cExbtah3ri1oaMkswyhKTs2MaRY
cI1UqJGSI0+EXndzrRc+4JdhOjgFntqqIeQsC2FXTFrSkdF7sNwZAz5PSKpECsd3
6r/eyzxM4cmWIw0+Vrxq4GdVgwDd26KMVxd6ANR9xh0HOJv73C2rTrW/HpyOfYDE
CxG56dPHJfO92wLjbjPeRGYnl0xzW8FJ6uYsmwIDAQABAoIBACi0BKcyQ3HElSJC
kaAao+Uvnzh4yvPg8Nwf5JDIp/uDdTMyIEWLtrLczRWrjGVZYbsVROinP5VfnPTT
kYwkfKINj2u+gC6lsNuPnRuvHXikF8eO/mYvCTur1zZvsQnF5kp4GGwIqr+qoPUP
bB0UMndG1PdpoMryHe+JcrvTrLHDmCeH10TqOwMsQMLHYLkowvxwJWsmTY7/Qr5S
Wm3PPpOcW2i0uyPVuyuv4yD1368fqnqJ8QFsQp1K6QtYsNnJ71Hut1/IoxK/e6hj
5Z+byKtHVtmcLnABuoOT7BhleJNFBksX9sh83jid4tMBgci+zXNeGmgqo2EmaWAb
agQslkECgYEA8B1rzjOHVQx/vwSzDa4XOrpoHQRfyElrGNz9JVBvnoC7AorezBXQ
M9WTHQIFTGMjzD8pb+YJGi3gj93VN51r0SmJRxBaBRh1ZZI9kFiFzngYev8POgD3
ygmlS3kTHCNxCK/CJkB+/jMBgtPj5ygDpCWVcTSuWlQFphePkW7jaaECgYEA1Blz
ulqgAyJHZaqgcbcCsI2q6m527hVr9pjzNjIVmkwu38yS9RTCgdlbEVVDnS0hoifl
+jVMEGXjF3xjyMvL50BKbQUH+KAa+V4n1WGlnZOxX9TMny8MBjEuSX2+362vQ3BX
4vOlX00gvoc+sY+lrzvfx/OdPCHQGVYzoKCxhLsCgYA07HcviuIAV/HsO2/vyvhp
xF5gTu+BqNUHNOZDDDid+ge+Jre2yfQLCL8VPLXIQW3Jff53IH/PGl+NtjphuLvj
7UDJvgvpZZuymIojP6+2c3gJ3CASC9aR3JBnUzdoE1O9s2eaoMqc4scpe+SWtZYf
3vzSZ+cqF6zrD/Rf/M35IQKBgHTU4E6ShPm09CcoaeC5sp2WK8OevZw/6IyZi78a
r5Oiy18zzO97U/k6xVMy6F+38ILl/2Rn31JZDVJujniY6eSkIVsUHmPxrWoXV1HO
y++U32uuSFiXDcSLarfIsE992MEJLSAynbF1Rsgsr3gXbGiuToJRyxbIeVy7gwzD
94TpAoGAY4/PejWQj9psZfAhyk5dRGra++gYRQ/gK1IIc1g+Dd2/BxbT/RHr05GK
6vwrfjsoRyMWteC1SsNs/CurjfQ/jqCfHNP5XPvxgd5Ec8sRJIiV7V5RTuWJsPu1
+3K6cnKEyg+0ekYmLertRFIY6SwWmY1fyKgTvxudMcsBY7dC4xs=
-----END RSA PRIVATE KEY-----
`)
func writeTempFile(byts []byte) (string, error) {
tmpf, err := os.CreateTemp(os.TempDir(), "rtsp-")
if err != nil {
return "", err
}
defer tmpf.Close()
_, err = tmpf.Write(byts)
if err != nil {
return "", err
}
return tmpf.Name(), nil
}
func newInstance(conf string) (*core.Core, bool) {
if conf == "" {
return core.New([]string{})
}
tmpf, err := test.CreateTempFile([]byte(conf))
tmpf, err := writeTempFile([]byte(conf))
if err != nil {
return nil, false
}

90
internal/metrics/metrics.go

@ -3,7 +3,6 @@ package metrics @@ -3,7 +3,6 @@ package metrics
import (
"io"
"net"
"net/http"
"reflect"
"strconv"
@ -13,10 +12,9 @@ import ( @@ -13,10 +12,9 @@ import (
"github.com/gin-gonic/gin"
"github.com/bluenviron/mediamtx/internal/api"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/protocols/httpp"
"github.com/bluenviron/mediamtx/internal/protocols/httpserv"
"github.com/bluenviron/mediamtx/internal/restrictnetwork"
)
@ -28,10 +26,6 @@ func metric(key string, tags string, value int64) string { @@ -28,10 +26,6 @@ func metric(key string, tags string, value int64) string {
return key + tags + " " + strconv.FormatInt(value, 10) + "\n"
}
func metricFloat(key string, tags string, value float64) string {
return key + tags + " " + strconv.FormatFloat(value, 'f', -1, 64) + "\n"
}
type metricsParent interface {
logger.Writer
}
@ -40,10 +34,9 @@ type metricsParent interface { @@ -40,10 +34,9 @@ type metricsParent interface {
type Metrics struct {
Address string
ReadTimeout conf.StringDuration
AuthManager *auth.Manager
Parent metricsParent
httpServer *httpp.WrappedServer
httpServer *httpserv.WrappedServer
mutex sync.Mutex
pathManager api.PathManager
rtspServer api.RTSPServer
@ -60,12 +53,12 @@ func (m *Metrics) Initialize() error { @@ -60,12 +53,12 @@ func (m *Metrics) Initialize() error {
router := gin.New()
router.SetTrustedProxies(nil) //nolint:errcheck
router.GET("/metrics", m.mwAuth, m.onMetrics)
router.GET("/metrics", m.onMetrics)
network, address := restrictnetwork.Restrict("tcp", m.Address)
var err error
m.httpServer, err = httpp.NewWrappedServer(
m.httpServer, err = httpserv.NewWrappedServer(
network,
address,
time.Duration(m.ReadTimeout),
@ -94,30 +87,6 @@ func (m *Metrics) Log(level logger.Level, format string, args ...interface{}) { @@ -94,30 +87,6 @@ func (m *Metrics) Log(level logger.Level, format string, args ...interface{}) {
m.Parent.Log(level, "[metrics] "+format, args...)
}
func (m *Metrics) mwAuth(ctx *gin.Context) {
user, pass, hasCredentials := ctx.Request.BasicAuth()
err := m.AuthManager.Authenticate(&auth.Request{
User: user,
Pass: pass,
IP: net.ParseIP(ctx.ClientIP()),
Action: conf.AuthActionMetrics,
})
if err != nil {
if !hasCredentials {
ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`)
ctx.AbortWithStatus(http.StatusUnauthorized)
return
}
// wait some seconds to mitigate brute force attacks
<-time.After(auth.PauseAfterError)
ctx.Writer.WriteHeader(http.StatusUnauthorized)
return
}
}
func (m *Metrics) onMetrics(ctx *gin.Context) {
out := ""
@ -260,57 +229,8 @@ func (m *Metrics) onMetrics(ctx *gin.Context) { @@ -260,57 +229,8 @@ func (m *Metrics) onMetrics(ctx *gin.Context) {
for _, i := range data.Items {
tags := "{id=\"" + i.ID.String() + "\",state=\"" + string(i.State) + "\"}"
out += metric("srt_conns", tags, 1)
out += metric("srt_conns_packets_sent", tags, int64(i.PacketsSent))
out += metric("srt_conns_packets_received", tags, int64(i.PacketsReceived))
out += metric("srt_conns_packets_sent_unique", tags, int64(i.PacketsSentUnique))
out += metric("srt_conns_packets_received_unique", tags, int64(i.PacketsReceivedUnique))
out += metric("srt_conns_packets_send_loss", tags, int64(i.PacketsSendLoss))
out += metric("srt_conns_packets_received_loss", tags, int64(i.PacketsReceivedLoss))
out += metric("srt_conns_packets_retrans", tags, int64(i.PacketsRetrans))
out += metric("srt_conns_packets_received_retrans", tags, int64(i.PacketsReceivedRetrans))
out += metric("srt_conns_packets_sent_ack", tags, int64(i.PacketsSentACK))
out += metric("srt_conns_packets_received_ack", tags, int64(i.PacketsReceivedACK))
out += metric("srt_conns_packets_sent_nak", tags, int64(i.PacketsSentNAK))
out += metric("srt_conns_packets_received_nak", tags, int64(i.PacketsReceivedNAK))
out += metric("srt_conns_packets_sent_km", tags, int64(i.PacketsSentKM))
out += metric("srt_conns_packets_received_km", tags, int64(i.PacketsReceivedKM))
out += metric("srt_conns_us_snd_duration", tags, int64(i.UsSndDuration))
out += metric("srt_conns_packets_send_drop", tags, int64(i.PacketsSendDrop))
out += metric("srt_conns_packets_received_drop", tags, int64(i.PacketsReceivedDrop))
out += metric("srt_conns_packets_received_undecrypt", tags, int64(i.PacketsReceivedUndecrypt))
out += metric("srt_conns_bytes_sent", tags, int64(i.BytesSent))
out += metric("srt_conns_bytes_received", tags, int64(i.BytesReceived))
out += metric("srt_conns_bytes_sent_unique", tags, int64(i.BytesSentUnique))
out += metric("srt_conns_bytes_received_unique", tags, int64(i.BytesReceivedUnique))
out += metric("srt_conns_bytes_received_loss", tags, int64(i.BytesReceivedLoss))
out += metric("srt_conns_bytes_retrans", tags, int64(i.BytesRetrans))
out += metric("srt_conns_bytes_received_retrans", tags, int64(i.BytesReceivedRetrans))
out += metric("srt_conns_bytes_send_drop", tags, int64(i.BytesSendDrop))
out += metric("srt_conns_bytes_received_drop", tags, int64(i.BytesReceivedDrop))
out += metric("srt_conns_bytes_received_undecrypt", tags, int64(i.BytesReceivedUndecrypt))
out += metricFloat("srt_conns_us_packets_send_period", tags, i.UsPacketsSendPeriod)
out += metric("srt_conns_packets_flow_window", tags, int64(i.PacketsFlowWindow))
out += metric("srt_conns_packets_flight_size", tags, int64(i.PacketsFlightSize))
out += metricFloat("srt_conns_ms_rtt", tags, i.MsRTT)
out += metricFloat("srt_conns_mbps_send_rate", tags, i.MbpsSendRate)
out += metricFloat("srt_conns_mbps_receive_rate", tags, i.MbpsReceiveRate)
out += metricFloat("srt_conns_mbps_link_capacity", tags, i.MbpsLinkCapacity)
out += metric("srt_conns_bytes_avail_send_buf", tags, int64(i.BytesAvailSendBuf))
out += metric("srt_conns_bytes_avail_receive_buf", tags, int64(i.BytesAvailReceiveBuf))
out += metricFloat("srt_conns_mbps_max_bw", tags, i.MbpsMaxBW)
out += metric("srt_conns_bytes_mss", tags, int64(i.ByteMSS))
out += metric("srt_conns_packets_send_buf", tags, int64(i.PacketsSendBuf))
out += metric("srt_conns_bytes_send_buf", tags, int64(i.BytesSendBuf))
out += metric("srt_conns_ms_send_buf", tags, int64(i.MsSendBuf))
out += metric("srt_conns_ms_send_tsb_pd_delay", tags, int64(i.MsSendTsbPdDelay))
out += metric("srt_conns_packets_receive_buf", tags, int64(i.PacketsReceiveBuf))
out += metric("srt_conns_bytes_receive_buf", tags, int64(i.BytesReceiveBuf))
out += metric("srt_conns_ms_receive_buf", tags, int64(i.MsReceiveBuf))
out += metric("srt_conns_ms_receive_tsb_pd_delay", tags, int64(i.MsReceiveTsbPdDelay))
out += metric("srt_conns_packets_reorder_tolerance", tags, int64(i.PacketsReorderTolerance))
out += metric("srt_conns_packets_received_avg_belated_time", tags, int64(i.PacketsReceivedAvgBelatedTime))
out += metricFloat("srt_conns_packets_send_loss_rate", tags, i.PacketsSendLossRate)
out += metricFloat("srt_conns_packets_received_loss_rate", tags, i.PacketsReceivedLossRate)
out += metric("srt_conns_bytes_sent", tags, int64(i.BytesSent))
}
} else {
out += metric("srt_conns", "", 0)

594
internal/playback/fmp4.go

@ -1,594 +0,0 @@ @@ -1,594 +0,0 @@
package playback
import (
"bytes"
"errors"
"fmt"
"io"
"time"
"github.com/abema/go-mp4"
"github.com/bluenviron/mediacommon/pkg/formats/fmp4"
"github.com/bluenviron/mediacommon/pkg/formats/fmp4/seekablebuffer"
)
const (
sampleFlagIsNonSyncSample = 1 << 16
concatenationTolerance = 1 * time.Second
fmp4Timescale = 90000
)
func durationGoToMp4(v time.Duration, timeScale uint32) uint64 {
timeScale64 := uint64(timeScale)
secs := v / time.Second
dec := v % time.Second
return uint64(secs)*timeScale64 + uint64(dec)*timeScale64/uint64(time.Second)
}
func durationMp4ToGo(v uint64, timeScale uint32) time.Duration {
timeScale64 := uint64(timeScale)
secs := v / timeScale64
dec := v % timeScale64
return time.Duration(secs)*time.Second + time.Duration(dec)*time.Second/time.Duration(timeScale64)
}
var errTerminated = errors.New("terminated")
func fmp4CanBeConcatenated(
prevInit []byte,
prevEnd time.Time,
curInit []byte,
curStart time.Time,
) bool {
return bytes.Equal(prevInit, curInit) &&
!curStart.Before(prevEnd.Add(-concatenationTolerance)) &&
!curStart.After(prevEnd.Add(concatenationTolerance))
}
func fmp4ReadInit(r io.ReadSeeker) ([]byte, error) {
buf := make([]byte, 8)
_, err := io.ReadFull(r, buf)
if err != nil {
return nil, err
}
// find ftyp
if !bytes.Equal(buf[4:], []byte{'f', 't', 'y', 'p'}) {
return nil, fmt.Errorf("ftyp box not found")
}
ftypSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
_, err = r.Seek(int64(ftypSize), io.SeekStart)
if err != nil {
return nil, err
}
// find moov
_, err = io.ReadFull(r, buf)
if err != nil {
return nil, err
}
if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'v'}) {
return nil, fmt.Errorf("moov box not found")
}
moovSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
_, err = r.Seek(0, io.SeekStart)
if err != nil {
return nil, err
}
// return ftyp and moov
buf = make([]byte, ftypSize+moovSize)
_, err = io.ReadFull(r, buf)
if err != nil {
return nil, err
}
return buf, nil
}
func fmp4ReadDuration(r io.ReadSeeker) (time.Duration, error) {
// find and skip ftyp
buf := make([]byte, 8)
_, err := io.ReadFull(r, buf)
if err != nil {
return 0, err
}
if !bytes.Equal(buf[4:], []byte{'f', 't', 'y', 'p'}) {
return 0, fmt.Errorf("ftyp box not found")
}
ftypSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
_, err = r.Seek(int64(ftypSize), io.SeekStart)
if err != nil {
return 0, err
}
// find and skip moov
_, err = io.ReadFull(r, buf)
if err != nil {
return 0, err
}
if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'v'}) {
return 0, fmt.Errorf("moov box not found")
}
moovSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
_, err = r.Seek(int64(moovSize)-8, io.SeekCurrent)
if err != nil {
return 0, err
}
// find last valid moof and mdat
lastMoofPos := int64(-1)
for {
moofPos, err := r.Seek(0, io.SeekCurrent)
if err != nil {
return 0, err
}
_, err = io.ReadFull(r, buf)
if err != nil {
break
}
if !bytes.Equal(buf[4:], []byte{'m', 'o', 'o', 'f'}) {
return 0, fmt.Errorf("moof box not found")
}
moofSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
_, err = r.Seek(int64(moofSize)-8, io.SeekCurrent)
if err != nil {
break
}
_, err = io.ReadFull(r, buf)
if err != nil {
break
}
if !bytes.Equal(buf[4:], []byte{'m', 'd', 'a', 't'}) {
return 0, fmt.Errorf("mdat box not found")
}
mdatSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
_, err = r.Seek(int64(mdatSize)-8, io.SeekCurrent)
if err != nil {
break
}
lastMoofPos = moofPos
}
if lastMoofPos < 0 {
return 0, fmt.Errorf("no moof boxes found")
}
// open last moof
_, err = r.Seek(lastMoofPos+8, io.SeekStart)
if err != nil {
return 0, err
}
_, err = io.ReadFull(r, buf)
if err != nil {
return 0, err
}
// skip mfhd
if !bytes.Equal(buf[4:], []byte{'m', 'f', 'h', 'd'}) {
return 0, fmt.Errorf("mfhd box not found")
}
_, err = r.Seek(8, io.SeekCurrent)
if err != nil {
return 0, err
}
maxElapsed := uint64(0)
// foreach traf
for {
_, err := io.ReadFull(r, buf)
if err != nil {
return 0, err
}
if !bytes.Equal(buf[4:], []byte{'t', 'r', 'a', 'f'}) {
if bytes.Equal(buf[4:], []byte{'m', 'd', 'a', 't'}) {
break
}
return 0, fmt.Errorf("traf box not found")
}
// skip tfhd
_, err = io.ReadFull(r, buf)
if err != nil {
return 0, err
}
if !bytes.Equal(buf[4:], []byte{'t', 'f', 'h', 'd'}) {
return 0, fmt.Errorf("tfhd box not found")
}
tfhdSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
_, err = r.Seek(int64(tfhdSize)-8, io.SeekCurrent)
if err != nil {
return 0, err
}
// parse tfdt
_, err = io.ReadFull(r, buf)
if err != nil {
return 0, err
}
if !bytes.Equal(buf[4:], []byte{'t', 'f', 'd', 't'}) {
return 0, fmt.Errorf("tfdt box not found")
}
tfdtSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
buf2 := make([]byte, tfdtSize-8)
_, err = io.ReadFull(r, buf2)
if err != nil {
return 0, err
}
var tfdt mp4.Tfdt
_, err = mp4.Unmarshal(bytes.NewReader(buf2), uint64(len(buf2)), &tfdt, mp4.Context{})
if err != nil {
return 0, fmt.Errorf("invalid tfdt box: %w", err)
}
elapsed := tfdt.BaseMediaDecodeTimeV1
// parse trun
_, err = io.ReadFull(r, buf)
if err != nil {
return 0, err
}
if !bytes.Equal(buf[4:], []byte{'t', 'r', 'u', 'n'}) {
return 0, fmt.Errorf("trun box not found")
}
trunSize := uint32(buf[0])<<24 | uint32(buf[1])<<16 | uint32(buf[2])<<8 | uint32(buf[3])
buf2 = make([]byte, trunSize-8)
_, err = io.ReadFull(r, buf2)
if err != nil {
return 0, err
}
var trun mp4.Trun
_, err = mp4.Unmarshal(bytes.NewReader(buf2), uint64(len(buf2)), &trun, mp4.Context{})
if err != nil {
return 0, fmt.Errorf("invalid trun box: %w", err)
}
for _, entry := range trun.Entries {
elapsed += uint64(entry.SampleDuration)
}
if elapsed > maxElapsed {
maxElapsed = elapsed
}
}
return durationMp4ToGo(maxElapsed, fmp4Timescale), nil
}
func fmp4SeekAndMuxParts(
r io.ReadSeeker,
init []byte,
minTime time.Duration,
maxTime time.Duration,
w io.Writer,
) (time.Duration, error) {
minTimeMP4 := durationGoToMp4(minTime, fmp4Timescale)
maxTimeMP4 := durationGoToMp4(maxTime, fmp4Timescale)
moofOffset := uint64(0)
var tfhd *mp4.Tfhd
var tfdt *mp4.Tfdt
var outPart *fmp4.Part
var outTrack *fmp4.PartTrack
var outBuf seekablebuffer.Buffer
elapsed := uint64(0)
initWritten := false
firstSampleWritten := make(map[uint32]struct{})
gop := make(map[uint32][]*fmp4.PartSample)
_, err := mp4.ReadBoxStructure(r, func(h *mp4.ReadHandle) (interface{}, error) {
switch h.BoxInfo.Type.String() {
case "moof":
moofOffset = h.BoxInfo.Offset
outPart = &fmp4.Part{}
return h.Expand()
case "traf":
return h.Expand()
case "tfhd":
box, _, err := h.ReadPayload()
if err != nil {
return nil, err
}
tfhd = box.(*mp4.Tfhd)
case "tfdt":
box, _, err := h.ReadPayload()
if err != nil {
return nil, err
}
tfdt = box.(*mp4.Tfdt)
if tfdt.BaseMediaDecodeTimeV1 >= maxTimeMP4 {
return nil, errTerminated
}
outTrack = &fmp4.PartTrack{ID: int(tfhd.TrackID)}
case "trun":
box, _, err := h.ReadPayload()
if err != nil {
return nil, err
}
trun := box.(*mp4.Trun)
dataOffset := moofOffset + uint64(trun.DataOffset)
_, err = r.Seek(int64(dataOffset), io.SeekStart)
if err != nil {
return nil, err
}
elapsed = tfdt.BaseMediaDecodeTimeV1
baseTimeSet := false
for _, e := range trun.Entries {
payload := make([]byte, e.SampleSize)
_, err := io.ReadFull(r, payload)
if err != nil {
return nil, err
}
if elapsed >= maxTimeMP4 {
break
}
isRandom := (e.SampleFlags & sampleFlagIsNonSyncSample) == 0
_, fsw := firstSampleWritten[tfhd.TrackID]
sa := &fmp4.PartSample{
Duration: e.SampleDuration,
PTSOffset: e.SampleCompositionTimeOffsetV1,
IsNonSyncSample: !isRandom,
Payload: payload,
}
if !fsw {
if isRandom {
gop[tfhd.TrackID] = []*fmp4.PartSample{sa}
} else {
gop[tfhd.TrackID] = append(gop[tfhd.TrackID], sa)
}
}
if elapsed >= minTimeMP4 {
if !baseTimeSet {
outTrack.BaseTime = elapsed - minTimeMP4
if !fsw {
if !isRandom {
for _, sa2 := range gop[tfhd.TrackID][:len(gop[tfhd.TrackID])-1] {
sa2.Duration = 0
sa2.PTSOffset = 0
outTrack.Samples = append(outTrack.Samples, sa2)
}
}
delete(gop, tfhd.TrackID)
firstSampleWritten[tfhd.TrackID] = struct{}{}
}
}
outTrack.Samples = append(outTrack.Samples, sa)
}
elapsed += uint64(e.SampleDuration)
}
if outTrack.Samples != nil {
outPart.Tracks = append(outPart.Tracks, outTrack)
}
outTrack = nil
case "mdat":
if outPart.Tracks != nil {
if !initWritten {
initWritten = true
_, err := w.Write(init)
if err != nil {
return nil, err
}
}
err := outPart.Marshal(&outBuf)
if err != nil {
return nil, err
}
_, err = w.Write(outBuf.Bytes())
if err != nil {
return nil, err
}
outBuf.Reset()
}
outPart = nil
}
return nil, nil
})
if err != nil && !errors.Is(err, errTerminated) {
return 0, err
}
if !initWritten {
return 0, errNoSegmentsFound
}
elapsed -= minTimeMP4
return durationMp4ToGo(elapsed, fmp4Timescale), nil
}
func fmp4MuxParts(
r io.ReadSeeker,
startTime time.Duration,
maxTime time.Duration,
w io.Writer,
) (time.Duration, error) {
maxTimeMP4 := durationGoToMp4(maxTime, fmp4Timescale)
moofOffset := uint64(0)
var tfhd *mp4.Tfhd
var tfdt *mp4.Tfdt
var outPart *fmp4.Part
var outTrack *fmp4.PartTrack
var outBuf seekablebuffer.Buffer
elapsed := uint64(0)
_, err := mp4.ReadBoxStructure(r, func(h *mp4.ReadHandle) (interface{}, error) {
switch h.BoxInfo.Type.String() {
case "moof":
moofOffset = h.BoxInfo.Offset
outPart = &fmp4.Part{}
return h.Expand()
case "traf":
return h.Expand()
case "tfhd":
box, _, err := h.ReadPayload()
if err != nil {
return nil, err
}
tfhd = box.(*mp4.Tfhd)
case "tfdt":
box, _, err := h.ReadPayload()
if err != nil {
return nil, err
}
tfdt = box.(*mp4.Tfdt)
if tfdt.BaseMediaDecodeTimeV1 >= maxTimeMP4 {
return nil, errTerminated
}
outTrack = &fmp4.PartTrack{
ID: int(tfhd.TrackID),
BaseTime: tfdt.BaseMediaDecodeTimeV1 + durationGoToMp4(startTime, fmp4Timescale),
}
case "trun":
box, _, err := h.ReadPayload()
if err != nil {
return nil, err
}
trun := box.(*mp4.Trun)
dataOffset := moofOffset + uint64(trun.DataOffset)
_, err = r.Seek(int64(dataOffset), io.SeekStart)
if err != nil {
return nil, err
}
elapsed = tfdt.BaseMediaDecodeTimeV1
for _, e := range trun.Entries {
payload := make([]byte, e.SampleSize)
_, err := io.ReadFull(r, payload)
if err != nil {
return nil, err
}
if elapsed >= maxTimeMP4 {
break
}
isRandom := (e.SampleFlags & sampleFlagIsNonSyncSample) == 0
sa := &fmp4.PartSample{
Duration: e.SampleDuration,
PTSOffset: e.SampleCompositionTimeOffsetV1,
IsNonSyncSample: !isRandom,
Payload: payload,
}
outTrack.Samples = append(outTrack.Samples, sa)
elapsed += uint64(e.SampleDuration)
}
if outTrack.Samples != nil {
outPart.Tracks = append(outPart.Tracks, outTrack)
}
outTrack = nil
case "mdat":
if outPart.Tracks != nil {
err := outPart.Marshal(&outBuf)
if err != nil {
return nil, err
}
_, err = w.Write(outBuf.Bytes())
if err != nil {
return nil, err
}
outBuf.Reset()
}
outPart = nil
}
return nil, nil
})
if err != nil && !errors.Is(err, errTerminated) {
return 0, err
}
return durationMp4ToGo(elapsed, fmp4Timescale), nil
}

75
internal/playback/fmp4_test.go

@ -1,75 +0,0 @@ @@ -1,75 +0,0 @@
package playback
import (
"io"
"os"
"testing"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio"
"github.com/bluenviron/mediacommon/pkg/formats/fmp4"
"github.com/bluenviron/mediamtx/internal/test"
)
func writeBenchInit(f io.WriteSeeker) {
init := fmp4.Init{
Tracks: []*fmp4.InitTrack{
{
ID: 1,
TimeScale: 90000,
Codec: &fmp4.CodecH264{
SPS: test.FormatH264.SPS,
PPS: test.FormatH264.PPS,
},
},
{
ID: 2,
TimeScale: 90000,
Codec: &fmp4.CodecMPEG4Audio{
Config: mpeg4audio.Config{
Type: mpeg4audio.ObjectTypeAACLC,
SampleRate: 48000,
ChannelCount: 2,
},
},
},
},
}
err := init.Marshal(f)
if err != nil {
panic(err)
}
_, err = f.Write([]byte{
'm', 'o', 'o', 'f', 0x00, 0x00, 0x00, 0x10,
})
if err != nil {
panic(err)
}
}
func BenchmarkFMP4ReadInit(b *testing.B) {
f, err := os.CreateTemp(os.TempDir(), "mediamtx-playback-fmp4-")
if err != nil {
panic(err)
}
defer os.Remove(f.Name())
writeBenchInit(f)
f.Close()
for n := 0; n < b.N; n++ {
func() {
f, err := os.Open(f.Name())
if err != nil {
panic(err)
}
defer f.Close()
_, err = fmp4ReadInit(f)
if err != nil {
panic(err)
}
}()
}
}

179
internal/playback/on_get.go

@ -1,179 +0,0 @@ @@ -1,179 +0,0 @@
package playback
import (
"errors"
"fmt"
"io"
"net"
"net/http"
"os"
"strconv"
"time"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/gin-gonic/gin"
)
var errStopIteration = errors.New("stop iteration")
func parseDuration(raw string) (time.Duration, error) {
// seconds
if secs, err := strconv.ParseFloat(raw, 64); err == nil {
return time.Duration(secs * float64(time.Second)), nil
}
// deprecated, golang format
return time.ParseDuration(raw)
}
func seekAndMux(
recordFormat conf.RecordFormat,
segments []*Segment,
start time.Time,
duration time.Duration,
w io.Writer,
) error {
if recordFormat == conf.RecordFormatFMP4 {
minTime := start.Sub(segments[0].Start)
maxTime := minTime + duration
var init []byte
var elapsed time.Duration
err := func() error {
f, err := os.Open(segments[0].Fpath)
if err != nil {
return err
}
defer f.Close()
init, err = fmp4ReadInit(f)
if err != nil {
return err
}
elapsed, err = fmp4SeekAndMuxParts(f, init, minTime, maxTime, w)
if err != nil {
return err
}
return nil
}()
if err != nil {
return err
}
prevInit := init
prevEnd := start.Add(elapsed)
duration -= elapsed
overallElapsed := elapsed
for _, seg := range segments[1:] {
err := func() error {
f, err := os.Open(seg.Fpath)
if err != nil {
return err
}
defer f.Close()
init, err := fmp4ReadInit(f)
if err != nil {
return err
}
if !fmp4CanBeConcatenated(prevInit, prevEnd, init, seg.Start) {
return errStopIteration
}
elapsed, err = fmp4MuxParts(f, overallElapsed, duration, w)
if err != nil {
return err
}
return nil
}()
if err != nil {
if errors.Is(err, errStopIteration) {
return nil
}
return err
}
prevEnd = seg.Start.Add(elapsed)
duration -= elapsed
overallElapsed += elapsed
}
return nil
}
return fmt.Errorf("MPEG-TS format is not supported yet")
}
func (p *Server) onGet(ctx *gin.Context) {
pathName := ctx.Query("path")
if !p.doAuth(ctx, pathName) {
return
}
start, err := time.Parse(time.RFC3339, ctx.Query("start"))
if err != nil {
p.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid start: %w", err))
return
}
duration, err := parseDuration(ctx.Query("duration"))
if err != nil {
p.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid duration: %w", err))
return
}
format := ctx.Query("format")
if format != "" && format != "fmp4" {
p.writeError(ctx, http.StatusBadRequest, fmt.Errorf("invalid format: %s", format))
return
}
pathConf, err := p.safeFindPathConf(pathName)
if err != nil {
p.writeError(ctx, http.StatusBadRequest, err)
return
}
segments, err := findSegmentsInTimespan(pathConf, pathName, start, duration)
if err != nil {
if errors.Is(err, errNoSegmentsFound) {
p.writeError(ctx, http.StatusNotFound, err)
} else {
p.writeError(ctx, http.StatusBadRequest, err)
}
return
}
ww := &writerWrapper{ctx: ctx}
err = seekAndMux(pathConf.RecordFormat, segments, start, duration, ww)
if err != nil {
// user aborted the download
var neterr *net.OpError
if errors.As(err, &neterr) {
return
}
// nothing has been written yet; send back JSON
if !ww.written {
if errors.Is(err, errNoSegmentsFound) {
p.writeError(ctx, http.StatusNotFound, err)
} else {
p.writeError(ctx, http.StatusBadRequest, err)
}
return
}
// something has already been written: abort and write logs only
p.Log(logger.Error, err.Error())
return
}
}

374
internal/playback/on_get_test.go

@ -1,374 +0,0 @@ @@ -1,374 +0,0 @@
package playback
import (
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio"
"github.com/bluenviron/mediacommon/pkg/formats/fmp4"
"github.com/bluenviron/mediacommon/pkg/formats/fmp4/seekablebuffer"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require"
)
func writeSegment1(t *testing.T, fpath string) {
init := fmp4.Init{
Tracks: []*fmp4.InitTrack{
{
ID: 1,
TimeScale: 90000,
Codec: &fmp4.CodecH264{
SPS: test.FormatH264.SPS,
PPS: test.FormatH264.PPS,
},
},
{
ID: 2,
TimeScale: 90000,
Codec: &fmp4.CodecMPEG4Audio{
Config: mpeg4audio.Config{
Type: mpeg4audio.ObjectTypeAACLC,
SampleRate: 48000,
ChannelCount: 2,
},
},
},
},
}
var buf1 seekablebuffer.Buffer
err := init.Marshal(&buf1)
require.NoError(t, err)
var buf2 seekablebuffer.Buffer
parts := fmp4.Parts{
{
SequenceNumber: 1,
Tracks: []*fmp4.PartTrack{{
ID: 1,
BaseTime: 0,
Samples: []*fmp4.PartSample{},
}},
},
{
SequenceNumber: 1,
Tracks: []*fmp4.PartTrack{{
ID: 1,
BaseTime: 30 * 90000,
Samples: []*fmp4.PartSample{
{
Duration: 30 * 90000,
IsNonSyncSample: false,
Payload: []byte{1, 2},
},
{
Duration: 1 * 90000,
IsNonSyncSample: false,
Payload: []byte{3, 4},
},
{
Duration: 1 * 90000,
IsNonSyncSample: true,
Payload: []byte{5, 6},
},
},
}},
},
}
err = parts.Marshal(&buf2)
require.NoError(t, err)
err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644)
require.NoError(t, err)
}
func writeSegment2(t *testing.T, fpath string) {
init := fmp4.Init{
Tracks: []*fmp4.InitTrack{
{
ID: 1,
TimeScale: 90000,
Codec: &fmp4.CodecH264{
SPS: test.FormatH264.SPS,
PPS: test.FormatH264.PPS,
},
},
{
ID: 2,
TimeScale: 90000,
Codec: &fmp4.CodecMPEG4Audio{
Config: mpeg4audio.Config{
Type: mpeg4audio.ObjectTypeAACLC,
SampleRate: 48000,
ChannelCount: 2,
},
},
},
},
}
var buf1 seekablebuffer.Buffer
err := init.Marshal(&buf1)
require.NoError(t, err)
var buf2 seekablebuffer.Buffer
parts := fmp4.Parts{
{
SequenceNumber: 1,
Tracks: []*fmp4.PartTrack{{
ID: 1,
BaseTime: 0,
Samples: []*fmp4.PartSample{
{
Duration: 1 * 90000,
IsNonSyncSample: false,
Payload: []byte{7, 8},
},
{
Duration: 1 * 90000,
IsNonSyncSample: false,
Payload: []byte{9, 10},
},
},
}},
},
}
err = parts.Marshal(&buf2)
require.NoError(t, err)
err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644)
require.NoError(t, err)
}
func writeSegment3(t *testing.T, fpath string) {
init := fmp4.Init{
Tracks: []*fmp4.InitTrack{
{
ID: 1,
TimeScale: 90000,
Codec: &fmp4.CodecH264{
SPS: test.FormatH264.SPS,
PPS: test.FormatH264.PPS,
},
},
},
}
var buf1 seekablebuffer.Buffer
err := init.Marshal(&buf1)
require.NoError(t, err)
var buf2 seekablebuffer.Buffer
parts := fmp4.Parts{
{
SequenceNumber: 1,
Tracks: []*fmp4.PartTrack{{
ID: 1,
BaseTime: 0,
Samples: []*fmp4.PartSample{
{
Duration: 1 * 90000,
IsNonSyncSample: false,
Payload: []byte{10, 11},
},
},
}},
},
}
err = parts.Marshal(&buf2)
require.NoError(t, err)
err = os.WriteFile(fpath, append(buf1.Bytes(), buf2.Bytes()...), 0o644)
require.NoError(t, err)
}
var authManager = &auth.Manager{
Method: conf.AuthMethodInternal,
InternalUsers: []conf.AuthInternalUser{
{
User: "myuser",
Pass: "mypass",
Permissions: []conf.AuthInternalUserPermission{
{
Action: conf.AuthActionPlayback,
Path: "mypath",
},
},
},
},
RTSPAuthMethods: nil,
}
func TestOnGet(t *testing.T) {
dir, err := os.MkdirTemp("", "mediamtx-playback")
require.NoError(t, err)
defer os.RemoveAll(dir)
err = os.Mkdir(filepath.Join(dir, "mypath"), 0o755)
require.NoError(t, err)
writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4"))
writeSegment2(t, filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4"))
s := &Server{
Address: "127.0.0.1:9996",
ReadTimeout: conf.StringDuration(10 * time.Second),
PathConfs: map[string]*conf.Path{
"mypath": {
Playback: true,
RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"),
},
},
AuthManager: authManager,
Parent: &test.NilLogger{},
}
err = s.Initialize()
require.NoError(t, err)
defer s.Close()
u, err := url.Parse("http://myuser:mypass@localhost:9996/get")
require.NoError(t, err)
v := url.Values{}
v.Set("path", "mypath")
v.Set("start", time.Date(2008, 11, 0o7, 11, 23, 1, 500000000, time.Local).Format(time.RFC3339Nano))
v.Set("duration", "2")
v.Set("format", "fmp4")
u.RawQuery = v.Encode()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
require.NoError(t, err)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
buf, err := io.ReadAll(res.Body)
require.NoError(t, err)
var parts fmp4.Parts
err = parts.Unmarshal(buf)
require.NoError(t, err)
require.Equal(t, fmp4.Parts{
{
SequenceNumber: 0,
Tracks: []*fmp4.PartTrack{
{
ID: 1,
Samples: []*fmp4.PartSample{
{
Duration: 0,
Payload: []byte{3, 4},
},
{
Duration: 90000,
IsNonSyncSample: true,
Payload: []byte{5, 6},
},
},
},
},
},
{
SequenceNumber: 0,
Tracks: []*fmp4.PartTrack{
{
ID: 1,
BaseTime: 90000,
Samples: []*fmp4.PartSample{
{
Duration: 90000,
Payload: []byte{7, 8},
},
},
},
},
},
}, parts)
}
func TestOnGetDifferentInit(t *testing.T) {
dir, err := os.MkdirTemp("", "mediamtx-playback")
require.NoError(t, err)
defer os.RemoveAll(dir)
err = os.Mkdir(filepath.Join(dir, "mypath"), 0o755)
require.NoError(t, err)
writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4"))
writeSegment3(t, filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4"))
s := &Server{
Address: "127.0.0.1:9996",
ReadTimeout: conf.StringDuration(10 * time.Second),
PathConfs: map[string]*conf.Path{
"mypath": {
Playback: true,
RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"),
},
},
AuthManager: authManager,
Parent: &test.NilLogger{},
}
err = s.Initialize()
require.NoError(t, err)
defer s.Close()
u, err := url.Parse("http://myuser:mypass@localhost:9996/get")
require.NoError(t, err)
v := url.Values{}
v.Set("path", "mypath")
v.Set("start", time.Date(2008, 11, 0o7, 11, 23, 1, 500000000, time.Local).Format(time.RFC3339Nano))
v.Set("duration", "2")
v.Set("format", "fmp4")
u.RawQuery = v.Encode()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
require.NoError(t, err)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
buf, err := io.ReadAll(res.Body)
require.NoError(t, err)
var parts fmp4.Parts
err = parts.Unmarshal(buf)
require.NoError(t, err)
require.Equal(t, fmp4.Parts{
{
SequenceNumber: 0,
Tracks: []*fmp4.PartTrack{
{
ID: 1,
Samples: []*fmp4.PartSample{
{
Duration: 0,
Payload: []byte{3, 4},
},
{
Duration: 90000,
IsNonSyncSample: true,
Payload: []byte{5, 6},
},
},
},
},
},
}, parts)
}

120
internal/playback/on_list.go

@ -1,120 +0,0 @@ @@ -1,120 +0,0 @@
package playback
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"time"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/gin-gonic/gin"
)
type listEntryDuration time.Duration
func (d listEntryDuration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(d).Seconds())
}
type listEntry struct {
Start time.Time `json:"start"`
Duration listEntryDuration `json:"duration"`
}
func computeDurationAndConcatenate(recordFormat conf.RecordFormat, segments []*Segment) ([]listEntry, error) {
if recordFormat == conf.RecordFormatFMP4 {
out := []listEntry{}
var prevInit []byte
for _, seg := range segments {
err := func() error {
f, err := os.Open(seg.Fpath)
if err != nil {
return err
}
defer f.Close()
init, err := fmp4ReadInit(f)
if err != nil {
return err
}
_, err = f.Seek(0, io.SeekStart)
if err != nil {
return err
}
duration, err := fmp4ReadDuration(f)
if err != nil {
return err
}
if len(out) != 0 && fmp4CanBeConcatenated(
prevInit,
out[len(out)-1].Start.Add(time.Duration(out[len(out)-1].Duration)),
init,
seg.Start) {
prevStart := out[len(out)-1].Start
curEnd := seg.Start.Add(duration)
out[len(out)-1].Duration = listEntryDuration(curEnd.Sub(prevStart))
} else {
out = append(out, listEntry{
Start: seg.Start,
Duration: listEntryDuration(duration),
})
}
prevInit = init
return nil
}()
if err != nil {
return nil, err
}
}
return out, nil
}
return nil, fmt.Errorf("MPEG-TS format is not supported yet")
}
func (p *Server) onList(ctx *gin.Context) {
pathName := ctx.Query("path")
if !p.doAuth(ctx, pathName) {
return
}
pathConf, err := p.safeFindPathConf(pathName)
if err != nil {
p.writeError(ctx, http.StatusBadRequest, err)
return
}
if !pathConf.Playback {
p.writeError(ctx, http.StatusBadRequest, fmt.Errorf("playback is disabled on path '%s'", pathName))
return
}
segments, err := FindSegments(pathConf, pathName)
if err != nil {
if errors.Is(err, errNoSegmentsFound) {
p.writeError(ctx, http.StatusNotFound, err)
} else {
p.writeError(ctx, http.StatusBadRequest, err)
}
return
}
out, err := computeDurationAndConcatenate(pathConf.RecordFormat, segments)
if err != nil {
p.writeError(ctx, http.StatusInternalServerError, err)
return
}
ctx.JSON(http.StatusOK, out)
}

134
internal/playback/on_list_test.go

@ -1,134 +0,0 @@ @@ -1,134 +0,0 @@
package playback
import (
"encoding/json"
"net/http"
"net/url"
"os"
"path/filepath"
"testing"
"time"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require"
)
func TestOnList(t *testing.T) {
dir, err := os.MkdirTemp("", "mediamtx-playback")
require.NoError(t, err)
defer os.RemoveAll(dir)
err = os.Mkdir(filepath.Join(dir, "mypath"), 0o755)
require.NoError(t, err)
writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4"))
writeSegment2(t, filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4"))
writeSegment2(t, filepath.Join(dir, "mypath", "2009-11-07_11-23-02-500000.mp4"))
s := &Server{
Address: "127.0.0.1:9996",
ReadTimeout: conf.StringDuration(10 * time.Second),
PathConfs: map[string]*conf.Path{
"mypath": {
Playback: true,
RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"),
},
},
AuthManager: authManager,
Parent: &test.NilLogger{},
}
err = s.Initialize()
require.NoError(t, err)
defer s.Close()
u, err := url.Parse("http://myuser:mypass@localhost:9996/list")
require.NoError(t, err)
v := url.Values{}
v.Set("path", "mypath")
u.RawQuery = v.Encode()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
require.NoError(t, err)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
var out interface{}
err = json.NewDecoder(res.Body).Decode(&out)
require.NoError(t, err)
require.Equal(t, []interface{}{
map[string]interface{}{
"duration": float64(64),
"start": time.Date(2008, 11, 0o7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano),
},
map[string]interface{}{
"duration": float64(2),
"start": time.Date(2009, 11, 0o7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano),
},
}, out)
}
func TestOnListDifferentInit(t *testing.T) {
dir, err := os.MkdirTemp("", "mediamtx-playback")
require.NoError(t, err)
defer os.RemoveAll(dir)
err = os.Mkdir(filepath.Join(dir, "mypath"), 0o755)
require.NoError(t, err)
writeSegment1(t, filepath.Join(dir, "mypath", "2008-11-07_11-22-00-500000.mp4"))
writeSegment3(t, filepath.Join(dir, "mypath", "2008-11-07_11-23-02-500000.mp4"))
s := &Server{
Address: "127.0.0.1:9996",
ReadTimeout: conf.StringDuration(10 * time.Second),
PathConfs: map[string]*conf.Path{
"mypath": {
Playback: true,
RecordPath: filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f"),
},
},
AuthManager: authManager,
Parent: &test.NilLogger{},
}
err = s.Initialize()
require.NoError(t, err)
defer s.Close()
u, err := url.Parse("http://myuser:mypass@localhost:9996/list")
require.NoError(t, err)
v := url.Values{}
v.Set("path", "mypath")
u.RawQuery = v.Encode()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
require.NoError(t, err)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer res.Body.Close()
require.Equal(t, http.StatusOK, res.StatusCode)
var out interface{}
err = json.NewDecoder(res.Body).Decode(&out)
require.NoError(t, err)
require.Equal(t, []interface{}{
map[string]interface{}{
"duration": float64(62),
"start": time.Date(2008, 11, 0o7, 11, 22, 0, 500000000, time.Local).Format(time.RFC3339Nano),
},
map[string]interface{}{
"duration": float64(1),
"start": time.Date(2008, 11, 0o7, 11, 23, 2, 500000000, time.Local).Format(time.RFC3339Nano),
},
}, out)
}

149
internal/playback/segment.go

@ -1,149 +0,0 @@ @@ -1,149 +0,0 @@
package playback
import (
"fmt"
"io/fs"
"path/filepath"
"sort"
"strings"
"time"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/record"
)
// Segment is a recording segment.
type Segment struct {
Fpath string
Start time.Time
}
func findSegmentsInTimespan(
pathConf *conf.Path,
pathName string,
start time.Time,
duration time.Duration,
) ([]*Segment, error) {
if !pathConf.Playback {
return nil, fmt.Errorf("playback is disabled on path '%s'", pathName)
}
recordPath := record.PathAddExtension(
strings.ReplaceAll(pathConf.RecordPath, "%path", pathName),
pathConf.RecordFormat,
)
// we have to convert to absolute paths
// otherwise, recordPath and fpath inside Walk() won't have common elements
recordPath, _ = filepath.Abs(recordPath)
commonPath := record.CommonPath(recordPath)
end := start.Add(duration)
var segments []*Segment
err := filepath.Walk(commonPath, func(fpath string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
var pa record.Path
ok := pa.Decode(recordPath, fpath)
// gather all segments that starts before the end of the playback
if ok && !end.Before(pa.Start) {
segments = append(segments, &Segment{
Fpath: fpath,
Start: pa.Start,
})
}
}
return nil
})
if err != nil {
return nil, err
}
if segments == nil {
return nil, errNoSegmentsFound
}
sort.Slice(segments, func(i, j int) bool {
return segments[i].Start.Before(segments[j].Start)
})
// find the segment that may contain the start of the playback and remove all previous ones
found := false
for i := 0; i < len(segments)-1; i++ {
if !start.Before(segments[i].Start) && start.Before(segments[i+1].Start) {
segments = segments[i:]
found = true
break
}
}
// otherwise, keep the last segment only and check if it may contain the start of the playback
if !found {
segments = segments[len(segments)-1:]
if segments[len(segments)-1].Start.After(start) {
return nil, errNoSegmentsFound
}
}
return segments, nil
}
// FindSegments returns all segments of a path.
func FindSegments(
pathConf *conf.Path,
pathName string,
) ([]*Segment, error) {
if !pathConf.Playback {
return nil, fmt.Errorf("playback is disabled on path '%s'", pathName)
}
recordPath := record.PathAddExtension(
strings.ReplaceAll(pathConf.RecordPath, "%path", pathName),
pathConf.RecordFormat,
)
// we have to convert to absolute paths
// otherwise, recordPath and fpath inside Walk() won't have common elements
recordPath, _ = filepath.Abs(recordPath)
commonPath := record.CommonPath(recordPath)
var segments []*Segment
err := filepath.Walk(commonPath, func(fpath string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
var pa record.Path
ok := pa.Decode(recordPath, fpath)
if ok {
segments = append(segments, &Segment{
Fpath: fpath,
Start: pa.Start,
})
}
}
return nil
})
if err != nil {
return nil, err
}
if segments == nil {
return nil, errNoSegmentsFound
}
sort.Slice(segments, func(i, j int) bool {
return segments[i].Start.Before(segments[j].Start)
})
return segments, nil
}

142
internal/playback/server.go

@ -1,142 +0,0 @@ @@ -1,142 +0,0 @@
// Package playback contains the playback server.
package playback
import (
"errors"
"net"
"net/http"
"sync"
"time"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/protocols/httpp"
"github.com/bluenviron/mediamtx/internal/restrictnetwork"
"github.com/gin-gonic/gin"
)
var errNoSegmentsFound = errors.New("no recording segments found for the given timestamp")
type writerWrapper struct {
ctx *gin.Context
written bool
}
func (w *writerWrapper) Write(p []byte) (int, error) {
if !w.written {
w.written = true
w.ctx.Header("Accept-Ranges", "none")
w.ctx.Header("Content-Type", "video/mp4")
}
return w.ctx.Writer.Write(p)
}
// Server is the playback server.
type Server struct {
Address string
ReadTimeout conf.StringDuration
PathConfs map[string]*conf.Path
AuthManager *auth.Manager
Parent logger.Writer
httpServer *httpp.WrappedServer
mutex sync.RWMutex
}
// Initialize initializes Server.
func (p *Server) Initialize() error {
router := gin.New()
router.SetTrustedProxies(nil) //nolint:errcheck
group := router.Group("/")
group.GET("/list", p.onList)
group.GET("/get", p.onGet)
network, address := restrictnetwork.Restrict("tcp", p.Address)
var err error
p.httpServer, err = httpp.NewWrappedServer(
network,
address,
time.Duration(p.ReadTimeout),
"",
"",
router,
p,
)
if err != nil {
return err
}
p.Log(logger.Info, "listener opened on "+address)
return nil
}
// Close closes Server.
func (p *Server) Close() {
p.Log(logger.Info, "listener is closing")
p.httpServer.Close()
}
// Log implements logger.Writer.
func (p *Server) Log(level logger.Level, format string, args ...interface{}) {
p.Parent.Log(level, "[playback] "+format, args...)
}
// ReloadPathConfs is called by core.Core.
func (p *Server) ReloadPathConfs(pathConfs map[string]*conf.Path) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.PathConfs = pathConfs
}
func (p *Server) writeError(ctx *gin.Context, status int, err error) {
// show error in logs
p.Log(logger.Error, err.Error())
// add error to response
ctx.String(status, err.Error())
}
func (p *Server) safeFindPathConf(name string) (*conf.Path, error) {
p.mutex.RLock()
defer p.mutex.RUnlock()
_, pathConf, _, err := conf.FindPathConf(p.PathConfs, name)
return pathConf, err
}
func (p *Server) doAuth(ctx *gin.Context, pathName string) bool {
user, pass, hasCredentials := ctx.Request.BasicAuth()
err := p.AuthManager.Authenticate(&auth.Request{
User: user,
Pass: pass,
IP: net.ParseIP(ctx.ClientIP()),
Action: conf.AuthActionPlayback,
Path: pathName,
})
if err != nil {
if !hasCredentials {
ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`)
ctx.Writer.WriteHeader(http.StatusUnauthorized)
return false
}
var terr auth.Error
errors.As(err, &terr)
p.Log(logger.Info, "connection %v failed to authenticate: %v", httpp.RemoteAddr(ctx), terr.Message)
// wait some seconds to mitigate brute force attacks
<-time.After(auth.PauseAfterError)
ctx.Writer.WriteHeader(http.StatusUnauthorized)
return false
}
return true
}

40
internal/pprof/pprof.go

@ -2,18 +2,15 @@ @@ -2,18 +2,15 @@
package pprof
import (
"net"
"net/http"
"strings"
"time"
// start pprof
_ "net/http/pprof"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/protocols/httpp"
"github.com/bluenviron/mediamtx/internal/protocols/httpserv"
"github.com/bluenviron/mediamtx/internal/restrictnetwork"
)
@ -25,10 +22,9 @@ type pprofParent interface { @@ -25,10 +22,9 @@ type pprofParent interface {
type PPROF struct {
Address string
ReadTimeout conf.StringDuration
AuthManager *auth.Manager
Parent pprofParent
httpServer *httpp.WrappedServer
httpServer *httpserv.WrappedServer
}
// Initialize initializes PPROF.
@ -36,13 +32,13 @@ func (pp *PPROF) Initialize() error { @@ -36,13 +32,13 @@ func (pp *PPROF) Initialize() error {
network, address := restrictnetwork.Restrict("tcp", pp.Address)
var err error
pp.httpServer, err = httpp.NewWrappedServer(
pp.httpServer, err = httpserv.NewWrappedServer(
network,
address,
time.Duration(pp.ReadTimeout),
"",
"",
pp,
http.DefaultServeMux,
pp,
)
if err != nil {
@ -64,31 +60,3 @@ func (pp *PPROF) Close() { @@ -64,31 +60,3 @@ func (pp *PPROF) Close() {
func (pp *PPROF) Log(level logger.Level, format string, args ...interface{}) {
pp.Parent.Log(level, "[pprof] "+format, args...)
}
func (pp *PPROF) ServeHTTP(w http.ResponseWriter, r *http.Request) {
user, pass, hasCredentials := r.BasicAuth()
ip, _, _ := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr))
err := pp.AuthManager.Authenticate(&auth.Request{
User: user,
Pass: pass,
IP: net.ParseIP(ip),
Action: conf.AuthActionMetrics,
})
if err != nil {
if !hasCredentials {
w.Header().Set("WWW-Authenticate", `Basic realm="mediamtx"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
// wait some seconds to mitigate brute force attacks
<-time.After(auth.PauseAfterError)
w.WriteHeader(http.StatusUnauthorized)
return
}
http.DefaultServeMux.ServeHTTP(w, r)
}

15
internal/protocols/httpp/remote_addr.go

@ -1,15 +0,0 @@ @@ -1,15 +0,0 @@
package httpp
import (
"net"
"github.com/gin-gonic/gin"
)
// RemoteAddr returns the remote address of an HTTP client,
// with the IP replaced by the real IP passed by any proxy in between.
func RemoteAddr(ctx *gin.Context) string {
ip := ctx.ClientIP()
_, port, _ := net.SplitHostPort(ctx.Request.RemoteAddr)
return net.JoinHostPort(ip, port)
}

2
internal/protocols/httpp/handler_exit_on_panic.go → internal/protocols/httpserv/handler_exit_on_panic.go

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
package httpp
package httpserv
import (
"fmt"

2
internal/protocols/httpp/handler_filter_requests.go → internal/protocols/httpserv/handler_filter_requests.go

@ -1,4 +1,4 @@ @@ -1,4 +1,4 @@
package httpp
package httpserv
import (
"net/http"

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save