Compare commits

..

359 Commits

Author SHA1 Message Date
Alessandro Ros 50322fc14e
playback: do not concatenate segments with different tracks (#3197) 3 years ago
Dan Bason 87c0535823
Add option for ICE servers to be client only (#3164) 3 years ago
dependabot[bot] 60e7d77e41
build(deps): bump golang.org/x/crypto from 0.21.0 to 0.22.0 (#3192) 3 years ago
dependabot[bot] 56261cc5b2
build(deps): bump golang.org/x/term from 0.18.0 to 0.19.0 (#3191) 3 years ago
dependabot[bot] f5d9fde604
build(deps): bump github.com/pion/sdp/v3 from 3.0.8 to 3.0.9 (#3179) 3 years ago
dependabot[bot] d578fef78f
build(deps): bump github.com/MicahParks/keyfunc/v3 from 3.2.9 to 3.3.2 (#3168) 3 years ago
dependabot[bot] 0b9b02321c
build(deps): bump github.com/pion/rtp from 1.8.4 to 1.8.5 (#3178) 3 years ago
Mauricio Antunes 4666e5f427
Fix API version in docs (#3180) 3 years ago
dependabot[bot] a540454332
build(deps): bump github.com/pion/interceptor from 0.1.25 to 0.1.27 (#3171) 3 years ago
dependabot[bot] ac14a2ff7c
build(deps): bump github.com/datarhei/gosrt from 0.5.7 to 0.6.0 (#3154) 3 years ago
dependabot[bot] a11403fb6b
build(deps): bump github.com/pion/rtp from 1.8.3 to 1.8.4 (#3153) 3 years ago
Alessandro Ros 4e581af7a6
hls: fix directory creation when using hlsDirectory (#3135) (#3151) 3 years ago
Alessandro Ros 1d4ea2cd9a
hls: fix freeze in case of muxing errors (#3135) (#3150) 3 years ago
Alessandro Ros c7dbb951f3
update golangci-lint (#3149) 3 years ago
dependabot[bot] 29f0ded9f1
build(deps): bump google.golang.org/protobuf from 1.30.0 to 1.33.0 (#3139) 3 years ago
dependabot[bot] cc565865fe
build(deps): bump github.com/alecthomas/kong from 0.8.1 to 0.9.0 (#3133) 3 years ago
dependabot[bot] 158786373c
build(deps): bump github.com/MicahParks/keyfunc/v3 from 3.2.8 to 3.2.9 (#3136) 3 years ago
dependabot[bot] 6bcc7dcee0
build(deps): bump github.com/MicahParks/keyfunc/v3 from 3.2.7 to 3.2.8 (#3132) 3 years ago
Alessandro Ros 24cc62e344
hls: decrease number of idle connections kept open after a reconnection (#3128) 3 years ago
Jonathan Martin 1989997fe1
webrtc: fix memory leak when WHEP track gathering fails and decrease count of idle HTTP connections (#3124) 3 years ago
dependabot[bot] f8d2343f7b
build(deps): bump github.com/pion/sdp/v3 from 3.0.7 to 3.0.8 (#3120) 3 years ago
Jonathan Martin 732bf565bf
webrtc: fix deadlock when a WHEP source fails (#3062) (#3108) (#3110) 3 years ago
Alessandro Ros dd3b268346
do not switch to legacy authentication system when readUser, readPass, publishUser, publishPass are present but are empty (#3113) 3 years ago
dependabot[bot] 2c857fc329
build(deps): bump golang.org/x/crypto from 0.20.0 to 0.21.0 (#3103) 3 years ago
dependabot[bot] 2428e53579
build(deps): bump github.com/MicahParks/keyfunc/v3 from 3.2.5 to 3.2.7 (#3105) 3 years ago
dependabot[bot] 628e96e9b8
build(deps): bump github.com/golang-jwt/jwt/v5 from 5.2.0 to 5.2.1 (#3104) 3 years ago
dependabot[bot] 69383137bf
build(deps): bump github.com/pion/sdp/v3 (#3102) 3 years ago
Daniel Lorenzo bb46640998
Correction for missing go generate in run makefile (#3100) 3 years ago
dependabot[bot] 3eb35b26b9
build(deps): bump golang.org/x/term from 0.17.0 to 0.18.0 (#3098) 3 years ago
dependabot[bot] 26f4cb81d4
build(deps): bump golang.org/x/sys from 0.17.0 to 0.18.0 (#3099) 3 years ago
Alessandro Ros dec395cce8
update dependencies (#3096) 3 years ago
Alessandro Ros 9c6ba7e2c7
New authentication system (#1341) (#1992) (#2205) (#3081) 3 years ago
dependabot[bot] 765d29fc8e
build(deps): bump github.com/pion/rtcp from 1.2.13 to 1.2.14 (#3089) 3 years ago
dependabot[bot] a2518845f6
build(deps): bump github.com/stretchr/testify from 1.8.4 to 1.9.0 (#3090) 3 years ago
Alessandro Ros 44918fce0d
when stopping hooks, stop all their subprocesses too (#3004) (#3087) 3 years ago
dependabot[bot] a40ca33300
build(deps): bump golang.org/x/crypto from 0.19.0 to 0.20.0 (#3078) 3 years ago
github-actions[bot] a0be4ca05f
bump hls.js to v1.5.7 (#3072) 3 years ago
Alessandro Ros b6db3121b5
rtsp: add random value to timestamp of tracks from other protocols (#3071) 3 years ago
Alessandro Ros da7c5744b1
rtmp: add new AMF0 encoder and encoder (#3069) 3 years ago
Alessandro Ros e06155b9b0
update README (#3053) 3 years ago
Alessandro Ros c7bdcea741
move RTSP tests into internal/servers/rtsp (#3049) 3 years ago
Dan Bason e8b19b82d5
in hooks, allow replacing placeholders with environment (#3044) 3 years ago
Alessandro Ros 34dbcfb508
move WebRTC tests into internal/servers/webrtc (#3043) 3 years ago
Alessandro Ros a52f550ee6
webrtc: return an error when proxying stream with no tracks (#3042) 3 years ago
Alessandro Ros 6e721201ed
remove double 'v' from hls.js bump messages (#3040) 3 years ago
github-actions[bot] 679bad7fbf
bump hls.js to v1.5.6 (#3038) 3 years ago
Alessandro Ros 9e5de737f0
move SRT tests into internal/servers/srt (#3037) 3 years ago
Alessandro Ros ad58efe47d
move RTMP tests into internal/servers/rtmp (#3035) 3 years ago
Spencer Lowe e5e029a7f4
srt: add additional metrics (#2962) 3 years ago
dependabot[bot] 970c73639f
build(deps): bump github.com/bluenviron/mediacommon from 1.9.1 to 1.9.2 (#3030) 3 years ago
Alessandro Ros e46a124eb7
update documentation (#3025) 3 years ago
Alessandro Ros 942ecf43a4
fix double 'v' in automatic hls.js bump commits (#3020) 3 years ago
github-actions[bot] 992a8082b8
bump hls-js to vv1.5.5 (#3019) 3 years ago
Alessandro Ros ba69241377
hls: stop spamming 'stream doesn't contain any supported codec' when hlsAlwaysRemux is true (#3018) 3 years ago
Alessandro Ros 1ae3240b91
hls: fix crash when muxer is being recreated, improve performance (#3017) 3 years ago
Alessandro Ros b6eaa6bc18
move test utilities into 'test' (#3016) 3 years ago
Alessandro Ros c2883f2ce9
hls: when alwaysRemux is true, prevent clients from creating muxers (#3015) 3 years ago
Alessandro Ros 3161e73a58
rename httpserv into httpp (#3014) 3 years ago
Alessandro Ros 487f92ac55
hls: in logs, store both ip and port of incoming requests (#3013) 3 years ago
Alessandro Ros df3dfea132
fix compilation with Windows and git autocrlf (#3010) (#3011) 3 years ago
Alessandro Ros 9eb97ad3a0
remove hls.js from the repository and restore plain MIT license (#3008) 3 years ago
Alessandro Ros fcf649cdaf
tests: make sure that dates with decimal seconds can be parsed correctly (#3007) 3 years ago
github-actions[bot] 1b13018321
bump hls-js to v1.5.4 (#2999) 3 years ago
dependabot[bot] e9f26f32c4
build(deps): bump golang.org/x/crypto from 0.18.0 to 0.19.0 (#3002) 3 years ago
Alessandro Ros 22a589b724
stop logging HTTP requests twice (#2993) 3 years ago
Alessandro Ros b92c8c2613
update dependencies (#2989) 3 years ago
Alessandro Ros 0332ba59a0
api: add endpoints for recording management (#2901) (#2988) 3 years ago
Alessandro Ros 5e27304935
apidocs: group operations by using tags (#2987) 3 years ago
Alessandro Ros 695e327a03
playback: make 'format' parameter optional (#2980) 3 years ago
Alessandro Ros de9a456e98
rename 'API' into 'Control API' (#2981) 3 years ago
Alessandro Ros ff70f9022e
playback: accept durations written in seconds (#2979) 3 years ago
Alessandro Ros e6bf095a05
playback: add /list endpoint to list available timespans (#2978) 3 years ago
Alessandro Ros 4553fc267c
hls, webrtc: in web page, add shadow to messages (#2959) 3 years ago
Alessandro Ros b32bc8dee9
hls, webrtc: in web page, prevent video from overflowing (#2958) 3 years ago
Alessandro Ros 320f5a7a21
api: improve performance by using RWMutex (#2968) 3 years ago
github-actions[bot] 97c58b4530
bump hls-js to v1.5.3 (#2964) 3 years ago
Alessandro Ros 0433af66a3
hls, webrtc: in the web page, show connection errors to users (#2957) 3 years ago
Alessandro Ros 7d0e702f14
hls: fix infinite loop in web client when reading incompatible codecs (#2956) 3 years ago
Alessandro Ros 0f733bab26
add rpiCameraAWBGains (#2858) (#2954) 3 years ago
Alessandro Ros 60aaed935b
bump Linux Alpine to 3.19 (#2837) (#2953) 3 years ago
Alessandro Ros 7caa08ea36
restore link to pion/sdp (#2952) 3 years ago
Alessandro Ros 6f6f8e0994
prevent multiple crashes when reloading the configuration (#2945) 3 years ago
github-actions[bot] 2f35bbc5bc
bump hls-js to v1.5.2 (#2948) 3 years ago
dependabot[bot] 3f330cca30
build(deps): bump github.com/google/uuid from 1.5.0 to 1.6.0 (#2939) 3 years ago
Alessandro Ros cf7088a91b
update dependencies (#2935) 3 years ago
Alessandro Ros 0e1204a943
add infos about SRT standard stream ID to the README (#2934) 3 years ago
Alessandro Ros 57c2d5aecb
add playback server (#2452) (#2906) 3 years ago
dependabot[bot] fd2466a8e5
build(deps): bump github.com/bluenviron/mediacommon from 1.8.0 to 1.9.0 (#2928) 3 years ago
Alessandro Ros 9b270adc03
record: use reception time instead of current time in segment names (#2925) 3 years ago
Alessandro Ros f8a56aae91
rtmp: simplify Audio message structure (#2924) 3 years ago
Alessandro Ros 7b9617f2e7
api: return 404 when an entity is not found (#2582) (#2920) 3 years ago
Alessandro Ros b3eaec50c1
srt: support standard streamID syntax (#2469) (#2919) 3 years ago
Alessandro Ros dd7d7c6c5d
srt: wait some seconds before returning authentication errors (#2918) 3 years ago
dependabot[bot] 84333dc304
build(deps): bump github.com/datarhei/gosrt from 0.5.5 to 0.5.7 (#2912) 3 years ago
dependabot[bot] 5cdc19d3e9
build(deps): bump github.com/abema/go-mp4 from 1.1.1 to 1.2.0 (#2913) 3 years ago
dependabot[bot] e144f988aa
build(deps): bump github.com/bluenviron/mediacommon from 1.7.1 to 1.8.0 (#2910) 3 years ago
dependabot[bot] c85410ecaa
build(deps): bump github.com/bluenviron/gortsplib/v4 (#2911) 3 years ago
Alessandro Ros cd2495423a
do not wait for HTTP connections to close when shutting down the server (#2909) 3 years ago
Alessandro Ros 514036d41a
treat different RTSP formats as different tracks in logs and API (#2907) 3 years ago
Sijmen 397c58a882
Add Argon2 credential hash support (#2888) 3 years ago
Alessandro Ros 20bb9b90cd
support G711 tracks with multiple channels and custom sample rates (#2891) 3 years ago
github-actions[bot] a6c7d287a7
bump hls-js to v1.5.1 (#2903) 3 years ago
dependabot[bot] 120791b415
build(deps): bump github.com/bluenviron/mediacommon from 1.7.0 to 1.7.1 (#2897) 3 years ago
github-actions[bot] 584fdb72a0
bump hls-js to v1.5.0 (#2900) 3 years ago
dependabot[bot] cf68fe459d
build(deps): bump golang.org/x/crypto from 0.17.0 to 0.18.0 (#2896) 3 years ago
Alessandro Ros b8b64fda80
update dependencies (#2885) 3 years ago
Alessandro Ros 27975d8b67
rtmp: support publishing G711 and LPCM tracks (#2857) (#2884) 3 years ago
RdL bc7804cb33
Update README.md (#2870) 3 years ago
dependabot[bot] 86e7ee608a
build(deps): bump golang.org/x/term from 0.15.0 to 0.16.0 (#2873) 3 years ago
Alessandro Ros 7437ee7a09
update golangci-lint (#2868) 3 years ago
Alessandro Ros e50def6afd
update gohlslib (#2862) 3 years ago
Alessandro Ros 698963ad03
support recording G711 tracks with fMP4 (#2853) 3 years ago
dependabot[bot] ef2b6c740d
build(deps): bump github.com/bluenviron/gohlslib from 1.0.6 to 1.1.0 (#2852) 3 years ago
Alessandro Ros 598fadc9fb
api: add 'query' field to RTMP, RTSP, SRT and WebRTC clients (#2689) (#2844) 3 years ago
Alessandro Ros 1341421412
move api, metrics and pprof into dedicated packages (#2843) 3 years ago
James Bohnert 3ecd79f076
RunOn.. commands - Propagate errors in restart configurations (#2828) 3 years ago
Alessandro Ros 1feeba92b0
webrtc: prevent NotReadableError when publishing with Android (#2698) (#2842) 3 years ago
github-actions[bot] e6fec31516
bump hls-js to v1.4.14 (#2825) 3 years ago
dependabot[bot] d20071565f
build(deps): bump golang.org/x/crypto from 0.16.0 to 0.17.0 (#2823) 3 years ago
Alessandro Ros fe4f436bd3
rtmp: change default RTMPS port to 1936 when it is omitted in source (#2821) 3 years ago
Alessandro Ros 4e8b8a2014
rtmp, srt: fix output of 'is reading from' log entry (#2820) 3 years ago
Alessandro Ros b0ca00fca6
add instructions on cross compilation (#2817) 3 years ago
Alessandro Ros db52e94040
update issue template (#2815) 3 years ago
Alessandro Ros 94953f5d22
webrtc: support Chrome versions older than M72 (#2621) (#2814) 3 years ago
Alessandro Ros 89560c19a0
rtmp: fix parsing error caused by extended timestamps (#2393) (#2556) (#2384) (#1550) (#2564) (#2808) 3 years ago
Alessandro Ros 0c131a2e92
rpi: pass log level to libcamera (#2617) (#2811) 3 years ago
Alessandro Ros 22414bb38c
rtmp: return error in case of extended chunk stream IDs (#2806) 3 years ago
dependabot[bot] 1b71d6975a
build(deps): bump github.com/google/uuid from 1.4.0 to 1.5.0 (#2804) 3 years ago
dependabot[bot] bae9052f22
build(deps): bump github.com/pion/rtcp from 1.2.12 to 1.2.13 (#2801) 3 years ago
Alessandro Ros d261bfe773
support static sources in paths with regular expressions (#824) (#2799) 3 years ago
Alessandro Ros 9bb9d58cf8
update gortsplib (#2800) 3 years ago
Alessandro Ros 15e6c199b4
always use 'all_others' or 'all' after every other path configuration (#2798) 3 years ago
Alessandro Ros e06f4bc998
add instructions on OpenWrt service (#2795) 3 years ago
Alessandro Ros 5ee26130d2
rewrite OpenWrt installation procedure (#2794) 3 years ago
Alessandro Ros 11988249df
move servers into internal/servers (#2792) 3 years ago
github-actions[bot] 3891e7eb26
bump hls-js to v1.4.13 (#2791) 3 years ago
dependabot[bot] ea28a1fef2
build(deps): bump github.com/bluenviron/gortsplib/v4 from 4.6.0 to 4.6.1 (#2785) 3 years ago
Alessandro Ros b8dd7b9e52
add RTMPS metrics (#2783) 3 years ago
Alessandro Ros ed72fa7db1
fix crash when requesting metrics and RTMP, SRT or WebRTC servers are not present anymore (#2782) 3 years ago
Alessandro Ros 20123fd5b9
record: rename segmentPath into path (#2777) 3 years ago
Alessandro Ros 7c8e593b0b
record: normalize decoding and encoding of segment paths (#2775) 3 years ago
Alessandro Ros 5da2ded815
record: rename recFormat into format (#2776) 3 years ago
Neeraj Kanhere 47bd7352f0
support unix timestamp in filenames of recorded segments (#2774) 3 years ago
Alessandro Ros 3e12f83732
hls, webrtc: fix appending slash to paths that contain slashes (#2773) 3 years ago
Alessandro Ros aade2eedb9
hls, webrtc: prevent XSS attack when appending slash to paths (#2766) (#2767) (#2772) 3 years ago
Alessandro Ros 4ccb245feb
webrtc: fix propagating query parameters when appending slash to paths (#2771) 3 years ago
Alessandro Ros 50e7b038c4
hls: fix appending slash when behind a reverse proxy (#2770) 3 years ago
Alessandro Ros 0e5e3324a7
rpicamera: allow to change bitrate and IDR period dynamically (#2703) (#2764) 3 years ago
Alessandro Ros 6ca59e0ed8
bump gosrt (#2761) 3 years ago
dependabot[bot] fe9426cc05
build(deps): bump golang.org/x/crypto from 0.15.0 to 0.16.0 (#2751) 3 years ago
Alessandro Ros ce45498769
move hooks into dedicated package (#2746) 3 years ago
Alessandro Ros d640dcf14d
fix missing comment in conf (#2745) 3 years ago
Alessandro Ros e4f86be005
rename github workflow (#2744) 3 years ago
Alessandro Ros 81c803ba64
webrtc: fix bad quality when converting Opus from WebRTC to LL-HLS (#2499) (#2740) 3 years ago
dependabot[bot] db5ba9903f
build(deps): bump github.com/bluenviron/gohlslib from 1.0.5 to 1.0.6 (#2736) 3 years ago
Alessandro Ros dc453620fe
record: fix invalid segment duration in case of offsets between video/audio (#2477) (#2715) 3 years ago
Alessandro Ros e6f861ee95
rename 'binaries' workflow into 'nightly_binaries' (#2714) 3 years ago
Eng Zer Jun f335fc67f9
test: use `t.Setenv` to set env vars in tests (#2722) 3 years ago
dependabot[bot] dee7176cb0
build(deps): bump github.com/bluenviron/mediacommon from 1.5.0 to 1.5.1 (#2711) 3 years ago
Alessandro Ros c3d9be322d
allow using 'fallback' with static sources (#2606) (#2706) 3 years ago
Bohdan Cherniakh 4fa6c16c85
Add query as optional block for SRT publish and read (#2656) 3 years ago
Alessandro Ros 3277765851
apidocs: add missing recording settings to PathConf (#2705) 3 years ago
dependabot[bot] 09f43d9764
build(deps): bump github.com/bluenviron/gortsplib/v4 from 4.5.0 to 4.6.0 (#2702) 3 years ago
Alessandro Ros 42150c7ae5
update readme (#2695) 3 years ago
Alessandro Ros a760a98bcc
webrtc: fix crash when reading from path 'publish' (#2688) (#2692) 3 years ago
Alessandro Ros e8f57153d5
after a release, post to issues once (#2691) 3 years ago
Alessandro Ros 7a1e155531
update dependencies (#2687) 3 years ago
Alessandro Ros 687d8685ef
webrtc: improve connectivity mechanism (#2686) 3 years ago
Alessandro Ros 4cf8948fe6
automatically inform authors of GitHub issues about new releases (#2685) 3 years ago
Alessandro Ros 83a3086de7
webrtc: prevent pion/webrtc from writing log lines (#2681) 3 years ago
dependabot[bot] 5ae35af464
build(deps): bump github.com/pion/webrtc/v3 from 3.2.21 to 3.2.22 (#2675) 3 years ago
dependabot[bot] f44d80867f
build(deps): bump github.com/pion/rtp from 1.8.2 to 1.8.3 (#2677) 3 years ago
dependabot[bot] 34275ca40d
build(deps): bump github.com/pion/rtcp from 1.2.11 to 1.2.12 (#2676) 3 years ago
Alessandro Ros 2fe31a2421
record: allow using special characters in recording path (#2674) 3 years ago
Alessandro Ros d51baa04f7
record: fix deleting segments in case of relative paths (#2526) (#2673) 3 years ago
Alessandro Ros ef19552632
fix setting 'recordDeleteAfter' to zero (#2670) (#2671) 3 years ago
dependabot[bot] fb585b5b72
build(deps): bump golang.org/x/crypto from 0.14.0 to 0.15.0 (#2668) 3 years ago
dependabot[bot] b87a3ca735
build(deps): bump golang.org/x/term from 0.13.0 to 0.14.0 (#2667) 3 years ago
dependabot[bot] ca2e3a9ebe
build(deps): bump github.com/pion/rtcp from 1.2.10 to 1.2.11 (#2669) 3 years ago
Alessandro Ros cb04d28f6e
metrics: expose state of WebRTC sessions (#2662) 3 years ago
Alessandro Ros f82c6e3654
tests: fix race condition in TestPathRunOnDemand (#2663) 3 years ago
Dr. Ralf S. Engelschall 4bf0d10079
metrics: add paths_bytes_sent, srt_conns, srt_conns_bytes_received, srt_conns_bytes_sent (#2620) (#2619) (#2629) 3 years ago
dependabot[bot] 2a6060d302
build(deps): bump github.com/gorilla/websocket from 1.5.0 to 1.5.1 (#2652) 3 years ago
Alessandro Ros 5dae270900
srt: fix race condition when disposing late packets (#2648) 3 years ago
Alessandro Ros 621a10a8e9
update gortsplib (#2646) 3 years ago
Alessandro Ros 813611057d
add runOnUnDemand hook (#2645) 3 years ago
Alessandro Ros 1d1d64cb89
rename sourceProtocol into rtspTransport, sourceAnyPortEnable into rtspAnyPort (#2644) 3 years ago
Alessandro Ros faf7218fda
webrtc: restore compatibility when running behind a proxy, in a subpath (#2638) 3 years ago
Alessandro Ros 4f876ed207
fix crash when publishing to a path with 'runOnDemand' from outside 'runOnDemand' (#2636) (#2637) 3 years ago
Alessandro Ros d41e4025de
hls: format code (#2634) 3 years ago
Dr. Ralf S. Engelschall 39a239caba
hls: bugfix, stability and resilience improvements in the webpage 3 years ago
Dr. Ralf S. Engelschall 42afc8d327
fix SRT URL in README by replacing 'publish' with 'read' (#2628) 3 years ago
Alessandro Ros 870238607c
update docs (#2630) 3 years ago
Alessandro Ros 15f1c73314
hls: apply readTimeout to HLS sources (#2627) 3 years ago
Alessandro Ros 68b862c7f6
webrtc: allow using sourceFingerprint with WebRTC sources (#2618) (#2626) 3 years ago
Lukinoh 107a9a4281
webrtc: add options (width, height, framerate, audio capture) and store parameters in URL (#1837) (#2167) (#2584) 3 years ago
dependabot[bot] 63c8feccab
build(deps): bump github.com/pion/interceptor from 0.1.24 to 0.1.25 (#2622) 3 years ago
Alessandro Ros 43d41c070b
move static sources into dedicated package (#2616) 3 years ago
Alessandro Ros e9528c0917
api: return empty list when page is empty (#2604) (#2614) 3 years ago
Alessandro Ros ecee2af05c
webrtc: fix crash in case of errors during PATCH (#2609) (#2613) 3 years ago
Alessandro Ros a2c092ea44
formatprocessor: add fuzz tests (#2612) 3 years ago
Alessandro Ros 7fb3b749d5
rtmp: fix publishing screen with iOS StreamLabs (#2352) (#2611) 3 years ago
Alessandro Ros 4c25529369
move rpicamera into internal/protocols (#2607) 3 years ago
Alessandro Ros 4b4d57f18e
api: add path name to config/paths/list and config/paths/get (#2535) (#2596) 3 years ago
Alessandro Ros 6e7a6fe71a
update dependencies (#2597) 3 years ago
Alessandro Ros bbb989ee87
api: return full configuration in config/paths/list and config/paths/get (#2535) (#2595) 3 years ago
Alessandro Ros 64eb90738a
webrtc: return detailed errors in responses (#2594) 3 years ago
Alessandro Ros c42fa76afd
rpi: switch default autofocus mode to 'continuous' (#2591) 3 years ago
Alessandro Ros f11f39f023
confwatcher: remove redundant code (#2592) 3 years ago
James Bohnert 88dd8d23f4
evaluate confwatcher event paths to ensure consistency with stored path (#2586) 3 years ago
Alessandro Ros 6d27d690dc
update docs (#2590) 3 years ago
Alessandro Ros cde19097bd
api: send error messages in response body (#2518) (#2583) 3 years ago
Alessandro Ros 07ff79f553
api: return 500 instead of 404 in case of non-existing items (#2582) 3 years ago
Alessandro Ros 6af27fdcf8
improve feature request template (#2580) 3 years ago
Alessandro Ros 99bc327d67
move protocol-related code into internal/protocols (#2572) 3 years ago
Alessandro Ros 3ebc585539
restart recordings in case of errors (#2439) (#2571) 3 years ago
Alessandro Ros 38f228c739
webrtc: improve stability by reordering incoming packets (#2570) 3 years ago
dependabot[bot] 20a16125ae
build(deps): bump github.com/google/uuid from 1.3.1 to 1.4.0 (#2569) 3 years ago
Alessandro Ros 6d616f130e
bump golangci-lint (#2560) 3 years ago
Alessandro Ros 28452acf56
move webrtc utilities into internal/webrtc (#2559) 3 years ago
Rui Lopes 9f5169ba26
webrtc: support WHIP/WHEP DELETE method (#2507) 3 years ago
Alessandro Ros 4dc6e338dd
fix crash when setting deprecated settings with environment (#2529) (#2550) 3 years ago
dependabot[bot] f237a1dc28
build(deps): bump github.com/fsnotify/fsnotify from 1.6.0 to 1.7.0 (#2553) 3 years ago
Alessandro Ros 141ee331c6
rpi camera: fix Raspberry Pi Camera 3 auto focus (#2326) (#2552) 3 years ago
Alessandro Ros 55b8985c8d
bump Go to 1.21 (#2546) 3 years ago
Alessandro Ros 4828736124
webrtc: fix compatibility with Alexa offers (#2544) 3 years ago
guangwu b3a3812097
fix: typo (#2532) 3 years ago
dependabot[bot] f47f2ca49e
build(deps): bump github.com/pion/interceptor from 0.1.23 to 0.1.24 (#2530) 3 years ago
Alessandro Ros 3a5bb06e26
add environment variable MTX_QUERY to some hooks (#2483) (#2522) 3 years ago
Alessandro Ros 91f83a8c45
rtmp: fix compatibility with nginx-rtmp-module (#2383) (#2520) 3 years ago
dependabot[bot] 648e90f72a
build(deps): bump github.com/pion/interceptor from 0.1.22 to 0.1.23 (#2515) 3 years ago
Alessandro Ros c25b51cc7e
update dependencies (#2506) 3 years ago
Alessandro Ros 95ab9375c7
support recording to MPEG-TS (#2505) 3 years ago
Alessandro Ros 4ec12a6c8b
add runOnRecordSegmentCreate hook (#2451) (#2503) 3 years ago
dependabot[bot] 38a2a127f5
build(deps): bump golang.org/x/net from 0.15.0 to 0.17.0 (#2501) 3 years ago
dependabot[bot] b220c8c020
build(deps): bump github.com/alecthomas/kong from 0.8.0 to 0.8.1 (#2493) 3 years ago
dependabot[bot] 9de64238a5
build(deps): bump github.com/pion/interceptor from 0.1.21 to 0.1.22 (#2482) 3 years ago
Aakash Singh 18733294c0
webrtc: expose ice servers on OPTIONS CORS requests (#2479) 3 years ago
Alessandro Ros 6c727b4472
rename 'all' path configuration into 'all_others' (#2443) 3 years ago
Alessandro Ros 8a633d2b79
allow setting different recording parameters for each path (#2410) (#2457) 3 years ago
Alessandro Ros 9a01ab7fd5
allow changing default path settings; bump API in order to allow so (#2455) 3 years ago
PieterFabry 3c4039b81f
Supports webrtc interface filtering on server (#2460) 3 years ago
Alessandro Ros bb8c02b9f0
fix 'fragment sequence discontinuity' warning when reading record segments with VLC (#2476) 3 years ago
Alessandro Ros ca2a4873a6
support recording LPCM tracks (#2475) 3 years ago
Alessandro Ros 64f4185537
webrtc: optimize publish page for mobile devices (#2066) (#2472) 3 years ago
Alessandro Ros 3b4cac5af7
webrtc: disallow publishing screen on devices that don't support it (#2066) (#2471) 3 years ago
Alessandro Ros 412a48ac74
webrtc: fix reading Opus stereo tracks with Chrome (#2043) (#2470) 3 years ago
Alessandro Ros c37fd38f5c
webrtc: print lost packets (#2468) 3 years ago
dependabot[bot] a6f929d111
build(deps): bump golang.org/x/crypto from 0.13.0 to 0.14.0 (#2465) 3 years ago
dependabot[bot] 7b75e5cbe9
build(deps): bump github.com/pion/interceptor from 0.1.20 to 0.1.21 (#2456) 3 years ago
Rui Lopes 215f88e2dd
webrtc: add Location header to CORS-allowed headers (#2453) 3 years ago
Alessandro Ros 4ba2dc1b34
apidocs: remove invalid value from PathSourceOrReader (#2450) 3 years ago
dependabot[bot] 34cdef1c49
build(deps): bump github.com/abema/go-mp4 from 1.1.0 to 1.1.1 (#2447) 3 years ago
Alessandro Ros 84b2293c9c
fix typo in README (#2446) 3 years ago
Alessandro Ros 9c6168e7e3
print path of configuration file (#2441) 3 years ago
Alessandro Ros d38061b704
add discussions template (#2444) 3 years ago
dependabot[bot] fdf4f7a16e
build(deps): bump github.com/pion/interceptor from 0.1.19 to 0.1.20 (#2437) 3 years ago
Alessandro Ros eb975027b2
add runOnRecordSegmentComplete and rclone integration (#2404) (#2428) 3 years ago
Alessandro Ros 2d929e1132
move 'srtReadPassphrase' into the right section (#2435) 3 years ago
Alessandro Ros 442a48363c
allow to start/stop recording without disconnecting clients (#2395) (#2434) 3 years ago
Paxx 72e74b6456
api: fix crash when retrieving RTMP and SRT connections (#2430) 3 years ago
Alessandro Ros 42aa979309
api: save errors in logs (#2426) 3 years ago
Alessandro Ros 61b77a3ff9
api: return 400 in case of non-existent config fields (#2425) 3 years ago
Alessandro Ros d7d96230ff
rtmp: fix compatibility issue with some DJI drones (#2375) (#2409) 3 years ago
dependabot[bot] 9044e88c9d
build(deps): bump github.com/abema/go-mp4 from 1.0.0 to 1.1.0 (#2421) 3 years ago
dependabot[bot] 0389d7ada0
build(deps): bump github.com/pion/webrtc/v3 from 3.2.20 to 3.2.21 (#2414) 3 years ago
dependabot[bot] 5f66cc83d8
build(deps): bump github.com/pion/rtp from 1.8.1 to 1.8.2 (#2415) 3 years ago
dependabot[bot] b4c73747d3
build(deps): bump github.com/abema/go-mp4 from 0.13.0 to 1.0.0 (#2413) 3 years ago
Alessandro Ros b1f74c30c0
bump dependencies (#2405) 3 years ago
Alessandro Ros f1e28d053f
webrtc: fix ETag header name according to specification (#2396) (#2401) 3 years ago
rmcnew 75f518a827
Support SRT encryption passphrases on configured paths (#2385) 3 years ago
Alessandro Ros cadc6b3ea7
rename 'external commands' into 'hooks' (#2400) 3 years ago
Alessandro Ros 3a7d86ec03
normalize configuration (#2399) 3 years ago
Alessandro Ros 1f11d95059
support recording M-JPEG tracks (#2391) 3 years ago
Alessandro Ros d07ba5983e
update gortsplib (#2390) 3 years ago
Alessandro Ros e4df14a447
fix timestamp of outgoing RTSP/RTP packets in case of aggregated access units (#2389) 3 years ago
Alessandro Ros 89cf3bb2fa
fix crash when processing H265 (#2378) (#2381) 3 years ago
Alessandro Ros fadfda936d
support AC-3 tracks in SRT and UDP; support recording AC-3 tracks (#2376) 3 years ago
Alessandro Ros 8fd7019f2a
rpi camera: add additional checks on configuration (#2368) 3 years ago
Alessandro Ros b86dc979ca
fix default value of some settings (#2367) 3 years ago
Alessandro Ros 7ca2571dc3
fix race condition wen record agent is closing (#2369) 3 years ago
Alessandro Ros ac10102329
automatically set 'record: yes' when not specified (#2366) 3 years ago
Alessandro Ros 338456423e
update recordDeleteAfter documentation (#2361) (#2362) 3 years ago
Alessandro Ros bedfa9651a
fix windows build (#2360) 3 years ago
Alessandro Ros 1f840a1bea
update dependencies (#2359) 3 years ago
Alessandro Ros f2f417e451
search for configuration file in various paths, print paths if configuration is not found (#1993) (#2276) (#2357) 3 years ago
Alessandro Ros 64d9060560
add additional environment variables to custom commands (#1414) (#2356) 3 years ago
Alessandro Ros ed77560811
add runOnDisconnect, runOnNotReady, runOnUnread (#1464) (#2355) 3 years ago
Alessandro Ros 73ddb21e63
implement native recording (#1399) (#2255) 3 years ago
Alessandro Ros b7e7758293
srt, udp: support publishing and reading MPEG-1/2/4 video with SRT and UDP/MPEG-TS (#2277) 3 years ago
Alessandro Ros c4cb4200ff
split RTP packet handling from data handling (#2337) 3 years ago
Alessandro Ros f786f64690
apidocs: mark discrete parameters as integers (#2331) (#2354) 3 years ago
Alessandro Ros ba954d5b93
update specs (#2344) 3 years ago
dependabot[bot] 8197831f49
build(deps): bump github.com/bluenviron/mediacommon from 1.1.1 to 1.2.0 (#2339) 3 years ago
dependabot[bot] 61a0bba2c5
build(deps): bump github.com/pion/webrtc/v3 from 3.2.19 to 3.2.20 (#2340) 3 years ago
Alessandro Ros a005de1aa0
udp: fix reading two streams with same port and different multicast IP (#2133) (#2332) 3 years ago
dependabot[bot] 2a26962167
build(deps): bump github.com/pion/interceptor from 0.1.18 to 0.1.19 (#2329) 3 years ago
dependabot[bot] 937fa3a2dd
build(deps): bump github.com/pion/webrtc/v3 from 3.2.18 to 3.2.19 (#2328) 3 years ago
Alessandro Ros f07886db5f
print the reason why a source is started or stopped (#2322) 3 years ago
Alessandro Ros 4b5a977c86
rtsp: normalize debug logging of requests / responses (#2321) 3 years ago
dependabot[bot] 6402e18b5c
build(deps): bump golang.org/x/net from 0.14.0 to 0.15.0 (#2301) 3 years ago
dependabot[bot] 6d9c8ffb89
build(deps): bump github.com/pion/ice/v2 from 2.3.10 to 2.3.11 (#2300) 3 years ago
dependabot[bot] 5f2b1114d1
build(deps): bump golang.org/x/crypto from 0.12.0 to 0.13.0 (#2299) 3 years ago
Alessandro Ros 5b92bd5699
fix compatibility with RTMP Dahua cameras (#2289) (#769) (#2298) 3 years ago
dependabot[bot] 608b373468
build(deps): bump github.com/pion/webrtc/v3 from 3.2.17 to 3.2.18 (#2292) 3 years ago
dependabot[bot] 2e554c4d6c
build(deps): bump golang.org/x/term from 0.11.0 to 0.12.0 (#2294) 3 years ago
dependabot[bot] bec9852934
build(deps): bump github.com/bluenviron/gortsplib/v4 from 4.0.0 to 4.0.1 (#2293) 3 years ago
github-actions[bot] 82714fddcd
bump hls-js to v1.4.12 (#2283) 3 years ago
Alessandro Ros ffa34428fc
fix bug that prevented multiple readers from accessing the same stream (#2281) (#2282) 3 years ago
Alessandro Ros 966bec88c6
bump gortsplib, gohlslib, mediacommon (#2279) 3 years ago
Alessandro Ros 5a40a06e9e
fix changing log level with hot reloading or API (#2278) 3 years ago
Alessandro Ros 95baade478
srt: fix memory leak during reader disconnection (#2273) 3 years ago
Alessandro Ros fc353ce66b
rtmp: fix RTMPE handshake error when a public key starts with zero (#2269) 3 years ago
Alessandro Ros f69be81e20
optimize generation of docker images (#2267) 3 years ago
Alessandro Ros 90bd6cb12b
update dependencies (#2266) 3 years ago
Alessandro Ros 5fb7f4e846
force all readers to use an asynchronous writer (#2265) 3 years ago
Alessandro Ros 30a69a7722
fix maxReaders limit in case of multiple tracks (#2246) (#2264) 3 years ago
Alessandro Ros bd1cb35022
fix conversion of AV1/VP9 tracks from HLS/RTMP to RTSP (#2263) 3 years ago
Alessandro Ros 8e955d2119
hls: return 404 when requesting hls.min.js.map (#2262) 3 years ago
SwhiG e74c45865a
Update README.md (#2256) 3 years ago
Alessandro Ros 30b7245bb9
limit logging of decode errors (#2253) 3 years ago
Alessandro Ros 34dc84de90
rtmp: add limit on message body size (#2252) 3 years ago
Alessandro Ros b72f3577c8
print warning when the write queue is full (#2251) 3 years ago
Alessandro Ros d6bdf4bf92
bump github.com/datarhei/gosrt to v0.5.4 (#2250) 3 years ago
Alessandro Ros cf86dbb303
switch to gortsplib/v4 (#2244) 3 years ago
Alessandro Ros 055767fef0
fix manual benchmarks (#2249) 3 years ago
Alessandro Ros bf8e69ea89
rename readBufferCount into writeQueueSize (#2248) 3 years ago
Alessandro Ros e0fb11040e
move units into dedicated package (#2245) 3 years ago
Alessandro Ros 23ddaac481
support publishing VP9 tracks with RTMP (#2247) 3 years ago
Alessandro Ros 482266ae95
hls source: fix formatting debug log messages (#2243) 3 years ago
github-actions[bot] de90baa697
bump hls-js to v1.4.10 (#2239) 3 years ago
Alessandro Ros d93d21ebbb
fix workflow (#2238) 3 years ago
Alessandro Ros eefc608549
fix workflow (#2237) 3 years ago
Alessandro Ros 1e15d4995c
embed hls.js into the server (#2202) (#2236) 3 years ago
Alessandro Ros 1133c734ab
support publishing AV1/H265 with OBS 30 (#2217) (#2234) 3 years ago
Xavier Hallade accfc49f9c
allow RTMP streaming with codecid=av01 or hvc1 (#2232) 3 years ago
dependabot[bot] c4409026e6
build(deps): bump github.com/pion/webrtc/v3 from 3.2.16 to 3.2.17 (#2229) 3 years ago
dependabot[bot] e380872dad
build(deps): bump github.com/google/uuid from 1.3.0 to 1.3.1 (#2228) 3 years ago
dependabot[bot] 858e68aa1d
build(deps): bump github.com/pion/webrtc/v3 from 3.2.15 to 3.2.16 (#2220) 3 years ago
dependabot[bot] 5e095971c4
build(deps): bump github.com/pion/webrtc/v3 from 3.2.14 to 3.2.15 (#2216) 3 years ago
Alessandro Ros a29a4c7de7
hls: fix wrong protocol sent to external authentication server (#2213) 3 years ago
Alessandro Ros 7e0fb20eed
add instructions on how to forward streams (#2212) 3 years ago
Alessandro Ros d289b9872e
make sure that GStreamer pipelines in README use yuv420 (#2211) 3 years ago
Alessandro Ros 659f19f8bb
enable errcheck (#2201) 3 years ago
Alessandro Ros 7001164e2f
simplify sample SRT read URL (#2196) 3 years ago
Alessandro Ros e937e37d4f
update Linux Alpine (#2195) 3 years ago
Alessandro Ros 5244e056f8
update gofumpt (#2194) 3 years ago
Alessandro Ros 7e180ceea2
rtmp: support ingesting RTMPE streams (#2189) 3 years ago
Alessandro Ros 57a436b0d5
add security policy (#2185) 3 years ago
Alessandro Ros 6f65aed1cb
fix typo in README (#2184) 3 years ago
Alessandro Ros 8357f294f6
update readme (#2183) 3 years ago
Alessandro Ros 27260572fc
fix make binaries (#2179) 3 years ago
Alessandro Ros 7e63b995bb
update dependencies (#2178) 3 years ago
Daniel 36e608902d
Add video player options via query string (#2145) 3 years ago
Alessandro Ros a3e5dff488
update readme (#2177) 3 years ago
Alessandro Ros cffbf59898
update codec checking tool (#2174) 3 years ago
Alessandro Ros 161a9b54b2
update dependencies (#2176) 3 years ago
dependabot[bot] bc8dcc4bb9
build(deps): bump github.com/pion/ice/v2 from 2.3.9 to 2.3.10 (#2171) 3 years ago
dependabot[bot] be0f454691
build(deps): bump golang.org/x/net from 0.13.0 to 0.14.0 (#2170) 3 years ago
  1. 1
      .dockerignore
  2. 16
      .github/DISCUSSION_TEMPLATE/questions.yml
  3. 2
      .github/ISSUE_TEMPLATE/bug.md
  4. 2
      .github/ISSUE_TEMPLATE/config.yml
  5. 4
      .github/ISSUE_TEMPLATE/feature.md
  6. 65
      .github/workflows/bump_hls_js.yml
  7. 18
      .github/workflows/code_lint.yml
  8. 8
      .github/workflows/code_test.yml
  9. 4
      .github/workflows/issue_lint.yml
  10. 4
      .github/workflows/issue_lock.yml
  11. 4
      .github/workflows/nightly_binaries.yml
  12. 51
      .github/workflows/release.yml
  13. 1
      .gitignore
  14. 45
      .golangci.yml
  15. 12
      Makefile
  16. 1139
      README.md
  17. 3
      SECURITY.md
  18. 1337
      apidocs/openapi.yaml
  19. 5
      bench/proxy/Dockerfile
  20. 16
      bench/proxy/start.sh
  21. 5
      bench/publish/Dockerfile
  22. 4
      bench/publish/start.sh
  23. 5
      bench/read/Dockerfile
  24. 6
      bench/read/start.sh
  25. 71
      go.mod
  26. 152
      go.sum
  27. 1186
      internal/api/api.go
  28. 701
      internal/api/api_test.go
  29. 139
      internal/api/record.go
  30. 76
      internal/asyncwriter/async_writer.go
  31. 22
      internal/asyncwriter/async_writer_test.go
  32. 327
      internal/auth/manager.go
  33. 309
      internal/auth/manager_test.go
  34. 52
      internal/conf/auth_action.go
  35. 15
      internal/conf/auth_internal_users.go
  36. 67
      internal/conf/auth_method.go
  37. 763
      internal/conf/conf.go
  38. 203
      internal/conf/conf_test.go
  39. 88
      internal/conf/credential.go
  40. 151
      internal/conf/credential_test.go
  41. 13
      internal/conf/encryption.go
  42. 134
      internal/conf/env/env.go
  43. 250
      internal/conf/env/env_test.go
  44. 41
      internal/conf/global.go
  45. 11
      internal/conf/hls_variant.go
  46. 84
      internal/conf/ip_networks.go
  47. 66
      internal/conf/ips_or_cidrs.go
  48. 11
      internal/conf/log_destination.go
  49. 11
      internal/conf/log_level.go
  50. 60
      internal/conf/optional_global.go
  51. 70
      internal/conf/optional_path.go
  52. 600
      internal/conf/path.go
  53. 13
      internal/conf/protocol.go
  54. 56
      internal/conf/record_format.go
  55. 63
      internal/conf/rtsp_auth_methods.go
  56. 43
      internal/conf/rtsp_range_type.go
  57. 21
      internal/conf/rtsp_transport.go
  58. 6
      internal/conf/string_duration.go
  59. 6
      internal/conf/string_size.go
  60. 7
      internal/conf/webrtc_ice_server.go
  61. 14
      internal/confwatcher/confwatcher.go
  62. 24
      internal/confwatcher/confwatcher_test.go
  63. 926
      internal/core/api.go
  64. 154
      internal/core/api_defs.go
  65. 1004
      internal/core/api_test.go
  66. 183
      internal/core/authentication.go
  67. 847
      internal/core/core.go
  68. 152
      internal/core/core_test.go
  69. 204
      internal/core/hls_http_server.go
  70. 68
      internal/core/hls_index.html
  71. 323
      internal/core/hls_manager.go
  72. 220
      internal/core/hls_manager_test.go
  73. 670
      internal/core/hls_muxer.go
  74. 238
      internal/core/hls_source.go
  75. 208
      internal/core/hls_source_test.go
  76. 23
      internal/core/ip.go
  77. 261
      internal/core/metrics.go
  78. 376
      internal/core/metrics_test.go
  79. 1122
      internal/core/path.go
  80. 569
      internal/core/path_manager.go
  81. 239
      internal/core/path_manager_test.go
  82. 797
      internal/core/path_test.go
  83. 62
      internal/core/pprof.go
  84. 7
      internal/core/publisher.go
  85. 7
      internal/core/reader.go
  86. 17
      internal/core/restrict_network.go
  87. 139
      internal/core/rpicamera_source.go
  88. 763
      internal/core/rtmp_conn.go
  89. 46
      internal/core/rtmp_listener.go
  90. 332
      internal/core/rtmp_server.go
  91. 377
      internal/core/rtmp_server_test.go
  92. 206
      internal/core/rtmp_source.go
  93. 147
      internal/core/rtmp_source_test.go
  94. 228
      internal/core/rtsp_conn.go
  95. 454
      internal/core/rtsp_server.go
  96. 422
      internal/core/rtsp_server_test.go
  97. 428
      internal/core/rtsp_session.go
  98. 201
      internal/core/rtsp_source.go
  99. 300
      internal/core/rtsp_source_test.go
  100. 48
      internal/core/source.go
  101. Some files were not shown because too many files have changed in this diff Show More

1
.dockerignore

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

16
.github/DISCUSSION_TEMPLATE/questions.yml

@ -0,0 +1,16 @@
body:
- type: textarea
attributes:
label: Question
validations:
required: true
- type: markdown
attributes:
value: |
Note: If you are asking for help because you're having trouble doing something, provide enough informations to replicate the problem. In particular, include in the question:
* the server version you are using
* precise instructions on how to replicate the problem
* server logs with setting `logLevel` set to `debug`

2
.github/ISSUE_TEMPLATE/bug.md

@ -63,7 +63,7 @@ yes / no
<!-- <!--
If the bug arises when using MediaMTX with an external hardware or software, the most helpful content you can provide is a dump of the data exchanged between the server and the target (network dump), that can be generated in this way: If the bug arises when using MediaMTX with an external hardware or software, the most helpful content you can provide is a dump of the data exchanged between the server and the target (network dump), that can be generated in this way:
1) Download wireshark (https://www.wireshark.org/) 1) Download wireshark (https://www.wireshark.org/)
2) Start capturing on the interface used for exchanging RTSP (if the server and the target software are both installed on your pc, the interface is probably "loopback", otherwise it's the one of your network card) 2) Start capturing on the interface used for exchanging packets (if the server and the external hardware or software are both installed on your pc, the interface is probably "loopback", otherwise it's the one of your network card)
3) Start the server and replicate the issue 3) Start the server and replicate the issue
4) Stop capturing, save the result in .pcap format 4) Stop capturing, save the result in .pcap format
5) Attach 5) Attach

2
.github/ISSUE_TEMPLATE/config.yml

@ -2,5 +2,5 @@ blank_issues_enabled: false
contact_links: contact_links:
- name: Question - name: Question
url: https://github.com/bluenviron/mediamtx/discussions/new url: https://github.com/bluenviron/mediamtx/discussions/new?category=questions
about: Ask the community for help about: Ask the community for help

4
.github/ISSUE_TEMPLATE/feature.md

@ -7,6 +7,10 @@ assignees: ''
--- ---
<!--
Please create a request FOR EACH feature. Do not report multiple features in a single request, otherwise they'll probably never get ALL implemented.
-->
## Describe the feature ## Describe the feature
Description Description

65
.github/workflows/bump_hls_js.yml

@ -0,0 +1,65 @@
name: bump_hls_js
on:
schedule:
- cron: '4 5 * * *'
workflow_dispatch:
jobs:
bump_hls_js:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- run: >
git config user.name mediamtx-bot
&& git config user.email bot@mediamtx
&& ((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
- id: check_repo
run: >
echo "clean=$(git status --porcelain)" >> "$GITHUB_OUTPUT"
- if: ${{ steps.check_repo.outputs.clean != '' }}
run: >
git reset ${GITHUB_REF_NAME}
&& git add .
&& git commit -m "bump hls.js to ${VERSION}"
&& git push --set-upstream origin deps/hlsjs --force
- if: ${{ steps.check_repo.outputs.clean != '' }}
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const prs = await github.rest.pulls.list({
owner: context.repo.owner,
repo: context.repo.repo,
head: `${context.repo.owner}:deps/hlsjs`,
state: 'open',
});
if (prs.data.length == 0) {
await github.rest.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
head: 'deps/hlsjs',
base: context.ref.slice('refs/heads/'.length),
title: `bump hls-js to ${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}`,
});
}

18
.github/workflows/lint.yml → .github/workflows/code_lint.yml

@ -1,4 +1,4 @@
name: lint name: code_lint
on: on:
push: push:
@ -7,7 +7,7 @@ on:
branches: [ main ] branches: [ main ]
jobs: jobs:
code: golangci_lint:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
@ -15,13 +15,15 @@ jobs:
- uses: actions/setup-go@v3 - uses: actions/setup-go@v3
with: with:
go-version: "1.19" go-version: "1.21"
- uses: golangci/golangci-lint-action@v3 - run: touch internal/servers/hls/hls.min.js
- uses: golangci/golangci-lint-action@v4
with: with:
version: v1.53.3 version: v1.55.0
mod-tidy: mod_tidy:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
@ -29,13 +31,13 @@ jobs:
- uses: actions/setup-go@v2 - uses: actions/setup-go@v2
with: with:
go-version: "1.20" go-version: "1.21"
- run: | - run: |
go mod tidy go mod tidy
git diff --exit-code git diff --exit-code
apidocs: api_docs:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:

8
.github/workflows/test.yml → .github/workflows/code_test.yml

@ -1,4 +1,4 @@
name: test name: code_test
on: on:
push: push:
@ -7,7 +7,7 @@ on:
branches: [ main ] branches: [ main ]
jobs: jobs:
test64: test_64:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
@ -19,7 +19,7 @@ jobs:
with: with:
token: ${{ secrets.CODECOV_TOKEN }} token: ${{ secrets.CODECOV_TOKEN }}
test32: test_32:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
@ -35,6 +35,6 @@ jobs:
- uses: actions/setup-go@v2 - uses: actions/setup-go@v2
with: with:
go-version: "1.20" go-version: "1.21"
- run: make test-highlevel-nodocker - run: make test-highlevel-nodocker

4
.github/workflows/issue-lint.yml → .github/workflows/issue_lint.yml

@ -1,11 +1,11 @@
name: issue-lint name: issue_lint
on: on:
issues: issues:
types: [opened] types: [opened]
jobs: jobs:
issue-lint: issue_lint:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:

4
.github/workflows/issue-lock.yml → .github/workflows/issue_lock.yml

@ -1,4 +1,4 @@
name: issue-lock name: issue_lock
on: on:
schedule: schedule:
@ -6,7 +6,7 @@ on:
workflow_dispatch: workflow_dispatch:
jobs: jobs:
issue-lock: issue_lock:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:

4
.github/workflows/binaries.yml → .github/workflows/nightly_binaries.yml

@ -1,10 +1,10 @@
name: binaries name: nightly_binaries
on: on:
workflow_dispatch: workflow_dispatch:
jobs: jobs:
binaries: nightly_binaries:
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:

51
.github/workflows/release.yml

@ -19,13 +19,11 @@ jobs:
name: binaries name: binaries
path: binaries path: binaries
github: github_release:
needs: binaries needs: binaries
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
steps: steps:
- uses: actions/checkout@v3
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v3
with: with:
name: binaries name: binaries
@ -58,6 +56,51 @@ jobs:
}); });
} }
github_notify_issues:
needs: github_release
runs-on: ubuntu-22.04
steps:
- uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { repo: { owner, repo } } = context;
const tags = await github.rest.repos.listTags({
owner,
repo,
});
const curTag = tags.data[0];
const prevTag = tags.data[1];
const diff = await github.rest.repos.compareCommitsWithBasehead({
owner,
repo,
basehead: `${prevTag.commit.sha}...${curTag.commit.sha}`,
});
const issues = {};
for (const commit of diff.data.commits) {
for (const match of commit.commit.message.matchAll(/(^| |\()#([0-9]+)( |\)|$)/g)) {
issues[match[2]] = 1;
}
}
for (const issue in issues) {
try {
await github.rest.issues.createComment({
owner,
repo,
issue_number: parseInt(issue),
body: `This issue is mentioned in release ${curTag.name} 🚀\n`
+ `Check out the entire changelog by [clicking here](https://github.com/${owner}/${repo}/releases/tag/${curTag.name})`,
});
} catch (exc) {}
}
dockerhub: dockerhub:
needs: binaries needs: binaries
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04
@ -87,7 +130,7 @@ jobs:
DOCKER_USER_LEGACY: ${{ secrets.DOCKER_USER_LEGACY }} DOCKER_USER_LEGACY: ${{ secrets.DOCKER_USER_LEGACY }}
DOCKER_PASSWORD_LEGACY: ${{ secrets.DOCKER_PASSWORD_LEGACY }} DOCKER_PASSWORD_LEGACY: ${{ secrets.DOCKER_PASSWORD_LEGACY }}
apidocs: api_docs:
needs: binaries needs: binaries
runs-on: ubuntu-22.04 runs-on: ubuntu-22.04

1
.gitignore vendored

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

45
.golangci.yml

@ -1,7 +1,10 @@
linters: linters:
enable: enable:
- asciicheck
- bidichk
- bodyclose - bodyclose
- dupl - dupl
- errorlint
- exportloopref - exportloopref
- gochecknoinits - gochecknoinits
- gocritic - gocritic
@ -12,16 +15,54 @@ linters:
- nilerr - nilerr
- prealloc - prealloc
- revive - revive
- usestdlibvars
- unconvert - unconvert
- tparallel
- wastedassign - wastedassign
- whitespace - whitespace
disable:
- errcheck
issues: issues:
exclude-use-default: false exclude-use-default: false
linters-settings: linters-settings:
errcheck:
exclude-functions:
- io.Copy
- (io.Closer).Close
- (io.Writer).Write
- (hash.Hash).Write
- (net.Conn).Close
- (net.Conn).SetReadDeadline
- (net.Conn).SetWriteDeadline
- (*net.TCPConn).SetKeepAlive
- (*net.TCPConn).SetKeepAlivePeriod
- (*net.TCPConn).SetNoDelay
- (net.Listener).Close
- (net.PacketConn).Close
- (net.PacketConn).SetReadDeadline
- (net.PacketConn).SetWriteDeadline
- (net/http.ResponseWriter).Write
- (*net/http.Server).Serve
- (*net/http.Server).ServeTLS
- (*net/http.Server).Shutdown
- os.Chdir
- os.Mkdir
- os.MkdirAll
- os.Remove
- os.RemoveAll
- os.Setenv
- os.Unsetenv
- (*os.File).WriteString
- (*os.File).Close
- (github.com/datarhei/gosrt.Conn).Close
- (github.com/datarhei/gosrt.Conn).SetReadDeadline
- (github.com/datarhei/gosrt.Conn).SetWriteDeadline
- (*github.com/bluenviron/gortsplib/v4.Client).Close
- (*github.com/bluenviron/gortsplib/v4.Server).Close
- (*github.com/bluenviron/gortsplib/v4.ServerSession).Close
- (*github.com/bluenviron/gortsplib/v4.ServerStream).Close
- (*github.com/bluenviron/gortsplib/v4.ServerConn).Close
govet: govet:
enable-all: true enable-all: true
disable: disable:

12
Makefile

@ -1,9 +1,9 @@
BASE_IMAGE = golang:1.20-alpine3.17 BASE_IMAGE = golang:1.21-alpine3.19
LINT_IMAGE = golangci/golangci-lint:v1.53.3 LINT_IMAGE = golangci/golangci-lint:v1.56.2
NODE_IMAGE = node:16-alpine3.17 NODE_IMAGE = node:20-alpine3.19
ALPINE_IMAGE = alpine:3.17 ALPINE_IMAGE = alpine:3.19
RPI32_IMAGE = balenalib/raspberry-pi:bullseye-run RPI32_IMAGE = balenalib/raspberry-pi:bullseye-run-20230712
RPI64_IMAGE = balenalib/raspberrypi3-64:bullseye-run RPI64_IMAGE = balenalib/raspberrypi3-64:bullseye-run-20230530
.PHONY: $(shell ls) .PHONY: $(shell ls)

1139
README.md

File diff suppressed because it is too large Load Diff

3
SECURITY.md

@ -0,0 +1,3 @@
# Security Policy
Vulnerabilities can be reported privately by using the [Security Advisory](https://github.com/bluenviron/mediamtx/security/advisories/new) feature of GitHub.

1337
apidocs/openapi.yaml

File diff suppressed because it is too large Load Diff

5
bench/proxy/Dockerfile

@ -1,9 +1,10 @@
FROM golang:1.20-alpine3.17 ARG BASE_IMAGE
FROM $BASE_IMAGE
RUN apk add --no-cache \ RUN apk add --no-cache \
ffmpeg ffmpeg
RUN wget -O /video.mkv http://jell.yfish.us/media/jellyfish-10-mbps-hd-h264.mkv RUN wget -O /video.mkv http://www.larmoire.info/jellyfish/media/jellyfish-10-mbps-hd-h264.mkv
WORKDIR /s WORKDIR /s

16
bench/proxy/start.sh

@ -1,21 +1,24 @@
#!/bin/sh -e #!/bin/sh -e
PROXY_COUNT=20 PROXY_COUNT=50
PROXY_PROTOCOL=tcp PROXY_PROTOCOL=tcp
##################################################### #####################################################
# source # source
CONF="" CONF=""
CONF="${CONF}rtmp: no\n"
CONF="${CONF}hls: no\n" CONF="${CONF}hls: no\n"
CONF="${CONF}webrtc: no\n"
CONF="${CONF}srt: no\n"
CONF="${CONF}rtspAddress: :8555\n" CONF="${CONF}rtspAddress: :8555\n"
CONF="${CONF}rtpAddress: :8002\n" CONF="${CONF}rtpAddress: :8002\n"
CONF="${CONF}rtcpAddress: :8003\n" CONF="${CONF}rtcpAddress: :8003\n"
CONF="${CONF}paths:\n" CONF="${CONF}paths:\n"
CONF="${CONF} all:\n" CONF="${CONF} all_others:\n"
echo -e "$CONF" > /source.conf echo -e "$CONF" > /source.conf
RTSP_RTMP=no /mediamtx /source.conf & /mediamtx /source.conf &
sleep 1 sleep 1
@ -28,17 +31,20 @@ sleep 1
# proxy # proxy
CONF="" CONF=""
CONF="${CONF}rtmp: no\n"
CONF="${CONF}hls: no\n" CONF="${CONF}hls: no\n"
CONF="${CONF}webrtc: no\n"
CONF="${CONF}srt: no\n"
CONF="${CONF}pprof: yes\n" CONF="${CONF}pprof: yes\n"
CONF="${CONF}paths:\n" CONF="${CONF}paths:\n"
for i in $(seq 1 $PROXY_COUNT); do for i in $(seq 1 $PROXY_COUNT); do
CONF="${CONF} proxy$i:\n" CONF="${CONF} proxy$i:\n"
CONF="${CONF} source: rtsp://localhost:8555/source\n" CONF="${CONF} source: rtsp://localhost:8555/source\n"
CONF="${CONF} sourceProtocol: $PROXY_PROTOCOL\n" CONF="${CONF} rtspTransport: $PROXY_PROTOCOL\n"
done done
echo -e "$CONF" > /proxy.conf echo -e "$CONF" > /proxy.conf
RTSP_RTMP=no /mediamtx /proxy.conf & /mediamtx /proxy.conf &
sleep 5 sleep 5

5
bench/publish/Dockerfile

@ -1,9 +1,10 @@
FROM golang:1.20-alpine3.17 ARG BASE_IMAGE
FROM $BASE_IMAGE
RUN apk add --no-cache \ RUN apk add --no-cache \
ffmpeg ffmpeg
RUN wget -O /video.mkv http://jell.yfish.us/media/jellyfish-10-mbps-hd-h264.mkv RUN wget -O /video.mkv http://www.larmoire.info/jellyfish/media/jellyfish-10-mbps-hd-h264.mkv
WORKDIR /s WORKDIR /s

4
bench/publish/start.sh

@ -1,6 +1,6 @@
#!/bin/sh -e #!/bin/sh -e
PUBLISHER_COUNT=20 PUBLISHER_COUNT=50
PUBLISHER_PROTOCOL=tcp PUBLISHER_PROTOCOL=tcp
##################################################### #####################################################
@ -9,7 +9,7 @@ PUBLISHER_PROTOCOL=tcp
CONF="" CONF=""
CONF="${CONF}pprof: yes\n" CONF="${CONF}pprof: yes\n"
CONF="${CONF}paths:\n" CONF="${CONF}paths:\n"
CONF="${CONF} all:\n" CONF="${CONF} all_others:\n"
echo -e "$CONF" > /source.conf echo -e "$CONF" > /source.conf
/mediamtx /source.conf & /mediamtx /source.conf &

5
bench/read/Dockerfile

@ -1,9 +1,10 @@
FROM golang:1.20-alpine3.17 ARG BASE_IMAGE
FROM $BASE_IMAGE
RUN apk add --no-cache \ RUN apk add --no-cache \
ffmpeg ffmpeg
RUN wget -O /video.mkv http://jell.yfish.us/media/jellyfish-10-mbps-hd-h264.mkv RUN wget -O /video.mkv http://www.larmoire.info/jellyfish/media/jellyfish-10-mbps-hd-h264.mkv
WORKDIR /s WORKDIR /s

6
bench/read/start.sh

@ -1,6 +1,6 @@
#!/bin/sh -e #!/bin/sh -e
READER_COUNT=20 READER_COUNT=50
READER_PROTOCOL=tcp READER_PROTOCOL=tcp
##################################################### #####################################################
@ -9,7 +9,7 @@ READER_PROTOCOL=tcp
CONF="" CONF=""
CONF="${CONF}pprof: yes\n" CONF="${CONF}pprof: yes\n"
CONF="${CONF}paths:\n" CONF="${CONF}paths:\n"
CONF="${CONF} all:\n" CONF="${CONF} all_others:\n"
echo -e "$CONF" > /source.conf echo -e "$CONF" > /source.conf
/mediamtx /source.conf & /mediamtx /source.conf &
@ -26,7 +26,7 @@ sleep 1
for i in $(seq 1 $READER_COUNT); do for i in $(seq 1 $READER_COUNT); do
ffmpeg -hide_banner -loglevel error \ ffmpeg -hide_banner -loglevel error \
-rtsp_transport $READER_PROTOCOL \ -rtsp_transport $READER_PROTOCOL \
-i rtsp://localhost:8554/source -c copy -f mpegts -y /dev/null & -i rtsp://localhost:8554/source -c copy -f null - &
done done
sleep 5 sleep 5

71
go.mod

@ -1,39 +1,42 @@
module github.com/bluenviron/mediamtx module github.com/bluenviron/mediamtx
go 1.20 go 1.21
require ( require (
code.cloudfoundry.org/bytefmt v0.0.0 code.cloudfoundry.org/bytefmt v0.0.0
github.com/abema/go-mp4 v0.11.0 github.com/MicahParks/keyfunc/v3 v3.3.2
github.com/alecthomas/kong v0.8.0 github.com/abema/go-mp4 v1.2.0
github.com/bluenviron/gohlslib v0.3.1-0.20230806182538-54b835e0ef2c github.com/alecthomas/kong v0.9.0
github.com/bluenviron/gortsplib/v3 v3.9.1-0.20230806185830-e6e9e8490907 github.com/bluenviron/gohlslib v1.3.0
github.com/bluenviron/mediacommon v0.7.1-0.20230806185229-f060a1e5295b github.com/bluenviron/gortsplib/v4 v4.8.0
github.com/datarhei/gosrt v0.5.3 github.com/bluenviron/mediacommon v1.9.2
github.com/fsnotify/fsnotify v1.6.0 github.com/datarhei/gosrt v0.6.0
github.com/fsnotify/fsnotify v1.7.0
github.com/gin-gonic/gin v1.9.1 github.com/gin-gonic/gin v1.9.1
github.com/google/uuid v1.3.0 github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/gookit/color v1.5.4 github.com/gookit/color v1.5.4
github.com/gorilla/websocket v1.5.0 github.com/gorilla/websocket v1.5.1
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/notedit/rtmp v0.0.2 github.com/matthewhartstonge/argon2 v1.0.0
github.com/pion/ice/v2 v2.3.9 github.com/pion/ice/v2 v2.3.11
github.com/pion/interceptor v0.1.17 github.com/pion/interceptor v0.1.27
github.com/pion/rtcp v1.2.10 github.com/pion/logging v0.2.2
github.com/pion/rtp v1.8.1 github.com/pion/rtcp v1.2.14
github.com/pion/sdp/v3 v3.0.6 github.com/pion/rtp v1.8.5
github.com/pion/webrtc/v3 v3.2.14 github.com/pion/sdp/v3 v3.0.9
github.com/stretchr/testify v1.8.4 github.com/pion/webrtc/v3 v3.2.22
golang.org/x/crypto v0.11.0 github.com/stretchr/testify v1.9.0
golang.org/x/net v0.13.0 golang.org/x/crypto v0.22.0
golang.org/x/term v0.11.0 golang.org/x/sys v0.19.0
golang.org/x/term v0.19.0
gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v2 v2.4.0
) )
require ( require (
github.com/aler9/writerseeker v1.0.0 // indirect github.com/MicahParks/jwkset v0.5.17 // indirect
github.com/asticode/go-astikit v0.30.0 // indirect github.com/asticode/go-astikit v0.30.0 // indirect
github.com/asticode/go-astits v1.12.0 // indirect github.com/asticode/go-astits v1.13.0 // indirect
github.com/benburkert/openpgp v0.0.0-20160410205803-c2471f86866c // indirect github.com/benburkert/openpgp v0.0.0-20160410205803-c2471f86866c // indirect
github.com/bytedance/sonic v1.9.1 // indirect github.com/bytedance/sonic v1.9.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
@ -53,25 +56,27 @@ require (
github.com/pelletier/go-toml/v2 v2.0.8 // indirect github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pion/datachannel v1.5.5 // indirect github.com/pion/datachannel v1.5.5 // indirect
github.com/pion/dtls/v2 v2.2.7 // indirect github.com/pion/dtls/v2 v2.2.7 // indirect
github.com/pion/logging v0.2.2 // indirect github.com/pion/mdns v0.0.9 // indirect
github.com/pion/mdns v0.0.7 // indirect
github.com/pion/randutil v0.1.0 // indirect github.com/pion/randutil v0.1.0 // indirect
github.com/pion/sctp v1.8.7 // indirect github.com/pion/sctp v1.8.8 // indirect
github.com/pion/srtp/v2 v2.0.16 // indirect github.com/pion/srtp/v2 v2.0.18 // indirect
github.com/pion/stun v0.6.1 // indirect github.com/pion/stun v0.6.1 // indirect
github.com/pion/transport/v2 v2.2.1 // indirect github.com/pion/transport/v2 v2.2.3 // indirect
github.com/pion/turn/v2 v2.1.2 // indirect github.com/pion/turn/v2 v2.1.3 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect github.com/ugorji/go/codec v1.2.11 // indirect
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
golang.org/x/arch v0.3.0 // indirect golang.org/x/arch v0.3.0 // indirect
golang.org/x/sys v0.11.0 // indirect golang.org/x/net v0.21.0 // indirect
golang.org/x/text v0.11.0 // indirect golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect golang.org/x/time v0.5.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )
replace code.cloudfoundry.org/bytefmt => github.com/cloudfoundry/bytefmt v0.0.0-20211005130812-5bb3c17173e5 replace code.cloudfoundry.org/bytefmt => github.com/cloudfoundry/bytefmt v0.0.0-20211005130812-5bb3c17173e5
replace github.com/datarhei/gosrt => github.com/aler9/gosrt v0.0.0-20230803201410-b26769a3a222 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

152
go.sum

@ -1,25 +1,31 @@
github.com/abema/go-mp4 v0.11.0 h1:XJfpSmEdUBMvWnDKIiNznLGZPpeDxJ/qDdN6Ust1ADk= github.com/MicahParks/jwkset v0.5.17 h1:DrcwyKwSP5adD0G2XJTvDulnWXjD6gbjROMgMXDbkKA=
github.com/abema/go-mp4 v0.11.0/go.mod h1:vPl9t5ZK7K0x68jh12/+ECWBCXoWuIDtNgPtU2f04ws= github.com/MicahParks/jwkset v0.5.17/go.mod h1:q8ptTGn/Z9c4MwbcfeCDssADeVQb3Pk7PnVxrvi+2QY=
github.com/alecthomas/assert/v2 v2.1.0 h1:tbredtNcQnoSd3QBhQWI7QZ3XHOVkw1Moklp2ojoH/0= github.com/MicahParks/keyfunc/v3 v3.3.2 h1:YTtwc4dxalBZKFqHhqctBWN6VhbLdGhywmne9u5RQVM=
github.com/alecthomas/kong v0.8.0 h1:ryDCzutfIqJPnNn0omnrgHLbAggDQM2VWHikE1xqK7s= github.com/MicahParks/keyfunc/v3 v3.3.2/go.mod h1:GJBeEjnv25OnD9y2OYQa7ELU6gYahEMBNXINZb+qm34=
github.com/alecthomas/kong v0.8.0/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U= github.com/abema/go-mp4 v1.2.0 h1:gi4X8xg/m179N/J15Fn5ugywN9vtI6PLk6iLldHGLAk=
github.com/alecthomas/repr v0.1.0 h1:ENn2e1+J3k09gyj2shc0dHr/yjaWSHRlrJ4DPMevDqE= github.com/abema/go-mp4 v1.2.0/go.mod h1:vPl9t5ZK7K0x68jh12/+ECWBCXoWuIDtNgPtU2f04ws=
github.com/aler9/gosrt v0.0.0-20230803201410-b26769a3a222 h1:69Oj9CKfxxkTqFtBfBNo7zP4HcxEwjpFnFNHHX2Z06c= github.com/alecthomas/assert/v2 v2.6.0 h1:o3WJwILtexrEUk3cUVal3oiQY2tfgr/FHWiz/v2n4FU=
github.com/aler9/gosrt v0.0.0-20230803201410-b26769a3a222/go.mod h1:EryxR+Men7aW67IX2FEo56SU+Pay9OHCw3kZx23qKyQ= github.com/alecthomas/assert/v2 v2.6.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
github.com/aler9/writerseeker v1.0.0 h1:3wI/NtI20WqX8iLjrivym5VGXxug3EkRPaLRw6k9f9M= github.com/alecthomas/kong v0.9.0 h1:G5diXxc85KvoV2f0ZRVuMsi45IrBgx9zDNGNj165aPA=
github.com/aler9/writerseeker v1.0.0/go.mod h1:J5H8yGtvHnTM3DddPusobve1mDTYgdAj7eAwjGj8FXY= 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/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/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/asticode/go-astikit v0.30.0 h1:DkBkRQRIxYcknlaU7W7ksNfn4gMFsB0tqMJflxkRsZA= 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-astikit v0.30.0/go.mod h1:h4ly7idim1tNhaVkdVBeXQZEE3L0xblP7fCWbgwipF0=
github.com/asticode/go-astits v1.12.0 h1:BiefTgVEyPgEB8nT6J+Sys/uxE4H/a04SW/aedpOpPc= github.com/asticode/go-astits v1.13.0 h1:XOgkaadfZODnyZRR5Y0/DWkA9vrkLLPLeeOvDwfKZ1c=
github.com/asticode/go-astits v1.12.0/go.mod h1:QSHmknZ51pf6KJdHKZHJTLlMegIrhega3LPWz3ND/iI= 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 h1:8XZeJrs4+ZYhJeJ2aZxADI2tGADS15AzIF8MQ8XAhT4=
github.com/benburkert/openpgp v0.0.0-20160410205803-c2471f86866c/go.mod h1:x1vxHcL/9AVzuk5HOloOEPrtJY0MaalYr78afXZ+pWI= github.com/benburkert/openpgp v0.0.0-20160410205803-c2471f86866c/go.mod h1:x1vxHcL/9AVzuk5HOloOEPrtJY0MaalYr78afXZ+pWI=
github.com/bluenviron/gohlslib v0.3.1-0.20230806182538-54b835e0ef2c h1:wztDQy5iTijIZz4v+mkbJkTIHoQ/MHtdMSPirTQy5uQ= github.com/bluenviron/gohlslib v1.3.0 h1:I9t1Nba6VJKg5rLoXSzQFPkZZYBUwBqCU2Divp0oU2I=
github.com/bluenviron/gohlslib v0.3.1-0.20230806182538-54b835e0ef2c/go.mod h1:SoCWetcOsLi70kcUBBrckYFfmLPJuqmXVGP10OlEc70= github.com/bluenviron/gohlslib v1.3.0/go.mod h1:wD8ysO6HB90d17sxoIQXGHINo2KYj/mZirMnPtKLJZQ=
github.com/bluenviron/gortsplib/v3 v3.9.1-0.20230806185830-e6e9e8490907 h1:EPRg+yYqp7eZr9ROvjSvHJf7TIcu31spCGKbjHzpilM= github.com/bluenviron/gortsplib/v4 v4.8.0 h1:nvFp6rHALcSep3G9uBFI0uogS9stVZLNq/92TzGZdQg=
github.com/bluenviron/gortsplib/v3 v3.9.1-0.20230806185830-e6e9e8490907/go.mod h1:tK2JtJRkKUIhmZEyRWCd8rtiqbirO4eMXt7fN5Yont4= github.com/bluenviron/gortsplib/v4 v4.8.0/go.mod h1:+d+veuyvhvikUNp0GRQkk6fEbd/DtcXNidMRm7FQRaA=
github.com/bluenviron/mediacommon v0.7.1-0.20230806185229-f060a1e5295b h1:53WQf0Kam0/Rj4bnTWhpo6n6cCrRE84tjf9xrwq8mWo= github.com/bluenviron/mediacommon v1.9.2 h1:EHcvoC5YMXRcFE010bTNf07ZiSlB/e/AdZyG7GsEYN0=
github.com/bluenviron/mediacommon v0.7.1-0.20230806185229-f060a1e5295b/go.mod h1:LR4w8cpvzo2ZcmBwXcentvBj7ZlyF9g9xP4dDbt8uJw= github.com/bluenviron/mediacommon v1.9.2/go.mod h1:lt8V+wMyPw8C69HAqDWV5tsAwzN9u2Z+ca8B6C//+n0=
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= 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 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
@ -29,13 +35,15 @@ 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 h1:xB7KkA98BcUdzVcwyZxb5R0FGIHxNPHgZOzkjPEY5gM=
github.com/cloudfoundry/bytefmt v0.0.0-20211005130812-5bb3c17173e5/go.mod h1:v4VVB6oBMz/c9fRY6vZrwr5xKRWOH5NPDjQZlPk0Gbs= 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/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/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
@ -43,6 +51,7 @@ github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
@ -52,6 +61,8 @@ 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/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 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= 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.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/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
@ -68,13 +79,15 @@ github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 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.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/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/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0=
github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
@ -91,6 +104,8 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/matthewhartstonge/argon2 v1.0.0 h1:e65fkae6O8Na6YTy2HAccUbXR+GQHOnpQxeWGqWCRIw=
github.com/matthewhartstonge/argon2 v1.0.0/go.mod h1:Fm4FHZxdxCM6hg21Jkz3YZVKnU7VnTlqDQ3ghS/Myok=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@ -98,8 +113,6 @@ 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/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 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= 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.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
@ -121,42 +134,46 @@ 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/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 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8=
github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s=
github.com/pion/ice/v2 v2.3.9 h1:7yZpHf3PhPxJGT4JkMj1Y8Rl5cQ6fB709iz99aeMd/U= github.com/pion/interceptor v0.1.25/go.mod h1:wkbPYAak5zKsfpVDYMtEfWEy8D4zL+rpxCxPImLOg3Y=
github.com/pion/ice/v2 v2.3.9/go.mod h1:lT3kv5uUIlHfXHU/ZRD7uKD/ufM202+eTa3C/umgGf4= github.com/pion/interceptor v0.1.27 h1:mZ01OiGiukwRxezmDGzYjjokCVlDOk4T6BfaL5qrtGo=
github.com/pion/interceptor v0.1.17 h1:prJtgwFh/gB8zMqGZoOgJPHivOwVAp61i2aG61Du/1w= github.com/pion/interceptor v0.1.27/go.mod h1:/vVaqLwDjGv4GRbgmChIKZIT5EXFDijwmj4WmIYy9bI=
github.com/pion/interceptor v0.1.17/go.mod h1:SY8kpmfVBvrbUzvj2bsXz7OJt5JvmVNZ+4Kjq7FcwrI=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= 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/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/mdns v0.0.7 h1:P0UB4Sr6xDWEox0kTVxF0LmQihtCbSAdW0H2nEgkA3U=
github.com/pion/mdns v0.0.7/go.mod h1:4iP2UbeFhLI/vWju/bw6ZfwjJzk0z8DNValjGxR/dD8= github.com/pion/mdns v0.0.7/go.mod h1:4iP2UbeFhLI/vWju/bw6ZfwjJzk0z8DNValjGxR/dD8=
github.com/pion/mdns v0.0.9 h1:7Ue5KZsqq8EuqStnpPWV33vYYEH0+skdDN5L7EiEsI4=
github.com/pion/mdns v0.0.9/go.mod h1:2JA5exfxwzXiCihmxpTKgFUpiQws2MnipoPK09vecIc=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= 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/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.10 h1:nkr3uj+8Sp97zyItdN60tE/S6vk4al5CPRR6Gejsdjc=
github.com/pion/rtcp v1.2.10/go.mod h1:ztfEwXZNLGyF1oQDttz/ZKIBaeeg/oWbRYqzBM9TL1I= github.com/pion/rtcp v1.2.10/go.mod h1:ztfEwXZNLGyF1oQDttz/ZKIBaeeg/oWbRYqzBM9TL1I=
github.com/pion/rtp v1.7.13/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko= github.com/pion/rtcp v1.2.12/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
github.com/pion/rtp v1.8.0/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU= github.com/pion/rtcp v1.2.14 h1:KCkGV3vJ+4DAJmvP0vaQShsb0xkRfWkO540Gy102KyE=
github.com/pion/rtp v1.8.1 h1:26OxTc6lKg/qLSGir5agLyj0QKaOv8OP5wps2SFnVNQ= github.com/pion/rtcp v1.2.14/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
github.com/pion/rtp v1.8.1/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU= github.com/pion/rtp v1.8.2/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
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.5/go.mod h1:SUFFfDpViyKejTAdwD1d/HQsCu+V/40cCs2nZIvC3s0=
github.com/pion/sctp v1.8.7 h1:JnABvFakZueGAn4KU/4PSKg+GWbF6QWbKTWZOSGJjXw= github.com/pion/sctp v1.8.8 h1:5EdnnKI4gpyR1a1TwbiS/wxEgcUWBHsc7ILAjARJB+U=
github.com/pion/sctp v1.8.7/go.mod h1:g1Ul+ARqZq5JEmoFy87Q/4CePtKnTJ1QCL9dBBdN6AU= github.com/pion/sctp v1.8.8/go.mod h1:igF9nZBrjh5AtmKc7U30jXltsFHicFCXSmWA2GWRaWs=
github.com/pion/sdp/v3 v3.0.6 h1:WuDLhtuFUUVpTfus9ILC4HRyHsW6TdugjEX/QY9OiUw=
github.com/pion/sdp/v3 v3.0.6/go.mod h1:iiFWFpQO8Fy3S5ldclBkpXqmWy02ns78NOKoLLL0YQw= github.com/pion/sdp/v3 v3.0.6/go.mod h1:iiFWFpQO8Fy3S5ldclBkpXqmWy02ns78NOKoLLL0YQw=
github.com/pion/srtp/v2 v2.0.16 h1:impT2XBrHKsDpXr1x5hHIRydwssrSWKpmw3KvSfXbso= github.com/pion/sdp/v3 v3.0.9 h1:pX++dCHoHUwq43kuwf3PyJfHlwIj4hXA7Vrifiq0IJY=
github.com/pion/srtp/v2 v2.0.16/go.mod h1:NCLCV+U+NpxQ+vXhfOETet4OgKioIgrFjZmIM3ldJYE= 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= github.com/pion/stun v0.6.1 h1:8lp6YejULeHBF8NmV8e2787BogQhduZugh5PdhDyyN4=
github.com/pion/stun v0.6.1/go.mod h1:/hO7APkX4hZKu/D0f2lHzNyvdkTGtIy3NDmLR7kSz/8= github.com/pion/stun v0.6.1/go.mod h1:/hO7APkX4hZKu/D0f2lHzNyvdkTGtIy3NDmLR7kSz/8=
github.com/pion/transport v0.14.1 h1:XSM6olwW+o8J4SCmOBb/BpwZypkHeyM0PGFCxNQBr40= github.com/pion/transport v0.14.1 h1:XSM6olwW+o8J4SCmOBb/BpwZypkHeyM0PGFCxNQBr40=
github.com/pion/transport v0.14.1/go.mod h1:4tGmbk00NeYA3rUa9+n+dzCCoKkcy3YlYb99Jn2fNnI= github.com/pion/transport v0.14.1/go.mod h1:4tGmbk00NeYA3rUa9+n+dzCCoKkcy3YlYb99Jn2fNnI=
github.com/pion/transport/v2 v2.0.0/go.mod h1:HS2MEBJTwD+1ZI2eSXSvHJx/HnzQqRy2/LXxt6eVMHc= github.com/pion/transport/v2 v2.0.0/go.mod h1:HS2MEBJTwD+1ZI2eSXSvHJx/HnzQqRy2/LXxt6eVMHc=
github.com/pion/transport/v2 v2.1.0/go.mod h1:AdSw4YBZVDkZm8fpoz+fclXyQwANWmZAlDuQdctTThQ=
github.com/pion/transport/v2 v2.2.0/go.mod h1:AdSw4YBZVDkZm8fpoz+fclXyQwANWmZAlDuQdctTThQ=
github.com/pion/transport/v2 v2.2.1 h1:7qYnCBlpgSJNYMbLCKuSY9KbQdBFoETvPNETv0y4N7c=
github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g=
github.com/pion/turn/v2 v2.1.2 h1:wj0cAoGKltaZ790XEGW9HwoUewqjliwmhtxCuB2ApyM= github.com/pion/transport/v2 v2.2.3 h1:XcOE3/x41HOSKbl1BfyY1TF1dERx7lVvlMCbXU7kfvA=
github.com/pion/transport/v2 v2.2.3/go.mod h1:q2U/tf9FEfnSBGSW6w5Qp5PFWRLRj3NjLhCCgpRK4p0=
github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouANiM=
github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0=
github.com/pion/turn/v2 v2.1.2/go.mod h1:1kjnPkBcex3dhCU2Am+AAmxDcGhLX3WnMfmkNpvSTQU= github.com/pion/turn/v2 v2.1.2/go.mod h1:1kjnPkBcex3dhCU2Am+AAmxDcGhLX3WnMfmkNpvSTQU=
github.com/pion/webrtc/v3 v3.2.14 h1:GlqnBnnLlcYYA/LOwqLLU1plZYwx0Y/e/57bZ2tzQcU= github.com/pion/turn/v2 v2.1.3 h1:pYxTVWG2gpC97opdRc5IGsQ1lJ9O/IlNhkzj7MMrGAA=
github.com/pion/webrtc/v3 v3.2.14/go.mod h1:r1mtixc2MH847mmQTPwlEvGge7D18C2T5qp8jI9Lm44= github.com/pion/turn/v2 v2.1.3/go.mod h1:huEpByKKHix2/b9kmTAM3YoX6MKP+/D//0ClgUYR2fY=
github.com/pkg/profile v1.4.0/go.mod h1:NWz/XGvpEW1FyYQ7fCx4dqYBLlfTcE+A9FLAkNKqjFE= github.com/pkg/profile v1.4.0/go.mod h1:NWz/XGvpEW1FyYQ7fCx4dqYBLlfTcE+A9FLAkNKqjFE=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
@ -164,6 +181,7 @@ 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.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.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.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.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 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= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
@ -173,8 +191,9 @@ 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.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/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.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.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/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 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
@ -193,8 +212,10 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= 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.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I=
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= 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/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 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.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
@ -209,13 +230,13 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= 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.11.0/go.mod h1:2L/ixqYpgIVXmeoSA/4Lu7BzTG4KIyPIryS4IsOd1oQ=
golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI=
golang.org/x/net v0.13.0 h1:Nvo8UFsZ8X3BhAC9699Z1j7XQ3rsZnUUm7jfBEk1ueY= golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.13.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA= 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/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 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-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -237,7 +258,6 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@ -246,21 +266,22 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 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.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.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/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 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.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= 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.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo=
golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o=
golang.org/x/term v0.11.0 h1:F9tnn/DA/Im8nCwm+fX+1/eBwi4qFjRT++MhtVC4ZX0=
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= 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/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 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.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@ -268,11 +289,14 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.11.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-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-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
@ -291,8 +315,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.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-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.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=

1186
internal/api/api.go

File diff suppressed because it is too large Load Diff

701
internal/api/api_test.go

@ -0,0 +1,701 @@
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++ {
items[i] = i
}
pageCount, err := paginate(&items, "1", "1")
require.NoError(t, err)
require.Equal(t, 5, pageCount)
require.Equal(t, []int{1}, items)
items = make([]int, 5)
for i := 0; i < 5; i++ {
items[i] = i
}
pageCount, err = paginate(&items, "3", "2")
require.NoError(t, err)
require.Equal(t, 2, pageCount)
require.Equal(t, []int{}, items)
items = make([]int, 6)
for i := 0; i < 6; i++ {
items[i] = i
}
pageCount, err = paginate(&items, "4", "1")
require.NoError(t, err)
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

@ -0,0 +1,139 @@
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
}

76
internal/asyncwriter/async_writer.go

@ -0,0 +1,76 @@
// Package asyncwriter contains an asynchronous writer.
package asyncwriter
import (
"fmt"
"github.com/bluenviron/gortsplib/v4/pkg/ringbuffer"
"github.com/bluenviron/mediamtx/internal/logger"
)
// Writer is an asynchronous writer.
type Writer struct {
writeErrLogger logger.Writer
buffer *ringbuffer.RingBuffer
// out
err chan error
}
// New allocates a Writer.
func New(
queueSize int,
parent logger.Writer,
) *Writer {
buffer, _ := ringbuffer.New(uint64(queueSize))
return &Writer{
writeErrLogger: logger.NewLimitedLogger(parent),
buffer: buffer,
err: make(chan error),
}
}
// Start starts the writer routine.
func (w *Writer) Start() {
go w.run()
}
// Stop stops the writer routine.
func (w *Writer) Stop() {
w.buffer.Close()
<-w.err
}
// Error returns whenever there's an error.
func (w *Writer) Error() chan error {
return w.err
}
func (w *Writer) run() {
w.err <- w.runInner()
close(w.err)
}
func (w *Writer) runInner() error {
for {
cb, ok := w.buffer.Pull()
if !ok {
return fmt.Errorf("terminated")
}
err := cb.(func() error)()
if err != nil {
return err
}
}
}
// Push appends an element to the queue.
func (w *Writer) Push(cb func() error) {
ok := w.buffer.Push(cb)
if !ok {
w.writeErrLogger.Log(logger.Warn, "write queue is full")
}
}

22
internal/asyncwriter/async_writer_test.go

@ -0,0 +1,22 @@
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

@ -0,0 +1,327 @@
// 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

@ -0,0 +1,309 @@
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

@ -0,0 +1,52 @@
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

@ -0,0 +1,15 @@
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"`
}

67
internal/conf/auth_method.go

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

763
internal/conf/conf.go

@ -6,14 +6,16 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"net"
"os" "os"
"reflect"
"sort" "sort"
"strings" "strings"
"time" "time"
"github.com/bluenviron/gohlslib" "github.com/bluenviron/gohlslib"
"github.com/bluenviron/gortsplib/v3" "github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v3/pkg/headers" "github.com/bluenviron/gortsplib/v4/pkg/headers"
"github.com/bluenviron/mediamtx/internal/conf/decrypt" "github.com/bluenviron/mediamtx/internal/conf/decrypt"
"github.com/bluenviron/mediamtx/internal/conf/env" "github.com/bluenviron/mediamtx/internal/conf/env"
@ -21,7 +23,10 @@ import (
"github.com/bluenviron/mediamtx/internal/logger" "github.com/bluenviron/mediamtx/internal/logger"
) )
func getSortedKeys(paths map[string]*PathConf) []string { // 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)) ret := make([]string, len(paths))
i := 0 i := 0
for name := range paths { for name := range paths {
@ -32,55 +37,83 @@ func getSortedKeys(paths map[string]*PathConf) []string {
return ret return ret
} }
func loadFromFile(fpath string, conf *Conf) (bool, error) { func firstThatExists(paths []string) string {
if fpath == "mediamtx.yml" { for _, pa := range paths {
// give priority to the legacy configuration file, in order not to break _, err := os.Stat(pa)
// existing setups if err == nil {
if _, err := os.Stat("rtsp-simple-server.yml"); err == nil { return pa
fpath = "rtsp-simple-server.yml"
} }
} }
return ""
}
// mediamtx.yml is optional func contains(list []headers.AuthMethod, item headers.AuthMethod) bool {
// other configuration files are not for _, i := range list {
if fpath == "mediamtx.yml" || fpath == "rtsp-simple-server.yml" { if i == item {
if _, err := os.Stat(fpath); errors.Is(err, os.ErrNotExist) { return true
conf.UnmarshalJSON(nil) // load defaults
return false, nil
} }
} }
return false
}
byts, err := os.ReadFile(fpath) func copyStructFields(dest interface{}, source interface{}) {
if err != nil { rvsource := reflect.ValueOf(source).Elem()
return true, err rvdest := reflect.ValueOf(dest)
} nf := rvsource.NumField()
var zero reflect.Value
if key, ok := os.LookupEnv("RTSP_CONFKEY"); ok { // legacy format
byts, err = decrypt.Decrypt(key, byts) for i := 0; i < nf; i++ {
if err != nil { fnew := rvsource.Field(i)
return true, err f := rvdest.Elem().FieldByName(rvsource.Type().Field(i).Name)
if f == zero {
continue
} }
}
if key, ok := os.LookupEnv("MTX_CONFKEY"); ok { if fnew.Kind() == reflect.Pointer {
byts, err = decrypt.Decrypt(key, byts) if !fnew.IsNil() {
if err != nil { if f.Kind() == reflect.Ptr {
return true, err f.Set(fnew)
} else {
f.Set(fnew.Elem())
}
}
} else {
f.Set(fnew)
} }
} }
}
err = yaml.Load(byts, conf) func mustParseCIDR(v string) net.IPNet {
_, ne, err := net.ParseCIDR(v)
if err != nil { if err != nil {
return true, err 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
}
return true, nil func credentialIsNotEmpty(c *Credential) bool {
return c != nil && *c != ""
} }
func contains(list []headers.AuthMethod, item headers.AuthMethod) bool { func ipNetworkIsNotEmpty(i *IPNetworks) bool {
for _, i := range list { return i != nil && len(*i) != 0
if i == item { }
return true
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 return false
@ -88,52 +121,68 @@ func contains(list []headers.AuthMethod, item headers.AuthMethod) bool {
// Conf is a configuration. // Conf is a configuration.
type Conf struct { type Conf struct {
// general // General
LogLevel LogLevel `json:"logLevel"` LogLevel LogLevel `json:"logLevel"`
LogDestinations LogDestinations `json:"logDestinations"` LogDestinations LogDestinations `json:"logDestinations"`
LogFile string `json:"logFile"` LogFile string `json:"logFile"`
ReadTimeout StringDuration `json:"readTimeout"` ReadTimeout StringDuration `json:"readTimeout"`
WriteTimeout StringDuration `json:"writeTimeout"` WriteTimeout StringDuration `json:"writeTimeout"`
ReadBufferCount int `json:"readBufferCount"` ReadBufferCount *int `json:"readBufferCount,omitempty"` // deprecated
UDPMaxPayloadSize int `json:"udpMaxPayloadSize"` WriteQueueSize int `json:"writeQueueSize"`
ExternalAuthenticationURL string `json:"externalAuthenticationURL"` UDPMaxPayloadSize int `json:"udpMaxPayloadSize"`
API bool `json:"api"` Metrics bool `json:"metrics"`
APIAddress string `json:"apiAddress"` MetricsAddress string `json:"metricsAddress"`
Metrics bool `json:"metrics"` PPROF bool `json:"pprof"`
MetricsAddress string `json:"metricsAddress"` PPROFAddress string `json:"pprofAddress"`
PPROF bool `json:"pprof"` RunOnConnect string `json:"runOnConnect"`
PPROFAddress string `json:"pprofAddress"` RunOnConnectRestart bool `json:"runOnConnectRestart"`
RunOnConnect string `json:"runOnConnect"` RunOnDisconnect string `json:"runOnDisconnect"`
RunOnConnectRestart bool `json:"runOnConnectRestart"`
// Authentication
// RTSP AuthMethod AuthMethod `json:"authMethod"`
RTSP bool `json:"rtsp"` AuthInternalUsers []AuthInternalUser `json:"authInternalUsers"`
RTSPDisable bool `json:"rtspDisable"` // deprecated AuthHTTPAddress string `json:"authHTTPAddress"`
Protocols Protocols `json:"protocols"` ExternalAuthenticationURL *string `json:"externalAuthenticationURL,omitempty"` // deprecated
Encryption Encryption `json:"encryption"` AuthHTTPExclude []AuthInternalUserPermission `json:"authHTTPExclude"`
RTSPAddress string `json:"rtspAddress"` AuthJWTJWKS string `json:"authJWTJWKS"`
RTSPSAddress string `json:"rtspsAddress"`
RTPAddress string `json:"rtpAddress"` // API
RTCPAddress string `json:"rtcpAddress"` API bool `json:"api"`
MulticastIPRange string `json:"multicastIPRange"` APIAddress string `json:"apiAddress"`
MulticastRTPPort int `json:"multicastRTPPort"`
MulticastRTCPPort int `json:"multicastRTCPPort"` // Playback
ServerKey string `json:"serverKey"` Playback bool `json:"playback"`
ServerCert string `json:"serverCert"` PlaybackAddress string `json:"playbackAddress"`
AuthMethods AuthMethods `json:"authMethods"`
// RTSP server
// RTMP 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"`
// RTMP server
RTMP bool `json:"rtmp"` RTMP bool `json:"rtmp"`
RTMPDisable bool `json:"rtmpDisable"` // deprecated RTMPDisable *bool `json:"rtmpDisable,omitempty"` // deprecated
RTMPAddress string `json:"rtmpAddress"` RTMPAddress string `json:"rtmpAddress"`
RTMPEncryption Encryption `json:"rtmpEncryption"` RTMPEncryption Encryption `json:"rtmpEncryption"`
RTMPSAddress string `json:"rtmpsAddress"` RTMPSAddress string `json:"rtmpsAddress"`
RTMPServerKey string `json:"rtmpServerKey"` RTMPServerKey string `json:"rtmpServerKey"`
RTMPServerCert string `json:"rtmpServerCert"` RTMPServerCert string `json:"rtmpServerCert"`
// HLS // HLS server
HLS bool `json:"hls"` HLS bool `json:"hls"`
HLSDisable bool `json:"hlsDisable"` // depreacted HLSDisable *bool `json:"hlsDisable,omitempty"` // depreacted
HLSAddress string `json:"hlsAddress"` HLSAddress string `json:"hlsAddress"`
HLSEncryption bool `json:"hlsEncryption"` HLSEncryption bool `json:"hlsEncryption"`
HLSServerKey string `json:"hlsServerKey"` HLSServerKey string `json:"hlsServerKey"`
@ -145,57 +194,233 @@ type Conf struct {
HLSPartDuration StringDuration `json:"hlsPartDuration"` HLSPartDuration StringDuration `json:"hlsPartDuration"`
HLSSegmentMaxSize StringSize `json:"hlsSegmentMaxSize"` HLSSegmentMaxSize StringSize `json:"hlsSegmentMaxSize"`
HLSAllowOrigin string `json:"hlsAllowOrigin"` HLSAllowOrigin string `json:"hlsAllowOrigin"`
HLSTrustedProxies IPsOrCIDRs `json:"hlsTrustedProxies"` HLSTrustedProxies IPNetworks `json:"hlsTrustedProxies"`
HLSDirectory string `json:"hlsDirectory"` HLSDirectory string `json:"hlsDirectory"`
// WebRTC // WebRTC server
WebRTC bool `json:"webrtc"` WebRTC bool `json:"webrtc"`
WebRTCDisable bool `json:"webrtcDisable"` // deprecated WebRTCDisable *bool `json:"webrtcDisable,omitempty"` // deprecated
WebRTCAddress string `json:"webrtcAddress"` WebRTCAddress string `json:"webrtcAddress"`
WebRTCEncryption bool `json:"webrtcEncryption"` WebRTCEncryption bool `json:"webrtcEncryption"`
WebRTCServerKey string `json:"webrtcServerKey"` WebRTCServerKey string `json:"webrtcServerKey"`
WebRTCServerCert string `json:"webrtcServerCert"` WebRTCServerCert string `json:"webrtcServerCert"`
WebRTCAllowOrigin string `json:"webrtcAllowOrigin"` WebRTCAllowOrigin string `json:"webrtcAllowOrigin"`
WebRTCTrustedProxies IPsOrCIDRs `json:"webrtcTrustedProxies"` WebRTCTrustedProxies IPNetworks `json:"webrtcTrustedProxies"`
WebRTCICEServers []string `json:"webrtcICEServers"` // deprecated WebRTCLocalUDPAddress string `json:"webrtcLocalUDPAddress"`
WebRTCICEServers2 []WebRTCICEServer `json:"webrtcICEServers2"` WebRTCLocalTCPAddress string `json:"webrtcLocalTCPAddress"`
WebRTCICEHostNAT1To1IPs []string `json:"webrtcICEHostNAT1To1IPs"` WebRTCIPsFromInterfaces bool `json:"webrtcIPsFromInterfaces"`
WebRTCICEUDPMuxAddress string `json:"webrtcICEUDPMuxAddress"` WebRTCIPsFromInterfacesList []string `json:"webrtcIPsFromInterfacesList"`
WebRTCICETCPMuxAddress string `json:"webrtcICETCPMuxAddress"` WebRTCAdditionalHosts []string `json:"webrtcAdditionalHosts"`
WebRTCICEServers2 []WebRTCICEServer `json:"webrtcICEServers2"`
// SRT WebRTCICEUDPMuxAddress *string `json:"webrtcICEUDPMuxAddress,omitempty"` // deprecated
WebRTCICETCPMuxAddress *string `json:"webrtcICETCPMuxAddress,omitempty"` // deprecated
WebRTCICEHostNAT1To1IPs *[]string `json:"webrtcICEHostNAT1To1IPs,omitempty"` // deprecated
WebRTCICEServers *[]string `json:"webrtcICEServers,omitempty"` // deprecated
// SRT server
SRT bool `json:"srt"` SRT bool `json:"srt"`
SRTAddress string `json:"srtAddress"` SRTAddress string `json:"srtAddress"`
// paths // Record (deprecated)
Paths map[string]*PathConf `json:"paths"` Record *bool `json:"record,omitempty"` // deprecated
RecordPath *string `json:"recordPath,omitempty"` // deprecated
RecordFormat *RecordFormat `json:"recordFormat,omitempty"` // deprecated
RecordPartDuration *StringDuration `json:"recordPartDuration,omitempty"` // deprecated
RecordSegmentDuration *StringDuration `json:"recordSegmentDuration,omitempty"` // deprecated
RecordDeleteAfter *StringDuration `json:"recordDeleteAfter,omitempty"` // deprecated
// Path defaults
PathDefaults Path `json:"pathDefaults"`
// Paths
OptionalPaths map[string]*OptionalPath `json:"paths"`
Paths map[string]*Path `json:"-"` // filled by Check()
}
func (conf *Conf) setDefaults() {
// General
conf.LogLevel = LogLevel(logger.Info)
conf.LogDestinations = LogDestinations{logger.DestinationStdout}
conf.LogFile = "mediamtx.log"
conf.ReadTimeout = 10 * StringDuration(time.Second)
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"
// RTSP server
conf.RTSP = true
conf.Protocols = Protocols{
Protocol(gortsplib.TransportUDP): {},
Protocol(gortsplib.TransportUDPMulticast): {},
Protocol(gortsplib.TransportTCP): {},
}
conf.RTSPAddress = ":8554"
conf.RTSPSAddress = ":8322"
conf.RTPAddress = ":8000"
conf.RTCPAddress = ":8001"
conf.MulticastIPRange = "224.1.0.0/16"
conf.MulticastRTPPort = 8002
conf.MulticastRTCPPort = 8003
conf.ServerKey = "server.key"
conf.ServerCert = "server.crt"
conf.RTSPAuthMethods = RTSPAuthMethods{headers.AuthBasic}
// RTMP server
conf.RTMP = true
conf.RTMPAddress = ":1935"
conf.RTMPSAddress = ":1936"
conf.RTMPServerKey = "server.key"
conf.RTMPServerCert = "server.crt"
// HLS
conf.HLS = true
conf.HLSAddress = ":8888"
conf.HLSServerKey = "server.key"
conf.HLSServerCert = "server.crt"
conf.HLSVariant = HLSVariant(gohlslib.MuxerVariantLowLatency)
conf.HLSSegmentCount = 7
conf.HLSSegmentDuration = 1 * StringDuration(time.Second)
conf.HLSPartDuration = 200 * StringDuration(time.Millisecond)
conf.HLSSegmentMaxSize = 50 * 1024 * 1024
conf.HLSAllowOrigin = "*"
// WebRTC server
conf.WebRTC = true
conf.WebRTCAddress = ":8889"
conf.WebRTCServerKey = "server.key"
conf.WebRTCServerCert = "server.crt"
conf.WebRTCAllowOrigin = "*"
conf.WebRTCLocalUDPAddress = ":8189"
conf.WebRTCIPsFromInterfaces = true
conf.WebRTCIPsFromInterfacesList = []string{}
conf.WebRTCAdditionalHosts = []string{}
conf.WebRTCICEServers2 = []WebRTCICEServer{}
// SRT server
conf.SRT = true
conf.SRTAddress = ":8890"
conf.PathDefaults.setDefaults()
} }
// Load loads a Conf. // Load loads a Conf.
func Load(fpath string) (*Conf, bool, error) { func Load(fpath string, defaultConfPaths []string) (*Conf, string, error) {
conf := &Conf{} conf := &Conf{}
found, err := loadFromFile(fpath, conf) fpath, err := conf.loadFromFile(fpath, defaultConfPaths)
if err != nil { if err != nil {
return nil, false, err return nil, "", err
} }
err = env.Load("RTSP", conf) // legacy prefix err = env.Load("RTSP", conf) // legacy prefix
if err != nil { if err != nil {
return nil, false, err return nil, "", err
} }
err = env.Load("MTX", conf) err = env.Load("MTX", conf)
if err != nil { if err != nil {
return nil, false, err return nil, "", err
} }
err = conf.Check() err = conf.Validate()
if err != nil { if err != nil {
return nil, false, err return nil, "", err
} }
return conf, found, nil return conf, fpath, nil
}
func (conf *Conf) loadFromFile(fpath string, defaultConfPaths []string) (string, error) {
if fpath == "" {
fpath = firstThatExists(defaultConfPaths)
// when the configuration file is not explicitly set,
// it is optional.
if fpath == "" {
conf.setDefaults()
return "", nil
}
}
byts, err := os.ReadFile(fpath)
if err != nil {
return "", err
}
if key, ok := os.LookupEnv("RTSP_CONFKEY"); ok { // legacy format
byts, err = decrypt.Decrypt(key, byts)
if err != nil {
return "", err
}
}
if key, ok := os.LookupEnv("MTX_CONFKEY"); ok {
byts, err = decrypt.Decrypt(key, byts)
if err != nil {
return "", err
}
}
err = yaml.Load(byts, conf)
if err != nil {
return "", err
}
return fpath, nil
} }
// Clone clones the configuration. // Clone clones the configuration.
@ -214,29 +439,89 @@ func (conf Conf) Clone() *Conf {
return &dest return &dest
} }
// Check checks the configuration for errors. // Validate checks the configuration for errors.
func (conf *Conf) Check() error { func (conf *Conf) Validate() error {
// general // General
if (conf.ReadBufferCount & (conf.ReadBufferCount - 1)) != 0 {
return fmt.Errorf("'readBufferCount' must be a power of two") if conf.ReadBufferCount != nil {
conf.WriteQueueSize = *conf.ReadBufferCount
}
if (conf.WriteQueueSize & (conf.WriteQueueSize - 1)) != 0 {
return fmt.Errorf("'writeQueueSize' must be a power of two")
} }
if conf.UDPMaxPayloadSize > 1472 { if conf.UDPMaxPayloadSize > 1472 {
return fmt.Errorf("'udpMaxPayloadSize' must be less than 1472") return fmt.Errorf("'udpMaxPayloadSize' must be less than 1472")
} }
if conf.ExternalAuthenticationURL != "" {
if !strings.HasPrefix(conf.ExternalAuthenticationURL, "http://") && // Authentication
!strings.HasPrefix(conf.ExternalAuthenticationURL, "https://") {
return fmt.Errorf("'externalAuthenticationURL' must be a HTTP URL") 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 contains(conf.AuthMethods, headers.AuthDigest) { case AuthMethodJWT:
return fmt.Errorf("'externalAuthenticationURL' can't be used when 'digest' is in authMethods") if conf.AuthJWTJWKS == "" {
return fmt.Errorf("'authJWTJWKS' is empty")
} }
} }
// RTSP // RTSP
if conf.RTSPDisable {
conf.RTSP = false if conf.RTSPDisable != nil {
conf.RTSP = !*conf.RTSPDisable
} }
if conf.Encryption == EncryptionStrict { if conf.Encryption == EncryptionStrict {
if _, ok := conf.Protocols[Protocol(gortsplib.TransportUDP)]; ok { if _, ok := conf.Protocols[Protocol(gortsplib.TransportUDP)]; ok {
@ -246,36 +531,62 @@ func (conf *Conf) Check() error {
return fmt.Errorf("strict encryption can't be used with the UDP-multicast transport protocol") 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 // RTMP
if conf.RTMPDisable {
conf.RTMP = false if conf.RTMPDisable != nil {
conf.RTMP = !*conf.RTMPDisable
} }
// HLS // HLS
if conf.HLSDisable {
conf.HLS = false if conf.HLSDisable != nil {
conf.HLS = !*conf.HLSDisable
} }
// WebRTC // WebRTC
if conf.WebRTCDisable {
conf.WebRTC = false if conf.WebRTCDisable != nil {
} conf.WebRTC = !*conf.WebRTCDisable
for _, server := range conf.WebRTCICEServers { }
parts := strings.Split(server, ":") if conf.WebRTCICEUDPMuxAddress != nil {
if len(parts) == 5 { conf.WebRTCLocalUDPAddress = *conf.WebRTCICEUDPMuxAddress
conf.WebRTCICEServers2 = append(conf.WebRTCICEServers2, WebRTCICEServer{ }
URL: parts[0] + ":" + parts[3] + ":" + parts[4], if conf.WebRTCICETCPMuxAddress != nil {
Username: parts[1], conf.WebRTCLocalTCPAddress = *conf.WebRTCICETCPMuxAddress
Password: parts[2], }
}) if conf.WebRTCICEHostNAT1To1IPs != nil {
} else { conf.WebRTCAdditionalHosts = *conf.WebRTCICEHostNAT1To1IPs
conf.WebRTCICEServers2 = append(conf.WebRTCICEServers2, WebRTCICEServer{ }
URL: server, if conf.WebRTCICEServers != nil {
}) for _, server := range *conf.WebRTCICEServers {
parts := strings.Split(server, ":")
if len(parts) == 5 {
conf.WebRTCICEServers2 = append(conf.WebRTCICEServers2, WebRTCICEServer{
URL: parts[0] + ":" + parts[3] + ":" + parts[4],
Username: parts[1],
Password: parts[2],
})
} else {
conf.WebRTCICEServers2 = append(conf.WebRTCICEServers2, WebRTCICEServer{
URL: server,
})
}
} }
} }
conf.WebRTCICEServers = nil
for _, server := range conf.WebRTCICEServers2 { for _, server := range conf.WebRTCICEServers2 {
if !strings.HasPrefix(server.URL, "stun:") && if !strings.HasPrefix(server.URL, "stun:") &&
!strings.HasPrefix(server.URL, "turn:") && !strings.HasPrefix(server.URL, "turn:") &&
@ -283,22 +594,62 @@ func (conf *Conf) Check() error {
return fmt.Errorf("invalid ICE server: '%s'", server.URL) return fmt.Errorf("invalid ICE server: '%s'", server.URL)
} }
} }
if conf.WebRTCLocalUDPAddress == "" &&
conf.WebRTCLocalTCPAddress == "" &&
len(conf.WebRTCICEServers2) == 0 {
return fmt.Errorf("at least one between 'webrtcLocalUDPAddress'," +
" 'webrtcLocalTCPAddress' or 'webrtcICEServers2' must be filled")
}
if conf.WebRTCLocalUDPAddress != "" || conf.WebRTCLocalTCPAddress != "" {
if !conf.WebRTCIPsFromInterfaces && len(conf.WebRTCAdditionalHosts) == 0 {
return fmt.Errorf("at least one between 'webrtcIPsFromInterfaces' or 'webrtcAdditionalHosts' must be filled")
}
}
// do not add automatically "all", since user may want to // Record (deprecated)
// initialize all paths through API or hot reloading. if conf.Record != nil {
if conf.Paths == nil { conf.PathDefaults.Record = *conf.Record
conf.Paths = make(map[string]*PathConf)
} }
if conf.RecordPath != nil {
conf.PathDefaults.RecordPath = *conf.RecordPath
}
if conf.RecordFormat != nil {
conf.PathDefaults.RecordFormat = *conf.RecordFormat
}
if conf.RecordPartDuration != nil {
conf.PathDefaults.RecordPartDuration = *conf.RecordPartDuration
}
if conf.RecordSegmentDuration != nil {
conf.PathDefaults.RecordSegmentDuration = *conf.RecordSegmentDuration
}
if conf.RecordDeleteAfter != nil {
conf.PathDefaults.RecordDeleteAfter = *conf.RecordDeleteAfter
}
hasAllOthers := false
for name := range conf.OptionalPaths {
if name == "all" || name == "all_others" || name == "~^.*$" {
if hasAllOthers {
return fmt.Errorf("all_others, all and '~^.*$' are aliases")
}
hasAllOthers = true
}
}
conf.Paths = make(map[string]*Path)
for _, name := range getSortedKeys(conf.Paths) { for _, name := range sortedKeys(conf.OptionalPaths) {
pconf := conf.Paths[name] optional := conf.OptionalPaths[name]
if pconf == nil { if optional == nil {
pconf = &PathConf{} optional = &OptionalPath{
pconf.UnmarshalJSON(nil) // fill defaults Values: newOptionalPathValues(),
conf.Paths[name] = pconf }
} }
err := pconf.check(conf, name) pconf := newPath(&conf.PathDefaults, optional)
conf.Paths[name] = pconf
err := pconf.validate(conf, name, deprecatedCredentialsMode)
if err != nil { if err != nil {
return err return err
} }
@ -307,69 +658,77 @@ func (conf *Conf) Check() error {
return nil return nil
} }
// UnmarshalJSON implements json.Unmarshaler. It is used to set default values. // UnmarshalJSON implements json.Unmarshaler.
func (conf *Conf) UnmarshalJSON(b []byte) error { func (conf *Conf) UnmarshalJSON(b []byte) error {
// general conf.setDefaults()
conf.LogLevel = LogLevel(logger.Info)
conf.LogDestinations = LogDestinations{logger.DestinationStdout}
conf.LogFile = "mediamtx.log"
conf.ReadTimeout = 10 * StringDuration(time.Second)
conf.WriteTimeout = 10 * StringDuration(time.Second)
conf.ReadBufferCount = 512
conf.UDPMaxPayloadSize = 1472
conf.APIAddress = "127.0.0.1:9997"
conf.MetricsAddress = "127.0.0.1:9998"
conf.PPROFAddress = "127.0.0.1:9999"
// RTSP type alias Conf
conf.RTSP = true d := json.NewDecoder(bytes.NewReader(b))
conf.Protocols = Protocols{ d.DisallowUnknownFields()
Protocol(gortsplib.TransportUDP): {}, return d.Decode((*alias)(conf))
Protocol(gortsplib.TransportUDPMulticast): {}, }
Protocol(gortsplib.TransportTCP): {},
// Global returns the global part of Conf.
func (conf *Conf) Global() *Global {
g := &Global{
Values: newGlobalValues(),
} }
conf.RTSPAddress = ":8554" copyStructFields(g.Values, conf)
conf.RTSPSAddress = ":8322" return g
conf.RTPAddress = ":8000" }
conf.RTCPAddress = ":8001"
conf.MulticastIPRange = "224.1.0.0/16"
conf.MulticastRTPPort = 8002
conf.MulticastRTCPPort = 8003
conf.ServerKey = "server.key"
conf.ServerCert = "server.crt"
conf.AuthMethods = AuthMethods{headers.AuthBasic}
// RTMP // PatchGlobal patches the global configuration.
conf.RTMP = true func (conf *Conf) PatchGlobal(optional *OptionalGlobal) {
conf.RTMPAddress = ":1935" copyStructFields(conf, optional.Values)
conf.RTMPSAddress = ":1936" }
// HLS // PatchPathDefaults patches path default settings.
conf.HLS = true func (conf *Conf) PatchPathDefaults(optional *OptionalPath) {
conf.HLSAddress = ":8888" copyStructFields(&conf.PathDefaults, optional.Values)
conf.HLSServerKey = "server.key" }
conf.HLSServerCert = "server.crt"
conf.HLSVariant = HLSVariant(gohlslib.MuxerVariantLowLatency)
conf.HLSSegmentCount = 7
conf.HLSSegmentDuration = 1 * StringDuration(time.Second)
conf.HLSPartDuration = 200 * StringDuration(time.Millisecond)
conf.HLSSegmentMaxSize = 50 * 1024 * 1024
conf.HLSAllowOrigin = "*"
// WebRTC // AddPath adds a path.
conf.WebRTC = true func (conf *Conf) AddPath(name string, p *OptionalPath) error {
conf.WebRTCAddress = ":8889" if _, ok := conf.OptionalPaths[name]; ok {
conf.WebRTCServerKey = "server.key" return fmt.Errorf("path already exists")
conf.WebRTCServerCert = "server.crt" }
conf.WebRTCAllowOrigin = "*"
conf.WebRTCICEServers2 = []WebRTCICEServer{{URL: "stun:stun.l.google.com:19302"}}
// SRT if conf.OptionalPaths == nil {
conf.SRT = true conf.OptionalPaths = make(map[string]*OptionalPath)
conf.SRTAddress = ":8890" }
type alias Conf conf.OptionalPaths[name] = p
d := json.NewDecoder(bytes.NewReader(b)) return nil
d.DisallowUnknownFields() }
return d.Decode((*alias)(conf))
// PatchPath patches a path.
func (conf *Conf) PatchPath(name string, optional2 *OptionalPath) error {
optional, ok := conf.OptionalPaths[name]
if !ok {
return ErrPathNotFound
}
copyStructFields(optional.Values, optional2.Values)
return nil
}
// ReplacePath replaces a path.
func (conf *Conf) ReplacePath(name string, optional2 *OptionalPath) error {
_, ok := conf.OptionalPaths[name]
if !ok {
return ErrPathNotFound
}
conf.OptionalPaths[name] = optional2
return nil
}
// RemovePath removes a path.
func (conf *Conf) RemovePath(name string) error {
if _, ok := conf.OptionalPaths[name]; !ok {
return ErrPathNotFound
}
delete(conf.OptionalPaths, name)
return nil
} }

203
internal/conf/conf_test.go

@ -8,14 +8,14 @@ import (
"testing" "testing"
"time" "time"
"github.com/bluenviron/gortsplib/v3" "github.com/bluenviron/gortsplib/v4"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"golang.org/x/crypto/nacl/secretbox" "golang.org/x/crypto/nacl/secretbox"
"github.com/bluenviron/mediamtx/internal/logger" "github.com/bluenviron/mediamtx/internal/logger"
) )
func writeTempFile(byts []byte) (string, error) { func createTempFile(byts []byte) (string, error) {
tmpf, err := os.CreateTemp(os.TempDir(), "rtsp-") tmpf, err := os.CreateTemp(os.TempDir(), "rtsp-")
if err != nil { if err != nil {
return "", err return "", err
@ -32,36 +32,51 @@ func writeTempFile(byts []byte) (string, error) {
func TestConfFromFile(t *testing.T) { func TestConfFromFile(t *testing.T) {
func() { func() {
tmpf, err := writeTempFile([]byte("logLevel: debug\n" + tmpf, err := createTempFile([]byte("logLevel: debug\n" +
"paths:\n" + "paths:\n" +
" cam1:\n" + " cam1:\n" +
" runOnDemandStartTimeout: 5s\n")) " runOnDemandStartTimeout: 5s\n"))
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpf) defer os.Remove(tmpf)
conf, hasFile, err := Load(tmpf) conf, confPath, err := Load(tmpf, nil)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, true, hasFile) require.Equal(t, tmpf, confPath)
require.Equal(t, LogLevel(logger.Debug), conf.LogLevel) require.Equal(t, LogLevel(logger.Debug), conf.LogLevel)
pa, ok := conf.Paths["cam1"] pa, ok := conf.Paths["cam1"]
require.Equal(t, true, ok) require.Equal(t, true, ok)
require.Equal(t, &PathConf{ require.Equal(t, &Path{
Name: "cam1",
Source: "publisher", Source: "publisher",
SourceOnDemandStartTimeout: 10 * StringDuration(time.Second), SourceOnDemandStartTimeout: 10 * StringDuration(time.Second),
SourceOnDemandCloseAfter: 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,
RecordSegmentDuration: 3600000000000,
RecordDeleteAfter: 86400000000000,
OverridePublisher: true, OverridePublisher: true,
RPICameraWidth: 1920, RPICameraWidth: 1920,
RPICameraHeight: 1080, RPICameraHeight: 1080,
RPICameraContrast: 1, RPICameraContrast: 1,
RPICameraSaturation: 1, RPICameraSaturation: 1,
RPICameraSharpness: 1, RPICameraSharpness: 1,
RPICameraExposure: "normal",
RPICameraAWB: "auto",
RPICameraAWBGains: []float64{0, 0},
RPICameraDenoise: "off",
RPICameraMetering: "centre",
RPICameraFPS: 30, RPICameraFPS: 30,
RPICameraIDRPeriod: 60, RPICameraIDRPeriod: 60,
RPICameraBitrate: 1000000, RPICameraBitrate: 1000000,
RPICameraProfile: "main", RPICameraProfile: "main",
RPICameraLevel: "4.1", RPICameraLevel: "4.1",
RPICameraAfMode: "continuous",
RPICameraAfRange: "normal",
RPICameraAfSpeed: "normal",
RPICameraTextOverlay: "%Y-%m-%d %H:%M:%S - MediaMTX", RPICameraTextOverlay: "%Y-%m-%d %H:%M:%S - MediaMTX",
RunOnDemandStartTimeout: 5 * StringDuration(time.Second), RunOnDemandStartTimeout: 5 * StringDuration(time.Second),
RunOnDemandCloseAfter: 10 * StringDuration(time.Second), RunOnDemandCloseAfter: 10 * StringDuration(time.Second),
@ -69,104 +84,78 @@ func TestConfFromFile(t *testing.T) {
}() }()
func() { func() {
tmpf, err := writeTempFile([]byte(``)) tmpf, err := createTempFile([]byte(``))
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpf) defer os.Remove(tmpf)
_, _, err = Load(tmpf) _, _, err = Load(tmpf, nil)
require.NoError(t, err) require.NoError(t, err)
}() }()
func() { func() {
tmpf, err := writeTempFile([]byte(`paths:`)) tmpf, err := createTempFile([]byte(`paths:`))
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpf) defer os.Remove(tmpf)
_, _, err = Load(tmpf) _, _, err = Load(tmpf, nil)
require.NoError(t, err) require.NoError(t, err)
}() }()
func() { func() {
tmpf, err := writeTempFile([]byte( tmpf, err := createTempFile([]byte(
"paths:\n" + "paths:\n" +
" mypath:\n")) " mypath:\n"))
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpf) defer os.Remove(tmpf)
_, _, err = Load(tmpf) _, _, err = Load(tmpf, nil)
require.NoError(t, err) require.NoError(t, err)
}() }()
} }
func TestConfFromFileAndEnv(t *testing.T) { func TestConfFromFileAndEnv(t *testing.T) {
os.Setenv("MTX_PATHS_CAM1_SOURCE", "rtsp://testing") // global parameter
defer os.Unsetenv("MTX_PATHS_CAM1_SOURCE") t.Setenv("RTSP_PROTOCOLS", "tcp")
os.Setenv("RTSP_PROTOCOLS", "tcp") // path parameter
defer os.Unsetenv("RTSP_PROTOCOLS") t.Setenv("MTX_PATHS_CAM1_SOURCE", "rtsp://testing")
tmpf, err := writeTempFile([]byte("{}")) // deprecated global parameter
t.Setenv("MTX_RTMPDISABLE", "yes")
// deprecated path parameter
t.Setenv("MTX_PATHS_CAM2_DISABLEPUBLISHEROVERRIDE", "yes")
tmpf, err := createTempFile([]byte("{}"))
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpf) defer os.Remove(tmpf)
conf, hasFile, err := Load(tmpf) conf, confPath, err := Load(tmpf, nil)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, true, hasFile) require.Equal(t, tmpf, confPath)
require.Equal(t, Protocols{Protocol(gortsplib.TransportTCP): {}}, conf.Protocols) require.Equal(t, Protocols{Protocol(gortsplib.TransportTCP): {}}, conf.Protocols)
require.Equal(t, false, conf.RTMP)
pa, ok := conf.Paths["cam1"] pa, ok := conf.Paths["cam1"]
require.Equal(t, true, ok) require.Equal(t, true, ok)
require.Equal(t, &PathConf{ require.Equal(t, "rtsp://testing", pa.Source)
Source: "rtsp://testing",
SourceOnDemandStartTimeout: 10 * StringDuration(time.Second), pa, ok = conf.Paths["cam2"]
SourceOnDemandCloseAfter: 10 * StringDuration(time.Second), require.Equal(t, true, ok)
OverridePublisher: true, require.Equal(t, false, pa.OverridePublisher)
RPICameraWidth: 1920,
RPICameraHeight: 1080,
RPICameraContrast: 1,
RPICameraSaturation: 1,
RPICameraSharpness: 1,
RPICameraFPS: 30,
RPICameraIDRPeriod: 60,
RPICameraBitrate: 1000000,
RPICameraProfile: "main",
RPICameraLevel: "4.1",
RPICameraTextOverlay: "%Y-%m-%d %H:%M:%S - MediaMTX",
RunOnDemandStartTimeout: 10 * StringDuration(time.Second),
RunOnDemandCloseAfter: 10 * StringDuration(time.Second),
}, pa)
} }
func TestConfFromEnvOnly(t *testing.T) { func TestConfFromEnvOnly(t *testing.T) {
os.Setenv("MTX_PATHS_CAM1_SOURCE", "rtsp://testing") t.Setenv("MTX_PATHS_CAM1_SOURCE", "rtsp://testing")
defer os.Unsetenv("MTX_PATHS_CAM1_SOURCE")
conf, hasFile, err := Load("mediamtx.yml") conf, confPath, err := Load("", nil)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, false, hasFile) require.Equal(t, "", confPath)
pa, ok := conf.Paths["cam1"] pa, ok := conf.Paths["cam1"]
require.Equal(t, true, ok) require.Equal(t, true, ok)
require.Equal(t, &PathConf{ require.Equal(t, "rtsp://testing", pa.Source)
Source: "rtsp://testing",
SourceOnDemandStartTimeout: 10 * StringDuration(time.Second),
SourceOnDemandCloseAfter: 10 * StringDuration(time.Second),
OverridePublisher: true,
RPICameraWidth: 1920,
RPICameraHeight: 1080,
RPICameraContrast: 1,
RPICameraSaturation: 1,
RPICameraSharpness: 1,
RPICameraFPS: 30,
RPICameraIDRPeriod: 60,
RPICameraBitrate: 1000000,
RPICameraProfile: "main",
RPICameraLevel: "4.1",
RPICameraTextOverlay: "%Y-%m-%d %H:%M:%S - MediaMTX",
RunOnDemandStartTimeout: 10 * StringDuration(time.Second),
RunOnDemandCloseAfter: 10 * StringDuration(time.Second),
}, pa)
} }
func TestConfEncryption(t *testing.T) { func TestConfEncryption(t *testing.T) {
@ -187,16 +176,15 @@ func TestConfEncryption(t *testing.T) {
return base64.StdEncoding.EncodeToString(encrypted) return base64.StdEncoding.EncodeToString(encrypted)
}() }()
os.Setenv("RTSP_CONFKEY", key) t.Setenv("RTSP_CONFKEY", key)
defer os.Unsetenv("RTSP_CONFKEY")
tmpf, err := writeTempFile([]byte(encryptedConf)) tmpf, err := createTempFile([]byte(encryptedConf))
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpf) defer os.Remove(tmpf)
conf, hasFile, err := Load(tmpf) conf, confPath, err := Load(tmpf, nil)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, true, hasFile) require.Equal(t, tmpf, confPath)
_, ok := conf.Paths["path1"] _, ok := conf.Paths["path1"]
require.Equal(t, true, ok) require.Equal(t, true, ok)
@ -217,26 +205,15 @@ func TestConfErrors(t *testing.T) {
"json: unknown field \"invalid\"", "json: unknown field \"invalid\"",
}, },
{ {
"invalid readBufferCount", "invalid writeQueueSize",
"readBufferCount: 1001\n", "writeQueueSize: 1001\n",
"'readBufferCount' must be a power of two", "'writeQueueSize' must be a power of two",
}, },
{ {
"invalid udpMaxPayloadSize", "invalid udpMaxPayloadSize",
"udpMaxPayloadSize: 5000\n", "udpMaxPayloadSize: 5000\n",
"'udpMaxPayloadSize' must be less than 1472", "'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", "invalid strict encryption 1",
"encryption: strict\n" + "encryption: strict\n" +
@ -275,16 +252,76 @@ func TestConfErrors(t *testing.T) {
" source: rpiCamera\n" + " source: rpiCamera\n" +
" cam2:\n" + " cam2:\n" +
" source: rpiCamera\n", " source: rpiCamera\n",
"'rpiCamera' with same camera ID 0 is used as source in two paths, 'cam1' and 'cam2'", "'rpiCamera' with same camera ID 0 is used as source in two paths, 'cam2' and 'cam1'",
},
{
"invalid srt publish passphrase",
"paths:\n" +
" mypath:\n" +
" srtPublishPassphrase: a\n",
`invalid 'srtPublishPassphrase': must be between 10 and 79 characters`,
},
{
"invalid srt read passphrase",
"paths:\n" +
" mypath:\n" +
" srtReadPassphrase: a\n",
`invalid 'readRTPassphrase': must be between 10 and 79 characters`,
},
{
"all_others aliases",
"paths:\n" +
" all:\n" +
" all_others:\n",
`all_others, all and '~^.*$' are aliases`,
},
{
"all_others aliases",
"paths:\n" +
" all_others:\n" +
" ~^.*$:\n",
`all_others, all and '~^.*$' are aliases`,
}, },
} { } {
t.Run(ca.name, func(t *testing.T) { t.Run(ca.name, func(t *testing.T) {
tmpf, err := writeTempFile([]byte(ca.conf)) tmpf, err := createTempFile([]byte(ca.conf))
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpf) defer os.Remove(tmpf)
_, _, err = Load(tmpf) _, _, err = Load(tmpf, nil)
require.EqualError(t, err, ca.err) require.EqualError(t, err, ca.err)
}) })
} }
} }
func TestSampleConfFile(t *testing.T) {
func() {
conf1, confPath1, err := Load("../../mediamtx.yml", nil)
require.NoError(t, err)
require.Equal(t, "../../mediamtx.yml", confPath1)
conf1.Paths = make(map[string]*Path)
conf1.OptionalPaths = nil
conf2, confPath2, err := Load("", nil)
require.NoError(t, err)
require.Equal(t, "", confPath2)
require.Equal(t, conf1, conf2)
}()
func() {
conf1, confPath1, err := Load("../../mediamtx.yml", nil)
require.NoError(t, err)
require.Equal(t, "../../mediamtx.yml", confPath1)
tmpf, err := createTempFile([]byte("paths:\n all_others:"))
require.NoError(t, err)
defer os.Remove(tmpf)
conf2, confPath2, err := Load(tmpf, nil)
require.NoError(t, err)
require.Equal(t, tmpf, confPath2)
require.Equal(t, conf1.Paths, conf2.Paths)
}()
}

88
internal/conf/credential.go

@ -1,15 +1,28 @@
package conf package conf
import ( import (
"crypto/sha256"
"encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"regexp" "regexp"
"strings" "strings"
"github.com/matthewhartstonge/argon2"
)
var (
rePlainCredential = regexp.MustCompile(`^[a-zA-Z0-9!\$\(\)\*\+\.;<=>\[\]\^_\-\{\}@#&]+$`)
reBase64 = regexp.MustCompile(`^sha256:[a-zA-Z0-9\+/=]+$`)
) )
var reCredential = regexp.MustCompile(`^[a-zA-Z0-9!\$\(\)\*\+\.;<=>\[\]\^_\-\{\}@#&]+$`) const plainCredentialSupportedChars = "A-Z,0-9,!,$,(,),*,+,.,;,<,=,>,[,],^,_,-,\",\",@,#,&"
const credentialSupportedChars = "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. // Credential is a parameter that is used as username or password.
type Credential string type Credential string
@ -26,17 +39,70 @@ func (d *Credential) UnmarshalJSON(b []byte) error {
return err return err
} }
if in != "" && *d = Credential(in)
!strings.HasPrefix(in, "sha256:") &&
!reCredential.MatchString(in) { return d.validate()
return fmt.Errorf("credential contains unsupported characters. Supported are: %s", credentialSupportedChars) }
// UnmarshalEnv implements env.Unmarshaler.
func (d *Credential) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + v + `"`))
}
// IsSha256 returns true if the credential is a sha256 hash.
func (d Credential) IsSha256() bool {
return strings.HasPrefix(string(d), "sha256:")
}
// IsArgon2 returns true if the credential is an argon2 hash.
func (d Credential) IsArgon2() bool {
return strings.HasPrefix(string(d), "argon2:")
}
// IsHashed returns true if the credential is a sha256 or argon2 hash.
func (d Credential) IsHashed() bool {
return d.IsSha256() || d.IsArgon2()
}
// Check returns true if the given value matches the credential.
func (d Credential) Check(guess string) bool {
if d.IsSha256() {
return string(d)[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:"):]))
return ok && err == nil
} }
*d = Credential(in) if d != "" {
return nil return string(d) == guess
}
return true
} }
// UnmarshalEnv implements envUnmarshaler. func (d Credential) validate() error {
func (d *Credential) UnmarshalEnv(s string) error { if d != "" {
return d.UnmarshalJSON([]byte(`"` + s + `"`)) 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)
}
}
}
return nil
} }

151
internal/conf/credential_test.go

@ -0,0 +1,151 @@
package conf
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCredential(t *testing.T) {
t.Run("MarshalJSON", func(t *testing.T) {
cred := Credential("password")
expectedJSON := []byte(`"password"`)
actualJSON, err := cred.MarshalJSON()
assert.NoError(t, err)
assert.Equal(t, expectedJSON, actualJSON)
})
t.Run("UnmarshalJSON", func(t *testing.T) {
expectedCred := Credential("password")
jsonData := []byte(`"password"`)
var actualCred Credential
err := actualCred.UnmarshalJSON(jsonData)
assert.NoError(t, err)
assert.Equal(t, expectedCred, actualCred)
})
t.Run("UnmarshalEnv", func(t *testing.T) {
cred := Credential("")
err := cred.UnmarshalEnv("", "password")
assert.NoError(t, err)
assert.Equal(t, Credential("password"), cred)
})
t.Run("IsSha256", func(t *testing.T) {
cred := Credential("")
assert.False(t, cred.IsSha256())
assert.False(t, cred.IsHashed())
cred = "sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo="
assert.True(t, cred.IsSha256())
assert.True(t, cred.IsHashed())
cred = "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("")
assert.False(t, cred.IsArgon2())
assert.False(t, cred.IsHashed())
cred = "sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo="
assert.False(t, cred.IsArgon2())
assert.True(t, cred.IsHashed())
cred = "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")
assert.True(t, cred.Check("password"))
assert.False(t, cred.Check("wrongpassword"))
})
t.Run("Check-sha256", func(t *testing.T) {
cred := Credential("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=")
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")
assert.True(t, cred.Check("testuser"))
assert.False(t, cred.Check("notestuser"))
})
t.Run("validate", func(t *testing.T) {
tests := []struct {
name string
cred Credential
wantErr bool
}{
{
name: "Empty credential",
cred: Credential(""),
wantErr: false,
},
{
name: "Valid plain credential",
cred: Credential("validPlain123"),
wantErr: false,
},
{
name: "Invalid plain credential",
cred: Credential("invalid/Plain"),
wantErr: true,
},
{
name: "Valid sha256 credential",
cred: Credential("sha256:validBase64EncodedHash=="),
wantErr: false,
},
{
name: "Invalid sha256 credential",
cred: Credential("sha256:inval*idBase64"),
wantErr: true,
},
{
name: "Valid Argon2 credential",
cred: Credential("argon2:$argon2id$v=19$m=4096," +
"t=3,p=1$MTIzNDU2Nzg$zarsL19s86GzUWlAkvwt4gJBFuU/A9CVuCjNI4fksow"),
wantErr: false,
},
{
name: "Invalid Argon2 credential",
cred: Credential("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"),
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.cred.validate()
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
})
}

13
internal/conf/encryption.go

@ -8,7 +8,7 @@ import (
// Encryption is the encryption parameter. // Encryption is the encryption parameter.
type Encryption int type Encryption int
// supported encryption policies. // values.
const ( const (
EncryptionNo Encryption = iota EncryptionNo Encryption = iota
EncryptionOptional EncryptionOptional
@ -26,11 +26,8 @@ func (d Encryption) MarshalJSON() ([]byte, error) {
case EncryptionOptional: case EncryptionOptional:
out = "optional" out = "optional"
case EncryptionStrict:
out = "strict"
default: default:
return nil, fmt.Errorf("invalid encryption: %v", d) out = "strict"
} }
return json.Marshal(out) return json.Marshal(out)
@ -60,7 +57,7 @@ func (d *Encryption) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *Encryption) UnmarshalEnv(s string) error { func (d *Encryption) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + s + `"`)) return d.UnmarshalJSON([]byte(`"` + v + `"`))
} }

134
internal/conf/env/env.go vendored

@ -2,7 +2,6 @@
package env package env
import ( import (
"encoding/json"
"fmt" "fmt"
"os" "os"
"reflect" "reflect"
@ -10,8 +9,9 @@ import (
"strings" "strings"
) )
type envUnmarshaler interface { // Unmarshaler can be implemented to override the unmarshaling process.
UnmarshalEnv(string) error type Unmarshaler interface {
UnmarshalEnv(prefix string, v string) error
} }
func envHasAtLeastAKeyWithPrefix(env map[string]string, prefix string) bool { func envHasAtLeastAKeyWithPrefix(env map[string]string, prefix string) bool {
@ -23,14 +23,27 @@ func envHasAtLeastAKeyWithPrefix(env map[string]string, prefix string) bool {
return false return false
} }
func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) error { func loadEnvInternal(env map[string]string, prefix string, prv reflect.Value) error {
rt := rv.Type() if prv.Kind() != reflect.Pointer {
return loadEnvInternal(env, prefix, prv.Addr())
}
rt := prv.Type().Elem()
if i, ok := rv.Addr().Interface().(envUnmarshaler); ok { if i, ok := prv.Interface().(Unmarshaler); ok {
if ev, ok := env[prefix]; ok { if ev, ok := env[prefix]; ok {
err := i.UnmarshalEnv(ev) if prv.IsNil() {
prv.Set(reflect.New(rt))
i = prv.Interface().(Unmarshaler)
}
err := i.UnmarshalEnv(prefix, ev)
if err != nil {
return fmt.Errorf("%s: %w", prefix, err)
}
} else if envHasAtLeastAKeyWithPrefix(env, prefix) {
err := i.UnmarshalEnv(prefix, "")
if err != nil { if err != nil {
return fmt.Errorf("%s: %s", prefix, err) return fmt.Errorf("%s: %w", prefix, err)
} }
} }
return nil return nil
@ -39,48 +52,63 @@ func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) err
switch rt { switch rt {
case reflect.TypeOf(""): case reflect.TypeOf(""):
if ev, ok := env[prefix]; ok { if ev, ok := env[prefix]; ok {
rv.SetString(ev) if prv.IsNil() {
prv.Set(reflect.New(rt))
}
prv.Elem().SetString(ev)
} }
return nil return nil
case reflect.TypeOf(int(0)): case reflect.TypeOf(int(0)):
if ev, ok := env[prefix]; ok { if ev, ok := env[prefix]; ok {
if prv.IsNil() {
prv.Set(reflect.New(rt))
}
iv, err := strconv.ParseInt(ev, 10, 32) iv, err := strconv.ParseInt(ev, 10, 32)
if err != nil { if err != nil {
return fmt.Errorf("%s: %s", prefix, err) return fmt.Errorf("%s: %w", prefix, err)
} }
rv.SetInt(iv) prv.Elem().SetInt(iv)
} }
return nil return nil
case reflect.TypeOf(uint64(0)): case reflect.TypeOf(uint64(0)):
if ev, ok := env[prefix]; ok { if ev, ok := env[prefix]; ok {
if prv.IsNil() {
prv.Set(reflect.New(rt))
}
iv, err := strconv.ParseUint(ev, 10, 32) iv, err := strconv.ParseUint(ev, 10, 32)
if err != nil { if err != nil {
return fmt.Errorf("%s: %s", prefix, err) return fmt.Errorf("%s: %w", prefix, err)
} }
rv.SetUint(iv) prv.Elem().SetUint(iv)
} }
return nil return nil
case reflect.TypeOf(float64(0)): case reflect.TypeOf(float64(0)):
if ev, ok := env[prefix]; ok { if ev, ok := env[prefix]; ok {
if prv.IsNil() {
prv.Set(reflect.New(rt))
}
iv, err := strconv.ParseFloat(ev, 64) iv, err := strconv.ParseFloat(ev, 64)
if err != nil { if err != nil {
return fmt.Errorf("%s: %s", prefix, err) return fmt.Errorf("%s: %w", prefix, err)
} }
rv.SetFloat(iv) prv.Elem().SetFloat(iv)
} }
return nil return nil
case reflect.TypeOf(bool(false)): case reflect.TypeOf(bool(false)):
if ev, ok := env[prefix]; ok { if ev, ok := env[prefix]; ok {
if prv.IsNil() {
prv.Set(reflect.New(rt))
}
switch strings.ToLower(ev) { switch strings.ToLower(ev) {
case "yes", "true": case "yes", "true":
rv.SetBool(true) prv.Elem().SetBool(true)
case "no", "false": case "no", "false":
rv.SetBool(false) prv.Elem().SetBool(false)
default: default:
return fmt.Errorf("%s: invalid value '%s'", prefix, ev) return fmt.Errorf("%s: invalid value '%s'", prefix, ev)
@ -107,19 +135,16 @@ func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) err
} }
// initialize only if there's at least one key // initialize only if there's at least one key
if rv.IsNil() { if prv.Elem().IsNil() {
rv.Set(reflect.MakeMap(rt)) prv.Elem().Set(reflect.MakeMap(rt))
} }
mapKeyLower := strings.ToLower(mapKey) mapKeyLower := strings.ToLower(mapKey)
nv := rv.MapIndex(reflect.ValueOf(mapKeyLower)) nv := prv.Elem().MapIndex(reflect.ValueOf(mapKeyLower))
zero := reflect.Value{} zero := reflect.Value{}
if nv == zero { if nv == zero {
nv = reflect.New(rt.Elem().Elem()) nv = reflect.New(rt.Elem().Elem())
if unm, ok := nv.Interface().(json.Unmarshaler); ok { prv.Elem().SetMapIndex(reflect.ValueOf(mapKeyLower), nv)
unm.UnmarshalJSON(nil) // load defaults
}
rv.SetMapIndex(reflect.ValueOf(mapKeyLower), nv)
} }
err := loadEnvInternal(env, prefix+"_"+mapKey, nv.Elem()) err := loadEnvInternal(env, prefix+"_"+mapKey, nv.Elem())
@ -133,13 +158,15 @@ func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) err
flen := rt.NumField() flen := rt.NumField()
for i := 0; i < flen; i++ { for i := 0; i < flen; i++ {
f := rt.Field(i) f := rt.Field(i)
jsonTag := f.Tag.Get("json")
// load only public fields // load only public fields
if f.Tag.Get("json") == "-" { if jsonTag == "-" {
continue continue
} }
err := loadEnvInternal(env, prefix+"_"+strings.ToUpper(f.Name), rv.Field(i)) err := loadEnvInternal(env, prefix+"_"+
strings.ToUpper(strings.TrimSuffix(jsonTag, ",omitempty")), prv.Elem().Field(i))
if err != nil { if err != nil {
return err return err
} }
@ -147,20 +174,48 @@ func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) err
return nil return nil
case reflect.Slice: case reflect.Slice:
if rt.Elem() == reflect.TypeOf("") { switch {
case rt.Elem() == reflect.TypeOf(""):
if ev, ok := env[prefix]; ok { if ev, ok := env[prefix]; ok {
if ev == "" { if ev == "" {
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0)) prv.Elem().Set(reflect.MakeSlice(prv.Elem().Type(), 0, 0))
} else { } else {
rv.Set(reflect.ValueOf(strings.Split(ev, ","))) if prv.IsNil() {
prv.Set(reflect.New(rt))
}
prv.Elem().Set(reflect.ValueOf(strings.Split(ev, ",")))
} }
} }
return nil return nil
}
if rt.Elem().Kind() == reflect.Struct { 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 if ev, ok := env[prefix]; ok && ev == "" { // special case: empty list
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0)) prv.Elem().Set(reflect.MakeSlice(prv.Elem().Type(), 0, 0))
} else { } else {
for i := 0; ; i++ { for i := 0; ; i++ {
itemPrefix := prefix + "_" + strconv.FormatInt(int64(i), 10) itemPrefix := prefix + "_" + strconv.FormatInt(int64(i), 10)
@ -174,7 +229,7 @@ func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) err
return err return err
} }
rv.Set(reflect.Append(rv, elem.Elem())) prv.Elem().Set(reflect.Append(prv.Elem(), elem.Elem()))
} }
} }
return nil return nil
@ -184,13 +239,20 @@ func loadEnvInternal(env map[string]string, prefix string, rv reflect.Value) err
return fmt.Errorf("unsupported type: %v", rt) return fmt.Errorf("unsupported type: %v", rt)
} }
// Load loads the configuration from the environment. func loadWithEnv(env map[string]string, prefix string, v interface{}) error {
func Load(prefix string, v interface{}) error { return loadEnvInternal(env, prefix, reflect.ValueOf(v).Elem())
}
func envToMap() map[string]string {
env := make(map[string]string) env := make(map[string]string)
for _, kv := range os.Environ() { for _, kv := range os.Environ() {
tmp := strings.SplitN(kv, "=", 2) tmp := strings.SplitN(kv, "=", 2)
env[tmp[0]] = tmp[1] env[tmp[0]] = tmp[1]
} }
return env
}
return loadEnvInternal(env, prefix, reflect.ValueOf(v).Elem()) // Load loads the configuration from the environment.
func Load(prefix string, v interface{}) error {
return loadWithEnv(envToMap(), prefix, v)
} }

250
internal/conf/env/env_test.go vendored

@ -2,20 +2,34 @@ package env
import ( import (
"encoding/json" "encoding/json"
"os"
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
type subStruct struct { func stringPtr(v string) *string {
MyParam int return &v
} }
type mapEntry struct { func intPtr(v int) *int {
MyValue string return &v
MyStruct subStruct }
func uint64Ptr(v uint64) *uint64 {
return &v
}
func boolPtr(v bool) *bool {
return &v
}
func float64Ptr(v float64) *float64 {
return &v
}
func durationPtr(v time.Duration) *time.Duration {
return &v
} }
type myDuration time.Duration type myDuration time.Duration
@ -35,111 +49,157 @@ func (d *myDuration) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *myDuration) UnmarshalEnv(s string) error { func (d *myDuration) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + s + `"`)) return d.UnmarshalJSON([]byte(`"` + v + `"`))
}
type subStruct struct {
MyParam int `json:"myParam"`
}
type mapEntry struct {
MyValue string `json:"myValue"`
MyStruct subStruct `json:"myStruct"`
} }
type mySubStruct struct { type mySubStruct struct {
URL string URL string `json:"url"`
Username string Username string `json:"username"`
Password string Password string `json:"password"`
MyInt2 int `json:"myInt2"`
} }
type testStruct struct { type testStruct struct {
MyString string MyString string `json:"myString"`
MyInt int MyStringOpt *string `json:"myStringOpt"`
MyFloat float64 MyInt int `json:"myInt"`
MyBool bool MyIntOpt *int `json:"myIntOpt"`
MyDuration myDuration MyUint uint64 `json:"myUint"`
MyMap map[string]*mapEntry MyUintOpt *uint64 `json:"myUintOpt"`
MySlice []string MyFloat float64 `json:"myFloat"`
MySliceEmpty []string MyFloatOpt *float64 `json:"myFloatOpt"`
MySliceSubStruct []mySubStruct MyBool bool `json:"myBool"`
MySliceSubStructEmpty []mySubStruct MyBoolOpt *bool `json:"myBoolOpt"`
MyDuration myDuration `json:"myDuration"`
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"`
MySliceStringOptUnset *[]string `json:"mySliceStringOptUnset"`
MySliceSubStruct []mySubStruct `json:"mySliceSubStruct"`
MySliceSubStructEmpty []mySubStruct `json:"mySliceSubStructEmpty"`
MySliceSubStructOpt *[]mySubStruct `json:"mySliceSubStructOpt"`
MySliceSubStructOptUnset *[]mySubStruct `json:"mySliceSubStructOptUnset"`
Unset *bool `json:"unset"`
} }
func TestLoad(t *testing.T) { func TestLoad(t *testing.T) {
os.Setenv("MYPREFIX_MYSTRING", "testcontent") env := map[string]string{
defer os.Unsetenv("MYPREFIX_MYSTRING") "MYPREFIX_MYSTRING": "testcontent",
"MYPREFIX_MYSTRINGOPT": "testcontent2",
os.Setenv("MYPREFIX_MYINT", "123") "MYPREFIX_MYINT": "123",
defer os.Unsetenv("MYPREFIX_MYINT") "MYPREFIX_MYINTOPT": "456",
"MYPREFIX_MYUINT": "8910",
os.Setenv("MYPREFIX_MYFLOAT", "15.2") "MYPREFIX_MYUINTOPT": "112313",
defer os.Unsetenv("MYPREFIX_MYFLOAT") "MYPREFIX_MYFLOAT": "15.2",
"MYPREFIX_MYFLOATOPT": "16.2",
os.Setenv("MYPREFIX_MYBOOL", "yes") "MYPREFIX_MYBOOL": "yes",
defer os.Unsetenv("MYPREFIX_MYBOOL") "MYPREFIX_MYBOOLOPT": "false",
"MYPREFIX_MYDURATION": "22s",
os.Setenv("MYPREFIX_MYDURATION", "22s") "MYPREFIX_MYDURATIONOPT": "30s",
defer os.Unsetenv("MYPREFIX_MYDURATION") "MYPREFIX_MYMAP_MYKEY": "",
"MYPREFIX_MYMAP_MYKEY2_MYVALUE": "asd",
os.Setenv("MYPREFIX_MYMAP_MYKEY", "") "MYPREFIX_MYMAP_MYKEY2_MYSTRUCT_MYPARAM": "456",
defer os.Unsetenv("MYPREFIX_MYMAP_MYKEY") "MYPREFIX_MYSLICEFLOAT": "0.5,0.5",
"MYPREFIX_MYSLICESTRING": "val1,val2",
os.Setenv("MYPREFIX_MYMAP_MYKEY2_MYVALUE", "asd") "MYPREFIX_MYSLICESTRINGEMPTY": "",
defer os.Unsetenv("MYPREFIX_MYMAP_MYKEY2_MYVALUE") "MYPREFIX_MYSLICESTRINGOPT": "aa",
"MYPREFIX_MYSLICESUBSTRUCT_0_URL": "url1",
os.Setenv("MYPREFIX_MYMAP_MYKEY2_MYSTRUCT_MYPARAM", "456") "MYPREFIX_MYSLICESUBSTRUCT_0_USERNAME": "user1",
defer os.Unsetenv("MYPREFIX_MYMAP_MYKEY2_MYSTRUCT_MYPARAM") "MYPREFIX_MYSLICESUBSTRUCT_0_PASSWORD": "pass1",
"MYPREFIX_MYSLICESUBSTRUCT_1_URL": "url2",
os.Setenv("MYPREFIX_MYSLICE", "val1,val2") "MYPREFIX_MYSLICESUBSTRUCT_1_PASSWORD": "pass2",
defer os.Unsetenv("MYPREFIX_MYSLICE") "MYPREFIX_MYSLICESUBSTRUCTEMPTY": "",
"MYPREFIX_MYSLICESUBSTRUCTOPT_1_PASSWORD": "pwd",
os.Setenv("MYPREFIX_MYSLICEEMPTY", "") }
defer os.Unsetenv("MYPREFIX_MYSLICEEMPTY")
os.Setenv("MYPREFIX_MYSLICESUBSTRUCT_0_URL", "url1")
defer os.Unsetenv("MYPREFIX_MYSLICESUBSTRUCT_0_URL")
os.Setenv("MYPREFIX_MYSLICESUBSTRUCT_0_USERNAME", "user1")
defer os.Unsetenv("MYPREFIX_MYSLICESUBSTRUCT_0_USERNAME")
os.Setenv("MYPREFIX_MYSLICESUBSTRUCT_0_PASSWORD", "pass1")
defer os.Unsetenv("MYPREFIX_MYSLICESUBSTRUCT_0_PASSWORD")
os.Setenv("MYPREFIX_MYSLICESUBSTRUCT_1_URL", "url2")
defer os.Unsetenv("MYPREFIX_MYSLICESUBSTRUCT_1_URL")
os.Setenv("MYPREFIX_MYSLICESUBSTRUCT_1_PASSWORD", "pass2")
defer os.Unsetenv("MYPREFIX_MYSLICESUBSTRUCT_1_PASSWORD")
os.Setenv("MYPREFIX_MYSLICESUBSTRUCTEMPTY", "") for key, val := range env {
defer os.Unsetenv("MYPREFIX_MYSLICESUBSTRUCTEMPTY") t.Setenv(key, val)
}
var s testStruct var s testStruct
err := Load("MYPREFIX", &s) err := Load("MYPREFIX", &s)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "testcontent", s.MyString) require.Equal(t, testStruct{
require.Equal(t, 123, s.MyInt) MyString: "testcontent",
require.Equal(t, 15.2, s.MyFloat) MyStringOpt: stringPtr("testcontent2"),
require.Equal(t, true, s.MyBool) MyInt: 123,
require.Equal(t, 22*myDuration(time.Second), s.MyDuration) MyIntOpt: intPtr(456),
MyUint: 8910,
_, ok := s.MyMap["mykey"] MyUintOpt: uint64Ptr(112313),
require.Equal(t, true, ok) MyFloat: 15.2,
MyFloatOpt: float64Ptr(16.2),
v, ok := s.MyMap["mykey2"] MyBool: true,
require.Equal(t, true, ok) MyBoolOpt: boolPtr(false),
require.Equal(t, "asd", v.MyValue) MyDuration: 22000000000,
require.Equal(t, 456, v.MyStruct.MyParam) MyDurationOpt: (*myDuration)(durationPtr(30000000000)),
MyMap: map[string]*mapEntry{
require.Equal(t, []string{"val1", "val2"}, s.MySlice) "mykey": {
require.Equal(t, []string{}, s.MySliceEmpty) MyValue: "",
MyStruct: subStruct{
require.Equal(t, []mySubStruct{ MyParam: 0,
{ },
URL: "url1", },
Username: "user1", "mykey2": {
Password: "pass1", MyValue: "asd",
MyStruct: subStruct{
MyParam: 456,
},
},
}, },
{ MySliceFloat: []float64{0.5, 0.5},
URL: "url2", MySliceString: []string{
Password: "pass2", "val1",
"val2",
}, },
}, s.MySliceSubStruct) MySliceStringEmpty: []string{},
MySliceStringOpt: &[]string{"aa"},
MySliceSubStruct: []mySubStruct{
{
URL: "url1",
Username: "user1",
Password: "pass1",
},
{
URL: "url2",
Username: "",
Password: "pass2",
},
},
MySliceSubStructEmpty: []mySubStruct{},
}, s)
}
require.Equal(t, []mySubStruct{}, s.MySliceSubStructEmpty) func FuzzLoad(f *testing.F) {
f.Add("MYPREFIX_MYINT", "a")
f.Add("MYPREFIX_MYUINT", "a")
f.Add("MYPREFIX_MYFLOAT", "a")
f.Add("MYPREFIX_MYBOOL", "a")
f.Add("MYPREFIX_MYSLICESUBSTRUCT_0_MYINT2", "a")
f.Add("MYPREFIX_MYDURATION", "a")
f.Add("MYPREFIX_MYDURATION_A", "a")
f.Fuzz(func(_ *testing.T, key string, val string) {
env := map[string]string{
key: val,
}
var s testStruct
loadWithEnv(env, "MYPREFIX", &s) //nolint:errcheck
})
} }

41
internal/conf/global.go

@ -0,0 +1,41 @@
package conf
import (
"encoding/json"
"reflect"
)
var globalValuesType = func() reflect.Type {
var fields []reflect.StructField
rt := reflect.TypeOf(Conf{})
nf := rt.NumField()
for i := 0; i < nf; i++ {
f := rt.Field(i)
j := f.Tag.Get("json")
if j != "-" && j != "pathDefaults" && j != "paths" {
fields = append(fields, reflect.StructField{
Name: f.Name,
Type: f.Type,
Tag: f.Tag,
})
}
}
return reflect.StructOf(fields)
}()
func newGlobalValues() interface{} {
return reflect.New(globalValuesType).Interface()
}
// Global is the global part of Conf.
type Global struct {
Values interface{}
}
// MarshalJSON implements json.Marshaler.
func (p *Global) MarshalJSON() ([]byte, error) {
return json.Marshal(p.Values)
}

11
internal/conf/hls_variant.go

@ -21,11 +21,8 @@ func (d HLSVariant) MarshalJSON() ([]byte, error) {
case HLSVariant(gohlslib.MuxerVariantFMP4): case HLSVariant(gohlslib.MuxerVariantFMP4):
out = "fmp4" out = "fmp4"
case HLSVariant(gohlslib.MuxerVariantLowLatency):
out = "lowLatency"
default: default:
return nil, fmt.Errorf("invalid HLS variant: %v", d) out = "lowLatency"
} }
return json.Marshal(out) return json.Marshal(out)
@ -55,7 +52,7 @@ func (d *HLSVariant) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *HLSVariant) UnmarshalEnv(s string) error { func (d *HLSVariant) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + s + `"`)) return d.UnmarshalJSON([]byte(`"` + v + `"`))
} }

84
internal/conf/ip_networks.go

@ -0,0 +1,84 @@
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

@ -1,66 +0,0 @@
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 envUnmarshaler.
func (d *IPsOrCIDRs) UnmarshalEnv(s string) error {
byts, _ := json.Marshal(strings.Split(s, ","))
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
}

11
internal/conf/log_destination.go

@ -26,11 +26,8 @@ func (d LogDestinations) MarshalJSON() ([]byte, error) {
case logger.DestinationFile: case logger.DestinationFile:
v = "file" v = "file"
case logger.DestinationSyslog:
v = "syslog"
default: default:
return nil, fmt.Errorf("invalid log destination: %v", p) v = "syslog"
} }
out[i] = v out[i] = v
@ -84,8 +81,8 @@ func (d *LogDestinations) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *LogDestinations) UnmarshalEnv(s string) error { func (d *LogDestinations) UnmarshalEnv(_ string, v string) error {
byts, _ := json.Marshal(strings.Split(s, ",")) byts, _ := json.Marshal(strings.Split(v, ","))
return d.UnmarshalJSON(byts) return d.UnmarshalJSON(byts)
} }

11
internal/conf/log_level.go

@ -24,11 +24,8 @@ func (d LogLevel) MarshalJSON() ([]byte, error) {
case LogLevel(logger.Info): case LogLevel(logger.Info):
out = "info" out = "info"
case LogLevel(logger.Debug):
out = "debug"
default: default:
return nil, fmt.Errorf("invalid log level: %v", d) out = "debug"
} }
return json.Marshal(out) return json.Marshal(out)
@ -61,7 +58,7 @@ func (d *LogLevel) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *LogLevel) UnmarshalEnv(s string) error { func (d *LogLevel) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + s + `"`)) return d.UnmarshalJSON([]byte(`"` + v + `"`))
} }

60
internal/conf/optional_global.go

@ -0,0 +1,60 @@
package conf
import (
"bytes"
"encoding/json"
"reflect"
"strings"
)
var optionalGlobalValuesType = func() reflect.Type {
var fields []reflect.StructField
rt := reflect.TypeOf(Conf{})
nf := rt.NumField()
for i := 0; i < nf; i++ {
f := rt.Field(i)
j := f.Tag.Get("json")
if j != "-" && j != "pathDefaults" && j != "paths" {
if !strings.Contains(j, ",omitempty") {
j += ",omitempty"
}
typ := f.Type
if typ.Kind() != reflect.Pointer {
typ = reflect.PtrTo(typ)
}
fields = append(fields, reflect.StructField{
Name: f.Name,
Type: typ,
Tag: reflect.StructTag(`json:"` + j + `"`),
})
}
}
return reflect.StructOf(fields)
}()
func newOptionalGlobalValues() interface{} {
return reflect.New(optionalGlobalValuesType).Interface()
}
// OptionalGlobal is a Conf whose values can all be optional.
type OptionalGlobal struct {
Values interface{}
}
// UnmarshalJSON implements json.Unmarshaler.
func (p *OptionalGlobal) UnmarshalJSON(b []byte) error {
p.Values = newOptionalGlobalValues()
d := json.NewDecoder(bytes.NewReader(b))
d.DisallowUnknownFields()
return d.Decode(p.Values)
}
// MarshalJSON implements json.Marshaler.
func (p *OptionalGlobal) MarshalJSON() ([]byte, error) {
return json.Marshal(p.Values)
}

70
internal/conf/optional_path.go

@ -0,0 +1,70 @@
package conf
import (
"bytes"
"encoding/json"
"reflect"
"strings"
"github.com/bluenviron/mediamtx/internal/conf/env"
)
var optionalPathValuesType = func() reflect.Type {
var fields []reflect.StructField
rt := reflect.TypeOf(Path{})
nf := rt.NumField()
for i := 0; i < nf; i++ {
f := rt.Field(i)
j := f.Tag.Get("json")
if j != "-" {
if !strings.Contains(j, ",omitempty") {
j += ",omitempty"
}
typ := f.Type
if typ.Kind() != reflect.Pointer {
typ = reflect.PtrTo(typ)
}
fields = append(fields, reflect.StructField{
Name: f.Name,
Type: typ,
Tag: reflect.StructTag(`json:"` + j + `"`),
})
}
}
return reflect.StructOf(fields)
}()
func newOptionalPathValues() interface{} {
return reflect.New(optionalPathValuesType).Interface()
}
// OptionalPath is a Path whose values can all be optional.
type OptionalPath struct {
Values interface{}
}
// UnmarshalJSON implements json.Unmarshaler.
func (p *OptionalPath) UnmarshalJSON(b []byte) error {
p.Values = newOptionalPathValues()
d := json.NewDecoder(bytes.NewReader(b))
d.DisallowUnknownFields()
return d.Decode(p.Values)
}
// UnmarshalEnv implements env.Unmarshaler.
func (p *OptionalPath) UnmarshalEnv(prefix string, _ string) error {
if p.Values == nil {
p.Values = newOptionalPathValues()
}
return env.Load(prefix, p.Values)
}
// MarshalJSON implements json.Marshaler.
func (p *OptionalPath) MarshalJSON() ([]byte, error) {
return json.Marshal(p.Values)
}

600
internal/conf/path.go

@ -1,7 +1,6 @@
package conf package conf
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net" "net"
@ -11,14 +10,12 @@ import (
"strings" "strings"
"time" "time"
"github.com/bluenviron/gortsplib/v3/pkg/headers" "github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/url"
) )
var rePathName = regexp.MustCompile(`^[0-9a-zA-Z_\-/\.~]+$`) var rePathName = regexp.MustCompile(`^[0-9a-zA-Z_\-/\.~]+$`)
// IsValidPathName checks if a path name is valid. func isValidPathName(name string) error {
func IsValidPathName(name string) error {
if name == "" { if name == "" {
return fmt.Errorf("cannot be empty") return fmt.Errorf("cannot be empty")
} }
@ -38,128 +35,264 @@ func IsValidPathName(name string) error {
return nil return nil
} }
// PathConf is a path configuration. func srtCheckPassphrase(passphrase string) error {
type PathConf struct { switch {
Regexp *regexp.Regexp `json:"-"` case len(passphrase) < 10 || len(passphrase) > 79:
return fmt.Errorf("must be between 10 and 79 characters")
default:
return nil
}
}
// 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
}
}
}
// source return "", nil, nil, fmt.Errorf("path '%s' is not configured", name)
Source string `json:"source"` }
// Path is a path configuration.
type Path struct {
Regexp *regexp.Regexp `json:"-"` // filled by Check()
Name string `json:"name"` // filled by Check()
// general // General
Source string `json:"source"`
SourceFingerprint string `json:"sourceFingerprint"` SourceFingerprint string `json:"sourceFingerprint"`
SourceOnDemand bool `json:"sourceOnDemand"` SourceOnDemand bool `json:"sourceOnDemand"`
SourceOnDemandStartTimeout StringDuration `json:"sourceOnDemandStartTimeout"` SourceOnDemandStartTimeout StringDuration `json:"sourceOnDemandStartTimeout"`
SourceOnDemandCloseAfter StringDuration `json:"sourceOnDemandCloseAfter"` SourceOnDemandCloseAfter StringDuration `json:"sourceOnDemandCloseAfter"`
MaxReaders int `json:"maxReaders"` MaxReaders int `json:"maxReaders"`
SRTReadPassphrase string `json:"srtReadPassphrase"`
Fallback string `json:"fallback"`
// Record and playback
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
// Publisher source
OverridePublisher bool `json:"overridePublisher"`
DisablePublisherOverride *bool `json:"disablePublisherOverride,omitempty"` // deprecated
SRTPublishPassphrase string `json:"srtPublishPassphrase"`
// RTSP source
RTSPTransport RTSPTransport `json:"rtspTransport"`
RTSPAnyPort bool `json:"rtspAnyPort"`
SourceProtocol *RTSPTransport `json:"sourceProtocol,omitempty"` // deprecated
SourceAnyPortEnable *bool `json:"sourceAnyPortEnable,omitempty"` // deprecated
RTSPRangeType RTSPRangeType `json:"rtspRangeType"`
RTSPRangeStart string `json:"rtspRangeStart"`
// Redirect source
SourceRedirect string `json:"sourceRedirect"`
// authentication // Raspberry Pi Camera source
PublishUser Credential `json:"publishUser"` RPICameraCamID int `json:"rpiCameraCamID"`
PublishPass Credential `json:"publishPass"` RPICameraWidth int `json:"rpiCameraWidth"`
PublishIPs IPsOrCIDRs `json:"publishIPs"` RPICameraHeight int `json:"rpiCameraHeight"`
ReadUser Credential `json:"readUser"` RPICameraHFlip bool `json:"rpiCameraHFlip"`
ReadPass Credential `json:"readPass"` RPICameraVFlip bool `json:"rpiCameraVFlip"`
ReadIPs IPsOrCIDRs `json:"readIPs"` 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"`
// Hooks
RunOnInit string `json:"runOnInit"`
RunOnInitRestart bool `json:"runOnInitRestart"`
RunOnDemand string `json:"runOnDemand"`
RunOnDemandRestart bool `json:"runOnDemandRestart"`
RunOnDemandStartTimeout StringDuration `json:"runOnDemandStartTimeout"`
RunOnDemandCloseAfter StringDuration `json:"runOnDemandCloseAfter"`
RunOnUnDemand string `json:"runOnUnDemand"`
RunOnReady string `json:"runOnReady"`
RunOnReadyRestart bool `json:"runOnReadyRestart"`
RunOnNotReady string `json:"runOnNotReady"`
RunOnRead string `json:"runOnRead"`
RunOnReadRestart bool `json:"runOnReadRestart"`
RunOnUnread string `json:"runOnUnread"`
RunOnRecordSegmentCreate string `json:"runOnRecordSegmentCreate"`
RunOnRecordSegmentComplete string `json:"runOnRecordSegmentComplete"`
}
// publisher func (pconf *Path) setDefaults() {
OverridePublisher bool `json:"overridePublisher"` // General
DisablePublisherOverride bool `json:"disablePublisherOverride"` // deprecated pconf.Source = "publisher"
Fallback string `json:"fallback"` pconf.SourceOnDemandStartTimeout = 10 * StringDuration(time.Second)
pconf.SourceOnDemandCloseAfter = 10 * StringDuration(time.Second)
// rtsp // Record and playback
SourceProtocol SourceProtocol `json:"sourceProtocol"` pconf.Playback = true
SourceAnyPortEnable bool `json:"sourceAnyPortEnable"` pconf.RecordPath = "./recordings/%path/%Y-%m-%d_%H-%M-%S-%f"
RtspRangeType RtspRangeType `json:"rtspRangeType"` pconf.RecordFormat = RecordFormatFMP4
RtspRangeStart string `json:"rtspRangeStart"` pconf.RecordPartDuration = 100 * StringDuration(time.Millisecond)
pconf.RecordSegmentDuration = 3600 * StringDuration(time.Second)
pconf.RecordDeleteAfter = 24 * 3600 * StringDuration(time.Second)
// redirect // Publisher source
SourceRedirect string `json:"sourceRedirect"` pconf.OverridePublisher = true
// Raspberry Pi Camera source
pconf.RPICameraWidth = 1920
pconf.RPICameraHeight = 1080
pconf.RPICameraContrast = 1
pconf.RPICameraSaturation = 1
pconf.RPICameraSharpness = 1
pconf.RPICameraExposure = "normal"
pconf.RPICameraAWB = "auto"
pconf.RPICameraAWBGains = []float64{0, 0}
pconf.RPICameraDenoise = "off"
pconf.RPICameraMetering = "centre"
pconf.RPICameraFPS = 30
pconf.RPICameraIDRPeriod = 60
pconf.RPICameraBitrate = 1000000
pconf.RPICameraProfile = "main"
pconf.RPICameraLevel = "4.1"
pconf.RPICameraAfMode = "continuous"
pconf.RPICameraAfRange = "normal"
pconf.RPICameraAfSpeed = "normal"
pconf.RPICameraTextOverlay = "%Y-%m-%d %H:%M:%S - MediaMTX"
// Hooks
pconf.RunOnDemandStartTimeout = 10 * StringDuration(time.Second)
pconf.RunOnDemandCloseAfter = 10 * StringDuration(time.Second)
}
func newPath(defaults *Path, partial *OptionalPath) *Path {
pconf := &Path{}
copyStructFields(pconf, defaults)
copyStructFields(pconf, partial.Values)
return pconf
}
// raspberry pi camera // Clone clones the configuration.
RPICameraCamID int `json:"rpiCameraCamID"` func (pconf Path) Clone() *Path {
RPICameraWidth int `json:"rpiCameraWidth"` enc, err := json.Marshal(pconf)
RPICameraHeight int `json:"rpiCameraHeight"` if err != nil {
RPICameraHFlip bool `json:"rpiCameraHFlip"` panic(err)
RPICameraVFlip bool `json:"rpiCameraVFlip"` }
RPICameraBrightness float64 `json:"rpiCameraBrightness"`
RPICameraContrast float64 `json:"rpiCameraContrast"` var dest Path
RPICameraSaturation float64 `json:"rpiCameraSaturation"` err = json.Unmarshal(enc, &dest)
RPICameraSharpness float64 `json:"rpiCameraSharpness"` if err != nil {
RPICameraExposure string `json:"rpiCameraExposure"` panic(err)
RPICameraAWB string `json:"rpiCameraAWB"` }
RPICameraDenoise string `json:"rpiCameraDenoise"`
RPICameraShutter int `json:"rpiCameraShutter"` dest.Regexp = pconf.Regexp
RPICameraMetering string `json:"rpiCameraMetering"`
RPICameraGain float64 `json:"rpiCameraGain"` return &dest
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"`
// external commands
RunOnInit string `json:"runOnInit"`
RunOnInitRestart bool `json:"runOnInitRestart"`
RunOnDemand string `json:"runOnDemand"`
RunOnDemandRestart bool `json:"runOnDemandRestart"`
RunOnDemandStartTimeout StringDuration `json:"runOnDemandStartTimeout"`
RunOnDemandCloseAfter StringDuration `json:"runOnDemandCloseAfter"`
RunOnReady string `json:"runOnReady"`
RunOnReadyRestart bool `json:"runOnReadyRestart"`
RunOnRead string `json:"runOnRead"`
RunOnReadRestart bool `json:"runOnReadRestart"`
} }
func (pconf *PathConf) check(conf *Conf, name string) error { func (pconf *Path) validate(
conf *Conf,
name string,
deprecatedCredentialsMode bool,
) error {
pconf.Name = name
switch { switch {
case name == "all": case name == "all_others", name == "all":
pconf.Regexp = regexp.MustCompile("^.*$") pconf.Regexp = regexp.MustCompile("^.*$")
case name == "" || name[0] != '~': // normal path case name == "" || name[0] != '~': // normal path
err := IsValidPathName(name) err := isValidPathName(name)
if err != nil { if err != nil {
return fmt.Errorf("invalid path name '%s': %s", name, err) return fmt.Errorf("invalid path name '%s': %w", name, err)
} }
default: // regular expression-based path default: // regular expression-based path
pathRegexp, err := regexp.Compile(name[1:]) regexp, err := regexp.Compile(name[1:])
if err != nil { if err != nil {
return fmt.Errorf("invalid regular expression: %s", name[1:]) return fmt.Errorf("invalid regular expression: %s", name[1:])
} }
pconf.Regexp = pathRegexp pconf.Regexp = regexp
} }
// General
if pconf.Source != "publisher" && pconf.Source != "redirect" &&
pconf.Regexp != nil && !pconf.SourceOnDemand {
return fmt.Errorf("a path with a regular expression (or path 'all') and a static source" +
" must have 'sourceOnDemand' set to true")
}
switch { switch {
case pconf.Source == "publisher": case pconf.Source == "publisher":
case strings.HasPrefix(pconf.Source, "rtsp://") || case strings.HasPrefix(pconf.Source, "rtsp://") ||
strings.HasPrefix(pconf.Source, "rtsps://"): strings.HasPrefix(pconf.Source, "rtsps://"):
if pconf.Regexp != nil { _, err := base.ParseURL(pconf.Source)
return fmt.Errorf("a path with a regular expression (or path 'all') cannot have a RTSP source. use another path")
}
_, err := url.Parse(pconf.Source)
if err != nil { if err != nil {
return fmt.Errorf("'%s' is not a valid URL", pconf.Source) return fmt.Errorf("'%s' is not a valid URL", pconf.Source)
} }
case strings.HasPrefix(pconf.Source, "rtmp://") || case strings.HasPrefix(pconf.Source, "rtmp://") ||
strings.HasPrefix(pconf.Source, "rtmps://"): strings.HasPrefix(pconf.Source, "rtmps://"):
if pconf.Regexp != nil {
return fmt.Errorf("a path with a regular expression (or path 'all') cannot have a RTMP source. use another path")
}
u, err := gourl.Parse(pconf.Source) u, err := gourl.Parse(pconf.Source)
if err != nil { if err != nil {
return fmt.Errorf("'%s' is not a valid URL", pconf.Source) return fmt.Errorf("'%s' is not a valid URL", pconf.Source)
@ -176,10 +309,6 @@ func (pconf *PathConf) check(conf *Conf, name string) error {
case strings.HasPrefix(pconf.Source, "http://") || case strings.HasPrefix(pconf.Source, "http://") ||
strings.HasPrefix(pconf.Source, "https://"): strings.HasPrefix(pconf.Source, "https://"):
if pconf.Regexp != nil {
return fmt.Errorf("a path with a regular expression (or path 'all') cannot have a HLS source. use another path")
}
u, err := gourl.Parse(pconf.Source) u, err := gourl.Parse(pconf.Source)
if err != nil { if err != nil {
return fmt.Errorf("'%s' is not a valid URL", pconf.Source) return fmt.Errorf("'%s' is not a valid URL", pconf.Source)
@ -198,19 +327,12 @@ func (pconf *PathConf) check(conf *Conf, name string) error {
} }
case strings.HasPrefix(pconf.Source, "udp://"): case strings.HasPrefix(pconf.Source, "udp://"):
if pconf.Regexp != nil {
return fmt.Errorf("a path with a regular expression (or path 'all') cannot have a HLS source. use another path")
}
_, _, err := net.SplitHostPort(pconf.Source[len("udp://"):]) _, _, err := net.SplitHostPort(pconf.Source[len("udp://"):])
if err != nil { if err != nil {
return fmt.Errorf("'%s' is not a valid UDP URL", pconf.Source) return fmt.Errorf("'%s' is not a valid UDP URL", pconf.Source)
} }
case strings.HasPrefix(pconf.Source, "srt://"): case strings.HasPrefix(pconf.Source, "srt://"):
if pconf.Regexp != nil {
return fmt.Errorf("a path with a regular expression (or path 'all') cannot have a SRT source. use another path")
}
_, err := gourl.Parse(pconf.Source) _, err := gourl.Parse(pconf.Source)
if err != nil { if err != nil {
@ -219,140 +341,219 @@ func (pconf *PathConf) check(conf *Conf, name string) error {
case strings.HasPrefix(pconf.Source, "whep://") || case strings.HasPrefix(pconf.Source, "whep://") ||
strings.HasPrefix(pconf.Source, "wheps://"): strings.HasPrefix(pconf.Source, "wheps://"):
if pconf.Regexp != nil {
return fmt.Errorf("a path with a regular expression (or path 'all') " +
"cannot have a WebRTC/WHEP source. use another path")
}
_, err := gourl.Parse(pconf.Source) _, err := gourl.Parse(pconf.Source)
if err != nil { if err != nil {
return fmt.Errorf("'%s' is not a valid URL", pconf.Source) return fmt.Errorf("'%s' is not a valid URL", pconf.Source)
} }
case pconf.Source == "redirect": case pconf.Source == "redirect":
if pconf.SourceRedirect == "" {
return fmt.Errorf("source redirect must be filled")
}
_, err := url.Parse(pconf.SourceRedirect)
if err != nil {
return fmt.Errorf("'%s' is not a valid RTSP URL", pconf.SourceRedirect)
}
case pconf.Source == "rpiCamera": case pconf.Source == "rpiCamera":
if pconf.Regexp != nil {
return fmt.Errorf(
"a path with a regular expression (or path 'all') cannot have 'rpiCamera' as source. use another path")
}
for otherName, otherPath := range conf.Paths {
if otherPath != pconf && otherPath != nil &&
otherPath.Source == "rpiCamera" && otherPath.RPICameraCamID == pconf.RPICameraCamID {
return fmt.Errorf("'rpiCamera' with same camera ID %d is used as source in two paths, '%s' and '%s'",
pconf.RPICameraCamID, name, otherName)
}
}
default: default:
return fmt.Errorf("invalid source: '%s'", pconf.Source) return fmt.Errorf("invalid source: '%s'", pconf.Source)
} }
if pconf.SourceOnDemand { if pconf.SourceOnDemand {
if pconf.Source == "publisher" { if pconf.Source == "publisher" {
return fmt.Errorf("'sourceOnDemand' is useless when source is 'publisher'") return fmt.Errorf("'sourceOnDemand' is useless when source is 'publisher'")
} }
} }
if pconf.SRTReadPassphrase != "" {
if pconf.DisablePublisherOverride { err := srtCheckPassphrase(pconf.SRTReadPassphrase)
pconf.OverridePublisher = true if err != nil {
return fmt.Errorf("invalid 'readRTPassphrase': %w", err)
}
} }
if pconf.Fallback != "" { if pconf.Fallback != "" {
if strings.HasPrefix(pconf.Fallback, "/") { if strings.HasPrefix(pconf.Fallback, "/") {
err := IsValidPathName(pconf.Fallback[1:]) err := isValidPathName(pconf.Fallback[1:])
if err != nil { if err != nil {
return fmt.Errorf("'%s': %s", pconf.Fallback, err) return fmt.Errorf("'%s': %w", pconf.Fallback, err)
} }
} else { } else {
_, err := url.Parse(pconf.Fallback) _, err := base.ParseURL(pconf.Fallback)
if err != nil { if err != nil {
return fmt.Errorf("'%s' is not a valid RTSP URL", pconf.Fallback) return fmt.Errorf("'%s' is not a valid RTSP URL", pconf.Fallback)
} }
} }
} }
if (pconf.PublishUser != "" && pconf.PublishPass == "") || // Authentication (deprecated)
(pconf.PublishUser == "" && pconf.PublishPass != "") {
return fmt.Errorf("read username and password must be both filled") 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 != "" && pconf.Source != "publisher" { // Publisher source
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 pconf.DisablePublisherOverride != nil {
pconf.OverridePublisher = !*pconf.DisablePublisherOverride
} }
if pconf.SRTPublishPassphrase != "" {
if pconf.Source != "publisher" {
return fmt.Errorf("'srtPublishPassphase' can only be used when source is 'publisher'")
}
if len(pconf.PublishIPs) > 0 && pconf.Source != "publisher" { err := srtCheckPassphrase(pconf.SRTPublishPassphrase)
return fmt.Errorf("'publishIPs' is useless when source is not 'publisher', since " + if err != nil {
"the stream is not provided by a publisher, but by a fixed source") return fmt.Errorf("invalid 'srtPublishPassphrase': %w", err)
}
} }
if (pconf.ReadUser != "" && pconf.ReadPass == "") || // RTSP source
(pconf.ReadUser == "" && pconf.ReadPass != "") {
return fmt.Errorf("read username and password must be both filled") if pconf.SourceProtocol != nil {
pconf.RTSPTransport = *pconf.SourceProtocol
}
if pconf.SourceAnyPortEnable != nil {
pconf.RTSPAnyPort = *pconf.SourceAnyPortEnable
} }
if contains(conf.AuthMethods, headers.AuthDigest) { // Redirect source
if strings.HasPrefix(string(pconf.PublishUser), "sha256:") ||
strings.HasPrefix(string(pconf.PublishPass), "sha256:") || if pconf.Source == "redirect" {
strings.HasPrefix(string(pconf.ReadUser), "sha256:") || if pconf.SourceRedirect == "" {
strings.HasPrefix(string(pconf.ReadPass), "sha256:") { return fmt.Errorf("source redirect must be filled")
return fmt.Errorf("hashed credentials can't be used when the digest auth method is available") }
_, err := base.ParseURL(pconf.SourceRedirect)
if err != nil {
return fmt.Errorf("'%s' is not a valid RTSP URL", pconf.SourceRedirect)
} }
} }
if conf.ExternalAuthenticationURL != "" { // Raspberry Pi Camera source
if pconf.PublishUser != "" ||
len(pconf.PublishIPs) > 0 || if pconf.Source == "rpiCamera" {
pconf.ReadUser != "" || for otherName, otherPath := range conf.Paths {
len(pconf.ReadIPs) > 0 { if otherPath != pconf && otherPath != nil &&
return fmt.Errorf("credentials or IPs can't be used together with 'externalAuthenticationURL'") otherPath.Source == "rpiCamera" && otherPath.RPICameraCamID == pconf.RPICameraCamID {
return fmt.Errorf("'rpiCamera' with same camera ID %d is used as source in two paths, '%s' and '%s'",
pconf.RPICameraCamID, name, otherName)
}
} }
} }
switch pconf.RPICameraExposure {
case "normal", "short", "long", "custom":
default:
return fmt.Errorf("invalid 'rpiCameraExposure' value")
}
switch pconf.RPICameraAWB {
case "auto", "incandescent", "tungsten", "fluorescent", "indoor", "daylight", "cloudy", "custom":
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:
return fmt.Errorf("invalid 'rpiCameraDenoise' value")
}
switch pconf.RPICameraMetering {
case "centre", "spot", "matrix", "custom":
default:
return fmt.Errorf("invalid 'rpiCameraMetering' value")
}
switch pconf.RPICameraAfMode {
case "auto", "manual", "continuous":
default:
return fmt.Errorf("invalid 'rpiCameraAfMode' value")
}
switch pconf.RPICameraAfRange {
case "normal", "macro", "full":
default:
return fmt.Errorf("invalid 'rpiCameraAfRange' value")
}
switch pconf.RPICameraAfSpeed {
case "normal", "fast":
default:
return fmt.Errorf("invalid 'rpiCameraAfSpeed' value")
}
// Hooks
if pconf.RunOnInit != "" && pconf.Regexp != nil { if pconf.RunOnInit != "" && pconf.Regexp != nil {
return fmt.Errorf("a path with a regular expression does not support option 'runOnInit'; use another path") return fmt.Errorf("a path with a regular expression (or path 'all')" +
" does not support option 'runOnInit'; use another path")
} }
if (pconf.RunOnDemand != "" || pconf.RunOnUnDemand != "") && pconf.Source != "publisher" {
if pconf.RunOnDemand != "" && pconf.Source != "publisher" { return fmt.Errorf("'runOnDemand' and 'runOnUnDemand' can be used only when source is 'publisher'")
return fmt.Errorf("'runOnDemand' can be used only when source is 'publisher'")
} }
return nil return nil
} }
// Equal checks whether two PathConfs are equal. // Equal checks whether two Paths are equal.
func (pconf *PathConf) Equal(other *PathConf) bool { func (pconf *Path) Equal(other *Path) bool {
return reflect.DeepEqual(pconf, other) return reflect.DeepEqual(pconf, other)
} }
// Clone clones the configuration.
func (pconf PathConf) Clone() *PathConf {
enc, err := json.Marshal(pconf)
if err != nil {
panic(err)
}
var dest PathConf
err = json.Unmarshal(enc, &dest)
if err != nil {
panic(err)
}
return &dest
}
// HasStaticSource checks whether the path has a static source. // HasStaticSource checks whether the path has a static source.
func (pconf PathConf) HasStaticSource() bool { func (pconf Path) HasStaticSource() bool {
return strings.HasPrefix(pconf.Source, "rtsp://") || return strings.HasPrefix(pconf.Source, "rtsp://") ||
strings.HasPrefix(pconf.Source, "rtsps://") || strings.HasPrefix(pconf.Source, "rtsps://") ||
strings.HasPrefix(pconf.Source, "rtmp://") || strings.HasPrefix(pconf.Source, "rtmp://") ||
@ -367,46 +568,11 @@ func (pconf PathConf) HasStaticSource() bool {
} }
// HasOnDemandStaticSource checks whether the path has a on demand static source. // HasOnDemandStaticSource checks whether the path has a on demand static source.
func (pconf PathConf) HasOnDemandStaticSource() bool { func (pconf Path) HasOnDemandStaticSource() bool {
return pconf.HasStaticSource() && pconf.SourceOnDemand return pconf.HasStaticSource() && pconf.SourceOnDemand
} }
// HasOnDemandPublisher checks whether the path has a on-demand publisher. // HasOnDemandPublisher checks whether the path has a on-demand publisher.
func (pconf PathConf) HasOnDemandPublisher() bool { func (pconf Path) HasOnDemandPublisher() bool {
return pconf.RunOnDemand != "" return pconf.RunOnDemand != ""
} }
// UnmarshalJSON implements json.Unmarshaler. It is used to set default values.
func (pconf *PathConf) UnmarshalJSON(b []byte) error {
// source
pconf.Source = "publisher"
// general
pconf.SourceOnDemandStartTimeout = 10 * StringDuration(time.Second)
pconf.SourceOnDemandCloseAfter = 10 * StringDuration(time.Second)
// publisher
pconf.OverridePublisher = true
// raspberry pi camera
pconf.RPICameraWidth = 1920
pconf.RPICameraHeight = 1080
pconf.RPICameraContrast = 1
pconf.RPICameraSaturation = 1
pconf.RPICameraSharpness = 1
pconf.RPICameraFPS = 30
pconf.RPICameraIDRPeriod = 60
pconf.RPICameraBitrate = 1000000
pconf.RPICameraProfile = "main"
pconf.RPICameraLevel = "4.1"
pconf.RPICameraTextOverlay = "%Y-%m-%d %H:%M:%S - MediaMTX"
// external commands
pconf.RunOnDemandStartTimeout = 10 * StringDuration(time.Second)
pconf.RunOnDemandCloseAfter = 10 * StringDuration(time.Second)
type alias PathConf
d := json.NewDecoder(bytes.NewReader(b))
d.DisallowUnknownFields()
return d.Decode((*alias)(pconf))
}

13
internal/conf/protocol.go

@ -6,7 +6,7 @@ import (
"sort" "sort"
"strings" "strings"
"github.com/bluenviron/gortsplib/v3" "github.com/bluenviron/gortsplib/v4"
) )
// Protocol is a RTSP transport. // Protocol is a RTSP transport.
@ -30,11 +30,8 @@ func (d Protocols) MarshalJSON() ([]byte, error) {
case Protocol(gortsplib.TransportUDPMulticast): case Protocol(gortsplib.TransportUDPMulticast):
v = "multicast" v = "multicast"
case Protocol(gortsplib.TransportTCP):
v = "tcp"
default: default:
return nil, fmt.Errorf("invalid protocol: %v", p) v = "tcp"
} }
out[i] = v out[i] = v
@ -74,8 +71,8 @@ func (d *Protocols) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *Protocols) UnmarshalEnv(s string) error { func (d *Protocols) UnmarshalEnv(_ string, v string) error {
byts, _ := json.Marshal(strings.Split(s, ",")) byts, _ := json.Marshal(strings.Split(v, ","))
return d.UnmarshalJSON(byts) return d.UnmarshalJSON(byts)
} }

56
internal/conf/record_format.go

@ -0,0 +1,56 @@
package conf
import (
"encoding/json"
"fmt"
)
// RecordFormat is the recordFormat parameter.
type RecordFormat int
// supported values.
const (
RecordFormatFMP4 RecordFormat = iota
RecordFormatMPEGTS
)
// MarshalJSON implements json.Marshaler.
func (d RecordFormat) MarshalJSON() ([]byte, error) {
var out string
switch d {
case RecordFormatMPEGTS:
out = "mpegts"
default:
out = "fmp4"
}
return json.Marshal(out)
}
// UnmarshalJSON implements json.Unmarshaler.
func (d *RecordFormat) UnmarshalJSON(b []byte) error {
var in string
if err := json.Unmarshal(b, &in); err != nil {
return err
}
switch in {
case "mpegts":
*d = RecordFormatMPEGTS
case "fmp4":
*d = RecordFormatFMP4
default:
return fmt.Errorf("invalid record format '%s'", in)
}
return nil
}
// UnmarshalEnv implements env.Unmarshaler.
func (d *RecordFormat) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + v + `"`))
}

63
internal/conf/rtsp_auth_methods.go

@ -0,0 +1,63 @@
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)
}

43
internal/conf/rtsp_range_type.go

@ -5,43 +5,40 @@ import (
"fmt" "fmt"
) )
// RtspRangeType is the type used in the Range header. // RTSPRangeType is the type used in the Range header.
type RtspRangeType int type RTSPRangeType int
// supported rtsp range types. // supported values.
const ( const (
RtspRangeTypeUndefined RtspRangeType = iota RTSPRangeTypeUndefined RTSPRangeType = iota
RtspRangeTypeClock RTSPRangeTypeClock
RtspRangeTypeNPT RTSPRangeTypeNPT
RtspRangeTypeSMPTE RTSPRangeTypeSMPTE
) )
// MarshalJSON implements json.Marshaler. // MarshalJSON implements json.Marshaler.
func (d RtspRangeType) MarshalJSON() ([]byte, error) { func (d RTSPRangeType) MarshalJSON() ([]byte, error) {
var out string var out string
switch d { switch d {
case RtspRangeTypeClock: case RTSPRangeTypeClock:
out = "clock" out = "clock"
case RtspRangeTypeNPT: case RTSPRangeTypeNPT:
out = "npt" out = "npt"
case RtspRangeTypeSMPTE: case RTSPRangeTypeSMPTE:
out = "smpte" out = "smpte"
case RtspRangeTypeUndefined:
out = ""
default: default:
return nil, fmt.Errorf("invalid rtsp range type: %v", d) out = ""
} }
return json.Marshal(out) return json.Marshal(out)
} }
// UnmarshalJSON implements json.Unmarshaler. // UnmarshalJSON implements json.Unmarshaler.
func (d *RtspRangeType) UnmarshalJSON(b []byte) error { func (d *RTSPRangeType) UnmarshalJSON(b []byte) error {
var in string var in string
if err := json.Unmarshal(b, &in); err != nil { if err := json.Unmarshal(b, &in); err != nil {
return err return err
@ -49,16 +46,16 @@ func (d *RtspRangeType) UnmarshalJSON(b []byte) error {
switch in { switch in {
case "clock": case "clock":
*d = RtspRangeTypeClock *d = RTSPRangeTypeClock
case "npt": case "npt":
*d = RtspRangeTypeNPT *d = RTSPRangeTypeNPT
case "smpte": case "smpte":
*d = RtspRangeTypeSMPTE *d = RTSPRangeTypeSMPTE
case "": case "":
*d = RtspRangeTypeUndefined *d = RTSPRangeTypeUndefined
default: default:
return fmt.Errorf("invalid rtsp range type: '%s'", in) return fmt.Errorf("invalid rtsp range type: '%s'", in)
@ -67,7 +64,7 @@ func (d *RtspRangeType) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *RtspRangeType) UnmarshalEnv(s string) error { func (d *RTSPRangeType) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + s + `"`)) return d.UnmarshalJSON([]byte(`"` + v + `"`))
} }

21
internal/conf/source_protocol.go → internal/conf/rtsp_transport.go

@ -4,16 +4,16 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/bluenviron/gortsplib/v3" "github.com/bluenviron/gortsplib/v4"
) )
// SourceProtocol is the sourceProtocol parameter. // RTSPTransport is the rtspTransport parameter.
type SourceProtocol struct { type RTSPTransport struct {
*gortsplib.Transport *gortsplib.Transport
} }
// MarshalJSON implements json.Marshaler. // MarshalJSON implements json.Marshaler.
func (d SourceProtocol) MarshalJSON() ([]byte, error) { func (d RTSPTransport) MarshalJSON() ([]byte, error) {
var out string var out string
if d.Transport == nil { if d.Transport == nil {
@ -26,11 +26,8 @@ func (d SourceProtocol) MarshalJSON() ([]byte, error) {
case gortsplib.TransportUDPMulticast: case gortsplib.TransportUDPMulticast:
out = "multicast" out = "multicast"
case gortsplib.TransportTCP:
out = "tcp"
default: default:
return nil, fmt.Errorf("invalid protocol: %v", d.Transport) out = "tcp"
} }
} }
@ -38,7 +35,7 @@ func (d SourceProtocol) MarshalJSON() ([]byte, error) {
} }
// UnmarshalJSON implements json.Unmarshaler. // UnmarshalJSON implements json.Unmarshaler.
func (d *SourceProtocol) UnmarshalJSON(b []byte) error { func (d *RTSPTransport) UnmarshalJSON(b []byte) error {
var in string var in string
if err := json.Unmarshal(b, &in); err != nil { if err := json.Unmarshal(b, &in); err != nil {
return err return err
@ -67,7 +64,7 @@ func (d *SourceProtocol) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *SourceProtocol) UnmarshalEnv(s string) error { func (d *RTSPTransport) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + s + `"`)) return d.UnmarshalJSON([]byte(`"` + v + `"`))
} }

6
internal/conf/string_duration.go

@ -30,7 +30,7 @@ func (d *StringDuration) UnmarshalJSON(b []byte) error {
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (d *StringDuration) UnmarshalEnv(s string) error { func (d *StringDuration) UnmarshalEnv(_ string, v string) error {
return d.UnmarshalJSON([]byte(`"` + s + `"`)) return d.UnmarshalJSON([]byte(`"` + v + `"`))
} }

6
internal/conf/string_size.go

@ -25,12 +25,12 @@ func (s *StringSize) UnmarshalJSON(b []byte) error {
if err != nil { if err != nil {
return err return err
} }
*s = StringSize(v) *s = StringSize(v)
return nil return nil
} }
// UnmarshalEnv implements envUnmarshaler. // UnmarshalEnv implements env.Unmarshaler.
func (s *StringSize) UnmarshalEnv(v string) error { func (s *StringSize) UnmarshalEnv(_ string, v string) error {
return s.UnmarshalJSON([]byte(`"` + v + `"`)) return s.UnmarshalJSON([]byte(`"` + v + `"`))
} }

7
internal/conf/webrtc_ice_server.go

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

14
internal/confwatcher/confwatcher.go

@ -30,14 +30,7 @@ type ConfWatcher struct {
// New allocates a ConfWatcher. // New allocates a ConfWatcher.
func New(confPath string) (*ConfWatcher, error) { func New(confPath string) (*ConfWatcher, error) {
if _, err := os.Stat(confPath); err != nil { if _, err := os.Stat(confPath); err != nil {
if confPath == "mediamtx.yml" { return nil, err
confPath = "rtsp-simple-server.yml"
if _, err := os.Stat(confPath); err != nil {
return nil, err
}
} else {
return nil, err
}
} }
inner, err := fsnotify.NewWatcher() inner, err := fsnotify.NewWatcher()
@ -51,7 +44,7 @@ func New(confPath string) (*ConfWatcher, error) {
err = inner.Add(parentPath) err = inner.Add(parentPath)
if err != nil { if err != nil {
inner.Close() inner.Close() //nolint:errcheck
return nil, err return nil, err
} }
@ -90,6 +83,7 @@ outer:
currentWatchedPath, _ := filepath.EvalSymlinks(w.watchedPath) currentWatchedPath, _ := filepath.EvalSymlinks(w.watchedPath)
eventPath, _ := filepath.Abs(event.Name) eventPath, _ := filepath.Abs(event.Name)
eventPath, _ = filepath.EvalSymlinks(eventPath)
if currentWatchedPath == "" { if currentWatchedPath == "" {
// watched file was removed; wait for write event to trigger reload // watched file was removed; wait for write event to trigger reload
@ -120,7 +114,7 @@ outer:
} }
close(w.signal) close(w.signal)
w.inner.Close() w.inner.Close() //nolint:errcheck
} }
// Watch returns a channel that is called after the configuration file has changed. // Watch returns a channel that is called after the configuration file has changed.

24
internal/confwatcher/confwatcher_test.go

@ -5,31 +5,17 @@ import (
"testing" "testing"
"time" "time"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require" "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) { func TestNoFile(t *testing.T) {
_, err := New("/nonexistent") _, err := New("/nonexistent")
require.Error(t, err) require.Error(t, err)
} }
func TestWrite(t *testing.T) { func TestWrite(t *testing.T) {
fpath, err := writeTempFile([]byte("{}")) fpath, err := test.CreateTempFile([]byte("{}"))
require.NoError(t, err) require.NoError(t, err)
w, err := New(fpath) w, err := New(fpath)
@ -54,7 +40,7 @@ func TestWrite(t *testing.T) {
} }
func TestWriteMultipleTimes(t *testing.T) { func TestWriteMultipleTimes(t *testing.T) {
fpath, err := writeTempFile([]byte("{}")) fpath, err := test.CreateTempFile([]byte("{}"))
require.NoError(t, err) require.NoError(t, err)
w, err := New(fpath) w, err := New(fpath)
@ -97,7 +83,7 @@ func TestWriteMultipleTimes(t *testing.T) {
} }
func TestDeleteCreate(t *testing.T) { func TestDeleteCreate(t *testing.T) {
fpath, err := writeTempFile([]byte("{}")) fpath, err := test.CreateTempFile([]byte("{}"))
require.NoError(t, err) require.NoError(t, err)
w, err := New(fpath) w, err := New(fpath)
@ -125,7 +111,7 @@ func TestDeleteCreate(t *testing.T) {
} }
func TestSymlinkDeleteCreate(t *testing.T) { func TestSymlinkDeleteCreate(t *testing.T) {
fpath, err := writeTempFile([]byte("{}")) fpath, err := test.CreateTempFile([]byte("{}"))
require.NoError(t, err) require.NoError(t, err)
err = os.Symlink(fpath, fpath+"-sym") err = os.Symlink(fpath, fpath+"-sym")

926
internal/core/api.go

@ -1,926 +0,0 @@
package core
import (
"encoding/json"
"errors"
"net/http"
"reflect"
"strconv"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/httpserv"
"github.com/bluenviron/mediamtx/internal/logger"
)
var errAPINotFound = errors.New("not found")
func interfaceIsEmpty(i interface{}) bool {
return reflect.ValueOf(i).Kind() != reflect.Ptr || reflect.ValueOf(i).IsNil()
}
func fillStruct(dest interface{}, source interface{}) {
rvsource := reflect.ValueOf(source).Elem()
rvdest := reflect.ValueOf(dest)
nf := rvsource.NumField()
for i := 0; i < nf; i++ {
fnew := rvsource.Field(i)
if !fnew.IsNil() {
f := rvdest.Elem().FieldByName(rvsource.Type().Field(i).Name)
if f.Kind() == reflect.Ptr {
f.Set(fnew)
} else {
f.Set(fnew.Elem())
}
}
}
}
func generateStructWithOptionalFields(model interface{}) interface{} {
var fields []reflect.StructField
rt := reflect.TypeOf(model)
nf := rt.NumField()
for i := 0; i < nf; i++ {
f := rt.Field(i)
j := f.Tag.Get("json")
if j != "-" && j != "paths" {
fields = append(fields, reflect.StructField{
Name: f.Name,
Type: reflect.PtrTo(f.Type),
Tag: f.Tag,
})
}
}
return reflect.New(reflect.StructOf(fields)).Interface()
}
func loadConfData(ctx *gin.Context) (interface{}, error) {
in := generateStructWithOptionalFields(conf.Conf{})
err := json.NewDecoder(ctx.Request.Body).Decode(in)
if err != nil {
return nil, err
}
return in, err
}
func loadConfPathData(ctx *gin.Context) (interface{}, error) {
in := generateStructWithOptionalFields(conf.PathConf{})
err := json.NewDecoder(ctx.Request.Body).Decode(in)
if err != nil {
return nil, err
}
return in, err
}
func paginate2(itemsPtr interface{}, itemsPerPage int, page int) int {
ritems := reflect.ValueOf(itemsPtr).Elem()
itemsLen := ritems.Len()
if itemsLen == 0 {
return 0
}
pageCount := (itemsLen / itemsPerPage)
if (itemsLen % itemsPerPage) != 0 {
pageCount++
}
min := page * itemsPerPage
if min >= itemsLen {
min = itemsLen - 1
}
max := (page + 1) * itemsPerPage
if max >= itemsLen {
max = itemsLen
}
ritems.Set(ritems.Slice(min, max))
return pageCount
}
func paginate(itemsPtr interface{}, itemsPerPageStr string, pageStr string) (int, error) {
itemsPerPage := 100
if itemsPerPageStr != "" {
tmp, err := strconv.ParseUint(itemsPerPageStr, 10, 31)
if err != nil {
return 0, err
}
itemsPerPage = int(tmp)
}
page := 0
if pageStr != "" {
tmp, err := strconv.ParseUint(pageStr, 10, 31)
if err != nil {
return 0, err
}
page = int(tmp)
}
return paginate2(itemsPtr, itemsPerPage, page), nil
}
func abortWithError(ctx *gin.Context, err error) {
if err == errAPINotFound {
ctx.AbortWithStatus(http.StatusNotFound)
} else {
ctx.AbortWithStatus(http.StatusInternalServerError)
}
}
func paramName(ctx *gin.Context) (string, bool) {
name := ctx.Param("name")
if len(name) < 2 || name[0] != '/' {
return "", false
}
return name[1:], true
}
type apiPathManager interface {
apiPathsList() (*apiPathsList, error)
apiPathsGet(string) (*apiPath, error)
}
type apiHLSManager interface {
apiMuxersList() (*apiHLSMuxersList, error)
apiMuxersGet(string) (*apiHLSMuxer, error)
}
type apiRTSPServer interface {
apiConnsList() (*apiRTSPConnsList, error)
apiConnsGet(uuid.UUID) (*apiRTSPConn, error)
apiSessionsList() (*apiRTSPSessionsList, error)
apiSessionsGet(uuid.UUID) (*apiRTSPSession, error)
apiSessionsKick(uuid.UUID) error
}
type apiRTMPServer interface {
apiConnsList() (*apiRTMPConnsList, error)
apiConnsGet(uuid.UUID) (*apiRTMPConn, error)
apiConnsKick(uuid.UUID) error
}
type apiWebRTCManager interface {
apiSessionsList() (*apiWebRTCSessionsList, error)
apiSessionsGet(uuid.UUID) (*apiWebRTCSession, error)
apiSessionsKick(uuid.UUID) error
}
type apiSRTServer interface {
apiConnsList() (*apiSRTConnsList, error)
apiConnsGet(uuid.UUID) (*apiSRTConn, error)
apiConnsKick(uuid.UUID) error
}
type apiParent interface {
logger.Writer
apiConfigSet(conf *conf.Conf)
}
type api struct {
conf *conf.Conf
pathManager apiPathManager
rtspServer apiRTSPServer
rtspsServer apiRTSPServer
rtmpServer apiRTMPServer
rtmpsServer apiRTMPServer
hlsManager apiHLSManager
webRTCManager apiWebRTCManager
srtServer apiSRTServer
parent apiParent
httpServer *httpserv.WrappedServer
mutex sync.Mutex
}
func newAPI(
address string,
readTimeout conf.StringDuration,
conf *conf.Conf,
pathManager apiPathManager,
rtspServer apiRTSPServer,
rtspsServer apiRTSPServer,
rtmpServer apiRTMPServer,
rtmpsServer apiRTMPServer,
hlsManager apiHLSManager,
webRTCManager apiWebRTCManager,
srtServer apiSRTServer,
parent apiParent,
) (*api, error) {
a := &api{
conf: conf,
pathManager: pathManager,
rtspServer: rtspServer,
rtspsServer: rtspsServer,
rtmpServer: rtmpServer,
rtmpsServer: rtmpsServer,
hlsManager: hlsManager,
webRTCManager: webRTCManager,
srtServer: srtServer,
parent: parent,
}
router := gin.New()
router.SetTrustedProxies(nil)
group := router.Group("/")
group.GET("/v2/config/get", a.onConfigGet)
group.POST("/v2/config/set", a.onConfigSet)
group.POST("/v2/config/paths/add/*name", a.onConfigPathsAdd)
group.POST("/v2/config/paths/edit/*name", a.onConfigPathsEdit)
group.POST("/v2/config/paths/remove/*name", a.onConfigPathsDelete)
if !interfaceIsEmpty(a.hlsManager) {
group.GET("/v2/hlsmuxers/list", a.onHLSMuxersList)
group.GET("/v2/hlsmuxers/get/*name", a.onHLSMuxersGet)
}
group.GET("/v2/paths/list", a.onPathsList)
group.GET("/v2/paths/get/*name", a.onPathsGet)
if !interfaceIsEmpty(a.rtspServer) {
group.GET("/v2/rtspconns/list", a.onRTSPConnsList)
group.GET("/v2/rtspconns/get/:id", a.onRTSPConnsGet)
group.GET("/v2/rtspsessions/list", a.onRTSPSessionsList)
group.GET("/v2/rtspsessions/get/:id", a.onRTSPSessionsGet)
group.POST("/v2/rtspsessions/kick/:id", a.onRTSPSessionsKick)
}
if !interfaceIsEmpty(a.rtspsServer) {
group.GET("/v2/rtspsconns/list", a.onRTSPSConnsList)
group.GET("/v2/rtspsconns/get/:id", a.onRTSPSConnsGet)
group.GET("/v2/rtspssessions/list", a.onRTSPSSessionsList)
group.GET("/v2/rtspssessions/get/:id", a.onRTSPSSessionsGet)
group.POST("/v2/rtspssessions/kick/:id", a.onRTSPSSessionsKick)
}
if !interfaceIsEmpty(a.rtmpServer) {
group.GET("/v2/rtmpconns/list", a.onRTMPConnsList)
group.GET("/v2/rtmpconns/get/:id", a.onRTMPConnsGet)
group.POST("/v2/rtmpconns/kick/:id", a.onRTMPConnsKick)
}
if !interfaceIsEmpty(a.rtmpsServer) {
group.GET("/v2/rtmpsconns/list", a.onRTMPSConnsList)
group.GET("/v2/rtmpsconns/get/:id", a.onRTMPSConnsGet)
group.POST("/v2/rtmpsconns/kick/:id", a.onRTMPSConnsKick)
}
if !interfaceIsEmpty(a.webRTCManager) {
group.GET("/v2/webrtcsessions/list", a.onWebRTCSessionsList)
group.GET("/v2/webrtcsessions/get/:id", a.onWebRTCSessionsGet)
group.POST("/v2/webrtcsessions/kick/:id", a.onWebRTCSessionsKick)
}
if !interfaceIsEmpty(a.srtServer) {
group.GET("/v2/srtconns/list", a.onSRTConnsList)
group.GET("/v2/srtconns/get/:id", a.onSRTConnsGet)
group.POST("/v2/srtconns/kick/:id", a.onSRTConnsKick)
}
network, address := restrictNetwork("tcp", address)
var err error
a.httpServer, err = httpserv.NewWrappedServer(
network,
address,
time.Duration(readTimeout),
"",
"",
router,
a,
)
if err != nil {
return nil, err
}
a.Log(logger.Info, "listener opened on "+address)
return a, nil
}
func (a *api) close() {
a.Log(logger.Info, "listener is closing")
a.httpServer.Close()
}
func (a *api) Log(level logger.Level, format string, args ...interface{}) {
a.parent.Log(level, "[API] "+format, args...)
}
func (a *api) onConfigGet(ctx *gin.Context) {
a.mutex.Lock()
c := a.conf
a.mutex.Unlock()
ctx.JSON(http.StatusOK, c)
}
func (a *api) onConfigSet(ctx *gin.Context) {
in, err := loadConfData(ctx)
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
a.mutex.Lock()
defer a.mutex.Unlock()
newConf := a.conf.Clone()
fillStruct(newConf, in)
err = newConf.Check()
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
a.conf = newConf
// since reloading the configuration can cause the shutdown of the API,
// call it in a goroutine
go a.parent.apiConfigSet(newConf)
ctx.Status(http.StatusOK)
}
func (a *api) onConfigPathsAdd(ctx *gin.Context) {
name, ok := paramName(ctx)
if !ok {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
in, err := loadConfPathData(ctx)
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
a.mutex.Lock()
defer a.mutex.Unlock()
newConf := a.conf.Clone()
if _, ok := newConf.Paths[name]; ok {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
newConfPath := &conf.PathConf{}
// load default values
newConfPath.UnmarshalJSON([]byte("{}"))
fillStruct(newConfPath, in)
newConf.Paths[name] = newConfPath
err = newConf.Check()
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
a.conf = newConf
// since reloading the configuration can cause the shutdown of the API,
// call it in a goroutine
go a.parent.apiConfigSet(newConf)
ctx.Status(http.StatusOK)
}
func (a *api) onConfigPathsEdit(ctx *gin.Context) {
name, ok := paramName(ctx)
if !ok {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
in, err := loadConfPathData(ctx)
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
a.mutex.Lock()
defer a.mutex.Unlock()
newConf := a.conf.Clone()
newConfPath, ok := newConf.Paths[name]
if !ok {
ctx.AbortWithStatus(http.StatusNotFound)
return
}
fillStruct(newConfPath, in)
err = newConf.Check()
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
a.conf = newConf
// since reloading the configuration can cause the shutdown of the API,
// call it in a goroutine
go a.parent.apiConfigSet(newConf)
ctx.Status(http.StatusOK)
}
func (a *api) onConfigPathsDelete(ctx *gin.Context) {
name, ok := paramName(ctx)
if !ok {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
a.mutex.Lock()
defer a.mutex.Unlock()
if _, ok := a.conf.Paths[name]; !ok {
ctx.AbortWithStatus(http.StatusNotFound)
return
}
newConf := a.conf.Clone()
delete(newConf.Paths, name)
err := newConf.Check()
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
a.conf = newConf
// since reloading the configuration can cause the shutdown of the API,
// call it in a goroutine
go a.parent.apiConfigSet(newConf)
ctx.Status(http.StatusOK)
}
func (a *api) onPathsList(ctx *gin.Context) {
data, err := a.pathManager.apiPathsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onPathsGet(ctx *gin.Context) {
name, ok := paramName(ctx)
if !ok {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.pathManager.apiPathsGet(name)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPConnsList(ctx *gin.Context) {
data, err := a.rtspServer.apiConnsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPConnsGet(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.rtspServer.apiConnsGet(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPSessionsList(ctx *gin.Context) {
data, err := a.rtspServer.apiSessionsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPSessionsGet(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.rtspServer.apiSessionsGet(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPSessionsKick(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
err = a.rtspServer.apiSessionsKick(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.Status(http.StatusOK)
}
func (a *api) onRTSPSConnsList(ctx *gin.Context) {
data, err := a.rtspsServer.apiConnsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPSConnsGet(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.rtspsServer.apiConnsGet(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPSSessionsList(ctx *gin.Context) {
data, err := a.rtspsServer.apiSessionsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPSSessionsGet(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.rtspsServer.apiSessionsGet(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTSPSSessionsKick(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
err = a.rtspsServer.apiSessionsKick(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.Status(http.StatusOK)
}
func (a *api) onRTMPConnsList(ctx *gin.Context) {
data, err := a.rtmpServer.apiConnsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTMPConnsGet(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.rtmpServer.apiConnsGet(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTMPConnsKick(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
err = a.rtmpServer.apiConnsKick(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.Status(http.StatusOK)
}
func (a *api) onRTMPSConnsList(ctx *gin.Context) {
data, err := a.rtmpsServer.apiConnsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTMPSConnsGet(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.rtmpsServer.apiConnsGet(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onRTMPSConnsKick(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
err = a.rtmpsServer.apiConnsKick(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.Status(http.StatusOK)
}
func (a *api) onHLSMuxersList(ctx *gin.Context) {
data, err := a.hlsManager.apiMuxersList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onHLSMuxersGet(ctx *gin.Context) {
name, ok := paramName(ctx)
if !ok {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.hlsManager.apiMuxersGet(name)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onWebRTCSessionsList(ctx *gin.Context) {
data, err := a.webRTCManager.apiSessionsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onWebRTCSessionsGet(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.webRTCManager.apiSessionsGet(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onWebRTCSessionsKick(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
err = a.webRTCManager.apiSessionsKick(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.Status(http.StatusOK)
}
func (a *api) onSRTConnsList(ctx *gin.Context) {
data, err := a.srtServer.apiConnsList()
if err != nil {
ctx.AbortWithStatus(http.StatusInternalServerError)
return
}
data.ItemCount = len(data.Items)
pageCount, err := paginate(&data.Items, ctx.Query("itemsPerPage"), ctx.Query("page"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data.PageCount = pageCount
ctx.JSON(http.StatusOK, data)
}
func (a *api) onSRTConnsGet(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
data, err := a.srtServer.apiConnsGet(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.JSON(http.StatusOK, data)
}
func (a *api) onSRTConnsKick(ctx *gin.Context) {
uuid, err := uuid.Parse(ctx.Param("id"))
if err != nil {
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
err = a.srtServer.apiConnsKick(uuid)
if err != nil {
abortWithError(ctx, err)
return
}
ctx.Status(http.StatusOK)
}
// confReload is called by core.
func (a *api) confReload(conf *conf.Conf) {
a.mutex.Lock()
defer a.mutex.Unlock()
a.conf = conf
}

154
internal/core/api_defs.go

@ -1,154 +0,0 @@
package core
import (
"time"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/conf"
)
type apiPath struct {
Name string `json:"name"`
ConfName string `json:"confName"`
Conf *conf.PathConf `json:"conf"`
Source interface{} `json:"source"`
SourceReady bool `json:"sourceReady"` // Deprecated: renamed to Ready
Ready bool `json:"ready"`
ReadyTime *time.Time `json:"readyTime"`
Tracks []string `json:"tracks"`
BytesReceived uint64 `json:"bytesReceived"`
Readers []interface{} `json:"readers"`
}
type apiPathsList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []*apiPath `json:"items"`
}
type apiHLSMuxer struct {
Path string `json:"path"`
Created time.Time `json:"created"`
LastRequest time.Time `json:"lastRequest"`
BytesSent uint64 `json:"bytesSent"`
}
type apiHLSMuxersList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []*apiHLSMuxer `json:"items"`
}
type apiRTSPConn struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
type apiRTSPConnsList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []*apiRTSPConn `json:"items"`
}
type apiRTMPConnState string
const (
apiRTMPConnStateIdle apiRTMPConnState = "idle"
apiRTMPConnStateRead apiRTMPConnState = "read"
apiRTMPConnStatePublish apiRTMPConnState = "publish"
)
type apiRTMPConn struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State apiRTMPConnState `json:"state"`
Path string `json:"path"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
type apiRTMPConnsList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []*apiRTMPConn `json:"items"`
}
type apiRTSPSessionState string
const (
apiRTSPSessionStateIdle apiRTSPSessionState = "idle"
apiRTSPSessionStateRead apiRTSPSessionState = "read"
apiRTSPSessionStatePublish apiRTSPSessionState = "publish"
)
type apiRTSPSession struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
State apiRTSPSessionState `json:"state"`
Path string `json:"path"`
Transport *string `json:"transport"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
type apiRTSPSessionsList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []*apiRTSPSession `json:"items"`
}
type apiSRTConnState string
const (
apiSRTConnStateIdle apiSRTConnState = "idle"
apiSRTConnStateRead apiSRTConnState = "read"
apiSRTConnStatePublish apiSRTConnState = "publish"
)
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"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
type apiSRTConnsList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []*apiSRTConn `json:"items"`
}
type apiWebRTCSessionState string
const (
apiWebRTCSessionStateRead apiWebRTCSessionState = "read"
apiWebRTCSessionStatePublish apiWebRTCSessionState = "publish"
)
type apiWebRTCSession struct {
ID uuid.UUID `json:"id"`
Created time.Time `json:"created"`
RemoteAddr string `json:"remoteAddr"`
PeerConnectionEstablished bool `json:"peerConnectionEstablished"`
LocalCandidate string `json:"localCandidate"`
RemoteCandidate string `json:"remoteCandidate"`
State apiWebRTCSessionState `json:"state"`
Path string `json:"path"`
BytesReceived uint64 `json:"bytesReceived"`
BytesSent uint64 `json:"bytesSent"`
}
type apiWebRTCSessionsList struct {
ItemCount int `json:"itemCount"`
PageCount int `json:"pageCount"`
Items []*apiWebRTCSession `json:"items"`
}

1004
internal/core/api_test.go

File diff suppressed because it is too large Load Diff

183
internal/core/authentication.go

@ -1,183 +0,0 @@
package core
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strings"
"github.com/bluenviron/gortsplib/v3/pkg/auth"
"github.com/bluenviron/gortsplib/v3/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/headers"
"github.com/bluenviron/gortsplib/v3/pkg/url"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/conf"
)
func sha256Base64(in string) string {
h := sha256.New()
h.Write([]byte(in))
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func checkCredential(right string, guess string) bool {
if strings.HasPrefix(right, "sha256:") {
return right[len("sha256:"):] == sha256Base64(guess)
}
return right == guess
}
type errAuthentication struct {
message string
}
// Error implements the error interface.
func (e *errAuthentication) Error() string {
return "authentication failed: " + e.message
}
type authProtocol string
const (
authProtocolRTSP authProtocol = "rtsp"
authProtocolRTMP authProtocol = "rtmp"
authProtocolHLS authProtocol = "hls"
authProtocolWebRTC authProtocol = "webrtc"
authProtocolSRT authProtocol = "srt"
)
type authCredentials struct {
query string
ip net.IP
user string
pass string
proto authProtocol
id *uuid.UUID
rtspRequest *base.Request
rtspBaseURL *url.URL
rtspNonce string
}
func doExternalAuthentication(
ur string,
path string,
publish bool,
credentials authCredentials,
) 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: credentials.ip.String(),
User: credentials.user,
Password: credentials.pass,
Path: path,
Protocol: string(credentials.proto),
ID: credentials.id,
Action: func() string {
if publish {
return "publish"
}
return "read"
}(),
Query: credentials.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,
pathName string,
pathConf *conf.PathConf,
publish bool,
credentials authCredentials,
) error {
var rtspAuth headers.Authorization
if credentials.rtspRequest != nil {
err := rtspAuth.Unmarshal(credentials.rtspRequest.Header["Authorization"])
if err == nil && rtspAuth.Method == headers.AuthBasic {
credentials.user = rtspAuth.BasicUser
credentials.pass = rtspAuth.BasicPass
}
}
if externalAuthenticationURL != "" {
err := doExternalAuthentication(
externalAuthenticationURL,
pathName,
publish,
credentials,
)
if err != nil {
return &errAuthentication{message: fmt.Sprintf("external authentication failed: %s", err)}
}
}
var pathIPs conf.IPsOrCIDRs
var pathUser string
var pathPass string
if publish {
pathIPs = pathConf.PublishIPs
pathUser = string(pathConf.PublishUser)
pathPass = string(pathConf.PublishPass)
} else {
pathIPs = pathConf.ReadIPs
pathUser = string(pathConf.ReadUser)
pathPass = string(pathConf.ReadPass)
}
if pathIPs != nil {
if !ipEqualOrInRange(credentials.ip, pathIPs) {
return &errAuthentication{message: fmt.Sprintf("IP %s not allowed", credentials.ip)}
}
}
if pathUser != "" {
if credentials.rtspRequest != nil && rtspAuth.Method == headers.AuthDigest {
err := auth.Validate(
credentials.rtspRequest,
pathUser,
pathPass,
credentials.rtspBaseURL,
rtspAuthMethods,
"IPCAM",
credentials.rtspNonce)
if err != nil {
return &errAuthentication{message: err.Error()}
}
} else if !checkCredential(pathUser, credentials.user) ||
!checkCredential(pathPass, credentials.pass) {
return &errAuthentication{message: "invalid credentials"}
}
}
return nil
}

847
internal/core/core.go

File diff suppressed because it is too large Load Diff

152
internal/core/core_test.go

@ -6,84 +6,18 @@ import (
"testing" "testing"
"time" "time"
"github.com/bluenviron/gortsplib/v3" "github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v3/pkg/media" "github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/mediamtx/internal/test"
"github.com/stretchr/testify/require" "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) { func newInstance(conf string) (*Core, bool) {
if conf == "" { if conf == "" {
return New([]string{}) return New([]string{})
} }
tmpf, err := writeTempFile([]byte(conf)) tmpf, err := test.CreateTempFile([]byte(conf))
if err != nil { if err != nil {
return nil, false return nil, false
} }
@ -92,6 +26,74 @@ func newInstance(conf string) (*Core, bool) {
return New([]string{tmpf}) 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) { func TestCoreHotReloading(t *testing.T) {
confPath := filepath.Join(os.TempDir(), "rtsp-conf") confPath := filepath.Join(os.TempDir(), "rtsp-conf")
@ -108,10 +110,9 @@ func TestCoreHotReloading(t *testing.T) {
defer p.Close() defer p.Close()
func() { func() {
medi := testMediaH264
c := gortsplib.Client{} c := gortsplib.Client{}
err = c.StartRecording("rtsp://localhost:8554/test1", media.Medias{medi}) err = c.StartRecording("rtsp://localhost:8554/test1",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.EqualError(t, err, "bad status code: 401 (Unauthorized)") require.EqualError(t, err, "bad status code: 401 (Unauthorized)")
}() }()
@ -123,10 +124,9 @@ func TestCoreHotReloading(t *testing.T) {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
func() { func() {
medi := testMediaH264
conn := gortsplib.Client{} conn := gortsplib.Client{}
err = conn.StartRecording("rtsp://localhost:8554/test1", media.Medias{medi}) err = conn.StartRecording("rtsp://localhost:8554/test1",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err) require.NoError(t, err)
defer conn.Close() defer conn.Close()
}() }()

204
internal/core/hls_http_server.go

@ -1,204 +0,0 @@
package core
import (
_ "embed"
"fmt"
"net"
"net/http"
gopath "path"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/httpserv"
"github.com/bluenviron/mediamtx/internal/logger"
)
const (
hlsPauseAfterAuthError = 2 * time.Second
)
//go:embed hls_index.html
var hlsIndex []byte
type hlsHTTPServerParent interface {
logger.Writer
handleRequest(req hlsMuxerHandleRequestReq)
}
type hlsHTTPServer struct {
allowOrigin string
pathManager *pathManager
parent hlsHTTPServerParent
inner *httpserv.WrappedServer
}
func newHLSHTTPServer( //nolint:dupl
address string,
encryption bool,
serverKey string,
serverCert string,
allowOrigin string,
trustedProxies conf.IPsOrCIDRs,
readTimeout conf.StringDuration,
pathManager *pathManager,
parent hlsHTTPServerParent,
) (*hlsHTTPServer, error) {
if encryption {
if serverCert == "" {
return nil, fmt.Errorf("server cert is missing")
}
} else {
serverKey = ""
serverCert = ""
}
s := &hlsHTTPServer{
allowOrigin: allowOrigin,
pathManager: pathManager,
parent: parent,
}
router := gin.New()
router.SetTrustedProxies(trustedProxies.ToTrustedProxies())
router.NoRoute(s.onRequest)
network, address := restrictNetwork("tcp", address)
var err error
s.inner, err = httpserv.NewWrappedServer(
network,
address,
time.Duration(readTimeout),
serverCert,
serverKey,
router,
s,
)
if err != nil {
return nil, err
}
return s, nil
}
func (s *hlsHTTPServer) Log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, format, args...)
}
func (s *hlsHTTPServer) close() {
s.inner.Close()
}
func (s *hlsHTTPServer) onRequest(ctx *gin.Context) {
ctx.Writer.Header().Set("Access-Control-Allow-Origin", s.allowOrigin)
ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
switch ctx.Request.Method {
case http.MethodOptions:
ctx.Writer.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET")
ctx.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization, Range")
ctx.Writer.WriteHeader(http.StatusNoContent)
return
case http.MethodGet:
default:
return
}
// remove leading prefix
pa := ctx.Request.URL.Path[1:]
var dir string
var fname string
switch {
case pa == "", pa == "favicon.ico":
return
case strings.HasSuffix(pa, ".m3u8") ||
strings.HasSuffix(pa, ".ts") ||
strings.HasSuffix(pa, ".mp4") ||
strings.HasSuffix(pa, ".mp"):
dir, fname = gopath.Dir(pa), gopath.Base(pa)
if strings.HasSuffix(fname, ".mp") {
fname += "4"
}
default:
dir, fname = pa, ""
if !strings.HasSuffix(dir, "/") {
l := "/" + dir + "/"
if ctx.Request.URL.RawQuery != "" {
l += "?" + ctx.Request.URL.RawQuery
}
ctx.Writer.Header().Set("Location", l)
ctx.Writer.WriteHeader(http.StatusMovedPermanently)
return
}
}
dir = strings.TrimSuffix(dir, "/")
if dir == "" {
return
}
user, pass, hasCredentials := ctx.Request.BasicAuth()
res := s.pathManager.getConfForPath(pathGetConfForPathReq{
name: dir,
publish: false,
credentials: authCredentials{
query: ctx.Request.URL.RawQuery,
ip: net.ParseIP(ctx.ClientIP()),
user: user,
pass: pass,
proto: authProtocolWebRTC,
},
})
if res.err != nil {
if terr, ok := res.err.(*errAuthentication); ok {
if !hasCredentials {
ctx.Header("WWW-Authenticate", `Basic realm="mediamtx"`)
ctx.Writer.WriteHeader(http.StatusUnauthorized)
return
}
ip := ctx.ClientIP()
_, port, _ := net.SplitHostPort(ctx.Request.RemoteAddr)
remoteAddr := net.JoinHostPort(ip, port)
s.Log(logger.Info, "connection %v failed to authenticate: %v", remoteAddr, terr.message)
// wait some seconds to stop brute force attacks
<-time.After(hlsPauseAfterAuthError)
ctx.Writer.WriteHeader(http.StatusUnauthorized)
return
}
ctx.Writer.WriteHeader(http.StatusNotFound)
return
}
switch fname {
case "":
ctx.Writer.Header().Set("Content-Type", "text/html")
ctx.Writer.WriteHeader(http.StatusOK)
ctx.Writer.Write(hlsIndex)
default:
s.parent.handleRequest(hlsMuxerHandleRequestReq{
path: dir,
file: fname,
ctx: ctx,
})
}
}

68
internal/core/hls_index.html

@ -1,68 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
#video {
width: 100%;
height: 100%;
background: black;
}
</style>
</head>
<body>
<video id="video" muted controls autoplay playsinline></video>
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.4.10"></script>
<script>
const create = () => {
const video = document.getElementById('video');
// always prefer hls.js over native HLS.
// this is because some Android versions support native HLS
// but don't support fMP4s.
if (Hls.isSupported()) {
const hls = new Hls({
maxLiveSyncPlaybackRate: 1.5,
});
hls.on(Hls.Events.ERROR, (evt, data) => {
if (data.fatal) {
hls.destroy();
setTimeout(create, 2000);
}
});
hls.loadSource('index.m3u8' + window.location.search);
hls.attachMedia(video);
video.play();
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
// since it's not possible to detect timeout errors in iOS,
// wait for the playlist to be available before starting the stream
fetch('index.m3u8')
.then(() => {
video.src = 'index.m3u8';
video.play();
});
}
};
window.addEventListener('DOMContentLoaded', create);
</script>
</body>
</html>

323
internal/core/hls_manager.go

@ -1,323 +0,0 @@
package core
import (
"context"
"fmt"
"sort"
"sync"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/logger"
)
type hlsManagerAPIMuxersListRes struct {
data *apiHLSMuxersList
err error
}
type hlsManagerAPIMuxersListReq struct {
res chan hlsManagerAPIMuxersListRes
}
type hlsManagerAPIMuxersGetRes struct {
data *apiHLSMuxer
err error
}
type hlsManagerAPIMuxersGetReq struct {
name string
res chan hlsManagerAPIMuxersGetRes
}
type hlsManagerParent interface {
logger.Writer
}
type hlsManager struct {
externalAuthenticationURL string
alwaysRemux bool
variant conf.HLSVariant
segmentCount int
segmentDuration conf.StringDuration
partDuration conf.StringDuration
segmentMaxSize conf.StringSize
directory string
readBufferCount int
pathManager *pathManager
metrics *metrics
parent hlsManagerParent
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
httpServer *hlsHTTPServer
muxers map[string]*hlsMuxer
// in
chPathReady chan *path
chPathNotReady chan *path
chHandleRequest chan hlsMuxerHandleRequestReq
chCloseMuxer chan *hlsMuxer
chAPIMuxerList chan hlsManagerAPIMuxersListReq
chAPIMuxerGet chan hlsManagerAPIMuxersGetReq
}
func newHLSManager(
address string,
encryption bool,
serverKey string,
serverCert string,
externalAuthenticationURL string,
alwaysRemux bool,
variant conf.HLSVariant,
segmentCount int,
segmentDuration conf.StringDuration,
partDuration conf.StringDuration,
segmentMaxSize conf.StringSize,
allowOrigin string,
trustedProxies conf.IPsOrCIDRs,
directory string,
readTimeout conf.StringDuration,
readBufferCount int,
pathManager *pathManager,
metrics *metrics,
parent hlsManagerParent,
) (*hlsManager, error) {
ctx, ctxCancel := context.WithCancel(context.Background())
m := &hlsManager{
externalAuthenticationURL: externalAuthenticationURL,
alwaysRemux: alwaysRemux,
variant: variant,
segmentCount: segmentCount,
segmentDuration: segmentDuration,
partDuration: partDuration,
segmentMaxSize: segmentMaxSize,
directory: directory,
readBufferCount: readBufferCount,
pathManager: pathManager,
parent: parent,
metrics: metrics,
ctx: ctx,
ctxCancel: ctxCancel,
muxers: make(map[string]*hlsMuxer),
chPathReady: make(chan *path),
chPathNotReady: make(chan *path),
chHandleRequest: make(chan hlsMuxerHandleRequestReq),
chCloseMuxer: make(chan *hlsMuxer),
chAPIMuxerList: make(chan hlsManagerAPIMuxersListReq),
chAPIMuxerGet: make(chan hlsManagerAPIMuxersGetReq),
}
var err error
m.httpServer, err = newHLSHTTPServer(
address,
encryption,
serverKey,
serverCert,
allowOrigin,
trustedProxies,
readTimeout,
m.pathManager,
m,
)
if err != nil {
ctxCancel()
return nil, err
}
m.Log(logger.Info, "listener opened on "+address)
m.pathManager.setHLSManager(m)
if m.metrics != nil {
m.metrics.setHLSManager(m)
}
m.wg.Add(1)
go m.run()
return m, nil
}
// Log is the main logging function.
func (m *hlsManager) Log(level logger.Level, format string, args ...interface{}) {
m.parent.Log(level, "[HLS] "+format, append([]interface{}{}, args...)...)
}
func (m *hlsManager) close() {
m.Log(logger.Info, "listener is closing")
m.ctxCancel()
m.wg.Wait()
}
func (m *hlsManager) run() {
defer m.wg.Done()
outer:
for {
select {
case pa := <-m.chPathReady:
if m.alwaysRemux && !pa.conf.SourceOnDemand {
if _, ok := m.muxers[pa.name]; !ok {
m.createMuxer(pa.name, "")
}
}
case pa := <-m.chPathNotReady:
c, ok := m.muxers[pa.name]
if ok && c.remoteAddr == "" { // created with "always remux"
c.close()
delete(m.muxers, pa.name)
}
case req := <-m.chHandleRequest:
r, ok := m.muxers[req.path]
switch {
case ok:
r.processRequest(&req)
default:
r := m.createMuxer(req.path, req.ctx.ClientIP())
r.processRequest(&req)
}
case c := <-m.chCloseMuxer:
if c2, ok := m.muxers[c.PathName()]; !ok || c2 != c {
continue
}
delete(m.muxers, c.PathName())
case req := <-m.chAPIMuxerList:
data := &apiHLSMuxersList{
Items: []*apiHLSMuxer{},
}
for _, muxer := range m.muxers {
data.Items = append(data.Items, muxer.apiItem())
}
sort.Slice(data.Items, func(i, j int) bool {
return data.Items[i].Created.Before(data.Items[j].Created)
})
req.res <- hlsManagerAPIMuxersListRes{
data: data,
}
case req := <-m.chAPIMuxerGet:
muxer, ok := m.muxers[req.name]
if !ok {
req.res <- hlsManagerAPIMuxersGetRes{err: errAPINotFound}
continue
}
req.res <- hlsManagerAPIMuxersGetRes{data: muxer.apiItem()}
case <-m.ctx.Done():
break outer
}
}
m.ctxCancel()
m.httpServer.close()
m.pathManager.setHLSManager(nil)
if m.metrics != nil {
m.metrics.setHLSManager(nil)
}
}
func (m *hlsManager) createMuxer(pathName string, remoteAddr string) *hlsMuxer {
r := newHLSMuxer(
m.ctx,
remoteAddr,
m.externalAuthenticationURL,
m.variant,
m.segmentCount,
m.segmentDuration,
m.partDuration,
m.segmentMaxSize,
m.directory,
m.readBufferCount,
&m.wg,
pathName,
m.pathManager,
m)
m.muxers[pathName] = r
return r
}
// closeMuxer is called by hlsMuxer.
func (m *hlsManager) closeMuxer(c *hlsMuxer) {
select {
case m.chCloseMuxer <- c:
case <-m.ctx.Done():
}
}
// pathReady is called by pathManager.
func (m *hlsManager) pathReady(pa *path) {
select {
case m.chPathReady <- pa:
case <-m.ctx.Done():
}
}
// pathNotReady is called by pathManager.
func (m *hlsManager) pathNotReady(pa *path) {
select {
case m.chPathNotReady <- pa:
case <-m.ctx.Done():
}
}
// apiMuxersList is called by api.
func (m *hlsManager) apiMuxersList() (*apiHLSMuxersList, error) {
req := hlsManagerAPIMuxersListReq{
res: make(chan hlsManagerAPIMuxersListRes),
}
select {
case m.chAPIMuxerList <- req:
res := <-req.res
return res.data, res.err
case <-m.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// apiMuxersGet is called by api.
func (m *hlsManager) apiMuxersGet(name string) (*apiHLSMuxer, error) {
req := hlsManagerAPIMuxersGetReq{
name: name,
res: make(chan hlsManagerAPIMuxersGetRes),
}
select {
case m.chAPIMuxerGet <- req:
res := <-req.res
return res.data, res.err
case <-m.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
func (m *hlsManager) handleRequest(req hlsMuxerHandleRequestReq) {
req.res = make(chan *hlsMuxer)
select {
case m.chHandleRequest <- req:
muxer := <-req.res
if muxer != nil {
req.ctx.Request.URL.Path = req.file
muxer.handleRequest(req.ctx)
}
case <-m.ctx.Done():
}
}

220
internal/core/hls_manager_test.go

@ -1,220 +0,0 @@
package core
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"testing"
"time"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"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:\n")
require.Equal(t, true, ok)
defer p.Close()
medi := &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{&formats.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", media.Medias{medi})
require.NoError(t, err)
defer source.Close()
time.Sleep(500 * time.Millisecond)
for i := 0; i < 2; i++ {
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
},
})
}
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:.+?Z\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)*/
}

670
internal/core/hls_muxer.go

@ -1,670 +0,0 @@
package core
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/bluenviron/gohlslib"
"github.com/bluenviron/gohlslib/pkg/codecs"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/gortsplib/v3/pkg/ringbuffer"
"github.com/gin-gonic/gin"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/formatprocessor"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/stream"
)
const (
closeCheckPeriod = 1 * time.Second
closeAfterInactivity = 60 * time.Second
hlsMuxerRecreatePause = 10 * time.Second
)
func int64Ptr(v int64) *int64 {
return &v
}
type responseWriterWithCounter struct {
http.ResponseWriter
bytesSent *uint64
}
func (w *responseWriterWithCounter) Write(p []byte) (int, error) {
n, err := w.ResponseWriter.Write(p)
atomic.AddUint64(w.bytesSent, uint64(n))
return n, err
}
type hlsMuxerHandleRequestReq struct {
path string
file string
ctx *gin.Context
res chan *hlsMuxer
}
type hlsMuxerParent interface {
logger.Writer
closeMuxer(*hlsMuxer)
}
type hlsMuxer struct {
remoteAddr string
externalAuthenticationURL string
variant conf.HLSVariant
segmentCount int
segmentDuration conf.StringDuration
partDuration conf.StringDuration
segmentMaxSize conf.StringSize
directory string
readBufferCount int
wg *sync.WaitGroup
pathName string
pathManager *pathManager
parent hlsMuxerParent
ctx context.Context
ctxCancel func()
created time.Time
path *path
ringBuffer *ringbuffer.RingBuffer
lastRequestTime *int64
muxer *gohlslib.Muxer
requests []*hlsMuxerHandleRequestReq
bytesSent *uint64
// in
chRequest chan *hlsMuxerHandleRequestReq
}
func newHLSMuxer(
parentCtx context.Context,
remoteAddr string,
externalAuthenticationURL string,
variant conf.HLSVariant,
segmentCount int,
segmentDuration conf.StringDuration,
partDuration conf.StringDuration,
segmentMaxSize conf.StringSize,
directory string,
readBufferCount int,
wg *sync.WaitGroup,
pathName string,
pathManager *pathManager,
parent hlsMuxerParent,
) *hlsMuxer {
ctx, ctxCancel := context.WithCancel(parentCtx)
m := &hlsMuxer{
remoteAddr: remoteAddr,
externalAuthenticationURL: externalAuthenticationURL,
variant: variant,
segmentCount: segmentCount,
segmentDuration: segmentDuration,
partDuration: partDuration,
segmentMaxSize: segmentMaxSize,
directory: directory,
readBufferCount: readBufferCount,
wg: wg,
pathName: pathName,
pathManager: pathManager,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
created: time.Now(),
lastRequestTime: int64Ptr(time.Now().UnixNano()),
bytesSent: new(uint64),
chRequest: make(chan *hlsMuxerHandleRequestReq),
}
m.Log(logger.Info, "created %s", func() string {
if remoteAddr == "" {
return "automatically"
}
return "(requested by " + remoteAddr + ")"
}())
m.wg.Add(1)
go m.run()
return m
}
func (m *hlsMuxer) close() {
m.ctxCancel()
}
func (m *hlsMuxer) Log(level logger.Level, format string, args ...interface{}) {
m.parent.Log(level, "[muxer %s] "+format, append([]interface{}{m.pathName}, args...)...)
}
// PathName returns the path name.
func (m *hlsMuxer) PathName() string {
return m.pathName
}
func (m *hlsMuxer) run() {
defer m.wg.Done()
err := func() error {
var innerReady chan struct{}
var innerErr chan error
var innerCtx context.Context
var innerCtxCancel func()
createInner := func() {
innerReady = make(chan struct{})
innerErr = make(chan error)
innerCtx, innerCtxCancel = context.WithCancel(context.Background())
go func() {
innerErr <- m.runInner(innerCtx, innerReady)
}()
}
createInner()
isReady := false
isRecreating := false
recreateTimer := newEmptyTimer()
for {
select {
case <-m.ctx.Done():
if !isRecreating {
innerCtxCancel()
<-innerErr
}
return errors.New("terminated")
case req := <-m.chRequest:
switch {
case isRecreating:
req.res <- nil
case isReady:
req.res <- m
default:
m.requests = append(m.requests, req)
}
case <-innerReady:
isReady = true
for _, req := range m.requests {
req.res <- m
}
m.requests = nil
case err := <-innerErr:
innerCtxCancel()
if m.remoteAddr == "" { // created with "always remux"
m.Log(logger.Info, "ERR: %v", err)
m.clearQueuedRequests()
isReady = false
isRecreating = true
recreateTimer = time.NewTimer(hlsMuxerRecreatePause)
} else {
return err
}
case <-recreateTimer.C:
isRecreating = false
createInner()
}
}
}()
m.ctxCancel()
m.clearQueuedRequests()
m.parent.closeMuxer(m)
m.Log(logger.Info, "destroyed (%v)", err)
}
func (m *hlsMuxer) clearQueuedRequests() {
for _, req := range m.requests {
req.res <- nil
}
m.requests = nil
}
func (m *hlsMuxer) runInner(innerCtx context.Context, innerReady chan struct{}) error {
res := m.pathManager.addReader(pathAddReaderReq{
author: m,
pathName: m.pathName,
skipAuth: true,
})
if res.err != nil {
return res.err
}
m.path = res.path
defer m.path.removeReader(pathRemoveReaderReq{author: m})
m.ringBuffer, _ = ringbuffer.New(uint64(m.readBufferCount))
var medias media.Medias
videoMedia, videoTrack := m.createVideoTrack(res.stream)
if videoMedia != nil {
medias = append(medias, videoMedia)
}
audioMedia, audioTrack := m.createAudioTrack(res.stream)
if audioMedia != nil {
medias = append(medias, audioMedia)
}
defer res.stream.RemoveReader(m)
if medias == nil {
return fmt.Errorf(
"the stream doesn't contain any supported codec, which are currently H265, H264, Opus, MPEG-4 Audio")
}
var muxerDirectory string
if m.directory != "" {
muxerDirectory = filepath.Join(m.directory, m.pathName)
os.MkdirAll(muxerDirectory, 0o755)
defer os.Remove(muxerDirectory)
}
m.muxer = &gohlslib.Muxer{
Variant: gohlslib.MuxerVariant(m.variant),
SegmentCount: m.segmentCount,
SegmentDuration: time.Duration(m.segmentDuration),
PartDuration: time.Duration(m.partDuration),
SegmentMaxSize: uint64(m.segmentMaxSize),
VideoTrack: videoTrack,
AudioTrack: audioTrack,
Directory: muxerDirectory,
}
err := m.muxer.Start()
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
defer m.muxer.Close()
innerReady <- struct{}{}
m.Log(logger.Info, "is converting into HLS, %s",
sourceMediaInfo(medias))
writerDone := make(chan error)
go func() {
writerDone <- m.runWriter()
}()
closeCheckTicker := time.NewTicker(closeCheckPeriod)
defer closeCheckTicker.Stop()
for {
select {
case <-closeCheckTicker.C:
if m.remoteAddr != "" {
t := time.Unix(0, atomic.LoadInt64(m.lastRequestTime))
if time.Since(t) >= closeAfterInactivity {
m.ringBuffer.Close()
<-writerDone
return fmt.Errorf("not used anymore")
}
}
case err := <-writerDone:
return err
case <-innerCtx.Done():
m.ringBuffer.Close()
<-writerDone
return fmt.Errorf("terminated")
}
}
}
func (m *hlsMuxer) createVideoTrack(stream *stream.Stream) (*media.Media, *gohlslib.Track) {
var videoFormatAV1 *formats.AV1
videoMedia := stream.Medias().FindFormat(&videoFormatAV1)
if videoFormatAV1 != nil {
startPTSFilled := false
var startPTS time.Duration
stream.AddReader(m, videoMedia, videoFormatAV1, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitAV1)
if tunit.OBUs == nil {
return nil
}
if !startPTSFilled {
startPTSFilled = true
startPTS = tunit.PTS
}
pts := tunit.PTS - startPTS
err := m.muxer.WriteAV1(tunit.NTP, pts, tunit.OBUs)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
return videoMedia, &gohlslib.Track{
Codec: &codecs.AV1{},
}
}
var videoFormatVP9 *formats.VP9
videoMedia = stream.Medias().FindFormat(&videoFormatVP9)
if videoFormatVP9 != nil {
startPTSFilled := false
var startPTS time.Duration
stream.AddReader(m, videoMedia, videoFormatVP9, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitVP9)
if tunit.Frame == nil {
return nil
}
if !startPTSFilled {
startPTSFilled = true
startPTS = tunit.PTS
}
pts := tunit.PTS - startPTS
err := m.muxer.WriteVP9(tunit.NTP, pts, tunit.Frame)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
return videoMedia, &gohlslib.Track{
Codec: &codecs.VP9{},
}
}
var videoFormatH265 *formats.H265
videoMedia = stream.Medias().FindFormat(&videoFormatH265)
if videoFormatH265 != nil {
startPTSFilled := false
var startPTS time.Duration
stream.AddReader(m, videoMedia, videoFormatH265, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitH265)
if tunit.AU == nil {
return nil
}
if !startPTSFilled {
startPTSFilled = true
startPTS = tunit.PTS
}
pts := tunit.PTS - startPTS
err := m.muxer.WriteH26x(tunit.NTP, pts, tunit.AU)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
vps, sps, pps := videoFormatH265.SafeParams()
return videoMedia, &gohlslib.Track{
Codec: &codecs.H265{
VPS: vps,
SPS: sps,
PPS: pps,
},
}
}
var videoFormatH264 *formats.H264
videoMedia = stream.Medias().FindFormat(&videoFormatH264)
if videoFormatH264 != nil {
startPTSFilled := false
var startPTS time.Duration
stream.AddReader(m, videoMedia, videoFormatH264, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitH264)
if tunit.AU == nil {
return nil
}
if !startPTSFilled {
startPTSFilled = true
startPTS = tunit.PTS
}
pts := tunit.PTS - startPTS
err := m.muxer.WriteH26x(tunit.NTP, pts, tunit.AU)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
sps, pps := videoFormatH264.SafeParams()
return videoMedia, &gohlslib.Track{
Codec: &codecs.H264{
SPS: sps,
PPS: pps,
},
}
}
return nil, nil
}
func (m *hlsMuxer) createAudioTrack(stream *stream.Stream) (*media.Media, *gohlslib.Track) {
var audioFormatOpus *formats.Opus
audioMedia := stream.Medias().FindFormat(&audioFormatOpus)
if audioMedia != nil {
audioStartPTSFilled := false
var audioStartPTS time.Duration
stream.AddReader(m, audioMedia, audioFormatOpus, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitOpus)
if !audioStartPTSFilled {
audioStartPTSFilled = true
audioStartPTS = tunit.PTS
}
pts := tunit.PTS - audioStartPTS
err := m.muxer.WriteOpus(
tunit.NTP,
pts,
tunit.Packets)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
return audioMedia, &gohlslib.Track{
Codec: &codecs.Opus{
ChannelCount: func() int {
if audioFormatOpus.IsStereo {
return 2
}
return 1
}(),
},
}
}
var audioFormatMPEG4AudioGeneric *formats.MPEG4AudioGeneric
audioMedia = stream.Medias().FindFormat(&audioFormatMPEG4AudioGeneric)
if audioMedia != nil {
audioStartPTSFilled := false
var audioStartPTS time.Duration
stream.AddReader(m, audioMedia, audioFormatMPEG4AudioGeneric, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitMPEG4AudioGeneric)
if tunit.AUs == nil {
return nil
}
if !audioStartPTSFilled {
audioStartPTSFilled = true
audioStartPTS = tunit.PTS
}
pts := tunit.PTS - audioStartPTS
err := m.muxer.WriteMPEG4Audio(
tunit.NTP,
pts,
tunit.AUs)
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
return audioMedia, &gohlslib.Track{
Codec: &codecs.MPEG4Audio{
Config: *audioFormatMPEG4AudioGeneric.Config,
},
}
}
var audioFormatMPEG4AudioLATM *formats.MPEG4AudioLATM
audioMedia = stream.Medias().FindFormat(&audioFormatMPEG4AudioLATM)
if audioMedia != nil &&
audioFormatMPEG4AudioLATM.Config != nil &&
len(audioFormatMPEG4AudioLATM.Config.Programs) == 1 &&
len(audioFormatMPEG4AudioLATM.Config.Programs[0].Layers) == 1 {
audioStartPTSFilled := false
var audioStartPTS time.Duration
stream.AddReader(m, audioMedia, audioFormatMPEG4AudioLATM, func(unit formatprocessor.Unit) {
m.ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitMPEG4AudioLATM)
if tunit.AU == nil {
return nil
}
if !audioStartPTSFilled {
audioStartPTSFilled = true
audioStartPTS = tunit.PTS
}
pts := tunit.PTS - audioStartPTS
err := m.muxer.WriteMPEG4Audio(
tunit.NTP,
pts,
[][]byte{tunit.AU})
if err != nil {
return fmt.Errorf("muxer error: %v", err)
}
return nil
})
})
return audioMedia, &gohlslib.Track{
Codec: &codecs.MPEG4Audio{
Config: *audioFormatMPEG4AudioLATM.Config.Programs[0].Layers[0].AudioSpecificConfig,
},
}
}
return nil, nil
}
func (m *hlsMuxer) runWriter() error {
for {
item, ok := m.ringBuffer.Pull()
if !ok {
return fmt.Errorf("terminated")
}
err := item.(func() error)()
if err != nil {
return err
}
}
}
func (m *hlsMuxer) handleRequest(ctx *gin.Context) {
atomic.StoreInt64(m.lastRequestTime, time.Now().UnixNano())
w := &responseWriterWithCounter{
ResponseWriter: ctx.Writer,
bytesSent: m.bytesSent,
}
m.muxer.Handle(w, ctx.Request)
}
// processRequest is called by hlsserver.Server (forwarded from ServeHTTP).
func (m *hlsMuxer) processRequest(req *hlsMuxerHandleRequestReq) {
select {
case m.chRequest <- req:
case <-m.ctx.Done():
req.res <- nil
}
}
// apiReaderDescribe implements reader.
func (m *hlsMuxer) apiReaderDescribe() pathAPISourceOrReader {
return pathAPISourceOrReader{
Type: "hlsMuxer",
ID: "",
}
}
func (m *hlsMuxer) apiItem() *apiHLSMuxer {
return &apiHLSMuxer{
Path: m.pathName,
Created: m.created,
LastRequest: time.Unix(0, atomic.LoadInt64(m.lastRequestTime)),
BytesSent: atomic.LoadUint64(m.bytesSent),
}
}

238
internal/core/hls_source.go

@ -1,238 +0,0 @@
package core
import (
"context"
"net/http"
"time"
"github.com/bluenviron/gohlslib"
"github.com/bluenviron/gohlslib/pkg/codecs"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/formatprocessor"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/stream"
)
type hlsSourceParent interface {
logger.Writer
setReady(req pathSourceStaticSetReadyReq) pathSourceStaticSetReadyRes
setNotReady(req pathSourceStaticSetNotReadyReq)
}
type hlsSource struct {
parent hlsSourceParent
}
func newHLSSource(
parent hlsSourceParent,
) *hlsSource {
return &hlsSource{
parent: parent,
}
}
func (s *hlsSource) Log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[HLS source] "+format, args...)
}
// run implements sourceStaticImpl.
func (s *hlsSource) run(ctx context.Context, cnf *conf.PathConf, reloadConf chan *conf.PathConf) error {
var stream *stream.Stream
defer func() {
if stream != nil {
s.parent.setNotReady(pathSourceStaticSetNotReadyReq{})
}
}()
c := &gohlslib.Client{
URI: cnf.Source,
HTTPClient: &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfigForFingerprint(cnf.SourceFingerprint),
},
},
OnDownloadPrimaryPlaylist: func(u string) {
s.Log(logger.Debug, "downloading primary playlist %u", u)
},
OnDownloadStreamPlaylist: func(u string) {
s.Log(logger.Debug, "downloading stream playlist %u", u)
},
OnDownloadSegment: func(u string) {
s.Log(logger.Debug, "downloading segment %u", u)
},
OnDecodeError: func(err error) {
s.Log(logger.Warn, err.Error())
},
}
c.OnTracks(func(tracks []*gohlslib.Track) error {
var medias media.Medias
for _, track := range tracks {
var medi *media.Media
switch tcodec := track.Codec.(type) {
case *codecs.AV1:
medi = &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{&formats.AV1{}},
}
c.OnDataAV1(track, func(pts time.Duration, obus [][]byte) {
stream.WriteUnit(medi, medi.Formats[0], &formatprocessor.UnitAV1{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
OBUs: obus,
})
})
case *codecs.VP9:
medi = &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{&formats.VP9{}},
}
c.OnDataVP9(track, func(pts time.Duration, frame []byte) {
stream.WriteUnit(medi, medi.Formats[0], &formatprocessor.UnitVP9{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
Frame: frame,
})
})
case *codecs.H264:
medi = &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{&formats.H264{
PayloadTyp: 96,
PacketizationMode: 1,
SPS: tcodec.SPS,
PPS: tcodec.PPS,
}},
}
c.OnDataH26x(track, func(pts time.Duration, dts time.Duration, au [][]byte) {
stream.WriteUnit(medi, medi.Formats[0], &formatprocessor.UnitH264{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
AU: au,
})
})
case *codecs.H265:
medi = &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{&formats.H265{
PayloadTyp: 96,
VPS: tcodec.VPS,
SPS: tcodec.SPS,
PPS: tcodec.PPS,
}},
}
c.OnDataH26x(track, func(pts time.Duration, dts time.Duration, au [][]byte) {
stream.WriteUnit(medi, medi.Formats[0], &formatprocessor.UnitH265{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
AU: au,
})
})
case *codecs.MPEG4Audio:
medi = &media.Media{
Type: media.TypeAudio,
Formats: []formats.Format{&formats.MPEG4Audio{
PayloadTyp: 96,
SizeLength: 13,
IndexLength: 3,
IndexDeltaLength: 3,
Config: &tcodec.Config,
}},
}
c.OnDataMPEG4Audio(track, func(pts time.Duration, aus [][]byte) {
stream.WriteUnit(medi, medi.Formats[0], &formatprocessor.UnitMPEG4AudioGeneric{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
AUs: aus,
})
})
case *codecs.Opus:
medi = &media.Media{
Type: media.TypeAudio,
Formats: []formats.Format{&formats.Opus{
PayloadTyp: 96,
IsStereo: (tcodec.ChannelCount == 2),
}},
}
c.OnDataOpus(track, func(pts time.Duration, packets [][]byte) {
stream.WriteUnit(medi, medi.Formats[0], &formatprocessor.UnitOpus{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
Packets: packets,
})
})
}
medias = append(medias, medi)
}
res := s.parent.setReady(pathSourceStaticSetReadyReq{
medias: medias,
generateRTPPackets: true,
})
if res.err != nil {
return res.err
}
stream = res.stream
return nil
})
err := c.Start()
if err != nil {
return err
}
for {
select {
case err := <-c.Wait():
c.Close()
return err
case <-reloadConf:
case <-ctx.Done():
c.Close()
<-c.Wait()
return nil
}
}
}
// apiSourceDescribe implements sourceStaticImpl.
func (*hlsSource) apiSourceDescribe() pathAPISourceOrReader {
return pathAPISourceOrReader{
Type: "hlsSource",
ID: "",
}
}

208
internal/core/hls_source_test.go

@ -1,208 +0,0 @@
package core
import (
"bytes"
"context"
"io"
"net"
"net/http"
"testing"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/gortsplib/v3/pkg/url"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio"
"github.com/bluenviron/mediacommon/pkg/formats/mpegts"
"github.com/gin-gonic/gin"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
)
var track1 = &mpegts.Track{
Codec: &mpegts.CodecH264{},
}
var track2 = &mpegts.Track{
Codec: &mpegts.CodecMPEG4Audio{
Config: mpeg4audio.Config{
Type: 2,
SampleRate: 44100,
ChannelCount: 2,
},
},
}
type testHLSManager struct {
s *http.Server
clientConnected chan struct{}
}
func newTestHLSManager() (*testHLSManager, error) {
ln, err := net.Listen("tcp", "localhost:5780")
if err != nil {
return nil, err
}
ts := &testHLSManager{
clientConnected: make(chan struct{}),
}
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.GET("/stream.m3u8", ts.onPlaylist)
router.GET("/segment1.ts", ts.onSegment1)
router.GET("/segment2.ts", ts.onSegment2)
ts.s = &http.Server{Handler: router}
go ts.s.Serve(ln)
return ts, nil
}
func (ts *testHLSManager) close() {
ts.s.Shutdown(context.Background())
}
func (ts *testHLSManager) onPlaylist(ctx *gin.Context) {
cnt := `#EXTM3U
#EXT-X-VERSION:3
#EXT-X-ALLOW-CACHE:NO
#EXT-X-TARGETDURATION:2
#EXT-X-MEDIA-SEQUENCE:0
#EXTINF:2,
segment1.ts
#EXTINF:2,
segment2.ts
#EXT-X-ENDLIST
`
ctx.Writer.Header().Set("Content-Type", `application/vnd.apple.mpegurl`)
io.Copy(ctx.Writer, bytes.NewReader([]byte(cnt)))
}
func (ts *testHLSManager) onSegment1(ctx *gin.Context) {
ctx.Writer.Header().Set("Content-Type", `video/MP2T`)
w := mpegts.NewWriter(ctx.Writer, []*mpegts.Track{track1, track2})
w.WriteMPEG4Audio(track2, 1*90000, [][]byte{{1, 2, 3, 4}})
}
func (ts *testHLSManager) onSegment2(ctx *gin.Context) {
<-ts.clientConnected
ctx.Writer.Header().Set("Content-Type", `video/MP2T`)
w := mpegts.NewWriter(ctx.Writer, []*mpegts.Track{track1, track2})
w.WriteH26x(track1, 2*90000, 2*90000, true, [][]byte{
{7, 1, 2, 3}, // SPS
{8}, // PPS
})
w.WriteMPEG4Audio(track2, 2*90000, [][]byte{{1, 2, 3, 4}})
w.WriteH26x(track1, 2*90000, 2*90000, true, [][]byte{
{5}, // IDR
})
}
func TestHLSSource(t *testing.T) {
ts, err := newTestHLSManager()
require.NoError(t, err)
defer ts.close()
p, ok := newInstance("rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" proxied:\n" +
" source: http://localhost:5780/stream.m3u8\n" +
" sourceOnDemand: yes\n")
require.Equal(t, true, ok)
defer p.Close()
frameRecv := make(chan struct{})
c := gortsplib.Client{}
u, err := url.Parse("rtsp://localhost:8554/proxied")
require.NoError(t, err)
err = c.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer c.Close()
medias, baseURL, _, err := c.Describe(u)
require.NoError(t, err)
require.Equal(t, media.Medias{
{
Type: media.TypeVideo,
Control: medias[0].Control,
Formats: []formats.Format{
&formats.H264{
PayloadTyp: 96,
PacketizationMode: 1,
},
},
},
{
Type: media.TypeAudio,
Control: medias[1].Control,
Formats: []formats.Format{
&formats.MPEG4Audio{
PayloadTyp: 96,
ProfileLevelID: 1,
Config: &mpeg4audio.Config{
Type: 2,
SampleRate: 44100,
ChannelCount: 2,
},
SizeLength: 13,
IndexLength: 3,
IndexDeltaLength: 3,
},
},
},
}, medias)
var forma *formats.H264
medi := medias.FindFormat(&forma)
_, err = c.Setup(medi, baseURL, 0, 0)
require.NoError(t, err)
c.OnPacketRTP(medi, forma, func(pkt *rtp.Packet) {
require.Equal(t, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: pkt.SequenceNumber,
Timestamp: pkt.Timestamp,
SSRC: pkt.SSRC,
CSRC: []uint32{},
},
Payload: []byte{
0x18,
0x00, 0x04,
0x07, 0x01, 0x02, 0x03, // SPS
0x00, 0x01,
0x08, // PPS
0x00, 0x01,
0x05, // IDR
},
}, pkt)
close(frameRecv)
})
_, err = c.Play(nil)
require.NoError(t, err)
close(ts.clientConnected)
<-frameRecv
}

23
internal/core/ip.go

@ -1,23 +0,0 @@
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
}

261
internal/core/metrics.go

@ -1,261 +0,0 @@
package core
import (
"io"
"net/http"
"strconv"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/httpserv"
"github.com/bluenviron/mediamtx/internal/logger"
)
func metric(key string, tags string, value int64) string {
return key + tags + " " + strconv.FormatInt(value, 10) + "\n"
}
type metricsParent interface {
logger.Writer
}
type metrics struct {
parent metricsParent
httpServer *httpserv.WrappedServer
mutex sync.Mutex
pathManager apiPathManager
rtspServer apiRTSPServer
rtspsServer apiRTSPServer
rtmpServer apiRTMPServer
hlsManager apiHLSManager
webRTCManager apiWebRTCManager
}
func newMetrics(
address string,
readTimeout conf.StringDuration,
parent metricsParent,
) (*metrics, error) {
m := &metrics{
parent: parent,
}
router := gin.New()
router.SetTrustedProxies(nil)
router.GET("/metrics", m.onMetrics)
network, address := restrictNetwork("tcp", address)
var err error
m.httpServer, err = httpserv.NewWrappedServer(
network,
address,
time.Duration(readTimeout),
"",
"",
router,
m,
)
if err != nil {
return nil, err
}
m.Log(logger.Info, "listener opened on "+address)
return m, nil
}
func (m *metrics) close() {
m.Log(logger.Info, "listener is closing")
m.httpServer.Close()
}
func (m *metrics) Log(level logger.Level, format string, args ...interface{}) {
m.parent.Log(level, "[metrics] "+format, args...)
}
func (m *metrics) onMetrics(ctx *gin.Context) {
out := ""
data, err := m.pathManager.apiPathsList()
if err == nil && len(data.Items) != 0 {
for _, i := range data.Items {
var state string
if i.SourceReady {
state = "ready"
} else {
state = "notReady"
}
tags := "{name=\"" + i.Name + "\",state=\"" + state + "\"}"
out += metric("paths", tags, 1)
out += metric("paths_bytes_received", tags, int64(i.BytesReceived))
}
} else {
out += metric("paths", "", 0)
}
if !interfaceIsEmpty(m.hlsManager) {
data, err := m.hlsManager.apiMuxersList()
if err == nil && len(data.Items) != 0 {
for _, i := range data.Items {
tags := "{name=\"" + i.Path + "\"}"
out += metric("hls_muxers", tags, 1)
out += metric("hls_muxers_bytes_sent", tags, int64(i.BytesSent))
}
} else {
out += metric("hls_muxers", "", 0)
out += metric("hls_muxers_bytes_sent", "", 0)
}
}
if !interfaceIsEmpty(m.rtspServer) { //nolint:dupl
func() {
data, err := m.rtspServer.apiConnsList()
if err == nil && len(data.Items) != 0 {
for _, i := range data.Items {
tags := "{id=\"" + i.ID.String() + "\"}"
out += metric("rtsp_conns", tags, 1)
out += metric("rtsp_conns_bytes_received", tags, int64(i.BytesReceived))
out += metric("rtsp_conns_bytes_sent", tags, int64(i.BytesSent))
}
} else {
out += metric("rtsp_conns", "", 0)
out += metric("rtsp_conns_bytes_received", "", 0)
out += metric("rtsp_conns_bytes_sent", "", 0)
}
}()
func() {
data, err := m.rtspServer.apiSessionsList()
if err == nil && len(data.Items) != 0 {
for _, i := range data.Items {
tags := "{id=\"" + i.ID.String() + "\",state=\"" + string(i.State) + "\"}"
out += metric("rtsp_sessions", tags, 1)
out += metric("rtsp_sessions_bytes_received", tags, int64(i.BytesReceived))
out += metric("rtsp_sessions_bytes_sent", tags, int64(i.BytesSent))
}
} else {
out += metric("rtsp_sessions", "", 0)
out += metric("rtsp_sessions_bytes_received", "", 0)
out += metric("rtsp_sessions_bytes_sent", "", 0)
}
}()
}
if !interfaceIsEmpty(m.rtspsServer) { //nolint:dupl
func() {
data, err := m.rtspsServer.apiConnsList()
if err == nil && len(data.Items) != 0 {
for _, i := range data.Items {
tags := "{id=\"" + i.ID.String() + "\"}"
out += metric("rtsps_conns", tags, 1)
out += metric("rtsps_conns_bytes_received", tags, int64(i.BytesReceived))
out += metric("rtsps_conns_bytes_sent", tags, int64(i.BytesSent))
}
} else {
out += metric("rtsps_conns", "", 0)
out += metric("rtsps_conns_bytes_received", "", 0)
out += metric("rtsps_conns_bytes_sent", "", 0)
}
}()
func() {
data, err := m.rtspsServer.apiSessionsList()
if err == nil && len(data.Items) != 0 {
for _, i := range data.Items {
tags := "{id=\"" + i.ID.String() + "\",state=\"" + string(i.State) + "\"}"
out += metric("rtsps_sessions", tags, 1)
out += metric("rtsps_sessions_bytes_received", tags, int64(i.BytesReceived))
out += metric("rtsps_sessions_bytes_sent", tags, int64(i.BytesSent))
}
} else {
out += metric("rtsps_sessions", "", 0)
out += metric("rtsps_sessions_bytes_received", "", 0)
out += metric("rtsps_sessions_bytes_sent", "", 0)
}
}()
}
if !interfaceIsEmpty(m.rtmpServer) {
data, err := m.rtmpServer.apiConnsList()
if err == nil && len(data.Items) != 0 {
for _, i := range data.Items {
tags := "{id=\"" + i.ID.String() + "\",state=\"" + string(i.State) + "\"}"
out += metric("rtmp_conns", tags, 1)
out += metric("rtmp_conns_bytes_received", tags, int64(i.BytesReceived))
out += metric("rtmp_conns_bytes_sent", tags, int64(i.BytesSent))
}
} else {
out += metric("rtmp_conns", "", 0)
out += metric("rtmp_conns_bytes_received", "", 0)
out += metric("rtmp_conns_bytes_sent", "", 0)
}
}
if !interfaceIsEmpty(m.webRTCManager) {
data, err := m.webRTCManager.apiSessionsList()
if err == nil && len(data.Items) != 0 {
for _, i := range data.Items {
tags := "{id=\"" + i.ID.String() + "\"}"
out += metric("webrtc_sessions", tags, 1)
out += metric("webrtc_sessions_bytes_received", tags, int64(i.BytesReceived))
out += metric("webrtc_sessions_bytes_sent", tags, int64(i.BytesSent))
}
} else {
out += metric("webrtc_sessions", "", 0)
out += metric("webrtc_sessions_bytes_received", "", 0)
out += metric("webrtc_sessions_bytes_sent", "", 0)
}
}
ctx.Writer.WriteHeader(http.StatusOK)
io.WriteString(ctx.Writer, out)
}
// pathManagerSet is called by pathManager.
func (m *metrics) pathManagerSet(s apiPathManager) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.pathManager = s
}
// setHLSManager is called by hlsManager.
func (m *metrics) setHLSManager(s apiHLSManager) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.hlsManager = s
}
// rtspServerSet is called by rtspServer (plain).
func (m *metrics) rtspServerSet(s apiRTSPServer) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.rtspServer = s
}
// rtspsServerSet is called by rtspServer (tls).
func (m *metrics) rtspsServerSet(s apiRTSPServer) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.rtspsServer = s
}
// rtmpServerSet is called by rtmpServer.
func (m *metrics) rtmpServerSet(s apiRTMPServer) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.rtmpServer = s
}
// webRTCManagerSet is called by webRTCManager.
func (m *metrics) webRTCManagerSet(s apiWebRTCManager) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.webRTCManager = s
}

376
internal/core/metrics_test.go

@ -1,48 +1,78 @@
package core package core
import ( import (
"bufio"
"context"
"crypto/tls" "crypto/tls"
"io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"sync"
"testing" "testing"
"time" "time"
"github.com/bluenviron/gortsplib/v3" "github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v3/pkg/formats" "github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/gortsplib/v3/pkg/media" "github.com/bluenviron/mediacommon/pkg/formats/mpegts"
srt "github.com/datarhei/gosrt"
"github.com/pion/rtp"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/rtmp" "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) { func TestMetrics(t *testing.T) {
serverCertFpath, err := writeTempFile(serverCert) serverCertFpath, err := test.CreateTempFile(test.TLSCertPub)
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(serverCertFpath) defer os.Remove(serverCertFpath)
serverKeyFpath, err := writeTempFile(serverKey) serverKeyFpath, err := test.CreateTempFile(test.TLSCertKey)
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(serverKeyFpath) defer os.Remove(serverKeyFpath)
p, ok := newInstance("hlsAlwaysRemux: yes\n" + p, ok := newInstance("api: yes\n" +
"hlsAlwaysRemux: yes\n" +
"metrics: yes\n" + "metrics: yes\n" +
"webrtcServerCert: " + serverCertFpath + "\n" + "webrtcServerCert: " + serverCertFpath + "\n" +
"webrtcServerKey: " + serverKeyFpath + "\n" + "webrtcServerKey: " + serverKeyFpath + "\n" +
"encryption: optional\n" + "encryption: optional\n" +
"serverCert: " + serverCertFpath + "\n" + "serverCert: " + serverCertFpath + "\n" +
"serverKey: " + serverKeyFpath + "\n" + "serverKey: " + serverKeyFpath + "\n" +
"rtmpEncryption: optional\n" +
"rtmpServerCert: " + serverCertFpath + "\n" +
"rtmpServerKey: " + serverKeyFpath + "\n" +
"paths:\n" + "paths:\n" +
" all:\n") " all_others:\n")
require.Equal(t, true, ok) require.Equal(t, true, ok)
defer p.Close() defer p.Close()
hc := &http.Client{Transport: &http.Transport{}} tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
bo := httpPullFile(t, hc, "http://localhost:9998/metrics") t.Run("initial", func(t *testing.T) {
bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
require.Equal(t, `paths 0 require.Equal(t, `paths 0
hls_muxers 0 hls_muxers 0
hls_muxers_bytes_sent 0 hls_muxers_bytes_sent 0
rtsp_conns 0 rtsp_conns 0
@ -60,84 +90,274 @@ rtsps_sessions_bytes_sent 0
rtmp_conns 0 rtmp_conns 0
rtmp_conns_bytes_received 0 rtmp_conns_bytes_received 0
rtmp_conns_bytes_sent 0 rtmp_conns_bytes_sent 0
rtmps_conns 0
rtmps_conns_bytes_received 0
rtmps_conns_bytes_sent 0
srt_conns 0
srt_conns_bytes_received 0
srt_conns_bytes_sent 0
webrtc_sessions 0 webrtc_sessions 0
webrtc_sessions_bytes_received 0 webrtc_sessions_bytes_received 0
webrtc_sessions_bytes_sent 0 webrtc_sessions_bytes_sent 0
`, string(bo)) `, string(bo))
})
medi := testMediaH264 t.Run("with data", func(t *testing.T) {
terminate := make(chan struct{})
var wg sync.WaitGroup
wg.Add(6)
source := gortsplib.Client{} go func() {
err = source.StartRecording("rtsp://localhost:8554/rtsp_path", defer wg.Done()
media.Medias{medi}) source := gortsplib.Client{}
require.NoError(t, err) err := source.StartRecording("rtsp://localhost:8554/rtsp_path",
defer source.Close() &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer source.Close()
<-terminate
}()
source2 := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}} go func() {
err = source2.StartRecording("rtsps://localhost:8322/rtsps_path", defer wg.Done()
media.Medias{medi}) source2 := gortsplib.Client{TLSConfig: &tls.Config{InsecureSkipVerify: true}}
require.NoError(t, err) err := source2.StartRecording("rtsps://localhost:8322/rtsps_path",
defer source2.Close() &description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer source2.Close()
<-terminate
}()
u, err := url.Parse("rtmp://localhost:1935/rtmp_path") go func() {
require.NoError(t, err) defer wg.Done()
u, err := url.Parse("rtmp://localhost:1935/rtmp_path")
require.NoError(t, err)
nconn, err := net.Dial("tcp", u.Host) nconn, err := net.Dial("tcp", u.Host)
require.NoError(t, err) require.NoError(t, err)
defer nconn.Close() defer nconn.Close()
conn, err := rtmp.NewClientConn(nconn, u, true) conn, err := rtmp.NewClientConn(nconn, u, true)
require.NoError(t, err) require.NoError(t, err)
videoTrack := &formats.H264{ _, err = rtmp.NewWriter(conn, test.FormatH264, nil)
PayloadTyp: 96, require.NoError(t, err)
SPS: []byte{ // 1920x1080 baseline <-terminate
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,
}
_, err = rtmp.NewWriter(conn, videoTrack, nil) go func() {
require.NoError(t, err) defer wg.Done()
u, err := url.Parse("rtmp://localhost:1936/rtmps_path")
require.NoError(t, err)
nconn, err := tls.Dial("tcp", u.Host, &tls.Config{InsecureSkipVerify: true})
require.NoError(t, err)
defer nconn.Close() //nolint:errcheck
conn, err := rtmp.NewClientConn(nconn, u, true)
require.NoError(t, err)
_, err = rtmp.NewWriter(conn, test.FormatH264, nil)
require.NoError(t, err)
<-terminate
}()
go func() {
defer wg.Done()
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,
URL: su,
Log: test.NilLogger{},
}
tracks, err := s.Publish(context.Background(), test.MediaH264.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)
<-terminate
}()
go func() {
defer wg.Done()
srtConf := srt.DefaultConfig()
address, err := srtConf.UnmarshalURL("srt://localhost:8890?streamid=publish:srt_path")
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{
test.FormatH264.SPS,
test.FormatH264.PPS,
{0x05, 1}, // IDR
})
require.NoError(t, err)
err = bw.Flush()
require.NoError(t, err)
<-terminate
}()
time.Sleep(500 * time.Millisecond)
bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
require.Regexp(t,
`^paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths_bytes_sent\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths_bytes_sent\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths_bytes_sent\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths_bytes_sent\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths_bytes_sent\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`paths_bytes_sent\{name=".*?",state="ready"\} [0-9]+`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} 0`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} 0`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} 0`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} 0`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} 0`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} 0`+"\n"+
`rtsp_conns\{id=".*?"\} 1`+"\n"+
`rtsp_conns_bytes_received\{id=".*?"\} [0-9]+`+"\n"+
`rtsp_conns_bytes_sent\{id=".*?"\} [0-9]+`+"\n"+
`rtsp_sessions\{id=".*?",state="publish"\} 1`+"\n"+
`rtsp_sessions_bytes_received\{id=".*?",state="publish"\} 0`+"\n"+
`rtsp_sessions_bytes_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`rtsps_conns\{id=".*?"\} 1`+"\n"+
`rtsps_conns_bytes_received\{id=".*?"\} [0-9]+`+"\n"+
`rtsps_conns_bytes_sent\{id=".*?"\} [0-9]+`+"\n"+
`rtsps_sessions\{id=".*?",state="publish"\} 1`+"\n"+
`rtsps_sessions_bytes_received\{id=".*?",state="publish"\} 0`+"\n"+
`rtsps_sessions_bytes_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`rtmp_conns\{id=".*?",state="publish"\} 1`+"\n"+
`rtmp_conns_bytes_received\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`rtmp_conns_bytes_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`rtmps_conns\{id=".*?",state="publish"\} 1`+"\n"+
`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"+
`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"+
"$",
string(bo))
close(terminate)
wg.Wait()
})
t.Run("servers deleted", func(t *testing.T) {
httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/global/patch", map[string]interface{}{
"rtsp": false,
"rtmp": false,
"srt": false,
"hls": false,
"webrtc": false,
}, nil)
time.Sleep(500 * time.Millisecond)
bo := httpPullFile(t, hc, "http://localhost:9998/metrics")
time.Sleep(500 * time.Millisecond) require.Equal(t, "paths 0\n", string(bo))
})
bo = httpPullFile(t, hc, "http://localhost:9998/metrics")
require.Regexp(t,
`^paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} 0`+"\n"+
`paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} 0`+"\n"+
`paths\{name=".*?",state="ready"\} 1`+"\n"+
`paths_bytes_received\{name=".*?",state="ready"\} 0`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} [0-9]+`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} [0-9]+`+"\n"+
`hls_muxers\{name=".*?"\} 1`+"\n"+
`hls_muxers_bytes_sent\{name=".*?"\} [0-9]+`+"\n"+
`rtsp_conns\{id=".*?"\} 1`+"\n"+
`rtsp_conns_bytes_received\{id=".*?"\} [0-9]+`+"\n"+
`rtsp_conns_bytes_sent\{id=".*?"\} [0-9]+`+"\n"+
`rtsp_sessions\{id=".*?",state="publish"\} 1`+"\n"+
`rtsp_sessions_bytes_received\{id=".*?",state="publish"\} 0`+"\n"+
`rtsp_sessions_bytes_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`rtsps_conns\{id=".*?"\} 1`+"\n"+
`rtsps_conns_bytes_received\{id=".*?"\} [0-9]+`+"\n"+
`rtsps_conns_bytes_sent\{id=".*?"\} [0-9]+`+"\n"+
`rtsps_sessions\{id=".*?",state="publish"\} 1`+"\n"+
`rtsps_sessions_bytes_received\{id=".*?",state="publish"\} 0`+"\n"+
`rtsps_sessions_bytes_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`rtmp_conns\{id=".*?",state="publish"\} 1`+"\n"+
`rtmp_conns_bytes_received\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`rtmp_conns_bytes_sent\{id=".*?",state="publish"\} [0-9]+`+"\n"+
`webrtc_sessions 0`+"\n"+
`webrtc_sessions_bytes_received 0`+"\n"+
`webrtc_sessions_bytes_sent 0`+"\n"+
"$",
string(bo))
} }

1122
internal/core/path.go

File diff suppressed because it is too large Load Diff

569
internal/core/path_manager.go

@ -6,57 +6,41 @@ import (
"sort" "sort"
"sync" "sync"
"github.com/bluenviron/mediamtx/internal/auth"
"github.com/bluenviron/mediamtx/internal/conf" "github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/defs"
"github.com/bluenviron/mediamtx/internal/externalcmd" "github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger" "github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/stream"
) )
func pathConfCanBeUpdated(oldPathConf *conf.PathConf, newPathConf *conf.PathConf) bool { func pathConfCanBeUpdated(oldPathConf *conf.Path, newPathConf *conf.Path) bool {
clone := oldPathConf.Clone() clone := oldPathConf.Clone()
clone.Record = newPathConf.Record
clone.RPICameraBrightness = newPathConf.RPICameraBrightness clone.RPICameraBrightness = newPathConf.RPICameraBrightness
clone.RPICameraContrast = newPathConf.RPICameraContrast clone.RPICameraContrast = newPathConf.RPICameraContrast
clone.RPICameraSaturation = newPathConf.RPICameraSaturation clone.RPICameraSaturation = newPathConf.RPICameraSaturation
clone.RPICameraSharpness = newPathConf.RPICameraSharpness clone.RPICameraSharpness = newPathConf.RPICameraSharpness
clone.RPICameraExposure = newPathConf.RPICameraExposure clone.RPICameraExposure = newPathConf.RPICameraExposure
clone.RPICameraAWB = newPathConf.RPICameraAWB clone.RPICameraAWB = newPathConf.RPICameraAWB
clone.RPICameraAWBGains = newPathConf.RPICameraAWBGains
clone.RPICameraDenoise = newPathConf.RPICameraDenoise clone.RPICameraDenoise = newPathConf.RPICameraDenoise
clone.RPICameraShutter = newPathConf.RPICameraShutter clone.RPICameraShutter = newPathConf.RPICameraShutter
clone.RPICameraMetering = newPathConf.RPICameraMetering clone.RPICameraMetering = newPathConf.RPICameraMetering
clone.RPICameraGain = newPathConf.RPICameraGain clone.RPICameraGain = newPathConf.RPICameraGain
clone.RPICameraEV = newPathConf.RPICameraEV clone.RPICameraEV = newPathConf.RPICameraEV
clone.RPICameraFPS = newPathConf.RPICameraFPS clone.RPICameraFPS = newPathConf.RPICameraFPS
clone.RPICameraIDRPeriod = newPathConf.RPICameraIDRPeriod
clone.RPICameraBitrate = newPathConf.RPICameraBitrate
return newPathConf.Equal(clone) return newPathConf.Equal(clone)
} }
func getConfForPath(pathConfs map[string]*conf.PathConf, name string) (string, *conf.PathConf, []string, error) { type pathManagerHLSServer interface {
err := conf.IsValidPathName(name) PathReady(defs.Path)
if err != nil { PathNotReady(defs.Path)
return "", nil, nil, fmt.Errorf("invalid path name: %s (%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 {
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 pathManagerHLSManager interface {
pathReady(*path)
pathNotReady(*path)
} }
type pathManagerParent interface { type pathManagerParent interface {
@ -64,82 +48,56 @@ type pathManagerParent interface {
} }
type pathManager struct { type pathManager struct {
externalAuthenticationURL string logLevel conf.LogLevel
rtspAddress string authManager *auth.Manager
authMethods conf.AuthMethods rtspAddress string
readTimeout conf.StringDuration readTimeout conf.StringDuration
writeTimeout conf.StringDuration writeTimeout conf.StringDuration
readBufferCount int writeQueueSize int
udpMaxPayloadSize int udpMaxPayloadSize int
pathConfs map[string]*conf.PathConf pathConfs map[string]*conf.Path
externalCmdPool *externalcmd.Pool externalCmdPool *externalcmd.Pool
metrics *metrics parent pathManagerParent
parent pathManagerParent
ctx context.Context ctx context.Context
ctxCancel func() ctxCancel func()
wg sync.WaitGroup wg sync.WaitGroup
hlsManager pathManagerHLSManager hlsManager pathManagerHLSServer
paths map[string]*path paths map[string]*path
pathsByConf map[string]map[*path]struct{} pathsByConf map[string]map[*path]struct{}
// in // in
chReloadConf chan map[string]*conf.PathConf chReloadConf chan map[string]*conf.Path
chClosePath chan *path chSetHLSServer chan pathManagerHLSServer
chPathReady chan *path chClosePath chan *path
chPathNotReady chan *path chPathReady chan *path
chGetConfForPath chan pathGetConfForPathReq chPathNotReady chan *path
chDescribe chan pathDescribeReq chFindPathConf chan defs.PathFindPathConfReq
chAddReader chan pathAddReaderReq chDescribe chan defs.PathDescribeReq
chAddPublisher chan pathAddPublisherReq chAddReader chan defs.PathAddReaderReq
chSetHLSManager chan pathManagerHLSManager chAddPublisher chan defs.PathAddPublisherReq
chAPIPathsList chan pathAPIPathsListReq chAPIPathsList chan pathAPIPathsListReq
chAPIPathsGet chan pathAPIPathsGetReq chAPIPathsGet chan pathAPIPathsGetReq
} }
func newPathManager( func (pm *pathManager) initialize() {
externalAuthenticationURL string,
rtspAddress string,
authMethods conf.AuthMethods,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
readBufferCount int,
udpMaxPayloadSize int,
pathConfs map[string]*conf.PathConf,
externalCmdPool *externalcmd.Pool,
metrics *metrics,
parent pathManagerParent,
) *pathManager {
ctx, ctxCancel := context.WithCancel(context.Background()) ctx, ctxCancel := context.WithCancel(context.Background())
pm := &pathManager{ pm.ctx = ctx
externalAuthenticationURL: externalAuthenticationURL, pm.ctxCancel = ctxCancel
rtspAddress: rtspAddress, pm.paths = make(map[string]*path)
authMethods: authMethods, pm.pathsByConf = make(map[string]map[*path]struct{})
readTimeout: readTimeout, pm.chReloadConf = make(chan map[string]*conf.Path)
writeTimeout: writeTimeout, pm.chSetHLSServer = make(chan pathManagerHLSServer)
readBufferCount: readBufferCount, pm.chClosePath = make(chan *path)
udpMaxPayloadSize: udpMaxPayloadSize, pm.chPathReady = make(chan *path)
pathConfs: pathConfs, pm.chPathNotReady = make(chan *path)
externalCmdPool: externalCmdPool, pm.chFindPathConf = make(chan defs.PathFindPathConfReq)
metrics: metrics, pm.chDescribe = make(chan defs.PathDescribeReq)
parent: parent, pm.chAddReader = make(chan defs.PathAddReaderReq)
ctx: ctx, pm.chAddPublisher = make(chan defs.PathAddPublisherReq)
ctxCancel: ctxCancel, pm.chAPIPathsList = make(chan pathAPIPathsListReq)
paths: make(map[string]*path), pm.chAPIPathsGet = make(chan pathAPIPathsGetReq)
pathsByConf: make(map[string]map[*path]struct{}),
chReloadConf: make(chan map[string]*conf.PathConf),
chClosePath: make(chan *path),
chPathReady: make(chan *path),
chPathNotReady: make(chan *path),
chGetConfForPath: make(chan pathGetConfForPathReq),
chDescribe: make(chan pathDescribeReq),
chAddReader: make(chan pathAddReaderReq),
chAddPublisher: make(chan pathAddPublisherReq),
chSetHLSManager: make(chan pathManagerHLSManager),
chAPIPathsList: make(chan pathAPIPathsListReq),
chAPIPathsGet: make(chan pathAPIPathsGetReq),
}
for pathConfName, pathConf := range pm.pathConfs { for pathConfName, pathConf := range pm.pathConfs {
if pathConf.Regexp == nil { if pathConf.Regexp == nil {
@ -147,16 +105,10 @@ func newPathManager(
} }
} }
if pm.metrics != nil {
pm.metrics.pathManagerSet(pm)
}
pm.Log(logger.Debug, "path manager created") pm.Log(logger.Debug, "path manager created")
pm.wg.Add(1) pm.wg.Add(1)
go pm.run() go pm.run()
return pm
} }
func (pm *pathManager) close() { func (pm *pathManager) close() {
@ -165,7 +117,7 @@ func (pm *pathManager) close() {
pm.wg.Wait() pm.wg.Wait()
} }
// Log is the main logging function. // Log implements logger.Writer.
func (pm *pathManager) Log(level logger.Level, format string, args ...interface{}) { func (pm *pathManager) Log(level logger.Level, format string, args ...interface{}) {
pm.parent.Log(level, format, args...) pm.parent.Log(level, format, args...)
} }
@ -176,191 +128,233 @@ func (pm *pathManager) run() {
outer: outer:
for { for {
select { select {
case newPathConfs := <-pm.chReloadConf: case newPaths := <-pm.chReloadConf:
for confName, pathConf := range pm.pathConfs { pm.doReloadConf(newPaths)
if newPathConf, ok := newPathConfs[confName]; ok {
// configuration has changed
if !newPathConf.Equal(pathConf) {
if pathConfCanBeUpdated(pathConf, newPathConf) { // paths associated with the configuration can be updated
for pa := range pm.pathsByConf[confName] {
go pa.reloadConf(newPathConf)
}
} else { // paths associated with the configuration must be recreated
for pa := range pm.pathsByConf[confName] {
pm.removePath(pa)
pa.close()
pa.wait() // avoid conflicts between sources
}
}
}
} else {
// configuration has been deleted, remove associated paths
for pa := range pm.pathsByConf[confName] {
pm.removePath(pa)
pa.close()
pa.wait() // avoid conflicts between sources
}
}
}
pm.pathConfs = newPathConfs case m := <-pm.chSetHLSServer:
pm.doSetHLSServer(m)
// add new paths
for pathConfName, pathConf := range pm.pathConfs {
if _, ok := pm.paths[pathConfName]; !ok && pathConf.Regexp == nil {
pm.createPath(pathConfName, pathConf, pathConfName, nil)
}
}
case pa := <-pm.chClosePath: case pa := <-pm.chClosePath:
if pmpa, ok := pm.paths[pa.name]; !ok || pmpa != pa { pm.doClosePath(pa)
continue
}
pm.removePath(pa)
case pa := <-pm.chPathReady: case pa := <-pm.chPathReady:
if pm.hlsManager != nil { pm.doPathReady(pa)
pm.hlsManager.pathReady(pa)
}
case pa := <-pm.chPathNotReady: case pa := <-pm.chPathNotReady:
if pm.hlsManager != nil { pm.doPathNotReady(pa)
pm.hlsManager.pathNotReady(pa)
}
case req := <-pm.chGetConfForPath: case req := <-pm.chFindPathConf:
_, pathConf, _, err := getConfForPath(pm.pathConfs, req.name) pm.doFindPathConf(req)
if err != nil {
req.res <- pathGetConfForPathRes{err: err}
continue
}
err = doAuthentication(pm.externalAuthenticationURL, pm.authMethods, case req := <-pm.chDescribe:
req.name, pathConf, req.publish, req.credentials) pm.doDescribe(req)
if err != nil {
req.res <- pathGetConfForPathRes{err: err}
continue
}
req.res <- pathGetConfForPathRes{conf: pathConf} case req := <-pm.chAddReader:
pm.doAddReader(req)
case req := <-pm.chDescribe: case req := <-pm.chAddPublisher:
pathConfName, pathConf, pathMatches, err := getConfForPath(pm.pathConfs, req.pathName) pm.doAddPublisher(req)
if err != nil {
req.res <- pathDescribeRes{err: err}
continue
}
err = doAuthentication(pm.externalAuthenticationURL, pm.authMethods, req.pathName, pathConf, false, req.credentials) case req := <-pm.chAPIPathsList:
if err != nil { pm.doAPIPathsList(req)
req.res <- pathDescribeRes{err: err}
continue
}
// create path if it doesn't exist case req := <-pm.chAPIPathsGet:
if _, ok := pm.paths[req.pathName]; !ok { pm.doAPIPathsGet(req)
pm.createPath(pathConfName, pathConf, req.pathName, pathMatches)
}
req.res <- pathDescribeRes{path: pm.paths[req.pathName]} case <-pm.ctx.Done():
break outer
}
}
case req := <-pm.chAddReader: pm.ctxCancel()
pathConfName, pathConf, pathMatches, err := getConfForPath(pm.pathConfs, req.pathName) }
if err != nil {
req.res <- pathAddReaderRes{err: err}
continue
}
if !req.skipAuth { func (pm *pathManager) doReloadConf(newPaths map[string]*conf.Path) {
err = doAuthentication(pm.externalAuthenticationURL, pm.authMethods, req.pathName, pathConf, false, req.credentials) for confName, pathConf := range pm.pathConfs {
if err != nil { if newPath, ok := newPaths[confName]; ok {
req.res <- pathAddReaderRes{err: err} // configuration has changed
continue if !newPath.Equal(pathConf) {
if pathConfCanBeUpdated(pathConf, newPath) { // paths associated with the configuration can be updated
for pa := range pm.pathsByConf[confName] {
go pa.reloadConf(newPath)
}
} else { // paths associated with the configuration must be recreated
for pa := range pm.pathsByConf[confName] {
pm.removePath(pa)
pa.close()
pa.wait() // avoid conflicts between sources
}
} }
} }
} else {
// create path if it doesn't exist // configuration has been deleted, remove associated paths
if _, ok := pm.paths[req.pathName]; !ok { for pa := range pm.pathsByConf[confName] {
pm.createPath(pathConfName, pathConf, req.pathName, pathMatches) pm.removePath(pa)
pa.close()
pa.wait() // avoid conflicts between sources
} }
}
}
req.res <- pathAddReaderRes{path: pm.paths[req.pathName]} pm.pathConfs = newPaths
case req := <-pm.chAddPublisher: // add new paths
pathConfName, pathConf, pathMatches, err := getConfForPath(pm.pathConfs, req.pathName) for pathConfName, pathConf := range pm.pathConfs {
if err != nil { if _, ok := pm.paths[pathConfName]; !ok && pathConf.Regexp == nil {
req.res <- pathAddPublisherRes{err: err} pm.createPath(pathConfName, pathConf, pathConfName, nil)
continue }
} }
}
if !req.skipAuth { func (pm *pathManager) doSetHLSServer(m pathManagerHLSServer) {
err = doAuthentication(pm.externalAuthenticationURL, pm.authMethods, req.pathName, pathConf, true, req.credentials) pm.hlsManager = m
if err != nil { }
req.res <- pathAddPublisherRes{err: err}
continue
}
}
// create path if it doesn't exist func (pm *pathManager) doClosePath(pa *path) {
if _, ok := pm.paths[req.pathName]; !ok { if pmpa, ok := pm.paths[pa.name]; !ok || pmpa != pa {
pm.createPath(pathConfName, pathConf, req.pathName, pathMatches) return
} }
pm.removePath(pa)
}
req.res <- pathAddPublisherRes{path: pm.paths[req.pathName]} func (pm *pathManager) doPathReady(pa *path) {
if pm.hlsManager != nil {
pm.hlsManager.PathReady(pa)
}
}
case s := <-pm.chSetHLSManager: func (pm *pathManager) doPathNotReady(pa *path) {
pm.hlsManager = s if pm.hlsManager != nil {
pm.hlsManager.PathNotReady(pa)
}
}
case req := <-pm.chAPIPathsList: func (pm *pathManager) doFindPathConf(req defs.PathFindPathConfReq) {
paths := make(map[string]*path) _, pathConf, _, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
if err != nil {
req.Res <- defs.PathFindPathConfRes{Err: err}
return
}
for name, pa := range pm.paths { err = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
paths[name] = pa if err != nil {
} req.Res <- defs.PathFindPathConfRes{Err: err}
return
}
req.res <- pathAPIPathsListRes{paths: paths} req.Res <- defs.PathFindPathConfRes{Conf: pathConf}
}
case req := <-pm.chAPIPathsGet: func (pm *pathManager) doDescribe(req defs.PathDescribeReq) {
path, ok := pm.paths[req.name] pathConfName, pathConf, pathMatches, err := conf.FindPathConf(pm.pathConfs, req.AccessRequest.Name)
if !ok { if err != nil {
req.res <- pathAPIPathsGetRes{err: errAPINotFound} req.Res <- defs.PathDescribeRes{Err: err}
continue return
} }
req.res <- pathAPIPathsGetRes{path: path} err = pm.authManager.Authenticate(req.AccessRequest.ToAuthRequest())
if err != nil {
req.Res <- defs.PathDescribeRes{Err: err}
return
}
case <-pm.ctx.Done(): // create path if it doesn't exist
break outer if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
pm.createPath(pathConfName, pathConf, req.AccessRequest.Name, pathMatches)
}
req.Res <- defs.PathDescribeRes{Path: pm.paths[req.AccessRequest.Name]}
}
func (pm *pathManager) doAddReader(req defs.PathAddReaderReq) {
pathConfName, pathConf, pathMatches, err := conf.FindPathConf(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())
if err != nil {
req.Res <- defs.PathAddReaderRes{Err: err}
return
} }
} }
pm.ctxCancel() // create path if it doesn't exist
if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
pm.createPath(pathConfName, pathConf, req.AccessRequest.Name, pathMatches)
}
req.Res <- defs.PathAddReaderRes{Path: pm.paths[req.AccessRequest.Name]}
}
if pm.metrics != nil { func (pm *pathManager) doAddPublisher(req defs.PathAddPublisherReq) {
pm.metrics.pathManagerSet(nil) pathConfName, pathConf, pathMatches, err := conf.FindPathConf(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())
if err != nil {
req.Res <- defs.PathAddPublisherRes{Err: err}
return
}
} }
// create path if it doesn't exist
if _, ok := pm.paths[req.AccessRequest.Name]; !ok {
pm.createPath(pathConfName, pathConf, req.AccessRequest.Name, pathMatches)
}
req.Res <- defs.PathAddPublisherRes{Path: pm.paths[req.AccessRequest.Name]}
}
func (pm *pathManager) doAPIPathsList(req pathAPIPathsListReq) {
paths := make(map[string]*path)
for name, pa := range pm.paths {
paths[name] = pa
}
req.res <- pathAPIPathsListRes{paths: paths}
}
func (pm *pathManager) doAPIPathsGet(req pathAPIPathsGetReq) {
path, ok := pm.paths[req.name]
if !ok {
req.res <- pathAPIPathsGetRes{err: conf.ErrPathNotFound}
return
}
req.res <- pathAPIPathsGetRes{path: path}
} }
func (pm *pathManager) createPath( func (pm *pathManager) createPath(
pathConfName string, pathConfName string,
pathConf *conf.PathConf, pathConf *conf.Path,
name string, name string,
matches []string, matches []string,
) { ) {
pa := newPath( pa := &path{
pm.ctx, parentCtx: pm.ctx,
pm.rtspAddress, logLevel: pm.logLevel,
pm.readTimeout, rtspAddress: pm.rtspAddress,
pm.writeTimeout, readTimeout: pm.readTimeout,
pm.readBufferCount, writeTimeout: pm.writeTimeout,
pm.udpMaxPayloadSize, writeQueueSize: pm.writeQueueSize,
pathConfName, udpMaxPayloadSize: pm.udpMaxPayloadSize,
pathConf, confName: pathConfName,
name, conf: pathConf,
matches, name: name,
&pm.wg, matches: matches,
pm.externalCmdPool, wg: &pm.wg,
pm) externalCmdPool: pm.externalCmdPool,
parent: pm,
}
pa.initialize()
pm.paths[name] = pa pm.paths[name] = pa
@ -378,8 +372,8 @@ func (pm *pathManager) removePath(pa *path) {
delete(pm.paths, pa.name) delete(pm.paths, pa.name)
} }
// confReload is called by core. // ReloadPathConfs is called by core.
func (pm *pathManager) confReload(pathConfs map[string]*conf.PathConf) { func (pm *pathManager) ReloadPathConfs(pathConfs map[string]*conf.Path) {
select { select {
case pm.chReloadConf <- pathConfs: case pm.chReloadConf <- pathConfs:
case <-pm.ctx.Done(): case <-pm.ctx.Done():
@ -413,85 +407,86 @@ func (pm *pathManager) closePath(pa *path) {
} }
} }
// getConfForPath is called by a reader or publisher. // GetConfForPath is called by a reader or publisher.
func (pm *pathManager) getConfForPath(req pathGetConfForPathReq) pathGetConfForPathRes { func (pm *pathManager) FindPathConf(req defs.PathFindPathConfReq) (*conf.Path, error) {
req.res = make(chan pathGetConfForPathRes) req.Res = make(chan defs.PathFindPathConfRes)
select { select {
case pm.chGetConfForPath <- req: case pm.chFindPathConf <- req:
return <-req.res res := <-req.Res
return res.Conf, res.Err
case <-pm.ctx.Done(): case <-pm.ctx.Done():
return pathGetConfForPathRes{err: fmt.Errorf("terminated")} return nil, fmt.Errorf("terminated")
} }
} }
// describe is called by a reader or publisher. // Describe is called by a reader or publisher.
func (pm *pathManager) describe(req pathDescribeReq) pathDescribeRes { func (pm *pathManager) Describe(req defs.PathDescribeReq) defs.PathDescribeRes {
req.res = make(chan pathDescribeRes) req.Res = make(chan defs.PathDescribeRes)
select { select {
case pm.chDescribe <- req: case pm.chDescribe <- req:
res1 := <-req.res res1 := <-req.Res
if res1.err != nil { if res1.Err != nil {
return res1 return res1
} }
res2 := res1.path.describe(req) res2 := res1.Path.(*path).describe(req)
if res2.err != nil { if res2.Err != nil {
return res2 return res2
} }
res2.path = res1.path res2.Path = res1.Path
return res2 return res2
case <-pm.ctx.Done(): case <-pm.ctx.Done():
return pathDescribeRes{err: fmt.Errorf("terminated")} return defs.PathDescribeRes{Err: fmt.Errorf("terminated")}
} }
} }
// addPublisher is called by a publisher. // AddPublisher is called by a publisher.
func (pm *pathManager) addPublisher(req pathAddPublisherReq) pathAddPublisherRes { func (pm *pathManager) AddPublisher(req defs.PathAddPublisherReq) (defs.Path, error) {
req.res = make(chan pathAddPublisherRes) req.Res = make(chan defs.PathAddPublisherRes)
select { select {
case pm.chAddPublisher <- req: case pm.chAddPublisher <- req:
res := <-req.res res := <-req.Res
if res.err != nil { if res.Err != nil {
return res return nil, res.Err
} }
return res.path.addPublisher(req) return res.Path.(*path).addPublisher(req)
case <-pm.ctx.Done(): case <-pm.ctx.Done():
return pathAddPublisherRes{err: fmt.Errorf("terminated")} return nil, fmt.Errorf("terminated")
} }
} }
// addReader is called by a reader. // AddReader is called by a reader.
func (pm *pathManager) addReader(req pathAddReaderReq) pathAddReaderRes { func (pm *pathManager) AddReader(req defs.PathAddReaderReq) (defs.Path, *stream.Stream, error) {
req.res = make(chan pathAddReaderRes) req.Res = make(chan defs.PathAddReaderRes)
select { select {
case pm.chAddReader <- req: case pm.chAddReader <- req:
res := <-req.res res := <-req.Res
if res.err != nil { if res.Err != nil {
return res return nil, nil, res.Err
} }
return res.path.addReader(req) return res.Path.(*path).addReader(req)
case <-pm.ctx.Done(): case <-pm.ctx.Done():
return pathAddReaderRes{err: fmt.Errorf("terminated")} return nil, nil, fmt.Errorf("terminated")
} }
} }
// setHLSManager is called by hlsManager. // setHLSServer is called by hlsManager.
func (pm *pathManager) setHLSManager(s pathManagerHLSManager) { func (pm *pathManager) setHLSServer(s pathManagerHLSServer) {
select { select {
case pm.chSetHLSManager <- s: case pm.chSetHLSServer <- s:
case <-pm.ctx.Done(): case <-pm.ctx.Done():
} }
} }
// apiPathsList is called by api. // APIPathsList is called by api.
func (pm *pathManager) apiPathsList() (*apiPathsList, error) { func (pm *pathManager) APIPathsList() (*defs.APIPathList, error) {
req := pathAPIPathsListReq{ req := pathAPIPathsListReq{
res: make(chan pathAPIPathsListRes), res: make(chan pathAPIPathsListRes),
} }
@ -500,12 +495,12 @@ func (pm *pathManager) apiPathsList() (*apiPathsList, error) {
case pm.chAPIPathsList <- req: case pm.chAPIPathsList <- req:
res := <-req.res res := <-req.res
res.data = &apiPathsList{ res.data = &defs.APIPathList{
Items: []*apiPath{}, Items: []*defs.APIPath{},
} }
for _, pa := range res.paths { for _, pa := range res.paths {
item, err := pa.apiPathsGet(pathAPIPathsGetReq{}) item, err := pa.APIPathsGet(pathAPIPathsGetReq{})
if err == nil { if err == nil {
res.data.Items = append(res.data.Items, item) res.data.Items = append(res.data.Items, item)
} }
@ -522,8 +517,8 @@ func (pm *pathManager) apiPathsList() (*apiPathsList, error) {
} }
} }
// apiPathsGet is called by api. // APIPathsGet is called by api.
func (pm *pathManager) apiPathsGet(name string) (*apiPath, error) { func (pm *pathManager) APIPathsGet(name string) (*defs.APIPath, error) {
req := pathAPIPathsGetReq{ req := pathAPIPathsGetReq{
name: name, name: name,
res: make(chan pathAPIPathsGetRes), res: make(chan pathAPIPathsGetRes),
@ -536,7 +531,7 @@ func (pm *pathManager) apiPathsGet(name string) (*apiPath, error) {
return nil, res.err return nil, res.err
} }
data, err := res.path.apiPathsGet(req) data, err := res.path.APIPathsGet(req)
return data, err return data, err
case <-pm.ctx.Done(): case <-pm.ctx.Done():

239
internal/core/path_manager_test.go

@ -2,20 +2,11 @@ package core
import ( import (
"bufio" "bufio"
"fmt"
"net" "net"
"os"
"os/exec"
"path/filepath"
"testing" "testing"
"time"
"github.com/bluenviron/gortsplib/v3" "github.com/bluenviron/gortsplib/v4/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/base" "github.com/bluenviron/gortsplib/v4/pkg/headers"
"github.com/bluenviron/gortsplib/v3/pkg/headers"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/gortsplib/v3/pkg/sdp"
"github.com/bluenviron/gortsplib/v3/pkg/url"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -23,7 +14,7 @@ func TestPathAutoDeletion(t *testing.T) {
for _, ca := range []string{"describe", "setup"} { for _, ca := range []string{"describe", "setup"} {
t.Run(ca, func(t *testing.T) { t.Run(ca, func(t *testing.T) {
p, ok := newInstance("paths:\n" + p, ok := newInstance("paths:\n" +
" all:\n") " all_others:\n")
require.Equal(t, true, ok) require.Equal(t, true, ok)
defer p.Close() defer p.Close()
@ -34,7 +25,7 @@ func TestPathAutoDeletion(t *testing.T) {
br := bufio.NewReader(conn) br := bufio.NewReader(conn)
if ca == "describe" { if ca == "describe" {
u, err := url.Parse("rtsp://localhost:8554/mypath") u, err := base.ParseURL("rtsp://localhost:8554/mypath")
require.NoError(t, err) require.NoError(t, err)
byts, _ := base.Request{ byts, _ := base.Request{
@ -52,7 +43,7 @@ func TestPathAutoDeletion(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, base.StatusNotFound, res.StatusCode) require.Equal(t, base.StatusNotFound, res.StatusCode)
} else { } else {
u, err := url.Parse("rtsp://localhost:8554/mypath/trackID=0") u, err := base.ParseURL("rtsp://localhost:8554/mypath/trackID=0")
require.NoError(t, err) require.NoError(t, err)
byts, _ := base.Request{ byts, _ := base.Request{
@ -84,228 +75,10 @@ func TestPathAutoDeletion(t *testing.T) {
} }
}() }()
data, err := p.pathManager.apiPathsList() data, err := p.pathManager.APIPathsList()
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, 0, len(data.Items)) require.Equal(t, 0, len(data.Items))
}) })
} }
} }
func TestPathRunOnDemand(t *testing.T) {
doneFile := filepath.Join(os.TempDir(), "ondemand_done")
srcFile := filepath.Join(os.TempDir(), "ondemand.go")
err := os.WriteFile(srcFile, []byte(`
package main
import (
"os"
"os/signal"
"syscall"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
)
func main() {
if os.Getenv("G1") != "on" {
panic("environment not set")
}
medi := &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{&formats.H264{
PayloadTyp: 96,
SPS: []byte{0x01, 0x02, 0x03, 0x04},
PPS: []byte{0x01, 0x02, 0x03, 0x04},
PacketizationMode: 1,
}},
}
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:" + os.Getenv("RTSP_PORT") + "/" + os.Getenv("MTX_PATH"),
media.Medias{medi})
if err != nil {
panic(err)
}
defer source.Close()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
<-c
err = os.WriteFile("`+doneFile+`", []byte(""), 0644)
if err != nil {
panic(err)
}
}
`), 0o644)
require.NoError(t, err)
execFile := filepath.Join(os.TempDir(), "ondemand_cmd")
cmd := exec.Command("go", "build", "-o", execFile, srcFile)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
require.NoError(t, err)
defer os.Remove(execFile)
os.Remove(srcFile)
for _, ca := range []string{"describe", "setup", "describe and setup"} {
t.Run(ca, func(t *testing.T) {
defer os.Remove(doneFile)
p1, ok := newInstance(fmt.Sprintf("rtmp: no\n"+
"hls: no\n"+
"webrtc: no\n"+
"paths:\n"+
" '~^(on)demand$':\n"+
" runOnDemand: %s\n"+
" runOnDemandCloseAfter: 1s\n", execFile))
require.Equal(t, true, ok)
defer p1.Close()
var control string
func() {
conn, err := net.Dial("tcp", "localhost:8554")
require.NoError(t, err)
defer conn.Close()
br := bufio.NewReader(conn)
if ca == "describe" || ca == "describe and setup" {
u, err := url.Parse("rtsp://localhost:8554/ondemand")
require.NoError(t, err)
byts, _ := base.Request{
Method: base.Describe,
URL: u,
Header: base.Header{
"CSeq": base.HeaderValue{"1"},
},
}.Marshal()
_, err = conn.Write(byts)
require.NoError(t, err)
var res base.Response
err = res.Unmarshal(br)
require.NoError(t, err)
require.Equal(t, base.StatusOK, res.StatusCode)
var desc sdp.SessionDescription
err = desc.Unmarshal(res.Body)
require.NoError(t, err)
control, _ = desc.MediaDescriptions[0].Attribute("control")
} else {
control = "rtsp://localhost:8554/ondemand/"
}
if ca == "setup" || ca == "describe and setup" {
u, err := url.Parse(control)
require.NoError(t, err)
byts, _ := base.Request{
Method: base.Setup,
URL: u,
Header: base.Header{
"CSeq": base.HeaderValue{"2"},
"Transport": headers.Transport{
Mode: func() *headers.TransportMode {
v := headers.TransportModePlay
return &v
}(),
Protocol: headers.TransportProtocolTCP,
InterleavedIDs: &[2]int{0, 1},
}.Marshal(),
},
}.Marshal()
_, err = conn.Write(byts)
require.NoError(t, err)
var res base.Response
err = res.Unmarshal(br)
require.NoError(t, err)
require.Equal(t, base.StatusOK, res.StatusCode)
}
}()
for {
_, err := os.Stat(doneFile)
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
})
}
}
func TestPathRunOnReady(t *testing.T) {
doneFile := filepath.Join(os.TempDir(), "onready_done")
defer os.Remove(doneFile)
p, ok := newInstance(fmt.Sprintf("rtmp: no\n"+
"hls: no\n"+
"webrtc: no\n"+
"paths:\n"+
" test:\n"+
" runOnReady: touch %s\n",
doneFile))
require.Equal(t, true, ok)
defer p.Close()
medi := testMediaH264
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://localhost:8554/test",
media.Medias{medi})
require.NoError(t, err)
defer c.Close()
time.Sleep(1 * time.Second)
_, err = os.Stat(doneFile)
require.NoError(t, err)
}
func TestPathMaxReaders(t *testing.T) {
p, ok := newInstance("paths:\n" +
" all:\n" +
" maxReaders: 1\n")
require.Equal(t, true, ok)
defer p.Close()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/mystream",
media.Medias{testMediaH264})
require.NoError(t, err)
defer source.Close()
for i := 0; i < 2; i++ {
reader := gortsplib.Client{}
u, err := url.Parse("rtsp://127.0.0.1:8554/mystream")
require.NoError(t, err)
err = reader.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer reader.Close()
medias, baseURL, _, err := reader.Describe(u)
require.NoError(t, err)
err = reader.SetupAll(medias, baseURL)
if i != 1 {
require.NoError(t, err)
} else {
require.Error(t, err)
}
}
}

797
internal/core/path_test.go

@ -0,0 +1,797 @@
package core
import (
"bufio"
"context"
"fmt"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"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/headers"
"github.com/bluenviron/gortsplib/v4/pkg/sdp"
srt "github.com/datarhei/gosrt"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
"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 = `
package main
import (
"os"
"os/signal"
"syscall"
"github.com/bluenviron/gortsplib/v4"
"github.com/bluenviron/gortsplib/v4/pkg/description"
"github.com/bluenviron/gortsplib/v4/pkg/format"
)
func main() {
if os.Getenv("MTX_PATH") != "ondemand" ||
os.Getenv("MTX_QUERY") != "param=value" ||
os.Getenv("G1") != "on" {
panic("environment not set")
}
medi := &description.Media{
Type: description.MediaTypeVideo,
Formats: []format.Format{&format.H264{
PayloadTyp: 96,
SPS: []byte{
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{0x01, 0x02, 0x03, 0x04},
PacketizationMode: 1,
}},
}
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:" + os.Getenv("RTSP_PORT") + "/" + os.Getenv("MTX_PATH"),
&description.Session{Medias: []*description.Media{medi}})
if err != nil {
panic(err)
}
defer source.Close()
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
<-c
err = os.WriteFile("ON_DEMAND_FILE", []byte(""), 0644)
if err != nil {
panic(err)
}
}
`
type testServer struct {
onDescribe func(*gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error)
onSetup func(*gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error)
onPlay func(*gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error)
}
func (sh *testServer) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
return sh.onDescribe(ctx)
}
func (sh *testServer) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
return sh.onSetup(ctx)
}
func (sh *testServer) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
return sh.onPlay(ctx)
}
var _ defs.Path = &path{}
func TestPathRunOnDemand(t *testing.T) {
onDemandFile := filepath.Join(os.TempDir(), "ondemand")
onUnDemandFile := filepath.Join(os.TempDir(), "onundemand")
srcFile := filepath.Join(os.TempDir(), "ondemand.go")
err := os.WriteFile(srcFile,
[]byte(strings.ReplaceAll(runOnDemandSampleScript, "ON_DEMAND_FILE", onDemandFile)), 0o644)
require.NoError(t, err)
execFile := filepath.Join(os.TempDir(), "ondemand_cmd")
cmd := exec.Command("go", "build", "-o", execFile, srcFile)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
require.NoError(t, err)
defer os.Remove(execFile)
os.Remove(srcFile)
for _, ca := range []string{"describe", "setup", "describe and setup"} {
t.Run(ca, func(t *testing.T) {
defer os.Remove(onDemandFile)
defer os.Remove(onUnDemandFile)
p1, ok := newInstance(fmt.Sprintf("rtmp: no\n"+
"hls: no\n"+
"webrtc: no\n"+
"paths:\n"+
" '~^(on)demand$':\n"+
" runOnDemand: %s\n"+
" runOnDemandCloseAfter: 1s\n"+
" runOnUnDemand: touch %s\n", execFile, onUnDemandFile))
require.Equal(t, true, ok)
defer p1.Close()
var control string
func() {
conn, err := net.Dial("tcp", "localhost:8554")
require.NoError(t, err)
defer conn.Close()
br := bufio.NewReader(conn)
if ca == "describe" || ca == "describe and setup" {
u, err := base.ParseURL("rtsp://localhost:8554/ondemand?param=value")
require.NoError(t, err)
byts, _ := base.Request{
Method: base.Describe,
URL: u,
Header: base.Header{
"CSeq": base.HeaderValue{"1"},
},
}.Marshal()
_, err = conn.Write(byts)
require.NoError(t, err)
var res base.Response
err = res.Unmarshal(br)
require.NoError(t, err)
require.Equal(t, base.StatusOK, res.StatusCode)
var desc sdp.SessionDescription
err = desc.Unmarshal(res.Body)
require.NoError(t, err)
control, _ = desc.MediaDescriptions[0].Attribute("control")
} else {
control = "rtsp://localhost:8554/ondemand?param=value/"
}
if ca == "setup" || ca == "describe and setup" {
u, err := base.ParseURL(control)
require.NoError(t, err)
byts, _ := base.Request{
Method: base.Setup,
URL: u,
Header: base.Header{
"CSeq": base.HeaderValue{"2"},
"Transport": headers.Transport{
Mode: func() *headers.TransportMode {
v := headers.TransportModePlay
return &v
}(),
Protocol: headers.TransportProtocolTCP,
InterleavedIDs: &[2]int{0, 1},
}.Marshal(),
},
}.Marshal()
_, err = conn.Write(byts)
require.NoError(t, err)
var res base.Response
err = res.Unmarshal(br)
require.NoError(t, err)
require.Equal(t, base.StatusOK, res.StatusCode)
}
}()
for {
_, err := os.Stat(onUnDemandFile)
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
_, err := os.Stat(onDemandFile)
require.NoError(t, err)
})
}
}
func TestPathRunOnConnect(t *testing.T) {
for _, ca := range []string{"rtsp", "rtmp", "srt"} {
t.Run(ca, func(t *testing.T) {
onConnectFile := filepath.Join(os.TempDir(), "onconnect")
defer os.Remove(onConnectFile)
onDisconnectFile := filepath.Join(os.TempDir(), "ondisconnect")
defer os.Remove(onDisconnectFile)
func() {
p, ok := newInstance(fmt.Sprintf(
"paths:\n"+
" test:\n"+
"runOnConnect: touch %s\n"+
"runOnDisconnect: touch %s\n",
onConnectFile, onDisconnectFile))
require.Equal(t, true, ok)
defer p.Close()
switch ca {
case "rtsp":
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://localhost:8554/test",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer c.Close()
case "rtmp":
u, err := url.Parse("rtmp://127.0.0.1:1935/test")
require.NoError(t, err)
nconn, err := net.Dial("tcp", u.Host)
require.NoError(t, err)
defer nconn.Close()
_, err = rtmp.NewClientConn(nconn, u, true)
require.NoError(t, err)
case "srt":
conf := srt.DefaultConfig()
address, err := conf.UnmarshalURL("srt://localhost:8890?streamid=publish:test")
require.NoError(t, err)
err = conf.Validate()
require.NoError(t, err)
c, err := srt.Dial("srt", address, conf)
require.NoError(t, err)
defer c.Close()
}
time.Sleep(500 * time.Millisecond)
}()
_, err := os.Stat(onConnectFile)
require.NoError(t, err)
_, err = os.Stat(onDisconnectFile)
require.NoError(t, err)
})
}
}
func TestPathRunOnReady(t *testing.T) {
onReadyFile := filepath.Join(os.TempDir(), "onready")
defer os.Remove(onReadyFile)
onNotReadyFile := filepath.Join(os.TempDir(), "onunready")
defer os.Remove(onNotReadyFile)
func() {
p, ok := newInstance(fmt.Sprintf("rtmp: no\n"+
"hls: no\n"+
"webrtc: no\n"+
"paths:\n"+
" test:\n"+
" runOnReady: sh -c 'echo \"$MTX_PATH $MTX_QUERY\" > %s'\n"+
" runOnNotReady: sh -c 'echo \"$MTX_PATH $MTX_QUERY\" > %s'\n",
onReadyFile, onNotReadyFile))
require.Equal(t, true, ok)
defer p.Close()
c := gortsplib.Client{}
err := c.StartRecording(
"rtsp://localhost:8554/test?query=value",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer c.Close()
time.Sleep(500 * time.Millisecond)
}()
byts, err := os.ReadFile(onReadyFile)
require.NoError(t, err)
require.Equal(t, "test query=value\n", string(byts))
byts, err = os.ReadFile(onNotReadyFile)
require.NoError(t, err)
require.Equal(t, "test query=value\n", string(byts))
}
func TestPathRunOnRead(t *testing.T) {
for _, ca := range []string{"rtsp", "rtmp", "srt", "webrtc"} {
t.Run(ca, func(t *testing.T) {
onReadFile := filepath.Join(os.TempDir(), "onread")
defer os.Remove(onReadFile)
onUnreadFile := filepath.Join(os.TempDir(), "onunread")
defer os.Remove(onUnreadFile)
func() {
p, ok := newInstance(fmt.Sprintf(
"paths:\n"+
" test:\n"+
" runOnRead: sh -c 'echo \"$MTX_PATH $MTX_QUERY\" > %s'\n"+
" runOnUnread: sh -c 'echo \"$MTX_PATH $MTX_QUERY\" > %s'\n",
onReadFile, onUnreadFile))
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}})
require.NoError(t, err)
defer source.Close()
switch ca {
case "rtsp":
reader := gortsplib.Client{}
u, err := base.ParseURL("rtsp://127.0.0.1:8554/test?query=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)
case "rtmp":
u, err := url.Parse("rtmp://127.0.0.1:1935/test?query=value")
require.NoError(t, err)
nconn, err := net.Dial("tcp", u.Host)
require.NoError(t, err)
defer nconn.Close()
conn, err := rtmp.NewClientConn(nconn, u, false)
require.NoError(t, err)
_, err = rtmp.NewReader(conn)
require.NoError(t, err)
case "srt":
conf := srt.DefaultConfig()
address, err := conf.UnmarshalURL("srt://localhost:8890?streamid=read:test:query=value")
require.NoError(t, err)
err = conf.Validate()
require.NoError(t, err)
reader, err := srt.Dial("srt", address, conf)
require.NoError(t, err)
defer reader.Close()
case "webrtc":
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
u, err := url.Parse("http://localhost:8889/test/whep?query=value")
require.NoError(t, err)
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)
}
time.Sleep(500 * time.Millisecond)
}()
byts, err := os.ReadFile(onReadFile)
require.NoError(t, err)
require.Equal(t, "test query=value\n", string(byts))
byts, err = os.ReadFile(onUnreadFile)
require.NoError(t, err)
require.Equal(t, "test query=value\n", string(byts))
})
}
}
func TestPathMaxReaders(t *testing.T) {
p, ok := newInstance("paths:\n" +
" all_others:\n" +
" maxReaders: 1\n")
require.Equal(t, true, ok)
defer p.Close()
source := gortsplib.Client{}
err := source.StartRecording(
"rtsp://localhost:8554/mystream",
&description.Session{Medias: []*description.Media{
test.UniqueMediaH264(),
test.UniqueMediaMPEG4Audio(),
}})
require.NoError(t, err)
defer source.Close()
for i := 0; i < 2; i++ {
reader := gortsplib.Client{}
u, err := base.ParseURL("rtsp://127.0.0.1:8554/mystream")
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)
if i != 1 {
require.NoError(t, err)
} else {
require.Error(t, err)
}
}
}
func TestPathRecord(t *testing.T) {
dir, err := os.MkdirTemp("", "rtsp-path-record")
require.NoError(t, err)
defer os.RemoveAll(dir)
p, ok := newInstance("api: yes\n" +
"record: yes\n" +
"recordPath: " + filepath.Join(dir, "%path/%Y-%m-%d_%H-%M-%S-%f") + "\n" +
"paths:\n" +
" all_others:\n" +
" record: yes\n")
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}})
require.NoError(t, err)
defer source.Close()
for i := 0; i < 4; i++ {
err := source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 1123 + uint16(i),
Timestamp: 45343 + 90000*uint32(i),
SSRC: 563423,
},
Payload: []byte{5},
})
require.NoError(t, err)
}
time.Sleep(500 * time.Millisecond)
files, err := os.ReadDir(filepath.Join(dir, "mystream"))
require.NoError(t, err)
require.Equal(t, 1, len(files))
tr := &http.Transport{}
defer tr.CloseIdleConnections()
hc := &http.Client{Transport: tr}
httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]interface{}{
"record": false,
}, nil)
time.Sleep(500 * time.Millisecond)
httpRequest(t, hc, http.MethodPatch, "http://localhost:9997/v3/config/paths/patch/all_others", map[string]interface{}{
"record": true,
}, nil)
time.Sleep(500 * time.Millisecond)
for i := 4; i < 8; i++ {
err := source.WritePacketRTP(media0, &rtp.Packet{
Header: rtp.Header{
Version: 2,
Marker: true,
PayloadType: 96,
SequenceNumber: 1123 + uint16(i),
Timestamp: 45343 + 90000*uint32(i),
SSRC: 563423,
},
Payload: []byte{5},
})
require.NoError(t, err)
}
time.Sleep(500 * time.Millisecond)
files, err = os.ReadDir(filepath.Join(dir, "mystream"))
require.NoError(t, err)
require.Equal(t, 2, len(files))
}
func TestPathFallback(t *testing.T) {
for _, ca := range []string{
"absolute",
"relative",
"source",
} {
t.Run(ca, func(t *testing.T) {
var conf string
switch ca {
case "absolute":
conf = "paths:\n" +
" path1:\n" +
" fallback: rtsp://localhost:8554/path2\n" +
" path2:\n"
case "relative":
conf = "paths:\n" +
" path1:\n" +
" fallback: /path2\n" +
" path2:\n"
case "source":
conf = "paths:\n" +
" path1:\n" +
" fallback: /path2\n" +
" source: rtsp://localhost:3333/nonexistent\n" +
" path2:\n"
}
p1, ok := newInstance(conf)
require.Equal(t, true, ok)
defer p1.Close()
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/path2",
&description.Session{Medias: []*description.Media{test.UniqueMediaH264()}})
require.NoError(t, err)
defer source.Close()
u, err := base.ParseURL("rtsp://localhost:8554/path1")
require.NoError(t, err)
dest := gortsplib.Client{}
err = dest.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer dest.Close()
desc, _, err := dest.Describe(u)
require.NoError(t, err)
require.Equal(t, 1, len(desc.Medias))
})
}
}
func TestPathSourceRegexp(t *testing.T) {
var stream *gortsplib.ServerStream
s := gortsplib.Server{
Handler: &testServer{
onDescribe: func(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
require.Equal(t, "/a", ctx.Path)
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onSetup: func(_ *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onPlay: func(_ *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, nil
},
},
RTSPAddress: "127.0.0.1:8555",
}
err := s.Start()
require.NoError(t, err)
defer s.Close()
stream = gortsplib.NewServerStream(&s, &description.Session{Medias: []*description.Media{test.MediaH264}})
defer stream.Close()
p, ok := newInstance(
"paths:\n" +
" '~^test_(.+)$':\n" +
" source: rtsp://127.0.0.1:8555/$G1\n" +
" sourceOnDemand: yes\n" +
" 'all':\n")
require.Equal(t, true, ok)
defer p.Close()
reader := gortsplib.Client{}
u, err := base.ParseURL("rtsp://127.0.0.1:8554/test_a")
require.NoError(t, err)
err = reader.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer reader.Close()
_, _, 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
})
}
}

62
internal/core/pprof.go

@ -1,62 +0,0 @@
package core
import (
"net/http"
"time"
// start pprof
_ "net/http/pprof"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/httpserv"
"github.com/bluenviron/mediamtx/internal/logger"
)
type pprofParent interface {
logger.Writer
}
type pprof struct {
parent pprofParent
httpServer *httpserv.WrappedServer
}
func newPPROF(
address string,
readTimeout conf.StringDuration,
parent pprofParent,
) (*pprof, error) {
pp := &pprof{
parent: parent,
}
network, address := restrictNetwork("tcp", address)
var err error
pp.httpServer, err = httpserv.NewWrappedServer(
network,
address,
time.Duration(readTimeout),
"",
"",
http.DefaultServeMux,
pp,
)
if err != nil {
return nil, err
}
pp.Log(logger.Info, "listener opened on "+address)
return pp, nil
}
func (pp *pprof) close() {
pp.Log(logger.Info, "listener is closing")
pp.httpServer.Close()
}
func (pp *pprof) Log(level logger.Level, format string, args ...interface{}) {
pp.parent.Log(level, "[pprof] "+format, args...)
}

7
internal/core/publisher.go

@ -1,7 +0,0 @@
package core
// publisher is an entity that can publish a stream.
type publisher interface {
source
close()
}

7
internal/core/reader.go

@ -1,7 +0,0 @@
package core
// reader is an entity that can read a stream.
type reader interface {
close()
apiReaderDescribe() pathAPISourceOrReader
}

17
internal/core/restrict_network.go

@ -1,17 +0,0 @@
package core
import (
"net"
)
// do not listen on IPv6 when address is 0.0.0.0.
func restrictNetwork(network string, address string) (string, string) {
host, _, err := net.SplitHostPort(address)
if err == nil {
if host == "0.0.0.0" {
return network + "4", address
}
}
return network, address
}

139
internal/core/rpicamera_source.go

@ -1,139 +0,0 @@
package core
import (
"context"
"time"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/formatprocessor"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/rpicamera"
"github.com/bluenviron/mediamtx/internal/stream"
)
func paramsFromConf(cnf *conf.PathConf) rpicamera.Params {
return rpicamera.Params{
CameraID: cnf.RPICameraCamID,
Width: cnf.RPICameraWidth,
Height: cnf.RPICameraHeight,
HFlip: cnf.RPICameraHFlip,
VFlip: cnf.RPICameraVFlip,
Brightness: cnf.RPICameraBrightness,
Contrast: cnf.RPICameraContrast,
Saturation: cnf.RPICameraSaturation,
Sharpness: cnf.RPICameraSharpness,
Exposure: cnf.RPICameraExposure,
AWB: cnf.RPICameraAWB,
Denoise: cnf.RPICameraDenoise,
Shutter: cnf.RPICameraShutter,
Metering: cnf.RPICameraMetering,
Gain: cnf.RPICameraGain,
EV: cnf.RPICameraEV,
ROI: cnf.RPICameraROI,
HDR: cnf.RPICameraHDR,
TuningFile: cnf.RPICameraTuningFile,
Mode: cnf.RPICameraMode,
FPS: cnf.RPICameraFPS,
IDRPeriod: cnf.RPICameraIDRPeriod,
Bitrate: cnf.RPICameraBitrate,
Profile: cnf.RPICameraProfile,
Level: cnf.RPICameraLevel,
AfMode: cnf.RPICameraAfMode,
AfRange: cnf.RPICameraAfRange,
AfSpeed: cnf.RPICameraAfSpeed,
LensPosition: cnf.RPICameraLensPosition,
AfWindow: cnf.RPICameraAfWindow,
TextOverlayEnable: cnf.RPICameraTextOverlayEnable,
TextOverlay: cnf.RPICameraTextOverlay,
}
}
type rpiCameraSourceParent interface {
logger.Writer
setReady(req pathSourceStaticSetReadyReq) pathSourceStaticSetReadyRes
setNotReady(req pathSourceStaticSetNotReadyReq)
}
type rpiCameraSource struct {
parent rpiCameraSourceParent
}
func newRPICameraSource(
parent rpiCameraSourceParent,
) *rpiCameraSource {
return &rpiCameraSource{
parent: parent,
}
}
func (s *rpiCameraSource) Log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[RPI Camera source] "+format, args...)
}
// run implements sourceStaticImpl.
func (s *rpiCameraSource) run(ctx context.Context, cnf *conf.PathConf, reloadConf chan *conf.PathConf) error {
medi := &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{&formats.H264{
PayloadTyp: 96,
PacketizationMode: 1,
}},
}
medias := media.Medias{medi}
var stream *stream.Stream
onData := func(dts time.Duration, au [][]byte) {
if stream == nil {
res := s.parent.setReady(pathSourceStaticSetReadyReq{
medias: medias,
generateRTPPackets: true,
})
if res.err != nil {
return
}
stream = res.stream
}
stream.WriteUnit(medi, medi.Formats[0], &formatprocessor.UnitH264{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: dts,
AU: au,
})
}
cam, err := rpicamera.New(paramsFromConf(cnf), onData)
if err != nil {
return err
}
defer cam.Close()
defer func() {
if stream != nil {
s.parent.setNotReady(pathSourceStaticSetNotReadyReq{})
}
}()
for {
select {
case cnf := <-reloadConf:
cam.ReloadParams(paramsFromConf(cnf))
case <-ctx.Done():
return nil
}
}
}
// apiSourceDescribe implements sourceStaticImpl.
func (*rpiCameraSource) apiSourceDescribe() pathAPISourceOrReader {
return pathAPISourceOrReader{
Type: "rpiCameraSource",
ID: "",
}
}

763
internal/core/rtmp_conn.go

@ -1,763 +0,0 @@
package core
import (
"context"
"errors"
"fmt"
"net"
"net/url"
"strings"
"sync"
"time"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/gortsplib/v3/pkg/ringbuffer"
"github.com/bluenviron/mediacommon/pkg/codecs/h264"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg1audio"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/formatprocessor"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/rtmp"
"github.com/bluenviron/mediamtx/internal/stream"
)
const (
rtmpPauseAfterAuthError = 2 * time.Second
)
func pathNameAndQuery(inURL *url.URL) (string, url.Values, string) {
// remove leading and trailing slashes inserted by OBS and some other clients
tmp := strings.TrimRight(inURL.String(), "/")
ur, _ := url.Parse(tmp)
pathName := strings.TrimLeft(ur.Path, "/")
return pathName, ur.Query(), ur.RawQuery
}
type rtmpConnState int
const (
rtmpConnStateRead rtmpConnState = iota + 1
rtmpConnStatePublish
)
type rtmpConnPathManager interface {
addReader(req pathAddReaderReq) pathAddReaderRes
addPublisher(req pathAddPublisherReq) pathAddPublisherRes
}
type rtmpConnParent interface {
logger.Writer
closeConn(*rtmpConn)
}
type rtmpConn struct {
isTLS bool
rtspAddress string
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
readBufferCount int
runOnConnect string
runOnConnectRestart bool
wg *sync.WaitGroup
nconn net.Conn
externalCmdPool *externalcmd.Pool
pathManager rtmpConnPathManager
parent rtmpConnParent
ctx context.Context
ctxCancel func()
uuid uuid.UUID
created time.Time
mutex sync.RWMutex
conn *rtmp.Conn
state rtmpConnState
pathName string
}
func newRTMPConn(
parentCtx context.Context,
isTLS bool,
rtspAddress string,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
readBufferCount int,
runOnConnect string,
runOnConnectRestart bool,
wg *sync.WaitGroup,
nconn net.Conn,
externalCmdPool *externalcmd.Pool,
pathManager rtmpConnPathManager,
parent rtmpConnParent,
) *rtmpConn {
ctx, ctxCancel := context.WithCancel(parentCtx)
c := &rtmpConn{
isTLS: isTLS,
rtspAddress: rtspAddress,
readTimeout: readTimeout,
writeTimeout: writeTimeout,
readBufferCount: readBufferCount,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
wg: wg,
nconn: nconn,
externalCmdPool: externalCmdPool,
pathManager: pathManager,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
uuid: uuid.New(),
created: time.Now(),
}
c.Log(logger.Info, "opened")
c.wg.Add(1)
go c.run()
return c
}
func (c *rtmpConn) close() {
c.ctxCancel()
}
func (c *rtmpConn) remoteAddr() net.Addr {
return c.nconn.RemoteAddr()
}
func (c *rtmpConn) Log(level logger.Level, format string, args ...interface{}) {
c.parent.Log(level, "[conn %v] "+format, append([]interface{}{c.nconn.RemoteAddr()}, args...)...)
}
func (c *rtmpConn) ip() net.IP {
return c.nconn.RemoteAddr().(*net.TCPAddr).IP
}
func (c *rtmpConn) run() {
defer c.wg.Done()
if c.runOnConnect != "" {
c.Log(logger.Info, "runOnConnect command started")
_, port, _ := net.SplitHostPort(c.rtspAddress)
onConnectCmd := externalcmd.NewCmd(
c.externalCmdPool,
c.runOnConnect,
c.runOnConnectRestart,
externalcmd.Environment{
"MTX_PATH": "",
"RTSP_PATH": "", // deprecated
"RTSP_PORT": port,
},
func(err error) {
c.Log(logger.Info, "runOnConnect command exited: %v", err)
})
defer func() {
onConnectCmd.Close()
c.Log(logger.Info, "runOnConnect command stopped")
}()
}
err := func() error {
readerErr := make(chan error)
go func() {
readerErr <- c.runReader()
}()
select {
case err := <-readerErr:
c.nconn.Close()
return err
case <-c.ctx.Done():
c.nconn.Close()
<-readerErr
return errors.New("terminated")
}
}()
c.ctxCancel()
c.parent.closeConn(c)
c.Log(logger.Info, "closed (%v)", err)
}
func (c *rtmpConn) runReader() error {
c.nconn.SetReadDeadline(time.Now().Add(time.Duration(c.readTimeout)))
c.nconn.SetWriteDeadline(time.Now().Add(time.Duration(c.writeTimeout)))
conn, u, publish, err := rtmp.NewServerConn(c.nconn)
if err != nil {
return err
}
c.mutex.Lock()
c.conn = conn
c.mutex.Unlock()
if !publish {
return c.runRead(conn, u)
}
return c.runPublish(conn, u)
}
func (c *rtmpConn) runRead(conn *rtmp.Conn, u *url.URL) error {
pathName, query, rawQuery := pathNameAndQuery(u)
res := c.pathManager.addReader(pathAddReaderReq{
author: c,
pathName: pathName,
credentials: authCredentials{
query: rawQuery,
ip: c.ip(),
user: query.Get("user"),
pass: query.Get("pass"),
proto: authProtocolRTMP,
id: &c.uuid,
},
})
if res.err != nil {
if terr, ok := res.err.(*errAuthentication); ok {
// wait some seconds to stop brute force attacks
<-time.After(rtmpPauseAfterAuthError)
return terr
}
return res.err
}
defer res.path.removeReader(pathRemoveReaderReq{author: c})
c.mutex.Lock()
c.state = rtmpConnStateRead
c.pathName = pathName
c.mutex.Unlock()
ringBuffer, _ := ringbuffer.New(uint64(c.readBufferCount))
go func() {
<-c.ctx.Done()
ringBuffer.Close()
}()
var medias media.Medias
videoFirstIDRFound := false
var videoStartDTS time.Duration
var w *rtmp.Writer
videoMedia, videoFormat := c.setupVideo(
&w,
res.stream,
ringBuffer,
&videoFirstIDRFound,
&videoStartDTS)
if videoMedia != nil {
medias = append(medias, videoMedia)
}
audioMedia, audioFormat := c.setupAudio(
&w,
res.stream,
ringBuffer,
videoFormat,
&videoFirstIDRFound,
&videoStartDTS)
if audioFormat != nil {
medias = append(medias, audioMedia)
}
if videoFormat == nil && audioFormat == nil {
return fmt.Errorf(
"the stream doesn't contain any supported codec, which are currently H264, MPEG-4 Audio, MPEG-1/2 Audio")
}
defer res.stream.RemoveReader(c)
c.Log(logger.Info, "is reading from path '%s', %s",
res.path.name, sourceMediaInfo(medias))
pathConf := res.path.safeConf()
if pathConf.RunOnRead != "" {
c.Log(logger.Info, "runOnRead command started")
onReadCmd := externalcmd.NewCmd(
c.externalCmdPool,
pathConf.RunOnRead,
pathConf.RunOnReadRestart,
res.path.externalCmdEnv(),
func(err error) {
c.Log(logger.Info, "runOnRead command exited: %v", err)
})
defer func() {
onReadCmd.Close()
c.Log(logger.Info, "runOnRead command stopped")
}()
}
var err error
w, err = rtmp.NewWriter(conn, videoFormat, audioFormat)
if err != nil {
return err
}
// disable read deadline
c.nconn.SetReadDeadline(time.Time{})
for {
item, ok := ringBuffer.Pull()
if !ok {
return fmt.Errorf("terminated")
}
err := item.(func() error)()
if err != nil {
return err
}
}
}
func (c *rtmpConn) setupVideo(
w **rtmp.Writer,
stream *stream.Stream,
ringBuffer *ringbuffer.RingBuffer,
videoFirstIDRFound *bool,
videoStartDTS *time.Duration,
) (*media.Media, formats.Format) {
var videoFormatH264 *formats.H264
videoMedia := stream.Medias().FindFormat(&videoFormatH264)
if videoFormatH264 != nil {
startPTSFilled := false
var startPTS time.Duration
var videoDTSExtractor *h264.DTSExtractor
stream.AddReader(c, videoMedia, videoFormatH264, func(unit formatprocessor.Unit) {
ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitH264)
if tunit.AU == nil {
return nil
}
if !startPTSFilled {
startPTSFilled = true
startPTS = tunit.PTS
}
pts := tunit.PTS - startPTS
idrPresent := false
nonIDRPresent := false
for _, nalu := range tunit.AU {
typ := h264.NALUType(nalu[0] & 0x1F)
switch typ {
case h264.NALUTypeIDR:
idrPresent = true
case h264.NALUTypeNonIDR:
nonIDRPresent = true
}
}
var dts time.Duration
// wait until we receive an IDR
if !*videoFirstIDRFound {
if !idrPresent {
return nil
}
*videoFirstIDRFound = true
videoDTSExtractor = h264.NewDTSExtractor()
var err error
dts, err = videoDTSExtractor.Extract(tunit.AU, pts)
if err != nil {
return err
}
*videoStartDTS = dts
dts = 0
pts -= *videoStartDTS
} else {
if !idrPresent && !nonIDRPresent {
return nil
}
var err error
dts, err = videoDTSExtractor.Extract(tunit.AU, pts)
if err != nil {
return err
}
dts -= *videoStartDTS
pts -= *videoStartDTS
}
c.nconn.SetWriteDeadline(time.Now().Add(time.Duration(c.writeTimeout)))
return (*w).WriteH264(pts, dts, idrPresent, tunit.AU)
})
})
return videoMedia, videoFormatH264
}
return nil, nil
}
func (c *rtmpConn) setupAudio(
w **rtmp.Writer,
stream *stream.Stream,
ringBuffer *ringbuffer.RingBuffer,
videoFormat formats.Format,
videoFirstIDRFound *bool,
videoStartDTS *time.Duration,
) (*media.Media, formats.Format) {
var audioFormatMPEG4Generic *formats.MPEG4AudioGeneric
audioMedia := stream.Medias().FindFormat(&audioFormatMPEG4Generic)
if audioMedia != nil {
startPTSFilled := false
var startPTS time.Duration
stream.AddReader(c, audioMedia, audioFormatMPEG4Generic, func(unit formatprocessor.Unit) {
ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitMPEG4AudioGeneric)
if tunit.AUs == nil {
return nil
}
if !startPTSFilled {
startPTSFilled = true
startPTS = tunit.PTS
}
pts := tunit.PTS - startPTS
if videoFormat != nil {
if !*videoFirstIDRFound {
return nil
}
pts -= *videoStartDTS
if pts < 0 {
return nil
}
}
for i, au := range tunit.AUs {
c.nconn.SetWriteDeadline(time.Now().Add(time.Duration(c.writeTimeout)))
err := (*w).WriteMPEG4Audio(
pts+time.Duration(i)*mpeg4audio.SamplesPerAccessUnit*
time.Second/time.Duration(audioFormatMPEG4Generic.ClockRate()),
au,
)
if err != nil {
return err
}
}
return nil
})
})
return audioMedia, audioFormatMPEG4Generic
}
var audioFormatMPEG4AudioLATM *formats.MPEG4AudioLATM
audioMedia = stream.Medias().FindFormat(&audioFormatMPEG4AudioLATM)
if audioMedia != nil &&
audioFormatMPEG4AudioLATM.Config != nil &&
len(audioFormatMPEG4AudioLATM.Config.Programs) == 1 &&
len(audioFormatMPEG4AudioLATM.Config.Programs[0].Layers) == 1 {
startPTSFilled := false
var startPTS time.Duration
stream.AddReader(c, audioMedia, audioFormatMPEG4AudioLATM, func(unit formatprocessor.Unit) {
ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitMPEG4AudioLATM)
if tunit.AU == nil {
return nil
}
if !startPTSFilled {
startPTSFilled = true
startPTS = tunit.PTS
}
pts := tunit.PTS - startPTS
if videoFormat != nil {
if !*videoFirstIDRFound {
return nil
}
pts -= *videoStartDTS
if pts < 0 {
return nil
}
}
c.nconn.SetWriteDeadline(time.Now().Add(time.Duration(c.writeTimeout)))
return (*w).WriteMPEG4Audio(pts, tunit.AU)
})
})
return audioMedia, audioFormatMPEG4AudioLATM
}
var audioFormatMPEG1 *formats.MPEG1Audio
audioMedia = stream.Medias().FindFormat(&audioFormatMPEG1)
if audioMedia != nil {
startPTSFilled := false
var startPTS time.Duration
stream.AddReader(c, audioMedia, audioFormatMPEG1, func(unit formatprocessor.Unit) {
ringBuffer.Push(func() error {
tunit := unit.(*formatprocessor.UnitMPEG1Audio)
if !startPTSFilled {
startPTSFilled = true
startPTS = tunit.PTS
}
pts := tunit.PTS - startPTS
if videoFormat != nil {
if !*videoFirstIDRFound {
return nil
}
pts -= *videoStartDTS
if pts < 0 {
return nil
}
}
for _, frame := range tunit.Frames {
var h mpeg1audio.FrameHeader
err := h.Unmarshal(frame)
if err != nil {
return err
}
if !(!h.MPEG2 && h.Layer == 3) {
return fmt.Errorf("RTMP only supports MPEG-1 layer 3 audio")
}
c.nconn.SetWriteDeadline(time.Now().Add(time.Duration(c.writeTimeout)))
err = (*w).WriteMPEG1Audio(pts, &h, frame)
if err != nil {
return err
}
pts += time.Duration(h.SampleCount()) *
time.Second / time.Duration(h.SampleRate)
}
return nil
})
})
return audioMedia, audioFormatMPEG1
}
return nil, nil
}
func (c *rtmpConn) runPublish(conn *rtmp.Conn, u *url.URL) error {
pathName, query, rawQuery := pathNameAndQuery(u)
res := c.pathManager.addPublisher(pathAddPublisherReq{
author: c,
pathName: pathName,
credentials: authCredentials{
query: rawQuery,
ip: c.ip(),
user: query.Get("user"),
pass: query.Get("pass"),
proto: authProtocolRTMP,
id: &c.uuid,
},
})
if res.err != nil {
if terr, ok := res.err.(*errAuthentication); ok {
// wait some seconds to stop brute force attacks
<-time.After(rtmpPauseAfterAuthError)
return terr
}
return res.err
}
defer res.path.removePublisher(pathRemovePublisherReq{author: c})
c.mutex.Lock()
c.state = rtmpConnStatePublish
c.pathName = pathName
c.mutex.Unlock()
r, err := rtmp.NewReader(conn)
if err != nil {
return err
}
videoFormat, audioFormat := r.Tracks()
var medias media.Medias
var stream *stream.Stream
if videoFormat != nil {
videoMedia := &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{videoFormat},
}
medias = append(medias, videoMedia)
switch videoFormat.(type) {
case *formats.AV1:
r.OnDataAV1(func(pts time.Duration, obus [][]byte) {
stream.WriteUnit(videoMedia, videoFormat, &formatprocessor.UnitAV1{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
OBUs: obus,
})
})
case *formats.H265:
r.OnDataH265(func(pts time.Duration, au [][]byte) {
stream.WriteUnit(videoMedia, videoFormat, &formatprocessor.UnitH265{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
AU: au,
})
})
case *formats.H264:
r.OnDataH264(func(pts time.Duration, au [][]byte) {
stream.WriteUnit(videoMedia, videoFormat, &formatprocessor.UnitH264{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
AU: au,
})
})
}
}
if audioFormat != nil { //nolint:dupl
audioMedia := &media.Media{
Type: media.TypeAudio,
Formats: []formats.Format{audioFormat},
}
medias = append(medias, audioMedia)
switch audioFormat.(type) {
case *formats.MPEG4AudioGeneric:
r.OnDataMPEG4Audio(func(pts time.Duration, au []byte) {
stream.WriteUnit(audioMedia, audioFormat, &formatprocessor.UnitMPEG4AudioGeneric{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
AUs: [][]byte{au},
})
})
case *formats.MPEG1Audio:
r.OnDataMPEG1Audio(func(pts time.Duration, frame []byte) {
stream.WriteUnit(audioMedia, audioFormat, &formatprocessor.UnitMPEG1Audio{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
Frames: [][]byte{frame},
})
})
}
}
rres := res.path.startPublisher(pathStartPublisherReq{
author: c,
medias: medias,
generateRTPPackets: true,
})
if rres.err != nil {
return rres.err
}
stream = rres.stream
// disable write deadline to allow outgoing acknowledges
c.nconn.SetWriteDeadline(time.Time{})
for {
c.nconn.SetReadDeadline(time.Now().Add(time.Duration(c.readTimeout)))
err := r.Read()
if err != nil {
return err
}
}
}
// apiReaderDescribe implements reader.
func (c *rtmpConn) apiReaderDescribe() pathAPISourceOrReader {
return pathAPISourceOrReader{
Type: func() string {
if c.isTLS {
return "rtmpsConn"
}
return "rtmpConn"
}(),
ID: c.uuid.String(),
}
}
// apiSourceDescribe implements source.
func (c *rtmpConn) apiSourceDescribe() pathAPISourceOrReader {
return c.apiReaderDescribe()
}
func (c *rtmpConn) apiItem() *apiRTMPConn {
c.mutex.RLock()
defer c.mutex.RUnlock()
bytesReceived := uint64(0)
bytesSent := uint64(0)
if c.conn != nil {
bytesReceived = c.conn.BytesReceived()
bytesSent = c.conn.BytesSent()
}
return &apiRTMPConn{
ID: c.uuid,
Created: c.created,
RemoteAddr: c.remoteAddr().String(),
State: func() apiRTMPConnState {
switch c.state {
case rtmpConnStateRead:
return apiRTMPConnStateRead
case rtmpConnStatePublish:
return apiRTMPConnStatePublish
default:
return apiRTMPConnStateIdle
}
}(),
Path: c.pathName,
BytesReceived: bytesReceived,
BytesSent: bytesSent,
}
}

46
internal/core/rtmp_listener.go

@ -1,46 +0,0 @@
package core
import (
"net"
"sync"
)
type rtmpListener struct {
ln net.Listener
wg *sync.WaitGroup
parent *rtmpServer
}
func newRTMPListener(
ln net.Listener,
wg *sync.WaitGroup,
parent *rtmpServer,
) *rtmpListener {
l := &rtmpListener{
ln: ln,
wg: wg,
parent: parent,
}
l.wg.Add(1)
go l.run()
return l
}
func (l *rtmpListener) run() {
defer l.wg.Done()
err := func() error {
for {
conn, err := l.ln.Accept()
if err != nil {
return err
}
l.parent.newConn(conn)
}
}()
l.parent.acceptError(err)
}

332
internal/core/rtmp_server.go

@ -1,332 +0,0 @@
package core
import (
"context"
"crypto/tls"
"fmt"
"net"
"sort"
"sync"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
)
type rtmpServerAPIConnsListRes struct {
data *apiRTMPConnsList
err error
}
type rtmpServerAPIConnsListReq struct {
res chan rtmpServerAPIConnsListRes
}
type rtmpServerAPIConnsGetRes struct {
data *apiRTMPConn
err error
}
type rtmpServerAPIConnsGetReq struct {
uuid uuid.UUID
res chan rtmpServerAPIConnsGetRes
}
type rtmpServerAPIConnsKickRes struct {
err error
}
type rtmpServerAPIConnsKickReq struct {
uuid uuid.UUID
res chan rtmpServerAPIConnsKickRes
}
type rtmpServerParent interface {
logger.Writer
}
type rtmpServer struct {
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
readBufferCount int
isTLS bool
rtspAddress string
runOnConnect string
runOnConnectRestart bool
externalCmdPool *externalcmd.Pool
metrics *metrics
pathManager *pathManager
parent rtmpServerParent
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
ln net.Listener
conns map[*rtmpConn]struct{}
// in
chNewConn chan net.Conn
chAcceptErr chan error
chCloseConn chan *rtmpConn
chAPIConnsList chan rtmpServerAPIConnsListReq
chAPIConnsGet chan rtmpServerAPIConnsGetReq
chAPIConnsKick chan rtmpServerAPIConnsKickReq
}
func newRTMPServer(
address string,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
readBufferCount int,
isTLS bool,
serverCert string,
serverKey string,
rtspAddress string,
runOnConnect string,
runOnConnectRestart bool,
externalCmdPool *externalcmd.Pool,
metrics *metrics,
pathManager *pathManager,
parent rtmpServerParent,
) (*rtmpServer, error) {
ln, err := func() (net.Listener, error) {
if !isTLS {
return net.Listen(restrictNetwork("tcp", address))
}
cert, err := tls.LoadX509KeyPair(serverCert, serverKey)
if err != nil {
return nil, err
}
network, address := restrictNetwork("tcp", address)
return tls.Listen(network, address, &tls.Config{Certificates: []tls.Certificate{cert}})
}()
if err != nil {
return nil, err
}
ctx, ctxCancel := context.WithCancel(context.Background())
s := &rtmpServer{
readTimeout: readTimeout,
writeTimeout: writeTimeout,
readBufferCount: readBufferCount,
rtspAddress: rtspAddress,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
isTLS: isTLS,
externalCmdPool: externalCmdPool,
metrics: metrics,
pathManager: pathManager,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
ln: ln,
conns: make(map[*rtmpConn]struct{}),
chNewConn: make(chan net.Conn),
chAcceptErr: make(chan error),
chCloseConn: make(chan *rtmpConn),
chAPIConnsList: make(chan rtmpServerAPIConnsListReq),
chAPIConnsGet: make(chan rtmpServerAPIConnsGetReq),
chAPIConnsKick: make(chan rtmpServerAPIConnsKickReq),
}
s.Log(logger.Info, "listener opened on %s", address)
if s.metrics != nil {
s.metrics.rtmpServerSet(s)
}
newRTMPListener(
s.ln,
&s.wg,
s,
)
s.wg.Add(1)
go s.run()
return s, nil
}
func (s *rtmpServer) Log(level logger.Level, format string, args ...interface{}) {
label := func() string {
if s.isTLS {
return "RTMPS"
}
return "RTMP"
}()
s.parent.Log(level, "[%s] "+format, append([]interface{}{label}, args...)...)
}
func (s *rtmpServer) close() {
s.Log(logger.Info, "listener is closing")
s.ctxCancel()
s.wg.Wait()
}
func (s *rtmpServer) run() {
defer s.wg.Done()
outer:
for {
select {
case err := <-s.chAcceptErr:
s.Log(logger.Error, "%s", err)
break outer
case nconn := <-s.chNewConn:
c := newRTMPConn(
s.ctx,
s.isTLS,
s.rtspAddress,
s.readTimeout,
s.writeTimeout,
s.readBufferCount,
s.runOnConnect,
s.runOnConnectRestart,
&s.wg,
nconn,
s.externalCmdPool,
s.pathManager,
s)
s.conns[c] = struct{}{}
case c := <-s.chCloseConn:
delete(s.conns, c)
case req := <-s.chAPIConnsList:
data := &apiRTMPConnsList{
Items: []*apiRTMPConn{},
}
for c := range s.conns {
data.Items = append(data.Items, c.apiItem())
}
sort.Slice(data.Items, func(i, j int) bool {
return data.Items[i].Created.Before(data.Items[j].Created)
})
req.res <- rtmpServerAPIConnsListRes{data: data}
case req := <-s.chAPIConnsGet:
c := s.findConnByUUID(req.uuid)
if c == nil {
req.res <- rtmpServerAPIConnsGetRes{err: errAPINotFound}
continue
}
req.res <- rtmpServerAPIConnsGetRes{data: c.apiItem()}
case req := <-s.chAPIConnsKick:
c := s.findConnByUUID(req.uuid)
if c == nil {
req.res <- rtmpServerAPIConnsKickRes{err: errAPINotFound}
continue
}
delete(s.conns, c)
c.close()
req.res <- rtmpServerAPIConnsKickRes{}
case <-s.ctx.Done():
break outer
}
}
s.ctxCancel()
s.ln.Close()
if s.metrics != nil {
s.metrics.rtmpServerSet(s)
}
}
func (s *rtmpServer) findConnByUUID(uuid uuid.UUID) *rtmpConn {
for c := range s.conns {
if c.uuid == uuid {
return c
}
}
return nil
}
// newConn is called by rtmpListener.
func (s *rtmpServer) newConn(conn net.Conn) {
select {
case s.chNewConn <- conn:
case <-s.ctx.Done():
conn.Close()
}
}
// acceptError is called by rtmpListener.
func (s *rtmpServer) acceptError(err error) {
select {
case s.chAcceptErr <- err:
case <-s.ctx.Done():
}
}
// closeConn is called by rtmpConn.
func (s *rtmpServer) closeConn(c *rtmpConn) {
select {
case s.chCloseConn <- c:
case <-s.ctx.Done():
}
}
// apiConnsList is called by api.
func (s *rtmpServer) apiConnsList() (*apiRTMPConnsList, error) {
req := rtmpServerAPIConnsListReq{
res: make(chan rtmpServerAPIConnsListRes),
}
select {
case s.chAPIConnsList <- req:
res := <-req.res
return res.data, res.err
case <-s.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// apiConnsGet is called by api.
func (s *rtmpServer) apiConnsGet(uuid uuid.UUID) (*apiRTMPConn, error) {
req := rtmpServerAPIConnsGetReq{
uuid: uuid,
res: make(chan rtmpServerAPIConnsGetRes),
}
select {
case s.chAPIConnsGet <- req:
res := <-req.res
return res.data, res.err
case <-s.ctx.Done():
return nil, fmt.Errorf("terminated")
}
}
// apiConnsKick is called by api.
func (s *rtmpServer) apiConnsKick(uuid uuid.UUID) error {
req := rtmpServerAPIConnsKickReq{
uuid: uuid,
res: make(chan rtmpServerAPIConnsKickRes),
}
select {
case s.chAPIConnsKick <- req:
res := <-req.res
return res.err
case <-s.ctx.Done():
return fmt.Errorf("terminated")
}
}

377
internal/core/rtmp_server_test.go

@ -1,377 +0,0 @@
package core //nolint:dupl
import (
"crypto/tls"
"net"
"net/url"
"os"
"testing"
"time"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio"
"github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/rtmp"
)
func TestRTMPServerRunOnConnect(t *testing.T) {
f, err := os.CreateTemp(os.TempDir(), "rtspss-runonconnect-")
require.NoError(t, err)
f.Close()
defer os.Remove(f.Name())
p, ok := newInstance(
"runOnConnect: sh -c 'echo aa > " + f.Name() + "'\n" +
"paths:\n" +
" all:\n")
require.Equal(t, true, ok)
defer p.Close()
u, err := url.Parse("rtmp://127.0.0.1:1935/teststream")
require.NoError(t, err)
nconn, err := net.Dial("tcp", u.Host)
require.NoError(t, err)
defer nconn.Close()
_, err = rtmp.NewClientConn(nconn, u, true)
require.NoError(t, err)
time.Sleep(500 * time.Millisecond)
byts, err := os.ReadFile(f.Name())
require.NoError(t, err)
require.Equal(t, "aa\n", string(byts))
}
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:\n"
case "internal":
conf += "paths:\n" +
" all:\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:\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 := &formats.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 := &formats.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:\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 := &formats.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:\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 := &formats.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:\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 := &formats.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")
})
}

206
internal/core/rtmp_source.go

@ -1,206 +0,0 @@
package core
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/url"
"time"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/formatprocessor"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/rtmp"
"github.com/bluenviron/mediamtx/internal/stream"
)
type rtmpSourceParent interface {
logger.Writer
setReady(req pathSourceStaticSetReadyReq) pathSourceStaticSetReadyRes
setNotReady(req pathSourceStaticSetNotReadyReq)
}
type rtmpSource struct {
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
parent rtmpSourceParent
}
func newRTMPSource(
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
parent rtmpSourceParent,
) *rtmpSource {
return &rtmpSource{
readTimeout: readTimeout,
writeTimeout: writeTimeout,
parent: parent,
}
}
func (s *rtmpSource) Log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[RTMP source] "+format, args...)
}
// run implements sourceStaticImpl.
func (s *rtmpSource) run(ctx context.Context, cnf *conf.PathConf, reloadConf chan *conf.PathConf) error {
s.Log(logger.Debug, "connecting")
u, err := url.Parse(cnf.Source)
if err != nil {
return err
}
// add default port
_, _, err = net.SplitHostPort(u.Host)
if err != nil {
u.Host = net.JoinHostPort(u.Host, "1935")
}
nconn, err := func() (net.Conn, error) {
ctx2, cancel2 := context.WithTimeout(ctx, time.Duration(s.readTimeout))
defer cancel2()
if u.Scheme == "rtmp" {
return (&net.Dialer{}).DialContext(ctx2, "tcp", u.Host)
}
return (&tls.Dialer{
Config: tlsConfigForFingerprint(cnf.SourceFingerprint),
}).DialContext(ctx2, "tcp", u.Host)
}()
if err != nil {
return err
}
readDone := make(chan error)
go func() {
readDone <- s.runReader(u, nconn)
}()
for {
select {
case err := <-readDone:
nconn.Close()
return err
case <-reloadConf:
case <-ctx.Done():
nconn.Close()
<-readDone
return nil
}
}
}
func (s *rtmpSource) runReader(u *url.URL, nconn net.Conn) error {
nconn.SetReadDeadline(time.Now().Add(time.Duration(s.readTimeout)))
nconn.SetWriteDeadline(time.Now().Add(time.Duration(s.writeTimeout)))
conn, err := rtmp.NewClientConn(nconn, u, false)
if err != nil {
return err
}
mc, err := rtmp.NewReader(conn)
if err != nil {
return err
}
videoFormat, audioFormat := mc.Tracks()
switch videoFormat.(type) {
case *formats.H265, *formats.AV1:
return fmt.Errorf("proxying H265 or AV1 tracks with RTMP is not supported")
}
var medias media.Medias
var stream *stream.Stream
if videoFormat != nil {
videoMedia := &media.Media{
Type: media.TypeVideo,
Formats: []formats.Format{videoFormat},
}
medias = append(medias, videoMedia)
if _, ok := videoFormat.(*formats.H264); ok {
mc.OnDataH264(func(pts time.Duration, au [][]byte) {
stream.WriteUnit(videoMedia, videoFormat, &formatprocessor.UnitH264{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
AU: au,
})
})
}
}
if audioFormat != nil { //nolint:dupl
audioMedia := &media.Media{
Type: media.TypeAudio,
Formats: []formats.Format{audioFormat},
}
medias = append(medias, audioMedia)
switch audioFormat.(type) {
case *formats.MPEG4AudioGeneric:
mc.OnDataMPEG4Audio(func(pts time.Duration, au []byte) {
stream.WriteUnit(audioMedia, audioFormat, &formatprocessor.UnitMPEG4AudioGeneric{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
AUs: [][]byte{au},
})
})
case *formats.MPEG1Audio:
mc.OnDataMPEG1Audio(func(pts time.Duration, frame []byte) {
stream.WriteUnit(audioMedia, audioFormat, &formatprocessor.UnitMPEG1Audio{
BaseUnit: formatprocessor.BaseUnit{
NTP: time.Now(),
},
PTS: pts,
Frames: [][]byte{frame},
})
})
}
}
res := s.parent.setReady(pathSourceStaticSetReadyReq{
medias: medias,
generateRTPPackets: true,
})
if res.err != nil {
return res.err
}
defer s.parent.setNotReady(pathSourceStaticSetNotReadyReq{})
stream = res.stream
// disable write deadline to allow outgoing acknowledges
nconn.SetWriteDeadline(time.Time{})
for {
nconn.SetReadDeadline(time.Now().Add(time.Duration(s.readTimeout)))
err := mc.Read()
if err != nil {
return err
}
}
}
// apiSourceDescribe implements sourceStaticImpl.
func (*rtmpSource) apiSourceDescribe() pathAPISourceOrReader {
return pathAPISourceOrReader{
Type: "rtmpSource",
ID: "",
}
}

147
internal/core/rtmp_source_test.go

@ -1,147 +0,0 @@
package core
import (
"crypto/tls"
"net"
"os"
"testing"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/url"
"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
"github.com/bluenviron/mediamtx/internal/rtmp"
)
func TestRTMPSource(t *testing.T) {
for _, ca := range []string{
"plain",
"tls",
} {
t.Run(ca, func(t *testing.T) {
ln, err := func() (net.Listener, error) {
if ca == "plain" {
return net.Listen("tcp", "127.0.0.1:1937")
}
serverCertFpath, err := writeTempFile(serverCert)
require.NoError(t, err)
defer os.Remove(serverCertFpath)
serverKeyFpath, err := writeTempFile(serverKey)
require.NoError(t, err)
defer os.Remove(serverKeyFpath)
var cert tls.Certificate
cert, err = tls.LoadX509KeyPair(serverCertFpath, serverKeyFpath)
require.NoError(t, err)
return tls.Listen("tcp", "127.0.0.1:1937", &tls.Config{Certificates: []tls.Certificate{cert}})
}()
require.NoError(t, err)
defer ln.Close()
connected := make(chan struct{})
received := make(chan struct{})
done := make(chan struct{})
go func() {
nconn, err := ln.Accept()
require.NoError(t, err)
defer nconn.Close()
conn, _, _, err := rtmp.NewServerConn(nconn)
require.NoError(t, err)
videoTrack := &formats.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 := &formats.MPEG4Audio{
PayloadTyp: 96,
Config: &mpeg4audio.Config{
Type: 2,
SampleRate: 44100,
ChannelCount: 2,
},
SizeLength: 13,
IndexLength: 3,
IndexDeltaLength: 3,
}
w, err := rtmp.NewWriter(conn, videoTrack, audioTrack)
require.NoError(t, err)
<-connected
err = w.WriteH264(0, 0, true, [][]byte{{0x05, 0x02, 0x03, 0x04}})
require.NoError(t, err)
<-done
}()
if ca == "plain" {
p, ok := newInstance("paths:\n" +
" proxied:\n" +
" source: rtmp://localhost:1937/teststream\n" +
" sourceOnDemand: yes\n")
require.Equal(t, true, ok)
defer p.Close()
} else {
p, ok := newInstance("paths:\n" +
" proxied:\n" +
" source: rtmps://localhost:1937/teststream\n" +
" sourceFingerprint: 33949E05FFFB5FF3E8AA16F8213A6251B4D9363804BA53233C4DA9A46D6F2739\n" +
" sourceOnDemand: yes\n")
require.Equal(t, true, ok)
defer p.Close()
}
c := gortsplib.Client{}
u, err := url.Parse("rtsp://127.0.0.1:8554/proxied")
require.NoError(t, err)
err = c.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer c.Close()
medias, baseURL, _, err := c.Describe(u)
require.NoError(t, err)
var forma *formats.H264
medi := medias.FindFormat(&forma)
_, err = c.Setup(medi, baseURL, 0, 0)
require.NoError(t, err)
c.OnPacketRTP(medi, forma, func(pkt *rtp.Packet) {
require.Equal(t, []byte{
0x18, 0x0, 0x19, 0x67, 0x42, 0xc0, 0x28, 0xd9,
0x0, 0x78, 0x2, 0x27, 0xe5, 0x84, 0x0, 0x0,
0x3, 0x0, 0x4, 0x0, 0x0, 0x3, 0x0, 0xf0,
0x3c, 0x60, 0xc9, 0x20, 0x0, 0x4, 0x8, 0x6,
0x7, 0x8, 0x0, 0x4, 0x5, 0x2, 0x3, 0x4,
}, pkt.Payload)
close(received)
})
_, err = c.Play(nil)
require.NoError(t, err)
close(connected)
<-received
close(done)
})
}
}

228
internal/core/rtsp_conn.go

@ -1,228 +0,0 @@
package core
import (
"fmt"
"net"
"time"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/auth"
"github.com/bluenviron/gortsplib/v3/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/headers"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
)
const (
rtspPauseAfterAuthError = 2 * time.Second
)
type rtspConnParent interface {
logger.Writer
}
type rtspConn struct {
rtspAddress string
authMethods []headers.AuthMethod
readTimeout conf.StringDuration
runOnConnect string
runOnConnectRestart bool
externalCmdPool *externalcmd.Pool
pathManager *pathManager
conn *gortsplib.ServerConn
parent rtspConnParent
uuid uuid.UUID
created time.Time
onConnectCmd *externalcmd.Cmd
authNonce string
authFailures int
}
func newRTSPConn(
rtspAddress string,
authMethods []headers.AuthMethod,
readTimeout conf.StringDuration,
runOnConnect string,
runOnConnectRestart bool,
externalCmdPool *externalcmd.Pool,
pathManager *pathManager,
conn *gortsplib.ServerConn,
parent rtspConnParent,
) *rtspConn {
c := &rtspConn{
rtspAddress: rtspAddress,
authMethods: authMethods,
readTimeout: readTimeout,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
externalCmdPool: externalCmdPool,
pathManager: pathManager,
conn: conn,
parent: parent,
uuid: uuid.New(),
created: time.Now(),
}
c.Log(logger.Info, "opened")
if c.runOnConnect != "" {
c.Log(logger.Info, "runOnConnect command started")
_, port, _ := net.SplitHostPort(c.rtspAddress)
c.onConnectCmd = externalcmd.NewCmd(
c.externalCmdPool,
c.runOnConnect,
c.runOnConnectRestart,
externalcmd.Environment{
"MTX_PATH": "",
"RTSP_PATH": "", // deprecated
"RTSP_PORT": port,
},
func(err error) {
c.Log(logger.Info, "runOnInit command exited: %v", err)
})
}
return c
}
func (c *rtspConn) Log(level logger.Level, format string, args ...interface{}) {
c.parent.Log(level, "[conn %v] "+format, append([]interface{}{c.conn.NetConn().RemoteAddr()}, args...)...)
}
// Conn returns the RTSP connection.
func (c *rtspConn) Conn() *gortsplib.ServerConn {
return c.conn
}
func (c *rtspConn) remoteAddr() net.Addr {
return c.conn.NetConn().RemoteAddr()
}
func (c *rtspConn) ip() net.IP {
return c.conn.NetConn().RemoteAddr().(*net.TCPAddr).IP
}
// onClose is called by rtspServer.
func (c *rtspConn) onClose(err error) {
c.Log(logger.Info, "closed (%v)", err)
if c.onConnectCmd != nil {
c.onConnectCmd.Close()
c.Log(logger.Info, "runOnConnect command stopped")
}
}
// onRequest is called by rtspServer.
func (c *rtspConn) onRequest(req *base.Request) {
c.Log(logger.Debug, "[c->s] %v", req)
}
// OnResponse is called by rtspServer.
func (c *rtspConn) OnResponse(res *base.Response) {
c.Log(logger.Debug, "[s->c] %v", res)
}
// onDescribe is called by rtspServer.
func (c *rtspConn) onDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
if len(ctx.Path) == 0 || ctx.Path[0] != '/' {
return &base.Response{
StatusCode: base.StatusBadRequest,
}, nil, fmt.Errorf("invalid path")
}
ctx.Path = ctx.Path[1:]
if c.authNonce == "" {
var err error
c.authNonce, err = auth.GenerateNonce2()
if err != nil {
return &base.Response{
StatusCode: base.StatusInternalServerError,
}, nil, err
}
}
res := c.pathManager.describe(pathDescribeReq{
pathName: ctx.Path,
url: ctx.Request.URL,
credentials: authCredentials{
query: ctx.Query,
ip: c.ip(),
proto: authProtocolRTSP,
id: &c.uuid,
rtspRequest: ctx.Request,
rtspNonce: c.authNonce,
},
})
if res.err != nil {
switch terr := res.err.(type) {
case *errAuthentication:
res, err := c.handleAuthError(terr)
return res, nil, err
case errPathNoOnePublishing:
return &base.Response{
StatusCode: base.StatusNotFound,
}, nil, res.err
default:
return &base.Response{
StatusCode: base.StatusBadRequest,
}, nil, res.err
}
}
if res.redirect != "" {
return &base.Response{
StatusCode: base.StatusMovedPermanently,
Header: base.Header{
"Location": base.HeaderValue{res.redirect},
},
}, nil, nil
}
return &base.Response{
StatusCode: base.StatusOK,
}, res.stream.RTSPStream(), nil
}
func (c *rtspConn) handleAuthError(authErr error) (*base.Response, error) {
c.authFailures++
// VLC with login prompt sends 4 requests:
// 1) without credentials
// 2) with password but without username
// 3) without credentials
// 4) with password and username
// therefore we must allow up to 3 failures
if c.authFailures <= 3 {
return &base.Response{
StatusCode: base.StatusUnauthorized,
Header: base.Header{
"WWW-Authenticate": auth.GenerateWWWAuthenticate(c.authMethods, "IPCAM", c.authNonce),
},
}, nil
}
// wait some seconds to stop brute force attacks
<-time.After(rtspPauseAfterAuthError)
return &base.Response{
StatusCode: base.StatusUnauthorized,
}, authErr
}
func (c *rtspConn) apiItem() *apiRTSPConn {
return &apiRTSPConn{
ID: c.uuid,
Created: c.created,
RemoteAddr: c.remoteAddr().String(),
BytesReceived: c.conn.BytesReceived(),
BytesSent: c.conn.BytesSent(),
}
}

454
internal/core/rtsp_server.go

@ -1,454 +0,0 @@
package core
import (
"context"
"crypto/tls"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/headers"
"github.com/bluenviron/gortsplib/v3/pkg/liberrors"
"github.com/google/uuid"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
)
type rtspServerParent interface {
logger.Writer
}
func printAddresses(srv *gortsplib.Server) string {
var ret []string
ret = append(ret, fmt.Sprintf("%s (TCP)", srv.RTSPAddress))
if srv.UDPRTPAddress != "" {
ret = append(ret, fmt.Sprintf("%s (UDP/RTP)", srv.UDPRTPAddress))
}
if srv.UDPRTCPAddress != "" {
ret = append(ret, fmt.Sprintf("%s (UDP/RTCP)", srv.UDPRTCPAddress))
}
return strings.Join(ret, ", ")
}
type rtspServer struct {
authMethods []headers.AuthMethod
readTimeout conf.StringDuration
isTLS bool
rtspAddress string
protocols map[conf.Protocol]struct{}
runOnConnect string
runOnConnectRestart bool
externalCmdPool *externalcmd.Pool
metrics *metrics
pathManager *pathManager
parent rtspServerParent
ctx context.Context
ctxCancel func()
wg sync.WaitGroup
srv *gortsplib.Server
mutex sync.RWMutex
conns map[*gortsplib.ServerConn]*rtspConn
sessions map[*gortsplib.ServerSession]*rtspSession
}
func newRTSPServer(
address string,
authMethods []headers.AuthMethod,
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
readBufferCount int,
useUDP bool,
useMulticast bool,
rtpAddress string,
rtcpAddress string,
multicastIPRange string,
multicastRTPPort int,
multicastRTCPPort int,
isTLS bool,
serverCert string,
serverKey string,
rtspAddress string,
protocols map[conf.Protocol]struct{},
runOnConnect string,
runOnConnectRestart bool,
externalCmdPool *externalcmd.Pool,
metrics *metrics,
pathManager *pathManager,
parent rtspServerParent,
) (*rtspServer, error) {
ctx, ctxCancel := context.WithCancel(context.Background())
s := &rtspServer{
authMethods: authMethods,
readTimeout: readTimeout,
isTLS: isTLS,
rtspAddress: rtspAddress,
protocols: protocols,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
externalCmdPool: externalCmdPool,
metrics: metrics,
pathManager: pathManager,
parent: parent,
ctx: ctx,
ctxCancel: ctxCancel,
conns: make(map[*gortsplib.ServerConn]*rtspConn),
sessions: make(map[*gortsplib.ServerSession]*rtspSession),
}
s.srv = &gortsplib.Server{
Handler: s,
ReadTimeout: time.Duration(readTimeout),
WriteTimeout: time.Duration(writeTimeout),
ReadBufferCount: readBufferCount,
WriteBufferCount: readBufferCount,
RTSPAddress: address,
}
if useUDP {
s.srv.UDPRTPAddress = rtpAddress
s.srv.UDPRTCPAddress = rtcpAddress
}
if useMulticast {
s.srv.MulticastIPRange = multicastIPRange
s.srv.MulticastRTPPort = multicastRTPPort
s.srv.MulticastRTCPPort = multicastRTCPPort
}
if isTLS {
cert, err := tls.LoadX509KeyPair(serverCert, serverKey)
if err != nil {
return nil, err
}
s.srv.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
}
err := s.srv.Start()
if err != nil {
return nil, err
}
s.Log(logger.Info, "listener opened on %s", printAddresses(s.srv))
if metrics != nil {
if !isTLS {
metrics.rtspServerSet(s)
} else {
metrics.rtspsServerSet(s)
}
}
s.wg.Add(1)
go s.run()
return s, nil
}
func (s *rtspServer) Log(level logger.Level, format string, args ...interface{}) {
label := func() string {
if s.isTLS {
return "RTSPS"
}
return "RTSP"
}()
s.parent.Log(level, "[%s] "+format, append([]interface{}{label}, args...)...)
}
func (s *rtspServer) close() {
s.Log(logger.Info, "listener is closing")
s.ctxCancel()
s.wg.Wait()
}
func (s *rtspServer) run() {
defer s.wg.Done()
serverErr := make(chan error)
go func() {
serverErr <- s.srv.Wait()
}()
outer:
select {
case err := <-serverErr:
s.Log(logger.Error, "%s", err)
break outer
case <-s.ctx.Done():
s.srv.Close()
<-serverErr
break outer
}
s.ctxCancel()
if s.metrics != nil {
if !s.isTLS {
s.metrics.rtspServerSet(nil)
} else {
s.metrics.rtspsServerSet(nil)
}
}
}
// OnConnOpen implements gortsplib.ServerHandlerOnConnOpen.
func (s *rtspServer) OnConnOpen(ctx *gortsplib.ServerHandlerOnConnOpenCtx) {
c := newRTSPConn(
s.rtspAddress,
s.authMethods,
s.readTimeout,
s.runOnConnect,
s.runOnConnectRestart,
s.externalCmdPool,
s.pathManager,
ctx.Conn,
s)
s.mutex.Lock()
s.conns[ctx.Conn] = c
s.mutex.Unlock()
ctx.Conn.SetUserData(c)
}
// OnConnClose implements gortsplib.ServerHandlerOnConnClose.
func (s *rtspServer) OnConnClose(ctx *gortsplib.ServerHandlerOnConnCloseCtx) {
s.mutex.Lock()
c := s.conns[ctx.Conn]
delete(s.conns, ctx.Conn)
s.mutex.Unlock()
c.onClose(ctx.Error)
}
// OnRequest implements gortsplib.ServerHandlerOnRequest.
func (s *rtspServer) OnRequest(sc *gortsplib.ServerConn, req *base.Request) {
c := sc.UserData().(*rtspConn)
c.onRequest(req)
}
// OnResponse implements gortsplib.ServerHandlerOnResponse.
func (s *rtspServer) OnResponse(sc *gortsplib.ServerConn, res *base.Response) {
c := sc.UserData().(*rtspConn)
c.OnResponse(res)
}
// OnSessionOpen implements gortsplib.ServerHandlerOnSessionOpen.
func (s *rtspServer) OnSessionOpen(ctx *gortsplib.ServerHandlerOnSessionOpenCtx) {
se := newRTSPSession(
s.isTLS,
s.protocols,
ctx.Session,
ctx.Conn,
s.externalCmdPool,
s.pathManager,
s)
s.mutex.Lock()
s.sessions[ctx.Session] = se
s.mutex.Unlock()
ctx.Session.SetUserData(se)
}
// OnSessionClose implements gortsplib.ServerHandlerOnSessionClose.
func (s *rtspServer) OnSessionClose(ctx *gortsplib.ServerHandlerOnSessionCloseCtx) {
s.mutex.Lock()
se := s.sessions[ctx.Session]
delete(s.sessions, ctx.Session)
s.mutex.Unlock()
if se != nil {
se.onClose(ctx.Error)
}
}
// OnDescribe implements gortsplib.ServerHandlerOnDescribe.
func (s *rtspServer) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
c := ctx.Conn.UserData().(*rtspConn)
return c.onDescribe(ctx)
}
// OnAnnounce implements gortsplib.ServerHandlerOnAnnounce.
func (s *rtspServer) OnAnnounce(ctx *gortsplib.ServerHandlerOnAnnounceCtx) (*base.Response, error) {
c := ctx.Conn.UserData().(*rtspConn)
se := ctx.Session.UserData().(*rtspSession)
return se.onAnnounce(c, ctx)
}
// OnSetup implements gortsplib.ServerHandlerOnSetup.
func (s *rtspServer) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
c := ctx.Conn.UserData().(*rtspConn)
se := ctx.Session.UserData().(*rtspSession)
return se.onSetup(c, ctx)
}
// OnPlay implements gortsplib.ServerHandlerOnPlay.
func (s *rtspServer) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
se := ctx.Session.UserData().(*rtspSession)
return se.onPlay(ctx)
}
// OnRecord implements gortsplib.ServerHandlerOnRecord.
func (s *rtspServer) OnRecord(ctx *gortsplib.ServerHandlerOnRecordCtx) (*base.Response, error) {
se := ctx.Session.UserData().(*rtspSession)
return se.onRecord(ctx)
}
// OnPause implements gortsplib.ServerHandlerOnPause.
func (s *rtspServer) OnPause(ctx *gortsplib.ServerHandlerOnPauseCtx) (*base.Response, error) {
se := ctx.Session.UserData().(*rtspSession)
return se.onPause(ctx)
}
// OnPacketLost implements gortsplib.ServerHandlerOnDecodeError.
func (s *rtspServer) OnPacketLost(ctx *gortsplib.ServerHandlerOnPacketLostCtx) {
se := ctx.Session.UserData().(*rtspSession)
se.onPacketLost(ctx)
}
// OnDecodeError implements gortsplib.ServerHandlerOnDecodeError.
func (s *rtspServer) OnDecodeError(ctx *gortsplib.ServerHandlerOnDecodeErrorCtx) {
se := ctx.Session.UserData().(*rtspSession)
se.onDecodeError(ctx)
}
func (s *rtspServer) findConnByUUID(uuid uuid.UUID) *rtspConn {
for _, c := range s.conns {
if c.uuid == uuid {
return c
}
}
return nil
}
func (s *rtspServer) findSessionByUUID(uuid uuid.UUID) (*gortsplib.ServerSession, *rtspSession) {
for key, sx := range s.sessions {
if sx.uuid == uuid {
return key, sx
}
}
return nil, nil
}
// apiConnsList is called by api and metrics.
func (s *rtspServer) apiConnsList() (*apiRTSPConnsList, error) {
select {
case <-s.ctx.Done():
return nil, fmt.Errorf("terminated")
default:
}
s.mutex.RLock()
defer s.mutex.RUnlock()
data := &apiRTSPConnsList{
Items: []*apiRTSPConn{},
}
for _, c := range s.conns {
data.Items = append(data.Items, c.apiItem())
}
sort.Slice(data.Items, func(i, j int) bool {
return data.Items[i].Created.Before(data.Items[j].Created)
})
return data, nil
}
// apiConnsGet is called by api.
func (s *rtspServer) apiConnsGet(uuid uuid.UUID) (*apiRTSPConn, error) {
select {
case <-s.ctx.Done():
return nil, fmt.Errorf("terminated")
default:
}
s.mutex.RLock()
defer s.mutex.RUnlock()
conn := s.findConnByUUID(uuid)
if conn == nil {
return nil, errAPINotFound
}
return conn.apiItem(), nil
}
// apiSessionsList is called by api and metrics.
func (s *rtspServer) apiSessionsList() (*apiRTSPSessionsList, error) {
select {
case <-s.ctx.Done():
return nil, fmt.Errorf("terminated")
default:
}
s.mutex.RLock()
defer s.mutex.RUnlock()
data := &apiRTSPSessionsList{
Items: []*apiRTSPSession{},
}
for _, s := range s.sessions {
data.Items = append(data.Items, s.apiItem())
}
sort.Slice(data.Items, func(i, j int) bool {
return data.Items[i].Created.Before(data.Items[j].Created)
})
return data, nil
}
// apiSessionsGet is called by api.
func (s *rtspServer) apiSessionsGet(uuid uuid.UUID) (*apiRTSPSession, error) {
select {
case <-s.ctx.Done():
return nil, fmt.Errorf("terminated")
default:
}
s.mutex.RLock()
defer s.mutex.RUnlock()
_, sx := s.findSessionByUUID(uuid)
if sx == nil {
return nil, errAPINotFound
}
return sx.apiItem(), nil
}
// apiSessionsKick is called by api.
func (s *rtspServer) apiSessionsKick(uuid uuid.UUID) error {
select {
case <-s.ctx.Done():
return fmt.Errorf("terminated")
default:
}
s.mutex.RLock()
defer s.mutex.RUnlock()
key, sx := s.findSessionByUUID(uuid)
if sx == nil {
return errAPINotFound
}
sx.close()
delete(s.sessions, key)
sx.onClose(liberrors.ErrServerTerminated{})
return nil
}

422
internal/core/rtsp_server_test.go

@ -1,422 +0,0 @@
package core
import (
"os"
"testing"
"time"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/gortsplib/v3/pkg/url"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
)
func TestRTSPServerRunOnConnect(t *testing.T) {
f, err := os.CreateTemp(os.TempDir(), "rtspss-runonconnect-")
require.NoError(t, err)
f.Close()
defer os.Remove(f.Name())
p, ok := newInstance(
"runOnConnect: sh -c 'echo aa > " + f.Name() + "'\n" +
"paths:\n" +
" all:\n")
require.Equal(t, true, ok)
defer p.Close()
source := gortsplib.Client{}
err = source.StartRecording(
"rtsp://127.0.0.1:8554/mypath",
media.Medias{testMediaH264})
require.NoError(t, err)
defer source.Close()
time.Sleep(500 * time.Millisecond)
byts, err := os.ReadFile(f.Name())
require.NoError(t, err)
require.Equal(t, "aa\n", string(byts))
}
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:\n"
case "internal":
conf = "rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all:\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:\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",
media.Medias{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 := url.Parse("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()
medias, baseURL, _, err := reader.Describe(u)
require.NoError(t, err)
err = reader.SetupAll(medias, baseURL)
require.NoError(t, err)
_, err = reader.Play(nil)
require.NoError(t, err)
})
}
}
func TestRTSPServerAuthHashed(t *testing.T) {
p, ok := newInstance(
"rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" all:\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",
media.Medias{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:\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",
media.Medias{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:\n" +
" readUser: testuser\n" +
" readPass: testpass\n")
require.Equal(t, true, ok)
defer p.Close()
c := gortsplib.Client{}
u, err := url.Parse("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:\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",
media.Medias{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:\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",
media.Medias{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:\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", media.Medias{medi})
require.NoError(t, err)
defer s1.Close()
s2 := gortsplib.Client{}
err = s2.StartRecording("rtsp://localhost:8554/teststream", media.Medias{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 := url.Parse("rtsp://localhost:8554/teststream")
require.NoError(t, err)
err = c.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer c.Close()
medias, baseURL, _, err := c.Describe(u)
require.NoError(t, err)
err = c.SetupAll(medias, baseURL)
require.NoError(t, err)
c.OnPacketRTP(medias[0], medias[0].Formats[0], func(pkt *rtp.Packet) {
if ca == "enabled" {
require.Equal(t, []byte{0x05, 0x06, 0x07, 0x08}, pkt.Payload)
} else {
require.Equal(t, []byte{0x01, 0x02, 0x03, 0x04}, 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{0x05, 0x06, 0x07, 0x08},
})
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{0x01, 0x02, 0x03, 0x04},
})
require.NoError(t, err)
}
<-frameRecv
})
}
}
func TestRTSPServerFallback(t *testing.T) {
for _, ca := range []string{
"absolute",
"relative",
} {
t.Run(ca, func(t *testing.T) {
val := func() string {
if ca == "absolute" {
return "rtsp://localhost:8554/path2"
}
return "/path2"
}()
p1, ok := newInstance("rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" path1:\n" +
" fallback: " + val + "\n" +
" path2:\n")
require.Equal(t, true, ok)
defer p1.Close()
source := gortsplib.Client{}
err := source.StartRecording("rtsp://localhost:8554/path2",
media.Medias{testMediaH264})
require.NoError(t, err)
defer source.Close()
u, err := url.Parse("rtsp://localhost:8554/path1")
require.NoError(t, err)
dest := gortsplib.Client{}
err = dest.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer dest.Close()
medias, _, _, err := dest.Describe(u)
require.NoError(t, err)
require.Equal(t, 1, len(medias))
})
}
}

428
internal/core/rtsp_session.go

@ -1,428 +0,0 @@
package core
import (
"encoding/hex"
"fmt"
"net"
"sync"
"time"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/auth"
"github.com/bluenviron/gortsplib/v3/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/url"
"github.com/google/uuid"
"github.com/pion/rtp"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
"github.com/bluenviron/mediamtx/internal/stream"
)
type rtspSessionPathManager interface {
addPublisher(req pathAddPublisherReq) pathAddPublisherRes
addReader(req pathAddReaderReq) pathAddReaderRes
}
type rtspSessionParent interface {
logger.Writer
}
type rtspSession struct {
isTLS bool
protocols map[conf.Protocol]struct{}
session *gortsplib.ServerSession
author *gortsplib.ServerConn
externalCmdPool *externalcmd.Pool
pathManager rtspSessionPathManager
parent rtspSessionParent
uuid uuid.UUID
created time.Time
path *path
stream *stream.Stream
onReadCmd *externalcmd.Cmd // read
mutex sync.Mutex
state gortsplib.ServerSessionState
transport *gortsplib.Transport
pathName string
}
func newRTSPSession(
isTLS bool,
protocols map[conf.Protocol]struct{},
session *gortsplib.ServerSession,
sc *gortsplib.ServerConn,
externalCmdPool *externalcmd.Pool,
pathManager rtspSessionPathManager,
parent rtspSessionParent,
) *rtspSession {
s := &rtspSession{
isTLS: isTLS,
protocols: protocols,
session: session,
author: sc,
externalCmdPool: externalCmdPool,
pathManager: pathManager,
parent: parent,
uuid: uuid.New(),
created: time.Now(),
}
s.Log(logger.Info, "created by %v", s.author.NetConn().RemoteAddr())
return s
}
// Close closes a Session.
func (s *rtspSession) close() {
s.session.Close()
}
func (s *rtspSession) remoteAddr() net.Addr {
return s.author.NetConn().RemoteAddr()
}
func (s *rtspSession) Log(level logger.Level, format string, args ...interface{}) {
id := hex.EncodeToString(s.uuid[:4])
s.parent.Log(level, "[session %s] "+format, append([]interface{}{id}, args...)...)
}
// onClose is called by rtspServer.
func (s *rtspSession) onClose(err error) {
if s.session.State() == gortsplib.ServerSessionStatePlay {
if s.onReadCmd != nil {
s.onReadCmd.Close()
s.onReadCmd = nil
s.Log(logger.Info, "runOnRead command stopped")
}
}
switch s.session.State() {
case gortsplib.ServerSessionStatePrePlay, gortsplib.ServerSessionStatePlay:
s.path.removeReader(pathRemoveReaderReq{author: s})
case gortsplib.ServerSessionStatePreRecord, gortsplib.ServerSessionStateRecord:
s.path.removePublisher(pathRemovePublisherReq{author: s})
}
s.path = nil
s.stream = nil
s.Log(logger.Info, "destroyed (%v)", err)
}
// onAnnounce is called by rtspServer.
func (s *rtspSession) onAnnounce(c *rtspConn, ctx *gortsplib.ServerHandlerOnAnnounceCtx) (*base.Response, error) {
if len(ctx.Path) == 0 || ctx.Path[0] != '/' {
return &base.Response{
StatusCode: base.StatusBadRequest,
}, fmt.Errorf("invalid path")
}
ctx.Path = ctx.Path[1:]
if c.authNonce == "" {
var err error
c.authNonce, err = auth.GenerateNonce2()
if err != nil {
return &base.Response{
StatusCode: base.StatusInternalServerError,
}, err
}
}
res := s.pathManager.addPublisher(pathAddPublisherReq{
author: s,
pathName: ctx.Path,
credentials: authCredentials{
query: ctx.Query,
ip: c.ip(),
proto: authProtocolRTSP,
id: &c.uuid,
rtspRequest: ctx.Request,
rtspBaseURL: nil,
rtspNonce: c.authNonce,
},
})
if res.err != nil {
switch terr := res.err.(type) {
case *errAuthentication:
return c.handleAuthError(terr)
default:
return &base.Response{
StatusCode: base.StatusBadRequest,
}, res.err
}
}
s.path = res.path
s.mutex.Lock()
s.state = gortsplib.ServerSessionStatePreRecord
s.pathName = ctx.Path
s.mutex.Unlock()
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
// onSetup is called by rtspServer.
func (s *rtspSession) onSetup(c *rtspConn, ctx *gortsplib.ServerHandlerOnSetupCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
if len(ctx.Path) == 0 || ctx.Path[0] != '/' {
return &base.Response{
StatusCode: base.StatusBadRequest,
}, nil, fmt.Errorf("invalid path")
}
ctx.Path = ctx.Path[1:]
// in case the client is setupping a stream with UDP or UDP-multicast, and these
// transport protocols are disabled, gortsplib already blocks the request.
// we have only to handle the case in which the transport protocol is TCP
// and it is disabled.
if ctx.Transport == gortsplib.TransportTCP {
if _, ok := s.protocols[conf.Protocol(gortsplib.TransportTCP)]; !ok {
return &base.Response{
StatusCode: base.StatusUnsupportedTransport,
}, nil, nil
}
}
switch s.session.State() {
case gortsplib.ServerSessionStateInitial, gortsplib.ServerSessionStatePrePlay: // play
baseURL := &url.URL{
Scheme: ctx.Request.URL.Scheme,
Host: ctx.Request.URL.Host,
Path: ctx.Path,
RawQuery: ctx.Query,
}
if ctx.Query != "" {
baseURL.RawQuery += "/"
} else {
baseURL.Path += "/"
}
if c.authNonce == "" {
var err error
c.authNonce, err = auth.GenerateNonce2()
if err != nil {
return &base.Response{
StatusCode: base.StatusInternalServerError,
}, nil, err
}
}
res := s.pathManager.addReader(pathAddReaderReq{
author: s,
pathName: ctx.Path,
credentials: authCredentials{
query: ctx.Query,
ip: c.ip(),
proto: authProtocolRTSP,
id: &c.uuid,
rtspRequest: ctx.Request,
rtspBaseURL: baseURL,
rtspNonce: c.authNonce,
},
})
if res.err != nil {
switch terr := res.err.(type) {
case *errAuthentication:
res, err := c.handleAuthError(terr)
return res, nil, err
case errPathNoOnePublishing:
return &base.Response{
StatusCode: base.StatusNotFound,
}, nil, res.err
default:
return &base.Response{
StatusCode: base.StatusBadRequest,
}, nil, res.err
}
}
s.path = res.path
s.stream = res.stream
s.mutex.Lock()
s.state = gortsplib.ServerSessionStatePrePlay
s.pathName = ctx.Path
s.mutex.Unlock()
return &base.Response{
StatusCode: base.StatusOK,
}, res.stream.RTSPStream(), nil
default: // record
return &base.Response{
StatusCode: base.StatusOK,
}, nil, nil
}
}
// onPlay is called by rtspServer.
func (s *rtspSession) onPlay(_ *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
h := make(base.Header)
if s.session.State() == gortsplib.ServerSessionStatePrePlay {
s.Log(logger.Info, "is reading from path '%s', with %s, %s",
s.path.name,
s.session.SetuppedTransport(),
sourceMediaInfo(s.session.SetuppedMedias()))
pathConf := s.path.safeConf()
if pathConf.RunOnRead != "" {
s.Log(logger.Info, "runOnRead command started")
s.onReadCmd = externalcmd.NewCmd(
s.externalCmdPool,
pathConf.RunOnRead,
pathConf.RunOnReadRestart,
s.path.externalCmdEnv(),
func(err error) {
s.Log(logger.Info, "runOnRead command exited: %v", err)
})
}
s.mutex.Lock()
s.state = gortsplib.ServerSessionStatePlay
s.transport = s.session.SetuppedTransport()
s.mutex.Unlock()
}
return &base.Response{
StatusCode: base.StatusOK,
Header: h,
}, nil
}
// onRecord is called by rtspServer.
func (s *rtspSession) onRecord(_ *gortsplib.ServerHandlerOnRecordCtx) (*base.Response, error) {
res := s.path.startPublisher(pathStartPublisherReq{
author: s,
medias: s.session.AnnouncedMedias(),
generateRTPPackets: false,
})
if res.err != nil {
return &base.Response{
StatusCode: base.StatusBadRequest,
}, res.err
}
s.stream = res.stream
for _, medi := range s.session.AnnouncedMedias() {
for _, forma := range medi.Formats {
cmedi := medi
cforma := forma
s.session.OnPacketRTP(cmedi, cforma, func(pkt *rtp.Packet) {
res.stream.WriteRTPPacket(cmedi, cforma, pkt, time.Now())
})
}
}
s.mutex.Lock()
s.state = gortsplib.ServerSessionStateRecord
s.transport = s.session.SetuppedTransport()
s.mutex.Unlock()
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
// onPause is called by rtspServer.
func (s *rtspSession) onPause(_ *gortsplib.ServerHandlerOnPauseCtx) (*base.Response, error) {
switch s.session.State() {
case gortsplib.ServerSessionStatePlay:
if s.onReadCmd != nil {
s.Log(logger.Info, "runOnRead command stopped")
s.onReadCmd.Close()
}
s.mutex.Lock()
s.state = gortsplib.ServerSessionStatePrePlay
s.mutex.Unlock()
case gortsplib.ServerSessionStateRecord:
s.path.stopPublisher(pathStopPublisherReq{author: s})
s.mutex.Lock()
s.state = gortsplib.ServerSessionStatePreRecord
s.mutex.Unlock()
}
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
// apiReaderDescribe implements reader.
func (s *rtspSession) apiReaderDescribe() pathAPISourceOrReader {
return pathAPISourceOrReader{
Type: func() string {
if s.isTLS {
return "rtspsSession"
}
return "rtspSession"
}(),
ID: s.uuid.String(),
}
}
// apiSourceDescribe implements source.
func (s *rtspSession) apiSourceDescribe() pathAPISourceOrReader {
return s.apiReaderDescribe()
}
// onPacketLost is called by rtspServer.
func (s *rtspSession) onPacketLost(ctx *gortsplib.ServerHandlerOnPacketLostCtx) {
s.Log(logger.Warn, ctx.Error.Error())
}
// onDecodeError is called by rtspServer.
func (s *rtspSession) onDecodeError(ctx *gortsplib.ServerHandlerOnDecodeErrorCtx) {
s.Log(logger.Warn, ctx.Error.Error())
}
func (s *rtspSession) apiItem() *apiRTSPSession {
s.mutex.Lock()
defer s.mutex.Unlock()
return &apiRTSPSession{
ID: s.uuid,
Created: s.created,
RemoteAddr: s.remoteAddr().String(),
State: func() apiRTSPSessionState {
switch s.state {
case gortsplib.ServerSessionStatePrePlay,
gortsplib.ServerSessionStatePlay:
return apiRTSPSessionStateRead
case gortsplib.ServerSessionStatePreRecord,
gortsplib.ServerSessionStateRecord:
return apiRTSPSessionStatePublish
}
return apiRTSPSessionStateIdle
}(),
Path: s.pathName,
Transport: func() *string {
if s.transport == nil {
return nil
}
v := s.transport.String()
return &v
}(),
BytesReceived: s.session.BytesReceived(),
BytesSent: s.session.BytesSent(),
}
}

201
internal/core/rtsp_source.go

@ -1,201 +0,0 @@
package core
import (
"context"
"time"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/headers"
"github.com/pion/rtp"
"github.com/bluenviron/gortsplib/v3/pkg/url"
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/logger"
)
func createRangeHeader(cnf *conf.PathConf) (*headers.Range, error) {
switch cnf.RtspRangeType {
case conf.RtspRangeTypeClock:
start, err := time.Parse("20060102T150405Z", cnf.RtspRangeStart)
if err != nil {
return nil, err
}
return &headers.Range{
Value: &headers.RangeUTC{
Start: start,
},
}, nil
case conf.RtspRangeTypeNPT:
start, err := time.ParseDuration(cnf.RtspRangeStart)
if err != nil {
return nil, err
}
return &headers.Range{
Value: &headers.RangeNPT{
Start: start,
},
}, nil
case conf.RtspRangeTypeSMPTE:
start, err := time.ParseDuration(cnf.RtspRangeStart)
if err != nil {
return nil, err
}
return &headers.Range{
Value: &headers.RangeSMPTE{
Start: headers.RangeSMPTETime{
Time: start,
},
},
}, nil
default:
return nil, nil
}
}
type rtspSourceParent interface {
logger.Writer
setReady(req pathSourceStaticSetReadyReq) pathSourceStaticSetReadyRes
setNotReady(req pathSourceStaticSetNotReadyReq)
}
type rtspSource struct {
readTimeout conf.StringDuration
writeTimeout conf.StringDuration
readBufferCount int
parent rtspSourceParent
}
func newRTSPSource(
readTimeout conf.StringDuration,
writeTimeout conf.StringDuration,
readBufferCount int,
parent rtspSourceParent,
) *rtspSource {
return &rtspSource{
readTimeout: readTimeout,
writeTimeout: writeTimeout,
readBufferCount: readBufferCount,
parent: parent,
}
}
func (s *rtspSource) Log(level logger.Level, format string, args ...interface{}) {
s.parent.Log(level, "[RTSP source] "+format, args...)
}
// run implements sourceStaticImpl.
func (s *rtspSource) run(ctx context.Context, cnf *conf.PathConf, reloadConf chan *conf.PathConf) error {
s.Log(logger.Debug, "connecting")
c := &gortsplib.Client{
Transport: cnf.SourceProtocol.Transport,
TLSConfig: tlsConfigForFingerprint(cnf.SourceFingerprint),
ReadTimeout: time.Duration(s.readTimeout),
WriteTimeout: time.Duration(s.writeTimeout),
ReadBufferCount: s.readBufferCount,
AnyPortEnable: cnf.SourceAnyPortEnable,
OnRequest: func(req *base.Request) {
s.Log(logger.Debug, "c->s %v", req)
},
OnResponse: func(res *base.Response) {
s.Log(logger.Debug, "s->c %v", res)
},
OnTransportSwitch: func(err error) {
s.Log(logger.Warn, err.Error())
},
OnPacketLost: func(err error) {
s.Log(logger.Warn, err.Error())
},
OnDecodeError: func(err error) {
s.Log(logger.Warn, err.Error())
},
}
u, err := url.Parse(cnf.Source)
if err != nil {
return err
}
err = c.Start(u.Scheme, u.Host)
if err != nil {
return err
}
defer c.Close()
readErr := make(chan error)
go func() {
readErr <- func() error {
medias, baseURL, _, err := c.Describe(u)
if err != nil {
return err
}
err = c.SetupAll(medias, baseURL)
if err != nil {
return err
}
res := s.parent.setReady(pathSourceStaticSetReadyReq{
medias: medias,
generateRTPPackets: false,
})
if res.err != nil {
return res.err
}
defer s.parent.setNotReady(pathSourceStaticSetNotReadyReq{})
for _, medi := range medias {
for _, forma := range medi.Formats {
cmedi := medi
cforma := forma
c.OnPacketRTP(cmedi, cforma, func(pkt *rtp.Packet) {
res.stream.WriteRTPPacket(cmedi, cforma, pkt, time.Now())
})
}
}
rangeHeader, err := createRangeHeader(cnf)
if err != nil {
return err
}
_, err = c.Play(rangeHeader)
if err != nil {
return err
}
return c.Wait()
}()
}()
for {
select {
case err := <-readErr:
return err
case <-reloadConf:
case <-ctx.Done():
c.Close()
<-readErr
return nil
}
}
}
// apiSourceDescribe implements sourceStaticImpl.
func (*rtspSource) apiSourceDescribe() pathAPISourceOrReader {
return pathAPISourceOrReader{
Type: "rtspSource",
ID: "",
}
}

300
internal/core/rtsp_source_test.go

@ -1,300 +0,0 @@
package core
import (
"crypto/tls"
"os"
"testing"
"time"
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/auth"
"github.com/bluenviron/gortsplib/v3/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/formats"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/gortsplib/v3/pkg/url"
"github.com/pion/rtp"
"github.com/stretchr/testify/require"
)
type testServer struct {
onDescribe func(*gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error)
onSetup func(*gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error)
onPlay func(*gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error)
}
func (sh *testServer) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
return sh.onDescribe(ctx)
}
func (sh *testServer) OnSetup(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
return sh.onSetup(ctx)
}
func (sh *testServer) OnPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
return sh.onPlay(ctx)
}
func TestRTSPSource(t *testing.T) {
for _, source := range []string{
"udp",
"tcp",
"tls",
} {
t.Run(source, func(t *testing.T) {
serverMedia := testMediaH264
stream := gortsplib.NewServerStream(media.Medias{serverMedia})
nonce, err := auth.GenerateNonce2()
require.NoError(t, err)
s := gortsplib.Server{
Handler: &testServer{
onDescribe: func(ctx *gortsplib.ServerHandlerOnDescribeCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
err := auth.Validate(ctx.Request, "testuser", "testpass", nil, nil, "IPCAM", nonce)
if err != nil {
return &base.Response{ //nolint:nilerr
StatusCode: base.StatusUnauthorized,
Header: base.Header{
"WWW-Authenticate": auth.GenerateWWWAuthenticate(nil, "IPCAM", nonce),
},
}, nil, nil
}
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onSetup: func(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onPlay: func(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
go func() {
time.Sleep(1 * time.Second)
stream.WritePacketRTP(serverMedia, &rtp.Packet{
Header: rtp.Header{
Version: 0x02,
PayloadType: 96,
SequenceNumber: 57899,
Timestamp: 345234345,
SSRC: 978651231,
Marker: true,
},
Payload: []byte{0x01, 0x02, 0x03, 0x04},
})
}()
return &base.Response{
StatusCode: base.StatusOK,
}, nil
},
},
RTSPAddress: "127.0.0.1:8555",
}
switch source {
case "udp":
s.UDPRTPAddress = "127.0.0.1:8002"
s.UDPRTCPAddress = "127.0.0.1:8003"
case "tls":
serverCertFpath, err := writeTempFile(serverCert)
require.NoError(t, err)
defer os.Remove(serverCertFpath)
serverKeyFpath, err := writeTempFile(serverKey)
require.NoError(t, err)
defer os.Remove(serverKeyFpath)
cert, err := tls.LoadX509KeyPair(serverCertFpath, serverKeyFpath)
require.NoError(t, err)
s.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cert}}
}
err = s.Start()
require.NoError(t, err)
defer s.Wait()
defer s.Close()
if source == "udp" || source == "tcp" {
p, ok := newInstance("paths:\n" +
" proxied:\n" +
" source: rtsp://testuser:testpass@localhost:8555/teststream\n" +
" sourceProtocol: " + source + "\n" +
" sourceOnDemand: yes\n")
require.Equal(t, true, ok)
defer p.Close()
} else {
p, ok := newInstance("paths:\n" +
" proxied:\n" +
" source: rtsps://testuser:testpass@localhost:8555/teststream\n" +
" sourceFingerprint: 33949E05FFFB5FF3E8AA16F8213A6251B4D9363804BA53233C4DA9A46D6F2739\n" +
" sourceOnDemand: yes\n")
require.Equal(t, true, ok)
defer p.Close()
}
received := make(chan struct{})
c := gortsplib.Client{}
u, err := url.Parse("rtsp://127.0.0.1:8554/proxied")
require.NoError(t, err)
err = c.Start(u.Scheme, u.Host)
require.NoError(t, err)
defer c.Close()
medias, baseURL, _, err := c.Describe(u)
require.NoError(t, err)
var forma *formats.H264
medi := medias.FindFormat(&forma)
_, err = c.Setup(medi, baseURL, 0, 0)
require.NoError(t, err)
c.OnPacketRTP(medi, forma, func(pkt *rtp.Packet) {
require.Equal(t, []byte{0x01, 0x02, 0x03, 0x04}, pkt.Payload)
close(received)
})
_, err = c.Play(nil)
require.NoError(t, err)
<-received
})
}
}
func TestRTSPSourceNoPassword(t *testing.T) {
stream := gortsplib.NewServerStream(media.Medias{testMediaH264})
nonce, err := auth.GenerateNonce2()
require.NoError(t, err)
done := make(chan struct{})
s := gortsplib.Server{
Handler: &testServer{
onDescribe: func(ctx *gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error) {
err := auth.Validate(ctx.Request, "testuser", "", nil, nil, "IPCAM", nonce)
if err != nil {
return &base.Response{ //nolint:nilerr
StatusCode: base.StatusUnauthorized,
Header: base.Header{
"WWW-Authenticate": auth.GenerateWWWAuthenticate(nil, "IPCAM", nonce),
},
}, nil, nil
}
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onSetup: func(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
close(done)
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onPlay: func(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, nil
},
},
RTSPAddress: "127.0.0.1:8555",
}
err = s.Start()
require.NoError(t, err)
defer s.Wait()
defer s.Close()
p, ok := newInstance("rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" proxied:\n" +
" source: rtsp://testuser:@127.0.0.1:8555/teststream\n" +
" sourceProtocol: tcp\n")
require.Equal(t, true, ok)
defer p.Close()
<-done
}
func TestRTSPSourceRange(t *testing.T) {
for _, ca := range []string{"clock", "npt", "smpte"} {
t.Run(ca, func(t *testing.T) {
stream := gortsplib.NewServerStream(media.Medias{testMediaH264})
done := make(chan struct{})
s := gortsplib.Server{
Handler: &testServer{
onDescribe: func(ctx *gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onSetup: func(ctx *gortsplib.ServerHandlerOnSetupCtx) (*base.Response, *gortsplib.ServerStream, error) {
return &base.Response{
StatusCode: base.StatusOK,
}, stream, nil
},
onPlay: func(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
switch ca {
case "clock":
require.Equal(t, base.HeaderValue{"clock=20230812T120000Z-"}, ctx.Request.Header["Range"])
case "npt":
require.Equal(t, base.HeaderValue{"npt=0.35-"}, ctx.Request.Header["Range"])
case "smpte":
require.Equal(t, base.HeaderValue{"smpte=0:02:10-"}, ctx.Request.Header["Range"])
}
close(done)
return &base.Response{
StatusCode: base.StatusOK,
}, nil
},
},
RTSPAddress: "127.0.0.1:8555",
}
err := s.Start()
require.NoError(t, err)
defer s.Wait()
defer s.Close()
var addConf string
switch ca {
case "clock":
addConf += " rtspRangeType: clock\n" +
" rtspRangeStart: 20230812T120000Z\n"
case "npt":
addConf += " rtspRangeType: npt\n" +
" rtspRangeStart: 350ms\n"
case "smpte":
addConf += " rtspRangeType: smpte\n" +
" rtspRangeStart: 130s\n"
}
p, ok := newInstance("rtmp: no\n" +
"hls: no\n" +
"webrtc: no\n" +
"paths:\n" +
" proxied:\n" +
" source: rtsp://testuser:@127.0.0.1:8555/teststream\n" + addConf)
require.Equal(t, true, ok)
defer p.Close()
<-done
})
}
}

48
internal/core/source.go

@ -1,48 +0,0 @@
package core
import (
"fmt"
"strings"
"github.com/bluenviron/gortsplib/v3/pkg/media"
"github.com/bluenviron/mediamtx/internal/logger"
)
// source is an entity that can provide a stream.
// it can be:
// - a publisher
// - sourceStatic
// - sourceRedirect
type source interface {
logger.Writer
apiSourceDescribe() pathAPISourceOrReader
}
func mediaDescription(media *media.Media) string {
ret := make([]string, len(media.Formats))
for i, forma := range media.Formats {
ret[i] = forma.Codec()
}
return strings.Join(ret, "/")
}
func mediasDescription(medias media.Medias) []string {
ret := make([]string, len(medias))
for i, media := range medias {
ret[i] = mediaDescription(media)
}
return ret
}
func sourceMediaInfo(medias media.Medias) string {
return fmt.Sprintf("%d %s (%s)",
len(medias),
func() string {
if len(medias) == 1 {
return "track"
}
return "tracks"
}(),
strings.Join(mediasDescription(medias), ", "))
}

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

Loading…
Cancel
Save