MediaMTX
바로 사용할 수 있는 SRT / RTSP / RTMP / LL-HLS / WebRTC 미디어 서버 및 비디오 및 오디오 스트림을 읽고 게시하고 프록시할 수 있는 미디어 프록시.
구 버전 이름으로 rtsp-simple-server 이다.
Categories
- MediaMTX:Configuration (mediamtx.yml파일 설정 방법)
Features
- 라이브 스트림을 서버에 게시
- 서버에서 라이브 스트림 읽기
- 항상 또는 주문형으로 다른 서버 또는 카메라의 프록시 스트림
- 스트림은 프로토콜에서 다른 프로토콜로 자동 변환됩니다. 예를 들어 RTSP로 스트림을 게시하고 HLS로 읽을 수 있습니다.
- 별도의 경로에서 한 번에 여러 스트림 제공
- 사용자를 인증합니다. 내부 또는 외부 인증 사용
- 리더를 다른 RTSP 서버로 리디렉션(로드 밸런싱)
- API를 통한 서버 조회 및 제어
- 기존 클라이언트 연결을 끊지 않고 구성 다시 로드(핫 리로딩)
- Prometheus 호환 메트릭 읽기
- 클라이언트가 스트림을 연결, 연결 해제, 읽기 또는 게시할 때 외부 명령 실행
- Linux, Windows 및 macOS와 호환되며 종속성이나 인터프리터가 필요하지 않으며 단일 실행 파일입니다.
Docker Image
FFmpeg호환 패키지명: bluenviron/mediamtx:latest-ffmpeg
Docker는 라우팅 이유로 UDP 패킷의 소스 포트를 변경할 수 있으므로 이 --network=host
플래그는 필수입니다. 이로 인해 RTSP 서버는 패킷 발신자를 식별할 수 없습니다. 이 문제는 UDP 전송 프로토콜을 비활성화하여 방지할 수 있습니다.
docker run --rm -it \
-e MTX_PROTOCOLS=tcp \
-p 8554:8554 \
-p 1935:1935 \
-p 8888:8888 \
-p 8889:8889 \
bluenviron/mediamtx
mediamtx.yml 파일은 다음 경로로 Host와 공유할 수 있다:
mystream
경로로 환경변수 설정하는 방법:
docker run --rm -it -e MTX_PATHS_MYSTREAM_SOURCE=rtsp://admin:[email protected]/stream1 -e MTX_PROTOCOLS=tcp -p 8554:8554 -p 1935:1935 -p 8888:8888 -p 8889:8889 bluenviron/mediamtx
스트림 게시 : 프로그램을 사용한 방법
독커를 실행하고 게시(Publish)를 위한 주소가 rtsp://localhost:8554/mystream
일 경우
FFmpeg
비디오/오디오 파일을 게시할 수 있습니다.
TCP로 전송하고 싶을 경우 -rtsp_transport tcp
를 추가하면 된다:
ffmpeg -re -stream_loop -1 -i file.ts -c copy -f rtsp -rtsp_transport tcp rtsp://localhost:8554/mystream
RTMP의 경우 flv 포맷을 사용하면 된다:
GStreamer
gst-launch-1.0 rtspclientsink name=s location=rtsp://localhost:8554/mystream filesrc location=file.mp4 ! qtdemux name=d d.video_0 ! queue ! s.sink_0 d.audio_0 ! queue ! s.sink_1
스트림이 비디오인 경우
gst-launch-1.0 filesrc location=file.mp4 ! qtdemux name=d d.video_0 ! rtspclientsink name=s location=rtsp://localhost:8554/mystream
protocols
플래그 를 사용하여 전송 프로토콜을 설정할 수 있음
gst-launch-1.0 filesrc location=file.mp4 ! qtdemux name=d d.video_0 ! rtspclientsink protocols=tcp name=s location=rtsp://localhost:8554/mystream
OBS Studio
RTMP로 스트리밍 하거나, 최신 버전의 OBS Studio 한전으로 WebRTC/WHIP 프로토콜을 사용하여 서버에 게시할 수 있습니다:
- Service: WHIP
- Server:
http://localhost:8889/mystream/whip
OpenCV
GStreamer가 지원되여야 한다.
python3 -c 'import cv2; print(cv2.getBuildInformation())'
를 사용하여 GStreamer: YES
가 출력되는지 확인하면 된다.
out = cv2.VideoWriter('appsrc ! videoconvert' + \
' ! x264enc speed-preset=ultrafast bitrate=600 key-int-max=' + str(fps * 2) + \
' ! video/x-h264,profile=baseline' + \
' ! rtspclientsink location=rtsp://localhost:8554/mystream',
cv2.CAP_GSTREAMER, 0, fps, (width, height), True)
if not out.isOpened():
raise Exception("can't open video writer")
브라우저
http://localhost:8889/mystream/publish
에 접속하면 WebRTC를 사용하여 게시할 수 있다.
필요하다면 해당 페이지를 iframe으로 임베딩 하자.
스트림 게시 : 프로토콜 별
WebRTC
http://localhost:8889/mystream/publish
WebRTC WHIP
http://localhost:8889/mystream/whip
RTSP
rtsp://localhost:8554/mystream
, 결과 스트림은 /mystream
이다.
카메라 및 서버일 경우:
/proxied1
과 /proxied2
으로 결과 스트림을 사용할 수 있다.
RTMP
rtmp://localhost/mystream
, 결과 스트림은 /mystream
이다.
카메라 및 서버일 경우:
paths:
proxied:
# url of the source stream, in the format rtmp://user:pass@host:port/path
source: rtmp://original-url
HLS 카메라 및 서버
paths:
proxied:
# url of the playlist of the stream, in the format http://user:pass@host:port/path
source: http://original-url/stream/index.m3u8
UDP/MPEG-TS
서버는 UDP/MPEG-TS 패킷(예: UDP와 함께 전송된 MPEG-TS 패킷) 수집을 지원합니다. 패킷은 유니캐스트, 브로드캐스트 또는 멀티캐스트일 수 있습니다. 예를 들어 GStreamer를 사용하여 멀티캐스트 UDP/MPEG-TS 스트림을 생성할 수 있습니다.
gst-launch-1.0 -v mpegtsmux name=mux alignment=1 ! udpsink host=238.0.0.1 port=1234 \
videotestsrc ! video/x-raw,width=1280,height=720 ! x264enc speed-preset=ultrafast bitrate=3000 key-int-max=60 ! video/x-h264,profile=high ! mux. \
audiotestsrc ! audioconvert ! avenc_aac ! mux.
mediamtx.yml
:
스트림 재생
예를 들어 VLC 로 스트림을 열 수 있습니다 .
Ubuntu 21.10 버그 |
Ubuntu 21.10의 경우 함께 제공되는 VLC는 라이선스 문제로 인해 RTSP 재생을 지원하지 않습니다. 이 문제를 해결하려면 기본 VLC 인스턴스를 제거하고 스냅 버전을 설치하십시오. |
또는 GStreamer:
또는 FFmpeg:
연결 불안정으로 인한 무제한 연결
VLC로 RTMP로 연결한 다음 "무한루프"(중요) 걸면 된다.
Authentication
Only clients that provide username and passwords will be able to perform a certain action:
If storing plain credentials in the configuration file is a security problem, username and passwords can be stored as hashed strings. The Argon2 and SHA256 hashing algorithms are supported. To use Argon2, the string must be hashed using Argon2id (recommended) or Argon2i:
Then stored with the argon2: prefix:
authInternalUsers:
- user: argon2:$argon2id$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$OGGO0eCMN0ievb4YGSzvS/H+Vajx1pcbUmtLp2tRqRU
pass: argon2:$argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$oct3kOiFywTdDdt19kT07hdvmsPTvt9zxAUho2DLqZw
permissions:
- action: publish
To use SHA256, the string must be hashed with SHA256 and encoded with base64:
Then stored with the sha256:
prefix:
authInternalUsers:
- user: sha256:j1tsRqDEw9xvq/D7/9tMx6Jh/jMhk3UfjwIB2f1zgMo=
pass: sha256:BdSWkrdV+ZxFBLUQQY7+7uv9RmiSVA8nrPmjGjJtZQQ=
permissions:
- action: publish
Remuxing, re-encoding, compression (Save streams to disk)
To save available streams to disk, use FFmpeg inside the runOnReady
parameter:
paths:
all:
runOnReady: >
ffmpeg -i rtsp://localhost:$RTSP_PORT/$MTX_PATH
-c copy
-f segment -strftime 1 -segment_time 60 -segment_format mpegts saved_%Y-%m-%d_%H-%M-%S.ts
runOnReadyRestart: yes
Record streams to disk
To save available streams to disk, set the record and the recordPath parameter in the configuration file:
pathDefaults:
# Record streams to disk.
record: yes
# Path of recording segments.
# Extension is added automatically.
# Available variables are %path (path name), %Y %m %d %H %M %S %f %s (time in strftime format)
recordPath: ./recordings/%path/%Y-%m-%d_%H-%M-%S-%f
원격 저장소에 동기화(업로드)하고 싶다면 rclone 를 설치하자:
pathDefaults:
# this is needed to sync segments after a crash.
# replace myconfig with the name of the rclone config.
runOnInit: rclone sync -v ./recordings myconfig:/my-path/recordings
# this is called when a segment has been finalized.
# replace myconfig with the name of the rclone config.
runOnRecordSegmentComplete: rclone sync -v --min-age=1ms ./recordings myconfig:/my-path/recordings
자동 제거 날짜 지정 또는 Disable
기본 설정은 1일 까지만 저장된다. 자동저장을 끄고 싶다면:
참고로 구버전에서 자동 제거가 1일 (==1d
)이 안먹힌다. 초단위로 하자. (==86400s
)
Record 관련 옵션 목록
pathDefaults:
###############################################
# Default path settings -> Record
# Record streams to disk.
record: no
# Path of recording segments.
# Extension is added automatically.
# Available variables are %path (path name), %Y %m %d %H %M %S %f %s (time in strftime format)
recordPath: ./recordings/%path/%Y-%m-%d_%H-%M-%S-%f
# Format of recorded segments.
# Available formats are "fmp4" (fragmented MP4) and "mpegts" (MPEG-TS).
recordFormat: fmp4
# fMP4 segments are concatenation of small MP4 files (parts), each with this duration.
# MPEG-TS segments are concatenation of 188-bytes packets, flushed to disk with this period.
# When a system failure occurs, the last part gets lost.
# Therefore, the part duration is equal to the RPO (recovery point objective).
recordPartDuration: 1s
# Minimum duration of each segment.
recordSegmentDuration: 1h
# Delete segments after this timespan.
# Set to 0s to disable automatic deletion.
recordDeleteAfter: 1d
See also
-
rtsp-simple-server- 구 버전 이름. - Simple Realtime Server (srs; SRS)